dc5079a912
* fix(providers): stop inventing 25% VAT on migrated invoices An invoice migrated from Fortnox displayed "Momsbehandling: 25 % moms" next to "Moms: 0 kr", with no line items behind it. It was not a display bug: the record really did hold vat_rate 25 and vat_amount 0. Fortnox answers GET /3/invoices with the short form, which carries no Net, no TotalVAT and no InvoiceRows; those live only on the detail form. The migration mapped the list payload alone, so `Net ?? total` made the net equal the gross, VAT derived as gross minus net came out 0, and with no rows to read a rate from, inferVatTreatment/inferVatRate fell through to their `return 'standard_25'` / `return 25` defaults. The result balanced, so nothing downstream noticed. Measured on prod: 8 712 sales invoices across 43 companies assert a rate beside 0 kr of VAT (286 MSEK of subtotal), plus 1 240 supplier invoices. None are booked, but 263 are still open, and the no-items booking fallback in invoice-entries.ts credits the full gross to 30xx and emits no 2611 line at all. Not Fortnox-only. Visma reported its VAT-inclusive TotalAmount as the ex-VAT amount and read rows via `LineTotal`/`VatRatePercent`, neither of which exists in the eAccounting schema (the real names are AmountNoVat and PercentVat), so its lines all landed at 0. Bjorn Lunden reported the gross as the net with no lines at all. Briox and WINT had the same gross-as-net fallback, and Bokio defaulted a missing totalTax to 0. - lib/providers/amounts.ts: readers that return undefined for an absent field, so "the provider says zero" stays distinct from "did not say" - every mapper: populate taxTotal and per-line taxAmount from what the payload actually states; leave the net undefined when it does not - provider-data-fetcher: hydrate the detail endpoint that every config has always declared and nothing ever called, open invoices first, within a time budget, reporting whatever it could not reach - entity-mapper: derive rate and treatment from evidence; when there is none, write vat_rate null and flag vatUnresolved instead of asserting a standard rate Existing rows are untouched; repairing them needs a separate decision. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(providers): keep subtotal + VAT equal to the invoice total Providers state net, VAT and gross independently and they need not agree: Fortnox's Total is the amount to pay after öresavrundning while Net + TotalVAT is the unrounded Gross, so the two differ by up to 50 öre. Passing both through as stated put that gap into the invoice row, where subtotal + vat_amount no longer equalled total. The header booking path in invoice-entries.ts derives the 1510 debit from the sum of its credits, so the receivable would land a few öre away from what the customer owes while the verifikat still balanced: the same silent shape as the bug this branch fixes. resolveVatTriple now always returns a pair summing to the gross, keeping the VAT intact (it reaches the momsdeklaration) and absorbing the rounding into the net. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(providers): address invoice detail by the configured idField Hydration built the detail path from dto.id. Björn Lundén's sales config names invoiceNumber as its idField while its mapper builds dto.id from entityId, so BL sales invoices would have been hydrated from the wrong resource, or from none. Every other provider/resource pair happens to agree on the two, which is what made the mismatch easy to miss. The config's idField is the authority, read off the raw payload, with dto.id only as the fallback. The regression test uses BL with entityId 99001 and invoiceNumber 5 so the two cannot coincide. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(providers): store vat_rate null for migrated mixed-rate invoices resolveInvoiceVat labelled the header with the first line's rate, so an invoice carrying both 25 % and 6 % lines was recorded as a 25 % invoice. buildInvoiceWriteData already stores isMixedRate ? null : theRate for natively created invoices; migrated ones now match. The money was already right and stays right: generatePerRateLines groups per item rate, so a mixed invoice books 25 % and 6 % separately off the per-line vat_rate/vat_amount this branch fixed. Only the header label was overstating what the source said. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(providers): bound hydration against auth failures and the clock Two failure modes that only appear against a real provider. A 401 or 403 fails identically for every remaining invoice, so the pass now stops on the first one instead of issuing hundreds more doomed calls. That matters more than it looks: TokenBucketRateLimiter keys on the literal string 'global', so Fortnox's 4 req/s is a platform-wide budget shared by every company and every concurrent migration, not a per-token one. A 404 is about one invoice and does not stop the pass. The budget was checked before starting a call but never during one. The clients retry 429s and 5xx with backoff (Fortnox: 6 attempts, up to 60 s apart), so a call starting one millisecond inside the budget could still be retrying minutes later, and three concurrent ones could hold the migration past its 300 s function ceiling. Each call is now raced against the deadline; the socket is not cancelled, but control returns and the remaining invoices are reported unhydrated instead of the run dying. Both outcomes are reported as HydrationReport.abortedBy so a partial pass is visible rather than looking complete. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Jakob Wennberg <invoice@arcim.io> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
125 lines
4.1 KiB
TypeScript
125 lines
4.1 KiB
TypeScript
import { describe, expect, it } from 'vitest';
|
|
import {
|
|
readNumber,
|
|
resolveVatTriple,
|
|
sumLineVat,
|
|
lineVatFromPercent,
|
|
multiplyIfBothPresent,
|
|
} from '../amounts';
|
|
|
|
describe('readNumber', () => {
|
|
it('returns the first present candidate, in order', () => {
|
|
expect(readNumber({ b: 2, a: 1 }, ['a', 'b'])).toBe(1);
|
|
expect(readNumber({ b: 2 }, ['a', 'b'])).toBe(2);
|
|
});
|
|
|
|
it('distinguishes an absent field from a zero one', () => {
|
|
expect(readNumber({ Net: 0 }, ['Net'])).toBe(0);
|
|
expect(readNumber({}, ['Net'])).toBeUndefined();
|
|
});
|
|
|
|
it('coerces string-serialised decimals', () => {
|
|
expect(readNumber({ net_amount: '1476.00' }, ['net_amount'])).toBe(1476);
|
|
});
|
|
|
|
it('skips nulls, empty strings and non-numerics rather than reading them as 0', () => {
|
|
expect(readNumber({ a: null, b: '', c: 'n/a', d: 5 }, ['a', 'b', 'c', 'd'])).toBe(5);
|
|
expect(readNumber({ a: null }, ['a'])).toBeUndefined();
|
|
});
|
|
|
|
it('tolerates a missing payload', () => {
|
|
expect(readNumber(undefined, ['a'])).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe('resolveVatTriple', () => {
|
|
it('completes VAT from a stated net', () => {
|
|
expect(resolveVatTriple({ gross: 1845000, net: 1476000 }))
|
|
.toEqual({ net: 1476000, vat: 369000 });
|
|
});
|
|
|
|
it('completes the net from a stated VAT', () => {
|
|
expect(resolveVatTriple({ gross: 1845000, vat: 369000 }))
|
|
.toEqual({ net: 1476000, vat: 369000 });
|
|
});
|
|
|
|
it('passes both through when both are stated and they agree', () => {
|
|
expect(resolveVatTriple({ gross: 100, net: 80, vat: 20 }))
|
|
.toEqual({ net: 80, vat: 20 });
|
|
});
|
|
|
|
it('keeps net + vat === gross when the provider states three that disagree', () => {
|
|
// Fortnox `Total` is post-öresavrundning while Net + TotalVAT is the
|
|
// unrounded Gross. Passing both through as stated would leave
|
|
// subtotal + vat_amount != total on the invoice row, and the header
|
|
// booking path derives the 1510 debit from the sum of its credits: the
|
|
// receivable would sit a few öre off what the customer owes, with the
|
|
// verifikat still balancing so nothing flags it.
|
|
const resolved = resolveVatTriple({ gross: 1250, net: 1000.4, vat: 250 });
|
|
|
|
expect(resolved.vat).toBe(250);
|
|
expect(resolved.net).toBe(1000);
|
|
expect((resolved.net ?? 0) + (resolved.vat ?? 0)).toBe(1250);
|
|
});
|
|
|
|
it('resolves NOTHING from a gross alone', () => {
|
|
// The regression this whole module exists for: with only the payable
|
|
// amount known, net = gross and VAT = 0 is an invention, not a default.
|
|
expect(resolveVatTriple({ gross: 1845000 })).toEqual({});
|
|
});
|
|
|
|
it('treats a genuine zero VAT as an answer, not as absence', () => {
|
|
expect(resolveVatTriple({ gross: 1000, vat: 0 })).toEqual({ net: 1000, vat: 0 });
|
|
});
|
|
});
|
|
|
|
describe('sumLineVat', () => {
|
|
it('sums when every line carries an amount', () => {
|
|
expect(sumLineVat([
|
|
{ taxAmount: { value: 250 } },
|
|
{ taxAmount: { value: 60 } },
|
|
])).toBe(310);
|
|
});
|
|
|
|
it('refuses a partial sum when any line is missing its VAT', () => {
|
|
expect(sumLineVat([
|
|
{ taxAmount: { value: 250 } },
|
|
{},
|
|
])).toBeUndefined();
|
|
});
|
|
|
|
it('returns undefined for no lines', () => {
|
|
expect(sumLineVat([])).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe('lineVatFromPercent', () => {
|
|
it('accepts both unit conventions', () => {
|
|
expect(lineVatFromPercent(1000, 25)).toBe(250);
|
|
expect(lineVatFromPercent(1000, 0.25)).toBe(250);
|
|
});
|
|
|
|
it('computes 0 for a stated 0 % rate', () => {
|
|
expect(lineVatFromPercent(1000, 0)).toBe(0);
|
|
});
|
|
|
|
it('returns undefined for an unstated rate rather than assuming one', () => {
|
|
expect(lineVatFromPercent(1000, undefined)).toBeUndefined();
|
|
});
|
|
|
|
it('rounds to öre without toFixed drift', () => {
|
|
expect(lineVatFromPercent(333.33, 25)).toBe(83.33);
|
|
});
|
|
});
|
|
|
|
describe('multiplyIfBothPresent', () => {
|
|
it('multiplies when both factors are known', () => {
|
|
expect(multiplyIfBothPresent(100, 3)).toBe(300);
|
|
});
|
|
|
|
it('returns undefined when either factor is missing', () => {
|
|
expect(multiplyIfBothPresent(100, undefined)).toBeUndefined();
|
|
expect(multiplyIfBothPresent(undefined, 3)).toBeUndefined();
|
|
});
|
|
});
|