* Refactor bookkeeping error handling and introduce new error classes - Introduced new error classes for better error categorization: - JournalEntryNotBalancedError - FiscalPeriodNotFoundError - EntryDateOutsideFiscalPeriodError - JournalEntryNotFoundError - CannotReverseNonPostedError - CannotCorrectNonPostedError - EntryAlreadyReversedError - CurrencyRevaluationAlreadyExistsError - InvalidMappingResultError - BookkeepingDatabaseError - Updated existing functions in engine.ts and transaction-entries.ts to throw specific errors instead of generic ones. - Enhanced error response handling in get-error-message.ts to provide localized messages for new error types. - Added unit tests for new error classes and error handling functions to ensure correctness and coverage. * feat(ai): implement AI proposal application and persistence - Add apply.ts to handle the application of AI proposals, including match and booking steps. - Introduce persist.ts for inserting and managing AI requests and proposals, ensuring unique constraints. - Create re-validate.ts for validating proposals before acceptance, checking for stale conditions. - Define database migrations for ai_requests and ai_proposals tables, including constraints and indexes. - Enhance journal_entries with AI provenance tracking, linking entries to AI proposals. - Update categorization_templates to distinguish AI-corrected templates. - Add company settings for toggling AI flow and managing backfill processes. - Extend processing_history to include AI-related events for better tracking. * feat: add uncategorized transactions API and UI for transaction selection - Implemented a new API endpoint for fetching uncategorized transactions with pagination and filtering options. - Created ChangeTransactionDialog component for selecting alternative transactions based on AI proposals. - Developed ReceiptDetailDialog to display detailed information about receipts, including upload functionality. - Added TransactionDetailDialog for viewing transaction details with links to the transaction list. - Introduced receipt quality assessment logic to evaluate extracted receipt data. - Implemented feature flagging for the AI bookkeeping agent to control availability in different environments. * feat: add manual receipt extraction dialog and integrate AWS Textract for expense analysis - Added ManualExtractDialog component for user input when AI fails to extract receipt data. - Implemented ReceiptsList component to manage and display uploaded receipts, including upload and rescan functionalities. - Introduced Textract integration for analyzing expenses, extracting fields like total, vendor, and date. - Updated package.json to include @aws-sdk/client-textract dependency. * fix(ai): handle livsmedel VAT transition (12% → 6%) in booking prompt and re-validate guard Add date-aware guidance to BOOKING_SYSTEM_PROMPT for the temporary livsmedel VAT cut (Prop. 2025/26:55, 2026-04-01 to 2027-12-31), with restaurang/servering carve-out at 12%. Add a re-validate safety net that rejects clearly-stale rate labels for grocery-chain merchants relative to the entry date. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
128 lines
4.0 KiB
TypeScript
128 lines
4.0 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { createClient } from '@/lib/supabase/server'
|
|
import { ensureInitialized } from '@/lib/init'
|
|
import { validateBody } from '@/lib/api/validate'
|
|
import { RememberLearningSchema } from '@/lib/api/schemas'
|
|
import { requireCompanyId } from '@/lib/company/context'
|
|
import { requireWritePermission } from '@/lib/auth/require-write'
|
|
import { calculateConfidence } from '@/lib/bookkeeping/counterparty-templates'
|
|
import { gateAgentInbox } from '@/lib/ai/feature-flag'
|
|
import type { AIProposal } from '@/types'
|
|
|
|
ensureInitialized()
|
|
|
|
/**
|
|
* POST /api/ai/learning/remember
|
|
*
|
|
* Called from the UI's learning-prompt dialog after a user edited and
|
|
* accepted an AI booking proposal. Upserts a categorization_templates row
|
|
* with source='ai_corrected' so next time's proposal for the same
|
|
* counterparty starts from the user's preference.
|
|
*
|
|
* This is the ONLY path that creates an ai_corrected template — the
|
|
* "silent learning" rule means every template with this source represents
|
|
* an explicit user choice.
|
|
*/
|
|
export async function POST(request: Request) {
|
|
const gate = gateAgentInbox()
|
|
if (gate) return gate
|
|
|
|
const supabase = await createClient()
|
|
const { data: { user } } = await supabase.auth.getUser()
|
|
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
|
|
const writeCheck = await requireWritePermission(supabase, user.id)
|
|
if (!writeCheck.ok) return writeCheck.response
|
|
|
|
const companyId = await requireCompanyId(supabase, user.id)
|
|
|
|
const validation = await validateBody(request, RememberLearningSchema)
|
|
if (!validation.success) return validation.response
|
|
const {
|
|
proposal_id,
|
|
counterparty_name,
|
|
debit_account,
|
|
credit_account,
|
|
vat_treatment,
|
|
category,
|
|
} = validation.data
|
|
|
|
// Verify the proposal is accepted + belongs to this company.
|
|
const { data: proposal } = await supabase
|
|
.from('ai_proposals')
|
|
.select('*')
|
|
.eq('id', proposal_id)
|
|
.eq('company_id', companyId)
|
|
.maybeSingle()
|
|
|
|
if (!proposal) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
|
const typed = proposal as AIProposal
|
|
if (typed.status !== 'accepted') {
|
|
return NextResponse.json(
|
|
{ error: 'Endast accepterade förslag kan lagras som mall.' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
if (typed.step_type !== 'booking') {
|
|
return NextResponse.json(
|
|
{ error: 'Endast bokföringssteget kan lagras som mall.' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// Upsert the template. Existing row for the same (user_id, counterparty_name)
|
|
// gets its source bumped up and occurrence incremented.
|
|
const { data: existing } = await supabase
|
|
.from('categorization_templates')
|
|
.select('*')
|
|
.eq('user_id', user.id)
|
|
.eq('counterparty_name', counterparty_name)
|
|
.maybeSingle()
|
|
|
|
const today = new Date().toISOString().slice(0, 10)
|
|
|
|
if (existing) {
|
|
const newOccurrence = existing.occurrence_count + 1
|
|
await supabase
|
|
.from('categorization_templates')
|
|
.update({
|
|
debit_account,
|
|
credit_account,
|
|
vat_treatment,
|
|
category,
|
|
source: 'ai_corrected',
|
|
occurrence_count: newOccurrence,
|
|
confidence: calculateConfidence(newOccurrence),
|
|
last_seen_date: today,
|
|
is_active: true,
|
|
})
|
|
.eq('id', existing.id)
|
|
|
|
return NextResponse.json({ data: { template_id: existing.id, updated: true } })
|
|
}
|
|
|
|
const { data: created, error: insertError } = await supabase
|
|
.from('categorization_templates')
|
|
.insert({
|
|
user_id: user.id,
|
|
company_id: companyId,
|
|
counterparty_name,
|
|
counterparty_aliases: [counterparty_name],
|
|
debit_account,
|
|
credit_account,
|
|
vat_treatment,
|
|
category,
|
|
source: 'ai_corrected',
|
|
occurrence_count: 1,
|
|
confidence: calculateConfidence(1),
|
|
last_seen_date: today,
|
|
is_active: true,
|
|
})
|
|
.select()
|
|
.single()
|
|
|
|
if (insertError) return NextResponse.json({ error: insertError.message }, { status: 500 })
|
|
|
|
return NextResponse.json({ data: { template_id: created.id, updated: false } })
|
|
}
|