Bug/open banking flow (#854)
* fix(enable-banking): pin Mobile BankID (decoupled) auth_method so Handelsbanken corporate connects We never sent auth_method to Enable Banking, so it fell back to the ASPSP's visible default — REDIRECT for Handelsbanken. For Handelsbanken *corporate* PSUs the redirect flow does not support Mobile BankID, so authorization failed right after the user approved in the BankID app. Mobile BankID at Handelsbanken is a DECOUPLED method flagged hidden_method=true, which Enable Banking only uses when requested explicitly. Resolve the bank's preferred auth method before /auth: query the ASPSP's auth_methods and pick the DECOUPLED (Mobile BankID) method when present, otherwise leave auth_method unset so banks that already work are untouched. The method name is read dynamically per psu_type, so it is robust across sandbox/production naming. - api-client: add approach/hidden_method to AuthMethod, fix ASPSP.auth_methods field name (was available_auth_methods, never populated), add getPreferredAuthMethod(), thread optional authMethod through startAuthorization - index: resolve authMethod in /connect and pass it on both fresh + reconnect - tests: cover method selection and request-body shaping Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * refactor(invoice-inbox): clean up bulk-selection toolbar UI Redesign the selection toolbar shown when inbox items are checked: one solid primary "Bokför valda" button with outlined secondary actions ("Fråga assistenten", "Ta bort") and a plain selection count. Removes the redundant "Avmarkera" button (users uncheck the still-visible box), fixes label clipping, and gives the toolbar more breathing room. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * chore(entitlements): bypass paywall in local development Add isPaywallBypassed() so all gated capabilities are testable locally without a subscription. Fires only on NODE_ENV=development (npm run dev) or an explicit DISABLE_PAYWALL=true escape hatch — production builds run under NODE_ENV=production and the entitlement suite runs under 'test', so both keep exercising the real gate. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(tic): resolve enskild firma bolagsuppgifter via 12-digit personnummer TIC's Lens search is fuzzy and only resolves an enskild firma from the 12-digit (century-prefixed) personnummer; a 10-digit form fuzzy-matched an unrelated entity. Expand personnummer to 12 digits before querying and reject hits whose registration number is unrelated to the request. Add a "Hämta" action to the settings Bolagsuppgifter panel to (re)fetch on demand. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(transactions): implement categorize core for bank transaction categorization - Added `categorize-core.ts` to handle categorization of bank transactions, supporting single and bulk operations. - Introduced `categorizeMatchedTransaction` and `bulkBookMatchedInboxItems` functions for transaction processing. - Implemented fiscal period validation and duplicate booking detection. - Enhanced logging and error handling for transaction categorization. feat(scripts): add diagnostic script for Handelsbanken ASPSP metadata - Created `check-handelsbanken-aspsp.mjs` to fetch and display available authentication methods for Handelsbanken. - Outputs metadata for business and personal PSU types, including default authentication methods. fix(migrations): increase statement timeout for SIE bulk delete operations - Updated `20260629160000_sie_bulk_delete_statement_timeout.sql` to set a longer statement timeout for bulk delete RPCs to prevent cancellations during large imports. feat(migrations): add bulk book inbox items to pending operations - Expanded `pending_operations` table to include `bulk_book_inbox_items` operation type in `20260630120000_pending_operations_add_bulk_book_inbox_items.sql`. - Supports bulk booking of matched inbox items against bank transactions. test(pg): add tests for replace_period_opening_balance_link RPC - Implemented tests in `replace-period-opening-balance-link.pg.test.ts` to validate the functionality of the opening-balance correction flow. - Ensured immutability of opening balance links and proper handling of posted vs. non-posted entries. * fix(sie-export): update journal entries and lines handling in SIE export tests * fix(migrations): resolve version collision on 20260629160000 The SIE bulk-delete statement_timeout migration shared version 20260629160000 with journal_entries_list_series_filter (merged from main via #798/#823), causing a schema_migrations_pkey duplicate key error on apply. Rename the branch's migration to 20260629160100. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(compliance): resolve compliance-swarm + review findings - opening-balance/correct: compensating rollback for the non-atomic storno+rebook so a mid-sequence failure never leaves two posted OB entries (ASVS V2.3); durable audit event on every failure path (V16); reference the original verifikationsnummer in the corrected entry per BFL 5 kap 5§; document that requireWrite already enforces write-role + membership (V8.2.1 was a false positive) - reports sources routes: validate the cursor date component as ISO (/^\d{4}-\d{2}-\d{2}$/) before use, 400 on malformed (ASVS V1.2), applied to both the VAT-declaration and trial-balance routes - AgentSessionList: await the rename PATCH, revert the optimistic title and toast on failure (ASVS V4.5) - bank booking: exclude same-batch siblings from the booking-time duplicate guard so bulk-booking distinct same-(date,amount) transactions no longer false-positives; pre-existing duplicate detection is preserved - BulkBookInboxDialog: drop the unsafe currency-based reverse_charge default, add an omvänd skattskyldighet advisory, and type VAT options to the backend VatTreatment union - OpeningBalanceRowEditor: hold onChange in a ref (synced in effect, not during render) so an unstable callback can't cause a render loop Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- 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
2da9c71eb3
commit
f63d3e3100
@@ -0,0 +1,139 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { verifikationDraft } from '../verifikation-draft'
|
||||
|
||||
// verifikation.draft is the assistant entry point on the manual bookkeeping
|
||||
// surfaces (Bokföring → "Skapa med assistent", the Ny verifikat-dialog handoff,
|
||||
// and a draft verifikat's own page). These tests lock in the two things that
|
||||
// make it actually useful:
|
||||
// 1. it carries the underlag-reading tools its ground rules already reference
|
||||
// (the intent shipped without them — instructions for tools it couldn't
|
||||
// call), and
|
||||
// 2. the prompt drives "read the underlag → suggest accounts → stage a
|
||||
// voucher", while guarding against duplicating an existing draft (there's
|
||||
// no MCP edit-draft tool, so for an existing draft the agent must advise,
|
||||
// not stage a second verifikat).
|
||||
|
||||
type Captured = Parameters<typeof verifikationDraft.promptTemplate>[0]['captured']
|
||||
|
||||
function baseCaptured(overrides: Partial<Captured> = {}): Captured {
|
||||
return {
|
||||
entry: null,
|
||||
current_lines: [],
|
||||
period_status: null,
|
||||
description_hint: null,
|
||||
underlag: [],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function renderPrompt(overrides: Partial<Captured> = {}, profileSummary: string | null = null): string {
|
||||
return verifikationDraft.promptTemplate({
|
||||
captured: baseCaptured(overrides),
|
||||
profileSummary,
|
||||
activeMemory: [],
|
||||
})
|
||||
}
|
||||
|
||||
describe('verifikation.draft tool scope', () => {
|
||||
it('carries the underlag-reading tools its ground rules reference', () => {
|
||||
// shared-rules.ts tells the agent to call gnubok_list_inbox_items /
|
||||
// gnubok_get_document_content before proposing a booking. The intent
|
||||
// originally omitted them, so those instructions were dead. Lock them in.
|
||||
expect(verifikationDraft.tools).toContain('gnubok_get_document_content')
|
||||
expect(verifikationDraft.tools).toContain('gnubok_list_inbox_items')
|
||||
expect(verifikationDraft.tools).toContain('gnubok_get_inbox_item')
|
||||
expect(verifikationDraft.tools).toContain('gnubok_list_unmatched_documents')
|
||||
})
|
||||
|
||||
it('can still stage the voucher', () => {
|
||||
expect(verifikationDraft.tools).toContain('gnubok_create_voucher')
|
||||
})
|
||||
})
|
||||
|
||||
describe('verifikation.draft prompt template', () => {
|
||||
it('renders the shared ground rules (underlag-first discipline)', () => {
|
||||
const out = renderPrompt()
|
||||
expect(out).toContain('UNDERLAG FÖRST')
|
||||
})
|
||||
|
||||
it('tells the agent to read the underlag before proposing accounts', () => {
|
||||
const out = renderPrompt()
|
||||
expect(out).toContain('UNDERLAG FÖRST.')
|
||||
expect(out).toContain('gnubok_list_inbox_items')
|
||||
expect(out).toContain('gnubok_get_document_content')
|
||||
})
|
||||
|
||||
it('stages a new voucher and links the inbox underlag to it', () => {
|
||||
const out = renderPrompt()
|
||||
expect(out).toContain('gnubok_create_voucher')
|
||||
// The kvitto must follow the booking — create_voucher takes inbox_item_id
|
||||
// and attaches the OCR document on commit.
|
||||
expect(out).toContain('inbox_item_id')
|
||||
})
|
||||
|
||||
it('guards against duplicating an existing draft', () => {
|
||||
// No MCP tool edits a draft in place, so for an existing draft the agent
|
||||
// must advise (suggest accounts / check balance) rather than stage a
|
||||
// second verifikat — otherwise "help me finish this draft" creates a dupe.
|
||||
const out = renderPrompt({
|
||||
entry: { id: 'e1', entry_date: '2026-05-01', description: 'Utkast', status: 'draft' },
|
||||
})
|
||||
expect(out).toContain('Staga INTE en ny verifikation för ett utkast som redan finns')
|
||||
})
|
||||
|
||||
it('surfaces extracted underlag fields so the agent does not re-ask', () => {
|
||||
const out = renderPrompt({
|
||||
entry: { id: 'e1', entry_date: '2026-05-01', description: 'Inköp', status: 'draft' },
|
||||
underlag: [
|
||||
{
|
||||
document_id: 'doc-1',
|
||||
file_name: 'kvitto.pdf',
|
||||
merchant_name: 'Clas Ohlson',
|
||||
receipt_date: '2026-05-01',
|
||||
total_amount: 499,
|
||||
vat_amount: 99.8,
|
||||
currency: 'SEK',
|
||||
raw_extraction: null,
|
||||
},
|
||||
],
|
||||
})
|
||||
expect(out).toContain('UNDERLAG kopplat till verifikationen')
|
||||
expect(out).toContain('Clas Ohlson')
|
||||
expect(out).toContain('document_id=doc-1')
|
||||
})
|
||||
|
||||
it('warns when the entry sits in a locked period', () => {
|
||||
const out = renderPrompt({
|
||||
entry: { id: 'e1', entry_date: '2025-12-31', description: 'Inköp', status: 'draft' },
|
||||
period_status: { period_id: 'p1', status: 'locked', lock_date: '2025-12-31' },
|
||||
})
|
||||
expect(out).toContain('PERIODEN ÄR LÅST')
|
||||
})
|
||||
|
||||
it('flags an unbalanced set of existing lines', () => {
|
||||
const out = renderPrompt({
|
||||
entry: { id: 'e1', entry_date: '2026-05-01', description: 'Inköp', status: 'draft' },
|
||||
current_lines: [
|
||||
{ account_number: '5410', debit_amount: 500, credit_amount: null, description: 'Förbrukning' },
|
||||
{ account_number: '1930', debit_amount: null, credit_amount: 400, description: 'Bank' },
|
||||
],
|
||||
})
|
||||
expect(out).toContain('debet ≠ kredit')
|
||||
})
|
||||
})
|
||||
|
||||
describe('verifikation.draft capture', () => {
|
||||
it('returns an empty draft (with an underlag array) when no entry id is given', async () => {
|
||||
// The fresh-start path (Bokföring → "Skapa med assistent") passes no
|
||||
// journal_entry_id and must not touch the database — the agent discovers
|
||||
// underlag itself via the inbox tools.
|
||||
const captured = await verifikationDraft.capture(
|
||||
{ description: 'Köp av router' },
|
||||
{ supabase: {} as never, userId: 'u1', companyId: 'c1' },
|
||||
)
|
||||
expect(captured.entry).toBeNull()
|
||||
expect(captured.current_lines).toEqual([])
|
||||
expect(captured.underlag).toEqual([])
|
||||
expect(captured.description_hint).toBe('Köp av router')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,197 @@
|
||||
import { defineAgentIntent } from './types'
|
||||
import { SONNET_MODEL, THINKING_BUDGET_STANDARD } from '@/lib/agent/composer/client'
|
||||
|
||||
// inbox.bulk-book — "Fråga assistenten" on a multi-selection in the Underlag
|
||||
// view (Dokumentinkorgen). Unlike transaction.categorization (which keys off the
|
||||
// single previewed item), this intent receives the user's CHECKBOX selection
|
||||
// (selectedIds) so Lena acts on exactly what the user marked — not whatever
|
||||
// happens to be open in the preview pane.
|
||||
//
|
||||
// Booking model (Modell B): each selected item is booked against its matched
|
||||
// bank transaction with one shared category + VAT treatment via
|
||||
// gnubok_bulk_book_inbox_items (which stages one approval). The agent groups the
|
||||
// selection by vendor/kind and books each homogeneous group, detecting
|
||||
// reverse-charge for foreign services.
|
||||
|
||||
interface InboxBulkBookArgs {
|
||||
item_ids: string[]
|
||||
}
|
||||
|
||||
interface CapturedInboxItem {
|
||||
item_id: string
|
||||
// bookable = matched to a tx and not yet booked; not_matched = needs a bank
|
||||
// match first; already_booked = resolved (skip).
|
||||
status: 'bookable' | 'not_matched' | 'already_booked'
|
||||
merchant_name: string | null
|
||||
invoice_date: string | null
|
||||
total: number | null
|
||||
vat_amount: number | null
|
||||
currency: string | null
|
||||
tx_date: string | null
|
||||
tx_amount_sek: number | null
|
||||
tx_description: string | null
|
||||
}
|
||||
|
||||
interface CapturedInboxBulk {
|
||||
items: CapturedInboxItem[]
|
||||
bookable_count: number
|
||||
}
|
||||
|
||||
// SEK magnitude of a (usually-SEK) bank transaction. Foreign rows are
|
||||
// normalised via their stored amount_sek/exchange_rate.
|
||||
function txSek(tx: {
|
||||
amount: number | null
|
||||
currency: string | null
|
||||
amount_sek: number | null
|
||||
exchange_rate: number | null
|
||||
}): number | null {
|
||||
if (tx.amount == null) return null
|
||||
const cur = String(tx.currency ?? 'SEK').toUpperCase()
|
||||
if (cur === 'SEK') return Math.abs(Number(tx.amount))
|
||||
const sek = tx.amount_sek ?? Number(tx.amount) * Number(tx.exchange_rate ?? 1)
|
||||
return Number.isFinite(sek) ? Math.abs(Number(sek)) : null
|
||||
}
|
||||
|
||||
export const inboxBulkBook = defineAgentIntent<InboxBulkBookArgs, CapturedInboxBulk>({
|
||||
id: 'inbox.bulk-book',
|
||||
buttonLabel: 'Fråga assistenten',
|
||||
sheetTitle: 'Bulkbokför underlag',
|
||||
|
||||
atoms: {
|
||||
mode: 'declarative',
|
||||
horizontal: ['swedish-vat', 'swedish-accounting-compliance', 'swedish-invoice-compliance'],
|
||||
includeCompanyVertical: true,
|
||||
includeCompanyModifiers: true,
|
||||
},
|
||||
|
||||
tools: [
|
||||
'gnubok_bulk_book_inbox_items',
|
||||
'gnubok_categorize_transaction',
|
||||
'gnubok_query_journal',
|
||||
'gnubok_get_document_content',
|
||||
'gnubok_list_inbox_items',
|
||||
'gnubok_load_skill',
|
||||
'gnubok_search_tools',
|
||||
'gnubok_remember_fact',
|
||||
'gnubok_forget_fact',
|
||||
],
|
||||
|
||||
model: SONNET_MODEL,
|
||||
|
||||
// Reason before proposing — group the selection and work out category + VAT
|
||||
// treatment in the thinking channel, so the visible reply is one short
|
||||
// motivation, not a play-by-play.
|
||||
thinking: { budgetTokens: THINKING_BUDGET_STANDARD },
|
||||
|
||||
capture: async ({ item_ids }, { supabase, companyId }) => {
|
||||
const ids = Array.isArray(item_ids) ? item_ids.filter((x): x is string => typeof x === 'string') : []
|
||||
if (ids.length === 0) return { items: [], bookable_count: 0 }
|
||||
|
||||
const { data: rows } = await supabase
|
||||
.from('invoice_inbox_items')
|
||||
.select('id, matched_transaction_id, created_journal_entry_id, created_supplier_invoice_id, extracted_data')
|
||||
.eq('company_id', companyId)
|
||||
.in('id', ids)
|
||||
|
||||
const txIds = Array.from(
|
||||
new Set((rows ?? []).map((r) => r.matched_transaction_id).filter(Boolean) as string[]),
|
||||
)
|
||||
interface TxRow {
|
||||
id: string
|
||||
date: string | null
|
||||
amount: number | null
|
||||
currency: string | null
|
||||
amount_sek: number | null
|
||||
exchange_rate: number | null
|
||||
description: string | null
|
||||
}
|
||||
const txById = new Map<string, TxRow>()
|
||||
if (txIds.length > 0) {
|
||||
const { data: txs } = await supabase
|
||||
.from('transactions')
|
||||
.select('id, date, amount, currency, amount_sek, exchange_rate, description')
|
||||
.eq('company_id', companyId)
|
||||
.in('id', txIds)
|
||||
for (const t of ((txs ?? []) as TxRow[])) txById.set(t.id, t)
|
||||
}
|
||||
|
||||
const items: CapturedInboxItem[] = (rows ?? []).map((r) => {
|
||||
const ex = (r.extracted_data ?? {}) as {
|
||||
supplier?: { name?: string | null }
|
||||
invoice?: { invoiceDate?: string | null; currency?: string | null }
|
||||
totals?: { total?: number | null; vatAmount?: number | null }
|
||||
}
|
||||
const tx = r.matched_transaction_id ? txById.get(r.matched_transaction_id as string) ?? null : null
|
||||
const status: CapturedInboxItem['status'] =
|
||||
r.created_journal_entry_id || r.created_supplier_invoice_id
|
||||
? 'already_booked'
|
||||
: r.matched_transaction_id
|
||||
? 'bookable'
|
||||
: 'not_matched'
|
||||
return {
|
||||
item_id: r.id as string,
|
||||
status,
|
||||
merchant_name: ex.supplier?.name ?? null,
|
||||
invoice_date: ex.invoice?.invoiceDate ?? null,
|
||||
total: ex.totals?.total ?? null,
|
||||
vat_amount: ex.totals?.vatAmount ?? null,
|
||||
currency: ex.invoice?.currency ?? null,
|
||||
tx_date: tx?.date ?? null,
|
||||
tx_amount_sek: tx ? txSek(tx) : null,
|
||||
tx_description: tx?.description ?? null,
|
||||
}
|
||||
})
|
||||
|
||||
return { items, bookable_count: items.filter((i) => i.status === 'bookable').length }
|
||||
},
|
||||
|
||||
promptTemplate: ({ captured, profileSummary }) => {
|
||||
const lines: string[] = []
|
||||
if (profileSummary) lines.push(`Företagets profil: ${profileSummary}`, '')
|
||||
|
||||
if (captured.items.length === 0) {
|
||||
return [
|
||||
'Användaren öppnade hjälpfönstret från en markering i Dokumentinkorgen, men inga underlag kunde läsas.',
|
||||
'Be användaren markera underlagen igen och försök på nytt.',
|
||||
].join(' ')
|
||||
}
|
||||
|
||||
const bookable = captured.items.filter((i) => i.status === 'bookable')
|
||||
const notMatched = captured.items.filter((i) => i.status === 'not_matched')
|
||||
const alreadyBooked = captured.items.filter((i) => i.status === 'already_booked')
|
||||
|
||||
lines.push(`Användaren har markerat ${captured.items.length} underlag i Dokumentinkorgen och vill bulkbokföra dem.`)
|
||||
lines.push('')
|
||||
lines.push(
|
||||
`MARKERADE UNDERLAG (${bookable.length} bokförbara, ${notMatched.length} saknar matchad transaktion, ${alreadyBooked.length} redan bokförda):`,
|
||||
)
|
||||
for (const it of bookable) {
|
||||
const parts: string[] = [`item_id=${it.item_id}`]
|
||||
if (it.merchant_name) parts.push(`leverantör=${it.merchant_name}`)
|
||||
if (it.total != null) parts.push(`belopp=${it.total.toLocaleString('sv-SE')} ${it.currency ?? 'SEK'}`)
|
||||
if (it.vat_amount != null) parts.push(`moms=${it.vat_amount.toLocaleString('sv-SE')} ${it.currency ?? 'SEK'}`)
|
||||
if (it.tx_amount_sek != null) parts.push(`bank=${it.tx_amount_sek.toLocaleString('sv-SE')} SEK`)
|
||||
if (it.tx_date) parts.push(`datum=${it.tx_date}`)
|
||||
lines.push(` • ${parts.join(', ')}`)
|
||||
}
|
||||
if (notMatched.length > 0) {
|
||||
lines.push('')
|
||||
lines.push('EJ MATCHADE (kan inte bulkbokföras förrän de matchats mot en banktransaktion):')
|
||||
for (const it of notMatched) {
|
||||
const label = it.merchant_name ?? it.tx_description ?? it.item_id
|
||||
lines.push(` • ${label}${it.total != null ? ` (${it.total.toLocaleString('sv-SE')} ${it.currency ?? 'SEK'})` : ''}`)
|
||||
}
|
||||
}
|
||||
lines.push('')
|
||||
lines.push('Arbetssätt:')
|
||||
lines.push('- Boka via banktransaktionen (Modell B): verktyget bokför varje underlag mot dess matchade banktransaktion, som redan bär SEK-beloppet. Du behöver inte räkna om valuta.')
|
||||
lines.push('- GRUPPERA de bokförbara underlagen efter leverantör/typ. Samma slags kostnad → samma kategori + momsbehandling. För varje homogen grupp anropar du gnubok_bulk_book_inbox_items med gruppens item_ids, en kategori (enum) och vat_treatment.')
|
||||
lines.push('- MOMS: en utländsk tjänst (t.ex. USD/EUR-prenumeration som Cursor/Anysphere där säljaren INTE debiterat svensk moms) är omvänd skattskyldighet → vat_treatment="reverse_charge". En svensk faktura med debiterad moms → standard_25 (eller den sats kvittot visar). Gissa aldrig — utgå från valuta + om underlaget visar moms.')
|
||||
lines.push('- KOLLA HUR MOTPARTEN BOKFÖRTS FÖRUT med gnubok_query_journal({ text: "<leverantör>", limit: 5 }) innan du väljer kategori. Följ ett tydligt tidigare mönster om inte underlaget motsäger det.')
|
||||
lines.push('- HOPPA ÖVER ej matchade underlag: be användaren matcha dem mot en banktransaktion först ("Matcha mot transaktion" i Dokumentinkorgen), så kan de bulkbokföras i nästa runda. Bokför ALDRIG ett underlag utan matchad transaktion via det här flödet.')
|
||||
lines.push('- Förklara kort på svenska VARFÖR du valde kategori + momsbehandling — använd kategori-namn (t.ex. "Programvara/IT-tjänster"), aldrig ett BAS-kontonummer. Godkännandekortet visar antal, konto och moms; upprepa inte de siffrorna och säg inte att operationen är "stagead".')
|
||||
lines.push('')
|
||||
lines.push('Svara på svenska och var direkt.')
|
||||
return lines.join('\n')
|
||||
},
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { AgentIntent } from './types'
|
||||
import { generalHelp } from './general-help'
|
||||
import { transactionCategorization } from './transaction-categorization'
|
||||
import { inboxBulkBook } from './inbox-bulk-book'
|
||||
import { invoiceDraft } from './invoice-draft'
|
||||
import { supplierInvoiceReview } from './supplier-invoice-review'
|
||||
import { vatReview } from './vat-review'
|
||||
@@ -23,6 +24,7 @@ import { onboardingIntake } from './onboarding-intake'
|
||||
const INTENTS: AgentIntent<any, any>[] = [
|
||||
generalHelp,
|
||||
transactionCategorization,
|
||||
inboxBulkBook,
|
||||
invoiceDraft,
|
||||
supplierInvoiceReview,
|
||||
vatReview,
|
||||
|
||||
@@ -44,6 +44,7 @@ export const AGENT_GROUND_RULES: string[] = [
|
||||
// standard-BAS account backfill in the engine/storno service.
|
||||
'- RÄTTA FEL I BOKFÖRDA VERIFIKATIONER — så fungerar det i Accounted (beskriv aldrig andra vägar än dessa):',
|
||||
' • En bokförd verifikation kan aldrig redigeras direkt (Bokföringslagen). Rättelse görs från verifikationens egen sida: Bokföring → öppna verifikationen → knappen "Rätta". "Rätta rader" skapar automatiskt en storno som nollställer originalet plus en ny rättelseverifikation med de rätta raderna, båda i originalets period. "Rätta datum" flyttar verifikationen till rätt datum/år (storno + ombokning under huven). Hela kedjan original → storno → rättelse länkas och visas på verifikationssidan.',
|
||||
' • INGÅENDE BALANSER (IB) rättas på sitt eget sätt — INTE via "Rätta rader". Gå till Bokföring, öppna IB-verifikationen (beskrivning "Ingående balanser", serie A) och klicka "Korrigera ingående balanser". Då öppnas IB-raderna så att beloppen kan ändras direkt; när man sparar stornas den gamla IB-verifikationen och en korrigerad bokförs, och periodens ingående balans pekas om till den nya. Detta gäller oavsett om IB kom från SIE-import, CSV/Excel-import eller föregående års bokslut. IB finns alltså INTE under Inställningar eller Kontoplan — korrigeringen görs på själva verifikationen.',
|
||||
' • Är verifikationen den SENASTE i sin serie kan den även raderas helt ("Radera verifikat") — då återanvänds löpnumret och ingen lucka uppstår.',
|
||||
' • Konton som finns i BAS-kontoplanen men saknas i företagets kontoplan läggs till AUTOMATISKT vid bokföring och rättelse. Be aldrig användaren registrera standardkonton manuellt innan de bokför — bara okända kontonummer eller avaktiverade konton stoppar.',
|
||||
' • När en bokning makuleras (storno utan rättelse) släpps den kopplade banktransaktionen och blir bokföringsbar igen i transaktionsvyn — användaren kan alltid klicka på transaktionen och bokföra om. Vid en rättelse följer transaktionen och underlaget med till rättelseverifikationen.',
|
||||
|
||||
@@ -2,12 +2,16 @@ import { defineAgentIntent } from './types'
|
||||
import { SONNET_MODEL, THINKING_BUDGET_STANDARD } from '@/lib/agent/composer/client'
|
||||
import { renderAgentGroundRules } from './shared-rules'
|
||||
|
||||
// verifikation.draft — "Fråga [namn]" on the journal entry creation form.
|
||||
// verifikation.draft — "Fråga om denna verifikation" on the journal entry
|
||||
// creation/draft surfaces (Bokföring → "Skapa med assistent", the Ny
|
||||
// verifikat-dialog, and a draft verifikat's own page).
|
||||
//
|
||||
// Helps the user construct a balanced verifikation: pick the right BAS
|
||||
// accounts, handle VAT splits, and detect when a transaction should instead
|
||||
// be matched to an invoice or supplier invoice (rather than booked from
|
||||
// scratch). Reads any in-progress draft state passed via intent_args.
|
||||
// Helps the user construct a balanced verifikation end to end: read the
|
||||
// underlag (kvitto/faktura) the user often can't see themselves and pull the
|
||||
// figures from it, pick the right BAS accounts, handle VAT splits, and detect
|
||||
// when a transaction should instead be matched to an invoice or supplier
|
||||
// invoice (rather than booked from scratch). Reads any in-progress draft state
|
||||
// + linked underlag passed via intent_args.
|
||||
|
||||
interface VerifikationDraftArgs {
|
||||
// Optional id when the user is editing an existing draft. null for /new.
|
||||
@@ -36,6 +40,21 @@ interface CapturedVerifikationDraft {
|
||||
lock_date: string | null
|
||||
} | null
|
||||
description_hint: string | null
|
||||
// Underlag already linked to the entry (when editing a draft). Flattened
|
||||
// from document_attachments.extracted_data the same way
|
||||
// transaction.categorization does, so the agent can read the figures
|
||||
// without a round-trip. Empty for a brand-new verifikation — there the
|
||||
// agent discovers underlag via gnubok_list_inbox_items.
|
||||
underlag: {
|
||||
document_id: string | null
|
||||
file_name: string | null
|
||||
merchant_name: string | null
|
||||
receipt_date: string | null
|
||||
total_amount: number | null
|
||||
vat_amount: number | null
|
||||
currency: string | null
|
||||
raw_extraction: Record<string, unknown> | null
|
||||
}[]
|
||||
}
|
||||
|
||||
export const verifikationDraft = defineAgentIntent<
|
||||
@@ -57,6 +76,13 @@ export const verifikationDraft = defineAgentIntent<
|
||||
'gnubok_get_trial_balance',
|
||||
'gnubok_query_journal',
|
||||
'gnubok_create_voucher',
|
||||
// Underlag reading — the ground rules (shared-rules.ts) already instruct
|
||||
// the agent to look in the inbox and read the underlag before proposing a
|
||||
// booking; these are the tools that make those instructions callable.
|
||||
'gnubok_get_document_content',
|
||||
'gnubok_list_inbox_items',
|
||||
'gnubok_list_unmatched_documents',
|
||||
'gnubok_get_inbox_item',
|
||||
'gnubok_load_skill',
|
||||
'gnubok_search_tools',
|
||||
'gnubok_remember_fact',
|
||||
@@ -76,6 +102,7 @@ export const verifikationDraft = defineAgentIntent<
|
||||
let entry: CapturedVerifikationDraft['entry'] = null
|
||||
let lines: CapturedVerifikationDraft['current_lines'] = []
|
||||
let periodStatus: CapturedVerifikationDraft['period_status'] = null
|
||||
const underlag: CapturedVerifikationDraft['underlag'] = []
|
||||
|
||||
if (journal_entry_id) {
|
||||
const { data: e } = await supabase
|
||||
@@ -114,6 +141,37 @@ export const verifikationDraft = defineAgentIntent<
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Underlag already linked to this draft — surface the extracted fields
|
||||
// so the agent suggests accounts from what's on the kvitto without
|
||||
// re-asking. Mirrors transaction.categorization's document_attachments
|
||||
// read (same table, same extracted_data shape).
|
||||
const { data: docs } = await supabase
|
||||
.from('document_attachments')
|
||||
.select('id, file_name, extracted_data')
|
||||
.eq('journal_entry_id', journal_entry_id)
|
||||
.eq('company_id', companyId)
|
||||
.eq('is_current_version', true)
|
||||
for (const d of (docs ?? []) as {
|
||||
id: string
|
||||
file_name: string | null
|
||||
extracted_data: Record<string, unknown> | null
|
||||
}[]) {
|
||||
const ex = d.extracted_data ?? null
|
||||
const supplier = (ex?.supplier as { name?: string | null } | undefined) ?? null
|
||||
const invoice = (ex?.invoice as { invoiceDate?: string | null; currency?: string | null } | undefined) ?? null
|
||||
const totals = (ex?.totals as { total?: number | null; vatAmount?: number | null } | undefined) ?? null
|
||||
underlag.push({
|
||||
document_id: d.id,
|
||||
file_name: d.file_name,
|
||||
merchant_name: supplier?.name ?? null,
|
||||
receipt_date: invoice?.invoiceDate ?? null,
|
||||
total_amount: totals?.total ?? null,
|
||||
vat_amount: totals?.vatAmount ?? null,
|
||||
currency: invoice?.currency ?? null,
|
||||
raw_extraction: ex,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,6 +180,7 @@ export const verifikationDraft = defineAgentIntent<
|
||||
current_lines: lines,
|
||||
period_status: periodStatus,
|
||||
description_hint: description ?? null,
|
||||
underlag,
|
||||
}
|
||||
},
|
||||
|
||||
@@ -164,6 +223,28 @@ export const verifikationDraft = defineAgentIntent<
|
||||
}
|
||||
}
|
||||
|
||||
if (captured.underlag.length > 0) {
|
||||
lines.push('')
|
||||
lines.push(`UNDERLAG kopplat till verifikationen: ${captured.underlag.length} st. Extraherade fält:`)
|
||||
for (const u of captured.underlag) {
|
||||
const parts: string[] = []
|
||||
if (u.document_id) parts.push(`document_id=${u.document_id}`)
|
||||
if (u.merchant_name) parts.push(`leverantör=${u.merchant_name}`)
|
||||
if (u.receipt_date) parts.push(`datum=${u.receipt_date}`)
|
||||
if (u.total_amount != null) {
|
||||
parts.push(`total=${u.total_amount.toLocaleString('sv-SE')} ${u.currency ?? 'SEK'}`)
|
||||
}
|
||||
if (u.vat_amount != null) {
|
||||
parts.push(`moms=${u.vat_amount.toLocaleString('sv-SE')} ${u.currency ?? 'SEK'}`)
|
||||
}
|
||||
lines.push(
|
||||
` • ${parts.join(', ') || `${u.file_name ?? 'underlag'} (ingen extraherad data — läs med gnubok_get_document_content)`}`,
|
||||
)
|
||||
}
|
||||
lines.push('')
|
||||
lines.push('Extraktionen ovan är det vi REDAN VET — fråga inte om leverantör/belopp som står där. Räcker den inte (t.ex. saknar momsbelopp), läs underlaget med gnubok_get_document_content(document_id=…).')
|
||||
}
|
||||
|
||||
if (captured.period_status) {
|
||||
lines.push('')
|
||||
lines.push(
|
||||
@@ -177,10 +258,13 @@ export const verifikationDraft = defineAgentIntent<
|
||||
}
|
||||
lines.push('')
|
||||
lines.push('Arbetssätt:')
|
||||
lines.push('1. Föreslå rätt BAS-konton baserat på beskrivningen. Syns en motpart i beskrivningen — kolla historiken med gnubok_query_journal({ text: "<motpartens namn>", limit: 5 }).')
|
||||
lines.push('2. Säkerställ att debet = kredit. Förklara varje rad kort.')
|
||||
lines.push('3. Om transaktionen i själva verket är en faktura/leverantörsfaktura/bankrad — be användaren matcha det istället. Direktbokning skapar dubbletter.')
|
||||
lines.push('4. Staga via gnubok_create_voucher när allt stämmer.')
|
||||
lines.push('1. UNDERLAG FÖRST. Saknas underlaget i sammanhanget ovan: leta i Dokumentinkorgen med gnubok_list_inbox_items (och gnubok_list_unmatched_documents). Läs det relevanta underlaget med gnubok_get_inbox_item / gnubok_get_document_content och dra fram datum, belopp, moms och motpart INNAN du föreslår konton. Användaren ser ofta inte underlagets innehåll själv — det är just det du hjälper till med.')
|
||||
lines.push('2. Föreslå rätt BAS-konton utifrån underlaget och beskrivningen. Syns en motpart — kolla historiken med gnubok_query_journal({ text: "<motpartens namn>", limit: 5 }) och följ tidigare mönster.')
|
||||
lines.push('3. Säkerställ att debet = kredit. Förklara varje rad kort (i kategori-/kontonamn, inte kontonummer).')
|
||||
lines.push('4. Är detta egentligen en kund-/leverantörsfaktura eller en bankrad? Be användaren matcha den istället — direktbokning skapar dubbletter.')
|
||||
lines.push('5. Skapa verifikationen:')
|
||||
lines.push(' • NY verifikation (inget utkast visas ovan): staga via gnubok_create_voucher när allt stämmer. Ligger underlaget i Dokumentinkorgen — skicka med inbox_item_id så kvittot kopplas till verifikationen automatiskt vid godkännande.')
|
||||
lines.push(' • BEFINTLIGT utkast (visas ovan): föreslå konton/moms och kontrollera balansen så att användaren kan färdigställa utkastet i formuläret. Staga INTE en ny verifikation för ett utkast som redan finns — det skapar en dubblett.')
|
||||
lines.push('')
|
||||
lines.push('Svara på svenska, kort och konkret.')
|
||||
return lines.join('\n')
|
||||
|
||||
@@ -797,6 +797,35 @@ export const BookInboxItemDirectlySchema = z.object({
|
||||
transaction_id: uuid.optional(),
|
||||
})
|
||||
|
||||
/**
|
||||
* Bulk-book selected Underlag (Dokumentinkorgen) against their matched bank
|
||||
* transactions. One shared category + VAT treatment is applied to every
|
||||
* selected item; each item is booked against its own matched transaction (which
|
||||
* carries the SEK amount), so the verifikat are individual — not a
|
||||
* samlingsverifikation. Items without a matched transaction, already booked, or
|
||||
* already linked to a leverantörsfaktura are skipped server-side.
|
||||
*
|
||||
* Used both as the UI route body (POST /items/bulk-book) and as the
|
||||
* pending-operation params for `bulk_book_inbox_items` (Lena-driven flow).
|
||||
*/
|
||||
export const BulkBookInboxSchema = z.object({
|
||||
item_ids: z.array(uuid).min(1, 'Minst ett underlag krävs').max(200, 'Högst 200 underlag per bokföring'),
|
||||
category: TransactionCategorySchema,
|
||||
// Optional fields are `.nullish()` (not just `.optional()`) because the
|
||||
// `bulk_book_inbox_items` pending operation persists absent optionals as
|
||||
// explicit JSON `null` (stagePendingOperation in mcp-server/server.ts). When
|
||||
// the executor re-parses those params on approval, a bare `.optional()` would
|
||||
// reject the stored `null`. `.transform` normalizes `null → undefined` so the
|
||||
// executor and categorizeMatchedTransaction never receive `null`.
|
||||
vat_treatment: VatTreatmentSchema.nullish().transform((v) => v ?? undefined),
|
||||
// The underlag's actual moms when it differs from rate × belopp (e.g. dricks).
|
||||
// Only valid with a rate-based vat_treatment; rejected otherwise downstream.
|
||||
vat_amount: z.number().positive().nullish().transform((v) => v ?? undefined),
|
||||
notes: z.string().max(2000).nullish().transform((v) => v ?? undefined),
|
||||
allow_duplicate: z.boolean().nullish().transform((v) => v ?? undefined),
|
||||
})
|
||||
export type BulkBookInboxInput = z.infer<typeof BulkBookInboxSchema>
|
||||
|
||||
export const MatchInvoiceSchema = z
|
||||
.object({
|
||||
invoice_id: uuid,
|
||||
|
||||
@@ -170,6 +170,7 @@ export const TOOL_SCOPE_MAP: Record<string, ApiKeyScope> = {
|
||||
gnubok_link_transaction_to_journal_entry: 'transactions:write',
|
||||
gnubok_match_batch_allocate: 'transactions:write',
|
||||
gnubok_bulk_book_transactions: 'transactions:write',
|
||||
gnubok_bulk_book_inbox_items: 'transactions:write',
|
||||
gnubok_auto_match_period: 'transactions:write',
|
||||
// Customers
|
||||
gnubok_list_customers: 'customers:read',
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
foldText,
|
||||
buildAccountIndex,
|
||||
searchAccounts,
|
||||
type SearchableAccount,
|
||||
} from '../account-search'
|
||||
|
||||
// Synthetic fixtures — `active` is a minimal chart, `catalog` is the full BAS
|
||||
// superset (and includes the active rows, as the real catalog does).
|
||||
const active: SearchableAccount[] = [
|
||||
{ account_number: '1930', account_name: 'Företagskonto', account_class: 1, description: 'Företagets huvudsakliga bankkonto.' },
|
||||
{ account_number: '5420', account_name: 'Programvaror', account_class: 5, description: 'Kostnader för mjukvara, prenumerationer och licenser.' },
|
||||
{ account_number: '7010', account_name: 'Lönekostnader tjänstemän', account_class: 7, description: 'Bruttolöner till anställda tjänstemän.' },
|
||||
]
|
||||
|
||||
const catalog: SearchableAccount[] = [
|
||||
...active,
|
||||
{ account_number: '6540', account_name: 'IT-tjänster', account_class: 6, description: 'Kostnader för extern IT-support, konsultation och drifttjänster.' },
|
||||
{ account_number: '6550', account_name: 'Konsultarvoden', account_class: 6, description: 'Arvode till externa konsulter för rådgivning.' },
|
||||
{ account_number: '6230', account_name: 'Datakommunikation', account_class: 6, description: 'Internet, bredband och fast uppkoppling.' },
|
||||
{ account_number: '6570', account_name: 'Bankkostnader', account_class: 6, description: 'Avgifter för banktjänster och konsultation.' },
|
||||
]
|
||||
|
||||
const idx = buildAccountIndex({ active, catalog })
|
||||
const numbers = (items: { account_number: string }[]) => items.map((i) => i.account_number)
|
||||
|
||||
describe('foldText', () => {
|
||||
it('lowercases and strips Swedish diacritics', () => {
|
||||
expect(foldText('Lön')).toBe('lon')
|
||||
expect(foldText('Intäkter')).toBe('intakter')
|
||||
expect(foldText('IT-tjänster')).toBe('it-tjanster')
|
||||
expect(foldText('Ränta')).toBe('ranta')
|
||||
})
|
||||
})
|
||||
|
||||
describe('searchAccounts', () => {
|
||||
it('returns the active chart (only) for an empty query', () => {
|
||||
const r = searchAccounts(idx, '')
|
||||
expect(numbers(r)).toEqual(['1930', '5420', '7010'])
|
||||
expect(r.every((i) => i.isActive)).toBe(true)
|
||||
})
|
||||
|
||||
it('finds a catalog-only account by name even when it is not in the chart (the "IT" case)', () => {
|
||||
const r = searchAccounts(idx, 'IT')
|
||||
expect(numbers(r)).toContain('6540')
|
||||
expect(r.find((i) => i.account_number === '6540')?.isActive).toBe(false)
|
||||
})
|
||||
|
||||
it('matches words that are not the leading word of the name', () => {
|
||||
expect(numbers(searchAccounts(idx, 'kommunikation'))).toContain('6230')
|
||||
})
|
||||
|
||||
it('matches words found only in the description', () => {
|
||||
// "drifttjänster" appears only in 6540's description, not its name.
|
||||
expect(numbers(searchAccounts(idx, 'drifttjänster'))).toEqual(['6540'])
|
||||
})
|
||||
|
||||
it('is diacritic-insensitive (query typed without å/ä/ö)', () => {
|
||||
expect(numbers(searchAccounts(idx, 'lonekostnader'))).toContain('7010')
|
||||
expect(numbers(searchAccounts(idx, 'lon'))).toContain('7010')
|
||||
})
|
||||
|
||||
it('requires every token to match (token-AND), regardless of order or hyphen', () => {
|
||||
// Both tokens live in 6540 (one in the name, one in the description).
|
||||
expect(numbers(searchAccounts(idx, 'drift it'))).toEqual(['6540'])
|
||||
// "extern konsultation": 6540 has both in its description; 6550/6570 miss one.
|
||||
expect(numbers(searchAccounts(idx, 'extern konsultation'))).toEqual(['6540'])
|
||||
})
|
||||
|
||||
it('prefix-matches account numbers across the full catalog', () => {
|
||||
const r = searchAccounts(idx, '65')
|
||||
expect(numbers(r).sort()).toEqual(['6540', '6550', '6570'])
|
||||
expect(r.every((i) => !i.isActive)).toBe(true)
|
||||
})
|
||||
|
||||
it('dedupes an account present in both active and catalog, preferring the active row', () => {
|
||||
const r = searchAccounts(idx, '1930')
|
||||
expect(r).toHaveLength(1)
|
||||
expect(r[0].isActive).toBe(true)
|
||||
})
|
||||
|
||||
it('ranks active accounts before catalog-only ones', () => {
|
||||
const r = searchAccounts(idx, 'kostnad')
|
||||
const firstCatalog = r.findIndex((i) => !i.isActive)
|
||||
const lastActive = r.map((i) => i.isActive).lastIndexOf(true)
|
||||
expect(lastActive).toBeLessThan(firstCatalog)
|
||||
// Within active, a name hit outranks a description-only hit.
|
||||
expect(r[0].account_number).toBe('7010')
|
||||
})
|
||||
|
||||
it('ranks a name "starts-with" hit first', () => {
|
||||
// "konsult": 6550 "Konsultarvoden" (name starts) over 6570 (description only).
|
||||
const r = searchAccounts(idx, 'konsult')
|
||||
expect(r[0].account_number).toBe('6550')
|
||||
})
|
||||
|
||||
it('returns nothing for a query that matches no account', () => {
|
||||
expect(searchAccounts(idx, 'zzzxyq')).toEqual([])
|
||||
})
|
||||
|
||||
it('honours the result limit', () => {
|
||||
expect(searchAccounts(idx, '', 2)).toHaveLength(2)
|
||||
expect(searchAccounts(idx, '6', 2)).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* Account search for the manual bookkeeping flow (AccountCombobox).
|
||||
*
|
||||
* Two problems this solves over a plain `account_name.includes(query)`:
|
||||
*
|
||||
* 1. Coverage — the combobox is fed two sources: the company's *active* chart
|
||||
* and (optionally) the full BAS 2026 catalog. A user who types "IT" should
|
||||
* find 6540 "IT-tjänster" even if it was never added to their chart yet.
|
||||
* Active accounts always rank first; selecting a catalog-only account is
|
||||
* handled by the existing activate-on-commit rail.
|
||||
*
|
||||
* 2. Matching — names are terse and statutory, so the everyday word the user
|
||||
* reaches for is often in the description, mid-name, or typed without
|
||||
* diacritics. We fold diacritics (so "lon" matches "Lön"), search
|
||||
* number + name + description, and require every token to match (so word
|
||||
* order and the hyphen in "IT-tjänster" stop mattering).
|
||||
*
|
||||
* Build the index once per (active, catalog) pair with buildAccountIndex, then
|
||||
* call searchAccounts per keystroke — the per-keystroke work is just substring
|
||||
* checks over pre-folded haystacks.
|
||||
*/
|
||||
|
||||
/** Minimal shape both an active BASAccount and a catalog row satisfy. */
|
||||
export interface SearchableAccount {
|
||||
account_number: string
|
||||
account_name: string
|
||||
account_class: number
|
||||
description?: string | null
|
||||
}
|
||||
|
||||
/** A single result row the combobox renders. */
|
||||
export interface AccountSearchItem {
|
||||
account_number: string
|
||||
account_name: string
|
||||
account_class: number
|
||||
/** true = already in the company's chart; false = catalog-only (activates on commit). */
|
||||
isActive: boolean
|
||||
}
|
||||
|
||||
export interface AccountIndexEntry {
|
||||
item: AccountSearchItem
|
||||
/** Folded "number name description" — the text every token is matched against. */
|
||||
haystack: string
|
||||
/** Folded name only — used for "starts with" / name-hit ranking. */
|
||||
nameFolded: string
|
||||
}
|
||||
|
||||
const DEFAULT_LIMIT = 50
|
||||
|
||||
/**
|
||||
* Lowercase + strip diacritics so a query typed without Swedish characters
|
||||
* still matches: "lon" → "lön", "intakter" → "intäkter", "ranta" → "ränta".
|
||||
*/
|
||||
export function foldText(input: string): string {
|
||||
return input
|
||||
.toLowerCase()
|
||||
.normalize('NFD')
|
||||
.replace(/[̀-ͯ]/g, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the searchable index. Active accounts are added first so that, on a
|
||||
* duplicate account number, the active row wins and catalog duplicates are
|
||||
* dropped.
|
||||
*/
|
||||
export function buildAccountIndex(opts: {
|
||||
active: SearchableAccount[]
|
||||
catalog?: SearchableAccount[]
|
||||
}): AccountIndexEntry[] {
|
||||
const seen = new Set<string>()
|
||||
const entries: AccountIndexEntry[] = []
|
||||
|
||||
const add = (acc: SearchableAccount, isActive: boolean) => {
|
||||
if (seen.has(acc.account_number)) return
|
||||
seen.add(acc.account_number)
|
||||
const description = acc.description ?? ''
|
||||
entries.push({
|
||||
item: {
|
||||
account_number: acc.account_number,
|
||||
account_name: acc.account_name,
|
||||
account_class: acc.account_class,
|
||||
isActive,
|
||||
},
|
||||
haystack: foldText(`${acc.account_number} ${acc.account_name} ${description}`),
|
||||
nameFolded: foldText(acc.account_name),
|
||||
})
|
||||
}
|
||||
|
||||
for (const a of opts.active) add(a, true)
|
||||
for (const c of opts.catalog ?? []) add(c, false)
|
||||
return entries
|
||||
}
|
||||
|
||||
/**
|
||||
* Search the index. Returns ranked items (active first), capped at `limit`.
|
||||
*
|
||||
* - Empty query → the active chart (what the dropdown shows when first opened).
|
||||
* - All-digit query → prefix match on the account number, spanning the catalog
|
||||
* so "65" browses every 65xx account, not just the active ones.
|
||||
* - Otherwise → token-AND substring match over number + name + description.
|
||||
*/
|
||||
export function searchAccounts(
|
||||
index: AccountIndexEntry[],
|
||||
query: string,
|
||||
limit: number = DEFAULT_LIMIT,
|
||||
): AccountSearchItem[] {
|
||||
const trimmed = query.trim()
|
||||
|
||||
if (!trimmed) {
|
||||
const out: AccountSearchItem[] = []
|
||||
for (const e of index) {
|
||||
if (!e.item.isActive) continue
|
||||
out.push(e.item)
|
||||
if (out.length >= limit) break
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
if (/^\d+$/.test(trimmed)) {
|
||||
const hits = index.filter((e) => e.item.account_number.startsWith(trimmed))
|
||||
return rank(hits, [trimmed], limit)
|
||||
}
|
||||
|
||||
const tokens = foldText(trimmed).split(/[\s-]+/).filter(Boolean)
|
||||
if (tokens.length === 0) return []
|
||||
const hits = index.filter((e) => tokens.every((t) => e.haystack.includes(t)))
|
||||
return rank(hits, tokens, limit)
|
||||
}
|
||||
|
||||
/**
|
||||
* Rank: active before catalog → name starts with the first token → all tokens
|
||||
* present in the name (vs only reachable via the description) → account number.
|
||||
*/
|
||||
function rank(entries: AccountIndexEntry[], tokens: string[], limit: number): AccountSearchItem[] {
|
||||
const firstToken = tokens[0] ?? ''
|
||||
const scored = entries.map((e) => {
|
||||
let score = 0
|
||||
if (e.item.isActive) score += 1000
|
||||
if (firstToken && e.nameFolded.startsWith(firstToken)) score += 100
|
||||
if (tokens.every((t) => e.nameFolded.includes(t))) score += 50
|
||||
return { e, score }
|
||||
})
|
||||
|
||||
scored.sort((a, b) =>
|
||||
b.score !== a.score
|
||||
? b.score - a.score
|
||||
: a.e.item.account_number.localeCompare(b.e.item.account_number),
|
||||
)
|
||||
|
||||
return scored.slice(0, limit).map((s) => s.e.item)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
'use client'
|
||||
|
||||
import type { SearchableAccount } from '@/lib/bookkeeping/account-search'
|
||||
|
||||
/**
|
||||
* Client-side loader for the full BAS catalogue used by AccountCombobox.
|
||||
*
|
||||
* The catalogue is static reference data, identical for every company, so we
|
||||
* fetch it once per session and share the in-flight promise across every
|
||||
* combobox instance and form mount. A failed fetch clears the cache so the
|
||||
* next caller retries rather than being stuck with an empty list.
|
||||
*/
|
||||
export interface CatalogAccount extends SearchableAccount {
|
||||
account_number: string
|
||||
account_name: string
|
||||
account_class: number
|
||||
account_group: string
|
||||
description: string | null
|
||||
}
|
||||
|
||||
let cache: Promise<CatalogAccount[]> | null = null
|
||||
|
||||
export function loadBasCatalog(): Promise<CatalogAccount[]> {
|
||||
if (!cache) {
|
||||
cache = fetch('/api/bookkeeping/accounts/bas-catalog')
|
||||
.then((res) => {
|
||||
if (!res.ok) throw new Error(`bas-catalog ${res.status}`)
|
||||
return res.json()
|
||||
})
|
||||
.then((body) => (body?.data as CatalogAccount[]) ?? [])
|
||||
.catch(() => {
|
||||
cache = null // allow a retry on the next call
|
||||
return []
|
||||
})
|
||||
}
|
||||
return cache
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
'use server'
|
||||
|
||||
import { cookies, headers } from 'next/headers'
|
||||
import { revalidatePath } from 'next/cache'
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { normalizeOrgNumber } from '@/lib/company-lookup/normalize-org-number'
|
||||
import { ensureTicSnapshot } from '@/lib/agent/composer/tic-fetch'
|
||||
|
||||
export interface RefreshCompanyProfileResult {
|
||||
ok?: true
|
||||
snapshot?: Record<string, unknown> | null
|
||||
fetchedAt?: string
|
||||
// Error *codes*, translated by the caller (same pattern as company/actions.ts):
|
||||
// unauthorized | org_number_invalid | persist_failed | not_found
|
||||
error?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch Bolagsuppgifter on demand from the settings → Företag panel.
|
||||
*
|
||||
* The panel normally shows the cached `companies.tic_snapshot`. This action
|
||||
* lets the user (re)fetch it live by submitting an org number / personnummer —
|
||||
* the path that recovers a company whose cached snapshot is missing or wrong
|
||||
* (e.g. an enskild firma whose 10-digit personnummer previously fuzzy-matched
|
||||
* the wrong entity; `searchCompanyByOrgNumber` now expands it to the 12-digit
|
||||
* form so Lens resolves it exactly).
|
||||
*
|
||||
* We persist the (normalized) number and clear `tic_snapshot_fetched_at` to
|
||||
* force `ensureTicSnapshot` past its 7-day cache, then let it do the live
|
||||
* /profile fetch + write. All writes are RLS-scoped to the caller's company.
|
||||
*/
|
||||
export async function refreshCompanyProfileAction(
|
||||
companyId: string,
|
||||
orgNumberRaw: string,
|
||||
): Promise<RefreshCompanyProfileResult> {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!user) return { error: 'unauthorized' }
|
||||
|
||||
// Refuse malformed input at the boundary rather than storing a value that
|
||||
// would later break SIE/SRU exports (same rule as createCompanyFromOnboarding).
|
||||
const cleaned = normalizeOrgNumber(orgNumberRaw)
|
||||
if (!cleaned) return { error: 'org_number_invalid' }
|
||||
|
||||
// Persist the (possibly corrected) number and force staleness so
|
||||
// ensureTicSnapshot re-fetches instead of returning the poisoned cache.
|
||||
const { error: updateError } = await supabase
|
||||
.from('companies')
|
||||
.update({ org_number: cleaned, tic_snapshot_fetched_at: null })
|
||||
.eq('id', companyId)
|
||||
if (updateError) return { error: 'persist_failed' }
|
||||
|
||||
// Keep the settings form (which reads company_settings.org_number) in sync —
|
||||
// best-effort; the TIC fetch reads companies.org_number, updated above.
|
||||
await supabase
|
||||
.from('company_settings')
|
||||
.update({ org_number: cleaned })
|
||||
.eq('company_id', companyId)
|
||||
|
||||
// Self-fetch needs the caller's session cookie and the current origin so it
|
||||
// reaches this same instance (dev / preview / prod) — see ensureTicSnapshot.
|
||||
const cookieStore = await cookies()
|
||||
const cookieHeader = cookieStore.getAll().map((c) => `${c.name}=${c.value}`).join('; ')
|
||||
const hdrs = await headers()
|
||||
const host = hdrs.get('host')
|
||||
const proto = hdrs.get('x-forwarded-proto') ?? 'https'
|
||||
const origin = host ? `${proto}://${host}` : undefined
|
||||
|
||||
const { snapshot, source } = await ensureTicSnapshot({
|
||||
supabase,
|
||||
companyId,
|
||||
cookieHeader,
|
||||
origin,
|
||||
// The user is watching a spinner; give the ~7-13 call Lens fan-out room to
|
||||
// finish (the 5s default aborted every fetch during the May quota incident).
|
||||
timeoutMs: 10_000,
|
||||
})
|
||||
|
||||
// 'fetched' = a fresh live fetch was persisted. 'fallback' = TIC returned
|
||||
// nothing / errored — surface it and leave the existing snapshot untouched
|
||||
// rather than blanking a good panel on a transient outage.
|
||||
if (source !== 'fetched' || !snapshot) {
|
||||
return { error: 'not_found' }
|
||||
}
|
||||
|
||||
revalidatePath('/settings')
|
||||
return { ok: true, snapshot, fetchedAt: new Date().toISOString() }
|
||||
}
|
||||
@@ -23,6 +23,23 @@ function isSelfHosted(): boolean {
|
||||
return process.env.NEXT_PUBLIC_SELF_HOSTED === 'true'
|
||||
}
|
||||
|
||||
/**
|
||||
* Local development is all-on so every gated feature is testable without a
|
||||
* subscription. Two triggers, both fail-safe for prod:
|
||||
* - NODE_ENV === 'development' (i.e. `npm run dev`). NOT 'test' — the
|
||||
* entitlement suite must still exercise the real gate — and NOT
|
||||
* 'production'.
|
||||
* - DISABLE_PAYWALL === 'true' — explicit escape hatch for a local
|
||||
* production build. Never set this in a hosted environment.
|
||||
*/
|
||||
function isPaywallBypassed(): boolean {
|
||||
return (
|
||||
isSelfHosted() ||
|
||||
process.env.NODE_ENV === 'development' ||
|
||||
process.env.DISABLE_PAYWALL === 'true'
|
||||
)
|
||||
}
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
||||
/**
|
||||
* Only server-resolved UUIDs may be interpolated into the PostgREST `.or()`
|
||||
@@ -38,7 +55,7 @@ export async function hasCapability(
|
||||
companyId: string,
|
||||
key: CapabilityKey,
|
||||
): Promise<boolean> {
|
||||
if (isSelfHosted()) return true
|
||||
if (isPaywallBypassed()) return true
|
||||
if (!isUuid(companyId)) return false // fail-closed: never interpolate a non-UUID
|
||||
|
||||
// Resolve the company's firm/team (firm-scoped grants cascade to clients).
|
||||
@@ -152,7 +169,7 @@ export async function getCompanyCapabilities(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
): Promise<CapabilityKey[]> {
|
||||
if (isSelfHosted()) return [...PAID_CAPABILITIES]
|
||||
if (isPaywallBypassed()) return [...PAID_CAPABILITIES]
|
||||
if (!isUuid(companyId)) return [] // fail-closed: never interpolate a non-UUID
|
||||
|
||||
const { data: company } = await supabase
|
||||
|
||||
@@ -915,6 +915,16 @@ const PERIOD: Record<string, StructuredErrorEntry> = {
|
||||
message_sv: 'Perioden är redan låst.',
|
||||
message_en: 'Period is already locked.',
|
||||
},
|
||||
PERIOD_UNLOCK_NOT_LOCKED: {
|
||||
httpStatus: 409,
|
||||
message_sv: 'Perioden är inte låst.',
|
||||
message_en: 'Period is not locked.',
|
||||
},
|
||||
PERIOD_UNLOCK_CLOSED: {
|
||||
httpStatus: 409,
|
||||
message_sv: 'Ett stängt räkenskapsår kan inte låsas upp.',
|
||||
message_en: 'A closed fiscal year cannot be unlocked.',
|
||||
},
|
||||
// Forward-chaining a new räkenskapsår is blocked while a prior period is
|
||||
// still fully open (not locked, not closed, not covered by the company-wide
|
||||
// lock-through date). BFL 6 kap allows löpande bokföring of the new year in
|
||||
@@ -1272,6 +1282,23 @@ const OPENING_BALANCE_IMPORT: Record<string, StructuredErrorEntry> = {
|
||||
message_sv: 'Importen misslyckades.',
|
||||
message_en: 'Opening balance import failed.',
|
||||
},
|
||||
OB_CORRECT_NO_EXISTING: {
|
||||
httpStatus: 409,
|
||||
message_sv: 'Perioden har inga ingående balanser att korrigera. Bokför dem först.',
|
||||
message_en: 'The period has no opening balances to correct. Book them first.',
|
||||
},
|
||||
OB_CORRECT_YEAR_END_EXISTS: {
|
||||
httpStatus: 409,
|
||||
message_sv:
|
||||
'Perioden har ett bokslut. Återför bokslutet och öppna perioden innan ingående balanser kan korrigeras.',
|
||||
message_en:
|
||||
'The period has a year-end close. Reverse the close and reopen the period before opening balances can be corrected.',
|
||||
},
|
||||
OB_CORRECT_FAILED: {
|
||||
httpStatus: 500,
|
||||
message_sv: 'Korrigeringen av ingående balanser misslyckades.',
|
||||
message_en: 'Opening balance correction failed.',
|
||||
},
|
||||
}
|
||||
|
||||
const REGISTER_IMPORT: Record<string, StructuredErrorEntry> = {
|
||||
|
||||
@@ -368,6 +368,27 @@ describe('sie_imports: partial unique index + replace flow', () => {
|
||||
expect(untouched.rows[0]?.journal_entry_id).toBe(manualEntry)
|
||||
})
|
||||
|
||||
it('replace_sie_import and undo_sie_import carry a raised statement_timeout', async () => {
|
||||
// Regression for the 8s-timeout cancellation (migration 20260629160000):
|
||||
// these RPCs run on the service-role REST client, which still inherits the
|
||||
// authenticator login role's 8s statement_timeout (service_role.rolconfig
|
||||
// is NULL). A large import's delete exceeded that and was cancelled, so the
|
||||
// functions now set a function-local statement_timeout well above 8s.
|
||||
const { rows } = await getPool().query<{ proname: string; proconfig: string[] | null }>(
|
||||
`SELECT proname, proconfig
|
||||
FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
|
||||
WHERE n.nspname = 'public'
|
||||
AND proname IN ('replace_sie_import', 'undo_sie_import')`,
|
||||
)
|
||||
expect(rows.length).toBe(2)
|
||||
for (const fn of rows) {
|
||||
const timeout = (fn.proconfig ?? []).find(c => c.startsWith('statement_timeout='))
|
||||
expect(timeout, `${fn.proname} should set statement_timeout`).toBeTruthy()
|
||||
const seconds = Number(/statement_timeout=(\d+)s/.exec(timeout!)?.[1] ?? 0)
|
||||
expect(seconds).toBeGreaterThan(8)
|
||||
}
|
||||
})
|
||||
|
||||
it('replace_sie_import on an already-replaced import raises', async () => {
|
||||
const { companyId, userId, fiscalPeriodId } = await seedCompany()
|
||||
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { getBASReference } from '@/lib/bookkeeping/bas-reference'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
|
||||
/**
|
||||
* Shared helpers for booking opening balances.
|
||||
*
|
||||
* Used by both the first-time import (`opening-balance/execute`) and the
|
||||
* correction flow (`opening-balance/correct`), which validate lines and
|
||||
* auto-activate accounts identically and differ only in what they do with
|
||||
* the resulting journal entry (set vs. storno + relink).
|
||||
*/
|
||||
|
||||
export interface OpeningBalanceLine {
|
||||
account_number: string
|
||||
debit_amount: number
|
||||
credit_amount: number
|
||||
}
|
||||
|
||||
export type OpeningBalanceValidation =
|
||||
| {
|
||||
ok: true
|
||||
validLines: OpeningBalanceLine[]
|
||||
totalDebit: number
|
||||
totalCredit: number
|
||||
}
|
||||
| { ok: false; code: 'OB_TOO_FEW_LINES' }
|
||||
| { ok: false; code: 'OB_PNL_ACCOUNT'; accounts: string[] }
|
||||
| { ok: false; code: 'OB_UNBALANCED'; totalDebit: number; totalCredit: number; diff: number }
|
||||
|
||||
/**
|
||||
* Validate opening-balance lines: drop zero-amount rows, require ≥2 lines,
|
||||
* reject P&L accounts (class 3–8), and verify debits equal credits.
|
||||
*/
|
||||
export function validateOpeningBalanceLines(
|
||||
lines: OpeningBalanceLine[],
|
||||
): OpeningBalanceValidation {
|
||||
const validLines = lines.filter((l) => l.debit_amount > 0 || l.credit_amount > 0)
|
||||
|
||||
if (validLines.length < 2) {
|
||||
return { ok: false, code: 'OB_TOO_FEW_LINES' }
|
||||
}
|
||||
|
||||
const pnlAccounts = validLines
|
||||
.map((l) => l.account_number)
|
||||
.filter((num) => {
|
||||
const cls = parseInt(num.charAt(0), 10)
|
||||
return cls >= 3 && cls <= 8
|
||||
})
|
||||
|
||||
if (pnlAccounts.length > 0) {
|
||||
return { ok: false, code: 'OB_PNL_ACCOUNT', accounts: pnlAccounts.slice(0, 5) }
|
||||
}
|
||||
|
||||
let totalDebit = 0
|
||||
let totalCredit = 0
|
||||
for (const line of validLines) {
|
||||
totalDebit = Math.round((totalDebit + line.debit_amount) * 100) / 100
|
||||
totalCredit = Math.round((totalCredit + line.credit_amount) * 100) / 100
|
||||
}
|
||||
|
||||
const diff = Math.round((totalDebit - totalCredit) * 100) / 100
|
||||
if (Math.abs(diff) >= 0.01) {
|
||||
return { ok: false, code: 'OB_UNBALANCED', totalDebit, totalCredit, diff }
|
||||
}
|
||||
|
||||
return { ok: true, validLines, totalDebit, totalCredit }
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-activate any BAS accounts referenced by the lines that are not yet in
|
||||
* the company's chart of accounts. Mirrors the behaviour of the first-time
|
||||
* import so a corrected file can reference accounts the original did not.
|
||||
*/
|
||||
export async function activateMissingAccounts(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
userId: string,
|
||||
accountNumbers: string[],
|
||||
): Promise<{ ok: true } | { ok: false; reason: string }> {
|
||||
const existingAccounts = await fetchAllRows<{ account_number: string }>(({ from, to }) =>
|
||||
supabase
|
||||
.from('chart_of_accounts')
|
||||
.select('account_number')
|
||||
.eq('company_id', companyId)
|
||||
.range(from, to),
|
||||
)
|
||||
|
||||
const existingNumbers = new Set(existingAccounts.map((a) => a.account_number))
|
||||
const accountsToActivate = accountNumbers
|
||||
.filter((num) => !existingNumbers.has(num))
|
||||
.map((num) => {
|
||||
const ref = getBASReference(num)
|
||||
|
||||
if (ref) {
|
||||
return {
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
account_number: ref.account_number,
|
||||
account_name: ref.account_name,
|
||||
account_class: ref.account_class,
|
||||
account_group: ref.account_group,
|
||||
account_type: ref.account_type,
|
||||
normal_balance: ref.normal_balance,
|
||||
plan_type: 'full_bas' as const,
|
||||
is_active: true,
|
||||
is_system_account: false,
|
||||
description: ref.description,
|
||||
sru_code: ref.sru_code,
|
||||
sort_order: parseInt(ref.account_number),
|
||||
}
|
||||
}
|
||||
|
||||
const accountClass = parseInt(num.charAt(0), 10)
|
||||
const accountGroup = num.substring(0, 2)
|
||||
const accountType =
|
||||
accountClass === 1 ? 'asset'
|
||||
: accountClass === 2 ? 'liability'
|
||||
: accountClass === 3 ? 'revenue'
|
||||
: 'expense'
|
||||
const normalBalance = accountClass <= 1 || accountClass >= 4 ? 'debit' : 'credit'
|
||||
|
||||
return {
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
account_number: num,
|
||||
account_name: `Konto ${num}`,
|
||||
account_class: accountClass,
|
||||
account_group: accountGroup,
|
||||
account_type: accountType,
|
||||
normal_balance: normalBalance,
|
||||
plan_type: 'full_bas' as const,
|
||||
is_active: true,
|
||||
is_system_account: false,
|
||||
description: `Konto ${num}`,
|
||||
sru_code: null,
|
||||
sort_order: parseInt(num),
|
||||
}
|
||||
})
|
||||
|
||||
if (accountsToActivate.length > 0) {
|
||||
const { error: activateError } = await supabase
|
||||
.from('chart_of_accounts')
|
||||
.insert(accountsToActivate)
|
||||
|
||||
if (activateError) {
|
||||
return { ok: false, reason: activateError.message }
|
||||
}
|
||||
}
|
||||
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
/** Map validated lines to journal entry line inputs. */
|
||||
export function buildOpeningBalanceEntryLines(validLines: OpeningBalanceLine[]) {
|
||||
return validLines.map((line) => ({
|
||||
account_number: line.account_number,
|
||||
debit_amount: line.debit_amount,
|
||||
credit_amount: line.credit_amount,
|
||||
line_description: `IB ${line.account_number}`,
|
||||
}))
|
||||
}
|
||||
@@ -65,4 +65,6 @@ export interface OpeningBalanceExecuteResult {
|
||||
total_debit: number
|
||||
total_credit: number
|
||||
error?: string
|
||||
/** Set when this was a correction: the stornoed previous IB entry id. */
|
||||
reversed_entry_id?: string | null
|
||||
}
|
||||
|
||||
@@ -15,9 +15,7 @@
|
||||
*/
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { buildMappingResultFromCategory } from '@/lib/bookkeeping/category-mapping'
|
||||
import { createTransactionJournalEntry } from '@/lib/bookkeeping/transaction-entries'
|
||||
import { upsertCounterpartyTemplate } from '@/lib/bookkeeping/counterparty-templates'
|
||||
import { bulkBookMatchedInboxItems, categorizeMatchedTransaction } from '@/lib/transactions/categorize-core'
|
||||
import { getVatRules, getAvailableVatRates } from '@/lib/invoices/vat-rules'
|
||||
import { fetchExchangeRate, convertToSEK } from '@/lib/currency/riksbanken'
|
||||
import { validateVatNumber } from '@/lib/vat/vies-client'
|
||||
@@ -44,7 +42,6 @@ import {
|
||||
} from '@/lib/bookkeeping/supplier-invoice-entries'
|
||||
import { linkInvoiceToVoucher } from '@/lib/invoices/voucher-matching'
|
||||
import { planInvoicePayment } from '@/lib/invoices/apply-invoice-payment'
|
||||
import { detectBookingDuplicate } from '@/lib/transactions/booking-duplicate-detection'
|
||||
import { findDuplicatePaymentCandidatesForInvoice } from '@/lib/invoices/duplicate-payment-candidates'
|
||||
import { linkSupplierInvoiceToVoucher } from '@/lib/invoices/supplier-voucher-matching'
|
||||
import { linkTransactionToJournalEntry } from '@/lib/transactions/link-journal-entry'
|
||||
@@ -74,9 +71,9 @@ import { prepareInvoicePdfRender, buildSwishQrDataUrl } from '@/lib/invoices/pdf
|
||||
import { ensureInvoiceNumber } from '@/lib/invoices/ensure-invoice-number'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { appendProcessingHistory } from '@/lib/processing-history/append'
|
||||
import { roundOre } from '@/lib/money'
|
||||
import { CreateSupplierParamsSchema } from '@/lib/pending-operations/schemas/create-supplier'
|
||||
import { CreateArticleParamsSchema, UpdateArticleParamsSchema } from '@/lib/pending-operations/schemas/article'
|
||||
import { BulkBookInboxSchema } from '@/lib/api/schemas'
|
||||
import { ensureArticleNumber } from '@/lib/articles/ensure-article-number'
|
||||
import { isValidRevenueAccount } from '@/lib/articles/validate-revenue-account'
|
||||
import { z } from 'zod'
|
||||
@@ -147,67 +144,9 @@ export interface CommitOptions {
|
||||
actor?: CommitActor
|
||||
}
|
||||
|
||||
// ── Helper: ensure fiscal period covers the date ──────────────────
|
||||
|
||||
async function ensureFiscalPeriod(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
date: string,
|
||||
fiscalYearStartMonth: number = 1
|
||||
): Promise<boolean> {
|
||||
const { data: existing } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.select('id')
|
||||
.eq('company_id', companyId)
|
||||
.lte('period_start', date)
|
||||
.gte('period_end', date)
|
||||
.eq('is_closed', false)
|
||||
.limit(1)
|
||||
|
||||
if (existing && existing.length > 0) return true
|
||||
|
||||
const txDate = new Date(date)
|
||||
const txMonth = txDate.getMonth() + 1
|
||||
const txYear = txDate.getFullYear()
|
||||
|
||||
let periodStartYear: number
|
||||
if (fiscalYearStartMonth === 1) {
|
||||
periodStartYear = txYear
|
||||
} else if (txMonth >= fiscalYearStartMonth) {
|
||||
periodStartYear = txYear
|
||||
} else {
|
||||
periodStartYear = txYear - 1
|
||||
}
|
||||
|
||||
const startMonth = String(fiscalYearStartMonth).padStart(2, '0')
|
||||
const periodStart = `${periodStartYear}-${startMonth}-01`
|
||||
|
||||
const endYear = fiscalYearStartMonth === 1 ? periodStartYear : periodStartYear + 1
|
||||
const endMonth = fiscalYearStartMonth === 1 ? 12 : fiscalYearStartMonth - 1
|
||||
const lastDay = new Date(endYear, endMonth, 0).getDate()
|
||||
const periodEnd = `${endYear}-${String(endMonth).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`
|
||||
|
||||
const periodName = fiscalYearStartMonth === 1
|
||||
? `Räkenskapsår ${periodStartYear}`
|
||||
: `Räkenskapsår ${periodStartYear}/${endYear}`
|
||||
|
||||
const { error } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.upsert({
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
name: periodName,
|
||||
period_start: periodStart,
|
||||
period_end: periodEnd,
|
||||
}, { onConflict: 'user_id,period_start,period_end' })
|
||||
|
||||
if (error) {
|
||||
log.error('Failed to create fiscal period:', error)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
// ensureFiscalPeriod moved to lib/transactions/categorize-core.ts (imported
|
||||
// above) so the bulk-book-inbox path and the single-categorize path share one
|
||||
// implementation.
|
||||
|
||||
async function recordSkippedInvoiceJournalEntry(
|
||||
invoiceId: string,
|
||||
@@ -270,203 +209,17 @@ async function commitCategorizeTransaction(
|
||||
? params.vat_amount
|
||||
: undefined
|
||||
|
||||
const { data: transaction, error: fetchError } = await supabase
|
||||
.from('transactions').select('*').eq('id', txId).eq('company_id', companyId).single()
|
||||
|
||||
if (fetchError || !transaction) {
|
||||
return { error: 'Transaction not found — it may have been deleted.', status: 404 }
|
||||
}
|
||||
if (transaction.journal_entry_id) {
|
||||
return { error: 'Transaction already has a journal entry — it was categorized in the meantime.', status: 409 }
|
||||
}
|
||||
|
||||
// Booking-time duplicate guard — parity with the web /categorize route, which
|
||||
// the agent path otherwise bypassed entirely. Refuse to mint a second
|
||||
// verifikat for an affärshändelse already in the ledger: an already-booked
|
||||
// sibling transaction, OR an unlinked voucher that already books this amount
|
||||
// on the bank account (invoice "markera som betald", the salary run's net-wage
|
||||
// payout, a manual verifikat). The agent has no interactive "Bokför ändå", so
|
||||
// it fails closed; re-stage with allow_duplicate=true after the user confirms
|
||||
// in chat that the bank line is a genuinely separate event. Fail-open on a
|
||||
// detection error so a transient query failure never blocks a real booking.
|
||||
if (params.allow_duplicate !== true) {
|
||||
let dup = null
|
||||
try {
|
||||
dup = await detectBookingDuplicate(supabase, companyId, {
|
||||
id: txId,
|
||||
date: transaction.date,
|
||||
amount: transaction.amount,
|
||||
cash_account_id: transaction.cash_account_id ?? null,
|
||||
})
|
||||
} catch (err) {
|
||||
log.warn('booking-time duplicate detection failed (continuing)', err)
|
||||
}
|
||||
if (dup) {
|
||||
const amountAbs = roundOre(Math.abs(Number(transaction.amount)))
|
||||
const voucher = dup.voucher_label ? `verifikat ${dup.voucher_label}` : 'en befintlig verifikation'
|
||||
return {
|
||||
error:
|
||||
`Möjlig dubblettbokföring: ${voucher} (${dup.entry_date}) bokför redan ${amountAbs} kr på bankkontot. ` +
|
||||
`Den här affärshändelsen ser redan ut att vara bokförd — länka transaktionen till den befintliga ` +
|
||||
`verifikationen i stället för att bokföra den igen. Om banktransaktionen verkligen är en separat ` +
|
||||
`affärshändelse, kör om med allow_duplicate=true.`,
|
||||
status: 409,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// allow_duplicate=true bypassed the guard. Booking over a possible
|
||||
// double-booking is a bookkeeping act that must leave a durable
|
||||
// behandlingshistorik record (BFNAR 2013:2 kap 8) — the web /book and
|
||||
// /categorize routes log BankTransactionDuplicateDismissed, and the agent
|
||||
// commit path must reach parity so an auditor can reconstruct why the
|
||||
// duplicate was allowed. Re-detect to capture the dismissed candidate;
|
||||
// best-effort, a logging failure must never block a legitimate booking.
|
||||
try {
|
||||
const dismissed = await detectBookingDuplicate(supabase, companyId, {
|
||||
id: txId,
|
||||
date: transaction.date,
|
||||
amount: transaction.amount,
|
||||
cash_account_id: transaction.cash_account_id ?? null,
|
||||
})
|
||||
if (dismissed) {
|
||||
await appendProcessingHistory({
|
||||
companyId,
|
||||
correlationId: txId,
|
||||
aggregateType: 'BankTransaction',
|
||||
aggregateId: txId,
|
||||
eventType: 'BankTransactionDuplicateDismissed',
|
||||
payload: {
|
||||
transaction_id: txId,
|
||||
dismissed_transaction_id: dismissed.transaction_id,
|
||||
dismissed_journal_entry_id: dismissed.journal_entry_id,
|
||||
amount_ore: Math.round(dismissed.amount * 100),
|
||||
entry_date: dismissed.entry_date,
|
||||
via: 'allow_duplicate',
|
||||
},
|
||||
actor: { type: 'user', id: userId },
|
||||
occurredAt: new Date(),
|
||||
})
|
||||
}
|
||||
} catch (logErr) {
|
||||
log.warn('failed to record duplicate-dismissal behandlingshistorik', logErr)
|
||||
}
|
||||
}
|
||||
|
||||
const isBusiness = category !== 'private'
|
||||
|
||||
const { data: settings } = await supabase
|
||||
.from('company_settings').select('entity_type, fiscal_year_start_month').eq('company_id', companyId).single()
|
||||
|
||||
const entityType: EntityType = (settings?.entity_type as EntityType) || 'enskild_firma'
|
||||
const fiscalYearStartMonth = settings?.fiscal_year_start_month ?? 1
|
||||
|
||||
const mappingResult = buildMappingResultFromCategory(
|
||||
category, transaction as Transaction, isBusiness, entityType, vatTreatment, vatAmount
|
||||
)
|
||||
|
||||
if (!mappingResult.debit_account || !mappingResult.credit_account) {
|
||||
return { error: `No account mapping for category "${category}" with entity type "${entityType}".`, status: 400 }
|
||||
}
|
||||
|
||||
await ensureFiscalPeriod(supabase, userId, companyId, transaction.date, fiscalYearStartMonth)
|
||||
|
||||
let journalEntryId: string | null = null
|
||||
try {
|
||||
const journalEntry = await createTransactionJournalEntry(
|
||||
supabase, companyId, userId, transaction as Transaction, mappingResult, notes,
|
||||
)
|
||||
if (journalEntry) journalEntryId = journalEntry.id
|
||||
} catch (err) {
|
||||
if (isBookkeepingError(err)) throw err
|
||||
log.error('Failed to create journal entry:', err)
|
||||
return { error: err instanceof Error ? err.message : 'Failed to create journal entry', status: 500 }
|
||||
}
|
||||
|
||||
const { error: updateError } = await supabase
|
||||
.from('transactions')
|
||||
.update({ is_business: isBusiness, category, journal_entry_id: journalEntryId })
|
||||
.eq('id', txId)
|
||||
|
||||
if (updateError) {
|
||||
log.error('Failed to update transaction:', updateError)
|
||||
return { error: 'Failed to update transaction', status: 500 }
|
||||
}
|
||||
|
||||
// Propagate the underlag from a matched invoice-inbox item onto the new
|
||||
// verifikation. Without this, BFL 7 kap is violated: a verifikation
|
||||
// exists with no underlag attached even though the user has explicitly
|
||||
// linked an inbox item (with a document) to this transaction in the
|
||||
// inbox workspace. We:
|
||||
// 1. find the inbox item(s) where matched_transaction_id = txId
|
||||
// 2. for each item with a document_id, set
|
||||
// document_attachments.journal_entry_id = journalEntryId
|
||||
// (idempotent — re-linking the same doc is a no-op write).
|
||||
// 3. stamp invoice_inbox_items.created_journal_entry_id so the inbox
|
||||
// row visibly moves to "Bearbetade" and shows "Öppna verifikation".
|
||||
// Errors are logged but don't fail the commit — the verifikation itself
|
||||
// is already posted, and the link can be repaired by re-running this
|
||||
// step. A future PR can move this into a single transaction with the
|
||||
// journal entry creation.
|
||||
if (journalEntryId) {
|
||||
try {
|
||||
const { data: matchedInboxItems } = await supabase
|
||||
.from('invoice_inbox_items')
|
||||
.select('id, document_id')
|
||||
.eq('company_id', companyId)
|
||||
.eq('matched_transaction_id', txId)
|
||||
.is('created_journal_entry_id', null)
|
||||
for (const inbox of (matchedInboxItems ?? []) as Array<{
|
||||
id: string
|
||||
document_id: string | null
|
||||
}>) {
|
||||
if (inbox.document_id) {
|
||||
try {
|
||||
await linkToJournalEntry(supabase, companyId, inbox.document_id, journalEntryId)
|
||||
} catch (err) {
|
||||
log.error('Failed to link inbox document to journal entry', {
|
||||
inbox_item_id: inbox.id,
|
||||
document_id: inbox.document_id,
|
||||
journal_entry_id: journalEntryId,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
})
|
||||
}
|
||||
}
|
||||
const { error: stampError } = await supabase
|
||||
.from('invoice_inbox_items')
|
||||
.update({ created_journal_entry_id: journalEntryId })
|
||||
.eq('id', inbox.id)
|
||||
.eq('company_id', companyId)
|
||||
if (stampError) {
|
||||
log.error('Failed to stamp inbox item created_journal_entry_id', {
|
||||
inbox_item_id: inbox.id,
|
||||
journal_entry_id: journalEntryId,
|
||||
error: stampError.message,
|
||||
})
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
log.error('Failed to propagate underlag from matched inbox items', err)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await upsertCounterpartyTemplate(
|
||||
supabase, userId, transaction as Transaction, mappingResult, 'user_approved'
|
||||
)
|
||||
} catch { /* non-critical */ }
|
||||
|
||||
await eventBus.emit({
|
||||
type: 'transaction.categorized',
|
||||
payload: {
|
||||
transaction: transaction as Transaction,
|
||||
account: mappingResult.debit_account,
|
||||
taxCode: mappingResult.vat_lines[0]?.account_number || '',
|
||||
userId,
|
||||
companyId,
|
||||
},
|
||||
// Booking, the duplicate guard, VAT mapping, and matched-inbox underlag
|
||||
// propagation all live in the shared core (lib/transactions/categorize-core.ts)
|
||||
// so the bulk-book-inbox executor and the Underlag "Bokför valda" route reuse
|
||||
// exactly this logic.
|
||||
return categorizeMatchedTransaction(supabase, userId, companyId, txId, {
|
||||
category,
|
||||
vatTreatment,
|
||||
vatAmount,
|
||||
notes,
|
||||
allowDuplicate: params.allow_duplicate === true,
|
||||
})
|
||||
|
||||
return { data: { journal_entry_id: journalEntryId, category } }
|
||||
}
|
||||
|
||||
async function commitCreateCustomer(
|
||||
@@ -3578,6 +3331,48 @@ async function commitBulkBookTransactions(
|
||||
return { data: result as unknown as Record<string, unknown>, status: 200 }
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulk-book selected Underlag (Dokumentinkorgen) — Lena-driven flow. Each
|
||||
* selected inbox item is booked against its matched bank transaction using one
|
||||
* shared category + VAT treatment. The booking, VAT (incl. reverse charge), and
|
||||
* underlag→verifikat propagation are the SAME shared core the single-item
|
||||
* categorize path uses (categorizeMatchedTransaction). Items that can't be
|
||||
* booked are skipped with a reason rather than failing the whole batch — the
|
||||
* "Bokför valda hoppar över" contract. A per-item throw (e.g. period locked,
|
||||
* accounts not in chart) is caught and recorded as a skip so one bad underlag
|
||||
* never blocks the rest.
|
||||
*/
|
||||
async function commitBulkBookInboxItems(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
params: Record<string, unknown>
|
||||
): Promise<ExecutorResult> {
|
||||
const parsed = BulkBookInboxSchema.safeParse(params)
|
||||
if (!parsed.success) {
|
||||
return { error: `Invalid bulk_book_inbox_items params: ${parsed.error.message}`, status: 400 }
|
||||
}
|
||||
|
||||
const { booked, skipped } = await bulkBookMatchedInboxItems(supabase, userId, companyId, parsed.data)
|
||||
|
||||
log.info('bulk_book_inbox_items committed', {
|
||||
companyId,
|
||||
operationType: 'bulk_book_inbox_items',
|
||||
requested: parsed.data.item_ids.length,
|
||||
bookedCount: booked.length,
|
||||
skippedCount: skipped.length,
|
||||
})
|
||||
|
||||
return {
|
||||
data: {
|
||||
booked_count: booked.length,
|
||||
skipped_count: skipped.length,
|
||||
booked,
|
||||
skipped,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function commitLinkTransactionJournalEntry(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
@@ -3827,6 +3622,9 @@ async function commitPendingOperationInner(
|
||||
case 'bulk_book_transactions':
|
||||
result = await commitBulkBookTransactions(supabase, companyId, pendingOp.params)
|
||||
break
|
||||
case 'bulk_book_inbox_items':
|
||||
result = await commitBulkBookInboxItems(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
case 'link_transaction_journal_entry':
|
||||
result = await commitLinkTransactionJournalEntry(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
|
||||
@@ -118,6 +118,12 @@ export const OPERATION_RISK_TIERS: Record<string, RiskLevel> = {
|
||||
// a verifikat with caller-supplied lines (template-expanded or manual),
|
||||
// the same compliance-critical surface as create_voucher. 'high'.
|
||||
bulk_book_transactions: 'high',
|
||||
// Bulk-book N selected Underlag (Dokumentinkorgen): one posted verifikat per
|
||||
// matched bank transaction, each with VAT (incl. reverse charge) derived from
|
||||
// a shared category. Posting N verifikat at once is the same compliance-
|
||||
// critical surface as bulk_book_transactions, so 'high' — never auto-commit;
|
||||
// approval requires confirmed=true.
|
||||
bulk_book_inbox_items: 'high',
|
||||
// Link a single bank tx to an already-posted verifikat (no new JE created).
|
||||
// Reversible by clearing transactions.journal_entry_id and deleting any
|
||||
// invoice_payments row — sits next to link_invoice_voucher semantically;
|
||||
|
||||
@@ -497,6 +497,7 @@ describe('generateSIEExport', () => {
|
||||
{ data: null, error: null }, // prevPeriod
|
||||
{ data: [], error: null }, // accounts
|
||||
{
|
||||
// journal_entries (fetchAllRows) — no embedded lines; stitched below
|
||||
data: [
|
||||
// The OB entry itself — must be excluded from movement/VER output
|
||||
{
|
||||
@@ -506,10 +507,6 @@ describe('generateSIEExport', () => {
|
||||
voucher_series: 'A',
|
||||
description: 'IB 2024',
|
||||
status: 'posted',
|
||||
lines: [
|
||||
{ account_number: '1933', debit_amount: 96466.59, credit_amount: 0, line_description: 'IB 1933', cost_center: null, project: null },
|
||||
{ account_number: '2019', debit_amount: 0, credit_amount: 96466.59, line_description: null, cost_center: null, project: null },
|
||||
],
|
||||
},
|
||||
// A real transaction: account 1933 swept to 1930
|
||||
{
|
||||
@@ -519,10 +516,6 @@ describe('generateSIEExport', () => {
|
||||
voucher_series: 'A',
|
||||
description: 'Stängning Bokio',
|
||||
status: 'posted',
|
||||
lines: [
|
||||
{ account_number: '1930', debit_amount: 96466.59, credit_amount: 0, line_description: null, cost_center: null, project: null },
|
||||
{ account_number: '1933', debit_amount: 0, credit_amount: 96466.59, line_description: null, cost_center: null, project: null },
|
||||
],
|
||||
},
|
||||
],
|
||||
error: null,
|
||||
|
||||
@@ -129,6 +129,30 @@ describe('detectBookedDuplicateTransaction', () => {
|
||||
})
|
||||
expect(result?.transaction_id).toBe('sib-2')
|
||||
})
|
||||
|
||||
// ── Intra-batch exclusion (bulk-book false-positive fix) ────────────────
|
||||
it('excludes a same-batch sibling whose id is in excludeTransactionIds', async () => {
|
||||
const supabase = makeSupabase([sibling({ id: 'sib-batch' })])
|
||||
const result = await detectBookedDuplicateTransaction(
|
||||
supabase,
|
||||
COMPANY,
|
||||
{ id: 'self', date: '2025-12-19', amount: -1616, cash_account_id: null },
|
||||
{ excludeTransactionIds: ['sib-batch'] },
|
||||
)
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('STILL flags a pre-existing sibling not in excludeTransactionIds (invariant preserved)', async () => {
|
||||
// 'sib-old' existed before the batch; only 'sib-batch' was booked this run.
|
||||
const supabase = makeSupabase([sibling({ id: 'sib-old' })])
|
||||
const result = await detectBookedDuplicateTransaction(
|
||||
supabase,
|
||||
COMPANY,
|
||||
{ id: 'self', date: '2025-12-19', amount: -1616, cash_account_id: null },
|
||||
{ excludeTransactionIds: ['sib-batch'] },
|
||||
)
|
||||
expect(result?.transaction_id).toBe('sib-old')
|
||||
})
|
||||
})
|
||||
|
||||
// ── Ledger-only voucher guard (the orphan with no sibling transaction) ───────
|
||||
@@ -305,6 +329,29 @@ describe('detectLedgerDuplicateVoucher', () => {
|
||||
})
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
// ── Intra-batch exclusion (bulk-book false-positive fix) ────────────────
|
||||
it('excludes a same-batch voucher whose journal_entry.id is in excludeJournalEntryIds', async () => {
|
||||
const supabase = makeLedgerSupabase({ lines: [jel()] }) // jel() → journal_entry.id 'je-2'
|
||||
const result = await detectLedgerDuplicateVoucher(
|
||||
supabase,
|
||||
COMPANY,
|
||||
{ id: 'self', date: '2026-03-26', amount: 98565, cash_account_id: null },
|
||||
{ excludeJournalEntryIds: ['je-2'] },
|
||||
)
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('STILL flags a pre-existing voucher not in excludeJournalEntryIds (invariant preserved)', async () => {
|
||||
const supabase = makeLedgerSupabase({ lines: [jel()] })
|
||||
const result = await detectLedgerDuplicateVoucher(
|
||||
supabase,
|
||||
COMPANY,
|
||||
{ id: 'self', date: '2026-03-26', amount: 98565, cash_account_id: null },
|
||||
{ excludeJournalEntryIds: ['je-booked-this-batch'] },
|
||||
)
|
||||
expect(result?.journal_entry_id).toBe('je-2')
|
||||
})
|
||||
})
|
||||
|
||||
describe('detectBookingDuplicate (orchestrator)', () => {
|
||||
@@ -332,4 +379,20 @@ describe('detectBookingDuplicate (orchestrator)', () => {
|
||||
})
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('propagates exclusions to BOTH the sibling scan and the ledger scan', async () => {
|
||||
// A matching sibling AND a matching ledger voucher exist, but both belong to
|
||||
// this same batch (excluded) → the orchestrator must report no duplicate.
|
||||
const supabase = makeLedgerSupabase({
|
||||
transactionRows: [sibling({ id: 'sib-batch', amount: 98565, journal_entry_id: 'je-sib' })],
|
||||
lines: [jel()], // journal_entry.id 'je-2'
|
||||
})
|
||||
const result = await detectBookingDuplicate(
|
||||
supabase,
|
||||
COMPANY,
|
||||
{ id: 'self', date: '2026-03-26', amount: 98565, cash_account_id: null },
|
||||
{ excludeTransactionIds: ['sib-batch'], excludeJournalEntryIds: ['je-2'] },
|
||||
)
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
/**
|
||||
* Bulk-book Underlag (Modell B) core logic.
|
||||
*
|
||||
* `bulkBookMatchedInboxItems` is shared by the direct UI route
|
||||
* (POST /items/bulk-book) and the `bulk_book_inbox_items` pending-operation
|
||||
* executor. These tests pin the "Bokför valda hoppar över" contract — items
|
||||
* that aren't matched / already booked / linked to a leverantörsfaktura are
|
||||
* SKIPPED, never errored — and the happy path where a matched item is booked
|
||||
* against its transaction via the shared categorize core.
|
||||
*
|
||||
* The single-item categorize core itself (createJE, duplicate guard, VAT
|
||||
* mapping, underlag propagation) is covered by
|
||||
* lib/pending-operations/__tests__/commit-duplicate-guard.test.ts and the
|
||||
* inbox-link pg tests; here we mock its downstream modules and assert the
|
||||
* loop's classification + collection.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
const mockCreateJE = vi.fn()
|
||||
const mockDetectDup = vi.fn()
|
||||
const mockMapping = vi.fn()
|
||||
const mockUpsertTemplate = vi.fn()
|
||||
const mockLinkToJE = vi.fn()
|
||||
|
||||
vi.mock('@/lib/bookkeeping/transaction-entries', () => ({
|
||||
createTransactionJournalEntry: (...args: unknown[]) => mockCreateJE(...args),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/booking-duplicate-detection', () => ({
|
||||
detectBookingDuplicate: (...args: unknown[]) => mockDetectDup(...args),
|
||||
}))
|
||||
vi.mock('@/lib/bookkeeping/category-mapping', () => ({
|
||||
buildMappingResultFromCategory: (...args: unknown[]) => mockMapping(...args),
|
||||
}))
|
||||
vi.mock('@/lib/bookkeeping/counterparty-templates', () => ({
|
||||
upsertCounterpartyTemplate: (...args: unknown[]) => mockUpsertTemplate(...args),
|
||||
}))
|
||||
vi.mock('@/lib/core/documents/document-service', () => ({
|
||||
linkToJournalEntry: (...args: unknown[]) => mockLinkToJE(...args),
|
||||
}))
|
||||
|
||||
import { bulkBookMatchedInboxItems } from '../categorize-core'
|
||||
import { BulkBookInboxSchema } from '@/lib/api/schemas'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
|
||||
/** Queue-based supabase mock: each `from()` consumes the next queued result. */
|
||||
function queuedSupabase(results: Array<{ data?: unknown; error?: unknown }>) {
|
||||
const queue = [...results]
|
||||
const from = vi.fn(() => {
|
||||
const raw = queue.shift() ?? { data: null, error: null }
|
||||
const result = { data: raw.data ?? null, error: raw.error ?? null }
|
||||
const chain: object = new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_t, prop) {
|
||||
if (prop === 'then') return (resolve: (v: unknown) => void) => resolve(result)
|
||||
return () => chain
|
||||
},
|
||||
},
|
||||
)
|
||||
return chain
|
||||
})
|
||||
return { from } as never
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
mockDetectDup.mockResolvedValue(null)
|
||||
mockMapping.mockReturnValue({
|
||||
rule: null,
|
||||
debit_account: '5420',
|
||||
credit_account: '1930',
|
||||
risk_level: 'LOW',
|
||||
confidence: 1,
|
||||
requires_review: false,
|
||||
default_private: false,
|
||||
vat_lines: [],
|
||||
description: 'Programvara',
|
||||
})
|
||||
mockCreateJE.mockResolvedValue({ id: 'je-1' })
|
||||
})
|
||||
|
||||
describe('BulkBookInboxSchema', () => {
|
||||
it('accepts a valid payload', () => {
|
||||
const r = BulkBookInboxSchema.safeParse({
|
||||
item_ids: ['11111111-1111-4111-8111-111111111111'],
|
||||
category: 'expense_software',
|
||||
vat_treatment: 'reverse_charge',
|
||||
})
|
||||
expect(r.success).toBe(true)
|
||||
})
|
||||
|
||||
// Regression: the bulk_book_inbox_items pending operation persists absent
|
||||
// optionals as explicit JSON null (stagePendingOperation in server.ts). A bare
|
||||
// `.optional()` rejected those on approval ("expected number, received null").
|
||||
it('accepts persisted params with explicit nulls and normalizes them to undefined', () => {
|
||||
const r = BulkBookInboxSchema.safeParse({
|
||||
item_ids: ['11111111-1111-4111-8111-111111111111'],
|
||||
category: 'expense_software',
|
||||
vat_treatment: null,
|
||||
vat_amount: null,
|
||||
notes: null,
|
||||
allow_duplicate: false,
|
||||
})
|
||||
expect(r.success).toBe(true)
|
||||
if (r.success) {
|
||||
// null must not leak downstream to categorizeMatchedTransaction.
|
||||
expect(r.data.vat_treatment).toBeUndefined()
|
||||
expect(r.data.vat_amount).toBeUndefined()
|
||||
expect(r.data.notes).toBeUndefined()
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects an empty item_ids array', () => {
|
||||
const r = BulkBookInboxSchema.safeParse({ item_ids: [], category: 'expense_software' })
|
||||
expect(r.success).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects a missing category', () => {
|
||||
const r = BulkBookInboxSchema.safeParse({ item_ids: ['11111111-1111-1111-1111-111111111111'] })
|
||||
expect(r.success).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects an invalid category', () => {
|
||||
const r = BulkBookInboxSchema.safeParse({
|
||||
item_ids: ['11111111-1111-1111-1111-111111111111'],
|
||||
category: 'expense_unicorns',
|
||||
})
|
||||
expect(r.success).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects an invalid vat_treatment', () => {
|
||||
const r = BulkBookInboxSchema.safeParse({
|
||||
item_ids: ['11111111-1111-1111-1111-111111111111'],
|
||||
category: 'expense_software',
|
||||
vat_treatment: 'omvänd',
|
||||
})
|
||||
expect(r.success).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects more than 200 items', () => {
|
||||
const ids = Array.from({ length: 201 }, (_, i) => `id-${i}`)
|
||||
const r = BulkBookInboxSchema.safeParse({ item_ids: ids, category: 'expense_software' })
|
||||
expect(r.success).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('bulkBookMatchedInboxItems — skip classification (never errors)', () => {
|
||||
const base = { category: 'expense_software' as const }
|
||||
|
||||
it('skips an item that is not found', async () => {
|
||||
const supabase = queuedSupabase([{ data: null }])
|
||||
const { booked, skipped } = await bulkBookMatchedInboxItems(supabase, 'u1', 'c1', {
|
||||
...base,
|
||||
item_ids: ['missing'],
|
||||
})
|
||||
expect(booked).toEqual([])
|
||||
expect(skipped).toEqual([{ item_id: 'missing', reason: 'not_found' }])
|
||||
expect(mockCreateJE).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('skips an item already booked (created_journal_entry_id)', async () => {
|
||||
const supabase = queuedSupabase([
|
||||
{ data: { id: 'i1', matched_transaction_id: 'tx-1', created_journal_entry_id: 'je-x', created_supplier_invoice_id: null } },
|
||||
])
|
||||
const { booked, skipped } = await bulkBookMatchedInboxItems(supabase, 'u1', 'c1', { ...base, item_ids: ['i1'] })
|
||||
expect(booked).toEqual([])
|
||||
expect(skipped).toEqual([{ item_id: 'i1', reason: 'already_booked' }])
|
||||
expect(mockCreateJE).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('skips an item linked to a supplier invoice', async () => {
|
||||
const supabase = queuedSupabase([
|
||||
{ data: { id: 'i1', matched_transaction_id: 'tx-1', created_journal_entry_id: null, created_supplier_invoice_id: 'si-x' } },
|
||||
])
|
||||
const { booked, skipped } = await bulkBookMatchedInboxItems(supabase, 'u1', 'c1', { ...base, item_ids: ['i1'] })
|
||||
expect(booked).toEqual([])
|
||||
expect(skipped).toEqual([{ item_id: 'i1', reason: 'is_supplier_invoice' }])
|
||||
expect(mockCreateJE).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('skips an item without a matched transaction', async () => {
|
||||
const supabase = queuedSupabase([
|
||||
{ data: { id: 'i1', matched_transaction_id: null, created_journal_entry_id: null, created_supplier_invoice_id: null } },
|
||||
])
|
||||
const { booked, skipped } = await bulkBookMatchedInboxItems(supabase, 'u1', 'c1', { ...base, item_ids: ['i1'] })
|
||||
expect(booked).toEqual([])
|
||||
expect(skipped).toEqual([{ item_id: 'i1', reason: 'not_matched' }])
|
||||
expect(mockCreateJE).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('bulkBookMatchedInboxItems — booking', () => {
|
||||
it('books a matched, unbooked item against its transaction', async () => {
|
||||
const supabase = queuedSupabase([
|
||||
// 1. inbox item fetch → bookable
|
||||
{ data: { id: 'i1', matched_transaction_id: 'tx-1', created_journal_entry_id: null, created_supplier_invoice_id: null } },
|
||||
// 2. transactions fetch (categorize core)
|
||||
{ data: { id: 'tx-1', date: '2026-06-01', amount: -700.28, currency: 'SEK', cash_account_id: null, journal_entry_id: null } },
|
||||
// 3. company_settings
|
||||
{ data: { entity_type: 'aktiebolag', fiscal_year_start_month: 1 } },
|
||||
// 4. ensureFiscalPeriod → existing period
|
||||
{ data: [{ id: 'fp-1' }] },
|
||||
// 5. transactions update (mark booked)
|
||||
{ error: null },
|
||||
// 6. propagation select (no matched inbox rows to stamp in this mock)
|
||||
{ data: [] },
|
||||
])
|
||||
|
||||
const { booked, skipped } = await bulkBookMatchedInboxItems(supabase, 'u1', 'c1', {
|
||||
item_ids: ['i1'],
|
||||
category: 'expense_software',
|
||||
vat_treatment: 'reverse_charge',
|
||||
})
|
||||
|
||||
expect(skipped).toEqual([])
|
||||
expect(booked).toEqual([{ item_id: 'i1', transaction_id: 'tx-1', journal_entry_id: 'je-1' }])
|
||||
expect(mockCreateJE).toHaveBeenCalledTimes(1)
|
||||
// The shared core received the chosen category + reverse-charge treatment.
|
||||
expect(mockMapping).toHaveBeenCalledWith(
|
||||
'expense_software',
|
||||
expect.objectContaining({ id: 'tx-1' }),
|
||||
true,
|
||||
'aktiebolag',
|
||||
'reverse_charge',
|
||||
undefined,
|
||||
)
|
||||
})
|
||||
|
||||
it('books the matched item and skips the unmatched one in a mixed batch', async () => {
|
||||
const supabase = queuedSupabase([
|
||||
// item i1 → not matched (1 from())
|
||||
{ data: { id: 'i1', matched_transaction_id: null, created_journal_entry_id: null, created_supplier_invoice_id: null } },
|
||||
// item i2 → bookable, then its categorize chain
|
||||
{ data: { id: 'i2', matched_transaction_id: 'tx-2', created_journal_entry_id: null, created_supplier_invoice_id: null } },
|
||||
{ data: { id: 'tx-2', date: '2026-06-02', amount: -25, currency: 'SEK', cash_account_id: null, journal_entry_id: null } },
|
||||
{ data: { entity_type: 'aktiebolag', fiscal_year_start_month: 1 } },
|
||||
{ data: [{ id: 'fp-1' }] },
|
||||
{ error: null },
|
||||
{ data: [] },
|
||||
])
|
||||
|
||||
const { booked, skipped } = await bulkBookMatchedInboxItems(supabase, 'u1', 'c1', {
|
||||
item_ids: ['i1', 'i2'],
|
||||
category: 'expense_software',
|
||||
})
|
||||
|
||||
expect(skipped).toEqual([{ item_id: 'i1', reason: 'not_matched' }])
|
||||
expect(booked).toEqual([{ item_id: 'i2', transaction_id: 'tx-2', journal_entry_id: 'je-1' }])
|
||||
expect(mockCreateJE).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('bulkBookMatchedInboxItems — intra-batch duplicate handling', () => {
|
||||
/** Six queued from() results for one successfully-booked item. */
|
||||
const bookableItem = (itemId: string, txId: string, amount: number) => [
|
||||
{ data: { id: itemId, matched_transaction_id: txId, created_journal_entry_id: null, created_supplier_invoice_id: null } },
|
||||
{ data: { id: txId, date: '2026-06-01', amount, currency: 'SEK', cash_account_id: null, journal_entry_id: null } },
|
||||
{ data: { entity_type: 'aktiebolag', fiscal_year_start_month: 1 } },
|
||||
{ data: [{ id: 'fp-1' }] },
|
||||
{ error: null },
|
||||
{ data: [] },
|
||||
]
|
||||
|
||||
it('books BOTH distinct transactions that share (date, amount) in one bulk run', async () => {
|
||||
// Model the reviewer-reported bug: the guard WOULD flag the second tx as a
|
||||
// duplicate of the first tx's freshly-created verifikat — but only when the
|
||||
// first tx is NOT excluded as a same-batch sibling. The fix must pass tx-1
|
||||
// in as an exclusion so tx-2 books instead of being skipped 409.
|
||||
mockDetectDup.mockImplementation(
|
||||
(_sb: unknown, _co: unknown, target: { id: string }, exclude?: { excludeTransactionIds?: string[] }) => {
|
||||
if (target.id === 'tx-2' && !(exclude?.excludeTransactionIds ?? []).includes('tx-1')) {
|
||||
return Promise.resolve({
|
||||
transaction_id: 'tx-1', journal_entry_id: 'je-1', voucher_label: 'A1',
|
||||
entry_date: '2026-06-01', description: null, amount: 700.28,
|
||||
})
|
||||
}
|
||||
return Promise.resolve(null)
|
||||
},
|
||||
)
|
||||
|
||||
const supabase = queuedSupabase([
|
||||
...bookableItem('i1', 'tx-1', -700.28),
|
||||
...bookableItem('i2', 'tx-2', -700.28),
|
||||
])
|
||||
|
||||
const { booked, skipped } = await bulkBookMatchedInboxItems(supabase, 'u1', 'c1', {
|
||||
item_ids: ['i1', 'i2'],
|
||||
category: 'expense_software',
|
||||
})
|
||||
|
||||
expect(skipped).toEqual([])
|
||||
expect(booked).toEqual([
|
||||
{ item_id: 'i1', transaction_id: 'tx-1', journal_entry_id: 'je-1' },
|
||||
{ item_id: 'i2', transaction_id: 'tx-2', journal_entry_id: 'je-1' },
|
||||
])
|
||||
expect(mockCreateJE).toHaveBeenCalledTimes(2)
|
||||
|
||||
// The SECOND booking was handed tx-1 (and its verifikat) as an intra-batch
|
||||
// exclusion; the first was handed an empty set.
|
||||
const firstCall = mockDetectDup.mock.calls.find((c) => (c[2] as { id: string }).id === 'tx-1')
|
||||
const secondCall = mockDetectDup.mock.calls.find((c) => (c[2] as { id: string }).id === 'tx-2')
|
||||
expect(firstCall?.[3]).toEqual({ excludeTransactionIds: [], excludeJournalEntryIds: [] })
|
||||
expect(secondCall?.[3]).toEqual({ excludeTransactionIds: ['tx-1'], excludeJournalEntryIds: ['je-1'] })
|
||||
})
|
||||
|
||||
it('STILL skips a pre-existing already-booked duplicate (cross-batch detection preserved)', async () => {
|
||||
// The guard fires on a duplicate that existed BEFORE this batch: its ids are
|
||||
// absent from the (empty) exclusion set, so the booking is refused (409) and
|
||||
// the item is skipped as a possible duplicate rather than double-booked.
|
||||
mockDetectDup.mockResolvedValue({
|
||||
transaction_id: 'tx-preexisting', journal_entry_id: 'je-old', voucher_label: 'A9',
|
||||
entry_date: '2026-06-01', description: null, amount: 700.28,
|
||||
})
|
||||
|
||||
const supabase = queuedSupabase([
|
||||
{ data: { id: 'i1', matched_transaction_id: 'tx-1', created_journal_entry_id: null, created_supplier_invoice_id: null } },
|
||||
{ data: { id: 'tx-1', date: '2026-06-01', amount: -700.28, currency: 'SEK', cash_account_id: null, journal_entry_id: null } },
|
||||
])
|
||||
|
||||
const { booked, skipped } = await bulkBookMatchedInboxItems(supabase, 'u1', 'c1', {
|
||||
item_ids: ['i1'],
|
||||
category: 'expense_software',
|
||||
})
|
||||
|
||||
expect(booked).toEqual([])
|
||||
expect(skipped).toHaveLength(1)
|
||||
expect(skipped[0].item_id).toBe('i1')
|
||||
expect(skipped[0].reason).toBe('already_booked_or_duplicate')
|
||||
expect(mockCreateJE).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -56,6 +56,28 @@ export interface BookingTarget {
|
||||
cash_account_id?: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Same-batch siblings to exclude from booking-time duplicate detection.
|
||||
*
|
||||
* When a bulk run books several DISTINCT bank movements that happen to share a
|
||||
* (date, amount, cash account) — several identical Swish transfers the user
|
||||
* explicitly selected — the second booking must NOT dedupe against the first
|
||||
* booking's freshly-created verifikat: they are separate affärshändelser. The
|
||||
* bulk driver accumulates the ids it has booked so far in THIS batch and passes
|
||||
* them here so intra-batch siblings never flag one another.
|
||||
*
|
||||
* CRITICAL: only ids created within the current batch belong here. A duplicate
|
||||
* that existed BEFORE the batch has neither its transaction id nor its voucher
|
||||
* id in these lists, so it is STILL detected and skipped. Both fields are
|
||||
* optional; the default (no exclusion) keeps single-booking callers unaffected.
|
||||
*/
|
||||
export interface BookingDuplicateExclusions {
|
||||
/** Sibling transaction ids booked earlier in the same bulk run. */
|
||||
excludeTransactionIds?: string[]
|
||||
/** Journal-entry ids minted earlier in the same bulk run. */
|
||||
excludeJournalEntryIds?: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an already-booked sibling transaction sharing (date, amount, account).
|
||||
* Returns the single best candidate, or null.
|
||||
@@ -73,9 +95,13 @@ export async function detectBookedDuplicateTransaction(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
target: BookingTarget,
|
||||
opts?: BookingDuplicateExclusions,
|
||||
): Promise<BookedDuplicateCandidate | null> {
|
||||
const targetOre = toOre(target.amount)
|
||||
if (targetOre === 0 || Number.isNaN(targetOre)) return null
|
||||
// Siblings booked earlier in this same bulk run are distinct events the user
|
||||
// selected, not duplicates — never flag one against another.
|
||||
const excludeTransactionIds = new Set(opts?.excludeTransactionIds ?? [])
|
||||
|
||||
// Same company, same date, already booked, not the target row itself. The
|
||||
// amount and account match is applied in JS so a numeric-string amount from
|
||||
@@ -101,6 +127,7 @@ export async function detectBookedDuplicateTransaction(
|
||||
}
|
||||
const targetAccount = target.cash_account_id ?? null
|
||||
const matches = (data as unknown as Row[]).filter((r) => {
|
||||
if (excludeTransactionIds.has(r.id)) return false
|
||||
if (toOre(r.amount) !== targetOre) return false
|
||||
// Account guard: both-known must match; a null on either side is compatible.
|
||||
if (targetAccount !== null && r.cash_account_id !== null && r.cash_account_id !== targetAccount) {
|
||||
@@ -179,9 +206,13 @@ export async function detectLedgerDuplicateVoucher(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
target: BookingTarget,
|
||||
opts?: BookingDuplicateExclusions,
|
||||
): Promise<BookedDuplicateCandidate | null> {
|
||||
const targetOre = toOre(target.amount)
|
||||
if (targetOre === 0 || Number.isNaN(targetOre)) return null
|
||||
// Vouchers minted earlier in this same bulk run are this batch's own fresh
|
||||
// bookings — a subsequent sibling must not dedupe against them.
|
||||
const excludeJournalEntryIds = new Set(opts?.excludeJournalEntryIds ?? [])
|
||||
const targetAmount = roundOre(Math.abs(Number(target.amount)))
|
||||
const inbound = targetOre > 0
|
||||
|
||||
@@ -251,6 +282,8 @@ export async function detectLedgerDuplicateVoucher(
|
||||
}
|
||||
}
|
||||
const candidates = (lines as unknown as LineRow[])
|
||||
// Same-batch vouchers are this run's own fresh bookings, never duplicates.
|
||||
.filter((l) => !excludeJournalEntryIds.has(l.journal_entry.id))
|
||||
.filter((l) => {
|
||||
const legAmount = roundOre(Number(inbound ? l.debit_amount : l.credit_amount))
|
||||
return Math.abs(legAmount - targetAmount) < 0.01
|
||||
@@ -309,8 +342,9 @@ export async function detectBookingDuplicate(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
target: BookingTarget,
|
||||
opts?: BookingDuplicateExclusions,
|
||||
): Promise<BookedDuplicateCandidate | null> {
|
||||
const sibling = await detectBookedDuplicateTransaction(supabase, companyId, target)
|
||||
const sibling = await detectBookedDuplicateTransaction(supabase, companyId, target, opts)
|
||||
if (sibling) return sibling
|
||||
return detectLedgerDuplicateVoucher(supabase, companyId, target)
|
||||
return detectLedgerDuplicateVoucher(supabase, companyId, target, opts)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,465 @@
|
||||
/**
|
||||
* Shared core for booking a bank transaction by category.
|
||||
*
|
||||
* This is the single implementation behind three callers:
|
||||
* 1. The single-transaction approval executor `commitCategorizeTransaction`
|
||||
* (lib/pending-operations/commit.ts) — the agent / web "Kategorisera"
|
||||
* flow.
|
||||
* 2. The bulk-book-inbox executor `commitBulkBookInboxItems`
|
||||
* (lib/pending-operations/commit.ts) — Lena driving the Underlag view.
|
||||
* 3. The direct UI bulk-book route (`POST /items/bulk-book` in the
|
||||
* invoice-inbox extension) — the "Bokför valda" button.
|
||||
*
|
||||
* Extracting it keeps the VAT/mapping logic, the duplicate guard, and the
|
||||
* matched-inbox underlag propagation in ONE place. "Booking an underlag" in the
|
||||
* Dokumentinkorgen is implemented as categorizing the bank transaction it is
|
||||
* matched to: `buildMappingResultFromCategory` produces correct accounts +
|
||||
* reverse-charge VAT, and the propagation step below attaches the underlag to
|
||||
* the new verifikation (BFL 7 kap) and stamps the inbox item resolved.
|
||||
*
|
||||
* Booking is always in SEK off the bank transaction's own amount (BFL 5 kap
|
||||
* 2§), so the foreign-currency underlag never needs an FX step here — the bank
|
||||
* already settled it.
|
||||
*/
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { buildMappingResultFromCategory } from '@/lib/bookkeeping/category-mapping'
|
||||
import { createTransactionJournalEntry } from '@/lib/bookkeeping/transaction-entries'
|
||||
import { upsertCounterpartyTemplate } from '@/lib/bookkeeping/counterparty-templates'
|
||||
import { isBookkeepingError } from '@/lib/bookkeeping/errors'
|
||||
import { linkToJournalEntry } from '@/lib/core/documents/document-service'
|
||||
import { detectBookingDuplicate, type BookingDuplicateExclusions } from '@/lib/transactions/booking-duplicate-detection'
|
||||
import { appendProcessingHistory } from '@/lib/processing-history/append'
|
||||
import { roundOre } from '@/lib/money'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import type { Transaction, TransactionCategory, EntityType, VatTreatment } from '@/types'
|
||||
|
||||
const log = createLogger('transactions/categorize-core')
|
||||
|
||||
/** Structurally compatible with the commit.ts `ExecutorResult`. */
|
||||
export interface CategorizeCoreResult {
|
||||
data?: Record<string, unknown>
|
||||
error?: string
|
||||
status?: number
|
||||
}
|
||||
|
||||
export interface CategorizeMatchedTransactionOpts {
|
||||
category: TransactionCategory
|
||||
vatTreatment?: VatTreatment
|
||||
/**
|
||||
* The underlag's actual VAT when it differs from rate × belopp (e.g. dricks).
|
||||
* Only valid with a rate-based vat_treatment; see buildMappingResultFromCategory.
|
||||
*/
|
||||
vatAmount?: number
|
||||
/** Audit-trail text appended to the verifikation description. */
|
||||
notes?: string
|
||||
/**
|
||||
* Bypass the booking-time duplicate guard. Default false — the guard fails
|
||||
* closed when another verifikat already books this amount on the bank
|
||||
* account, and the caller surfaces the skip.
|
||||
*/
|
||||
allowDuplicate?: boolean
|
||||
}
|
||||
|
||||
// ── Helper: ensure a fiscal period covers the date ──────────────────
|
||||
//
|
||||
// Moved here from lib/pending-operations/commit.ts so the core is
|
||||
// self-contained; commit.ts now imports it from this module.
|
||||
|
||||
export async function ensureFiscalPeriod(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
date: string,
|
||||
fiscalYearStartMonth: number = 1
|
||||
): Promise<boolean> {
|
||||
const { data: existing } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.select('id')
|
||||
.eq('company_id', companyId)
|
||||
.lte('period_start', date)
|
||||
.gte('period_end', date)
|
||||
.eq('is_closed', false)
|
||||
.limit(1)
|
||||
|
||||
if (existing && existing.length > 0) return true
|
||||
|
||||
const txDate = new Date(date)
|
||||
const txMonth = txDate.getMonth() + 1
|
||||
const txYear = txDate.getFullYear()
|
||||
|
||||
let periodStartYear: number
|
||||
if (fiscalYearStartMonth === 1) {
|
||||
periodStartYear = txYear
|
||||
} else if (txMonth >= fiscalYearStartMonth) {
|
||||
periodStartYear = txYear
|
||||
} else {
|
||||
periodStartYear = txYear - 1
|
||||
}
|
||||
|
||||
const startMonth = String(fiscalYearStartMonth).padStart(2, '0')
|
||||
const periodStart = `${periodStartYear}-${startMonth}-01`
|
||||
|
||||
const endYear = fiscalYearStartMonth === 1 ? periodStartYear : periodStartYear + 1
|
||||
const endMonth = fiscalYearStartMonth === 1 ? 12 : fiscalYearStartMonth - 1
|
||||
const lastDay = new Date(endYear, endMonth, 0).getDate()
|
||||
const periodEnd = `${endYear}-${String(endMonth).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`
|
||||
|
||||
const periodName = fiscalYearStartMonth === 1
|
||||
? `Räkenskapsår ${periodStartYear}`
|
||||
: `Räkenskapsår ${periodStartYear}/${endYear}`
|
||||
|
||||
const { error } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.upsert({
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
name: periodName,
|
||||
period_start: periodStart,
|
||||
period_end: periodEnd,
|
||||
}, { onConflict: 'user_id,period_start,period_end' })
|
||||
|
||||
if (error) {
|
||||
log.error('Failed to create fiscal period:', error)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Book a single bank transaction by category. Creates the verifikation, marks
|
||||
* the transaction booked, propagates any matched invoice-inbox underlag onto
|
||||
* the new entry (stamping `created_journal_entry_id` so the inbox row moves to
|
||||
* "Bearbetade"), and records the counterparty template.
|
||||
*
|
||||
* Returns `{ data }` on success or `{ error, status }` on a recoverable
|
||||
* failure (404 missing tx, 409 already booked / possible duplicate, 400 no
|
||||
* mapping, 500 DB). Throws only on AccountsNotInChartError so the caller's
|
||||
* recover-and-retry path stays intact.
|
||||
*/
|
||||
export async function categorizeMatchedTransaction(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
txId: string,
|
||||
opts: CategorizeMatchedTransactionOpts,
|
||||
/**
|
||||
* Same-batch siblings to exclude from the duplicate guard. Only set by the
|
||||
* bulk driver so intra-batch bookings of DISTINCT same-(date,amount) events
|
||||
* never dedupe against one another. Omitted (single-booking callers) = the
|
||||
* full guard runs unchanged.
|
||||
*/
|
||||
exclude?: BookingDuplicateExclusions,
|
||||
): Promise<CategorizeCoreResult> {
|
||||
const { category, vatTreatment, vatAmount, notes, allowDuplicate } = opts
|
||||
|
||||
const { data: transaction, error: fetchError } = await supabase
|
||||
.from('transactions').select('*').eq('id', txId).eq('company_id', companyId).single()
|
||||
|
||||
if (fetchError || !transaction) {
|
||||
return { error: 'Transaction not found — it may have been deleted.', status: 404 }
|
||||
}
|
||||
if (transaction.journal_entry_id) {
|
||||
return { error: 'Transaction already has a journal entry — it was categorized in the meantime.', status: 409 }
|
||||
}
|
||||
|
||||
// Booking-time duplicate guard — parity with the web /categorize route.
|
||||
// Refuse to mint a second verifikat for an affärshändelse already in the
|
||||
// ledger: an already-booked sibling transaction, OR an unlinked voucher that
|
||||
// already books this amount on the bank account (invoice "markera som
|
||||
// betald", the salary run's net-wage payout, a manual verifikat). Fail
|
||||
// closed; the caller re-runs with allowDuplicate=true after the user
|
||||
// confirms the bank line is a genuinely separate event. Fail-open on a
|
||||
// detection error so a transient query failure never blocks a real booking.
|
||||
if (allowDuplicate !== true) {
|
||||
let dup = null
|
||||
try {
|
||||
dup = await detectBookingDuplicate(supabase, companyId, {
|
||||
id: txId,
|
||||
date: transaction.date,
|
||||
amount: transaction.amount,
|
||||
cash_account_id: transaction.cash_account_id ?? null,
|
||||
}, exclude)
|
||||
} catch (err) {
|
||||
log.warn('booking-time duplicate detection failed (continuing)', err)
|
||||
}
|
||||
if (dup) {
|
||||
const amountAbs = roundOre(Math.abs(Number(transaction.amount)))
|
||||
const voucher = dup.voucher_label ? `verifikat ${dup.voucher_label}` : 'en befintlig verifikation'
|
||||
return {
|
||||
error:
|
||||
`Möjlig dubblettbokföring: ${voucher} (${dup.entry_date}) bokför redan ${amountAbs} kr på bankkontot. ` +
|
||||
`Den här affärshändelsen ser redan ut att vara bokförd — länka transaktionen till den befintliga ` +
|
||||
`verifikationen i stället för att bokföra den igen. Om banktransaktionen verkligen är en separat ` +
|
||||
`affärshändelse, kör om med allow_duplicate=true.`,
|
||||
status: 409,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// allowDuplicate=true bypassed the guard. Booking over a possible
|
||||
// double-booking is a bookkeeping act that must leave a durable
|
||||
// behandlingshistorik record (BFNAR 2013:2 kap 8). Re-detect to capture
|
||||
// the dismissed candidate; best-effort, a logging failure must never block
|
||||
// a legitimate booking.
|
||||
try {
|
||||
const dismissed = await detectBookingDuplicate(supabase, companyId, {
|
||||
id: txId,
|
||||
date: transaction.date,
|
||||
amount: transaction.amount,
|
||||
cash_account_id: transaction.cash_account_id ?? null,
|
||||
}, exclude)
|
||||
if (dismissed) {
|
||||
await appendProcessingHistory({
|
||||
companyId,
|
||||
correlationId: txId,
|
||||
aggregateType: 'BankTransaction',
|
||||
aggregateId: txId,
|
||||
eventType: 'BankTransactionDuplicateDismissed',
|
||||
payload: {
|
||||
transaction_id: txId,
|
||||
dismissed_transaction_id: dismissed.transaction_id,
|
||||
dismissed_journal_entry_id: dismissed.journal_entry_id,
|
||||
amount_ore: Math.round(dismissed.amount * 100),
|
||||
entry_date: dismissed.entry_date,
|
||||
via: 'allow_duplicate',
|
||||
},
|
||||
actor: { type: 'user', id: userId },
|
||||
occurredAt: new Date(),
|
||||
})
|
||||
}
|
||||
} catch (logErr) {
|
||||
log.warn('failed to record duplicate-dismissal behandlingshistorik', logErr)
|
||||
}
|
||||
}
|
||||
|
||||
const isBusiness = category !== 'private'
|
||||
|
||||
const { data: settings } = await supabase
|
||||
.from('company_settings').select('entity_type, fiscal_year_start_month').eq('company_id', companyId).single()
|
||||
|
||||
const entityType: EntityType = (settings?.entity_type as EntityType) || 'enskild_firma'
|
||||
const fiscalYearStartMonth = settings?.fiscal_year_start_month ?? 1
|
||||
|
||||
const mappingResult = buildMappingResultFromCategory(
|
||||
category, transaction as Transaction, isBusiness, entityType, vatTreatment, vatAmount
|
||||
)
|
||||
|
||||
if (!mappingResult.debit_account || !mappingResult.credit_account) {
|
||||
return { error: `No account mapping for category "${category}" with entity type "${entityType}".`, status: 400 }
|
||||
}
|
||||
|
||||
await ensureFiscalPeriod(supabase, userId, companyId, transaction.date, fiscalYearStartMonth)
|
||||
|
||||
let journalEntryId: string | null = null
|
||||
try {
|
||||
const journalEntry = await createTransactionJournalEntry(
|
||||
supabase, companyId, userId, transaction as Transaction, mappingResult, notes,
|
||||
)
|
||||
if (journalEntry) journalEntryId = journalEntry.id
|
||||
} catch (err) {
|
||||
if (isBookkeepingError(err)) throw err
|
||||
log.error('Failed to create journal entry:', err)
|
||||
return { error: err instanceof Error ? err.message : 'Failed to create journal entry', status: 500 }
|
||||
}
|
||||
|
||||
const { error: updateError } = await supabase
|
||||
.from('transactions')
|
||||
.update({ is_business: isBusiness, category, journal_entry_id: journalEntryId })
|
||||
.eq('id', txId)
|
||||
|
||||
if (updateError) {
|
||||
log.error('Failed to update transaction:', updateError)
|
||||
return { error: 'Failed to update transaction', status: 500 }
|
||||
}
|
||||
|
||||
// Propagate the underlag from a matched invoice-inbox item onto the new
|
||||
// verifikation. Without this, BFL 7 kap is violated: a verifikation exists
|
||||
// with no underlag attached even though the user explicitly linked an inbox
|
||||
// item (with a document) to this transaction. We:
|
||||
// 1. find the inbox item(s) where matched_transaction_id = txId
|
||||
// 2. for each item with a document_id, set
|
||||
// document_attachments.journal_entry_id = journalEntryId (idempotent)
|
||||
// 3. stamp invoice_inbox_items.created_journal_entry_id so the inbox row
|
||||
// visibly moves to "Bearbetade" and shows "Öppna verifikation".
|
||||
// Errors are logged but don't fail the commit — the verifikation itself is
|
||||
// already posted, and the link can be repaired by re-running this step.
|
||||
if (journalEntryId) {
|
||||
try {
|
||||
const { data: matchedInboxItems } = await supabase
|
||||
.from('invoice_inbox_items')
|
||||
.select('id, document_id')
|
||||
.eq('company_id', companyId)
|
||||
.eq('matched_transaction_id', txId)
|
||||
.is('created_journal_entry_id', null)
|
||||
for (const inbox of (matchedInboxItems ?? []) as Array<{
|
||||
id: string
|
||||
document_id: string | null
|
||||
}>) {
|
||||
if (inbox.document_id) {
|
||||
try {
|
||||
await linkToJournalEntry(supabase, companyId, inbox.document_id, journalEntryId)
|
||||
} catch (err) {
|
||||
log.error('Failed to link inbox document to journal entry', {
|
||||
inbox_item_id: inbox.id,
|
||||
document_id: inbox.document_id,
|
||||
journal_entry_id: journalEntryId,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
})
|
||||
}
|
||||
}
|
||||
const { error: stampError } = await supabase
|
||||
.from('invoice_inbox_items')
|
||||
.update({ created_journal_entry_id: journalEntryId })
|
||||
.eq('id', inbox.id)
|
||||
.eq('company_id', companyId)
|
||||
if (stampError) {
|
||||
log.error('Failed to stamp inbox item created_journal_entry_id', {
|
||||
inbox_item_id: inbox.id,
|
||||
journal_entry_id: journalEntryId,
|
||||
error: stampError.message,
|
||||
})
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
log.error('Failed to propagate underlag from matched inbox items', err)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await upsertCounterpartyTemplate(
|
||||
supabase, userId, transaction as Transaction, mappingResult, 'user_approved'
|
||||
)
|
||||
} catch { /* non-critical */ }
|
||||
|
||||
await eventBus.emit({
|
||||
type: 'transaction.categorized',
|
||||
payload: {
|
||||
transaction: transaction as Transaction,
|
||||
account: mappingResult.debit_account,
|
||||
taxCode: mappingResult.vat_lines[0]?.account_number || '',
|
||||
userId,
|
||||
companyId,
|
||||
},
|
||||
})
|
||||
|
||||
return { data: { journal_entry_id: journalEntryId, category } }
|
||||
}
|
||||
|
||||
// ── Bulk: book N selected Underlag against their matched transactions ──────
|
||||
|
||||
export interface BulkBookInboxInput {
|
||||
item_ids: string[]
|
||||
category: TransactionCategory
|
||||
vat_treatment?: VatTreatment
|
||||
vat_amount?: number
|
||||
notes?: string
|
||||
allow_duplicate?: boolean
|
||||
}
|
||||
|
||||
export interface BulkBookInboxResult {
|
||||
booked: Array<{ item_id: string; transaction_id: string; journal_entry_id: string | null }>
|
||||
skipped: Array<{ item_id: string; reason: string; detail?: string }>
|
||||
}
|
||||
|
||||
/**
|
||||
* Book each selected inbox item against its matched bank transaction with one
|
||||
* shared category + VAT treatment. Items without a matched transaction, already
|
||||
* booked, or already linked to a leverantörsfaktura are skipped — never an
|
||||
* error — so one bad underlag never blocks the rest ("Bokför valda hoppar
|
||||
* över"). A per-item throw (period locked, accounts not in chart) is caught and
|
||||
* recorded as a skip with the actionable message.
|
||||
*
|
||||
* Shared by the direct UI route (POST /items/bulk-book) and the
|
||||
* `bulk_book_inbox_items` pending-operation executor (Lena-driven flow).
|
||||
*/
|
||||
export async function bulkBookMatchedInboxItems(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
input: BulkBookInboxInput,
|
||||
): Promise<BulkBookInboxResult> {
|
||||
const { item_ids, category, vat_treatment, vat_amount, notes, allow_duplicate } = input
|
||||
|
||||
const booked: BulkBookInboxResult['booked'] = []
|
||||
const skipped: BulkBookInboxResult['skipped'] = []
|
||||
|
||||
// Ids booked so far in THIS batch. Passed as exclusions to each subsequent
|
||||
// booking so two DISTINCT bank movements the user selected that share a
|
||||
// (date, amount, cash account) don't dedupe against each other's freshly
|
||||
// minted verifikat. Duplicates that existed BEFORE the batch are absent from
|
||||
// these lists, so the guard still catches them (see BookingDuplicateExclusions).
|
||||
const bookedTransactionIds: string[] = []
|
||||
const bookedJournalEntryIds: string[] = []
|
||||
|
||||
for (const itemId of item_ids) {
|
||||
const { data: item, error: itemError } = await supabase
|
||||
.from('invoice_inbox_items')
|
||||
.select('id, matched_transaction_id, created_journal_entry_id, created_supplier_invoice_id')
|
||||
.eq('id', itemId)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
|
||||
if (itemError || !item) {
|
||||
skipped.push({ item_id: itemId, reason: 'not_found' })
|
||||
continue
|
||||
}
|
||||
if (item.created_journal_entry_id) {
|
||||
skipped.push({ item_id: itemId, reason: 'already_booked' })
|
||||
continue
|
||||
}
|
||||
if (item.created_supplier_invoice_id) {
|
||||
skipped.push({ item_id: itemId, reason: 'is_supplier_invoice' })
|
||||
continue
|
||||
}
|
||||
if (!item.matched_transaction_id) {
|
||||
skipped.push({ item_id: itemId, reason: 'not_matched' })
|
||||
continue
|
||||
}
|
||||
|
||||
let result: CategorizeCoreResult
|
||||
try {
|
||||
result = await categorizeMatchedTransaction(
|
||||
supabase,
|
||||
userId,
|
||||
companyId,
|
||||
item.matched_transaction_id as string,
|
||||
{ category, vatTreatment: vat_treatment, vatAmount: vat_amount, notes, allowDuplicate: allow_duplicate },
|
||||
// Snapshot copies so the guard sees only the prior bookings of this batch.
|
||||
{ excludeTransactionIds: [...bookedTransactionIds], excludeJournalEntryIds: [...bookedJournalEntryIds] },
|
||||
)
|
||||
} catch (err) {
|
||||
// Caught per-item (incl. AccountsNotInChartError / period-lock bookkeeping
|
||||
// errors) so the batch keeps going. The message carries the actionable
|
||||
// detail (e.g. which BAS accounts to activate).
|
||||
skipped.push({
|
||||
item_id: itemId,
|
||||
reason: 'error',
|
||||
detail: err instanceof Error ? err.message : String(err),
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
if (result.error) {
|
||||
const reason =
|
||||
result.status === 404 ? 'transaction_not_found'
|
||||
: result.status === 409 ? 'already_booked_or_duplicate'
|
||||
: result.status === 400 ? 'no_account_mapping'
|
||||
: 'error'
|
||||
skipped.push({ item_id: itemId, reason, detail: result.error })
|
||||
continue
|
||||
}
|
||||
|
||||
const bookedTxId = item.matched_transaction_id as string
|
||||
const bookedJeId = (result.data?.journal_entry_id as string | null) ?? null
|
||||
// Record this booking so it is excluded from the NEXT item's duplicate guard.
|
||||
bookedTransactionIds.push(bookedTxId)
|
||||
if (bookedJeId) bookedJournalEntryIds.push(bookedJeId)
|
||||
booked.push({
|
||||
item_id: itemId,
|
||||
transaction_id: bookedTxId,
|
||||
journal_entry_id: bookedJeId,
|
||||
})
|
||||
}
|
||||
|
||||
return { booked, skipped }
|
||||
}
|
||||
Reference in New Issue
Block a user