Files
accounted/lib/init.ts
T
Jakob Wennberg f3ae3cd361 feat: event log, pending operations, and MCP staging (#135)
* feat: event log, pending operations, and MCP staging

- Event log system: persist bus events to event_log table for external
  automation platforms. Batch insert for transaction.synced. Daily
  cleanup cron at 02:00 UTC.
- Pending operations: MCP write tools (categorize, create customer,
  create invoice) now stage to pending_operations instead of executing
  directly. Users review and commit/reject from /pending in the web UI.
- Granskning page: card-based review UI with expandable previews,
  commit/reject dialogs. Only shown in nav when pending ops exist.
- Commit route re-executes using core lib functions (no extension
  imports). Guards against stale state (double-commit, deleted entities).

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

* feat: stage new MCP write tools after main merge

Add staging for 4 new write tools from #133:
- mark_invoice_paid, send_invoice, mark_invoice_sent,
  match_transaction_invoice
- Expand pending_operations CHECK constraint
- Add commit executors with full execution logic
- Add UI labels and generic preview component
- Remove confirm parameter from categorize (single-call staging)
- Fix UUID in pending op title (fetch transaction description)
- Hide Granskning nav when no pending ops

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

* fix: address PR review feedback

- Fix TS build error: use `select('*, customer:customers(*)')` for
  match_transaction_invoice to avoid array type inference
- Add status guard to commitSendInvoice (prevents duplicate sends)
- Replace auth.admin.getUserById with user email from session auth
- Restore optimistic lock check in commitMatchTransactionInvoice
- Fix tool description typo: expense_software → expense_office

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-03-26 10:07:36 +01:00

83 lines
2.3 KiB
TypeScript

import { loadExtensions } from '@/lib/extensions/loader'
import { setContextFactory } from '@/lib/extensions/registry'
import { createExtensionContext } from '@/lib/extensions/context-factory'
import { registerSupplierInvoiceHandler } from '@/lib/bookkeeping/handlers/supplier-invoice-handler'
import { registerEventLogHandler } from '@/lib/events/handlers/event-log-handler'
import { createLogger } from '@/lib/logger'
const log = createLogger('init')
let initialized = false
const REQUIRED_CORE_VARS = [
'NEXT_PUBLIC_SUPABASE_URL',
'NEXT_PUBLIC_SUPABASE_ANON_KEY',
'SUPABASE_SERVICE_ROLE_KEY',
'NEXT_PUBLIC_APP_URL',
'CRON_SECRET',
] as const
const REQUIRED_EXTENSION_VARS = [
'ENABLE_BANKING_APP_ID',
'ENABLE_BANKING_PRIVATE_KEY',
'ANTHROPIC_API_KEY',
'OPENAI_API_KEY',
] as const
const OPTIONAL_VARS = [
'SENTRY_DSN',
'LANGFUSE_SECRET_KEY',
'LANGFUSE_PUBLIC_KEY',
] as const
function validateEnvironment(): void {
// During builds (CI, Docker, Vercel), env vars may be absent or set to
// placeholder sentinels. Skip validation so Next.js page collection
// doesn't fail — real validation happens at runtime.
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
if (!supabaseUrl || supabaseUrl.startsWith('__')) return
const missing: string[] = []
for (const v of REQUIRED_CORE_VARS) {
if (!process.env[v]) missing.push(v)
}
if (missing.length > 0) {
throw new Error(`Missing required environment variables: ${missing.join(', ')}`)
}
const missingExt: string[] = []
for (const v of REQUIRED_EXTENSION_VARS) {
if (!process.env[v]) missingExt.push(v)
}
if (missingExt.length > 0) {
log.warn(`Missing extension environment variables (extensions needing them may not work): ${missingExt.join(', ')}`)
}
for (const v of OPTIONAL_VARS) {
if (!process.env[v]) {
log.warn(`Optional environment variable ${v} is not set`)
}
}
}
/**
* Ensure the system is initialized (extensions loaded, context factory wired,
* core event handlers registered).
* Called from API routes that emit events.
* Idempotent — safe to call multiple times.
*/
export function ensureInitialized(): void {
if (initialized) return
validateEnvironment()
setContextFactory(createExtensionContext)
registerSupplierInvoiceHandler()
registerEventLogHandler()
loadExtensions()
initialized = true
}