payment checkpoint 3

This commit is contained in:
2025-08-08 00:34:56 +05:30
parent c107c798cf
commit 89897ef2d6
11 changed files with 699 additions and 274 deletions

View File

@@ -1,140 +1,452 @@
import { useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import { z } from "zod";
import { format } from "date-fns";
import { PaymentUncheckedCreateInputObjectSchema } from "@repo/db/usedSchemas";
import { formatDateToHumanReadable } from "@/utils/dateUtils";
import React, { useState } from "react";
import { paymentStatusOptions, PaymentWithExtras } from "@repo/db/types";
import { PaymentStatus, PaymentMethod } from "@repo/db/types";
type Payment = z.infer<typeof PaymentUncheckedCreateInputObjectSchema>;
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@radix-ui/react-select";
import { Input } from "@/components/ui/input";
import Decimal from "decimal.js";
import { toast } from "@/hooks/use-toast";
interface PaymentEditModalProps {
type PaymentEditModalProps = {
isOpen: boolean;
onOpenChange: (open: boolean) => void;
onClose: () => void;
payment: Payment;
onSave: () => void;
}
onEditServiceLine: (updatedPayment: PaymentWithExtras) => void;
payment: PaymentWithExtras | null;
};
export default function PaymentEditModal({
isOpen,
onOpenChange,
onClose,
payment,
onSave,
onEditServiceLine,
}: PaymentEditModalProps) {
const { toast } = useToast();
const [form, setForm] = useState({
payerName: payment.payerName,
amountPaid: payment.amountPaid.toString(),
paymentDate: format(new Date(payment.paymentDate), "yyyy-MM-dd"),
paymentMethod: payment.paymentMethod,
note: payment.note || "",
});
if (!payment) return null;
const [loading, setLoading] = useState(false);
const [expandedLineId, setExpandedLineId] = useState<number | null>(null);
const [updatedPaidAmounts, setUpdatedPaidAmounts] = useState<
Record<number, number>
>({});
const [updatedAdjustedAmounts, setUpdatedAdjustedAmounts] = useState<
Record<number, number>
>({});
const [updatedNotes, setUpdatedNotes] = useState<Record<number, string>>({});
const [updatedPaymentStatus, setUpdatedPaymentStatus] =
useState<PaymentStatus>(payment?.status ?? "PENDING");
const [updatedTransactions, setUpdatedTransactions] = useState(
() => payment?.transactions ?? []
);
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { name, value } = e.target;
setForm({ ...form, [name]: value });
type DraftPaymentData = {
paidAmount: number;
adjustedAmount?: number;
notes?: string;
paymentStatus?: PaymentStatus;
payerName?: string;
method: PaymentMethod;
receivedDate: string;
};
const handleSubmit = async () => {
setLoading(true);
const [serviceLineDrafts, setServiceLineDrafts] = useState<Record<number, any>>({});
const totalPaid = payment.transactions.reduce(
(sum, tx) =>
sum +
tx.serviceLinePayments.reduce((s, sp) => s + Number(sp.paidAmount), 0),
0
);
const totalBilled = payment.claim.serviceLines.reduce(
(sum, line) => sum + line.billedAmount,
0
);
const totalDue = totalBilled - totalPaid;
const handleEditServiceLine = (lineId: number) => {
setExpandedLineId(lineId === expandedLineId ? null : lineId);
};
const handleFieldChange = (lineId: number, field: string, value: any) => {
setServiceLineDrafts((prev) => ({
...prev,
[lineId]: {
...prev[lineId],
[field]: value,
},
}));
};
// const handleSavePayment = (lineId: number) => {
// const newPaidAmount = updatedPaidAmounts[lineId];
// const newAdjustedAmount = updatedAdjustedAmounts[lineId] ?? 0;
// const newNotes = updatedNotes[lineId] ?? "";
// if (newPaidAmount == null || isNaN(newPaidAmount)) return;
// const updatedTxs = updatedTransactions.map((tx) => ({
// ...tx,
// serviceLinePayments: tx.serviceLinePayments.map((sp) =>
// sp.serviceLineId === lineId
// ? {
// ...sp,
// paidAmount: new Decimal(newPaidAmount),
// adjustedAmount: new Decimal(newAdjustedAmount),
// notes: newNotes,
// }
// : sp
// ),
// }));
// const updatedPayment: PaymentWithExtras = {
// ...payment,
// transactions: updatedTxs,
// status: updatedPaymentStatus,
// };
// setUpdatedTransactions(updatedTxs);
// onEditServiceLine(updatedPayment);
// setExpandedLineId(null);
// };
const handleSavePayment = async (lineId: number) => {
const data = serviceLineDrafts[lineId];
if (!data || !data.paidAmount || !data.method || !data.receivedDate) {
console.log("please fill al")
return;
}
const transactionPayload = {
paymentId: payment.id,
amount: data.paidAmount + (data.adjustedAmount ?? 0),
method: data.method,
payerName: data.payerName,
notes: data.notes,
receivedDate: new Date(data.receivedDate),
serviceLinePayments: [
{
serviceLineId: lineId,
paidAmount: data.paidAmount,
adjustedAmount: data.adjustedAmount ?? 0,
notes: data.notes,
},
],
};
try {
const res = await apiRequest("PUT", `/api/payments/${payment.id}`, {
...form,
amountPaid: parseFloat(form.amountPaid),
paymentDate: new Date(form.paymentDate),
});
if (!res.ok) throw new Error("Failed to update payment");
toast({ title: "Success", description: "Payment updated successfully" });
queryClient.invalidateQueries();
await onEditServiceLine(transactionPayload);
setExpandedLineId(null);
onClose();
onSave();
} catch (error) {
toast({
title: "Error",
description: "Failed to update payment",
variant: "destructive",
});
} finally {
setLoading(false);
} catch (err) {
console.log(err)
}
};
const renderInput = (label: string, type: string, lineId: number, field: string, step?: string) => (
<div className="space-y-1">
<label className="text-sm font-medium">{label}</label>
<Input
type={type}
step={step}
value={serviceLineDrafts[lineId]?.[field] ?? ""}
onChange={(e) =>
handleFieldChange(lineId, field, type === "number" ? parseFloat(e.target.value) : e.target.value)
}
/>
</div>
);
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent>
<Dialog open={isOpen} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Edit Payment</DialogTitle>
<DialogDescription>
View and manage payments applied to service lines.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="grid gap-2">
<Label htmlFor="payerName">Payer Name</Label>
<Input
id="payerName"
name="payerName"
value={form.payerName}
onChange={handleChange}
/>
{/* Claim + Patient Info */}
<div className="space-y-1">
<h3 className="text-xl font-semibold">
{payment.claim.patientName}
</h3>
<p className="text-gray-500">
Claim ID: {payment.claimId.toString().padStart(4, "0")}
</p>
<p className="text-gray-500">
Service Date:{" "}
{formatDateToHumanReadable(payment.claim.serviceDate)}
</p>
</div>
<div className="grid gap-2">
<Label htmlFor="amountPaid">Amount Paid</Label>
<Input
id="amountPaid"
name="amountPaid"
type="number"
step="0.01"
value={form.amountPaid}
onChange={handleChange}
/>
{/* Payment Summary */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2">
<div>
<h4 className="font-medium text-gray-900">Payment Info</h4>
<div className="mt-2 space-y-1">
<p>
<span className="text-gray-500">Total Billed:</span> $
{totalBilled.toFixed(2)}
</p>
<p>
<span className="text-gray-500">Total Paid:</span> $
{totalPaid.toFixed(2)}
</p>
<p>
<span className="text-gray-500">Total Due:</span> $
{totalDue.toFixed(2)}
</p>
<div className="pt-2">
<label className="text-sm text-gray-600">Status</label>
<Select
value={updatedPaymentStatus}
onValueChange={(value: PaymentStatus) =>
setUpdatedPaymentStatus(value)
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{paymentStatusOptions.map((status) => (
<SelectItem key={status} value={status}>
{status}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
<div>
<h4 className="font-medium text-gray-900">Metadata</h4>
<div className="mt-2 space-y-1">
<p>
<span className="text-gray-500">Received Date:</span>{" "}
{payment.receivedDate
? formatDateToHumanReadable(payment.receivedDate)
: "N/A"}
</p>
<p>
<span className="text-gray-500">Method:</span>{" "}
{payment.paymentMethod ?? "N/A"}
</p>
<p>
<span className="text-gray-500">Notes:</span>{" "}
{payment.notes || "N/A"}
</p>
</div>
</div>
</div>
<div className="grid gap-2">
<Label htmlFor="paymentDate">Payment Date</Label>
<Input
id="paymentDate"
name="paymentDate"
type="date"
value={form.paymentDate}
onChange={handleChange}
/>
{/* Service Lines Payments */}
<div>
<h4 className="font-medium text-gray-900 pt-4">Service Lines</h4>
<div className="mt-2 space-y-3">
{payment.claim.serviceLines.length > 0 ? (
<>
{payment.claim.serviceLines.map((line) => {
const linePayments = payment.transactions.flatMap((tx) =>
tx.serviceLinePayments.filter(
(sp) => sp.serviceLineId === line.id
)
);
const paidAmount = linePayments.reduce(
(sum, sp) => sum + Number(sp.paidAmount),
0
);
const adjusted = linePayments.reduce(
(sum, sp) => sum + Number(sp.adjustedAmount),
0
);
const due = line.billedAmount - paidAmount;
return (
<div
key={line.id}
className="border p-3 rounded-md bg-gray-50"
>
<p>
<span className="text-gray-500">Procedure Code:</span>{" "}
{line.procedureCode}
</p>
<p>
<span className="text-gray-500">Billed:</span> $
{line.billedAmount.toFixed(2)}
</p>
<p>
<span className="text-gray-500">Paid:</span> $
{paidAmount.toFixed(2)}
</p>
<p>
<span className="text-gray-500">Adjusted:</span> $
{adjusted.toFixed(2)}
</p>
<p>
<span className="text-gray-500">Due:</span> $
{due.toFixed(2)}
</p>
<div className="pt-2">
<Button
variant="outline"
size="sm"
onClick={() => handleEditServiceLine(line.id)}
>
{expandedLineId === line.id
? "Cancel"
: "Edit Payments"}
</Button>
</div>
{expandedLineId === line.id && (
<div className="mt-3 space-y-2">
<div className="space-y-1">
<label
htmlFor={`paid-${line.id}`}
className="text-sm font-medium"
>
Paid Amount
</label>
<Input
type="number"
step="0.01"
placeholder="Paid Amount"
defaultValue={paidAmount}
onChange={(e) =>
setUpdatedPaidAmounts({
...updatedPaidAmounts,
[line.id]: parseFloat(e.target.value),
})
}
/>
</div>
<div className="space-y-1">
<label
htmlFor={`adjusted-${line.id}`}
className="text-sm font-medium"
>
Adjusted Amount
</label>
<Input
id={`adjusted-${line.id}`}
type="number"
step="0.01"
placeholder="Adjusted Amount"
defaultValue={adjusted}
onChange={(e) =>
setUpdatedAdjustedAmounts({
...updatedAdjustedAmounts,
[line.id]: parseFloat(e.target.value),
})
}
/>
</div>
<div className="space-y-1">
<label
htmlFor={`notes-${line.id}`}
className="text-sm font-medium"
>
Notes
</label>
<Input
id={`notes-${line.id}`}
type="text"
placeholder="Notes"
onChange={(e) =>
setUpdatedNotes({
...updatedNotes,
[line.id]: e.target.value,
})
}
/>
</div>
<Button
size="sm"
onClick={() => handleSavePayment(line.id)}
>
Save
</Button>
</div>
)}
</div>
);
})}
</>
) : (
<p className="text-gray-500">No service lines available.</p>
)}
</div>
</div>
<div className="grid gap-2">
<Label htmlFor="paymentMethod">Payment Method</Label>
<Input
id="paymentMethod"
name="paymentMethod"
value={form.paymentMethod}
onChange={handleChange}
/>
{/* Transactions Overview */}
<div>
<h4 className="font-medium text-gray-900 pt-6">All Transactions</h4>
<div className="mt-2 space-y-2">
{payment.transactions.length > 0 ? (
payment.transactions.map((tx) => (
<div
key={tx.id}
className="border p-3 rounded-md bg-white shadow-sm"
>
<p>
<span className="text-gray-500">Date:</span>{" "}
{formatDateToHumanReadable(tx.receivedDate)}
</p>
<p>
<span className="text-gray-500">Amount:</span> $
{Number(tx.amount).toFixed(2)}
</p>
<p>
<span className="text-gray-500">Method:</span> {tx.method}
</p>
{tx.serviceLinePayments.map((sp) => (
<p key={sp.id} className="text-sm text-gray-600 ml-2">
Applied ${Number(sp.paidAmount).toFixed(2)} to service
line ID {sp.serviceLineId}
</p>
))}
</div>
))
) : (
<p className="text-gray-500">No transactions recorded.</p>
)}
</div>
</div>
<div className="grid gap-2">
<Label htmlFor="note">Note</Label>
<Textarea
id="note"
name="note"
value={form.note}
onChange={handleChange}
/>
{/* Actions */}
<div className="flex justify-end space-x-2 pt-6">
<Button variant="outline" onClick={onClose}>
Close
</Button>
</div>
</div>
<DialogFooter>
<Button variant="ghost" onClick={onClose} disabled={loading}>Cancel</Button>
<Button onClick={handleSubmit} disabled={loading}>
{loading ? "Saving..." : "Save Changes"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);

View File

@@ -29,84 +29,23 @@ import {
PaginationPrevious,
} from "@/components/ui/pagination";
import { Checkbox } from "@/components/ui/checkbox";
import {
PaymentUncheckedCreateInputObjectSchema,
PaymentTransactionCreateInputObjectSchema,
ServiceLinePaymentCreateInputObjectSchema,
ClaimUncheckedCreateInputObjectSchema,
ClaimStatusSchema,
StaffUncheckedCreateInputObjectSchema,
} from "@repo/db/usedSchemas";
import { z } from "zod";
import { DeleteConfirmationDialog } from "../ui/deleteDialog";
import PaymentViewModal from "./payment-view-modal";
import PaymentEditModal from "./payment-edit-modal";
import { Prisma } from "@repo/db/generated/prisma";
import LoadingScreen from "../ui/LoadingScreen";
type Payment = z.infer<typeof PaymentUncheckedCreateInputObjectSchema>;
type PaymentTransaction = z.infer<
typeof PaymentTransactionCreateInputObjectSchema
>;
type ServiceLinePayment = z.infer<
typeof ServiceLinePaymentCreateInputObjectSchema
>;
const insertPaymentSchema = (
PaymentUncheckedCreateInputObjectSchema as unknown as z.ZodObject<any>
).omit({
id: true,
createdAt: true,
updatedAt: true,
});
type InsertPayment = z.infer<typeof insertPaymentSchema>;
const updatePaymentSchema = (
PaymentUncheckedCreateInputObjectSchema as unknown as z.ZodObject<any>
)
.omit({
id: true,
createdAt: true,
})
.partial();
type UpdatePayment = z.infer<typeof updatePaymentSchema>;
type PaymentWithExtras = Prisma.PaymentGetPayload<{
include: {
claim: { include: { serviceLines: true } };
servicePayments: true;
transactions: true;
};
}> & {
patientName: string;
paymentDate: Date;
paymentMethod: string;
};
import {
ClaimStatus,
ClaimWithServiceLines,
Payment,
PaymentWithExtras,
} from "@repo/db/types";
import EditPaymentModal from "./payment-edit-modal";
interface PaymentApiResponse {
payments: PaymentWithExtras[];
totalCount: number;
}
//creating types out of schema auto generated.
type Claim = z.infer<typeof ClaimUncheckedCreateInputObjectSchema>;
export type ClaimStatus = z.infer<typeof ClaimStatusSchema>;
type Staff = z.infer<typeof StaffUncheckedCreateInputObjectSchema>;
type ClaimWithServiceLines = Claim & {
serviceLines: {
id: number;
claimId: number;
procedureCode: string;
procedureDate: Date;
oralCavityArea: string | null;
toothNumber: string | null;
toothSurface: string | null;
billedAmount: number;
}[];
staff: Staff | null;
};
interface PaymentsRecentTableProps {
allowEdit?: boolean;
allowView?: boolean;
@@ -179,7 +118,7 @@ export default function PaymentsRecentTable({
});
const updatePaymentMutation = useMutation({
mutationFn: async (payment: Payment) => {
mutationFn: async (payment: PaymentWithExtras) => {
const response = await apiRequest("PUT", `/api/claims/${payment.id}`, {
data: payment,
});
@@ -424,12 +363,14 @@ export default function PaymentsRecentTable({
.claim as ClaimWithServiceLines;
const totalBilled = getTotalBilled(claim);
const totalPaid = (
payment as PaymentWithExtras
).servicePayments.reduce(
(sum, sp) => sum + (sp.paidAmount?.toNumber?.() ?? 0),
0
);
const totalPaid = (payment as PaymentWithExtras).transactions
.flatMap((tx) => tx.serviceLinePayments)
.reduce(
(sum, sp) => sum + (sp.paidAmount?.toNumber?.() ?? 0),
0
);
const outstanding = totalBilled - totalPaid;
return (
@@ -539,19 +480,19 @@ export default function PaymentsRecentTable({
onEditClaim={(payment) => handleEditPayment(payment)}
payment={currentPayment}
/>
)}
)} */}
{isEditPaymentOpen && currentPayment && (
<ClaimPaymentModal
<EditPaymentModal
isOpen={isEditPaymentOpen}
onClose={() => setIsEditPaymentOpen(false)}
onOpenChange={(open) => setIsEditPaymentOpen(open)}
onClose={() => setIsEditPaymentOpen(false)}
payment={currentPayment}
onSave={(updatedPayment) => {
onEditServiceLine={(updatedPayment) => {
updatePaymentMutation.mutate(updatedPayment);
}}
/>
)} */}
)}
{/* Pagination */}
{totalPages > 1 && (