"use client"; import { DocumentIcon, TrashIcon } from "@heroicons/react/24/outline"; import { Bill, BillingLocation } from "../lib/db-types"; import React, { FC } from "react"; import { useFormState } from "react-dom"; import { updateOrAddBill } from "../lib/actions/billActions"; import Link from "next/link"; import { formatYearMonth } from "../lib/format"; import { findDecodePdf417 } from "../lib/pdf/barcodeDecoder"; // 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 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 const billAttachment = formData.get('billAttachment') as File; formData.set('billAttachment', billAttachment, encodeURIComponent(billAttachment.name)); return updateOrAddBill(locationId, billId, billYear, billMonth, prevState, formData); } export interface BillEditFormProps { location: BillingLocation, bill?: Bill, } export const BillEditForm:FC = ({ location, bill }) => { const { _id: billID, name, paid, attachment, notes, payedAmount } = bill ?? { _id:undefined, name:"", paid:false, notes:"" }; const { yearMonth:{year: billYear, month: billMonth}, _id: locationID } = location; const initialState = { message: null, errors: {} }; const handleAction = updateOrAddBillMiddleware.bind(null, locationID, billID, billYear, billMonth); const [ state, dispatch ] = useFormState(handleAction, initialState); const [ isPaid, setIsPaid ] = React.useState(paid); const billPaid_handleChange = (event: React.ChangeEvent) => { setIsPaid(event.target.checked); } const billAttachment_handleChange = (event: React.ChangeEvent) => { findDecodePdf417(event).then(result => console.log(result)); } return(

{`${formatYearMonth(location.yearMonth)} ${location.name}`}

{ // don't show the delete button if we are adding a new bill bill ? : null }
{state.errors?.billName && state.errors.billName.map((error: string) => (

{error}

))}
{ // attachment ? {decodeURIComponent(attachment.fileName)} : null }
{state.errors?.billAttachment && state.errors.billAttachment.map((error: string) => (

{error}

))}
{ isPaid && <>
{state.errors?.payedAmount && state.errors.payedAmount.map((error: string) => (

{error}

))}
}
{state.errors?.billNotes && state.errors.billNotes.map((error: string) => (

{error}

))}
Cancel
{state.message &&

{state.message}

}
); }