Files
accounted/components/agent-inbox/receipt-quality.ts
T
MattssonandClaude Opus 4.7 1af977950b 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>
2026-04-27 10:32:15 +02:00

56 lines
1.8 KiB
TypeScript

import type { AgentInboxItemView } from '@/app/(dashboard)/agent-inbox/page'
export type ReceiptQualityIssue =
| 'missing_merchant'
| 'missing_total'
| 'missing_date'
| 'low_confidence'
export interface ReceiptQualityAssessment {
ok: boolean
issues: ReceiptQualityIssue[]
message: string | null
}
const ISSUE_LABELS: Record<ReceiptQualityIssue, string> = {
missing_merchant: 'handlare saknas',
missing_total: 'belopp saknas',
missing_date: 'datum saknas',
low_confidence: 'låg extraktionssäkerhet',
}
// Heuristic quality check on a classified receipt. Until the classification
// prompt returns an explicit quality_score, we infer it from which critical
// fields came back and the LLM's self-reported confidence (stored on
// invoice_inbox_items.confidence after classification). 0.6 is the cutoff
// where accepted vs. edited rates diverge noticeably in practice.
export function assessReceiptQuality(
inbox: AgentInboxItemView['inbox_item']
): ReceiptQualityAssessment {
const data = inbox.extracted_data as {
merchant?: { name?: string | null } | null
receipt?: { date?: string | null } | null
totals?: { total?: number | null } | null
} | null
const issues: ReceiptQualityIssue[] = []
if (!data?.merchant?.name) issues.push('missing_merchant')
if (data?.totals?.total == null) issues.push('missing_total')
if (!data?.receipt?.date) issues.push('missing_date')
const confidence = inbox.confidence == null ? null : Number(inbox.confidence)
if (confidence != null && confidence < 0.6) issues.push('low_confidence')
if (issues.length === 0) {
return { ok: true, issues, message: null }
}
const labels = issues.map((i) => ISSUE_LABELS[i])
return {
ok: false,
issues,
message: `Kvittot verkar otydligt — ${labels.join(', ')}.`,
}
}