marco.pms.web/src/hooks/useDirectory.js
2025-09-30 23:39:41 +05:30

591 lines
16 KiB
JavaScript

import { useEffect, useState } from "react";
import { DirectoryRepository } from "../repositories/DirectoryRepository";
import { cacheData, getCachedData } from "../slices/apiDataManager";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import showToast from "../services/toastService";
import { queryClient } from "../layouts/AuthLayout";
export const useDirectory = (isActive, prefernceContacts) => {
const [contacts, setContacts] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const fetch = async (activeParam = isActive) => {
setLoading(true);
try {
const response = await DirectoryRepository.GetContacts(
activeParam,
prefernceContacts
);
setContacts(response.data);
cacheData("contacts", { data: response.data, isActive: activeParam });
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
};
useEffect(() => {
const cachedContacts = getCachedData("contacts");
if (
!cachedContacts?.data ||
cachedContacts.isActive !== isActive ||
prefernceContacts
) {
fetch(isActive, prefernceContacts);
} else {
setContacts(cachedContacts.data);
}
}, [isActive, prefernceContacts]);
return {
contacts,
loading,
error,
refetch: fetch,
};
};
export const useBuckets = () => {
const [buckets, setBuckets] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const fetchBuckets = async () => {
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);
setLoading(false);
}
};
useEffect(() => {
const cacheBuckets = getCachedData("buckets");
if (!cacheBuckets) {
fetchBuckets();
} else {
setBuckets(cacheBuckets);
}
}, []);
return { buckets, loading, error, refetch: fetchBuckets };
};
export const useContactProfile = (id) => {
const [contactProfile, setContactProfile] = useState(null);
const [loading, setLoading] = useState(false);
const [Error, setError] = useState("");
const fetchContactProfile = async () => {
setLoading(true);
try {
const resp = await DirectoryRepository.GetContactProfile(id);
setContactProfile(resp.data);
cacheData("Contact Profile", { data: resp.data, contactId: id });
} catch (err) {
const msg =
err?.response?.data?.message || err?.message || "Something went wrong";
setError(msg);
} finally {
setLoading(false);
}
};
useEffect(() => {
const cached = getCachedData("Contact Profile");
if (!cached || cached.contactId !== id) {
fetchContactProfile(id);
} else {
setContactProfile(cached.data);
}
}, [id]);
return { contactProfile, loading, Error, refetch: fetchContactProfile };
};
export const useContactNotes = (id, IsActive) => {
const [contactNotes, setContactNotes] = useState([]);
const [loading, setLoading] = useState(false);
const [Error, setError] = useState("");
const fetchContactNotes = async (id, IsActive) => {
setLoading(true);
try {
const resp = await DirectoryRepository.GetNote(id, IsActive);
setContactNotes(resp.data);
cacheData("Contact Notes", { data: resp.data, contactId: id });
} catch (err) {
const msg =
err?.response?.data?.message || err?.message || "Something went wrong";
setError(msg);
} finally {
setLoading(false);
}
};
useEffect(() => {
const cached = getCachedData("Contact Notes");
if (!cached || cached.contactId !== id) {
id && fetchContactNotes(id, IsActive);
} else {
setContactNotes(cached.data);
}
}, [id, IsActive]);
return { contactNotes, loading, Error, refetch: fetchContactNotes };
};
export const useOrganization = () => {
const [organizationList, setOrganizationList] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const fetchOrg = async () => {
const cacheOrg = getCachedData("organizations");
if (cacheOrg?.length != 0) {
setLoading(true);
try {
const resp = await DirectoryRepository.GetOrganizations();
cacheData("organizations", resp.data);
setOrganizationList(resp.data);
setLoading(false);
} catch (error) {
const msg =
error?.response?.data?.message ||
error?.message ||
"Something went wrong";
setError(msg);
}
} else {
setOrganizationList(cacheOrg);
}
};
useEffect(() => {
fetchOrg();
}, []);
return { organizationList, loading, error };
};
export const useDesignation = () => {
const [designationList, setDesignationList] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const fetchOrg = async () => {
const cacheOrg = getCachedData("designation");
if (cacheOrg?.length != 0) {
setLoading(true);
try {
const resp = await DirectoryRepository.GetDesignations();
cacheData("designation", resp.data);
setDesignationList(resp.data);
setLoading(false);
} catch (error) {
const msg =
error?.response?.data?.message ||
error?.message ||
"Something went wrong";
setError(msg);
}
} else {
setDesignationList(cacheOrg);
}
};
useEffect(() => {
fetchOrg();
}, []);
return { designationList, loading, error };
};
// ------------------------------Query------------------------------------------------------------------
export const useBucketList = () => {
return useQuery({
queryKey: ["bucketList"],
queryFn: async () => {
const resp = await DirectoryRepository.GetBucktes();
return resp.data;
},
});
};
export const useDirectoryNotes = (
pageSize,
pageNumber,
filter,
searchString
) => {
return useQuery({
queryKey: ["directoryNotes", pageSize, pageNumber, filter, searchString],
queryFn: async () =>
await DirectoryRepository.GetBucktes(
pageSize,
pageNumber,
filter,
searchString
),
});
};
const cleanFilter = (filter) => {
const cleaned = { ...filter };
["bucketIds", "categoryIds"].forEach((key) => {
if (Array.isArray(cleaned[key]) && cleaned[key].length === 0) {
delete cleaned[key];
}
});
return cleaned;
};
export const useContactList = (
isActive,
projectId,
pageSize,
pageNumber,
filter,
searchString = ""
) => {
return useQuery({
queryKey: [
"contacts",
isActive,
projectId,
pageSize,
pageNumber,
filter,
searchString,
],
queryFn: async () => {
const cleanedFilter = cleanFilter(filter);
const resp = await DirectoryRepository.GetContacts(
isActive,
projectId,
pageSize,
pageNumber,
cleanedFilter,
searchString
);
return resp.data;
},
});
};
export const useContactFilter = () => {
return useQuery({
queryKey: ["contactFilter"],
queryFn: async () => {
const resp = await DirectoryRepository.GetContactFilter();
return resp.data;
},
});
};
export const useContactDetails = (contactId) => {
return useQuery({
queryKey: ["Contact", contactId],
queryFn: async () => {
const resp = await await DirectoryRepository.GetContact(contactId);
return resp.data;
},
enabled: !!contactId,
});
};
const cleanNoteFilter = (filter) => {
const cleaned = { ...filter };
["createdByIds", "organizations"].forEach((key) => {
if (Array.isArray(cleaned[key]) && cleaned[key].length === 0) {
delete cleaned[key];
}
});
return cleaned;
};
export const useNotes = (
projectId,
pageSize,
pageNumber,
filter,
searchString = ""
) => {
return useQuery({
queryKey: ["Notes", projectId, pageSize, pageNumber, filter, searchString],
queryFn: async () => {
const cleanedFilter = cleanNoteFilter(filter);
const resp = await DirectoryRepository.GetNotes(
projectId,
pageSize,
pageNumber,
cleanedFilter,
searchString
);
return resp.data;
},
});
};
export const useNoteFilter = () => {
return useQuery({
queryKey: ["NoteFilter"],
queryFn: async () => {
const resp = await DirectoryRepository.GetNoteFilter();
return resp.data;
},
});
};
export const useContactProfile1 = (contactId) => {
return useQuery({
queryKey: ["ContactProfile", contactId],
queryFn: async () => {
const resp = await DirectoryRepository.GetContactProfile(contactId);
return resp.data;
},
enabled: !!contactId,
});
};
export const useContactNotes1 = (contactId, active) => {
return useQuery({
queryKey: ["ContactNotes", contactId, active],
queryFn: async () => {
const resp = await DirectoryRepository.GetContactNotes(contactId, active);
return resp.data;
},
enabled: !!contactId,
});
};
// ---------------------------Mutation------------------------------------------------------------------
export const useCreateBucket = (onSuccessCallBack) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (BucketPayload) =>
await DirectoryRepository.CreateBuckets(BucketPayload),
onSuccess: (_, variables) => {
queryClient.invalidateQueries({ queryKey: ["bucketList"] });
showToast("Bucket created Successfully", "success");
if (onSuccessCallBack) onSuccessCallBack();
},
onError: (error) => {
showToast(
error.response.data.message ||
"Something went wrong.Please try again later.",
"error"
);
},
});
};
export const useUpdateBucket = (onSuccessCallBack) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ bucketId, BucketPayload }) =>
await DirectoryRepository.UpdateBuckets(bucketId, BucketPayload),
onSuccess: (_, variables) => {
debugger;
queryClient.invalidateQueries({ queryKey: ["bucketList"] });
showToast("Bucket updated successfully", "success");
if (onSuccessCallBack) onSuccessCallBack();
},
onError: (error) => {
debugger;
showToast(
error?.response?.data?.message ||
"Something went wrong. Please try again later.",
"error"
);
},
});
};
export const useAssignEmpToBucket = (onSuccessCallBack) => {
return useMutation({
mutationFn: async ({ bucketId, EmployeePayload }) =>
await DirectoryRepository.AssignedBuckets(bucketId, EmployeePayload),
onSuccess: (_, variables) => {
const { EmployeePayload } = variables;
queryClient.invalidateQueries({ queryKey: ["bucketList"] });
showToast(
`Bucket shared ${EmployeePayload?.length} Employee Successfully`,
"success"
);
if (onSuccessCallBack) onSuccessCallBack();
},
onError: (error) => {
showToast(
error.response.data.message ||
"Something went wrong.Please try again later.",
"error"
);
},
});
};
export const useDeleteBucket = (onSuccessCallBack) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (bucketId) =>
await DirectoryRepository.DeleteBucket(bucketId),
onSuccess: (_, variables) => {
queryClient.invalidateQueries({ queryKey: ["bucketList"] });
showToast("Bucket deleted Successfully", "success");
if (onSuccessCallBack) onSuccessCallBack();
},
onError: (error) => {
showToast(
error.response.data.message ||
"Something went wrong.Please try again later.",
"error"
);
},
});
};
export const useCreateContact = (onSuccessCallBack) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (contactPayload) =>
await DirectoryRepository.CreateContact(contactPayload),
onSuccess: (_, variables) => {
queryClient.invalidateQueries({ queryKey: ["contacts"] });
showToast("Contact created Successfully", "success");
if (onSuccessCallBack) onSuccessCallBack();
},
onError: (error) => {
showToast(
error.response.data.message ||
"Something went wrong.Please try again later.",
"error"
);
},
});
};
export const useUpdateContact = (onSuccessCallBack) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ contactId, contactPayload }) =>
await DirectoryRepository.UpdateContact(contactId, contactPayload),
onSuccess: (_, variables) => {
queryClient.invalidateQueries({ queryKey: ["Contact"] });
queryClient.invalidateQueries({ queryKey: ["contacts"] });
showToast("Contact updated Successfully", "success");
if (onSuccessCallBack) onSuccessCallBack();
},
onError: (error) => {
showToast(
error.response.data.message ||
"Something went wrong.Please try again later.",
"error"
);
},
});
};
export const useActiveInActiveContact = (onSuccessCallBack) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ contactId, contactStatus }) =>
await DirectoryRepository.DeleteContact(contactId, contactStatus),
onSuccess: (_, variables) => {
const { contactStatus } = variables;
queryClient.invalidateQueries({ queryKey: ["contacts"] });
showToast(
`Contact ${contactStatus ? "Restored" : "Deleted"} Successfully`,
"success"
);
if (onSuccessCallBack) onSuccessCallBack();
},
onError: (error) => {
showToast(
error.response.data.message ||
"Something went wrong.Please try again later.",
"error"
);
},
});
};
export const useCreateNote = (onSuccessCallBack) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (notPayload) =>
await DirectoryRepository.CreateNote(notPayload),
onSuccess: (_, variables) => {
queryClient.invalidateQueries({ queryKey: ["Notes"] });
queryClient.invalidateQueries({ queryKey: ["ContactNotes"] });
showToast(`Note Created Successfully`, "success");
if (onSuccessCallBack) onSuccessCallBack();
},
onError: (error) => {
showToast(
error.response.data.message ||
"Something went wrong.Please try again later.",
"error"
);
},
});
};
export const useUpdateNote = (onSuccessCallBack) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ noteId, notePayload }) =>
await DirectoryRepository.UpdateNote(noteId, notePayload),
onSuccess: (_, variables) => {
queryClient.invalidateQueries({ queryKey: ["Notes"] });
queryClient.invalidateQueries({ queryKey: ["ContactNotes"] });
showToast("Note updated Successfully", "success");
if (onSuccessCallBack) onSuccessCallBack();
},
onError: (error) => {
showToast(
error.response.data.message ||
"Something went wrong.Please try again later.",
"error"
);
},
});
};
export const useActiveInActiveNote = (onSuccessCallBack) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ noteId, noteStatus }) =>
await DirectoryRepository.DeleteNote(noteId, noteStatus),
onSuccess: (_, variables) => {
const { noteStatus } = variables;
queryClient.invalidateQueries({ queryKey: ["Notes"] });
queryClient.invalidateQueries({ queryKey: ["ContactNotes"] });
showToast(
`Note ${noteStatus ? "Restored" : "Deleted"} Successfully`,
"success"
);
if (onSuccessCallBack) onSuccessCallBack();
},
onError: (error) => {
showToast(
error.response.data.message ||
"Something went wrong.Please try again later.",
"error"
);
},
});
};