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
@@ -31,9 +31,16 @@ describe('tools/list payload size guard', () => {
|
||||
// closes the MCP parity gap with the existing REST endpoint so agents
|
||||
// can attach a bank tx to an already-posted verifikat without creating
|
||||
// duplicate bookkeeping. Description trimmed to ~180 chars.
|
||||
// * 31.5K → 32K when gnubok_find_voucher_candidates_for_supplier_invoice +
|
||||
// gnubok_link_supplier_invoice_to_voucher landed — the supplier-side
|
||||
// mirror of the customer find/link voucher tools. The link tool inlines
|
||||
// the shared STAGED_OPERATION_SCHEMA. Lets agents mark a leverantörs-
|
||||
// faktura paid against an already-posted verifikat (no new bokföring),
|
||||
// which is exactly the fix for invoices imported from Fortnox as open
|
||||
// payables while their payment already exists in the SIE-imported GL.
|
||||
// Long-term answer to growth is leaning harder on gnubok_search_tools — if this
|
||||
// fires again, prefer trimming descriptions or making a tool opt-in via search
|
||||
// before bumping further.
|
||||
expect(approxTokens).toBeLessThan(31_500)
|
||||
expect(approxTokens).toBeLessThan(32_000)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -52,6 +52,10 @@ import {
|
||||
findMatchingVouchersForInvoice,
|
||||
validateVoucherForInvoiceLink,
|
||||
} from '@/lib/invoices/voucher-matching'
|
||||
import {
|
||||
findMatchingVouchersForSupplierInvoice,
|
||||
validateVoucherForSupplierInvoiceLink,
|
||||
} from '@/lib/invoices/supplier-voucher-matching'
|
||||
import { findFiscalPeriod, reverseEntry, validateBalance } from '@/lib/bookkeeping/engine'
|
||||
import { closePeriod, lockPeriod, resolvePeriodStatusForDate, type PeriodStatusForDate } from '@/lib/core/bookkeeping/period-service'
|
||||
import { validateYearEndReadiness, previewYearEndClosing } from '@/lib/core/bookkeeping/year-end-service'
|
||||
@@ -5087,6 +5091,157 @@ export const tools: McpTool[] = [
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: 'gnubok_find_voucher_candidates_for_supplier_invoice',
|
||||
description: 'List posted verifikat that debit leverantörsskuld (2440) and could be the payment for this supplier invoice. Use before gnubok_link_supplier_invoice_to_voucher when marking a leverantörsfaktura paid against an existing verifikation (no new bokföring).',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
supplier_invoice_id: { type: 'string', description: 'UUID of the supplier invoice to find candidates for' },
|
||||
limit: { type: 'number', description: 'Max candidates to return (default 10, max 50)' },
|
||||
},
|
||||
required: ['supplier_invoice_id'],
|
||||
},
|
||||
outputSchema: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
supplier_invoice_id: { type: 'string' },
|
||||
invoice_status: { type: 'string' },
|
||||
candidates: { type: 'array', items: { type: 'object' } },
|
||||
},
|
||||
required: ['supplier_invoice_id', 'candidates'],
|
||||
},
|
||||
annotations: {
|
||||
readOnlyHint: true,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: false,
|
||||
},
|
||||
async execute(args, companyId, _userId, supabase) {
|
||||
const supplierInvoiceId = args.supplier_invoice_id as string
|
||||
if (!supplierInvoiceId) throw new Error('supplier_invoice_id is required')
|
||||
const limit = Math.min(Math.max(1, Number(args.limit) || 10), 50)
|
||||
|
||||
const { data: invoice, error } = await supabase
|
||||
.from('supplier_invoices')
|
||||
.select(
|
||||
'id, supplier_invoice_number, arrival_number, status, currency, total, paid_amount, remaining_amount, due_date, paid_at, exchange_rate, supplier_id, supplier:suppliers(id, name)'
|
||||
)
|
||||
.eq('id', supplierInvoiceId)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
if (error || !invoice) throw new Error('Supplier invoice not found')
|
||||
|
||||
if (!['registered', 'approved', 'overdue', 'partially_paid'].includes(invoice.status)) {
|
||||
return {
|
||||
supplier_invoice_id: supplierInvoiceId,
|
||||
invoice_status: invoice.status,
|
||||
candidates: [],
|
||||
}
|
||||
}
|
||||
|
||||
const candidates = await findMatchingVouchersForSupplierInvoice(
|
||||
supabase,
|
||||
companyId,
|
||||
invoice as never,
|
||||
{ limit },
|
||||
)
|
||||
return {
|
||||
supplier_invoice_id: supplierInvoiceId,
|
||||
invoice_status: invoice.status,
|
||||
candidates,
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: 'gnubok_link_supplier_invoice_to_voucher',
|
||||
description: 'Markera en leverantörsfaktura som betald genom att länka till en befintlig verifikation som redan debiterar leverantörsskuld (2440). Ingen ny verifikation skapas. Hitta kandidater med gnubok_find_voucher_candidates_for_supplier_invoice först.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
supplier_invoice_id: { type: 'string', description: 'UUID of the supplier invoice to mark paid' },
|
||||
journal_entry_id: { type: 'string', description: 'UUID of the existing posted verifikat to link' },
|
||||
notes: { type: 'string', description: 'Optional note stored on the supplier_invoice_payments row' },
|
||||
},
|
||||
required: ['supplier_invoice_id', 'journal_entry_id'],
|
||||
},
|
||||
outputSchema: STAGED_OPERATION_SCHEMA,
|
||||
annotations: {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: false,
|
||||
idempotentHint: false,
|
||||
openWorldHint: false,
|
||||
},
|
||||
async execute(args, companyId, userId, supabase, actor) {
|
||||
const supplierInvoiceId = args.supplier_invoice_id as string
|
||||
const journalEntryId = args.journal_entry_id as string
|
||||
const notes = (args.notes as string | undefined) ?? undefined
|
||||
if (!supplierInvoiceId || !journalEntryId) {
|
||||
throw new Error('supplier_invoice_id and journal_entry_id are required')
|
||||
}
|
||||
|
||||
const { data: invoice, error: invErr } = await supabase
|
||||
.from('supplier_invoices')
|
||||
.select(
|
||||
'id, supplier_invoice_number, arrival_number, status, currency, total, paid_amount, remaining_amount, due_date, paid_at, exchange_rate, supplier_id, supplier:suppliers(id, name)'
|
||||
)
|
||||
.eq('id', supplierInvoiceId)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
if (invErr || !invoice) throw new Error('Supplier invoice not found')
|
||||
if (!['registered', 'approved', 'overdue', 'partially_paid'].includes(invoice.status)) {
|
||||
throw new Error('Supplier invoice is not in a matchable state (must be registered, approved, overdue, or partially_paid)')
|
||||
}
|
||||
|
||||
const validation = await validateVoucherForSupplierInvoiceLink(
|
||||
supabase,
|
||||
companyId,
|
||||
invoice as never,
|
||||
journalEntryId,
|
||||
)
|
||||
if (!validation.ok) {
|
||||
throw new Error(
|
||||
`${validation.code}${validation.details ? `: ${JSON.stringify(validation.details)}` : ''}`,
|
||||
)
|
||||
}
|
||||
|
||||
const voucherLabel = validation.voucher.voucher_series && validation.voucher.voucher_number != null
|
||||
? `${validation.voucher.voucher_series}-${validation.voucher.voucher_number}`
|
||||
: journalEntryId.slice(0, 8)
|
||||
|
||||
return stagePendingOperation(
|
||||
supabase,
|
||||
companyId,
|
||||
userId,
|
||||
'link_supplier_invoice_voucher',
|
||||
`Länka verifikat ${voucherLabel} → leverantörsfaktura ${invoice.supplier_invoice_number ?? supplierInvoiceId.slice(0, 8)}`,
|
||||
{ supplier_invoice_id: supplierInvoiceId, journal_entry_id: journalEntryId, notes },
|
||||
{
|
||||
supplier_invoice_number: invoice.supplier_invoice_number,
|
||||
invoice_currency: invoice.currency,
|
||||
invoice_remaining: invoice.remaining_amount,
|
||||
voucher_label: voucherLabel,
|
||||
voucher_date: validation.voucher.entry_date,
|
||||
voucher_description: validation.voucher.description,
|
||||
ap_debit_amount: validation.apDebitAmount,
|
||||
payment_amount: validation.paymentAmount,
|
||||
will_be_fully_paid: validation.isFullyPaid,
|
||||
remaining_after: validation.remainingAfter,
|
||||
supplier_name: (invoice.supplier as unknown as { name?: string } | null)?.name ?? null,
|
||||
},
|
||||
actor,
|
||||
{
|
||||
description: 'After approval the supplier invoice transitions to paid (or partially_paid). No new verifikat is created — the existing voucher is the payment posting.',
|
||||
tool: 'gnubok_get_supplier_ledger',
|
||||
},
|
||||
)
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: 'gnubok_auto_match_period',
|
||||
description: "Bulk reconciliation: scan unmatched income transactions in a date range and propose invoice matches with confidence + reasoning. dry_run=true (default) previews without staging; dry_run=false stages every match above confidence_threshold as a pending operation.",
|
||||
|
||||
Reference in New Issue
Block a user