feat(inbox): say what an underlag would be booked as (#1514)
Nothing proposed a kontering for a document. The receipt hunt attaches paper and stops; "klart att bokföra" existed only as an idea. The right pane had extracted fields and no answer to the question the user is actually there to settle. POST /items/:id/suggest-booking answers it, read-only. The lines come from buildTransactionEntryLines, the same function the commit path and the pending-operations preview use, so what is shown cannot drift from what gets posted. That is the whole reason to compose the existing chain rather than write a second one. Derived on demand rather than stored on the row. A stored proposal goes stale against a corrected amount, a re-matched transaction or a template the company taught itself yesterday. The hunt deliberately does not compute it either: the nightly run is already at its time ceiling and a proposal nobody opens is wasted work. Five honest outcomes instead of one optimistic guess: - already_booked, checked against the transaction and not only the inbox row. Booking from Transaktioner, bulk-book or MCP stamps the transaction and leaves the inbox row untouched, so trusting the row alone proposed a second verifikat for money that already had one. - no_transaction, because without one there is no trusted amount, no settlement account and no learned counterparty. - no_mapping, which now includes the engine's own 6991 placeholder at confidence 0.1. Rendering that dressed "no idea" up as an answer one click from the ledger. - currency_unsupported on a foreign row matched by a mapping rule. mapping-engine's rule branch computes VAT from the transaction's own currency while every other line is SEK, so 100 EUR at 11.5 shows 20 kr of moms instead of 230. The entry balances, so nothing downstream catches it. The counterparty and static-template paths convert properly and are not withheld. - a proposal, with the provenance named correctly: template_id marks a static library template, and a learned konteringskarta match sets neither field. Read the other way round, the company's most trusted suggestion was labelled 'default', the same word the placeholder gets. The entity type is now resolved and passed. Left undefined it silently proposed enskild-firma accounts to aktiebolag. The settlement account is no longer applied twice, since evaluateMappingRules applies it on every return path and a second pass rewrote a legitimate 1930 leg. Both queries report a database failure as a failure instead of as "Posten hittades inte". Twenty-one tests, mostly about what the route must not do. Every guard was removed in turn to confirm a test fails without it. Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -861,3 +861,4 @@ One line per decision: `[YYYY-MM-DD] <decision>: <why>`. Appended by agents and
|
||||
[2026-08-10] Validex round 3 falsified the round-2 reading: rule 237 (creditor PstlAdr mandatory) fires on the BGNR-to-BGNR path too, so rule 020's "required unless DbtrAcct is BGNR" only governs the Ctry element, not the address as a whole. Creditor PstlAdr is now emitted on every payment, TwnNm from the payee_city snapshot when known, and the preview warns (payee_city_missing) when the supplier register lacks a city, since 237 + 222 together make a town effectively mandatory at Swedbank and a Ctry-only address is rejected today, not from November.
|
||||
[2026-08-10] Tax table percent rows (>80 000 kr/month) drop ore via Math.floor: whole-krona rule (oretal bortfaller) per SFF 2011:1261 22 kap. 1 § as applied by Skatteverket's tabellavdrag guidance (the statute governs stated amounts; Skatteverket's tables and guidance apply the same truncation to computed skatteavdrag); an API response missing either table section (30B or 30%) is treated as API failure so the bundled fallback serves complete data instead of clamping. Incomplete bracket data (gaps, failed pagination pages, malformed kolumn values) fails loudly rather than withholding 0.
|
||||
[2026-08-10] Staging DB reconcile (metjnjrhvujscngnpzdv): the tracker had skipped everything from 20260721101500 to 2026-08-10 (105 local-only versions) while 25 rows existed only remotely. Renamed 10 remote rows to their repo versions (same name, MCP apply-time version drift: sandbox-cleanup consolidation, shopify, tax-depreciation, JEL index), deleted 7 superseded sandbox-iteration rows with no local file, and left 8 rows from unmerged branches (white-label brands/teams, vacation columns, agent-atom product tier) untouched since their content is deliberately live for the byra rigs. Older seed_agent_atom_bodies files register version-only: each seed is a full idempotent upsert with a version guard, so only the newest seed's content needs to run.
|
||||
[2026-08-11] suggest-booking derives the proposed kontering on demand rather than storing it on the inbox row or computing it in the receipt hunt: a stored proposal goes stale against a corrected amount, a re-matched transaction or a template the company taught itself since, and the nightly hunt is already at its 300 s ceiling for a proposal most rows never open. It composes the existing evaluateMappingRules -> buildTransactionEntryLines chain rather than a second one, so the shown lines cannot drift from the posted lines. It withholds the proposal entirely on a foreign-currency row that matched via the mapping_rules branch: mapping-engine.ts buildResult computes VAT from the transaction's own currency while every other line is SEK (its own NOTE tracks this), which understates ingaende moms by the exchange rate and still balances, so nothing downstream catches it. Guarding the surface was chosen over fixing buildResult in this PR because that changes posted VAT amounts across every caller; the counterparty and static-template paths already convert correctly and are not withheld.
|
||||
|
||||
@@ -0,0 +1,369 @@
|
||||
/**
|
||||
* What this underlag would be booked as.
|
||||
*
|
||||
* The route is read-only and advisory: it proposes, the user approves, and the
|
||||
* posting still goes through book-direct. So the tests are mostly about what it
|
||||
* must NOT do — propose beside an already-posted verifikat, invent a booking for
|
||||
* an unmatched document, or turn an unmappable transaction into an error the
|
||||
* user cannot act on.
|
||||
*
|
||||
* The lines themselves come from buildTransactionEntryLines, which is the same
|
||||
* function the commit path uses. That is deliberate and is the one thing worth
|
||||
* asserting about them: what is shown cannot drift from what gets posted.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { invoiceInboxExtension } from '@/extensions/general/invoice-inbox'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
import type { ExtensionContext } from '@/lib/extensions/types'
|
||||
|
||||
const evaluateMappingRules = vi.fn()
|
||||
vi.mock('@/lib/bookkeeping/mapping-engine', async (orig) => ({
|
||||
...(await orig<Record<string, unknown>>()),
|
||||
evaluateMappingRules: (...a: unknown[]) => evaluateMappingRules(...a),
|
||||
}))
|
||||
vi.mock('@/lib/bookkeeping/settlement-account', () => ({
|
||||
resolveSettlementAccount: vi.fn(async () => '1930'),
|
||||
}))
|
||||
|
||||
const route = invoiceInboxExtension.apiRoutes!.find(
|
||||
(r) => r.method === 'POST' && r.path === '/items/:id/suggest-booking',
|
||||
)!
|
||||
|
||||
function buildCtx(supabase: unknown): ExtensionContext {
|
||||
return {
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
extensionId: 'invoice-inbox',
|
||||
supabase: supabase as ExtensionContext['supabase'],
|
||||
emit: vi.fn(),
|
||||
settings: { get: vi.fn(), set: vi.fn() },
|
||||
storage: { from: vi.fn() } as unknown as ExtensionContext['storage'],
|
||||
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } as unknown as ExtensionContext['log'],
|
||||
services: {},
|
||||
} as unknown as ExtensionContext
|
||||
}
|
||||
|
||||
const req = () =>
|
||||
createMockRequest('/items/item-1/suggest-booking', {
|
||||
method: 'POST',
|
||||
searchParams: { _id: 'item-1' },
|
||||
})
|
||||
|
||||
/** An ordinary domestic expense the konteringskarta already recognises. */
|
||||
function mappingResult(over: Record<string, unknown> = {}) {
|
||||
return {
|
||||
rule: null,
|
||||
template_id: 'tmpl-1',
|
||||
debit_account: '5410',
|
||||
credit_account: '1930',
|
||||
risk_level: 'low',
|
||||
confidence: 0.92,
|
||||
requires_review: false,
|
||||
default_private: false,
|
||||
vat_lines: [],
|
||||
description: 'Elgiganten',
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
function transaction(over: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'tx-1',
|
||||
company_id: 'company-1',
|
||||
date: '2026-08-04',
|
||||
amount: -21639,
|
||||
amount_sek: null,
|
||||
currency: 'SEK',
|
||||
exchange_rate: null,
|
||||
cash_account_id: null,
|
||||
journal_entry_id: null,
|
||||
description: 'Elgiganten Aktiebolag K3667',
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
/** item row + transaction row + company_settings row, in query order. */
|
||||
function queueRows(
|
||||
mock: ReturnType<typeof createQueuedMockSupabase>,
|
||||
opts: { item?: Record<string, unknown>; tx?: Record<string, unknown>; entityType?: string } = {},
|
||||
) {
|
||||
mock.enqueue({
|
||||
data: {
|
||||
id: 'item-1',
|
||||
matched_transaction_id: 'tx-1',
|
||||
created_journal_entry_id: null,
|
||||
created_supplier_invoice_id: null,
|
||||
...opts.item,
|
||||
},
|
||||
})
|
||||
mock.enqueue({ data: transaction(opts.tx) })
|
||||
mock.enqueue({ data: { entity_type: opts.entityType ?? 'aktiebolag' } })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
evaluateMappingRules.mockResolvedValue(mappingResult())
|
||||
})
|
||||
|
||||
describe('POST /items/:id/suggest-booking', () => {
|
||||
it('returns 401 without a context', async () => {
|
||||
expect((await route.handler(req())).status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 404 for an item in another company', async () => {
|
||||
const mock = createQueuedMockSupabase()
|
||||
mock.enqueue({ data: null })
|
||||
const res = await route.handler(req(), buildCtx(mock.supabase))
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('proposes nothing once the item is already booked', async () => {
|
||||
// A suggestion beside a posted verifikat is an invitation to book twice.
|
||||
const mock = createQueuedMockSupabase()
|
||||
mock.enqueue({
|
||||
data: { id: 'item-1', matched_transaction_id: 'tx-1', created_journal_entry_id: 'je-1', created_supplier_invoice_id: null },
|
||||
})
|
||||
const res = await route.handler(req(), buildCtx(mock.supabase))
|
||||
const { body } = await parseJsonResponse<{ data: { source: string; lines: unknown[] } }>(res)
|
||||
expect(body.data.source).toBe('already_booked')
|
||||
expect(body.data.lines).toEqual([])
|
||||
expect(evaluateMappingRules).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('proposes nothing when the item became a supplier invoice', async () => {
|
||||
const mock = createQueuedMockSupabase()
|
||||
mock.enqueue({
|
||||
data: { id: 'item-1', matched_transaction_id: 'tx-1', created_journal_entry_id: null, created_supplier_invoice_id: 'si-1' },
|
||||
})
|
||||
const { body } = await parseJsonResponse<{ data: { source: string } }>(
|
||||
await route.handler(req(), buildCtx(mock.supabase)),
|
||||
)
|
||||
expect(body.data.source).toBe('already_booked')
|
||||
})
|
||||
|
||||
it('says so honestly when nothing is matched yet', async () => {
|
||||
// No transaction means no trusted amount, no settlement account and no
|
||||
// learned counterparty. Guessing here would be worse than saying nothing.
|
||||
const mock = createQueuedMockSupabase()
|
||||
mock.enqueue({
|
||||
data: { id: 'item-1', matched_transaction_id: null, created_journal_entry_id: null, created_supplier_invoice_id: null },
|
||||
})
|
||||
const { body } = await parseJsonResponse<{ data: { source: string; lines: unknown[] } }>(
|
||||
await route.handler(req(), buildCtx(mock.supabase)),
|
||||
)
|
||||
expect(body.data.source).toBe('no_transaction')
|
||||
expect(body.data.lines).toEqual([])
|
||||
expect(evaluateMappingRules).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns balanced lines for a matched transaction', async () => {
|
||||
const mock = createQueuedMockSupabase()
|
||||
queueRows(mock)
|
||||
|
||||
const { body } = await parseJsonResponse<{
|
||||
data: { source: string; lines: { debit_amount: number; credit_amount: number }[]; entry_date: string }
|
||||
}>(await route.handler(req(), buildCtx(mock.supabase)))
|
||||
|
||||
expect(body.data.source).toBe('booking_template')
|
||||
expect(body.data.lines.length).toBeGreaterThan(0)
|
||||
const debit = body.data.lines.reduce((t, l) => t + (l.debit_amount || 0), 0)
|
||||
const credit = body.data.lines.reduce((t, l) => t + (l.credit_amount || 0), 0)
|
||||
expect(Math.round((debit - credit) * 100)).toBe(0)
|
||||
})
|
||||
|
||||
it('books on the day the money moved, not the day on the document', async () => {
|
||||
const mock = createQueuedMockSupabase()
|
||||
queueRows(mock, { tx: { date: '2026-08-04' } })
|
||||
const { body } = await parseJsonResponse<{ data: { entry_date: string } }>(
|
||||
await route.handler(req(), buildCtx(mock.supabase)),
|
||||
)
|
||||
expect(body.data.entry_date).toBe('2026-08-04')
|
||||
})
|
||||
|
||||
it('carries the review flags the "Varför så här?" fold reads', async () => {
|
||||
evaluateMappingRules.mockResolvedValue(
|
||||
mappingResult({ confidence: 0.55, requires_review: true, direction_mismatch: true, template_id: undefined, rule: { rule_name: 'Drivmedel' } }),
|
||||
)
|
||||
const mock = createQueuedMockSupabase()
|
||||
queueRows(mock)
|
||||
const { body } = await parseJsonResponse<{
|
||||
data: { source: string; confidence: number; requires_review: boolean; direction_mismatch: boolean; rule_name: string }
|
||||
}>(await route.handler(req(), buildCtx(mock.supabase)))
|
||||
|
||||
expect(body.data.source).toBe('mapping_rule')
|
||||
expect(body.data.confidence).toBe(0.55)
|
||||
expect(body.data.requires_review).toBe(true)
|
||||
// A refund matching an expense-learned template: mirrored and review-gated
|
||||
// upstream, and the pane must be able to say so.
|
||||
expect(body.data.direction_mismatch).toBe(true)
|
||||
expect(body.data.rule_name).toBe('Drivmedel')
|
||||
})
|
||||
|
||||
it('degrades to no proposal when neither side of the mapping resolves', async () => {
|
||||
// Real for a company with no rule and no history. Not an error the user
|
||||
// can act on, so it must not read as one.
|
||||
evaluateMappingRules.mockResolvedValue(mappingResult({ debit_account: '', credit_account: '' }))
|
||||
const mock = createQueuedMockSupabase()
|
||||
queueRows(mock)
|
||||
const res = await route.handler(req(), buildCtx(mock.supabase))
|
||||
expect(res.status).toBe(200)
|
||||
const { body } = await parseJsonResponse<{ data: { source: string; lines: unknown[] } }>(res)
|
||||
expect(body.data.source).toBe('no_mapping')
|
||||
expect(body.data.lines).toEqual([])
|
||||
})
|
||||
|
||||
it('degrades rather than 500s when the mapping engine throws', async () => {
|
||||
evaluateMappingRules.mockRejectedValue(new Error('boom'))
|
||||
const mock = createQueuedMockSupabase()
|
||||
queueRows(mock)
|
||||
const res = await route.handler(req(), buildCtx(mock.supabase))
|
||||
expect(res.status).toBe(200)
|
||||
const { body } = await parseJsonResponse<{ data: { source: string } }>(res)
|
||||
expect(body.data.source).toBe('no_mapping')
|
||||
})
|
||||
|
||||
it('proposes nothing when the bank line already has a verifikat', async () => {
|
||||
// The inbox row is not the only way a purchase gets booked. Booking from
|
||||
// Transaktioner, bulk-book or MCP leaves created_journal_entry_id null on
|
||||
// the inbox row, so trusting that row alone proposes a second verifikat
|
||||
// for money that already has one.
|
||||
const mock = createQueuedMockSupabase()
|
||||
queueRows(mock, { tx: { journal_entry_id: 'je-9' } })
|
||||
const { body } = await parseJsonResponse<{ data: { source: string; lines: unknown[] } }>(
|
||||
await route.handler(req(), buildCtx(mock.supabase)),
|
||||
)
|
||||
expect(body.data.source).toBe('already_booked')
|
||||
expect(body.data.lines).toEqual([])
|
||||
expect(evaluateMappingRules).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('tells the mapping engine which entity type the company is', async () => {
|
||||
// Left undefined, the engine proposed enskild-firma accounts to an
|
||||
// aktiebolag: 2013 instead of 2893 for an owner expense.
|
||||
const mock = createQueuedMockSupabase()
|
||||
queueRows(mock, { entityType: 'aktiebolag' })
|
||||
await route.handler(req(), buildCtx(mock.supabase))
|
||||
expect(evaluateMappingRules).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'company-1',
|
||||
expect.objectContaining({ id: 'tx-1' }),
|
||||
'aktiebolag',
|
||||
expect.anything(),
|
||||
)
|
||||
})
|
||||
|
||||
it('falls back to enskild firma when no entity type is stored', async () => {
|
||||
const mock = createQueuedMockSupabase()
|
||||
mock.enqueue({
|
||||
data: { id: 'item-1', matched_transaction_id: 'tx-1', created_journal_entry_id: null, created_supplier_invoice_id: null },
|
||||
})
|
||||
mock.enqueue({ data: transaction() })
|
||||
mock.enqueue({ data: null })
|
||||
await route.handler(req(), buildCtx(mock.supabase))
|
||||
expect(evaluateMappingRules).toHaveBeenCalledWith(
|
||||
expect.anything(), 'company-1', expect.anything(), 'enskild_firma', expect.anything(),
|
||||
)
|
||||
})
|
||||
|
||||
it('does not apply the settlement account a second time', async () => {
|
||||
// evaluateMappingRules applies it on every return path. Applying it again
|
||||
// rewrote a legitimate 1930 leg, collapsing an own-account transfer onto
|
||||
// a single account.
|
||||
evaluateMappingRules.mockResolvedValue(
|
||||
mappingResult({ debit_account: '1930', credit_account: '1931', template_id: undefined, confidence: 0.85 }),
|
||||
)
|
||||
const mock = createQueuedMockSupabase()
|
||||
queueRows(mock)
|
||||
const { body } = await parseJsonResponse<{ data: { lines: { account_number: string }[] } }>(
|
||||
await route.handler(req(), buildCtx(mock.supabase)),
|
||||
)
|
||||
const accounts = body.data.lines.map((l) => l.account_number)
|
||||
expect(accounts).toContain('1930')
|
||||
expect(accounts).toContain('1931')
|
||||
})
|
||||
|
||||
it('reports the engine placeholder as no proposal, not as an answer', async () => {
|
||||
// getDefaultResult is how the engine says it has nothing: 6991 at
|
||||
// confidence 0.1. Rendering it dresses "no idea" up as a kontering.
|
||||
evaluateMappingRules.mockResolvedValue(
|
||||
mappingResult({ rule: null, template_id: undefined, debit_account: '6991', confidence: 0.1, requires_review: true }),
|
||||
)
|
||||
const mock = createQueuedMockSupabase()
|
||||
queueRows(mock)
|
||||
const { body } = await parseJsonResponse<{ data: { source: string; lines: unknown[] } }>(
|
||||
await route.handler(req(), buildCtx(mock.supabase)),
|
||||
)
|
||||
expect(body.data.source).toBe('no_mapping')
|
||||
expect(body.data.lines).toEqual([])
|
||||
})
|
||||
|
||||
it('calls a learned counterparty match what it is', async () => {
|
||||
// template_id marks a STATIC library template; a learned konteringskarta
|
||||
// match sets neither field. Read the other way round, the company's most
|
||||
// trusted proposal was labelled 'default'.
|
||||
evaluateMappingRules.mockResolvedValue(
|
||||
mappingResult({ rule: null, template_id: undefined, confidence: 0.85 }),
|
||||
)
|
||||
const mock = createQueuedMockSupabase()
|
||||
queueRows(mock)
|
||||
const { body } = await parseJsonResponse<{ data: { source: string } }>(
|
||||
await route.handler(req(), buildCtx(mock.supabase)),
|
||||
)
|
||||
expect(body.data.source).toBe('counterparty_template')
|
||||
})
|
||||
|
||||
it('withholds a rule-branch proposal on a foreign-currency row', async () => {
|
||||
// mapping-engine computes rule-branch VAT from the transaction's own
|
||||
// currency while every other line is SEK, so 100 EUR at 11.5 shows 20 kr
|
||||
// of moms instead of 230. The entry balances, so nothing downstream
|
||||
// catches it. A wrong number one click from the ledger is worse than none.
|
||||
evaluateMappingRules.mockResolvedValue(mappingResult({ rule: { rule_name: 'ACME' }, template_id: undefined }))
|
||||
const mock = createQueuedMockSupabase()
|
||||
queueRows(mock, { tx: { amount: -100, amount_sek: -1150, currency: 'EUR', exchange_rate: 11.5 } })
|
||||
const { body } = await parseJsonResponse<{ data: { source: string; lines: unknown[] } }>(
|
||||
await route.handler(req(), buildCtx(mock.supabase)),
|
||||
)
|
||||
expect(body.data.source).toBe('currency_unsupported')
|
||||
expect(body.data.lines).toEqual([])
|
||||
})
|
||||
|
||||
it('still proposes on a foreign row when the match came from the konteringskarta', async () => {
|
||||
// Counterparty and static-template paths convert to SEK before generating
|
||||
// VAT, so only the rule branch is withheld.
|
||||
evaluateMappingRules.mockResolvedValue(mappingResult({ rule: null, template_id: undefined, confidence: 0.85 }))
|
||||
const mock = createQueuedMockSupabase()
|
||||
queueRows(mock, { tx: { amount: -100, amount_sek: -1150, currency: 'EUR', exchange_rate: 11.5 } })
|
||||
const { body } = await parseJsonResponse<{ data: { source: string; lines: unknown[] } }>(
|
||||
await route.handler(req(), buildCtx(mock.supabase)),
|
||||
)
|
||||
expect(body.data.source).toBe('counterparty_template')
|
||||
expect(body.data.lines.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('reports a database failure as a failure, not as a missing document', async () => {
|
||||
const mock = createQueuedMockSupabase()
|
||||
mock.enqueue({ data: null, error: { message: 'column does not exist' } })
|
||||
const res = await route.handler(req(), buildCtx(mock.supabase))
|
||||
expect(res.status).toBe(500)
|
||||
})
|
||||
|
||||
it('scopes every read to the company', async () => {
|
||||
const mock = createQueuedMockSupabase()
|
||||
queueRows(mock)
|
||||
await route.handler(req(), buildCtx(mock.supabase))
|
||||
const scoped = mock.calls.filter(
|
||||
(c) => c.method === 'eq' && c.args?.[0] === 'company_id' && c.args?.[1] === 'company-1',
|
||||
)
|
||||
// invoice_inbox_items, transactions and company_settings.
|
||||
expect(scoped.length).toBeGreaterThanOrEqual(3)
|
||||
})
|
||||
|
||||
it('never writes', async () => {
|
||||
const mock = createQueuedMockSupabase()
|
||||
queueRows(mock)
|
||||
await route.handler(req(), buildCtx(mock.supabase))
|
||||
for (const m of ['insert', 'update', 'upsert', 'delete']) {
|
||||
expect(mock.calls.some((c) => c.method === m), `route called .${m}()`).toBe(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -55,6 +55,11 @@ import { CreateSupplierInvoiceSchema, BookInboxItemDirectlySchema, BulkBookInbox
|
||||
import { bulkBookMatchedInboxItems } from '@/lib/transactions/categorize-core'
|
||||
import { hasCapability, capabilityBlockedResponse } from '@/lib/entitlements/has-capability'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import { evaluateMappingRules } from '@/lib/bookkeeping/mapping-engine'
|
||||
import { buildTransactionEntryLines } from '@/lib/bookkeeping/transaction-entries'
|
||||
import { resolveSettlementAccount } from '@/lib/bookkeeping/settlement-account'
|
||||
import type { Transaction, EntityType } from '@/types'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { appendProcessingHistory } from '@/lib/processing-history/append'
|
||||
import { checkInboxUploadRateLimit } from '@/lib/rate-limits/inbox'
|
||||
import { simpleParser } from 'mailparser'
|
||||
@@ -2244,6 +2249,207 @@ export const invoiceInboxExtension: Extension = {
|
||||
})
|
||||
},
|
||||
},
|
||||
|
||||
// ── What this underlag would be booked as ─────────────────────
|
||||
//
|
||||
// Read-only. Nothing here writes, and nothing here is authoritative: the
|
||||
// answer is a suggestion the user approves, edits or ignores, and the
|
||||
// actual posting still goes through book-direct → createJournalEntry.
|
||||
//
|
||||
// Derived on demand rather than stored on the row, so it cannot go stale
|
||||
// against a corrected amount, a re-matched transaction or a template the
|
||||
// company taught itself yesterday. The receipt hunt deliberately does not
|
||||
// compute it: the nightly run is already at its time ceiling, and a
|
||||
// proposal nobody opens is wasted work.
|
||||
//
|
||||
// The lines come from buildTransactionEntryLines, the same function the
|
||||
// commit path and the pending-operations preview use, so what is shown
|
||||
// here cannot drift from what gets posted.
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/items/:id/suggest-booking',
|
||||
handler: async (request: Request, ctx?: ExtensionContext) => {
|
||||
if (!ctx) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const url = new URL(request.url)
|
||||
const id = url.searchParams.get('_id')
|
||||
if (!id) return NextResponse.json({ error: 'Missing id' }, { status: 400 })
|
||||
|
||||
// A dropped `error` here would report a missing column or a lagging
|
||||
// migration as "Posten hittades inte", pointing the user at their
|
||||
// document instead of at the database.
|
||||
const { data: item, error: itemError } = await ctx.supabase
|
||||
.from('invoice_inbox_items')
|
||||
.select('id, matched_transaction_id, created_journal_entry_id, created_supplier_invoice_id')
|
||||
.eq('id', id)
|
||||
.eq('company_id', ctx.companyId)
|
||||
.maybeSingle()
|
||||
|
||||
if (itemError) {
|
||||
ctx.log.error('suggest-booking: inbox lookup failed', { itemId: id, error: itemError.message })
|
||||
return NextResponse.json({ error: 'Kunde inte läsa posten' }, { status: 500 })
|
||||
}
|
||||
if (!item) return NextResponse.json({ error: 'Posten hittades inte' }, { status: 404 })
|
||||
|
||||
// Already resolved: there is nothing left to propose, and showing a
|
||||
// suggestion beside a posted verifikat invites double-booking.
|
||||
if (item.created_journal_entry_id || item.created_supplier_invoice_id) {
|
||||
return NextResponse.json({
|
||||
data: { source: 'already_booked' as const, lines: [], confidence: null },
|
||||
})
|
||||
}
|
||||
|
||||
if (!item.matched_transaction_id) {
|
||||
// Without a transaction there is no amount we trust, no settlement
|
||||
// account and no learned counterparty. The honest answer is that we
|
||||
// cannot propose one yet; the UI asks the user to match first.
|
||||
return NextResponse.json({
|
||||
data: { source: 'no_transaction' as const, lines: [], confidence: null },
|
||||
})
|
||||
}
|
||||
|
||||
// The transaction is queried explicitly by company even though RLS
|
||||
// would narrow it: service-role paths have none, and the filter is the
|
||||
// defense-in-depth this repo mandates.
|
||||
const { data: tx, error: txError } = await ctx.supabase
|
||||
.from('transactions')
|
||||
.select('*')
|
||||
.eq('id', item.matched_transaction_id)
|
||||
.eq('company_id', ctx.companyId)
|
||||
.maybeSingle()
|
||||
|
||||
if (txError) {
|
||||
ctx.log.error('suggest-booking: transaction lookup failed', {
|
||||
itemId: id,
|
||||
error: txError.message,
|
||||
})
|
||||
return NextResponse.json({ error: 'Kunde inte läsa transaktionen' }, { status: 500 })
|
||||
}
|
||||
if (!tx) {
|
||||
return NextResponse.json({ error: 'Transaktionen hittades inte' }, { status: 404 })
|
||||
}
|
||||
|
||||
// The inbox row is not the only way a purchase gets booked. Booking the
|
||||
// bank line from Transaktioner, from bulk-book or over MCP stamps the
|
||||
// transaction and leaves invoice_inbox_items.created_journal_entry_id
|
||||
// null, so trusting the inbox row alone proposes a second verifikat for
|
||||
// money that already has one.
|
||||
if ((tx as Transaction).journal_entry_id) {
|
||||
return NextResponse.json({
|
||||
data: { source: 'already_booked' as const, lines: [], confidence: null },
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
const { data: settings } = await ctx.supabase
|
||||
.from('company_settings')
|
||||
.select('entity_type')
|
||||
.eq('company_id', ctx.companyId)
|
||||
.maybeSingle()
|
||||
// Same default as categorize-core. Leaving it undefined silently
|
||||
// proposed enskild-firma accounts to aktiebolag: 2013 instead of
|
||||
// 2893 for an owner expense, 6991 instead of 7610 for a course.
|
||||
const entityType: EntityType = (settings?.entity_type as EntityType) || 'enskild_firma'
|
||||
|
||||
const settlementAccount = await resolveSettlementAccount(
|
||||
ctx.supabase,
|
||||
ctx.companyId,
|
||||
(tx as Transaction).cash_account_id,
|
||||
createLogger('invoice-inbox.suggest-booking'),
|
||||
)
|
||||
// evaluateMappingRules applies the settlement account itself on every
|
||||
// return path. Applying it again rewrote a legitimate 1930 leg, which
|
||||
// on an own-account transfer collapsed both sides onto one account.
|
||||
const mapping = await evaluateMappingRules(
|
||||
ctx.supabase,
|
||||
ctx.companyId,
|
||||
tx as Transaction,
|
||||
entityType,
|
||||
settlementAccount,
|
||||
)
|
||||
|
||||
// getDefaultResult is the engine's way of saying it has nothing: a
|
||||
// 6991 placeholder at confidence 0.1. Rendering that as a proposal
|
||||
// dresses "no idea" up as an answer, so it is reported as no_mapping,
|
||||
// which is what the empty branch was always meant to cover.
|
||||
const isPlaceholder =
|
||||
!mapping.rule && !mapping.template_id && mapping.confidence <= 0.1
|
||||
if (isPlaceholder || !mapping.debit_account || !mapping.credit_account) {
|
||||
return NextResponse.json({
|
||||
data: { source: 'no_mapping' as const, lines: [], confidence: mapping.confidence ?? null },
|
||||
})
|
||||
}
|
||||
|
||||
// mapping-engine's rule branch computes VAT from the transaction's own
|
||||
// currency while every other line is built in SEK (see the NOTE at
|
||||
// buildResult). On a non-SEK row that understates ingående moms by the
|
||||
// exchange rate: 100 EUR at 11.5 shows 20 kr of moms instead of 230.
|
||||
// The entry still balances, so nothing downstream catches it. Until
|
||||
// that is fixed in the engine, this surface does not render it: a
|
||||
// wrong number one click from the ledger is worse than no number.
|
||||
const sekAmount = (tx as Transaction).amount_sek
|
||||
const isForeign =
|
||||
(tx as Transaction).currency !== 'SEK' &&
|
||||
sekAmount != null &&
|
||||
Math.abs(sekAmount) !== Math.abs((tx as Transaction).amount)
|
||||
if (mapping.rule && isForeign) {
|
||||
ctx.log.info('suggest-booking: withheld a rule-branch proposal on a foreign-currency row', {
|
||||
itemId: id,
|
||||
currency: (tx as Transaction).currency,
|
||||
})
|
||||
return NextResponse.json({
|
||||
data: { source: 'currency_unsupported' as const, lines: [], confidence: null },
|
||||
})
|
||||
}
|
||||
|
||||
const lines = buildTransactionEntryLines(tx as Transaction, mapping).map((l) => ({
|
||||
account_number: l.account_number,
|
||||
debit_amount: l.debit_amount,
|
||||
credit_amount: l.credit_amount,
|
||||
description: l.line_description ?? '',
|
||||
}))
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
// template_id marks a static library template; a learned
|
||||
// counterparty template sets neither field. Reading it the other
|
||||
// way round labelled the konteringskarta's most trusted match
|
||||
// 'default', the same word the 6991 placeholder gets.
|
||||
source: mapping.rule
|
||||
? ('mapping_rule' as const)
|
||||
: mapping.template_id
|
||||
? ('booking_template' as const)
|
||||
: ('counterparty_template' as const),
|
||||
lines,
|
||||
// Everything below is what the "Varför så här?" fold reads. It
|
||||
// already existed on MappingResult and nothing rendered it.
|
||||
confidence: mapping.confidence,
|
||||
requires_review: mapping.requires_review,
|
||||
direction_mismatch: mapping.direction_mismatch ?? false,
|
||||
risk_level: mapping.risk_level,
|
||||
description: mapping.description,
|
||||
rule_name: mapping.rule?.rule_name ?? null,
|
||||
template_id: mapping.template_id ?? null,
|
||||
dimensions: mapping.dimensions ?? null,
|
||||
// The day the money moved, not the day printed on the document:
|
||||
// it is what decides the period the entry lands in.
|
||||
entry_date: (tx as Transaction).date,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
ctx.log.warn('suggest-booking failed', {
|
||||
itemId: id,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
})
|
||||
// A suggestion that cannot be produced is not an error the user did
|
||||
// anything about: fall back to the empty proposal and let them book
|
||||
// by hand.
|
||||
return NextResponse.json({
|
||||
data: { source: 'no_mapping' as const, lines: [], confidence: null },
|
||||
})
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user