* 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>
143 lines
4.4 KiB
TypeScript
143 lines
4.4 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { createClient } from '@/lib/supabase/server'
|
|
import { eventBus } from '@/lib/events/bus'
|
|
import { ensureInitialized } from '@/lib/init'
|
|
import { validateBody } from '@/lib/api/validate'
|
|
import { BatchAcceptSchema } from '@/lib/api/schemas'
|
|
import { requireCompanyId } from '@/lib/company/context'
|
|
import { requireWritePermission } from '@/lib/auth/require-write'
|
|
import { reValidateProposal } from '@/lib/ai/proposals/re-validate'
|
|
import { applyProposal } from '@/lib/ai/proposals/apply'
|
|
import { gateAgentInbox } from '@/lib/ai/feature-flag'
|
|
import type { AIProposal, InvoiceInboxItem } from '@/types'
|
|
|
|
ensureInitialized()
|
|
|
|
interface BatchOutcomePerProposal {
|
|
proposal_id: string
|
|
ok: boolean
|
|
error?: string
|
|
code?: string
|
|
applied_entry_id?: string | null
|
|
}
|
|
|
|
/**
|
|
* POST /api/ai/proposals/batch-accept
|
|
*
|
|
* Accept multiple pending proposals in one click. Best-effort: each item is
|
|
* independently re-validated and applied. The response contains per-item
|
|
* outcomes so the UI can show checkmarks + specific failure messages
|
|
* (e.g., "fiscal period closed since you loaded the page").
|
|
*
|
|
* No edits are supported in batch mode — edits require the user to open the
|
|
* individual proposal and approve from there.
|
|
*/
|
|
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, BatchAcceptSchema)
|
|
if (!validation.success) return validation.response
|
|
const { proposal_ids } = validation.data
|
|
|
|
const outcomes: BatchOutcomePerProposal[] = []
|
|
|
|
for (const proposalId of proposal_ids) {
|
|
const outcome = await acceptOne(supabase, companyId, user.id, proposalId)
|
|
outcomes.push(outcome)
|
|
}
|
|
|
|
return NextResponse.json({
|
|
data: {
|
|
outcomes,
|
|
accepted: outcomes.filter((o) => o.ok).length,
|
|
failed: outcomes.filter((o) => !o.ok).length,
|
|
},
|
|
})
|
|
}
|
|
|
|
async function acceptOne(
|
|
supabase: Awaited<ReturnType<typeof createClient>>,
|
|
companyId: string,
|
|
userId: string,
|
|
proposalId: string
|
|
): Promise<BatchOutcomePerProposal> {
|
|
const { data: proposal } = await supabase
|
|
.from('ai_proposals')
|
|
.select('*')
|
|
.eq('id', proposalId)
|
|
.eq('company_id', companyId)
|
|
.maybeSingle()
|
|
|
|
if (!proposal) return { proposal_id: proposalId, ok: false, error: 'Not found', code: 'not_found' }
|
|
|
|
const typed = proposal as AIProposal
|
|
if (typed.status !== 'pending') {
|
|
return { proposal_id: proposalId, ok: false, error: `Already ${typed.status}`, code: 'not_pending' }
|
|
}
|
|
|
|
const check = await reValidateProposal(supabase, companyId, typed)
|
|
if (!check.ok) {
|
|
await supabase
|
|
.from('ai_proposals')
|
|
.update({ status: 'invalidated', invalidated_reason: check.code })
|
|
.eq('id', typed.id)
|
|
.eq('version', typed.version)
|
|
return { proposal_id: proposalId, ok: false, error: check.message, code: check.code }
|
|
}
|
|
|
|
const inboxItem = check.inboxItem as InvoiceInboxItem
|
|
|
|
let outcome
|
|
try {
|
|
outcome = await applyProposal(supabase, companyId, userId, typed, inboxItem)
|
|
} catch (err) {
|
|
return {
|
|
proposal_id: proposalId,
|
|
ok: false,
|
|
error: err instanceof Error ? err.message : 'apply_failed',
|
|
code: 'apply_failed',
|
|
}
|
|
}
|
|
|
|
const appliedEntryId =
|
|
outcome.kind === 'booking_applied' ? outcome.journalEntry.id : null
|
|
|
|
const { data: updated } = await supabase
|
|
.from('ai_proposals')
|
|
.update({
|
|
status: 'accepted',
|
|
accepted_at: new Date().toISOString(),
|
|
accepted_by_user_id: userId,
|
|
version: typed.version + 1,
|
|
applied_entry_id: appliedEntryId,
|
|
})
|
|
.eq('id', typed.id)
|
|
.eq('version', typed.version)
|
|
.select()
|
|
.maybeSingle()
|
|
|
|
try {
|
|
await eventBus.emit({
|
|
type: 'ai_proposal.accepted',
|
|
payload: {
|
|
proposal: (updated as AIProposal | null) ?? typed,
|
|
appliedEntry: outcome.kind === 'booking_applied' ? outcome.journalEntry : null,
|
|
userId,
|
|
companyId,
|
|
},
|
|
})
|
|
} catch { /* non-blocking */ }
|
|
|
|
return { proposal_id: proposalId, ok: true, applied_entry_id: appliedEntryId }
|
|
}
|