Files
accounted/lib/events/handlers/event-log-handler.ts
T
Jakob WennbergandClaude Opus 4.6 e46654ab25 feat: concurrency guards, account validation, and reversal side-effects (#247)
* feat: add concurrency guards, account validation, and reversal side-effects to bookkeeping engine

Prevent double-booking via CAS guards on mark-paid and categorize routes (409 on conflict),
make payment GL entries blocking (AP/AR must match GL), validate account resolution in engine,
and auto-sync invoice status on payment reversal. Adds journal_entry.reversed event type.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address Greptile review — company_id filter, voucher gaps, status restore

- Add missing company_id filter on supplier-invoice CAS update (defense in depth)
- Add voucher_gap_explanations insert on CAS-cancelled entries in both mark-paid
  routes (BFNAR 2013:2 compliance, matching categorize route pattern)
- Fix reversal status restore: check due_date to determine overdue vs sent/approved
  instead of always reverting to sent/approved
- Rename shadowed reversedLines variable to originalLines (P2 clarity)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: derive reversal payment amount from payments table, not GL lines

The reversal GL entry is already a line-by-line mirror per BFL 5 kap 5§.
For the business-level invoice sync, use the payment record amount from
supplier_invoice_payments / invoice_payments instead of inspecting GL
account numbers — works identically for kontantmetod and faktureringsmetod
without needing to know which accounts were used.

Also adds company_id filter on all reversal sync queries (defense in depth).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: allow reversal of partially_paid customer invoices

Widen the status filter from .eq('status', 'paid') to
.in('status', ['paid', 'partially_paid']) so that reversing a partial
payment GL entry correctly updates the invoice state.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 15:23:08 +02:00

157 lines
4.8 KiB
TypeScript

import { eventBus } from '@/lib/events/bus'
import type { CoreEventType } from '@/lib/events/types'
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
import { createLogger } from '@/lib/logger'
const log = createLogger('event-log')
/**
* Event types persisted to the event_log table for external automation platforms.
* Excludes noise events that are always followed by an actionable event.
*/
const PERSISTED_EVENT_TYPES: CoreEventType[] = [
'journal_entry.committed',
'journal_entry.reversed',
'journal_entry.corrected',
'document.uploaded',
'document.accessed',
'invoice.created',
'invoice.sent',
'credit_note.created',
'transaction.synced',
'transaction.categorized',
'transaction.reconciled',
'period.locked',
'period.year_closed',
'customer.created',
'receipt.matched',
'receipt.confirmed',
'supplier_invoice.registered',
'supplier_invoice.approved',
'supplier_invoice.paid',
'supplier_invoice.credited',
'invoice.match_confirmed',
'supplier_invoice.match_confirmed',
'supplier_invoice.confirmed',
]
// Excluded (with reasoning):
// - journal_entry.drafted: always followed by .committed
// - receipt.extracted: intermediate AI step; .matched/.confirmed are actionable
// - supplier_invoice.received: inbox receipt; .confirmed is actionable
// - supplier_invoice.extracted: intermediate AI step
/**
* Extract the primary entity ID from an event payload.
*/
function extractEntityId(payload: Record<string, unknown>): string | null {
// Try common entity shapes in priority order
const entityKeys = [
'entry', 'invoice', 'transaction', 'customer', 'receipt',
'supplierInvoice', 'creditNote', 'period', 'document', 'inboxItem',
] as const
for (const key of entityKeys) {
const entity = payload[key]
if (entity && typeof entity === 'object' && 'id' in entity) {
const id = (entity as Record<string, unknown>).id
if (typeof id === 'string') return id
}
}
// For journal_entry.corrected: use the corrected entry's ID
if ('corrected' in payload) {
const corrected = payload.corrected
if (corrected && typeof corrected === 'object' && 'id' in corrected) {
const id = (corrected as Record<string, unknown>).id
if (typeof id === 'string') return id
}
}
// For journal_entry.reversed: use the reversal entry's ID
if ('reversalEntry' in payload) {
const reversalEntry = payload.reversalEntry
if (reversalEntry && typeof reversalEntry === 'object' && 'id' in reversalEntry) {
const id = (reversalEntry as Record<string, unknown>).id
if (typeof id === 'string') return id
}
}
return null
}
/**
* Strip userId from payload (stored in its own column) and return clean data.
*/
function stripUserId(payload: Record<string, unknown>): Record<string, unknown> {
const { userId: _userId, ...data } = payload
return data
}
/**
* Persist a single event to the event_log table.
*/
async function persistEvent(
eventType: string,
userId: string,
entityId: string | null,
data: Record<string, unknown>
): Promise<void> {
const supabase = createServiceClientNoCookies()
const { error } = await supabase
.from('event_log')
.insert({
user_id: userId,
event_type: eventType,
entity_id: entityId,
data,
})
if (error) {
log.error(`Failed to persist event ${eventType}:`, error.message)
}
}
/**
* Register event log handlers on the event bus.
* Persists events to the event_log table for external automation platforms.
* Returns an array of unsubscribe functions.
*/
export function registerEventLogHandler(): (() => void)[] {
return PERSISTED_EVENT_TYPES.map((eventType) =>
eventBus.on(eventType, async (payload) => {
try {
const rawPayload = payload as Record<string, unknown>
const userId = rawPayload.userId as string
// transaction.synced carries an array — batch insert
if (eventType === 'transaction.synced' && Array.isArray(rawPayload.transactions)) {
const transactions = rawPayload.transactions as Array<Record<string, unknown>>
if (transactions.length === 0) return
const rows = transactions.map(tx => ({
user_id: userId,
event_type: eventType,
entity_id: typeof tx.id === 'string' ? tx.id : null,
data: { transaction: tx },
}))
const supabase = createServiceClientNoCookies()
const { error } = await supabase.from('event_log').insert(rows)
if (error) {
log.error(`Failed to persist batch transaction.synced:`, error.message)
}
return
}
const entityId = extractEntityId(rawPayload)
const data = stripUserId(rawPayload)
await persistEvent(eventType, userId, entityId, data)
} catch (err) {
log.error(`Event log handler error for ${eventType}:`, err)
}
})
)
}