Bug/customer invoice bug (#628)

* fix(supplier-invoices): self-assess reverse-charge VAT + link payments to vouchers

Reverse-charge supplier invoices now carry a per-item reverse_charge_rate (0.06/0.12/0.25). Under omvänd skattskyldighet the supplier charges 0% VAT, so the line vat_rate stays 0 and the buyer self-assesses fiktiv moms at the statutory rate. Centralizes rate resolution (resolveReverseChargeRate) and the ruta 20-24 basis-account guard (isReverseChargeBasisAccount) in vat-entries so the booking engine and review-dialog preview can no longer drift.

Adds the link_supplier_invoice_voucher pending operation: mark a leverantorsfaktura paid by linking an existing posted verifikat that debits 2440, with no new journal entry. Exposes find-candidates/link MCP tools and the bulk-reconcile helper, scoped under suppliers:read/write.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(vat): report yearly VAT over the rakenskapsar, not the calendar year

Annual VAT (helarsmoms) is filed per beskattningsar/rakenskapsar (SFL 26 kap), which can be extended or shortened up to 18 months. The previous Jan-Dec calendar span silently dropped part of an extended first year. calculateVatDeclaration now accepts a fiscalPeriodId and resolves the period's actual bounds for yearly; monthly/quarterly stay calendar. The reports UI passes the selected fiscal period, defaults the periodicity from the company's moms_period setting, and carries the period into the ruta drill-down. full-archive export threads the period id through too.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(migration): resolve supplier invoice status from payment amounts

The provider's lifecycle status and its payment status are computed independently upstream and can contradict each other (e.g. a Fortnox invoice marked booked but fully paid). Both the arcim entity-mapper and the Fortnox mapper now let payment state win: fully paid -> paid, partial -> partially_paid, otherwise the mapped lifecycle status, with credit notes forced terminal. Balance is compared numerically (never strict === 0) so float drift or a residual ore resolves cleanly, and an absent Balance is treated as unpaid.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(enable-banking): only ingest booked transactions to stop re-import drift

Pending entries are skipped during sync: a pending row is unstable across syncs (a later 'synka nu' returns it still pending or finally booked, often with a different effective date). Because both the dedup external_id and the content-dedup key are date-derived, that drift minted a new id and re-imported a transaction that already existed - observed in production as the same amount+description landing twice with different dates. Gating the import set on a stable booking_date removes the drift at the source and leaves booked rows' ids byte-identical.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(gitignore): ignore local SIE test fixtures

tests/fixtures/sie/ may contain real or scrubbed company data and must never be committed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(invoice): handle errors during registration journal entry creation and ensure invoice rollback
feat(tests): add test for reverse charge rate handling on supplier invoice line items
feat(fortnox): ensure paid status reflects zero balance for fully paid invoices
chore(migrations): add reverse_charge_rate to supplier_invoice_items and backfill link_supplier_invoice_voucher

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-06-02 13:25:48 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent 358c25094d
commit f6ee0c2a82
43 changed files with 2226 additions and 182 deletions
@@ -0,0 +1,112 @@
import { describe, it, expect } from 'vitest'
import { mapFortnoxToSupplierInvoice, mapFortnoxToSalesInvoice } from '../mapper'
/**
* Guards the paid-status hardening: deriveInvoiceStatus and paymentStatus.paid
* share one isFullyPaid() source of truth, so status === 'paid' iff
* paymentStatus.paid (for non-cancelled / non-credit rows). An ABSENT Balance
* must never be read as paid — on either the supplier OR the sales path.
*/
function supplierRaw(over: Record<string, unknown>): Record<string, unknown> {
return {
GivenNumber: '100',
Total: 1000,
InvoiceDate: '2026-01-10',
DueDate: '2026-02-10',
SupplierName: 'Leverantör AB',
Booked: true,
...over,
}
}
function salesRaw(over: Record<string, unknown>): Record<string, unknown> {
return {
DocumentNumber: '200',
Total: 1000,
InvoiceDate: '2026-01-10',
DueDate: '2026-02-10',
CustomerName: 'Kund AB',
Sent: true,
...over,
}
}
describe('Fortnox mapper — paid-status consistency', () => {
it('supplier: absent Balance is NOT paid (defaults to unpaid, not 0)', () => {
const dto = mapFortnoxToSupplierInvoice(supplierRaw({})) // no Balance key
expect(dto.status).toBe('booked')
expect(dto.paymentStatus.paid).toBe(false)
expect(dto.paymentStatus.balance.value).toBe(1000)
})
it('supplier: Balance 0 → paid and status paid', () => {
const dto = mapFortnoxToSupplierInvoice(supplierRaw({ Balance: 0 }))
expect(dto.status).toBe('paid')
expect(dto.paymentStatus.paid).toBe(true)
})
it('supplier: positive Balance → unpaid', () => {
const dto = mapFortnoxToSupplierInvoice(supplierRaw({ Balance: 250 }))
expect(dto.status).toBe('booked')
expect(dto.paymentStatus.paid).toBe(false)
expect(dto.paymentStatus.balance.value).toBe(250)
})
it('supplier: FullyPaid flag with absent Balance keeps status and paid CONSISTENT', () => {
// Previously deriveInvoiceStatus said paid while paymentStatus.paid said unpaid.
const dto = mapFortnoxToSupplierInvoice(supplierRaw({ FullyPaid: true }))
expect(dto.status).toBe('paid')
expect(dto.paymentStatus.paid).toBe(true)
// paid ⇒ no outstanding balance, even though the raw payload omits Balance
// (previously balance fell back to the full total, contradicting paid=true).
expect(dto.paymentStatus.balance.value).toBe(0)
})
it('sales: absent Balance is NOT paid (no false-paid on the sales path)', () => {
const dto = mapFortnoxToSalesInvoice(salesRaw({})) // no Balance key
expect(dto.status).toBe('sent')
expect(dto.paymentStatus.paid).toBe(false)
expect(dto.paymentStatus.balance.value).toBe(1000)
})
it('sales: Balance 0 → paid and status paid', () => {
const dto = mapFortnoxToSalesInvoice(salesRaw({ Balance: 0 }))
expect(dto.status).toBe('paid')
expect(dto.paymentStatus.paid).toBe(true)
})
it('sales: FullyPaid flag with absent Balance → paid with zero balance', () => {
const dto = mapFortnoxToSalesInvoice(salesRaw({ FullyPaid: true }))
expect(dto.status).toBe('paid')
expect(dto.paymentStatus.paid).toBe(true)
expect(dto.paymentStatus.balance.value).toBe(0)
})
it('status === paid iff paymentStatus.paid across a matrix (both paths)', () => {
const balances = [undefined, 0, 0.004, 250, 1000]
const flags = [undefined, true]
for (const Balance of balances) {
for (const FullyPaid of flags) {
const over: Record<string, unknown> = { FullyPaid }
if (Balance !== undefined) over.Balance = Balance
for (const dto of [
mapFortnoxToSupplierInvoice(supplierRaw(over)),
mapFortnoxToSalesInvoice(salesRaw(over)),
]) {
expect(
dto.status === 'paid',
`Balance=${Balance} FullyPaid=${FullyPaid}`,
).toBe(dto.paymentStatus.paid)
// Invariant: paid ⇒ balance zeroed (never "fully paid yet full balance").
if (dto.paymentStatus.paid) {
expect(
dto.paymentStatus.balance.value,
`Balance=${Balance} FullyPaid=${FullyPaid}`,
).toBe(0)
}
}
}
}
})
})
+32 -5
View File
@@ -14,10 +14,22 @@ function amount(value: number | undefined | null, currency: string = 'SEK'): Amo
return { value: value ?? 0, currencyCode: currency };
}
/**
* Single source of truth for "is this invoice fully settled?", used by BOTH
* deriveInvoiceStatus and the paymentStatus.paid flag so they can never diverge.
* Numeric, not strict === 0, so a residual öre / float drift still reads as paid.
* Number(undefined ?? NaN) = NaN and NaN <= 0 is false, so an ABSENT Balance is
* treated as NOT paid (the supplier-invoice list payload omits Balance) — only an
* explicit FullyPaid flag or a present non-positive Balance counts as paid.
*/
function isFullyPaid(raw: Record<string, unknown>): boolean {
return raw['FullyPaid'] === true || Number(raw['Balance'] ?? NaN) <= 0;
}
function deriveInvoiceStatus(raw: Record<string, unknown>): InvoiceStatusCode {
if (raw['Cancelled'] === true) return 'cancelled';
if (raw['Credit'] === true) return 'credited';
if (raw['FullyPaid'] === true || raw['Balance'] === 0) return 'paid';
if (isFullyPaid(raw)) return 'paid';
if (raw['Booked'] === true) return 'booked';
if (raw['Sent'] === true) return 'sent';
return 'draft';
@@ -49,7 +61,14 @@ function buildParty(name: string, orgNumber?: string, address?: Record<string, u
export function mapFortnoxToSalesInvoice(raw: Record<string, unknown>): SalesInvoiceDto {
const currency = (raw['Currency'] as string) ?? 'SEK';
const total = raw['Total'] as number ?? 0;
const balance = raw['Balance'] as number ?? 0;
// Default an ABSENT Balance to the full total (= fully unpaid), never 0, so a
// missing Balance never silently reads as paid. A present Balance (incl. 0) is
// used as-is. Mirrors the supplier path; paid-ness comes from isFullyPaid().
// When paid, force balance to 0 so the DTO is internally consistent
// (paid ⇒ nothing outstanding): an explicit FullyPaid with no Balance field
// would otherwise leave balance = total alongside paid = true.
const paid = isFullyPaid(raw);
const balance = paid ? 0 : ((raw['Balance'] as number | undefined) ?? total);
const rows = (raw['InvoiceRows'] as Record<string, unknown>[] | undefined) ?? [];
const lines: SalesInvoiceLineDto[] = rows.map((row, idx) => ({
@@ -72,7 +91,7 @@ export function mapFortnoxToSalesInvoice(raw: Record<string, unknown>): SalesInv
};
const paymentStatus: PaymentStatusDto = {
paid: balance === 0 && total > 0,
paid,
balance: amount(balance, currency),
};
@@ -107,7 +126,15 @@ export function mapFortnoxToSalesInvoice(raw: Record<string, unknown>): SalesInv
export function mapFortnoxToSupplierInvoice(raw: Record<string, unknown>): SupplierInvoiceDto {
const currency = (raw['Currency'] as string) ?? 'SEK';
const total = raw['Total'] as number ?? 0;
const balance = raw['Balance'] as number ?? 0;
// Default an ABSENT Balance to the full total (= fully unpaid), never 0.
// The supplier-invoice list is fetched with ?filter=unpaid, so a missing
// Balance must not be mistaken for "settled" — that would flip a genuinely
// open payable to paid downstream. A present Balance (incl. 0) is used as-is.
// When paid, force balance to 0 so the DTO is internally consistent
// (paid ⇒ nothing outstanding): an explicit FullyPaid with no Balance field
// would otherwise leave balance = total alongside paid = true.
const paid = isFullyPaid(raw);
const balance = paid ? 0 : ((raw['Balance'] as number | undefined) ?? total);
const rows = (raw['SupplierInvoiceRows'] as Record<string, unknown>[] | undefined) ?? [];
const lines: SupplierInvoiceLineDto[] = rows.map((row, idx) => ({
@@ -127,7 +154,7 @@ export function mapFortnoxToSupplierInvoice(raw: Record<string, unknown>): Suppl
};
const paymentStatus: PaymentStatusDto = {
paid: balance === 0 && total > 0,
paid,
balance: amount(balance, currency),
};