import React, { useEffect } from "react"; import Label from "../common/Label"; import { AppFormController, useAppFormContext, } from "../../hooks/appHooks/useAppForm"; import DatePicker from "../common/DatePicker"; import { useInvoiceAttachmentTypes } from "../../hooks/masterHook/useMaster"; import Filelist from "../Expenses/Filelist"; import SelectField from "../common/Forms/SelectField"; import { useWatch } from "react-hook-form"; import WarningBlock from "../InfoBlock/WarningBlock"; import { FILE_UPLOAD_INFO } from "../../utils/staticContent"; const PurchasePaymentDetails = ({ purchaseId = null }) => { const { data, isLoading, error, isError } = useInvoiceAttachmentTypes(); const { data: InvoiceDocTypes, isLoading: invoiceDocLoading } = useInvoiceAttachmentTypes(); const { register, watch, setValue, control, formState: { errors }, } = useAppFormContext(); const baseAmount = watch("baseAmount"); const taxAmount = watch("taxAmount"); const trCharge = watch("transportCharges"); useEffect(() => { const base = parseFloat(baseAmount) || 0; const tax = parseFloat(taxAmount) || 0; const transportCharges = parseFloat(trCharge) || 0; if (base || tax || transportCharges) { setValue("totalAmount", (base + tax + transportCharges).toFixed(2)); } }, [baseAmount, taxAmount, trCharge, setValue]); const invoiceAttachmentType = watch("invoiceAttachmentTypeId"); const files = watch("attachments"); const toBase64 = (file) => new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result.split(",")[1]); reader.onerror = (error) => reject(error); }); const onFileChange = async (e) => { const newFiles = Array.from(e.target.files); if (newFiles.length === 0) return; const existingFiles = watch("attachments") || []; const parsedFiles = await Promise.all( newFiles.map(async (file) => { const base64Data = await toBase64(file); return { fileName: file.name, base64Data, contentType: file.type, fileSize: file.size, description: "", isActive: true, invoiceAttachmentTypeId: invoiceAttachmentType, isNew: true, // <-- temp tempId: crypto.randomUUID(), // temp - id }; }) ); const combinedFiles = [ ...existingFiles, ...parsedFiles.filter( (newFile) => !existingFiles.some( (f) => f.fileName === newFile.fileName && f.fileSize === newFile.fileSize ) ), ]; setValue("attachments", combinedFiles, { shouldDirty: true, shouldValidate: true, }); }; const removeFile = (index) => { const updated = files.flatMap((file, i) => { // NEW FILE → remove completely if (file.isNew && file.tempId === index) { return []; // remove from array } // EXISTING FILE → mark inactive if (!file.isNew && file.documentId === index) { return [{ ...file, isActive: false }]; } return [file]; }); setValue("attachments", updated, { shouldDirty: true, shouldValidate: true, }); }; const hasNumber = !!watch("proformaInvoiceNumber"); return (