integrated collection details api

This commit is contained in:
pramod.mahajan 2025-10-14 13:36:19 +05:30
parent 301684a12b
commit 272645f0b4
8 changed files with 302 additions and 36 deletions

View File

@ -1,11 +1,123 @@
import React from 'react'
import { zodResolver } from "@hookform/resolvers/zod";
import React, { useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { defaultPayment, paymentSchema } from "./collectionSchema";
import Label from "../common/Label";
import DatePicker from "../common/DatePicker";
import { formatDate } from "date-fns";
import { useCollectionContext } from "../../pages/collections/CollectionPage";
import { useAddPayment, useCollection } from "../../hooks/useCollections";
import { localToUtc } from "../../utils/appUtils";
const AddPayment = ({ onClose }) => {
const { addPayment } = useCollectionContext();
const { data, isLoading, isError, error } = useCollection(
addPayment?.invoiceId
);
const methods = useForm({
resolver: zodResolver(paymentSchema),
defaultValues: defaultPayment,
});
const {
control,
register,
handleSubmit,
reset,
formState: { errors },
} = methods;
const { mutate: AddPayment, isPending } = useAddPayment(() => {
handleClose();
});
const onSubmit = (formData) => {
const payload = {
...formData,
paymentReceivedDate: localToUtc(formData.paymentReceivedDate),
invoiceId: addPayment.invoiceId,
};
debugger;
AddPayment(payload);
};
const handleClose = (formData) => {
reset(defaultPayment);
onClose();
};
const AddPayment = () => {
return (
<div className='row'>
</div>
)
}
<div className="container pb-3">
<div className="text-black fs-5 mb-2">Add Payment</div>
<FormProvider {...methods}>
<form onSubmit={handleSubmit(onSubmit)} className="p-0 text-start">
<div className="row px-md-1 px-0">
<div className="col-12 col-md-6 mb-2">
<Label required>TransanctionId</Label>
<input
type="text"
className="form-control form-control-sm"
{...register("transactionId")}
/>
{errors.transactionId && (
<small className="danger-text">
{errors.transactionId.message}
</small>
)}
</div>
export default AddPayment
<div className="col-12 col-md-6 mb-2">
<Label required>Transaction Date </Label>
<DatePicker
name="paymentReceivedDate"
control={control}
maxDate={new Date()}
/>
{errors.paymentReceivedDate && (
<small className="danger-text">
{errors.paymentReceivedDate.message}
</small>
)}
</div>
<div className="col-12 col-md-6 mb-2">
<Label htmlFor="amount" className="form-label" required>
Amount
</Label>
<input
type="number"
id="amount"
className="form-control form-control-sm"
min="1"
step="0.01"
inputMode="decimal"
{...register("amount", { valueAsNumber: true })}
/>
{errors.amount && (
<small className="danger-text">{errors.amount.message}</small>
)}
</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>
);
};
export default AddPayment;

View File

@ -19,7 +19,7 @@ const CollectionList = ({ fromDate, toDate, isPending, searchString }) => {
true,
searchDebounce
);
const {setProcessedPayment} = useCollectionContext()
const {setProcessedPayment,setAddPayment,setViewCollection} = useCollectionContext()
const paginate = (page) => {
if (page >= 1 && page <= (data?.totalPages ?? 1)) {
@ -183,7 +183,7 @@ const CollectionList = ({ fromDate, toDate, isPending, searchString }) => {
<ul className="dropdown-menu dropdown-menu-end">
{/* View */}
<li>
<a className="dropdown-item cursor-pointer">
<a className="dropdown-item cursor-pointer" onClick={()=>setViewCollection(row.id)}>
<i className="bx bx-show me-2 text-primary"></i>
<span>View</span>
</a>
@ -191,7 +191,7 @@ const CollectionList = ({ fromDate, toDate, isPending, searchString }) => {
{/* Add Payment */}
<li>
<a className="dropdown-item cursor-pointer">
<a className="dropdown-item cursor-pointer" onClick={()=>setAddPayment({isOpen:true,invoiceId:row.id})}>
<i className="bx bx-wallet me-2 text-warning"></i>
<span>Add Payment</span>
</a>
@ -199,7 +199,7 @@ const CollectionList = ({ fromDate, toDate, isPending, searchString }) => {
{/* Mark Payment */}
<li>
<a className="dropdown-item cursor-pointer" onClick={()=>setProcessedPayment({isOpen:true,invoiceId:row.id})}>
<a className="dropdown-item cursor-pointer" onClick={()=>setProcessedPayment({isOpen:true,invoiceId:row})}>
<i className="bx bx-check-circle me-2 text-success"></i>
<span>Mark Payment</span>
</a>

View File

@ -32,12 +32,12 @@ const NewCollection = ({ collectionId, onClose }) => {
handleClose()
});
const files = watch("billAttachments");
const files = watch("attachments");
const onFileChange = async (e) => {
const newFiles = Array.from(e.target.files);
if (newFiles.length === 0) return;
const existingFiles = watch("billAttachments") || [];
const existingFiles = watch("attachments") || [];
const parsedFiles = await Promise.all(
newFiles.map(async (file) => {
@ -64,7 +64,7 @@ const NewCollection = ({ collectionId, onClose }) => {
),
];
setValue("billAttachments", combinedFiles, {
setValue("attachments", combinedFiles, {
shouldDirty: true,
shouldValidate: true,
});
@ -86,10 +86,10 @@ const NewCollection = ({ collectionId, onClose }) => {
isActive: false,
};
});
setValue("billAttachments", newFiles, { shouldValidate: true });
setValue("attachments", newFiles, { shouldValidate: true });
} else {
const newFiles = files.filter((_, i) => i !== index);
setValue("billAttachments", newFiles, { shouldValidate: true });
setValue("attachments", newFiles, { shouldValidate: true });
}
};
@ -283,7 +283,7 @@ const NewCollection = ({ collectionId, onClose }) => {
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()
document.getElementById("attachments").click()
}
>
<i className="bx bx-cloud-upload d-block bx-lg "> </i>
@ -294,20 +294,20 @@ const NewCollection = ({ collectionId, onClose }) => {
<input
type="file"
id="billAttachments"
id="attachments"
accept=".pdf,.jpg,.jpeg,.png"
multiple
style={{ display: "none" }}
{...register("billAttachments")}
{...register("attachments")}
onChange={(e) => {
onFileChange(e);
e.target.value = "";
}}
/>
</div>
{errors.billAttachments && (
{errors.attachments && (
<small className="danger-text">
{errors.billAttachments.message}
{errors.attachments.message}
</small>
)}
{files.length > 0 && (
@ -347,8 +347,8 @@ const NewCollection = ({ collectionId, onClose }) => {
</div>
)}
{Array.isArray(errors.billAttachments) &&
errors.billAttachments.map((fileError, index) => (
{Array.isArray(errors.attachments) &&
errors.attachments.map((fileError, index) => (
<div key={index} className="danger-text small mt-1">
{
(fileError?.fileSize?.message ||

View File

@ -0,0 +1,94 @@
import React from 'react'
import { useCollectionContext } from '../../pages/collections/CollectionPage';
import { useCollection } from '../../hooks/useCollections';
import { formatUTCToLocalTime } from '../../utils/dateUtils';
import { formatFigure } from '../../utils/appUtils';
import Avatar from '../common/Avatar';
const ViewCollection = () => {
const { viewCollection } = useCollectionContext();
const { data, isLoading, isError, error } = useCollection(
viewCollection
);
console.log(data)
if(isLoading) return <div>isLoading...</div>;
if(isError) return <div>{error.message}</div>;
return (
<div className="container p-3">
<p className="fs-5 fw-semibold">Collection Details</p>
<div className="text-start ">
<div className="mb-3">
<p className="mb-1 fs-5">{data?.title}</p>
<p className="mb-3">{data?.description}</p>
</div>
<div className="row mb-3">
<div className="col-md-6"><strong>Invoice Number:</strong> {data?.invoiceNumber}</div>
<div className="col-md-6"><strong>E-Invoice Number:</strong> {data?.eInvoiceNumber}</div>
</div>
<div className="row mb-3">
<div className="col-md-6"><strong>Project:</strong> {data?.project?.name}</div>
<div className="col-md-6"><strong>Status:</strong> {data?.isActive ? "Active" : "Inactive"}</div>
</div>
<div className="row mb-3">
<div className="col-md-6"><strong>Invoice Date:</strong> {formatUTCToLocalTime(data?.invoiceDate)}</div>
<div className="col-md-6"><strong>Client Submitted Date:</strong> {formatUTCToLocalTime(data?.clientSubmitedDate)}</div>
</div>
<div className="row mb-3">
<div className="col-md-6"><strong>Expected Payment Date:</strong> {formatUTCToLocalTime(data?.exceptedPaymentDate)}</div>
<div className="col-md-6"><strong>Mark as Completed:</strong> {data?.markAsCompleted ? "Yes" : "No"}</div>
</div>
<div className="row mb-3">
<div className="col-md-6"><strong>Basic Amount:</strong> {formatFigure(data?.basicAmount, { type: "currency", currency: "INR" })}</div>
<div className="col-md-6"><strong>Tax Amount:</strong> {formatFigure(data?.taxAmount, { type: "currency", currency: "INR" })}</div>
</div>
<div className="row mb-3">
<div className="col-md-6"><strong>Balance Amount:</strong> {formatFigure(data?.balanceAmount, { type: "currency", currency: "INR" })}</div>
<div className="col-md-6"><strong>Created At:</strong> {formatUTCToLocalTime(data?.createdAt)}</div>
</div>
<div className="row mb-3">
<div className="col-md-6"><strong>Created By:</strong> <div className='d-flex align-items-center'><Avatar size='xs' firstName={data.createdBy?.firstName} lastName={data.createdBy?.lastName}/>{data?.createdBy?.firstName} {data?.createdBy?.lastName} ({data?.createdBy?.jobRoleName})</div> </div>
{/* <div className="col-md-6"><strong>Updated At:</strong> {data?.updatedAt ? formatUTCToLocalTime(data?.updatedAt) : "-"}</div> */}
</div>
{data?.receivedInvoicePayments?.length > 0 && (
<div className="mt-4">
<h5>Received Payments</h5>
<table className="table table-bordered mt-2">
<thead className="table-light">
<tr>
<th className=''>Sr,No</th>
<th>Transaction ID</th>
<th> Received Date</th>
<th>Amount</th>
<th>Received By</th>
</tr>
</thead>
<tbody>
{data.receivedInvoicePayments.map((payment, index) => (
<tr key={payment.id}>
<td>{index + 1}</td>
<td>{payment.transactionId}</td>
<td>{formatUTCToLocalTime(payment.paymentReceivedDate)}</td>
<td className='text-end'>{formatFigure(payment.amount, { type: "currency", currency: "INR" })}</td>
<td><div className='d-flex align-items-center'>
<Avatar size='xs' firstName={payment.createdBy?.firstName} lastName={payment.createdBy?.lastName}/>{payment.createdBy?.firstName} {payment.createdBy?.lastName}
</div></td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
)
}
export default ViewCollection

View File

@ -40,7 +40,7 @@ export const newCollection = z.object({
.refine((val) => /^\d+(\.\d{1,2})?$/.test(val.toString()), {
message: "Amount must have at most 2 decimal places",
}),
billAttachments: z
attachments: z
.array(
z.object({
fileName: z.string().min(1, { message: "Filename is required" }),
@ -70,19 +70,17 @@ export const defaultCollection = {
taxAmount: "",
basicAmount: "",
description: "",
billAttachments: [],
attachments: [],
};
export const paymentSchema = z.object({
invoiceId: z.string().min(1, { message: "Invoice Id required" }),
paymentReceivedDate: z.string().datetime(),
paymentReceivedDate: z.string().min(1, { message: "Date is required" }),
transactionId: z.string().min(1, "Transaction ID is required"),
amount: z.number().min(1, "Amount must be greater than zero"),
});
// Default Value
export const defaultPayment = {
invoiceId: "",
paymentReceivedDate: null,
transactionId: "",
amount: 0,

View File

@ -41,6 +41,21 @@ export const useCollections = (
});
};
export const useCollection =(collectionId)=>{
return useQuery({
queryKey:["collection",collectionId],
queryFn:async()=> {
const resp = await CollectionRepository.getCollection(collectionId);
return resp.data
},
enabled:!!collectionId
})
}
// =========================Mutation======================
export const useCreateCollection = (onSuccessCallBack) => {
const clinent = useQueryClient();
return useMutation({
@ -76,3 +91,21 @@ export const useMarkedPaymentReceived = (onSuccessCallBack) => {
},
});
};
export const useAddPayment = (onSuccessCallBack) => {
const client = useQueryClient();
return useMutation({
mutationFn: (payload) => CollectionRepository.makeReceivePayment(payload),
onSuccess: () => {
client.invalidateQueries({ queryKey: ["collections"] });
showToast("Payment Received marked Successfully", "success");
if (onSuccessCallBack) onSuccessCallBack();
},
onError: (error) => {
showToast(
error?.response?.data?.message || error.message || "Something Went wrong"
);
},
});
};

View File

@ -12,6 +12,8 @@ import showToast from "../../services/toastService";
import { useMarkedPaymentReceived } from "../../hooks/useCollections";
import NewCollection from "../../components/collections/NewCollection";
import GlobalModel from "../../components/common/GlobalModel";
import AddPayment from "../../components/collections/AddPayment";
import ViewCollection from "../../components/collections/ViewCollection";
const CollectionContext = createContext();
export const useCollectionContext = () => {
@ -23,12 +25,16 @@ export const useCollectionContext = () => {
return context;
};
const CollectionPage = () => {
const { onOpen } = useModal("newCollection");
const [viewCollection,setViewCollection] = useState(null)
const [makeCollection, setCollection] = useState({
isOpen: false,
invoiceId: null,
});
const [processedPayment, setProcessedPayment] = useState(null);
const [addPayment, setAddPayment] = useState({
isOpen: false,
invoiceId: null,
});
const [showPending, setShowPending] = useState(false);
const [searchText, setSearchText] = useState("");
const methods = useForm({
@ -43,6 +49,10 @@ const CollectionPage = () => {
const contextMassager = {
setProcessedPayment,
setAddPayment,
addPayment,
setViewCollection,
viewCollection
};
const { mutate: MarkedReceived, isPending } = useMarkedPaymentReceived(() => {
setProcessedPayment(null);
@ -95,7 +105,7 @@ const CollectionPage = () => {
<button
className="btn btn-sm btn-primary"
type="button"
onClick={()=>setCollection({isOpen:true,invoiceId:null})}
onClick={() => setCollection({ isOpen: true, invoiceId: null })}
>
<i className="bx bx-plus-circle me-2"></i>
<span className="d-none d-md-inline-block">
@ -115,16 +125,35 @@ const CollectionPage = () => {
{makeCollection.isOpen && (
<GlobalModel
isOpen={makeCollection.isOpen} size="lg"
isOpen={makeCollection.isOpen}
size="lg"
closeModal={() => setCollection({ isOpen: false, invoiceId: null })}
>
<NewCollection
collectionId={null}
onClose={()=>setCollection({ isOpen: false, invoiceId: null })}
onClose={() => setCollection({ isOpen: false, invoiceId: null })}
/>
</GlobalModel>
)}
{addPayment.isOpen && (
<GlobalModel
size="lg"
isOpen={addPayment.isOpen}
closeModal={() => setAddPayment({ isOpen: false, invoiceId: null })}
>
<AddPayment
onClose={() => setAddPayment({ isOpen: false, invoiceId: null })}
/>
</GlobalModel>
)}
{viewCollection && (
<GlobalModel size="lg" isOpen={viewCollection} closeModal={()=>setViewCollection(null)}>
<ViewCollection onClose={()=>setViewCollection(null)}/>
</GlobalModel>
)}
<ConfirmModal
type="success"
header="Payment Successful Received"

View File

@ -17,8 +17,8 @@ export const CollectionRepository = {
return api.get(url);
},
makeReceivePayment:(data)=> api.post(`/api/Collection/invoice/payment/received`),
markPaymentReceived:(invoiceId)=>api.put(`/api/Collection/invoice/marked/completed/${invoiceId}`)
makeReceivePayment:(data)=> api.post(`/api/Collection/invoice/payment/received`,data),
markPaymentReceived:(invoiceId)=>api.put(`/api/Collection/invoice/marked/completed/${invoiceId}`),
getCollection:(id)=>api.get(`/api/Collection/invoice/details/${id}`)
};