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,18 +52,20 @@ 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>
{/* Actions */} {/* Actions */}
<td className="align-middle text-center "> <td className="align-middle text-center ">
<i className='bx bx-edit bx-sm text-primary cursor-pointer'></i> <i className='bx bx-edit bx-sm text-primary cursor-pointer'></i>
<i className='bx bx-trash bx-sm text-danger cursor-pointer'></i> <i className='bx bx-trash bx-sm text-danger cursor-pointer'></i>
</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,357 +51,160 @@ 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">Organization</label> <label className="form-label">Last Name</label>
<input <input className="form-control form-control-sm" {...register("lastName")} />
className="form-control form-control-sm" {errors.lastName && <small className="danger-text">{errors.lastName.message}</small>}
{...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">
{emailFields.map((field, index) => ( <label className="form-label">Email</label>
<div {emailFields.map((field, index) => (<>
key={field.id} <div key={field.id} className="d-flex align-items-center mb-1">
className="row d-flex align-items-center mb-1" <input
> type="email"
<div className="col-5"> className="form-control form-control-sm"
<label className="form-label">Label</label> {...register(`email.${index}`)}
<select placeholder="email@example.com"
className="form-select form-select-sm" />
{...register(`ContactEmails.${index}.label`)} {index === emailFields.length - 1 ? (
<button
type="button"
className="btn btn-xs btn-primary ms-1"
onClick={handleAddEmail}
> >
<option value="Work">Work</option> <i className="bx bx-plus bx-xs" />
<option value="Personal">Personal</option> </button>
<option value="Other">Other</option> ) : (
</select> <button
{errors.ContactEmails?.[index]?.label && ( type="button"
<small className="danger-text"> className="btn btn-xs btn-danger ms-1"
{errors.ContactEmails[index].label.message} onClick={() => removeEmail(index)}
</small> >
)} <i className="bx bx-x bx-xs" />
</div> </button>
<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">
{phoneFields.map((field, index) => ( <label className="form-label">Phone</label>
<div {phoneFields.map((field, index) => (<>
key={field.id} <div key={field.id} className="d-flex align-items-center mb-1">
className="row d-flex align-items-center mb-2" <input
> type="text"
<div className="col-5"> className="form-control form-control-sm"
<label className="form-label">Label</label> {...register(`phone.${index}`)}
<select placeholder="9876543210"
className="form-select form-select-sm" />
{...register(`ContactPhones.${index}.label`)} {index === phoneFields.length - 1 ? (
<button
type="button"
className="btn btn-xs btn-primary ms-1"
onClick={handleAddPhone}
> >
<option value="Office">Office</option> <i className="bx bx-plus bx-xs" />
<option value="Personal">Personal</option> </button>
<option value="Business">Business</option> ) : (
</select> <button
{errors.phone?.[index]?.label && ( type="button"
<small className="danger-text"> className="btn btn-xs btn-danger ms-1"
{errors.ContactPhones[index].label.message} onClick={() => removePhone(index)} // Remove the phone field
</small> >
)} <i className="bx bx-x bx-xs" />
</div> </button>
<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">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

@ -12,29 +12,28 @@ const GlobalModel = ({
}) => { }) => {
const modalRef = useRef(null); // Reference to the modal element const modalRef = useRef(null); // Reference to the modal element
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
});
if (isOpen) { // Show modal if isOpen is true
modalInstance.show(); if (isOpen) {
} else { modalInstance.show();
modalInstance.hide(); } else {
} modalInstance.hide();
}
const handleHideModal = () => { // Handle modal hide event to invoke the closeModal function
closeModal(); const handleHideModal = () => {
}; closeModal(); // Close the modal via React state
};
modalElement.addEventListener('hidden.bs.modal', handleHideModal); modalElement.addEventListener('hidden.bs.modal', handleHideModal);
return () => {
modalElement.removeEventListener('hidden.bs.modal', handleHideModal);
};
}, [isOpen, closeModal]);
return () => {
modalElement.removeEventListener('hidden.bs.modal', handleHideModal);
};
}, [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, name, setValue]);
tags.map((tag) => ({
id: tag.id ?? null,
name: tag.name,
}))
);
}, [ tags, name, setValue ] );
useEffect(() => { const addTag = (e) => {
if (input.trim() === "") { e.preventDefault();
setSuggestions([]); const trimmed = input.trim();
} else { if (trimmed !== "" && !tags.includes(trimmed)) {
const filtered = options?.filter( setTags([...tags, trimmed]);
(opt) => setInput("");
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();
const existing = options.find(
(opt) => opt.name.toLowerCase() === input.trim().toLowerCase()
);
const newTag = existing
? 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,72 +34,32 @@ 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) => (
<span
<div key={i}
className="form-control form-control-sm p-1" className="d-flex align-items-center"
style={{ minHeight: "38px", position: "relative" }}
>
<div className="d-flex flex-wrap align-items-center gap-1">
{tags.map((tag, index) => (
<span
key={index}
className="d-flex align-items-center"
style={{
color: iconColor,
backgroundColor,
padding: "2px 6px",
borderRadius: "2px",
fontSize: "0.85rem",
}}
>
{tag.name}
<i
className="bx bx-x bx-xs ms-1"
onClick={() => removeTag(index)}
style={{ cursor: "pointer" }}
/>
</span>
))}
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleInputKeyDown}
placeholder={placeholder}
style={{ style={{
border: "none", color: iconColor,
outline: "none", backgroundColor,
flex: 1, padding: "2px 3px",
minWidth: "120px", borderRadius: "2px"
}}
onFocus={() => dispatch(changeMaster("Contact Tag"))}
/>
</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) => ( {tag}
<li <i className="bx bx-x bx-xs ms-1" onClick={() => removeTag(i)}></i>
key={i} </span>
className="dropdown-item p-1 hoverBox" ))}
onClick={() => handleSuggestionClick(sugg)} <input
style={{ cursor: "pointer", fontSize: "0.875rem" }} type="text"
> className="border-0 flex-grow-1"
{sugg.name} value={input}
</li> onChange={(e) => setInput(e.target.value)}
))} onKeyDown={(e) => (e.key === "Enter" ? addTag(e) : null)}
</ul> placeholder={placeholder}
)} style={{ outline: "none", minWidth: "120px" }}
/>
</div> </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";
@ -20,16 +20,12 @@ 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 </GlobalModel>
submitContact={submitContact}
onCLosed={closedModel}
/>
</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">
@ -80,9 +48,9 @@ const Directory = () => {
</div> </div>
<div className="table-responsive text-nowrap py-2 "> <div className="table-responsive text-nowrap py-2 ">
<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,23 +137,9 @@ 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>
</div> </div>

View File

@ -1,8 +1,5 @@
import {api} from "../utils/axiosClient"; 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`)
} }