1af977950b
* 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>
85 lines
2.5 KiB
TypeScript
85 lines
2.5 KiB
TypeScript
import { loadExtensions } from '@/lib/extensions/loader'
|
|
import { setContextFactory } from '@/lib/extensions/registry'
|
|
import { createExtensionContext } from '@/lib/extensions/context-factory'
|
|
import { registerSupplierInvoiceHandler } from '@/lib/bookkeeping/handlers/supplier-invoice-handler'
|
|
import { registerEventLogHandler } from '@/lib/events/handlers/event-log-handler'
|
|
import { registerAIProposalHandler } from '@/lib/ai/orchestrator'
|
|
import { isAgentInboxEnabled } from '@/lib/ai/feature-flag'
|
|
import { createLogger } from '@/lib/logger'
|
|
|
|
const log = createLogger('init')
|
|
|
|
let initialized = false
|
|
|
|
const REQUIRED_CORE_VARS = [
|
|
'NEXT_PUBLIC_SUPABASE_URL',
|
|
'NEXT_PUBLIC_SUPABASE_ANON_KEY',
|
|
'SUPABASE_SERVICE_ROLE_KEY',
|
|
'NEXT_PUBLIC_APP_URL',
|
|
'CRON_SECRET',
|
|
] as const
|
|
|
|
const REQUIRED_EXTENSION_VARS = [
|
|
'ENABLE_BANKING_APP_ID',
|
|
'ENABLE_BANKING_PRIVATE_KEY',
|
|
'ANTHROPIC_API_KEY',
|
|
'OPENAI_API_KEY',
|
|
] as const
|
|
|
|
const OPTIONAL_VARS = [
|
|
'LANGFUSE_SECRET_KEY',
|
|
'LANGFUSE_PUBLIC_KEY',
|
|
] as const
|
|
|
|
function validateEnvironment(): void {
|
|
// During builds (CI, Docker, Vercel), env vars may be absent or set to
|
|
// placeholder sentinels. Skip validation so Next.js page collection
|
|
// doesn't fail — real validation happens at runtime.
|
|
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
|
|
if (!supabaseUrl || supabaseUrl.startsWith('__')) return
|
|
|
|
const missing: string[] = []
|
|
|
|
for (const v of REQUIRED_CORE_VARS) {
|
|
if (!process.env[v]) missing.push(v)
|
|
}
|
|
|
|
if (missing.length > 0) {
|
|
throw new Error(`Missing required environment variables: ${missing.join(', ')}`)
|
|
}
|
|
|
|
const missingExt: string[] = []
|
|
for (const v of REQUIRED_EXTENSION_VARS) {
|
|
if (!process.env[v]) missingExt.push(v)
|
|
}
|
|
|
|
if (missingExt.length > 0) {
|
|
log.warn(`Missing extension environment variables (extensions needing them may not work): ${missingExt.join(', ')}`)
|
|
}
|
|
|
|
for (const v of OPTIONAL_VARS) {
|
|
if (!process.env[v]) {
|
|
log.warn(`Optional environment variable ${v} is not set`)
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Ensure the system is initialized (extensions loaded, context factory wired,
|
|
* core event handlers registered).
|
|
* Called from API routes that emit events.
|
|
* Idempotent — safe to call multiple times.
|
|
*/
|
|
export function ensureInitialized(): void {
|
|
if (initialized) return
|
|
|
|
validateEnvironment()
|
|
setContextFactory(createExtensionContext)
|
|
registerSupplierInvoiceHandler()
|
|
registerEventLogHandler()
|
|
if (isAgentInboxEnabled()) registerAIProposalHandler()
|
|
loadExtensions()
|
|
|
|
initialized = true
|
|
}
|