This commit is contained in:
44
src/utils/invoice.ts
Normal file
44
src/utils/invoice.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { db } from "../db";
|
||||
import { invoices, invoiceItems } from "../db/schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
/**
|
||||
* Recalculates the subtotal, tax amount, and total for a specific invoice
|
||||
* based on its items and tax rate.
|
||||
*/
|
||||
export async function recalculateInvoiceTotals(invoiceId: string) {
|
||||
// Fetch invoice to get tax rate
|
||||
const invoice = await db
|
||||
.select()
|
||||
.from(invoices)
|
||||
.where(eq(invoices.id, invoiceId))
|
||||
.get();
|
||||
|
||||
if (!invoice) return;
|
||||
|
||||
// Fetch all items
|
||||
const items = await db
|
||||
.select()
|
||||
.from(invoiceItems)
|
||||
.where(eq(invoiceItems.invoiceId, invoiceId))
|
||||
.all();
|
||||
|
||||
// Calculate totals
|
||||
// Note: amounts are in cents
|
||||
const subtotal = items.reduce((acc, item) => acc + item.amount, 0);
|
||||
|
||||
const taxRate = invoice.taxRate || 0;
|
||||
const taxAmount = Math.round(subtotal * (taxRate / 100));
|
||||
|
||||
const total = subtotal + taxAmount;
|
||||
|
||||
// Update invoice
|
||||
await db
|
||||
.update(invoices)
|
||||
.set({
|
||||
subtotal,
|
||||
taxAmount,
|
||||
total,
|
||||
})
|
||||
.where(eq(invoices.id, invoiceId));
|
||||
}
|
||||
Reference in New Issue
Block a user