Compare commits

...

10 Commits

Author SHA1 Message Date
Pramod Mahajan
28e409ff99 Uncommented reset logic on component unmount for cleanup 2025-05-18 17:13:58 +05:30
Pramod Mahajan
b6a0fb54ac Re-enabled submit and reset logic, removed console log 2025-05-18 17:13:15 +05:30
Pramod Mahajan
61ce554e05 prevent to reset form before calling api. 2025-05-18 16:57:06 +05:30
Pramod Mahajan
d956bfd3cc added new method for update contact 2025-05-18 02:26:58 +05:30
Pramod Mahajan
71b9a3602b added update contact modal 2025-05-18 02:25:42 +05:30
Pramod Mahajan
68999401e5 created separate contactCategory and contactTag hook for managing contacts creation and edition 2025-05-18 02:24:10 +05:30
Pramod Mahajan
a837b16a7d removed console 2025-05-18 02:22:21 +05:30
Pramod Mahajan
d716a5ffac modified hook prevent to recall api 2025-05-18 02:22:01 +05:30
Pramod Mahajan
5f33826e61 created new component for update contact 2025-05-18 02:18:53 +05:30
Pramod Mahajan
8e06991bd3 modified as per required changes. 2025-05-18 02:18:13 +05:30
6 changed files with 755 additions and 245 deletions

View File

@ -7,76 +7,48 @@ import {
} from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import TagInput from "../common/TagInput";
import { z } from "zod";
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 { changeMaster } from "../../slices/localVariablesSlice";
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(
(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 { buckets, loading: bucketsLoaging } = useBuckets();
const { projects, loading: projectLoading } = useProjects();
const { contactCategory, loading: contactCategoryLoading } =
useContactCategory();
const { contactTags, loading: Tagloading } = useContactTags();
const [IsSubmitting, setSubmitting] = useState(false);
const dispatch = useDispatch();
const methods = useForm({
resolver: zodResolver(ContactSchema),
defaultValues: {
Name: "",
name: "",
organization: "",
ContactCategoryId: null,
contactCategoryId: null,
address: "",
description: "",
ProjectId:null,
ContactEmails: [],
ContactPhones: [],
projectIds: [],
contactEmails: [],
contactPhones: [],
tags: [],
BucketIds: [],
bucketIds: [],
},
});
@ -96,93 +68,98 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
fields: emailFields,
append: appendEmail,
remove: removeEmail,
} = useFieldArray({ control, name: "ContactEmails" });
} = useFieldArray({ control, name: "contactEmails" });
const {
fields: phoneFields,
append: appendPhone,
remove: removePhone,
} = useFieldArray({ control, name: "ContactPhones" });
} = useFieldArray({ control, name: "contactPhones" });
useEffect(() => {
if (emailFields.length === 0) appendEmail("");
if (phoneFields.length === 0) appendPhone("");
}, [emailFields.length, phoneFields.length]);
useEffect(() => {
if (emailFields.length === 0) {
appendEmail({ label: "Work", emailAddress: "" });
}
if (phoneFields.length === 0) {
appendPhone({ label: "Office", phoneNumber: "" });
}
}, [emailFields.length, phoneFields.length]);
const handleAddEmail = async () => {
const emails = getValues("ContactEmails");
const emails = getValues("contactEmails");
const lastIndex = emails.length - 1;
const valid = await trigger(`ContactEmails.${lastIndex}.emailAddress`);
const valid = await trigger(`contactEmails.${lastIndex}.emailAddress`);
if (valid) {
appendEmail({ label: "Work", emailAddress: "" });
}
};
const handleAddPhone = async () => {
const phones = getValues("ContactPhones");
const phones = getValues("contactPhones");
const lastIndex = phones.length - 1;
const valid = await trigger(`ContactPhones.${lastIndex}.phoneNumber`);
const valid = await trigger(`contactPhones.${lastIndex}.phoneNumber`);
if (valid) {
appendPhone({ label: "Office", phoneNumber: "" });
}
};
useEffect(() => {
if (selectedMaster === "Contact Category") {
setCategoryData(data);
} else {
setTagsData(data);
}
}, [selectedMaster, data]);
const watchBucketIds = watch("BucketIds");
const watchBucketIds = watch("bucketIds");
const toggleBucketId = (id) => {
const updated = watchBucketIds?.includes(id)
? watchBucketIds.filter((val) => val !== id)
: [...watchBucketIds, id];
setValue("BucketIds", updated, { shouldValidate: true });
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 });
setValue("bucketIds", updated, { shouldValidate: true });
};
const onSubmit = ( data ) =>
{
setSubmitting(true)
submitContact( data, reset, setSubmitting )
const cleaned = {
...data,
contactEmails: (data.contactEmails || []).filter(
(e) => e.emailAddress?.trim() !== ""
),
contactPhones: (data.contactPhones || []).filter(
(p) => p.phoneNumber?.trim() !== ""
),
};
setSubmitting(true);
submitContact(cleaned, reset, setSubmitting);
};
const handleClosed = () => {
onCLosed();
};
return (
<FormProvider {...methods}>
<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" />{" "}
<h6 className="m-0 fw-18"> Create New Contact</h6>
</div>
<div className="row">
<div className="col-md-6">
<div className="col-md-6 text-start">
<label className="form-label">Name</label>
<input
className="form-control form-control-sm"
{...register("Name")}
{...register("name")}
/>
{errors.Name && (
<small className="danger-text">{errors.Name.message}</small>
{errors.name && (
<small className="danger-text">{errors.name.message}</small>
)}
</div>
<div className="col-md-6">
<div className="col-md-6 text-start">
<label className="form-label">Organization</label>
<input
className="form-control form-control-sm"
@ -202,29 +179,29 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
key={field.id}
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>
<select
className="form-select form-select-sm"
{...register(`ContactEmails.${index}.label`)}
{...register(`contactEmails.${index}.label`)}
>
<option value="Work">Work</option>
<option value="Personal">Personal</option>
<option value="Other">Other</option>
</select>
{errors.ContactEmails?.[index]?.label && (
{errors.contactEmails?.[index]?.label && (
<small className="danger-text">
{errors.ContactEmails[index].label.message}
{errors.contactEmails[index].label.message}
</small>
)}
</div>
<div className="col-7">
<div className="col-7 text-start">
<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`)}
{...register(`contactEmails.${index}.emailAddress`)}
placeholder="email@example.com"
/>
{index === emailFields.length - 1 ? (
@ -247,27 +224,26 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
</button>
)}
</div>
{errors.ContactEmails?.[index]?.emailAddress && (
{errors.contactEmails?.[index]?.emailAddress && (
<small className="danger-text">
{errors.ContactEmails[index].emailAddress.message}
{errors.contactEmails[index].emailAddress.message}
</small>
)}
</div>
</div>
))}
</div>
<div className="col-md-6">
{phoneFields.map((field, index) => (
<div
key={field.id}
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>
<select
className="form-select form-select-sm"
{...register(`ContactPhones.${index}.label`)}
{...register(`contactPhones.${index}.label`)}
>
<option value="Office">Office</option>
<option value="Personal">Personal</option>
@ -279,13 +255,13 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
</small>
)}
</div>
<div className="col-7">
<div className="col-7 text-start">
<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`)}
{...register(`contactPhones.${index}.phoneNumber`)}
placeholder="9876543210"
/>
{index === phoneFields.length - 1 ? (
@ -308,27 +284,28 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
</button>
)}
</div>
{errors.ContactPhones?.[index]?.phoneNumber && (
{errors.contactPhones?.[index]?.phoneNumber && (
<small className="danger-text">
{errors.ContactPhones[index].phoneNumber.message}
{errors.contactPhones[index].phoneNumber.message}
</small>
)}
</div>
</div>
))}
</div>
{errors.contactPhone?.message && (
<div className="danger-text">{errors.contactPhone.message}</div>
)}
</div>
<div className="row my-1">
<div className="col-md-6">
<div className="col-md-6 text-start">
<label className="form-label">Category</label>
<select
defaultValue=""
className="form-select form-select-sm"
{...register("ContactCategoryId")}
onClick={() => dispatch(changeMaster("Contact Category"))}
{...register("contactCategoryId")}
>
{loading && !categoryData ? (
{contactCategoryLoading && !contactCategory ? (
<option disabled value="">
Loading...
</option>
@ -337,7 +314,7 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
<option disabled selected value="">
Select Category
</option>
{categoryData?.map((cate) => (
{contactCategory?.map((cate) => (
<option key={cate.id} value={cate.id}>
{cate.name}
</option>
@ -345,26 +322,52 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
</>
)}
</select>
{errors.ContactCategoryId && (
<small className="danger-text">{errors.ContactCategoryId.message}</small>
{errors.contactCategoryId && (
<small className="danger-text">
{errors.contactCategoryId.message}
</small>
)}
</div>
<div className="col-md-6">
<TagInput name="tags" label="Tags" options={data} />
<div className="col-12 col-md-6 text-start">
<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 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" }}
<div className="col-12 text-start">
<TagInput name="tags" label="Tags" options={contactTags} />
{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>}
{buckets?.map((item) => (
<div className="col-6 col-sm-6 " key={item.id}>
<div className="form-check mb-2">
<li
key={item.id}
className="list-inline-item flex-shrink-0 me-6 mb-2"
>
<div className="form-check ">
<input
type="checkbox"
className="form-check-input"
@ -379,47 +382,17 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
{item.name}
</label>
</div>
</div>
</li>
))}
</div>
</ul>
{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 className="col-12">
<div className="col-12 text-start">
<label className="form-label">Address</label>
<textarea
className="form-control form-control-sm"
@ -428,7 +401,7 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
/>
</div>
<div className="col-12">
<div className="col-12 text-start">
<label className="form-label">Description</label>
<textarea
className="form-control form-control-sm"
@ -444,7 +417,11 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
<button className="btn btn-sm btn-primary" type="submit">
{IsSubmitting ? "Please Wait..." : "Submit"}
</button>
<button className="btn btn-sm btn-secondary" type="button" onClick={onCLosed}>
<button
className="btn btn-sm btn-secondary"
type="button"
onClick={handleClosed}
>
Cancel
</button>
</div>

View File

@ -0,0 +1,455 @@
import React, { useEffect, useState } from "react";
import {
useForm,
useFieldArray,
FormProvider,
useFormContext,
} from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import TagInput from "../common/TagInput";
import IconButton from "../common/IconButton";
import useMaster, {
useContactCategory,
useContactTags,
} 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";
import SelectMultiple from "../common/SelectMultiple";
import { ContactSchema } from "./DirectorySchema";
const UpdateContact = ({ submitContact, existingContact, 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 { contactCategory, loading: contactCategoryLoading } =
useContactCategory();
const { contactTags, loading: Tagloading } = useContactTags();
const [ IsSubmitting, setSubmitting ] = useState( false );
const [isInitialized, setIsInitialized] = useState(false);
const dispatch = useDispatch();
const methods = useForm({
resolver: zodResolver(ContactSchema),
defaultValues: {
name: "",
organization: "",
contactCategoryId: null,
address: "",
description: "",
projectIds: [],
contactEmails: [],
contactPhones: [],
tags: [],
bucketIds: [],
},
});
const {
register,
handleSubmit,
control,
getValues,
trigger,
setValue,
watch,
reset,
formState: { errors },
} = methods;
const {
fields: emailFields,
append: appendEmail,
remove: removeEmail,
} = useFieldArray({ control, name: "contactEmails" });
const {
fields: phoneFields,
append: appendPhone,
remove: removePhone,
} = useFieldArray({ control, name: "contactPhones" });
const handleAddEmail = async () => {
const emails = getValues("contactEmails");
const lastIndex = emails.length - 1;
const valid = await trigger(`contactEmails.${lastIndex}.emailAddress`);
if (valid) {
appendEmail({ label: "Work", emailAddress: "" });
}
};
const handleAddPhone = async () => {
const phones = getValues("contactPhones");
const lastIndex = phones.length - 1;
const valid = await trigger(`contactPhones.${lastIndex}.phoneNumber`);
if (valid) {
appendPhone({ label: "Office", phoneNumber: "" });
}
};
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 = async (data) => {
debugger;
const cleaned = {
...data,
contactEmails: (data.contactEmails || []).filter(
(e) => e.emailAddress?.trim() !== ""
),
contactPhones: (data.contactPhones || []).filter(
(p) => p.phoneNumber?.trim() !== ""
),
};
setSubmitting(true);
await submitContact({ ...cleaned, id: existingContact.id });
setSubmitting(false);
};
const handleClosed = () => {
onCLosed();
};
useEffect(() => {
const isValidContact =
existingContact &&
typeof existingContact === "object" &&
!Array.isArray(existingContact);
if (!isInitialized &&isValidContact && TagsData) {
reset({
name: existingContact.name || "",
organization: existingContact.organization || "",
contactEmails: existingContact.contactEmails || [],
contactPhones: existingContact.contactPhones || [],
contactCategoryId: existingContact.contactCategory?.id || null,
address: existingContact.address || "",
description: existingContact.description || "",
projectIds: existingContact.projectIds || null,
tags: existingContact.tags || [],
bucketIds: existingContact.bucketIds || [],
} );
if (!existingContact.contactPhones || existingContact.contactPhones.length === 0) {
appendPhone({ label: "Office", phoneNumber: "" });
}
if (!existingContact.contactEmails || existingContact.contactEmails.length === 0) {
appendEmail({ label: "Work", emailAddress: "" });
}
setIsInitialized(true)
}
return()=> reset()
}, [ existingContact, buckets, projects ] );
return (
<FormProvider {...methods}>
<form className="p-2 p-sm-0" onSubmit={handleSubmit(onSubmit)}>
<div className="d-flex justify-content-center align-items-center">
<IconButton size={15} iconClass="bx bx-user-plus" color="primary" />{" "}
<h6 className="m-0 fw-18"> Update Contact</h6>
</div>
<div className="row">
<div className="col-md-6 text-start">
<label className="form-label">Name</label>
<input
className="form-control form-control-sm"
{...register("name")}
/>
{errors.name && (
<small className="danger-text">{errors.name.message}</small>
)}
</div>
<div className="col-md-6 text-start">
<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>
<div className="row mt-1">
<div className="col-md-6">
{emailFields.map((field, index) => (
<div
key={field.id}
className="row d-flex align-items-center mb-1"
>
<div className="col-5 text-start">
<label className="form-label">Label</label>
<select
className="form-select form-select-sm"
{...register(`contactEmails.${index}.label`)}
>
<option value="Work">Work</option>
<option value="Personal">Personal</option>
<option value="Other">Other</option>
</select>
{errors.contactEmails?.[index]?.label && (
<small className="danger-text">
{errors.contactEmails[index].label.message}
</small>
)}
</div>
<div className="col-7 text-start">
<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>
<div className="col-md-6">
{phoneFields.map((field, index) => (
<div
key={field.id}
className="row d-flex align-items-center mb-2"
>
<div className="col-5 text-start">
<label className="form-label">Label</label>
<select
className="form-select form-select-sm"
{...register(`contactPhones.${index}.label`)}
>
<option value="Office">Office</option>
<option value="Personal">Personal</option>
<option value="Business">Business</option>
</select>
{errors.phone?.[index]?.label && (
<small className="danger-text">
{errors.ContactPhones[index].label.message}
</small>
)}
</div>
<div className="col-7 text-start">
<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.contactPhone?.message && (
<div className="danger-text">{errors.contactPhone.message}</div>
)}
</div>
<div className="row my-1">
<div className="col-md-6 text-start">
<label className="form-label">Category</label>
<select
className="form-select form-select-sm"
{...register("contactCategoryId")}
>
{contactCategoryLoading && !contactCategory ? (
<option disabled value="">
Loading...
</option>
) : (
<>
<option disabled selected value="">
Select Category
</option>
{contactCategory?.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 className="col-12 col-md-6 text-start">
<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 className="col-12 text-start">
<TagInput name="tags" label="Tags" options={contactTags} />
{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>}
{buckets?.map((item) => (
<li
key={item.id}
className="list-inline-item flex-shrink-0 me-6 mb-2"
>
<div className="form-check ">
<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>
</li>
))}
</ul>
{errors.BucketIds && (
<small className="text-danger">{errors.BucketIds.message}</small>
)}
</div>
</div>
<div className="col-12 text-start">
<label className="form-label">Address</label>
<textarea
className="form-control form-control-sm"
rows="2"
{...register("address")}
/>
</div>
<div className="col-12 text-start">
<label className="form-label">Description</label>
<textarea
className="form-control form-control-sm"
rows="2"
{...register("description")}
/>
{errors.description && (
<small className="danger-text">{errors.description.message}</small>
)}
</div>
<div className="d-flex justify-content-center gap-1 py-2">
<button className="btn btn-sm btn-primary" type="submit" disabled={IsSubmitting}>
{IsSubmitting ? "Please Wait..." : "Update"}
</button>
<button
className="btn btn-sm btn-secondary"
type="button"
onClick={handleClosed}
disabled={IsSubmitting}
>
Cancel
</button>
</div>
</form>
</FormProvider>
);
};
export default UpdateContact;

View File

@ -157,4 +157,67 @@ export const useActivitiesMaster = () =>
}, [] )
return {categories,categoryLoading,categoryError}
}
}
export const useContactCategory = () =>
{
const [ contactCategory, setContactCategory ] = useState( [] )
const [ loading, setLoading ] = useState( false )
const [ Error, setError ] = useState()
const fetchConatctCategory = async() =>
{
const cache_Category = getCachedData( "Contact Category" );
if ( !cache_Category )
{
try
{
let resp = await MasterRespository.getContactCategory();
setContactCategory( resp.data );
cacheData("Contact Category",resp.data)
} catch ( error )
{
setError(error)
}
} else
{
setContactCategory(cache_Category)
}
}
useEffect( () =>
{
fetchConatctCategory()
}, [] )
return { contactCategory,loading,Error}
}
export const useContactTags = () => {
const [contactTags, setContactTags] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
const fetchContactTag = async () => {
const cache_Tags = getCachedData("Contact Tag");
if (!cache_Tags) {
setLoading(true);
try {
const resp = await MasterRespository.getContactTag();
setContactTags(resp.data);
cacheData("Contact Tag", resp.data);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
} else {
setContactTags(cache_Tags);
}
};
fetchContactTag();
}, []);
return { contactTags, loading, error };
};

View File

@ -1,77 +1,63 @@
import {useEffect, useState} from "react"
import {DirectoryRepository} from "../repositories/DirectoryRepository";
import {cacheData, getCachedData} from "../slices/apiDataManager";
import { useEffect, useState } from "react";
import { DirectoryRepository } from "../repositories/DirectoryRepository";
import { cacheData, getCachedData } from "../slices/apiDataManager";
export const useDirectory = () =>
{
const [ contacts, setContacts ] = useState( [] )
const [ loading, setLoading ] = useState( false )
const [ error, setError ] = useState();
export const useDirectory = () => {
const [contacts, setContacts] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState();
const fetch = async() =>
{
const cache_contacts = getCachedData( "contacts" );
if ( !cache_contacts )
{
setLoading(true)
try
{
const response = await DirectoryRepository.GetContacts();
setContacts( response.data )
cacheData( "contacts", response.data )
setLoading(false)
} catch ( error )
{
setError( error );
setLoading(false)
}
} else
{
setContacts(cache_contacts)
}
const fetch = async () => {
const cache_contacts = getCachedData("contacts");
if (!cache_contacts) {
setLoading(true);
try {
const response = await DirectoryRepository.GetContacts();
setContacts(response.data);
cacheData("contacts", response.data);
setLoading(false);
} catch (error) {
setError(error);
setLoading(false);
}
} else {
setContacts(cache_contacts);
}
};
useState( () =>
{
fetch()
}, [] )
return {contacts,loading,error}
}
useState(() => {
fetch();
}, []);
return { contacts, loading, error };
};
export const useBuckets = () =>
{
const [ buckets, setbuckets ] = useState();
const [ loading, setLoading ] = useState();
const [ Error, setError ] = useState( '' )
const fetch = async() =>
{ const cache_buckets = getCachedData("buckets")
if ( !cache_buckets )
{
setLoading(true)
try
{
const resp = await DirectoryRepository.GetBucktes();
setbuckets( resp.data );
cacheData( "bucktes", resp.data )
setLoading(false)
} catch ( error )
{
const msg = error.response.data.message || error.message || "Something wrong";
setError(msg)
}
} else
{
setbuckets(cache_buckets)
}
export const useBuckets = () => {
const [buckets, setBuckets] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const fetchBuckets = async () => {
const cacheBuckets = getCachedData("buckets");
if (!cacheBuckets) {
setLoading( true );
try {
const resp = await DirectoryRepository.GetBucktes();
setBuckets(resp.data);
cacheData( "buckets", resp.data );
setLoading(false);
} catch (error) {
const msg =
error?.response?.data?.message || error?.message || "Something went wrong";
setError(msg);
}
} else {
setBuckets(cacheBuckets);
}
};
useEffect( () =>
{
fetch()
}, [] )
return {buckets,loading,Error}
}
useEffect(() => {
fetchBuckets();
}, []);
return { buckets, loading, error };
};

View File

@ -8,35 +8,50 @@ import { useDirectory } from "../../hooks/useDirectory";
import { DirectoryRepository } from "../../repositories/DirectoryRepository";
import { getCachedData } from "../../slices/apiDataManager";
import showToast from "../../services/toastService";
import UpdateContact from "../../components/Directory/UpdateContact";
const Directory = () => {
const [isOpenModal, setIsOpenModal] = useState(false);
const closedModel = () => setIsOpenModal(false);
const [selectedContact, setSelectedContact] = useState(null);
const [ContatList, setContactList] = useState([]);
const { contacts, loading } = useDirectory();
const submitContact = async (data, setLoading, reset) => {
try
{
debugger
const resp = await DirectoryRepository.CreateContact(data)
const submitContact = async (data) => {
try {
let response;
let updatedContacts;
const contacts_cache = getCachedData("contacts") || [];
const updated_contacts = [...contacts_cache, resp.data];
setContactList(updated_contacts);
showToast(resp.message || "Contact created successfully", "success");
setLoading(false);
reset();
setIsOpenModal(false);
if (selectedContact) {
response = await DirectoryRepository.UpdateContact(data.id, data);
updatedContacts = contacts_cache.map((contact) =>
contact.id === data.id ? response.data : contact
);
showToast("Contact updated successfully", "success");
setIsOpenModal( false );
setSelectedContact(null);
} else {
response = await DirectoryRepository.CreateContact(data);
updatedContacts = [...contacts_cache, response.data];
showToast("Contact created successfully", "success");
setIsOpenModal(false);
}
setContactList(updatedContacts);
} catch (error) {
const msg =
error.response.data.message ||
error.response?.data?.message ||
error.message ||
"Error Occured during api calling !";
"Error occurred during API call!";
showToast(msg, "error");
}
};
const closedModel = () => {
setIsOpenModal(false);
setSelectedContact(null);
};
useEffect(() => {
setContactList(contacts);
}, [contacts]);
@ -50,11 +65,23 @@ const Directory = () => {
></Breadcrumb>
{isOpenModal && (
<GlobalModel isOpen={isOpenModal} closeModal={()=>setIsOpenModal(false)} size="lg">
<ManageDirectory
submitContact={submitContact}
onCLosed={closedModel}
/>
<GlobalModel
isOpen={isOpenModal}
closeModal={() => setIsOpenModal(false)}
size="lg"
>
{selectedContact ? (
<UpdateContact
existingContact={selectedContact}
submitContact={submitContact}
onCLosed={closedModel}
/>
) : (
<ManageDirectory
submitContact={submitContact}
onCLosed={closedModel}
/>
)}
</GlobalModel>
)}
@ -93,7 +120,7 @@ const Directory = () => {
<span>Name</span>
</div>
</th>
<th className="px-2 text-start">
<th className="px-2 text-start">
<div className="d-flex text-center align-items-center gap-1 justify-content-start">
<IconButton
size={12}
@ -169,21 +196,22 @@ const Directory = () => {
</tr>
</thead>
<tbody className="table-border-bottom-0 overflow-auto ">
{(loading && ContatList.length === 0) && (
{loading && ContatList.length === 0 && (
<tr>
<td colSpan={10}>Loading...</td>
</tr>
)}
{(!loading && contacts.length == 0 && ContatList.length === 0) && (
{!loading && contacts.length == 0 && ContatList.length === 0 && (
<tr>
<td colSpan={10}>No Contact Found</td>
</tr>
)}
)}
{!loading &&
ContatList.map((contact) => (
<ListViewDirectory
contact={contact}
submitContact={submitContact}
setSelectedContact={setSelectedContact}
setIsOpenModal={setIsOpenModal}
/>
))}
</tbody>

View File

@ -2,7 +2,8 @@ import {api} from "../utils/axiosClient";
export const DirectoryRepository = {
GetContacts: () => api.get( '/api/directory' ),
CreateContact:(data)=>api.post('/api/directory',data),
CreateContact: ( data ) => api.post( '/api/directory', data ),
UpdateContact:(id,data)=>api.put(`/api/directory/${id}`,data),
GetBucktes:()=>api.get(`/api/Directory/buckets`)
}