Added Violation component and modifeid Comment Componnent and Delete Component

thats all related to  RequestComponent
master
YasamanKahdooei 2024-05-30 15:00:41 +03:30
parent d82592c189
commit f8d9513d6a
6 changed files with 282 additions and 108 deletions

View File

@ -46,7 +46,7 @@ function RecentRequests() {
<div className="w-full rounded-md bg-rose-100"> <div className="w-full rounded-md bg-rose-100">
<div id="map" aria-label="نقشه"> <div id="map" aria-label="نقشه">
{/* <OnMapRequests /> */} {/* <OnMapRequests /> */}
<ComponentMap /> {/* <ComponentMap /> */}
</div> </div>
</div> </div>

View File

@ -15,6 +15,8 @@ import { convertFullTime } from "@/lib/utils";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import RequestViolations from "./RequestViolations"; import RequestViolations from "./RequestViolations";
import { postReportViolation } from "@/utils/CitizenReport";
// interface RequestCardProps { // interface RequestCardProps {
// isSelfRequest?: boolean; // isSelfRequest?: boolean;
// } // }
@ -42,6 +44,16 @@ interface RequestCardProps {
isSelfRequest?: boolean; isSelfRequest?: boolean;
} }
// Define the post violation function type
type PostViolationArgs = {
id: string;
payload: {
instanceId: number;
violationTypeId: number;
description: string;
};
};
const RequestCard: React.FC<RequestCardProps> = ({ item, isSelfRequest }) => { const RequestCard: React.FC<RequestCardProps> = ({ item, isSelfRequest }) => {
const router = useRouter(); const router = useRouter();
@ -50,6 +62,15 @@ const RequestCard: React.FC<RequestCardProps> = ({ item, isSelfRequest }) => {
router.push(`/User/MyRequest/${item.id}`); router.push(`/User/MyRequest/${item.id}`);
} }
}; };
// Correctly wrapped function
const wrappedPostReportViolation = async ({
id,
payload,
}: PostViolationArgs) => {
return postReportViolation(id, payload);
};
return ( return (
// <div className="overflow-x-hidden overflow-y-scroll pl-5 scrollbar-thin scrollbar-thumb-yellow scrollbar-track-white"> // <div className="overflow-x-hidden overflow-y-scroll pl-5 scrollbar-thin scrollbar-thumb-yellow scrollbar-track-white">
<> <>
@ -105,13 +126,22 @@ const RequestCard: React.FC<RequestCardProps> = ({ item, isSelfRequest }) => {
<div className="w-full flex items-center justify-between mb-[10px]"> <div className="w-full flex items-center justify-between mb-[10px]">
<RequestProcessIcon /> <RequestProcessIcon />
<div className="flex items-center justify-center"> <div className="flex items-center justify-center">
<RequestViolations /> {/* <RequestViolations reportId={item.id} /> */}
<RequestViolations
reportId={item.id}
mutationFn={wrappedPostReportViolation}
/>
<RequestLike <RequestLike
reportId={item.id} reportId={item.id}
initialIsLiked={item.isLiked} initialIsLiked={item.isLiked}
initialLikes={item.likes} initialLikes={item.likes}
/> />
<RequestComments reportId={item.id} commentsCount={item.commentsCount}/> <RequestComments
reportId={item.id}
commentsCount={item.commentsCount}
/>
</div> </div>
</div> </div>
</div> </div>

View File

@ -5,9 +5,10 @@ import RequestViolation from "./RequestViolation";
import { BsTrash3 } from "react-icons/bs"; import { BsTrash3 } from "react-icons/bs";
import ph from "@/assets/images/ph.png"; import ph from "@/assets/images/ph.png";
import Image from "next/image"; import Image from "next/image";
import { useMutation } from "@tanstack/react-query"; import { useMutation, useQueryClient } from "@tanstack/react-query";
import { deleteComment } from "@/utils/CitizenReport"; import { deleteComment, postCommentViolation } from "@/utils/CitizenReport";
import { toast } from "sonner"; import { toast } from "sonner";
import RequestViolations from "./RequestViolations";
interface RequestCommentProps { interface RequestCommentProps {
id: string; id: string;
@ -15,9 +16,21 @@ interface RequestCommentProps {
dateTime: string; dateTime: string;
user: any; user: any;
canDelete: boolean; canDelete: boolean;
onDeleteCommentSuccess:any onDeleteCommentSuccess: any;
commentsCount: () => void;
} }
// Define the post violation function type
type PostViolationArgs = {
id: string;
payload: {
instanceId: number;
violationTypeId: number;
description: string;
};
};
const getUserTitle = (user: any) => { const getUserTitle = (user: any) => {
if (user.firstName || user.lastName) if (user.firstName || user.lastName)
return `${user.firstName || ""} ${user.lastName || ""}`; return `${user.firstName || ""} ${user.lastName || ""}`;
@ -32,14 +45,18 @@ const RequestComment: React.FC<RequestCommentProps> = ({
user, user,
canDelete, canDelete,
onDeleteCommentSuccess, onDeleteCommentSuccess,
commentsCount,
}) => { }) => {
const queryClient = useQueryClient();
const DeleteComment = useMutation({ const DeleteComment = useMutation({
mutationKey: ["deleteComment"], mutationKey: ["deleteComment"],
mutationFn: deleteComment, mutationFn: deleteComment,
onSuccess: (res) => { onSuccess: (res) => {
queryClient.invalidateQueries({ queryKey: ["Comments"] });
commentsCount();
toast(<>{res.message}</>, { toast(<>{res.message}</>, {
className: "!bg-green !text-black", className: "!bg-green !text-black flex justify-end",
}); });
}, },
onError: (error: any | string) => { onError: (error: any | string) => {
@ -53,6 +70,13 @@ const RequestComment: React.FC<RequestCommentProps> = ({
const handelDelete = () => { const handelDelete = () => {
DeleteComment.mutate(id); DeleteComment.mutate(id);
}; };
// Correctly wrapped function
const wrappedPostCommentViolation = async ({
id,
payload,
}: PostViolationArgs) => {
return postCommentViolation(id, payload);
};
return ( return (
<div className="flex w-full items-stretch mb-3 p-2 border-b-[1px] border-b-gray-200 last:border-b-0"> <div className="flex w-full items-stretch mb-3 p-2 border-b-[1px] border-b-gray-200 last:border-b-0">
@ -88,9 +112,15 @@ const RequestComment: React.FC<RequestCommentProps> = ({
{comment} {comment}
</p> </p>
{canDelete && ( {canDelete && (
<BsTrash3 className="text-red cursor-pointer" onClick={handelDelete} /> <BsTrash3
className="text-red cursor-pointer"
onClick={handelDelete}
/>
)} )}
<RequestViolation /> <RequestViolations
reportId={id}
mutationFn={wrappedPostCommentViolation}
/>
</div> </div>
</div> </div>
</div> </div>

View File

@ -33,7 +33,7 @@ interface Comment {
dateTime: string; dateTime: string;
user: any; user: any;
canDelete: boolean; canDelete: boolean;
onDeleteCommentSuccess:any onDeleteCommentSuccess: any;
} }
// Define the post comment function type // Define the post comment function type
@ -75,8 +75,8 @@ const RequestComments: React.FC<RequestCommentsProps> = ({
setCommentText(""); setCommentText("");
// Increment the comments count // Increment the comments count
setCommentsCounts((prevCount) => prevCount + 1); setCommentsCounts((prevCount) => prevCount + 1);
toast("successfully", { toast("نظر شما با موفقیت ثبت شد", {
className: "!bg-green !text-black", className: "!bg-green !text-black flex justify-end",
}); });
}, },
onError: (error) => { onError: (error) => {
@ -129,6 +129,9 @@ const RequestComments: React.FC<RequestCommentsProps> = ({
user={comment.user} user={comment.user}
canDelete={comment.canDelete} canDelete={comment.canDelete}
onDeleteCommentSuccess={refetch()} onDeleteCommentSuccess={refetch()}
commentsCount={() =>
setCommentsCounts((prev) => prev - 1)
}
/> />
</> </>
))} ))}

View File

@ -29,27 +29,54 @@ import {
import { import {
Select, Select,
SelectContent, SelectContent,
SelectGroup,
SelectItem, SelectItem,
SelectLabel,
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} from "../ui/select"; } from "../ui/select";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
import { z } from "zod"; import { z } from "zod";
import { postReportViolation } from "@/utils/CitizenReport";
import { toast } from "sonner";
import { FaCheckCircle } from "react-icons/fa";
const formSchema = z.object({ interface RequestViolationsProps {
violationTypeId: z.string({ reportId: string;
required_error: "لطفا دسته بندی را انتخاب نمایید.", mutationFn: ({ id, payload }: PostViolationArgs) => Promise<any>;
}), }
description: z.string(),
});
const RequestViolations = ({ request = {}, comment = {}, type = "" }) => { // 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 // states
const [currentStep, setCurrentStep] = useState<number>(1);
const [violationType, setViolationType] = useState(""); const [violationType, setViolationType] = useState("");
const [instanceId, setInstanceId] = useState<number>(1);
const [violationDescription, setViolationDescription] = useState(""); const [violationDescription, setViolationDescription] = useState("");
const [charCount, setCharCount] = useState(0); 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 { const {
data: violationTypes, data: violationTypes,
@ -64,11 +91,16 @@ const RequestViolations = ({ request = {}, comment = {}, type = "" }) => {
}); });
// functions // functions
const onSelectType = (vT: string) => (e: any) => { // const onSelectType = (vT: string) => (e: any) => {
e.stopPropagation(); // e.stopPropagation();
setViolationType(vT); // setViolationType(vT);
setCurrentStep((prev) => prev + 1); // setCurrentStep((prev) => prev + 1);
}; // };
const formSchema = z.object({
violationTypeId: z.string().nonempty("لطفا دسته بندی را انتخاب نمایید."),
description: z.string(),
});
// 1. Define your form. // 1. Define your form.
const form = useForm<z.infer<typeof formSchema>>({ const form = useForm<z.infer<typeof formSchema>>({
@ -83,33 +115,75 @@ const RequestViolations = ({ request = {}, comment = {}, type = "" }) => {
setCharCount(form.watch("description").length); setCharCount(form.watch("description").length);
}, [form.watch("description")]); }, [form.watch("description")]);
// 2. Define a submit handler. const violationMutation = useMutation({
function onSubmit(values: z.infer<typeof formSchema>) { mutationKey: ["violationMutation"],
// Do something with the form values. // mutationFn: ({ id, payload }: PostViolationArgs) =>
// ✅ This will be type-safe and validated. // postReportViolation(id, payload),
console.log(values); 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>) {
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,
},
});
} }
const handleSubmit = () => {};
return ( return (
<Dialog> <>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild> <DialogTrigger asChild>
{/* <Button variant="outline">Share</Button> */} {/* <Button variant="outline">Share</Button> */}
<FaRegFlag className="text-lg mx-1 cursor-pointer" /> <FaRegFlag className="text-lg mx-1 cursor-pointer" />
</DialogTrigger> </DialogTrigger>
<DialogContent className="sm:max-w-md"> <DialogContent className="sm:max-w-xl">
<div className=""> <div className="">
<Form {...form}> <Form {...form}>
<form <form
onSubmit={form.handleSubmit(onSubmit)} onSubmit={form.handleSubmit(onSubmit)}
className="flex flex-col w-full mt-6" className="flex flex-col gap-8 w-full mt-6"
> >
<FormField <FormField
control={form.control} control={form.control}
name="violationTypeId" name="violationTypeId"
render={({ field }) => ( render={({ field }) => (
<FormItem className="w-full"> <FormItem className="w-full mb-4">
{/* <FormLabel className="text-[#7C838A] text-sm font-medium mt-7"> {/* <FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
عنوان تخلف عنوان تخلف
</FormLabel> */} </FormLabel> */}
@ -119,16 +193,21 @@ const RequestViolations = ({ request = {}, comment = {}, type = "" }) => {
dir="rtl" dir="rtl"
> >
<FormControl> <FormControl>
<SelectTrigger className="bg-slate-200"> <SelectTrigger className="bg-white">
<SelectValue placeholder=" عنوان تخلف" /> <SelectValue placeholder=" عنوان تخلف" />
</SelectTrigger> </SelectTrigger>
</FormControl> </FormControl>
<SelectContent> <SelectContent>
{violationTypes?.data.map((Items: any, index: any) => ( <SelectGroup>
<SelectItem key={index} value={Items.id}> {/* <SelectLabel>Fruits</SelectLabel> */}
{violationTypes?.data.map(
(Items: any, index: any) => (
<SelectItem key={index} value={Items.title}>
{Items.title} {Items.title}
</SelectItem> </SelectItem>
))} )
)}
</SelectGroup>
</SelectContent> </SelectContent>
</Select> </Select>
<FormMessage className="mt-2 " /> <FormMessage className="mt-2 " />
@ -147,7 +226,7 @@ const RequestViolations = ({ request = {}, comment = {}, type = "" }) => {
<FormControl> <FormControl>
<Textarea <Textarea
placeholder=" توضیحات خود را بنویسید" placeholder=" توضیحات خود را بنویسید"
className="mb-3 resize-none" className=" resize-none bg-white text-black text-sm "
{...field} {...field}
/> />
</FormControl> </FormControl>
@ -155,11 +234,46 @@ const RequestViolations = ({ request = {}, comment = {}, type = "" }) => {
</FormItem> </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>
</Form> </Form>
</div> </div>
</DialogContent> </DialogContent>
</Dialog> </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>
</>
); );
}; };

View File

@ -133,10 +133,9 @@ export async function postCommentViolation(
id: string, id: string,
payload: { instanceId: number; violationTypeId: number; description: string } payload: { instanceId: number; violationTypeId: number; description: string }
) { ) {
const data = await axios.post(`/api/CitizenReport/CommentViolation/${id}`, { const data = await axios.post(`/api/CitizenReport/CommentViolation/${id}`,payload);
payload,
});
return data.data; return data.data;
} }
// Post CitizenReport ReportViolation {id} // Post CitizenReport ReportViolation {id}
@ -144,8 +143,6 @@ export async function postReportViolation(
id: string, id: string,
payload: { instanceId: number; violationTypeId: number; description: string } payload: { instanceId: number; violationTypeId: number; description: string }
) { ) {
const data = await axios.post(`/api/CitizenReport/ReportViolation/${id}`, { const data = await axios.post(`/api/CitizenReport/ReportViolation/${id}`,payload);
payload,
});
return data.data; return data.data;
} }