Merge pull request #680 from Luca-Timo/fix/invoice-pdf-multipage

Fix/invoice pdf multipage
This commit is contained in:
Paul Nothaft
2026-06-28 22:17:07 +02:00
committed by GitHub
12 changed files with 337 additions and 41 deletions
+37 -1
View File
@@ -23,6 +23,7 @@ const crypto = require('crypto');
const { db, withRetry, logActivity } = require('../database/db');
const logger = require('../utils/logger');
const { getAppSetting } = require('../utils/appSettings');
const { cleanNetMinor } = require('../utils/invoiceRounding');
const { AppError } = require('../utils/errors');
const { formatBoolean } = require('../utils/dbCompat');
const { claimNextSequence } = require('../utils/documentSequences');
@@ -786,6 +787,15 @@ async function createInvoice(payload, adminId, trx = db) {
for (const li of items) {
if (li.parent_position == null) netMinor += ensureInt(li.line_total_minor);
}
// Optional sub-cent reconciliation (crm_invoice_round_total). When on,
// store the full-precision net rounded ONCE so the total matches
// qty × unit arithmetic; the per-line rounding drift is surfaced as a
// "Rundung" row at render time (storedNet Σ line totals). Off by
// default ⇒ net stays the sum of rounded lines, unchanged behaviour.
const roundTotal = (await getAppSetting('crm_invoice_round_total', false)) === true;
if (roundTotal) {
netMinor = cleanNetMinor(items, { parentKey: 'parent_position', positionKey: 'position' });
}
const vatRate = ensureNumber(payload.vatRate, 0);
const vatMinor = Math.round(netMinor * vatRate / 100);
const shippingMinor = ensureInt(payload.shippingAmountMinor);
@@ -1764,6 +1774,25 @@ async function buildInvoiceRenderContext(invoice, lineItems) {
else if (typeof raw === 'string' && raw.trim()) dateFormat = { format: raw.trim() };
} catch (_) { /* fall back to default */ }
// Sub-cent reconciliation (crm_invoice_round_total). "Betrag Netto"
// shows the sum of the visible line totals so it foots with the items;
// the stored net may be the clean (rounded-once) value, and the gap is
// shown as a "Rundung" row. Legacy/unrounded invoices have equal
// values ⇒ adjustment 0, no row. Suppressed on Storno/Mahnung: those
// negate the stored net and flip line-total signs at render, so the
// forward "storedNet Σ lines" derivation doesn't apply.
const isReversalDoc = invoice.kind === 'storno' || invoice.kind === 'mahnung';
const displayedNetMinor = isReversalDoc
? ensureInt(invoice.net_amount_minor)
: lineItems.reduce(
(s, li) => (li.parent_line_item_id == null && (li.parent_position == null || li.parent_position === '')
? s + ensureInt(li.line_total_minor) : s),
0,
);
const roundingAdjustmentMinor = isReversalDoc
? 0
: ensureInt(invoice.net_amount_minor) - displayedNetMinor;
return {
locale: invoice.language || profile?.default_locale || 'de',
currency: invoice.currency,
@@ -1791,7 +1820,8 @@ async function buildInvoiceRenderContext(invoice, lineItems) {
detailsText: li.details_text || null,
})),
totals: {
netAmountMinor: invoice.net_amount_minor,
netAmountMinor: displayedNetMinor,
roundingAdjustmentMinor,
vatRate: invoice.vat_rate,
// Migration 130 — VAT-code snapshot (so re-editing preserves it).
vatCode: invoice.vat_code ?? null,
@@ -1908,6 +1938,12 @@ async function renderInvoicePdfFromPayload(payload) {
netMinor += ensureInt(it.line_total_minor);
}
}
// Match the saved-invoice math: clean-net reconciliation when the
// crm_invoice_round_total setting is on (see createInvoice).
const roundTotal = (await getAppSetting('crm_invoice_round_total', false)) === true;
if (roundTotal) {
netMinor = cleanNetMinor(items, { parentKey: 'parent_position', positionKey: 'position' });
}
const vatRate = ensureNumber(payload.vatRate, 0);
const vatMinor = Math.round(netMinor * vatRate / 100);
const shippingMinor = ensureInt(payload.shippingAmountMinor);
+6
View File
@@ -45,6 +45,7 @@ const LABELS = {
totals_shipping: 'Shipping',
totals_vat: 'VAT',
totals_late_fee: 'Late fee',
totals_rounding: 'Rounding',
totals_grand: 'Total',
payment_conditions: 'Payment conditions',
iban_intro: 'Please transfer the amount to the following bank account:',
@@ -175,6 +176,7 @@ const LABELS = {
totals_shipping: 'Versand',
totals_vat: 'ges. MwSt.',
totals_late_fee: 'Mahngebühr',
totals_rounding: 'Rundung',
totals_grand: 'Gesamtbetrag',
payment_conditions: 'Zahlungsbedingungen',
iban_intro: 'Der Betrag ist auf die folgende Bankverbindung zu überweisen:',
@@ -295,6 +297,7 @@ const LABELS = {
totals_shipping: 'Frais d\'expédition',
totals_vat: 'TVA',
totals_late_fee: 'Frais de retard',
totals_rounding: 'Arrondi',
totals_grand: 'Total',
payment_conditions: 'Conditions de paiement',
iban_intro: 'Veuillez virer le montant sur le compte suivant :',
@@ -384,6 +387,7 @@ const LABELS = {
totals_shipping: 'Verzending',
totals_vat: 'BTW',
totals_late_fee: 'Aanmaningskosten',
totals_rounding: 'Afronding',
totals_grand: 'Totaal',
payment_conditions: 'Betalingsvoorwaarden',
iban_intro: 'Gelieve het bedrag over te maken op de volgende bankrekening:',
@@ -473,6 +477,7 @@ const LABELS = {
totals_shipping: 'Envio',
totals_vat: 'IVA',
totals_late_fee: 'Taxa de atraso',
totals_rounding: 'Arredondamento',
totals_grand: 'Total',
payment_conditions: 'Condições de pagamento',
iban_intro: 'Por favor transfira o valor para a seguinte conta bancária:',
@@ -562,6 +567,7 @@ const LABELS = {
totals_shipping: 'Доставка',
totals_vat: 'НДС',
totals_late_fee: 'Пеня за просрочку',
totals_rounding: 'Округление',
totals_grand: 'Итого',
payment_conditions: 'Условия оплаты',
iban_intro: 'Просим перевести сумму на следующий банковский счёт:',
+39 -24
View File
@@ -861,6 +861,18 @@ function drawTotals(doc, ctx, x, y, width) {
doc.font(doc._fonts ? doc._fonts.body : FONT_BODY).text(formatMinor(lateFeeMinor, currency, intlLocale), valueX, y, { width: valueCol, align: 'right' });
y = doc.y + 4;
}
// Rundung — sub-cent reconciliation row (crm_invoice_round_total). Only
// rendered when the stored (clean) net differs from the sum of the
// visible line totals; bridges "Betrag Netto" (= Σ lines, foots with
// the items) down/up to the clean Gesamtbetrag below. Zero ⇒ omitted,
// so unrounded documents are byte-identical to before.
const roundingMinor = Number(totals.roundingAdjustmentMinor || 0);
if (roundingMinor !== 0) {
doc.font(doc._fonts ? doc._fonts.bold : FONT_BOLD).text(t(locale, 'totals_rounding'), labelX, y, { width: labelCol });
doc.font(doc._fonts ? doc._fonts.body : FONT_BODY).text(formatMinor(roundingMinor, currency, intlLocale), valueX, y, { width: valueCol, align: 'right' });
y = doc.y + 4;
}
y += 6;
// Divider line above grand total — spans the right half of the
@@ -916,7 +928,14 @@ function drawPaymentBlock(doc, ctx, x, y, width) {
const showSkontoHere = isQuote
? (issuer?.quoteShowSkonto !== false)
: reminderLevel === 0;
const showIbanHere = !isQuote;
// Invoices show the IBAN block in the right column EXCEPT when a
// Swiss QR-bill slip is appended: that slip already prints the
// account/IBAN ("Konto / Zahlbar an") in human-readable form, so
// repeating "Der Betrag ist auf die folgende Bankverbindung zu
// überweisen: …" under the totals is pure duplication. The EPC QR
// path keeps the block — its QR lives on a trailing page, so having
// the bank details on the invoice page itself still helps.
const showIbanHere = !isQuote && ctx.qrFormat !== 'swiss';
// If the quote has nothing to print in either column, bail out
// early — don't render a bare "Payment conditions:" header with
@@ -1610,29 +1629,25 @@ function renderDocument(type, context) {
doc.y = y;
doc.x = leftX;
// Force the items table to auto-paginate BEFORE it can collide
// with the totals + payment block at the page bottom. We
// compute the same anchor as below, then temporarily inflate
// the page's bottom margin so swissqrbill's Table sees a
// shorter usable area and breaks to a new page when items
// would otherwise spill into the totals zone. The header row
// is already marked `header: true` so it auto-repeats on the
// continuation page.
const _origBottomMargin = doc.page.margins.bottom;
const _itemsBottomReserve = PAGE.marginBottom
+ 30 // FOOTER_RESERVE
+ (ctx.paymentTerm ? 80 : 50) // PAYMENT_BLOCK_HEIGHT
+ 12 // gap between totals + payment
+ 90 // TOTALS_BLOCK_HEIGHT
+ 20; // small breathing room
doc.page.margins.bottom = _itemsBottomReserve;
try {
drawLineItems(doc, ctx);
} finally {
// Restore even if drawLineItems threw — keeps subsequent
// pages on the document's normal margin geometry.
doc.page.margins.bottom = _origBottomMargin;
}
// Let the items table paginate with the document's NORMAL
// margins so each page fills to the bottom. The header row is
// marked `header: true` so it auto-repeats on every
// continuation page. Totals/payment placement is handled below:
// they're pinned to a fixed anchor near the page bottom, and if
// the last item row spilled past that anchor we advance to a
// fresh page before drawing them (see the desiredTotalsY check).
//
// We deliberately do NOT inflate the bottom margin here to
// "reserve" the totals zone on every page. That older approach
// shortened the usable area on EVERY page (not just the last),
// so a long invoice broke far too early — only a handful of
// line items rendered on page 1 with a large blank gap beneath.
// Worse, the inflated margin was set on the page active when the
// table started but restored on whichever page the table ended,
// leaving page 1 permanently short: the page-number stamp later
// landed below that page's phantom bottom margin and spawned a
// stray blank trailing page (which then desynced "Seite X von Y").
drawLineItems(doc, ctx);
// y after the table — used only to detect whether the items
// overflowed past the totals anchor below. We don't use it as
// the totals position directly because the totals block is
+40 -5
View File
@@ -30,6 +30,7 @@ const crypto = require('crypto');
const { db, withRetry, logActivity } = require('../database/db');
const logger = require('../utils/logger');
const { getAppSetting } = require('../utils/appSettings');
const { cleanNetMinor } = require('../utils/invoiceRounding');
const { AppError } = require('../utils/errors');
const { formatBoolean } = require('../utils/dbCompat');
const { claimNextSequence } = require('../utils/documentSequences');
@@ -88,7 +89,7 @@ const { ensureInt, ensureNumber } = require('../utils/numericHelpers');
* array; we treat anything truthy on `parent_position` (number or
* string that parses to int) as "I'm a sub-item".
*/
function computeTotals(lineItems, vatRate, shippingAmountMinor = 0) {
function computeTotals(lineItems, vatRate, shippingAmountMinor = 0, options = {}) {
// Phase 1: compute raw line_total_minor for every row from its own
// qty × unit × discount. Sub-item lines are computed here too so
// the renderer can display their individual amounts.
@@ -135,6 +136,20 @@ function computeTotals(lineItems, vatRate, shippingAmountMinor = 0) {
if (li.parent_position == null) netMinor += ensureInt(li.line_total_minor);
}
// Optional sub-cent reconciliation (crm_invoice_round_total). When on,
// the stored net becomes the full-precision sum rounded ONCE so the
// total matches qty × unit arithmetic; the few-Rappen drift from the
// per-line rounding is surfaced as a "Rundung" row at render time
// (derived as storedNet Σ line totals). Off by default ⇒ net stays
// the sum of rounded lines and roundingAdjustmentMinor is 0.
const roundedNet = netMinor;
let roundingAdjustmentMinor = 0;
if (options.roundTotal) {
const clean = cleanNetMinor(computed, { parentKey: 'parent_position', positionKey: 'position' });
roundingAdjustmentMinor = clean - roundedNet;
netMinor = clean;
}
const vatPercent = ensureNumber(vatRate, 0);
const vatMinor = Math.round(netMinor * vatPercent / 100);
const shipping = ensureInt(shippingAmountMinor);
@@ -144,6 +159,7 @@ function computeTotals(lineItems, vatRate, shippingAmountMinor = 0) {
vatAmountMinor: vatMinor,
shippingAmountMinor: shipping,
totalAmountMinor: totalMinor,
roundingAdjustmentMinor,
lineItems: computed,
};
}
@@ -504,10 +520,12 @@ async function createQuote(payload, adminId) {
.toISOString().slice(0, 10);
// Authoritative totals.
const roundTotal = (await getAppSetting('crm_invoice_round_total', false)) === true;
const totals = computeTotals(
Array.isArray(payload.lineItems) ? payload.lineItems : [],
payload.vatRate,
payload.shippingAmountMinor
payload.shippingAmountMinor,
{ roundTotal }
);
// Negative line items (Rabatt) are allowed, but the resulting
@@ -665,10 +683,12 @@ async function updateQuote(id, payload, adminId) {
);
}
const roundTotal = (await getAppSetting('crm_invoice_round_total', false)) === true;
const totals = computeTotals(
Array.isArray(payload.lineItems) ? payload.lineItems : [],
payload.vatRate ?? existing.vat_rate,
payload.shippingAmountMinor ?? existing.shipping_amount_minor
payload.shippingAmountMinor ?? existing.shipping_amount_minor,
{ roundTotal }
);
// Negative line items (Rabatt) are allowed, but the resulting
@@ -835,6 +855,18 @@ async function buildRenderContext(quote, lineItems) {
else if (typeof raw === 'string' && raw.trim()) dateFormat = { format: raw.trim() };
} catch (_) { /* fall back to default */ }
// Sub-cent reconciliation (crm_invoice_round_total). The displayed
// "Betrag Netto" is always the sum of the visible line totals so it
// foots with the items; the stored net may be the clean (rounded-once)
// value, in which case the gap is shown as a "Rundung" row. For
// legacy/unrounded quotes the two are equal ⇒ adjustment 0, no row.
const displayedNetMinor = lineItems.reduce(
(s, li) => (li.parent_line_item_id == null && (li.parent_position == null || li.parent_position === '')
? s + ensureInt(li.line_total_minor) : s),
0,
);
const roundingAdjustmentMinor = ensureInt(quote.net_amount_minor) - displayedNetMinor;
return {
locale: quote.language || profile?.default_locale || 'de',
currency: quote.currency,
@@ -876,7 +908,8 @@ async function buildRenderContext(quote, lineItems) {
detailsText: li.details_text || null,
})),
totals: {
netAmountMinor: quote.net_amount_minor,
netAmountMinor: displayedNetMinor,
roundingAdjustmentMinor,
vatRate: quote.vat_rate,
vatAmountMinor: quote.vat_amount_minor,
shippingAmountMinor: quote.shipping_amount_minor,
@@ -907,10 +940,12 @@ async function renderQuotePdfBuffer(quoteId) {
*/
async function renderQuotePdfFromPayload(payload) {
const customer = await db('customer_accounts').where({ id: payload.customerAccountId }).first();
const roundTotal = (await getAppSetting('crm_invoice_round_total', false)) === true;
const totals = computeTotals(
Array.isArray(payload.lineItems) ? payload.lineItems : [],
payload.vatRate,
payload.shippingAmountMinor
payload.shippingAmountMinor,
{ roundTotal }
);
const fakeQuote = {
quote_number: 'PREVIEW',
+95
View File
@@ -0,0 +1,95 @@
'use strict';
/**
* Sub-cent rounding reconciliation for CRM documents (quotes + invoices).
*
* Each line's total is rounded to the whole minor unit (Rappen/cent)
* BEFORE the net is summed so for quantities with fractional tails
* (e.g. 2.5 h × 32.25 = 80.625 80.63) the sum of the rounded lines can
* drift a few minor units away from the "pure" product. Worked example
* from a real invoice: 68 h × 32.25 = 2193.00, but the 21 individually
* rounded line totals sum to 2193.02.
*
* This is the standard "sum of rounded lines" convention (Stripe,
* QuickBooks, Xero all do the same) and it foots the printed line
* amounts genuinely add up to the shown total. But some issuers prefer
* the total to match the customer's mental arithmetic (hours × rate).
*
* When the `crm_invoice_round_total` setting is on, the create paths
* replace the stored net with `cleanNetMinor(...)` the full-precision
* sum rounded ONCE and the drift is surfaced to the reader as an
* explicit "Rundung" row, derived at render time as
* `storedNet Σ(line totals)` (see the render-context builders). When
* the setting is off, stored net === Σ(line totals) and the adjustment
* is zero, so the behaviour is unchanged.
*/
function ensureNumber(v, d = 0) {
const n = Number(v);
return Number.isFinite(n) ? n : d;
}
function ensureInt(v, d = 0) {
const n = Math.round(Number(v));
return Number.isFinite(n) ? n : d;
}
/**
* Full-precision contribution of one line in minor units (NOT rounded):
* quantity × unit_price_minor × (1 discount%/100)
*/
function exactLineMinor(li) {
const qty = ensureNumber(li.quantity, 1);
const unit = ensureInt(li.unit_price_minor);
const disc = Math.max(0, Math.min(100, ensureNumber(li.discount_percent, 0)));
return qty * unit * (1 - disc / 100);
}
function isTopLevel(li, parentKey) {
const p = li[parentKey];
return p == null || p === '';
}
/**
* Clean net = round(Σ full-precision contributions of the rows that roll
* into net). Mirrors the rounded-net summation exactly top-level rows
* only, with a parent whose priced sub-items override it contributing
* its children instead of itself (migration 119 hierarchy) but sums at
* full precision and rounds ONCE at the very end.
*
* `items` must carry quantity / unit_price_minor / discount_percent and,
* for the hierarchy resolution, `line_total_minor` (the already-rounded
* per-line value, used only to decide whether a parent is overridden by
* priced children same test as computeTotals / resolveParentTotals).
*
* @param {Array} items
* @param {{parentKey?: string, positionKey?: string}} opts
* @returns {number} clean net in minor units
*/
function cleanNetMinor(items, { parentKey = 'parent_position', positionKey = 'position' } = {}) {
const childrenByParent = new Map();
for (const li of items) {
if (isTopLevel(li, parentKey)) continue;
const key = ensureInt(li[parentKey]);
if (!childrenByParent.has(key)) childrenByParent.set(key, []);
childrenByParent.get(key).push(li);
}
let exact = 0;
for (const li of items) {
if (!isTopLevel(li, parentKey)) continue; // sub-items roll into their parent
const kids = childrenByParent.get(ensureInt(li[positionKey])) || [];
const pricedKids = kids.filter((c) => ensureInt(c.unit_price_minor) > 0);
const pricedKidsRounded = pricedKids.reduce((s, c) => s + ensureInt(c.line_total_minor), 0);
// Same override test as computeTotals phase 2: a parent with at least
// one priced sub-item derives its total from those children.
if (pricedKidsRounded > 0) {
for (const c of pricedKids) exact += exactLineMinor(c);
} else {
exact += exactLineMinor(li);
}
}
return Math.round(exact);
}
module.exports = { cleanNetMinor, exactLineMinor };