Files
accounted/app/api/agent/categorize/route.ts
T
e7a5e65ecf feat(categorize): Tier 1 candidate gathering + the proposal route (#1781)
The auto-booking cascade end to end (retrieval → selector), minus the write.

- lib/agent/categorize/candidates.ts (Tier 1): assembles the deterministic
  candidate slate for a transaction — the learned counterparty template
  (strongest, carries its own VAT) plus mapping rules / patterns / per-merchant
  history via the same engine gnubok_suggest_categories uses. No model call.
  Deduped by account (highest confidence wins), capped; suggestions get the
  category's default VAT treatment derived.
- POST /api/agent/categorize: loads the transaction + company VAT context,
  runs Tier 1 → Tier 2 selectAccount, returns the proposed account + VAT +
  confidence + reasoning + the candidate slate. Never posts anything — the
  caller renders an approval card. Gated on configured (any provider incl.
  local), same gates as /api/agent/ask.

12 tests: candidate merge/dedupe/VAT-derivation, and the route (401/429/400/
403/404/503 + happy path threading entity type, VAT, underlag, samples).

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-21 13:32:09 +02:00

115 lines
4.7 KiB
TypeScript

import { NextResponse } from 'next/server'
import { z } from 'zod'
import { requireAuth } from '@/lib/auth/require-auth'
import { getActiveCompanyId } from '@/lib/company/context'
import { checkAgentRateLimit, agentRateLimitResponseBody } from '@/lib/rate-limits/agent'
import { guardSandbox } from '@/lib/sandbox/guard'
import { requireCapability } from '@/lib/entitlements/has-capability'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { getAiStatus } from '@/lib/ai'
import { gatherCandidates } from '@/lib/agent/categorize/candidates'
import { selectAccount } from '@/lib/agent/categorize/select-account'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import type { EntityType, Transaction } from '@/types'
/**
* POST /api/agent/categorize: a provider-agnostic booking proposal for one
* transaction — the auto-booking cascade end to end (Tier 1 retrieval → Tier 2
* selector), minus the write.
*
* It gathers the deterministic candidate accounts (counterparty templates,
* rules, history) with NO model call, then has the model SELECT among them
* (self-consistency sampled), and returns the proposed account + VAT +
* confidence + reasoning + the candidate slate. It never posts anything: the
* caller (the transaction row) renders the proposal as an approval card.
*
* Runs on any configured backend (Bedrock or a local model), so it is gated on
* `configured`, not `assistantAvailable` — same as /api/agent/ask.
*/
const Schema = z.object({
transaction_id: z.string().uuid(),
company_id: z.string().uuid().optional(),
/** Extracted receipt/invoice text, if the caller already has it. */
underlag: z.string().max(24_000).optional(),
/** Self-consistency samples (default 3). */
samples: z.number().int().min(1).max(5).optional(),
})
export async function POST(request: Request): Promise<Response> {
const { user, supabase, error } = await requireAuth()
if (error) return error
const rate = await checkAgentRateLimit(supabase, user.id)
if (!rate.ok) return NextResponse.json(agentRateLimitResponseBody(rate), { status: 429 })
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
}
const parsed = Schema.safeParse(body)
if (!parsed.success) {
return NextResponse.json({ error: 'Ogiltig förfrågan.', type: 'validation_error' }, { status: 400 })
}
const companyId = parsed.data.company_id ?? (await getActiveCompanyId(supabase, user.id))
if (!companyId) return NextResponse.json({ error: 'No active company' }, { status: 400 })
const { data: membership } = await supabase
.from('company_members')
.select('user_id')
.eq('company_id', companyId)
.eq('user_id', user.id)
.maybeSingle()
if (!membership) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const blocked = await guardSandbox(supabase, companyId)
if (blocked) return blocked
const capBlocked = await requireCapability(supabase, companyId, CAPABILITY.ai)
if (capBlocked) return capBlocked
if (!getAiStatus().configured) {
return NextResponse.json(
{ error: 'Assistenten är inte konfigurerad på den här installationen.', code: 'ai_unconfigured' },
{ status: 503 },
)
}
const { data: tx } = await supabase
.from('transactions')
.select('id, merchant_name, description, original_description, amount, date, currency, category, is_business')
.eq('id', parsed.data.transaction_id)
.eq('company_id', companyId)
.maybeSingle()
if (!tx) return NextResponse.json({ error: 'Transaktionen hittades inte.' }, { status: 404 })
const [{ data: company }, { data: settings }] = await Promise.all([
supabase.from('companies').select('entity_type').eq('id', companyId).maybeSingle(),
supabase.from('company_settings').select('vat_registered').eq('company_id', companyId).maybeSingle(),
])
try {
const candidates = await gatherCandidates(supabase, companyId, tx as Transaction)
const selection = await selectAccount({
transaction: {
merchantName: (tx as Transaction).merchant_name,
description: (tx as Transaction).description,
amount: (tx as Transaction).amount,
date: (tx as Transaction).date,
currency: (tx as Transaction).currency,
},
underlag: parsed.data.underlag,
candidates,
entityType: ((company?.entity_type as EntityType | undefined) ?? 'enskild_firma'),
vatRegistered: settings?.vat_registered ?? false,
samples: parsed.data.samples,
})
return NextResponse.json({ data: { ...selection, candidates } })
} catch (err) {
return NextResponse.json({ error: getUserErrorMessage(err) }, { status: 500 })
}
}