intergrated get list and create collection

This commit is contained in:
pramod.mahajan 2025-10-14 00:21:19 +05:30
parent 58c2fbdf1b
commit 376a2a397f
7 changed files with 815 additions and 24 deletions

View File

@ -4,17 +4,20 @@ import OrganizationModal from "./components/Organization/OrganizationModal";
import { useAuthModal, useModal } from "./hooks/useAuth";
import SwitchTenant from "./pages/authentication/SwitchTenant";
import ChangePasswordPage from "./pages/authentication/ChangePassword";
import NewCollection from "./components/collections/NewCollection";
const ModalProvider = () => {
const { isOpen, onClose } = useOrganizationModal();
const { isOpen: isAuthOpen } = useAuthModal();
const {isOpen:isChangePass} = useModal("ChangePassword")
const {isOpen:isCollectionNew} = useModal("newCollection");
return (
<>
{isOpen && <OrganizationModal />}
{isAuthOpen && <SwitchTenant />}
{isChangePass && <ChangePasswordPage /> }
{isCollectionNew && <NewCollection/>}
</>
);
};

View File

@ -1,11 +1,193 @@
import React from 'react'
import React, { useState } from "react";
import { useCollections } from "../../hooks/useCollections";
import { ITEMS_PER_PAGE } from "../../utils/constants";
import { formatFigure, localToUtc, useDebounce } from "../../utils/appUtils";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import Pagination from "../common/Pagination";
const CollectionList = () => {
return (
<div>
const CollectionList = ({ fromDate, toDate, isPending, searchString }) => {
const [currentPage, setCurrentPage] = useState(1);
const searchDebounce = useDebounce(searchString, 500);
</div>
)
const { data, isLoading, isError, error } = useCollections(
ITEMS_PER_PAGE,
currentPage,
localToUtc(fromDate),
localToUtc(toDate),
isPending,
true,
searchDebounce
);
const paginate = (page) => {
if (page >= 1 && page <= (data?.totalPages ?? 1)) {
setCurrentPage(page);
}
};
export default CollectionList
const collectionColumns = [
{
key: "invoiceDate",
label: "Invoice Date",
getValue: (col) => (
<span
className="text-truncate d-inline-block"
style={{ maxWidth: "200px" }}
>
{formatUTCToLocalTime(col.invoiceDate)}
</span>
),
align: "text-start",
},
{
key: "invoiceId",
label: "Invoice Id",
getValue: (col) => (
<span
className="text-truncate d-inline-block"
style={{ maxWidth: "200px" }}
>
{col?.invoiceNumber ?? "-"}
</span>
),
align: "text-start",
},
{
key: "project",
label: "Project",
getValue: (col) => (
<span
className="text-truncate d-inline-block"
style={{ maxWidth: "200px" }}
>
{col?.project?.name ?? "-"}
</span>
),
align: "text-start",
},
{
key: "submittedDate",
label: "Submitted Date",
getValue: (col) => (
<span
className="text-truncate d-inline-block"
style={{ maxWidth: "200px" }}
>
{formatUTCToLocalTime(col.createdAt)}
</span>
),
align: "text-start",
},
{
key: "expectedSubmittedDate",
label: "Expected Payment Date",
getValue: (col) => (
<span
className="text-truncate d-inline-block"
style={{ maxWidth: "200px" }}
>
{formatUTCToLocalTime(col.exceptedPaymentDate) ?? "-"}
</span>
),
align: "text-start",
},
{
key: "amount",
label: "Amount",
getValue: (col) => (
<span
className="text-truncate d-inline-block"
style={{ maxWidth: "200px" }}
>
{formatFigure(col?.basicAmount, { type: "currency", currency: "INR" }) ?? 0}
</span>
),
align: "text-end",
},
{
key: "balance",
label: "Balance",
getValue: (col) => (
<span
className="text-truncate d-inline-block py-3"
style={{ maxWidth: "200px" }}
>
{formatFigure(col?.balanceAmount, { type: "currency", currency: "INR" }) ?? 0}
</span>
),
align: "text-end",
},
];
if (isLoading) return <p>Loading...</p>;
if (isError) return <p>{error.message}</p>;
return (
<div className="card ">
<div
className="card-datatable table-responsive page-min-h"
id="horizontal-example"
>
<div className="dataTables_wrapper no-footer mx-5 pb-2">
<table className="table dataTable text-nowrap">
<thead>
<tr className="table_header_border">
{collectionColumns.map((col) => (
<th key={col.key} className={col.align}>
{col.label}
</th>
))}
<th className="sticky-action-column bg-white text-center">
Action
</th>
</tr>
</thead>
<tbody>
{Array.isArray(data?.data) && data.data.length > 0 ? (
data.data.map((row, i) => (
<tr key={i}>
{collectionColumns.map((col) => (
<td key={col.key} className={col.align}>
{col.getValue(row)}
</td>
))}
<td
className="sticky-action-column text-center"
style={{ padding: "12px 8px" }}
>
<div className="d-flex justify-content-center gap-2">
<i className="bx bx-show text-primary cursor-pointer"></i>
<i className="bx bx-edit text-secondary cursor-pointer"></i>
<i className="bx bx-trash text-danger cursor-pointer"></i>
</div>
</td>
</tr>
))
) : (
<tr style={{ height: "200px" }}>
<td
colSpan={collectionColumns.length + 1}
className="text-center border-0 align-middle"
>
No Collections Found
</td>
</tr>
)}
</tbody>
</table>
{data?.data?.length > 0 && (
<div className="d-flex justify-content-start mt-2">
<Pagination
currentPage={currentPage}
totalPages={data?.totalPages}
onPageChange={paginate}
/>
</div>
)}
</div>
</div>
</div>
);
};
export default CollectionList;

View File

@ -0,0 +1,391 @@
import React from "react";
import { useModal } from "../../hooks/useAuth";
import Modal from "../common/Modal";
import { FormProvider, useForm } from "react-hook-form";
import Label from "../common/Label";
import { zodResolver } from "@hookform/resolvers/zod";
import { defaultCollection, newCollection } from "./collectionSchema";
import SelectMultiple from "../common/SelectMultiple";
import { useProjectName } from "../../hooks/useProjects";
import DatePicker from "../common/DatePicker";
import { useCreateCollection } from "../../hooks/useCollections";
import { formatFileSize, localToUtc } from "../../utils/appUtils";
const NewCollection = ({ collectionId }) => {
const { onClose, onOpen, isOpen } = useModal("newCollection");
const { projectNames, projectLoading } = useProjectName();
console.log(projectNames);
const methods = useForm({
resolver: zodResolver(newCollection),
defaultValues: defaultCollection,
});
const {
control,
watch,
register,
setValue,
handleSubmit,
reset,
formState: { errors },
} = methods;
const { mutate: createNewCollection, isPending } = useCreateCollection(()=>{
handleClose()
});
const files = watch("billAttachments");
const onFileChange = async (e) => {
const newFiles = Array.from(e.target.files);
if (newFiles.length === 0) return;
const existingFiles = watch("billAttachments") || [];
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,
};
})
);
const combinedFiles = [
...existingFiles,
...parsedFiles.filter(
(newFile) =>
!existingFiles.some(
(f) =>
f.fileName === newFile.fileName && f.fileSize === newFile.fileSize
)
),
];
setValue("billAttachments", combinedFiles, {
shouldDirty: true,
shouldValidate: true,
});
};
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 removeFile = (index) => {
if (collectionId) {
const newFiles = files.map((file, i) => {
if (file.documentId !== index) return file;
return {
...file,
isActive: false,
};
});
setValue("billAttachments", newFiles, { shouldValidate: true });
} else {
const newFiles = files.filter((_, i) => i !== index);
setValue("billAttachments", newFiles, { shouldValidate: true });
}
};
const onSubmit = (formData) => {
const payload = {
...formData,
clientSubmitedDate: localToUtc(formData.clientSubmitedDate),
invoiceDate: localToUtc(formData.invoiceDate),
exceptedPaymentDate: localToUtc(formData.exceptedPaymentDate),
};
createNewCollection(payload);
};
const handleClose = () => {
reset(defaultCollection);
onClose();
};
const bodyContent = (
<div className="row">
<div className="text-black fs-5 mb-2">New Collection</div>
<FormProvider {...methods}>
<form onSubmit={handleSubmit(onSubmit)} className="p-0 text-start">
<div className="row px-md-4 px-0">
<div className="col-12 col-md-6 mb-2">
<Label required>Title</Label>
<input
type="text"
className="form-control form-control-sm"
{...register("title")}
/>
{errors.title && (
<small className="danger-text">{errors.title.message}</small>
)}
</div>
<div className="col-12 col-md-6 mb-2">
<Label required>Invoice Number</Label>
<input
type="text"
className="form-control form-control-sm"
{...register("invoiceNumber")}
/>
{errors.invoiceId && (
<small className="danger-text">
{errors.invoiceId.message}
</small>
)}
</div>
<div className="col-12 col-md-6 mb-2">
<Label required>E-Invoice Number</Label>
<input
type="text"
className="form-control form-control-sm"
{...register("eInvoiceNumber")}
/>
{errors.invoiceId && (
<small className="danger-text">
{errors.invoiceId.message}
</small>
)}
</div>
<div className="col-12 col-md-6 mb-2">
<Label required>Invoice Date</Label>
<DatePicker
name="invoiceDate"
control={control}
maxDate={new Date()}
/>
{errors.invoiceDate && (
<small className="danger-text">
{errors.invoiceDate.message}
</small>
)}
</div>
<div className="col-12 col-md-6 mb-2">
<Label required>Expected Date</Label>
<DatePicker
name="exceptedPaymentDate"
control={control}
minDate={watch("invoiceDate")}
/>
{errors.exceptedPaymentDate && (
<small className="danger-text">
{errors.exceptedPaymentDate.message}
</small>
)}
</div>
<div className="col-12 col-md-6 mb-2">
<Label required>Submission Date (Client)</Label>
<DatePicker
name="clientSubmitedDate"
control={control}
maxDate={new Date()}
/>
{errors.exceptedPaymentDate && (
<small className="danger-text">
{errors.exceptedPaymentDate.message}
</small>
)}
</div>
<div className="col-12 col-md-6 mb-2">
<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">
<Label htmlFor="basicAmount" className="form-label" required>
Amount
</Label>
<input
type="number"
id="basicAmount"
className="form-control form-control-sm"
min="1"
step="0.01"
inputMode="decimal"
{...register("basicAmount", { valueAsNumber: true })}
/>
{errors.basicAmount && (
<small className="danger-text">
{errors.basicAmount.message}
</small>
)}
</div>
<div className="col-12 col-md-6 mb-2">
<Label htmlFor="taxAmount" className="form-label" required>
Tax Amount
</Label>
<input
type="number"
id="taxAmount"
className="form-control form-control-sm"
min="1"
step="0.01"
inputMode="decimal"
{...register("taxAmount", { valueAsNumber: true })}
/>
{errors.taxAmount && (
<small className="danger-text">
{errors.taxAmount.message}
</small>
)}
</div>
<div className="col-12 my-2 text-start mb-2">
<div className="col-md-12">
<Label htmlFor="description" className="form-label" required>
Description
</Label>
<textarea
id="description"
className="form-control form-control-sm"
{...register("description")}
rows="2"
></textarea>
{errors.description && (
<small className="danger-text">
{errors.description.message}
</small>
)}
</div>
</div>
<div className="col-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 text-black"
style={{ cursor: "pointer" }}
onClick={() =>
document.getElementById("billAttachments").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="billAttachments"
accept=".pdf,.jpg,.jpeg,.png"
multiple
style={{ display: "none" }}
{...register("billAttachments")}
onChange={(e) => {
onFileChange(e);
e.target.value = "";
}}
/>
</div>
{errors.billAttachments && (
<small className="danger-text">
{errors.billAttachments.message}
</small>
)}
{files.length > 0 && (
<div className="d-block">
{files
.filter((file) => {
if (collectionId) {
return file.isActive;
}
return true;
})
.map((file, idx) => (
<a
key={idx}
className="d-flex justify-content-between text-start p-1"
href={file.preSignedUrl || "#"}
target="_blank"
rel="noopener noreferrer"
>
<div>
<span className="mb-0 text-secondary small d-block">
{file.fileName}
</span>
<span className="text-body-secondary small d-block">
{file.fileSize ? formatFileSize(file.fileSize) : ""}
</span>
</div>
<i
className="bx bx-trash bx-sm cursor-pointer text-danger"
onClick={(e) => {
e.preventDefault();
removeFile(collectionId ? file.documentId : idx);
}}
></i>
</a>
))}
</div>
)}
{Array.isArray(errors.billAttachments) &&
errors.billAttachments.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>
))}
</div>
<div className="d-flex justify-content-end gap-3">
{" "}
<button
type="reset"
className="btn btn-label-secondary btn-sm mt-3"
onClick={handleClose}
disabled={isPending}
>
Cancel
</button>
<button
type="submit"
className="btn btn-primary btn-sm mt-3"
disabled={isPending}
>
{isPending ? "Please Wait..." : "Submit"}
</button>
</div>
</div>
</form>
</FormProvider>
</div>
);
return (
<Modal size="lg" isOpen={isOpen} onClose={onClose} body={bodyContent} />
);
};
export default NewCollection;

View File

@ -0,0 +1,67 @@
import { z } from "zod";
const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
const ALLOWED_TYPES = [
"application/pdf",
"image/png",
"image/jpg",
"image/jpeg",
];
export const newCollection = z.object({
title: z.string().trim().min(1, { message: "Title is required" }),
projectId: z.string().trim().min(1, { message: "Project is required" }),
invoiceDate: z.string().min(1, { message: "Date is required" }),
description: z.string().trim().optional(),
clientSubmitedDate: z.string().min(1, { message: "Date is required" }),
exceptedPaymentDate: z.string().min(1, { message: "Date is required" }),
invoiceNumber: z.string().trim().min(1, { message: "Invoice is required" }).max(17,{message:"Invalid Number"}),
eInvoiceNumber: z.string().trim().min(1, { message: "E-Invoice No is required" }),
taxAmount: z.coerce
.number({
invalid_type_error: "Amount is required and must be a number",
})
.min(1, "Amount must be Enter")
.refine((val) => /^\d+(\.\d{1,2})?$/.test(val.toString()), {
message: "Amount must have at most 2 decimal places",
}),
basicAmount: z.coerce
.number({
invalid_type_error: "Amount is required and must be a number",
})
.min(1, "Amount must be Enter")
.refine((val) => /^\d+(\.\d{1,2})?$/.test(val.toString()), {
message: "Amount must have at most 2 decimal places",
}),
billAttachments: z
.array(
z.object({
fileName: z.string().min(1, { message: "Filename is required" }),
base64Data: z.string().nullable(),
contentType: z.string().refine((val) => ALLOWED_TYPES.includes(val), {
message: "Only PDF, PNG, JPG, or JPEG files are allowed",
}),
documentId: z.string().optional(),
fileSize: z.number().max(MAX_FILE_SIZE, {
message: "File size must be less than or equal to 5MB",
}),
description: z.string().optional(),
isActive: z.boolean().default(true),
})
)
.nonempty({ message: "At least one file attachment is required" }),
});
export const defaultCollection = {
projectId: "",
invoiceNumber: " ",
eInvoiceNumber: "",
title: "",
clientSubmitedDate: null,
invoiceDate: null,
exceptedPaymentDate: null,
taxAmount: "",
basicAmount:"",
description: "",
billAttachments: [],
};

View File

@ -0,0 +1,58 @@
import { useMutation, useQuery } from "@tanstack/react-query";
import { CollectionRepository } from "../repositories/ColllectionRepository";
import showToast from "../services/toastService";
export const useCollections = (
pageSize,
pageNumber,
fromDate,
toDate,
isPending,
isActive,
searchString
) => {
return useQuery({
queryKey: [
"collections",
pageSize,
pageNumber,
fromDate,
toDate,
isPending,
isActive,
searchString,
],
queryFn: async () => {
const response = await CollectionRepository.getCollections(
pageSize,
pageNumber,
fromDate,
toDate,
isPending,
isActive,
searchString
);
return response.data;
},
keepPreviousData: true,
staleTime: 1000 * 60 * 1,
});
};
export const useCreateCollection = (onSuccessCallBack) => {
return useMutation({
mutationFn: async (payload) =>
await CollectionRepository.createNewCollection(payload),
onSuccess: (_, variables) => {
showToast("New Collection created Successfully", "success");
if (onSuccessCallBack) onSuccessCallBack();
},
onError: (error) => {
showToast(
error.message || error.response.data.message || "Something Went wrong"
);
},
});
};

View File

@ -1,21 +1,91 @@
import React from 'react'
import Breadcrumb from '../../components/common/Breadcrumb'
import React, { useState } from "react";
import moment from "moment";
import Breadcrumb from "../../components/common/Breadcrumb";
import CollectionList from "../../components/collections/CollectionList";
import { useModal } from "../../hooks/useAuth";
import { FormProvider, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { DateRangePicker1 } from "../../components/common/DateRangePicker";
import { isPending } from "@reduxjs/toolkit";
const CollectionPage = () => {
const { onOpen } = useModal("newCollection");
const [showPending, setShowPending] = useState(false);
const [searchText, setSearchText] = useState("");
const methods = useForm({
defaultValues: {
fromDate: moment().subtract(6, "days").format("DD-MM-YYYY"),
toDate: moment().format("DD-MM-YYYY"),
},
});
const { watch } = methods;
const [fromDate, toDate] = watch(["fromDate", "toDate"]);
const handleToggleActive = (e) => setShowPending(e.target.checked);
return (
<div className='container-fluid'>
<div className="container-fluid">
<Breadcrumb
data={[{ label: "Home", link: "/" }, { label: "Collection" }]}
/>
<div className='card px-2 py-1'>
<div className='row'>
<div className='col-12'>
<div className="card my-3 py-2 px-sm-4 px-0">
<div className="row">
<div className="col-3">
<FormProvider {...methods}>
<DateRangePicker1 />
</FormProvider>
</div>
<div className="col-3 d-flex align-items-center gap-2 ">
<div className="form-check form-switch text-start align-items-center">
<input
type="checkbox"
className="form-check-input"
role="switch"
id="inactiveEmployeesCheckbox"
checked={showPending}
onChange={(e) => setShowPending(e.target.checked)}
/>
<label
className="form-check-label ms-0"
htmlFor="inactiveEmployeesCheckbox"
>
Show Pending
</label>
</div>
</div>
</div>
</div>
)
}
export default CollectionPage
<div className="col-6 d-flex justify-content-end gap-4">
<div className="">
{" "}
<input
type="search"
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
placeholder="search Collection"
className="form-control form-control-sm"
/>
</div>
<button
className="btn btn-sm btn-primary"
type="button"
onClick={onOpen}
>
<i className="bx bx-plus-circle me-2"></i>
<span className="d-none d-md-inline-block">
Add New Collection
</span>
</button>
</div>
</div>
</div>
<CollectionList
fromDate={fromDate}
toDate={toDate}
isPending={showPending}
searchString={searchText}
/>
</div>
);
};
export default CollectionPage;

View File

@ -0,0 +1,20 @@
import { api } from "../utils/axiosClient";
import { DirectoryRepository } from "./DirectoryRepository";
export const CollectionRepository = {
createNewCollection: (data) =>
api.post(`/api/Collection/invoice/create`, data),
getCollections: (pageSize, pageNumber,fromDate,toDate, isPending,isActive, searchString) => {
let url = `/api/Collection/invoice/list?pageSize=${pageSize}&pageNumber=${pageNumber}&isPending=${isPending}&isActive=${isActive}&searchString=${searchString}`;
const params = [];
if (fromDate) params.push(`fromDate=${fromDate}`);
if (toDate) params.push(`toDate=${toDate}`);
if (params.length > 0) {
url += `&${params.join("&")}`;
}
return api.get(url);
},
};