Claim form - combos buttons feature 1

This commit is contained in:
2025-08-28 00:19:54 +05:30
parent 09ae4df819
commit 269cdf29b3
11 changed files with 3540 additions and 475 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -10,7 +10,7 @@ import {
} from "@/components/ui/select";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { X, Calendar as CalendarIcon, HelpCircle } from "lucide-react";
import { X, Calendar as CalendarIcon, HelpCircle, Trash2 } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { Calendar } from "@/components/ui/calendar";
import {
@@ -27,7 +27,6 @@ import {
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import procedureCodes from "../../assets/data/procedureCodes.json";
import { formatLocalDate, parseLocalDate } from "@/utils/dateUtils";
import {
Claim,
@@ -39,6 +38,12 @@ import {
UpdatePatient,
} from "@repo/db/types";
import { Decimal } from "decimal.js";
import {
COMBO_BUTTONS,
mapPricesForForm,
applyComboToForm,
getDescriptionForCode,
} from "@/utils/procedureCombosMapping";
interface ClaimFormData {
patientId: number;
@@ -252,25 +257,13 @@ export function ClaimForm({
};
// Map Price function
const mapPrices = () => {
const updatedLines = form.serviceLines.map((line) => {
if (line.procedureCode && line.procedureCode.trim() !== "") {
const normalizedCode = line.procedureCode.toUpperCase().trim();
const procedureInfo = procedureCodes.find(
(p) => p["Procedure Code"].toUpperCase().trim() === normalizedCode
);
if (procedureInfo && procedureInfo.Price) {
return {
...line,
totalBilled: new Decimal(parseFloat(procedureInfo.Price)),
};
}
}
return line;
});
setForm({ ...form, serviceLines: updatedLines });
const onMapPrice = () => {
setForm((prev) =>
mapPricesForForm({
form: prev,
patientDOB: patient?.dateOfBirth ?? "",
})
);
};
// FILE UPLOAD ZONE
@@ -554,9 +547,13 @@ export function ClaimForm({
</div>
</div>
<div className="grid grid-cols-7 gap-4 mb-2 font-medium text-sm text-gray-700">
<span>Procedure Code</span>
<span>Abbreviation</span>
{/* Header */}
<div className="grid grid-cols-[1.5fr,0.5fr,1fr,1fr,1fr,1fr,1fr] gap-1 mb-2 font-medium text-sm text-gray-700 items-center">
<div className="grid grid-cols-[auto,1fr] items-center gap-2">
<span />
<span className="pl-8">Procedure Code</span>
</div>
<span className="justify-self-center">Info</span>
<span>Procedure Date</span>
<span>Oral Cavity Area</span>
<span>Tooth Number</span>
@@ -565,116 +562,128 @@ export function ClaimForm({
</div>
{/* Dynamic Rows */}
{form.serviceLines.map((line, i) => (
<div key={i} className="grid grid-cols-7 gap-1 mb-2">
<Input
placeholder="eg. D0120"
value={line.procedureCode}
onChange={(e) =>
updateServiceLine(
i,
"procedureCode",
e.target.value.toUpperCase()
)
}
/>
{form.serviceLines.map((line, i) => {
const raw = line.procedureCode || "";
const code = raw.trim();
const desc = code
? getDescriptionForCode(code) || "No description available"
: "Enter a procedure code";
<div className="flex items-center justify-center">
<Tooltip>
<TooltipTrigger asChild>
<HelpCircle className="h-4 w-4 text-gray-400 hover:text-gray-600 cursor-help" />
</TooltipTrigger>
<TooltipContent>
<div className="text-sm">
{line.procedureCode &&
line.procedureCode.trim() !== ""
? (() => {
const normalizedCode = line.procedureCode
.toUpperCase()
.trim();
const procedureInfo = procedureCodes.find(
(p) =>
p["Procedure Code"].toUpperCase().trim() ===
normalizedCode
);
return procedureInfo
? procedureInfo.Description ||
"No description available"
: "Enter a valid procedure code";
})()
: "Enter a procedure code"}
</div>
</TooltipContent>
</Tooltip>
</div>
{/* Date Picker */}
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
className="w-full text-left font-normal"
return (
<div
key={i}
className="grid grid-cols-[1.5fr,0.5fr,1fr,1fr,1fr,1fr,1fr] gap-1 mb-2 items-center"
>
<div className="grid grid-cols-[auto,1fr] items-center gap-2">
<button
type="button"
onClick={() =>
setForm((prev) => {
const next = {
...prev,
serviceLines: [...prev.serviceLines],
};
next.serviceLines.splice(i, 1);
return next;
})
}
className="p-1 rounded hover:bg-red-50"
>
<CalendarIcon className="mr-2 h-4 w-4" />
{line.procedureDate || "Pick Date"}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<Calendar
mode="single"
selected={new Date(line.procedureDate)}
onSelect={(date) => updateProcedureDate(i, date)}
<Trash2 className="h-4 w-4 text-red-500 hover:text-red-700" />
</button>
<Input
placeholder="eg. D0120"
value={line.procedureCode}
onChange={(e) =>
updateServiceLine(
i,
"procedureCode",
e.target.value.toUpperCase()
)
}
/>
</PopoverContent>
</Popover>
</div>
<Input
placeholder="Oral Cavity Area"
value={line.oralCavityArea}
onChange={(e) =>
updateServiceLine(i, "oralCavityArea", e.target.value)
}
/>
<Input
placeholder="eg. 14"
value={line.toothNumber}
onChange={(e) =>
updateServiceLine(i, "toothNumber", e.target.value)
}
/>
<Input
placeholder="eg. 'B', 'D', 'F', 'I', 'L', 'M', 'O'"
value={line.toothSurface}
onChange={(e) =>
updateServiceLine(i, "toothSurface", e.target.value)
}
/>
<Input
type="number"
step="0.01"
placeholder="$0.00"
value={
line.totalBilled?.toNumber() === 0
? ""
: line.totalBilled?.toNumber()
}
onChange={(e) => {
updateServiceLine(i, "totalBilled", e.target.value);
}}
onBlur={(e) => {
const val = parseFloat(e.target.value);
const rounded = Math.round(val * 100) / 100;
updateServiceLine(
i,
"totalBilled",
isNaN(rounded) ? 0 : rounded
);
}}
/>
</div>
))}
<div className="flex justify-center">
<Tooltip>
<TooltipTrigger asChild>
<HelpCircle className="h-4 w-4 text-gray-400 hover:text-gray-600 cursor-help" />
</TooltipTrigger>
<TooltipContent>
<div className="text-sm">{desc}</div>
</TooltipContent>
</Tooltip>
</div>
{/* Date Picker */}
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
className="w-full text-left font-normal"
>
<CalendarIcon className="mr-2 h-4 w-4" />
{line.procedureDate || "Pick Date"}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<Calendar
mode="single"
selected={new Date(line.procedureDate)}
onSelect={(date) => updateProcedureDate(i, date)}
/>
</PopoverContent>
</Popover>
<Input
placeholder="Oral Cavity Area"
value={line.oralCavityArea}
onChange={(e) =>
updateServiceLine(i, "oralCavityArea", e.target.value)
}
/>
<Input
placeholder="eg. 14"
value={line.toothNumber}
onChange={(e) =>
updateServiceLine(i, "toothNumber", e.target.value)
}
/>
<Input
placeholder="eg. 'B', 'D', 'F', 'I', 'L', 'M', 'O'"
value={line.toothSurface}
onChange={(e) =>
updateServiceLine(i, "toothSurface", e.target.value)
}
/>
<Input
type="number"
step="0.01"
placeholder="$0.00"
value={
line.totalBilled?.toNumber() === 0
? ""
: line.totalBilled?.toNumber()
}
onChange={(e) => {
updateServiceLine(i, "totalBilled", e.target.value);
}}
onBlur={(e) => {
const val = parseFloat(e.target.value);
const rounded = Math.round(val * 100) / 100;
updateServiceLine(
i,
"totalBilled",
isNaN(rounded) ? 0 : rounded
);
}}
/>
</div>
);
})}
<Button
className="mt-2"
variant="outline"
onClick={() =>
setForm((prev) => ({
@@ -699,10 +708,28 @@ export function ClaimForm({
</Button>
<div className="flex gap-2 mt-10 mb-10">
<Button variant="outline">Child Prophy Codes</Button>
<Button variant="outline">Adult Prophy Codes</Button>
<Button variant="outline">Customized Group Codes</Button>
<Button variant="success" onClick={mapPrices}>
{COMBO_BUTTONS.map((b) => (
<Button
key={b.id}
variant="secondary"
onClick={() =>
setForm((prev) =>
applyComboToForm(
prev,
b.id as any,
patient?.dateOfBirth ?? "",
{
replaceAll: true,
lineDate: prev.serviceDate,
}
)
)
}
>
{b.label}
</Button>
))}
<Button variant="success" onClick={onMapPrice}>
Map Price
</Button>
</div>

View File

@@ -0,0 +1,37 @@
export const PROCEDURE_COMBOS: Record<
string,
{ id: string; label: string; codes: string[] }
> = {
childRecall: {
id: "childRecall",
label: "Child Recall",
codes: [
"D0120",
"D1120",
"D0272",
"D1208",
"D2331",
"D0120",
"D1120",
"D0272",
"D1208",
"D2331",
"D0120",
"D1120",
"D0272",
"D1208",
"D2331",
],
},
adultProphy: {
id: "adultProphy",
label: "Adult Prophy",
codes: ["D0150", "D1110", "D0274", "D1208"],
},
bitewingsOnly: {
id: "bitewingsOnly",
label: "Bitewings Only",
codes: ["D0272"],
},
// add more…
};

View File

@@ -0,0 +1,270 @@
import { InputServiceLine } from "@repo/db/types";
import Decimal from "decimal.js";
import rawCodeTable from "@/assets/data/procedureCodes.json";
import { PROCEDURE_COMBOS } from "./procedureCombos";
/* ----------------------------- Types ----------------------------- */
export type CodeRow = {
"Procedure Code": string;
Description?: string;
Price?: string | number | null;
PriceLTEQ21?: string | number | null;
PriceGT21?: string | number | null;
[k: string]: unknown;
};
const CODE_TABLE = rawCodeTable as CodeRow[];
export type ClaimFormLike = {
serviceDate: string; // form-level service date
serviceLines: InputServiceLine[];
};
export type ApplyOptions = {
append?: boolean;
startIndex?: number;
lineDate?: string;
clearTrailing?: boolean;
replaceAll?: boolean;
};
/* ----------------------------- Helpers ----------------------------- */
export const COMBO_BUTTONS = Object.values(PROCEDURE_COMBOS).map((c) => ({
id: c.id,
label: c.label,
}));
// Build a fast lookup map keyed by normalized code
const normalizeCode = (code: string) => code.replace(/\s+/g, "").toUpperCase();
const CODE_MAP: Map<string, CodeRow> = (() => {
const m = new Map<string, CodeRow>();
for (const r of CODE_TABLE) {
const k = normalizeCode(String(r["Procedure Code"] || ""));
if (k && !m.has(k)) m.set(k, r);
}
return m;
})();
// this function is solely for abbrevations feature in claim-form
export function getDescriptionForCode(
code: string | undefined
): string | undefined {
if (!code) return undefined;
const row = CODE_MAP.get(normalizeCode(code));
return row?.Description;
}
const isBlankPrice = (v: unknown) => {
if (v == null) return true;
const s = String(v).trim().toUpperCase();
return s === "" || s === "IC" || s === "NC";
};
const toDecimalOrZero = (v: unknown): Decimal => {
if (isBlankPrice(v)) return new Decimal(0);
const n = typeof v === "string" ? parseFloat(v) : (v as number);
return new Decimal(Number.isFinite(n) ? n : 0);
};
// Accepts string or Date, supports MM/DD/YYYY and YYYY-MM-DD
type DateInput = string | Date;
const parseDate = (d: DateInput): Date => {
if (d instanceof Date)
return new Date(d.getFullYear(), d.getMonth(), d.getDate());
const s = String(d).trim();
// MM/DD/YYYY
const mdy = /^(\d{2})\/(\d{2})\/(\d{4})$/;
const m1 = mdy.exec(s);
if (m1) {
const mm = Number(m1[1]);
const dd = Number(m1[2]);
const yyyy = Number(m1[3]);
return new Date(yyyy, mm - 1, dd);
}
// YYYY-MM-DD
const ymd = /^(\d{4})-(\d{2})-(\d{2})$/;
const m2 = ymd.exec(s);
if (m2) {
const yyyy = Number(m2[1]);
const mm = Number(m2[2]);
const dd = Number(m2[3]);
return new Date(yyyy, mm - 1, dd);
}
// Fallback
return new Date(s);
};
const ageOnDate = (dob: DateInput, on: DateInput): number => {
const birth = parseDate(dob);
const ref = parseDate(on);
let age = ref.getFullYear() - birth.getFullYear();
const hadBirthday =
ref.getMonth() > birth.getMonth() ||
(ref.getMonth() === birth.getMonth() && ref.getDate() >= birth.getDate());
if (!hadBirthday) age -= 1;
return age;
};
/**
* Price chooser that respects your age rules and IC/NC semantics.
* - If <=21 → PriceLTEQ21 (if present and not IC/NC/blank) else Price.
* - If >21 → PriceGT21 (if present and not IC/NC/blank) else Price.
* - If chosen field is IC/NC/blank → 0 (leave empty).
*/
export function pickPriceForRowByAge(row: CodeRow, age: number): Decimal {
if (age <= 21) {
if (!isBlankPrice(row.PriceLTEQ21)) return toDecimalOrZero(row.PriceLTEQ21);
} else {
if (!isBlankPrice(row.PriceGT21)) return toDecimalOrZero(row.PriceGT21);
}
// Fallback to Price if tiered not available/blank
if (!isBlankPrice(row.Price)) return toDecimalOrZero(row.Price);
return new Decimal(0);
}
/**
* Gets price for a code using age & code table.
*/
function getPriceForCodeWithAgeFromMap(
map: Map<string, CodeRow>,
code: string,
age: number
): Decimal {
const row = map.get(normalizeCode(code));
return row ? pickPriceForRowByAge(row, age) : new Decimal(0);
}
// helper keeping lines empty,
export const makeEmptyLine = (lineDate: string): InputServiceLine => ({
procedureCode: "",
procedureDate: lineDate,
oralCavityArea: "",
toothNumber: "",
toothSurface: "",
totalBilled: new Decimal(0),
totalAdjusted: new Decimal(0),
totalPaid: new Decimal(0),
});
// Ensure the array has at least `min` lines; append blank ones if needed.
const ensureCapacity = (
lines: (InputServiceLine | undefined)[],
min: number,
lineDate: string
) => {
while (lines.length < min) {
lines.push(makeEmptyLine(lineDate));
}
};
/* ------------------------- Main entry points ------------------------- */
/**
* Map prices for ALL existing lines in a form (your "Map Price" button),
* using patient's DOB and the form's serviceDate (or per-line procedureDate).
* Returns a NEW form object (immutable).
*/
export function mapPricesForForm<T extends ClaimFormLike>(params: {
form: T;
patientDOB: DateInput;
}): T {
const { form, patientDOB } = params;
return {
...form,
serviceLines: form.serviceLines.map((ln) => {
const age = ageOnDate(patientDOB, form.serviceDate);
const code = normalizeCode(ln.procedureCode || "");
if (!code) return { ...ln };
const price = getPriceForCodeWithAgeFromMap(CODE_MAP, code, age);
return { ...ln, procedureCode: code, totalBilled: price };
}),
};
}
/**
* Apply a preset combo (fills codes & prices) using patientDOB and serviceDate.
* Returns a NEW form object (immutable).
*/
export function applyComboToForm<T extends ClaimFormLike>(
form: T,
comboId: keyof typeof PROCEDURE_COMBOS,
patientDOB: DateInput,
options: ApplyOptions = {}
): T {
const preset = PROCEDURE_COMBOS[String(comboId)];
if (!preset) return form;
const {
append = true,
startIndex,
lineDate = form.serviceDate,
clearTrailing = false,
replaceAll = false, // NEW
} = options;
const next: T = { ...form, serviceLines: [...form.serviceLines] };
// Replace-all: blank all existing and start from 0
if (replaceAll) {
for (let i = 0; i < next.serviceLines.length; i++) {
next.serviceLines[i] = makeEmptyLine(lineDate);
}
}
// determine insertion index
let insertAt = 0;
if (!replaceAll) {
if (append) {
let last = -1;
next.serviceLines.forEach((ln, i) => {
if (ln.procedureCode?.trim()) last = i;
});
insertAt = Math.max(0, last + 1);
} else if (typeof startIndex === "number") {
insertAt = Math.max(
0,
Math.min(startIndex, next.serviceLines.length - 1)
);
}
} // if replaceAll, insertAt stays 0
// Make sure we have enough rows for the whole combo
ensureCapacity(next.serviceLines, insertAt + preset.codes.length, lineDate);
// Age on the specific line date we will set
const age = ageOnDate(patientDOB, lineDate);
for (let j = 0; j < preset.codes.length; j++) {
const i = insertAt + j;
if (i >= next.serviceLines.length) break;
const codeRaw = preset.codes[j];
if (!codeRaw) continue;
const code = normalizeCode(codeRaw);
const price = getPriceForCodeWithAgeFromMap(CODE_MAP, code, age);
const original = next.serviceLines[i];
next.serviceLines[i] = {
...original,
procedureCode: code,
procedureDate: lineDate,
oralCavityArea: original?.oralCavityArea ?? "",
toothNumber: original?.toothNumber ?? "",
toothSurface: original?.toothSurface ?? "",
totalBilled: price,
totalAdjusted: new Decimal(0),
totalPaid: new Decimal(0),
} as InputServiceLine;
}
if (replaceAll || clearTrailing) {
const after = insertAt + preset.codes.length;
for (let i = after; i < next.serviceLines.length; i++) {
next.serviceLines[i] = makeEmptyLine(lineDate);
}
}
return next;
}