const fs = require("fs"); function finalizeInvoice(filePath, invoiceId, customerType) { const raw = fs.readFileSync(filePath, "utf8"); const state = JSON.parse(raw); const invoice = state.invoices.find((item) => item.id === invoiceId); if (!invoice) { throw new Error("Invoice not found"); } let subtotal = 0; for (const line of invoice.lines) { subtotal = subtotal + line.quantity * line.unitPrice; } let discount = 0; if (customerType === "vip") { discount = subtotal * 0.15; } if (subtotal > 200) { discount = discount + 10; } const taxed = (subtotal - discount) * 1.1; invoice.status = "finalized"; invoice.total = Math.round(taxed * 100) / 100; invoice.finalizedAt = new Date().toISOString(); fs.writeFileSync(filePath, JSON.stringify(state, null, 2)); console.log("Invoice finalized", invoiceId); return invoice; } module.exports = { finalizeInvoice };