pramod_Task#295 : Create Contact Modal for Directory #116

Merged
pramod.mahajan merged 7 commits from pramod_Task#295 into Feature_Directory 2025-05-16 15:15:59 +00:00
Showing only changes of commit c7b5a0ba7d - Show all commits

View File

@ -1,40 +1,82 @@
import React, { useEffect } from "react"; import React, { useEffect, useState } from "react";
import { useForm, useFieldArray, FormProvider } from "react-hook-form"; import {
useForm,
useFieldArray,
FormProvider,
useFormContext,
} 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 { z } from "zod";
import IconButton from "../common/IconButton";
import useMaster from "../../hooks/masterHook/useMaster";
import { useDispatch, useSelector } from "react-redux";
import { changeMaster } from "../../slices/localVariablesSlice";
import { useBuckets } from "../../hooks/useDirectory";
import {useProjects} from "../../hooks/useProjects";
export const directorySchema = z.object({ export const ContactSchema = z.object({
firstName: z.string().min(1, "First Name is required"), Name: z.string().min(1, "Name is required"),
lastName: z.string().min(1, "Last Name is required"),
organization: z.string().min(1, "Organization name is required"), organization: z.string().min(1, "Organization name is required"),
type: z.string().min(1, "Type is required"), ContactCategoryId: z.string().optional(),
address: z.string().optional(), address: z.string().optional(),
description: z.string().min(1, { message: "Description is required" }), description: z.string().min( 1, {message: "Description is required"} ),
email: z ProjectId :z.string().optional(),
.array(z.string().email("Invalid email")) ContactEmails: z
.nonempty("At least one email required"), .array(
phone: z z.object({
.array(z.string().regex(/^\d{10}$/, "Phone must be 10 digits")) label: z.string(),
.nonempty("At least one phone number is required"), emailAddress: z.string().email("Invalid email"),
tags: z.array(z.string()).optional(), })
)
.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 selectedMaster = useSelector(
(store) => store.localVariables.selectedMaster
);
const [categoryData, setCategoryData] = useState([]);
const [TagsData, setTagsData] = useState([]);
const { data, loading } = useMaster();
const {buckets, loading: bucketsLoaging} = useBuckets();
const {projects, loading: projectLoading} = useProjects();
const [IsSubmitting,setSubmitting] = useState(false)
const dispatch = useDispatch();
const ManageDirectory = () => {
const methods = useForm({ const methods = useForm({
resolver: zodResolver(directorySchema), resolver: zodResolver(ContactSchema),
defaultValues: { defaultValues: {
firstName: "", Name: "",
lastName: "",
organization: "", organization: "",
type: "", ContactCategoryId: null,
address: "", address: "",
description: "", description: "",
email: [""], ProjectId:null,
phone: [""], ContactEmails: [],
ContactPhones: [],
tags: [], tags: [],
BucketIds: [],
}, },
}); });
@ -44,6 +86,9 @@ const ManageDirectory = () => {
control, control,
getValues, getValues,
trigger, trigger,
setValue,
watch,
reset,
formState: { errors }, formState: { errors },
} = methods; } = methods;
@ -51,160 +96,357 @@ const ManageDirectory = () => {
fields: emailFields, fields: emailFields,
append: appendEmail, append: appendEmail,
remove: removeEmail, remove: removeEmail,
} = useFieldArray({ control, name: "email" }); } = useFieldArray({ control, name: "ContactEmails" });
const { const {
fields: phoneFields, fields: phoneFields,
append: appendPhone, append: appendPhone,
remove: removePhone, remove: removePhone,
} = useFieldArray({ control, name: "phone" }); } = useFieldArray({ control, name: "ContactPhones" });
useEffect(() => { useEffect(() => {
if (emailFields.length === 0) appendEmail(""); if (emailFields.length === 0) appendEmail("");
if (phoneFields.length === 0) appendPhone(""); if (phoneFields.length === 0) appendPhone("");
}, [emailFields.length, phoneFields.length]); }, [emailFields.length, phoneFields.length]);
const onSubmit = (data) => {
// console.log("Submitted:\n" + JSON.stringify(data, null, 2));
};
const handleAddEmail = async () => { const handleAddEmail = async () => {
const emails = getValues("email"); const emails = getValues("ContactEmails");
const lastIndex = emails.length - 1; const lastIndex = emails.length - 1;
const valid = await trigger(`email.${lastIndex}`); const valid = await trigger(`ContactEmails.${lastIndex}.emailAddress`);
if (valid) appendEmail(""); if (valid) {
appendEmail({ label: "Work", emailAddress: "" });
}
}; };
const handleAddPhone = async () => { const handleAddPhone = async () => {
const phones = getValues("phone"); const phones = getValues("ContactPhones");
const lastIndex = phones.length - 1; const lastIndex = phones.length - 1;
const valid = await trigger(`phone.${lastIndex}`); const valid = await trigger(`ContactPhones.${lastIndex}.phoneNumber`);
if (valid) appendPhone(""); if (valid) {
appendPhone({ label: "Office", phoneNumber: "" });
}
}; };
useEffect(() => {
if (selectedMaster === "Contact Category") {
setCategoryData(data);
} else {
setTagsData(data);
}
}, [selectedMaster, data]);
const watchBucketIds = watch("BucketIds");
const toggleBucketId = (id) => {
const updated = watchBucketIds?.includes(id)
? watchBucketIds.filter((val) => val !== id)
: [...watchBucketIds, id];
setValue("BucketIds", updated, { shouldValidate: true });
};
const handleCheckboxChange = (id) => {
const updated = watchBucketIds.includes(id)
? watchBucketIds.filter((i) => i !== id)
: [...watchBucketIds, id];
setValue("BucketIds", updated, { shouldValidate: true });
};
const onSubmit = ( data ) =>
{
setSubmitting(true)
submitContact( data, reset, setSubmitting )
};
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">
<IconButton size={15} iconClass="bx bx-user-plus" color="primary" />{" "}
<h6 className="m-0 fw-18"> Create New Contact</h6>
</div>
<div className="row"> <div className="row">
<div className="col-md-6"> <div className="col-md-6">
<label className="form-label">First Name</label> <label className="form-label">Name</label>
<input className="form-control form-control-sm" {...register("firstName")} /> <input
{errors.firstName && <small className="danger-text">{errors.firstName.message}</small>} className="form-control form-control-sm"
{...register("Name")}
/>
{errors.Name && (
<small className="danger-text">{errors.Name.message}</small>
)}
</div> </div>
<div className="col-md-6"> <div className="col-md-6">
<label className="form-label">Last Name</label> <label className="form-label">Organization</label>
<input className="form-control form-control-sm" {...register("lastName")} /> <input
{errors.lastName && <small className="danger-text">{errors.lastName.message}</small>} className="form-control form-control-sm"
{...register("organization")}
/>
{errors.organization && (
<small className="danger-text">
{errors.organization.message}
</small>
)}
</div> </div>
</div> </div>
<div className="row mt-1">
<div className="col-12">
<label className="form-label">Organization</label>
<input className="form-control form-control-sm" {...register("organization")} />
{errors.organization && <small className="danger-text">{errors.organization.message}</small>}
</div>
<div className="row">
<div className="col-md-6"> <div className="col-md-6">
<label className="form-label">Email</label> {emailFields.map((field, index) => (
{emailFields.map((field, index) => (<> <div
<div key={field.id} className="d-flex align-items-center mb-1"> key={field.id}
<input className="row d-flex align-items-center mb-1"
type="email" >
className="form-control form-control-sm" <div className="col-5">
{...register(`email.${index}`)} <label className="form-label">Label</label>
placeholder="email@example.com" <select
/> className="form-select form-select-sm"
{index === emailFields.length - 1 ? ( {...register(`ContactEmails.${index}.label`)}
<button
type="button"
className="btn btn-xs btn-primary ms-1"
onClick={handleAddEmail}
> >
<i className="bx bx-plus bx-xs" /> <option value="Work">Work</option>
</button> <option value="Personal">Personal</option>
) : ( <option value="Other">Other</option>
<button </select>
type="button" {errors.ContactEmails?.[index]?.label && (
className="btn btn-xs btn-danger ms-1" <small className="danger-text">
onClick={() => removeEmail(index)} {errors.ContactEmails[index].label.message}
> </small>
<i className="bx bx-x bx-xs" /> )}
</button> </div>
)} <div className="col-7">
<label className="form-label">Email</label>
<div className="d-flex align-items-center">
<input
type="email"
className="form-control form-control-sm"
{...register(`ContactEmails.${index}.emailAddress`)}
placeholder="email@example.com"
/>
{index === emailFields.length - 1 ? (
<button
type="button"
className="btn btn-xs btn-primary ms-1"
onClick={handleAddEmail}
style={{ width: "24px", height: "24px" }}
>
<i className="bx bx-plus bx-xs" />
</button>
) : (
<button
type="button"
className="btn btn-xs btn-danger ms-1 p-0"
onClick={() => removeEmail(index)}
style={{ width: "24px", height: "24px" }}
>
<i className="bx bx-x bx-xs" />
</button>
)}
</div>
{errors.ContactEmails?.[index]?.emailAddress && (
<small className="danger-text">
{errors.ContactEmails[index].emailAddress.message}
</small>
)}
</div>
</div> </div>
{errors.email?.[index] && (
<small className="danger-text ms-2">
{errors.email[index]?.message}
</small>
)}
</>
))} ))}
</div> </div>
<div className="col-md-6"> <div className="col-md-6">
<label className="form-label">Phone</label> {phoneFields.map((field, index) => (
{phoneFields.map((field, index) => (<> <div
<div key={field.id} className="d-flex align-items-center mb-1"> key={field.id}
<input className="row d-flex align-items-center mb-2"
type="text" >
className="form-control form-control-sm" <div className="col-5">
{...register(`phone.${index}`)} <label className="form-label">Label</label>
placeholder="9876543210" <select
/> className="form-select form-select-sm"
{index === phoneFields.length - 1 ? ( {...register(`ContactPhones.${index}.label`)}
<button
type="button"
className="btn btn-xs btn-primary ms-1"
onClick={handleAddPhone}
> >
<i className="bx bx-plus bx-xs" /> <option value="Office">Office</option>
</button> <option value="Personal">Personal</option>
) : ( <option value="Business">Business</option>
<button </select>
type="button" {errors.phone?.[index]?.label && (
className="btn btn-xs btn-danger ms-1" <small className="danger-text">
onClick={() => removePhone(index)} // Remove the phone field {errors.ContactPhones[index].label.message}
> </small>
<i className="bx bx-x bx-xs" /> )}
</button> </div>
)} <div className="col-7">
<label className="form-label">Phone</label>
<div className="d-flex align-items-center">
<input
type="text"
className="form-control form-control-sm"
{...register(`ContactPhones.${index}.phoneNumber`)}
placeholder="9876543210"
/>
{index === phoneFields.length - 1 ? (
<button
type="button"
className="btn btn-xs btn-primary ms-1"
onClick={handleAddPhone}
style={{ width: "24px", height: "24px" }}
>
<i className="bx bx-plus bx-xs" />
</button>
) : (
<button
type="button"
className="btn btn-xs btn-danger ms-1"
onClick={() => removePhone(index)}
style={{ width: "24px", height: "24px" }}
>
<i className="bx bx-x bx-xs" />
</button>
)}
</div>
{errors.ContactPhones?.[index]?.phoneNumber && (
<small className="danger-text">
{errors.ContactPhones[index].phoneNumber.message}
</small>
)}
</div>
</div> </div>
{errors.phone?.[ index ] && <small className="danger-text ms-2">{errors.phone[ index ]?.message}</small>}
</>
))} ))}
</div> </div>
</div> </div>
<div className="row my-1"> <div className="row my-1">
<div className="col-md-6"> <div className="col-md-6">
<label className="form-label">Type</label> <label className="form-label">Category</label>
<input className="form-control form-control-sm" {...register("type")} /> <select
{errors.type && <small className="danger-text">{errors.type.message}</small>} defaultValue=""
className="form-select form-select-sm"
{...register("ContactCategoryId")}
onClick={() => dispatch(changeMaster("Contact Category"))}
>
{loading && !categoryData ? (
<option disabled value="">
Loading...
</option>
) : (
<>
<option disabled selected value="">
Select Category
</option>
{categoryData?.map((cate) => (
<option key={cate.id} value={cate.id}>
{cate.name}
</option>
))}
</>
)}
</select>
{errors.ContactCategoryId && (
<small className="danger-text">{errors.ContactCategoryId.message}</small>
)}
</div> </div>
<div className="col-md-6"> <div className="col-md-6">
<TagInput name="tags" label="Tags" /> <TagInput name="tags" label="Tags" options={data} />
</div>
</div>
<div className="row">
<div className="col-md-6 text-start">
<label className="form-label mb-2">Select Label</label>
<div
className="row px-1"
style={{ maxHeight: "100px", overflowY: "auto" }}
>
{bucketsLoaging && <p>Loading...</p>}
{buckets?.map((item) => (
<div className="col-6 col-sm-6 " key={item.id}>
<div className="form-check mb-2">
<input
type="checkbox"
className="form-check-input"
id={`item-${item.id}`}
checked={watchBucketIds.includes(item.id)}
onChange={() => handleCheckboxChange(item.id)}
/>
<label
className="form-check-label"
htmlFor={`item-${item.id}`}
>
{item.name}
</label>
</div>
</div>
))}
</div>
{errors.BucketIds && (
<small className="text-danger">{errors.BucketIds.message}</small>
)}
</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>
<div className="col-12"> <div className="col-12">
<label className="form-label">Address</label> <label className="form-label">Address</label>
<textarea className="form-control form-control-sm" rows="2" {...register("address")} /> <textarea
className="form-control form-control-sm"
rows="2"
{...register("address")}
/>
</div> </div>
<div className="col-12"> <div className="col-12">
<label className="form-label">Description</label> <label className="form-label">Description</label>
<textarea className="form-control form-control-sm" rows="2" {...register("description")} /> <textarea
{errors.description && <small className="danger-text">{errors.description.message}</small>} className="form-control form-control-sm"
rows="2"
{...register("description")}
/>
{errors.description && (
<small className="danger-text">{errors.description.message}</small>
)}
</div> </div>
<div className="d-flex justify-content-evenly py-2"> <div className="d-flex justify-content-center gap-1 py-2">
<button className="btn btn-sm btn-primary" type="submit">Submit</button> <button className="btn btn-sm btn-primary" type="submit">
<button className="btn btn-sm btn-secondary" type="button">Cancel</button> {IsSubmitting ? "Please Wait..." : "Submit"}
</button>
<button className="btn btn-sm btn-secondary" type="button" onClick={onCLosed}>
Cancel
</button>
</div> </div>
</form> </form>
</FormProvider> </FormProvider>