Files
accounted/lib/ai/proposal-service.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

124 lines
3.2 KiB
TypeScript

/**
* AI Proposal Service Interface
*
* Core defines the contract. The `ai-agent` extension registers a real
* implementation backed by Bedrock. Without the extension, the noop service
* is used — every call returns `null` and the orchestrator degrades by
* issuing a `needs_manual` ai_request so the user sees the item and knows
* they need to process it manually.
*
* Mirrors the pattern in lib/email/service.ts.
*/
import type {
InvoiceInboxItem,
Transaction,
MatchProposalPayload,
BookingProposalPayload,
AIRequestType,
CategorizationTemplate,
PickTransactionOption,
} from '@/types'
// Shared fields any LLM call returns for audit.
export interface ProposalProvenance {
model: string
prompt_version: string
input_tokens: number
output_tokens: number
}
// When the AI produces a concrete suggestion.
export interface MatchProposalResult {
kind: 'proposal'
proposal: MatchProposalPayload
confidence: number
reasoning: string
provenance: ProposalProvenance
}
export interface BookingProposalResult {
kind: 'proposal'
proposal: BookingProposalPayload
confidence: number
reasoning: string
provenance: ProposalProvenance
}
// When the AI would rather ask the user than guess.
export interface AIRequestResult {
kind: 'request'
request: {
request_type: AIRequestType
message: string
required_fields?: Record<string, unknown>
options?: Record<string, unknown> | { candidates: PickTransactionOption[] }
}
provenance: Partial<ProposalProvenance>
}
// Context passed to each generator. Keeping the contract tight so extensions
// can't accidentally see more than they need.
export interface GenerateMatchContext {
inboxItem: InvoiceInboxItem
userId: string
companyId: string
}
export interface GenerateBookingContext {
inboxItem: InvoiceInboxItem
matchedTransaction: Transaction
existingTemplates: CategorizationTemplate[]
entityType: 'enskild_firma' | 'aktiebolag'
userId: string
companyId: string
}
export interface AIProposalService {
/** True when a real (non-noop) implementation is registered and ready. */
isEnabled(): boolean
/**
* Propose which bank transaction matches an incoming receipt.
* Returns null on service outage (orchestrator will issue needs_manual).
*/
generateMatchProposal(
ctx: GenerateMatchContext
): Promise<MatchProposalResult | AIRequestResult | null>
/**
* Propose how to book the matched transaction (accounts, VAT, lines).
* Returns null on service outage (orchestrator will issue needs_manual).
*/
generateBookingProposal(
ctx: GenerateBookingContext
): Promise<BookingProposalResult | AIRequestResult | null>
}
class NoopAIProposalService implements AIProposalService {
isEnabled(): boolean {
return false
}
async generateMatchProposal(): Promise<null> {
return null
}
async generateBookingProposal(): Promise<null> {
return null
}
}
let service: AIProposalService = new NoopAIProposalService()
export function getAIProposalService(): AIProposalService {
return service
}
export function registerAIProposalService(svc: AIProposalService): void {
service = svc
}
/** Reset to noop — for tests only. */
export function _resetAIProposalService(): void {
service = new NoopAIProposalService()
}