Refactor: Replace barcodeImage with hub3aText in BillEditForm

- Changed from storing base64-encoded bitmap to decoded HUB-3A payment string
- Implemented migration logic to convert legacy barcodeImage to hub3aText on component mount
- Updated state management to use hub3aText instead of barcodeImage
- Replaced image display with Pdf417Barcode component for consistent rendering
- Added error handling for migration promise
- Updated useEffect dependencies to prevent stale closures
- More efficient storage and easier to work with payment data going forward

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Knee Cola
2025-11-23 08:24:08 +01:00
parent a254ca5430
commit 278976b75b

View File

@@ -2,17 +2,18 @@
import { DocumentIcon, TrashIcon } from "@heroicons/react/24/outline"; import { DocumentIcon, TrashIcon } from "@heroicons/react/24/outline";
import { Bill, BilledTo, BillingLocation } from "../lib/db-types"; import { Bill, BilledTo, BillingLocation } from "../lib/db-types";
import React, { FC } from "react"; import React, { FC, useEffect } from "react";
import { useFormState } from "react-dom"; import { useFormState } from "react-dom";
import { updateOrAddBill } from "../lib/actions/billActions"; import { updateOrAddBill } from "../lib/actions/billActions";
import Link from "next/link"; import Link from "next/link";
import { formatYearMonth } from "../lib/format"; import { formatYearMonth } from "../lib/format";
import { DecodeResult, findDecodePdf417 } from "../lib/pdf/barcodeDecoder"; import { decodeFromImage, DecodeResult, findDecodePdf417 } from "../lib/pdf/barcodeDecoder";
import { useLocale, useTranslations } from "next-intl"; import { useLocale, useTranslations } from "next-intl";
import { Pdf417Barcode } from "./Pdf417Barcode";
// Next.js does not encode an utf-8 file name correctly when sending a form with a file attachment // Next.js does not encode an utf-8 file name correctly when sending a form with a file attachment
// This is a workaround for that // This is a workaround for that
const updateOrAddBillMiddleware = (locationId: string, billId:string|undefined, billYear:number|undefined, billMonth:number|undefined, prevState:any, formData: FormData) => { const updateOrAddBillMiddleware = (locationId: string, billId: string | undefined, billYear: number | undefined, billMonth: number | undefined, prevState: any, formData: FormData) => {
// URL encode the file name of the attachment so it is correctly sent to the server // URL encode the file name of the attachment so it is correctly sent to the server
const billAttachment = formData.get('billAttachment') as File; const billAttachment = formData.get('billAttachment') as File;
formData.set('billAttachment', billAttachment, encodeURIComponent(billAttachment.name)); formData.set('billAttachment', billAttachment, encodeURIComponent(billAttachment.name));
@@ -24,26 +25,46 @@ export interface BillEditFormProps {
bill?: Bill, bill?: Bill,
} }
export const BillEditForm:FC<BillEditFormProps> = ({ location, bill }) => { export const BillEditForm: FC<BillEditFormProps> = ({ location, bill }) => {
const t = useTranslations("bill-edit-form"); const t = useTranslations("bill-edit-form");
const locale = useLocale(); const locale = useLocale();
const { _id: billID, name, paid, billedTo = BilledTo.Tenant, attachment, notes, payedAmount: initialPayedAmount, barcodeImage: initialBarcodeImage } = bill ?? { _id:undefined, name:"", paid:false, notes:"" }; const { _id: billID, name, paid, billedTo = BilledTo.Tenant, attachment, notes, payedAmount: initialPayedAmount } = bill ?? { _id: undefined, name: "", paid: false, notes: "" };
const { yearMonth:{year: billYear, month: billMonth}, _id: locationID } = location; const { yearMonth: { year: billYear, month: billMonth }, _id: locationID } = location;
const initialState = { message: null, errors: {} }; const initialState = { message: null, errors: {} };
const handleAction = updateOrAddBillMiddleware.bind(null, locationID, billID, billYear, billMonth); const handleAction = updateOrAddBillMiddleware.bind(null, locationID, billID, billYear, billMonth);
const [ isScanningPDF, setIsScanningPDF ] = React.useState<boolean>(false); const [isScanningPDF, setIsScanningPDF] = React.useState<boolean>(false);
const [ state, dispatch ] = useFormState(handleAction, initialState); const [state, dispatch] = useFormState(handleAction, initialState);
const [ isPaid, setIsPaid ] = React.useState<boolean>(paid); const [isPaid, setIsPaid] = React.useState<boolean>(paid);
const [ billedToValue, setBilledToValue ] = React.useState<BilledTo>(billedTo); const [billedToValue, setBilledToValue] = React.useState<BilledTo>(billedTo);
const [ payedAmount, setPayedAmount ] = React.useState<string>(initialPayedAmount ? `${initialPayedAmount/100}` : "" ); const [payedAmount, setPayedAmount] = React.useState<string>(initialPayedAmount ? `${initialPayedAmount / 100}` : "");
const [ barcodeImage, setBarcodeImage ] = React.useState<string | undefined>(initialBarcodeImage);
const [ barcodeResults, setBarcodeResults ] = React.useState<Array<DecodeResult> | null>(null); // legacy support - to be removed
const [hub3aText, setHub3aText] = React.useState<string | undefined>(bill?.hub3aText);
const [barcodeResults, setBarcodeResults] = React.useState<Array<DecodeResult> | null>(null);
useEffect(() => {
// migrating the legacy `barcodeImage` field to `hub3aText`
// by converting it to `hub3aText`
if (!hub3aText && bill?.barcodeImage) {
decodeFromImage(bill.barcodeImage).then(results => {
if (results && results.length > 0) {
const {
hub3aText: decodedHub3aText,
} = results[0];
setHub3aText(decodedHub3aText);
}
}).catch(error => {
console.error('Failed to migrate barcodeImage to hub3aText:', error);
});
}
}, [bill?.barcodeImage, hub3aText]);
const billedTo_handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { const billedTo_handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
@@ -62,203 +83,201 @@ export const BillEditForm:FC<BillEditFormProps> = ({ location, bill }) => {
setIsScanningPDF(true); setIsScanningPDF(true);
setPayedAmount(""); setPayedAmount("");
setBarcodeImage(undefined);
setBarcodeResults(null); setBarcodeResults(null);
const results = await findDecodePdf417(event); const results = await findDecodePdf417(event);
if(results && results.length > 0) { if (results && results.length > 0) {
if(results.length === 1) { if (results.length === 1) {
const { const {
barcodeImage, hub3aText,
billInfo billInfo
} = results[0]; } = results[0];
setPayedAmount(`${billInfo.amount/100}`); setPayedAmount(`${billInfo.amount / 100}`);
setBarcodeImage(barcodeImage); setHub3aText(hub3aText);
} else { } else {
setPayedAmount(""); setPayedAmount("");
setBarcodeImage(undefined);
setBarcodeResults(results); setBarcodeResults(results);
setHub3aText(undefined);
} }
} }
setIsScanningPDF(false); setIsScanningPDF(false);
} }
const handleBarcodeSelectClick = (result: DecodeResult) => { const handleBarcodeSelectClick = (result: DecodeResult) => {
setPayedAmount(`${result.billInfo.amount/100}`); setPayedAmount(`${result.billInfo.amount / 100}`);
setBarcodeImage(result.barcodeImage); setHub3aText(result.hub3aText);
setBarcodeResults(null); setBarcodeResults(null);
} }
return( return (
<div className="card card-compact card-bordered bg-base-100 shadow-s"> <div className="card card-compact card-bordered bg-base-100 shadow-s">
<div className="card-body"> <div className="card-body">
<h2 className="card-title">{`${formatYearMonth(location.yearMonth)} ${location.name}`}</h2> <h2 className="card-title">{`${formatYearMonth(location.yearMonth)} ${location.name}`}</h2>
<form action={ dispatch }> <form action={dispatch}>
{ {
// don't show the delete button if we are adding a new bill // don't show the delete button if we are adding a new bill
bill ? bill ?
<Link href={`/${locale}/bill/${locationID}-${billID}/delete/`} data-tip={t("delete-tooltip")}> <Link href={`/${locale}/bill/${locationID}-${billID}/delete/`} data-tip={t("delete-tooltip")}>
<TrashIcon className="h-[1em] w-[1em] absolute cursor-pointer text-error bottom-5 right-4 text-2xl" /> <TrashIcon className="h-[1em] w-[1em] absolute cursor-pointer text-error bottom-5 right-4 text-2xl" />
</Link> : null </Link> : null
} }
<input id="billName" name="billName" type="text" placeholder={t("bill-name-placeholder")} className="input input-bordered w-full" defaultValue={name} required /> <input id="billName" name="billName" type="text" placeholder={t("bill-name-placeholder")} className="input input-bordered w-full" defaultValue={name} required />
<div id="status-error" aria-live="polite" aria-atomic="true"> <div id="status-error" aria-live="polite" aria-atomic="true">
{state.errors?.billName && {state.errors?.billName &&
state.errors.billName.map((error: string) => ( state.errors.billName.map((error: string) => (
<p className="mt-2 text-sm text-red-500" key={error}> <p className="mt-2 text-sm text-red-500" key={error}>
{error} {error}
</p> </p>
))} ))}
</div>
{
// <textarea className="textarea textarea-bordered my-1 w-full max-w-sm block" placeholder="Opis" value="Pričuva, Voda, Smeće"></textarea>
attachment ?
<Link href={`/attachment/${locationID}-${billID}/`} target="_blank" className='text-center w-full max-w-[20em] text-nowrap truncate inline-block mt-4'>
<DocumentIcon className="h-[1em] w-[1em] text-2xl inline-block mr-1" />
{decodeURIComponent(attachment.fileName)}
</Link>
: null
}
<div className="flex">
<input id="billAttachment" name="billAttachment" type="file" className="file-input file-input-bordered grow file-input-s my-2 block max-w-[17em] md:max-w-[80em] break-words" onChange={billAttachment_handleChange} />
</div>
{
isScanningPDF &&
<div className="flex flex-row items-center w-full mt-2">
<div className="loading loading-spinner loading-m mr-2"></div>
<span>{t("scanning-pdf")}</span>
</div> </div>
} {
{ // <textarea className="textarea textarea-bordered my-1 w-full max-w-sm block" placeholder="Opis" value="Pričuva, Voda, Smeće"></textarea>
// if multiple results are found, show them as a list
// and notify the user to select the correct one attachment ?
barcodeResults && barcodeResults.length > 0 && <Link href={`/attachment/${locationID}-${billID}/`} target="_blank" className='text-center w-full max-w-[20em] text-nowrap truncate inline-block mt-4'>
<> <DocumentIcon className="h-[1em] w-[1em] text-2xl inline-block mr-1" />
<div className="flex mt-2 ml-2"> {decodeURIComponent(attachment.fileName)}
<label className="label-text max-w-xs break-words">{t("multiple-barcode-results-notification")}</label> </Link>
: null
}
<div className="flex">
<input id="billAttachment" name="billAttachment" type="file" className="file-input file-input-bordered grow file-input-s my-2 block max-w-[17em] md:max-w-[80em] break-words" onChange={billAttachment_handleChange} />
</div>
{
isScanningPDF &&
<div className="flex flex-row items-center w-full mt-2">
<div className="loading loading-spinner loading-m mr-2"></div>
<span>{t("scanning-pdf")}</span>
</div>
}
{
// if multiple results are found, show them as a list
// and notify the user to select the correct one
barcodeResults && barcodeResults.length > 0 &&
<>
<div className="flex mt-2 ml-2">
<label className="label-text max-w-xs break-words">{t("multiple-barcode-results-notification")}</label>
</div>
<div className="flex">
<label className="label grow pt-0 ml-3">
<ul className="list-none">
{barcodeResults.map((result, index) => (
<li key={index} className="cursor-pointer mt-3" onClick={() => handleBarcodeSelectClick(result)}>
👉 {result.billInfo.description}
</li>
))}
</ul>
</label>
</div>
</>
}
<div id="status-error" aria-live="polite" aria-atomic="true">
{state.errors?.billAttachment &&
state.errors.billAttachment.map((error: string) => (
<p className="mt-2 text-sm text-red-500" key={error}>
{error}
</p>
))}
</div> </div>
<div className="flex"> <div className="flex">
<label className="label grow pt-0 ml-3"> <div className="form-control flex-row">
<ul className="list-none"> <label className="cursor-pointer label align-middle">
{barcodeResults.map((result, index) => ( <span className="label-text mr-[1em]">{t("paid-checkbox")}</span>
<li key={index} className="cursor-pointer mt-3" onClick={() => handleBarcodeSelectClick(result)}> <input id="billPaid" name="billPaid" type="checkbox" className="toggle toggle-success" defaultChecked={paid} onChange={billPaid_handleChange} />
👉 { result.billInfo.description } </label>
</li> </div>
))} <div className="form-control grow">
</ul> <label className="cursor-pointer label grow">
</label> <span className="label-text mx-[1em]">{t("payed-amount")}</span>
<input type="text" id="payedAmount" name="payedAmount" className="input input-bordered text-right w-[5em] grow" placeholder="0.00" value={payedAmount} onFocus={e => e.target.select()} onChange={payedAmount_handleChange} />
</label>
</div>
</div> </div>
</> <div id="status-error" aria-live="polite" aria-atomic="true">
} {state.errors?.payedAmount &&
<div id="status-error" aria-live="polite" aria-atomic="true"> state.errors.payedAmount.map((error: string) => (
{state.errors?.billAttachment && <p className="mt-2 text-sm text-red-500" key={error}>
state.errors.billAttachment.map((error: string) => ( {error}
<p className="mt-2 text-sm text-red-500" key={error}> </p>
{error} ))}
</p>
))}
</div>
<div className="flex">
<div className="form-control flex-row">
<label className="cursor-pointer label align-middle">
<span className="label-text mr-[1em]">{t("paid-checkbox")}</span>
<input id="billPaid" name="billPaid" type="checkbox" className="toggle toggle-success" defaultChecked={paid} onChange={billPaid_handleChange} />
</label>
</div> </div>
<div className="form-control grow">
<label className="cursor-pointer label grow">
<span className="label-text mx-[1em]">{t("payed-amount")}</span>
<input type="text" id="payedAmount" name="payedAmount" className="input input-bordered text-right w-[5em] grow" placeholder="0.00" value={payedAmount} onFocus={e => e.target.select()} onChange={payedAmount_handleChange} />
</label>
</div>
</div>
<div id="status-error" aria-live="polite" aria-atomic="true">
{state.errors?.payedAmount &&
state.errors.payedAmount.map((error: string) => (
<p className="mt-2 text-sm text-red-500" key={error}>
{error}
</p>
))}
</div>
<input type="hidden" name="barcodeImage" value={barcodeImage} /> <input type="hidden" name="hub3aText" value={hub3aText} />
{ {
barcodeImage ? hub3aText ?
<div className="form-control p-1"> <div className="form-control p-1">
<label className="cursor-pointer label p-2 grow bg-white"> <label className="cursor-pointer label p-2 grow bg-white">
<img src={barcodeImage} className="grow sm:max-w-[350px]" alt="2D Barcode" /> <Pdf417Barcode hub3aText={hub3aText} />
</label> </label>
<p className="text-xs my-1">{t.rich('barcode-disclaimer', { br: () => <br /> })}</p> <p className="text-xs my-1">{t.rich('barcode-disclaimer', { br: () => <br /> })}</p>
</div> : null </div> : null
}
<textarea id="billNotes" name="billNotes" className="textarea textarea-bordered my-2 max-w-lg w-full block" placeholder={t("notes-placeholder")} defaultValue={notes ?? ''}></textarea>
<div id="status-error" aria-live="polite" aria-atomic="true">
{state.errors?.billNotes &&
state.errors.billNotes.map((error: string) => (
<p className="mt-2 text-sm text-red-500" key={error}>
{error}
</p>
))}
</div>
<div className="form-control mt-4">
<div className="flex items-center gap-4">
<span className="label-text">{t("billed-to-label")}</span>
<label className="label cursor-pointer gap-2">
<input
type="radio"
name="billedTo"
value={BilledTo.Tenant}
className="radio radio-primary"
checked={billedToValue === BilledTo.Tenant}
onChange={billedTo_handleChange}
/>
<span className="label-text">{t("billed-to-tenant-option")}</span>
</label>
<label className="label cursor-pointer gap-2">
<input
type="radio"
name="billedTo"
value={BilledTo.Landlord}
className="radio radio-primary"
checked={billedToValue === BilledTo.Landlord}
onChange={billedTo_handleChange}
/>
<span className="label-text">{t("billed-to-landlord-option")}</span>
</label>
</div>
</div>
{/* Show toggle only when adding a new bill (not editing) */}
{!bill && (
<div className="form-control">
<label className="label cursor-pointer">
<span className="label-text">{t("add-to-subsequent-months")}</span>
<input type="checkbox" name="addToSubsequentMonths" className="toggle toggle-primary" />
</label>
</div>
)}
<div className="pt-4">
<button type="submit" className="btn btn-primary">{t("save-button")}</button>
<Link className="btn btn-neutral ml-3" href={`/?year=${billYear}&month=${billMonth}`}>{t("cancel-button")}</Link>
</div>
<div id="status-error" aria-live="polite" aria-atomic="true">
{state.message &&
<p className="mt-2 text-sm text-red-500">
{state.message}
</p>
} }
</div> <textarea id="billNotes" name="billNotes" className="textarea textarea-bordered my-2 max-w-lg w-full block" placeholder={t("notes-placeholder")} defaultValue={notes ?? ''}></textarea>
</form> <div id="status-error" aria-live="polite" aria-atomic="true">
</div> {state.errors?.billNotes &&
</div>); state.errors.billNotes.map((error: string) => (
<p className="mt-2 text-sm text-red-500" key={error}>
{error}
</p>
))}
</div>
<div className="form-control mt-4">
<div className="flex items-center gap-4">
<span className="label-text">{t("billed-to-label")}</span>
<label className="label cursor-pointer gap-2">
<input
type="radio"
name="billedTo"
value={BilledTo.Tenant}
className="radio radio-primary"
checked={billedToValue === BilledTo.Tenant}
onChange={billedTo_handleChange}
/>
<span className="label-text">{t("billed-to-tenant-option")}</span>
</label>
<label className="label cursor-pointer gap-2">
<input
type="radio"
name="billedTo"
value={BilledTo.Landlord}
className="radio radio-primary"
checked={billedToValue === BilledTo.Landlord}
onChange={billedTo_handleChange}
/>
<span className="label-text">{t("billed-to-landlord-option")}</span>
</label>
</div>
</div>
{/* Show toggle only when adding a new bill (not editing) */}
{!bill && (
<div className="form-control">
<label className="label cursor-pointer">
<span className="label-text">{t("add-to-subsequent-months")}</span>
<input type="checkbox" name="addToSubsequentMonths" className="toggle toggle-primary" />
</label>
</div>
)}
<div className="pt-4">
<button type="submit" className="btn btn-primary">{t("save-button")}</button>
<Link className="btn btn-neutral ml-3" href={`/?year=${billYear}&month=${billMonth}`}>{t("cancel-button")}</Link>
</div>
<div id="status-error" aria-live="polite" aria-atomic="true">
{state.message &&
<p className="mt-2 text-sm text-red-500">
{state.message}
</p>
}
</div>
</form>
</div>
</div>);
} }