Ai/full autonomous flow (#359)

* 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>
This commit is contained in:
Mattsson
2026-04-27 10:32:15 +02:00
committed by GitHub
co-authored by Claude Opus 4.7
parent ab63da8324
commit 1af977950b
70 changed files with 9735 additions and 451 deletions
+147 -1
View File
@@ -132,6 +132,8 @@ export type ProcessingHistoryAggregateType =
| 'Period'
| 'Migration'
| 'System'
| 'AIProposal'
| 'AIRequest'
export interface ProcessingHistoryEvent {
event_id: string
@@ -254,6 +256,12 @@ export interface CompanySettings {
// Sandbox
is_sandbox: boolean
// AI agent (receipts v1). When ai_flow_enabled is true, the auto-book
// path in lib/transactions/ingest.ts is disabled and every uncategorized
// transaction becomes an AI proposal the user must accept.
ai_flow_enabled: boolean
ai_backfill_cancel_requested: boolean
// Timestamps
created_at: string
updated_at: string
@@ -982,6 +990,8 @@ export interface JournalEntry {
rubric_version: string | null
source_voucher_series: string | null
source_voucher_number: number | null
created_via: CreatedVia
source_proposal_id: string | null
created_at: string
updated_at: string
// Relations
@@ -1073,7 +1083,7 @@ export interface VatJournalLine {
}
// Categorization template source
export type CategorizationTemplateSource = 'sie_import' | 'user_approved' | 'sni_default' | 'auto_learned'
export type CategorizationTemplateSource = 'sie_import' | 'user_approved' | 'sni_default' | 'auto_learned' | 'ai_corrected'
// Multi-line booking pattern entry
export interface LinePatternEntry {
@@ -1225,6 +1235,10 @@ export interface CreateJournalEntryInput {
voucher_series?: string
notes?: string
lines: CreateJournalEntryLineInput[]
// AI agent provenance — set on the draft INSERT, then frozen at commit.
// Manual/imported/system callers omit these; the engine defaults created_via to 'manual'.
created_via?: CreatedVia
source_proposal_id?: string
}
export interface CreateJournalEntryLineInput {
@@ -2572,3 +2586,135 @@ export interface AGIDeclaration {
created_at: string
updated_at: string
}
// ============================================================================
// AI agent flow (receipts v1)
// ============================================================================
// How was a journal entry created? `source_type` describes the business event;
// `created_via` describes the method.
export type CreatedVia = 'manual' | 'ai_proposed' | 'imported' | 'system'
// The only subject type in v1 is inbox_item; invoices and bare transactions come later.
export type AISubjectType = 'inbox_item'
// Proposal step in the agent pipeline. A receipt goes match -> booking.
export type AIProposalStepType = 'match' | 'booking'
// Proposal lifecycle. Next step chains on accepted/skipped; rejected terminates the chain.
export type AIProposalStatus =
| 'pending'
| 'accepted'
| 'rejected'
| 'skipped' // user went manual on this step
| 'invalidated' // re-validation failed or superseded
// Structured requests the AI makes when it can't produce a proposal.
export type AIRequestType =
| 'reupload_document'
| 'pick_transaction'
| 'specify_vat'
| 'clarify_business_private'
| 'needs_manual'
export type AIRequestStatus = 'open' | 'resolved' | 'dismissed'
// Proposal payload shapes (what lives in ai_proposals.proposal_json).
export interface MatchProposalAlternative {
transaction_id: string
confidence: number
reasoning: string
}
export interface MatchProposalPayload {
matched_transaction_id: string
alternatives: MatchProposalAlternative[]
top_confidence: number
}
export interface BookingProposalLine {
account_number: string
debit_amount: number
credit_amount: number
description: string
}
export interface BookingProposalCounterpartyTemplate {
counterparty_name: string
debit_account: string
credit_account: string
vat_treatment: VatTreatment | null
category: TransactionCategory | null
}
export interface BookingProposalPayload {
lines: BookingProposalLine[]
vat_treatment: VatTreatment | null
default_private: boolean
counterparty_template_proposal: BookingProposalCounterpartyTemplate | null
fiscal_period_id: string
entry_date: string
description: string
}
export type AIProposalPayload = MatchProposalPayload | BookingProposalPayload
// AI proposal row (ai_proposals table)
export interface AIProposal {
id: string
company_id: string
user_id: string
subject_type: AISubjectType
subject_id: string
step_type: AIProposalStepType
status: AIProposalStatus
version: number
proposal_json: AIProposalPayload
confidence: number | null
reasoning: string | null
ai_request_id: string | null
model: string
prompt_version: string
input_token_count: number
output_token_count: number
edit_diff: Record<string, unknown> | null
applied_entry_id: string | null
invalidated_reason: string | null
created_at: string
accepted_at: string | null
accepted_by_user_id: string | null
rejected_at: string | null
updated_at: string
}
// AI request row (ai_requests table)
export interface AIRequest {
id: string
company_id: string
subject_type: AISubjectType
subject_id: string
request_type: AIRequestType
message: string
required_fields: Record<string, unknown> | null
options: Record<string, unknown> | null
status: AIRequestStatus
response_json: Record<string, unknown> | null
resolved_at: string | null
resolved_by_user_id: string | null
model: string | null
prompt_version: string | null
created_at: string
updated_at: string
}
// Candidate transaction summary used in pick_transaction requests' options array.
export interface PickTransactionOption {
transaction_id: string
date: string
description: string
amount: number
currency: string
merchant_name: string | null
}