Merge branch 'Purchase_Invoice_Management' of https://git.marcoaiot.com/admin/marco.pms.web into Finance_Export_Functionality

This commit is contained in:
Kartik Sharma 2025-12-01 15:16:51 +05:30
commit 03fb5f7bc3
41 changed files with 1655 additions and 557 deletions

View File

@ -234,7 +234,9 @@ font-weight: normal;
.h-min { height: min-content; } .h-min { height: min-content; }
.h-max { height: max-content; } .h-max { height: max-content; }
.vh-50 {
height: 50vh !important;
}

View File

@ -39,14 +39,12 @@ const TaskReportFilterPanel = ({ handleFilter }) => {
dateTo: localToUtc(formData.dateTo), dateTo: localToUtc(formData.dateTo),
}; };
handleFilter(filterPayload); handleFilter(filterPayload);
closePanel();
}; };
const onClear = () => { const onClear = () => {
setResetKey((prev) => prev + 1); setResetKey((prev) => prev + 1);
handleFilter(TaskReportDefaultValue); handleFilter(TaskReportDefaultValue);
reset(TaskReportDefaultValue); reset(TaskReportDefaultValue);
closePanel();
}; };
return ( return (
<FormProvider {...methods}> <FormProvider {...methods}>

View File

@ -204,24 +204,34 @@ const TaskReportList = () => {
<HoverPopup <HoverPopup
id="total_pending_task" id="total_pending_task"
title="Total Pending Task" title="Total Pending Task"
content={<p>This shows the total pending tasks for each activity on that date.</p>} content={
<div className="text-wrap" style={{ maxWidth: "200px" }}>
This shows the total pending tasks for each activity on that date.
</div>
}
> >
<i className="bx bx-xs ms-1 bx-info-circle cursor-pointer"></i> <i className="bx bx-xs ms-1 bx-info-circle cursor-pointer"></i>
</HoverPopup> </HoverPopup>
</span> </span>
</th> </th>
<th> <th>
<span> <span>
Reported/Planned{" "} Reported/Planned{" "}
<HoverPopup <HoverPopup
id="reportes_and_planned_task" id="reportes_and_planned_task"
title="Reported and Planned Task" title="Reported and Planned Task"
content={<p>This shows the reported versus planned tasks for each activity on that date.</p>} content={
<div className="text-wrap" style={{ maxWidth: "200px" }}>
This shows the reported versus planned tasks for each activity on that date.
</div>
}
> >
<i className="bx bx-xs ms-1 bx-info-circle cursor-pointer"></i> <i className="bx bx-xs ms-1 bx-info-circle cursor-pointer"></i>
</HoverPopup> </HoverPopup>
</span> </span>
</th> </th>
<th>Assign Date</th> <th>Assign Date</th>
<th>Team</th> <th>Team</th>
<th className="text-center">Actions</th> <th className="text-center">Actions</th>

View File

@ -100,7 +100,7 @@ const AttendanceOverview = () => {
}; };
return ( return (
<div className="bg-white px-4 rounded shadow d-flex flex-column h-100"> <div className="bg-white px-4 rounded shadow d-flex flex-column h-100" style={{ minHeight: "450px" }}>
{/* Header */} {/* Header */}
<div className="d-flex mt-2 justify-content-between align-items-center mb-3"> <div className="d-flex mt-2 justify-content-between align-items-center mb-3">
<div className="card-title mb-0 text-start"> <div className="card-title mb-0 text-start">

View File

@ -17,12 +17,19 @@ import ExpenseAnalysis from "./ExpenseAnalysis";
import ExpenseStatus from "./ExpenseStatus"; import ExpenseStatus from "./ExpenseStatus";
import ExpenseByProject from "./ExpenseByProject"; import ExpenseByProject from "./ExpenseByProject";
import ProjectStatistics from "../Project/ProjectStatistics"; import ProjectStatistics from "../Project/ProjectStatistics";
import ServiceJobs from "./ServiceJobs";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { REGULARIZE_ATTENDANCE, SELF_ATTENDANCE, TEAM_ATTENDANCE } from "../../utils/constants";
const Dashboard = () => { const Dashboard = () => {
// Get the selected project ID from Redux store // Get the selected project ID from Redux store
const projectId = useSelector((store) => store.localVariables.projectId); const projectId = useSelector((store) => store.localVariables.projectId);
const isAllProjectsSelected = projectId === null; const isAllProjectsSelected = projectId === null;
const canRegularize = useHasUserPermission(REGULARIZE_ATTENDANCE);
const canTeamAttendance = useHasUserPermission(TEAM_ATTENDANCE);
const canSelfAttendance = useHasUserPermission(SELF_ATTENDANCE);
return ( return (
<div className="container-fluid mt-5"> <div className="container-fluid mt-5">
@ -40,26 +47,6 @@ const Dashboard = () => {
<div className={`${!isAllProjectsSelected ? "col-sm-6 col-lg-6" : "col-sm-6 col-lg-4"}`}> <div className={`${!isAllProjectsSelected ? "col-sm-6 col-lg-6" : "col-sm-6 col-lg-4"}`}>
<TasksCard /> <TasksCard />
</div> </div>
{isAllProjectsSelected && (
<div className="col-xxl-6 col-lg-6">
<ProjectCompletionChart />
</div>
)}
<div className="col-xxl-6 col-lg-6">
<ProjectProgressChart />
</div>
{!isAllProjectsSelected && (
<div className="col-12 col-md-6 mb-sm-0 mb-4">
<AttendanceOverview />
</div>
)}
{!isAllProjectsSelected && (
<div className="col-xxl-4 col-lg-4">
<ProjectStatistics />
</div>
)}
<div className="col-12 col-xl-4 col-md-6"> <div className="col-12 col-xl-4 col-md-6">
<div className="card "> <div className="card ">
<ExpenseStatus /> <ExpenseStatus />
@ -74,6 +61,32 @@ const Dashboard = () => {
<div className="col-12 col-md-6"> <div className="col-12 col-md-6">
<ExpenseByProject /> <ExpenseByProject />
</div> </div>
{isAllProjectsSelected && (
<div className="col-xxl-6 col-lg-6">
<ProjectCompletionChart />
</div>
)}
<div className="col-xxl-6 col-lg-6">
<ProjectProgressChart />
</div>
{!isAllProjectsSelected && (canRegularize || canTeamAttendance || canSelfAttendance) && (
<div className="col-12 col-md-6 mb-sm-0 mb-4">
<AttendanceOverview />
</div>
)}
{!isAllProjectsSelected && (
<div className="col-xxl-4 col-lg-4">
<div className="card h-100">
<ProjectStatistics />
</div>
</div>
)}
{/* <div className="col-12 col-md-12">
<ServiceJobs />
</div> */}
</div> </div>
</div> </div>
); );

View File

@ -0,0 +1,237 @@
import React from "react";
const ServiceJobs = () => {
return (
<div className="col-xxl-4 col-lg-6">
<div className="card h-100">
<div className="card-header d-flex justify-content-between">
<div className="card-title mb-0 text-start">
<h5 className="mb-1">Service Jobs</h5>
<p className="card-subtitle">All Projects</p>
</div>
</div>
<div className="card-body p-0">
<div className="nav-align-top">
{/* Tabs */}
<ul className="nav nav-tabs nav-fill rounded-0 timeline-indicator-advanced" role="tablist">
<li className="nav-item">
<button className="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-new">
My Jobs
</button>
</li>
<li className="nav-item">
<button className="nav-link" data-bs-toggle="tab" data-bs-target="#tab-preparing">
Assigned
</button>
</li>
<li className="nav-item">
<button className="nav-link" data-bs-toggle="tab" data-bs-target="#tab-shipping">
In Progress
</button>
</li>
</ul>
{/* Tab Content */}
<div className="tab-content border-0 mx-1 text-start">
{/* ---------------------- NEW TAB ---------------------- */}
<div className="tab-pane fade show active" id="tab-new">
{/* Entry 1 */}
<ul className="timeline mb-0">
<li className="timeline-item ps-6 border-left-dashed">
<span className="timeline-indicator-advanced timeline-indicator-success border-0 shadow-none">
<i className="bx bx-check-circle"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-success text-uppercase">Sender</small>
</div>
<h6 className="my-50">Myrtle Ullrich</h6>
<p className="text-body mb-0">101 Boulder, California(CA), 95959</p>
</div>
</li>
<li className="timeline-item ps-6 border-transparent">
<span className="timeline-indicator-advanced timeline-indicator-primary border-0 shadow-none">
<i className="bx bx-map"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-primary text-uppercase">Receiver</small>
</div>
<h6 className="my-50">Barry Schowalter</h6>
<p className="text-body mb-0">939 Orange, California(CA), 92118</p>
</div>
</li>
</ul>
<div className="border-1 border-light border-top border-dashed my-4"></div>
{/* Entry 2 */}
<ul className="timeline mb-0">
<li className="timeline-item ps-6 border-left-dashed">
<span className="timeline-indicator-advanced timeline-indicator-success border-0 shadow-none">
<i className="bx bx-check-circle"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-success text-uppercase">Sender</small>
</div>
<h6 className="my-50">Veronica Herman</h6>
<p className="text-body mb-0">162 Windsor, California(CA), 95492</p>
</div>
</li>
<li className="timeline-item ps-6 border-transparent">
<span className="timeline-indicator-advanced timeline-indicator-primary border-0 shadow-none">
<i className="bx bx-map"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-primary text-uppercase">Receiver</small>
</div>
<h6 className="my-50">Helen Jacobs</h6>
<p className="text-body mb-0">487 Sunset, California(CA), 94043</p>
</div>
</li>
</ul>
</div>
{/* ---------------------- PREPARING TAB ---------------------- */}
<div className="tab-pane fade" id="tab-preparing">
{/* Entry 1 */}
<ul className="timeline mb-0">
<li className="timeline-item ps-6 border-left-dashed">
<span className="timeline-indicator-advanced timeline-indicator-warning border-0 shadow-none">
<i className="bx bx-time-five"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-warning text-uppercase">Sender</small>
</div>
<h6 className="my-50">Oliver Grant</h6>
<p className="text-body mb-0">220 Pine St, California(CA), 95765</p>
</div>
</li>
<li className="timeline-item ps-6 border-transparent">
<span className="timeline-indicator-advanced timeline-indicator-primary border-0 shadow-none">
<i className="bx bx-map"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-primary text-uppercase">Receiver</small>
</div>
<h6 className="my-50">Samantha Lee</h6>
<p className="text-body mb-0">744 Bay Area, California(CA), 94016</p>
</div>
</li>
</ul>
<div className="border-1 border-light border-top border-dashed my-4"></div>
{/* Entry 2 */}
<ul className="timeline mb-0">
<li className="timeline-item ps-6 border-left-dashed">
<span className="timeline-indicator-advanced timeline-indicator-warning border-0 shadow-none">
<i className="bx bx-time-five"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-warning text-uppercase">Sender</small>
</div>
<h6 className="my-50">Marcus Howard</h6>
<p className="text-body mb-0">58 Avenue, California(CA), 95376</p>
</div>
</li>
<li className="timeline-item ps-6 border-transparent">
<span className="timeline-indicator-advanced timeline-indicator-primary border-0 shadow-none">
<i className="bx bx-map"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-primary text-uppercase">Receiver</small>
</div>
<h6 className="my-50">Daniel Foster</h6>
<p className="text-body mb-0">312 Marina, California(CA), 94109</p>
</div>
</li>
</ul>
</div>
{/* ---------------------- SHIPPING TAB ---------------------- */}
<div className="tab-pane fade" id="tab-shipping">
{/* Entry 1 */}
<ul className="timeline mb-0">
<li className="timeline-item ps-6 border-left-dashed">
<span className="timeline-indicator-advanced timeline-indicator-info border-0 shadow-none">
<i className="bx bx-package"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-info text-uppercase">Sender</small>
</div>
<h6 className="my-50">James Carter</h6>
<p className="text-body mb-0">441 Market St, California(CA), 94111</p>
</div>
</li>
<li className="timeline-item ps-6 border-transparent">
<span className="timeline-indicator-advanced timeline-indicator-primary border-0 shadow-none">
<i className="bx bx-map"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-primary text-uppercase">Receiver</small>
</div>
<h6 className="my-50">Linda Moore</h6>
<p className="text-body mb-0">990 Willow Road, California(CA), 94025</p>
</div>
</li>
</ul>
<div className="border-1 border-light border-top border-dashed my-4"></div>
{/* Entry 2 */}
<ul className="timeline mb-0">
<li className="timeline-item ps-6 border-left-dashed">
<span className="timeline-indicator-advanced timeline-indicator-info border-0 shadow-none">
<i className="bx bx-package"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-info text-uppercase">Sender</small>
</div>
<h6 className="my-50">Sarah Bennett</h6>
<p className="text-body mb-0">882 Canyon Rd, California(CA), 94704</p>
</div>
</li>
<li className="timeline-item ps-6 border-transparent">
<span className="timeline-indicator-advanced timeline-indicator-primary border-0 shadow-none">
<i className="bx bx-map"></i>
</span>
<div className="timeline-event ps-1">
<div className="timeline-header">
<small className="text-primary text-uppercase">Receiver</small>
</div>
<h6 className="my-50">George Simmons</h6>
<p className="text-body mb-0">19 Palm St, California(CA), 93001</p>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
);
};
export default ServiceJobs;

View File

@ -18,12 +18,11 @@ const Filelist = ({ files, removeFile, expenseToEdit,sm=6,md=4 }) => {
{/* File icon and info */} {/* File icon and info */}
<div className="d-flex align-items-center flex-grow-1 gap-2 overflow-hidden"> <div className="d-flex align-items-center flex-grow-1 gap-2 overflow-hidden">
<i <i
className={`bx ${getIconByFileType( className={`bx ${getIconByFileType(file?.contentType)} fs-3 `}
file?.contentType
)} fs-3 `}
style={{ minWidth: "30px" }} style={{ minWidth: "30px" }}
></i> ></i>
<Tooltip text={file.fileName}>
<div className="d-flex flex-column text-truncate"> <div className="d-flex flex-column text-truncate">
<span className="fw-semibold small text-truncate"> <span className="fw-semibold small text-truncate">
{file.fileName} {file.fileName}
@ -32,6 +31,7 @@ const Filelist = ({ files, removeFile, expenseToEdit,sm=6,md=4 }) => {
{file.fileSize ? formatFileSize(file.fileSize) : ""} {file.fileSize ? formatFileSize(file.fileSize) : ""}
</span> </span>
</div> </div>
</Tooltip>
</div> </div>
{/* Delete icon */} {/* Delete icon */}
@ -41,7 +41,7 @@ const Filelist = ({ files, removeFile, expenseToEdit,sm=6,md=4 }) => {
role="button" role="button"
onClick={(e) => { onClick={(e) => {
e.preventDefault(); e.preventDefault();
removeFile(expenseToEdit ? file.documentId : idx); removeFile(expenseToEdit ? file.documentId ?? file.tempId ?? idx : file.tempId ?? idx);
}} }}
></i> ></i>
</Tooltip> </Tooltip>
@ -49,7 +49,6 @@ const Filelist = ({ files, removeFile, expenseToEdit,sm=6,md=4 }) => {
</div> </div>
))} ))}
</div> </div>
); );
}; };
@ -62,9 +61,7 @@ export const FilelistView = ({ files, viewFile }) => {
<div className="row align-items-center"> <div className="row align-items-center">
{/* File icon and info */} {/* File icon and info */}
<div className="col-12 d-flex align-items-center gap-2"> <div className="col-12 d-flex align-items-center gap-2">
<i <i className={`bx ${getIconByFileType(file?.fileName)} fs-3`}></i>
className={`bx ${getIconByFileType(file?.fileName)} fs-3`}
></i>
<div <div
className="d-flex flex-column text-truncate" className="d-flex flex-column text-truncate"
@ -72,7 +69,7 @@ export const FilelistView = ({ files, viewFile }) => {
e.preventDefault(); e.preventDefault();
viewFile({ viewFile({
IsOpen: true, IsOpen: true,
Image: file.preSignedUrl, Image: files,
}); });
}} }}
> >
@ -93,3 +90,44 @@ export const FilelistView = ({ files, viewFile }) => {
</div> </div>
); );
}; };
export const FileView = ({ file, viewFile }) => {
if (!file) {
return (
<div className="d-flex justify-content-center align-items-center py-4">
<p className="mb-0 text-muted small">No file uploaded</p>
</div>
);
}
return (
<div className=" bg-white ">
<div className="row align-items-center">
{/* File icon and info */}
<div className="col-12 d-flex align-items-center gap-2 ms-n1">
<i className={`bx ${getIconByFileType(file?.contentType)} fs-4`}></i>
<div
className="d-flex flex-column text-truncate"
onClick={(e) => {
e.preventDefault();
viewFile({
IsOpen: true,
Image: file.preSignedUrl,
});
}}
>
<span className="text-muted small text-truncate mb-n4">
{file.fileName}
</span>
<span className="text-body-secondary small">
<Tooltip text={"Click on file"}>
{" "}
{file.fileSize ? formatFileSize(file.fileSize) : ""}
</Tooltip>
</span>
</div>
</div>
</div>
</div>
);
};

View File

@ -237,30 +237,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
</h5> </h5>
<form id="expenseForm" onSubmit={handleSubmit(onSubmit)}> <form id="expenseForm" onSubmit={handleSubmit(onSubmit)}>
<div className="row my-2 text-start"> <div className="row my-2 text-start">
{/* <div className="col-md-6"> <div className="col-12 col-md-6">
<Label className="form-label" required>
Select Project
</Label>
<select
className="form-select form-select-sm"
{...register("projectId")}
>
<option value="">Select Project</option>
{projectLoading ? (
<option>Loading...</option>
) : (
projectNames?.map((project) => (
<option key={project.id} value={project.id}>
{project.name}
</option>
))
)}
</select>
{errors.projectId && (
<small className="danger-text">{errors.projectId.message}</small>
)}
</div> */}
<div className="col-12 col-md-6 mb-2">
<SelectProjectField <SelectProjectField
label="Project" label="Project"
required required
@ -283,7 +260,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
Expense Category Expense Category
</Label> </Label>
<select <select
className="form-select form-select-sm" className="form-select "
id="expenseCategoryId" id="expenseCategoryId"
{...register("expenseCategoryId")} {...register("expenseCategoryId")}
> >
@ -314,7 +291,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
Payment Mode Payment Mode
</Label> </Label>
<select <select
className="form-select form-select-sm" className="form-select "
id="paymentModeId" id="paymentModeId"
{...register("paymentModeId")} {...register("paymentModeId")}
> >
@ -338,33 +315,22 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
)} )}
</div> </div>
<div className="col-12 col-md-6 text-start"> <div className="col-12 col-md-6 text-start">
{/* <Label className="form-label" required>
Paid By{" "}
</Label> */}
{/* <EmployeeSearchInput
control={control}
name="paidById"
projectId={null}
forAll={true}
/> */}
<AppFormController <AppFormController
name="paidById" name="paidById"
control={control} control={control}
render={({ field }) => ( render={({ field }) => (
<SelectEmployeeServerSide <SelectEmployeeServerSide
label="Paid By" required label="Paid By" required
value={field.value} value={field.value}
onChange={field.onChange} onChange={field.onChange}
isFullObject={false} // because using ID isFullObject={false}
/> />
)} )}
/> />
</div> </div>
</div> </div>
<div className="row my-2 text-start"> <div className="row my-2 text-start mb-4">
<div className="col-md-6"> <div className="col-md-6">
<Label htmlFor="transactionDate" className="form-label" required> <Label htmlFor="transactionDate" className="form-label" required>
Transaction Date Transaction Date
@ -374,6 +340,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
className="w-100" className="w-100"
control={control} control={control}
maxDate={new Date()} maxDate={new Date()}
size="md"
/> />
{errors.transactionDate && ( {errors.transactionDate && (
@ -390,7 +357,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
<input <input
type="number" type="number"
id="amount" id="amount"
className="form-control form-control-sm" className="form-control "
min="1" min="1"
step="0.01" step="0.01"
inputMode="decimal" inputMode="decimal"
@ -402,7 +369,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
</div> </div>
</div> </div>
<div className="row my-2 text-start"> <div className="row my-2 text-start mb-4">
<div className="col-md-6"> <div className="col-md-6">
<Label htmlFor="supplerName" className="form-label" required> <Label htmlFor="supplerName" className="form-label" required>
Supplier Name/Transporter Name/Other Supplier Name/Transporter Name/Other
@ -410,7 +377,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
<input <input
type="text" type="text"
id="supplerName" id="supplerName"
className="form-control form-control-sm" className="form-control "
{...register("supplerName")} {...register("supplerName")}
/> />
{errors.supplerName && ( {errors.supplerName && (
@ -427,7 +394,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
<input <input
type="text" type="text"
id="location" id="location"
className="form-control form-control-sm" className="form-control "
{...register("location")} {...register("location")}
/> />
{errors.location && ( {errors.location && (
@ -435,7 +402,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
)} )}
</div> </div>
</div> </div>
<div className="row my-2 text-start"> <div className="row my-2 text-start mb-4">
<div className="col-md-6"> <div className="col-md-6">
<label htmlFor="statusId" className="form-label "> <label htmlFor="statusId" className="form-label ">
Transaction ID Transaction ID
@ -443,7 +410,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
<input <input
type="text" type="text"
id="transactionId" id="transactionId"
className="form-control form-control-sm" className="form-control "
min="1" min="1"
{...register("transactionId")} {...register("transactionId")}
/> />
@ -460,7 +427,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
<input <input
type="text" type="text"
id="gstNumber" id="gstNumber"
className="form-control form-control-sm" className="form-control "
min="1" min="1"
{...register("gstNumber")} {...register("gstNumber")}
/> />
@ -469,13 +436,13 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
)} )}
</div> </div>
</div> </div>
<div className="row"> <div className="row mb-4">
<div className="col-md-6 text-start "> <div className="col-md-6 text-start ">
<Label htmlFor="currencyId" className="form-label" required> <Label htmlFor="currencyId" className="form-label" required>
Select Currency Select Currency
</Label> </Label>
<select <select
className="form-select form-select-sm" className="form-select "
id="currencyId" id="currencyId"
{...register("currencyId")} {...register("currencyId")}
> >
@ -504,7 +471,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
<input <input
type="number" type="number"
id="noOfPersons" id="noOfPersons"
className="form-control form-control-sm" className="form-control "
{...register("noOfPersons")} {...register("noOfPersons")}
inputMode="numeric" inputMode="numeric"
/> />
@ -517,14 +484,14 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
)} )}
</div> </div>
<div className="row my-2 text-start"> <div className="row my-2 text-start mb-4">
<div className="col-md-12"> <div className="col-md-12">
<Label htmlFor="description" className="form-label" required> <Label htmlFor="description" className="form-label" required>
Description Description
</Label> </Label>
<textarea <textarea
id="description" id="description"
className="form-control form-control-sm" className="form-control "
{...register("description")} {...register("description")}
rows="2" rows="2"
></textarea> ></textarea>
@ -536,7 +503,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
</div> </div>
</div> </div>
<div className="row my-2 text-start"> <div className="row my-4 text-start">
<div className="col-md-12"> <div className="col-md-12">
<Label className="form-label" required> <Label className="form-label" required>
Upload Bill{" "} Upload Bill{" "}

View File

@ -1,80 +1,169 @@
import { useState } from "react"; import { useState, useRef, useEffect } from "react";
const PreviewDocument = ({ files = [] }) => {
const images = Array.isArray(files) ? files : [files];
const PreviewDocument = ({ imageUrl }) => { const [index, setIndex] = useState(0);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [rotation, setRotation] = useState(0); const [rotation, setRotation] = useState(0);
const [scale, setScale] = useState(1); const [scale, setScale] = useState(1);
const [position, setPosition] = useState({ x: 0, y: 0 });
const [dragging, setDragging] = useState(false);
const startPos = useRef({ x: 0, y: 0 });
const MIN_ZOOM = 0.4;
const MAX_ZOOM = 3;
const currentImage = images[index];
// Reset on image change
useEffect(() => {
setRotation(0);
setScale(1);
setPosition({ x: 0, y: 0 });
setLoading(true);
}, [index]);
const zoomIn = () => setScale((prev) => Math.min(prev + 0.2, MAX_ZOOM));
const zoomOut = () => setScale((prev) => Math.max(prev - 0.2, MIN_ZOOM));
const zoomIn = () => setScale((prev) => Math.min(prev + 0.2, 3));
const zoomOut = () => setScale((prev) => Math.max(prev - 0.2, 0.4));
const resetAll = () => { const resetAll = () => {
setRotation(0); setRotation(0);
setScale(1); setScale(1);
setPosition({ x: 0, y: 0 });
}; };
const nextImage = () => {
if (index < images.length - 1) setIndex((i) => i + 1);
};
const prevImage = () => {
if (index > 0) setIndex((i) => i - 1);
};
const handleWheel = (e) => {
e.preventDefault();
if (e.ctrlKey) {
const delta = e.deltaY > 0 ? -0.1 : 0.1;
setScale((prev) => {
let next = prev + delta;
if (next < MIN_ZOOM) next = MIN_ZOOM;
if (next > MAX_ZOOM) next = MAX_ZOOM;
return next;
});
} else {
if (e.deltaY > 0) nextImage();
else prevImage();
}
};
const handleMouseDown = (e) => {
setDragging(true);
startPos.current = {
x: e.clientX - position.x,
y: e.clientY - position.y,
};
};
const handleMouseMove = (e) => {
if (!dragging) return;
setPosition({
x: e.clientX - startPos.current.x,
y: e.clientY - startPos.current.y,
});
};
const handleMouseUp = () => setDragging(false);
const handleDoubleClick = () => resetAll();
return ( return (
<> <>
<div className="d-flex justify-content-start gap-3 mb-2"> {/* Top Controls */}
<div className="d-flex justify-content-start align-items-center mb-2">
{/* Left */}
<div className="d-flex gap-3">
<i <i
className="bx bx-rotate-right cursor-pointer fs-4" className="bx bx-rotate-right cursor-pointer fs-4"
title="Rotate"
onClick={() => setRotation((prev) => prev + 90)} onClick={() => setRotation((prev) => prev + 90)}
></i> title="Rotate"
/>
<i <i
className="bx bx-zoom-in cursor-pointer fs-4" className="bx bx-zoom-in cursor-pointer fs-4"
title="Zoom In"
onClick={zoomIn} onClick={zoomIn}
></i> title="Zoom In"
/>
<i <i
className="bx bx-zoom-out cursor-pointer fs-4" className="bx bx-zoom-out cursor-pointer fs-4"
title="Zoom Out"
onClick={zoomOut} onClick={zoomOut}
></i> title="Zoom Out"
/>
<i
className="bx bx-reset cursor-pointer fs-4"
onClick={resetAll}
title="Reset"
/>
</div>
</div> </div>
<div <div
className="position-relative d-flex flex-column justify-content-center align-items-center overflow-hidden" onWheel={handleWheel}
style={{ minHeight: "80vh" }} onMouseDown={handleMouseDown}
> onMouseMove={handleMouseMove}
{loading && ( onMouseUp={handleMouseUp}
<div className="text-secondary text-center mb-2"> onMouseLeave={handleMouseUp}
Loading... onDoubleClick={handleDoubleClick}
</div> className="position-relative d-flex justify-content-center align-items-center bg-light-secondary overflow-hidden"
)}
<div className="mb-3 d-flex justify-content-center align-items-center">
<img
src={imageUrl}
alt="Full View"
className="img-fluid"
style={{ style={{
maxHeight: "80vh", minHeight: "70vh",
objectFit: "contain", userSelect: "none",
borderRadius: "10px",
}}
>
{loading && <div className="text-secondary">Loading...</div>}
<img
src={currentImage?.preSignedUrl}
alt="Preview"
draggable="false"
style={{
maxHeight: "60vh",
display: loading ? "none" : "block", display: loading ? "none" : "block",
transform: `rotate(${rotation}deg) scale(${scale})`, transform: `
transition: "transform 0.3s ease", translate(${position.x}px, ${position.y}px)
cursor: "grab", scale(${scale})
rotate(${rotation}deg)
`,
transition: dragging ? "none" : "transform 0.2s ease",
cursor: dragging ? "grabbing" : "grab",
}} }}
onLoad={() => setLoading(false)} onLoad={() => setLoading(false)}
/> />
</div> </div>
<div className="position-absolute bottom-0 start-0 m-2"> <div className="d-flex justify-content-between">
<button <div className="text-center text-muted mt-2 small">
className="btn btn-outline-secondary" Scroll = change image | Double click = reset
onClick={resetAll} </div>
> <div className="d-flex align-items-center gap-2">
<i className="bx bx-reset"></i> Reset <i
</button> className="bx bx-chevron-left cursor-pointer fs-4"
onClick={prevImage}
/>
<span>
{index + 1} / {images.length}
</span>
<i
className="bx bx-chevron-right cursor-pointer fs-4"
onClick={nextImage}
/>
</div> </div>
</div> </div>
</> </>
); );
}; };
export default PreviewDocument; export default PreviewDocument;

View File

@ -393,7 +393,7 @@ const tdsPercentage = Number(watch("tdsPercentage")) || 0;
if (isImage) { if (isImage) {
setDocumentView({ setDocumentView({
IsOpen: true, IsOpen: true,
Image: doc.preSignedUrl, Images: data?.documents,
}); });
} }
}} }}

View File

@ -0,0 +1,16 @@
import React from 'react'
const WarningBlock = ({content}) => {
return (
<div className="col-12 my-1">
<div className="d-flex align-items-center gap-2 p-3 rounded bg-warning bg-opacity-10 border border-warning-subtle text-start align-item-start">
<i className="bx bx-info-circle text-warning fs-5"></i>
<p className="mb-0 small">
{content}
</p>
</div>
</div>
)
}
export default WarningBlock

View File

@ -239,7 +239,7 @@ function ManagePaymentRequest({ closeModal, requestToEdit = null }) {
Select Project Select Project
</Label> */} </Label> */}
{/* <select {/* <select
className="form-select form-select-sm" className="form-select "
{...register("projectId")} {...register("projectId")}
disabled={ disabled={
data?.recurringPayment?.isVariable && !isDraft && !isProcessed data?.recurringPayment?.isVariable && !isDraft && !isProcessed
@ -282,7 +282,7 @@ function ManagePaymentRequest({ closeModal, requestToEdit = null }) {
Expense Category Expense Category
</Label> </Label>
<select <select
className="form-select form-select-sm" className="form-select "
id="expenseCategoryId" id="expenseCategoryId"
{...register("expenseCategoryId")} {...register("expenseCategoryId")}
disabled={ disabled={
@ -311,7 +311,7 @@ function ManagePaymentRequest({ closeModal, requestToEdit = null }) {
</div> </div>
{/* Title and Advance Payment */} {/* Title and Advance Payment */}
<div className="row my-2 text-start"> <div className="row mt-n2 text-start">
<div className="col-md-6"> <div className="col-md-6">
<Label htmlFor="title" className="form-label" required> <Label htmlFor="title" className="form-label" required>
Title Title
@ -319,7 +319,7 @@ function ManagePaymentRequest({ closeModal, requestToEdit = null }) {
<input <input
type="text" type="text"
id="title" id="title"
className="form-control form-control-sm" className="form-control "
{...register("title")} {...register("title")}
disabled={ disabled={
data?.recurringPayment?.isVariable && !isDraft && !isProcessed data?.recurringPayment?.isVariable && !isDraft && !isProcessed
@ -343,7 +343,7 @@ function ManagePaymentRequest({ closeModal, requestToEdit = null }) {
data?.recurringPayment?.isVariable && !isDraft && !isProcessed data?.recurringPayment?.isVariable && !isDraft && !isProcessed
} }
render={({ field }) => ( render={({ field }) => (
<div className="d-flex align-items-center gap-3"> <div className="d-flex align-items-center gap-3 mt-3">
<div className="form-check d-flex flex-row m-0 gap-2"> <div className="form-check d-flex flex-row m-0 gap-2">
<input <input
type="radio" type="radio"
@ -387,6 +387,7 @@ function ManagePaymentRequest({ closeModal, requestToEdit = null }) {
control={control} control={control}
minDate={new Date()} minDate={new Date()}
className="w-100" className="w-100"
size="md"
disabled={ disabled={
data?.recurringPayment?.isVariable && !isDraft && !isProcessed data?.recurringPayment?.isVariable && !isDraft && !isProcessed
} }
@ -404,7 +405,7 @@ function ManagePaymentRequest({ closeModal, requestToEdit = null }) {
<input <input
type="number" type="number"
id="amount" id="amount"
className="form-control form-control-sm" className="form-control "
min="1" min="1"
step="0.01" step="0.01"
inputMode="decimal" inputMode="decimal"
@ -429,6 +430,7 @@ function ManagePaymentRequest({ closeModal, requestToEdit = null }) {
setValue("payee", val, { shouldValidate: true }) setValue("payee", val, { shouldValidate: true })
} }
error={errors.payee?.message} error={errors.payee?.message}
size="md"
disabled={ disabled={
data?.recurringPayment?.isVariable && !isDraft && !isProcessed data?.recurringPayment?.isVariable && !isDraft && !isProcessed
} }
@ -458,7 +460,7 @@ function ManagePaymentRequest({ closeModal, requestToEdit = null }) {
</Label> </Label>
<select <select
id="currencyId" id="currencyId"
className="form-select form-select-sm" className="form-select "
{...register("currencyId")} {...register("currencyId")}
disabled={ disabled={
data?.recurringPayment?.isVariable && !isDraft && !isProcessed data?.recurringPayment?.isVariable && !isDraft && !isProcessed
@ -490,7 +492,7 @@ function ManagePaymentRequest({ closeModal, requestToEdit = null }) {
</Label> </Label>
<textarea <textarea
id="description" id="description"
className="form-control form-control-sm" className="form-control "
{...register("description")} {...register("description")}
rows="2" rows="2"
disabled={ disabled={

View File

@ -165,7 +165,7 @@ const ProjectStatistics = ({ project }) => {
}, [selectedProject]); }, [selectedProject]);
return ( return (
<div className="card h-100"> <>
<div className="card-header text-start"> <div className="card-header text-start">
<h5 className="card-action-title mb-0"> <h5 className="card-action-title mb-0">
{" "} {" "}
@ -242,8 +242,8 @@ const ProjectStatistics = ({ project }) => {
</li> </li>
</ul> </ul>
</div> </div>
</>
</div>
); );
}; };

View File

@ -165,7 +165,7 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
<div className="row my-2 text-start"> <div className="row my-2 text-start">
<div className="col-md-6"> <div className="col-md-6">
{/* <select {/* <select
className="form-select form-select-sm" className="form-select"
{...register("projectId")} {...register("projectId")}
> >
<option value="">Select Project</option> <option value="">Select Project</option>
@ -201,7 +201,7 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
Expense Category Expense Category
</Label> </Label>
<select <select
className="form-select form-select-sm" className="form-select"
id="expenseCategoryId" id="expenseCategoryId"
{...register("expenseCategoryId")} {...register("expenseCategoryId")}
> >
@ -227,7 +227,7 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
</div> </div>
{/* Title and Is Variable */} {/* Title and Is Variable */}
<div className="row my-2 text-start"> <div className="row my-2 text-start mt-n2">
<div className="col-md-6"> <div className="col-md-6">
<Label htmlFor="title" className="form-label" required> <Label htmlFor="title" className="form-label" required>
Title Title
@ -235,7 +235,7 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
<input <input
type="text" type="text"
id="title" id="title"
className="form-control form-control-sm" className="form-control "
{...register("title")} {...register("title")}
placeholder="Enter title" placeholder="Enter title"
/> />
@ -244,7 +244,7 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
)} )}
</div> </div>
<div className="col-md-6 mt-2"> <div className="col-md-6">
<div className="d-flex justify-content-start align-items-center text-nowrap gap-2"> <div className="d-flex justify-content-start align-items-center text-nowrap gap-2">
<Label htmlFor="isVariable" className="form-label mb-0" required> <Label htmlFor="isVariable" className="form-label mb-0" required>
Payment Type Payment Type
@ -252,16 +252,15 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
<HoverPopup <HoverPopup
title="Payment Type" title="Payment Type"
id="payment_type" id="payment_type"
content={ content={
<div className=" w-50"> <div className="text-wrap" style={{ maxWidth: "200px" }}>
<p>
Choose whether the payment amount varies or remains fixed Choose whether the payment amount varies or remains fixed
each cycle. each cycle.
<br /> <br />
<strong>Is Variable:</strong> Amount changes per cycle. <strong>Is Variable:</strong> Amount changes per cycle.
<br /> <br />
<strong>Fixed:</strong> Amount stays constant. <strong>Fixed:</strong> Amount stays constant.
</p>
</div> </div>
} }
> >
@ -274,7 +273,7 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
control={control} control={control}
defaultValue={defaultRecurringExpense.isVariable ?? false} defaultValue={defaultRecurringExpense.isVariable ?? false}
render={({ field }) => ( render={({ field }) => (
<div className="d-flex align-items-center gap-3 mt-1"> <div className="d-flex align-items-center gap-3 mt-2">
<div className="form-check"> <div className="form-check">
<input <input
type="radio" type="radio"
@ -327,6 +326,7 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
control={control} control={control}
minDate={new Date()} minDate={new Date()}
className="w-100" className="w-100"
size="md"
/> />
{errors.strikeDate && ( {errors.strikeDate && (
<small className="danger-text">{errors.strikeDate.message}</small> <small className="danger-text">{errors.strikeDate.message}</small>
@ -340,7 +340,7 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
<input <input
type="number" type="number"
id="amount" id="amount"
className="form-control form-control-sm" className="form-control "
min="1" min="1"
step="0.01" step="0.01"
inputMode="decimal" inputMode="decimal"
@ -354,7 +354,7 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
</div> </div>
{/* Payee and Currency */} {/* Payee and Currency */}
<div className="row my-2 text-start"> <div className="row my-2 text-start mt-3">
<div className="col-md-6"> <div className="col-md-6">
<Label htmlFor="payee" className="form-label" required> <Label htmlFor="payee" className="form-label" required>
Payee (Supplier Name/Transporter Name/Other) Payee (Supplier Name/Transporter Name/Other)
@ -367,6 +367,7 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
} }
error={errors.payee?.message} error={errors.payee?.message}
placeholder="Select or enter payee" placeholder="Select or enter payee"
size="md"
/> />
</div> </div>
@ -376,7 +377,7 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
</Label> </Label>
<select <select
id="currencyId" id="currencyId"
className="form-select form-select-sm" className="form-select"
{...register("currencyId")} {...register("currencyId")}
> >
<option value="">Select Currency</option> <option value="">Select Currency</option>
@ -398,7 +399,7 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
</div> </div>
{/* Frequency To and Status Id */} {/* Frequency To and Status Id */}
<div className="row my-2 text-start"> <div className="row my-2 text-start mt-n2">
<div className="col-md-6"> <div className="col-md-6">
<div className="d-flex justify-content-start align-items-center gap-2"> <div className="d-flex justify-content-start align-items-center gap-2">
<Label htmlFor="frequency" className="form-label mb-0" required> <Label htmlFor="frequency" className="form-label mb-0" required>
@ -420,7 +421,7 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
<select <select
id="frequency" id="frequency"
className="form-select form-select-sm mt-1" className="form-select mt-1"
{...register("frequency", { valueAsNumber: true })} {...register("frequency", { valueAsNumber: true })}
> >
<option value="">Select Frequency</option> <option value="">Select Frequency</option>
@ -442,7 +443,7 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
</Label> </Label>
<select <select
id="statusId" id="statusId"
className="form-select form-select-sm" className="form-select"
{...register("statusId")} {...register("statusId")}
> >
<option value="">Select Status</option> <option value="">Select Status</option>
@ -476,10 +477,10 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
title="Payment Buffer Days" title="Payment Buffer Days"
id="payment_buffer_days" id="payment_buffer_days"
content={ content={
<p> <div className="text-wrap" style={{ maxWidth: "200px" }}>
Number of extra days allowed after the due date before Number of extra days allowed after the due date before
payment is considered late. payment is considered late.
</p> </div>
} }
> >
<i className="bx bx-info-circle bx-xs text-muted cursor-pointer"></i> <i className="bx bx-info-circle bx-xs text-muted cursor-pointer"></i>
@ -489,7 +490,7 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
<input <input
type="number" type="number"
id="paymentBufferDays" id="paymentBufferDays"
className="form-control form-control-sm mt-1" className="form-control mt-1"
min="0" min="0"
step="1" step="1"
{...register("paymentBufferDays", { valueAsNumber: true })} {...register("paymentBufferDays", { valueAsNumber: true })}
@ -511,10 +512,11 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
<HoverPopup <HoverPopup
title="End Date" title="End Date"
id="end_date" id="end_date"
content={ content={
<p> <div className="text-wrap" style={{ maxWidth: "200px" }}>
The date when the last payment in the recurrence occurs. The date when the last payment in the recurrence occurs.
</p> </div>
} }
> >
<i className="bx bx-info-circle bx-xs text-muted cursor-pointer"></i> <i className="bx bx-info-circle bx-xs text-muted cursor-pointer"></i>
@ -526,6 +528,7 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
control={control} control={control}
minDate={StrikeDate} minDate={StrikeDate}
className="w-100 mt-1" className="w-100 mt-1"
size="md"
/> />
{errors.endDate && ( {errors.endDate && (
@ -568,7 +571,7 @@ const ManageRecurringExpense = ({ closeModal, requestToEdit = null }) => {
</Label> </Label>
<textarea <textarea
id="description" id="description"
className="form-control form-control-sm" className="form-control "
{...register("description")} {...register("description")}
rows="2" rows="2"
></textarea> ></textarea>

View File

@ -175,12 +175,9 @@ const JobList = ({ isArchive }) => {
<td <td
key={col.key} key={col.key}
className={col.className} className={col.className}
// onClick={() =>
// setSelectedJob({ showCanvas: true, job: row?.id })
// }
onClick={() => { onClick={() => {
if (!isArchive) { if (!isArchive) {
setSelectedJob({ showCanvas: true, job: e?.id }); setSelectedJob({ showCanvas: true, job: row?.id });
} }
}} }}

View File

@ -223,9 +223,6 @@ const ManageServiceProject = ({ serviceProjectId, onClose }) => {
className="form-control form-control-sm" className="form-control form-control-sm"
{...register("contactName")} {...register("contactName")}
placeholder="Enter Employee name.." placeholder="Enter Employee name.."
onInput={(e) => {
e.target.value = e.target.value.replace(/[^A-Za-z ]/g, "");
}}
/> />
{errors?.contactName && ( {errors?.contactName && (
<span className="danger-text">{errors.contactName.message}</span> <span className="danger-text">{errors.contactName.message}</span>

View File

@ -237,14 +237,17 @@ const ServiceBranch = () => {
!isError && !isError &&
(!data?.data || data.data.length === 0) && ( (!data?.data || data.data.length === 0) && (
<tr> <tr>
<td <td colSpan={columns.length + 1}>
colSpan={columns.length + 1} <div
className="text-center py-12" className="d-flex justify-content-center align-items-center"
style={{ height: "150px" }}
> >
No Branch Found No Branch Found
</div>
</td> </td>
</tr> </tr>
)} )}
</tbody> </tbody>
</table> </table>

View File

@ -150,7 +150,7 @@ const JobComments = ({ data }) => {
type="submit" type="submit"
disabled={!watch("comment")?.trim() || isPending} disabled={!watch("comment")?.trim() || isPending}
> >
Send Submit
</button> </button>
</div> </div>
</form> </form>

View File

@ -22,8 +22,7 @@ export const projectSchema = z.object({
contactName: z contactName: z
.string() .string()
.trim() .trim()
.min(1, "Contact name is required") .min(1, "Contact name is required"),
.regex(/^[A-Za-z\s]+$/, "Contact name can contain only letters"),
contactPhone: z contactPhone: z
.string() .string()

View File

@ -77,6 +77,7 @@ const ServiceProjectTeamList = () => {
<td <td
colSpan={servceProjectColmen.length} colSpan={servceProjectColmen.length}
className="text-center py-4 border-0" className="text-center py-4 border-0"
style={{ height: "200px" }}
> >
{isLoading ? ( {isLoading ? (
<SpinnerLoader /> <SpinnerLoader />
@ -85,6 +86,7 @@ const ServiceProjectTeamList = () => {
)} )}
</td> </td>
</tr> </tr>
)} )}
</tbody> </tbody>
</table> </table>

View File

@ -457,6 +457,7 @@ export const SelectFieldSearch = ({
const handleSelect = (option) => { const handleSelect = (option) => {
if (!isMultiple) { if (!isMultiple) {
onChange(isFullObject ? option : option[valueKey]); onChange(isFullObject ? option : option[valueKey]);
setOpen(false)
} else { } else {
const exists = selectedList.some((e) => e[valueKey] === option[valueKey]); const exists = selectedList.some((e) => e[valueKey] === option[valueKey]);
const updated = exists const updated = exists

View File

@ -58,117 +58,43 @@ const HoverPopup = ({
return () => document.removeEventListener("click", handler); return () => document.removeEventListener("click", handler);
}, [Mode, visible, dispatch, id]); }, [Mode, visible, dispatch, id]);
// Positioning effect: respects align prop and stays inside boundary (drawer)
useEffect(() => { useEffect(() => {
if (!visible || !popupRef.current || !triggerRef.current) return; if (!visible || !popupRef.current || !triggerRef.current) return;
// run in next frame so DOM/layout settles
requestAnimationFrame(() => { requestAnimationFrame(() => {
const popup = popupRef.current; const popup = popupRef.current;
const boundaryEl = (boundaryRef && boundaryRef.current) || popup.parentElement;
// choose boundary: provided boundaryRef or nearest positioned parent (popup.parentElement)
const boundaryEl =
(boundaryRef && boundaryRef.current) || popup.parentElement;
if (!boundaryEl) return; if (!boundaryEl) return;
const boundaryRect = boundaryEl.getBoundingClientRect(); const boundaryRect = boundaryEl.getBoundingClientRect();
const triggerRect = triggerRef.current.getBoundingClientRect(); const triggerRect = triggerRef.current.getBoundingClientRect();
// reset styles first
popup.style.left = ""; popup.style.left = "";
popup.style.right = ""; popup.style.right = "";
popup.style.transform = ""; popup.style.transform = "";
popup.style.top = ""; popup.style.top = "";
const popupRect = popup.getBoundingClientRect(); const popupRect = popup.getBoundingClientRect();
const parentRect = boundaryRect; // alias const triggerCenterX = triggerRect.left + triggerRect.width / 2 - boundaryRect.left;
let left = triggerCenterX - popupRect.width / 2;
// Convert trigger center to parent coordinates // Clamp to boundaries
const triggerCenterX = left = Math.max(0, Math.min(left, boundaryRect.width - popupRect.width));
triggerRect.left + triggerRect.width / 2 - parentRect.left; popup.style.left = `${left}px`;
// preferred left so popup center aligns to trigger center:
const preferredLeft = triggerCenterX - popupRect.width / 2;
// Helpers to set styles in parent's coordinate system:
const setLeft = (leftPx) => {
popup.style.left = `${leftPx}px`;
popup.style.right = "auto";
popup.style.transform = "none";
};
const setRight = (rightPx) => {
popup.style.left = "auto";
popup.style.right = `${rightPx}px`;
popup.style.transform = "none";
};
// If user forced align:
if (align === "left") {
// align popup's left to parent's left (0)
setLeft(0);
return;
}
if (align === "right") {
// align popup's right to parent's right (0)
setRight(0);
return;
}
if (align === "center") {
popup.style.left = "50%";
popup.style.right = "auto";
popup.style.transform = "translateX(-50%)";
return;
}
// align === "auto": try preferred centered position, but flip fully if overflow
// clamp preferredLeft to boundaries so it doesn't render partially outside
const leftIfCentered = Math.max(
0,
Math.min(preferredLeft, parentRect.width - popupRect.width)
);
// if centered fits, use it
if (leftIfCentered === preferredLeft) {
setLeft(leftIfCentered);
return;
}
// if centering would overflow right -> stick popup fully to left (left=0)
if (preferredLeft > parentRect.width - popupRect.width) {
// place popup so its right aligns to parent's right
// i.e., left = parent width - popup width
setLeft(parentRect.width - popupRect.width);
return;
}
// if centering would overflow left -> stick popup fully to left=0
if (preferredLeft < 0) {
setLeft(0);
return;
}
// fallback center
setLeft(leftIfCentered);
}); });
}, [visible, align, boundaryRef]); }, [visible, align, boundaryRef]);
return ( return (
<div <div
className="d-inline-block position-relative" // <-- ADD THIS !! className="d-inline-block position-relative" // <-- ADD THIS !!
style={{ style={{ overflow: "visible" }}
maxWidth: "calc(700px - 100px)",
width: "100%",
wordWrap: "break-word",
overflow: "visible", // also make sure popup isn't clipped
}}
> >
<div <div
className="d-inline-block"
ref={triggerRef} ref={triggerRef}
onMouseEnter={handleMouseEnter} onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave} onMouseLeave={handleMouseLeave}
onClick={handleClick} onClick={handleClick}
style={{ cursor: "pointer" }} style={{ cursor: "pointer", display: "inline-block" }}
> >
{children} {children}
</div> </div>
@ -180,8 +106,9 @@ const HoverPopup = ({
style={{ style={{
zIndex: 2000, zIndex: 2000,
top: "100%", top: "100%",
width: "max-content", minWidth: "200px",
minWidth: "120px", maxWidth: "300px",
wordWrap: "break-word",
}} }}
onClick={(e) => e.stopPropagation()} onClick={(e) => e.stopPropagation()}
> >

View File

@ -4,6 +4,7 @@ const InputSuggestions = ({
organizationList = [], organizationList = [],
value, value,
onChange, onChange,
size = "sm",
error, error,
disabled = false, disabled = false,
}) => { }) => {
@ -27,7 +28,7 @@ const InputSuggestions = ({
return ( return (
<div className="mb-3 position-relative"> <div className="mb-3 position-relative">
<input <input
className="form-control form-control-sm" className={`form-control form-control-${size}`}
value={value} value={value}
onChange={handleInputChange} onChange={handleInputChange}
onBlur={() => setTimeout(() => setShowSuggestions(false), 150)} onBlur={() => setTimeout(() => setShowSuggestions(false), 150)}
@ -57,8 +58,7 @@ const InputSuggestions = ({
transition: "background-color 0.2s", transition: "background-color 0.2s",
}} }}
onMouseDown={() => handleSelectSuggestion(org)} onMouseDown={() => handleSelectSuggestion(org)}
className={`dropdown-item ${ className={`dropdown-item ${org === value ? "active" : ""
org === value ? "active" : ""
}`} }`}
> >
{org} {org}

View File

@ -0,0 +1,111 @@
import { useRef } from "react";
import Label from "./Label";
import Tooltip from "./Tooltip";
import { formatFileSize, getIconByFileType } from "../../utils/appUtils";
const SingleFileUploader = ({
label = "Upload Document",
required = false,
value,
onChange,
onRemove,
disabled,
error,
accept = ".pdf,.jpg,.jpeg,.png",
maxSizeMB = 25,
hint = "(PDF, JPG, PNG, max 5MB)",
}) => {
const inputRef = useRef(null);
const handleFileSelect = async (e) => {
const file = e.target.files?.[0];
if (!file) return;
// Validate size
if (file.size > maxSizeMB * 1024 * 1024) {
alert(`File size cannot exceed ${maxSizeMB}MB`);
e.target.value = "";
return;
}
// Convert to base64
const base64Data = await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result.split(",")[1]);
reader.onerror = (err) => reject(err);
});
const attachmentObj = {
fileName: file.name,
base64Data,
invoiceAttachmentTypeId: "", // set dynamically if needed
contentType: file.type,
fileSize: file.size,
description: "",
isActive: true,
};
onChange(attachmentObj);
e.target.value = "";
};
return (
<div className="col-md-12">
<Label className="form-label" required={required}>
{label}
</Label>
<div
className="border border-secondary border-dashed rounded p-4 text-center bg-textMuted position-relative"
style={{ cursor: "pointer" }}
onClick={() => inputRef.current.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">{hint}</small>
<input
type="file"
ref={inputRef}
accept={accept}
style={{ display: "none" }}
onChange={handleFileSelect}
disabled={disabled}
/>
</div>
{error && <small className="danger-text">{error}</small>}
{value && (
<div className="mt-3">
<div className="d-flex align-items-center justify-content-between bg-white border rounded p-2">
<div className="d-flex align-items-center gap-2">
<i
className={`bx ${getIconByFileType(value.contentType)} fs-3`}
></i>
<div className="d-flex flex-column text-truncate">
<span className="fw-semibold small text-truncate">
{value.fileName}
</span>
<small className="text-muted">
{value.fileSize ? formatFileSize(value.fileSize) : ""}
</small>
</div>
</div>
<i
className="bx bx-trash text-danger fs-5 cursor-pointer"
onClick={onRemove}
></i>
</div>
</div>
)}
</div>
);
};
export default SingleFileUploader;

View File

@ -0,0 +1,68 @@
import React from "react";
import { useDeliverChallane } from "../../hooks/usePurchase";
import { SpinnerLoader } from "../common/Loader";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import { FileView } from "../Expenses/Filelist";
const DeliverChallanList = ({ purchaseId }) => {
const { data, isLoading, isError, error } = useDeliverChallane(purchaseId);
if (isLoading) {
return (
<div className="d-flex justify-content-center align-items-center text-center vh-50">
<SpinnerLoader />
</div>
);
}
if (isError) {
return (
<div className="py-3">
<Error error={error} />
</div>
);
}
if (!isLoading && data.length === 0)
return (
<div className="d-flex justify-content-center align-items-center text-center vh-50">
<p className="mb-0">Not Yet</p>
</div>
);
return (
<div className="list-group list-group-flush text-start">
{data.map((item) => (
<div
key={item.id}
className="list-group-item d-flex justify-content-between align-items-start flex-wrap px-3 w-full"
>
{/* LEFT SIDE */}
<div className=" pe-3 text-break w-full">
<div className="d-flex justify-content-between">
<p className="mb-1 fw-semibold">{item.deliveryChallanNumber}</p>
<small className="text-muted text-end">
{formatUTCToLocalTime(item.deliveryChallanDate, true)}
</small>
</div>
<div className="mb-1 small text-muted text-break">
<span className="fw-semibold me-1">Invoice:</span>
{item.purchaseInvoice?.title} (
{item.purchaseInvoice?.purchaseInvoiceUId})
</div>
<p className="mb-1 text-break">
<span className="fw-semibold">Description:</span>{" "}
{item.description || "-"}
</p>
{item.attachment?.preSignedUrl && (
<FileView file={item.attachment} />
)}
</div>
</div>
))}
</div>
);
};
export default DeliverChallanList;

View File

@ -0,0 +1,200 @@
import React, { useState } from "react";
import {
useAddDeliverChallan,
useDeliverChallane,
} from "../../hooks/usePurchase";
import { SpinnerLoader } from "../common/Loader";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import DeliverChallanList from "./DeliverChallanList";
import { AppFormController, useAppForm } from "../../hooks/appHooks/useAppForm";
import { zodResolver } from "@hookform/resolvers/zod";
import {
DeliveryChallanDefaultValue,
DeliveryChallanSchema,
} from "./PurchaseSchema";
import Label from "../common/Label";
import DatePicker from "../common/DatePicker";
import { useInvoiceAttachmentTypes } from "../../hooks/masterHook/useMaster";
import SelectField from "../common/Forms/SelectField";
import Filelist from "../Expenses/Filelist";
import SingleFileUploader from "../common/SigleFileUploader";
import { localToUtc } from "../../utils/appUtils";
import WarningBlock from "../InfoBlock/WarningBlock";
import { FILE_UPLOAD_INFO } from "../../utils/staticContent";
const DeliveryChallane = ({ purchaseId }) => {
const [file, setFile] = useState(null);
const {
register,
control,
handleSubmit,
setValue,
trigger,
watch,
reset,
formState: { errors },
} = useAppForm({
resolver: zodResolver(DeliveryChallanSchema),
defaultValues: DeliveryChallanDefaultValue,
});
const { data, isLoading } = useInvoiceAttachmentTypes();
const { mutate: AddChallan, isPending } = useAddDeliverChallan(() => {
setFile(null);
setValue("attachment", null, { shouldValidate: false });
reset({
...DeliveryChallanDefaultValue,
attachment: null,
});
});
const onSubmit = async (formData) => {
const valid = await trigger();
if (!valid) return;
const { invoiceAttachmentTypeId, ...rest } = formData;
const payload = {
...rest,
attachment: formData.attachment
? {
...formData.attachment,
invoiceAttachmentTypeId,
}
: null,
purchaseInvoiceId: purchaseId,
deliveryChallanDate: formData.deliveryChallanDate
? localToUtc(formData.deliveryChallanDate)
: null,
};
AddChallan(payload);
};
const isUploaded = watch("attachment");
const isDocumentType = watch("invoiceAttachmentTypeId");
return (
<div className="row px-3 px-sm-1">
<div className="fw-semibold mb-3 fs-5">Delivery Challans</div>
<div className="col-md-6">
<form
onSubmit={handleSubmit(onSubmit)}
className="row g-3 text-start"
noValidate
>
{/* Challan Number */}
<div className="col-md-6">
<Label required>Delivery Challan No</Label>
<input
type="text"
className="form-control"
{...register("deliveryChallanNumber")}
/>
{errors?.deliveryChallanNumber && (
<small className="danger-text">
{errors.deliveryChallanNumber.message}
</small>
)}
</div>
<div className="col-md-6">
<Label required>Delivery Date</Label>
<DatePicker
name="deliveryChallanDate"
control={control}
className="w-100"
size="xs"
/>
{errors?.deliveryChallanDate && (
<small className="danger-text">
{errors.deliveryChallanDate.message}
</small>
)}
</div>
<div className="col-12">
<Label required>Description</Label>
<textarea
className="form-control form-control-sm"
rows="3"
{...register("description")}
/>
{errors?.description && (
<small className="danger-text">
{errors.description.message}
</small>
)}
</div>
<div className="col-12">
<AppFormController
name="invoiceAttachmentTypeId"
control={control}
render={({ field }) => (
<SelectField
label="Select Document Type"
options={data ?? []}
placeholder="Choose Type"
labelKeyKey="name"
valueKeyKey="id"
value={field.value}
onChange={field.onChange}
isLoading={isLoading}
className="m-0"
/>
)}
/>
{errors?.invoiceAttachmentTypeId && (
<small className="danger-text">
{errors.invoiceAttachmentTypeId.message}
</small>
)}
</div>
<SingleFileUploader
label="Upload Bill"
required
value={file}
onChange={(selectedFile) => {
setFile(selectedFile);
setValue("attachment", selectedFile, { shouldValidate: true });
}}
disabled={!isDocumentType}
onRemove={() => {
setFile(null);
setValue("attachment", null, { shouldValidate: true });
}}
error={errors?.attachment?.message}
/>
<div className="col-12 text-end my-3">
<button type="submit" className="btn btn-sm btn-primary px-4">
{isPending ? "Please Wait..." : "Submit"}
</button>
</div>
</form>
{!isUploaded && (
<WarningBlock content={FILE_UPLOAD_INFO} />
)}
</div>
<div className="col-md-6 text-start">
<div className="d-flex justiffy-content-start align-items-center gap-1 ms-2">
<i className="bx bx-history bx-xs"></i>{" "}
<p className="fw-medium mb-0">History</p>
</div>
<div className="overflow-auto " style={{ maxHeight: "420px" }}>
<DeliverChallanList purchaseId={purchaseId} />
</div>
</div>
</div>
);
};
export default DeliveryChallane;

View File

@ -1,26 +1,37 @@
import React, { useState } from "react"; import React, { useEffect, useMemo, useCallback, useState } from "react";
import { AppFormProvider, useAppForm } from "../../hooks/appHooks/useAppForm"; import { AppFormProvider, useAppForm } from "../../hooks/appHooks/useAppForm";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { import {
defaultPurchaseValue, defaultPurchaseValue,
PurchaseSchema, PurchaseSchema,
getStepFields, getStepFields,
} from "./PurchaseSchema"; } from "./PurchaseSchema";
import PurchasePartyDetails from "./PurchasePartyDetails"; import PurchasePartyDetails from "./PurchasePartyDetails";
import PurchaseTransportDetails from "./PurchaseTransportDetails"; import PurchaseTransportDetails from "./PurchaseTransportDetails";
import PurchasePaymentDetails from "./PurchasePaymentDetails"; import PurchasePaymentDetails from "./PurchasePaymentDetails";
import { useCreatePurchaseInvoice } from "../../hooks/usePurchase";
const ManagePurchase = ({ onClose }) => { import {
useCreatePurchaseInvoice,
usePurchase,
useUpdatePurchaseInvoice,
} from "../../hooks/usePurchase";
import { error } from "pdf-lib";
const ManagePurchase = ({ onClose, purchaseId }) => {
const { data } = usePurchase(purchaseId);
const [activeTab, setActiveTab] = useState(0); const [activeTab, setActiveTab] = useState(0);
const [completedTabs, setCompletedTabs] = useState([]); const [completedTabs, setCompletedTabs] = useState([]);
const stepsConfig = [ const stepsConfig = useMemo(
() => [
{ {
name: "Party Details", name: "Party Details",
icon: "bx bx-user bx-md", icon: "bx bx-user bx-md",
subtitle: "Supplier & project information", subtitle: "Supplier & project information",
component: <PurchasePartyDetails />, component: <PurchasePartyDetails purchase={data} />,
}, },
{ {
name: "Invoice & Transport", name: "Invoice & Transport",
@ -32,47 +43,104 @@ const ManagePurchase = ({ onClose }) => {
name: "Payment Details", name: "Payment Details",
icon: "bx bx-credit-card bx-md", icon: "bx bx-credit-card bx-md",
subtitle: "Amount, tax & due date", subtitle: "Amount, tax & due date",
component: <PurchasePaymentDetails />, component: <PurchasePaymentDetails purchaseId={purchaseId} />,
}, },
]; ],
[data, purchaseId]
);
const purchaseOrder = useAppForm({ const purchaseOrder = useAppForm({
resolver: zodResolver(PurchaseSchema), resolver: zodResolver(PurchaseSchema),
defaultValues: defaultPurchaseValue, defaultValues: defaultPurchaseValue,
mode: "onChange", mode: "onChange",
shouldUnregister: false,
}); });
const {reset} = purchaseOrder;
const handleNext = async () => { const { reset, formState } = purchaseOrder;
const currentStepFields = getStepFields(activeTab);
const valid = await purchaseOrder.trigger(currentStepFields); useEffect(() => {
if (!purchaseId || !data) return;
reset({
...data,
projectId: data?.project?.id,
organizationId: data?.organization?.id,
supplierId: data?.supplier?.id,
invoiceAttachmentTypeId: null,
attachments:
data?.attachments?.map((doc) => ({
fileName: doc.fileName,
base64Data: null,
contentType: doc.contentType,
documentId: doc.documentId ?? null,
invoiceAttachmentTypeId: doc.invoiceAttachmentType?.id ?? null,
fileSize: 0,
description: "",
preSignedUrl: doc.preSignedUrl,
isActive: doc.isActive ?? true,
})) || [],
});
setCompletedTabs([0, 1, 2]);
}, [purchaseId, data, reset]);
const handleNext = useCallback(async () => {
const fields = getStepFields(activeTab);
const valid = await purchaseOrder.trigger(fields);
if (!valid) return;
if (valid) {
setCompletedTabs((prev) => [...new Set([...prev, activeTab])]); setCompletedTabs((prev) => [...new Set([...prev, activeTab])]);
setActiveTab((prev) => Math.min(prev + 1, stepsConfig.length - 1)); setActiveTab((prev) => Math.min(prev + 1, stepsConfig.length - 1));
} }, [activeTab, purchaseOrder, stepsConfig.length]);
};
const handlePrev = () => { const handlePrev = useCallback(() => {
setActiveTab((prev) => Math.max(prev - 1, 0)); setActiveTab((prev) => Math.max(prev - 1, 0));
}; }, []);
const generatePatchOps = useCallback(
(formData) => {
const { dirtyFields } = formState;
return Object.keys(dirtyFields)
.filter((key) => key !== "invoiceAttachmentTypeId")
.map((key) => ({
operationType: 0,
path: `/${key}`,
op: "replace",
value: formData[key],
}));
},
[formState]
);
const { mutate: CreateInvoice, isPending } = useCreatePurchaseInvoice(() => { const { mutate: CreateInvoice, isPending } = useCreatePurchaseInvoice(() => {
reset() reset();
onClose(); onClose();
}); });
const onSubmit = (formData) => { const { mutate: updatePurchase, isPending: isUpdating } =
let payload = formData; useUpdatePurchaseInvoice(() => {
CreateInvoice(payload); reset();
}; onClose();
});
const onSubmit = useCallback(
(formData) => {
if (activeTab !== 2) return;
if (purchaseId) {
const payload = generatePatchOps(formData);
updatePurchase({ purchaseId, payload });
} else {
CreateInvoice(formData);
}
},
[activeTab, purchaseId, generatePatchOps, updatePurchase, CreateInvoice]
);
return ( return (
<div <div className="bs-stepper horizontically mt-2 b-secondry shadow-none border-0">
id="wizard-property-listing" {/* --- Steps Header --- */}
className="bs-stepper horizontically mt-2 b-secondry px-1 py-1 shadow-none border-0"
>
{/* Header */}
<div className="bs-stepper-header text-start px-0 py-1"> <div className="bs-stepper-header text-start px-0 py-1">
{stepsConfig.map((step, index) => { {stepsConfig.map((step, index) => {
const isActive = activeTab === index; const isActive = activeTab === index;
@ -81,11 +149,15 @@ const ManagePurchase = ({ onClose }) => {
return ( return (
<React.Fragment key={step.name}> <React.Fragment key={step.name}>
<div <div
className={`step ${isActive ? "active" : ""} ${ className={`step text-truncate ${isActive ? "active" : ""} ${
isCompleted ? "crossed" : "" isCompleted ? "crossed" : ""
}`} }`}
> >
<button type="button" className="step-trigger"> <button
type="button"
className={`step-trigger`}
onClick={() => purchaseId && setActiveTab(index)}
>
<span className="bs-stepper-circle"> <span className="bs-stepper-circle">
{isCompleted ? ( {isCompleted ? (
<i className="bx bx-check"></i> <i className="bx bx-check"></i>
@ -109,12 +181,21 @@ const ManagePurchase = ({ onClose }) => {
})} })}
</div> </div>
{/* Content */} {/* --- Form Content --- */}
<div className="bs-stepper-content py-2"> <div className="bs-stepper-content py-2 px-3">
<AppFormProvider {...purchaseOrder}> <AppFormProvider {...purchaseOrder}>
<form onSubmit={purchaseOrder.handleSubmit(onSubmit)}> <form
onSubmitCapture={(e) => {
if (activeTab !== 2) {
e.preventDefault();
e.stopPropagation();
}
}}
onSubmit={purchaseOrder.handleSubmit(onSubmit)}
>
{stepsConfig[activeTab].component} {stepsConfig[activeTab].component}
{/* Buttons */}
<div className="d-flex justify-content-between mt-4"> <div className="d-flex justify-content-between mt-4">
<button <button
type="button" type="button"
@ -124,21 +205,27 @@ const ManagePurchase = ({ onClose }) => {
> >
Previous Previous
</button> </button>
<di>
<div>
{activeTab < stepsConfig.length - 1 ? ( {activeTab < stepsConfig.length - 1 ? (
<button <button
type="button" type="button"
className="btn btn-sm btn-primary" className="btn btn-sm btn-primary"
onClick={handleNext} onClick={handleNext}
disabled={isPending || isUpdating}
> >
Next <i className="bx bx-sm bx-right-arrow"></i> Next
</button> </button>
) : ( ) : (
<button type="submit" className="btn btn-sm btn-primary"> <button
{isPending ? "Please Wait" : "SUbmit"} type={activeTab == 2 ? "submit" : "button"}
className="btn btn-sm btn-primary"
disabled={isPending || isUpdating}
>
{isPending || isUpdating ? "Please Wait" : "Submit"}
</button> </button>
)} )}
</di> </div>
</div> </div>
</form> </form>
</AppFormProvider> </AppFormProvider>

View File

@ -8,7 +8,8 @@ import { useDebounce } from "../../utils/appUtils";
import { usePurchaseContext } from "../../pages/purchase/PurchasePage"; import { usePurchaseContext } from "../../pages/purchase/PurchasePage";
const PurchaseList = ({ searchString }) => { const PurchaseList = ({ searchString }) => {
const { setViewPurchase } = usePurchaseContext(); const { setViewPurchase, setManagePurchase, setChallan } =
usePurchaseContext();
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const debounceSearch = useDebounce(searchString, 300); const debounceSearch = useDebounce(searchString, 300);
const { data, isLoading } = usePurchasesList( const { data, isLoading } = usePurchasesList(
@ -28,8 +29,8 @@ const PurchaseList = ({ searchString }) => {
const visibleColumns = PurchaseColumn.filter((col) => !col.hidden); const visibleColumns = PurchaseColumn.filter((col) => !col.hidden);
return ( return (
<div className="card mt-2"> <div className="card mt-2 page-min-h px-sm-4">
<div className="table-responsive px-3"> <div className="table-responsive px-2">
<table className="datatables-users table border-top text-nowrap"> <table className="datatables-users table border-top text-nowrap">
<thead> <thead>
<tr> <tr>
@ -46,7 +47,7 @@ const PurchaseList = ({ searchString }) => {
{/* LOADING */} {/* LOADING */}
{isLoading && ( {isLoading && (
<tr> <tr>
<td colSpan={3} colSpan={visibleColumns.length}> <td colSpan={visibleColumns.length + 1} className="border-0">
<div className="py-6 py-12"> <div className="py-6 py-12">
<SpinnerLoader /> <SpinnerLoader />
</div> </div>
@ -57,8 +58,7 @@ const PurchaseList = ({ searchString }) => {
<tr> <tr>
<td <td
colSpan={visibleColumns.length} colSpan={visibleColumns.length}
className="text-center py-4" className="text-center py-4 border-0"
colSpan={4}
> >
No Data Found No Data Found
</td> </td>
@ -101,20 +101,37 @@ const PurchaseList = ({ searchString }) => {
}) })
} }
> >
<i className="bx bx-eye me-2"></i> <i className="bx bx-show me-2"></i>
<span className="align-left">view</span> <span className="align-left">view</span>
</a> </a>
</li> </li>
<li> <li>
<a className="dropdown-item cursor-pointer"> <a
<i className="bx bx-trash me-2"></i> className="dropdown-item cursor-pointer"
<span className="align-left">Add</span> onClick={() =>
setManagePurchase({
isOpen: true,
purchaseId: item.id,
})
}
>
<i className="bx bx-edit me-2"></i>
<span className="align-left">Edit</span>
</a> </a>
</li> </li>
<li> <li>
<a className="dropdown-item cursor-pointer"> <a
<i className="bx bx-trash me-2"></i> className="dropdown-item cursor-pointer"
<span className="align-left">Delete</span> onClick={() =>
setChallan({
isOpen: true,
purchaseId: item.id,
})
}
>
<i className="bx bx-file bx-plus me-2"></i>
<span className="align-left">Add Delivery Challan</span>
</a> </a>
</li> </li>
</ul> </ul>

View File

@ -1,12 +1,19 @@
import React from "react"; import React from "react";
import { AppFormController, useAppFormContext } from "../../hooks/appHooks/useAppForm"; import {
AppFormController,
useAppFormContext,
} from "../../hooks/appHooks/useAppForm";
import Label from "../common/Label"; import Label from "../common/Label";
import DatePicker from "../common/DatePicker"; import DatePicker from "../common/DatePicker";
import { import {
SelectFieldSearch, SelectFieldSearch,
SelectProjectField, SelectProjectField,
} from "../common/Forms/SelectFieldServerSide"; } from "../common/Forms/SelectFieldServerSide";
import { useGlobaleOrganizations, useOrganization, useOrganizationsList } from "../../hooks/useOrganization"; import {
useGlobaleOrganizations,
useOrganization,
useOrganizationsList,
} from "../../hooks/useOrganization";
import { ITEMS_PER_PAGE } from "../../utils/constants"; import { ITEMS_PER_PAGE } from "../../utils/constants";
const PurchasePartyDetails = () => { const PurchasePartyDetails = () => {
@ -18,9 +25,8 @@ const PurchasePartyDetails = () => {
formState: { errors }, formState: { errors },
} = useAppFormContext(); } = useAppFormContext();
return ( return (
<div className="row g-2 text-start"> <div className="row g-3 text-start">
{/* Title */} {/* Title */}
<div className="col-12 col-md-6"> <div className="col-12 col-md-6">
<Label htmlFor="title" required> <Label htmlFor="title" required>
@ -30,7 +36,7 @@ const PurchasePartyDetails = () => {
<input <input
id="title" id="title"
type="text" type="text"
className={`form-control form-control-md ${ className={`form-control form-control-xs ${
errors?.title ? "is-invalid" : "" errors?.title ? "is-invalid" : ""
}`} }`}
{...register("title")} {...register("title")}
@ -44,7 +50,7 @@ const PurchasePartyDetails = () => {
{/* Project ID */} {/* Project ID */}
<div className="col-12 col-md-6"> <div className="col-12 col-md-6">
<SelectProjectField <SelectProjectField
className={`form-control form-control-md ${ className={`form-control form-control-xs ${
errors?.projectId ? "is-invalid" : "" errors?.projectId ? "is-invalid" : ""
}`} }`}
label="Project" label="Project"
@ -61,40 +67,27 @@ const PurchasePartyDetails = () => {
/> />
</div> </div>
{/* Organization */} <div className="col-12 col-md-6 my-0">
<div className="col-12 col-md-6">
{/* <input
id="organizationId"
type="text"
className={`form-control form-control-md `}
{...register("organizationId")}
/> */}
<AppFormController <AppFormController
name="organizationId" name="organizationId"
control={control} control={control}
render={({ field }) => ( render={({ field }) => (
<SelectFieldSearch <SelectFieldSearch
{...field}
label="Organization" label="Organization"
placeholder="Select Organization" placeholder="Select Organization"
required required
value={field.value}
onChange={field.onChange}
valueKey="id" valueKey="id"
labelKey="name" labelKey="name"
useFetchHook={useGlobaleOrganizations} useFetchHook={useGlobaleOrganizations}
hookParams={[ITEMS_PER_PAGE, 1]} hookParams={[ITEMS_PER_PAGE, 1]}
errors={errors?.organizationId} error={errors?.organizationId?.message}
/> />
)} )}
/> />
</div> </div>
{/* Supplier */} <div className="col-12 col-md-6 my-0">
<div className="col-12 col-md-6">
<AppFormController <AppFormController
name="supplierId" name="supplierId"
control={control} control={control}
@ -109,24 +102,19 @@ const PurchasePartyDetails = () => {
labelKey="name" labelKey="name"
useFetchHook={useGlobaleOrganizations} useFetchHook={useGlobaleOrganizations}
hookParams={[ITEMS_PER_PAGE, 1]} hookParams={[ITEMS_PER_PAGE, 1]}
errors={errors?.organizationId} errors={errors.supplierId}
/> />
)} )}
/> />
{errors?.supplierId && (
<div className="danger-text">{errors.supplierId.message}</div>
)}
</div> </div>
{/* Billing Address */} <div className="col-12 col-md-6 my-0">
<div className="col-12 col-md-6">
<Label htmlFor="billingAddress">Billing Address</Label> <Label htmlFor="billingAddress">Billing Address</Label>
<textarea <textarea
id="billingAddress" id="billingAddress"
rows="2" rows="2"
className={`form-control form-control-md `} className={`form-control form-control-xs `}
{...register("billingAddress")} {...register("billingAddress")}
/> />
@ -135,13 +123,13 @@ const PurchasePartyDetails = () => {
)} )}
</div> </div>
<div className="col-12 col-md-6"> <div className="col-12 col-md-6 my-0 mb-1">
<Label htmlFor="shippingAddress">Shipping Address</Label> <Label htmlFor="shippingAddress">Shipping Address</Label>
<textarea <textarea
id="shippingAddress" id="shippingAddress"
rows="2" rows="2"
className={`form-control form-control-md `} className={`form-control form-control-xs `}
{...register("shippingAddress")} {...register("shippingAddress")}
/> />
@ -159,7 +147,7 @@ const PurchasePartyDetails = () => {
<input <input
id="purchaseOrderNumber" id="purchaseOrderNumber"
type="text" type="text"
className={`form-control form-control-md `} className={`form-control form-control-xs `}
{...register("purchaseOrderNumber")} {...register("purchaseOrderNumber")}
/> />
@ -171,7 +159,7 @@ const PurchasePartyDetails = () => {
</div> </div>
{/* Purchase Order Date */} {/* Purchase Order Date */}
<div className="col-12 col-md-6"> <div className="col-12 col-md-6 mb-1">
<Label htmlFor="purchaseOrderDate" required> <Label htmlFor="purchaseOrderDate" required>
Purchase Order Date Purchase Order Date
</Label> </Label>
@ -179,6 +167,7 @@ const PurchasePartyDetails = () => {
<DatePicker <DatePicker
control={control} control={control}
name="purchaseOrderDate" name="purchaseOrderDate"
size="xs"
className={` w-full ${ className={` w-full ${
errors?.purchaseOrderDate ? "is-invalid" : "" errors?.purchaseOrderDate ? "is-invalid" : ""
}`} }`}
@ -205,7 +194,7 @@ const PurchasePartyDetails = () => {
</div> </div>
)} )}
</div> </div>
<div className="col-12 col-md-6"> <div className="col-12 col-md-6 mb-1">
<Label htmlFor="proformaInvoiceAmountt">Proforma Amount</Label> <Label htmlFor="proformaInvoiceAmountt">Proforma Amount</Label>
<input <input
id="proformaInvoiceAmount" id="proformaInvoiceAmount"
@ -220,13 +209,14 @@ const PurchasePartyDetails = () => {
</div> </div>
)} )}
</div> </div>
<div className="col-12 col-md-6"> <div className="col-12 col-md-6 mb-2">
<Label htmlFor="proformaInvoiceDate">Proforma Date</Label> <Label htmlFor="proformaInvoiceDate">Proforma Date</Label>
<DatePicker <DatePicker
control={control} control={control}
name="proformaInvoiceDate" name="proformaInvoiceDate"
className="w-full" className="w-full"
size="xs"
/> />
{errors?.proformaInvoiceDate && ( {errors?.proformaInvoiceDate && (

View File

@ -1,11 +1,21 @@
import React, { useEffect } from "react"; import React, { useEffect } from "react";
import Label from "../common/Label"; import Label from "../common/Label";
import { useAppFormContext } from "../../hooks/appHooks/useAppForm"; import {
AppFormController,
useAppFormContext,
} from "../../hooks/appHooks/useAppForm";
import DatePicker from "../common/DatePicker"; import DatePicker from "../common/DatePicker";
import { useInvoiceAttachmentTypes } from "../../hooks/masterHook/useMaster"; import { useInvoiceAttachmentTypes } from "../../hooks/masterHook/useMaster";
import Filelist from "../Expenses/Filelist";
import SelectField from "../common/Forms/SelectField";
import { useWatch } from "react-hook-form";
import WarningBlock from "../InfoBlock/WarningBlock";
import { FILE_UPLOAD_INFO } from "../../utils/staticContent";
const PurchasePaymentDetails = () => { const PurchasePaymentDetails = ({ purchaseId = null }) => {
const { data, isLoading, error, isError } = useInvoiceAttachmentTypes(); const { data, isLoading, error, isError } = useInvoiceAttachmentTypes();
const { data: InvoiceDocTypes, isLoading: invoiceDocLoading } =
useInvoiceAttachmentTypes();
const { const {
register, register,
watch, watch,
@ -25,9 +35,78 @@ const PurchasePaymentDetails = () => {
setValue("totalAmount", (base + tax).toFixed(2)); setValue("totalAmount", (base + tax).toFixed(2));
} }
}, [baseAmount, taxAmount, setValue]); }, [baseAmount, taxAmount, setValue]);
const invoiceAttachmentType = watch("invoiceAttachmentTypeId");
const files = watch("attachments");
const toBase64 = (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result.split(",")[1]);
reader.onerror = (error) => reject(error);
});
const onFileChange = async (e) => {
const newFiles = Array.from(e.target.files);
if (newFiles.length === 0) return;
const existingFiles = watch("attachments") || [];
const parsedFiles = await Promise.all(
newFiles.map(async (file) => {
const base64Data = await toBase64(file);
return {
fileName: file.name,
base64Data,
contentType: file.type,
fileSize: file.size,
description: "",
isActive: true,
invoiceAttachmentTypeId: invoiceAttachmentType,
isNew: true, // <-- temp
tempId: crypto.randomUUID(), // temp - id
};
})
);
const combinedFiles = [
...existingFiles,
...parsedFiles.filter(
(newFile) =>
!existingFiles.some(
(f) =>
f.fileName === newFile.fileName && f.fileSize === newFile.fileSize
)
),
];
setValue("attachments", combinedFiles, {
shouldDirty: true,
shouldValidate: true,
});
};
const removeFile = (index) => {
const updated = files.flatMap((file, i) => {
// NEW FILE remove completely
if (file.isNew && file.tempId === index) {
return []; // remove from array
}
// EXISTING FILE mark inactive
if (!file.isNew && file.documentId === index) {
return [{ ...file, isActive: false }];
}
return [file];
});
setValue("attachments", updated, {
shouldDirty: true,
shouldValidate: true,
});
};
return ( return (
<div className="row g-2 text-start"> <div className="row g-1 text-start">
<div className="col-12 col-md-4"> <div className="col-12 col-md-4">
<Label htmlFor="baseAmount" required> <Label htmlFor="baseAmount" required>
Base Amount Base Amount
@ -36,8 +115,8 @@ const PurchasePaymentDetails = () => {
<input <input
id="baseAmount" id="baseAmount"
type="number" type="number"
className="form-control form-control-md" className="form-control form-control-xs"
{...register("baseAmount")} {...register("baseAmount", { valueAsNumber: true })}
/> />
{errors?.baseAmount && ( {errors?.baseAmount && (
@ -55,8 +134,8 @@ const PurchasePaymentDetails = () => {
<input <input
id="taxAmount" id="taxAmount"
type="number" type="number"
className="form-control form-control-md" className="form-control form-control-xs"
{...register("taxAmount")} {...register("taxAmount", { valueAsNumber: true })}
/> />
{errors?.taxAmount && ( {errors?.taxAmount && (
@ -74,8 +153,8 @@ const PurchasePaymentDetails = () => {
<input <input
id="totalAmount" id="totalAmount"
type="number" type="number"
className="form-control form-control-md" className="form-control form-control-xs"
{...register("totalAmount")} {...register("totalAmount", { valueAsNumber: true })}
readOnly readOnly
/> />
@ -92,8 +171,8 @@ const PurchasePaymentDetails = () => {
<input <input
id="transportCharges" id="transportCharges"
type="number" type="number"
className="form-control form-control-md" className="form-control form-control-xs"
{...register("transportCharges")} {...register("transportCharges", { valueAsNumber: true })}
/> />
{errors?.transportCharges && ( {errors?.transportCharges && (
@ -110,6 +189,7 @@ const PurchasePaymentDetails = () => {
name={"paymentDueDate"} name={"paymentDueDate"}
control={control} control={control}
className="w-full" className="w-full"
size="xs"
/> />
{errors?.paymentDueDate && ( {errors?.paymentDueDate && (
@ -119,7 +199,7 @@ const PurchasePaymentDetails = () => {
)} )}
</div> </div>
<div className="col-12"> <div className="col-12 mb-2">
<Label htmlFor="description" required> <Label htmlFor="description" required>
Description Description
</Label> </Label>
@ -127,7 +207,7 @@ const PurchasePaymentDetails = () => {
<textarea <textarea
id="description" id="description"
rows="3" rows="3"
className="form-control form-control-md" className="form-control form-control-xs"
{...register("description")} {...register("description")}
/> />
@ -137,6 +217,90 @@ const PurchasePaymentDetails = () => {
</div> </div>
)} )}
</div> </div>
<div className="col-12">
<AppFormController
name="invoiceAttachmentTypeId"
control={control}
render={({ field }) => (
<SelectField
label="Select Document Type"
options={InvoiceDocTypes ?? []}
placeholder="Choose Type"
labelKeyKey="name"
valueKeyKey="id"
value={field.value}
onChange={field.onChange}
isLoading={invoiceDocLoading}
className="m-0"
/>
)}
/>
{errors?.invoiceAttachmentTypeId && (
<small className="danger-text">
{errors.invoiceAttachmentTypeId.message}
</small>
)}
</div>
<div className="text-start">
<div className="col-md-12">
<Label className="form-label" required>
Upload Bill{" "}
</Label>
<div
className="border border-secondary border-dashed rounded p-4 text-center bg-textMuted position-relative"
style={{ cursor: "pointer" }}
onClick={() => document.getElementById("attachments").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">(PDF, JPG, PNG, max 5MB)</small>
<input
type="file"
id="attachments"
accept=".pdf,.jpg,.jpeg,.png"
multiple
disabled={!invoiceAttachmentType}
style={{ display: "none" }}
{...register("attachments")}
onChange={(e) => {
onFileChange(e);
e.target.value = "";
}}
/>
</div>
{errors.attachments && (
<small className="danger-text">{errors.attachments.message}</small>
)}
{files.length > 0 && (
<Filelist
files={files}
removeFile={removeFile}
expenseToEdit={purchaseId}
/>
)}
{Array.isArray(errors.attachments) &&
errors.attachments.map((fileError, index) => (
<div key={index} className="danger-text small mt-1">
{
(fileError?.fileSize?.message ||
fileError?.contentType?.message ||
fileError?.base64Data?.message,
fileError?.documentId?.message)
}
</div>
))}
{!invoiceAttachmentType && (
<WarningBlock content={FILE_UPLOAD_INFO} />
)}
</div>
</div>
</div> </div>
); );
}; };

View File

@ -1,39 +1,31 @@
import { z } from "zod"; import { z } from "zod";
import { normalizeAllowedContentTypes } from "../../utils/appUtils"; import { normalizeAllowedContentTypes } from "../../utils/appUtils";
export const AttachmentSchema = (allowedContentType, maxSizeAllowedInMB) => { const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
const allowedTypes = normalizeAllowedContentTypes(allowedContentType); const ALLOWED_TYPES = [
"application/pdf",
"image/png",
"image/jpg",
"image/jpeg",
];
return z.object({ export const AttachmentSchema = z.object({
invoiceAttachmentTypeId: z.string().nullable(),
fileName: z.string().min(1, { message: "Filename is required" }), fileName: z.string().min(1, { message: "Filename is required" }),
base64Data: z.string().min(1, { message: "File data is required" }), base64Data: z.string().nullable(),
invoiceAttachmentTypeId: z
.string()
.min(1, { message: "File data is required" }),
contentType: z contentType: z
.string() .string()
.min(1, { message: "MIME type is required" }) .refine((val) => ALLOWED_TYPES.includes(val), {
.refine( message: "Only PDF, PNG, JPG, or JPEG files are allowed",
(val) => (allowedTypes.length ? allowedTypes.includes(val) : true), }),
{ fileSize: z.number().max(MAX_FILE_SIZE, {
message: `File type must be one of: ${allowedTypes.join(", ")}`, message: "File size must be less than or equal to 5MB",
} }),
),
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(""), description: z.string().optional().default(""),
isActive: z.boolean(), isActive: z.boolean().default(true),
documentId:z.string().nullable().default(null)
}); });
};
export const PurchaseSchema = z.object({ export const PurchaseSchema = z.object({
title: z.string().min(1, { message: "Title is required" }), title: z.string().min(1, { message: "Title is required" }),
@ -49,7 +41,7 @@ export const PurchaseSchema = z.object({
proformaInvoiceNumber: z.string().nullable(), proformaInvoiceNumber: z.string().nullable(),
proformaInvoiceDate: z.coerce.date().nullable(), proformaInvoiceDate: z.coerce.date().nullable(),
proformaInvoiceAmount: z.string().nullable(), proformaInvoiceAmount: z.coerce.number().optional(),
invoiceNumber: z.string().nullable(), invoiceNumber: z.string().nullable(),
invoiceDate: z.coerce.date().nullable(), invoiceDate: z.coerce.date().nullable(),
@ -59,21 +51,19 @@ export const PurchaseSchema = z.object({
acknowledgmentDate: z.coerce.date().nullable(), acknowledgmentDate: z.coerce.date().nullable(),
acknowledgmentNumber: z.string().nullable(), acknowledgmentNumber: z.string().nullable(),
baseAmount: z.string().min(1, { message: "Base amount is required" }), baseAmount: z.number().min(1, { message: "Base amount is required" }),
taxAmount: z.string().min(1, { message: "Tax amount is required" }), taxAmount: z.number().min(1, { message: "Tax amount is required" }),
totalAmount: z.string().min(1, { message: "Total amount is required" }), totalAmount: z.number().min(1, { message: "Total amount is required" }),
paymentDueDate: z.coerce.date().nullable(), paymentDueDate: z.coerce.date().nullable(),
transportCharges: z.string().nullable(), transportCharges: z.number().nullable(),
description: z.string().min(1, { message: "Description is required" }), description: z.string().min(1, { message: "Description is required" }),
invoiceAttachmentTypeId:z.string().nullable(),
attachments: z
.array(AttachmentSchema)
attachments: z.array(AttachmentSchema([], 25)).optional(),
}); });
// deliveryChallanNo: z
// .string()
// .min(1, { message: "Delivery Challan No is required" }),
// deliveryDate: z.string().min(1, { message: "Delevery Date is required" }),
// shippingAddress: z.string().min(1, { message: "Delevery Date is required" }),
export const defaultPurchaseValue = { export const defaultPurchaseValue = {
title: "", title: "",
@ -88,7 +78,7 @@ export const defaultPurchaseValue = {
proformaInvoiceNumber: null, proformaInvoiceNumber: null,
proformaInvoiceDate: null, proformaInvoiceDate: null,
proformaInvoiceAmount: null, proformaInvoiceAmount: 0,
invoiceNumber: null, invoiceNumber: null,
invoiceDate: null, invoiceDate: null,
@ -98,13 +88,13 @@ export const defaultPurchaseValue = {
acknowledgmentNumber: null, acknowledgmentNumber: null,
acknowledgmentDate: null, acknowledgmentDate: null,
baseAmount: "", baseAmount: 0,
taxAmount: "", taxAmount: 0,
totalAmount: "", totalAmount: 0,
paymentDueDate: null, paymentDueDate: null,
transportCharges: null, transportCharges: null,
description: "", description: "",
invoiceAttachmentTypeId:null,
attachments: [], attachments: [],
}; };
@ -138,9 +128,62 @@ export const getStepFields = (stepIndex) => {
"totalAmount", "totalAmount",
"transportCharges", "transportCharges",
"paymentDueDate", "paymentDueDate",
"invoiceAttachmentTypeId",
"description", "description",
"attachments"
], ],
}; };
return stepFieldMap[stepIndex] || []; return stepFieldMap[stepIndex] || [];
}; };
export const SingleAttachmentSchema = z.object({
fileName: z.string().min(1, { message: "File name is required" }),
base64Data: z.string().min(1, { message: "File data is required" }),
invoiceAttachmentTypeId: z.string().nullable(),
contentType: z
.string()
.min(1, { message: "MIME type is required" })
.refine(
(val) =>
["application/pdf", "image/jpeg", "image/jpg", "image/png"].includes(
val
),
{
message: "File type must be PDF, JPG, JPEG or PNG",
}
),
fileSize: z
.number()
.int()
.nonnegative("fileSize must be ≥ 0")
.max(5 * 1024 * 1024, "File size must be ≤ 5MB"),
description: z.string().optional().default(""),
isActive: z.boolean(),
});
export const DeliveryChallanSchema = z.object({
deliveryChallanNumber: z
.string()
.min(1, { message: "Challan Number required" }),
invoiceAttachmentTypeId: z.string().nullable(),
deliveryChallanDate: z.string().min(1, { message: "Deliver date required" }),
description: z.string().min(1, { message: "Description required" }),
attachment: z.any().refine(
(val) => val && typeof val === "object" && !!val.base64Data,
{
message: "Please upload document",
}
),
});
export const DeliveryChallanDefaultValue = {
deliveryChallanNumber: "",
deliveryChallanDate: "",
description: "",
attachment: null,
invoiceAttachmentTypeId: null,
};

View File

@ -10,7 +10,7 @@ const PurchaseTransportDetails = () => {
} = useAppFormContext(); } = useAppFormContext();
return ( return (
<div className="row g-2 text-start"> <div className="row g-3 text-start">
{/* Invoice Number */} {/* Invoice Number */}
<div className="col-12 col-md-6"> <div className="col-12 col-md-6">
<Label htmlFor="invoiceNumber" required> <Label htmlFor="invoiceNumber" required>
@ -20,7 +20,7 @@ const PurchaseTransportDetails = () => {
<input <input
id="invoiceNumber" id="invoiceNumber"
type="text" type="text"
className="form-control form-control-md" className="form-control form-control-xs"
{...register("invoiceNumber")} {...register("invoiceNumber")}
/> />
@ -36,7 +36,7 @@ const PurchaseTransportDetails = () => {
<Label htmlFor="invoiceDate">Invoice Date</Label> <Label htmlFor="invoiceDate">Invoice Date</Label>
<DatePicker control={control} name="invoiceDate" className="w-full"/> <DatePicker control={control} name="invoiceDate" className="w-full" size="xs"/>
{errors?.invoiceDate && ( {errors?.invoiceDate && (
<div className="small text-danger mt-1"> <div className="small text-danger mt-1">
@ -52,7 +52,7 @@ const PurchaseTransportDetails = () => {
<input <input
id="eWayBillNumber" id="eWayBillNumber"
type="text" type="text"
className="form-control form-control-md" className="form-control form-control-xs"
{...register("eWayBillNumber")} {...register("eWayBillNumber")}
/> />
@ -84,7 +84,7 @@ const PurchaseTransportDetails = () => {
<input <input
id="invoiceReferenceNumber" id="invoiceReferenceNumber"
type="text" type="text"
className="form-control form-control-md" className="form-control form-control-xs"
{...register("invoiceReferenceNumber")} {...register("invoiceReferenceNumber")}
/> />
@ -102,7 +102,7 @@ const PurchaseTransportDetails = () => {
<input <input
id="acknowledgmentNumber" id="acknowledgmentNumber"
type="text" type="text"
className="form-control form-control-md" className="form-control form-control-xs"
{...register("acknowledgmentNumber")} {...register("acknowledgmentNumber")}
/> />
@ -113,10 +113,10 @@ const PurchaseTransportDetails = () => {
)} )}
</div> </div>
<div className="col-12 col-md-6"> <div className="col-12 col-md-6 mb-2">
<Label htmlFor="acknowledgmentDate">Acknowledgment Date</Label> <Label htmlFor="acknowledgmentDate">Acknowledgment Date</Label>
<DatePicker control={control} name="acknowledgmentDate" className="w-full"/> <DatePicker control={control} name="acknowledgmentDate" className="w-full" size="xs"/>
{errors?.acknowledgmentDate && ( {errors?.acknowledgmentDate && (
<div className="small text-danger mt-1"> <div className="small text-danger mt-1">

View File

@ -26,13 +26,13 @@ export const PurchaseColumn = [
{ {
key: "project", key: "project",
label: "Project", label: "Project",
className: "text-start d-none d-sm-table-cell", className: "text-start ",
render: (item) => <span>{item?.project?.name || "NA"}</span>, render: (item) => <span>{item?.project?.name || "NA"}</span>,
}, },
{ {
key: "supplier", key: "supplier",
label: "Supplier", label: "Supplier",
className: "text-start d-none d-sm-table-cell", className: "text-start ",
render: (item) => <span>{item?.supplier?.name || "NA"}</span>, render: (item) => <span>{item?.supplier?.name || "NA"}</span>,
}, },
{ {
@ -52,7 +52,7 @@ export const PurchaseColumn = [
{ {
key: "totalAmount", key: "totalAmount",
label: "Total Amount", label: "Total Amount",
className: " text-end w-min", className: "text-end",
render: (item) => ( render: (item) => (
<span>{formatFigure(item?.totalAmount, { type: "currency" })}</span> <span>{formatFigure(item?.totalAmount, { type: "currency" })}</span>
), ),

View File

@ -39,13 +39,13 @@ export const useOrganizationModal = () => {
// ================================Query============================================================= // ================================Query=============================================================
export const useGlobaleOrganizations = (pageSize, pageNumber, searchString) => { export const useGlobaleOrganizations = (pageSize, pageNumber,id, searchString) => {
return useQuery({ return useQuery({
queryKey: ["global_organization",pageSize, pageNumber, searchString], queryKey: ["global_organization",pageSize, pageNumber,id, searchString],
queryFn: async () => { queryFn: async () => {
const resp = await OrganizationRepository.getGlobalOrganization( const resp = await OrganizationRepository.getGlobalOrganization(
pageSize, pageSize,
pageNumber, pageNumber,id,
searchString searchString
); );
return resp.data; return resp.data;

View File

@ -31,6 +31,19 @@ export const usePurchasesList = (
}); });
}; };
export const useDeliverChallane = (purchaseInvoiceId) => {
return useQuery({
queryKey: ["deliverliy_challane", purchaseInvoiceId],
queryFn: async () => {
const resp = await PurchaseRepository.GetDeliveryChallan(
purchaseInvoiceId
);
return resp.data;
},
enabled: !!purchaseInvoiceId,
});
};
export const usePurchase = (id) => { export const usePurchase = (id) => {
return useQuery({ return useQuery({
queryKey: ["purchase", id], queryKey: ["purchase", id],
@ -49,6 +62,7 @@ export const useCreatePurchaseInvoice = (onSuccessCallback) => {
mutationFn: async (payload) => mutationFn: async (payload) =>
await PurchaseRepository.CreatePurchase(payload), await PurchaseRepository.CreatePurchase(payload),
onSuccess: (data, variables) => { onSuccess: (data, variables) => {
queryClient.invalidateQueries({ queryKey: ["purchase_list"] });
showToast("Purchase Invoice Created successfully", "success"); showToast("Purchase Invoice Created successfully", "success");
if (onSuccessCallback) onSuccessCallback(); if (onSuccessCallback) onSuccessCallback();
}, },
@ -62,3 +76,47 @@ export const useCreatePurchaseInvoice = (onSuccessCallback) => {
}, },
}); });
}; };
export const useUpdatePurchaseInvoice = (onSuccessCallback) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ purchaseId, payload }) =>
PurchaseRepository.UpdatePurchase(purchaseId, payload),
onSuccess: (data, variables) => {
queryClient.invalidateQueries({ queryKey: ["purchase_list"] });
queryClient.invalidateQueries({ queryKey: ["purchase"] });
showToast("Purchase Invoice Updated successfully", "success");
if (onSuccessCallback) onSuccessCallback();
},
onError: (error) => {
showToast(
error?.response?.data?.message ||
error.message ||
"Failed to create invoice",
"error"
);
},
});
};
export const useAddDeliverChallan = (onSuccessCallback) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (payload) =>
PurchaseRepository.addDelievryChallan(payload),
onSuccess: (data, variables) => {
queryClient.invalidateQueries({ queryKey: ["deliverliy_challane"] });
showToast("Challan added successfully", "success");
if (onSuccessCallback) onSuccessCallback();
},
onError: (error) => {
showToast(
error?.response?.data?.message ||
error.message ||
"Failed to create invoice",
"error"
);
},
});
};

View File

@ -63,7 +63,7 @@ const ExpensePage = () => {
const [ViewDocument, setDocumentView] = useState({ const [ViewDocument, setDocumentView] = useState({
IsOpen: false, IsOpen: false,
Image: null, Images: null,
}); });
const IsCreatedAble = useHasUserPermission(CREATE_EXEPENSE); const IsCreatedAble = useHasUserPermission(CREATE_EXEPENSE);
@ -260,10 +260,10 @@ const ExpensePage = () => {
<GlobalModel <GlobalModel
isOpen isOpen
size="md" size="md"
key={ViewDocument.Image ?? "doc"} key={ViewDocument.Images ?? "doc"}
closeModal={() => setDocumentView({ IsOpen: false, Image: null })} closeModal={() => setDocumentView({ IsOpen: false, Images: null })}
> >
<PreviewDocument imageUrl={ViewDocument.Image} /> <PreviewDocument files={ViewDocument.Images} />
</GlobalModel> </GlobalModel>
)} )}
</div> </div>

View File

@ -24,6 +24,9 @@ import { useProjectAccess } from "../../hooks/useProjectAccess";
import "./ProjectDetails.css"; import "./ProjectDetails.css";
import ProjectOrganizations from "../../components/Project/ProjectOrganizations"; import ProjectOrganizations from "../../components/Project/ProjectOrganizations";
import ProjectStatistics from "../../components/Project/ProjectStatistics";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { REGULARIZE_ATTENDANCE, SELF_ATTENDANCE, TEAM_ATTENDANCE } from "../../utils/constants";
const ProjectDetails = () => { const ProjectDetails = () => {
const projectId = useSelectedProject(); const projectId = useSelectedProject();
@ -34,6 +37,10 @@ const ProjectDetails = () => {
useProjectDetails(projectId); useProjectDetails(projectId);
const { canView, loading: permsLoading } = useProjectAccess(projectId); const { canView, loading: permsLoading } = useProjectAccess(projectId);
const canRegularize = useHasUserPermission(REGULARIZE_ATTENDANCE);
const canTeamAttendance = useHasUserPermission(TEAM_ATTENDANCE);
const canSelfAttendance = useHasUserPermission(SELF_ATTENDANCE);
useEffect(() => { useEffect(() => {
if (!projectId && projectNames.length > 0) { if (!projectId && projectNames.length > 0) {
@ -82,13 +89,16 @@ const ProjectDetails = () => {
<div className="row"> <div className="row">
<div className="col-lg-4 col-md-5 mt-2"> <div className="col-lg-4 col-md-5 mt-2">
<AboutProject /> <AboutProject />
<ProjectOverview project={projectId} /> <div className="card"><ProjectStatistics project={projectId} /></div>
</div> </div>
<div className="col-lg-8 col-md-7 mt-2"> <div className="col-lg-8 col-md-7 mt-2">
<ProjectProgressChart ShowAllProject="false" DefaultRange="1M" /> <ProjectProgressChart ShowAllProject="false" DefaultRange="1M" />
{(canRegularize || canTeamAttendance || canSelfAttendance) && (
<div className="mt-5"> <div className="mt-5">
<AttendanceOverview /> <AttendanceOverview />
</div> </div>
)}
</div> </div>
</div> </div>
); );

View File

@ -5,6 +5,7 @@ import GlobalModel from "../../components/common/GlobalModel";
import ManagePurchase from "../../components/purchase/ManagePurchase"; import ManagePurchase from "../../components/purchase/ManagePurchase";
import PurchaseList from "../../components/purchase/PurchaseList"; import PurchaseList from "../../components/purchase/PurchaseList";
import ViewPurchase from "../../components/purchase/ViewPurchase"; import ViewPurchase from "../../components/purchase/ViewPurchase";
import DeliveryChallane from "../../components/purchase/DeliveryChallane";
export const PurchaseContext = createContext(); export const PurchaseContext = createContext();
export const usePurchaseContext = () => { export const usePurchaseContext = () => {
@ -18,7 +19,14 @@ export const usePurchaseContext = () => {
}; };
const PurchasePage = () => { const PurchasePage = () => {
const [searchText, setSearchText] = useState(""); const [searchText, setSearchText] = useState("");
const [addePurchase, setAddedPurchase] = useState(false); const [addChallan, setChallan] = useState({
isOpen: false,
purchaseId: null,
});
const [managePurchase, setManagePurchase] = useState({
isOpen: false,
purchaseId: null,
});
const [viewPurchaseState, setViewPurchase] = useState({ const [viewPurchaseState, setViewPurchase] = useState({
isOpen: false, isOpen: false,
purchaseId: null, purchaseId: null,
@ -26,8 +34,9 @@ const PurchasePage = () => {
const contextValue = { const contextValue = {
setViewPurchase, setViewPurchase,
setManagePurchase,
setChallan,
}; };
console.log(ViewPurchase);
return ( return (
<PurchaseContext.Provider value={contextValue}> <PurchaseContext.Provider value={contextValue}>
<div className="container-fluid"> <div className="container-fluid">
@ -38,9 +47,9 @@ const PurchasePage = () => {
{ label: "Purchase" }, { label: "Purchase" },
]} ]}
/> />
<div className="card"> <div className="card px-sm-4 my-3">
<div className="row p-2"> <div className="row p-2">
<div className="col-12 col-md-6 text-start"> <div className="col-12 col-sm-6 text-start">
{" "} {" "}
<label className="mb-0"> <label className="mb-0">
<input <input
@ -53,10 +62,15 @@ const PurchasePage = () => {
/> />
</label> </label>
</div> </div>
<di className="col-6 text-end"> <di className="col-sm-6 text-end">
<button <button
className="btn btn-sm btn-primary" className="btn btn-sm btn-primary"
onClick={() => setAddedPurchase(true)} onClick={() =>
setManagePurchase({
isOpen: true,
purchaseId: null,
})
}
> >
<i className="bx bx-plus-circle me-2"></i>Add <i className="bx bx-plus-circle me-2"></i>Add
</button> </button>
@ -65,13 +79,26 @@ const PurchasePage = () => {
</div> </div>
<PurchaseList searchString={searchText} /> <PurchaseList searchString={searchText} />
{addePurchase && ( {managePurchase.isOpen && (
<GlobalModel <GlobalModel
isOpen={addePurchase} isOpen={managePurchase.isOpen}
size="lg" size="lg"
closeModal={() => setAddedPurchase(false)} closeModal={() =>
setManagePurchase({
isOpen: false,
purchaseId: null,
})
}
> >
<ManagePurchase onClose={() => setAddedPurchase(false)} /> <ManagePurchase
onClose={() =>
setManagePurchase({
isOpen: false,
purchaseId: null,
})
}
purchaseId={managePurchase.purchaseId}
/>
</GlobalModel> </GlobalModel>
)} )}
@ -86,6 +113,18 @@ const PurchasePage = () => {
<ViewPurchase purchaseId={viewPurchaseState.purchaseId} /> <ViewPurchase purchaseId={viewPurchaseState.purchaseId} />
</GlobalModel> </GlobalModel>
)} )}
{addChallan.isOpen && (
<GlobalModel size="xl"
isOpen={addChallan.isOpen}
closeModal={() => setChallan({ isOpen: false, purchaseId: null })}
>
<DeliveryChallane
purchaseId={addChallan.purchaseId}
onClose={() => setChallan({ isOpen: false, purchaseId: null })}
/>
</GlobalModel>
)}
</div> </div>
</PurchaseContext.Provider> </PurchaseContext.Provider>
); );

View File

@ -41,9 +41,11 @@ const OrganizationRepository = {
return api.get(url); return api.get(url);
}, },
getGlobalOrganization: (pageSize, pageNumber, searchString) => getGlobalOrganization: (pageSize, pageNumber, searchString, id) =>
api.get( api.get(
`/api/Organization/list/basic?pageSize=${pageSize}&pageNumber=${pageNumber}&searchString=${searchString}` `/api/Organization/list/basic?pageSize=${pageSize}&pageNumber=${pageNumber}${
id ? `&id=${id}` : ""
}&searchString=${searchString}`
), ),
}; };

View File

@ -10,6 +10,10 @@ export const PurchaseRepository = {
GetPurchase: (id) => api.get(`/api/PurchaseInvoice/details/${id}`), GetPurchase: (id) => api.get(`/api/PurchaseInvoice/details/${id}`),
UpdatePurchase: (id, data) => UpdatePurchase: (id, data) =>
api.patch(`/api/PurchaseInvoice/edit/${id}`, data), api.patch(`/api/PurchaseInvoice/edit/${id}`, data),
GetDeliveryChallan: (purchaseInvoiceId) =>
api.get(`/api/PurchaseInvoice/delivery-challan/list/${purchaseInvoiceId}`),
addDelievryChallan: (data) =>
api.post(`/api/PurchaseInvoice/delivery-challan/create`, data),
}; };
// const filterPayload = JSON.stringify({ // const filterPayload = JSON.stringify({

View File

@ -0,0 +1,4 @@
export const FILE_UPLOAD_INFO = `
If you want to upload a document, please select a document type
before uploading the document.
`;