fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, createMockRouteParams, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({ requireAuth: () => requireAuthMock() }))
|
||||
vi.mock('@/lib/company/context', () => ({ getActiveCompanyId: vi.fn().mockResolvedValue('company-1') }))
|
||||
const checkRate = vi.fn()
|
||||
vi.mock('@/lib/rate-limits/agent', () => ({
|
||||
checkAgentRateLimit: () => checkRate(),
|
||||
agentRateLimitResponseBody: () => ({ error: 'rate' }),
|
||||
}))
|
||||
vi.mock('@/lib/sandbox/guard', () => ({ guardSandbox: vi.fn().mockResolvedValue(null) }))
|
||||
const requireCapability = vi.fn()
|
||||
vi.mock('@/lib/entitlements/has-capability', () => ({ requireCapability: () => requireCapability() }))
|
||||
vi.mock('@/lib/entitlements/keys', () => ({ CAPABILITY: { ai: 'ai' } }))
|
||||
const aiStatus = vi.fn()
|
||||
vi.mock('@/lib/ai', () => ({ getAiStatus: () => aiStatus() }))
|
||||
const gatherCandidates = vi.fn()
|
||||
vi.mock('@/lib/agent/categorize/candidates', () => ({ gatherCandidates: (...a: unknown[]) => gatherCandidates(...a) }))
|
||||
const gatherUnderlag = vi.fn()
|
||||
vi.mock('@/lib/agent/categorize/underlag', () => ({ gatherUnderlag: (...a: unknown[]) => gatherUnderlag(...a) }))
|
||||
const selectAccount = vi.fn()
|
||||
vi.mock('@/lib/agent/categorize/select-account', () => ({ selectAccount: (...a: unknown[]) => selectAccount(...a) }))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
// supabase router: membership + transactions + companies + company_settings.
|
||||
function makeSupabase(opts: { tx?: unknown; member?: boolean } = {}) {
|
||||
return {
|
||||
auth: { getUser: vi.fn() },
|
||||
from(table: string) {
|
||||
const rows: Record<string, unknown> = {
|
||||
company_members: opts.member === false ? null : { user_id: 'user-1' },
|
||||
transactions: opts.tx === undefined ? { id: 'tx-1' } : opts.tx,
|
||||
companies: { entity_type: 'aktiebolag' },
|
||||
company_settings: { vat_registered: true },
|
||||
}
|
||||
const chain = {
|
||||
select: () => chain,
|
||||
eq: () => chain,
|
||||
maybeSingle: async () => ({ data: rows[table] ?? null }),
|
||||
}
|
||||
return chain
|
||||
},
|
||||
}
|
||||
}
|
||||
const supabase = makeSupabase()
|
||||
|
||||
const VALID_TX = '11111111-1111-4111-8111-111111111111'
|
||||
const body = (o: Record<string, unknown> = {}) => ({ transaction_id: VALID_TX, ...o })
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
checkRate.mockResolvedValue({ ok: true })
|
||||
requireCapability.mockResolvedValue(null)
|
||||
aiStatus.mockReturnValue({ configured: true })
|
||||
gatherCandidates.mockResolvedValue([{ account: '5410', label: 'Material', vatTreatment: 'standard_25', source: 'counterparty_template', confidence: 0.9 }])
|
||||
gatherUnderlag.mockResolvedValue('Kvitto: Biltema, totalt 499 SEK.')
|
||||
selectAccount.mockResolvedValue({
|
||||
account: '5410', category: null, vatTreatment: 'standard_25', reverseCharge: false,
|
||||
confidence: 0.86, modelConfidence: 'high', agreement: 1, reasoning: 'r',
|
||||
choice: { kind: 'candidate', account: '5410' }, model: 'qwen3.8', fromCandidate: true,
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/agent/categorize', () => {
|
||||
it('401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: null, supabase, error: NextResponse.json({ error: 'x' }, { status: 401 }) })
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))).status).toBe(401)
|
||||
expect(selectAccount).not.toHaveBeenCalled()
|
||||
})
|
||||
it('resolves the session through requireAuth (withRouteContext), never a hand-rolled getUser()', async () => {
|
||||
await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
expect(requireAuthMock).toHaveBeenCalledTimes(1)
|
||||
expect(supabase.auth.getUser).not.toHaveBeenCalled()
|
||||
})
|
||||
it('403 when the body names a company the caller is not a member of', async () => {
|
||||
const other = '22222222-2222-4222-8222-222222222222'
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: makeSupabase({ member: false }), error: null })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ company_id: other }) }), createMockRouteParams({}))
|
||||
expect(res.status).toBe(403)
|
||||
expect(selectAccount).not.toHaveBeenCalled()
|
||||
})
|
||||
it('uses the active company without a membership round trip when no override is given', async () => {
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
expect(res.status).toBe(200)
|
||||
expect(gatherCandidates).toHaveBeenCalledWith(expect.anything(), 'company-1', expect.anything())
|
||||
})
|
||||
it('429 when rate limited', async () => {
|
||||
checkRate.mockResolvedValue({ ok: false })
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))).status).toBe(429)
|
||||
})
|
||||
it('400 on a missing/invalid transaction_id', async () => {
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: {} }), createMockRouteParams({}))).status).toBe(400)
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: { transaction_id: 'nope' } }), createMockRouteParams({}))).status).toBe(400)
|
||||
})
|
||||
it('403 without the ai capability', async () => {
|
||||
requireCapability.mockResolvedValue(NextResponse.json({ error: 'pay' }, { status: 403 }))
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))).status).toBe(403)
|
||||
})
|
||||
it('503 when no backend is configured', async () => {
|
||||
aiStatus.mockReturnValue({ configured: false })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
const { status, body: b } = await parseJsonResponse<{ code: string }>(res)
|
||||
expect(status).toBe(503)
|
||||
expect(b.code).toBe('ai_unconfigured')
|
||||
expect(selectAccount).not.toHaveBeenCalled()
|
||||
})
|
||||
it('404 when the transaction is not found / not this company', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: makeSupabase({ tx: null }), error: null })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
expect(res.status).toBe(404)
|
||||
expect(selectAccount).not.toHaveBeenCalled()
|
||||
})
|
||||
it('returns the selection + candidate slate on the happy path', async () => {
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ samples: 3, underlag: 'Biltema AB 499 kr' }) }), createMockRouteParams({}))
|
||||
const { status, body: b } = await parseJsonResponse<{
|
||||
data: { account: string; confidence: number; candidates: { account: string }[] }
|
||||
}>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(b.data.account).toBe('5410')
|
||||
expect(b.data.confidence).toBe(0.86)
|
||||
expect(b.data.candidates[0].account).toBe('5410')
|
||||
// A caller-supplied underlag is used verbatim (no server gather).
|
||||
expect(gatherUnderlag).not.toHaveBeenCalled()
|
||||
expect(selectAccount).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ entityType: 'aktiebolag', vatRegistered: true, underlag: 'Biltema AB 499 kr', samples: 3 }),
|
||||
)
|
||||
})
|
||||
|
||||
it('gathers underlag server-side when the caller did not supply it', async () => {
|
||||
await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
expect(gatherUnderlag).toHaveBeenCalled()
|
||||
expect(selectAccount).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ underlag: 'Kvitto: Biltema, totalt 499 SEK.' }),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,107 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest } from '@/tests/helpers'
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({ requireAuth: () => requireAuthMock() }))
|
||||
vi.mock('@/lib/company/context', () => ({ getActiveCompanyId: vi.fn().mockResolvedValue('company-1') }))
|
||||
const guardSandbox = vi.fn()
|
||||
vi.mock('@/lib/sandbox/guard', () => ({ guardSandbox: () => guardSandbox() }))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const inserts: Record<string, unknown>[] = []
|
||||
// company_settings.maybeSingle() feeds the consent gate; company_members
|
||||
// feeds the membership check. Default: a member of an opted-in company.
|
||||
function makeSupabase(membership: unknown = { user_id: 'user-1' }, optedIn = true) {
|
||||
return {
|
||||
from(table: string) {
|
||||
const chain = {
|
||||
select: () => chain,
|
||||
eq: () => chain,
|
||||
maybeSingle: async () =>
|
||||
table === 'company_settings'
|
||||
? { data: { data_analysis_opt_in: optedIn }, error: null }
|
||||
: { data: membership, error: null },
|
||||
insert: async (payload: Record<string, unknown>) => {
|
||||
if (table === 'categorize_calibration_samples') inserts.push(payload)
|
||||
return { error: null }
|
||||
},
|
||||
}
|
||||
return chain
|
||||
},
|
||||
}
|
||||
}
|
||||
const supabase = makeSupabase()
|
||||
|
||||
const body = (o: Record<string, unknown> = {}) => ({ confidence: 0.9, booked_account: '5410', ...o })
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
inserts.length = 0
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
guardSandbox.mockResolvedValue(null)
|
||||
})
|
||||
|
||||
describe('POST /api/agent/categorize/outcome', () => {
|
||||
it('401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: null, supabase, error: NextResponse.json({ error: 'x' }, { status: 401 }) })
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }))).status).toBe(401)
|
||||
})
|
||||
|
||||
it('400 on an invalid body', async () => {
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: { confidence: 2 } }))).status).toBe(400)
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: { booked_account: '5410' } }))).status).toBe(400)
|
||||
})
|
||||
|
||||
it('403 without company membership', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: makeSupabase(null), error: null })
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }))).status).toBe(403)
|
||||
})
|
||||
|
||||
it('skips sandbox bookings (204, no sample)', async () => {
|
||||
guardSandbox.mockResolvedValue(NextResponse.json({ error: 'sandbox' }, { status: 403 }))
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }))
|
||||
expect(res.status).toBe(204)
|
||||
expect(inserts).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('skips companies that have not opted in to data analysis (204, no sample)', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: makeSupabase({ user_id: 'user-1' }, false), error: null })
|
||||
const res = await POST(
|
||||
createMockRequest('/x', { method: 'POST', body: body({ proposed_account: '5410', booked_account: '5410' }) }),
|
||||
)
|
||||
expect(res.status).toBe(204)
|
||||
expect(inserts).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('logs was_correct=true when the proposed account was booked (opted-in company)', async () => {
|
||||
const res = await POST(
|
||||
createMockRequest('/x', {
|
||||
method: 'POST',
|
||||
body: body({ proposed_account: '5410', booked_account: '5410', confidence: 0.86, source: 'counterparty_template', amount: 499 }),
|
||||
}),
|
||||
)
|
||||
expect(res.status).toBe(204)
|
||||
expect(inserts).toHaveLength(1)
|
||||
expect(inserts[0]).toMatchObject({
|
||||
company_id: 'company-1',
|
||||
confidence: 0.86,
|
||||
proposed_account: '5410',
|
||||
booked_account: '5410',
|
||||
was_correct: true,
|
||||
source: 'counterparty_template',
|
||||
amount: 499,
|
||||
})
|
||||
})
|
||||
|
||||
it('logs was_correct=false when the user booked a different account', async () => {
|
||||
await POST(createMockRequest('/x', { method: 'POST', body: body({ proposed_account: '5410', booked_account: '6110' }) }))
|
||||
expect(inserts[0].was_correct).toBe(false)
|
||||
})
|
||||
|
||||
it('logs was_correct=false when there was no proposed account', async () => {
|
||||
await POST(createMockRequest('/x', { method: 'POST', body: body({ proposed_account: null, booked_account: '5410' }) }))
|
||||
expect(inserts[0].was_correct).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,89 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { isDataAnalysisOptedIn } from '@/lib/company/data-analysis'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
|
||||
/**
|
||||
* POST /api/agent/categorize/outcome: log one calibration sample.
|
||||
*
|
||||
* Called (fire-and-forget) after a user books an AI proposal: it records the
|
||||
* confidence the model reported and whether the proposed account was the one
|
||||
* actually booked. That corpus is what lib/agent/categorize/calibration.ts
|
||||
* later fits an isotonic calibrator on, so "säker" can be made to mean ~right.
|
||||
*
|
||||
* Telemetry only: it never posts anything and is gated on auth + membership.
|
||||
* Sandbox bookings run on seed data, so they are silently skipped (a 204) to
|
||||
* keep the corpus clean. The corpus is read across companies, so it only
|
||||
* collects from companies that opted in to data analysis
|
||||
* (company_settings.data_analysis_opt_in, #1346): everyone else gets the same
|
||||
* silent 204 and no row.
|
||||
*/
|
||||
|
||||
const Schema = z.object({
|
||||
company_id: z.string().uuid().optional(),
|
||||
confidence: z.number().min(0).max(1),
|
||||
proposed_account: z.string().max(20).nullable().optional(),
|
||||
booked_account: z.string().min(1).max(20),
|
||||
agreement: z.number().min(0).max(1).nullable().optional(),
|
||||
model_confidence: z.enum(['high', 'medium', 'low']).nullable().optional(),
|
||||
source: z.string().max(40).nullable().optional(),
|
||||
amount: z.number().nullable().optional(),
|
||||
})
|
||||
|
||||
const noContent = () => new Response(null, { status: 204 })
|
||||
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
const { user, supabase, error } = await requireAuth()
|
||||
if (error) return error
|
||||
|
||||
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: 'Invalid body' }, { status: 400 })
|
||||
|
||||
const companyId = parsed.data.company_id ?? (await getActiveCompanyId(supabase, user.id))
|
||||
if (!companyId) return noContent()
|
||||
|
||||
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 })
|
||||
|
||||
// Sandbox bookings are seed data: don't pollute the calibration corpus.
|
||||
const blocked = await guardSandbox(supabase, companyId)
|
||||
if (blocked) return noContent()
|
||||
|
||||
// Consent gate: the corpus is analysed across companies, so a company that
|
||||
// has not opted in contributes nothing (default false, no grandfathering).
|
||||
if (!(await isDataAnalysisOptedIn(supabase, companyId))) return noContent()
|
||||
|
||||
const proposed = parsed.data.proposed_account ?? null
|
||||
|
||||
// Best-effort: a failed telemetry insert must never surface to the user.
|
||||
try {
|
||||
await supabase.from('categorize_calibration_samples').insert({
|
||||
company_id: companyId,
|
||||
confidence: parsed.data.confidence,
|
||||
agreement: parsed.data.agreement ?? null,
|
||||
model_confidence: parsed.data.model_confidence ?? null,
|
||||
source: parsed.data.source ?? null,
|
||||
proposed_account: proposed,
|
||||
booked_account: parsed.data.booked_account,
|
||||
was_correct: proposed !== null && proposed === parsed.data.booked_account,
|
||||
amount: parsed.data.amount ?? null,
|
||||
})
|
||||
} catch {
|
||||
// swallow
|
||||
}
|
||||
|
||||
return noContent()
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { parseEntityType } from '@/lib/company/entity-type'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-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 { gatherUnderlag } from '@/lib/agent/categorize/underlag'
|
||||
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(),
|
||||
})
|
||||
|
||||
// withRouteContext enforces auth (MFA on hosted) and resolves the active
|
||||
// company; the body may still name another company the caller belongs to.
|
||||
export const POST = withRouteContext(
|
||||
'agent.categorize',
|
||||
async (request, { user, supabase, companyId: activeCompanyId }) => {
|
||||
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 ?? activeCompanyId
|
||||
|
||||
// The wrapper already guarantees membership of the active company; an
|
||||
// explicit company_id override must be verified the same way.
|
||||
if (companyId !== activeCompanyId) {
|
||||
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, document_id')
|
||||
.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 {
|
||||
// Gather the matched receipt/invoice text when the caller didn't supply it:
|
||||
// this is what lifts the cold-start case — the model reads the actual
|
||||
// supplier + line items, not just the bank line. Best-effort; '' if none.
|
||||
const underlag =
|
||||
parsed.data.underlag ??
|
||||
(await gatherUnderlag(
|
||||
supabase,
|
||||
companyId,
|
||||
(tx as Transaction).id,
|
||||
(tx as { document_id?: string | null }).document_id,
|
||||
))
|
||||
|
||||
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,
|
||||
candidates,
|
||||
entityType: parseEntityType(company?.entity_type),
|
||||
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 })
|
||||
}
|
||||
},
|
||||
)
|
||||
Reference in New Issue
Block a user