Files
accounted/extensions/general/arcim-migration/lib/__tests__/entity-mapper-status.test.ts
T
MattssonandClaude Opus 4.8 f6ee0c2a82 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>
2026-06-02 13:25:48 +02:00

128 lines
4.8 KiB
TypeScript

import { describe, it, expect } from 'vitest'
import { mapSupplierInvoice } from '../entity-mapper'
import type { SupplierInvoiceDto, InvoiceStatusCode, PartyDto } from '@/lib/providers/dto'
/**
* Guards the status/paid consistency hardening in mapSupplierInvoice: the
* provider's lifecycle status (dto.status) and its payment status are computed
* independently upstream and can contradict each other. The mapper must emit a
* `status` that always agrees with paid_amount / remaining_amount, and treat
* Balance numerically (drift-safe), without ever flipping a credit note.
*/
const party: PartyDto = { name: 'Leverantör AB', identifications: [] }
function makeDto(over: {
status?: InvoiceStatusCode
paid?: boolean
balance?: number
total?: number
invoiceTypeCode?: string
lastPaymentDate?: string
}): SupplierInvoiceDto {
const total = over.total ?? 1000
return {
id: 'inv-1',
invoiceNumber: 'F-100',
issueDate: '2026-01-10',
dueDate: '2026-02-10',
invoiceTypeCode: over.invoiceTypeCode,
currencyCode: 'SEK',
status: over.status ?? 'booked',
supplier: party,
buyer: party,
lines: [
{
id: '1',
description: 'Tjänst',
lineExtensionAmount: { value: total, currencyCode: 'SEK' },
taxPercent: 25,
},
],
legalMonetaryTotal: {
lineExtensionAmount: { value: total, currencyCode: 'SEK' },
payableAmount: { value: total, currencyCode: 'SEK' },
},
paymentStatus: {
paid: over.paid ?? false,
balance: { value: over.balance ?? total, currencyCode: 'SEK' },
lastPaymentDate: over.lastPaymentDate,
},
}
}
function map(over: Parameters<typeof makeDto>[0]) {
return mapSupplierInvoice(makeDto(over), 'user-1', 'company-1', 'supplier-1').invoice
}
describe('mapSupplierInvoice — status/paid consistency', () => {
it('unpaid booked invoice → registered with full remaining', () => {
const inv = map({ status: 'booked', paid: false, balance: 1000, total: 1000 })
expect(inv.status).toBe('registered')
expect(inv.paid_amount).toBe(0)
expect(inv.remaining_amount).toBe(1000)
expect(inv.paid_at).toBeNull()
})
it('booked-but-paid invoice → flips to paid (status follows payment)', () => {
// The bug: dto.status='booked' (→registered) while paymentStatus.paid=true.
const inv = map({ status: 'booked', paid: true, balance: 0, total: 1000, lastPaymentDate: '2026-02-05' })
expect(inv.status).toBe('paid')
expect(inv.paid_amount).toBe(1000)
expect(inv.remaining_amount).toBe(0)
expect(inv.paid_at).toBe('2026-02-05')
})
it('near-zero residual balance (0.004) resolves to paid, not unpaid', () => {
const inv = map({ status: 'booked', paid: false, balance: 0.004, total: 1000 })
expect(inv.status).toBe('paid')
expect(inv.remaining_amount).toBe(0)
expect(inv.paid_amount).toBe(1000)
})
it('partially-paid invoice (0 < paid < total) → partially_paid', () => {
const inv = map({ status: 'booked', paid: false, balance: 300, total: 1000 })
expect(inv.status).toBe('partially_paid')
expect(inv.paid_amount).toBe(700)
expect(inv.remaining_amount).toBe(300)
expect(inv.paid_at).not.toBeNull()
})
it('credit note with zero balance stays credited — never flipped to paid', () => {
const inv = map({ status: 'credited', paid: true, balance: 0, total: 1000, invoiceTypeCode: '381' })
expect(inv.status).toBe('credited')
expect(inv.is_credit_note).toBe(true)
})
it('credit note is forced to credited even if the provider sends a non-terminal status', () => {
// invoiceTypeCode='381' but a contradictory lifecycle status (the arcim
// gateway does not guarantee status='credited' alongside the type code).
for (const status of ['booked', 'paid', 'sent', 'draft'] as InvoiceStatusCode[]) {
const inv = map({ status, paid: true, balance: 0, total: 1000, invoiceTypeCode: '381' })
expect(inv.status, `status=${status}`).toBe('credited')
expect(inv.is_credit_note).toBe(true)
expect(inv.paid_at).toBeNull()
}
})
it('overdue lifecycle status is preserved when nothing is paid', () => {
const inv = map({ status: 'overdue', paid: false, balance: 1000, total: 1000 })
expect(inv.status).toBe('overdue')
expect(inv.remaining_amount).toBe(1000)
})
it('never emits a status outside the supplier_invoices CHECK allow-list', () => {
const allowed = new Set([
'registered', 'approved', 'paid', 'partially_paid', 'overdue', 'disputed', 'credited', 'reversed',
])
for (const status of ['draft', 'sent', 'booked', 'paid', 'overdue', 'cancelled', 'credited'] as InvoiceStatusCode[]) {
for (const paid of [true, false]) {
for (const balance of [0, 250, 1000]) {
const inv = map({ status, paid, balance, total: 1000 })
expect(allowed.has(inv.status as string)).toBe(true)
}
}
}
})
})