This commit is contained in:
David Arranz 2025-11-09 12:27:05 +01:00
parent 07e71e70a5
commit ff036a7d81

View File

@ -11,6 +11,7 @@ import { InvoiceFormData, InvoiceItemFormData } from "../../schemas";
export type UseInvoiceAutoRecalcParams = {
currency_code: string;
taxCatalog: TaxCatalogProvider;
debug?: boolean;
};
/**
@ -21,7 +22,7 @@ export type UseInvoiceAutoRecalcParams = {
*/
export function useInvoiceAutoRecalc(
form: UseFormReturn<InvoiceFormData>,
{ currency_code, taxCatalog }: UseInvoiceAutoRecalcParams
{ currency_code, taxCatalog, debug = false }: UseInvoiceAutoRecalcParams
) {
const { setValue, trigger, control } = form;
@ -99,12 +100,14 @@ export function useInvoiceAutoRecalc(
shouldUpdateHeader = true;
itemCache.current.set(idx, next);
setInvoiceItemTotals(form, idx, next);
if (debug) console.log(`💡 Recalc line ${idx + 1}`, next);
}
});
if (shouldUpdateHeader) {
const totals = calculateInvoiceTotals(deferredItems, deferredDiscount);
setInvoiceTotals(form, totals);
if (debug) console.log("📊 Recalc invoice totals", totals);
void trigger([
"subtotal_amount",
@ -119,7 +122,15 @@ export function useInvoiceAutoRecalc(
return () => {
if (debounceTimer.current) clearTimeout(debounceTimer.current);
};
}, [deferredItems, deferredDiscount, calculateItemTotals, calculateInvoiceTotals, form, trigger]);
}, [
deferredItems,
deferredDiscount,
calculateItemTotals,
calculateInvoiceTotals,
form,
trigger,
debug,
]);
}
// Ayudante para rellenar los importes de una línea