diff --git a/components/AdminCategories.tsx b/components/AdminCategories.tsx index 27110e0..43d89ef 100644 --- a/components/AdminCategories.tsx +++ b/components/AdminCategories.tsx @@ -344,7 +344,7 @@ export default function AdminCategories() {

- تغییر کلید + تغییر دسته بندی

diff --git a/components/AdminNews.tsx b/components/AdminNews.tsx index 6a40544..5b24ac0 100644 --- a/components/AdminNews.tsx +++ b/components/AdminNews.tsx @@ -1,7 +1,766 @@ -import React from 'react' +"use client"; + +import React, { useState, useRef, useEffect } from "react"; +import { useMutation, useQuery, RefetchOptions } from "@tanstack/react-query"; +import { + GetAllNews, + GetSingleNews, + SubmitNews, + UpdateNews, + DeleteNews, + GetAllOrganizations, + GetSingleOrganization, + SubmitOrganization, + UpdateOrganization, + DeleteOrganization, +} from "@/utils/adminApi"; +import { FaRegEdit } from "react-icons/fa"; +import { IoMdClose } from "react-icons/io"; +import { RiDeleteBin6Line } from "react-icons/ri"; +import { useRouter } from "next/navigation"; +import { ThreeDots } from "react-loader-spinner"; +import { Button } from "@/components/ui/button"; +import { toast } from "sonner"; + +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, + AlertDialogTrigger, +} from "@/components/ui/alert-dialog"; + +import { + Form, + FormControl, + FormDescription, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form"; +import { Input } from "@/components/ui/input"; + +import { zodResolver } from "@hookform/resolvers/zod"; +import { useForm } from "react-hook-form"; +import * as z from "zod"; +import { Textarea } from "./ui/textarea"; +import { Switch } from "@/components/ui/switch"; +import Image from "next/image"; + +const MAX_IMAGE_SIZE = 5242880; // 5 MB +const ALLOWED_IMAGE_TYPES = [ + "image/jpeg", + "image/png", + "image/webp", + "image/jpg", +]; +// Form Validation +const EditNewsFormSchema = z.object({ + titleNews: z + .string() + .min(2, { + message: "عنوان باید حداقل 2 کاراکتر باشد.", + }) + .max(30, { + message: "عنوان نباید بیشتر از 30 کاراکتر باشد.", + }), + + uploadImg: z + .custom((val) => val instanceof File, "Required") + .refine( + (file) => file.size <= MAX_IMAGE_SIZE, + `File size should be less than ${MAX_IMAGE_SIZE / (1024 * 1024)} MB.` + ) + .refine( + (file) => ALLOWED_IMAGE_TYPES.includes(file.type), + "Only these types are allowed .jpg, .jpeg, .png and .webp" + ) + .nullish(), + + urlNews: z.string(), + description: z.string().max(2000), + content: z.string(), +}); + +// Add Key Form +const AddNewsFormSchema = z.object({ + titleNews: z + .string() + .min(2, { + message: "عنوان باید حداقل 2 کاراکتر باشد.", + }) + .max(30, { + message: "عنوان نباید بیشتر از 30 کاراکتر باشد.", + }), + + uploadImg: z + .custom((val) => val instanceof File, "Required") + .refine( + (file) => file.size <= MAX_IMAGE_SIZE, + `File size should be less than ${MAX_IMAGE_SIZE / (1024 * 1024)} MB.` + ) + .refine( + (file) => ALLOWED_IMAGE_TYPES.includes(file.type), + "Only these types are allowed .jpg, .jpeg, .png and .webp" + ) + .nullish(), + + urlNews: z.string(), + description: z.string().max(2000), + content: z.string(), +}); export default function AdminNews() { + const router = useRouter(); + const [keyId, setKeyId] = useState(""); + const [titleNews, setTitleNews] = useState(""); + const [descNews, setDescNews] = useState(""); + const [urlNews, setUrlNews] = useState(""); + const [contentNews, setContentNews] = useState(""); + const [imageNews, setImageNews] = useState(""); + + const [keyIdDel, setKeyIdDel] = useState(""); + + const [openAdd, setOpenAdd] = React.useState(false); + const [openEdit, setOpenEdit] = React.useState(false); + + const [delOrg, setDelOrg] = React.useState(false); + + // List News + const { + data: data1, + error: Error1, + isLoading: isListLoading, + refetch: refetch1, + } = useQuery({ + queryKey: ["NewsList"], + queryFn: () => GetAllNews(), + // queryFn: () => GetAllOrganizations(), + // refetchOnWindowFocus: false, + }); + console.log(data1); + + // Edit + const handleClickEdit = ( + id: string, + title: string, + description: string, + url: string, + content: string, + image: string + ) => { + // Set state variables + setKeyId(id); + setTitleNews(title); + setDescNews(description); + setUrlNews(url); + setContentNews(content); + setImageNews(image); + + // Reset the form with new default values + formEdit.reset({ + titleNews: title, + description: description, + urlNews: url, + content: content, + // uploadImg:image + }); + }; + + // Form Edit + type EditNewsFormValues = z.infer; + // This can come from your database or API. + const defaultValuesEdit: Partial = { + titleNews: "", + description: "", + urlNews: "", + content: "", + }; + + const formEdit = useForm({ + resolver: zodResolver(EditNewsFormSchema), + defaultValues: defaultValuesEdit, + mode: "onChange", + }); + + // Form Add + type AddNewsFormValues = z.infer; + // This can come from your database or API. + const defaultValuesAdd: Partial = { + titleNews: "", + description: "", + urlNews: "", + content: "", + }; + + const formAdd = useForm({ + resolver: zodResolver(AddNewsFormSchema), + defaultValues: defaultValuesAdd, + mode: "onChange", + }); + // Edit Submit + + // ............'Mutation' Change News Submit + const ChangeNewsMutation = useMutation({ + mutationKey: ["ChangeNews"], + mutationFn: UpdateNews, + onSuccess: (res) => { + console.log(res); + console.log("Success Change News"); + setOpenEdit(false); + + refetch1(); + + toast("عملیات شما با موفقیت انجام شد. ", { + className: "!bg-green-500 !text-white", + }); + }, + onError: (error) => { + console.log(error); + console.log(error?.message); + + setOpenEdit(false); + + toast(error?.message, { + className: "!bg-red-500 !text-black", + }); + }, + }); + + //Delete + const DeleteNewsMutation = useMutation({ + mutationKey: ["DeleteNews"], + mutationFn: DeleteNews, + onSuccess: (res) => { + console.log(res); + console.log("Success Change News"); + setOpenEdit(false); + refetch1(); + toast("عملیات شما با موفقیت انجام شد. ", { + className: "!bg-green-500 !text-white", + }); + }, + onError: (error) => { + console.log(error); + console.log(error?.message); + + toast(error?.message, { + className: "!bg-red-500 !text-black", + }); + }, + }); + + // Add + // ............'Mutation' Add News Submit + const AddNewsMutation = useMutation({ + mutationKey: ["AddNews"], + mutationFn: SubmitNews, + onSuccess: (res) => { + console.log(res); + console.log("Success Change News"); + setOpenAdd(false); + + refetch1(); + + toast("عملیات شما با موفقیت انجام شد. ", { + className: "!bg-green-500 !text-white", + }); + }, + onError: (error) => { + console.log(error); + console.log(error?.message); + + setOpenAdd(false); + + toast(error?.message, { + className: "!bg-red-500 !text-black", + }); + }, + }); + + function onSubmitEdit(data: EditNewsFormValues) { + const formData = new FormData(); + formData.append("Title", data.titleNews); + if (data?.uploadImg instanceof File) { + formData.append("Image", data.uploadImg); + } + formData.append("Url", data.urlNews); + formData.append("Description", data.description); + formData.append("Content", data.content); + + // if (data?.media && data?.media?.length > 0) { + // for (let i = 0; i < data.media.length; i++) { + // formData.append("Medias", data.media[i]); + // } + // } + ChangeNewsMutation.mutate({ id: keyId, payload: formData }); + + refetch1(); + resetField("Title"); + resetField("Image"); + resetField("Url"); + resetField("Description"); + resetField("Content"); + + console.log(data); + } + const { resetField } = useForm(); + + function onSubmitAdd(data: AddNewsFormValues) { + const formData = new FormData(); + formData.append("Title", data.titleNews); + formData.append("Url", data.urlNews); + formData.append("Description", data.description); + formData.append("Content", data.content); + + if (data?.uploadImg instanceof File) { + formData.append("Image", data.uploadImg); + } + + AddNewsMutation.mutate(formData); + + console.log(data); + } + return ( -
AdminNews
- ) +
+
+
+ {/* 1 */} +
+ لیست خبر ها +
+ {/* 2 */} + + {/* 1 */} + + + + + + + +

+ افزودن خبر +

+ + + +
+ + +
+
+ +
+ ( + + عنوان خبر + + + + + + )} + /> + + { + // Get current uploadFile value (always watched updated) + const uploadImg = formAdd.watch("uploadImg"); + var filename: string | undefined = undefined; + + if (uploadImg) { + const file: File | null = uploadImg || null; + + if (file) { + // Check if the file is an image + const allowedImageTypes = [ + "image/jpeg", + "image/png", + "image/webp", + "image/jpg", + ]; + + if (allowedImageTypes.includes(file.type)) { + // Valid image file type + filename = file.name; + } else { + // Invalid file type + // You may want to display an error message or take appropriate action + console.error( + "Invalid file type. Only images (JPEG, PNG, GIF) are allowed." + ); + } + } + } + + return ( + + + پیوست + + {/* File Upload */} + + { + const newFile = event.target.files?.[0]; + onChange(newFile); + }} + /> + + {/* Show File Name */} + {/* {filename} */} + + + ); + }} + /> + + ( + + لینک + + + + + + )} + /> + + ( + + توضیحات + +