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:
co-authored by
Claude Opus 4.8
parent
358c25094d
commit
f6ee0c2a82
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* Unit tests for commitLinkSupplierInvoiceVoucher, driven through the public
|
||||
* commitPendingOperation dispatcher.
|
||||
*
|
||||
* The MCP tool gnubok_link_supplier_invoice_to_voucher stages a
|
||||
* 'link_supplier_invoice_voucher' pending_operation; this dispatcher picks it up
|
||||
* and the executor delegates to linkSupplierInvoiceToVoucher (the atomic
|
||||
* link_supplier_invoice_to_voucher RPC). The RPC itself is covered by
|
||||
* lib/invoices/__tests__/supplier-voucher-matching{,.pg}.test.ts — these tests
|
||||
* focus on the dispatcher/executor wiring + status mapping.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
import { createQueuedMockSupabase, makeSupplierInvoice } from '@/tests/helpers'
|
||||
import type { PendingOperation } from '@/types'
|
||||
|
||||
import { commitPendingOperation } from '../commit'
|
||||
|
||||
const SI_UUID = '550e8400-e29b-41d4-a716-446655440010'
|
||||
const JE_UUID = '550e8400-e29b-41d4-a716-446655440011'
|
||||
|
||||
function makePendingOp(overrides: Partial<PendingOperation>): PendingOperation {
|
||||
return {
|
||||
id: 'op-1',
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
operation_type: 'link_supplier_invoice_voucher',
|
||||
status: 'pending',
|
||||
title: 'test',
|
||||
params: {},
|
||||
preview_data: {},
|
||||
result_data: null,
|
||||
actor_type: 'user',
|
||||
actor_id: null,
|
||||
actor_label: null,
|
||||
risk_level: 'medium',
|
||||
created_at: '2026-06-01T00:00:00Z',
|
||||
resolved_at: null,
|
||||
updated_at: '2026-06-01T00:00:00Z',
|
||||
...overrides,
|
||||
} as PendingOperation
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
})
|
||||
|
||||
describe('commitPendingOperation: link_supplier_invoice_voucher', () => {
|
||||
it('returns 400 when supplier_invoice_id is missing', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' }, error: null }) // CAS claim
|
||||
enqueue({ data: null, error: null }) // dispatcher's reject update
|
||||
|
||||
const op = makePendingOp({ params: { journal_entry_id: JE_UUID } })
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
|
||||
|
||||
expect(result.status).toBe('failed')
|
||||
expect(result.http_status).toBe(400)
|
||||
expect(result.error).toMatch(/supplier_invoice_id/i)
|
||||
})
|
||||
|
||||
it('happy path: links the verifikat and marks the supplier invoice paid', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
vi.spyOn(eventBus, 'emit').mockResolvedValue(undefined)
|
||||
|
||||
enqueue({ data: { id: 'op-1' }, error: null }) // CAS claim
|
||||
// executor -> linkSupplierInvoiceToVoucher -> RPC
|
||||
enqueue({
|
||||
data: {
|
||||
ok: true,
|
||||
payment_id: 'sip-1',
|
||||
invoice_status: 'paid',
|
||||
paid_amount: 1000,
|
||||
remaining_amount: 0,
|
||||
payment_amount: 1000,
|
||||
journal_entry_id: JE_UUID,
|
||||
currency: 'SEK',
|
||||
},
|
||||
error: null,
|
||||
})
|
||||
// post-link invoice re-fetch for the event payload
|
||||
enqueue({
|
||||
data: makeSupplierInvoice({ id: SI_UUID, status: 'paid', total: 1000, remaining_amount: 0 }),
|
||||
error: null,
|
||||
})
|
||||
enqueue({ data: null, error: null }) // dispatcher commit update
|
||||
|
||||
const op = makePendingOp({ params: { supplier_invoice_id: SI_UUID, journal_entry_id: JE_UUID } })
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(result.data).toMatchObject({
|
||||
invoice_status: 'paid',
|
||||
paid_amount: 1000,
|
||||
remaining_amount: 0,
|
||||
payment_amount: 1000,
|
||||
payment_id: 'sip-1',
|
||||
journal_entry_id: JE_UUID,
|
||||
})
|
||||
})
|
||||
|
||||
it('auto-rejects with 404 when the RPC reports the invoice is gone', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' }, error: null }) // CAS claim
|
||||
enqueue({ data: { ok: false, code: 'LINK_SI_VOUCHER_INVOICE_NOT_FOUND' }, error: null }) // RPC
|
||||
enqueue({ data: null, error: null }) // dispatcher's auto-reject update
|
||||
|
||||
const op = makePendingOp({ params: { supplier_invoice_id: SI_UUID, journal_entry_id: JE_UUID } })
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
|
||||
|
||||
expect(result.status).toBe('rejected')
|
||||
expect(result.http_status).toBe(404)
|
||||
})
|
||||
|
||||
it('auto-rejects with 409 when the verifikat is already linked', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' }, error: null }) // CAS claim
|
||||
enqueue({ data: { ok: false, code: 'LINK_SI_VOUCHER_ALREADY_LINKED' }, error: null }) // RPC
|
||||
enqueue({ data: null, error: null }) // dispatcher's auto-reject update
|
||||
|
||||
const op = makePendingOp({ params: { supplier_invoice_id: SI_UUID, journal_entry_id: JE_UUID } })
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
|
||||
|
||||
expect(result.status).toBe('rejected')
|
||||
expect(result.http_status).toBe(409)
|
||||
})
|
||||
})
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
createSupplierInvoiceRegistrationEntry,
|
||||
} from '@/lib/bookkeeping/supplier-invoice-entries'
|
||||
import { linkInvoiceToVoucher } from '@/lib/invoices/voucher-matching'
|
||||
import { linkSupplierInvoiceToVoucher } from '@/lib/invoices/supplier-voucher-matching'
|
||||
import { linkTransactionToJournalEntry } from '@/lib/transactions/link-journal-entry'
|
||||
import { getErrorEntry } from '@/lib/errors/structured-errors'
|
||||
import { parseSIEFile } from '@/lib/import/sie-parser'
|
||||
@@ -1038,6 +1039,48 @@ async function commitLinkInvoiceVoucher(
|
||||
}
|
||||
}
|
||||
|
||||
async function commitLinkSupplierInvoiceVoucher(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
params: Record<string, unknown>
|
||||
): Promise<ExecutorResult> {
|
||||
const supplierInvoiceId = params.supplier_invoice_id as string | undefined
|
||||
const journalEntryId = params.journal_entry_id as string | undefined
|
||||
const notes = (params.notes as string | undefined) ?? undefined
|
||||
|
||||
if (!supplierInvoiceId || !journalEntryId) {
|
||||
return { error: 'supplier_invoice_id and journal_entry_id are required', status: 400 }
|
||||
}
|
||||
|
||||
const outcome = await linkSupplierInvoiceToVoucher(supabase, userId, companyId, {
|
||||
supplierInvoiceId,
|
||||
journalEntryId,
|
||||
notes,
|
||||
})
|
||||
|
||||
if (!outcome.ok) {
|
||||
const entry = getErrorEntry(outcome.code)
|
||||
// 404/409 are auto-rejected by the dispatcher (the user can re-stage with
|
||||
// adjusted inputs); 400 surfaces as a normal failure so the UI can explain.
|
||||
return {
|
||||
error: entry?.message_en ?? outcome.code,
|
||||
status: entry?.httpStatus ?? 500,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
data: {
|
||||
invoice_status: outcome.result.invoiceStatus,
|
||||
paid_amount: outcome.result.paidAmount,
|
||||
remaining_amount: outcome.result.remainingAmount,
|
||||
payment_amount: outcome.result.paymentAmount,
|
||||
payment_id: outcome.result.paymentId,
|
||||
journal_entry_id: outcome.result.journalEntryId,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ── Stream 1 Phase 1 + follow-up executors ───────────────────────
|
||||
|
||||
async function commitClosePeriod(
|
||||
@@ -1614,6 +1657,11 @@ async function commitCreateSupplierInvoiceFromInbox(
|
||||
vat_code: null,
|
||||
vat_rate: vatRate,
|
||||
vat_amount: vatAmt,
|
||||
// For reverse charge the buyer self-assesses VAT; carry an explicit
|
||||
// statutory rate when staged, else null (engine defaults to 25%).
|
||||
reverse_charge_rate: reverseCharge
|
||||
? ([0.06, 0.12, 0.25].includes(Number(item.reverse_charge_rate)) ? Number(item.reverse_charge_rate) : null)
|
||||
: null,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -2909,6 +2957,9 @@ export async function commitPendingOperation(
|
||||
case 'link_invoice_voucher':
|
||||
result = await commitLinkInvoiceVoucher(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
case 'link_supplier_invoice_voucher':
|
||||
result = await commitLinkSupplierInvoiceVoucher(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
case 'close_period':
|
||||
result = await commitClosePeriod(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
|
||||
@@ -30,6 +30,11 @@ export const OPERATION_RISK_TIERS: Record<string, RiskLevel> = {
|
||||
// entry is created or modified. Sits next to match_transaction_invoice
|
||||
// semantically — both attach an existing booking to an invoice.
|
||||
link_invoice_voucher: 'medium',
|
||||
// Supplier-side mirror of link_invoice_voucher: link an existing posted
|
||||
// verifikat (Dr 2440) as payment for a leverantörsfaktura. Reversible by
|
||||
// deleting the supplier_invoice_payments row and reverting status; no journal
|
||||
// entry is created or modified.
|
||||
link_supplier_invoice_voucher: 'medium',
|
||||
create_invoice: 'medium', // creates as draft; sending is a separate op
|
||||
create_transaction: 'medium', // ingests an uncategorized row; reversible by delete
|
||||
// Supplier master data carries payment-routing fields (IBAN, BIC, bankgiro,
|
||||
|
||||
Reference in New Issue
Block a user