shahrbin-citizen/components/Requests/RequestViolations.tsx

285 lines
8.8 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, { MouseEventHandler, useEffect, useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { getViolationTypes } from "@/utils/CitizenCommon";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "../ui/textarea";
import { Oval } from "react-loader-spinner";
import { FaRegFlag } from "react-icons/fa";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "../ui/form";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from "../ui/select";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { postReportViolation } from "@/utils/CitizenReport";
import { toast } from "sonner";
import { FaCheckCircle } from "react-icons/fa";
interface RequestViolationsProps {
reportId: string;
mutationFn: ({ id, payload }: PostViolationArgs) => Promise<any>;
}
// Define the post violation function type
type PostViolationArgs = {
id: string;
payload: {
instanceId: number;
violationTypeId: number;
description: string;
};
};
const RequestViolations: React.FC<RequestViolationsProps> = ({
reportId,
mutationFn,
}) => {
// states
const [violationType, setViolationType] = useState("");
const [instanceId, setInstanceId] = useState<number>(1);
const [violationDescription, setViolationDescription] = useState("");
const [charCount, setCharCount] = useState(0);
const [currentStep, setCurrentStep] = useState<number>(1);
const [open, setOpen] = useState<boolean>();
const [open2, setOpen2] = useState<boolean>(false);
useEffect(() => {
const CtizenInstances = localStorage.getItem("SH_CT_INSTANCE");
if (CtizenInstances) {
const parsedItem = JSON.parse(CtizenInstances);
setInstanceId(parsedItem.id);
}
}, []);
const {
data: violationTypes,
isLoading,
isError,
isSuccess,
refetch,
} = useQuery({
queryKey: ["Violation"],
queryFn: () => getViolationTypes(),
// refetchOnWindowFocus: false,
});
// functions
// const onSelectType = (vT: string) => (e: any) => {
// e.stopPropagation();
// setViolationType(vT);
// setCurrentStep((prev) => prev + 1);
// };
const formSchema = z.object({
violationTypeId: z.string().nonempty("لطفا دسته بندی را انتخاب نمایید."),
description: z.string(),
});
// 1. Define your form.
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
violationTypeId: "",
description: "",
},
});
useEffect(() => {
setCharCount(form.watch("description").length);
}, [form.watch("description")]);
const violationMutation = useMutation({
mutationKey: ["violationMutation"],
// mutationFn: ({ id, payload }: PostViolationArgs) =>
// postReportViolation(id, payload),
mutationFn: mutationFn,
onSuccess: (res) => {
// toast(<>{"گزارش شما با موفقیت ثبت شد"}</>, {
// className: "!bg-green !text-white flex justify-end",
// });
setOpen(false);
setOpen2(true);
},
onError: (err: any | string) => {
toast(<>{err.response.data.detail}</>, {
className: "!bg-rose-800 !text-white",
});
refetch();
},
});
// Function to search for an ID based on the title
function findViolationTypeIdByTitle(title: string) {
if (violationTypes?.data) {
const foundItem = violationTypes.data.find(
(item: any) => item.title === title
);
return foundItem ? foundItem.id : null;
}
return null;
}
// 2. Define a submit handler.
function onSubmit(values: z.infer<typeof formSchema>) {
// e.stopPropagation();
console.log(values);
setViolationType(values.violationTypeId);
setViolationDescription(values.description);
const violationId = findViolationTypeIdByTitle(values.violationTypeId);
violationMutation.mutate({
id: reportId,
payload: {
instanceId: instanceId,
violationTypeId: violationId,
description: values.description,
},
});
}
return (
<>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
{/* <Button variant="outline">Share</Button> */}
<FaRegFlag className="text-lg mx-1 cursor-pointer"
onClick={(e) => e.stopPropagation()}
/>
</DialogTrigger>
<DialogContent className="sm:max-w-xl">
<div className="">
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="flex flex-col gap-8 w-full mt-6"
>
<FormField
control={form.control}
name="violationTypeId"
render={({ field }) => (
<FormItem className="w-full mb-4">
{/* <FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
عنوان تخلف
</FormLabel> */}
<Select
onValueChange={field.onChange}
defaultValue={field.value}
dir="rtl"
>
<FormControl>
<SelectTrigger className="bg-white">
<SelectValue placeholder=" عنوان تخلف" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectGroup>
{/* <SelectLabel>Fruits</SelectLabel> */}
{violationTypes?.data.map(
(Items: any, index: any) => (
<SelectItem key={index} value={Items.title}>
{Items.title}
</SelectItem>
)
)}
</SelectGroup>
</SelectContent>
</Select>
<FormMessage className="mt-2 " />
</FormItem>
)}
/>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel className="text-[#7C838A] text-sm font-medium">
توضیحات ({charCount}/1024)
</FormLabel>
<FormControl>
<Textarea
placeholder=" توضیحات خود را بنویسید"
className=" resize-none bg-white text-black text-sm "
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* <DialogClose asChild> */}
<Button
type="submit"
className="w-1/2 p-2 text-center text-black sm:w-1/3 lg:w-1/4 bg-yellow hover:bg-yellow rounded-xl self-end"
>
{/* {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>
{/* </DialogClose> */}
</form>
</Form>
</div>
</DialogContent>
</Dialog>
<Dialog open={open2} onOpenChange={setOpen2}>
<DialogContent>
<div className="flex flex-col justify-center items-center gap-8">
<FaCheckCircle className="text-green w-12 h-12 " />
<p className="text-green text-sm">
شهروند گرامی، گزارش تخلف شما ثبت شد و در اسرع وقت بررسی می‌گردد.
</p>
</div>
</DialogContent>
</Dialog>
</>
);
};
export default RequestViolations;