- {contact.contactPhones?.length > 0 ? (
- contact.contactPhones?.map((phone, index) => (
-
+ {firstPhone ? (
+
- {phone.phoneNumber}
+ {firstPhone.phoneNumber}
- ))
- ):(NA )}
+ ) : (
+ NA
+ )}
@@ -88,12 +94,6 @@ const ListViewDirectory = ({
{contact.organization}
- {/*
-
- {contact?.contactCategory?.name || "Other"}
-
- */}
-
{contact?.contactCategory?.name || "Other"}
@@ -118,9 +118,10 @@ const ListViewDirectory = ({
)}
{!IsActive && (
{
diff --git a/src/components/Directory/ManageDirectory.jsx b/src/components/Directory/ManageDirectory.jsx
index 285b74f2..5c858815 100644
--- a/src/components/Directory/ManageDirectory.jsx
+++ b/src/components/Directory/ManageDirectory.jsx
@@ -14,7 +14,11 @@ import useMaster, {
} from "../../hooks/masterHook/useMaster";
import { useDispatch, useSelector } from "react-redux";
import { changeMaster } from "../../slices/localVariablesSlice";
-import { useBuckets, useOrganization } from "../../hooks/useDirectory";
+import {
+ useBuckets,
+ useDesignation,
+ useOrganization,
+} from "../../hooks/useDirectory";
import { useProjects } from "../../hooks/useProjects";
import SelectMultiple from "../common/SelectMultiple";
import { ContactSchema } from "./DirectorySchema";
@@ -33,8 +37,11 @@ const ManageDirectory = ({ submitContact, onCLosed }) => {
const { contactCategory, loading: contactCategoryLoading } =
useContactCategory();
const { organizationList, loading: orgLoading } = useOrganization();
+ const { designationList, loading: designloading } = useDesignation();
const { contactTags, loading: Tagloading } = useContactTags();
const [IsSubmitting, setSubmitting] = useState(false);
+ const [showSuggestions,setShowSuggestions] = useState(false);
+ const [filteredDesignationList, setFilteredDesignationList] = useState([]);
const dispatch = useDispatch();
const methods = useForm({
@@ -45,6 +52,7 @@ const ManageDirectory = ({ submitContact, onCLosed }) => {
contactCategoryId: null,
address: "",
description: "",
+ designation: "",
projectIds: [],
contactEmails: [],
contactPhones: [],
@@ -106,6 +114,25 @@ const ManageDirectory = ({ submitContact, onCLosed }) => {
const watchBucketIds = watch("bucketIds");
+ // handle logic when input of desgination is changed
+ const handleDesignationChange = (e) => {
+ const val = e.target.value;
+
+ const matches = designationList.filter((org) =>
+ org.toLowerCase().includes(val.toLowerCase())
+ );
+ setFilteredDesignationList(matches);
+ setShowSuggestions(true);
+ setTimeout(() => setShowSuggestions(false), 5000);
+ };
+
+ // handle logic when designation is selected
+ const handleSelectDesignation = (val) => {
+ setShowSuggestions(false);
+ setValue("designation", val);
+ };
+
+
const toggleBucketId = (id) => {
const updated = watchBucketIds?.includes(id)
? watchBucketIds.filter((val) => val !== id)
@@ -168,6 +195,55 @@ const ManageDirectory = ({ submitContact, onCLosed }) => {
/>
+
+
+
Designation
+
+ {showSuggestions && filteredDesignationList.length > 0 && (
+
+ {filteredDesignationList.map((designation) => (
+ handleSelectDesignation(designation)}
+ onMouseEnter={(e) =>
+ (e.currentTarget.style.backgroundColor = "#f8f9fa")
+ }
+ onMouseLeave={(e) =>
+ (e.currentTarget.style.backgroundColor = "transparent")
+ }
+ >
+ {designation}
+
+ ))}
+
+ )}
+ {errors.designation && (
+
+ {errors.designation.message}
+
+ )}
+
+
{emailFields.map((field, index) => (
@@ -381,13 +457,12 @@ const ManageDirectory = ({ submitContact, onCLosed }) => {
))}
-
- {errors.bucketIds && (
-
- {errors.bucketIds.message}
-
- )}
+ {errors.bucketIds && (
+
+ {errors.bucketIds.message}
+
+ )}
diff --git a/src/components/Directory/NoteCardDirectoryEditable.jsx b/src/components/Directory/NoteCardDirectoryEditable.jsx
index de91ad69..5ccfefdf 100644
--- a/src/components/Directory/NoteCardDirectoryEditable.jsx
+++ b/src/components/Directory/NoteCardDirectoryEditable.jsx
@@ -153,7 +153,7 @@ const NoteCardDirectoryEditable = ({
.utc(noteItem?.createdAt)
.add(5, "hours")
.add(30, "minutes")
- .format("MMMM DD, YYYY [at] hh:mm A")}
+ .format("DD MMMM, YYYY [at] hh:mm A")}
diff --git a/src/components/Directory/NotesDirectory.jsx b/src/components/Directory/NotesDirectory.jsx
index 61908853..cccfd8ef 100644
--- a/src/components/Directory/NotesDirectory.jsx
+++ b/src/components/Directory/NotesDirectory.jsx
@@ -4,7 +4,6 @@ import Avatar from "../common/Avatar";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
-import { showText } from "pdf-lib";
import { DirectoryRepository } from "../../repositories/DirectoryRepository";
import moment from "moment";
import { cacheData, getCachedData } from "../../slices/apiDataManager";
@@ -19,15 +18,17 @@ const schema = z.object({
const NotesDirectory = ({
refetchProfile,
isLoading,
- contactProfile,
+ contactProfile, // This contactProfile now reliably includes firstName, middleName, lastName, and fullName
setProfileContact,
}) => {
const [IsActive, setIsActive] = useState(true);
- const { contactNotes, refetch } = useContactNotes(contactProfile?.id, true);
+ const { contactNotes, refetch } = useContactNotes(
+ contactProfile?.id,
+ IsActive
+ );
- const [NotesData, setNotesData] = useState();
const [IsSubmitting, setIsSubmitting] = useState(false);
- const [addNote, setAddNote] = useState(true);
+ const [showEditor, setShowEditor] = useState(false);
const {
register,
handleSubmit,
@@ -67,102 +68,122 @@ const NotesDirectory = ({
) {
const updatedProfile = {
...cached_contactProfile.data,
- notes: [...(cached_contactProfile.notes || []), createdNote],
+ notes: [...(cached_contactProfile.data.notes || []), createdNote],
};
- cacheData("Contact Profile", updatedProfile);
+ cacheData("Contact Profile", {
+ contactId: contactProfile?.id,
+ data: updatedProfile,
+ });
}
setValue("note", "");
setIsSubmitting(false);
showToast("Note added successfully!", "success");
- setAddNote(true);
+ setShowEditor(false);
setIsActive(true);
+ refetch(contactProfile?.id, true);
} catch (error) {
setIsSubmitting(false);
const msg =
- error.response.data.message ||
+ error.response?.data?.message ||
error.message ||
- "Error occured during API calling";
+ "Error occurred during API calling";
showToast(msg, "error");
}
};
const onCancel = () => {
- setValue( "note", "" );
-
+ setValue("note", "");
+ setShowEditor(false);
};
+
const handleSwitch = () => {
- setIsActive(!IsActive);
- if (IsActive) {
- refetch(contactProfile?.id, false);
- }
+ setIsActive((prevIsActive) => {
+ const newState = !prevIsActive;
+ refetch(contactProfile?.id, newState);
+ return newState;
+ });
};
+ // Use the fullName from contactProfile, which now includes middle and last names if available
+ const contactName =
+ contactProfile?.fullName || contactProfile?.firstName || "Contact";
+ const noNotesMessage = `Be the first to share your insights! ${contactName} currently has no notes.`;
+
+ const notesToDisplay = IsActive
+ ? contactProfile?.notes || []
+ : contactNotes || [];
+
return (
-
+
-
-
-
- setAddNote(!addNote)}
- >
- {addNote ? "Hide Editor" : "Add a Note"}
-
-
-
-
-
- {addNote && (
-
-
+ setAddNote(!addNote)}
- >
- {/*
- setAddNote(!addNote)}
- >
- {addNote ? "Hide Editor" : "Add Note"}
-
-
*/}
+ onClick={() => setShowEditor(false)}
+ >
+
+
)}
-
+
{isLoading && (
)}
- {!isLoading &&
- [...(IsActive ? contactProfile?.notes || [] : contactNotes || [])]
- .reverse()
- .map((noteItem) => (
-
- ))}
-
- {IsActive && (
-
- {!isLoading && contactProfile?.notes.length == 0 && !addNote && (
-
No Notes Found
+ {!isLoading && notesToDisplay.length > 0
+ ? notesToDisplay
+ .slice()
+ .reverse()
+ .map((noteItem) => (
+
+ ))
+ : !isLoading &&
+ !showEditor && (
+
{noNotesMessage}
)}
-
- )}
- {!IsActive && (
-
- {!isLoading && contactNotes.length == 0 && !addNote && (
-
No Notes Found
- )}
-
- )}
);
diff --git a/src/components/Directory/ProfileContactDirectory.jsx b/src/components/Directory/ProfileContactDirectory.jsx
index 256e2ea8..f7e8c456 100644
--- a/src/components/Directory/ProfileContactDirectory.jsx
+++ b/src/components/Directory/ProfileContactDirectory.jsx
@@ -8,9 +8,10 @@ const ProfileContactDirectory = ({ contact, setOpen_contact, closeModal }) => {
const { contactProfile, loading, refetch } = useContactProfile(contact?.id);
const [copiedIndex, setCopiedIndex] = useState(null);
- const [profileContact, setProfileContact] = useState();
+ const [profileContactState, setProfileContactState] = useState(null);
const [expanded, setExpanded] = useState(false);
- const description = contactProfile?.description || "";
+
+ const description = profileContactState?.description || "";
const limit = 500;
const toggleReadMore = () => setExpanded(!expanded);
@@ -19,14 +20,51 @@ const ProfileContactDirectory = ({ contact, setOpen_contact, closeModal }) => {
const displayText = expanded
? description
: description.slice(0, limit) + (isLong ? "..." : "");
+
useEffect(() => {
- setProfileContact(contactProfile);
- }, [contactProfile]);
+ if (contactProfile) {
+ const names = (contact?.name || "").trim().split(" ");
+ let firstName = "";
+ let middleName = "";
+ let lastName = "";
+ let fullName = contact?.name || "";
+
+ // Logic to determine first, middle, and last names
+ if (names.length === 1) {
+ firstName = names[0];
+ } else if (names.length === 2) {
+ firstName = names[0];
+ lastName = names[1];
+ } else if (names.length >= 3) {
+ firstName = names[0];
+ middleName = names[1]; // This was an error in the original prompt, corrected to names[1]
+ lastName = names[names.length - 1];
+ // Reconstruct full name to be precise with spacing
+ fullName = `${firstName} ${middleName ? middleName + ' ' : ''}${lastName}`;
+ } else {
+ // Fallback if no names or empty string
+ firstName = "Contact";
+ fullName = "Contact";
+ }
+
+
+ setProfileContactState({
+ ...contactProfile,
+ firstName: contactProfile.firstName || firstName,
+ // Adding middleName and lastName to the state for potential future use or more granular access
+ middleName: contactProfile.middleName || middleName,
+ lastName: contactProfile.lastName || lastName,
+ fullName: contactProfile.fullName || fullName, // Prioritize fetched fullName, fallback to derived
+ });
+ }
+ }, [contactProfile, contact?.name]);
+
const handleCopy = (email, index) => {
navigator.clipboard.writeText(email);
setCopiedIndex(index);
- setTimeout(() => setCopiedIndex(null), 2000); // Reset after 2 seconds
+ setTimeout(() => setCopiedIndex(null), 2000);
};
+
return (
@@ -47,31 +85,35 @@ const ProfileContactDirectory = ({ contact, setOpen_contact, closeModal }) => {
{contact?.name}
- {contactProfile?.tags?.map((tag) => tag.name).join(" | ")}
+ {profileContactState?.designation}
-
+
- {contactProfile?.contactEmails?.length > 0 && (
-
-
-
Email:
+ {profileContactState?.contactEmails?.length > 0 && (
+
+
+
+
+ Email
+
+ :
+
- {contactProfile.contactEmails.map((email, idx) => (
+ {profileContactState.contactEmails.map((email, idx) => (
-
-
+
{email.emailAddress}
handleCopy(email.emailAddress, idx)}
@@ -83,17 +125,22 @@ const ProfileContactDirectory = ({ contact, setOpen_contact, closeModal }) => {
)}
- {contactProfile?.contactPhones?.length > 0 && (
-
-
-
Phone :
+ {profileContactState?.contactPhones?.length > 0 && (
+
+
+
+
+ Phone
+
+ :
+
- {contactProfile?.contactPhones.map((phone, idx) => (
-
-
+ {profileContactState.contactPhones.map((phone, idx) => (
+
{phone.phoneNumber}
+ {idx < profileContactState.contactPhones.length - 1 && ","}
))}
@@ -101,74 +148,93 @@ const ProfileContactDirectory = ({ contact, setOpen_contact, closeModal }) => {
)}
- {contactProfile?.createdAt && (
-
-
-
Created :
+ {profileContactState?.createdAt && (
+
+
+
+
+ Created
+
+ :
+
-
-
- {moment(contactProfile.createdAt).format("MMMM, DD YYYY")}
-
+
+ {moment(profileContactState.createdAt).format("DD MMMM, YYYY")}
+
)}
- {contactProfile?.address && (
-
-
-
-
-
- {contactProfile.address}
+
+ {profileContactState?.address && (
+
+
+
+
+ Location
+ :
+
+
+ {profileContactState.address}
)}
- {contactProfile?.organization && (
-
-
-
Orgnization :
+ {profileContactState?.organization && (
+
+
+
+
+ Organization
+
+ :
-
-
+
- {contactProfile.organization}
+ {profileContactState.organization}
)}
- {contactProfile?.contactCategory && (
-
-
-
Category :
+
+ {profileContactState?.contactCategory && (
+
+
+
+
+ Category
+
+ :
+
-
- {contactProfile.contactCategory.name}
+ {profileContactState.contactCategory.name}
)}
- {contactProfile?.tags?.length > 0 && (
-
-
-
Tags :
+
+ {profileContactState?.tags?.length > 0 && (
+
+
+
+
+ Tags
+
+ :
+
- {contactProfile.tags.map((tag, index) => (
+ {profileContactState.tags.map((tag, index) => (
-
{tag.name}
))}
@@ -177,75 +243,91 @@ const ProfileContactDirectory = ({ contact, setOpen_contact, closeModal }) => {
)}
- {contactProfile?.buckets?.length > 0 && (
-
- {contactProfile?.contactEmails?.length > 0 && (
-
-
-
-
- {contactProfile.buckets.map((bucket) => (
-
-
- {bucket.name}
-
-
- ))}
-
-
-
- )}
+ {profileContactState?.buckets?.length > 0 && (
+
+
+
+
+ Buckets
+
+ :
+
+
+
+
+ {profileContactState.buckets.map((bucket) => (
+
+
+ {bucket.name}
+
+
+ ))}
+
+
)}
-
- {contactProfile?.projects?.length > 0 && (
-
-
-
-
- {contactProfile.projects.map((project, index) => (
-
- {project.name}
- {index < contactProfile.projects.length - 1 && ","}
-
- ))}
-
-
-
- )}
-
-
-
Description :
+ {profileContactState?.projects?.length > 0 && (
+
+
+
+
+ Projects
+
+ :
+
+
+
+
+ {profileContactState.projects.map((project, index) => (
+
+ {project.name}
+ {index < profileContactState.projects.length - 1 && ","}
+
+ ))}
+
+
+
+ )}
+
+
+
+
+
+
+ Description
+
+ :
+
{displayText}
{isLong && (
-
- {expanded ? "Read less" : "Read more"}
-
+ <>
+
+
+ {expanded ? "Read less" : "Read more"}
+
+ >
)}
+
);
};
-export default ProfileContactDirectory;
+export default ProfileContactDirectory;
\ No newline at end of file
diff --git a/src/components/Directory/UpdateContact.jsx b/src/components/Directory/UpdateContact.jsx
index 985229a3..9d74fc35 100644
--- a/src/components/Directory/UpdateContact.jsx
+++ b/src/components/Directory/UpdateContact.jsx
@@ -14,7 +14,11 @@ import useMaster, {
} from "../../hooks/masterHook/useMaster";
import { useDispatch, useSelector } from "react-redux";
import { changeMaster } from "../../slices/localVariablesSlice";
-import { useBuckets, useOrganization } from "../../hooks/useDirectory";
+import {
+ useBuckets,
+ useDesignation,
+ useOrganization,
+} from "../../hooks/useDirectory";
import { useProjects } from "../../hooks/useProjects";
import SelectMultiple from "../common/SelectMultiple";
import { ContactSchema } from "./DirectorySchema";
@@ -32,10 +36,13 @@ const UpdateContact = ({ submitContact, existingContact, onCLosed }) => {
const { contactCategory, loading: contactCategoryLoading } =
useContactCategory();
const { contactTags, loading: Tagloading } = useContactTags();
- const [ IsSubmitting, setSubmitting ] = useState( false );
+ const [IsSubmitting, setSubmitting] = useState(false);
const [isInitialized, setIsInitialized] = useState(false);
const dispatch = useDispatch();
- const {organizationList} = useOrganization()
+ const { organizationList } = useOrganization();
+ const { designationList } = useDesignation();
+ const [showSuggestions, setShowSuggestions] = useState(false);
+ const [filteredDesignationList, setFilteredDesignationList] = useState([]);
const methods = useForm({
resolver: zodResolver(ContactSchema),
@@ -45,6 +52,7 @@ const UpdateContact = ({ submitContact, existingContact, onCLosed }) => {
contactCategoryId: null,
address: "",
description: "",
+ designation: "",
projectIds: [],
contactEmails: [],
contactPhones: [],
@@ -95,6 +103,24 @@ const UpdateContact = ({ submitContact, existingContact, onCLosed }) => {
}
};
+ // handle logic when input of desgination is changed
+ const handleDesignationChange = (e) => {
+ const val = e.target.value;
+
+ const matches = designationList.filter((org) =>
+ org.toLowerCase().includes(val.toLowerCase())
+ );
+ setFilteredDesignationList(matches);
+ setShowSuggestions(true);
+ setTimeout(() => setShowSuggestions(false), 5000);
+ };
+
+ // handle logic when designation is selected
+ const handleSelectDesignation = (val) => {
+ setShowSuggestions(false);
+ setValue("designation", val);
+ };
+
const watchBucketIds = watch("bucketIds");
const toggleBucketId = (id) => {
@@ -113,33 +139,28 @@ const UpdateContact = ({ submitContact, existingContact, onCLosed }) => {
};
const onSubmit = async (data) => {
-const cleaned = {
- ...data,
- contactEmails: (data.contactEmails || [])
- .filter((e) => e.emailAddress?.trim() !== "")
- .map((email, index) => {
- const existingEmail = existingContact.contactEmails?.[index];
- return existingEmail
- ? { ...email, id: existingEmail.id }
- : email;
- }),
- contactPhones: (data.contactPhones || [])
- .filter((p) => p.phoneNumber?.trim() !== "")
- .map((phone, index) => {
- const existingPhone = existingContact.contactPhones?.[index];
- return existingPhone
- ? { ...phone, id: existingPhone.id }
- : phone;
- }),
-};
+ const cleaned = {
+ ...data,
+ contactEmails: (data.contactEmails || [])
+ .filter((e) => e.emailAddress?.trim() !== "")
+ .map((email, index) => {
+ const existingEmail = existingContact.contactEmails?.[index];
+ return existingEmail ? { ...email, id: existingEmail.id } : email;
+ }),
+ contactPhones: (data.contactPhones || [])
+ .filter((p) => p.phoneNumber?.trim() !== "")
+ .map((phone, index) => {
+ const existingPhone = existingContact.contactPhones?.[index];
+ return existingPhone ? { ...phone, id: existingPhone.id } : phone;
+ }),
+ };
-setSubmitting(true);
-await submitContact({ ...cleaned, id: existingContact.id });
+ setSubmitting(true);
+ await submitContact({ ...cleaned, id: existingContact.id });
setSubmitting(false);
-
};
- const orgValue = watch("organization")
+ const orgValue = watch("organization");
const handleClosed = () => {
onCLosed();
};
@@ -149,7 +170,7 @@ await submitContact({ ...cleaned, id: existingContact.id });
typeof existingContact === "object" &&
!Array.isArray(existingContact);
- if (!isInitialized &&isValidContact && TagsData) {
+ if (!isInitialized && isValidContact && TagsData) {
reset({
name: existingContact.name || "",
organization: existingContact.organization || "",
@@ -158,24 +179,30 @@ await submitContact({ ...cleaned, id: existingContact.id });
contactCategoryId: existingContact.contactCategory?.id || null,
address: existingContact.address || "",
description: existingContact.description || "",
+ designation: existingContact.designation || "",
projectIds: existingContact.projectIds || null,
tags: existingContact.tags || [],
bucketIds: existingContact.bucketIds || [],
- } );
-
- if (!existingContact.contactPhones || existingContact.contactPhones.length === 0) {
- appendPhone({ label: "Office", phoneNumber: "" });
+ });
+
+ if (
+ !existingContact.contactPhones ||
+ existingContact.contactPhones.length === 0
+ ) {
+ appendPhone({ label: "Office", phoneNumber: "" });
+ }
+
+ if (
+ !existingContact.contactEmails ||
+ existingContact.contactEmails.length === 0
+ ) {
+ appendEmail({ label: "Work", emailAddress: "" });
+ }
+ setIsInitialized(true);
}
- if (!existingContact.contactEmails || existingContact.contactEmails.length === 0) {
- appendEmail({ label: "Work", emailAddress: "" });
- }
- setIsInitialized(true)
- }
-
// return()=> reset()
- }, [ existingContact, buckets, projects ] );
-
+ }, [existingContact, buckets, projects]);
return (
@@ -195,15 +222,14 @@ await submitContact({ ...cleaned, id: existingContact.id });
)}
-
Organization
setValue("organization", val)}
- error={errors.organization?.message}
- />
+ organizationList={organizationList}
+ value={getValues("organization") || ""}
+ onChange={(val) => setValue("organization", val)}
+ error={errors.organization?.message}
+ />
{errors.organization && (
{errors.organization.message}
@@ -211,6 +237,55 @@ await submitContact({ ...cleaned, id: existingContact.id });
)}
+
+
+
Designation
+
+ {showSuggestions && filteredDesignationList.length > 0 && (
+
+ {filteredDesignationList.map((designation) => (
+ handleSelectDesignation(designation)}
+ onMouseEnter={(e) =>
+ (e.currentTarget.style.backgroundColor = "#f8f9fa")
+ }
+ onMouseLeave={(e) =>
+ (e.currentTarget.style.backgroundColor = "transparent")
+ }
+ >
+ {designation}
+
+ ))}
+
+ )}
+ {errors.designation && (
+
+ {errors.designation.message}
+
+ )}
+
+
{emailFields.map((field, index) => (
@@ -247,11 +322,13 @@ await submitContact({ ...cleaned, id: existingContact.id });
//
-
-
+
) : (
// removeEmail(index)}
// style={{ width: "24px", height: "24px" }}
// >
- removeEmail(index)}/>
-
+ removeEmail(index)}
+ />
)}
{errors.contactEmails?.[index]?.emailAddress && (
@@ -310,7 +389,10 @@ await submitContact({ ...cleaned, id: existingContact.id });
// onClick={handleAddPhone}
// style={{ width: "24px", height: "24px" }}
// >
-
+
) : (
//
removePhone(index)}
// style={{ width: "24px", height: "24px" }}
// >
- removePhone(index)} />
+ removePhone(index)}
+ />
)}
{errors.contactPhones?.[index]?.phoneNumber && (
@@ -348,7 +433,7 @@ await submitContact({ ...cleaned, id: existingContact.id });
) : (
<>
-
+
Select Category
{contactCategory?.map((cate) => (
@@ -387,7 +472,7 @@ await submitContact({ ...cleaned, id: existingContact.id });
)}
-
+
Select Label
@@ -445,7 +530,11 @@ await submitContact({ ...cleaned, id: existingContact.id });
-
+
{IsSubmitting ? "Please Wait..." : "Update"}
-
Role
+
Official Designation
{
const navigate = useNavigate();
const HasManageProjectPermission = useHasUserPermission(MANAGE_PROJECT);
- const isDirectoryPath = /^\/directory$/.test(location.pathname);
- const isProjectPath = /^\/projects$/.test(location.pathname);
- const isDashboard = /^\/dashboard$/.test(location.pathname) || /^\/$/.test(location.pathname) ;
+ const isDirectoryPath = /^\/directory$/.test(location.pathname);
+ const isProjectPath = /^\/projects$/.test(location.pathname);
+ const isDashboard =
+ /^\/dashboard$/.test(location.pathname) || /^\/$/.test(location.pathname);
+
+ const allowedProjectStatusIds = [
+ "603e994b-a27f-4e5d-a251-f3d69b0498ba",
+ "cdad86aa-8a56-4ff4-b633-9c629057dfef",
+ "b74da4c2-d07e-46f2-9919-e75e49b12731",
+ ];
+
const getRole = (roles, joRoleId) => {
if (!Array.isArray(roles)) return "User";
let role = roles.find((role) => role.id === joRoleId);
@@ -38,7 +46,7 @@ const Header = () => {
};
const handleLogout = (e) => {
- e.preventDefault();
+ e.preventDefault();
logout();
};
@@ -49,7 +57,7 @@ const Header = () => {
};
AuthRepository.logout(data)
- .then((response) => {
+ .then(() => {
localStorage.removeItem("jwtToken");
localStorage.removeItem("refreshToken");
localStorage.removeItem("user");
@@ -57,11 +65,11 @@ const Header = () => {
clearAllCache();
window.location.href = "/auth/login";
})
- .catch((error) => {
- // Even if logout API fails, clear local storage and redirect
+ .catch(() => {
localStorage.removeItem("jwtToken");
localStorage.removeItem("refreshToken");
localStorage.removeItem("user");
+ localStorage.clear();
clearAllCache();
window.location.href = "/auth/login";
});
@@ -79,22 +87,30 @@ const Header = () => {
const { projectNames, loading: projectLoading, fetchData } = useProjectName();
- const selectedProject = useSelector(
- (store) => store.localVariables.projectId
- );
+ const selectedProject = useSelectedproject();
- // Determine the display text for the project dropdown
- let displayText = "All Projects";
- if (selectedProject === null) {
- displayText = "All Projects";
- } else if (selectedProject) {
- const selectedProjectObj = projectNames?.find(
- (p) => p?.id === selectedProject
- );
- // Fallback to selectedProject ID if name not found during loading or mismatch
- displayText = selectedProjectObj ? selectedProjectObj.name : selectedProject;
- } else if (projectLoading) {
- displayText = "Loading...";
+ const projectsForDropdown = isDashboard
+ ? projectNames
+ : projectNames?.filter(project =>
+ allowedProjectStatusIds.includes(project.projectStatusId)
+ );
+
+ let currentProjectDisplayName;
+ if (projectLoading) {
+ currentProjectDisplayName = "Loading...";
+ } else if (!projectNames || projectNames.length === 0) {
+ currentProjectDisplayName = "No Projects Assigned";
+ } else if (projectNames.length === 1) {
+ currentProjectDisplayName = projectNames[0].name;
+ } else {
+ if (selectedProject === null) {
+ currentProjectDisplayName = "All Projects";
+ } else {
+ const selectedProjectObj = projectNames.find(
+ (p) => p?.id === selectedProject
+ );
+ currentProjectDisplayName = selectedProjectObj ? selectedProjectObj.name : "All Projects";
+ }
}
const { openChangePassword } = useChangePassword();
@@ -106,17 +122,18 @@ const Header = () => {
selectedProject === undefined &&
!getCachedData("hasReceived")
) {
- if(isDashboard){
- dispatch(setProjectId(null));
- }else{
- dispatch(setProjectId(projectNames[0]?.id));
+ if (projectNames.length === 1) {
+ dispatch(setProjectId(projectNames[0]?.id || null));
+ } else {
+ if (isDashboard) {
+ dispatch(setProjectId(null));
+ } else {
+ const firstAllowedProject = projectNames.find(project => allowedProjectStatusIds.includes(project.projectStatusId));
+ dispatch(setProjectId(firstAllowedProject?.id || null));
+ }
}
}
- }, [projectNames, selectedProject, dispatch]);
-
-
- /** Check if current page is project details page or directory page */
- // const isProjectPath = /^\/projects\/[a-f0-9-]{36}$/.test(location.pathname);
+ }, [projectNames, selectedProject, dispatch, isDashboard]);
const handler = useCallback(
@@ -160,14 +177,15 @@ const Header = () => {
};
}, [handler, newProjectHandler]);
- const handleProjectChange =(project)=>{
- if(isProjectPath){
- dispatch(setProjectId(project))
- navigate("/projects/details")
- } else{
- dispatch(setProjectId(project))
+ const handleProjectChange = (project) => {
+ dispatch(setProjectId(project));
+
+ if (isProjectPath && project !== null) {
+ navigate("/projects/details");
}
- }
+ };
+
+ const shouldShowDropdown = projectNames && projectNames.length > 1;
return (
{