Compare commits

..

No commits in common. "431a541a89f1f2f4575773cb2598e80c70c8aef5" and "9a0482071ab74678e50dace679f4893773e10357" have entirely different histories.

7 changed files with 204 additions and 630 deletions

View File

@ -26,10 +26,10 @@ const getPhoneIcon = (type) => {
const ListViewDirectory = ({ contact }) => { const ListViewDirectory = ({ contact }) => {
return ( return (
<tr key={contact.id} > <tr key={contact.id} >
<td className="text-start" colSpan={2}>{`${contact.name}`}</td> <td className="text-start">{`${contact.name}`}</td>
{/* Emails */} {/* Emails */}
<td > <td colSpan="2">
<div className="d-flex flex-column align-items-start px-1"> <div className="d-flex flex-column align-items-start px-1">
{contact.contactEmails?.map((email, index) => ( {contact.contactEmails?.map((email, index) => (
<span key={email.id}> <span key={email.id}>
@ -52,13 +52,15 @@ const ListViewDirectory = ({ contact }) => {
</div> </div>
</td> </td>
{/* Organization */}
<td className="text-start">{contact.organization}</td> <td className="text-start">{contact.organization}</td>
{/* Tags */}
<td> <td>
<div className="d-flex flex-column align-items-start"> <div className="d-flex flex-column align-items-start">
<span class="badge badge-outline-primary">{contact?.contactCategory?.name }</span> {contact.tags?.map((tag, index) => (
<span key={index} className="badge bg-light text-dark mb-1">{tag}</span>
))}
</div> </div>
</td> </td>

View File

@ -1,82 +1,40 @@
import React, { useEffect, useState } from "react"; import React, { useEffect } from "react";
import { import { useForm, useFieldArray, FormProvider } from "react-hook-form";
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 ContactSchema = z.object({ export const directorySchema = z.object({
Name: z.string().min(1, "Name is required"), firstName: z.string().min(1, "First 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"),
ContactCategoryId: z.string().optional(), type: z.string().min(1, "Type is required"),
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" }),
ProjectId :z.string().optional(), email: z
ContactEmails: z .array(z.string().email("Invalid email"))
.array( .nonempty("At least one email required"),
z.object({ phone: z
label: z.string(), .array(z.string().regex(/^\d{10}$/, "Phone must be 10 digits"))
emailAddress: z.string().email("Invalid email"), .nonempty("At least one phone number is required"),
}) 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(ContactSchema), resolver: zodResolver(directorySchema),
defaultValues: { defaultValues: {
Name: "", firstName: "",
lastName: "",
organization: "", organization: "",
ContactCategoryId: null, type: "",
address: "", address: "",
description: "", description: "",
ProjectId:null, email: [""],
ContactEmails: [], phone: [""],
ContactPhones: [],
tags: [], tags: [],
BucketIds: [],
}, },
}); });
@ -86,9 +44,6 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
control, control,
getValues, getValues,
trigger, trigger,
setValue,
watch,
reset,
formState: { errors }, formState: { errors },
} = methods; } = methods;
@ -96,135 +51,69 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
fields: emailFields, fields: emailFields,
append: appendEmail, append: appendEmail,
remove: removeEmail, remove: removeEmail,
} = useFieldArray({ control, name: "ContactEmails" }); } = useFieldArray({ control, name: "email" });
const { const {
fields: phoneFields, fields: phoneFields,
append: appendPhone, append: appendPhone,
remove: removePhone, remove: removePhone,
} = useFieldArray({ control, name: "ContactPhones" }); } = useFieldArray({ control, name: "phone" });
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("ContactEmails"); const emails = getValues("email");
const lastIndex = emails.length - 1; const lastIndex = emails.length - 1;
const valid = await trigger(`ContactEmails.${lastIndex}.emailAddress`); const valid = await trigger(`email.${lastIndex}`);
if (valid) { if (valid) appendEmail("");
appendEmail({ label: "Work", emailAddress: "" });
}
}; };
const handleAddPhone = async () => { const handleAddPhone = async () => {
const phones = getValues("ContactPhones"); const phones = getValues("phone");
const lastIndex = phones.length - 1; const lastIndex = phones.length - 1;
const valid = await trigger(`ContactPhones.${lastIndex}.phoneNumber`); const valid = await trigger(`phone.${lastIndex}`);
if (valid) { if (valid) appendPhone("");
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">Name</label> <label className="form-label">First Name</label>
<input <input className="form-control form-control-sm" {...register("firstName")} />
className="form-control form-control-sm" {errors.firstName && <small className="danger-text">{errors.firstName.message}</small>}
{...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>
<input className="form-control form-control-sm" {...register("lastName")} />
{errors.lastName && <small className="danger-text">{errors.lastName.message}</small>}
</div>
</div>
<div className="col-12">
<label className="form-label">Organization</label> <label className="form-label">Organization</label>
<input <input className="form-control form-control-sm" {...register("organization")} />
className="form-control form-control-sm" {errors.organization && <small className="danger-text">{errors.organization.message}</small>}
{...register("organization")}
/>
{errors.organization && (
<small className="danger-text">
{errors.organization.message}
</small>
)}
</div> </div>
</div>
<div className="row mt-1"> <div className="row">
<div className="col-md-6"> <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">
<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">
<label className="form-label">Email</label> <label className="form-label">Email</label>
<div className="d-flex align-items-center"> {emailFields.map((field, index) => (<>
<div key={field.id} className="d-flex align-items-center mb-1">
<input <input
type="email" type="email"
className="form-control form-control-sm" className="form-control form-control-sm"
{...register(`ContactEmails.${index}.emailAddress`)} {...register(`email.${index}`)}
placeholder="email@example.com" placeholder="email@example.com"
/> />
{index === emailFields.length - 1 ? ( {index === emailFields.length - 1 ? (
@ -232,68 +121,6 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
type="button" type="button"
className="btn btn-xs btn-primary ms-1" className="btn btn-xs btn-primary ms-1"
onClick={handleAddEmail} 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">
<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">
<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" /> <i className="bx bx-plus bx-xs" />
</button> </button>
@ -301,152 +128,83 @@ const ManageDirectory = ({submitContact,onCLosed}) => {
<button <button
type="button" type="button"
className="btn btn-xs btn-danger ms-1" className="btn btn-xs btn-danger ms-1"
onClick={() => removePhone(index)} onClick={() => removeEmail(index)}
style={{ width: "24px", height: "24px" }}
> >
<i className="bx bx-x bx-xs" /> <i className="bx bx-x bx-xs" />
</button> </button>
)} )}
</div> </div>
{errors.ContactPhones?.[index]?.phoneNumber && ( {errors.email?.[index] && (
<small className="danger-text"> <small className="danger-text ms-2">
{errors.ContactPhones[index].phoneNumber.message} {errors.email[index]?.message}
</small> </small>
)} )}
</div> </>
</div>
))} ))}
</div>
<div className="col-md-6">
<label className="form-label">Phone</label>
{phoneFields.map((field, index) => (<>
<div key={field.id} className="d-flex align-items-center mb-1">
<input
type="text"
className="form-control form-control-sm"
{...register(`phone.${index}`)}
placeholder="9876543210"
/>
{index === phoneFields.length - 1 ? (
<button
type="button"
className="btn btn-xs btn-primary ms-1"
onClick={handleAddPhone}
>
<i className="bx bx-plus bx-xs" />
</button>
) : (
<button
type="button"
className="btn btn-xs btn-danger ms-1"
onClick={() => removePhone(index)} // Remove the phone field
>
<i className="bx bx-x bx-xs" />
</button>
)}
</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">Category</label> <label className="form-label">Type</label>
<select <input className="form-control form-control-sm" {...register("type")} />
defaultValue="" {errors.type && <small className="danger-text">{errors.type.message}</small>}
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" options={data} /> <TagInput name="tags" label="Tags" />
</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 <textarea className="form-control form-control-sm" rows="2" {...register("address")} />
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 <textarea className="form-control form-control-sm" rows="2" {...register("description")} />
className="form-control form-control-sm" {errors.description && <small className="danger-text">{errors.description.message}</small>}
rows="2"
{...register("description")}
/>
{errors.description && (
<small className="danger-text">{errors.description.message}</small>
)}
</div> </div>
<div className="d-flex justify-content-center gap-1 py-2"> <div className="d-flex justify-content-evenly py-2">
<button className="btn btn-sm btn-primary" type="submit"> <button className="btn btn-sm btn-primary" type="submit">Submit</button>
{IsSubmitting ? "Please Wait..." : "Submit"} <button className="btn btn-sm btn-secondary" type="button">Cancel</button>
</button>
<button className="btn btn-sm btn-secondary" type="button" onClick={onCLosed}>
Cancel
</button>
</div> </div>
</form> </form>
</FormProvider> </FormProvider>

View File

@ -14,18 +14,18 @@ const GlobalModel = ({
useEffect(() => { useEffect(() => {
const modalElement = modalRef.current; const modalElement = modalRef.current;
const modalInstance = new window.bootstrap.Modal(modalElement, { const modalInstance = new window.bootstrap.Modal(modalElement);
backdrop: false // Disable backdrop
});
// Show modal if isOpen is true
if (isOpen) { if (isOpen) {
modalInstance.show(); modalInstance.show();
} else { } else {
modalInstance.hide(); modalInstance.hide();
} }
// Handle modal hide event to invoke the closeModal function
const handleHideModal = () => { const handleHideModal = () => {
closeModal(); closeModal(); // Close the modal via React state
}; };
modalElement.addEventListener('hidden.bs.modal', handleHideModal); modalElement.addEventListener('hidden.bs.modal', handleHideModal);
@ -35,7 +35,6 @@ useEffect(() => {
}; };
}, [isOpen, closeModal]); }, [isOpen, closeModal]);
// Dynamically set the modal size classes (modal-sm, modal-lg, modal-xl) // Dynamically set the modal size classes (modal-sm, modal-lg, modal-xl)
const modalSizeClass = size ? `modal-${size}` : ''; // Default is empty if no size is specified const modalSizeClass = size ? `modal-${size}` : ''; // Default is empty if no size is specified

View File

@ -1,89 +1,32 @@
import React, { useState, useEffect } from "react";
import { useFormContext } from "react-hook-form"; import { useFormContext } from "react-hook-form";
import React, { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { changeMaster } from "../../slices/localVariablesSlice";
const TagInput = ({ const TagInput = ({
label = "Tags", label = "Tags",
name = "tags", name = "tags",
placeholder = "Start typing to add...", placeholder = "Enter ... ",
color = "#e9ecef", color = "#e9ecef",
options = [],
}) => { }) => {
const [tags, setTags] = useState([]); const [tags, setTags] = useState([]);
const [input, setInput] = useState(""); const [input, setInput] = useState("");
const [suggestions, setSuggestions] = useState([]); const { setValue } = useFormContext();
const { setValue, trigger } = useFormContext();
const dispatch = useDispatch();
useEffect(() => { useEffect(() => {
setValue( setValue(name, tags); // sync to form when tags change
name,
tags.map((tag) => ({
id: tag.id ?? null,
name: tag.name,
}))
);
}, [tags, name, setValue]); }, [tags, name, setValue]);
useEffect(() => { const addTag = (e) => {
if (input.trim() === "") {
setSuggestions([]);
} else {
const filtered = options?.filter(
(opt) =>
opt?.name?.toLowerCase()?.includes(input?.toLowerCase()) &&
!tags?.some((tag) => tag?.name === opt?.name)
);
setSuggestions(filtered);
}
}, [input, options, tags]);
const addTag = async ( tagObj ) =>
{
if (!tags.some((tag) => tag.id === tagObj.id)) {
const cleanedTag = {
id: tagObj.id ?? null,
name: tagObj.name,
};
const newTags = [...tags, cleanedTag];
setTags(newTags);
setValue(name, newTags, { shouldValidate: true }); // only id + name
await trigger(name);
setInput("");
setSuggestions([]);
}
};
const handleInputKeyDown = (e) => {
if (e.key === "Enter" && input.trim() !== "") {
e.preventDefault(); e.preventDefault();
const existing = options.find( const trimmed = input.trim();
(opt) => opt.name.toLowerCase() === input.trim().toLowerCase() if (trimmed !== "" && !tags.includes(trimmed)) {
); setTags([...tags, trimmed]);
const newTag = existing setInput("");
? existing
: {
id: null,
name: input.trim(),
description: input.trim(),
};
addTag(newTag); // Call async function (not awaiting because it's UI input)
} else if (e.key === "Backspace" && input === "") {
setTags((prev) => prev.slice(0, -1));
} }
}; };
const handleSuggestionClick = (suggestion) => { const removeTag = (removeIndex) => {
addTag(suggestion); const updated = tags.filter((_, i) => i !== removeIndex);
}; setTags(updated);
const removeTag = (indexToRemove) => {
const newTags = tags.filter((_, i) => i !== indexToRemove);
setTags(newTags);
setValue(name, newTags, { shouldValidate: true });
trigger(name);
}; };
const backgroundColor = color || "#f8f9fa"; const backgroundColor = color || "#f8f9fa";
@ -91,73 +34,33 @@ const TagInput = ({
return ( return (
<> <>
<label htmlFor={name} className="form-label"> <label htmlFor={name} className="form-label">{label}</label>
{label} <div className="form-control form-control-sm d-flex justify-content-start flex-wrap gap-1" style={{ minHeight: "12px" }}>
</label> {tags.map((tag, i) => (
<div
className="form-control form-control-sm p-1"
style={{ minHeight: "38px", position: "relative" }}
>
<div className="d-flex flex-wrap align-items-center gap-1">
{tags.map((tag, index) => (
<span <span
key={index} key={i}
className="d-flex align-items-center" className="d-flex align-items-center"
style={{ style={{
color: iconColor, color: iconColor,
backgroundColor, backgroundColor,
padding: "2px 6px", padding: "2px 3px",
borderRadius: "2px", borderRadius: "2px"
fontSize: "0.85rem",
}} }}
> >
{tag.name} {tag}
<i <i className="bx bx-x bx-xs ms-1" onClick={() => removeTag(i)}></i>
className="bx bx-x bx-xs ms-1"
onClick={() => removeTag(index)}
style={{ cursor: "pointer" }}
/>
</span> </span>
))} ))}
<input <input
type="text" type="text"
className="border-0 flex-grow-1"
value={input} value={input}
onChange={(e) => setInput(e.target.value)} onChange={(e) => setInput(e.target.value)}
onKeyDown={handleInputKeyDown} onKeyDown={(e) => (e.key === "Enter" ? addTag(e) : null)}
placeholder={placeholder} placeholder={placeholder}
style={{ style={{ outline: "none", minWidth: "120px" }}
border: "none",
outline: "none",
flex: 1,
minWidth: "120px",
}}
onFocus={() => dispatch(changeMaster("Contact Tag"))}
/> />
</div> </div>
{suggestions.length > 0 && (
<ul
className="list-group position-absolute mt-1 bg-white w-50 shadow-sm"
style={{
zIndex: 1000,
maxHeight: "150px",
overflowY: "auto",
}}
>
{suggestions.map((sugg, i) => (
<li
key={i}
className="dropdown-item p-1 hoverBox"
onClick={() => handleSuggestionClick(sugg)}
style={{ cursor: "pointer", fontSize: "0.875rem" }}
>
{sugg.name}
</li>
))}
</ul>
)}
</div>
</> </>
); );
}; };

View File

@ -1,4 +1,4 @@
import {useEffect, useState} from "react" import {useState} from "react"
import {DirectoryRepository} from "../repositories/DirectoryRepository"; import {DirectoryRepository} from "../repositories/DirectoryRepository";
import {cacheData, getCachedData} from "../slices/apiDataManager"; import {cacheData, getCachedData} from "../slices/apiDataManager";
@ -21,15 +21,11 @@ export const useDirectory = () =>
const response = await DirectoryRepository.GetContacts(); const response = await DirectoryRepository.GetContacts();
setContacts( response.data ) setContacts( response.data )
cacheData("contacts",response.data) cacheData("contacts",response.data)
setLoading(false)
} catch ( error ) } catch ( error )
{ {
setError( error ); setError( error );
setLoading(false) setLoading(false)
} }
} else
{
setContacts(cache_contacts)
} }
} }
@ -40,38 +36,3 @@ export const useDirectory = () =>
}, [] ) }, [] )
return {contacts,loading,error} 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)
}
}
useEffect( () =>
{
fetch()
}, [] )
return {buckets,loading,Error}
}

View File

@ -1,45 +1,18 @@
import React, { useEffect, useState } from "react"; import React, { useState } from "react";
import Breadcrumb from "../../components/common/Breadcrumb"; import Breadcrumb from "../../components/common/Breadcrumb";
import IconButton from "../../components/common/IconButton"; import IconButton from "../../components/common/IconButton";
import GlobalModel from "../../components/common/GlobalModel"; import GlobalModel from "../../components/common/GlobalModel";
import ManageDirectory from "../../components/Directory/ManageDirectory"; import ManageDirectory from "../../components/Directory/ManageDirectory";
import ListViewDirectory from "../../components/Directory/ListViewDirectory"; import ListViewDirectory from "../../components/Directory/ListViewDirectory";
import {useDirectory} from "../../hooks/useDirectory"; import {useDirectory} from "../../hooks/useDirectory";
import { DirectoryRepository } from "../../repositories/DirectoryRepository";
import { getCachedData } from "../../slices/apiDataManager";
import showToast from "../../services/toastService";
const Directory = () => { const Directory = () => {
const [isOpenModal, setIsOpenModal] = useState(false); const [isOpenModal, setIsOpenModal] = useState(false);
const closedModel = () => setIsOpenModal( false ); const closedModel = () => setIsOpenModal( false );
const [ContatList, setContactList] = useState([]);
const { contacts, loading } = useDirectory(); const {contacts} = useDirectory();
const submitContact = async (data, setLoading, reset) => { console.log(contacts)
try
{
debugger
const resp = await DirectoryRepository.CreateContact(data)
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);
} catch (error) {
const msg =
error.response.data.message ||
error.message ||
"Error Occured during api calling !";
showToast(msg, "error");
}
};
useEffect(() => {
setContactList(contacts);
}, [contacts]);
return ( return (
<div className="container-xxl flex-grow-1 container-p-y"> <div className="container-xxl flex-grow-1 container-p-y">
<Breadcrumb <Breadcrumb
@ -49,14 +22,9 @@ const Directory = () => {
]} ]}
></Breadcrumb> ></Breadcrumb>
{isOpenModal && ( <GlobalModel isOpen={isOpenModal} closeModal={closedModel} size="lg">
<GlobalModel isOpen={isOpenModal} closeModal={()=>setIsOpenModal(false)} size="lg"> <ManageDirectory />
<ManageDirectory
submitContact={submitContact}
onCLosed={closedModel}
/>
</GlobalModel> </GlobalModel>
)}
<div className="card p-2"> <div className="card p-2">
<div className="row mx-0 px-0"> <div className="row mx-0 px-0">
@ -82,7 +50,7 @@ const Directory = () => {
<table className="table px-2"> <table className="table px-2">
<thead > <thead >
<tr> <tr>
<th colSpan={2}> <th>
<div className="d-flex align-items-center gap-1"> <div className="d-flex align-items-center gap-1">
<IconButton <IconButton
size={12} size={12}
@ -93,8 +61,8 @@ const Directory = () => {
<span>Name</span> <span>Name</span>
</div> </div>
</th> </th>
<th className="px-2 text-start"> <th colSpan="2" className="px-2 text-center">
<div className="d-flex text-center align-items-center gap-1 justify-content-start"> <div className="d-flex text-center align-items-center gap-1 justify-content-center">
<IconButton <IconButton
size={12} size={12}
iconClass="bx bx-envelope" iconClass="bx bx-envelope"
@ -169,22 +137,8 @@ const Directory = () => {
</tr> </tr>
</thead> </thead>
<tbody className="table-border-bottom-0 overflow-auto "> <tbody className="table-border-bottom-0 overflow-auto ">
{(loading && ContatList.length === 0) && ( {contacts.map((contact) => (
<tr> <ListViewDirectory contact={contact} />
<td colSpan={10}>Loading...</td>
</tr>
)}
{(!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}
/>
))} ))}
</tbody> </tbody>
</table> </table>

View File

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