feat: remove AI extensions, restructure settings, and add atomic voucher commits (#157)
Remove AI-dependent extensions (ai-chat, ai-categorization, receipt-ocr, invoice-inbox) and their infrastructure (lib/ai/*, ai-consent, LangChain/ Anthropic/OpenAI deps) to simplify core and reduce bundle size. Restructure monolithic settings page into dedicated sub-pages (company, bookkeeping, invoicing, tax, banking, api, account, team, templates) with shared layout and sidebar navigation. Add atomic commit_journal_entry RPC so voucher number increment and status update happen in a single transaction — prevents burned numbers on constraint failures. Add continuity check report and voucher gap explanation tracking. Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
e89f2c402d
commit
d0b3f21bde
@@ -1,161 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import type { ApiRouteDefinition, ExtensionContext } from '@/lib/extensions/types'
|
||||
import type { CategorizationSuggestion } from './categorizer'
|
||||
import { categorizeTransactions, getSettings, saveSettings } from './index'
|
||||
|
||||
// ============================================================
|
||||
// /suggestions — GET: fetch stored suggestions
|
||||
// ============================================================
|
||||
|
||||
async function handleGetSuggestions(
|
||||
request: Request,
|
||||
ctx?: ExtensionContext
|
||||
): Promise<Response> {
|
||||
const userId = ctx!.userId
|
||||
const { createClient } = await import('@/lib/supabase/server')
|
||||
const supabase = await createClient()
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const idsParam = searchParams.get('transaction_ids')
|
||||
|
||||
if (!idsParam) {
|
||||
return NextResponse.json({ error: 'transaction_ids is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const transactionIds = idsParam.split(',').filter(Boolean).slice(0, 50)
|
||||
|
||||
// Read stored suggestions from extension_data
|
||||
const keys = transactionIds.map((id) => `suggestion:${id}`)
|
||||
|
||||
const { data: records } = await supabase
|
||||
.from('extension_data')
|
||||
.select('key, value')
|
||||
.eq('company_id', userId)
|
||||
.eq('extension_id', 'ai-categorization')
|
||||
.in('key', keys)
|
||||
|
||||
const suggestions: Record<string, CategorizationSuggestion> = {}
|
||||
if (records) {
|
||||
for (const record of records) {
|
||||
const txId = record.key.replace('suggestion:', '')
|
||||
suggestions[txId] = record.value as unknown as CategorizationSuggestion
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ suggestions })
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// /suggestions — POST: trigger on-demand categorization
|
||||
// ============================================================
|
||||
|
||||
async function handlePostSuggestions(
|
||||
request: Request,
|
||||
ctx?: ExtensionContext
|
||||
): Promise<Response> {
|
||||
const userId = ctx!.userId
|
||||
|
||||
const body = await request.json()
|
||||
const { transaction_ids } = body
|
||||
|
||||
if (!Array.isArray(transaction_ids) || transaction_ids.length === 0) {
|
||||
return NextResponse.json({ error: 'transaction_ids is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const ids = transaction_ids.slice(0, 50)
|
||||
|
||||
try {
|
||||
const suggestions = await categorizeTransactions(userId, ids)
|
||||
|
||||
// Group by transaction ID
|
||||
const grouped: Record<string, CategorizationSuggestion> = {}
|
||||
for (const s of suggestions) {
|
||||
grouped[s.transactionId] = s
|
||||
}
|
||||
|
||||
return NextResponse.json({ suggestions: grouped })
|
||||
} catch (error) {
|
||||
console.error('[ai-categorization] On-demand categorization failed:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'AI categorization failed' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// /settings — GET: get current settings
|
||||
// ============================================================
|
||||
|
||||
async function handleGetSettings(
|
||||
_request: Request,
|
||||
ctx?: ExtensionContext
|
||||
): Promise<Response> {
|
||||
const userId = ctx!.userId
|
||||
const settings = await getSettings(userId)
|
||||
return NextResponse.json({ data: settings })
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// /settings — PUT/PATCH: update settings
|
||||
// ============================================================
|
||||
|
||||
async function handleUpdateSettings(
|
||||
request: Request,
|
||||
ctx?: ExtensionContext
|
||||
): Promise<Response> {
|
||||
const userId = ctx!.userId
|
||||
const body = await request.json()
|
||||
|
||||
// Validate setting keys
|
||||
const allowedKeys = [
|
||||
'autoSuggestEnabled',
|
||||
'confidenceThreshold',
|
||||
'providerModel',
|
||||
]
|
||||
const filtered: Record<string, unknown> = {}
|
||||
for (const key of allowedKeys) {
|
||||
if (key in body) {
|
||||
filtered[key] = body[key]
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(filtered).length === 0) {
|
||||
return NextResponse.json({ error: 'No valid settings provided' }, { status: 400 })
|
||||
}
|
||||
|
||||
const settings = await saveSettings(userId, filtered)
|
||||
return NextResponse.json({ data: settings })
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Route definitions
|
||||
// ============================================================
|
||||
|
||||
export const aiCategorizationApiRoutes: ApiRouteDefinition[] = [
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/suggestions',
|
||||
handler: handleGetSuggestions,
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/suggestions',
|
||||
handler: handlePostSuggestions,
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/settings',
|
||||
handler: handleGetSettings,
|
||||
},
|
||||
{
|
||||
method: 'PUT',
|
||||
path: '/settings',
|
||||
handler: handleUpdateSettings,
|
||||
},
|
||||
{
|
||||
method: 'PATCH',
|
||||
path: '/settings',
|
||||
handler: handleUpdateSettings,
|
||||
},
|
||||
]
|
||||
@@ -1,465 +0,0 @@
|
||||
/**
|
||||
* AI Categorization Engine
|
||||
*
|
||||
* SERVER-ONLY: Uses the Anthropic SDK and must only be imported
|
||||
* in server components or API routes.
|
||||
*
|
||||
* Provider-abstracted AI categorization for Swedish BAS account mapping.
|
||||
* Uses Claude Haiku with structured tool outputs for reliable JSON.
|
||||
* Accepts pre-filtered candidate templates from embedding search (Tier 2)
|
||||
* instead of dumping all ~100 templates into the prompt.
|
||||
*/
|
||||
|
||||
import 'server-only'
|
||||
import Anthropic from '@anthropic-ai/sdk'
|
||||
import { BOOKING_TEMPLATES, type BookingTemplate } from '@/lib/bookkeeping/booking-templates'
|
||||
import type { TransactionCategory, EntityType } from '@/types'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
// ============================================================
|
||||
// Types
|
||||
// ============================================================
|
||||
|
||||
export interface TransactionForCategorization {
|
||||
id: string
|
||||
description: string
|
||||
amount: number
|
||||
date: string
|
||||
merchant_name: string | null
|
||||
mcc_code: number | null
|
||||
currency: string
|
||||
}
|
||||
|
||||
export interface AccountUsageEntry {
|
||||
account_number: string
|
||||
count: number
|
||||
}
|
||||
|
||||
export interface MerchantHistoryEntry {
|
||||
merchant_name: string
|
||||
category: string
|
||||
template_id: string | null
|
||||
count: number
|
||||
}
|
||||
|
||||
export interface CategorizationContext {
|
||||
entityType: EntityType
|
||||
recentHistory: { description: string; category: string }[]
|
||||
}
|
||||
|
||||
export interface DocumentEnrichment {
|
||||
type: 'receipt' | 'supplier_invoice'
|
||||
merchantName?: string
|
||||
lineItems?: Array<{ description: string; amount: number; category?: string; accountSuggestion?: string }>
|
||||
vatBreakdown?: Array<{ rate: number; amount: number }>
|
||||
isReverseCharge?: boolean
|
||||
}
|
||||
|
||||
export interface EnrichedCategorizationContext extends CategorizationContext {
|
||||
candidateTemplates: BookingTemplate[]
|
||||
userAccountUsage: AccountUsageEntry[]
|
||||
merchantHistory: MerchantHistoryEntry[]
|
||||
documentData?: DocumentEnrichment
|
||||
}
|
||||
|
||||
export interface CategorizationSuggestion {
|
||||
transactionId: string
|
||||
category: TransactionCategory
|
||||
basAccount: string
|
||||
taxCode: string | null
|
||||
confidence: number
|
||||
reasoning: string
|
||||
isPrivate: boolean
|
||||
templateId?: string
|
||||
}
|
||||
|
||||
export interface TrackingContext {
|
||||
supabase: SupabaseClient
|
||||
userId: string
|
||||
companyId?: string
|
||||
}
|
||||
|
||||
export interface CategorizationProvider {
|
||||
categorize(
|
||||
transactions: TransactionForCategorization[],
|
||||
context: CategorizationContext | EnrichedCategorizationContext,
|
||||
tracking?: TrackingContext
|
||||
): Promise<CategorizationSuggestion[]>
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// BAS Account + Category Mapping (used in prompt)
|
||||
// ============================================================
|
||||
|
||||
function getCategoryAccountMap(entityType: EntityType): Record<string, { account: string; label: string }> {
|
||||
const educationAccount = entityType === 'aktiebolag' ? '7610' : '6991'
|
||||
return {
|
||||
income_services: { account: '3001', label: 'Tjänsteförsäljning' },
|
||||
income_products: { account: '3001', label: 'Varuförsäljning' },
|
||||
income_other: { account: '3900', label: 'Övriga intäkter' },
|
||||
expense_equipment: { account: '5410', label: 'Förbrukningsinventarier' },
|
||||
expense_software: { account: '5420', label: 'Programvara' },
|
||||
expense_travel: { account: '5800', label: 'Resekostnader' },
|
||||
expense_office: { account: '5010', label: 'Lokalhyra/kontorskostnad' },
|
||||
expense_marketing: { account: '5910', label: 'Annonsering/marknadsföring' },
|
||||
expense_professional_services: { account: '6530', label: 'Redovisning/konsulttjänster' },
|
||||
expense_education: { account: educationAccount, label: 'Utbildning' },
|
||||
expense_representation: { account: '6071', label: 'Representation (mat/möte)' },
|
||||
expense_consumables: { account: '5460', label: 'Förbrukningsvaror' },
|
||||
expense_vehicle: { account: '5611', label: 'Bil & drivmedel' },
|
||||
expense_telecom: { account: '6200', label: 'Telefon & internet' },
|
||||
expense_bank_fees: { account: '6570', label: 'Bankavgifter' },
|
||||
expense_card_fees: { account: '6570', label: 'Kortavgifter' },
|
||||
expense_currency_exchange: { account: '7960', label: 'Valutakursförluster' },
|
||||
expense_interest: { account: '8410', label: 'Räntekostnader' },
|
||||
financial_loan_repayment: { account: '2350', label: 'Amortering lån (kreditinstitut)' },
|
||||
expense_other: { account: '6991', label: 'Övriga kostnader' },
|
||||
}
|
||||
}
|
||||
|
||||
/** Fallback template IDs when AI doesn't provide one */
|
||||
const CATEGORY_DEFAULT_TEMPLATES: Record<string, string> = {
|
||||
expense_representation: 'representation_external',
|
||||
expense_equipment: 'equipment_small',
|
||||
expense_software: 'it_saas_subscription',
|
||||
expense_travel: 'travel_transport',
|
||||
expense_office: 'office_supplies_general',
|
||||
expense_consumables: 'office_supplies_general',
|
||||
expense_vehicle: 'vehicle_fuel',
|
||||
expense_telecom: 'telecom_mobile',
|
||||
expense_marketing: 'marketing_online_ads_eu',
|
||||
expense_education: 'education_course',
|
||||
expense_professional_services: 'prof_accounting',
|
||||
}
|
||||
|
||||
/**
|
||||
* Build template reference from candidate templates (pre-filtered by embeddings)
|
||||
* or fall back to full template list if no candidates provided.
|
||||
*/
|
||||
function getTemplateReference(
|
||||
direction: 'expense' | 'income',
|
||||
candidateTemplates?: BookingTemplate[]
|
||||
): string {
|
||||
const templates = candidateTemplates && candidateTemplates.length > 0
|
||||
? candidateTemplates
|
||||
: BOOKING_TEMPLATES
|
||||
|
||||
return templates
|
||||
.filter((t) => t.direction === direction || t.direction === 'transfer')
|
||||
.map((t) => `${t.id}: ${t.name_sv} → ${t.debit_account}/${t.credit_account}`)
|
||||
.join('\n')
|
||||
}
|
||||
|
||||
const NON_DEDUCTIBLE_RULES = `
|
||||
MOMSREGLER FÖR SPECIFIKA KATEGORIER:
|
||||
- Representation/måltider: Max 300 kr/person exkl. moms (IL 16 kap 2§), konto 6071/6072
|
||||
- Gåvor: Reklamgåvor max 300 kr/mottagare, representationsgåvor max 180 kr
|
||||
- Telefon/dator vid blandad användning: Bara yrkesmässig del avdragsgill
|
||||
`
|
||||
|
||||
// ============================================================
|
||||
// Classify Transaction Tool Schema
|
||||
// ============================================================
|
||||
|
||||
const CLASSIFY_TOOL: Anthropic.Tool = {
|
||||
name: 'classify_transactions',
|
||||
description: 'Classify a batch of bank transactions into Swedish BAS accounts and booking templates.',
|
||||
input_schema: {
|
||||
type: 'object' as const,
|
||||
properties: {
|
||||
suggestions: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
transactionId: { type: 'string', description: 'Transaction ID' },
|
||||
templateId: { type: 'string', description: 'Booking template ID (REQUIRED — must be from the provided templates list)' },
|
||||
category: { type: 'string', description: 'Transaction category (e.g. expense_representation, expense_equipment, expense_office)' },
|
||||
basAccount: { type: 'string', description: 'BAS account number (4 digits)' },
|
||||
taxCode: { type: ['string', 'null'], description: 'Tax code: MPI for deductible expenses with VAT, MP1 for income with VAT, null for VAT-exempt/private' },
|
||||
confidence: { type: 'number', description: 'Confidence score 0.0-1.0' },
|
||||
reasoning: { type: 'string', description: 'Short reasoning in Swedish' },
|
||||
isPrivate: { type: 'boolean', description: 'Whether this is a private expense' },
|
||||
},
|
||||
required: ['transactionId', 'templateId', 'category', 'basAccount', 'confidence', 'reasoning', 'isPrivate'],
|
||||
},
|
||||
},
|
||||
},
|
||||
required: ['suggestions'],
|
||||
},
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Anthropic Provider
|
||||
// ============================================================
|
||||
|
||||
const MAX_RETRIES = 3
|
||||
const RETRY_DELAY_MS = 1000
|
||||
const MAX_BATCH_SIZE = 20
|
||||
|
||||
export class AnthropicCategorizationProvider implements CategorizationProvider {
|
||||
private client: Anthropic
|
||||
private model: string
|
||||
|
||||
constructor(model = 'claude-haiku-4-5-20251001') {
|
||||
this.client = new Anthropic()
|
||||
this.model = model
|
||||
}
|
||||
|
||||
async categorize(
|
||||
transactions: TransactionForCategorization[],
|
||||
context: CategorizationContext | EnrichedCategorizationContext,
|
||||
tracking?: TrackingContext
|
||||
): Promise<CategorizationSuggestion[]> {
|
||||
// Cap batch size
|
||||
const batch = transactions.slice(0, MAX_BATCH_SIZE)
|
||||
if (batch.length === 0) return []
|
||||
|
||||
const enriched = isEnrichedContext(context) ? context : null
|
||||
const privateAccount = context.entityType === 'aktiebolag' ? '2893' : '2013'
|
||||
const categoryAccountMap = getCategoryAccountMap(context.entityType)
|
||||
|
||||
// Build template references — use candidate templates if available
|
||||
const hasExpenses = batch.some((t) => t.amount < 0)
|
||||
const hasIncome = batch.some((t) => t.amount > 0)
|
||||
const candidates = enriched?.candidateTemplates
|
||||
const templateRef = [
|
||||
hasExpenses ? `UTGIFTSMALLAR:\n${getTemplateReference('expense', candidates)}` : '',
|
||||
hasIncome ? `INTÄKTSMALLAR:\n${getTemplateReference('income', candidates)}` : '',
|
||||
].filter(Boolean).join('\n\n')
|
||||
|
||||
// Build account usage context
|
||||
const accountUsageContext = enriched?.userAccountUsage && enriched.userAccountUsage.length > 0
|
||||
? `\nAnvändarens mest använda konton:\n${enriched.userAccountUsage
|
||||
.slice(0, 15)
|
||||
.map((a) => `- ${a.account_number} (${a.count} bokningar)`)
|
||||
.join('\n')}`
|
||||
: ''
|
||||
|
||||
// Build merchant history context
|
||||
const merchantHistoryContext = enriched?.merchantHistory && enriched.merchantHistory.length > 0
|
||||
? `\nTidigare kategorisering av dessa handlare:\n${enriched.merchantHistory
|
||||
.map((m) => `- "${m.merchant_name}" → ${m.category}${m.template_id ? ` (mall: ${m.template_id})` : ''} (${m.count}x)`)
|
||||
.join('\n')}`
|
||||
: ''
|
||||
|
||||
// Build document enrichment context (from linked receipt or supplier invoice)
|
||||
const documentContext = enriched?.documentData
|
||||
? buildDocumentContext(enriched.documentData)
|
||||
: ''
|
||||
|
||||
const systemPrompt = `Du är expert på svensk bokföring och kategorisering av banktransaktioner enligt BAS-kontoplanen.
|
||||
Din uppgift är att kategorisera varje transaktion till rätt mall-ID (templateId) och BAS-konto.
|
||||
|
||||
BOKFÖRINGSMALLAR (id: namn → debitkonto/kreditkonto):
|
||||
${templateRef}
|
||||
|
||||
KATEGORIER (fallback om ingen mall matchar):
|
||||
${Object.entries(categoryAccountMap)
|
||||
.map(([cat, info]) => `- ${cat}: ${info.account} (${info.label})`)
|
||||
.join('\n')}
|
||||
|
||||
Företagsform: ${context.entityType === 'aktiebolag' ? 'Aktiebolag (AB)' : 'Enskild firma (EF)'}
|
||||
Privatkonto: ${privateAccount}
|
||||
|
||||
MOMSHANTERING:
|
||||
- Bankavgifter, kortavgifter, valutaväxling: MOMSFRIA
|
||||
- Övriga affärskostnader: Normalt 25% moms (ingående moms, MPI)
|
||||
- Intäkter: Normalt 25% moms (utgående moms, MP1)
|
||||
|
||||
${NON_DEDUCTIBLE_RULES}
|
||||
${documentContext}
|
||||
REGLER:
|
||||
1. Negativa belopp = utgifter, positiva = intäkter
|
||||
2. VIKTIGT: Dessa transaktioner kommer från företagets bankkonto/kort. Anta ALLTID att de är affärsrelaterade. Klassificera ALDRIG som "private" — det beslutet tar användaren själv.
|
||||
3. Ange confidence 0.0-1.0 baserat på hur säker du är på rätt affärskategori
|
||||
4. Ange kort reasoning på svenska
|
||||
5. Restauranger/mat/café → expense_representation (6071). Bygghandel/järnhandel → expense_equipment eller expense_consumables. Heminredning/kontorsvaror → expense_office.
|
||||
6. taxCode: "MPI" för avdragsgilla affärskostnader med moms, "MP1" för intäkter med moms, null för momsfria
|
||||
7. templateId är OBLIGATORISKT — välj alltid den mest passande mallen från listan ovan, även för alternativa förslag
|
||||
8. isPrivate ska ALLTID vara false — användaren avgör själv vad som är privat
|
||||
9. Ange TVÅ förslag per transaktion: ett primärt (mest troligt) och ett alternativt (näst mest troligt, annan kategori, lägre confidence). Båda ska vara affärskategorier.
|
||||
10. SKULDER: Konto 2440 (leverantörsskulder) ska BARA användas för leverantörsfakturor. Lån/amorteringar från banker eller kreditinstitut (Almi, Nordea, SEB, Handelsbanken, Swedbank, etc.) ska använda 2350 (skulder till kreditinstitut) via mallen financial_loan_repayment. Räntebetalningar ska använda 8410 (räntekostnader).`
|
||||
|
||||
const historyContext =
|
||||
context.recentHistory.length > 0
|
||||
? `\nAnvändarens senaste kategoriseringar (lär dig mönster):\n${context.recentHistory
|
||||
.slice(0, 30)
|
||||
.map((h) => `- "${h.description}" → ${h.category}`)
|
||||
.join('\n')}`
|
||||
: ''
|
||||
|
||||
const transactionList = batch
|
||||
.map(
|
||||
(t, i) =>
|
||||
`${i + 1}. ID: ${t.id}
|
||||
Beskrivning: ${t.description}
|
||||
Belopp: ${t.amount} ${t.currency}
|
||||
Datum: ${t.date}${t.merchant_name ? `\n Handlare: ${t.merchant_name}` : ''}${t.mcc_code ? `\n MCC: ${t.mcc_code}` : ''}`
|
||||
)
|
||||
.join('\n\n')
|
||||
|
||||
const userPrompt = `Kategorisera följande transaktioner med classify_transactions-verktyget.
|
||||
Ange TVÅ förslag per transaktion (primärt + alternativ med lägre confidence):
|
||||
${historyContext}${accountUsageContext}${merchantHistoryContext}
|
||||
|
||||
TRANSAKTIONER:
|
||||
${transactionList}`
|
||||
|
||||
let lastError: Error | null = null
|
||||
|
||||
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
|
||||
try {
|
||||
const message = await this.client.messages.create({
|
||||
model: this.model,
|
||||
max_tokens: 4096,
|
||||
system: [
|
||||
{
|
||||
type: 'text',
|
||||
text: systemPrompt,
|
||||
cache_control: { type: 'ephemeral' },
|
||||
},
|
||||
],
|
||||
tools: [CLASSIFY_TOOL],
|
||||
tool_choice: { type: 'tool', name: 'classify_transactions' },
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: userPrompt,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
// Track token usage (fire-and-forget)
|
||||
if (tracking && message.usage) {
|
||||
const { trackTokenUsage } = await import('@/lib/ai/usage-tracker')
|
||||
trackTokenUsage(tracking.supabase, tracking.userId, 'ai-categorization', {
|
||||
inputTokens: message.usage.input_tokens,
|
||||
outputTokens: message.usage.output_tokens,
|
||||
model: this.model,
|
||||
}, tracking.companyId)
|
||||
}
|
||||
|
||||
// Extract tool_use block from response
|
||||
const toolUseBlock = message.content.find(
|
||||
(block) => block.type === 'tool_use' && block.name === 'classify_transactions'
|
||||
)
|
||||
|
||||
if (!toolUseBlock || toolUseBlock.type !== 'tool_use') {
|
||||
throw new Error('No tool_use block in AI response')
|
||||
}
|
||||
|
||||
const input = toolUseBlock.input as { suggestions?: unknown[] }
|
||||
return this.validateSuggestions(input.suggestions || [], batch, context.entityType)
|
||||
} catch (error) {
|
||||
lastError = error instanceof Error ? error : new Error('Unknown error')
|
||||
|
||||
if (attempt < MAX_RETRIES - 1) {
|
||||
await sleep(RETRY_DELAY_MS * (attempt + 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`AI categorization failed after ${MAX_RETRIES} attempts: ${lastError?.message}`
|
||||
)
|
||||
}
|
||||
|
||||
private validateSuggestions(
|
||||
raw: unknown[],
|
||||
transactions: TransactionForCategorization[],
|
||||
entityType: EntityType
|
||||
): CategorizationSuggestion[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
|
||||
const categoryAccountMap = getCategoryAccountMap(entityType)
|
||||
const validTransactionIds = new Set(transactions.map((t) => t.id))
|
||||
const validCategories = new Set(Object.keys(categoryAccountMap).concat(['uncategorized']))
|
||||
const transactionMap = new Map(transactions.map((t) => [t.id, t]))
|
||||
|
||||
return raw
|
||||
.filter(
|
||||
(s): s is Record<string, unknown> =>
|
||||
s !== null && typeof s === 'object' && 'transactionId' in s
|
||||
)
|
||||
.filter((s) => validTransactionIds.has(s.transactionId as string))
|
||||
.map((s) => {
|
||||
// Never let AI classify as private — remap to expense_other
|
||||
let category = validCategories.has(s.category as string)
|
||||
? (s.category as TransactionCategory)
|
||||
: 'expense_other'
|
||||
if (category === 'private') {
|
||||
category = 'expense_other'
|
||||
}
|
||||
|
||||
// Enforce direction: positive amounts = income, negative = expense
|
||||
const tx = transactionMap.get(s.transactionId as string)
|
||||
if (tx) {
|
||||
if (tx.amount > 0 && category.startsWith('expense_')) {
|
||||
category = 'income_other' as TransactionCategory
|
||||
} else if (tx.amount < 0 && category.startsWith('income_')) {
|
||||
category = 'expense_other' as TransactionCategory
|
||||
}
|
||||
}
|
||||
|
||||
const accountInfo = categoryAccountMap[category]
|
||||
|
||||
return {
|
||||
transactionId: s.transactionId as string,
|
||||
category,
|
||||
basAccount: accountInfo?.account || (s.basAccount as string) || '6991',
|
||||
taxCode: (s.taxCode as string) || null,
|
||||
confidence: Math.max(0, Math.min(1, Number(s.confidence) || 0.5)),
|
||||
reasoning: (s.reasoning as string) || '',
|
||||
isPrivate: false,
|
||||
templateId: (s.templateId as string) || CATEGORY_DEFAULT_TEMPLATES[category] || undefined,
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function buildDocumentContext(doc: DocumentEnrichment): string {
|
||||
const parts: string[] = []
|
||||
|
||||
const typeLabel = doc.type === 'receipt' ? 'KVITTO' : 'LEVERANTÖRSFAKTURA'
|
||||
parts.push(`LÄNKAT DOKUMENT (${typeLabel}):`)
|
||||
|
||||
if (doc.merchantName) {
|
||||
parts.push(`Handlare/leverantör: ${doc.merchantName}`)
|
||||
}
|
||||
|
||||
if (doc.lineItems && doc.lineItems.length > 0) {
|
||||
parts.push('Rader:')
|
||||
for (const item of doc.lineItems) {
|
||||
let line = `- ${item.description}: ${item.amount} kr`
|
||||
if (item.accountSuggestion) line += ` (föreslaget konto: ${item.accountSuggestion})`
|
||||
if (item.category) line += ` [${item.category}]`
|
||||
parts.push(line)
|
||||
}
|
||||
}
|
||||
|
||||
if (doc.vatBreakdown && doc.vatBreakdown.length > 0) {
|
||||
parts.push('Momsfördelning:')
|
||||
for (const vat of doc.vatBreakdown) {
|
||||
parts.push(`- ${vat.rate}%: ${vat.amount} kr`)
|
||||
}
|
||||
}
|
||||
|
||||
if (doc.isReverseCharge) {
|
||||
parts.push(`VIKTIGT: Omvänd skattskyldighet (reverse charge). Använd dubbelkontering:
|
||||
- Debitera 2645 (beräknad ingående moms) OCH kreditera 2614 (utgående moms, omvänd skattskyldighet)
|
||||
- Mallen "purchase_eu_service_reverse_charge" ska användas om tillgänglig`)
|
||||
}
|
||||
|
||||
return parts.join('\n') + '\n'
|
||||
}
|
||||
|
||||
function isEnrichedContext(
|
||||
ctx: CategorizationContext | EnrichedCategorizationContext
|
||||
): ctx is EnrichedCategorizationContext {
|
||||
return 'candidateTemplates' in ctx
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
@@ -1,400 +0,0 @@
|
||||
import type { Extension, ExtensionContext } from '@/lib/extensions/types'
|
||||
import { aiCategorizationApiRoutes } from './api-routes'
|
||||
import type { EventPayload } from '@/lib/events/types'
|
||||
import type { Transaction, EntityType } from '@/types'
|
||||
import {
|
||||
AnthropicCategorizationProvider,
|
||||
type CategorizationProvider,
|
||||
type TransactionForCategorization,
|
||||
type EnrichedCategorizationContext,
|
||||
type CategorizationSuggestion,
|
||||
type AccountUsageEntry,
|
||||
type MerchantHistoryEntry,
|
||||
} from './categorizer'
|
||||
import type { BookingTemplate } from '@/lib/bookkeeping/booking-templates'
|
||||
|
||||
// ============================================================
|
||||
// Settings
|
||||
// ============================================================
|
||||
|
||||
export interface AiCategorizationSettings {
|
||||
autoSuggestEnabled: boolean
|
||||
confidenceThreshold: number
|
||||
providerModel: string
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: AiCategorizationSettings = {
|
||||
autoSuggestEnabled: true,
|
||||
confidenceThreshold: 0.7,
|
||||
providerModel: 'claude-haiku-4-5-20251001',
|
||||
}
|
||||
|
||||
/** Get settings via ExtensionContext (preferred in event handlers) */
|
||||
async function getSettingsViaCtx(ctx: ExtensionContext): Promise<AiCategorizationSettings> {
|
||||
const stored = await ctx.settings.get<Partial<AiCategorizationSettings>>()
|
||||
return { ...DEFAULT_SETTINGS, ...(stored || {}) }
|
||||
}
|
||||
|
||||
/** Get settings for external callers (settings routes, on-demand API) */
|
||||
export async function getSettings(userId: string): Promise<AiCategorizationSettings> {
|
||||
const { createClient } = await import('@/lib/supabase/server')
|
||||
const supabase = await createClient()
|
||||
|
||||
const { data } = await supabase
|
||||
.from('extension_data')
|
||||
.select('value')
|
||||
.eq('company_id', userId)
|
||||
.eq('extension_id', 'ai-categorization')
|
||||
.eq('key', 'settings')
|
||||
.single()
|
||||
|
||||
if (!data?.value) return { ...DEFAULT_SETTINGS }
|
||||
return { ...DEFAULT_SETTINGS, ...(data.value as Partial<AiCategorizationSettings>) }
|
||||
}
|
||||
|
||||
export async function saveSettings(
|
||||
userId: string,
|
||||
partial: Partial<AiCategorizationSettings>
|
||||
): Promise<AiCategorizationSettings> {
|
||||
const current = await getSettings(userId)
|
||||
const merged = { ...current, ...partial }
|
||||
|
||||
const { createClient } = await import('@/lib/supabase/server')
|
||||
const supabase = await createClient()
|
||||
|
||||
await supabase
|
||||
.from('extension_data')
|
||||
.upsert(
|
||||
{
|
||||
user_id: userId,
|
||||
extension_id: 'ai-categorization',
|
||||
key: 'settings',
|
||||
value: merged,
|
||||
},
|
||||
{ onConflict: 'user_id,extension_id,key' }
|
||||
)
|
||||
|
||||
return merged
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Provider
|
||||
// ============================================================
|
||||
|
||||
let provider: CategorizationProvider | null = null
|
||||
|
||||
function getProvider(model?: string): CategorizationProvider {
|
||||
if (!provider) {
|
||||
provider = new AnthropicCategorizationProvider(model)
|
||||
}
|
||||
return provider
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Public API — on-demand categorization
|
||||
// ============================================================
|
||||
|
||||
export async function categorizeTransactions(
|
||||
userId: string,
|
||||
transactionIds: string[]
|
||||
): Promise<CategorizationSuggestion[]> {
|
||||
const { createClient } = await import('@/lib/supabase/server')
|
||||
const supabase = await createClient()
|
||||
const settings = await getSettings(userId)
|
||||
|
||||
// Fetch transactions
|
||||
const { data: transactions } = await supabase
|
||||
.from('transactions')
|
||||
.select('id, description, amount, date, merchant_name, mcc_code, currency')
|
||||
.eq('company_id', userId)
|
||||
.in('id', transactionIds)
|
||||
|
||||
if (!transactions || transactions.length === 0) return []
|
||||
|
||||
const batch: TransactionForCategorization[] = transactions.map((t) => ({
|
||||
id: t.id,
|
||||
description: t.description,
|
||||
amount: t.amount,
|
||||
date: t.date,
|
||||
merchant_name: t.merchant_name,
|
||||
mcc_code: t.mcc_code,
|
||||
currency: t.currency,
|
||||
}))
|
||||
|
||||
const context = await buildEnrichedContext(userId, supabase, batch)
|
||||
|
||||
const aiProvider = getProvider(settings.providerModel)
|
||||
const suggestions = await aiProvider.categorize(batch, context, { supabase, userId })
|
||||
|
||||
// Store suggestions
|
||||
await storeSuggestions(userId, suggestions, supabase)
|
||||
|
||||
return suggestions
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Event Handler
|
||||
// ============================================================
|
||||
|
||||
async function handleTransactionSynced(
|
||||
payload: EventPayload<'transaction.synced'>,
|
||||
ctx?: ExtensionContext
|
||||
): Promise<void> {
|
||||
const { transactions: syncedTransactions, userId } = payload
|
||||
const log = ctx?.log ?? console
|
||||
|
||||
// Gate: Is autoSuggestEnabled?
|
||||
const settings = ctx ? await getSettingsViaCtx(ctx) : await getSettings(userId)
|
||||
if (!settings.autoSuggestEnabled) {
|
||||
return
|
||||
}
|
||||
|
||||
// Gate: Filter to uncategorized transactions only
|
||||
const uncategorized = syncedTransactions.filter(
|
||||
(t: Transaction) => t.is_business === null
|
||||
)
|
||||
if (uncategorized.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
log.info(`Auto-suggest triggered for ${uncategorized.length} uncategorized transactions`)
|
||||
|
||||
try {
|
||||
const supabase = ctx?.supabase ?? await (await import('@/lib/supabase/server')).createClient()
|
||||
|
||||
const batch: TransactionForCategorization[] = uncategorized.map((t: Transaction) => ({
|
||||
id: t.id,
|
||||
description: t.description,
|
||||
amount: t.amount,
|
||||
date: t.date,
|
||||
merchant_name: t.merchant_name,
|
||||
mcc_code: t.mcc_code,
|
||||
currency: t.currency,
|
||||
}))
|
||||
|
||||
const context = await buildEnrichedContext(userId, supabase, batch)
|
||||
const aiProvider = getProvider(settings.providerModel)
|
||||
const suggestions = await aiProvider.categorize(batch, context, { supabase, userId })
|
||||
|
||||
// Store only suggestions above confidence threshold
|
||||
const qualifiedSuggestions = suggestions.filter(
|
||||
(s) => s.confidence >= settings.confidenceThreshold
|
||||
)
|
||||
|
||||
if (qualifiedSuggestions.length > 0) {
|
||||
await storeSuggestions(userId, qualifiedSuggestions, supabase)
|
||||
}
|
||||
|
||||
log.info(
|
||||
`Generated ${suggestions.length} suggestions, ${qualifiedSuggestions.length} above threshold (${settings.confidenceThreshold})`
|
||||
)
|
||||
} catch (error) {
|
||||
log.error('handleTransactionSynced failed:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Helpers
|
||||
// ============================================================
|
||||
|
||||
async function buildEnrichedContext(
|
||||
userId: string,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
supabase: any,
|
||||
transactions: TransactionForCategorization[]
|
||||
): Promise<EnrichedCategorizationContext> {
|
||||
// Fetch entity type
|
||||
const { data: companySettings } = await supabase
|
||||
.from('company_settings')
|
||||
.select('entity_type')
|
||||
.eq('company_id', userId)
|
||||
.single()
|
||||
|
||||
const entityType: EntityType = companySettings?.entity_type || 'enskild_firma'
|
||||
|
||||
// Fetch recent categorization history
|
||||
const { data: historicalTxns } = await supabase
|
||||
.from('transactions')
|
||||
.select('description, category')
|
||||
.eq('company_id', userId)
|
||||
.not('is_business', 'is', null)
|
||||
.neq('category', 'uncategorized')
|
||||
.order('updated_at', { ascending: false })
|
||||
.limit(50)
|
||||
|
||||
const recentHistory = (historicalTxns || []).map(
|
||||
(t: { description: string; category: string }) => ({
|
||||
description: t.description,
|
||||
category: t.category,
|
||||
})
|
||||
)
|
||||
|
||||
// Fetch user's most-used accounts (top 30)
|
||||
const { data: accountUsageRows } = await supabase
|
||||
.from('journal_entry_lines')
|
||||
.select('account_number')
|
||||
.eq('company_id', userId)
|
||||
|
||||
const accountCounts = new Map<string, number>()
|
||||
if (accountUsageRows) {
|
||||
for (const row of accountUsageRows as { account_number: string }[]) {
|
||||
accountCounts.set(row.account_number, (accountCounts.get(row.account_number) || 0) + 1)
|
||||
}
|
||||
}
|
||||
const userAccountUsage: AccountUsageEntry[] = Array.from(accountCounts.entries())
|
||||
.map(([account_number, count]) => ({ account_number, count }))
|
||||
.sort((a, b) => b.count - a.count)
|
||||
.slice(0, 30)
|
||||
|
||||
// Fetch merchant history for this batch's merchants
|
||||
const merchantNames = [...new Set(
|
||||
transactions
|
||||
.map((t) => t.merchant_name)
|
||||
.filter((n): n is string => n !== null && n.length > 0)
|
||||
)]
|
||||
|
||||
let merchantHistory: MerchantHistoryEntry[] = []
|
||||
if (merchantNames.length > 0) {
|
||||
const { data: merchantRows } = await supabase
|
||||
.from('transactions')
|
||||
.select('merchant_name, category, template_id')
|
||||
.eq('company_id', userId)
|
||||
.not('is_business', 'is', null)
|
||||
.neq('category', 'uncategorized')
|
||||
.in('merchant_name', merchantNames)
|
||||
.limit(200)
|
||||
|
||||
if (merchantRows) {
|
||||
const merchantMap = new Map<string, MerchantHistoryEntry>()
|
||||
for (const row of merchantRows as { merchant_name: string; category: string; template_id: string | null }[]) {
|
||||
const key = `${row.merchant_name}:${row.category}`
|
||||
const existing = merchantMap.get(key)
|
||||
if (existing) {
|
||||
existing.count++
|
||||
} else {
|
||||
merchantMap.set(key, {
|
||||
merchant_name: row.merchant_name,
|
||||
category: row.category,
|
||||
template_id: row.template_id,
|
||||
count: 1,
|
||||
})
|
||||
}
|
||||
}
|
||||
merchantHistory = Array.from(merchantMap.values())
|
||||
.sort((a, b) => b.count - a.count)
|
||||
}
|
||||
}
|
||||
|
||||
// Find candidate templates via embedding search
|
||||
// Use a representative subset of transactions to find candidates
|
||||
const { findSimilarTemplates } = await import('./lib/template-embeddings')
|
||||
const representativeTransactions = transactions.slice(0, 5)
|
||||
const candidateMap = new Map<string, BookingTemplate>()
|
||||
|
||||
for (const tx of representativeTransactions) {
|
||||
try {
|
||||
const matches = await findSimilarTemplates(
|
||||
tx as unknown as Transaction,
|
||||
entityType
|
||||
)
|
||||
for (const m of matches) {
|
||||
if (!candidateMap.has(m.template.id)) {
|
||||
candidateMap.set(m.template.id, m.template)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Embedding search failed — continue without candidates
|
||||
}
|
||||
}
|
||||
|
||||
const candidateTemplates = Array.from(candidateMap.values())
|
||||
|
||||
return {
|
||||
entityType,
|
||||
recentHistory,
|
||||
candidateTemplates,
|
||||
userAccountUsage,
|
||||
merchantHistory,
|
||||
}
|
||||
}
|
||||
|
||||
async function storeSuggestions(
|
||||
userId: string,
|
||||
suggestions: CategorizationSuggestion[],
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
supabase: any
|
||||
): Promise<void> {
|
||||
// Group suggestions by transactionId (AI now returns multiple per transaction)
|
||||
const grouped: Record<string, CategorizationSuggestion[]> = {}
|
||||
for (const suggestion of suggestions) {
|
||||
if (!grouped[suggestion.transactionId]) {
|
||||
grouped[suggestion.transactionId] = []
|
||||
}
|
||||
grouped[suggestion.transactionId].push(suggestion)
|
||||
}
|
||||
|
||||
for (const [txId, txSuggestions] of Object.entries(grouped)) {
|
||||
const { error } = await supabase.from('extension_data').upsert(
|
||||
{
|
||||
user_id: userId,
|
||||
extension_id: 'ai-categorization',
|
||||
key: `suggestion:${txId}`,
|
||||
value: txSuggestions,
|
||||
},
|
||||
{ onConflict: 'user_id,extension_id,key' }
|
||||
)
|
||||
if (error) {
|
||||
console.error(`[ai-categorization] Failed to store suggestion for ${txId}:`, error.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Extension Object
|
||||
// ============================================================
|
||||
|
||||
export const aiCategorizationExtension: Extension = {
|
||||
id: 'ai-categorization',
|
||||
name: 'AI Kategorisering',
|
||||
version: '1.0.0',
|
||||
sector: 'general',
|
||||
apiRoutes: aiCategorizationApiRoutes,
|
||||
eventHandlers: [
|
||||
{ eventType: 'transaction.synced', handler: handleTransactionSynced },
|
||||
],
|
||||
settingsPanel: {
|
||||
label: 'AI Kategorisering',
|
||||
path: '/settings/extensions/ai-categorization',
|
||||
},
|
||||
services: {
|
||||
findSimilarTemplates: async (...args: unknown[]) => {
|
||||
const { findSimilarTemplates } = await import('./lib/template-embeddings')
|
||||
return findSimilarTemplates(
|
||||
args[0] as Transaction,
|
||||
args[1] as EntityType | undefined,
|
||||
args[2] as number | undefined,
|
||||
args[3] as string | undefined
|
||||
)
|
||||
},
|
||||
seedAllTemplateEmbeddings: async () => {
|
||||
const { seedAllTemplateEmbeddings } = await import('./lib/template-embeddings')
|
||||
return seedAllTemplateEmbeddings()
|
||||
},
|
||||
getSchemaVersion: async () => {
|
||||
const { getSchemaVersion } = await import('./lib/template-embeddings')
|
||||
return getSchemaVersion()
|
||||
},
|
||||
categorizeTransactions: async (...args: unknown[]) => {
|
||||
return categorizeTransactions(args[0] as string, args[1] as string[])
|
||||
},
|
||||
analyzeDescription: async (...args: unknown[]) => {
|
||||
const { analyzeDescription } = await import('./lib/description-analyzer')
|
||||
return analyzeDescription(
|
||||
args[0] as import('./lib/description-analyzer').DescriptionAnalysisInput
|
||||
)
|
||||
},
|
||||
},
|
||||
async onInstall(ctx) {
|
||||
await ctx.settings.set('settings', DEFAULT_SETTINGS)
|
||||
},
|
||||
}
|
||||
@@ -1,297 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
// Mock server-only (no-op in tests)
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
// Mock Anthropic SDK
|
||||
const mockCreate = vi.fn()
|
||||
vi.mock('@anthropic-ai/sdk', () => {
|
||||
class MockAnthropic {
|
||||
messages = { create: mockCreate }
|
||||
}
|
||||
return { default: MockAnthropic }
|
||||
})
|
||||
|
||||
function makeToolResponse(input: Record<string, unknown>) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'tool_use',
|
||||
name: 'analyze_description',
|
||||
input,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
describe('description-analyzer', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('returns correct result for an expense with standard VAT', async () => {
|
||||
mockCreate.mockResolvedValueOnce(
|
||||
makeToolResponse({
|
||||
debitAccount: '6071',
|
||||
creditAccount: '1930',
|
||||
vatTreatment: 'standard_25',
|
||||
category: 'expense_representation',
|
||||
confidence: 0.85,
|
||||
reasoning: 'Lunch med kund klassificeras som representation.',
|
||||
warnings: ['Max 300 kr/person for avdragsratt'],
|
||||
templateId: null,
|
||||
})
|
||||
)
|
||||
|
||||
const { analyzeDescription } = await import('../description-analyzer')
|
||||
|
||||
const result = await analyzeDescription({
|
||||
description: 'Lunch med kund',
|
||||
transactionAmount: -450,
|
||||
transactionDate: '2026-01-15',
|
||||
transactionDescription: 'RESTAURANT XYZ',
|
||||
merchantName: 'Restaurant XYZ',
|
||||
currency: 'SEK',
|
||||
entityType: 'enskild_firma',
|
||||
})
|
||||
|
||||
expect(result.debitAccount).toBe('6071')
|
||||
expect(result.creditAccount).toBe('1930')
|
||||
expect(result.vatTreatment).toBe('standard_25')
|
||||
expect(result.category).toBe('expense_representation')
|
||||
expect(result.confidence).toBe(0.85)
|
||||
expect(result.reasoning).toContain('representation')
|
||||
expect(result.warnings).toHaveLength(1)
|
||||
expect(result.templateId).toBeNull()
|
||||
})
|
||||
|
||||
it('returns correct result for income', async () => {
|
||||
mockCreate.mockResolvedValueOnce(
|
||||
makeToolResponse({
|
||||
debitAccount: '1930',
|
||||
creditAccount: '3001',
|
||||
vatTreatment: 'standard_25',
|
||||
category: 'income_services',
|
||||
confidence: 0.9,
|
||||
reasoning: 'Konsultarvode bokförs som tjänsteintäkt.',
|
||||
warnings: [],
|
||||
templateId: null,
|
||||
})
|
||||
)
|
||||
|
||||
const { analyzeDescription } = await import('../description-analyzer')
|
||||
|
||||
const result = await analyzeDescription({
|
||||
description: 'Konsultarvode',
|
||||
transactionAmount: 25000,
|
||||
transactionDate: '2026-01-15',
|
||||
transactionDescription: 'PAYMENT FROM CLIENT',
|
||||
merchantName: null,
|
||||
currency: 'SEK',
|
||||
entityType: 'aktiebolag',
|
||||
})
|
||||
|
||||
expect(result.debitAccount).toBe('1930')
|
||||
expect(result.creditAccount).toBe('3001')
|
||||
expect(result.category).toBe('income_services')
|
||||
expect(result.confidence).toBe(0.9)
|
||||
})
|
||||
|
||||
it('corrects category direction mismatch', async () => {
|
||||
mockCreate.mockResolvedValueOnce(
|
||||
makeToolResponse({
|
||||
debitAccount: '6071',
|
||||
creditAccount: '1930',
|
||||
vatTreatment: null,
|
||||
category: 'income_services', // Wrong direction for expense
|
||||
confidence: 0.7,
|
||||
reasoning: 'Test',
|
||||
warnings: [],
|
||||
templateId: null,
|
||||
})
|
||||
)
|
||||
|
||||
const { analyzeDescription } = await import('../description-analyzer')
|
||||
|
||||
const result = await analyzeDescription({
|
||||
description: 'Something',
|
||||
transactionAmount: -500,
|
||||
transactionDate: '2026-01-15',
|
||||
transactionDescription: 'PAYMENT',
|
||||
merchantName: null,
|
||||
currency: 'SEK',
|
||||
entityType: 'enskild_firma',
|
||||
})
|
||||
|
||||
// Income category should be corrected to expense for negative amount
|
||||
expect(result.category).toBe('expense_other')
|
||||
})
|
||||
|
||||
it('clamps confidence to [0, 1]', async () => {
|
||||
mockCreate.mockResolvedValueOnce(
|
||||
makeToolResponse({
|
||||
debitAccount: '6991',
|
||||
creditAccount: '1930',
|
||||
vatTreatment: null,
|
||||
category: 'expense_other',
|
||||
confidence: 1.5, // Over 1
|
||||
reasoning: 'Test',
|
||||
warnings: [],
|
||||
templateId: null,
|
||||
})
|
||||
)
|
||||
|
||||
const { analyzeDescription } = await import('../description-analyzer')
|
||||
|
||||
const result = await analyzeDescription({
|
||||
description: 'Something',
|
||||
transactionAmount: -100,
|
||||
transactionDate: '2026-01-15',
|
||||
transactionDescription: 'PAYMENT',
|
||||
merchantName: null,
|
||||
currency: 'SEK',
|
||||
entityType: 'enskild_firma',
|
||||
})
|
||||
|
||||
expect(result.confidence).toBe(1)
|
||||
})
|
||||
|
||||
it('falls back to default accounts for invalid account numbers', async () => {
|
||||
mockCreate.mockResolvedValueOnce(
|
||||
makeToolResponse({
|
||||
debitAccount: 'INVALID',
|
||||
creditAccount: 'bad',
|
||||
vatTreatment: null,
|
||||
category: 'expense_other',
|
||||
confidence: 0.5,
|
||||
reasoning: 'Test',
|
||||
warnings: [],
|
||||
templateId: null,
|
||||
})
|
||||
)
|
||||
|
||||
const { analyzeDescription } = await import('../description-analyzer')
|
||||
|
||||
const result = await analyzeDescription({
|
||||
description: 'Something',
|
||||
transactionAmount: -100,
|
||||
transactionDate: '2026-01-15',
|
||||
transactionDescription: 'PAYMENT',
|
||||
merchantName: null,
|
||||
currency: 'SEK',
|
||||
entityType: 'enskild_firma',
|
||||
})
|
||||
|
||||
// Should fall back to safe defaults
|
||||
expect(result.debitAccount).toBe('6991')
|
||||
expect(result.creditAccount).toBe('1930')
|
||||
})
|
||||
|
||||
it('enforces expense direction: credit account must be 1930', async () => {
|
||||
mockCreate.mockResolvedValueOnce(
|
||||
makeToolResponse({
|
||||
debitAccount: '5420',
|
||||
creditAccount: '2440', // Not 1930 for a bank transaction expense
|
||||
vatTreatment: 'standard_25',
|
||||
category: 'expense_software',
|
||||
confidence: 0.8,
|
||||
reasoning: 'Test',
|
||||
warnings: [],
|
||||
templateId: null,
|
||||
})
|
||||
)
|
||||
|
||||
const { analyzeDescription } = await import('../description-analyzer')
|
||||
|
||||
const result = await analyzeDescription({
|
||||
description: 'Software subscription',
|
||||
transactionAmount: -500,
|
||||
transactionDate: '2026-01-15',
|
||||
transactionDescription: 'PAYMENT',
|
||||
merchantName: null,
|
||||
currency: 'SEK',
|
||||
entityType: 'enskild_firma',
|
||||
})
|
||||
|
||||
expect(result.creditAccount).toBe('1930')
|
||||
})
|
||||
|
||||
it('rejects private category', async () => {
|
||||
mockCreate.mockResolvedValueOnce(
|
||||
makeToolResponse({
|
||||
debitAccount: '2013',
|
||||
creditAccount: '1930',
|
||||
vatTreatment: null,
|
||||
category: 'private',
|
||||
confidence: 0.9,
|
||||
reasoning: 'Test',
|
||||
warnings: [],
|
||||
templateId: null,
|
||||
})
|
||||
)
|
||||
|
||||
const { analyzeDescription } = await import('../description-analyzer')
|
||||
|
||||
const result = await analyzeDescription({
|
||||
description: 'Something',
|
||||
transactionAmount: -100,
|
||||
transactionDate: '2026-01-15',
|
||||
transactionDescription: 'PAYMENT',
|
||||
merchantName: null,
|
||||
currency: 'SEK',
|
||||
entityType: 'enskild_firma',
|
||||
})
|
||||
|
||||
expect(result.category).toBe('expense_other')
|
||||
})
|
||||
|
||||
it('throws after retries exhausted', async () => {
|
||||
mockCreate.mockRejectedValue(new Error('API error'))
|
||||
|
||||
const { analyzeDescription } = await import('../description-analyzer')
|
||||
|
||||
await expect(
|
||||
analyzeDescription({
|
||||
description: 'Something',
|
||||
transactionAmount: -100,
|
||||
transactionDate: '2026-01-15',
|
||||
transactionDescription: 'PAYMENT',
|
||||
merchantName: null,
|
||||
currency: 'SEK',
|
||||
entityType: 'enskild_firma',
|
||||
})
|
||||
).rejects.toThrow('AI description analysis failed after 3 attempts')
|
||||
|
||||
// Should have retried 3 times (initial + 2 retries)
|
||||
expect(mockCreate).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('validates invalid VAT treatment to null', async () => {
|
||||
mockCreate.mockResolvedValueOnce(
|
||||
makeToolResponse({
|
||||
debitAccount: '6991',
|
||||
creditAccount: '1930',
|
||||
vatTreatment: 'invalid_vat',
|
||||
category: 'expense_other',
|
||||
confidence: 0.5,
|
||||
reasoning: 'Test',
|
||||
warnings: [],
|
||||
templateId: null,
|
||||
})
|
||||
)
|
||||
|
||||
const { analyzeDescription } = await import('../description-analyzer')
|
||||
|
||||
const result = await analyzeDescription({
|
||||
description: 'Something',
|
||||
transactionAmount: -100,
|
||||
transactionDate: '2026-01-15',
|
||||
transactionDescription: 'PAYMENT',
|
||||
merchantName: null,
|
||||
currency: 'SEK',
|
||||
entityType: 'enskild_firma',
|
||||
})
|
||||
|
||||
expect(result.vatTreatment).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,233 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { makeTransaction, createMockSupabase } from '@/tests/helpers'
|
||||
import { BOOKING_TEMPLATES } from '@/lib/bookkeeping/booking-templates'
|
||||
|
||||
// Mock server-only (no-op in tests)
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
// Mock OpenAI Embeddings
|
||||
vi.mock('@langchain/openai', () => {
|
||||
class MockOpenAIEmbeddings {
|
||||
embedQuery = vi.fn().mockResolvedValue(new Array(1536).fill(0.1))
|
||||
embedDocuments = vi.fn().mockImplementation((texts: string[]) =>
|
||||
Promise.resolve(texts.map(() => new Array(1536).fill(0.1)))
|
||||
)
|
||||
}
|
||||
return { OpenAIEmbeddings: MockOpenAIEmbeddings }
|
||||
})
|
||||
|
||||
// Mock Supabase
|
||||
const { supabase: mockSupabase, mockResult } = createMockSupabase()
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createServiceClient: vi.fn().mockResolvedValue(mockSupabase),
|
||||
}))
|
||||
|
||||
describe('template-embeddings', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('buildEmbeddingText', () => {
|
||||
it('includes all relevant fields for a template', async () => {
|
||||
const { buildEmbeddingText } = await import('../template-embeddings')
|
||||
|
||||
const template = BOOKING_TEMPLATES.find((t) => t.id === 'premises_rent')!
|
||||
const text = buildEmbeddingText(template)
|
||||
|
||||
// Should include Swedish and English name
|
||||
expect(text).toContain('Lokalhyra')
|
||||
expect(text).toContain('Office rent')
|
||||
|
||||
// Should include description
|
||||
expect(text).toContain(template.description_sv)
|
||||
|
||||
// Should include keywords
|
||||
expect(text).toContain('hyra')
|
||||
expect(text).toContain('lokal')
|
||||
|
||||
// Should include group
|
||||
expect(text).toContain('premises')
|
||||
|
||||
// Should include direction
|
||||
expect(text).toContain('utgift')
|
||||
|
||||
// Should include accounts
|
||||
expect(text).toContain('5010')
|
||||
expect(text).toContain('1930')
|
||||
})
|
||||
|
||||
it('includes VAT treatment when present', async () => {
|
||||
const { buildEmbeddingText } = await import('../template-embeddings')
|
||||
|
||||
const template = BOOKING_TEMPLATES.find((t) => t.id === 'premises_electricity')!
|
||||
const text = buildEmbeddingText(template)
|
||||
|
||||
expect(text).toContain('standard_25')
|
||||
expect(text).toContain('25%')
|
||||
})
|
||||
|
||||
it('includes special rules when present', async () => {
|
||||
const { buildEmbeddingText } = await import('../template-embeddings')
|
||||
|
||||
const template = BOOKING_TEMPLATES.find((t) => t.id === 'premises_rent')!
|
||||
const text = buildEmbeddingText(template)
|
||||
|
||||
expect(text).toContain(template.special_rules_sv!)
|
||||
})
|
||||
|
||||
it('includes MCC codes when present', async () => {
|
||||
const { buildEmbeddingText } = await import('../template-embeddings')
|
||||
|
||||
const template = BOOKING_TEMPLATES.find((t) => t.id === 'premises_electricity')!
|
||||
const text = buildEmbeddingText(template)
|
||||
|
||||
expect(text).toContain('4900')
|
||||
})
|
||||
|
||||
it('includes deductibility note for non-full deductibility', async () => {
|
||||
const { buildEmbeddingText } = await import('../template-embeddings')
|
||||
|
||||
const template = BOOKING_TEMPLATES.find((t) => t.deductibility === 'non_deductible')!
|
||||
const text = buildEmbeddingText(template)
|
||||
|
||||
expect(text).toContain('non_deductible')
|
||||
})
|
||||
|
||||
it('generates text for all templates without error', async () => {
|
||||
const { buildEmbeddingText } = await import('../template-embeddings')
|
||||
|
||||
for (const template of BOOKING_TEMPLATES) {
|
||||
const text = buildEmbeddingText(template)
|
||||
expect(text.length).toBeGreaterThan(10)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildTransactionQueryText', () => {
|
||||
it('combines description, merchant, and direction', async () => {
|
||||
const { buildTransactionQueryText } = await import('../template-embeddings')
|
||||
|
||||
const tx = makeTransaction({
|
||||
description: 'SPOTIFY PREMIUM',
|
||||
merchant_name: 'Spotify',
|
||||
amount: -109,
|
||||
mcc_code: 5815,
|
||||
})
|
||||
|
||||
const text = buildTransactionQueryText(tx)
|
||||
|
||||
expect(text).toContain('SPOTIFY PREMIUM')
|
||||
expect(text).toContain('Spotify')
|
||||
expect(text).toContain('MCC 5815')
|
||||
expect(text).toContain('utgift')
|
||||
})
|
||||
|
||||
it('marks positive amounts as income', async () => {
|
||||
const { buildTransactionQueryText } = await import('../template-embeddings')
|
||||
|
||||
const tx = makeTransaction({
|
||||
description: 'Inbetalning',
|
||||
amount: 5000,
|
||||
})
|
||||
|
||||
const text = buildTransactionQueryText(tx)
|
||||
expect(text).toContain('intäkt')
|
||||
})
|
||||
|
||||
it('handles null merchant_name and mcc_code', async () => {
|
||||
const { buildTransactionQueryText } = await import('../template-embeddings')
|
||||
|
||||
const tx = makeTransaction({
|
||||
description: 'Some payment',
|
||||
merchant_name: null,
|
||||
mcc_code: null,
|
||||
amount: -100,
|
||||
})
|
||||
|
||||
const text = buildTransactionQueryText(tx)
|
||||
expect(text).toContain('Some payment')
|
||||
expect(text).toContain('utgift')
|
||||
expect(text).not.toContain('MCC')
|
||||
})
|
||||
|
||||
it('prepends user description when provided', async () => {
|
||||
const { buildTransactionQueryText } = await import('../template-embeddings')
|
||||
|
||||
const tx = makeTransaction({
|
||||
description: 'SWE REST 4521 STHLM',
|
||||
merchant_name: 'Unknown',
|
||||
amount: -450,
|
||||
})
|
||||
|
||||
const text = buildTransactionQueryText(tx, 'business lunch with client')
|
||||
|
||||
// User description should appear first
|
||||
expect(text.indexOf('business lunch with client')).toBe(0)
|
||||
// Transaction data should still be present
|
||||
expect(text).toContain('SWE REST 4521 STHLM')
|
||||
expect(text).toContain('Unknown')
|
||||
expect(text).toContain('utgift')
|
||||
})
|
||||
|
||||
it('behaves identically when userDescription is undefined', async () => {
|
||||
const { buildTransactionQueryText } = await import('../template-embeddings')
|
||||
|
||||
const tx = makeTransaction({
|
||||
description: 'SPOTIFY PREMIUM',
|
||||
merchant_name: 'Spotify',
|
||||
amount: -109,
|
||||
})
|
||||
|
||||
const withoutDesc = buildTransactionQueryText(tx)
|
||||
const withUndefined = buildTransactionQueryText(tx, undefined)
|
||||
|
||||
expect(withoutDesc).toBe(withUndefined)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getSchemaVersion', () => {
|
||||
it('returns a consistent hash string', async () => {
|
||||
const { getSchemaVersion } = await import('../template-embeddings')
|
||||
|
||||
const v1 = getSchemaVersion()
|
||||
const v2 = getSchemaVersion()
|
||||
|
||||
expect(v1).toBe(v2)
|
||||
expect(v1).toHaveLength(12)
|
||||
expect(v1).toMatch(/^[a-f0-9]+$/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('findSimilarTemplates', () => {
|
||||
it('returns empty array on RPC error (graceful fallback)', async () => {
|
||||
const { findSimilarTemplates } = await import('../template-embeddings')
|
||||
|
||||
// Mock staleness check
|
||||
mockResult({ data: { schema_version: 'test' }, error: null })
|
||||
|
||||
const tx = makeTransaction({
|
||||
description: 'SPOTIFY',
|
||||
amount: -109,
|
||||
})
|
||||
|
||||
// The mock will return error for the RPC call
|
||||
mockResult({ data: null, error: { message: 'RPC failed' } })
|
||||
const results = await findSimilarTemplates(tx)
|
||||
expect(results).toEqual([])
|
||||
})
|
||||
|
||||
it('returns empty array when no embeddings exist', async () => {
|
||||
const { findSimilarTemplates } = await import('../template-embeddings')
|
||||
|
||||
mockResult({ data: [], error: null })
|
||||
|
||||
const tx = makeTransaction({
|
||||
description: 'Random purchase',
|
||||
amount: -50,
|
||||
})
|
||||
|
||||
const results = await findSimilarTemplates(tx)
|
||||
expect(results).toEqual([])
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,277 +0,0 @@
|
||||
/**
|
||||
* AI Description Analyzer
|
||||
*
|
||||
* SERVER-ONLY: Uses the Anthropic SDK and must only be imported
|
||||
* in server components or API routes.
|
||||
*
|
||||
* Interprets a user's plain-language description of a bank transaction
|
||||
* and returns a structured booking suggestion with Swedish accounting reasoning.
|
||||
* Uses Claude Haiku with structured tool outputs for reliable JSON.
|
||||
*/
|
||||
|
||||
import 'server-only'
|
||||
import Anthropic from '@anthropic-ai/sdk'
|
||||
import type { TransactionCategory, VatTreatment, EntityType } from '@/types'
|
||||
|
||||
// ============================================================
|
||||
// Types
|
||||
// ============================================================
|
||||
|
||||
export interface DescriptionAnalysisInput {
|
||||
description: string
|
||||
transactionAmount: number
|
||||
transactionDate: string
|
||||
transactionDescription: string
|
||||
merchantName: string | null
|
||||
currency: string
|
||||
entityType: EntityType
|
||||
}
|
||||
|
||||
export interface DescriptionAnalysisResult {
|
||||
debitAccount: string
|
||||
creditAccount: string
|
||||
vatTreatment: VatTreatment | null
|
||||
category: TransactionCategory
|
||||
confidence: number
|
||||
reasoning: string
|
||||
warnings: string[]
|
||||
templateId: string | null
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Constants
|
||||
// ============================================================
|
||||
|
||||
const MAX_RETRIES = 2
|
||||
const RETRY_DELAY_MS = 500
|
||||
const MODEL = 'claude-haiku-4-5-20251001'
|
||||
|
||||
const VALID_CATEGORIES = new Set<string>([
|
||||
'income_services', 'income_products', 'income_other',
|
||||
'expense_equipment', 'expense_software', 'expense_travel',
|
||||
'expense_office', 'expense_marketing', 'expense_professional_services',
|
||||
'expense_education', 'expense_representation', 'expense_consumables',
|
||||
'expense_vehicle', 'expense_telecom', 'expense_bank_fees',
|
||||
'expense_card_fees', 'expense_currency_exchange', 'expense_other',
|
||||
])
|
||||
|
||||
const VALID_VAT_TREATMENTS = new Set<string>([
|
||||
'standard_25', 'reduced_12', 'reduced_6', 'reverse_charge', 'export', 'exempt',
|
||||
])
|
||||
|
||||
// ============================================================
|
||||
// Tool Schema
|
||||
// ============================================================
|
||||
|
||||
const ANALYZE_TOOL: Anthropic.Tool = {
|
||||
name: 'analyze_description',
|
||||
description: 'Analyze a user description and return a structured booking suggestion for the transaction.',
|
||||
input_schema: {
|
||||
type: 'object' as const,
|
||||
properties: {
|
||||
debitAccount: { type: 'string', description: 'BAS debit account number (4 digits)' },
|
||||
creditAccount: { type: 'string', description: 'BAS credit account number (4 digits)' },
|
||||
vatTreatment: {
|
||||
type: ['string', 'null'],
|
||||
description: 'VAT treatment: standard_25, reduced_12, reduced_6, reverse_charge, export, exempt, or null if exempt/no VAT',
|
||||
},
|
||||
category: { type: 'string', description: 'Transaction category (e.g. expense_representation, income_services)' },
|
||||
confidence: { type: 'number', description: 'Confidence score 0.0-1.0' },
|
||||
reasoning: { type: 'string', description: 'Explanation in Swedish of why this booking is correct' },
|
||||
warnings: {
|
||||
type: 'array',
|
||||
items: { type: 'string' },
|
||||
description: 'Warnings about deductibility limits, special rules, etc. (in Swedish)',
|
||||
},
|
||||
templateId: {
|
||||
type: ['string', 'null'],
|
||||
description: 'Matching booking template ID if applicable, or null',
|
||||
},
|
||||
},
|
||||
required: ['debitAccount', 'creditAccount', 'vatTreatment', 'category', 'confidence', 'reasoning', 'warnings', 'templateId'],
|
||||
},
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// System Prompt
|
||||
// ============================================================
|
||||
|
||||
function buildSystemPrompt(entityType: EntityType): string {
|
||||
const privateAccount = entityType === 'aktiebolag' ? '2893' : '2013'
|
||||
const entityLabel = entityType === 'aktiebolag' ? 'Aktiebolag (AB)' : 'Enskild firma (EF)'
|
||||
|
||||
return `Du är expert på svensk bokföring enligt BAS-kontoplanen. Analysera användarens beskrivning av en banktransaktion och returnera ett bokföringsförslag.
|
||||
|
||||
VANLIGA BAS-KONTON:
|
||||
Utgifter: 5010 Lokalhyra | 5410 Förbrukningsinventarier | 5420 Programvara | 5460 Förbrukningsvaror | 5611 Bil/drivmedel | 5800 Resekostnader | 5910 Annonsering | 6071 Representation mat | 6200 Telefon/internet | 6530 Redovisning/konsult | 6570 Bankavgifter | 6991 Övriga kostnader | ${entityType === 'aktiebolag' ? '7610' : '6991'} Utbildning
|
||||
Intäkter: 3001 Försäljning 25% | 3002 Försäljning 12% | 3003 Försäljning 6% | 3305 Export | 3308 EU-tjänster | 3900 Övriga intäkter
|
||||
Moms: 2611 Utg moms 25% | 2621 Utg moms 12% | 2631 Utg moms 6% | 2641 Ing moms | 2645 Beräknad ing moms
|
||||
Skulder: 2350 Skulder till kreditinstitut (banklån, Almi) | 2440 Leverantörsskulder (ENBART för leverantörsfakturor)
|
||||
Övrigt: 1510 Kundfordringar | 1930 Företagskonto | 8410 Räntekostnader | ${privateAccount} Privat
|
||||
|
||||
MOMSREGLER:
|
||||
- standard_25: Normala varor/tjänster (25%)
|
||||
- reduced_12: Livsmedel, hotell, konstverk (12%)
|
||||
- reduced_6: Böcker, tidningar, kollektivtrafik, kultur (6%)
|
||||
- reverse_charge: Tjänsteköp från utlandet/EU
|
||||
- export: Försäljning utanför Sverige
|
||||
- exempt: Momsfritt (bank, försäkring, sjukvård, utbildning)
|
||||
|
||||
VARNINGSREGLER:
|
||||
- Representation/måltider: Max 300 kr/person exkl moms för avdragsrätt (IL 16 kap 2§)
|
||||
- Gåvor: Reklamgåvor max 300 kr, representationsgåvor max 180 kr
|
||||
- Blandad användning (telefon/dator): Bara yrkesmässig del avdragsgill
|
||||
- Bankavgifter, kortavgifter, valutaväxling: MOMSFRIA (exempt)
|
||||
|
||||
Företagsform: ${entityLabel}
|
||||
Privatkonto: ${privateAccount}
|
||||
|
||||
REGLER:
|
||||
1. Negativt belopp = utgift: debitera kostnadskonto, kreditera 1930
|
||||
2. Positivt belopp = intäkt: debitera 1930, kreditera intäktskonto
|
||||
3. Ge ett klart reasoning på svenska som förklarar valet
|
||||
4. Lägg till warnings för avdragsbegränsningar eller speciella regler
|
||||
5. templateId: null (vi matchar mallar separat)`
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Analyzer
|
||||
// ============================================================
|
||||
|
||||
export async function analyzeDescription(
|
||||
input: DescriptionAnalysisInput
|
||||
): Promise<DescriptionAnalysisResult> {
|
||||
const client = new Anthropic()
|
||||
const isExpense = input.transactionAmount < 0
|
||||
|
||||
const userPrompt = `Transaktion:
|
||||
- Användarens beskrivning: "${input.description}"
|
||||
- Banktext: "${input.transactionDescription}"
|
||||
- Belopp: ${input.transactionAmount} ${input.currency}
|
||||
- Datum: ${input.transactionDate}${input.merchantName ? `\n- Handlare: ${input.merchantName}` : ''}
|
||||
|
||||
Analysera och returnera bokföringsförslag med analyze_description-verktyget.`
|
||||
|
||||
let lastError: Error | null = null
|
||||
|
||||
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
||||
try {
|
||||
const message = await client.messages.create({
|
||||
model: MODEL,
|
||||
max_tokens: 1024,
|
||||
system: [
|
||||
{
|
||||
type: 'text',
|
||||
text: buildSystemPrompt(input.entityType),
|
||||
cache_control: { type: 'ephemeral' },
|
||||
},
|
||||
],
|
||||
tools: [ANALYZE_TOOL],
|
||||
tool_choice: { type: 'tool', name: 'analyze_description' },
|
||||
messages: [{ role: 'user', content: userPrompt }],
|
||||
})
|
||||
|
||||
const toolUseBlock = message.content.find(
|
||||
(block) => block.type === 'tool_use' && block.name === 'analyze_description'
|
||||
)
|
||||
|
||||
if (!toolUseBlock || toolUseBlock.type !== 'tool_use') {
|
||||
throw new Error('No tool_use block in AI response')
|
||||
}
|
||||
|
||||
return validateResult(toolUseBlock.input as Record<string, unknown>, isExpense, input.entityType)
|
||||
} catch (error) {
|
||||
lastError = error instanceof Error ? error : new Error('Unknown error')
|
||||
if (attempt < MAX_RETRIES) {
|
||||
await sleep(RETRY_DELAY_MS * (attempt + 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`AI description analysis failed after ${MAX_RETRIES + 1} attempts: ${lastError?.message}`
|
||||
)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Validation
|
||||
// ============================================================
|
||||
|
||||
function validateResult(
|
||||
raw: Record<string, unknown>,
|
||||
isExpense: boolean,
|
||||
entityType: EntityType
|
||||
): DescriptionAnalysisResult {
|
||||
const ACCOUNT_REGEX = /^\d{4}$/
|
||||
|
||||
// Validate accounts — default to safe fallbacks
|
||||
let debitAccount = typeof raw.debitAccount === 'string' && ACCOUNT_REGEX.test(raw.debitAccount)
|
||||
? raw.debitAccount
|
||||
: (isExpense ? '6991' : '1930')
|
||||
|
||||
let creditAccount = typeof raw.creditAccount === 'string' && ACCOUNT_REGEX.test(raw.creditAccount)
|
||||
? raw.creditAccount
|
||||
: (isExpense ? '1930' : '3001')
|
||||
|
||||
// Enforce direction: expenses debit expense account + credit 1930, income debit 1930 + credit revenue
|
||||
if (isExpense && creditAccount !== '1930') {
|
||||
creditAccount = '1930'
|
||||
}
|
||||
if (!isExpense && debitAccount !== '1930') {
|
||||
debitAccount = '1930'
|
||||
}
|
||||
|
||||
// Validate VAT treatment
|
||||
const rawVat = raw.vatTreatment as string | null
|
||||
const vatTreatment = rawVat && VALID_VAT_TREATMENTS.has(rawVat)
|
||||
? rawVat as VatTreatment
|
||||
: null
|
||||
|
||||
// Validate category with direction correction
|
||||
let category = VALID_CATEGORIES.has(raw.category as string)
|
||||
? (raw.category as TransactionCategory)
|
||||
: (isExpense ? 'expense_other' : 'income_other')
|
||||
|
||||
if (category === 'private') {
|
||||
category = isExpense ? 'expense_other' : 'income_other'
|
||||
}
|
||||
if (isExpense && category.startsWith('income_')) {
|
||||
category = 'expense_other'
|
||||
}
|
||||
if (!isExpense && category.startsWith('expense_')) {
|
||||
category = 'income_other'
|
||||
}
|
||||
|
||||
// Clamp confidence
|
||||
const confidence = Math.max(0, Math.min(1, Number(raw.confidence) || 0.5))
|
||||
|
||||
// Reasoning — must be a non-empty string
|
||||
const reasoning = typeof raw.reasoning === 'string' && raw.reasoning.length > 0
|
||||
? raw.reasoning
|
||||
: (isExpense ? 'Utgift bokförd på standardkonto' : 'Intäkt bokförd på standardkonto')
|
||||
|
||||
// Warnings
|
||||
const warnings = Array.isArray(raw.warnings)
|
||||
? (raw.warnings as unknown[]).filter((w): w is string => typeof w === 'string')
|
||||
: []
|
||||
|
||||
// Template ID
|
||||
const templateId = typeof raw.templateId === 'string' && raw.templateId.length > 0
|
||||
? raw.templateId
|
||||
: null
|
||||
|
||||
return {
|
||||
debitAccount,
|
||||
creditAccount,
|
||||
vatTreatment,
|
||||
category,
|
||||
confidence,
|
||||
reasoning,
|
||||
warnings,
|
||||
templateId,
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
@@ -1,265 +0,0 @@
|
||||
/**
|
||||
* Template Embeddings Module
|
||||
*
|
||||
* SERVER-ONLY: Uses OpenAI embeddings and Supabase service client.
|
||||
*
|
||||
* Provides semantic search over booking templates using pgvector.
|
||||
* Templates are pre-embedded and stored in the database. Transaction
|
||||
* text is embedded at query time and compared via cosine similarity.
|
||||
*/
|
||||
|
||||
import 'server-only'
|
||||
import { OpenAIEmbeddings } from '@langchain/openai'
|
||||
import {
|
||||
BOOKING_TEMPLATES,
|
||||
getTemplateById,
|
||||
type BookingTemplate,
|
||||
type TemplateMatch,
|
||||
} from '@/lib/bookkeeping/booking-templates'
|
||||
import type { Transaction, EntityType } from '@/types'
|
||||
import { createHash } from 'crypto'
|
||||
|
||||
// ============================================================
|
||||
// Constants
|
||||
// ============================================================
|
||||
|
||||
export const EMBEDDING_MODEL = 'text-embedding-3-small'
|
||||
const EMBEDDING_LOGIC_VERSION = '1'
|
||||
const MATCH_COUNT = 5
|
||||
const MATCH_THRESHOLD = 0.5
|
||||
|
||||
/**
|
||||
* Schema version is a hash of the model + embedding logic version.
|
||||
* Bump EMBEDDING_LOGIC_VERSION when buildEmbeddingText changes.
|
||||
*/
|
||||
export function getSchemaVersion(): string {
|
||||
return createHash('sha256')
|
||||
.update(`${EMBEDDING_MODEL}:${EMBEDDING_LOGIC_VERSION}`)
|
||||
.digest('hex')
|
||||
.slice(0, 12)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Embedding Text Builders
|
||||
// ============================================================
|
||||
|
||||
/**
|
||||
* Build a rich text representation of a template for embedding.
|
||||
* Includes all semantically relevant fields.
|
||||
*/
|
||||
export function buildEmbeddingText(template: BookingTemplate): string {
|
||||
const parts: string[] = []
|
||||
|
||||
parts.push(`${template.name_sv} (${template.name_en})`)
|
||||
parts.push(template.description_sv)
|
||||
|
||||
if (template.keywords.length > 0) {
|
||||
parts.push(`Nyckelord: ${template.keywords.join(', ')}`)
|
||||
}
|
||||
|
||||
parts.push(`Grupp: ${template.group}`)
|
||||
parts.push(`Typ: ${template.direction === 'expense' ? 'utgift' : template.direction === 'income' ? 'intäkt' : 'överföring'}`)
|
||||
parts.push(`Konton: ${template.debit_account} (debet) / ${template.credit_account} (kredit)`)
|
||||
|
||||
if (template.vat_treatment) {
|
||||
parts.push(`Moms: ${template.vat_treatment} (${template.vat_rate * 100}%)`)
|
||||
}
|
||||
|
||||
if (template.special_rules_sv) {
|
||||
parts.push(`Regler: ${template.special_rules_sv}`)
|
||||
}
|
||||
|
||||
if (template.mcc_codes.length > 0) {
|
||||
parts.push(`MCC-koder: ${template.mcc_codes.join(', ')}`)
|
||||
}
|
||||
|
||||
if (template.deductibility !== 'full') {
|
||||
parts.push(`Avdragsrätt: ${template.deductibility}`)
|
||||
}
|
||||
|
||||
return parts.join('. ')
|
||||
}
|
||||
|
||||
/**
|
||||
* Build query text from a transaction for embedding search.
|
||||
* When userDescription is provided, it is prepended so it dominates
|
||||
* the semantic search (user intent > raw bank text).
|
||||
*/
|
||||
export function buildTransactionQueryText(
|
||||
transaction: Transaction,
|
||||
userDescription?: string
|
||||
): string {
|
||||
const parts: string[] = []
|
||||
|
||||
if (userDescription) {
|
||||
parts.push(userDescription)
|
||||
}
|
||||
|
||||
if (transaction.description) {
|
||||
parts.push(transaction.description)
|
||||
}
|
||||
|
||||
if (transaction.merchant_name) {
|
||||
parts.push(transaction.merchant_name)
|
||||
}
|
||||
|
||||
if (transaction.mcc_code) {
|
||||
parts.push(`MCC ${transaction.mcc_code}`)
|
||||
}
|
||||
|
||||
parts.push(transaction.amount < 0 ? 'utgift' : 'intäkt')
|
||||
|
||||
return parts.join(' — ')
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Embeddings Client
|
||||
// ============================================================
|
||||
|
||||
let embeddingsInstance: OpenAIEmbeddings | null = null
|
||||
|
||||
function getEmbeddingsClient(): OpenAIEmbeddings {
|
||||
if (!embeddingsInstance) {
|
||||
embeddingsInstance = new OpenAIEmbeddings({
|
||||
modelName: EMBEDDING_MODEL,
|
||||
openAIApiKey: process.env.OPENAI_API_KEY,
|
||||
})
|
||||
}
|
||||
return embeddingsInstance
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Seed All Template Embeddings
|
||||
// ============================================================
|
||||
|
||||
export async function seedAllTemplateEmbeddings(): Promise<{
|
||||
seeded: number
|
||||
errors: string[]
|
||||
}> {
|
||||
const { createServiceClient } = await import('@/lib/supabase/server')
|
||||
const supabase = await createServiceClient()
|
||||
const embeddings = getEmbeddingsClient()
|
||||
const schemaVersion = getSchemaVersion()
|
||||
const errors: string[] = []
|
||||
|
||||
// Build texts for all templates
|
||||
const texts = BOOKING_TEMPLATES.map((t) => buildEmbeddingText(t))
|
||||
|
||||
// Batch embed all texts
|
||||
let vectors: number[][]
|
||||
try {
|
||||
vectors = await embeddings.embedDocuments(texts)
|
||||
} catch (error) {
|
||||
return { seeded: 0, errors: [`Embedding generation failed: ${error}`] }
|
||||
}
|
||||
|
||||
// Upsert each template embedding
|
||||
let seeded = 0
|
||||
for (let i = 0; i < BOOKING_TEMPLATES.length; i++) {
|
||||
const template = BOOKING_TEMPLATES[i]
|
||||
const { error } = await supabase
|
||||
.from('booking_template_embeddings')
|
||||
.upsert(
|
||||
{
|
||||
template_id: template.id,
|
||||
embedding: JSON.stringify(vectors[i]),
|
||||
embedding_text: texts[i],
|
||||
model: EMBEDDING_MODEL,
|
||||
schema_version: schemaVersion,
|
||||
},
|
||||
{ onConflict: 'template_id' }
|
||||
)
|
||||
|
||||
if (error) {
|
||||
errors.push(`Failed to upsert ${template.id}: ${error.message}`)
|
||||
} else {
|
||||
seeded++
|
||||
}
|
||||
}
|
||||
|
||||
return { seeded, errors }
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Find Similar Templates (Semantic Search)
|
||||
// ============================================================
|
||||
|
||||
let stalenessWarned = false
|
||||
|
||||
export async function findSimilarTemplates(
|
||||
transaction: Transaction,
|
||||
entityType?: EntityType,
|
||||
matchCount: number = MATCH_COUNT,
|
||||
userDescription?: string
|
||||
): Promise<TemplateMatch[]> {
|
||||
try {
|
||||
const { createServiceClient } = await import('@/lib/supabase/server')
|
||||
const supabase = await createServiceClient()
|
||||
const embeddings = getEmbeddingsClient()
|
||||
|
||||
// Check schema version staleness on first call
|
||||
if (!stalenessWarned) {
|
||||
const { data: sample } = await supabase
|
||||
.from('booking_template_embeddings')
|
||||
.select('schema_version')
|
||||
.limit(1)
|
||||
.single()
|
||||
|
||||
if (sample && sample.schema_version !== getSchemaVersion()) {
|
||||
console.warn(
|
||||
`[template-embeddings] Schema version mismatch: DB has "${sample.schema_version}", current is "${getSchemaVersion()}". Re-seed embeddings.`
|
||||
)
|
||||
}
|
||||
stalenessWarned = true
|
||||
}
|
||||
|
||||
// Embed the transaction query text
|
||||
const queryText = buildTransactionQueryText(transaction, userDescription)
|
||||
const queryVector = await embeddings.embedQuery(queryText)
|
||||
|
||||
// Request extra results to account for post-filtering
|
||||
const requestCount = matchCount + 10
|
||||
|
||||
const { data, error } = await supabase.rpc('match_booking_templates', {
|
||||
query_embedding: JSON.stringify(queryVector),
|
||||
match_count: requestCount,
|
||||
match_threshold: MATCH_THRESHOLD,
|
||||
})
|
||||
|
||||
if (error || !data) {
|
||||
console.error('[template-embeddings] RPC error:', error)
|
||||
return []
|
||||
}
|
||||
|
||||
// Map RPC results to TemplateMatch[], filtering by entity type and direction
|
||||
const isExpense = transaction.amount < 0
|
||||
const isIncome = transaction.amount > 0
|
||||
const results: TemplateMatch[] = []
|
||||
|
||||
for (const row of data as { template_id: string; similarity: number }[]) {
|
||||
const template = getTemplateById(row.template_id)
|
||||
if (!template) continue
|
||||
|
||||
// Filter by entity applicability
|
||||
if (entityType && template.entity_applicability !== 'all' && template.entity_applicability !== entityType) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Filter by direction
|
||||
if (template.direction === 'expense' && !isExpense) continue
|
||||
if (template.direction === 'income' && !isIncome) continue
|
||||
|
||||
results.push({
|
||||
template,
|
||||
confidence: Math.round(row.similarity * 100) / 100,
|
||||
})
|
||||
|
||||
if (results.length >= matchCount) break
|
||||
}
|
||||
|
||||
return results
|
||||
} catch (error) {
|
||||
console.error('[template-embeddings] findSimilarTemplates failed:', error)
|
||||
return []
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"id": "ai-categorization",
|
||||
"sector": "general",
|
||||
"exportName": "aiCategorizationExtension",
|
||||
"entryPoint": "@/extensions/general/ai-categorization",
|
||||
"workspace": "@/components/extensions/general/AiCategorizationWorkspace",
|
||||
"requiredEnvVars": ["ANTHROPIC_API_KEY", "OPENAI_API_KEY"],
|
||||
"optionalEnvVars": [],
|
||||
"npmDependencies": ["@anthropic-ai/sdk", "@langchain/openai"],
|
||||
"definition": {
|
||||
"name": "AI-kategorisering",
|
||||
"category": "operations",
|
||||
"icon": "Wand",
|
||||
"dataPattern": "core",
|
||||
"readsCoreTables": ["transactions"],
|
||||
"description": "AI-drivna kategoriförslag för transaktioner",
|
||||
"longDescription": "Använder AI för att automatiskt föreslå BAS-kontokategorier för dina banktransaktioner. Lär sig från dina tidigare bokföringsval."
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,133 +0,0 @@
|
||||
import { ChatAnthropic } from '@langchain/anthropic'
|
||||
import { createReactAgent } from '@langchain/langgraph/prebuilt'
|
||||
import { HumanMessage, AIMessage } from '@langchain/core/messages'
|
||||
import type { StructuredToolInterface } from '@langchain/core/tools'
|
||||
import { CHATBOT_CONFIG } from './config'
|
||||
import {
|
||||
SYSTEM_PROMPT_DATA,
|
||||
SYSTEM_PROMPT_HYBRID,
|
||||
formatConversationHistory,
|
||||
} from './prompts'
|
||||
import type { ChatMessage } from '@/types/chat'
|
||||
import type { RouteType } from './router'
|
||||
|
||||
export interface AgentStreamEvent {
|
||||
type: 'tool_start' | 'content' | 'done'
|
||||
toolName?: string
|
||||
content?: string
|
||||
toolResults?: ToolResultEntry[]
|
||||
}
|
||||
|
||||
export interface ToolResultEntry {
|
||||
toolName: string
|
||||
result: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the LangGraph agent with tool calling and stream events.
|
||||
*/
|
||||
export async function* streamAgentResponse(options: {
|
||||
query: string
|
||||
route: RouteType
|
||||
tools: StructuredToolInterface[]
|
||||
conversationHistory: ChatMessage[]
|
||||
ragContext?: string
|
||||
}): AsyncGenerator<AgentStreamEvent> {
|
||||
const { query, route, tools, conversationHistory, ragContext } = options
|
||||
|
||||
// Build system prompt based on route
|
||||
const historyText = formatConversationHistory(
|
||||
conversationHistory.slice(-CHATBOT_CONFIG.maxHistoryMessages).map((m) => ({
|
||||
role: m.role,
|
||||
content: m.content,
|
||||
}))
|
||||
)
|
||||
|
||||
let systemPrompt: string
|
||||
if (route === 'data') {
|
||||
systemPrompt = SYSTEM_PROMPT_DATA.replace('{history}', historyText)
|
||||
} else {
|
||||
const context = ragContext || 'Ingen specifik kontext hittades i kunskapsbasen.'
|
||||
systemPrompt = SYSTEM_PROMPT_HYBRID
|
||||
.replace('{context}', context)
|
||||
.replace('{history}', historyText)
|
||||
}
|
||||
|
||||
// Create the model
|
||||
const model = new ChatAnthropic({
|
||||
modelName: CHATBOT_CONFIG.agentModel,
|
||||
maxTokens: CHATBOT_CONFIG.agentMaxTokens,
|
||||
temperature: CHATBOT_CONFIG.temperature,
|
||||
anthropicApiKey: process.env.ANTHROPIC_API_KEY,
|
||||
})
|
||||
|
||||
// Create the agent
|
||||
const agent = createReactAgent({
|
||||
llm: model,
|
||||
tools,
|
||||
prompt: systemPrompt,
|
||||
})
|
||||
|
||||
// Build input messages
|
||||
const messages: (HumanMessage | AIMessage)[] = []
|
||||
|
||||
// Add recent history as messages for the agent
|
||||
const recent = conversationHistory.slice(-CHATBOT_CONFIG.maxHistoryMessages)
|
||||
for (const msg of recent) {
|
||||
if (msg.role === 'user') {
|
||||
messages.push(new HumanMessage(msg.content))
|
||||
} else {
|
||||
messages.push(new AIMessage(msg.content))
|
||||
}
|
||||
}
|
||||
messages.push(new HumanMessage(query))
|
||||
|
||||
// Track tool results for artifact generation
|
||||
const toolResults: ToolResultEntry[] = []
|
||||
|
||||
// Stream the agent execution using streamEvents for fine-grained control
|
||||
const eventStream = agent.streamEvents(
|
||||
{ messages },
|
||||
{
|
||||
version: 'v2',
|
||||
recursionLimit: CHATBOT_CONFIG.maxAgentIterations * 2 + 1,
|
||||
}
|
||||
)
|
||||
|
||||
for await (const event of eventStream) {
|
||||
// Tool start events
|
||||
if (event.event === 'on_tool_start') {
|
||||
yield { type: 'tool_start', toolName: event.name }
|
||||
}
|
||||
|
||||
// Tool end events — capture results
|
||||
if (event.event === 'on_tool_end') {
|
||||
const output = event.data?.output
|
||||
const result = typeof output === 'string' ? output : JSON.stringify(output ?? '')
|
||||
toolResults.push({
|
||||
toolName: event.name,
|
||||
result,
|
||||
})
|
||||
}
|
||||
|
||||
// LLM streaming tokens (final response text)
|
||||
if (event.event === 'on_chat_model_stream') {
|
||||
const chunk = event.data?.chunk
|
||||
if (chunk) {
|
||||
const content = typeof chunk.content === 'string'
|
||||
? chunk.content
|
||||
: Array.isArray(chunk.content)
|
||||
? chunk.content
|
||||
.filter((c: { type: string }) => c.type === 'text')
|
||||
.map((c: { text: string }) => c.text)
|
||||
.join('')
|
||||
: ''
|
||||
if (content) {
|
||||
yield { type: 'content', content }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
yield { type: 'done', toolResults }
|
||||
}
|
||||
@@ -1,237 +0,0 @@
|
||||
import { ChatAnthropic } from '@langchain/anthropic'
|
||||
import { z } from 'zod'
|
||||
import { CHATBOT_CONFIG } from './config'
|
||||
import type { ToolResultEntry } from './agent'
|
||||
import type { ArtifactSpec } from '@/types/chat'
|
||||
|
||||
// ── Artifact Zod Schemas ────────────────────────────────────────
|
||||
|
||||
const ChartDataPoint = z.object({
|
||||
label: z.string(),
|
||||
value: z.number(),
|
||||
color: z.string().optional(),
|
||||
})
|
||||
|
||||
const ChartArtifact = z.object({
|
||||
type: z.enum(['bar_chart', 'line_chart', 'pie_chart', 'stacked_bar']),
|
||||
title: z.string(),
|
||||
data: z.array(ChartDataPoint),
|
||||
unit: z.string().optional(),
|
||||
subtitle: z.string().optional(),
|
||||
})
|
||||
|
||||
const TableColumn = z.object({
|
||||
key: z.string(),
|
||||
label: z.string(),
|
||||
align: z.enum(['left', 'right']).optional(),
|
||||
})
|
||||
|
||||
const TableArtifact = z.object({
|
||||
type: z.literal('table'),
|
||||
title: z.string(),
|
||||
columns: z.array(TableColumn),
|
||||
rows: z.array(z.record(z.string(), z.union([z.string(), z.number()]))),
|
||||
summary_row: z.record(z.string(), z.union([z.string(), z.number()])).optional(),
|
||||
})
|
||||
|
||||
const KpiCard = z.object({
|
||||
label: z.string(),
|
||||
value: z.string(),
|
||||
trend: z.enum(['up', 'down', 'flat']).optional(),
|
||||
change: z.string().optional(),
|
||||
})
|
||||
|
||||
const KpiCardsArtifact = z.object({
|
||||
type: z.literal('kpi_cards'),
|
||||
title: z.string().optional(),
|
||||
cards: z.array(KpiCard),
|
||||
})
|
||||
|
||||
const AgingBucket = z.object({
|
||||
label: z.string(),
|
||||
amount: z.number(),
|
||||
count: z.number(),
|
||||
})
|
||||
|
||||
const AgingBucketsArtifact = z.object({
|
||||
type: z.literal('aging_buckets'),
|
||||
title: z.string(),
|
||||
buckets: z.array(AgingBucket),
|
||||
total: z.number(),
|
||||
})
|
||||
|
||||
export const ArtifactSpecSchema = z.discriminatedUnion('type', [
|
||||
ChartArtifact,
|
||||
TableArtifact,
|
||||
KpiCardsArtifact,
|
||||
AgingBucketsArtifact,
|
||||
])
|
||||
|
||||
export type { ArtifactSpec } from '@/types/chat'
|
||||
|
||||
// ── Artifact System Prompt ──────────────────────────────────────
|
||||
|
||||
const ARTIFACT_SYSTEM_PROMPT = `You are a data visualization expert. Given tool results and an AI response about accounting data, generate a structured artifact spec for visual display.
|
||||
|
||||
## EXACT schemas (follow field names precisely):
|
||||
|
||||
### Chart (bar_chart, line_chart, pie_chart, stacked_bar):
|
||||
{"type":"bar_chart","title":"...","data":[{"label":"Category name","value":1234}],"unit":"kr"}
|
||||
IMPORTANT: Each item in "data" MUST have "label" (string) and "value" (number). NOT "name", NOT "amount" — use exactly "label" and "value".
|
||||
|
||||
### Table:
|
||||
{"type":"table","title":"...","columns":[{"key":"col1","label":"Header","align":"right"}],"rows":[{"col1":"value"}],"summary_row":{"col1":"Total"}}
|
||||
|
||||
### KPI cards:
|
||||
{"type":"kpi_cards","title":"...","cards":[{"label":"Metric","value":"1 234 kr","trend":"up","change":"+12%"}]}
|
||||
IMPORTANT: "trend" MUST be exactly "up", "down", or "flat". No other values allowed.
|
||||
|
||||
### Aging buckets:
|
||||
{"type":"aging_buckets","title":"...","buckets":[{"label":"0 dagar","amount":1000,"count":2}],"total":5000}
|
||||
|
||||
## Rules:
|
||||
1. Return ONLY a single JSON object (not an array!) or the word "null". The top-level must be an object with a "type" field.
|
||||
2. Choose chart type based on data:
|
||||
- Income/balance sheet sections → "bar_chart"
|
||||
- Distribution (VAT, account classes) → "pie_chart"
|
||||
- Company overview → "kpi_cards"
|
||||
- AR/AP aging → "aging_buckets"
|
||||
- Lists with >3 items + amounts → "table"
|
||||
- Simple answers, few items, yes/no → null
|
||||
3. Use Swedish labels. Use "kr" as unit for monetary charts.
|
||||
4. Max 12 chart data points. Aggregate small items as "Övrigt".
|
||||
5. For tables, include summary_row with totals where appropriate.`
|
||||
|
||||
// ── Normalizer ──────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Fix common LLM field name mistakes before Zod validation.
|
||||
* Mutates the object in place.
|
||||
*/
|
||||
function normalizeArtifact(obj: Record<string, unknown>): void {
|
||||
if (!obj || typeof obj !== 'object') return
|
||||
|
||||
// Chart types: normalize data[].name→label, data[].amount→value
|
||||
const chartTypes = ['bar_chart', 'line_chart', 'pie_chart', 'stacked_bar']
|
||||
if (chartTypes.includes(obj.type as string) && Array.isArray(obj.data)) {
|
||||
for (const item of obj.data) {
|
||||
if (item && typeof item === 'object') {
|
||||
if ('name' in item && !('label' in item)) {
|
||||
item.label = item.name
|
||||
delete item.name
|
||||
}
|
||||
if ('amount' in item && !('value' in item)) {
|
||||
item.value = item.amount
|
||||
delete item.amount
|
||||
}
|
||||
if ('total' in item && !('value' in item)) {
|
||||
item.value = item.total
|
||||
delete item.total
|
||||
}
|
||||
if ('value' in item && typeof item.value === 'string') {
|
||||
const num = parseFloat(String(item.value).replace(/\s/g, '').replace(',', '.'))
|
||||
if (!isNaN(num)) item.value = num
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// KPI cards: normalize trend values
|
||||
if (obj.type === 'kpi_cards' && Array.isArray(obj.cards)) {
|
||||
const trendMap: Record<string, string> = {
|
||||
neutral: 'flat', stable: 'flat', none: 'flat', '-': 'flat',
|
||||
negative: 'down', decrease: 'down', declining: 'down',
|
||||
positive: 'up', increase: 'up', increasing: 'up', growing: 'up',
|
||||
}
|
||||
for (const card of obj.cards) {
|
||||
if (card && typeof card === 'object' && 'trend' in card) {
|
||||
const t = String(card.trend).toLowerCase()
|
||||
if (trendMap[t]) {
|
||||
card.trend = trendMap[t]
|
||||
} else if (t !== 'up' && t !== 'down' && t !== 'flat') {
|
||||
// Unknown trend value — remove it so optional field passes
|
||||
delete card.trend
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Generator ───────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Generate an artifact spec from tool results using a post-processing LLM call.
|
||||
* Returns null if no visualization is appropriate.
|
||||
*/
|
||||
export async function generateArtifact(
|
||||
toolResults: ToolResultEntry[],
|
||||
assistantResponse: string
|
||||
): Promise<ArtifactSpec | null> {
|
||||
if (toolResults.length === 0) return null
|
||||
|
||||
const model = new ChatAnthropic({
|
||||
modelName: CHATBOT_CONFIG.artifactModel,
|
||||
maxTokens: 1024,
|
||||
temperature: 0,
|
||||
anthropicApiKey: process.env.ANTHROPIC_API_KEY,
|
||||
})
|
||||
|
||||
const toolSummary = toolResults
|
||||
.map((r) => `Tool: ${r.toolName}\nResult: ${r.result.slice(0, 2000)}`)
|
||||
.join('\n\n---\n\n')
|
||||
|
||||
const prompt = `${ARTIFACT_SYSTEM_PROMPT}
|
||||
|
||||
## Tool results:
|
||||
${toolSummary}
|
||||
|
||||
## AI response:
|
||||
${assistantResponse.slice(0, 1000)}
|
||||
|
||||
Generate the artifact JSON or "null":`
|
||||
|
||||
try {
|
||||
const response = await model.invoke(prompt)
|
||||
const text = typeof response.content === 'string'
|
||||
? response.content
|
||||
: JSON.stringify(response.content)
|
||||
|
||||
const trimmed = text.trim()
|
||||
if (trimmed === 'null' || trimmed === '"null"') return null
|
||||
|
||||
// Extract JSON from response (handle markdown code blocks)
|
||||
let jsonStr = trimmed
|
||||
const codeBlockMatch = trimmed.match(/```(?:json)?\s*([\s\S]*?)```/)
|
||||
if (codeBlockMatch) {
|
||||
jsonStr = codeBlockMatch[1].trim()
|
||||
}
|
||||
|
||||
let parsed = JSON.parse(jsonStr)
|
||||
|
||||
// If LLM returned an array, try to wrap it as kpi_cards
|
||||
if (Array.isArray(parsed)) {
|
||||
// Array of cards → wrap as kpi_cards
|
||||
if (parsed.length > 0 && parsed[0] && typeof parsed[0] === 'object' && 'label' in parsed[0]) {
|
||||
parsed = { type: 'kpi_cards', title: 'Översikt', cards: parsed }
|
||||
} else {
|
||||
console.warn('Artifact returned unexpected array')
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize common LLM field name mistakes before validation
|
||||
normalizeArtifact(parsed)
|
||||
|
||||
const validated = ArtifactSpecSchema.safeParse(parsed)
|
||||
|
||||
if (validated.success) {
|
||||
return validated.data as ArtifactSpec
|
||||
}
|
||||
|
||||
console.warn('Artifact validation failed:', validated.error.issues)
|
||||
return null
|
||||
} catch (e) {
|
||||
console.warn('Artifact generation failed:', e)
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -1,250 +0,0 @@
|
||||
import { ChatAnthropic } from '@langchain/anthropic'
|
||||
import { HumanMessage, SystemMessage } from '@langchain/core/messages'
|
||||
import { CHATBOT_CONFIG } from './config'
|
||||
import {
|
||||
SYSTEM_PROMPT,
|
||||
formatContextFromSources,
|
||||
formatConversationHistory,
|
||||
} from './prompts'
|
||||
import {
|
||||
retrieveRelevantDocuments,
|
||||
documentsToSources,
|
||||
} from './retriever'
|
||||
import { routeMessage, type RouteType } from './router'
|
||||
import { createAccountingTools } from './tools'
|
||||
import { streamAgentResponse, type ToolResultEntry } from './agent'
|
||||
import { generateArtifact, type ArtifactSpec } from './artifacts'
|
||||
import type { ChatMessage, SourceReference } from '@/types/chat'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { trackTokenUsage } from '@/lib/ai/usage-tracker'
|
||||
|
||||
// Initialize the LLM
|
||||
function getChatModel() {
|
||||
return new ChatAnthropic({
|
||||
modelName: CHATBOT_CONFIG.model,
|
||||
maxTokens: CHATBOT_CONFIG.maxTokens,
|
||||
temperature: CHATBOT_CONFIG.temperature,
|
||||
anthropicApiKey: process.env.ANTHROPIC_API_KEY,
|
||||
})
|
||||
}
|
||||
|
||||
export interface ChatResult {
|
||||
content: string
|
||||
sources: SourceReference[]
|
||||
}
|
||||
|
||||
export async function generateChatResponse(
|
||||
userMessage: string,
|
||||
conversationHistory: ChatMessage[],
|
||||
tracking?: { supabase: SupabaseClient; userId: string; companyId?: string }
|
||||
): Promise<ChatResult> {
|
||||
// 1. Retrieve relevant documents
|
||||
const relevantDocs = await retrieveRelevantDocuments(userMessage)
|
||||
|
||||
// 2. Format context from retrieved documents
|
||||
const context = formatContextFromSources(
|
||||
relevantDocs.map((doc) => ({
|
||||
content: doc.content,
|
||||
title: doc.title,
|
||||
section_title: doc.section_title,
|
||||
source_file: doc.source_file,
|
||||
}))
|
||||
)
|
||||
|
||||
// 3. Format conversation history (last N messages)
|
||||
const recentHistory = conversationHistory.slice(
|
||||
-CHATBOT_CONFIG.maxHistoryMessages
|
||||
)
|
||||
const historyText = formatConversationHistory(
|
||||
recentHistory.map((msg) => ({
|
||||
role: msg.role,
|
||||
content: msg.content,
|
||||
}))
|
||||
)
|
||||
|
||||
// 4. Build the system prompt with context
|
||||
const systemPrompt = SYSTEM_PROMPT.replace('{context}', context).replace(
|
||||
'{history}',
|
||||
historyText
|
||||
)
|
||||
|
||||
// 5. Generate response
|
||||
const model = getChatModel()
|
||||
const response = await model.invoke([
|
||||
new SystemMessage(systemPrompt),
|
||||
new HumanMessage(userMessage),
|
||||
])
|
||||
|
||||
// 6. Track token usage
|
||||
if (tracking && response.usage_metadata) {
|
||||
trackTokenUsage(tracking.supabase, tracking.userId, 'ai-chat', {
|
||||
inputTokens: response.usage_metadata.input_tokens ?? 0,
|
||||
outputTokens: response.usage_metadata.output_tokens ?? 0,
|
||||
model: CHATBOT_CONFIG.model,
|
||||
}, tracking.companyId)
|
||||
}
|
||||
|
||||
// 7. Extract content and sources
|
||||
const content =
|
||||
typeof response.content === 'string'
|
||||
? response.content
|
||||
: JSON.stringify(response.content)
|
||||
|
||||
return {
|
||||
content,
|
||||
sources: documentsToSources(relevantDocs),
|
||||
}
|
||||
}
|
||||
|
||||
export async function* streamChatResponse(
|
||||
userMessage: string,
|
||||
conversationHistory: ChatMessage[]
|
||||
): AsyncGenerator<{ type: 'content' | 'sources'; data: string | SourceReference[] }> {
|
||||
// 1. Retrieve relevant documents first
|
||||
const relevantDocs = await retrieveRelevantDocuments(userMessage)
|
||||
|
||||
// 2. Format context from retrieved documents
|
||||
const context = formatContextFromSources(
|
||||
relevantDocs.map((doc) => ({
|
||||
content: doc.content,
|
||||
title: doc.title,
|
||||
section_title: doc.section_title,
|
||||
source_file: doc.source_file,
|
||||
}))
|
||||
)
|
||||
|
||||
// 3. Format conversation history
|
||||
const recentHistory = conversationHistory.slice(
|
||||
-CHATBOT_CONFIG.maxHistoryMessages
|
||||
)
|
||||
const historyText = formatConversationHistory(
|
||||
recentHistory.map((msg) => ({
|
||||
role: msg.role,
|
||||
content: msg.content,
|
||||
}))
|
||||
)
|
||||
|
||||
// 4. Build the system prompt
|
||||
const systemPrompt = SYSTEM_PROMPT.replace('{context}', context).replace(
|
||||
'{history}',
|
||||
historyText
|
||||
)
|
||||
|
||||
// 5. Stream the response
|
||||
const model = getChatModel()
|
||||
const stream = await model.stream([
|
||||
new SystemMessage(systemPrompt),
|
||||
new HumanMessage(userMessage),
|
||||
])
|
||||
|
||||
for await (const chunk of stream) {
|
||||
const content =
|
||||
typeof chunk.content === 'string'
|
||||
? chunk.content
|
||||
: JSON.stringify(chunk.content)
|
||||
if (content) {
|
||||
yield { type: 'content', data: content }
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Yield sources at the end
|
||||
yield { type: 'sources', data: documentsToSources(relevantDocs) }
|
||||
}
|
||||
|
||||
// ── Routed response (data / hybrid / knowledge) ────────────────
|
||||
|
||||
export type RoutedStreamEvent =
|
||||
| { type: 'content'; content: string }
|
||||
| { type: 'sources'; sources: SourceReference[] }
|
||||
| { type: 'tool_start'; toolName: string }
|
||||
| { type: 'artifact'; artifact: ArtifactSpec }
|
||||
| { type: 'route'; route: RouteType }
|
||||
|
||||
/**
|
||||
* High-level streaming function: routes the message, then either uses
|
||||
* the existing RAG chain (knowledge) or the LangGraph agent (data/hybrid).
|
||||
* Generates artifact post-hoc on data/hybrid routes.
|
||||
*/
|
||||
export async function* streamRoutedResponse(
|
||||
userMessage: string,
|
||||
conversationHistory: ChatMessage[],
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
_sessionId?: string
|
||||
): AsyncGenerator<RoutedStreamEvent> {
|
||||
// 1. Route the message
|
||||
const { route, rewrittenQuery } = await routeMessage(userMessage, conversationHistory)
|
||||
yield { type: 'route', route }
|
||||
|
||||
// 2. Knowledge-only: use existing RAG chain
|
||||
if (route === 'knowledge') {
|
||||
for await (const chunk of streamChatResponse(rewrittenQuery, conversationHistory)) {
|
||||
if (chunk.type === 'content') {
|
||||
yield { type: 'content', content: chunk.data as string }
|
||||
} else if (chunk.type === 'sources') {
|
||||
yield { type: 'sources', sources: chunk.data as SourceReference[] }
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 3. Data or hybrid: use LangGraph agent with tools
|
||||
const tools = createAccountingTools(supabase, userId)
|
||||
|
||||
// For hybrid, get RAG context
|
||||
let ragContext: string | undefined
|
||||
let sources: SourceReference[] = []
|
||||
if (route === 'hybrid') {
|
||||
try {
|
||||
const relevantDocs = await retrieveRelevantDocuments(rewrittenQuery)
|
||||
ragContext = formatContextFromSources(
|
||||
relevantDocs.map((doc) => ({
|
||||
content: doc.content,
|
||||
title: doc.title,
|
||||
section_title: doc.section_title,
|
||||
source_file: doc.source_file,
|
||||
}))
|
||||
)
|
||||
sources = documentsToSources(relevantDocs)
|
||||
} catch {
|
||||
// RAG failure is non-critical for hybrid route
|
||||
}
|
||||
}
|
||||
|
||||
let fullContent = ''
|
||||
let toolResults: ToolResultEntry[] = []
|
||||
|
||||
for await (const event of streamAgentResponse({
|
||||
query: rewrittenQuery,
|
||||
route,
|
||||
tools,
|
||||
conversationHistory,
|
||||
ragContext,
|
||||
})) {
|
||||
if (event.type === 'tool_start') {
|
||||
yield { type: 'tool_start', toolName: event.toolName! }
|
||||
} else if (event.type === 'content') {
|
||||
fullContent += event.content!
|
||||
yield { type: 'content', content: event.content! }
|
||||
} else if (event.type === 'done') {
|
||||
toolResults = event.toolResults || []
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Yield sources if hybrid
|
||||
if (sources.length > 0) {
|
||||
yield { type: 'sources', sources }
|
||||
}
|
||||
|
||||
// 5. Generate artifact (post-processing)
|
||||
if (toolResults.length > 0 && fullContent.length > 0) {
|
||||
try {
|
||||
const artifact = await generateArtifact(toolResults, fullContent)
|
||||
if (artifact) {
|
||||
yield { type: 'artifact', artifact }
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('Artifact generation failed:', e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
// AI Chatbot configuration
|
||||
|
||||
export const CHATBOT_CONFIG = {
|
||||
// LLM settings
|
||||
model: 'claude-haiku-4-5-20251001',
|
||||
maxTokens: 2048,
|
||||
temperature: 0.3,
|
||||
|
||||
// Agent settings
|
||||
agentModel: 'claude-sonnet-4-6',
|
||||
agentMaxTokens: 4096,
|
||||
maxAgentIterations: 5,
|
||||
|
||||
// Router settings
|
||||
routerModel: 'claude-haiku-4-5-20251001',
|
||||
|
||||
// Artifact generation
|
||||
artifactModel: 'claude-haiku-4-5-20251001',
|
||||
|
||||
// Retrieval settings
|
||||
retrievalK: 5,
|
||||
similarityThreshold: 0.7,
|
||||
|
||||
// Embedding settings
|
||||
embeddingModel: 'text-embedding-ada-002',
|
||||
|
||||
// Chunking settings for ingestion
|
||||
chunkSize: 1000,
|
||||
chunkOverlap: 200,
|
||||
|
||||
// Rate limiting
|
||||
rateLimitPerMinute: 10,
|
||||
|
||||
// Conversation history
|
||||
maxHistoryMessages: 10,
|
||||
} as const
|
||||
@@ -1,25 +0,0 @@
|
||||
import { OpenAIEmbeddings } from '@langchain/openai'
|
||||
import { CHATBOT_CONFIG } from './config'
|
||||
|
||||
// Singleton instance for embeddings
|
||||
let embeddingsInstance: OpenAIEmbeddings | null = null
|
||||
|
||||
export function getEmbeddings(): OpenAIEmbeddings {
|
||||
if (!embeddingsInstance) {
|
||||
embeddingsInstance = new OpenAIEmbeddings({
|
||||
modelName: CHATBOT_CONFIG.embeddingModel,
|
||||
openAIApiKey: process.env.OPENAI_API_KEY,
|
||||
})
|
||||
}
|
||||
return embeddingsInstance
|
||||
}
|
||||
|
||||
export async function generateEmbedding(text: string): Promise<number[]> {
|
||||
const embeddings = getEmbeddings()
|
||||
return embeddings.embedQuery(text)
|
||||
}
|
||||
|
||||
export async function generateEmbeddings(texts: string[]): Promise<number[][]> {
|
||||
const embeddings = getEmbeddings()
|
||||
return embeddings.embedDocuments(texts)
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
// Swedish system prompt for bookkeeping AI assistant
|
||||
|
||||
export const SYSTEM_PROMPT = `Du är en expert AI-assistent som hjälper svenska företagare med skatt, moms, bokföring och företagsekonomi. Du arbetar inom en ekonomiplattform för småföretag.
|
||||
|
||||
## Dina kunskapsområden:
|
||||
- Svensk skattlagstiftning för enskild firma och aktiebolag
|
||||
- Moms och momsdeklaration
|
||||
- Bokföring enligt BAS-kontoplanen
|
||||
- Egenavgifter och socialförsäkring
|
||||
- Avdrag för utrustning, resor, hemmakontor och liknande
|
||||
- Fakturering och kundhantering
|
||||
- NE-bilaga och inkomstdeklaration
|
||||
|
||||
## Viktiga tröskelvärden att komma ihåg:
|
||||
- Momsregistrering: 120 000 kr omsättning under 12 månader
|
||||
- Direktavdrag vs inventarier: 26 250 kr (halvt prisbasbelopp)
|
||||
- SGI-gräns för sjukpenning: 13 500 kr/år minsta inkomst
|
||||
- Karensavdrag: 20% av sjuklönen
|
||||
- Friskvårdsbidrag max: 6 000 kr/år (ej skattepliktigt)
|
||||
- Representationsavdrag mat: 90 kr exkl moms per person
|
||||
|
||||
## Instruktioner:
|
||||
1. Svara alltid på svenska med korrekt terminologi
|
||||
2. Var konkret och ge specifika exempel när möjligt
|
||||
3. Referera till relevanta tröskelvärden och regler
|
||||
4. Om du är osäker, säg det och rekommendera att användaren konsulterar en revisor
|
||||
5. Använd information från de tillhandahållna källorna för att ge korrekta svar
|
||||
6. Formatera svaren tydligt med punktlistor när det passar
|
||||
7. Om frågan gäller något utanför dina kunskapsområden, hänvisa till rätt instans
|
||||
|
||||
## Kontext från kunskapsbasen:
|
||||
{context}
|
||||
|
||||
## Tidigare konversation:
|
||||
{history}
|
||||
|
||||
Svara på användarens fråga baserat på din expertkunskap och den tillhandahållna kontexten. Om kontexten inte innehåller relevant information, använd din allmänna kunskap om svenska skatteregler för företagare.`
|
||||
|
||||
export const RETRIEVAL_PROMPT = `Baserat på följande fråga, hitta relevant information från kunskapsbasen.
|
||||
|
||||
Fråga: {question}
|
||||
|
||||
Sök efter information som hjälper att besvara frågan korrekt och fullständigt.`
|
||||
|
||||
/**
|
||||
* System prompt for tool-calling agent (data route).
|
||||
* No RAG context — relies entirely on tools.
|
||||
*/
|
||||
export const SYSTEM_PROMPT_DATA = `Du är en AI-assistent i en svensk ekonomiplattform. Du har tillgång till verktyg som hämtar användarens bokföringsdata i realtid.
|
||||
|
||||
## Instruktioner:
|
||||
1. Svara alltid på svenska
|
||||
2. Använd verktygen för att hämta data innan du svarar — gissa aldrig siffror
|
||||
3. Presentera data tydligt med belopp i SEK om inget annat anges
|
||||
4. Om ett verktyg returnerar tom data, berätta det vänligt (t.ex. "Du har inga obetalda fakturor just nu")
|
||||
5. Avrunda belopp till hela kronor i text, men behåll decimaler i tabeller
|
||||
6. Använd svenska bokföringstermer (verifikation, kontering, resultaträkning, etc.)
|
||||
7. Förklara kort vad siffrorna betyder i kontext — var pedagogisk
|
||||
|
||||
## Formatering:
|
||||
- Använd markdown: **fetstil** för belopp, punktlistor för detaljer
|
||||
- ABSOLUT FÖRBJUDET att använda markdown-tabeller (|---|). Använd ALDRIG pipe-tecken för tabeller. Data visas automatiskt i en visuell komponent nedanför ditt svar
|
||||
- Använd punktlistor eller fetstil istället för tabeller
|
||||
- Sammanfatta huvudinsikten först, detaljer sedan
|
||||
- Max 3-4 meningar för enkla frågor, mer för rapporter
|
||||
- Använd inte emojis
|
||||
|
||||
## Tidigare konversation:
|
||||
{history}`
|
||||
|
||||
/**
|
||||
* System prompt for hybrid route: RAG context + tools.
|
||||
*/
|
||||
export const SYSTEM_PROMPT_HYBRID = `Du är en expert AI-assistent i en svensk ekonomiplattform. Du har tillgång till verktyg som hämtar användarens bokföringsdata, samt kunskap om svenska skatteregler.
|
||||
|
||||
## Kunskapsområden:
|
||||
- Svensk skattlagstiftning, moms, bokföring (BAS-kontoplanen)
|
||||
- Avdrag, egenavgifter, socialförsäkring
|
||||
- Fakturering, NE-bilaga, inkomstdeklaration
|
||||
|
||||
## Viktiga tröskelvärden:
|
||||
- Momsregistrering: 120 000 kr/12 mån
|
||||
- Direktavdrag: 26 250 kr
|
||||
- Friskvårdsbidrag: 6 000 kr/år
|
||||
|
||||
## Instruktioner:
|
||||
1. Svara alltid på svenska med korrekt terminologi
|
||||
2. Använd verktygen för att hämta data — gissa aldrig siffror
|
||||
3. Kombinera data med regelkunskap för att ge kontextuella råd
|
||||
4. Om du är osäker, rekommendera att konsultera en revisor
|
||||
5. Formatera tydligt med markdown, men ABSOLUT FÖRBJUDET att använda markdown-tabeller (|---|). Använd ALDRIG pipe-tecken för tabeller — data visas automatiskt i en visuell komponent. Använd punktlistor istället. Använd inte emojis
|
||||
|
||||
## Kontext från kunskapsbasen:
|
||||
{context}
|
||||
|
||||
## Tidigare konversation:
|
||||
{history}`
|
||||
|
||||
export function formatContextFromSources(
|
||||
sources: Array<{
|
||||
content: string
|
||||
title: string
|
||||
section_title: string | null
|
||||
source_file: string
|
||||
}>
|
||||
): string {
|
||||
if (sources.length === 0) {
|
||||
return 'Ingen specifik kontext hittades i kunskapsbasen.'
|
||||
}
|
||||
|
||||
return sources
|
||||
.map((source, index) => {
|
||||
const sectionInfo = source.section_title
|
||||
? ` > ${source.section_title}`
|
||||
: ''
|
||||
return `[Källa ${index + 1}: ${source.title}${sectionInfo}]\n${source.content}`
|
||||
})
|
||||
.join('\n\n---\n\n')
|
||||
}
|
||||
|
||||
export function formatConversationHistory(
|
||||
messages: Array<{ role: 'user' | 'assistant'; content: string }>
|
||||
): string {
|
||||
if (messages.length === 0) {
|
||||
return 'Ingen tidigare konversation.'
|
||||
}
|
||||
|
||||
return messages
|
||||
.map((msg) => {
|
||||
const role = msg.role === 'user' ? 'Användare' : 'Assistent'
|
||||
return `${role}: ${msg.content}`
|
||||
})
|
||||
.join('\n\n')
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { generateEmbedding } from './embeddings'
|
||||
import { CHATBOT_CONFIG } from './config'
|
||||
import type { SourceReference } from '@/types/chat'
|
||||
|
||||
export interface RetrievedDocument {
|
||||
id: string
|
||||
source_file: string
|
||||
title: string
|
||||
section_title: string | null
|
||||
content: string
|
||||
metadata: Record<string, unknown>
|
||||
similarity: number
|
||||
}
|
||||
|
||||
export async function retrieveRelevantDocuments(
|
||||
query: string,
|
||||
matchCount: number = CHATBOT_CONFIG.retrievalK,
|
||||
matchThreshold: number = CHATBOT_CONFIG.similarityThreshold
|
||||
): Promise<RetrievedDocument[]> {
|
||||
const supabase = await createServiceClient()
|
||||
|
||||
// Generate embedding for the query
|
||||
const queryEmbedding = await generateEmbedding(query)
|
||||
|
||||
// Call the match_documents function
|
||||
const { data, error } = await supabase.rpc('match_documents', {
|
||||
query_embedding: queryEmbedding,
|
||||
match_count: matchCount,
|
||||
match_threshold: matchThreshold,
|
||||
})
|
||||
|
||||
if (error) {
|
||||
console.error('Error retrieving documents:', error)
|
||||
throw new Error('Failed to retrieve relevant documents')
|
||||
}
|
||||
|
||||
return (data || []) as RetrievedDocument[]
|
||||
}
|
||||
|
||||
export function documentsToSources(
|
||||
documents: RetrievedDocument[]
|
||||
): SourceReference[] {
|
||||
return documents.map((doc) => ({
|
||||
id: doc.id,
|
||||
source_file: doc.source_file,
|
||||
title: doc.title,
|
||||
section_title: doc.section_title,
|
||||
similarity: doc.similarity,
|
||||
}))
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
import { ChatAnthropic } from '@langchain/anthropic'
|
||||
import { CHATBOT_CONFIG } from './config'
|
||||
import type { ChatMessage } from '@/types/chat'
|
||||
|
||||
export type RouteType = 'knowledge' | 'data' | 'hybrid'
|
||||
|
||||
export interface RouterResult {
|
||||
route: RouteType
|
||||
rewrittenQuery: string
|
||||
}
|
||||
|
||||
// Swedish data-related keywords for fast-path heuristic
|
||||
const DATA_NOUNS = [
|
||||
'faktura', 'fakturor', 'fakturorna',
|
||||
'leverantörsfaktura', 'leverantörsfakturor',
|
||||
'transaktion', 'transaktioner', 'transaktionerna',
|
||||
'verifikation', 'verifikationer', 'verifikationerna',
|
||||
'resultaträkning', 'balansräkning',
|
||||
'moms', 'momsdeklaration', 'momssammanställning',
|
||||
'saldo', 'saldon', 'kontosaldo',
|
||||
'konto', 'konton', 'kontona',
|
||||
'kunder', 'kundfordringar',
|
||||
'leverantörsskulder',
|
||||
'intäkter', 'kostnader', 'utgifter',
|
||||
'resultat', 'årsresultat',
|
||||
'bokföring', 'bokförda', 'obokförda',
|
||||
'obetalda', 'förfallna',
|
||||
'nyckeltal', 'företaget', 'företagsinfo',
|
||||
]
|
||||
|
||||
const POSSESSIVE_PRONOUNS = ['mina', 'min', 'mitt', 'mig', 'våra', 'vår', 'vårt']
|
||||
|
||||
const KNOWLEDGE_TERMS = [
|
||||
'momsgransen', 'momsgränsen', 'avdrag', 'skatteregler',
|
||||
'bokföringslag', 'bokföringslagen', 'regler', 'lag',
|
||||
'hur fungerar', 'vad innebär', 'vad betyder', 'vad är',
|
||||
'när måste', 'hur räknar', 'hur beräknar',
|
||||
'enskild firma', 'aktiebolag', 'egenavgifter',
|
||||
'prisbasbelopp', 'schablonavdrag', 'representation',
|
||||
'friskvårdsbidrag', 'traktamente',
|
||||
]
|
||||
|
||||
/**
|
||||
* Fast-path keyword heuristic. Returns a route if confident, null otherwise.
|
||||
*/
|
||||
function heuristicClassify(query: string): RouteType | null {
|
||||
const lower = query.toLowerCase()
|
||||
const words = lower.split(/\s+/)
|
||||
|
||||
const hasPossessive = POSSESSIVE_PRONOUNS.some((p) => words.includes(p))
|
||||
const hasDataNoun = DATA_NOUNS.some((n) => lower.includes(n))
|
||||
const hasKnowledgeTerm = KNOWLEDGE_TERMS.some((t) => lower.includes(t))
|
||||
|
||||
// "Visa mina fakturor" — clearly data
|
||||
if (hasPossessive && hasDataNoun && !hasKnowledgeTerm) return 'data'
|
||||
|
||||
// Action verbs with data nouns
|
||||
const actionVerbs = ['visa', 'hämta', 'lista', 'sök', 'hitta', 'hur går', 'hur ser', 'hur mycket', 'hur många', 'vilka']
|
||||
const hasAction = actionVerbs.some((v) => lower.includes(v))
|
||||
if (hasAction && hasDataNoun && !hasKnowledgeTerm) return 'data'
|
||||
|
||||
// Pure knowledge question with no data references
|
||||
if (hasKnowledgeTerm && !hasPossessive && !hasDataNoun) return 'knowledge'
|
||||
|
||||
// "Hur ser min resultaträkning ut?" — data (has possessive + data noun)
|
||||
if (hasPossessive && hasDataNoun && hasKnowledgeTerm) return 'hybrid'
|
||||
|
||||
return null // ambiguous → fall through to LLM
|
||||
}
|
||||
|
||||
/**
|
||||
* LLM-based classification + query rewrite for multi-turn context.
|
||||
*/
|
||||
async function llmClassify(
|
||||
query: string,
|
||||
conversationHistory: ChatMessage[]
|
||||
): Promise<RouterResult> {
|
||||
const model = new ChatAnthropic({
|
||||
modelName: CHATBOT_CONFIG.routerModel,
|
||||
maxTokens: 256,
|
||||
temperature: 0,
|
||||
anthropicApiKey: process.env.ANTHROPIC_API_KEY,
|
||||
})
|
||||
|
||||
const historyContext = conversationHistory
|
||||
.slice(-4)
|
||||
.map((m) => `${m.role === 'user' ? 'User' : 'Assistant'}: ${m.content.slice(0, 200)}`)
|
||||
.join('\n')
|
||||
|
||||
const prompt = `Classify the user's question and rewrite it for a data query system.
|
||||
|
||||
Conversation history:
|
||||
${historyContext || '(none)'}
|
||||
|
||||
User question: "${query}"
|
||||
|
||||
Classification rules:
|
||||
- "knowledge": General questions about Swedish tax law, accounting rules, regulations (no user-specific data needed)
|
||||
- "data": Questions about the user's own accounting data (invoices, transactions, balances, reports)
|
||||
- "hybrid": Questions that need both user data AND knowledge context
|
||||
|
||||
Rewriting rules:
|
||||
- Resolve pronouns ("dem", "de", "den") using conversation history
|
||||
- Make the query self-contained (no context needed to understand it)
|
||||
- If it's a knowledge question, keep the original query
|
||||
|
||||
Respond ONLY with valid JSON:
|
||||
{"route": "knowledge"|"data"|"hybrid", "rewrittenQuery": "..."}
|
||||
`
|
||||
|
||||
try {
|
||||
const response = await model.invoke(prompt)
|
||||
const text = typeof response.content === 'string'
|
||||
? response.content
|
||||
: JSON.stringify(response.content)
|
||||
|
||||
// Extract JSON from response
|
||||
const jsonMatch = text.match(/\{[^}]+\}/)
|
||||
if (jsonMatch) {
|
||||
const parsed = JSON.parse(jsonMatch[0])
|
||||
const route = ['knowledge', 'data', 'hybrid'].includes(parsed.route)
|
||||
? (parsed.route as RouteType)
|
||||
: 'hybrid'
|
||||
return {
|
||||
route,
|
||||
rewrittenQuery: parsed.rewrittenQuery || query,
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('Router LLM classification failed, defaulting to hybrid:', e)
|
||||
}
|
||||
|
||||
return { route: 'hybrid', rewrittenQuery: query }
|
||||
}
|
||||
|
||||
/**
|
||||
* Route a user message: fast-path heuristic first, LLM fallback for ambiguous cases.
|
||||
*/
|
||||
export async function routeMessage(
|
||||
query: string,
|
||||
conversationHistory: ChatMessage[]
|
||||
): Promise<RouterResult> {
|
||||
const heuristicResult = heuristicClassify(query)
|
||||
|
||||
if (heuristicResult) {
|
||||
// For data/hybrid with conversation history, still rewrite the query for context
|
||||
if (heuristicResult !== 'knowledge' && conversationHistory.length > 0) {
|
||||
const { rewrittenQuery } = await llmClassify(query, conversationHistory)
|
||||
return { route: heuristicResult, rewrittenQuery }
|
||||
}
|
||||
return { route: heuristicResult, rewrittenQuery: query }
|
||||
}
|
||||
|
||||
// Ambiguous — use LLM
|
||||
return llmClassify(query, conversationHistory)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,49 +0,0 @@
|
||||
import { CallbackHandler } from '@langfuse/langchain'
|
||||
|
||||
let langfuseConfigured: boolean | null = null
|
||||
|
||||
function isLangfuseConfigured(): boolean {
|
||||
if (langfuseConfigured !== null) return langfuseConfigured
|
||||
langfuseConfigured = !!(
|
||||
process.env.LANGFUSE_SECRET_KEY &&
|
||||
process.env.LANGFUSE_PUBLIC_KEY
|
||||
)
|
||||
return langfuseConfigured
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a Langfuse callback handler for LangChain tracing.
|
||||
* Returns null if Langfuse is not configured (graceful degradation).
|
||||
*/
|
||||
export function createTraceHandler(options: {
|
||||
sessionId?: string
|
||||
userId?: string
|
||||
metadata?: Record<string, unknown>
|
||||
}): CallbackHandler | null {
|
||||
if (!isLangfuseConfigured()) return null
|
||||
|
||||
try {
|
||||
return new CallbackHandler({
|
||||
sessionId: options.sessionId,
|
||||
userId: options.userId,
|
||||
})
|
||||
} catch {
|
||||
console.warn('Failed to create Langfuse handler, tracing disabled')
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush Langfuse handler. Safe to call with null.
|
||||
*/
|
||||
export async function flushTrace(handler: CallbackHandler | null): Promise<void> {
|
||||
if (!handler) return
|
||||
try {
|
||||
// Langfuse CallbackHandler may expose flush via different methods
|
||||
if ('shutdownAsync' in handler && typeof handler.shutdownAsync === 'function') {
|
||||
await handler.shutdownAsync()
|
||||
}
|
||||
} catch {
|
||||
// Non-critical — tracing failure should never block response
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import type { Extension } from '@/lib/extensions/types'
|
||||
import { aiChatApiRoutes } from './api-routes'
|
||||
|
||||
/**
|
||||
* AI Chat Extension
|
||||
*
|
||||
* Provides an AI-powered chatbot assistant for Swedish tax and bookkeeping
|
||||
* questions. Uses RAG (Retrieval Augmented Generation) with a knowledge base
|
||||
* of Swedish tax laws, regulations, and best practices.
|
||||
*
|
||||
* Components:
|
||||
* - chatbot/: Chain, config, prompts, embeddings, retriever
|
||||
* - ingestion/: CLI tool for ingesting knowledge base documents
|
||||
*/
|
||||
export const aiChatExtension: Extension = {
|
||||
id: 'ai-chat',
|
||||
name: 'AI-assistent',
|
||||
version: '1.0.0',
|
||||
sector: 'general',
|
||||
apiRoutes: aiChatApiRoutes,
|
||||
settingsPanel: {
|
||||
label: 'AI-assistent',
|
||||
path: '/settings/extensions/ai-chat',
|
||||
},
|
||||
}
|
||||
@@ -1,353 +0,0 @@
|
||||
/**
|
||||
* Knowledge Base Ingestion Script
|
||||
*
|
||||
* Loads markdown files from dev_docs/ai_knowledge_base/,
|
||||
* chunks them by sections, generates embeddings, and stores in Supabase.
|
||||
*
|
||||
* Run with: npx tsx lib/ai/ingestion/ingest.ts
|
||||
*/
|
||||
|
||||
import * as dotenv from 'dotenv'
|
||||
dotenv.config({ path: '.env.local' })
|
||||
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
import { OpenAIEmbeddings } from '@langchain/openai'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import * as crypto from 'crypto'
|
||||
|
||||
// Configuration
|
||||
// NOTE: The ai_knowledge_base directory must be created and populated before running ingestion.
|
||||
// Create dev_docs/ai_knowledge_base/ and add markdown files to ingest.
|
||||
const DOCS_DIR = path.join(process.cwd(), 'dev_docs', 'ai_knowledge_base')
|
||||
const CHUNK_SIZE = 1000
|
||||
const CHUNK_OVERLAP = 200
|
||||
const EMBEDDING_MODEL = 'text-embedding-ada-002'
|
||||
|
||||
// Initialize clients
|
||||
const supabase = createClient(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY!
|
||||
)
|
||||
|
||||
const embeddings = new OpenAIEmbeddings({
|
||||
modelName: EMBEDDING_MODEL,
|
||||
openAIApiKey: process.env.OPENAI_API_KEY,
|
||||
})
|
||||
|
||||
interface DocumentChunk {
|
||||
source_file: string
|
||||
title: string
|
||||
section_title: string | null
|
||||
content: string
|
||||
content_hash: string
|
||||
metadata: Record<string, unknown>
|
||||
}
|
||||
|
||||
interface Section {
|
||||
title: string
|
||||
content: string
|
||||
level: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a markdown file into sections based on headings
|
||||
*/
|
||||
function parseMarkdownSections(content: string): Section[] {
|
||||
const lines = content.split('\n')
|
||||
const sections: Section[] = []
|
||||
let currentSection: Section | null = null
|
||||
let contentBuffer: string[] = []
|
||||
|
||||
for (const line of lines) {
|
||||
// Check for headings (H1, H2, H3)
|
||||
const h1Match = line.match(/^# (.+)$/)
|
||||
const h2Match = line.match(/^## (.+)$/)
|
||||
const h3Match = line.match(/^### (.+)$/)
|
||||
|
||||
if (h1Match || h2Match || h3Match) {
|
||||
// Save previous section
|
||||
if (currentSection && contentBuffer.length > 0) {
|
||||
currentSection.content = contentBuffer.join('\n').trim()
|
||||
if (currentSection.content) {
|
||||
sections.push(currentSection)
|
||||
}
|
||||
}
|
||||
|
||||
// Start new section
|
||||
const title = h1Match?.[1] || h2Match?.[1] || h3Match?.[1] || ''
|
||||
const level = h1Match ? 1 : h2Match ? 2 : 3
|
||||
currentSection = { title, content: '', level }
|
||||
contentBuffer = []
|
||||
} else {
|
||||
contentBuffer.push(line)
|
||||
}
|
||||
}
|
||||
|
||||
// Don't forget the last section
|
||||
if (currentSection && contentBuffer.length > 0) {
|
||||
currentSection.content = contentBuffer.join('\n').trim()
|
||||
if (currentSection.content) {
|
||||
sections.push(currentSection)
|
||||
}
|
||||
}
|
||||
|
||||
return sections
|
||||
}
|
||||
|
||||
/**
|
||||
* Split text into chunks while preserving context
|
||||
*/
|
||||
function chunkText(text: string, maxSize: number, overlap: number): string[] {
|
||||
if (text.length <= maxSize) {
|
||||
return [text]
|
||||
}
|
||||
|
||||
const chunks: string[] = []
|
||||
let start = 0
|
||||
|
||||
while (start < text.length) {
|
||||
let end = start + maxSize
|
||||
|
||||
// Try to break at a natural point (paragraph, sentence, or word)
|
||||
if (end < text.length) {
|
||||
// Look for paragraph break
|
||||
const paragraphBreak = text.lastIndexOf('\n\n', end)
|
||||
if (paragraphBreak > start + maxSize / 2) {
|
||||
end = paragraphBreak
|
||||
} else {
|
||||
// Look for sentence break
|
||||
const sentenceBreak = text.lastIndexOf('. ', end)
|
||||
if (sentenceBreak > start + maxSize / 2) {
|
||||
end = sentenceBreak + 1
|
||||
} else {
|
||||
// Look for word break
|
||||
const wordBreak = text.lastIndexOf(' ', end)
|
||||
if (wordBreak > start + maxSize / 2) {
|
||||
end = wordBreak
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
chunks.push(text.slice(start, end).trim())
|
||||
start = end - overlap
|
||||
if (start < 0) start = 0
|
||||
if (end >= text.length) break
|
||||
}
|
||||
|
||||
return chunks.filter((c) => c.length > 0)
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract metadata from content (trigger words, categories, etc.)
|
||||
*/
|
||||
function extractMetadata(
|
||||
content: string,
|
||||
_sectionTitle: string
|
||||
): Record<string, unknown> {
|
||||
const metadata: Record<string, unknown> = {}
|
||||
|
||||
// Extract scenario IDs (e.g., "Scenario 001")
|
||||
const scenarioMatches = content.match(/Scenario\s+(\d{3})/gi)
|
||||
if (scenarioMatches) {
|
||||
metadata.scenarios = scenarioMatches.map((m) =>
|
||||
m.replace(/Scenario\s+/i, '')
|
||||
)
|
||||
}
|
||||
|
||||
// Extract mentioned thresholds/amounts
|
||||
const amountMatches = content.match(/(\d+[\s\d]*)\s*(kr|SEK|kronor)/gi)
|
||||
if (amountMatches) {
|
||||
metadata.amounts = amountMatches.slice(0, 5) // Limit to first 5
|
||||
}
|
||||
|
||||
// Extract platform mentions
|
||||
const platforms = [
|
||||
'YouTube',
|
||||
'Twitch',
|
||||
'Instagram',
|
||||
'TikTok',
|
||||
'Patreon',
|
||||
'Spotify',
|
||||
'Adtraction',
|
||||
]
|
||||
const mentionedPlatforms = platforms.filter((p) =>
|
||||
content.toLowerCase().includes(p.toLowerCase())
|
||||
)
|
||||
if (mentionedPlatforms.length > 0) {
|
||||
metadata.platforms = mentionedPlatforms
|
||||
}
|
||||
|
||||
// Extract categories based on keywords
|
||||
const categories: string[] = []
|
||||
if (/moms|vat/i.test(content)) categories.push('moms')
|
||||
if (/skatt|deklaration/i.test(content)) categories.push('skatt')
|
||||
if (/avdrag/i.test(content)) categories.push('avdrag')
|
||||
if (/bokför|konto|bas/i.test(content)) categories.push('bokföring')
|
||||
if (/sgi|sjuk|föräldra|pension/i.test(content))
|
||||
categories.push('socialförsäkring')
|
||||
if (/ef|enskild firma/i.test(content)) categories.push('enskild_firma')
|
||||
if (/ab|aktiebolag/i.test(content)) categories.push('aktiebolag')
|
||||
|
||||
if (categories.length > 0) {
|
||||
metadata.categories = categories
|
||||
}
|
||||
|
||||
return metadata
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate content hash for deduplication
|
||||
*/
|
||||
function generateHash(content: string): string {
|
||||
return crypto.createHash('sha256').update(content).digest('hex').slice(0, 16)
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a single markdown file
|
||||
*/
|
||||
function processFile(filePath: string): DocumentChunk[] {
|
||||
const content = fs.readFileSync(filePath, 'utf-8')
|
||||
const fileName = path.basename(filePath)
|
||||
const sections = parseMarkdownSections(content)
|
||||
|
||||
const chunks: DocumentChunk[] = []
|
||||
|
||||
// Get document title from first H1
|
||||
const documentTitle =
|
||||
sections.find((s) => s.level === 1)?.title || fileName.replace('.md', '')
|
||||
|
||||
for (const section of sections) {
|
||||
// Skip empty sections
|
||||
if (!section.content || section.content.length < 50) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Chunk large sections
|
||||
const textChunks = chunkText(section.content, CHUNK_SIZE, CHUNK_OVERLAP)
|
||||
|
||||
for (let i = 0; i < textChunks.length; i++) {
|
||||
const chunkContent = textChunks[i]
|
||||
const sectionTitle =
|
||||
section.level === 1
|
||||
? null
|
||||
: textChunks.length > 1
|
||||
? `${section.title} (del ${i + 1}/${textChunks.length})`
|
||||
: section.title
|
||||
|
||||
chunks.push({
|
||||
source_file: fileName,
|
||||
title: documentTitle,
|
||||
section_title: sectionTitle,
|
||||
content: chunkContent,
|
||||
content_hash: generateHash(chunkContent),
|
||||
metadata: extractMetadata(chunkContent, section.title),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return chunks
|
||||
}
|
||||
|
||||
/**
|
||||
* Main ingestion function
|
||||
*/
|
||||
async function ingest() {
|
||||
console.log('Starting knowledge base ingestion...')
|
||||
console.log(`Reading files from: ${DOCS_DIR}`)
|
||||
|
||||
if (!fs.existsSync(DOCS_DIR)) {
|
||||
console.error(`Error: Knowledge base directory not found: ${DOCS_DIR}`)
|
||||
console.error('Create dev_docs/ai_knowledge_base/ and add markdown files before running ingestion.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// Get all markdown files
|
||||
const files = fs
|
||||
.readdirSync(DOCS_DIR)
|
||||
.filter((f) => f.endsWith('.md'))
|
||||
.sort()
|
||||
|
||||
console.log(`Found ${files.length} markdown files`)
|
||||
|
||||
// Process all files
|
||||
const allChunks: DocumentChunk[] = []
|
||||
for (const file of files) {
|
||||
const filePath = path.join(DOCS_DIR, file)
|
||||
console.log(`Processing: ${file}`)
|
||||
const chunks = processFile(filePath)
|
||||
allChunks.push(...chunks)
|
||||
console.log(` -> ${chunks.length} chunks`)
|
||||
}
|
||||
|
||||
console.log(`Total chunks: ${allChunks.length}`)
|
||||
|
||||
// Clear existing documents (optional - comment out for incremental updates)
|
||||
console.log('Clearing existing documents...')
|
||||
const { error: deleteError } = await supabase
|
||||
.from('knowledge_documents')
|
||||
.delete()
|
||||
.neq('id', '00000000-0000-0000-0000-000000000000') // Delete all
|
||||
|
||||
if (deleteError) {
|
||||
console.error('Error clearing documents:', deleteError)
|
||||
// Continue anyway
|
||||
}
|
||||
|
||||
// Generate embeddings in batches
|
||||
const BATCH_SIZE = 20
|
||||
let processed = 0
|
||||
|
||||
for (let i = 0; i < allChunks.length; i += BATCH_SIZE) {
|
||||
const batch = allChunks.slice(i, i + BATCH_SIZE)
|
||||
const contents = batch.map((c) => c.content)
|
||||
|
||||
console.log(
|
||||
`Generating embeddings for batch ${Math.floor(i / BATCH_SIZE) + 1}/${Math.ceil(allChunks.length / BATCH_SIZE)}...`
|
||||
)
|
||||
|
||||
// Generate embeddings
|
||||
const embeddingVectors = await embeddings.embedDocuments(contents)
|
||||
|
||||
// Prepare records for insertion
|
||||
const records = batch.map((chunk, idx) => ({
|
||||
source_file: chunk.source_file,
|
||||
title: chunk.title,
|
||||
section_title: chunk.section_title,
|
||||
content: chunk.content,
|
||||
content_hash: chunk.content_hash,
|
||||
embedding: embeddingVectors[idx],
|
||||
metadata: chunk.metadata,
|
||||
}))
|
||||
|
||||
// Insert into Supabase
|
||||
const { error: insertError } = await supabase
|
||||
.from('knowledge_documents')
|
||||
.insert(records)
|
||||
|
||||
if (insertError) {
|
||||
console.error('Error inserting batch:', insertError)
|
||||
throw insertError
|
||||
}
|
||||
|
||||
processed += batch.length
|
||||
console.log(` Inserted ${processed}/${allChunks.length} documents`)
|
||||
}
|
||||
|
||||
console.log('\nIngestion complete!')
|
||||
console.log(`Total documents inserted: ${allChunks.length}`)
|
||||
|
||||
// Verify
|
||||
const { count } = await supabase
|
||||
.from('knowledge_documents')
|
||||
.select('*', { count: 'exact', head: true })
|
||||
|
||||
console.log(`Documents in database: ${count}`)
|
||||
}
|
||||
|
||||
// Run if called directly
|
||||
ingest().catch((error) => {
|
||||
console.error('Ingestion failed:', error)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"id": "ai-chat",
|
||||
"sector": "general",
|
||||
"exportName": "aiChatExtension",
|
||||
"entryPoint": "@/extensions/general/ai-chat",
|
||||
"workspace": "@/components/extensions/general/AiChatWorkspace",
|
||||
"requiredEnvVars": ["ANTHROPIC_API_KEY", "OPENAI_API_KEY"],
|
||||
"optionalEnvVars": ["LANGFUSE_SECRET_KEY", "LANGFUSE_PUBLIC_KEY", "LANGFUSE_BASE_URL"],
|
||||
"npmDependencies": ["@langchain/anthropic", "@langchain/core", "langchain", "@langchain/openai", "@langchain/langgraph", "@langfuse/core", "@langfuse/langchain"],
|
||||
"definition": {
|
||||
"name": "AI-assistent",
|
||||
"category": "operations",
|
||||
"icon": "MessageSquare",
|
||||
"dataPattern": "both",
|
||||
"readsCoreTables": ["invoices", "supplier_invoices", "transactions", "journal_entries", "journal_entry_lines", "fiscal_periods", "company_settings", "customers", "suppliers", "chart_of_accounts"],
|
||||
"hasOwnData": true,
|
||||
"description": "AI-assistent för skatte- och bokföringsfrågor med tillgång till din data",
|
||||
"longDescription": "Ställ frågor om skatt, bokföring och företagande till en AI-assistent som förstår svensk redovisning. Kan hämta och visualisera din bokföringsdata — fakturor, transaktioner, resultaträkning, balansräkning och mer.",
|
||||
"quickAction": {
|
||||
"label": "AI-assistent",
|
||||
"description": "Fråga om bokföring",
|
||||
"icon": "MessageSquare",
|
||||
"event": "open-ai-chat"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ export const enableBankingExtension: Extension = {
|
||||
|
||||
settingsPanel: {
|
||||
label: 'Bankintegration (PSD2)',
|
||||
path: '/settings?tab=banking',
|
||||
path: '/settings/banking',
|
||||
},
|
||||
|
||||
apiRoutes: [
|
||||
|
||||
@@ -1,103 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
import { createMockSupabase } from '@/tests/helpers'
|
||||
|
||||
// Mock dependencies
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../lib/invoice-analyzer', () => ({
|
||||
analyzeInvoice: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../lib/supplier-matcher', () => ({
|
||||
matchSupplier: vi.fn(),
|
||||
}))
|
||||
|
||||
// Mock api-routes to avoid transitive server-only import from document-analyzer
|
||||
vi.mock('../api-routes', () => ({
|
||||
invoiceInboxApiRoutes: [],
|
||||
}))
|
||||
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { invoiceInboxExtension, getSettings, saveSettings } from '../index'
|
||||
|
||||
const mockCreateClient = vi.mocked(createClient)
|
||||
|
||||
describe('Invoice Inbox Extension', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
})
|
||||
|
||||
describe('Extension metadata', () => {
|
||||
it('has correct id and version', () => {
|
||||
expect(invoiceInboxExtension.id).toBe('invoice-inbox')
|
||||
expect(invoiceInboxExtension.name).toBe('Invoice Inbox')
|
||||
expect(invoiceInboxExtension.version).toBe('1.0.0')
|
||||
})
|
||||
|
||||
it('has event handler for document.uploaded', () => {
|
||||
expect(invoiceInboxExtension.eventHandlers).toHaveLength(1)
|
||||
expect(invoiceInboxExtension.eventHandlers![0].eventType).toBe('document.uploaded')
|
||||
})
|
||||
|
||||
it('has settings panel', () => {
|
||||
expect(invoiceInboxExtension.settingsPanel).toEqual({
|
||||
label: 'Invoice Inbox',
|
||||
path: '/settings/extensions/invoice-inbox',
|
||||
})
|
||||
})
|
||||
|
||||
it('has onInstall hook', () => {
|
||||
expect(invoiceInboxExtension.onInstall).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getSettings', () => {
|
||||
it('returns default settings when no data exists', async () => {
|
||||
const { supabase, mockResult } = createMockSupabase()
|
||||
mockCreateClient.mockResolvedValue(supabase as never)
|
||||
mockResult({ data: null, error: null })
|
||||
|
||||
const settings = await getSettings('user-1')
|
||||
|
||||
expect(settings).toEqual({
|
||||
autoProcessEnabled: true,
|
||||
autoMatchSupplierEnabled: true,
|
||||
supplierMatchThreshold: 0.7,
|
||||
inboxEmail: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('merges stored settings with defaults', async () => {
|
||||
const { supabase, mockResult } = createMockSupabase()
|
||||
mockCreateClient.mockResolvedValue(supabase as never)
|
||||
mockResult({
|
||||
data: { value: { inboxEmail: '[email protected]' } },
|
||||
error: null,
|
||||
})
|
||||
|
||||
const settings = await getSettings('user-1')
|
||||
|
||||
expect(settings.inboxEmail).toBe('[email protected]')
|
||||
expect(settings.autoProcessEnabled).toBe(true) // default
|
||||
})
|
||||
})
|
||||
|
||||
describe('saveSettings', () => {
|
||||
it('merges partial settings with current', async () => {
|
||||
const { supabase, mockResult } = createMockSupabase()
|
||||
mockCreateClient.mockResolvedValue(supabase as never)
|
||||
|
||||
// First call for getSettings (inside saveSettings)
|
||||
mockResult({ data: null, error: null })
|
||||
|
||||
const settings = await saveSettings('user-1', { inboxEmail: '[email protected]' })
|
||||
|
||||
expect(settings.inboxEmail).toBe('[email protected]')
|
||||
expect(settings.autoProcessEnabled).toBe(true)
|
||||
})
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,227 +0,0 @@
|
||||
import { analyzeInvoice } from './lib/invoice-analyzer'
|
||||
import { matchSupplier } from './lib/supplier-matcher'
|
||||
import type { Extension, ExtensionContext } from '@/lib/extensions/types'
|
||||
import type { EventPayload } from '@/lib/events/types'
|
||||
import type { InvoiceInboxSettings } from './types'
|
||||
import { invoiceInboxApiRoutes } from './api-routes'
|
||||
|
||||
// ============================================================
|
||||
// Settings
|
||||
// ============================================================
|
||||
|
||||
const DEFAULT_SETTINGS: InvoiceInboxSettings = {
|
||||
autoProcessEnabled: true,
|
||||
autoMatchSupplierEnabled: true,
|
||||
supplierMatchThreshold: 0.7,
|
||||
inboxEmail: null,
|
||||
}
|
||||
|
||||
/** Get settings via ExtensionContext (preferred in event handlers) */
|
||||
async function getSettingsViaCtx(ctx: ExtensionContext): Promise<InvoiceInboxSettings> {
|
||||
const stored = await ctx.settings.get<Partial<InvoiceInboxSettings>>()
|
||||
return { ...DEFAULT_SETTINGS, ...(stored || {}) }
|
||||
}
|
||||
|
||||
/** Get settings for external callers (settings routes, API routes) */
|
||||
export async function getSettings(userId: string): Promise<InvoiceInboxSettings> {
|
||||
const { createClient } = await import('@/lib/supabase/server')
|
||||
const supabase = await createClient()
|
||||
|
||||
const { data } = await supabase
|
||||
.from('extension_data')
|
||||
.select('value')
|
||||
.eq('company_id', userId)
|
||||
.eq('extension_id', 'invoice-inbox')
|
||||
.eq('key', 'settings')
|
||||
.single()
|
||||
|
||||
if (!data?.value) return { ...DEFAULT_SETTINGS }
|
||||
|
||||
return { ...DEFAULT_SETTINGS, ...(data.value as Partial<InvoiceInboxSettings>) }
|
||||
}
|
||||
|
||||
export async function saveSettings(
|
||||
userId: string,
|
||||
partial: Partial<InvoiceInboxSettings>
|
||||
): Promise<InvoiceInboxSettings> {
|
||||
const current = await getSettings(userId)
|
||||
const merged = { ...current, ...partial }
|
||||
|
||||
const { createClient } = await import('@/lib/supabase/server')
|
||||
const supabase = await createClient()
|
||||
|
||||
await supabase
|
||||
.from('extension_data')
|
||||
.upsert(
|
||||
{
|
||||
user_id: userId,
|
||||
extension_id: 'invoice-inbox',
|
||||
key: 'settings',
|
||||
value: merged,
|
||||
},
|
||||
{ onConflict: 'user_id,extension_id,key' }
|
||||
)
|
||||
|
||||
return merged
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Event Handlers
|
||||
// ============================================================
|
||||
|
||||
const INVOICE_MIME_TYPES = [
|
||||
'application/pdf',
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
'image/webp',
|
||||
]
|
||||
|
||||
/**
|
||||
* When a PDF/image is uploaded via the document archive, check if it should
|
||||
* be auto-processed as a supplier invoice.
|
||||
*/
|
||||
async function handleDocumentUploaded(
|
||||
payload: EventPayload<'document.uploaded'>,
|
||||
ctx?: ExtensionContext
|
||||
): Promise<void> {
|
||||
const { document, userId, companyId } = payload
|
||||
const log = ctx?.log ?? console
|
||||
|
||||
// Gate: Is it a supported file type?
|
||||
if (!document.mime_type || !INVOICE_MIME_TYPES.includes(document.mime_type)) {
|
||||
return
|
||||
}
|
||||
|
||||
// Gate: Is autoProcessEnabled?
|
||||
const settings = ctx ? await getSettingsViaCtx(ctx) : await getSettings(userId)
|
||||
if (!settings.autoProcessEnabled) {
|
||||
return
|
||||
}
|
||||
|
||||
// Gate: Was this document already processed as an inbox item?
|
||||
const supabase = ctx?.supabase ?? await (await import('@/lib/supabase/server')).createClient()
|
||||
const { data: existing } = await supabase
|
||||
.from('invoice_inbox_items')
|
||||
.select('id')
|
||||
.eq('company_id', userId)
|
||||
.eq('document_id', document.id)
|
||||
.limit(1)
|
||||
|
||||
if (existing && existing.length > 0) {
|
||||
return
|
||||
}
|
||||
|
||||
log.info(`Auto-process triggered for document ${document.id}`)
|
||||
|
||||
try {
|
||||
// Create inbox item
|
||||
const { data: inboxItem, error: insertError } = await supabase
|
||||
.from('invoice_inbox_items')
|
||||
.insert({
|
||||
user_id: userId,
|
||||
status: 'processing',
|
||||
source: 'upload',
|
||||
document_id: document.id,
|
||||
})
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (insertError || !inboxItem) {
|
||||
log.error('Failed to create inbox item:', insertError)
|
||||
return
|
||||
}
|
||||
|
||||
// Download file from storage
|
||||
const { data: fileData, error: downloadError } = await supabase.storage
|
||||
.from('documents')
|
||||
.download(document.storage_path)
|
||||
|
||||
if (downloadError || !fileData) {
|
||||
await supabase
|
||||
.from('invoice_inbox_items')
|
||||
.update({ status: 'error', error_message: 'Failed to download document' })
|
||||
.eq('id', inboxItem.id)
|
||||
return
|
||||
}
|
||||
|
||||
// Convert to base64
|
||||
const arrayBuffer = await fileData.arrayBuffer()
|
||||
const base64 = Buffer.from(arrayBuffer).toString('base64')
|
||||
|
||||
// Analyze invoice
|
||||
const extraction = await analyzeInvoice(base64, document.mime_type)
|
||||
|
||||
// Supplier matching
|
||||
let matchedSupplierId: string | null = null
|
||||
if (settings.autoMatchSupplierEnabled) {
|
||||
const { data: suppliers } = await supabase
|
||||
.from('suppliers')
|
||||
.select('*')
|
||||
.eq('company_id', userId)
|
||||
|
||||
if (suppliers && suppliers.length > 0) {
|
||||
const match = matchSupplier(extraction, suppliers)
|
||||
if (match && match.confidence >= settings.supplierMatchThreshold) {
|
||||
matchedSupplierId = match.supplierId
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update inbox item with extracted data
|
||||
await supabase
|
||||
.from('invoice_inbox_items')
|
||||
.update({
|
||||
status: 'ready',
|
||||
extracted_data: extraction as unknown as Record<string, unknown>,
|
||||
confidence: extraction.confidence,
|
||||
matched_supplier_id: matchedSupplierId,
|
||||
})
|
||||
.eq('id', inboxItem.id)
|
||||
|
||||
// Fetch updated item
|
||||
const { data: updatedItem } = await supabase
|
||||
.from('invoice_inbox_items')
|
||||
.select('*')
|
||||
.eq('id', inboxItem.id)
|
||||
.single()
|
||||
|
||||
if (updatedItem) {
|
||||
const emit = ctx?.emit ?? (await import('@/lib/events/bus')).eventBus.emit.bind((await import('@/lib/events/bus')).eventBus)
|
||||
await emit({
|
||||
type: 'supplier_invoice.extracted',
|
||||
payload: {
|
||||
inboxItem: updatedItem,
|
||||
confidence: extraction.confidence,
|
||||
userId,
|
||||
companyId,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
log.info(`Invoice ${inboxItem.id} processed (confidence: ${extraction.confidence})`)
|
||||
} catch (error) {
|
||||
log.error('handleDocumentUploaded failed:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Extension Object
|
||||
// ============================================================
|
||||
|
||||
export const invoiceInboxExtension: Extension = {
|
||||
id: 'invoice-inbox',
|
||||
name: 'Invoice Inbox',
|
||||
version: '1.0.0',
|
||||
sector: 'general',
|
||||
apiRoutes: invoiceInboxApiRoutes,
|
||||
eventHandlers: [
|
||||
{ eventType: 'document.uploaded', handler: handleDocumentUploaded },
|
||||
],
|
||||
settingsPanel: {
|
||||
label: 'Invoice Inbox',
|
||||
path: '/settings/extensions/invoice-inbox',
|
||||
},
|
||||
async onInstall(ctx) {
|
||||
await ctx.settings.set('settings', DEFAULT_SETTINGS)
|
||||
},
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
|
||||
// Mock server-only
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
import { parseInboundPayload, extractAttachments, resolveUserFromEmail } from '../email-handler'
|
||||
import type { ResendInboundPayload } from '../../types'
|
||||
|
||||
describe('Email Handler', () => {
|
||||
describe('parseInboundPayload', () => {
|
||||
it('returns null for null input', () => {
|
||||
expect(parseInboundPayload(null)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for non-object input', () => {
|
||||
expect(parseInboundPayload('string')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when from is missing', () => {
|
||||
expect(parseInboundPayload({ to: '[email protected]' })).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when to is missing', () => {
|
||||
expect(parseInboundPayload({ from: '[email protected]' })).toBeNull()
|
||||
})
|
||||
|
||||
it('parses valid payload', () => {
|
||||
const result = parseInboundPayload({
|
||||
from: '[email protected]',
|
||||
to: '[email protected]',
|
||||
subject: 'Faktura F-001',
|
||||
html: '<p>Attached</p>',
|
||||
text: 'Attached',
|
||||
attachments: [{ filename: 'invoice.pdf', content_type: 'application/pdf', content: 'base64data' }],
|
||||
created_at: '2024-06-15T10:00:00Z',
|
||||
})
|
||||
|
||||
expect(result).not.toBeNull()
|
||||
expect(result!.from).toBe('[email protected]')
|
||||
expect(result!.to).toBe('[email protected]')
|
||||
expect(result!.subject).toBe('Faktura F-001')
|
||||
expect(result!.attachments).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('handles missing optional fields', () => {
|
||||
const result = parseInboundPayload({
|
||||
from: '[email protected]',
|
||||
to: '[email protected]',
|
||||
})
|
||||
|
||||
expect(result).not.toBeNull()
|
||||
expect(result!.subject).toBe('')
|
||||
expect(result!.html).toBeNull()
|
||||
expect(result!.text).toBeNull()
|
||||
expect(result!.attachments).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('extractAttachments', () => {
|
||||
it('filters to supported file types only', () => {
|
||||
const payload: ResendInboundPayload = {
|
||||
from: '[email protected]',
|
||||
to: '[email protected]',
|
||||
subject: 'Test',
|
||||
html: null,
|
||||
text: null,
|
||||
created_at: '2024-06-15T10:00:00Z',
|
||||
attachments: [
|
||||
{ filename: 'invoice.pdf', content_type: 'application/pdf', content: 'base64' },
|
||||
{ filename: 'photo.jpg', content_type: 'image/jpeg', content: 'base64' },
|
||||
{ filename: 'doc.docx', content_type: 'application/vnd.openxmlformats', content: 'base64' },
|
||||
{ filename: 'sheet.xlsx', content_type: 'application/vnd.ms-excel', content: 'base64' },
|
||||
{ filename: 'scan.png', content_type: 'image/png', content: 'base64' },
|
||||
],
|
||||
}
|
||||
|
||||
const result = extractAttachments(payload)
|
||||
expect(result).toHaveLength(3)
|
||||
expect(result.map(a => a.content_type)).toEqual([
|
||||
'application/pdf',
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
])
|
||||
})
|
||||
|
||||
it('filters out attachments without content', () => {
|
||||
const payload: ResendInboundPayload = {
|
||||
from: '[email protected]',
|
||||
to: '[email protected]',
|
||||
subject: 'Test',
|
||||
html: null,
|
||||
text: null,
|
||||
created_at: '2024-06-15T10:00:00Z',
|
||||
attachments: [
|
||||
{ filename: 'invoice.pdf', content_type: 'application/pdf', content: '' },
|
||||
{ filename: 'photo.jpg', content_type: 'image/jpeg', content: 'base64data' },
|
||||
],
|
||||
}
|
||||
|
||||
const result = extractAttachments(payload)
|
||||
expect(result).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveUserFromEmail', () => {
|
||||
it('returns null when no extension data found', async () => {
|
||||
const mockClient = {
|
||||
from: vi.fn().mockReturnValue({
|
||||
select: vi.fn().mockReturnValue({
|
||||
eq: vi.fn().mockReturnValue({
|
||||
eq: vi.fn().mockResolvedValue({ data: null, error: { message: 'not found' } }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}
|
||||
|
||||
const result = await resolveUserFromEmail('[email protected]', mockClient)
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('returns user_id when email matches', async () => {
|
||||
const mockClient = {
|
||||
from: vi.fn().mockReturnValue({
|
||||
select: vi.fn().mockReturnValue({
|
||||
eq: vi.fn().mockReturnValue({
|
||||
eq: vi.fn().mockResolvedValue({
|
||||
data: [
|
||||
{ user_id: 'user-1', company_id: 'company-1', value: { inboxEmail: '[email protected]' } },
|
||||
{ user_id: 'user-2', company_id: 'company-2', value: { inboxEmail: '[email protected]' } },
|
||||
],
|
||||
error: null,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}
|
||||
|
||||
const result = await resolveUserFromEmail('[email protected]', mockClient)
|
||||
expect(result).toEqual({ userId: 'user-1', companyId: 'company-1' })
|
||||
})
|
||||
|
||||
it('handles case-insensitive email matching', async () => {
|
||||
const mockClient = {
|
||||
from: vi.fn().mockReturnValue({
|
||||
select: vi.fn().mockReturnValue({
|
||||
eq: vi.fn().mockReturnValue({
|
||||
eq: vi.fn().mockResolvedValue({
|
||||
data: [
|
||||
{ user_id: 'user-1', company_id: 'company-1', value: { inboxEmail: '[email protected]' } },
|
||||
],
|
||||
error: null,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}
|
||||
|
||||
const result = await resolveUserFromEmail('[email protected]', mockClient)
|
||||
expect(result).toEqual({ userId: 'user-1', companyId: 'company-1' })
|
||||
})
|
||||
|
||||
it('returns null when no matching email', async () => {
|
||||
const mockClient = {
|
||||
from: vi.fn().mockReturnValue({
|
||||
select: vi.fn().mockReturnValue({
|
||||
eq: vi.fn().mockReturnValue({
|
||||
eq: vi.fn().mockResolvedValue({
|
||||
data: [
|
||||
{ user_id: 'user-1', value: { inboxEmail: '[email protected]' } },
|
||||
],
|
||||
error: null,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}
|
||||
|
||||
const result = await resolveUserFromEmail('[email protected]', mockClient)
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,113 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
// Mock server-only
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
// Mock the core document-analyzer module
|
||||
const { mockExtractInvoice } = vi.hoisted(() => ({
|
||||
mockExtractInvoice: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/ai/document-analyzer', () => ({
|
||||
extractInvoice: mockExtractInvoice,
|
||||
}))
|
||||
|
||||
import { analyzeInvoice } from '../invoice-analyzer'
|
||||
|
||||
describe('Invoice Analyzer', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
const validExtraction = {
|
||||
supplier: {
|
||||
name: 'Kontorsbolaget AB',
|
||||
orgNumber: '556123-4567',
|
||||
vatNumber: 'SE5561234567',
|
||||
address: 'Storgatan 1, 111 22 Stockholm',
|
||||
bankgiro: '123-4567',
|
||||
plusgiro: null,
|
||||
},
|
||||
invoice: {
|
||||
invoiceNumber: 'F-2024-001',
|
||||
invoiceDate: '2024-06-15',
|
||||
dueDate: '2024-07-15',
|
||||
paymentReference: '1234567890',
|
||||
currency: 'SEK',
|
||||
},
|
||||
lineItems: [
|
||||
{
|
||||
description: 'Kontorsmaterial',
|
||||
quantity: 10,
|
||||
unitPrice: 50,
|
||||
lineTotal: 500,
|
||||
vatRate: 25,
|
||||
accountSuggestion: '6100',
|
||||
},
|
||||
],
|
||||
totals: {
|
||||
subtotal: 500,
|
||||
vatAmount: 125,
|
||||
total: 625,
|
||||
},
|
||||
vatBreakdown: [
|
||||
{ rate: 25, base: 500, amount: 125 },
|
||||
],
|
||||
confidence: 0.92,
|
||||
}
|
||||
|
||||
it('delegates to extractInvoice from core', async () => {
|
||||
mockExtractInvoice.mockResolvedValueOnce(validExtraction)
|
||||
|
||||
const result = await analyzeInvoice('base64data', 'application/pdf')
|
||||
|
||||
expect(mockExtractInvoice).toHaveBeenCalledWith('base64data', 'application/pdf')
|
||||
expect(result.supplier.name).toBe('Kontorsbolaget AB')
|
||||
expect(result.supplier.orgNumber).toBe('556123-4567')
|
||||
expect(result.invoice.invoiceNumber).toBe('F-2024-001')
|
||||
expect(result.lineItems).toHaveLength(1)
|
||||
expect(result.lineItems[0].lineTotal).toBe(500)
|
||||
expect(result.totals.total).toBe(625)
|
||||
expect(result.confidence).toBe(0.92)
|
||||
})
|
||||
|
||||
it('works with image mime types', async () => {
|
||||
mockExtractInvoice.mockResolvedValueOnce(validExtraction)
|
||||
|
||||
const result = await analyzeInvoice('base64data', 'image/jpeg')
|
||||
|
||||
expect(mockExtractInvoice).toHaveBeenCalledWith('base64data', 'image/jpeg')
|
||||
expect(result.supplier.name).toBe('Kontorsbolaget AB')
|
||||
})
|
||||
|
||||
it('propagates errors from core', async () => {
|
||||
mockExtractInvoice.mockRejectedValueOnce(new Error('Vision API call failed after 3 attempts'))
|
||||
|
||||
await expect(analyzeInvoice('base64data', 'application/pdf')).rejects.toThrow(
|
||||
'Vision API call failed after 3 attempts'
|
||||
)
|
||||
})
|
||||
|
||||
it('propagates unsupported file type errors', async () => {
|
||||
mockExtractInvoice.mockRejectedValueOnce(new Error('Unsupported file type: text/plain'))
|
||||
|
||||
await expect(analyzeInvoice('base64data', 'text/plain')).rejects.toThrow(
|
||||
'Unsupported file type'
|
||||
)
|
||||
})
|
||||
|
||||
it('returns validated account suggestions', async () => {
|
||||
const extractionWithAccounts = {
|
||||
...validExtraction,
|
||||
lineItems: [
|
||||
{ description: 'Item', quantity: 1, unitPrice: 100, lineTotal: 100, vatRate: 25, accountSuggestion: '6100' },
|
||||
{ description: 'Bad', quantity: 1, unitPrice: 50, lineTotal: 50, vatRate: 25, accountSuggestion: null },
|
||||
],
|
||||
}
|
||||
mockExtractInvoice.mockResolvedValueOnce(extractionWithAccounts)
|
||||
|
||||
const result = await analyzeInvoice('base64data', 'application/pdf')
|
||||
expect(result.lineItems[0].accountSuggestion).toBe('6100')
|
||||
expect(result.lineItems[1].accountSuggestion).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,240 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
matchSupplier,
|
||||
normalizeOrgNumber,
|
||||
normalizeVatNumber,
|
||||
normalizeBankgiro,
|
||||
calculateNameSimilarity,
|
||||
normalizeCompanyName,
|
||||
levenshteinDistance,
|
||||
} from '../supplier-matcher'
|
||||
import { makeSupplier } from '@/tests/helpers'
|
||||
import type { InvoiceExtractionResult } from '../../types'
|
||||
|
||||
function makeExtraction(overrides: Partial<InvoiceExtractionResult['supplier']> = {}): InvoiceExtractionResult {
|
||||
return {
|
||||
supplier: {
|
||||
name: null,
|
||||
orgNumber: null,
|
||||
vatNumber: null,
|
||||
address: null,
|
||||
bankgiro: null,
|
||||
plusgiro: null,
|
||||
...overrides,
|
||||
},
|
||||
invoice: {
|
||||
invoiceNumber: null,
|
||||
invoiceDate: null,
|
||||
dueDate: null,
|
||||
paymentReference: null,
|
||||
currency: 'SEK',
|
||||
},
|
||||
lineItems: [],
|
||||
totals: { subtotal: null, vatAmount: null, total: null },
|
||||
vatBreakdown: [],
|
||||
confidence: 0.9,
|
||||
}
|
||||
}
|
||||
|
||||
describe('Supplier Matcher', () => {
|
||||
describe('matchSupplier', () => {
|
||||
it('returns null for empty supplier list', () => {
|
||||
const result = matchSupplier(
|
||||
makeExtraction({ name: 'Test AB' }),
|
||||
[]
|
||||
)
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('matches by exact org number (pass 1)', () => {
|
||||
const suppliers = [
|
||||
makeSupplier({ id: 's1', name: 'Supplier A', org_number: '5599887766' }),
|
||||
makeSupplier({ id: 's2', name: 'Supplier B', org_number: '1122334455' }),
|
||||
]
|
||||
|
||||
const result = matchSupplier(
|
||||
makeExtraction({ orgNumber: '559988-7766' }),
|
||||
suppliers
|
||||
)
|
||||
|
||||
expect(result).not.toBeNull()
|
||||
expect(result!.supplierId).toBe('s1')
|
||||
expect(result!.matchMethod).toBe('org_number')
|
||||
expect(result!.confidence).toBe(0.98)
|
||||
})
|
||||
|
||||
it('matches by org number with different formatting', () => {
|
||||
const suppliers = [
|
||||
makeSupplier({ id: 's1', org_number: '556123-4567' }),
|
||||
]
|
||||
|
||||
const result = matchSupplier(
|
||||
makeExtraction({ orgNumber: '5561234567' }),
|
||||
suppliers
|
||||
)
|
||||
|
||||
expect(result).not.toBeNull()
|
||||
expect(result!.matchMethod).toBe('org_number')
|
||||
})
|
||||
|
||||
it('matches by VAT number (pass 2)', () => {
|
||||
const suppliers = [
|
||||
makeSupplier({ id: 's1', vat_number: 'SE556123456701' }),
|
||||
]
|
||||
|
||||
const result = matchSupplier(
|
||||
makeExtraction({ vatNumber: 'SE 5561 2345 6701' }),
|
||||
suppliers
|
||||
)
|
||||
|
||||
expect(result).not.toBeNull()
|
||||
expect(result!.matchMethod).toBe('vat_number')
|
||||
expect(result!.confidence).toBe(0.95)
|
||||
})
|
||||
|
||||
it('matches by bankgiro (pass 3)', () => {
|
||||
const suppliers = [
|
||||
makeSupplier({ id: 's1', bankgiro: '123-4567' }),
|
||||
]
|
||||
|
||||
const result = matchSupplier(
|
||||
makeExtraction({ bankgiro: '1234567' }),
|
||||
suppliers
|
||||
)
|
||||
|
||||
expect(result).not.toBeNull()
|
||||
expect(result!.matchMethod).toBe('bankgiro')
|
||||
expect(result!.confidence).toBe(0.92)
|
||||
})
|
||||
|
||||
it('matches by plusgiro', () => {
|
||||
const suppliers = [
|
||||
makeSupplier({ id: 's1', plusgiro: '123456-7' }),
|
||||
]
|
||||
|
||||
const result = matchSupplier(
|
||||
makeExtraction({ plusgiro: '1234567' }),
|
||||
suppliers
|
||||
)
|
||||
|
||||
expect(result).not.toBeNull()
|
||||
expect(result!.matchMethod).toBe('bankgiro')
|
||||
})
|
||||
|
||||
it('matches by fuzzy name (pass 4)', () => {
|
||||
const suppliers = [
|
||||
makeSupplier({ id: 's1', name: 'Kontorsbolaget AB' }),
|
||||
makeSupplier({ id: 's2', name: 'Byggmaterial i Stockholm' }),
|
||||
]
|
||||
|
||||
const result = matchSupplier(
|
||||
makeExtraction({ name: 'Kontorsbolaget' }),
|
||||
suppliers
|
||||
)
|
||||
|
||||
expect(result).not.toBeNull()
|
||||
expect(result!.supplierId).toBe('s1')
|
||||
expect(result!.matchMethod).toBe('fuzzy_name')
|
||||
})
|
||||
|
||||
it('returns null for low-confidence fuzzy name match', () => {
|
||||
const suppliers = [
|
||||
makeSupplier({ id: 's1', name: 'Completely Different Name AB' }),
|
||||
]
|
||||
|
||||
const result = matchSupplier(
|
||||
makeExtraction({ name: 'XYZ Corp' }),
|
||||
suppliers
|
||||
)
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('prefers org number match over name match', () => {
|
||||
const suppliers = [
|
||||
makeSupplier({ id: 's1', name: 'Kontorsbolaget AB', org_number: '5599887766' }),
|
||||
]
|
||||
|
||||
const result = matchSupplier(
|
||||
makeExtraction({ name: 'Kontorsbolaget', orgNumber: '559988-7766' }),
|
||||
suppliers
|
||||
)
|
||||
|
||||
expect(result!.matchMethod).toBe('org_number')
|
||||
})
|
||||
})
|
||||
|
||||
describe('normalizeOrgNumber', () => {
|
||||
it('strips non-digits', () => {
|
||||
expect(normalizeOrgNumber('556123-4567')).toBe('5561234567')
|
||||
expect(normalizeOrgNumber('556123 4567')).toBe('5561234567')
|
||||
})
|
||||
})
|
||||
|
||||
describe('normalizeVatNumber', () => {
|
||||
it('uppercases and removes spaces', () => {
|
||||
expect(normalizeVatNumber('se 5561234567 01')).toBe('SE556123456701')
|
||||
})
|
||||
})
|
||||
|
||||
describe('normalizeBankgiro', () => {
|
||||
it('strips non-digits', () => {
|
||||
expect(normalizeBankgiro('123-4567')).toBe('1234567')
|
||||
})
|
||||
})
|
||||
|
||||
describe('normalizeCompanyName', () => {
|
||||
it('strips AB suffix', () => {
|
||||
expect(normalizeCompanyName('Kontorsbolaget AB')).toBe('kontorsbolaget')
|
||||
})
|
||||
|
||||
it('strips HB suffix', () => {
|
||||
expect(normalizeCompanyName('Bröderna Svensson HB')).toBe('bröderna svensson')
|
||||
})
|
||||
|
||||
it('strips Aktiebolag', () => {
|
||||
expect(normalizeCompanyName('Test Aktiebolag')).toBe('test')
|
||||
})
|
||||
|
||||
it('strips Enskild firma', () => {
|
||||
expect(normalizeCompanyName('Test Enskild firma')).toBe('test')
|
||||
})
|
||||
|
||||
it('normalizes whitespace', () => {
|
||||
expect(normalizeCompanyName(' Multiple Spaces ')).toBe('multiple spaces')
|
||||
})
|
||||
})
|
||||
|
||||
describe('calculateNameSimilarity', () => {
|
||||
it('returns 1 for identical names', () => {
|
||||
expect(calculateNameSimilarity('Test AB', 'Test AB')).toBe(1)
|
||||
})
|
||||
|
||||
it('returns high score when one contains the other', () => {
|
||||
// After normalization 'AB' is stripped, so they become identical → 1.0
|
||||
expect(calculateNameSimilarity('Kontorsbolaget', 'Kontorsbolaget AB')).toBe(1)
|
||||
// With an actual substring relationship (not suffix stripping):
|
||||
expect(calculateNameSimilarity('Kontor', 'Kontorsbolaget')).toBe(0.9)
|
||||
})
|
||||
|
||||
it('returns 0 for empty strings', () => {
|
||||
expect(calculateNameSimilarity('', 'Test')).toBe(0)
|
||||
expect(calculateNameSimilarity('Test', '')).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('levenshteinDistance', () => {
|
||||
it('returns 0 for identical strings', () => {
|
||||
expect(levenshteinDistance('test', 'test')).toBe(0)
|
||||
})
|
||||
|
||||
it('calculates correct distance', () => {
|
||||
expect(levenshteinDistance('kitten', 'sitting')).toBe(3)
|
||||
})
|
||||
|
||||
it('handles empty strings', () => {
|
||||
expect(levenshteinDistance('', 'abc')).toBe(3)
|
||||
expect(levenshteinDistance('abc', '')).toBe(3)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,83 +0,0 @@
|
||||
/**
|
||||
* Email Handler - Parse Resend inbound webhook payloads
|
||||
*
|
||||
* SERVER-ONLY: Uses service role client for cross-user lookups.
|
||||
*/
|
||||
|
||||
import 'server-only'
|
||||
import type { ResendInboundPayload, ResendAttachment } from '../types'
|
||||
|
||||
const SUPPORTED_MIME_TYPES = [
|
||||
'application/pdf',
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
'image/webp',
|
||||
]
|
||||
|
||||
/**
|
||||
* Parse and validate a Resend inbound webhook payload
|
||||
*/
|
||||
export function parseInboundPayload(body: unknown): ResendInboundPayload | null {
|
||||
if (!body || typeof body !== 'object') return null
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const data = body as any
|
||||
|
||||
if (!data.from || !data.to) return null
|
||||
|
||||
return {
|
||||
from: String(data.from),
|
||||
to: String(data.to),
|
||||
subject: data.subject ? String(data.subject) : '',
|
||||
html: data.html || null,
|
||||
text: data.text || null,
|
||||
attachments: Array.isArray(data.attachments) ? data.attachments : [],
|
||||
created_at: data.created_at || new Date().toISOString(),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract supported file attachments from the payload.
|
||||
* Returns only PDF and image attachments.
|
||||
*/
|
||||
export function extractAttachments(payload: ResendInboundPayload): ResendAttachment[] {
|
||||
return payload.attachments.filter(
|
||||
(att) => att.content_type && SUPPORTED_MIME_TYPES.includes(att.content_type) && att.content
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve user_id from the recipient email address.
|
||||
* Looks up the extension_data table where users store their inbox email setting.
|
||||
*
|
||||
* Uses a service role client (passed as parameter) since webhook requests
|
||||
* don't have user authentication.
|
||||
*/
|
||||
export async function resolveUserFromEmail(
|
||||
recipientEmail: string,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
serviceClient: any
|
||||
): Promise<{ userId: string; companyId: string } | null> {
|
||||
// Extract the local part (before @) to handle address variants
|
||||
const normalizedEmail = recipientEmail.toLowerCase().trim()
|
||||
|
||||
// Look up in extension_data where invoice-inbox settings store the inbox email
|
||||
const { data, error } = await serviceClient
|
||||
.from('extension_data')
|
||||
.select('user_id, company_id, value')
|
||||
.eq('extension_id', 'invoice-inbox')
|
||||
.eq('key', 'settings')
|
||||
|
||||
if (error || !data) return null
|
||||
|
||||
// Find the user whose inboxEmail matches the recipient
|
||||
for (const row of data) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const settings = row.value as any
|
||||
if (settings?.inboxEmail && settings.inboxEmail.toLowerCase().trim() === normalizedEmail) {
|
||||
return { userId: row.user_id, companyId: row.company_id }
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user