Fix batch payment totals in Telegram and ERPNext invoice flow

This commit is contained in:
justin 2026-06-10 07:04:06 -05:00
parent 6827aafdbc
commit 7708086130

View file

@ -1676,6 +1676,21 @@ export async function handlePaymentComplete(
const paymentMethod = (order.payment_method as string) || "card";
console.log(`[checkout] Payment confirmed: ${order_type} ${order_id} via ${paymentMethod}`);
// Prefer the payment gateway's recorded total when available. This keeps
// downstream notifications honest even if older rows still carry stale
// per-line surcharge values from before the batch-surcharge split fix.
let actualPaidCents: number | null = null;
if (stripe && session_id && !session_id.startsWith("crypto-")) {
try {
const session = await stripe.checkout.sessions.retrieve(session_id);
if (typeof session.amount_total === "number") {
actualPaidCents = session.amount_total;
}
} catch (stripeErr) {
console.warn(`[checkout] Could not retrieve Stripe session ${session_id} for notification totals:`, stripeErr);
}
}
// ── Telegram order notification ──────────────────────────────────────
try {
const botToken = process.env.TELEGRAM_BOT_TOKEN;
@ -1696,7 +1711,11 @@ export async function handlePaymentComplete(
surchargeCents += Number(r.surcharge_cents || 0);
serviceNames.push((r.service_name as string) || (r.service_slug as string) || "");
}
const totalCents = subtotalCents - discountCents + surchargeCents;
const totalCents = actualPaidCents ?? (subtotalCents - discountCents + surchargeCents);
const derivedSurchargeCents = totalCents - subtotalCents + discountCents;
if (derivedSurchargeCents >= 0) {
surchargeCents = derivedSurchargeCents;
}
const totalDollars = (totalCents / 100).toFixed(2);
const serviceLine = serviceNames.length <= 1
@ -1970,10 +1989,13 @@ export async function handlePaymentComplete(
// Create Sales Invoice
try {
// Calculate batch total (sum of all line items minus discounts)
const batchTotalCents = (batchRows.rows as any[]).reduce((sum, bo) => {
// Calculate the actual paid amount for the batch: service + gov fees
// - discounts + surcharge. Older versions passed only the pre-
// surcharge total, which understated the Payment Entry amount.
const batchBaseCents = (batchRows.rows as any[]).reduce((sum, bo) => {
return sum + (bo.service_fee_cents || 0) + (bo.gov_fee_cents || 0) - (bo.discount_cents || 0);
}, 0);
const batchTotalCents = batchBaseCents + ((Number(order.surcharge_cents) || 0));
const invName = await createInvoiceFromSalesOrder({
salesOrderName: soName,
paymentGateway: paymentMethod,