Files
accounted/extensions/general/inbox-smart-match/__tests__/match-receipt.test.ts
T
Jakob WennbergandClaude Opus 4.7 0076aa85f8 feat: arcim inbox (Resend Inbound) + smart-match extension + commit metadata (#286)
* feat: multi-series SIE import, reusable FiscalYearSelector, library templates in picker

- SIE import preserves each voucher's source series (B/C/I/V/...), essential
  for Fortnox migrations where series carry semantic meaning (kundfakturor,
  inbetalningar, etc.). Target numbering still goes through next_voucher_number
  per series; source (series, number) is stored in the migration mapping for
  BFNAR 2013:2 audit trail.
- Execute route reads company_settings.default_voucher_series as the fallback
  for vouchers arriving without a series (SIE4I).
- Extract shared FiscalYearSelector component; adopt in /reports and
  /bookkeeping.
- Transaction TemplatePicker now surfaces user-created library templates
  (company + team scope) alongside the static registry, with a helper to
  convert simple library templates into the BookingTemplate shape.
- Exclude 8999 "Årets resultat" from income statement financial section and
  monthly breakdown so year-end closing entries don't cancel the net result.

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

* test: skip Bokio SIE regression when fixtures are absent

/dev_docs is gitignored (contains anonymised customer exports), so the
integration test can't find its input files in CI. Gate the suite on
fixture presence so it still runs locally.

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

* fix: address Greptile review feedback

- convertLibraryToBookingTemplate: default entity_applicability to 'all'
  when the source template has no entity_type, so TemplatePicker doesn't
  silently hide it for companies with a set entity type.
- FiscalYearSelector: fire onReady in the no-company early-return branch
  so consumers (e.g. ReportsPage) don't get stuck in a loading skeleton
  while the company context is still hydrating.

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

* feat: arcim inbox + smart-match extension + commit metadata

Three threads, all gated off in extensions.config.json (invoice-inbox and
inbox-smart-match are not in the enabled list for this PR).

invoice-inbox: Gmail OAuth -> Resend Inbound (v2.0.0)
- Remove gmail-scanner / gmail-helpers
- Add resend-inbound.ts (webhook verify, attachment fetch) and
  inbox-provisioning.ts (per-company @arcim.io address with rotation)
- Replace /gmail/* routes with /inbox/address and admin-only /inbox/rotate
- Workspace UI: card layout + MatchBlock surfacing AI transaction matches
- classify-document: tightened discount/total prompt; cap confidence at
  50% when line items do not reconcile with amount_incl_vat
- Manifest requires RESEND_API_KEY, RESEND_INBOUND_DOMAIN,
  RESEND_INBOUND_WEBHOOK_SECRET

inbox-smart-match (new extension)
- Event-driven AI matching of receipts to bank transactions
- Listens on inbox_item.classified (match now) and transaction.synced
  (retro-match receipts waiting for a transaction)
- Uses service-role client; processing_history append is scoped by
  company_id from the event payload

commit metadata + audit plumbing
- journal_entries gains commit_method and rubric_version columns
- commit_journal_entry RPC accepts both (BFNAR 2013:2 behandlingshistorik)
- processing-history PII detector strips UUID-shaped substrings before
  personnummer pattern matching (UUIDs were triggering false positives)
- New generic inbox_item.classified event

Migrations
- arcim_inbox: company_inboxes table, resend_email_id, email_body_text,
  auto-provision trigger, drops obsolete email_connections
- journal_entry_commit_metadata: new columns + updated RPC
- inbox_attachment_composite: resend_attachment_id + composite unique index
- inbox_smart_match: correlation_id, match_reasoning, expanded match_method
  CHECK, pending-match and correlation indexes

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 21:50:07 +02:00

135 lines
4.1 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
// Mock Bedrock SDK before importing the module under test
const mockSend = vi.fn()
vi.mock('@aws-sdk/client-bedrock-runtime', () => {
class ConverseCommand {
public input: unknown
constructor(input: unknown) { this.input = input }
}
class BedrockRuntimeClient {
send(command: unknown) { return mockSend(command) }
}
return { BedrockRuntimeClient, ConverseCommand }
})
import { matchReceiptToCandidate } from '@/extensions/general/inbox-smart-match/lib/match-receipt'
import type { ReceiptExtractionResult } from '@/types'
import type { CandidateTransaction } from '@/extensions/general/inbox-smart-match/lib/fetch-candidates'
function makeExtracted(): ReceiptExtractionResult {
return {
merchant: { name: 'Willys Hemma', orgNumber: null, vatNumber: null, isForeign: false },
receipt: { date: '2026-04-15', time: null, currency: 'SEK' },
lineItems: [],
totals: { subtotal: 239, vatAmount: 60, total: 299 },
flags: { isRestaurant: false, isSystembolaget: false, isForeignMerchant: false },
confidence: 0.9,
} as ReceiptExtractionResult
}
function makeCandidates(): CandidateTransaction[] {
return [
{ id: 't1', date: '2026-04-15', description: 'WILLYS SÖDERM', amount: -299, amount_sek: null, currency: 'SEK', merchant_name: 'Willys' },
{ id: 't2', date: '2026-04-14', description: 'ICA MAXI', amount: -312, amount_sek: null, currency: 'SEK', merchant_name: 'ICA' },
]
}
function mockBedrockResponse(toolInput: Record<string, unknown>) {
mockSend.mockResolvedValue({
output: {
message: {
content: [
{
toolUse: {
toolUseId: 'id',
name: 'match_receipt',
input: toolInput,
},
},
],
},
},
usage: { inputTokens: 100, outputTokens: 20 },
})
}
describe('matchReceiptToCandidate', () => {
beforeEach(() => {
mockSend.mockReset()
process.env.AWS_ACCESS_KEY_ID = 'test'
process.env.AWS_SECRET_ACCESS_KEY = 'test'
process.env.AWS_REGION = 'eu-north-1'
})
it('returns a matched result when LLM picks a valid candidate', async () => {
mockBedrockResponse({
matched: true,
transaction_id: 't1',
confidence: 96,
reasoning: 'Exakt belopp och datum. Willys matchar WILLYS SÖDERM.',
})
const result = await matchReceiptToCandidate({
extracted: makeExtracted(),
candidates: makeCandidates(),
})
expect(result.matched).toBe(true)
expect(result.transactionId).toBe('t1')
expect(result.confidence).toBeCloseTo(0.96, 2)
expect(result.reasoning).toContain('Willys')
})
it('returns no match when LLM says matched=false', async () => {
mockBedrockResponse({
matched: false,
transaction_id: null,
confidence: 10,
reasoning: 'Ingen kandidat har rätt belopp eller handlare.',
})
const result = await matchReceiptToCandidate({
extracted: makeExtracted(),
candidates: makeCandidates(),
})
expect(result.matched).toBe(false)
expect(result.transactionId).toBeNull()
expect(result.confidence).toBeCloseTo(0.1, 2)
})
it('degrades to no-match when LLM returns unknown transaction_id', async () => {
mockBedrockResponse({
matched: true,
transaction_id: 'hallucinated-id-not-in-candidates',
confidence: 80,
reasoning: 'Detta är fel id',
})
const result = await matchReceiptToCandidate({
extracted: makeExtracted(),
candidates: makeCandidates(),
})
expect(result.matched).toBe(false)
expect(result.transactionId).toBeNull()
expect(result.confidence).toBe(0)
})
it('returns safe default when no tool use in response', async () => {
mockSend.mockResolvedValue({
output: { message: { content: [] } },
usage: { inputTokens: 0, outputTokens: 0 },
})
const result = await matchReceiptToCandidate({
extracted: makeExtracted(),
candidates: makeCandidates(),
})
expect(result.matched).toBe(false)
expect(result.transactionId).toBeNull()
})
})