From 5f094aa2e6157ce10ede8a79ebd4c9615dfac4bc Mon Sep 17 00:00:00 2001 From: Pramod Mahajan Date: Tue, 15 Apr 2025 00:36:20 +0530 Subject: [PATCH] added CreateActivity and EditActivity components. --- src/components/master/CreateActivity.jsx | 304 +++++++++++++---------- src/components/master/EditActivity.jsx | 297 +++++++++++++--------- 2 files changed, 353 insertions(+), 248 deletions(-) diff --git a/src/components/master/CreateActivity.jsx b/src/components/master/CreateActivity.jsx index 604adeea..8493c2ac 100644 --- a/src/components/master/CreateActivity.jsx +++ b/src/components/master/CreateActivity.jsx @@ -1,26 +1,30 @@ -import React,{useState,useEffect} from 'react' -import {useFieldArray, useForm } from 'react-hook-form'; -import { z } from 'zod'; -import {zodResolver} from '@hookform/resolvers/zod'; +import React, { useState, useEffect } from "react"; +import { useFieldArray, useForm } from "react-hook-form"; +import { z } from "zod"; +import { zodResolver } from "@hookform/resolvers/zod"; -import { MasterRespository } from '../../repositories/MastersRepository'; -import { clearApiCacheKey } from '../../slices/apiCacheSlice'; -import { getCachedData,cacheData } from '../../slices/apiDataManager'; -import showToast from '../../services/toastService'; +import { MasterRespository } from "../../repositories/MastersRepository"; +import { clearApiCacheKey } from "../../slices/apiCacheSlice"; +import { getCachedData, cacheData } from "../../slices/apiDataManager"; +import showToast from "../../services/toastService"; const schema = z.object({ activityName: z.string().min(1, { message: "Role is required" }), unitOfMeasurement: z.string().min(1, { message: "Description is required" }), checkList: z - .array(z.string().min(1, { message: "Checklist item cannot be empty" })) - .optional(), - }); - -const CreateActivity = ({onClose}) => -{ + .array( + z.object({ + check: z.string().min(1, { message: "Checklist item cannot be empty" }), + isMandatory: z.boolean().default(false), + id: z.any().default(0), + }) + ) + .optional(), +}); + +const CreateActivity = ({ onClose }) => { + const [isLoading, setIsLoading] = useState(false); - const [ isLoading, setIsLoading ] = useState( false ) - const { register, handleSubmit, @@ -34,147 +38,197 @@ const CreateActivity = ({onClose}) => } = useForm({ resolver: zodResolver(schema), defaultValues: { - activityName: '', - unitOfMeasurement: '', + activityName: "", + unitOfMeasurement: "", checkList: [], }, }); - // Setting up field array for checkList (dynamic fields) + const { fields: checkListItems, append, remove, } = useFieldArray({ control, - name: 'checkList', + name: "checkList", }); // Form submission handler - const onSubmit = ( data ) => - { - console.log(data) - setIsLoading(true) - - - MasterRespository.updateActivity(data).then((resp)=>{ - setIsLoading(false) - - const cachedData = getCachedData("Activity"); - const updatedData = [...cachedData, resp?.data]; - cacheData("Activity", updatedData); - showToast("Activity Added successfully.", "success"); + const onSubmit = (data) => { + console.log(data); + setIsLoading(true); - onClose() - }).catch((error)=>{ - showToast(error.message, "error"); - setIsLoading(false) - }) + MasterRespository.createActivity(data) + .then( ( resp ) => + { + + const cachedData = getCachedData("Activity"); + const updatedData = [ ...cachedData, resp?.data ]; + cacheData("Activity", updatedData); + showToast("Activity Successfully Added.", "success"); + setIsLoading(false); + handleClose() + }) + .catch((error) => { + showToast(error.message, "error"); + setIsLoading(false); + }); }; - // Add a new checklist item - const addChecklistItem = () => { - const values = getValues('checkList'); - const lastIndex = checkListItems.length - 1; - - if (checkListItems.length > 0 && (!values?.[lastIndex] || values[lastIndex].trim() === '')) { - setError(`checkList.${lastIndex}`, { - type: 'manual', - message: 'Please fill this checklist item before adding another.', + const addChecklistItem = () => { + const values = getValues("checkList"); + const lastIndex = checkListItems.length - 1; + if ( + checkListItems.length > 0 && + (!values?.[lastIndex] || values[lastIndex].check.trim() === "") + ) { + setError(`checkList.${lastIndex}.check`, { + type: "manual", + message: "Please fill this checklist item before adding another.", }); return; } - - clearErrors(`checkList.${lastIndex}`); // Clear the error if the input is filled. - append(''); // Add a new empty checklist input + clearErrors(`checkList.${lastIndex}.check`); + append({ + id: 0, + check: "", + isMandatory: false, + }); }; - const removeChecklistItem = (index) => { - remove(index); + remove(index); }; - // Handle checklist item input change + const handleChecklistChange = (index, value) => { - setValue(`checkList.${index}`, value); + setValue(`checkList.${index}`, value); }; - const handleClose = () => - { - reset() - onClose() - } + const handleClose = () => { + reset(); + onClose(); + }; return (
-
-
- - - {errors.activityName &&

{errors.activityName.message}

} -
+
Create Activity
+
+
+ + + {errors.activityName && ( +

{errors.activityName.message}

+ )} +
-
- - - {errors.unitOfMeasurement && ( -

{errors.unitOfMeasurement.message}

- )} -
+
+ + + {errors.unitOfMeasurement && ( +

{errors.unitOfMeasurement.message}

+ )} +
-
- {/* Dynamic checklist items */} - {checkListItems.map((item, index) => ( -
-
- handleChecklistChange(index, e.target.value)} // Handle input change - /> - -
- {errors.checkList?.[index] && ( -

{errors.checkList[index]?.message}

- )} -
- ))} - {/* Add new checklist item */} - -
+
+

{checkListItems.length > 0 ? "Check List" : "Add Check List" }

+ {checkListItems.length > 0 && ( + + + + + + + + + + {checkListItems.map((item, index) => ( + + + + + + ))} + +
+ Name + + Is Mandatory + Action
+ + + handleChecklistChange(index, e.target.value) + } + /> + {errors.checkList?.[index]?.check && ( + + {errors.checkList[index]?.check?.message} + + )} + + + + +
+ )} + +
-
- - +
+ + +
-
- - ) -} + + ); +}; -export default CreateActivity \ No newline at end of file +export default CreateActivity; diff --git a/src/components/master/EditActivity.jsx b/src/components/master/EditActivity.jsx index bb829bf9..11d8c5f7 100644 --- a/src/components/master/EditActivity.jsx +++ b/src/components/master/EditActivity.jsx @@ -1,23 +1,28 @@ -import React, { useState, useEffect } from 'react'; -import { useFieldArray, useForm } from 'react-hook-form'; -import { z } from 'zod'; -import { zodResolver } from '@hookform/resolvers/zod'; -import {MasterRespository} from '../../repositories/MastersRepository'; -import axios from 'axios'; -import showToast from '../../services/toastService'; -import {cacheData, getCachedData} from '../../slices/apiDataManager'; +import React, { useEffect, useState } from "react"; +import { useForm, useFieldArray } from "react-hook-form"; +import { z } from "zod"; +import { zodResolver } from "@hookform/resolvers/zod"; +import {MasterRespository} from "../../repositories/MastersRepository"; +import showToast from "../../services/toastService"; +import {getCachedData,cacheData} from "../../slices/apiDataManager"; + -// Zod Schema for validation const schema = z.object({ activityName: z.string().min(1, { message: "Activity name is required" }), unitOfMeasurement: z.string().min(1, { message: "Measurement is required" }), checkList: z - .array(z.string().min(1, { message: "Checklist item cannot be empty" })) + .array( + z.object({ + id: z.any().default(0), + check: z.string().min(1, { message: "Checklist item cannot be empty" }), + isMandatory: z.boolean().default(false), + }) + ) .optional(), -} ); +}); -let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOlsiOGFmNjFlNDgtYzRkMy00MTYzLWI4NjAtMmEyZWNiNjQ3NDZiIiwiYjUxMzcwOWEtYmZiZS00OTM1LTlmNWMtOGVjN2IwMzFjNTFlIl0sInN1YiI6InZpa2FzQG1hcmNvYWlvdC5jb20iLCJUZW5hbnRJZCI6IjIiLCJleHAiOjE3NDQzNzQyNzAsImlzcyI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTI0NiIsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTI0NiJ9.reQlePmwDpBL-_mcGOrWwADLJrxmUse5Gd7A-OgDi9s" -const EditActivity = ({activityData,onClose}) => { + +const UpdateActivity = ({ activityData, onClose }) => { const [isLoading, setIsLoading] = useState(false); const { @@ -25,166 +30,212 @@ const EditActivity = ({activityData,onClose}) => { handleSubmit, control, setValue, - clearErrors, - setError, - getValues, reset, + setError, + clearErrors, + getValues, formState: { errors }, } = useForm({ resolver: zodResolver(schema), defaultValues: { - activityName: '', - unitOfMeasurement: '', - checkList: [], + id:activityData.id, + activityName: activityData.activityName, + unitOfMeasurement: activityData.unitOfMeasurement, + checkLists: activityData.checkLists || [], }, }); - // Setting up field array for checkList (dynamic fields) - const { - fields: checkListItems, - append, - remove, - } = useFieldArray({ + const { fields: checkListItems, append, remove } = useFieldArray({ control, - name: 'checkList', + name: "checkList", }); - // Pre-populating the form with initial data when component mounts or initialData changes + // Load initial data useEffect(() => { if (activityData) { - reset({ + reset( { + id:activityData.id, activityName: activityData.activityName, unitOfMeasurement: activityData.unitOfMeasurement, - checkList: activityData.checkList || [], + checkList: activityData.checkLists || [], }); } - }, [activityData, reset]); + }, [activityData]); - // Form submission handler - const onSubmit = async( data ) => + + const handleChecklistChange = (index, value) => { + setValue(`checkList.${index}`, value); + }; + + // Submit handler + const onSubmit = async(data) => { + setIsLoading(true); + + const Activity = {...data, id:activityData.id} + try { - console.log(data) - setIsLoading(true) - MasterRespository.updateActivity(activityData?.id,data).then((resp)=>{ - setIsLoading(false) - const cachedData = getCachedData("Activity"); - if (cachedData) { - const updatedData = cachedData.map((activity) => - activity.id === activityData?.id - ? { - ...activity, - activityName: resp.data.activityName, - unitOfMeasurement: resp.data.unitOfMeasurement, - } - : activity - ); - - cacheData("Activity", updatedData); - } - showToast("Activity Added successfully.", "success"); + const response = await MasterRespository.updateActivity( activityData?.id, Activity ); + const updatedActivity = response.data; + const cachedData = getCachedData("Activity") + + if (cachedData) { + const updatedActivities = cachedData.map((activity) => + activity.id === updatedActivity.id ? { ...activity, ...updatedActivity } : activity + ); + + cacheData( "Activity", updatedActivities ); onClose() - }).catch((error)=>{ - showToast(error.message, "error"); - setIsLoading(false) - }) - - - }; + } + setIsLoading( false ) + showToast("Activity Successfully Updated", "success"); + } catch ( err ) + { + setIsLoading( false ) - // Add a new checklist item + showToast("error.message", "error"); + console.log(err) + } + }; + + + + // Add new checklist item const addChecklistItem = () => { - const values = getValues('checkList'); + const values = getValues("checkList"); const lastIndex = checkListItems.length - 1; - // Prevent adding new input if the last one is empty - if (checkListItems.length > 0 && (!values?.[lastIndex] || values[lastIndex].trim() === '')) { - setError(`checkList.${lastIndex}`, { - type: 'manual', - message: 'Please fill this checklist item before adding another.', + if ( + checkListItems.length > 0 && + (!values?.[lastIndex] || values[lastIndex].check.trim() === "") + ) { + setError(`checkList.${lastIndex}.check`, { + type: "manual", + message: "Please fill this checklist item before adding another.", }); return; } - clearErrors(`checkList.${lastIndex}`); // Clear the error if the input is filled. - append(''); // Add a new empty checklist input + clearErrors(`checkList.${lastIndex}.check`); + append({ id: 0, check: "", isMandatory: false }); }; - // Remove a checklist item const removeChecklistItem = (index) => { - remove(index); // Remove the checklist item from the field array + remove(index); }; - // Handle checklist item input change - const handleChecklistChange = (index, value) => { - setValue(`checkList.${index}`, value); // Update the value of the checklist item - }; - - const handleCLose = () => - { - () => reset() - onClose() - } return (
+
Update Activity
-
- + {/* Activity Name */} +
+ - {errors.activityName &&

{errors.activityName.message}

} -
- -
- - - {errors.unitOfMeasurement && ( -

{errors.unitOfMeasurement.message}

+ {errors.activityName && ( +
{errors.activityName.message}
)}
-
- {/* Dynamic checklist items */} - {checkListItems.map((item, index) => ( -
- handleChecklistChange(index, e.target.value)} // Handle input change - /> - - {errors.checkList?.[index] && ( -

{errors.checkList[index]?.message}

- )} -
- ))} - {/* Add new checklist item */} -
+ {/* Submit / Cancel */}
@@ -194,4 +245,4 @@ const EditActivity = ({activityData,onClose}) => { ); }; -export default EditActivity; +export default UpdateActivity;