pramod_Task-#298 : Update Contact #119

Merged
pramod.mahajan merged 16 commits from pramod_Task-#298 into Feature_Directory 2025-05-18 12:35:55 +00:00
Showing only changes of commit 8e06991bd3 - Show all commits

View File

@ -7,76 +7,48 @@ import {
} from "react-hook-form"; } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import TagInput from "../common/TagInput"; import TagInput from "../common/TagInput";
import { z } from "zod";
import IconButton from "../common/IconButton"; import IconButton from "../common/IconButton";
import useMaster from "../../hooks/masterHook/useMaster"; import useMaster, {
useContactCategory,
useContactTags,
} from "../../hooks/masterHook/useMaster";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { changeMaster } from "../../slices/localVariablesSlice"; import { changeMaster } from "../../slices/localVariablesSlice";
import { useBuckets } from "../../hooks/useDirectory"; import { useBuckets } from "../../hooks/useDirectory";
import {useProjects} from "../../hooks/useProjects"; import { useProjects } from "../../hooks/useProjects";
import SelectMultiple from "../common/SelectMultiple";
import {ContactSchema} from "./DirectorySchema";
export const ContactSchema = z.object({
Name: z.string().min(1, "Name is required"),
organization: z.string().min(1, "Organization name is required"),
ContactCategoryId: z.string().optional(),
address: z.string().optional(),
description: z.string().min( 1, {message: "Description is required"} ),
ProjectId :z.string().optional(),
ContactEmails: z
.array(
z.object({
label: z.string(),
emailAddress: z.string().email("Invalid email"),
})
)
.optional()
.default([]),
ContactPhones: z
.array(
z.object({
label: z.string(),
phoneNumber: z.string().regex(/^\d{10}$/, "Phone must be 10 digits"),
})
)
.optional()
.default([]),
tags: z
.array(
z.object({
id: z.string().nullable(),
name: z.string(),
})
)
.optional(),
BucketIds: z.array(z.string()).optional(),
});
const ManageDirectory = ({submitContact,onCLosed}) => { const ManageDirectory = ({ submitContact, onCLosed }) => {
const selectedMaster = useSelector( const selectedMaster = useSelector(
(store) => store.localVariables.selectedMaster (store) => store.localVariables.selectedMaster
); );
const [categoryData, setCategoryData] = useState([]); const [categoryData, setCategoryData] = useState([]);
const [TagsData, setTagsData] = useState([]); const [TagsData, setTagsData] = useState([]);
const { data, loading } = useMaster(); const { data, loading } = useMaster();
const {buckets, loading: bucketsLoaging} = useBuckets(); const { buckets, loading: bucketsLoaging } = useBuckets();
const {projects, loading: projectLoading} = useProjects(); const { projects, loading: projectLoading } = useProjects();
const [IsSubmitting,setSubmitting] = useState(false) const { contactCategory, loading: contactCategoryLoading } =
useContactCategory();
const { contactTags, loading: Tagloading } = useContactTags();
const [IsSubmitting, setSubmitting] = useState(false);
const dispatch = useDispatch(); const dispatch = useDispatch();
const methods = useForm({ const methods = useForm({
resolver: zodResolver(ContactSchema), resolver: zodResolver(ContactSchema),
defaultValues: { defaultValues: {
Name: "", name: "",
organization: "", organization: "",
ContactCategoryId: null, contactCategoryId: null,
address: "", address: "",
description: "", description: "",
ProjectId:null, projectIds: [],
ContactEmails: [], contactEmails: [],
ContactPhones: [], contactPhones: [],
tags: [], tags: [],
BucketIds: [], bucketIds: [],
}, },
}); });
@ -96,93 +68,100 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
fields: emailFields, fields: emailFields,
append: appendEmail, append: appendEmail,
remove: removeEmail, remove: removeEmail,
} = useFieldArray({ control, name: "ContactEmails" }); } = useFieldArray({ control, name: "contactEmails" });
const { const {
fields: phoneFields, fields: phoneFields,
append: appendPhone, append: appendPhone,
remove: removePhone, remove: removePhone,
} = useFieldArray({ control, name: "ContactPhones" }); } = useFieldArray({ control, name: "contactPhones" });
useEffect(() => { useEffect(() => {
if (emailFields.length === 0) appendEmail(""); if (emailFields.length === 0) {
if (phoneFields.length === 0) appendPhone(""); appendEmail({ label: "Work", emailAddress: "" }); // valid object
}, [emailFields.length, phoneFields.length]); }
if (phoneFields.length === 0) {
appendPhone({ label: "Office", phoneNumber: "" }); // valid object
}
}, [emailFields.length, phoneFields.length]);
const handleAddEmail = async () => { const handleAddEmail = async () => {
const emails = getValues("ContactEmails"); const emails = getValues("contactEmails");
const lastIndex = emails.length - 1; const lastIndex = emails.length - 1;
const valid = await trigger(`ContactEmails.${lastIndex}.emailAddress`); const valid = await trigger(`contactEmails.${lastIndex}.emailAddress`);
if (valid) { if (valid) {
appendEmail({ label: "Work", emailAddress: "" }); appendEmail({ label: "Work", emailAddress: "" });
} }
}; };
const handleAddPhone = async () => { const handleAddPhone = async () => {
const phones = getValues("ContactPhones"); const phones = getValues("contactPhones");
const lastIndex = phones.length - 1; const lastIndex = phones.length - 1;
const valid = await trigger(`ContactPhones.${lastIndex}.phoneNumber`); const valid = await trigger(`contactPhones.${lastIndex}.phoneNumber`);
if (valid) { if (valid) {
appendPhone({ label: "Office", phoneNumber: "" }); appendPhone({ label: "Office", phoneNumber: "" });
} }
}; };
useEffect(() => { const watchBucketIds = watch("bucketIds");
if (selectedMaster === "Contact Category") {
setCategoryData(data);
} else {
setTagsData(data);
}
}, [selectedMaster, data]);
const watchBucketIds = watch("BucketIds");
const toggleBucketId = (id) => { const toggleBucketId = (id) => {
const updated = watchBucketIds?.includes(id) const updated = watchBucketIds?.includes(id)
? watchBucketIds.filter((val) => val !== id) ? watchBucketIds.filter((val) => val !== id)
: [...watchBucketIds, id]; : [...watchBucketIds, id];
setValue("BucketIds", updated, { shouldValidate: true }); setValue("bucketIds", updated, { shouldValidate: true });
}; };
const handleCheckboxChange = (id) => { const handleCheckboxChange = (id) => {
const updated = watchBucketIds.includes(id) const updated = watchBucketIds.includes(id)
? watchBucketIds.filter((i) => i !== id) ? watchBucketIds.filter((i) => i !== id)
: [...watchBucketIds, id]; : [...watchBucketIds, id];
setValue("BucketIds", updated, { shouldValidate: true }); setValue("bucketIds", updated, { shouldValidate: true });
}; };
const onSubmit = ( data ) => const onSubmit = ( data ) =>
{ {
setSubmitting(true) const cleaned = {
submitContact( data, reset, setSubmitting ) ...data,
contactEmails: (data.contactEmails || []).filter(
(e) => e.emailAddress?.trim() !== ""
),
contactPhones: (data.contactPhones || []).filter(
(p) => p.phoneNumber?.trim() !== ""
),
};
// Submit cleaned data
console.log(cleaned);
// setSubmitting(true);
// submitContact(data, reset, setSubmitting);
};
const handleClosed = () => {
onCLosed();
}; };
return ( return (
<FormProvider {...methods}> <FormProvider {...methods}>
<form className="p-2 p-sm-0" onSubmit={handleSubmit(onSubmit)}> <form className="p-2 p-sm-0" onSubmit={handleSubmit(onSubmit)}>
<div className="text-start d-flex align-items-center"> <div className="d-flex justify-content-center align-items-center">
<IconButton size={15} iconClass="bx bx-user-plus" color="primary" />{" "} <IconButton size={15} iconClass="bx bx-user-plus" color="primary" />{" "}
<h6 className="m-0 fw-18"> Create New Contact</h6> <h6 className="m-0 fw-18"> Create New Contact</h6>
</div> </div>
<div className="row"> <div className="row">
<div className="col-md-6"> <div className="col-md-6 text-start">
<label className="form-label">Name</label> <label className="form-label">Name</label>
<input <input
className="form-control form-control-sm" className="form-control form-control-sm"
{...register("Name")} {...register("name")}
/> />
{errors.Name && ( {errors.name && (
<small className="danger-text">{errors.Name.message}</small> <small className="danger-text">{errors.name.message}</small>
)} )}
</div> </div>
<div className="col-md-6"> <div className="col-md-6 text-start">
<label className="form-label">Organization</label> <label className="form-label">Organization</label>
<input <input
className="form-control form-control-sm" className="form-control form-control-sm"
@ -202,29 +181,29 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
key={field.id} key={field.id}
className="row d-flex align-items-center mb-1" className="row d-flex align-items-center mb-1"
> >
<div className="col-5"> <div className="col-5 text-start">
<label className="form-label">Label</label> <label className="form-label">Label</label>
<select <select
className="form-select form-select-sm" className="form-select form-select-sm"
{...register(`ContactEmails.${index}.label`)} {...register(`contactEmails.${index}.label`)}
> >
<option value="Work">Work</option> <option value="Work">Work</option>
<option value="Personal">Personal</option> <option value="Personal">Personal</option>
<option value="Other">Other</option> <option value="Other">Other</option>
</select> </select>
{errors.ContactEmails?.[index]?.label && ( {errors.contactEmails?.[index]?.label && (
<small className="danger-text"> <small className="danger-text">
{errors.ContactEmails[index].label.message} {errors.contactEmails[index].label.message}
</small> </small>
)} )}
</div> </div>
<div className="col-7"> <div className="col-7 text-start">
<label className="form-label">Email</label> <label className="form-label">Email</label>
<div className="d-flex align-items-center"> <div className="d-flex align-items-center">
<input <input
type="email" type="email"
className="form-control form-control-sm" className="form-control form-control-sm"
{...register(`ContactEmails.${index}.emailAddress`)} {...register(`contactEmails.${index}.emailAddress`)}
placeholder="email@example.com" placeholder="email@example.com"
/> />
{index === emailFields.length - 1 ? ( {index === emailFields.length - 1 ? (
@ -247,27 +226,26 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
</button> </button>
)} )}
</div> </div>
{errors.ContactEmails?.[index]?.emailAddress && ( {errors.contactEmails?.[index]?.emailAddress && (
<small className="danger-text"> <small className="danger-text">
{errors.ContactEmails[index].emailAddress.message} {errors.contactEmails[index].emailAddress.message}
</small> </small>
)} )}
</div> </div>
</div> </div>
))} ))}
</div> </div>
<div className="col-md-6"> <div className="col-md-6">
{phoneFields.map((field, index) => ( {phoneFields.map((field, index) => (
<div <div
key={field.id} key={field.id}
className="row d-flex align-items-center mb-2" className="row d-flex align-items-center mb-2"
> >
<div className="col-5"> <div className="col-5 text-start">
<label className="form-label">Label</label> <label className="form-label">Label</label>
<select <select
className="form-select form-select-sm" className="form-select form-select-sm"
{...register(`ContactPhones.${index}.label`)} {...register(`contactPhones.${index}.label`)}
> >
<option value="Office">Office</option> <option value="Office">Office</option>
<option value="Personal">Personal</option> <option value="Personal">Personal</option>
@ -279,13 +257,13 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
</small> </small>
)} )}
</div> </div>
<div className="col-7"> <div className="col-7 text-start">
<label className="form-label">Phone</label> <label className="form-label">Phone</label>
<div className="d-flex align-items-center"> <div className="d-flex align-items-center">
<input <input
type="text" type="text"
className="form-control form-control-sm" className="form-control form-control-sm"
{...register(`ContactPhones.${index}.phoneNumber`)} {...register(`contactPhones.${index}.phoneNumber`)}
placeholder="9876543210" placeholder="9876543210"
/> />
{index === phoneFields.length - 1 ? ( {index === phoneFields.length - 1 ? (
@ -308,27 +286,28 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
</button> </button>
)} )}
</div> </div>
{errors.ContactPhones?.[index]?.phoneNumber && ( {errors.contactPhones?.[index]?.phoneNumber && (
<small className="danger-text"> <small className="danger-text">
{errors.ContactPhones[index].phoneNumber.message} {errors.contactPhones[index].phoneNumber.message}
</small> </small>
)} )}
</div> </div>
</div> </div>
))} ))}
</div> </div>
{errors.contactPhone?.message && (
<div className="danger-text">{errors.contactPhone.message}</div>
)}
</div> </div>
<div className="row my-1"> <div className="row my-1">
<div className="col-md-6"> <div className="col-md-6 text-start">
<label className="form-label">Category</label> <label className="form-label">Category</label>
<select <select
defaultValue=""
className="form-select form-select-sm" className="form-select form-select-sm"
{...register("ContactCategoryId")} {...register("contactCategoryId")}
onClick={() => dispatch(changeMaster("Contact Category"))}
> >
{loading && !categoryData ? ( {contactCategoryLoading && !contactCategory ? (
<option disabled value=""> <option disabled value="">
Loading... Loading...
</option> </option>
@ -337,7 +316,7 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
<option disabled selected value=""> <option disabled selected value="">
Select Category Select Category
</option> </option>
{categoryData?.map((cate) => ( {contactCategory?.map((cate) => (
<option key={cate.id} value={cate.id}> <option key={cate.id} value={cate.id}>
{cate.name} {cate.name}
</option> </option>
@ -345,26 +324,52 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
</> </>
)} )}
</select> </select>
{errors.ContactCategoryId && ( {errors.contactCategoryId && (
<small className="danger-text">{errors.ContactCategoryId.message}</small> <small className="danger-text">
{errors.contactCategoryId.message}
</small>
)} )}
</div> </div>
<div className="col-md-6"> <div className="col-12 col-md-6 text-start">
<TagInput name="tags" label="Tags" options={data} /> <SelectMultiple
name="projectIds"
label="Select Projects"
options={projects}
labelKey="name"
valueKey="id"
IsLoading={projectLoading}
/>
{errors.projectIds && (
<small className="danger-text">
{errors.projectIds.message}
</small>
)}
</div> </div>
</div> </div>
<div className="row">
<div className="col-md-6 text-start">
<label className="form-label mb-2">Select Label</label>
<div <div className="col-12 text-start">
className="row px-1" <TagInput name="tags" label="Tags" options={contactTags} />
style={{ maxHeight: "100px", overflowY: "auto" }} {errors.tags && (
<small className="danger-text">
{errors.tags.message}
</small>
)}
</div>
<div className="row">
<div className="col-md-12 mt-1 text-start">
<label className="form-label ">Select Label</label>
<ul
className="d-flex flex-wrap px-1 list-unstyled overflow-auto mb-0"
style={{ maxHeight: "80px" }}
> >
{bucketsLoaging && <p>Loading...</p>} {bucketsLoaging && <p>Loading...</p>}
{buckets?.map((item) => ( {buckets?.map((item) => (
<div className="col-6 col-sm-6 " key={item.id}> <li
<div className="form-check mb-2"> key={item.id}
className="list-inline-item flex-shrink-0 me-6 mb-2"
>
<div className="form-check ">
<input <input
type="checkbox" type="checkbox"
className="form-check-input" className="form-check-input"
@ -379,47 +384,17 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
{item.name} {item.name}
</label> </label>
</div> </div>
</div> </li>
))} ))}
</div> </ul>
{errors.BucketIds && ( {errors.BucketIds && (
<small className="text-danger">{errors.BucketIds.message}</small> <small className="text-danger">{errors.BucketIds.message}</small>
)} )}
</div> </div>
<div className="col-12 col-md-6">
<label className="form-label">Category</label>
<select
defaultValue=""
className="form-select form-select-sm"
{...register("ProjectId")}
>
{loading && !categoryData ? (
<option disabled value="">
Loading...
</option>
) : (
<>
<option disabled selected value="">
Select Project
</option>
{projects?.map((project) => (
<option key={project.id} value={project.id}>
{project.name}
</option>
))}
</>
)}
</select>
{errors.category && (
<small className="danger-text">{errors.category.message}</small>
)}
</div>
</div> </div>
<div className="col-12"> <div className="col-12 text-start">
<label className="form-label">Address</label> <label className="form-label">Address</label>
<textarea <textarea
className="form-control form-control-sm" className="form-control form-control-sm"
@ -428,7 +403,7 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
/> />
</div> </div>
<div className="col-12"> <div className="col-12 text-start">
<label className="form-label">Description</label> <label className="form-label">Description</label>
<textarea <textarea
className="form-control form-control-sm" className="form-control form-control-sm"
@ -444,7 +419,11 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
<button className="btn btn-sm btn-primary" type="submit"> <button className="btn btn-sm btn-primary" type="submit">
{IsSubmitting ? "Please Wait..." : "Submit"} {IsSubmitting ? "Please Wait..." : "Submit"}
</button> </button>
<button className="btn btn-sm btn-secondary" type="button" onClick={onCLosed}> <button
className="btn btn-sm btn-secondary"
type="button"
onClick={handleClosed}
>
Cancel Cancel
</button> </button>
</div> </div>