* feat: add INK2 declaration improvements, invoice delivery date, and Swedish compliance skills Expand INK2 engine with full INK2S/INK2R support and improved SRU generation. Add delivery_date field to invoices and corresponding PDF/migration support. Add Claude skills for Swedish asset accounting, invoice compliance, SIE import/export, SRU filing, and tax planning. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address PR review — map BAS 4500–4899, strip CRLF in SRU, document P3 - Map BAS accounts 4500–4599 (legoarbeten), 4700–4899 (diverse varuinköpskostnader) to SRU 7512 so they are not silently dropped from INK2R declarations - Strip \r\n in sanitizeString to prevent CRLF injection in SRU fields - Document P3 period suffix limitation for brutet räkenskapsår Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct BAS 4500-4599, 4700-4899 mapping from 7512 to 7511 Per the official BAS-to-SRU mapping, these account ranges are cost of goods (legoarbeten, inkurans, svinn) and belong under 7511 (Råvaror och förnödenheter), not 7512 (Handelsvaror). 7512 remains 4600-4699. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: Swedish VAT compliance — representation VAT, domestic RC, full BAS 26xx mapping, SIE encoding - Representation expenses now default to reduced_12 VAT (ML 13 kap 24-25 §§); income tax deduction was abolished 2017 but VAT deduction at 12% remains - Domestic reverse charge (byggtjänster etc.) uses 2647 instead of 2645, with distinct line descriptions for Swedish vs EU/non-EU RC - VAT declaration maps all BAS 26xx variant accounts (egna uttag 2612/2622/2632, uthyrning 2613/2623/2633, VMB 2616/2626/2636, import 2615/2625/2635, domestic RC 2647, frivillig skattskyldighet 2642) and revenue variants (3108/3105/3004/3100) to correct momsdeklaration rutor - SIE parser: remove unreliable #FORMAT PC8 encoding detection (most software exports UTF-8 with PC8 header), parse #FLAGGA for import-already-done warning, default SIE type to 1 when absent, fix RTRANS/BTRANS documentation - SIE export: add #RAR -1 (previous fiscal year), fix UB = IB + movements - Error messages: add pattern matching for locked period trigger errors Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address Greptile review — update ruta49 JSDoc, use null sentinel in error map Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: harden storno CAS guard, document integrity, and BFNAR archive compliance - Storno: defer original→reversed until both entries succeed, add CAS guard for concurrent reversals, use cancelEntry() instead of delete - Document: add document.accessed event, enrich archive manifest with metadata, add BFNAR 2013:2 systemdokumentation to full archive export - Verify cron: run daily, configurable batch size, include company_id in audit - Migrations: integrity audit actions, document version chain, metadata immutability, audit deletions, fix immutability for posted/cancelled Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address Greptile review — allow is_current_version in immutability trigger, log cancelEntry errors - Remove is_current_version from blocked fields in enforce_document_metadata_immutability trigger so create_document_version RPC can supersede documents linked to posted entries - Add error logging to cancelEntry for observability on cleanup failures Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
147 lines
4.5 KiB
TypeScript
147 lines
4.5 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.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
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|
|
})
|
|
)
|
|
}
|