Compare commits

...

38 Commits

Author SHA1 Message Date
0194c4427a Merge branch 'UI_Changes_PMS' of https://git.marcoaiot.com/admin/marco.pms.web into UI_Changes_PMS 2025-09-08 11:57:30 +05:30
ea022d37c8 Merge branch 'Document_Manag' of https://git.marcoaiot.com/admin/marco.pms.web into UI_Changes_PMS 2025-09-08 11:50:58 +05:30
f9fe987a94 changed useproject hook name 2025-09-05 11:58:36 +05:30
87221965de Merge branch 'main' of https://git.marcoaiot.com/admin/marco.pms.web into Document_Manag 2025-09-05 11:52:50 +05:30
6caad7850d clear and structured code 2025-09-05 11:45:04 +05:30
2b5fc9aaac added project level feature 2025-09-04 18:06:58 +05:30
1eaf4a080c fixed confirm modal close button 2025-09-04 14:18:57 +05:30
fe3d356c2e Ui changed for document version list 2025-09-04 14:16:15 +05:30
e66ce11cd5 changes tage reponse and changed confirm modal format 2025-09-03 16:40:20 +05:30
a8239d5c31 document version list display 10 version at per page 2025-09-03 15:49:12 +05:30
97a32b8f42 display suggestion for tags when create or update documen form 2025-09-03 15:45:50 +05:30
a52cf0bc39 allow to delete document category and type and edit type 2025-09-03 15:16:37 +05:30
e007c0e8da allow to add and update document category inside master 2025-09-03 12:56:39 +05:30
e2de5eba40 added document permissions 2025-09-03 11:52:49 +05:30
fd14328562 enable activating or deactivating existing documents 2025-09-03 11:18:12 +05:30
e8459d3671 convert fileSize to KB before sending request 2025-09-03 11:16:40 +05:30
528d3b756c InActiving documents 2025-09-02 20:28:23 +05:30
11be36b67a login user can be verify documents 2025-09-02 20:00:18 +05:30
ef00f83c44 document can inside open in browser 2025-09-02 19:34:42 +05:30
809f2ef726 dynamicallu show Document Id it required ? or not base document Type 2025-09-02 16:43:04 +05:30
a95e365087 removed static page size of Expense list 2025-09-02 16:42:06 +05:30
2ee9c8ecbd prevent to stay outside if have logged 2025-09-02 16:40:51 +05:30
7eb22bb785 added pagination 2025-09-02 16:40:04 +05:30
cd32f743ce changed segment button radio 2025-09-02 16:39:44 +05:30
acd642c935 display document details and document meta data and added skeleton 2025-09-02 16:39:06 +05:30
06503ac4d3 completd updation of documents 2025-09-01 22:06:13 +05:30
ee1887de8f fixed reduant api calling 2025-09-01 18:51:23 +05:30
2f24d4a7ff initially setup update document 2025-09-01 18:15:30 +05:30
518928e439 adedd fillter sidepanel and handle filter object on api level 2025-08-30 17:31:36 +05:30
cec16ded3e added skeleton for document list 2025-08-29 20:52:36 +05:30
b70d03af8a Search , Refresh featured added and initial setup for filter 2025-08-29 20:34:37 +05:30
daf7f11310 Upload new document api integrated and use can upload document at employee 2025-08-29 16:05:54 +05:30
b93eaf6b95 initial setuo new document 2025-08-28 20:22:17 +05:30
d42790628c successfully master fetched of documentType and documentCategor 2025-08-28 15:19:15 +05:30
1c9df57c74 Merge pull request 'MasterModalRefactor : Changed Master Modal' (#357) from MasterModalRefactor into Document_Manag
Reviewed-on: #357
Merged
2025-08-28 06:48:43 +00:00
d4804e4c3f updated Master modal 2025-08-28 06:48:43 +00:00
14fba75d19 setup routes 2025-08-28 11:31:01 +05:30
65b90bc9ac initial setup document page 2025-08-28 11:17:54 +05:30
58 changed files with 3750 additions and 760 deletions

View File

@ -198,23 +198,14 @@ const ManageBucket = () => {
return (
<>
{deleteBucket && (
<div
className={`modal fade ${deleteBucket ? "show" : ""}`}
tabIndex="-1"
role="dialog"
style={{
display: deleteBucket ? "block" : "none",
backgroundColor: deleteBucket ? "rgba(0,0,0,0.5)" : "transparent",
}}
>
<ConfirmModal
type={"delete"}
header={"Delete Bucket"}
message={"Are you sure you want to delete this bucket?"}
onSubmit={handleDeleteContact}
onClose={() => setDeleteBucket(null)}
/>
</div>
<ConfirmModal
isOpen={!!deleteBucket}
type="delete"
header="Delete Bucket"
message="Are you sure you want to delete this bucket?"
onSubmit={handleDeleteContact}
onClose={() => setDeleteBucket(null)}
/>
)}
<div className="container m-0 p-0" style={{ minHeight: "00px" }}>
@ -237,8 +228,9 @@ const ManageBucket = () => {
onChange={(e) => setSearchTerm(e.target.value)}
/>
<i
className={`bx bx-refresh cursor-pointer fs-4 ${loading ? "spin" : ""
}`}
className={`bx bx-refresh cursor-pointer fs-4 ${
loading ? "spin" : ""
}`}
title="Refresh"
onClick={() => refetch()}
/>
@ -247,8 +239,9 @@ const ManageBucket = () => {
<button
type="button"
className={`btn btn-sm btn-primary ms-auto ${action_bucket ? "d-none" : ""
}`}
className={`btn btn-sm btn-primary ms-auto ${
action_bucket ? "d-none" : ""
}`}
onClick={() => {
setAction_bucket(true);
select_bucket(null);
@ -285,16 +278,18 @@ const ManageBucket = () => {
</div>
)}
{!loading && buckets.length > 0 && sortedBucktesList.length === 0 && (
<div className="col-12">
<div
className="d-flex justify-content-center align-items-center py-5 w-100"
style={{ marginLeft: "250px" }}
>
No matching buckets found.
{!loading &&
buckets.length > 0 &&
sortedBucktesList.length === 0 && (
<div className="col-12">
<div
className="d-flex justify-content-center align-items-center py-5 w-100"
style={{ marginLeft: "250px" }}
>
No matching buckets found.
</div>
</div>
</div>
)}
)}
{!loading &&
sortedBucktesList.map((bucket) => (
<div className="col" key={bucket.id}>
@ -305,29 +300,29 @@ const ManageBucket = () => {
{(DirManager ||
DirAdmin ||
bucket?.createdBy?.id ===
profile?.employeeInfo?.id) && (
<div className="d-flex gap-2">
<i
className="bx bx-edit bx-sm text-primary cursor-pointer"
onClick={() => {
select_bucket(bucket);
setAction_bucket(true);
const initialSelectedEmployees = employeesList
.filter((emp) =>
bucket.employeeIds?.includes(
emp.employeeId
)
profile?.employeeInfo?.id) && (
<div className="d-flex gap-2">
<i
className="bx bx-edit bx-sm text-primary cursor-pointer"
onClick={() => {
select_bucket(bucket);
setAction_bucket(true);
const initialSelectedEmployees = employeesList
.filter((emp) =>
bucket.employeeIds?.includes(
emp.employeeId
)
.map((emp) => ({ ...emp, isActive: true }));
setSelectEmployee(initialSelectedEmployees);
}}
></i>
<i
className="bx bx-trash bx-sm text-danger cursor-pointer ms-0"
onClick={() => setDeleteBucket(bucket?.id)}
></i>
</div>
)}
)
.map((emp) => ({ ...emp, isActive: true }));
setSelectEmployee(initialSelectedEmployees);
}}
></i>
<i
className="bx bx-trash bx-sm text-danger cursor-pointer ms-0"
onClick={() => setDeleteBucket(bucket?.id)}
></i>
</div>
)}
</h6>
<h6 className="card-subtitle mb-2 text-muted text-start">
Contacts:{" "}

View File

@ -33,7 +33,10 @@ const NoteCardDirectoryEditable = ({
note: editorValue,
contactId,
};
const response = await DirectoryRepository.UpdateNote(noteItem.id, payload);
const response = await DirectoryRepository.UpdateNote(
noteItem.id,
payload
);
const cachedContactProfile = getCachedData("Contact Profile");
if (cachedContactProfile?.contactId === contactId) {
@ -75,9 +78,9 @@ const NoteCardDirectoryEditable = ({
const contactProfile = (contactId) => {
DirectoryRepository.GetContactProfile(contactId).then((res) => {
setOpen_contact(res?.data);
setIsOpenModalNote(true);
});
setOpen_contact(res?.data);
setIsOpenModalNote(true);
});
};
const handleRestore = async () => {
@ -95,7 +98,6 @@ const NoteCardDirectoryEditable = ({
return (
<>
{isOpenModalNote && (
<GlobalModel
isOpen={isOpenModalNote}
@ -125,7 +127,6 @@ const NoteCardDirectoryEditable = ({
{/* Header */}
<div className="d-flex justify-content-between align-items-center mb-1">
<div className="d-flex align-items-center">
<Avatar
size="xxs"
firstName={noteItem?.createdBy?.firstName}
@ -133,30 +134,36 @@ const NoteCardDirectoryEditable = ({
className="m-0"
/>
<div>
<div className="d-flex ms-0 align-middle cursor-pointer" onClick={() =>contactProfile(noteItem.contactId)}>
<div
className="d-flex ms-0 align-middle cursor-pointer"
onClick={() => contactProfile(noteItem.contactId)}
>
<span>
<span className="fw-bold "> {noteItem?.contactName} </span> <span className="text-muted font-weight-normal">
<span className="fw-bold "> {noteItem?.contactName} </span>{" "}
<span className="text-muted font-weight-normal">
({noteItem?.organizationName})
</span>
</span>
</div>
<div className="d-flex ms-0 align-middle">
</div>
<div className="d-flex ms-0 align-middle"></div>
<div className="d-flex ms-0 mt-2">
<span className="text-muted">
by <span className="fw-bold "> {noteItem?.createdBy?.firstName} {noteItem?.createdBy?.lastName} </span>
&nbsp; <span className="text-muted">
on {moment
by{" "}
<span className="fw-bold ">
{" "}
{noteItem?.createdBy?.firstName}{" "}
{noteItem?.createdBy?.lastName}{" "}
</span>
&nbsp;{" "}
<span className="text-muted">
on{" "}
{moment
.utc(noteItem?.createdAt)
.add(5, "hours")
.add(30, "minutes")
.format("DD MMMM, YYYY [at] hh:mm A")}
</span>
</span>
</div>
</div>
</div>
@ -228,26 +235,16 @@ const NoteCardDirectoryEditable = ({
{/* Delete Confirm Modal */}
{isDeleteModalOpen && (
<div
className={`modal fade ${isDeleteModalOpen ? "show" : ""}`}
tabIndex="-1"
role="dialog"
style={{
display: isDeleteModalOpen ? "block" : "none",
backgroundColor: "rgba(0,0,0,0.5)",
}}
aria-hidden="false"
>
<ConfirmModal
type={"delete"}
header={"Delete Note"}
message={"Are you sure you want to delete this note?"}
onSubmit={suspendEmployee}
onClose={() => setIsDeleteModalOpen(false)}
loading={isDeleting}
paramData={noteItem}
/>
</div>
<ConfirmModal
isOpen={isDeleteModalOpen}
type="delete"
header="Delete Note"
message="Are you sure you want to delete this note?"
onSubmit={suspendEmployee}
onClose={() => setIsDeleteModalOpen(false)}
loading={isDeleting}
paramData={noteItem}
/>
)}
</>
);

View File

@ -0,0 +1,88 @@
import React from "react";
import VersionListSkeleton from "./VersionListSkeleton";
const SkeletonLine = ({ height = 16, width = "100%", className = "" }) => (
<div
className={`skeleton mb-2 ${className}`}
style={{
height,
width,
borderRadius: 4,
}}
></div>
);
const DocumentDetailsSkeleton = () => {
return (
<div className="p-1">
<p className="fw-bold fs-6">Document Details</p>
{/* Row 1 */}
<div className="row mb-2">
<div className="col-12 col-md-6">
<div className="d-flex gap-2">
<SkeletonLine width="130px" />
<SkeletonLine width="60%" />
</div>
</div>
<div className="col-12 col-md-6">
<div className="d-flex gap-2">
<SkeletonLine width="130px" />
<SkeletonLine width="50%" />
</div>
</div>
</div>
{/* Row 2 */}
<div className="row mb-2">
<div className="col-12 col-md-6">
<div className="d-flex gap-2">
<SkeletonLine width="130px" />
<SkeletonLine width="40%" />
</div>
</div>
<div className="col-12 col-md-6">
<div className="d-flex gap-2">
<SkeletonLine width="130px" />
<SkeletonLine width="60%" />
</div>
</div>
</div>
{/* Row 3 */}
<div className="row mb-2">
<div className="col-12 col-md-6">
<div className="d-flex gap-2">
<SkeletonLine width="130px" />
<SkeletonLine width="40%" />
</div>
</div>
<div className="col-12 col-md-6">
<div className="d-flex gap-2">
<SkeletonLine width="130px" />
<SkeletonLine width="50%" />
</div>
</div>
</div>
{/* Row 6 - Description */}
<div className="row mb-2">
<div className="col-12">
<div className="d-flex">
<SkeletonLine width="100%" height={40} />
</div>
</div>
</div>
{/* Version list skeleton */}
<div className="row text-start py-2">
<VersionListSkeleton items={2} />
</div>
</div>
);
};
export default DocumentDetailsSkeleton;

View File

@ -0,0 +1,205 @@
import React, { useState } from "react";
import { useDocumentFilterEntities } from "../../hooks/useDocument";
import { FormProvider, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
DocumentFilterDefaultValues,
DocumentFilterSchema,
} from "./DocumentSchema";
import { DateRangePicker1 } from "../common/DateRangePicker";
import SelectMultiple from "../common/SelectMultiple";
import moment from "moment";
const DocumentFilterPanel = ({ entityTypeId, onApply }) => {
const [resetKey, setResetKey] = useState(0);
const { data, isError, isLoading, error } =
useDocumentFilterEntities(entityTypeId);
const methods = useForm({
resolver: zodResolver(DocumentFilterSchema),
defaultValues: DocumentFilterDefaultValues,
});
const { handleSubmit, reset, setValue, watch } = methods;
// Watch values from form
const isUploadedAt = watch("isUploadedAt");
const isVerified = watch("isVerified");
// Close the offcanvas (bootstrap specific)
const closePanel = () => {
document.querySelector(".offcanvas.show .btn-close")?.click();
};
const onSubmit = (values) => {
onApply({
...values,
startDate: values.startDate
? moment.utc(values.startDate, "DD-MM-YYYY").toISOString()
: null,
endDate: values.endDate
? moment.utc(values.endDate, "DD-MM-YYYY").toISOString()
: null,
});
closePanel();
};
const onClear = () => {
reset(DocumentFilterDefaultValues);
setResetKey((prev) => prev + 1);
onApply(DocumentFilterDefaultValues);
closePanel();
};
if (isLoading) return <div>Loading...</div>;
if (isError)
return <div>Error: {error?.message || "Something went wrong!"}</div>;
const {
uploadedBy = [],
documentCategory = [],
documentType = [],
documentTag = [],
} = data?.data || {};
return (
<FormProvider {...methods}>
<form onSubmit={handleSubmit(onSubmit)}>
{/* Date Range Section */}
<div className="mb-2">
<div className="text-start d-flex align-items-center my-1">
<label className="form-label me-2 my-0">Choose Date:</label>
<div className="d-inline-flex border rounded-pill overflow-hidden shadow-none">
<button
type="button"
className={`btn px-2 py-1 rounded-0 text-tiny ${
isUploadedAt ? "active btn-secondary text-white" : ""
}`}
onClick={() => setValue("isUploadedAt", true)}
>
Uploaded On
</button>
<button
type="button"
className={`btn px-2 py-1 rounded-0 text-tiny ${
!isUploadedAt ? "active btn-secondary text-white" : ""
}`}
onClick={() => setValue("isUploadedAt", false)}
>
Updated On
</button>
</div>
</div>
<DateRangePicker1
placeholder="DD-MM-YYYY To DD-MM-YYYY"
startField="startDate"
endField="endDate"
defaultRange={false}
resetSignal={resetKey}
/>
</div>
{/* Dropdown Filters */}
<div className="row g-2 text-start">
<SelectMultiple
name="uploadedByIds"
label="Uploaded By:"
options={uploadedBy}
labelKey="name"
valueKey="id"
/>
<SelectMultiple
name="documentCategoryIds"
label="Document Category:"
options={documentCategory}
labelKey="name"
valueKey="id"
/>
<SelectMultiple
name="documentTypeIds"
label="Document Type:"
options={documentType}
labelKey="name"
valueKey="id"
/>
<SelectMultiple
name="documentTagIds"
label="Tags:"
options={documentTag}
labelKey="name"
valueKey="id"
/>
</div>
{/* Status Filter */}
<div className="text-start my-2">
<label className="form-label d-block mb-2">Choose Status:</label>
<div className="d-flex gap-4">
<label className="switch switch-sm">
<input
type="radio"
className="switch-input"
name="isVerified"
checked={isVerified === null}
onChange={() => setValue("isVerified", null)}
/>
<span className="switch-toggle-slider">
<span className="switch-on"></span>
<span className="switch-off"></span>
</span>
<span className="switch-label">All</span>
</label>
<label className="switch switch-sm">
<input
type="radio"
className="switch-input"
name="isVerified"
checked={isVerified === true}
onChange={() => setValue("isVerified", true)}
/>
<span className="switch-toggle-slider">
<span className="switch-on"></span>
<span className="switch-off"></span>
</span>
<span className="switch-label">Verified</span>
</label>
<label className="switch switch-sm">
<input
type="radio"
className="switch-input"
name="isVerified"
checked={isVerified === false}
onChange={() => setValue("isVerified", false)}
/>
<span className="switch-toggle-slider">
<span className="switch-on"></span>
<span className="switch-off"></span>
</span>
<span className="switch-label">Rejected</span>
</label>
</div>
</div>
{/* Footer Buttons */}
<div className="d-flex justify-content-end py-3 gap-2">
<button
type="button"
className="btn btn-secondary btn-xs"
onClick={onClear}
>
Clear
</button>
<button type="submit" className="btn btn-primary btn-xs">
Apply
</button>
</div>
</form>
</FormProvider>
);
};
export default DocumentFilterPanel;

View File

@ -0,0 +1,132 @@
import { z } from "zod";
import { normalizeAllowedContentTypes } from "../../utils/appUtils";
export const AttachmentSchema = (allowedContentType, maxSizeAllowedInMB) => {
const allowedTypes = normalizeAllowedContentTypes(allowedContentType);
return z.object({
fileName: z.string().min(1, { message: "File name is required" }),
base64Data: z.string().min(1, { message: "File data is required" }),
contentType: z
.string()
.min(1, { message: "MIME type is required" })
.refine(
(val) => (allowedTypes.length ? allowedTypes.includes(val) : true),
{
message: `File type must be one of: ${allowedTypes.join(", ")}`,
}
),
fileSize: z
.number()
.int()
.nonnegative("fileSize must be ≥ 0")
.max(
(maxSizeAllowedInMB ?? 25) * 1024 * 1024,
`fileSize must be ≤ ${maxSizeAllowedInMB ?? 25}MB`
),
description: z.string().optional().default(""),
isActive: z.boolean(),
});
};
export const TagSchema = z.object({
name: z.string().min(1, "Tag name is required"),
isActive: z.boolean().default(true),
});
export const DocumentPayloadSchema = (docConfig = {}) => {
const {
isMandatory,
regexExpression,
allowedContentType,
maxSizeAllowedInMB,
isUpdateForm,
} = docConfig;
let documentIdSchema = z.string();
if (isMandatory) {
documentIdSchema = documentIdSchema.min(1, {
message: "DocumentId is required",
});
}
if (regexExpression) {
documentIdSchema = documentIdSchema.regex(
new RegExp(regexExpression),
"Invalid DocumentId format"
);
}
// Base attachment schema
let attachmentSchema = AttachmentSchema(
allowedContentType,
maxSizeAllowedInMB
).nullable();
// If not update form, require attachment
if (!isUpdateForm) {
attachmentSchema = attachmentSchema.refine((val) => val !== null, {
message: "Attachment is required",
});
}
return z.object({
name: z.string().min(1, "Name is required"),
documentId: documentIdSchema,
description: z.string().min(1, { message: "Description is required" }),
documentTypeId: z
.string()
.min(1, { message: "Please Select Document Type" }),
documentCategoryId: z
.string()
.min(1, { message: "Please Select Document Category" }),
attachment: attachmentSchema,
tags: z.array(TagSchema).optional().default([]),
});
};
export const defaultDocumentValues = {
name: "",
documentId: "",
description: "",
// entityId: "",
documentTypeId: "",
documentCategoryId: "",
// attachment: {
// fileName: "",
// base64Data: "",
// contentType: "",
// fileSize: 0,
// description: "",
// isActive: true,
// },
attachment:null,
tags: [],
};
//--------------------Filter-------------------------
export const DocumentFilterSchema = z.object({
uploadedByIds: z.array(z.string()).default([]),
documentCategoryIds: z.array(z.string()).default([]),
documentTypeIds: z.array(z.string()).default([]),
documentTagIds: z.array(z.string()).default([]),
isUploadedAt: z.boolean().default(true),
isVerified: z.boolean().nullable().optional(),
startDate: z.string().nullable().optional(),
endDate: z.string().nullable().optional(),
});
export const DocumentFilterDefaultValues = {
uploadedByIds: [],
documentCategoryIds: [],
documentTypeIds: [],
documentTagIds: [],
isUploadedAt: true,
isVerified: null,
startDate: null,
endDate: null,
};

View File

@ -0,0 +1,70 @@
import React from "react";
const SkeletonCell = ({
width = "100%",
height = 20,
className = "",
style = {},
}) => (
<div
className={`skeleton ${className}`}
style={{
width,
height,
borderRadius: 4,
...style,
}}
/>
);
export const DocumentTableSkeleton = ({ rows = 5 }) => {
return (
<table className="card-body table border-top dataTable no-footer dtr-column text-nowrap">
<thead>
<tr>
<th className="text-start">Name</th>
<th className="text-start">Document Type</th>
<th className="text-start">Uploaded By</th>
<th className="text-center">Uploaded on</th>
<th className="text-center">Status</th>
</tr>
</thead>
<tbody>
{[...Array(rows)].map((_, idx) => (
<tr key={idx} className={idx % 2 === 0 ? "odd" : "even"}>
{/* Name */}
<td className="text-start">
<SkeletonCell width="120px" height={16} />
</td>
{/* Document Type */}
<td className="text-start">
<SkeletonCell width="100px" height={16} />
</td>
{/* Uploaded By (Avatar + Name) */}
<td className="text-start">
<div className="d-flex align-items-center gap-2">
<SkeletonCell width="30px" height={30} className="rounded-circle" />
<SkeletonCell width="80px" height={16} />
</div>
</td>
{/* Uploaded on */}
<td className="text-center">
<SkeletonCell width="80px" height={16} />
</td>
{/* Status */}
<td className="text-center">
<SkeletonCell width="70px" height={20} className="rounded" />
</td>
</tr>
))}
</tbody>
</table>
);
};

View File

@ -0,0 +1,170 @@
import React from "react";
import VersionListSkeleton from "./VersionListSkeleton";
import { getDocuementsStatus } from "./Documents";
import Avatar from "../common/Avatar";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { DOWNLOAD_DOCUMENT, VERIFY_DOCUMENT } from "../../utils/constants";
import { FileIcon } from "../../utils/FileIcon";
const DocumentVersionList = ({
versionLoding,
versionList,
isPending,
setOpenDocument,
VerifyDocument,
}) => {
const canVerifyDocument = useHasUserPermission(VERIFY_DOCUMENT);
const canDownloadDocument = useHasUserPermission(DOWNLOAD_DOCUMENT);
const handleOpenDocument = () => {
if (canDownloadDocument) {
setOpenDocument(true);
}
};
const contentTypeIcons = {
"application/pdf": "fa-solid fa-file-pdf text-primary",
"application/msword": "fa-solid fa-file-word text-primary",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document":
"fa-solid fa-file-word text-primary",
"application/vnd.ms-excel": "fa-solid fa-file-excel text-success",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
"fa-solid fa-file-excel text-primary",
"application/vnd.ms-powerpoint": "fa-solid fa-file-powerpoint text-primary",
"application/vnd.openxmlformats-officedocument.presentationml.presentation":
"fa-solid fa-file-powerpoint text-primary",
"image/jpg": "fa-solid fa-file-image text-primary",
"image/jpeg": "fa-solid fa-file-image text-primary",
"image/png": "fa-solid fa-file-image text-primary",
"image/gif": "fa-solid fa-file-image text-primary",
"text/plain": "fa-solid fa-file-lines text-primary",
"text/csv": "fa-solid fa-file-csv text-primary",
"application/json": "fa-solid fa-file-code text-primary",
default: "fa-solid fa-file text-primary",
};
const getIcon = (fileName = "") => {
const ext = fileName.split(".").pop().toLowerCase();
return contentTypeIcons[ext] || contentTypeIcons.default;
};
const sortedVersions = versionList?.data
? [...versionList.data].sort((a, b) => b.version - a.version)
: [];
if (versionLoding) {
return <VersionListSkeleton items={2} />;
}
if (!sortedVersions.length) {
return <p className="text-muted">No documents available.</p>;
}
const latestDoc = sortedVersions[0];
return (
<div className="accordion" id="docAccordion">
<div className="accordion-item shadow-none">
<h2 className="accordion-header" id="headingDoc">
<button
className="accordion-button"
type="button"
data-bs-toggle="collapse"
data-bs-target="#collapseDoc"
aria-expanded="true"
aria-controls="collapseDoc"
>
<i className="bx bxs-folder me-2 text-warning fs-5"></i>
{latestDoc.name} (Latest v{latestDoc.version})
</button>
</h2>
<div
id="collapseDoc"
className="accordion-collapse collapse show"
aria-labelledby="headingDoc"
data-bs-parent="#docAccordion"
>
<div className="accordion-body p-2">
<div className="list-group list-group-flush">
{sortedVersions.map((document, index) => (
<div
key={document.id}
className={`list-group-item list-group-item-action d-flex align-items-center cursor-pointer ${
index > 0 ? "ms-4" : "" // indent only older versions
}`}
>
<FileIcon
type={document.contentType}
size="fs-2"
className="me-2"
/>
<div className="w-100">
<div className="d-flex justify-content-between align-items-center">
<small className=" fw-normal">{document.name}</small>
<small className=" fw-normal">
Version-{document.version}
</small>{" "}
<small className=" text-secondary fw-normal">
fileSize: {document.fileSize} Kb
</small>
</div>
<div className="d-flex justify-content-between m-0">
<div
className="user-info text-start m-0"
onClick={handleOpenDocument}
>
<div className="d-flex align-items-center">
{formatUTCToLocalTime(document?.uploadedAt)} |
Uploaded by{" "}
<div className="d-flex align-items-center ms-1">
<Avatar
size="xs"
classAvatar="m-0"
firstName={document.uploadedBy?.firstName}
lastName={document.uploadedBy?.lastName}
/>
<span className="text-truncate ms-1">
{`${document.uploadedBy?.firstName ?? ""} ${
document.uploadedBy?.lastName ?? ""
}`.trim() || "N/A"}
</span>
</div>
</div>
{document?.updatedAt && (
<div className="d-flex align-items-center">
{formatUTCToLocalTime(document?.updatedAt)} |
Updated by{" "}
<div className="d-flex align-items-center ms-1">
<Avatar
size="xs"
classAvatar="m-0"
firstName={document.updatedBy?.firstName}
lastName={document.updatedBy?.lastName}
/>
<span className="text-truncate ms-1">
{`${document.updatedBy?.firstName ?? ""} ${
document.updatedBy?.lastName ?? ""
}`.trim() || "N/A"}
</span>
</div>
</div>
)}
</div>
<div className="d-flex align-items-end">
{getDocuementsStatus(document.isVerified)}
</div>
</div>
</div>
</div>
))}
</div>
</div>
</div>
</div>
</div>
);
};
export default DocumentVersionList;

View File

@ -0,0 +1,27 @@
import React, { useEffect } from "react";
import { useDocumentVersion } from "../../hooks/useDocument";
import { useDocumentContext } from "./Documents";
import { error } from "pdf-lib";
const DocumentViewerModal = () => {
const { viewDoc,setOpenDocument } = useDocumentContext();
const { data, isLoading, isError,error } = useDocumentVersion(viewDoc.document);
useEffect(() => {
if (data?.data) {
const fileUrl = data.data;
window.open(fileUrl, "_blank");
setOpenDocument(false)
}
}, [data]);
if (isLoading) return <p>Loading document...</p>;
if (isError) return <div>
<p className="danger-text">{error.message}</p>
</div>;
// Nothing to render inside modal since we redirect
return null;
};
export default DocumentViewerModal;

View File

@ -0,0 +1,239 @@
import React, { createContext, useContext, useEffect, useState } from "react";
import GlobalModel from "../common/GlobalModel";
import NewDocument from "./ManageDocument";
import { DOCUMENTS_ENTITIES, UPLOAD_DOCUMENT } from "../../utils/constants";
import { useParams } from "react-router-dom";
import DocumentsList from "./DocumentsList";
import DocumentFilterPanel from "./DocumentFilterPanel";
import { useFab } from "../../Context/FabContext";
import { useForm } from "react-hook-form";
import {
DocumentFilterDefaultValues,
DocumentFilterSchema,
} from "./DocumentSchema";
import { zodResolver } from "@hookform/resolvers/zod";
import ManageDocument from "./ManageDocument";
import ViewDocument from "./ViewDocument";
import DocumentViewerModal from "./DocumentViewerModal";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
// Context
export const DocumentContext = createContext();
export const useDocumentContext = () => {
const context = useContext(DocumentContext);
if (!context) {
throw new Error(
"useDocumentContext must be used within an DocumentProvider"
);
}
return context;
};
export const getDocuementsStatus = (status) => {
switch (status) {
case true:
return (
<span className="badge rounded-pill bg-label-success">Verified</span>
);
case false:
return (
<span className="badge rounded-pill bg-label-danger">Rejected</span>
);
case null:
default:
return (
<span className="badge rounded-pill bg-label-warning"> Pending</span>
);
}
};
const Documents = ({ Document_Entity, Entity }) => {
const [searchText, setSearchText] = useState("");
const [isActive, setIsActive] = useState(true);
const [filters, setFilter] = useState();
const [isRefetching, setIsRefetching] = useState(false);
const [refetchFn, setRefetchFn] = useState(null);
const [DocumentEntity, setDocumentEntity] = useState(Document_Entity);
const { employeeId } = useParams();
const [OpenDocument, setOpenDocument] = useState(false);
const [ManageDoc, setManageDoc] = useState({
document: null,
isOpen: false,
});
const [viewDoc, setViewDoc] = useState({
document: null,
isOpen: false,
});
const canUploadDocument = useHasUserPermission(UPLOAD_DOCUMENT)
const { setOffcanvasContent, setShowTrigger } = useFab();
const methods = useForm({
resolver: zodResolver(DocumentFilterSchema),
defaultValues: DocumentFilterDefaultValues,
});
const { reset } = methods;
const clearFilter = () => {
setFilter(DocumentFilterDefaultValues);
reset();
};
useEffect(() => {
setShowTrigger(true);
setOffcanvasContent(
"Document Filters",
<DocumentFilterPanel entityTypeId={DocumentEntity} onApply={setFilter} />
);
return () => {
setShowTrigger(false);
setOffcanvasContent("", null);
};
}, []);
const contextValues = {
ManageDoc,
setManageDoc,
viewDoc,
setViewDoc,
setOpenDocument,
OpenDocument,
};
useEffect(() => {
if (Document_Entity) {
setDocumentEntity(Document_Entity);
}
}, [Document_Entity]);
return (
<DocumentContext.Provider value={contextValues}>
<div className="mt-5">
<div className="card d-flex p-2">
<div className="row align-items-center">
{/* Search */}
<div className="d-flex col-8 col-md-8 col-lg-4 mb-md-0 align-items-center">
<div className="d-flex"> <input
type="search"
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
className="form-control form-control-sm"
placeholder="Search Document"
/></div>
<label className="switch switch-sm mx-2">
<input
type="checkbox"
className="switch-input"
checked={isActive}
onChange={(e) => setIsActive(e.target.checked)}
/>
<span className="switch-toggle-slider">
<span className="switch-on"></span>
<span className="switch-off"></span>
</span>
<span className="switch-label">
{isActive ? "Active" : "In-Active"}
</span>
</label>
</div>
{/* Actions */}
<div className="col-6 col-md-6 col-lg-8 text-end">
{/* <span
className="text-tiny text-muted p-1 border-0 bg-none lead mx-3 cursor-pointer"
disabled={isRefetching}
onClick={() => {
setSearchText("");
setFilter(DocumentFilterDefaultValues);
refetchFn && refetchFn();
}}
>
Refresh
<i
className={`bx bx-refresh ms-1 ${
isRefetching ? "bx-spin" : ""
}`}
></i>
</span> */}
{canUploadDocument && (<button
type="button"
title="Add New Document"
className="p-1 bg-primary rounded-circle cursor-pointer"
onClick={() =>
setManageDoc({
document: null,
isOpen: true,
})
}
>
<i className="bx bx-plus fs-4 text-white"></i>
</button>)}
</div>
</div>
<DocumentsList
Document_Entity={DocumentEntity}
Entity={Entity}
filters={filters}
searchText={searchText}
setIsRefetching={setIsRefetching}
setRefetchFn={setRefetchFn}
isActive={isActive}
/>
</div>
{ManageDoc.isOpen && (
<GlobalModel
isOpen={ManageDoc.isOpen}
closeModal={() =>
setManageDoc({
document: null,
isOpen: false,
})
}
>
<ManageDocument
closeModal={() =>
setManageDoc({
document: null,
isOpen: false,
})
}
Document_Entity={DocumentEntity}
Entity={Entity}
/>
</GlobalModel>
)}
{viewDoc.isOpen && (
<GlobalModel
size="lg"
isOpen={viewDoc.isOpen}
closeModal={() =>
setViewDoc({
document: null,
isOpen: false,
})
}
>
<ViewDocument />
</GlobalModel>
)}
{OpenDocument && (
<GlobalModel
isOpen={OpenDocument}
closeModal={() => setOpenDocument(false)}
>
<DocumentViewerModal />
</GlobalModel>
)}
</div>
</DocumentContext.Provider>
);
};
export default Documents;

View File

@ -0,0 +1,251 @@
import React, { useEffect, useState } from "react";
import {
useActiveInActiveDocument,
useDocumentListByEntityId,
} from "../../hooks/useDocument";
import {
DELETE_DOCUMENT,
ITEMS_PER_PAGE,
MODIFY_DOCUMENT,
} from "../../utils/constants";
import Avatar from "../common/Avatar";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import { useDebounce } from "../../utils/appUtils";
import { DocumentTableSkeleton } from "./DocumentSkeleton";
import { getDocuementsStatus, useDocumentContext } from "./Documents";
import Pagination from "../common/Pagination";
import ConfirmModal from "../common/ConfirmModal";
import { isPending } from "@reduxjs/toolkit";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
const DocumentsList = ({
Document_Entity,
Entity,
filters,
searchText,
setIsRefetching,
setRefetchFn,
isActive,
}) => {
const [IsDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
const [deletingId, setDeletingId] = useState(null);
const [restoringIds, setRestoringIds] = useState([]);
const debouncedSearch = useDebounce(searchText, 500);
const [currentPage, setCurrentPage] = useState(1);
const canDeleteDocument = useHasUserPermission(DELETE_DOCUMENT);
const canModifyDocument = useHasUserPermission(MODIFY_DOCUMENT);
const { data, isError, isLoading, error, refetch, isFetching } =
useDocumentListByEntityId(
Document_Entity,
Entity,
ITEMS_PER_PAGE,
currentPage,
filters,
debouncedSearch,
isActive
);
useEffect(() => {
setRefetchFn(() => refetch);
}, [setRefetchFn, refetch]);
useEffect(() => {
setIsRefetching(isFetching);
}, [isFetching, setIsRefetching]);
const { setManageDoc, setViewDoc } = useDocumentContext();
const { mutate: ActiveInActive, isPending } = useActiveInActiveDocument();
const paginate = (page) => {
if (page >= 1 && page <= (data?.totalPages ?? 1)) {
setCurrentPage(page);
}
};
const noData = !isLoading && !isError && data?.data.length === 0;
const isSearchEmpty = noData && !!debouncedSearch;
const isFilterEmpty = noData && !!filters && Object.keys(filters).length > 0;
const isInitialEmpty = noData && !debouncedSearch && !isFilterEmpty;
if (isLoading || isFetching) return <DocumentTableSkeleton />;
if (isError)
return <div>Error: {error?.message || "Something went wrong"}</div>;
if (isInitialEmpty) return <div>No documents found yet.</div>;
if (isSearchEmpty) return <div>No results found for "{debouncedSearch}"</div>;
if (isFilterEmpty) return <div>No documents match your filter.</div>;
const handleDelete = () => {
ActiveInActive(
{ documentId: deletingId, isActive: !isActive },
{
onSettled: () => {
setDeletingId(null);
setIsDeleteModalOpen(false);
},
}
);
};
const handleRestore = (docId) => {
setRestoringIds((prev) => [...prev, docId]);
ActiveInActive(
{ documentId: docId, isActive: true },
{
onSettled: () => {
setRestoringIds((prev) => prev.filter((id) => id !== docId));
refetch();
},
}
);
};
const DocumentColumns = [
{
key: "name",
label: "Name",
getValue: (e) => e.name || "N/A",
align: "text-start",
},
{
key: "documentType",
label: "Document Type",
getValue: (e) => e.documentType?.name || "N/A",
align: "text-start",
},
{
key: "uploadedBy",
label: "Uploaded By",
align: "text-start",
customRender: (e) => (
<div className="d-flex align-items-center">
<Avatar
size="xs"
classAvatar="m-0"
firstName={e.uploadedBy?.firstName}
lastName={e.uploadedBy?.lastName}
/>
<span className="text-truncate ms-1">
{`${e.uploadedBy?.firstName ?? ""} ${
e.uploadedBy?.lastName ?? ""
}`.trim() || "N/A"}
</span>
</div>
),
getValue: (e) =>
`${e.uploadedBy?.firstName ?? ""} ${
e.uploadedBy?.lastName ?? ""
}`.trim() || "N/A",
},
{
key: "uploadedAt",
label: "Uploaded on",
getValue: (e) => formatUTCToLocalTime(e.uploadedAt),
align: "text-center",
isAlwaysVisible: true,
},
{
key: "Status",
label: "Status",
getValue: (e) => getDocuementsStatus(e.isVerified),
align: "text-center",
isAlwaysVisible: true,
},
];
return (
<>
{IsDeleteModalOpen && (
<ConfirmModal
isOpen={IsDeleteModalOpen}
type="delete"
header="Delete Document"
message="Are you sure you want to delete this document?"
onSubmit={handleDelete}
onClose={() => setIsDeleteModalOpen(false)}
loading={!!isPending}
paramData={deletingId}
/>
)}
<div className="table-responsive">
<table className="table border-top dataTable text-nowrap">
<thead>
<tr className="shadow-sm">
{DocumentColumns.map((col) => (
<th key={col.key} className={`sorting ${col.align}`}>
{col.label}
</th>
))}
<th className="sticky-action-column bg-white text-center">
Action
</th>
</tr>
</thead>
<tbody className="text-start">
{data?.data?.map((doc) => {
const isRestoring = restoringIds.includes(doc.id);
return (
<tr key={doc.id}>
{DocumentColumns.map((col) => (
<td key={col.key} className={`sorting ${col.align}`}>
{col.customRender
? col.customRender(doc)
: col.getValue(doc)}
</td>
))}
<td className="text-center">
{doc.isActive ? (
<div className="d-flex justify-content-center gap-2">
<i
className="bx bx-show text-primary cursor-pointer"
onClick={() =>
setViewDoc({ document: doc.id, isOpen: true })
}
></i>
{canModifyDocument && (
<i
className="bx bx-edit text-secondary cursor-pointer"
onClick={() =>
setManageDoc({ document: doc.id, isOpen: true })
}
></i>
)}
{canDeleteDocument && (
<i
className="bx bx-trash text-danger cursor-pointer"
onClick={() => {
setIsDeleteModalOpen(true);
setDeletingId(doc.id);
}}
></i>
)}
</div>
) : isRestoring ? (
<div
className="spinner-border spinner-border-sm text-primary"
role="status"
>
<span className="visually-hidden">Loading...</span>
</div>
) : (
<i
className="bx bx-recycle me-1 text-primary cursor-pointer"
onClick={() => handleRestore(doc.id)}
></i>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</>
);
};
export default DocumentsList;

View File

@ -0,0 +1,428 @@
import { zodResolver } from "@hookform/resolvers/zod";
import React, { useEffect, useState } from "react";
import { useForm, FormProvider } from "react-hook-form";
import { defaultDocumentValues, DocumentPayloadSchema } from "./DocumentSchema";
import Label from "../common/Label";
import {
useDocumentCategories,
useDocumentTypes,
} from "../../hooks/masterHook/useMaster";
import TagInput from "../common/TagInput";
import {
useDocumentDetails,
useDocumentTags,
useUpdateDocument,
useUploadDocument,
} from "../../hooks/useDocument";
import showToast from "../../services/toastService";
import { useDocumentContext } from "./Documents";
import { isPending } from "@reduxjs/toolkit";
const toBase64 = (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = (err) => reject(err);
});
const MergedTagsWithExistenStatus = (formTags = [], originalTags = []) => {
const tagMap = new Map();
const safeFormTags = Array.isArray(formTags) ? formTags : [];
const safeOriginalTags = Array.isArray(originalTags) ? originalTags : [];
safeOriginalTags.forEach(tag => {
if (tag?.name) {
tagMap.set(tag.name, { ...tag, isActive: tag.isActive ?? true });
}
});
safeFormTags.forEach(tag => {
if (tag?.name) {
tagMap.set(tag.name, { ...tag, isActive: true });
}
});
safeOriginalTags.forEach(tag => {
if (tag?.name && !safeFormTags.some(t => t.name === tag.name)) {
tagMap.set(tag.name, { ...tag, isActive: false });
}
});
return Array.from(tagMap.values());
};
const ManageDocument = ({ closeModal, Document_Entity, Entity }) => {
const { ManageDoc } = useDocumentContext();
const isUpdateForm = Boolean(ManageDoc?.document);
const [selectedType, setSelectedType] = useState(null);
const [selectedCategory, setSelectedCategory] = useState(null);
const [schema, setSchema] = useState(() =>
DocumentPayloadSchema({ isUpdateForm })
);
const methods = useForm({
resolver: zodResolver(schema),
defaultValues: defaultDocumentValues,
});
const {
register,
handleSubmit,
watch,
setValue,
reset,
formState: { errors },
} = methods;
const { mutate: UploadDocument, isPending: isUploading } = useUploadDocument(
() => {
showToast("Document Uploaded Successfully", "success");
closeModal();
}
);
const { mutate: UpdateDocument, isPending: isUpdating } = useUpdateDocument(
() => {
showToast("Document Updated Successfully", "success");
closeModal();
}
);
const onSubmit = (data) => {
const normalizeAttachment = (attachment) => {
if (!attachment) return null;
return {
...attachment,
fileSize: Math.ceil(attachment.fileSize / 1024),
};
};
const payload = {
...data,
attachment: normalizeAttachment(data.attachment),
};
if (ManageDoc?.document) {
const DocumentPayload = {
...payload,
id: DocData.id,
tags: MergedTagsWithExistenStatus(data?.tags, DocData?.tags),
};
UpdateDocument({ documentId: DocData?.id, DocumentPayload });
} else {
const DocumentPayload = { ...payload, entityId: Entity };
UploadDocument(DocumentPayload);
}
};
const {
data: DocData,
isLoading: isDocLoading,
isError: isDocError,
DocError,
} = useDocumentDetails(ManageDoc?.document);
const file = watch("attachment");
const documentTypeId = watch("documentTypeId");
// This hooks calling api base Entity(Employee) and Category
const { DocumentCategories, isLoading } =
useDocumentCategories(Document_Entity);
const categoryId = watch("documentCategoryId");
const { DocumentTypes, isLoading: isTypeLoading } = useDocumentTypes(
categoryId || null
);
const {data:DocumentTags} = useDocumentTags()
// Update schema whenever document type changes
useEffect(() => {
if (!documentTypeId) return;
const type = DocumentTypes?.find(
(t) => String(t.id) === String(documentTypeId)
);
if (!type) return;
setSelectedType(type)
const newSchema = DocumentPayloadSchema({
isMandatory: type.isMandatory ?? false,
regexExpression: type.regexExpression ?? null,
allowedContentType: type.allowedContentType ?? [
"application/pdf",
"image/jpeg",
"image/png",
],
maxSizeAllowedInMB: type.maxSizeAllowedInMB ?? 25,
isUpdateForm,
});
setSchema(() => newSchema);
methods.reset(methods.getValues(), { keepValues: true });
methods.formState.errors; // triggers revalidation
}, [documentTypeId, DocumentTypes, isUpdateForm]);
// File Upload
const onFileChange = async (e) => {
const uploaded = e.target.files[0];
if (!uploaded) return;
const base64Data = await toBase64(uploaded);
const parsedFile = {
fileName: uploaded.name,
base64Data,
contentType: uploaded.type,
fileSize: uploaded.size,
description: "",
isActive: true,
};
setValue("attachment", parsedFile, {
shouldDirty: true,
shouldValidate: true,
});
};
const removeFile = () => {
setValue("attachment", null, {
shouldDirty: true,
shouldValidate: true,
});
};
// build dynamic file accept string
const fileAccept =
selectedType?.allowedContentType
?.split(",")
.map((t) =>
t === "application/pdf"
? ".pdf"
: t === "image/jpeg"
? ".jpg,.jpeg"
: t === "image/png"
? ".png"
: ""
)
.join(",") || "";
useEffect(() => {
if (DocData) {
reset({
...defaultDocumentValues,
name: DocData?.name ?? "",
documentCategoryId: DocData?.documentType?.documentCategory?.id
? String(DocData.documentType.documentCategory.id)
: "",
documentTypeId: DocData?.documentType?.id
? String(DocData.documentType.id)
: "",
documentId: DocData?.documentId ?? "",
description: DocData?.description ?? "",
attachment: DocData?.attachment ?? null,
tags: DocData?.tags ?? [],
});
}
}, [DocData, reset]);
if (isDocLoading) return <div>Loading...</div>;
if (isDocError) return <div>{DocError.message}</div>;
const isPending = isUploading || isUpdating;
return (
<div className="p-2">
<p className="fw-bold fs-6">Upload New Document</p>
<FormProvider key={documentTypeId} {...methods}>
<form onSubmit={handleSubmit(onSubmit)} className="text-start">
{/* Document Name */}
<div className="mb-2">
<Label htmlFor="name" required>
Document Name
</Label>
<input
type="text"
className="form-control form-control-sm"
{...register("name")}
/>
{errors.name && (
<div className="danger-text">{errors.name.message}</div>
)}
</div>
{/* Category */}
<div className="mb-2">
<Label htmlFor="documentCategoryId">Document Category</Label>
<select
{...register("documentCategoryId")}
className="form-select form-select-sm"
>
{isLoading && (
<option disabled value="">
Loading...
</option>
)}
{!isLoading && <option value="">Select Category</option>}
{DocumentCategories?.map((type) => (
<option key={type.id} value={type.id}>
{type.name}
</option>
))}
</select>
{errors.documentCategoryId && (
<div className="danger-text">
{errors.documentCategoryId.message}
</div>
)}
</div>
{/* Type */}
{categoryId && (
<div className="mb-2">
<Label htmlFor="documentTypeId">Document Type</Label>
<select
{...register("documentTypeId")}
className="form-select form-select-sm"
>
{isTypeLoading && (
<option disabled value="">
Loading...
</option>
)}
{DocumentTypes?.map((type) => (
<option key={type.id} value={type.id}>
{type.name}
</option>
))}
</select>
{errors.documentTypeId && (
<div className="danger-text">
{errors.documentTypeId.message}
</div>
)}
</div>
)}
{/* Document ID */}
<div className="mb-2">
<Label
htmlFor="documentId"
required={selectedType?.isMandatory ?? false}
>
Document ID
</Label>
<input
type="text"
className="form-control form-control-sm"
{...register("documentId")}
/>
{errors.documentId && (
<div className="danger-text">{errors.documentId.message}</div>
)}
</div>
{/* Upload */}
<div className="row my-2">
<div className="col-md-12">
<Label htmlFor="attachment" required>Upload Document</Label>
<div
className="border border-secondary border-dashed rounded p-4 text-center bg-textMuted position-relative"
style={{ cursor: "pointer" }}
onClick={() => document.getElementById("attachment").click()}
>
<i className="bx bx-cloud-upload d-block bx-lg"></i>
<span className="text-muted d-block">
Click to select or click here to browse
</span>
<small className="text-muted">
({selectedType?.allowedContentType || "PDF/JPG/PNG"}, max{" "}
{selectedType?.maxSizeAllowedInMB ?? 25}MB)
</small>
<input
type="file"
id="attachment"
accept={selectedType?.allowedContentType}
style={{ display: "none" }}
onChange={(e) => {
onFileChange(e);
e.target.value = ""; // reset input
}}
/>
</div>
{errors.attachment && (
<small className="danger-text">
{errors.attachment.message
? errors.attachment.message
: errors.attachment.fileName?.message ||
errors.attachment.base64Data?.message ||
errors.attachment.contentType?.message ||
errors.attachment.fileSize?.message}
</small>
)}
{file?.base64Data && (
<div className="d-flex justify-content-between text-start p-1 mt-2">
<div>
<span className="mb-0 text-secondary small d-block">
{file.fileName}
</span>
<span className="text-body-secondary small d-block">
{(file.fileSize / 1024).toFixed(1)} KB
</span>
</div>
<i
className="bx bx-trash bx-sm cursor-pointer text-danger"
onClick={removeFile}
></i>
</div>
)}
</div>
</div>
<div className="mb-2">
<TagInput name="tags" label="Tags" placeholder="Tags.." options={DocumentTags} />
{errors.tags && (
<small className="danger-text">{errors.tags.message}</small>
)}
</div>
{/* Description */}
<div className="mb-2">
<Label htmlFor="description" required>Description</Label>
<textarea
rows="2"
className="form-control"
{...register("description")}
></textarea>
{errors.description && (
<div className="danger-text">{errors.description.message}</div>
)}
</div>
{/* Buttons */}
<div className="d-flex justify-content-center gap-3">
<button
type="submit"
className="btn btn-primary btn-sm"
disabled={isPending}
>
{isPending ? "Please Wait..." : " Submit"}
</button>
<button
type="reset"
className="btn btn-secondary btn-sm"
disabled={isPending}
onClick={closeModal}
>
Cancel
</button>
</div>
</form>
</FormProvider>
</div>
);
};
export default ManageDocument;

View File

@ -0,0 +1,47 @@
import React from "react";
const SkeletonLine = ({ height = 16, width = "100%", className = "" }) => (
<div
className={`skeleton mb-1 ${className}`}
style={{
height,
width,
borderRadius: 4,
}}
></div>
);
const VersionListSkeleton = ({ items = 5 }) => {
return (
<div className="list-group mx-0">
{[...Array(items)].map((_, idx) => (
<div
key={idx}
className="list-group-item py-2 border border-bottom border-top-0 border-start-0 border-end-0"
>
{/* Top row: document name + version/status */}
<div className="d-flex w-100 justify-content-between">
<SkeletonLine width="40%" height={16} />
<div className="d-flex gap-2">
<SkeletonLine width="60px" height={14} />
<SkeletonLine width="80px" height={14} />
</div>
</div>
{/* Upload by row */}
<div className="d-flex align-items-center gap-2 mt-2">
<SkeletonLine width="24px" height="24px" className="rounded-circle" />
<SkeletonLine width="120px" height={14} />
</div>
{/* Updated at row */}
<div className="d-flex gap-2 mt-2">
<SkeletonLine width="150px" height={14} />
</div>
</div>
))}
</div>
);
};
export default VersionListSkeleton;

View File

@ -0,0 +1,234 @@
import React, { useState } from "react";
import {
useDocumentDetails,
useDocumentVersionList,
useVerifyDocument,
} from "../../hooks/useDocument";
import { getDocuementsStatus, useDocumentContext } from "./Documents";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import Avatar from "../common/Avatar";
import {
DOWNLOAD_DOCUMENT,
ITEMS_PER_PAGE,
VERIFY_DOCUMENT,
} from "../../utils/constants";
import Pagination from "../common/Pagination";
import VersionListSkeleton from "./VersionListSkeleton";
import DocumentDetailsSkeleton from "./DocumentDetailsSkeleton ";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import DocumentVersionList from "./DocumentVersionList";
const ViewDocument = () => {
const { viewDoc, setViewDoc, setOpenDocument } = useDocumentContext();
const [currentPage, setCurrentPage] = useState(1);
const canVerifyDocument = useHasUserPermission(VERIFY_DOCUMENT);
const canDownloadDocument = useHasUserPermission(DOWNLOAD_DOCUMENT);
const { data, isLoading, isError, error } = useDocumentDetails(
viewDoc?.document
);
const {
data: versionList,
isError: isVersionError,
isLoading: versionLoding,
error: versionError,
} = useDocumentVersionList(
data?.parentAttachmentId,
ITEMS_PER_PAGE - 10,
currentPage
);
const paginate = (page) => {
if (page >= 1 && page <= (versionList?.totalPages ?? 1)) {
setCurrentPage(page);
}
};
const { mutate: VerifyDoc, isPending } = useVerifyDocument();
const VerifyDocument = () => {
VerifyDoc({ documentId: viewDoc?.document, isVerify: true });
};
const RejectDocument = () => {
VerifyDoc({ documentId: viewDoc?.document, isVerify: false });
};
if (isLoading) return <DocumentDetailsSkeleton />;
if (isError)
return (
<div>
<p>{error?.response?.data?.message || error?.message}</p>
<p className="danger-text">{error?.response?.status}</p>
</div>
);
return (
<div className="p-1">
<p className="fw-bold fs-6">Document Details</p>
<div className="row mb-2">
<div className="col-12 col-md-6">
<div className="d-flex text-start">
<span className="fw-semibold me-2" style={{ minWidth: "130px" }}>
Document Name:
</span>
<span className="text-muted">{data.name || "-"}</span>
</div>
</div>
<div className="col-12 col-md-6">
<div className="d-flex text-start">
<span className="fw-semibold me-2" style={{ minWidth: "130px" }}>
Document ID:
</span>
<span className="text-muted">{data.documentId || "-"}</span>
</div>
</div>
</div>
{/* Row 2 */}
<div className="row mb-2">
<div className="col-12 col-md-6 text-start">
<div className="d-flex">
<span className="fw-semibold me-2" style={{ minWidth: "130px" }}>
Version:
</span>
<span className="text-muted">{data.version || "-"}</span>
</div>
</div>
<div className="col-12 col-md-6 text-start">
<div className="d-flex">
<span className="fw-semibold me-2" style={{ minWidth: "130px" }}>
Uploaded At:
</span>
<span className="text-muted">
{formatUTCToLocalTime(data.uploadedAt)}
</span>
</div>
</div>
</div>
{/* Row 3 */}
<div className="row mb-2 text-start">
<div className="col-12 col-md-6">
<div className="d-flex">
<span className="fw-semibold me-2" style={{ minWidth: "130px" }}>
Uploaded By:
</span>
<div className="d-flex align-items-center ms-1">
<Avatar
size="xs"
classAvatar="m-0"
firstName={data.uploadedBy?.firstName}
lastName={data.uploadedBy?.lastName}
/>
<span className="text-truncate ms-1">
{`${data.uploadedBy?.firstName ?? ""} ${
data.uploadedBy?.lastName ?? ""
}`.trim() || "N/A"}
</span>
</div>
</div>
</div>
{data.updatedAt && (
<div className="d-flex">
<span className="fw-semibold me-2" style={{ minWidth: "130px" }}>
Updated At:
</span>
<span className="text-muted">
{formatUTCToLocalTime(data.updatedAt) || "-"}
</span>
</div>
)}{" "}
<div className="col-12 col-md-6"></div>
</div>
{/* Row 4 */}
<div className="row mb-2 text-start">
<div className="col-12 col-md-6">
<div className="d-flex">
<span className="fw-semibold me-2" style={{ minWidth: "130px" }}>
Category:
</span>
<span className="text-muted">
{data.documentType?.documentCategory?.name || "-"}
</span>
</div>
</div>
<div className="col-12 col-md-6">
<div className="d-flex">
<span className="fw-semibold me-2" style={{ minWidth: "130px" }}>
Type:
</span>
<span className="text-muted">{data.documentType?.name || "-"}</span>
</div>
</div>
</div>
{/* Row 5 - Tags full width */}
<div className="row mb-2 text-start">
<div className="col-12">
<div className="d-flex">
<span className="fw-semibold me-2" style={{ minWidth: "130px" }}>
Tags:
</span>
<div className="d-flex flex-wrap gap-2">
{data.tags?.length > 0 ? (
data.tags.map((t, i) => (
<span
key={i}
className="badge rounded-pill bg-label-secondary"
>
{t.name}
</span>
))
) : (
<span className="text-muted">-</span>
)}
</div>
</div>
</div>
</div>
<div className="row mb-2 text-start">
<div className="col-12">
<div className="d-flex">
<span className="fw-semibold me-2" style={{ minWidth: "130px" }}>
Description:
</span>
<span className="text-muted">{data.description || "-"}</span>
</div>
</div>
</div>
{data.isVerified === null && (
<div className="d-flex justify-content-end">
<div className="d-flex text-start text-sm-end">
{" "}
{isPending ? (
"Please Wait..."
) : (
<div className="mx-2">
<a
onClick={VerifyDocument}
className="cursor-pointer text-primary"
>
Verify
</a>
<a
onClick={RejectDocument}
className="cursor-pointer text-danger mx-2"
>
Reject
</a>
</div>
)}
</div>
</div>
)}
<DocumentVersionList
versionLoding={versionLoding}
versionList={versionList}
isPending={isPending}
setOpenDocument={setOpenDocument}
VerifyDocument={VerifyDocument}
/>
</div>
);
};
export default ViewDocument;

View File

@ -9,7 +9,6 @@ const EmpDashboard = ({ profile }) => {
refetch,
} = useProjectsAllocationByEmployee(profile?.id);
console.log(projectList);
return (
<>
<div className="row">

View File

@ -1,10 +1,15 @@
import React, { useState, useEffect } from "react";
import { ComingSoonPage } from "../../pages/Misc/ComingSoonPage";
import DocumentPage from "../../pages/Documents/DocumentPage";
import Documents from "../Documents/Documents";
import { useParams } from "react-router-dom";
import { DOCUMENTS_ENTITIES } from "../../utils/constants";
const EmpDocuments = ({ profile, loggedInUser }) => {
const {employeeId} = useParams()
return (
<>
<ComingSoonPage/>
<Documents Document_Entity={DOCUMENTS_ENTITIES.EmployeeEntity} Entity={employeeId} />
</>
);
};

View File

@ -4,4 +4,4 @@ const EmployeeList = () => {
return <div>EmployeeList</div>;
};
export default EmployeeList;
export default EmployeeList;

View File

@ -1,11 +1,18 @@
import React from "react";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { VIEW_DOCUMENT } from "../../utils/constants";
const EmployeeNav = ({ onPillClick, activePill }) => {
const tabs = [
const canViewDocuments = useHasUserPermission(VIEW_DOCUMENT)
const tabs = [
{ key: "profile", icon: "bx bx-user", label: "Profile" },
{ key: "attendance", icon: "bx bx-group", label: "Attendances" },
{ key: "documents", icon: "bx bx-user", label: "Documents" },
canViewDocuments && {
key: "documents",
icon: "bx bx-file",
label: "Documents",
},
{ key: "activities", icon: "bx bx-grid-alt", label: "Activities" },
];
].filter(Boolean);
return (
<div className="col-md-12">

View File

@ -71,7 +71,7 @@ const ExpenseFilterPanel = ({ onApply, handleGroupBy }) => {
closePanel();
};
// Close popup when navigating to another component
// Close popup when navigating to another component
const location = useLocation();
useEffect(() => {
closePanel();

View File

@ -8,6 +8,7 @@ import {
APPROVE_EXPENSE,
EXPENSE_DRAFT,
EXPENSE_REJECTEDBY,
ITEMS_PER_PAGE,
} from "../../utils/constants";
import { getColorNameFromHex, useDebounce } from "../../utils/appUtils";
import { ExpenseTableSkeleton } from "./ExpenseSkeleton";
@ -22,12 +23,11 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
const IsExpenseEditable = useHasUserPermission();
const IsExpesneApprpve = useHasUserPermission(APPROVE_EXPENSE);
const [currentPage, setCurrentPage] = useState(1);
const pageSize = 20;
const debouncedSearch = useDebounce(searchText, 500);
const { mutate: DeleteExpense, isPending } = useDeleteExpense();
const { data, isLoading, isError, isInitialLoading, error } = useExpenseList(
pageSize,
ITEMS_PER_PAGE,
currentPage,
filters,
debouncedSearch
@ -110,8 +110,9 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
label: "Submitted By",
align: "text-start",
getValue: (e) =>
`${e.createdBy?.firstName ?? ""} ${e.createdBy?.lastName ?? ""}`.trim() ||
"N/A",
`${e.createdBy?.firstName ?? ""} ${
e.createdBy?.lastName ?? ""
}`.trim() || "N/A",
customRender: (e) => (
<div className="d-flex align-items-center">
<Avatar
@ -185,26 +186,16 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
return (
<>
{IsDeleteModalOpen && (
<div
className={`modal fade show`}
tabIndex="-1"
role="dialog"
style={{
display: "block",
backgroundColor: "rgba(0,0,0,0.5)",
}}
aria-hidden="false"
>
<ConfirmModal
type="delete"
header="Delete Expense"
message="Are you sure you want delete?"
onSubmit={handleDelete}
onClose={() => setIsDeleteModalOpen(false)}
loading={isPending}
paramData={deletingId}
/>
</div>
<ConfirmModal
isOpen={IsDeleteModalOpen}
type="delete"
header="Delete Expense"
message="Are you sure you want delete?"
onSubmit={handleDelete}
onClose={() => setIsDeleteModalOpen(false)}
loading={isPending}
paramData={deletingId}
/>
)}
<div className="card px-0 px-sm-4">

View File

@ -32,8 +32,8 @@ const WorkItem = ({
forWorkArea,
deleteHandleTask,
}) => {
const projectId = useSelector((store)=>store.localVariables.projectId)
const isTaskPlanning = /^\/activities\/task$/.test(location.pathname);
const projectId = useSelector((store) => store.localVariables.projectId);
const isTaskPlanning = /^\/activities\/task$/.test(location.pathname);
const [itemName, setItemName] = useState("");
const [NewWorkItem, setNewWorkItem] = useState();
@ -135,25 +135,15 @@ const isTaskPlanning = /^\/activities\/task$/.test(location.pathname);
)}
{showModal2 && (
<div
className={`modal fade ${showModal2 ? "show" : ""}`}
tabIndex="-1"
role="dialog"
style={{
display: showModal2 ? "block" : "none",
backgroundColor: showModal2 ? "rgba(0,0,0,0.5)" : "transparent",
}}
aria-hidden="false"
>
<ConfirmModal
type={"delete"}
header={"Delete Activity"}
message={"Are you sure you want delete?"}
onSubmit={handleSubmit}
onClose={closeModalDelete}
loading={loadingDelete}
/>
</div>
<ConfirmModal
isOpen={showModal2}
type="delete"
header="Delete Activity"
message="Are you sure you want delete?"
onSubmit={handleSubmit}
onClose={closeModalDelete}
loading={isPending}
/>
)}
<tr key={NewWorkItem?.workItemId}>
@ -240,9 +230,7 @@ const isTaskPlanning = /^\/activities\/task$/.test(location.pathname);
</td>
{(ManageInfra ||
(
ManageAndAssignTak &&
PlannedWork !== CompletedWork)) && (
(ManageAndAssignTak && PlannedWork !== CompletedWork)) && (
<td className="text-end align-items-middle border-top">
{/* Desktop (md and up): inline icons */}
<div className="d-none d-md-flex justify-content-end gap-1 px-2">

View File

@ -0,0 +1,14 @@
import React from "react";
import Documents from "../Documents/Documents";
import { useSelectedProject } from "../../slices/apiDataManager";
import { DOCUMENTS_ENTITIES } from "../../utils/constants";
const ProjectDocuments = () => {
const selectedProject = useSelectedProject()
return (
<>
<Documents Document_Entity={DOCUMENTS_ENTITIES.ProjectEntity} Entity={selectedProject} />
</>
);
};
export default ProjectDocuments;

View File

@ -1,84 +1,57 @@
import React from "react";
import { hasUserPermission } from "../../utils/authUtils";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { DIRECTORY_ADMIN, DIRECTORY_MANAGER, DIRECTORY_USER, VIEW_PROJECT_INFRA } from "../../utils/constants";
import {
DIRECTORY_ADMIN,
DIRECTORY_MANAGER,
DIRECTORY_USER,
VIEW_PROJECT_INFRA,
} from "../../utils/constants";
const ProjectNav = ({ onPillClick, activePill }) => {
const HasViewInfraStructure = useHasUserPermission( VIEW_PROJECT_INFRA );
const HasViewInfraStructure = useHasUserPermission(VIEW_PROJECT_INFRA);
const DirAdmin = useHasUserPermission(DIRECTORY_ADMIN);
const DireManager = useHasUserPermission(DIRECTORY_MANAGER)
const DirUser = useHasUserPermission(DIRECTORY_USER)
const DireManager = useHasUserPermission(DIRECTORY_MANAGER);
const DirUser = useHasUserPermission(DIRECTORY_USER);
const ProjectTab = [
{ key: "profile", icon: "bx bx-user", label: "Profile" },
{ key: "teams", icon: "bx bx-group", label: "Teams" },
{
key: "infra",
icon: "bx bx-grid-alt",
label: "Infrastructure",
hidden: !HasViewInfraStructure,
},
{
key: "directory",
icon: "bx bxs-contact",
label: "Directory",
hidden: !(DirAdmin || DireManager || DirUser),
},
{ key: "documents", icon: "bx bx-folder-open", label: "Documents" },
{ key: "setting", icon: "bx bxs-cog", label: "Setting" },
];
return (
<div className="nav-align-top">
<ul className="nav nav-tabs ">
<li className="nav-item">
<a
className={`nav-link ${activePill === "profile" ? "active" : ""} fs-6`}
href="#"
onClick={(e) => {
e.preventDefault();
onPillClick("profile");
}}
>
<i className="bx bx-user bx-sm me-1_5"></i> <span className="d-none d-md-inline">Profile</span>
</a>
</li>
<li className="nav-item">
<a
className={`nav-link ${activePill === "teams" ? "active" : ""} fs-6`}
href="#"
onClick={(e) => {
e.preventDefault();
onPillClick("teams");
}}
>
<i className="bx bx-group bx-sm me-1_5"></i><span className="d-none d-md-inline" > Teams</span>
</a>
</li>
<li className={`nav-item ${!HasViewInfraStructure && "d-none"} `}>
<a
className={`nav-link ${activePill === "infra" ? "active" : ""} fs-6`}
href="#"
onClick={(e) => {
e.preventDefault();
onPillClick("infra");
}}
>
<i className="bx bx-grid-alt bx-sm me-1_5"></i> <span className="d-none d-md-inline">Infrastructure</span>
</a>
</li>
{(DirAdmin || DireManager || DirUser) && (
<li className="nav-item">
<a
className={`nav-link ${activePill === "directory" ? "active" : ""} fs-6`}
href="#"
onClick={(e) => {
e.preventDefault(); // Prevent page reload
onPillClick("directory");
}}
>
<i className='bx bxs-contact bx-sm me-1_5'></i> <span className="d-none d-md-inline">Directory</span>
</a>
</li>
)}
<li className="nav-item">
<a
className={`nav-link ${
activePill === "imagegallary" ? "active" : ""
} fs-6`}
href="#"
onClick={(e) => {
e.preventDefault(); // Prevent page reload
onPillClick("imagegallary");
}}
>
<i className='bx bxs-cog bx-sm me-1_5'></i> <span className="d-none d-md-inline">project Setup</span>
</a>
</li>
<ul className="nav nav-tabs">
{ProjectTab?.filter((tab) => !tab.hidden)?.map((tab) => (
<li key={tab.key} className="nav-item cursor-pointer">
<a
className={`nav-link ${
activePill === tab.key ? "active cursor-pointer" : ""
} fs-6`}
onClick={(e) => {
e.preventDefault();
onPillClick(tab.key);
}}
>
<i className={`${tab.icon} bx-sm me-1_5`}></i>
<span className="d-none d-md-inline ">{tab.label}</span>
</a>
</li>
))}
</ul>
</div>
);

View File

@ -0,0 +1,181 @@
import React, { useEffect } from "react";
import {
useProjectLevelEmployeePermission,
useProjectLevelModules,
useUpdateProjectLevelEmployeePermission,
} from "../../hooks/useProjects";
import { useSelectedProject } from "../../slices/apiDataManager";
import { useEmployeesByProject } from "../../hooks/useEmployees";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import showToast from "../../services/toastService";
export const ProjectPermissionSchema = z.object({
employeeId: z.string().min(1, "Employee is required"),
selectedPermissions: z.array(z.string()).optional(),
});
const ProjectPermission = () => {
const selectedProject = useSelectedProject();
const { data: ProjectModules = [] } = useProjectLevelModules();
const { employees = [], loading } = useEmployeesByProject(selectedProject);
const {
register,
watch,
handleSubmit,
reset,
formState: { errors },
} = useForm({
resolver: zodResolver(ProjectPermissionSchema),
defaultValues: {
employeeId: "",
selectedPermissions: [],
},
});
const selectedEmployee = watch("employeeId");
const { data: selectedEmpPermissions } = useProjectLevelEmployeePermission(
selectedEmployee || "",
selectedProject
);
useEffect(() => {
if (!employees.length) return;
const enabledPerms =
selectedEmpPermissions?.permissions
?.filter((perm) => perm.isEnabled)
?.map((perm) => perm.id) || [];
reset({
employeeId: selectedEmployee || employees[0]?.id || "",
selectedPermissions: enabledPerms,
});
}, [selectedEmpPermissions, reset, selectedEmployee, employees]);
const { mutate: updatePermission, isPending } =
useUpdateProjectLevelEmployeePermission();
const onSubmit = (formData) => {
if (!formData.employeeId) {
showToast("Please select an employee", "warn");
return;
}
const existingPermissions = selectedEmpPermissions?.permissions || [];
const payloadPermissions =
existingPermissions.length > 0
? existingPermissions.map((perm) => ({
id: perm.id,
isEnabled: formData.selectedPermissions?.includes(perm.id) || false,
}))
: (formData.selectedPermissions || []).map((id) => ({
id,
isEnabled: true,
}));
if (payloadPermissions.length === 0) {
showToast("No permissions selected", "warn");
return;
}
const hasChanges = existingPermissions.some(
(perm) =>
perm.isEnabled !==
(formData.selectedPermissions?.includes(perm.id) || false)
);
if (!hasChanges && existingPermissions.length > 0) {
showToast("No changes detected", "info");
return;
}
const payload = {
employeeId: formData.employeeId,
projectId: selectedProject,
permission: payloadPermissions,
};
updatePermission(payload);
};
return (
<div className="row">
<form className="row" onSubmit={handleSubmit(onSubmit)}>
{/* Employee Dropdown */}
<div className="d-flex align-items-end gap-2">
<div className="text-start">
<label className="form-label">Select Employee</label>
<select
className="form-select form-select-sm"
{...register("employeeId")}
disabled={isPending}
>
{loading ? (
<option value="">Loading...</option>
) : (
<>
<option value="">-- Select --</option>
{employees.map((emp) => (
<option key={emp.id} value={emp.id}>
{emp.firstName} {emp.lastName}
</option>
))}
</>
)}
</select>
{errors.employeeId && (
<div className="text-danger small">
{errors.employeeId.message}
</div>
)}
</div>
<button className="btn btn-sm btn-primary" disabled={isPending || loading}>
{isPending ? "Please Wait..." : "Update Permission"}
</button>
</div>
{/* Permissions */}
{ProjectModules.map((feature) => (
<div key={feature.id} className="row my-2">
<div className="col-12 text-start fw-semibold mb-2">
{feature.name}
</div>
<div className="col-12">
<div className="row">
{feature.featurePermissions?.map((perm) => (
<div
className="col-12 col-sm-6 col-md-4 mb-2"
key={perm.id}
>
<label
className="form-check-label d-flex align-items-center"
htmlFor={perm.id}
>
<input
type="checkbox"
className="form-check-input me-2"
id={perm.id}
value={perm.id}
{...register("selectedPermissions")}
/>
{perm.name}
</label>
</div>
))}
</div>
</div>
<hr className="my-2" />
</div>
))}
</form>
</div>
);
};
export default ProjectPermission;

View File

@ -0,0 +1,74 @@
import React, { useState } from "react";
import { ComingSoonPage } from "../../pages/Misc/ComingSoonPage";
import ProjectPermission from "./ProjectPermission";
const ProjectSetting = () => {
const [activePill, setActivePill] = useState(() => {
return localStorage.getItem("lastActiveProjectSettingTab") || "Permissions";
});
const projectSettingTab = [
{ key: "Permissions", label: "Permissions" },
{ key: "Notification", label: "Notification" },
{ key: "SeparatedLink", label: "Separated link", isButton: true },
];
const handlePillClick = (pillKey) => {
setActivePill(pillKey);
localStorage.setItem("lastActiveProjectSettingTab", pillKey);
};
const renderContent = () => {
switch (activePill) {
case "Permissions":
return <ProjectPermission />;
case "Notification":
return <ComingSoonPage />;
default:
return <ComingSoonPage />;
}
};
return (
<div className="w-100">
<div className="card p-3">
<div className="col-4">
<div className="dropdown text-start">
<button
className="btn btn-sm btn-outline-primary dropdown-toggle"
type="button"
id="dropdownMenuButton"
data-bs-toggle="dropdown"
aria-expanded="false"
>
{activePill || "Select Option"}
</button>
<ul className="dropdown-menu" aria-labelledby="dropdownMenuButton">
{projectSettingTab.map((item) =>
item.isButton ? (
<li key={item.key}>
<button className="dropdown-item">{item.label}</button>
</li>
) : (
<li key={item.key}>
<button
className="dropdown-item"
onClick={() => handlePillClick(item.key)}
>
{item.label}
</button>
</li>
)
)}
</ul>
</div>
</div>
<div className="mt-3">{renderContent()}</div>
</div>
</div>
);
};
export default ProjectSetting;

View File

@ -249,26 +249,15 @@ const Teams = () => {
</div>
{IsDeleteModal && (
<div
className={`modal fade ${IsDeleteModal ? "show" : ""}`}
tabIndex="-1"
role="dialog"
style={{
display: IsDeleteModal ? "block" : "none",
backgroundColor: IsDeleteModal ? "rgba(0,0,0,0.5)" : "transparent",
}}
aria-hidden="false"
>
<ConfirmModal
type={"delete"}
header={"Removed Employee"}
message={"Are you sure you want delete?"}
onSubmit={removeAllocation}
onClose={closeDeleteModal}
loading={isPending}
paramData={deleteEmployee}
/>
</div>
<ConfirmModal
isOpen={IsDeleteModal}
type="delete"
header="Removed Employee"
message="Are you sure you want delete?"
onSubmit={() => removeAllocation(deleteEmployee)}
onClose={closeDeleteModal}
loading={isPending}
/>
)}
<div className="card card-action mb-6">

View File

@ -1,70 +1,71 @@
import React, { useState } from 'react';
import React from "react";
const ConfirmModal = ({ type, onSubmit, onClose, message, loading ,header, paramData}) => {
const TypeofIcon = (type) => {
switch (type) {
case "delete":
return <i className='bx bx-x-circle text-danger ' style={{fontSize:"60px"}} ></i>;
default:
return null;
const ConfirmModal = ({
type,
onSubmit,
onClose,
message,
loading,
header,
paramData,
isOpen = false,
}) => {
if (!isOpen) return null;
const TypeofIcon = () => {
if (type === "delete") {
return (
<i
className="bx bx-x-circle text-danger"
style={{ fontSize: "60px" }}
></i>
);
}
return null;
};
const TypeofModal = (type) => {
switch (type) {
case "delete":
return "sm";
case "other":
return "md";
default:
return "sm";
}
};
const modalSize = type === "delete" ? "sm" : "md";
return (
<div className={`modal-dialog modal-${TypeofModal(type)} modal-simple modal-confirm`}>
<div className='modal-dialog modal-dialog-centered'>
<div
className="modal fade show"
style={{ display: "block", backgroundColor: "rgba(0,0,0,0.5)" }}
role="dialog"
aria-modal="true"
>
<div className={`modal-dialog modal-${modalSize} modal-dialog-top`}>
<div className="modal-content">
<div className="modal-body py-1 px-2">
<div className="row">
<div className="text-start mb-1">
<div className=' d-flex justify-content-between mb-4'>
{header && < strong className='mb-0 font-weight-bold'>{header }</strong>}
<div className="d-flex justify-content-between mb-4 pt-2">
{header && <strong className="mb-0">{header}</strong>}
<button
type="button"
className="btn-close"
className="btn-close "
aria-label="Close"
onClick={onClose}
/>
</div>
<div className='row'>
<div className='col-4 col-sm-2'> {TypeofIcon(type)}</div>
<div className='col-8 col-sm-10 py-sm-2 py-1 text-sm-start'>
<span className='fs-6 text'>{message}</span>
<div className='d-flex justify-content-end mt-4'>
</div>
<div className="row">
<div className="col-4 col-sm-2">{TypeofIcon()}</div>
<div className="col-8 col-sm-10 py-sm-2 py-1 text-sm-start">
<span className="fs-6">{message}</span>
<div className="d-flex justify-content-end mt-4">
<button
className='btn btn-primary btn-sm'
onClick={()=>onSubmit(paramData)}
disabled={loading}
className="btn btn-primary btn-sm"
onClick={() => onSubmit(paramData)}
disabled={loading}
>
{loading ? "Please Wait..." : "Yes"}
</button>
<button
className='btn btn-secondary ms-4 btn-sm'
className="btn btn-secondary ms-4 btn-sm"
onClick={onClose}
disabled={loading}
disabled={loading}
>
No
</button>
</div>
</div>
</div>
</div>
</div>
</div>

View File

@ -2,111 +2,67 @@ import { useFormContext, useWatch } from "react-hook-form";
import React, { useEffect, useState } from "react";
import Label from "./Label";
const TagInput = ({
label = "Tags",
name = "tags",
placeholder = "Start typing to add... like employee, manager",
color = "#e9ecef",
options = [],
}) => {
const [tags, setTags] = useState([]);
const TagInput = ({ label, name, placeholder, color = "#e9ecef", options = [] }) => {
const { setValue, watch } = useFormContext();
const tags = watch(name) || [];
const [input, setInput] = useState("");
const [suggestions, setSuggestions] = useState([]);
const { setValue, trigger, control } = useFormContext();
const watchedTags = useWatch({ control, name });
const handleAdd = (newTag) => {
const tagObj = typeof newTag === "string" ? { name: newTag, isActive: true } : newTag;
useEffect(() => {
if (
Array.isArray(watchedTags) &&
JSON.stringify(tags) !== JSON.stringify(watchedTags)
) {
setTags(watchedTags);
}
}, [JSON.stringify(watchedTags)]);
useEffect(() => {
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);
if (!tags.some((t) => t.name === tagObj.name)) {
setValue(name, [...tags, tagObj], { shouldValidate: true });
}
}, [input, options, tags]);
};
const addTag = async (tagObj) => {
if (!tags.some((tag) => tag.name === tagObj.name)) {
const cleanedTag = {
id: tagObj.id ?? null,
name: tagObj.name,
};
const newTags = [...tags, cleanedTag];
setTags(newTags);
setValue(name, newTags, { shouldValidate: true });
await trigger(name);
const handleRemove = (tagName) => {
setValue(
name,
tags.filter((t) => t.name !== tagName),
{ shouldValidate: true }
);
};
const handleKeyDown = (e) => {
if (e.key === "Enter" && input.trim()) {
e.preventDefault();
handleAdd(input.trim());
setInput("");
setSuggestions([]);
}
};
const removeTag = (indexToRemove) => {
const newTags = tags.filter((_, i) => i !== indexToRemove);
setTags(newTags);
setValue(name, newTags, { shouldValidate: true });
trigger(name);
};
const handleChange = (e) => {
const val = e.target.value;
setInput(val);
const handleInputKeyDown = (e) => {
if ((e.key === "Enter" || e.key === " ")&& 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);
} else if (e.key === "Backspace" && input === "") {
setTags((prev) => prev.slice(0, -1));
}
};
const handleInputKey = (e) => {
const key = e.key?.toLowerCase();
if ((key === "enter" || key === " " || e.code === "Space") && input.trim() !== "") {
e.preventDefault();
const existing = options.find(
(opt) => opt.name.toLowerCase() === input.trim().toLowerCase()
if (val) {
setSuggestions(
options
.filter((opt) => {
const label = typeof opt === "string" ? opt : opt.name;
return (
label.toLowerCase().includes(val.toLowerCase()) &&
!tags.some((t) => t.name === label)
);
})
.map((opt) => ({
name: typeof opt === "string" ? opt : opt.name,
isActive: true,
}))
);
const newTag = existing
? existing
: {
id: null,
name: input.trim(),
description: input.trim(),
};
addTag(newTag);
} else if ((key === "backspace" || e.code === "Backspace") && input === "") {
setTags((prev) => prev.slice(0, -1));
} else {
setSuggestions([]);
}
};
const handleSuggestionClick = (suggestion) => {
addTag(suggestion);
const handleSuggestionClick = (sugg) => {
handleAdd(sugg);
setInput("");
setSuggestions([]);
};
const backgroundColor = color || "#f8f9fa";
const iconColor = `var(--bs-${color})`;
return (
<>
<Label htmlFor={name} className="form-label" required>
@ -123,17 +79,16 @@ useEffect(() => {
key={index}
className="d-flex align-items-center"
style={{
color: iconColor,
backgroundColor,
backgroundColor: color,
padding: "2px 6px",
borderRadius: "2px",
fontSize: "0.85rem",
fontSize: "0.8rem",
}}
>
{tag.name}
<i
className="bx bx-x bx-xs ms-1"
onClick={() => removeTag(index)}
onClick={() => handleRemove(tag.name)}
style={{ cursor: "pointer" }}
/>
</span>
@ -142,9 +97,8 @@ useEffect(() => {
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleInputKeyDown}
onKeyUp={handleInputKey}
onChange={handleChange}
onKeyDown={handleKeyDown}
placeholder={placeholder}
style={{
border: "none",
@ -157,12 +111,13 @@ useEffect(() => {
{suggestions.length > 0 && (
<ul
className="list-group position-absolute mt-1 bg-white w-50 shadow-sm "
className="list-group position-absolute mt-1 bg-white w-50 shadow-sm"
style={{
zIndex: 1000,
maxHeight: "150px",
overflowY: "auto",
boxShadow:"0px 4px 10px rgba(0, 0, 0, 0.2)",borderRadius:"3px",border:"1px solid #ddd"
borderRadius: "3px",
border: "1px solid #ddd",
}}
>
{suggestions.map((sugg, i) => (
@ -170,8 +125,7 @@ useEffect(() => {
key={i}
className="dropdown-item p-1 hoverBox"
onClick={() => handleSuggestionClick(sugg)}
style={{cursor: "pointer", fontSize: "0.875rem"}}
style={{ cursor: "pointer", fontSize: "0.875rem" }}
>
{sugg.name}
</li>
@ -182,4 +136,7 @@ useEffect(() => {
</>
);
};
export default TagInput;

View File

@ -222,7 +222,7 @@ const CreateActivity = ({ onClose }) => {
<div className="col-12 text-end mt-3">
<button
type="button" // change to button
type="reset"
className="btn btn-sm btn-label-secondary me-3"
onClick={handleClose}
>

View File

@ -6,7 +6,7 @@ import { MasterRespository } from '../../repositories/MastersRepository';
import { clearApiCacheKey } from '../../slices/apiCacheSlice';
import { getCachedData, cacheData } from '../../slices/apiDataManager';
import showToast from '../../services/toastService';
import { useCreateContactCategory } from '../../hooks/masterHook/useMaster';
import {useCreateContactCategory} from '../../hooks/masterHook/useMaster';
import Label from '../common/Label';
@ -65,17 +65,17 @@ const CreateContactCategory = ({ onClose }) => {
}, []);
return (<>
<form className="row g-2" onSubmit={handleSubmit(onSubmit)}>
<div className="col-12 col-md-12 text-start">
<Label className="form-label" required>Category Name</Label>
<input type="text"
{...register("name")}
className={`form-control ${errors.name ? 'is-invalids' : ''}`}
/>
{errors.name && <p className="text-danger">{errors.name.message}</p>}
</div>
<div className="col-12 col-md-12 text-start">
<Label className="form-label" htmlFor="description" required>Description</Label>
<form className="row g-2" onSubmit={handleSubmit(onSubmit)}>
<div className="col-12 col-md-12 text-start">
<Label className="form-label" required>Category Name</Label>
<input type="text"
{...register("name")}
className={`form-control ${errors.name ? 'is-invalids' : ''}`}
/>
{errors.name && <p className="text-danger">{errors.name.message}</p>}
</div>
<div className="col-12 col-md-12 text-start">
<Label className="form-label" htmlFor="description" required>Description</Label>
<textarea
rows="3"
{...register("description")}
@ -93,21 +93,19 @@ const CreateContactCategory = ({ onClose }) => {
)}
</div>
<div className="col-12 text-end mt-3">
<button
type="button" // not reset
<div className="col-12 text-end">
<button
type="reset"
className="btn btn-sm btn-label-secondary me-3"
onClick={() => {
resetForm(); // clear inputs
onClose?.(); // close modal from parent
}}
data-bs-dismiss="modal"
aria-label="Close"
>
Cancel
</button>
<button type="submit" className="btn btn-sm btn-primary">
{isLoading ? "Please Wait..." : "Submit"}
<button type="submit" className="btn btn-sm btn-primary">
{isLoading? "Please Wait...":"Submit"}
</button>
</div>
</form>

View File

@ -93,22 +93,19 @@ const CreateContactTag = ({ onClose }) => {
)}
</div>
<div className="col-12 text-end mt-3">
<button
type="button" // not reset
<div className="col-12 text-end">
<button
type="reset"
className="btn btn-sm btn-label-secondary me-3"
onClick={() => {
resetForm(); // clear inputs
onClose?.(); // close modal from parent
}}
data-bs-dismiss="modal"
aria-label="Close"
>
Cancel
</button>
<button type="submit" className="btn btn-sm btn-primary">
{isLoading ? "Please Wait..." : "Submit"}
<button type="submit" className="btn btn-sm btn-primary">
{isLoading? "Please Wait...":"Submit"}
</button>
</div>
</form>

View File

@ -119,22 +119,19 @@ const CreateJobRole = ({ onClose }) => {
)}
</div>
<div className="col-12 text-end mt-3">
<button
type="button" // change from reset button
<div className="col-12 text-end">
<button
type="reset"
className="btn btn-sm btn-label-secondary me-3"
onClick={() => {
resetForm(); // optional: clears form
onClose?.(); // close modal via parent
}}
data-bs-dismiss="modal"
aria-label="Close"
>
Cancel
</button>
<button type="submit" className="btn btn-sm btn-primary">
{isLoading ? "Please Wait..." : "Submit"}
<button type="submit" className="btn btn-sm btn-primary">
{isLoading? "Please Wait...":"Submit"}
</button>
</div>
</form>

View File

@ -229,19 +229,19 @@ const CreateRole = ({ modalType, onClose }) => {
{masterFeatures && (
<div className="col-12 text-end mt-3">
<button
type="button"
<div className="col-12 text-end">
<button
type="reset"
className="btn btn-sm btn-label-secondary me-3"
onClick={onClose}
data-bs-dismiss="modal"
aria-label="Close"
>
Cancel
</button>
<button type="submit" className="btn btn-sm btn-primary">
<button type="submit" className="btn btn-sm btn-primary">
{isLoading ? "Please Wait..." : "Submit"}
</button>
</div>
)}
</form>

View File

@ -109,15 +109,12 @@ const CreateWorkCategory = ({ onClose }) => {
)}
</div>
<div className="col-12 text-end mt-3">
<button
type="button" // not reset
<div className="col-12 text-end">
<button
type="reset"
className="btn btn-sm btn-label-secondary me-3"
onClick={() => {
resetForm(); // clear inputs
onClose?.(); // close modal from parent
}}
data-bs-dismiss="modal"
aria-label="Close"
>
Cancel
</button>

View File

@ -239,7 +239,7 @@ const UpdateActivity = ({ activityData, onClose }) => {
{/* Submit / Cancel */}
<div className="col-12 text-end mt-3">
<button
type="button" // change to button
type="button"
className="btn btn-sm btn-label-secondary me-3"
onClick={onClose}
>

View File

@ -112,15 +112,12 @@ const EditContactCategory = ({ data, onClose }) => {
)}
</div>
<div className="col-12 text-end mt-3">
<button
type="button" // not reset
<div className="col-12 text-end">
<button
type="button"
className="btn btn-sm btn-label-secondary me-3"
onClick={() => {
resetForm(); // clear inputs
onClose?.(); // close modal from parent
}}
data-bs-dismiss="modal"
aria-label="Close"
>
Cancel
</button>

View File

@ -112,15 +112,12 @@ const EditContactTag = ({ data, onClose }) => {
)}
</div>
<div className="col-12 text-end mt-3">
<button
type="button" // not reset
<div className="col-12 text-end">
<button
type="button"
className="btn btn-sm btn-label-secondary me-3"
onClick={() => {
resetForm(); // clear inputs
onClose?.(); // close modal from parent
}}
data-bs-dismiss="modal"
aria-label="Close"
>
Cancel
</button>

View File

@ -128,12 +128,12 @@ const EditJobRole = ({ data, onClose }) => {
</div>
<div className="col-12 text-end mt-3">
<button
<div className="col-12 text-end">
<button
type="button"
className="btn btn-sm btn-label-secondary me-3"
onClick={onClose} // 👈 This will now close the popup
data-bs-dismiss="modal"
aria-label="Close"
>
Cancel
</button>

View File

@ -0,0 +1,156 @@
import React, { useEffect } from "react";
import { useForm, FormProvider } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useFeatures } from "../../hooks/useMasterRole";
import { DOCUMENTS_ENTITIES, EXPENSE_MANAGEMENT } from "../../utils/constants";
import {
useCreateDocumentCatgory,
useUpdateDocumentCategory,
} from "../../hooks/masterHook/useMaster";
export const Document_Entity = Object.entries(DOCUMENTS_ENTITIES).map(
([key, value]) => ({ key, value })
);
const ExpenseStatusSchema = z.object({
name: z.string().min(1, { message: "Name is required" }),
description: z.string().min(1, { message: "Description is required" }),
entityTypeId: z.string().min(1, { message: "Entity is required" }),
});
const ManageDocumentCategory = ({ data, onClose }) => {
const methods = useForm({
resolver: zodResolver(ExpenseStatusSchema),
defaultValues: {
name: "",
description: "",
entityTypeId: "",
},
});
const {
register,
handleSubmit,
reset,
formState: { errors },
} = methods;
const { masterFeatures, loading } = useFeatures();
const ExpenseFeature = masterFeatures?.find(
(appfeature) => appfeature.id === EXPENSE_MANAGEMENT
);
const { mutate: CreateDocumentCategory, isPending } =
useCreateDocumentCatgory(() => onClose?.());
const { mutate: UpdateDocumentCategory, isPending: Updating } =
useUpdateDocumentCategory(() => onClose?.());
const onSubmit = (payload) => {
if (data) {
UpdateDocumentCategory({
id: data.id,
payload: { ...payload, id: data.id },
});
} else {
CreateDocumentCategory(payload);
}
};
useEffect(() => {
if (data) {
reset({
name: data.name ?? "",
description: data.description ?? "",
entityTypeId: data.entityTypeId ?? "",
});
}
}, [data, reset]);
return (
<FormProvider {...methods}>
{loading ? (
<div>Loading...</div>
) : (
<div>
<div>
<p className="fw-semibold">
{data ? "Update Document Category" : "Add Document Category"}
</p>
</div>
<form
className="row g-2 text-start"
onSubmit={handleSubmit(onSubmit)}
>
<div className="col-12">
<label className="form-label">Category Name</label>
<input
type="text"
{...register("name")}
className={`form-control form-control-sm `}
/>
{errors.name && (
<p className="danger-text">{errors.name.message}</p>
)}
</div>
<div className="col-12">
<label className="form-label">Select Entity</label>
<select
className="form-select form-select-sm"
{...register("entityTypeId")}
>
<option value="" disabled>Select entity</option>
{Document_Entity.map((entity) => (
<option key={entity.key} value={entity.value}>
{entity.key}
</option>
))}
</select>
{errors.entityTypeId && (
<p className="danger-text">{errors.entityTypeId.message}</p>
)}
</div>
<div className="col-12">
<label className="form-label">Description</label>
<textarea
rows="3"
{...register("description")}
className={`form-control form-control-sm`}
/>
{errors.description && (
<p className="danger-text">{errors.description.message}</p>
)}
</div>
<div className="col-12 text-center">
<button
type="submit"
className="btn btn-sm btn-primary me-3"
disabled={isPending || Updating}
>
{isPending || Updating
? "Please Wait..."
: data
? "Update"
: "Submit"}
</button>
<button
type="button"
className="btn btn-sm btn-secondary"
onClick={onClose}
disabled={isPending || Updating}
>
Cancel
</button>
</div>
</form>
</div>
)}
</FormProvider>
);
};
export default ManageDocumentCategory;

View File

@ -0,0 +1,223 @@
import React, { useEffect } from "react";
import { useForm, FormProvider } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useCreateDocumentType, useDocumentCategories, useUpdateDocumentType } from "../../hooks/masterHook/useMaster";
import { DOCUMENTS_ENTITIES } from "../../utils/constants";
export const Document_Entity = Object.entries(DOCUMENTS_ENTITIES).map(
([key, value]) => ({ key, value })
);
const DocumentTypeSchema = z.object({
name: z.string().min(1, { message: "Name is required" }),
regexExpression: z.string().optional(),
allowedContentType: z.string().min(1, { message: "Allowed content type is required" }),
maxSizeAllowedInMB: z
.number({ invalid_type_error: "Must be a number" })
.min(1, { message: "Max size must be at least 1MB" }),
isValidationRequired: z.boolean().default(true),
isMandatory: z.boolean().default(true),
documentCategoryId: z.string().min(1, { message: "Document Category is required" }),
});
const ManageDocumentType = ({ data, onClose, documentCategories = [] }) => {
const methods = useForm({
resolver: zodResolver(DocumentTypeSchema),
defaultValues: {
name: "",
regexExpression: "",
allowedContentType: "",
maxSizeAllowedInMB: 25,
isValidationRequired: true,
isMandatory: true,
documentCategoryId: "",
entityTypeId:""
},
});
const {
register,
handleSubmit,
reset,watch,
formState: { errors },
} = methods;
const selectedDocumentEntity = watch("entityTypeId")
const {DocumentCategories,isLoading} = useDocumentCategories(selectedDocumentEntity)
const { mutate: createDocType, isPending: creating } = useCreateDocumentType(() =>
onClose?.()
);
const { mutate: updateDocType, isPending: updating } = useUpdateDocumentType(() =>
onClose?.()
);
const onSubmit = (payload) => {
const { entityTypeId, ...rest } = payload;
if (data) {
updateDocType({ id: data.id, payload: { ...rest, id: data.id } });
} else {
createDocType(rest);
}
};
useEffect(() => {
if (data) {
reset({
name: data.name ?? "",
regexExpression: data.regexExpression ?? "",
allowedContentType: data.allowedContentType ?? "",
maxSizeAllowedInMB: data.maxSizeAllowedInMB ?? 25,
isValidationRequired: data.isValidationRequired ?? true,
isMandatory: data.isMandatory ?? true,
documentCategoryId: data.documentCategory?.id ?? "",
entityTypeId:data.documentCategory?.entityTypeId ?? ""
});
}
}, [data]);
return (
<FormProvider {...methods}>
<form className="row g-2 text-start" onSubmit={handleSubmit(onSubmit)}>
<div className="text-center">
<p className="fw-semibold">
{data ? "Edit Document Type" : "Add Document Type"}
</p>
</div>
{/* Name */}
<div className="col-12">
<label className="form-label">Name</label>
<input
type="text"
{...register("name")}
className={`form-control form-control-sm `}
/>
{errors.name && <a className="text-danger">{errors.name.message}</a>}
</div>
{/* Regex Expression */}
<div className="col-12">
<label className="form-label">Regex Expression</label>
<input
type="text"
{...register("regexExpression")}
className="form-control form-control-sm"
/>
</div>
{/* Allowed Content Type */}
<div className="col-12">
<label className="form-label">Allowed Content Type</label>
<input
type="text"
{...register("allowedContentType")}
className={`form-control form-control form-control-sm`}
/>
{errors.allowedContentType && (
<a className="text-danger">{errors.allowedContentType.message}</a>
)}
</div>
{/* Max Size */}
<div className="col-12">
<label className="form-label">Max Size Allowed (MB)</label>
<input
type="number"
{...register("maxSizeAllowedInMB", { valueAsNumber: true })}
className={`form-control form-control-sm`}
/>
{errors.maxSizeAllowedInMB && (
<a className="text-danger">{errors.maxSizeAllowedInMB.message}</a>
)}
</div>
{/* Validation Required */}
<div className="col-6 form-check">
<input
type="checkbox"
className="form-check-input"
{...register("isValidationRequired")}
/>
<label className="form-check-label">Validation Required</label>
</div>
{/* Mandatory */}
<div className="col-6 form-check">
<input
type="checkbox"
className="form-check-input "
{...register("isMandatory")}
/>
<label className="form-check-label">Mandatory</label>
</div>
<div className="col-12">
<label className="form-label">Document Entity</label>
<select
{...register("entityTypeId")}
className={`form-select form-select-sm`}
>
<option value="">-- Select Category --</option>
{Document_Entity.map((entity) => (
<option key={entity.key} value={entity.value}>
{entity.key}
</option>
))}
</select>
{errors.entityTypeId && (
<a className="text-danger">{errors.entityTypeId.message}</a>
)}
</div>
{/* Category */}
<div className="col-12">
<label className="form-label">Document Category</label>
<select
{...register("documentCategoryId")}
className={`form-select form-select-sm`}
>
{isLoading && <option value="" disabled>Loading....</option> }
<option value="">-- Select Category --</option>
{!isLoading && DocumentCategories?.map((cat) => (
<option key={cat.id} value={cat.id}>
{cat.name}
</option>
))}
</select>
{errors.documentCategoryId && (
<a className="text-danger">{errors.documentCategoryId.message}</a>
)}
</div>
{/* Buttons */}
<div className="col-12 text-center">
<button
type="submit"
className="btn btn-sm btn-primary me-3"
disabled={creating || updating}
>
{creating || updating
? "Please Wait..."
: data
? "Update"
: "Submit"}
</button>
<button
type="button"
className="btn btn-sm btn-secondary"
onClick={onClose}
disabled={creating || updating}
>
Cancel
</button>
</div>
</form>
</FormProvider>
);
};
export default ManageDocumentType;

View File

@ -71,23 +71,24 @@ const ManagePaymentMode = ({ data = null, onClose }) => {
)}
</div>
<div className="col-12 text-end mt-3">
<div className="col-12 text-end">
<button
type="button"
type="reset"
className="btn btn-sm btn-label-secondary me-3"
onClick={onClose} // call onClose here
data-bs-dismiss="modal"
aria-label="Close"
disabled={isPending || Updating}
>
Cancel
</button>
<button
<button
type="submit"
className="btn btn-sm btn-primary"
disabled={isPending || Updating}
>
{isPending || Updating ? "Please Wait..." : Updating ? "Update" : "Submit"}
</button>
</div>
</form>
);

View File

@ -1,145 +1,68 @@
import React, { useState, useEffect } from "react";
import React from "react";
import CreateRole from "./CreateRole";
import DeleteMaster from "./DeleteMaster";
import EditRole from "./EditRole";
import CreateJobRole from "./CreateJobRole";
import EditJobRole from "./EditJobRole";
import CreateActivity from "./CreateActivity";
import EditActivity from "./EditActivity";
import ConfirmModal from "../common/ConfirmModal";
import { MasterRespository } from "../../repositories/MastersRepository";
import { cacheData, getCachedData } from "../../slices/apiDataManager";
import showToast from "../../services/toastService";
import CreateWorkCategory from "./CreateWorkCategory";
import EditWorkCategory from "./EditWorkCategory";
import CreateCategory from "./CreateContactCategory";
import CreateContactTag from "./CreateContactTag";
import EditContactCategory from "./EditContactCategory";
import EditContactTag from "./EditContactTag";
import { useDeleteMasterItem } from "../../hooks/masterHook/useMaster";
import ManageExpenseType from "./ManageExpenseType";
import ManagePaymentMode from "./ManagePaymentMode";
import ManageExpenseStatus from "./ManageExpenseStatus";
import ManageDocumentCategory from "./ManageDocumentCategory";
import ManageDocumentType from "./ManageDocumentType";
const MasterModal = ({ modaldata, closeModal }) => {
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
const { mutate: deleteMasterItem, isPending } = useDeleteMasterItem();
const handleSelectedMasterDeleted = () => {
const { masterType, item, validateFn } = modaldata || {};
if (!masterType || !item?.id) {
showToast("Missing master type or item", "error");
return;
}
deleteMasterItem(
{ masterType, item, validateFn },
{ onSuccess: handleCloseDeleteModal }
);
};
const handleCloseDeleteModal = () => {
setIsDeleteModalOpen(false);
closeModal();
};
useEffect(() => {
if (modaldata?.modalType === "delete") {
setIsDeleteModalOpen(true);
}
}, [modaldata]);
if (!modaldata?.modalType) {
closeModal();
if (!modaldata?.modalType || modaldata.modalType === "delete") {
return null;
}
if (modaldata.modalType === "delete" && isDeleteModalOpen) {
return (
<div
className="modal fade show"
tabIndex="-1"
role="dialog"
style={{ display: "block", backgroundColor: "rgba(0,0,0,0.5)" }}
aria-hidden="false"
>
<ConfirmModal
type="delete"
header={`Delete ${modaldata.masterType}`}
message="Are you sure you want delete?"
onSubmit={handleSelectedMasterDeleted}
onClose={handleCloseDeleteModal}
/>
</div>
);
}
const { modalType, item, masterType } = modaldata;
const renderModalContent = () => {
const { modalType, item, masterType } = modaldata;
const modalComponents = {
"Application Role": <CreateRole masmodalType={masterType} onClose={closeModal} />,
"Edit-Application Role": <EditRole master={modaldata} onClose={closeModal} />,
"Job Role": <CreateJobRole onClose={closeModal} />,
"Edit-Job Role": <EditJobRole data={item} onClose={closeModal} />,
"Activity": <CreateActivity onClose={closeModal} />,
"Edit-Activity": <EditActivity activityData={item} onClose={closeModal} />,
"Work Category": <CreateWorkCategory onClose={closeModal} />,
"Edit-Work Category": <EditWorkCategory data={item} onClose={closeModal} />,
"Contact Category": <CreateCategory data={item} onClose={closeModal} />,
"Edit-Contact Category": <EditContactCategory data={item} onClose={closeModal} />,
"Contact Tag": <CreateContactTag data={item} onClose={closeModal} />,
"Edit-Contact Tag": <EditContactTag data={item} onClose={closeModal} />,
"Expense Type":<ManageExpenseType onClose={closeModal} />,
"Edit-Expense Type":<ManageExpenseType data={item} onClose={closeModal} />,
"Payment Mode":<ManagePaymentMode onClose={closeModal}/>,
"Edit-Payment Mode":<ManagePaymentMode data={item} onClose={closeModal}/>,
"Expense Status":<ManageExpenseStatus onClose={closeModal}/>,
"Edit-Expense Status":<ManageExpenseStatus data={item} onClose={closeModal}/>
};
return modalComponents[modalType] || null;
const modalComponents = {
"Application Role": (
<CreateRole masmodalType={masterType} onClose={closeModal} />
),
"Edit-Application Role": (
<EditRole master={modaldata} onClose={closeModal} />
),
"Job Role": <CreateJobRole onClose={closeModal} />,
"Edit-Job Role": <EditJobRole data={item} onClose={closeModal} />,
"Activity": <CreateActivity onClose={closeModal} />,
"Edit-Activity": <EditActivity activityData={item} onClose={closeModal} />,
"Work Category": <CreateWorkCategory onClose={closeModal} />,
"Edit-Work Category": <EditWorkCategory data={item} onClose={closeModal} />,
"Contact Category": <CreateCategory data={item} onClose={closeModal} />,
"Edit-Contact Category": (
<EditContactCategory data={item} onClose={closeModal} />
),
"Contact Tag": <CreateContactTag data={item} onClose={closeModal} />,
"Edit-Contact Tag": <EditContactTag data={item} onClose={closeModal} />,
"Expense Type": <ManageExpenseType onClose={closeModal} />,
"Edit-Expense Type": <ManageExpenseType data={item} onClose={closeModal} />,
"Payment Mode": <ManagePaymentMode onClose={closeModal} />,
"Edit-Payment Mode": <ManagePaymentMode data={item} onClose={closeModal} />,
"Expense Status": <ManageExpenseStatus onClose={closeModal} />,
"Edit-Expense Status": (
<ManageExpenseStatus data={item} onClose={closeModal} />
),
"Document Category": <ManageDocumentCategory onClose={closeModal} />,
"Edit-Document Category": (
<ManageDocumentCategory data={item} onClose={closeModal} />
),
"Document Type": <ManageDocumentType onClose={closeModal} />,
"Edit-Document Type": (
<ManageDocumentType data={item} onClose={closeModal} />
),
};
const isLargeModal = ["Application Role", "Edit-Application Role"].includes(
modaldata.modalType
);
return (
<div
className="modal fade show"
id="master-modal"
tabIndex="-1"
role="dialog"
aria-hidden="true"
aria-labelledby="modalToggleLabel"
style={{ display: "block" }}
>
<div className={`modal-dialog mx-sm-auto mx-1 ${isLargeModal ? "modal-lg" : "modal-md"} modal-simple`}>
<div className="modal-content">
<div className="modal-body p-sm-4 p-0">
{/* ✅ Centered Heading */}
<div className="d-flex justify-content-between align-items-center">
<h5 className="modal-title w-100 text-center mb-0">
{modaldata?.modalType}
</h5>
<button
type="button"
className="btn-close position-absolute end-0 me-3"
data-bs-dismiss="modal"
aria-label="Close"
onClick={closeModal}
/>
</div>
{/* ✅ Render Modal Body */}
<div className="mt-3">{renderModalContent()}</div>
</div>
</div>
</div>
</div>
);
return modalComponents[modalType] || null;
};
export default MasterModal;

View File

@ -171,6 +171,56 @@ const {
return { ExpenseStatus, loading, error };
}
export const useDocumentTypes =(category)=>{
const {
data: DocumentTypes = [],
error,
isError,
isLoading
} = useQuery({
queryKey: ["Document Type",category],
queryFn: async () => {
const res = await MasterRespository.getDocumentTypes(category)
return res.data;
},
enabled:!!category,
onError: (error) => {
showToast(
error?.response?.data?.message ||
error.message ||
"Failed to fetch Expense Status",
"error"
);
},
});
return { DocumentTypes, isError, isLoading, error };
}
export const useDocumentCategories =(EntityType)=>{
const {
data: DocumentCategories = [],
error,
isError,
isLoading
} = useQuery({
queryKey: ["Document Category",EntityType],
queryFn: async () => {
const res = await MasterRespository.getDocumentCategories(EntityType)
return res.data;
},
enabled:!!EntityType,
onError: (error) => {
showToast(
error?.response?.data?.message ||
error.message ||
"Failed to fetch Expense Status",
"error"
);
},
});
return { DocumentCategories, isError, isLoading, error };
}
// ===Application Masters Query=================================================
const fetchMasterData = async (masterType) => {
@ -193,6 +243,10 @@ const fetchMasterData = async (masterType) => {
return (await MasterRespository.getPaymentMode()).data;
case "Expense Status":
return (await MasterRespository.getExpenseStatus()).data;
case "Document Type":
return (await MasterRespository.getDocumentTypes()).data;
case "Document Category":
return (await MasterRespository.getDocumentCategories()).data;
case "Status":
return [
{
@ -634,6 +688,7 @@ export const useUpdatePaymentMode = (onSuccessCallback)=>{
}
})
}
// -------------------Expense Status----------------------------------
export const useCreateExpenseStatus =(onSuccessCallback)=>{
const queryClient = useQueryClient();
@ -677,6 +732,100 @@ export const useUpdateExpenseStatus = (onSuccessCallback)=>{
}
})
}
// --------------------Document-Category--------------------------------
export const useCreateDocumentCatgory =(onSuccessCallback)=>{
const queryClient = useQueryClient();
return useMutation( {
mutationFn: async ( payload ) =>
{
const resp = await MasterRespository.createDocumenyCategory(payload);
return resp.data;
},
onSuccess: ( data ) =>
{
queryClient.invalidateQueries( {queryKey:[ "masterData", "Document Category" ]} )
queryClient.invalidateQueries( {queryKey:[ "Document Category" ]} )
showToast( "Document Category added successfully", "success" );
if(onSuccessCallback) onSuccessCallback(data)
},
onError: ( error ) =>
{
showToast(error.message || "Something went wrong", "error");
}
})
}
export const useUpdateDocumentCategory =(onSuccessCallback)=>{
const queryClient = useQueryClient();
return useMutation( {
mutationFn: async ( {id,payload} ) =>
{
const resp = await MasterRespository.updateDocumentCategory(id,payload);
return resp.data;
},
onSuccess: ( data ) =>
{
queryClient.invalidateQueries( {queryKey:[ "masterData", "Document Category" ]} )
queryClient.invalidateQueries( {queryKey:[ "Document Category" ]} )
showToast( "Document Category Updated successfully", "success" );
if(onSuccessCallback) onSuccessCallback(data)
},
onError: ( error ) =>
{
showToast(error.message || "Something went wrong", "error");
}
})
}
// ------------------------------Document-Type-----------------------------------
export const useCreateDocumentType =(onSuccessCallback)=>{
const queryClient = useQueryClient();
return useMutation( {
mutationFn: async ( payload ) =>
{
const resp = await MasterRespository.createDocumentType(payload);
return resp.data;
},
onSuccess: ( data ) =>
{
queryClient.invalidateQueries( {queryKey:[ "masterData", "Document Type" ]} )
showToast( "Document Type added successfully", "success" );
if(onSuccessCallback) onSuccessCallback(data)
},
onError: ( error ) =>
{
showToast(error.message || "Something went wrong", "error");
}
})
}
export const useUpdateDocumentType =(onSuccessCallback)=>{
const queryClient = useQueryClient();
return useMutation( {
mutationFn: async ( {id,payload} ) =>
{
const resp = await MasterRespository.updateDocumentType(id,payload);
return resp.data;
},
onSuccess: ( data ) =>
{
queryClient.invalidateQueries( {queryKey:[ "masterData", "Document Type" ]} )
showToast( "Document Type Updated successfully", "success" );
if(onSuccessCallback) onSuccessCallback(data)
},
onError: ( error ) =>
{
showToast(error.message || "Something went wrong", "error");
}
})
}
// -Delete Master --------
export const useDeleteMasterItem = () => {
const queryClient = useQueryClient();

204
src/hooks/useDocument.js Normal file
View File

@ -0,0 +1,204 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import showToast from "../services/toastService";
import { DocumentRepository } from "../repositories/DocumentRepository";
// ----------------------Query-------------------------------
const cleanFilter = (filter) => {
const cleaned = { ...filter };
[
"uploadedByIds",
"documentCategoryIds",
"documentTypeIds",
"documentTagIds",
].forEach((key) => {
if (Array.isArray(cleaned[key]) && cleaned[key].length === 0) {
delete cleaned[key];
}
});
["startDate", "endDate", "isVerified"].forEach((key) => {
if (cleaned[key] === null) {
delete cleaned[key];
}
});
return cleaned;
};
export const useDocumentListByEntityId = (
entityTypeId,
entityId,
pageSize,
pageNumber,
filter,
searchString = "",
isActive
) => {
return useQuery({
queryKey: [
"DocumentList",
entityTypeId,
entityId,
pageSize,
pageNumber,
filter,
searchString,
isActive
],
queryFn: async () => {
const cleanedFilter = cleanFilter(filter);
const resp = await DocumentRepository.getDocumentList(
entityTypeId,
entityId,
pageSize,
pageNumber,
cleanedFilter,
searchString,
isActive
);
return resp.data
},
enabled: !!entityTypeId && !!entityId,
});
};
export const useDocumentFilterEntities = (entityTypeId) => {
return useQuery({
queryKey: ["DFilter", entityTypeId],
queryFn: async () =>
await DocumentRepository.getFilterEntities(entityTypeId),
});
};
export const useDocumentDetails = (documentId) => {
return useQuery({
queryKey: ["Document", documentId],
queryFn: async () => {
const resp = await DocumentRepository.getDocumentById(documentId);
return resp.data;
},
enabled: !!documentId,
});
};
export const useDocumentVersionList = (parentAttachmentId,pageSize,pageNumber) => {
return useQuery({
queryKey: ["DocumentVersionList", parentAttachmentId,pageSize,pageNumber],
queryFn: async () => {
const resp = await DocumentRepository.getDocumentVersionList(parentAttachmentId,pageSize,pageNumber);
return resp.data
},
enabled: !!parentAttachmentId,
});
};
export const useDocumentVersion = (id)=>{
return useQuery({
queryKey:["DocumentVersion",id],
queryFn:async()=> await DocumentRepository.getDocumentVersion(id),
enabled:!!id
})
}
export const useDocumentTags =()=>{
return useQuery({
queryKey:["DocumentTag"],
queryFn:async()=> {const resp = await DocumentRepository.getDocumentTags()
return resp.data
}
})
}
//----------------------- MUTATION -------------------------
export const useUploadDocument = (onSuccessCallBack) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (DocumentPayload) =>
DocumentRepository.uploadDocument(DocumentPayload),
onSuccess: (data, variables) => {
queryClient.invalidateQueries({ queryKey: ["DocumentList"] });
if (onSuccessCallBack) onSuccessCallBack();
},
onError: (error) => {
console.log(error);
showToast(
error.response.data.message ||
"Something went wrong please try again !",
"error"
);
},
});
};
export const useUpdateDocument = (onSuccessCallBack) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ documentId, DocumentPayload }) =>
DocumentRepository.UpdateDocument(documentId, DocumentPayload),
onSuccess: (data, variables) => {
const { documentId } = variables;
queryClient.invalidateQueries({ queryKey: ["DocumentList"] });
queryClient.invalidateQueries({ queryKey: ["Document", documentId] });
if (onSuccessCallBack) onSuccessCallBack();
},
onError: (error) => {
console.log(error);
showToast(
error.response.data.message ||
"Something went wrong please try again !",
"error"
);
},
});
};
export const useVerifyDocument = ()=>{
const queryClient = useQueryClient();
return useMutation({
mutationFn:async({documentId,isVerify}) => await DocumentRepository.verifyDocument(documentId,isVerify),
onSuccess: (data, variables) => {
queryClient.invalidateQueries({ queryKey: ["DocumentVersionList"] });
queryClient.invalidateQueries({ queryKey: ["DocumentList"] });
queryClient.invalidateQueries({ queryKey: ["Document"] });
showToast(
data.response.data.message ||
"Document Successfully Verified !",
"success"
);
},
onError: (error) => {
showToast(
error.response.data.message ||
"Something went wrong please try again !",
"error"
);
},
})
}
export const useActiveInActiveDocument = ()=>{
const queryClient = useQueryClient();
return useMutation({
mutationFn:async({documentId,isActive}) => await DocumentRepository.deleteDocument(documentId,isActive),
onSuccess: (data, variables) => {
queryClient.invalidateQueries({ queryKey: ["DocumentList"] });
showToast(
data.response.data.message ||
"Document Successfully Verified !",
"success"
);
},
onError: (error) => {
showToast(
error.response.data.message ||
"Something went wrong please try again !",
"error"
);
},
})
}

View File

@ -14,7 +14,6 @@ import {
} from "@tanstack/react-query";
import showToast from "../services/toastService";
// ------------------------------Query-------------------
export const useProjects = () => {
@ -153,7 +152,7 @@ export const useProjectName = () => {
isLoading,
error,
refetch,
isError
isError,
} = useQuery({
queryKey: ["basicProjectNameList"],
queryFn: async () => {
@ -164,7 +163,13 @@ export const useProjectName = () => {
showToast(error.message || "Error while Fetching project Name", "error");
},
});
return { projectNames: data, loading: isLoading, Error: error, refetch,isError };
return {
projectNames: data,
loading: isLoading,
Error: error,
refetch,
isError,
};
};
export const useProjectInfra = (projectId) => {
@ -175,7 +180,7 @@ export const useProjectInfra = (projectId) => {
} = useQuery({
queryKey: ["ProjectInfra", projectId],
queryFn: async () => {
if(!projectId) return null;
if (!projectId) return null;
const res = await ProjectRepository.getProjectInfraByproject(projectId);
return res.data;
},
@ -207,12 +212,7 @@ export const useProjectTasks = (workAreaId, IsExpandedArea = false) => {
return { ProjectTaskList, isLoading, error };
};
export const useProjectTasksByEmployee = (
employeeId,
fromDate,
toDate,
) => {
export const useProjectTasksByEmployee = (employeeId, fromDate, toDate) => {
return useQuery({
queryKey: ["TasksByEmployee", employeeId],
queryFn: async () => {
@ -230,6 +230,43 @@ export const useProjectTasksByEmployee = (
});
};
export const useProjectLevelEmployeeList = (ProjectId) => {
return useQuery({
queryKey: ["ProjectLevelEmployeeList", ProjectId],
queryFn: async () => {
const resp = await ProjectRepository.getProjectLevelEmployeeList(
ProjectId
);
return resp.data;
},
enabled: !!ProjectId,
});
};
export const useProjectLevelModules = () => {
return useQuery({
queryKey: ["ProjectLevelModules"],
queryFn: async () => {
const resp = await ProjectRepository.getProjectLevelModules();
return resp.data;
},
});
};
export const useProjectLevelEmployeePermission = (employeeId, projectId) => {
return useQuery({
queryKey: ["ProjectLevelEmployeePermission", employeeId, projectId],
queryFn: async () => {
const resp = await ProjectRepository.getProjectLevelEmployeePermissions(
employeeId,
projectId
);
return resp.data;
},
enabled: !!employeeId && !!projectId,
});
};
// -- -------------Mutation-------------------------------
export const useCreateProject = ({ onSuccessCallback }) => {
@ -558,3 +595,26 @@ export const useDeleteProjectTask = (onSuccessCallback) => {
},
});
};
export const useUpdateProjectLevelEmployeePermission = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (payload) =>
await ProjectRepository.updateProjectLevelEmployeePermission(payload),
onSuccess: (data, variables, context) => {
queryClient.invalidateQueries({
queryKey: ["ProjectLevelEmployeePermission"],
});
showToast("Permission Updated successfully", "success");
},
onError: (error) => {
showToast(
error?.response?.data?.message ||
error.message ||
"Failed to delete task",
"error"
);
if (onSuccessCallback) onSuccessCallback();
},
});
};

View File

@ -301,25 +301,15 @@ const Directory = ({ IsPage = true, prefernceContacts }) => {
</GlobalModel>
)}
{deleteContact && (
<div
className={`modal fade ${deleteContact ? "show" : ""}`}
tabIndex="-1"
role="dialog"
style={{
display: deleteContact ? "block" : "none",
backgroundColor: deleteContact ? "rgba(0,0,0,0.5)" : "transparent",
}}
aria-hidden="false"
>
<ConfirmModal
type={"delete"}
header={"Delete Contact"}
message={"Are you sure you want delete?"}
onSubmit={handleDeleteContact}
onClose={() => setDeleteContact(null)}
loading={IsDeleting}
/>
</div>
<ConfirmModal
isOpen={!!deleteContact}
type="delete"
header="Delete Contact"
message="Are you sure you want delete?"
onSubmit={handleDeleteContact}
onClose={() => setDeleteContact(null)}
loading={IsDeleting}
/>
)}
{openBucketModal && (
@ -383,12 +373,14 @@ const Directory = ({ IsPage = true, prefernceContacts }) => {
{/* Empty state AFTER list */}
{!loading && contacts?.length === 0 && (
<p className="mt-3 ms-3 text-muted" >No contact found</p>
<p className="mt-3 ms-3 text-muted">No contact found</p>
)}
{!loading &&
contacts?.length > 0 &&
currentItems.length === 0 && (
<p className="mt-3 ms-3 text-muted">No matching contact found</p>
<p className="mt-3 ms-3 text-muted">
No matching contact found
</p>
)}
</div>
</div>
@ -419,11 +411,9 @@ const Directory = ({ IsPage = true, prefernceContacts }) => {
{!loading && contacts?.length === 0 && (
<p className="mt-3 ms-3 text-muted">No contact found</p>
)}
{!loading &&
contacts?.length > 0 &&
currentItems.length === 0 && (
<p className="mt-3 ms-3 text-muted">No matching contact found</p>
)}
{!loading && contacts?.length > 0 && currentItems.length === 0 && (
<p className="mt-3 ms-3 text-muted">No matching contact found</p>
)}
</div>
)}
@ -446,7 +436,9 @@ const Directory = ({ IsPage = true, prefernceContacts }) => {
currentItems.length > ITEMS_PER_PAGE && (
<nav aria-label="Page navigation">
<ul className="pagination pagination-sm justify-content-end py-1">
<li className={`page-item ${currentPage === 1 ? "disabled" : ""}`}>
<li
className={`page-item ${currentPage === 1 ? "disabled" : ""}`}
>
<button
className="page-link btn-xs"
onClick={() => paginate(currentPage - 1)}
@ -458,8 +450,9 @@ const Directory = ({ IsPage = true, prefernceContacts }) => {
{[...Array(totalPages)].map((_, index) => (
<li
key={index}
className={`page-item ${currentPage === index + 1 ? "active" : ""
}`}
className={`page-item ${
currentPage === index + 1 ? "active" : ""
}`}
>
<button
className="page-link"
@ -471,8 +464,9 @@ const Directory = ({ IsPage = true, prefernceContacts }) => {
))}
<li
className={`page-item ${currentPage === totalPages ? "disabled" : ""
}`}
className={`page-item ${
currentPage === totalPages ? "disabled" : ""
}`}
>
<button
className="page-link"
@ -489,4 +483,4 @@ const Directory = ({ IsPage = true, prefernceContacts }) => {
);
};
export default Directory;
export default Directory;

View File

@ -0,0 +1,41 @@
import React from 'react'
import Breadcrumb from '../../components/common/Breadcrumb'
const DocumentPage = () => {
return (
<div className=''>
<div className="card d-flex p-2">
<div className="row align-items-center">
{/* Search */}
<div className="col-6 col-md-6 col-lg-3 mb-md-0">
<input
type="search"
className="form-control form-control-sm"
placeholder="Search Document"
/>
</div>
{/* Actions */}
<div className="col-6 col-md-6 col-lg-9 text-end">
<span className="text-tiny text-muted p-1 border-0 bg-none lead mx-3 cursor-pointer">
Refresh
< i className={`bx bx-refresh ms-1 `}></i>
</span>
<button
type="button"
title="Add New Document"
className="p-1 bg-primary rounded-circle cursor-pointer"
>
<i className="bx bx-plus fs-4 text-white"></i>
</button>
</div>
</div>
</div>
</div>
)
}
export default DocumentPage

View File

@ -85,6 +85,14 @@ const LoginPage = () => {
navigate("/auth/login-otp");
}
}, [IsLoginWithOTP]);
// useEffect(() => {
// const token = localStorage.getItem("jwtToken");
// if (token) {
// navigate("/dashboard");
// }
// }, [navigate]);
return (
<AuthWrapper>
<h4 className="mb-2">Welcome to PMS!</h4>

View File

@ -177,10 +177,12 @@ const EmployeeList = () => {
useEffect(() => {
if (!loading && Array.isArray(employees)) {
const sorted = [...employees].sort((a, b) => {
const nameA = `${a.firstName || ""}${a.middleName || ""}${a.lastName || ""
}`.toLowerCase();
const nameB = `${b.firstName || ""}${b.middleName || ""}${b.lastName || ""
}`.toLowerCase();
const nameA = `${a.firstName || ""}${a.middleName || ""}${
a.lastName || ""
}`.toLowerCase();
const nameB = `${b.firstName || ""}${b.middleName || ""}${
b.lastName || ""
}`.toLowerCase();
return nameA?.localeCompare(nameB);
});
@ -259,37 +261,26 @@ const EmployeeList = () => {
)}
{IsDeleteModalOpen && (
<div
className={`modal fade ${IsDeleteModalOpen ? "show" : ""}`}
tabIndex="-1"
role="dialog"
style={{
display: IsDeleteModalOpen ? "block" : "none",
backgroundColor: IsDeleteModalOpen
? "rgba(0,0,0,0.5)"
: "transparent",
}}
aria-hidden="false"
>
<ConfirmModal
type={"delete"}
header={
selectedEmpFordelete?.isActive
? "Suspend Employee"
: "Reactivate Employee"
}
message={`Are you sure you want to ${selectedEmpFordelete?.isActive ? "suspend" : "reactivate"
} this employee?`}
onSubmit={() =>
suspendEmployee({
employeeId: selectedEmpFordelete.id,
active: !selectedEmpFordelete.isActive,
})
}
onClose={() => setIsDeleteModalOpen(false)}
loading={employeeLodaing}
/>
</div>
<ConfirmModal
isOpen={IsDeleteModalOpen}
type="delete"
header={
selectedEmpFordelete?.isActive
? "Suspend Employee"
: "Reactivate Employee"
}
message={`Are you sure you want to ${
selectedEmpFordelete?.isActive ? "suspend" : "reactivate"
} this employee?`}
onSubmit={() =>
suspendEmployee({
employeeId: selectedEmpFordelete.id,
active: !selectedEmpFordelete.isActive,
})
}
onClose={() => setIsDeleteModalOpen(false)}
loading={employeeLodaing}
/>
)}
<div className="container-fluid">
@ -508,8 +499,9 @@ const EmployeeList = () => {
Status
</th>
<th
className={`sorting_disabled ${!Manage_Employee && "d-none"
}`}
className={`sorting_disabled ${
!Manage_Employee && "d-none"
}`}
rowSpan="1"
colSpan="1"
style={{ width: "50px" }}
@ -529,9 +521,9 @@ const EmployeeList = () => {
)}
{/* Conditional messages for no data or no search results */}
{!loading &&
displayData?.length === 0 &&
searchText &&
!showAllEmployees ? (
displayData?.length === 0 &&
searchText &&
!showAllEmployees ? (
<tr>
<td colSpan={8}>
<small className="muted">
@ -541,8 +533,8 @@ const EmployeeList = () => {
</tr>
) : null}
{!loading &&
displayData?.length === 0 &&
(!searchText || showAllEmployees) ? (
displayData?.length === 0 &&
(!searchText || showAllEmployees) ? (
<tr>
<td
colSpan={8}
@ -636,7 +628,9 @@ const EmployeeList = () => {
<div className="dropdown-menu dropdown-menu-end">
{/* View always visible */}
<button
onClick={() => navigate(`/employee/${item.id}`)}
onClick={() =>
navigate(`/employee/${item.id}`)
}
className="dropdown-item py-1"
>
<i className="bx bx-show text-primary bx-sm"></i> View
@ -647,7 +641,9 @@ const EmployeeList = () => {
<>
<button
className="dropdown-item py-1"
onClick={() => handleEmployeeModel(item.id)}
onClick={() =>
handleEmployeeModel(item.id)
}
>
<i className="bx bx-edit text-secondary bx-sm"></i> Edit
</button>
@ -667,11 +663,13 @@ const EmployeeList = () => {
type="button"
data-bs-toggle="modal"
data-bs-target="#managerole-modal"
onClick={() => setEmpForManageRole(item.id)}
onClick={() =>
setEmpForManageRole(item.id)
}
>
<i className="bx bx-cog bx-sm"></i> Manage Role
<i className="bx bx-cog bx-sm"></i>{" "}
Manage Role
</button>
</>
)}
@ -700,8 +698,9 @@ const EmployeeList = () => {
<nav aria-label="Page">
<ul className="pagination pagination-sm justify-content-end py-1">
<li
className={`page-item ${currentPage === 1 ? "disabled" : ""
}`}
className={`page-item ${
currentPage === 1 ? "disabled" : ""
}`}
>
<button
className="page-link btn-xs"
@ -714,8 +713,9 @@ const EmployeeList = () => {
{[...Array(totalPages)]?.map((_, index) => (
<li
key={index}
className={`page-item ${currentPage === index + 1 ? "active" : ""
}`}
className={`page-item ${
currentPage === index + 1 ? "active" : ""
}`}
>
<button
className="page-link"
@ -727,8 +727,9 @@ const EmployeeList = () => {
))}
<li
className={`page-item ${currentPage === totalPages ? "disabled" : ""
}`}
className={`page-item ${
currentPage === totalPages ? "disabled" : ""
}`}
>
<button
className="page-link"

View File

@ -4,43 +4,45 @@ import MasterModal from "../../components/master/MasterModal";
import { mastersList } from "../../data/masters";
import { useDispatch, useSelector } from "react-redux";
import { changeMaster } from "../../slices/localVariablesSlice";
import useMaster, { useMasterMenu } from "../../hooks/masterHook/useMaster"
import useMaster, {
useDeleteMasterItem,
useMasterMenu,
} from "../../hooks/masterHook/useMaster";
import MasterTable from "./MasterTable";
import { getCachedData } from "../../slices/apiDataManager";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { MANAGE_MASTER } from "../../utils/constants";
import { useQueryClient } from "@tanstack/react-query";
import GlobalModel from "../../components/common/GlobalModel";
import ConfirmModal from "../../components/common/ConfirmModal";
const MasterPage = () => {
const {data,isLoading,isError,error:menuError} = useMasterMenu()
const [modalConfig, setModalConfig] = useState({ modalType: "", item: null, masterType: null });
const [searchTerm, setSearchTerm] = useState('');
const { data, isLoading, isError, error: menuError } = useMasterMenu();
const [modalConfig, setModalConfig] = useState(null);
const [searchTerm, setSearchTerm] = useState("");
const [filteredResults, setFilteredResults] = useState([]);
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
const hasMasterPermission = useHasUserPermission(MANAGE_MASTER);
const dispatch = useDispatch();
const selectedMaster = useSelector((store) => store.localVariables.selectedMaster);
const selectedMaster = useSelector(
(store) => store.localVariables.selectedMaster
);
const queryClient = useQueryClient();
const { data: masterData = [], loading, error, RecallApi,isError:isMasterError } = useMaster();
const {
data: masterData = [],
loading,
error,
RecallApi,
isError: isMasterError,
} = useMaster();
const { mutate: deleteMasterItem, isPending } = useDeleteMasterItem();
const openModal = () => setIsCreateModalOpen(true);
const closeModal = () => {
setIsCreateModalOpen(false);
setModalConfig(null);
// Clean up Bootstrap modal manually
const modalEl = document.getElementById('master-modal');
modalEl?.classList.remove('show');
if (modalEl) modalEl.style.display = 'none';
document.body.classList.remove('modal-open');
document.body.style.overflow = 'auto';
document.querySelectorAll('.modal-backdrop').forEach((el) => el.remove());
};
const handleModalData = (modalType, item, masterType = selectedMaster) => {
@ -54,15 +56,17 @@ const MasterPage = () => {
if (!masterData?.length) return;
const results = masterData.filter((item) =>
Object.values(item).some(
(field) => field?.toString().toLowerCase().includes(value)
Object.values(item).some((field) =>
field?.toString().toLowerCase().includes(value)
)
);
setFilteredResults(results);
};
const displayData = useMemo(() => {
if (searchTerm) return filteredResults;
return queryClient.getQueryData(["masterData", selectedMaster]) || masterData;
return (
queryClient.getQueryData(["masterData", selectedMaster]) || masterData
);
}, [searchTerm, filteredResults, selectedMaster, masterData]);
const columns = useMemo(() => {
@ -73,9 +77,12 @@ const MasterPage = () => {
}));
}, [displayData]);
useEffect(() => {
if (modalConfig) openModal();
}, [modalConfig]);
useEffect(() => {
if (modalConfig?.modalType && modalConfig?.modalType !== "delete") {
openModal();
}
}, [modalConfig]);
useEffect(() => {
return () => {
@ -84,15 +91,46 @@ const MasterPage = () => {
};
}, []);
if(isError || isMasterError) return <div className="d-flex flex-column align-items-center justify-content-center py-5">
<h4 className=" mb-3"><i className="fa-solid fa-triangle-exclamation fs-5" /> Oops, an error occurred</h4>
<p className="text-muted">{error?.message || menuError?.message}</p>
</div>
if (isError || isMasterError)
return (
<div className="d-flex flex-column align-items-center justify-content-center py-5">
<h4 className=" mb-3">
<i className="fa-solid fa-triangle-exclamation fs-5" /> Oops, an error
occurred
</h4>
<p className="text-muted">{error?.message || menuError?.message}</p>
</div>
);
return (
<>
{isCreateModalOpen && (
<MasterModal modaldata={modalConfig} closeModal={closeModal} />
{modalConfig?.modalType === "delete" && (
<ConfirmModal
type="delete"
header={`Delete ${modalConfig.masterType}`}
message="Are you sure you want to delete?"
onSubmit={() => {
deleteMasterItem(
{
masterType: modalConfig.masterType,
item: modalConfig.item,
validateFn: modalConfig.validateFn,
},
{ onSuccess: closeModal }
);
}}
onClose={closeModal}
loading={isPending}
isOpen={true}
/>
)}
{isCreateModalOpen && modalConfig?.modalType !== "delete" && (
<GlobalModel
isOpen={isCreateModalOpen}
closeModal={closeModal}
size={modalConfig?.masterType === "Application Role" ? "lg" : "md"}
>
<MasterModal modaldata={modalConfig} closeModal={closeModal} />
</GlobalModel>
)}
<div className="container-fluid">
@ -119,15 +157,20 @@ const MasterPage = () => {
>
<label>
<select
onChange={(e) => dispatch(changeMaster(e.target.value))}
onChange={(e) =>
dispatch(changeMaster(e.target.value))
}
name="DataTables_Table_0_length"
aria-controls="DataTables_Table_0"
className="form-select py-1 px-2"
style={{ fontSize: "0.875rem", height: "32px", width: "170px" }}
value={selectedMaster}
>
{isLoading && <option value="">Loading...</option>}
{isLoading && (
<option value={null}>Loading...</option>
)}
{!isLoading &&
data &&
data?.map((item) => (
<option key={item.id} value={item.name}>
{item.name}
@ -155,10 +198,13 @@ const MasterPage = () => {
></input>
</label>
</div>
<div className={`dt-buttons btn-group flex-wrap ${!hasMasterPermission && 'd-none'}`}>
<div
className={`dt-buttons btn-group flex-wrap ${
!hasMasterPermission && "d-none"
}`}
>
{" "}
<div className="input-group">
<button
className={`btn btn-sm add-new btn-primary `}
tabIndex="0"
@ -167,13 +213,17 @@ const MasterPage = () => {
data-bs-toggle="modal"
data-bs-target="#master-modal"
onClick={() => {
handleModalData(selectedMaster, "null", selectedMaster)
handleModalData(
selectedMaster,
null,
selectedMaster
);
}}
>
<span>
<i className="bx bx-plus-circle me-2"></i>
<span className=" d-sm-inline-block">
Add {selectedMaster}
Add {selectedMaster}
</span>
</span>
</button>{" "}
@ -183,13 +233,17 @@ const MasterPage = () => {
</div>
</div>
<MasterTable data={displayData} columns={columns} loading={loading} handleModalData={handleModalData} />
<MasterTable
data={displayData}
columns={columns}
loading={loading}
handleModalData={handleModalData}
/>
<div style={{ width: "1%" }}></div>
</div>
</div>
</div>
</div>
</div>
</>
);

View File

@ -20,7 +20,14 @@ const MasterTable = ({ data, columns, loading, handleModalData }) => {
"noOfPersonsRequired",
"color",
"displayName",
"permissionIds"
"permissionIds",
"entityTypeId",
"regexExpression",
"isMandatory",
"maxFilesAllowed",
"maxSizeAllowedInMB",
"isValidationRequired",
"documentCategory"
];
const safeData = Array.isArray(data) ? data : [];
@ -75,17 +82,16 @@ const MasterTable = ({ data, columns, loading, handleModalData }) => {
{loading ? (
<p>Loading...</p>
) : (
<table
className="datatables-users table border-top dataTable no-footer dtr-column"
id="DataTables_Table_0"
aria-describedby="DataTables_Table_0_info"
style={{ width: "100%" }}
>
<thead>
<table className="datatables-users table border-top dataTable no-footer dtr-column w-100">
<thead className="shadow-sm">
<tr>
<th></th>
<th className="text-start"> {selectedMaster === "Activity" ? "Activity" : "Name"}</th>
<th className="text-start"> {selectedMaster === "Activity" ? "Unit" : "Description"}</th>
<th className="text-start"> {selectedMaster === "Activity"
? "Unit"
: selectedMaster === "Document Type"
? "Content Type"
: "Description"}</th>
<th className={` ${!hasMasterPermission && "d-none"}`}>
Actions
</th>
@ -151,19 +157,17 @@ const MasterTable = ({ data, columns, loading, handleModalData }) => {
data-bs-target="#master-modal"
className="btn p-0 dropdown-toggle hide-arrow"
onClick={() =>
handleModalData(`Edit-${selectedMaster}`, item)
handleModalData(`Edit-${selectedMaster}`, item, selectedMaster)
}
>
<i className="bx bxs-edit me-2 text-primary"></i>
</button>
<button
aria-label="Delete"
type="button"
className="btn p-0 dropdown-toggle hide-arrow"
data-bs-toggle="modal"
data-bs-target="#master-modal"
onClick={() => handleModalData("delete", item)}
aria-label="Delete"
type="button"
className="btn p-0 dropdown-toggle hide-arrow"
onClick={() => handleModalData("delete", item, selectedMaster)}
>
<i className="bx bx-trash me-1 text-danger"></i>
</button>

View File

@ -16,9 +16,7 @@ import {
useSelectedProject,
} from "../../slices/apiDataManager";
import "./ProjectDetails.css";
import {
useProjectDetails,
} from "../../hooks/useProjects";
import { useProjectDetails } from "../../hooks/useProjects";
import { ComingSoonPage } from "../Misc/ComingSoonPage";
import Directory from "../Directory/Directory";
import eventBus from "../../services/eventBus";
@ -26,19 +24,22 @@ import ProjectProgressChart from "../../components/Dashboard/ProjectProgressChar
import { useProjectName } from "../../hooks/useProjects";
import AttendanceOverview from "../../components/Dashboard/AttendanceChart";
import { setProjectId } from "../../slices/localVariablesSlice";
import ProjectDocument from "../../components/Project/ProjectDocuments";
import ProjectDocuments from "../../components/Project/ProjectDocuments";
import ProjectSetting from "../../components/Project/ProjectSetting";
const ProjectDetails = () => {
const projectId = useSelectedProject()
const { projectNames, fetchData } = useProjectName();
const dispatch = useDispatch()
const dispatch = useDispatch();
useEffect(() => {
if (projectId == null) {
dispatch(setProjectId(projectNames[0]?.id));
}
}, [projectNames])
}, [projectNames]);
const {
projects_Details,
@ -49,12 +50,15 @@ const ProjectDetails = () => {
// const [activePill, setActivePill] = useState("profile");
const [activePill, setActivePill] = useState(() => {
return localStorage.getItem("lastActiveProjectTab") || "profile";
});
return localStorage.getItem("lastActiveProjectTab") || "profile";
});
const handler = useCallback(
(msg) => {
if (msg.keyword === "Update_Project" && projects_Details?.id === msg.response.id) {
if (
msg.keyword === "Update_Project" &&
projects_Details?.id === msg.response.id
) {
refetch();
}
},
@ -66,11 +70,10 @@ const ProjectDetails = () => {
return () => eventBus.off("project", handler);
}, [handler]);
const handlePillClick = (pillKey) => {
setActivePill(pillKey);
localStorage.setItem("lastActiveProjectTab", pillKey); // Save to localStorage
};
const handlePillClick = (pillKey) => {
setActivePill(pillKey);
localStorage.setItem("lastActiveProjectTab", pillKey); // Save to localStorage
};
const renderContent = () => {
if (projectLoading || !projects_Details) return <Loader />;
@ -84,10 +87,15 @@ const ProjectDetails = () => {
<AboutProject></AboutProject>
<ProjectOverview project={projectId} />
</div>
<div className="col-lg-8 col-md-7 mt-2">
<ProjectProgressChart ShowAllProject="false" DefaultRange="1M" />
<div className="mt-4"> <AttendanceOverview /></div>
<div className="col-lg-8 col-md-7 mt-5">
<ProjectProgressChart
ShowAllProject="false"
DefaultRange="1M"
/>
<div className="mt-5">
{" "}
<AttendanceOverview />
</div>
</div>
</div>
</>
@ -103,14 +111,10 @@ const ProjectDetails = () => {
);
case "infra":
return (
<ProjectInfra data={projects_Details} onDataChange={refetch} />
);
return <ProjectInfra data={projects_Details} onDataChange={refetch} />;
case "workplan":
return (
<WorkPlan data={projects_Details} onDataChange={refetch} />
);
return <WorkPlan data={projects_Details} onDataChange={refetch} />;
case "directory":
return (
@ -118,6 +122,18 @@ const ProjectDetails = () => {
<Directory IsPage={false} prefernceContacts={projects_Details.id} />
</div>
);
case "documents":
return (
<div className="row">
<ProjectDocuments />
</div>
);
case "setting":
return (
<div className="row">
<ProjectSetting />
</div>
);
default:
return <ComingSoonPage />;
@ -142,4 +158,4 @@ const ProjectDetails = () => {
);
};
export default ProjectDetails;
export default ProjectDetails;

View File

@ -0,0 +1,26 @@
import { api } from "../utils/axiosClient";
export const DocumentRepository = {
uploadDocument:(data)=> api.post(`/api/Document/upload`,data),
getDocumentList:(entityTypeId,entityId,pageSize, pageNumber, filter,searchString,isActive)=>{
const payloadJsonString = JSON.stringify(filter);
return api.get(`/api/Document/list/${entityTypeId}/entity/${entityId}/?pageSize=${pageSize}&pageNumber=${pageNumber}&filter=${payloadJsonString}&searchString=${searchString}&isActive=${isActive}`)
},
getDocumentById:(id)=>api.get(`/api/Document/get/details/${id}`),
getFilterEntities:(entityTypeId)=>api.get(`/api/Document/get/filter/${entityTypeId}`),
UpdateDocument:(documentId,data)=>api.put(`/api/Document/edit/${documentId}`,data),
getDocumentVersionList:(parentAttachmentId,pageSize,pageNumber)=>api.get(`/api/Document/list/versions/${parentAttachmentId}/?pageSize=${pageSize}&pageNumber=${pageNumber}`),
getDocumentVersion:(id)=>api.get(`/api/Document/get/version/${id}`),
verifyDocument:(id,isVerify)=>api.post(`/api/Document/verify/${id}/?isVerify=${isVerify}`),
deleteDocument:(id,isActive)=>api.delete(`/api/Document/delete/${id}/?isActive=${isActive}`),
getDocumentTags:()=>api.get('/api/Document/get/tags')
}

View File

@ -18,7 +18,7 @@ export const RolesRepository = {
};
export const MasterRespository = {
getMasterMenus:()=>api.get("/api/AppMenu/get/master-list"),
getMasterMenus: () => api.get("/api/AppMenu/get/master-list"),
getRoles: () => api.get("/api/roles"),
createRole: (data) => api.post("/api/roles", data),
@ -48,6 +48,9 @@ export const MasterRespository = {
api.delete(`/api/Master/payment-mode/delete/${id}`, (isActive = false)),
"Expense Status": (id, isActive) =>
api.delete(`/api/Master/expenses-status/delete/${id}`, (isActive = false)),
"Document Type": (id) => api.delete(`/api/Master/document-type/delete/${id}`),
"Document Category": (id) =>
api.delete(`/api/Master/document-category/delete/${id}`),
getWorkCategory: () => api.get(`/api/master/work-categories`),
createWorkCategory: (data) => api.post(`/api/master/work-category`, data),
@ -58,7 +61,7 @@ export const MasterRespository = {
createContactCategory: (data) =>
api.post(`/api/master/contact-category`, data),
updateContactCategory: (id, data) =>
api.post(`/api/master/contact-category/edit/${id}`, data),
api.put(`/api/master/contact-category/edit/${id}`, data),
getContactTag: () => api.get(`/api/master/contact-tags`),
createContactTag: (data) => api.post(`/api/master/contact-tag`, data),
@ -81,4 +84,26 @@ export const MasterRespository = {
createExpenseStatus: (data) => api.post("/api/Master/expenses-status", data),
updateExepnseStatus: (id, data) =>
api.put(`/api/Master/expenses-status/edit/${id}`, data),
getDocumentCategories: (entityType) =>
api.get(
`/api/Master/document-category/list${
entityType ? `?entityTypeId=${entityType}` : ""
}`
),
createDocumenyCategory: (data) =>
api.post(`/api/Master/document-category`, data),
updateDocumentCategory: (id, data) =>
api.put(`/api/Master/document-category/edit/${id}`, data),
getDocumentTypes: (category) =>
api.get(
`/api/Master/document-type/list${
category ? `?documentCategoryId=${category}` : ""
}`
),
createDocumentType: (data) => api.post(`/api/Master/document-type`, data),
updateDocumentType: (id, data) =>
api.put(`/api/Master/document-type/edit/${id}`, data),
};

View File

@ -37,6 +37,14 @@ const ProjectRepository = {
api.get(
`/api/project/tasks-employee/${id}?fromDate=${fromDate}&toDate=${toDate}`
),
// Permission Managment for Employee at Project Level
getProjectLevelEmployeeList:(projectId)=>api.get(`/api/Project/get/proejct-level/employees/${projectId}`),
getProjectLevelModules:()=>api.get(`/api/Project/get/proejct-level/modules`),
getProjectLevelEmployeePermissions:(employeeId,projectId)=>api.get(`/api/Project/get/project-level-permission/employee/${employeeId}/project/${projectId}`),
updateProjectLevelEmployeePermission:(data)=>api.post(`/api/Project/assign/project-level-permission`,data)
};
export const TasksRepository = {

View File

@ -44,6 +44,7 @@ import ExpensePage from "../pages/Expense/ExpensePage";
import TenantDetails from "../pages/Tenant/TenantDetails";
import SelfTenantDetails from "../pages/Tenant/SelfTenantDetails";
import SuperTenantDetails from "../pages/Tenant/SuperTenantDetails";
import DocumentPage from "../pages/Documents/DocumentPage";
const router = createBrowserRouter(
[
@ -69,6 +70,7 @@ const router = createBrowserRouter(
{ path: "/", element: <Dashboard /> },
{ path: "/dashboard", element: <Dashboard /> },
{ path: "/projects", element: <ProjectList /> },
{ path: "/document", element: <DocumentPage /> },
{ path: "/projects/details", element: <ProjectDetails /> },
{ path: "/project/manage/:projectId", element: <ManageProject /> },
{ path: "/employees", element: <EmployeeList /> },

26
src/utils/FileIcon.jsx Normal file
View File

@ -0,0 +1,26 @@
const contentTypeIcons = {
"application/pdf": "fa-solid fa-file-pdf text-danger",
"application/msword": "fa-solid fa-file-word text-primary",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document":
"fa-solid fa-file-word text-primary",
"application/vnd.ms-excel": "fa-solid fa-file-excel text-success",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
"fa-solid fa-file-excel text-success",
"application/vnd.ms-powerpoint": "fa-solid fa-file-powerpoint text-warning",
"application/vnd.openxmlformats-officedocument.presentationml.presentation":
"fa-solid fa-file-powerpoint text-warning",
"image/jpg": "fa-solid fa-file-image text-info",
"image/jpeg": "fa-solid fa-file-image text-info",
"image/png": "fa-solid fa-file-image text-info",
"image/gif": "fa-solid fa-file-image text-info",
"text/plain": "fa-solid fa-file-lines text-secondary",
"text/csv": "fa-solid fa-file-csv text-success",
"application/json": "fa-solid fa-file-code text-dark",
folder: "fa-solid fa-folder text-warning", // special for folders
default: "fa-solid fa-file text-muted",
};
export const FileIcon = ({ type, size = "fs-4", className = "" }) => {
const iconClass = contentTypeIcons[type] || contentTypeIcons.default;
return <i className={`${iconClass} ${size} ${className}`}></i>;
};

View File

@ -61,3 +61,11 @@ export const getIconByFileType = (type = "") => {
return "bx bx-file";
};
export const normalizeAllowedContentTypes = (allowedContentType) => {
if (!allowedContentType) return [];
if (Array.isArray(allowedContentType)) return allowedContentType;
if (typeof allowedContentType === "string") return allowedContentType.split(",");
return [];
};

View File

@ -39,12 +39,14 @@ export const VIEW_TASK = "9fcc5f87-25e3-4846-90ac-67a71ab92e3c"
export const ASSIGN_REPORT_TASK = "6a32379b-8b3f-49a6-8c48-4b7ac1b55dc2"
// ------------------------Directory-------------------------------------
export const DIRECTORY_ADMIN = "4286a13b-bb40-4879-8c6d-18e9e393beda"
export const DIRECTORY_MANAGER = "62668630-13ce-4f52-a0f0-db38af2230c5"
export const DIRECTORY_USER = "0f919170-92d4-4337-abd3-49b66fc871bb"
// -----------------------Expense----------------------------------------
export const VIEW_SELF_EXPENSE = "385be49f-8fde-440e-bdbc-3dffeb8dd116"
export const VIEW_ALL_EXPNESE = "01e06444-9ca7-4df4-b900-8c3fa051b92f";
@ -55,7 +57,6 @@ export const REVIEW_EXPENSE = "1f4bda08-1873-449a-bb66-3e8222bd871b";
export const APPROVE_EXPENSE = "eaafdd76-8aac-45f9-a530-315589c6deca";
export const PROCESS_EXPENSE = "ea5a1529-4ee8-4828-80ea-0e23c9d4dd11"
export const EXPENSE_MANAGE = "ea5a1529-4ee8-4828-80ea-0e23c9d4dd11"
@ -64,10 +65,19 @@ export const EXPENSE_REJECTEDBY = ["d1ee5eec-24b6-4364-8673-a8f859c60729","965ed
export const EXPENSE_DRAFT = "297e0d8f-f668-41b5-bfea-e03b354251c8"
// ----------------------------Tenant-------------------------
export const SUPPER_TENANT = "d032cb1a-3f30-462c-bef0-7ace73a71c0b"
export const MANAGE_TENANTS = "00e20637-ce8d-4417-bec4-9b31b5e65092"
export const VIEW_TENANTS = "647145c6-2108-4c98-aab4-178602236e55"
export const ActiveTenant = "297e0d8f-f668-41b5-bfea-e03b354251c8"
// ---------------------Documents---------------------------------
export const VIEW_DOCUMENT = "71189504-f1c8-4ca5-8db6-810497be2854";
export const UPLOAD_DOCUMENT = "3f6d1f67-6fa5-4b7c-b17b-018d4fe4aab8";
export const MODIFY_DOCUMENT = "c423fd81-6273-4b9d-bb5e-76a0fb343833";
export const DELETE_DOCUMENT = "40863a13-5a66-469d-9b48-135bc5dbf486";
export const DOWNLOAD_DOCUMENT = "404373d0-860f-490e-a575-1c086ffbce1d";
export const VERIFY_DOCUMENT = "13a1f30f-38d1-41bf-8e7a-b75189aab8e0";
// -------------------Application Role------------------------------
// 1 - Expense Manage
@ -79,6 +89,12 @@ export const TENANT_STATUS = [
{id:"35d7840a-164a-448b-95e6-efb2ec84a751",name:"Supspended"}
]
export const DOCUMENTS_ENTITIES = {
ProjectEntity : "c8fe7115-aa27-43bc-99f4-7b05fabe436e",
EmployeeEntity:"dbb9555a-7a0c-40f2-a9ed-f0463f1ceed7",
}
export const CONSTANT_TEXT = {
}