Sootzani/components/RequestStep2.tsx

579 lines
21 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"use client";
import React, { useEffect, useState } from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import Link from "next/link";
import RequestResult from "./RequestResult";
import Image from "next/image";
import Img1 from "../public/img/logo.png";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
postAuthorizedComplaintSubmit,
postComplaintSubmit,
} from "@/utils/citizenApi";
import { useRouter } from "next/navigation";
import {
getCaptcha,
getCategory,
getOptions,
getOrganizations,
} from "@/utils/commonApi";
import { Oval, ThreeDots } from "react-loader-spinner";
import useToken from "@/store/useToken";
import { toast } from "sonner";
import { Eye, RefreshCcw, Upload } from "lucide-react";
import { getCookie } from "cookies-next";
import { formatBytes } from "@/lib/utils";
import AttachmentsDialog from "./AttachmentsDialog";
import { DialogTrigger } from "./ui/dialog";
interface Organization {
title: string;
description: string;
isDeleted: string;
id: string;
}
export default function RequestStep2() {
const router = useRouter();
const [file, setFile] = useState<File[]>([]);
const [charCount, setCharCount] = useState(0);
// Queries
const { data: optionsData, isLoading: isLoadingData } = useQuery({
queryKey: ["Options"],
queryFn: () => getOptions(),
refetchOnWindowFocus: false,
});
const FormSchema = z.object({
title: z.string().min(1, {
message: "لطفا موضوع شکایت را وارد نمایید.",
}),
OrganizationId: z.string({
required_error: "لطفا دستگاه مربوطه را انتخاب نمایید.",
}),
person: z.string().optional(),
description: z
.string()
.min(1, {
message: "لطفا توضیحات خود را بنویسید.",
})
.max(optionsData?.maxTextLength, {
message: "تعداد کاراکترها بیشتر از حد مجاز میباشد.",
}),
uploadFile: z
.custom<File[]>()
// .refine((files) => files.length > 0, `Required`)
.refine(
(files) => files.length <= optionsData?.maxFileCount,
`تعداد فایل های پیوست شده می بایست حداکثر ${optionsData?.maxFileCount} عدد باشد.`
)
.refine(
(files) => files.every((item) => item.size < optionsData?.maxFileSize),
`حجم هر فایل حداکثر می بایست ${formatBytes(
optionsData?.maxFileSize
)} باشد.`
)
.nullish(),
categoryId: z.string({
required_error: "لطفا دسته بندی را انتخاب نمایید.",
}),
captchaValue: z.string().min(1, {
message: "لطفا کد امنیتی را وارد نمایید.",
}),
});
const complaintSubmitMutation = useMutation({
mutationKey: ["complaintSubmit"],
mutationFn: postComplaintSubmit,
onSuccess: (res) => {
localStorage.setItem("trackingNumber", res.trackingNumber);
localStorage.setItem("password", res.password);
localStorage.removeItem("unknown");
router.push("/RequestResult");
},
onError: (err: any | string) => {
refetch();
toast(<>{err.response.data.detail}</>, {
className: "!bg-red-500 !text-white",
});
},
});
const authorizedComplaintSubmitMutation = useMutation({
mutationKey: ["authorizedComplaintSubmit"],
mutationFn: postAuthorizedComplaintSubmit,
onSuccess: (res) => {
const currentDate = new Date();
const formattedDate = currentDate.toISOString();
localStorage.setItem("trackingNumber", res.trackingNumber);
localStorage.setItem("password", res.password);
// localStorage.setItem("registeredAt", res.registeredAt);
localStorage.setItem("registeredAt", formattedDate);
localStorage.removeItem("authorized");
localStorage.removeItem("unknown");
router.push("/RequestResult");
},
onError: (err: any | string) => {
refetch();
toast(<>{err.response.data.detail}</>, {
className: "!bg-red-500 !text-white",
});
},
});
// All Category
const { data: categoryData } = useQuery({
queryKey: ["Category"],
queryFn: () => getCategory(),
});
const { data: organizationsData } = useQuery({
queryKey: ["organizations"],
queryFn: () => getOrganizations(),
});
// Captcha
const {
data: CaptchaData,
isLoading,
refetch,
} = useQuery({
queryKey: ["Captcha"],
queryFn: () => getCaptcha(),
});
const srcForImage = CaptchaData
? URL.createObjectURL(CaptchaData.data)
: null;
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
defaultValues: {
title: "",
person: "",
description: "",
captchaValue: "",
// uploadFile: null,
},
});
// Add the useEffect hook to monitor changes in the description field
useEffect(() => {
setCharCount(form.watch("description").length);
}, [form.watch("description")]);
function handleDescriptionChange(event: React.ChangeEvent<HTMLTextAreaElement>) {
const newCharCount = event.target.value.length;
// Update charCount only when the user types or removes characters
if (newCharCount <= optionsData?.maxTextLength) {
setCharCount(newCharCount);
}
}
function onSubmit(data: z.infer<typeof FormSchema>) {
console.log(data);
const formData = new FormData();
formData.append("Title", data.title);
formData.append("Text", data.description);
formData.append("CategoryId", data.categoryId);
if (data?.uploadFile && data?.uploadFile?.length > 0) {
for (let i = 0; i < data.uploadFile.length; i++) {
formData.append("Medias", data.uploadFile[i]);
}
}
formData.append("Captcha.Value", data.captchaValue);
formData.append("Captcha.Key", CaptchaData?.headers["captcha-key"]);
formData.append("Complaining", data.person ? data.person : "-");
formData.append("OrganizationId", data.OrganizationId);
const unknown = localStorage.getItem("unknown");
const isAuth = getCookie("Sootzani_Token");
if (isAuth && !unknown) {
authorizedComplaintSubmitMutation.mutate({
Data: formData,
});
} else {
complaintSubmitMutation.mutate({
Data: formData,
});
}
resetField("Title");
resetField("Text");
resetField("Medias");
resetField("CategoryId");
resetField("Captcha.Value");
}
const { resetField } = useForm();
const deleteFileFromAttachments = (File: any) => {
const filtered = file?.filter((item) => item.name !== File);
setFile(filtered);
form.setValue("uploadFile", filtered);
};
const allowedExtensions = optionsData?.allowedExtensions;
const split = allowedExtensions?.split(",");
const withDot = split?.map((item: string) => "." + item);
const newAllowedExtensions = withDot?.join(",");
const formatSize = (size: number) => {
const string = formatBytes(size);
return (
<span className="" dir="ltr">
{string}
</span>
);
};
return (
<div className="w-full h-full pt-12 sm:w-2/3 md:w-2/4 max-sm:p-8">
<div className="flex flex-col justify-center h-full space-y-3 md:space-y-4">
<p className="text-sm font-bold leading-tight tracking-tight md:text-base text-blue dark:text-white">
لطفا جهت ارسال درخواست فرم زیر را تکمیل نمایید.
</p>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="flex flex-col w-full mt-6"
>
<FormField
control={form.control}
name="title"
render={({ field }) => (
<FormItem>
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
*موضوع گزارش
</FormLabel>
<FormControl>
<Input
placeholder="موضوع گزارش خود را بنویسید"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex flex-row flex-wrap justify-between">
<FormField
control={form.control}
name="OrganizationId"
render={({ field }) => (
<FormItem className=" w-full sm:w-[48%]">
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
*واحد مورد گزارش
</FormLabel>
<Select
onValueChange={field.onChange}
defaultValue={field.value}
dir="rtl"
>
<FormControl>
<SelectTrigger
className=" bg-slate-200 !text-[#7C838A]"
dir="rtl"
>
<SelectValue
className=""
placeholder="واحد مورد گزارش را انتخاب نمایید."
/>
</SelectTrigger>
</FormControl>
<SelectContent dir="rtl">
<SelectGroup>
{organizationsData?.map((item: any) => {
return (
<SelectItem key={item.id} value={item.id}>
{item.title}
</SelectItem>
);
})}
</SelectGroup>
</SelectContent>
</Select>
<FormMessage className="mt-2 " />
</FormItem>
)}
/>
<FormField
control={form.control}
name="person"
render={({ field }) => (
<FormItem className=" w-full sm:w-[48%]">
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
فرد مربوطه
</FormLabel>
<FormControl>
<Input
placeholder="نام فرد مورد نظر خود را بنویسید"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
توضیحات ({charCount}/{optionsData?.maxTextLength})
</FormLabel>
<FormControl>
<Textarea
placeholder=" توضیحات خود را بنویسید"
className="mb-3 resize-none"
{...field}
onChange={(e) => {
const currentValue = e.target.value;
if (currentValue.length <= optionsData?.maxTextLength) {
field.onChange(e);
handleDescriptionChange(e);
} else {
// Truncate the value to the allowed limit
field.onChange(currentValue.substring(0, optionsData?.maxTextLength));
}
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex flex-row flex-wrap justify-between mb-2">
{/* Select Option */}
<FormField
control={form.control}
name="categoryId"
render={({ field }) => (
<FormItem className="w-full sm:w-[48%] flex-row-reverse">
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
انتخاب دسته بندی
</FormLabel>
<Select
onValueChange={field.onChange}
defaultValue={field.value}
dir="rtl"
>
<FormControl>
<SelectTrigger className="bg-slate-200">
<SelectValue placeholder=" دسته بندی ها" />
</SelectTrigger>
</FormControl>
<SelectContent>
{categoryData?.map((catItems: any, index: any) => (
<SelectItem key={index} value={catItems.id}>
{catItems.title}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage className="mt-2 " />
</FormItem>
)}
/>
{/* uploadFile */}
<FormField
control={form.control}
name="uploadFile"
render={({ fieldState: { error }, field }) => {
// Get current uploadFile value (always watched updated)
const uploadFile = form.watch("uploadFile");
var filenames: string[] | undefined = undefined;
if (uploadFile) {
// 1. covert to File[] using Array.from
const files: File[] = Array.from(uploadFile);
// 2. now you can use array methods on files;
filenames = files.map((file) => file?.name);
}
return (
<FormItem className="w-full sm:w-[48%]">
<FormLabel className=" text-[#7C838A] text-sm mt-7">
پیوست‌ها (
{field?.value?.length ? field.value.length : 0})
</FormLabel>
<div className="flex gap-2 w-full items-center">
<AttachmentsDialog
attachments={file}
deleteFile={(item) => deleteFileFromAttachments(item)}
>
<DialogTrigger className=" bg-slate-200 rounded-md h-9 text-xs flex-1 flex gap-2 items-center justify-center">
<Eye className=" w-4 h-4" />
<p>مشاهده</p>
</DialogTrigger>
</AttachmentsDialog>
<label
htmlFor="fileInput"
className="cursor-pointer text-sm rounded-md grid place-content-center h-9 px-2 bg-slate-200 w-1/2 items-center"
>
<div className=" flex gap-2 justify-center items-center">
<p className="text-xs flex gap-2 items-center">
<Upload className=" w-4 h-4" />
<span>افزودن</span>
</p>
</div>
</label>
<input
id="fileInput"
type="file"
className="hidden"
accept={newAllowedExtensions}
multiple
onChange={(e) => {
// field.onChange(e.target.files ? e.target.files : null);
if (file && e.target.files) {
const fileArray1 = Array.from(file);
const fileArray2 = Array.from(e.target.files);
const mergedArray = fileArray1.concat(fileArray2);
setFile(mergedArray);
field.onChange(mergedArray);
} else if (!file && e.target.files) {
const fileArray2 = Array.from(e.target.files);
setFile(fileArray2);
field.onChange(fileArray2);
}
}}
/>
</div>
{/* {!error ? (
<FormDescription className=" text-xs my-1 ">
<span>
حجم هر فایل حداکثر می بایست{" "}
{formatSize(optionsData?.maxFileSize)} مگابایت باشد
</span>{" "}
و{" "}
{`تعداد فایل های پیوست شده می بایست حداکثر ${optionsData?.maxFileCount} تا باشد.`}
</FormDescription>
) : (
<FormMessage />
)} */}
<FormMessage />
</FormItem>
);
}}
/>
</div>
{/* Captcha */}
<div className="flex flex-row justify-between items-center w-full lg:w-[48%] gap-2">
<FormField
control={form.control}
name="captchaValue"
render={({ field }) => (
<FormItem className="w-1/2 ">
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
*کد امنیتی
</FormLabel>
<FormControl>
<Input
placeholder="کد تصویر روبرو را وارد کنید "
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{isLoading ? (
<div className=" w-1/2 max-w[11rem] flex justify-center text-center">
<ThreeDots
visible={true}
height="50"
width="50"
color="#003778"
radius="9"
ariaLabel="three-dots-loading"
wrapperStyle={{}}
wrapperClass=""
/>
</div>
) : (
<div className=" w-1/2 max-w[11rem] flex justify-center items-center text-center gap-2">
<Image
alt="icon"
src={srcForImage as string}
className="h-12 rounded-md shadow-md w-4/5"
width={150}
height={20}
quality={100}
/>
<RefreshCcw
className="cursor-pointer w-1/5"
onClick={() => refetch()}
color="#003778"
/>
</div>
)}
</div>
<div className="flex justify-center w-full gap-2 mt-4 sm:justify-end">
<Button
type="submit"
className="w-1/2 p-2 mb-4 text-center text-white sm:w-1/3 lg:w-1/4 bg-blue rounded-xl"
>
{authorizedComplaintSubmitMutation.isPending ||
complaintSubmitMutation.isPending ? (
<div className="flex items-center justify-center gap-2">
<Oval
visible={true}
height="20"
width="20"
color="#fff"
ariaLabel="oval-loading"
wrapperStyle={{}}
wrapperClass=""
/>
</div>
) : (
"ارسال درخواست"
)}
</Button>
</div>
</form>
</Form>
</div>
</div>
);
}