@happyvertical/smrt-ledgers 0.51.23 → 0.51.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/__smrt-register__.ts","../src/prompts.ts","../src/models/Account.ts","../src/collections/Accounts.ts","../src/models/JournalEntry.ts","../src/collections/JournalEntries.ts","../src/models/Journal.ts","../src/collections/Journals.ts"],"sourcesContent":["/**\n * Self-registers this package's build-time manifest before any @smrt() decorator\n * in the package fires. Fixes issue #1132: in consumer runtimes (tsx, SvelteKit\n * SSR, plain `vite dev`) the decorator's synchronous manifest lookup previously\n * missed because no step populated the global manifest cache — classes got\n * registered with zero fields and `save()` / `toJSON()` silently dropped every\n * declared property.\n *\n * Import this module as the first statement in `src/index.ts` so its top-level\n * side effect runs ahead of any class module's @smrt() decorator.\n *\n * Silent no-op in dev/test, where the vitest plugin already populates manifests\n * via a different path. Only needs to succeed in the published dist output.\n *\n * @see https://github.com/happyvertical/smrt/issues/1132\n */\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\n// During library builds, smrtPlugin replaces this entire module with generated\n// code that embeds the scanned manifest inline (#1506/#1507) — published dists\n// never resolve this URL, so downstream bundlers cannot break registration by\n// relocating the compiled module away from dist/manifest.json. The runtime\n// lookup below is the fallback for source-mode runs without that transform.\nObjectRegistry.registerPackageManifest(\n new URL('./manifest.json', import.meta.url),\n);\n","/**\n * Prompt registrations for the @happyvertical/smrt-ledgers package.\n *\n * Prompts are registered at module-load time via `definePrompt()` so that\n * tenant-aware overrides can be applied at call time via `resolvePrompt()`.\n *\n * Mirrors the pattern used by `@happyvertical/smrt-properties` (see\n * `prompts.ts`) and `@happyvertical/smrt-content` (see `content-prompts.ts`).\n */\n\nimport {\n definePrompt,\n type ResolvedPromptAI,\n} from '@happyvertical/smrt-prompts';\n\n// Journal summarization only uses non-PII journal fields\n// (number, date, description, status, balanced flag) plus aggregate totals\n// and entry count. Internal/foreign-key fields like tenantId, sourceRef,\n// individual entry account IDs, and the extensible `metadata` blob are\n// intentionally NOT passed to the AI provider — they may link to identifying\n// records (customer/vendor IDs via sourceRef) or contain tenant-private\n// configuration. If a downstream tenant needs richer context they can\n// override the template via PromptOverride.\n// Note: smrt-prompts substitutes `{token}` placeholders. The currency prefix\n// is folded into the `journalTotal` variable value (e.g. \"$100.00\") rather\n// than written as a literal `$` in the template — earlier revisions used\n// `\\${journalTotal}` (a template-literal escape that renders as the literal\n// `${journalTotal}` at runtime). That technically worked because the regex\n// still matched the inner `{journalTotal}` and produced `$100.00`, but it\n// confused reviewers; folding the prefix into the value avoids the trap.\nexport const smrtLedgersJournalSummarizePrompt = definePrompt({\n key: 'smrtLedgers.journal.summarize',\n template: `Summarize this accounting journal entry:\nNumber: {journalNumber}\nDate: {journalDate}\nDescription: {journalDescription}\nStatus: {journalStatus}\nTotal: {journalTotal}\nEntries: {entryCount}\nBalanced: {journalBalanced}`,\n editable: {\n template: true,\n profile: true,\n model: true,\n params: true,\n },\n});\n\nexport function promptMessageOptions(ai: ResolvedPromptAI) {\n return {\n ...(ai.params || {}),\n ...(ai.model ? { model: ai.model } : {}),\n ...(typeof ai.temperature === 'number'\n ? { temperature: ai.temperature }\n : {}),\n ...(typeof ai.maxTokens === 'number' ? { maxTokens: ai.maxTokens } : {}),\n };\n}\n","/**\n * Account model - Chart of accounts entry\n *\n * Represents a single account in the chart of accounts.\n * The 5 core types: Asset, Liability, Equity, Revenue, Expense\n */\n\nimport { SmrtHierarchical, smrt } from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport type { AccountOptions, AccountTreeNode, AccountType } from '../types';\n\n@TenantScoped({ mode: 'optional' })\n@smrt({\n api: { include: ['list', 'get', 'create', 'update', 'delete'] },\n mcp: { include: ['list', 'get', 'create'] },\n cli: { skipApiCheck: true },\n})\nexport class Account extends SmrtHierarchical {\n /**\n * Tenant ID for multi-tenancy support (nullable for global accounts)\n */\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n /**\n * Account number (e.g., \"1000\", \"5030\")\n */\n number: string = '';\n\n /**\n * Account name (e.g., \"Cash\", \"Coffee Expense\")\n */\n name: string = '';\n\n /**\n * Account description\n */\n description: string = '';\n\n /**\n * Account type - one of the 5 core types\n */\n type: AccountType = 'asset';\n\n // parentId inherited from SmrtHierarchical (null = top-level)\n\n /**\n * Whether the account is active\n */\n active: boolean = true;\n\n /**\n * Extensible metadata\n */\n metadata: Record<string, unknown> = {};\n\n constructor(options: AccountOptions = {}) {\n super(options);\n if (options.number !== undefined) this.number = options.number;\n if (options.name !== undefined) this.name = options.name;\n if (options.description !== undefined)\n this.description = options.description;\n if (options.type !== undefined) this.type = options.type;\n if (options.parentId !== undefined) this.parentId = options.parentId;\n if (options.active !== undefined) this.active = options.active;\n if (options.metadata !== undefined) this.metadata = options.metadata;\n }\n\n /**\n * Check if this is a top-level account (no parent)\n */\n isTopLevel(): boolean {\n return this.parentId === null;\n }\n\n /**\n * Check if this is a debit-normal account (Asset, Expense)\n * Debit-normal accounts increase with debits\n */\n isDebitNormal(): boolean {\n return this.type === 'asset' || this.type === 'expense';\n }\n\n /**\n * Check if this is a credit-normal account (Liability, Equity, Revenue)\n * Credit-normal accounts increase with credits\n */\n isCreditNormal(): boolean {\n return (\n this.type === 'liability' ||\n this.type === 'equity' ||\n this.type === 'revenue'\n );\n }\n\n // Hierarchy traversal (getParent / getChildren / getAncestors /\n // getDescendants / getHierarchy / moveTo) provided by SmrtHierarchical.\n // Account-specific helpers (getFullPath / getBalance / createChild /\n // toTreeNode) remain below.\n\n /**\n * Get full account path (e.g., \"Assets > Current > Cash\")\n */\n async getFullPath(): Promise<string> {\n const ancestors = await this.getAncestors();\n const names = [...ancestors.map((a) => a.name), this.name];\n return names.join(' > ');\n }\n\n /**\n * Build tree node for this account and its children\n */\n async toTreeNode(): Promise<AccountTreeNode> {\n const children = await this.getChildren();\n const childNodes = await Promise.all(children.map((c) => c.toTreeNode()));\n return {\n account: this,\n children: childNodes,\n };\n }\n\n /**\n * Get the current balance of this account\n */\n async getBalance(asOfDate?: Date): Promise<number> {\n if (!this.id) return 0;\n const { JournalEntryCollection } = await import(\n '../collections/JournalEntries'\n );\n const collection = await JournalEntryCollection.create(this.options);\n return await collection.getAccountBalance(this.id, asOfDate);\n }\n\n /**\n * Create a sub-account under this account\n */\n async createChild(\n options: Omit<AccountOptions, 'parentId' | 'type'>,\n ): Promise<Account> {\n if (!this.id) {\n throw new Error('Account must be saved before creating children');\n }\n const { AccountCollection } = await import('../collections/Accounts');\n const collection = await AccountCollection.create(this.options);\n const account = await collection.create({\n ...options,\n parentId: this.id,\n type: this.type, // Inherit type from parent\n });\n await account.save();\n return account;\n }\n}\n","/**\n * AccountCollection - Collection manager for Account objects\n *\n * Provides querying and tree operations for chart of accounts.\n */\n\nimport { SmrtCollection } from '@happyvertical/smrt-core';\nimport { queryGlobal, queryWithGlobals } from '@happyvertical/smrt-tenancy';\nimport { Account } from '../models/Account';\nimport type { AccountTree, AccountTreeNode, AccountType } from '../types';\n\nexport class AccountCollection extends SmrtCollection<Account> {\n static readonly _itemClass = Account;\n\n /**\n * Find account by number\n *\n * @param number - Account number\n * @returns Account or null\n */\n async findByNumber(number: string): Promise<Account | null> {\n const accounts = await this.list({\n where: { number },\n limit: 1,\n });\n return accounts[0] || null;\n }\n\n /**\n * Find accounts by type\n *\n * @param type - Account type\n * @returns Array of accounts\n */\n async findByType(type: AccountType): Promise<Account[]> {\n return await this.list({\n where: { type },\n orderBy: 'number ASC',\n });\n }\n\n /**\n * Find all active accounts\n *\n * @returns Array of active accounts\n */\n async findActive(): Promise<Account[]> {\n return await this.list({\n where: { active: true },\n orderBy: 'number ASC',\n });\n }\n\n /**\n * Find top-level accounts (no parent)\n *\n * @returns Array of top-level accounts\n */\n async findTopLevel(): Promise<Account[]> {\n return await this.list({\n where: { parentId: null },\n orderBy: 'number ASC',\n });\n }\n\n /**\n * Find direct children of an account\n *\n * @param parentId - Parent account ID\n * @returns Array of child accounts\n */\n async findChildren(parentId: string): Promise<Account[]> {\n return await this.list({\n where: { parentId },\n orderBy: 'number ASC',\n });\n }\n\n /**\n * Get the complete account tree\n *\n * @returns AccountTree structure\n */\n async getTree(): Promise<AccountTree> {\n const allAccounts = await this.list({\n orderBy: 'number ASC',\n });\n\n const accountMap = new Map<string, Account>();\n const childrenMap = new Map<string, Account[]>();\n\n // Build lookup maps\n for (const account of allAccounts) {\n if (account.id) {\n accountMap.set(account.id, account);\n }\n if (!childrenMap.has(account.parentId || '')) {\n childrenMap.set(account.parentId || '', []);\n }\n childrenMap.get(account.parentId || '')?.push(account);\n }\n\n // Build tree nodes recursively\n const buildNode = (account: Account): AccountTreeNode => {\n const children = (account.id ? childrenMap.get(account.id) : []) || [];\n return {\n account,\n children: children.map(buildNode),\n };\n };\n\n // Get root nodes (no parent)\n const roots = childrenMap.get('') || [];\n\n return {\n roots: roots.map(buildNode),\n };\n }\n\n /**\n * Get or create an account by number\n *\n * @param number - Account number\n * @param defaults - Default values if creating\n * @returns Account\n */\n async getOrCreateByNumber(\n number: string,\n defaults: Partial<{\n name: string;\n description: string;\n type: AccountType;\n parentId: string | null;\n }> = {},\n ): Promise<Account> {\n const existing = await this.findByNumber(number);\n if (existing) {\n return existing;\n }\n\n const account = await this.create({\n number,\n name: defaults.name || number,\n description: defaults.description || '',\n type: defaults.type || 'asset',\n parentId: defaults.parentId || null,\n });\n await account.save();\n return account;\n }\n\n /**\n * Find accounts grouped by type\n *\n * @returns Record of type to accounts array\n */\n async groupByType(): Promise<Record<AccountType, Account[]>> {\n const accounts = await this.findActive();\n const grouped: Record<AccountType, Account[]> = {\n asset: [],\n liability: [],\n equity: [],\n revenue: [],\n expense: [],\n };\n\n for (const account of accounts) {\n grouped[account.type].push(account);\n }\n\n return grouped;\n }\n\n /**\n * Get all descendants of an account recursively\n *\n * @param accountId - Account ID\n * @returns Array of all descendant accounts\n */\n async getDescendants(accountId: string): Promise<Account[]> {\n const descendants: Account[] = [];\n const queue: string[] = [accountId];\n\n while (queue.length > 0) {\n const currentId = queue.shift();\n if (!currentId) continue;\n\n const children = await this.findChildren(currentId);\n\n for (const child of children) {\n descendants.push(child);\n if (child.id) {\n queue.push(child.id);\n }\n }\n }\n\n return descendants;\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Tenant Helper Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Find all accounts belonging to a specific tenant\n *\n * @param tenantId - Tenant ID\n * @returns Array of tenant's accounts\n */\n async findByTenant(tenantId: string): Promise<Account[]> {\n return this.list({ where: { tenantId } });\n }\n\n /**\n * Find all global accounts (no tenant association).\n *\n * Routes through the shared tenant-global helper so it does not throw under\n * an active tenant context (an explicit `tenant_id IS NULL` filter would be\n * flagged as an isolation violation). (#1600)\n *\n * @returns Array of global accounts\n */\n async findGlobal(): Promise<Account[]> {\n return queryGlobal<Account>(this);\n }\n\n /**\n * Find accounts for a tenant plus all global accounts.\n *\n * Fails closed if an active tenant context requests a different tenant's\n * rows; the admin/system path keeps the cross-tenant capability. (#1600)\n *\n * @param tenantId - Tenant ID\n * @returns Array of tenant's accounts and global accounts\n */\n async findWithGlobals(tenantId: string): Promise<Account[]> {\n return queryWithGlobals<Account>(this, tenantId, 'Account.findWithGlobals');\n }\n}\n","/**\n * JournalEntry model - Individual ledger line\n *\n * The atomic unit of double-entry accounting - a single debit or credit.\n * Each entry belongs to a Journal and references an Account.\n */\n\nimport { foreignKey, SmrtObject, smrt } from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport type { JournalEntryOptions } from '../types';\n\n@TenantScoped({ mode: 'optional' })\n@smrt({\n api: { include: ['list', 'get'] }, // Created via Journal, not directly\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n})\nexport class JournalEntry extends SmrtObject {\n /**\n * Tenant ID for multi-tenancy support (nullable for global entries)\n */\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n /**\n * Parent journal ID (required)\n */\n @foreignKey('Journal')\n journalId: string = '';\n\n /**\n * Account ID (required)\n */\n @foreignKey('Account')\n accountId: string = '';\n\n /**\n * Debit amount (left side)\n */\n debit: number = 0.0;\n\n /**\n * Credit amount (right side)\n */\n credit: number = 0.0;\n\n /**\n * Currency code (e.g., \"USD\", \"CAD\", \"EUR\")\n */\n currency: string = 'USD';\n\n /**\n * Exchange rate to base currency\n */\n exchangeRate: number = 1.0;\n\n /**\n * Line memo/description\n */\n memo: string = '';\n\n /**\n * Extensible metadata\n */\n metadata: Record<string, unknown> = {};\n\n constructor(options: JournalEntryOptions = {}) {\n super(options);\n if (options.journalId !== undefined) this.journalId = options.journalId;\n if (options.accountId !== undefined) this.accountId = options.accountId;\n if (options.debit !== undefined) this.debit = options.debit;\n if (options.credit !== undefined) this.credit = options.credit;\n if (options.currency !== undefined) this.currency = options.currency;\n if (options.exchangeRate !== undefined)\n this.exchangeRate = options.exchangeRate;\n if (options.memo !== undefined) this.memo = options.memo;\n if (options.metadata !== undefined) this.metadata = options.metadata;\n }\n\n /**\n * Validate entry before save\n */\n protected async validateBeforeSave(): Promise<void> {\n await super.validateBeforeSave();\n // Validate amounts are non-negative\n if (this.debit < 0) {\n throw new Error('Debit amount cannot be negative');\n }\n if (this.credit < 0) {\n throw new Error('Credit amount cannot be negative');\n }\n\n // Validate that entry has debit OR credit, not both\n if (this.debit > 0 && this.credit > 0) {\n throw new Error('Entry cannot have both debit and credit amounts');\n }\n\n // Validate that entry has at least one amount\n if (this.debit === 0 && this.credit === 0) {\n throw new Error('Entry must have either a debit or credit amount');\n }\n\n // Validate exchange rate is positive\n if (this.exchangeRate <= 0) {\n throw new Error('Exchange rate must be positive');\n }\n }\n\n /**\n * Check if this is a debit entry\n */\n isDebit(): boolean {\n return this.debit > 0;\n }\n\n /**\n * Check if this is a credit entry\n */\n isCredit(): boolean {\n return this.credit > 0;\n }\n\n /**\n * Get the entry amount (positive value regardless of debit/credit)\n */\n getAmount(): number {\n return this.debit > 0 ? this.debit : this.credit;\n }\n\n /**\n * Get the amount in base currency\n */\n getBaseAmount(): number {\n return this.getAmount() * this.exchangeRate;\n }\n\n /**\n * Get the parent journal\n */\n async getJournal(): Promise<import('./Journal').Journal | null> {\n if (!this.journalId) return null;\n const { JournalCollection } = await import('../collections/Journals');\n const collection = await JournalCollection.create(this.options);\n return await collection.get({ id: this.journalId });\n }\n\n /**\n * Get the account\n */\n async getAccount(): Promise<import('./Account').Account | null> {\n if (!this.accountId) return null;\n const { AccountCollection } = await import('../collections/Accounts');\n const collection = await AccountCollection.create(this.options);\n return await collection.get({ id: this.accountId });\n }\n\n /**\n * Get a formatted description of this entry\n */\n async getDescription(): Promise<string> {\n const account = await this.getAccount();\n const accountName = account?.name || 'Unknown Account';\n const type = this.isDebit() ? 'DR' : 'CR';\n const amount = this.getAmount().toFixed(2);\n\n return `${type} ${accountName}: $${amount}${this.memo ? ` - ${this.memo}` : ''}`;\n }\n}\n","/**\n * JournalEntryCollection - Collection manager for JournalEntry objects\n *\n * Provides querying and balance calculations for ledger entries.\n */\n\nimport { SmrtCollection } from '@happyvertical/smrt-core';\nimport { queryGlobal, queryWithGlobals } from '@happyvertical/smrt-tenancy';\nimport { JournalEntry } from '../models/JournalEntry';\nimport { BALANCE_EPSILON, type TrialBalanceRow } from '../types';\n\nexport class JournalEntryCollection extends SmrtCollection<JournalEntry> {\n static readonly _itemClass = JournalEntry;\n\n /**\n * Find entries by journal\n *\n * @param journalId - Journal ID\n * @returns Array of entries\n */\n async findByJournal(journalId: string): Promise<JournalEntry[]> {\n return await this.list({\n where: { journalId },\n });\n }\n\n /**\n * Find entries by account\n *\n * @param accountId - Account ID\n * @returns Array of entries\n */\n async findByAccount(accountId: string): Promise<JournalEntry[]> {\n return await this.list({\n where: { accountId },\n });\n }\n\n /**\n * Get account balance\n *\n * For debit-normal accounts (Asset, Expense): balance = debits - credits\n * For credit-normal accounts (Liability, Equity, Revenue): balance = credits - debits\n *\n * @param accountId - Account ID\n * @param asOfDate - Optional date to calculate balance as of\n * @returns Account balance\n */\n async getAccountBalance(accountId: string, asOfDate?: Date): Promise<number> {\n // Get entries for this account from posted journals only\n const { JournalCollection } = await import('./Journals');\n const journalCollection = await JournalCollection.create(this.options);\n const { AccountCollection } = await import('./Accounts');\n const accountCollection = await AccountCollection.create(this.options);\n\n // Get the account to determine if it's debit or credit normal\n const account = await accountCollection.get({ id: accountId });\n if (!account) {\n throw new Error(`Account not found: ${accountId}`);\n }\n\n // Get all entries for this account\n const allEntries = await this.findByAccount(accountId);\n\n let totalDebits = 0;\n let totalCredits = 0;\n\n for (const entry of allEntries) {\n // Get the journal to check status and date\n const journal = await journalCollection.get({ id: entry.journalId });\n if (!journal) continue;\n\n // Only include posted journals\n if (!journal.isPosted()) continue;\n\n // Check date if specified\n if (asOfDate && journal.date > asOfDate) continue;\n\n totalDebits += entry.debit;\n totalCredits += entry.credit;\n }\n\n // Calculate balance based on account type\n if (account.isDebitNormal()) {\n // Asset, Expense: increases with debits\n return totalDebits - totalCredits;\n } else {\n // Liability, Equity, Revenue: increases with credits\n return totalCredits - totalDebits;\n }\n }\n\n /**\n * Get trial balance\n *\n * @param asOfDate - Optional date for trial balance\n * @returns Array of trial balance rows\n */\n async getTrialBalance(asOfDate?: Date): Promise<TrialBalanceRow[]> {\n const { AccountCollection } = await import('./Accounts');\n const accountCollection = await AccountCollection.create(this.options);\n\n const accounts = await accountCollection.findActive();\n const rows: TrialBalanceRow[] = [];\n\n for (const account of accounts) {\n if (!account.id) continue;\n\n const balance = await this.getAccountBalance(account.id, asOfDate);\n\n // Skip zero-balance accounts\n if (Math.abs(balance) < BALANCE_EPSILON) continue;\n\n rows.push({\n accountId: account.id,\n accountNumber: account.number,\n accountName: account.name,\n accountType: account.type,\n debitBalance: account.isDebitNormal() && balance > 0 ? balance : 0,\n creditBalance: account.isCreditNormal() && balance > 0 ? balance : 0,\n });\n }\n\n // Sort by account number\n rows.sort((a, b) => a.accountNumber.localeCompare(b.accountNumber));\n\n return rows;\n }\n\n /**\n * Get total debits and credits for a date range\n *\n * @param start - Start date\n * @param end - End date\n * @returns Object with totalDebits and totalCredits\n */\n async getTotalsForDateRange(\n start: Date,\n end: Date,\n ): Promise<{ totalDebits: number; totalCredits: number }> {\n const { JournalCollection } = await import('./Journals');\n const journalCollection = await JournalCollection.create(this.options);\n\n const journals = await journalCollection.findByDateRange(start, end);\n\n let totalDebits = 0;\n let totalCredits = 0;\n\n for (const journal of journals) {\n if (!journal.isPosted()) continue;\n\n const entries = await this.findByJournal(journal.id!);\n for (const entry of entries) {\n totalDebits += entry.debit;\n totalCredits += entry.credit;\n }\n }\n\n return { totalDebits, totalCredits };\n }\n\n /**\n * Get entries for multiple accounts\n *\n * @param accountIds - Array of account IDs\n * @returns Array of entries\n */\n async findByAccounts(accountIds: string[]): Promise<JournalEntry[]> {\n if (accountIds.length === 0) {\n return [];\n }\n\n // Use single query with IN clause to avoid N+1 problem\n return await this.list({\n where: { accountId: accountIds },\n });\n }\n\n /**\n * Get the running balance for an account (list of entries with running total)\n *\n * @param accountId - Account ID\n * @returns Array of entries with running balance\n */\n async getAccountLedger(\n accountId: string,\n ): Promise<Array<{ entry: JournalEntry; runningBalance: number }>> {\n const { JournalCollection } = await import('./Journals');\n const { AccountCollection } = await import('./Accounts');\n const journalCollection = await JournalCollection.create(this.options);\n const accountCollection = await AccountCollection.create(this.options);\n\n const account = await accountCollection.get({ id: accountId });\n if (!account) {\n throw new Error(`Account not found: ${accountId}`);\n }\n\n const entries = await this.findByAccount(accountId);\n const ledger: Array<{ entry: JournalEntry; runningBalance: number }> = [];\n let runningBalance = 0;\n\n // Sort entries by journal date\n const entriesWithJournals = await Promise.all(\n entries.map(async (entry) => ({\n entry,\n journal: await journalCollection.get({ id: entry.journalId }),\n })),\n );\n\n entriesWithJournals.sort((a, b) => {\n if (!a.journal || !b.journal) return 0;\n return a.journal.date.getTime() - b.journal.date.getTime();\n });\n\n for (const { entry, journal } of entriesWithJournals) {\n if (!journal?.isPosted()) continue;\n\n if (account.isDebitNormal()) {\n runningBalance += entry.debit - entry.credit;\n } else {\n runningBalance += entry.credit - entry.debit;\n }\n\n ledger.push({ entry, runningBalance });\n }\n\n return ledger;\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Tenant Helper Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Find all journal entries belonging to a specific tenant\n *\n * @param tenantId - Tenant ID\n * @returns Array of tenant's journal entries\n */\n async findByTenant(tenantId: string): Promise<JournalEntry[]> {\n return this.list({ where: { tenantId } });\n }\n\n /**\n * Find all global journal entries (no tenant association).\n *\n * Routes through the shared tenant-global helper so it does not throw under\n * an active tenant context. (#1600)\n *\n * @returns Array of global journal entries\n */\n async findGlobal(): Promise<JournalEntry[]> {\n return queryGlobal<JournalEntry>(this);\n }\n\n /**\n * Find journal entries for a tenant plus all global entries.\n *\n * Fails closed if an active tenant context requests a different tenant's\n * rows; the admin/system path keeps the cross-tenant capability. (#1600)\n *\n * @param tenantId - Tenant ID\n * @returns Array of tenant's entries and global entries\n */\n async findWithGlobals(tenantId: string): Promise<JournalEntry[]> {\n return queryWithGlobals<JournalEntry>(\n this,\n tenantId,\n 'JournalEntry.findWithGlobals',\n );\n }\n}\n","/**\n * Journal model - Financial event container\n *\n * Represents a single, discrete financial event.\n * Contains one or more JournalEntry records that must balance (debits = credits).\n */\n\nimport { SmrtObject, smrt } from '@happyvertical/smrt-core';\nimport { resolvePrompt } from '@happyvertical/smrt-prompts';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport {\n promptMessageOptions,\n smrtLedgersJournalSummarizePrompt,\n} from '../prompts';\nimport {\n BALANCE_EPSILON,\n type JournalEntryData,\n type JournalOptions,\n type JournalStatus,\n} from '../types';\n\n@TenantScoped({ mode: 'optional' })\n@smrt({\n api: { include: ['list', 'get', 'create'] }, // No update/delete - immutable after posting\n mcp: { include: ['list', 'get', 'create'] },\n cli: { skipApiCheck: true },\n})\nexport class Journal extends SmrtObject {\n /**\n * Tenant ID for multi-tenancy support (nullable for global journals)\n */\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n /**\n * Journal number (auto-generated sequence, e.g., \"JNL-0001\")\n */\n number: string = '';\n\n /**\n * Transaction date\n */\n date: Date = new Date();\n\n /**\n * Description of the financial event\n */\n description: string = '';\n\n /**\n * Source module that created this journal (e.g., \"smrt-commerce\", \"manual\")\n */\n sourceModule: string = '';\n\n /**\n * External reference (e.g., order ID, invoice number)\n */\n sourceRef: string | null = null;\n\n /**\n * Journal status: draft, posted, voided\n */\n status: JournalStatus = 'draft';\n\n /**\n * When the journal was posted (finalized)\n */\n postedAt: Date | null = null;\n\n /**\n * When the journal was voided\n */\n voidedAt: Date | null = null;\n\n /**\n * Reason for voiding (if voided)\n */\n voidReason: string | null = null;\n\n /**\n * Extensible metadata\n */\n metadata: Record<string, unknown> = {};\n\n constructor(options: JournalOptions = {}) {\n super(options);\n if (options.number !== undefined) this.number = options.number;\n if (options.date !== undefined) this.date = options.date;\n if (options.description !== undefined)\n this.description = options.description;\n if (options.sourceModule !== undefined)\n this.sourceModule = options.sourceModule;\n if (options.sourceRef !== undefined) this.sourceRef = options.sourceRef;\n if (options.status !== undefined) this.status = options.status;\n if (options.postedAt !== undefined) this.postedAt = options.postedAt;\n if (options.voidedAt !== undefined) this.voidedAt = options.voidedAt;\n if (options.voidReason !== undefined) this.voidReason = options.voidReason;\n if (options.metadata !== undefined) this.metadata = options.metadata;\n }\n\n /**\n * Check if journal is in draft status\n */\n isDraft(): boolean {\n return this.status === 'draft';\n }\n\n /**\n * Check if journal has been posted\n */\n isPosted(): boolean {\n return this.status === 'posted';\n }\n\n /**\n * Check if journal has been voided\n */\n isVoided(): boolean {\n return this.status === 'voided';\n }\n\n /**\n * Check if journal can be modified\n */\n isEditable(): boolean {\n return this.status === 'draft';\n }\n\n /**\n * Get all entries for this journal\n */\n async getEntries(): Promise<import('./JournalEntry').JournalEntry[]> {\n if (!this.id) return [];\n const { JournalEntryCollection } = await import(\n '../collections/JournalEntries'\n );\n const collection = await JournalEntryCollection.create(this.options);\n return await collection.findByJournal(this.id);\n }\n\n /**\n * Calculate total debits\n */\n async getTotalDebits(): Promise<number> {\n const entries = await this.getEntries();\n return entries.reduce((sum, entry) => sum + entry.debit, 0);\n }\n\n /**\n * Calculate total credits\n */\n async getTotalCredits(): Promise<number> {\n const entries = await this.getEntries();\n return entries.reduce((sum, entry) => sum + entry.credit, 0);\n }\n\n /**\n * Check if journal entries are balanced (debits = credits)\n */\n async isBalanced(): Promise<boolean> {\n const debits = await this.getTotalDebits();\n const credits = await this.getTotalCredits();\n return Math.abs(debits - credits) < BALANCE_EPSILON;\n }\n\n /**\n * Add an entry to this journal (only if draft)\n */\n async addEntry(data: JournalEntryData): Promise<void> {\n if (!this.id) {\n throw new Error('Journal must be saved before adding entries');\n }\n if (!this.isEditable()) {\n throw new Error('Cannot add entries to a posted or voided journal');\n }\n\n const { JournalEntryCollection } = await import(\n '../collections/JournalEntries'\n );\n const collection = await JournalEntryCollection.create(this.options);\n const entry = await collection.create({\n journalId: this.id,\n accountId: data.accountId,\n debit: data.debit || 0,\n credit: data.credit || 0,\n currency: data.currency || 'USD',\n exchangeRate: data.exchangeRate || 1.0,\n memo: data.memo || '',\n });\n await entry.save();\n }\n\n /**\n * Post the journal (finalize and make immutable)\n */\n async post(): Promise<void> {\n if (!this.isDraft()) {\n throw new Error('Only draft journals can be posted');\n }\n\n const balanced = await this.isBalanced();\n if (!balanced) {\n const debits = await this.getTotalDebits();\n const credits = await this.getTotalCredits();\n throw new Error(\n `Journal is not balanced. Debits: ${debits}, Credits: ${credits}`,\n );\n }\n\n const entries = await this.getEntries();\n if (entries.length === 0) {\n throw new Error('Journal must have at least one entry');\n }\n\n this.status = 'posted';\n this.postedAt = new Date();\n await this.save();\n }\n\n /**\n * Void the journal (mark as cancelled with reason)\n */\n async void(reason: string): Promise<void> {\n if (this.isVoided()) {\n throw new Error('Journal is already voided');\n }\n\n this.status = 'voided';\n this.voidedAt = new Date();\n this.voidReason = reason;\n await this.save();\n }\n\n /**\n * AI-powered: Generate a summary of this journal.\n *\n * Uses the `smrtLedgers.journal.summarize` prompt registered via\n * `@happyvertical/smrt-prompts`, allowing tenant- or instance-level\n * overrides of the template, model, and parameters at runtime.\n *\n * Only non-PII journal fields (number, date, description, status, balanced\n * flag) plus aggregate totals and entry count are sent to the AI provider.\n * Internal foreign-key fields (tenantId, sourceRef, individual entry\n * account IDs) and the extensible `metadata` blob are intentionally\n * excluded.\n *\n * @returns Generated summary text\n */\n async summarize(): Promise<string> {\n const entries = await this.getEntries();\n const debits = await this.getTotalDebits();\n const balanced = await this.isBalanced();\n\n // Resolve `db` from either the canonical `db` option or its `persistence`\n // alias. SmrtClass maps `persistence → db` lazily during `initialize()`,\n // so on a freshly-constructed Journal that has not yet been initialized,\n // `this.options.db` may be undefined while `this.options.persistence` is\n // set. Falling back here ensures stored app- and tenant-level prompt\n // overrides in `_smrt_prompt_overrides` are honored on the first call —\n // before `getAiClient()` triggers full initialization further below.\n const db = this.options.db ?? this.options.persistence;\n\n const resolvedPrompt = await resolvePrompt(\n smrtLedgersJournalSummarizePrompt.key,\n {\n db,\n tenantId: this.tenantId,\n variables: {\n journalNumber: this.number || '',\n journalDate: this.date.toISOString().split('T')[0],\n journalDescription: this.description || '',\n journalStatus: this.status || '',\n // Currency prefix folded into the value rather than the template\n // — see the `smrtLedgersJournalSummarizePrompt` comment block.\n journalTotal: `$${debits.toFixed(2)}`,\n entryCount: String(entries.length),\n journalBalanced: balanced ? 'Yes' : 'No',\n },\n },\n );\n\n const ai = await this.getAiClient();\n const response = await ai.message(\n resolvedPrompt.text,\n promptMessageOptions(resolvedPrompt.ai),\n );\n\n return response.trim();\n }\n}\n","/**\n * JournalCollection - Collection manager for Journal objects\n *\n * Provides querying and operations for financial journals.\n */\n\nimport { SmrtCollection } from '@happyvertical/smrt-core';\nimport { queryGlobal, queryWithGlobals } from '@happyvertical/smrt-tenancy';\nimport { Journal } from '../models/Journal';\nimport {\n BALANCE_EPSILON,\n type CreateJournalData,\n type JournalStatus,\n} from '../types';\n\nexport class JournalCollection extends SmrtCollection<Journal> {\n static readonly _itemClass = Journal;\n\n /**\n * Generate next journal number\n *\n * Uses timestamp and random component to avoid collisions\n * in concurrent environments without relying on shared state.\n */\n private generateJournalNumber(): string {\n const timestamp = Date.now().toString(36);\n const randomPart = Math.random().toString(36).slice(2, 6);\n return `JNL-${timestamp}-${randomPart}`;\n }\n\n /**\n * Find journal by number\n *\n * @param number - Journal number\n * @returns Journal or null\n */\n async findByNumber(number: string): Promise<Journal | null> {\n const journals = await this.list({\n where: { number },\n limit: 1,\n });\n return journals[0] || null;\n }\n\n /**\n * Find journals by date range\n *\n * @param start - Start date\n * @param end - End date\n * @returns Array of journals\n */\n async findByDateRange(start: Date, end: Date): Promise<Journal[]> {\n return await this.list({\n where: {\n 'date >=': start.toISOString(),\n 'date <=': end.toISOString(),\n },\n orderBy: 'date ASC',\n });\n }\n\n /**\n * Find journals by source module\n *\n * @param sourceModule - Source module name\n * @returns Array of journals\n */\n async findBySource(sourceModule: string): Promise<Journal[]> {\n return await this.list({\n where: { sourceModule },\n orderBy: 'date DESC',\n });\n }\n\n /**\n * Find journals by status\n *\n * @param status - Journal status\n * @returns Array of journals\n */\n async findByStatus(status: JournalStatus): Promise<Journal[]> {\n return await this.list({\n where: { status },\n orderBy: 'date DESC',\n });\n }\n\n /**\n * Find draft journals\n *\n * @returns Array of draft journals\n */\n async findDrafts(): Promise<Journal[]> {\n return await this.findByStatus('draft');\n }\n\n /**\n * Find posted journals\n *\n * @returns Array of posted journals\n */\n async findPosted(): Promise<Journal[]> {\n return await this.findByStatus('posted');\n }\n\n /**\n * Create a complete journal with entries\n *\n * @param data - Journal data with entries\n * @returns Created journal\n */\n async createWithEntries(data: CreateJournalData): Promise<Journal> {\n // Validate entries balance\n let totalDebits = 0;\n let totalCredits = 0;\n\n for (const entry of data.entries) {\n totalDebits += entry.debit || 0;\n totalCredits += entry.credit || 0;\n }\n\n if (Math.abs(totalDebits - totalCredits) >= BALANCE_EPSILON) {\n throw new Error(\n `Entries are not balanced. Debits: ${totalDebits}, Credits: ${totalCredits}`,\n );\n }\n\n if (data.entries.length === 0) {\n throw new Error('Journal must have at least one entry');\n }\n\n // Create journal\n const journalNumber = await this.generateJournalNumber();\n const journal = await this.create({\n number: journalNumber,\n date: data.date || new Date(),\n description: data.description,\n sourceModule: data.sourceModule || 'manual',\n sourceRef: data.sourceRef || null,\n metadata: data.metadata || {},\n });\n await journal.save();\n\n // Create entries\n for (const entryData of data.entries) {\n await journal.addEntry(entryData);\n }\n\n return journal;\n }\n\n /**\n * Post a journal by ID\n *\n * @param journalId - Journal ID\n * @returns Posted journal\n */\n async post(journalId: string): Promise<Journal> {\n const journal = await this.get({ id: journalId });\n if (!journal) {\n throw new Error(`Journal not found: ${journalId}`);\n }\n await journal.post();\n return journal;\n }\n\n /**\n * Void a journal by ID\n *\n * @param journalId - Journal ID\n * @param reason - Reason for voiding\n * @returns Voided journal\n */\n async void(journalId: string, reason: string): Promise<Journal> {\n const journal = await this.get({ id: journalId });\n if (!journal) {\n throw new Error(`Journal not found: ${journalId}`);\n }\n await journal.void(reason);\n return journal;\n }\n\n /**\n * Find journals by source reference\n *\n * @param sourceRef - External reference\n * @returns Array of journals\n */\n async findBySourceRef(sourceRef: string): Promise<Journal[]> {\n return await this.list({\n where: { sourceRef },\n orderBy: 'date DESC',\n });\n }\n\n /**\n * Get journals for a specific month\n *\n * @param year - Year\n * @param month - Month (1-12)\n * @returns Array of journals\n */\n async findByMonth(year: number, month: number): Promise<Journal[]> {\n const start = new Date(year, month - 1, 1);\n const end = new Date(year, month, 0, 23, 59, 59, 999);\n return await this.findByDateRange(start, end);\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Tenant Helper Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Find all journals belonging to a specific tenant\n *\n * @param tenantId - Tenant ID\n * @returns Array of tenant's journals\n */\n async findByTenant(tenantId: string): Promise<Journal[]> {\n return this.list({ where: { tenantId } });\n }\n\n /**\n * Find all global journals (no tenant association).\n *\n * Routes through the shared tenant-global helper so it does not throw under\n * an active tenant context. (#1600)\n *\n * @returns Array of global journals\n */\n async findGlobal(): Promise<Journal[]> {\n return queryGlobal<Journal>(this);\n }\n\n /**\n * Find journals for a tenant plus all global journals.\n *\n * Fails closed if an active tenant context requests a different tenant's\n * rows; the admin/system path keeps the cross-tenant capability. (#1600)\n *\n * @param tenantId - Tenant ID\n * @returns Array of tenant's journals and global journals\n */\n async findWithGlobals(tenantId: string): Promise<Journal[]> {\n return queryWithGlobals<Journal>(this, tenantId, 'Journal.findWithGlobals');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AC8BO,IAAM,oCAAoC,aAAa;CAC5D,KAAK;CACL,UAAU;;;;;;;;CAQV,UAAU;EACR,UAAU;EACV,SAAS;EACT,OAAO;EACP,QAAQ;CACV;AACF,CAAC;AAEM,SAAS,qBAAqB,IAAsB;CACzD,OAAO;EACL,GAAI,GAAG,UAAU,CAAC;EAClB,GAAI,GAAG,QAAQ,EAAE,OAAO,GAAG,MAAM,IAAI,CAAC;EACtC,GAAI,OAAO,GAAG,gBAAgB,WAC1B,EAAE,aAAa,GAAG,YAAY,IAC9B,CAAC;EACL,GAAI,OAAO,GAAG,cAAc,WAAW,EAAE,WAAW,GAAG,UAAU,IAAI,CAAC;CACxE;AACF;;;;;;;;;;;ACxCO,IAAM,UAAN,cAAsB,iBAAiB;CAK5C,WAA0B;;;;CAK1B,SAAiB;;;;CAKjB,OAAe;;;;CAKf,cAAsB;;;;CAKtB,OAAoB;;;;CAOpB,SAAkB;;;;CAKlB,WAAoC,CAAC;CAErC,YAAY,UAA0B,CAAC,GAAG;EACxC,MAAM,OAAO;EACb,IAAI,QAAQ,WAAW,KAAA,GAAW,KAAK,SAAS,QAAQ;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AM,IAAI,MAAM,sBAAsB,WAAW;EAEnD,MAAM,QAAQ,KAAK,MAAM;EACzB,OAAO;CACT;;;;;;;CAQA,MAAM,gBAAgB,WAAuC;EAC3D,OAAO,MAAM,KAAK,KAAK;GACrB,OAAO,EAAE,UAAU;GACnB,SAAS;EACX,CAAC;CACH;;;;;;;;CASA,MAAM,YAAY,MAAc,OAAmC;EACjE,MAAM,QAAQ,IAAI,KAAK,MAAM,QAAQ,GAAG,CAAC;EACzC,MAAM,MAAM,IAAI,KAAK,MAAM,OAAO,GAAG,IAAI,IAAI,IAAI,GAAG;EACpD,OAAO,MAAM,KAAK,gBAAgB,OAAO,GAAG;CAC9C;;;;;;;CAYA,MAAM,aAAa,UAAsC;EACvD,OAAO,KAAK,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;CAC1C;;;;;;;;;CAUA,MAAM,aAAiC;EACrC,OAAO,YAAqB,IAAI;CAClC;;;;;;;;;;CAWA,MAAM,gBAAgB,UAAsC;EAC1D,OAAO,iBAA0B,MAAM,UAAU,yBAAyB;CAC5E;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/__smrt-register__.ts","../src/prompts.ts","../src/collections/Accounts.ts","../src/models/JournalEntry.ts","../src/collections/JournalEntries.ts","../src/models/Journal.ts","../src/collections/Journals.ts","../src/migrations/ledger-accounts-table.ts"],"sourcesContent":["/**\n * Self-registers this package's build-time manifest before any @smrt() decorator\n * in the package fires. Fixes issue #1132: in consumer runtimes (tsx, SvelteKit\n * SSR, plain `vite dev`) the decorator's synchronous manifest lookup previously\n * missed because no step populated the global manifest cache — classes got\n * registered with zero fields and `save()` / `toJSON()` silently dropped every\n * declared property.\n *\n * Import this module as the first statement in `src/index.ts` so its top-level\n * side effect runs ahead of any class module's @smrt() decorator.\n *\n * Silent no-op in dev/test, where the vitest plugin already populates manifests\n * via a different path. Only needs to succeed in the published dist output.\n *\n * @see https://github.com/happyvertical/smrt/issues/1132\n */\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\n// During library builds, smrtPlugin replaces this entire module with generated\n// code that embeds the scanned manifest inline (#1506/#1507) — published dists\n// never resolve this URL, so downstream bundlers cannot break registration by\n// relocating the compiled module away from dist/manifest.json. The runtime\n// lookup below is the fallback for source-mode runs without that transform.\nObjectRegistry.registerPackageManifest(\n new URL('./manifest.json', import.meta.url),\n);\n","/**\n * Prompt registrations for the @happyvertical/smrt-ledgers package.\n *\n * Prompts are registered at module-load time via `definePrompt()` so that\n * tenant-aware overrides can be applied at call time via `resolvePrompt()`.\n *\n * Mirrors the pattern used by `@happyvertical/smrt-properties` (see\n * `prompts.ts`) and `@happyvertical/smrt-content` (see `content-prompts.ts`).\n */\n\nimport {\n definePrompt,\n type ResolvedPromptAI,\n} from '@happyvertical/smrt-prompts';\n\n// Journal summarization only uses non-PII journal fields\n// (number, date, description, status, balanced flag) plus aggregate totals\n// and entry count. Internal/foreign-key fields like tenantId, sourceRef,\n// individual entry account IDs, and the extensible `metadata` blob are\n// intentionally NOT passed to the AI provider — they may link to identifying\n// records (customer/vendor IDs via sourceRef) or contain tenant-private\n// configuration. If a downstream tenant needs richer context they can\n// override the template via PromptOverride.\n// Note: smrt-prompts substitutes `{token}` placeholders. The currency prefix\n// is folded into the `journalTotal` variable value (e.g. \"$100.00\") rather\n// than written as a literal `$` in the template — earlier revisions used\n// `\\${journalTotal}` (a template-literal escape that renders as the literal\n// `${journalTotal}` at runtime). That technically worked because the regex\n// still matched the inner `{journalTotal}` and produced `$100.00`, but it\n// confused reviewers; folding the prefix into the value avoids the trap.\nexport const smrtLedgersJournalSummarizePrompt = definePrompt({\n key: 'smrtLedgers.journal.summarize',\n template: `Summarize this accounting journal entry:\nNumber: {journalNumber}\nDate: {journalDate}\nDescription: {journalDescription}\nStatus: {journalStatus}\nTotal: {journalTotal}\nEntries: {entryCount}\nBalanced: {journalBalanced}`,\n editable: {\n template: true,\n profile: true,\n model: true,\n params: true,\n },\n});\n\nexport function promptMessageOptions(ai: ResolvedPromptAI) {\n return {\n ...(ai.params || {}),\n ...(ai.model ? { model: ai.model } : {}),\n ...(typeof ai.temperature === 'number'\n ? { temperature: ai.temperature }\n : {}),\n ...(typeof ai.maxTokens === 'number' ? { maxTokens: ai.maxTokens } : {}),\n };\n}\n","/**\n * AccountCollection - Collection manager for Account objects\n *\n * Provides querying and tree operations for chart of accounts.\n */\n\nimport { SmrtCollection } from '@happyvertical/smrt-core';\nimport { queryGlobal, queryWithGlobals } from '@happyvertical/smrt-tenancy';\nimport { Account } from '../models/Account';\nimport type { AccountTree, AccountTreeNode, AccountType } from '../types';\n\nexport class AccountCollection extends SmrtCollection<Account> {\n static readonly _itemClass = Account;\n\n /**\n * Find account by number\n *\n * @param number - Account number\n * @returns Account or null\n */\n async findByNumber(number: string): Promise<Account | null> {\n const accounts = await this.list({\n where: { number },\n limit: 1,\n });\n return accounts[0] || null;\n }\n\n /**\n * Find accounts by type\n *\n * @param type - Account type\n * @returns Array of accounts\n */\n async findByType(type: AccountType): Promise<Account[]> {\n return await this.list({\n where: { type },\n orderBy: 'number ASC',\n });\n }\n\n /**\n * Find all active accounts\n *\n * @returns Array of active accounts\n */\n async findActive(): Promise<Account[]> {\n return await this.list({\n where: { active: true },\n orderBy: 'number ASC',\n });\n }\n\n /**\n * Find top-level accounts (no parent)\n *\n * @returns Array of top-level accounts\n */\n async findTopLevel(): Promise<Account[]> {\n return await this.list({\n where: { parentId: null },\n orderBy: 'number ASC',\n });\n }\n\n /**\n * Find direct children of an account\n *\n * @param parentId - Parent account ID\n * @returns Array of child accounts\n */\n async findChildren(parentId: string): Promise<Account[]> {\n return await this.list({\n where: { parentId },\n orderBy: 'number ASC',\n });\n }\n\n /**\n * Get the complete account tree\n *\n * @returns AccountTree structure\n */\n async getTree(): Promise<AccountTree> {\n const allAccounts = await this.list({\n orderBy: 'number ASC',\n });\n\n const accountMap = new Map<string, Account>();\n const childrenMap = new Map<string, Account[]>();\n\n // Build lookup maps\n for (const account of allAccounts) {\n if (account.id) {\n accountMap.set(account.id, account);\n }\n if (!childrenMap.has(account.parentId || '')) {\n childrenMap.set(account.parentId || '', []);\n }\n childrenMap.get(account.parentId || '')?.push(account);\n }\n\n // Build tree nodes recursively\n const buildNode = (account: Account): AccountTreeNode => {\n const children = (account.id ? childrenMap.get(account.id) : []) || [];\n return {\n account,\n children: children.map(buildNode),\n };\n };\n\n // Get root nodes (no parent)\n const roots = childrenMap.get('') || [];\n\n return {\n roots: roots.map(buildNode),\n };\n }\n\n /**\n * Get or create an account by number\n *\n * @param number - Account number\n * @param defaults - Default values if creating\n * @returns Account\n */\n async getOrCreateByNumber(\n number: string,\n defaults: Partial<{\n name: string;\n description: string;\n type: AccountType;\n parentId: string | null;\n }> = {},\n ): Promise<Account> {\n const existing = await this.findByNumber(number);\n if (existing) {\n return existing;\n }\n\n const account = await this.create({\n number,\n name: defaults.name || number,\n description: defaults.description || '',\n type: defaults.type || 'asset',\n parentId: defaults.parentId || null,\n });\n await account.save();\n return account;\n }\n\n /**\n * Find accounts grouped by type\n *\n * @returns Record of type to accounts array\n */\n async groupByType(): Promise<Record<AccountType, Account[]>> {\n const accounts = await this.findActive();\n const grouped: Record<AccountType, Account[]> = {\n asset: [],\n liability: [],\n equity: [],\n revenue: [],\n expense: [],\n };\n\n for (const account of accounts) {\n grouped[account.type].push(account);\n }\n\n return grouped;\n }\n\n /**\n * Get all descendants of an account recursively\n *\n * @param accountId - Account ID\n * @returns Array of all descendant accounts\n */\n async getDescendants(accountId: string): Promise<Account[]> {\n const descendants: Account[] = [];\n const queue: string[] = [accountId];\n\n while (queue.length > 0) {\n const currentId = queue.shift();\n if (!currentId) continue;\n\n const children = await this.findChildren(currentId);\n\n for (const child of children) {\n descendants.push(child);\n if (child.id) {\n queue.push(child.id);\n }\n }\n }\n\n return descendants;\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Tenant Helper Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Find all accounts belonging to a specific tenant\n *\n * @param tenantId - Tenant ID\n * @returns Array of tenant's accounts\n */\n async findByTenant(tenantId: string): Promise<Account[]> {\n return this.list({ where: { tenantId } });\n }\n\n /**\n * Find all global accounts (no tenant association).\n *\n * Routes through the shared tenant-global helper so it does not throw under\n * an active tenant context (an explicit `tenant_id IS NULL` filter would be\n * flagged as an isolation violation). (#1600)\n *\n * @returns Array of global accounts\n */\n async findGlobal(): Promise<Account[]> {\n return queryGlobal<Account>(this);\n }\n\n /**\n * Find accounts for a tenant plus all global accounts.\n *\n * Fails closed if an active tenant context requests a different tenant's\n * rows; the admin/system path keeps the cross-tenant capability. (#1600)\n *\n * @param tenantId - Tenant ID\n * @returns Array of tenant's accounts and global accounts\n */\n async findWithGlobals(tenantId: string): Promise<Account[]> {\n return queryWithGlobals<Account>(this, tenantId, 'Account.findWithGlobals');\n }\n}\n","/**\n * JournalEntry model - Individual ledger line\n *\n * The atomic unit of double-entry accounting - a single debit or credit.\n * Each entry belongs to a Journal and references an Account.\n */\n\nimport { foreignKey, SmrtObject, smrt } from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport type { JournalEntryOptions } from '../types';\nimport { Account } from './Account';\n\n@TenantScoped({ mode: 'optional' })\n@smrt({\n api: { include: ['list', 'get'] }, // Created via Journal, not directly\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n})\nexport class JournalEntry extends SmrtObject {\n /**\n * Tenant ID for multi-tenancy support (nullable for global entries)\n */\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n /**\n * Parent journal ID (required)\n */\n @foreignKey('Journal')\n journalId: string = '';\n\n /**\n * Account ID (required)\n */\n // Constructor reference, not the simple name `Account` (also declared by\n // smrt-messages, #3098).\n @foreignKey(Account)\n accountId: string = '';\n\n /**\n * Debit amount (left side)\n */\n debit: number = 0.0;\n\n /**\n * Credit amount (right side)\n */\n credit: number = 0.0;\n\n /**\n * Currency code (e.g., \"USD\", \"CAD\", \"EUR\")\n */\n currency: string = 'USD';\n\n /**\n * Exchange rate to base currency\n */\n exchangeRate: number = 1.0;\n\n /**\n * Line memo/description\n */\n memo: string = '';\n\n /**\n * Extensible metadata\n */\n metadata: Record<string, unknown> = {};\n\n constructor(options: JournalEntryOptions = {}) {\n super(options);\n if (options.journalId !== undefined) this.journalId = options.journalId;\n if (options.accountId !== undefined) this.accountId = options.accountId;\n if (options.debit !== undefined) this.debit = options.debit;\n if (options.credit !== undefined) this.credit = options.credit;\n if (options.currency !== undefined) this.currency = options.currency;\n if (options.exchangeRate !== undefined)\n this.exchangeRate = options.exchangeRate;\n if (options.memo !== undefined) this.memo = options.memo;\n if (options.metadata !== undefined) this.metadata = options.metadata;\n }\n\n /**\n * Validate entry before save\n */\n protected async validateBeforeSave(): Promise<void> {\n await super.validateBeforeSave();\n // Validate amounts are non-negative\n if (this.debit < 0) {\n throw new Error('Debit amount cannot be negative');\n }\n if (this.credit < 0) {\n throw new Error('Credit amount cannot be negative');\n }\n\n // Validate that entry has debit OR credit, not both\n if (this.debit > 0 && this.credit > 0) {\n throw new Error('Entry cannot have both debit and credit amounts');\n }\n\n // Validate that entry has at least one amount\n if (this.debit === 0 && this.credit === 0) {\n throw new Error('Entry must have either a debit or credit amount');\n }\n\n // Validate exchange rate is positive\n if (this.exchangeRate <= 0) {\n throw new Error('Exchange rate must be positive');\n }\n }\n\n /**\n * Check if this is a debit entry\n */\n isDebit(): boolean {\n return this.debit > 0;\n }\n\n /**\n * Check if this is a credit entry\n */\n isCredit(): boolean {\n return this.credit > 0;\n }\n\n /**\n * Get the entry amount (positive value regardless of debit/credit)\n */\n getAmount(): number {\n return this.debit > 0 ? this.debit : this.credit;\n }\n\n /**\n * Get the amount in base currency\n */\n getBaseAmount(): number {\n return this.getAmount() * this.exchangeRate;\n }\n\n /**\n * Get the parent journal\n */\n async getJournal(): Promise<import('./Journal').Journal | null> {\n if (!this.journalId) return null;\n const { JournalCollection } = await import('../collections/Journals');\n const collection = await JournalCollection.create(this.options);\n return await collection.get({ id: this.journalId });\n }\n\n /**\n * Get the account\n */\n async getAccount(): Promise<import('./Account').Account | null> {\n if (!this.accountId) return null;\n const { AccountCollection } = await import('../collections/Accounts');\n const collection = await AccountCollection.create(this.options);\n return await collection.get({ id: this.accountId });\n }\n\n /**\n * Get a formatted description of this entry\n */\n async getDescription(): Promise<string> {\n const account = await this.getAccount();\n const accountName = account?.name || 'Unknown Account';\n const type = this.isDebit() ? 'DR' : 'CR';\n const amount = this.getAmount().toFixed(2);\n\n return `${type} ${accountName}: $${amount}${this.memo ? ` - ${this.memo}` : ''}`;\n }\n}\n","/**\n * JournalEntryCollection - Collection manager for JournalEntry objects\n *\n * Provides querying and balance calculations for ledger entries.\n */\n\nimport { SmrtCollection } from '@happyvertical/smrt-core';\nimport { queryGlobal, queryWithGlobals } from '@happyvertical/smrt-tenancy';\nimport { JournalEntry } from '../models/JournalEntry';\nimport { BALANCE_EPSILON, type TrialBalanceRow } from '../types';\n\nexport class JournalEntryCollection extends SmrtCollection<JournalEntry> {\n static readonly _itemClass = JournalEntry;\n\n /**\n * Find entries by journal\n *\n * @param journalId - Journal ID\n * @returns Array of entries\n */\n async findByJournal(journalId: string): Promise<JournalEntry[]> {\n return await this.list({\n where: { journalId },\n });\n }\n\n /**\n * Find entries by account\n *\n * @param accountId - Account ID\n * @returns Array of entries\n */\n async findByAccount(accountId: string): Promise<JournalEntry[]> {\n return await this.list({\n where: { accountId },\n });\n }\n\n /**\n * Get account balance\n *\n * For debit-normal accounts (Asset, Expense): balance = debits - credits\n * For credit-normal accounts (Liability, Equity, Revenue): balance = credits - debits\n *\n * @param accountId - Account ID\n * @param asOfDate - Optional date to calculate balance as of\n * @returns Account balance\n */\n async getAccountBalance(accountId: string, asOfDate?: Date): Promise<number> {\n // Get entries for this account from posted journals only\n const { JournalCollection } = await import('./Journals');\n const journalCollection = await JournalCollection.create(this.options);\n const { AccountCollection } = await import('./Accounts');\n const accountCollection = await AccountCollection.create(this.options);\n\n // Get the account to determine if it's debit or credit normal\n const account = await accountCollection.get({ id: accountId });\n if (!account) {\n throw new Error(`Account not found: ${accountId}`);\n }\n\n // Get all entries for this account\n const allEntries = await this.findByAccount(accountId);\n\n let totalDebits = 0;\n let totalCredits = 0;\n\n for (const entry of allEntries) {\n // Get the journal to check status and date\n const journal = await journalCollection.get({ id: entry.journalId });\n if (!journal) continue;\n\n // Only include posted journals\n if (!journal.isPosted()) continue;\n\n // Check date if specified\n if (asOfDate && journal.date > asOfDate) continue;\n\n totalDebits += entry.debit;\n totalCredits += entry.credit;\n }\n\n // Calculate balance based on account type\n if (account.isDebitNormal()) {\n // Asset, Expense: increases with debits\n return totalDebits - totalCredits;\n } else {\n // Liability, Equity, Revenue: increases with credits\n return totalCredits - totalDebits;\n }\n }\n\n /**\n * Get trial balance\n *\n * @param asOfDate - Optional date for trial balance\n * @returns Array of trial balance rows\n */\n async getTrialBalance(asOfDate?: Date): Promise<TrialBalanceRow[]> {\n const { AccountCollection } = await import('./Accounts');\n const accountCollection = await AccountCollection.create(this.options);\n\n const accounts = await accountCollection.findActive();\n const rows: TrialBalanceRow[] = [];\n\n for (const account of accounts) {\n if (!account.id) continue;\n\n const balance = await this.getAccountBalance(account.id, asOfDate);\n\n // Skip zero-balance accounts\n if (Math.abs(balance) < BALANCE_EPSILON) continue;\n\n rows.push({\n accountId: account.id,\n accountNumber: account.number,\n accountName: account.name,\n accountType: account.type,\n debitBalance: account.isDebitNormal() && balance > 0 ? balance : 0,\n creditBalance: account.isCreditNormal() && balance > 0 ? balance : 0,\n });\n }\n\n // Sort by account number\n rows.sort((a, b) => a.accountNumber.localeCompare(b.accountNumber));\n\n return rows;\n }\n\n /**\n * Get total debits and credits for a date range\n *\n * @param start - Start date\n * @param end - End date\n * @returns Object with totalDebits and totalCredits\n */\n async getTotalsForDateRange(\n start: Date,\n end: Date,\n ): Promise<{ totalDebits: number; totalCredits: number }> {\n const { JournalCollection } = await import('./Journals');\n const journalCollection = await JournalCollection.create(this.options);\n\n const journals = await journalCollection.findByDateRange(start, end);\n\n let totalDebits = 0;\n let totalCredits = 0;\n\n for (const journal of journals) {\n if (!journal.isPosted()) continue;\n\n const entries = await this.findByJournal(journal.id!);\n for (const entry of entries) {\n totalDebits += entry.debit;\n totalCredits += entry.credit;\n }\n }\n\n return { totalDebits, totalCredits };\n }\n\n /**\n * Get entries for multiple accounts\n *\n * @param accountIds - Array of account IDs\n * @returns Array of entries\n */\n async findByAccounts(accountIds: string[]): Promise<JournalEntry[]> {\n if (accountIds.length === 0) {\n return [];\n }\n\n // Use single query with IN clause to avoid N+1 problem\n return await this.list({\n where: { accountId: accountIds },\n });\n }\n\n /**\n * Get the running balance for an account (list of entries with running total)\n *\n * @param accountId - Account ID\n * @returns Array of entries with running balance\n */\n async getAccountLedger(\n accountId: string,\n ): Promise<Array<{ entry: JournalEntry; runningBalance: number }>> {\n const { JournalCollection } = await import('./Journals');\n const { AccountCollection } = await import('./Accounts');\n const journalCollection = await JournalCollection.create(this.options);\n const accountCollection = await AccountCollection.create(this.options);\n\n const account = await accountCollection.get({ id: accountId });\n if (!account) {\n throw new Error(`Account not found: ${accountId}`);\n }\n\n const entries = await this.findByAccount(accountId);\n const ledger: Array<{ entry: JournalEntry; runningBalance: number }> = [];\n let runningBalance = 0;\n\n // Sort entries by journal date\n const entriesWithJournals = await Promise.all(\n entries.map(async (entry) => ({\n entry,\n journal: await journalCollection.get({ id: entry.journalId }),\n })),\n );\n\n entriesWithJournals.sort((a, b) => {\n if (!a.journal || !b.journal) return 0;\n return a.journal.date.getTime() - b.journal.date.getTime();\n });\n\n for (const { entry, journal } of entriesWithJournals) {\n if (!journal?.isPosted()) continue;\n\n if (account.isDebitNormal()) {\n runningBalance += entry.debit - entry.credit;\n } else {\n runningBalance += entry.credit - entry.debit;\n }\n\n ledger.push({ entry, runningBalance });\n }\n\n return ledger;\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Tenant Helper Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Find all journal entries belonging to a specific tenant\n *\n * @param tenantId - Tenant ID\n * @returns Array of tenant's journal entries\n */\n async findByTenant(tenantId: string): Promise<JournalEntry[]> {\n return this.list({ where: { tenantId } });\n }\n\n /**\n * Find all global journal entries (no tenant association).\n *\n * Routes through the shared tenant-global helper so it does not throw under\n * an active tenant context. (#1600)\n *\n * @returns Array of global journal entries\n */\n async findGlobal(): Promise<JournalEntry[]> {\n return queryGlobal<JournalEntry>(this);\n }\n\n /**\n * Find journal entries for a tenant plus all global entries.\n *\n * Fails closed if an active tenant context requests a different tenant's\n * rows; the admin/system path keeps the cross-tenant capability. (#1600)\n *\n * @param tenantId - Tenant ID\n * @returns Array of tenant's entries and global entries\n */\n async findWithGlobals(tenantId: string): Promise<JournalEntry[]> {\n return queryWithGlobals<JournalEntry>(\n this,\n tenantId,\n 'JournalEntry.findWithGlobals',\n );\n }\n}\n","/**\n * Journal model - Financial event container\n *\n * Represents a single, discrete financial event.\n * Contains one or more JournalEntry records that must balance (debits = credits).\n */\n\nimport { SmrtObject, smrt } from '@happyvertical/smrt-core';\nimport { resolvePrompt } from '@happyvertical/smrt-prompts';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport {\n promptMessageOptions,\n smrtLedgersJournalSummarizePrompt,\n} from '../prompts';\nimport {\n BALANCE_EPSILON,\n type JournalEntryData,\n type JournalOptions,\n type JournalStatus,\n} from '../types';\n\n@TenantScoped({ mode: 'optional' })\n@smrt({\n api: { include: ['list', 'get', 'create'] }, // No update/delete - immutable after posting\n mcp: { include: ['list', 'get', 'create'] },\n cli: { skipApiCheck: true },\n})\nexport class Journal extends SmrtObject {\n /**\n * Tenant ID for multi-tenancy support (nullable for global journals)\n */\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n /**\n * Journal number (auto-generated sequence, e.g., \"JNL-0001\")\n */\n number: string = '';\n\n /**\n * Transaction date\n */\n date: Date = new Date();\n\n /**\n * Description of the financial event\n */\n description: string = '';\n\n /**\n * Source module that created this journal (e.g., \"smrt-commerce\", \"manual\")\n */\n sourceModule: string = '';\n\n /**\n * External reference (e.g., order ID, invoice number)\n */\n sourceRef: string | null = null;\n\n /**\n * Journal status: draft, posted, voided\n */\n status: JournalStatus = 'draft';\n\n /**\n * When the journal was posted (finalized)\n */\n postedAt: Date | null = null;\n\n /**\n * When the journal was voided\n */\n voidedAt: Date | null = null;\n\n /**\n * Reason for voiding (if voided)\n */\n voidReason: string | null = null;\n\n /**\n * Extensible metadata\n */\n metadata: Record<string, unknown> = {};\n\n constructor(options: JournalOptions = {}) {\n super(options);\n if (options.number !== undefined) this.number = options.number;\n if (options.date !== undefined) this.date = options.date;\n if (options.description !== undefined)\n this.description = options.description;\n if (options.sourceModule !== undefined)\n this.sourceModule = options.sourceModule;\n if (options.sourceRef !== undefined) this.sourceRef = options.sourceRef;\n if (options.status !== undefined) this.status = options.status;\n if (options.postedAt !== undefined) this.postedAt = options.postedAt;\n if (options.voidedAt !== undefined) this.voidedAt = options.voidedAt;\n if (options.voidReason !== undefined) this.voidReason = options.voidReason;\n if (options.metadata !== undefined) this.metadata = options.metadata;\n }\n\n /**\n * Check if journal is in draft status\n */\n isDraft(): boolean {\n return this.status === 'draft';\n }\n\n /**\n * Check if journal has been posted\n */\n isPosted(): boolean {\n return this.status === 'posted';\n }\n\n /**\n * Check if journal has been voided\n */\n isVoided(): boolean {\n return this.status === 'voided';\n }\n\n /**\n * Check if journal can be modified\n */\n isEditable(): boolean {\n return this.status === 'draft';\n }\n\n /**\n * Get all entries for this journal\n */\n async getEntries(): Promise<import('./JournalEntry').JournalEntry[]> {\n if (!this.id) return [];\n const { JournalEntryCollection } = await import(\n '../collections/JournalEntries'\n );\n const collection = await JournalEntryCollection.create(this.options);\n return await collection.findByJournal(this.id);\n }\n\n /**\n * Calculate total debits\n */\n async getTotalDebits(): Promise<number> {\n const entries = await this.getEntries();\n return entries.reduce((sum, entry) => sum + entry.debit, 0);\n }\n\n /**\n * Calculate total credits\n */\n async getTotalCredits(): Promise<number> {\n const entries = await this.getEntries();\n return entries.reduce((sum, entry) => sum + entry.credit, 0);\n }\n\n /**\n * Check if journal entries are balanced (debits = credits)\n */\n async isBalanced(): Promise<boolean> {\n const debits = await this.getTotalDebits();\n const credits = await this.getTotalCredits();\n return Math.abs(debits - credits) < BALANCE_EPSILON;\n }\n\n /**\n * Add an entry to this journal (only if draft)\n */\n async addEntry(data: JournalEntryData): Promise<void> {\n if (!this.id) {\n throw new Error('Journal must be saved before adding entries');\n }\n if (!this.isEditable()) {\n throw new Error('Cannot add entries to a posted or voided journal');\n }\n\n const { JournalEntryCollection } = await import(\n '../collections/JournalEntries'\n );\n const collection = await JournalEntryCollection.create(this.options);\n const entry = await collection.create({\n journalId: this.id,\n accountId: data.accountId,\n debit: data.debit || 0,\n credit: data.credit || 0,\n currency: data.currency || 'USD',\n exchangeRate: data.exchangeRate || 1.0,\n memo: data.memo || '',\n });\n await entry.save();\n }\n\n /**\n * Post the journal (finalize and make immutable)\n */\n async post(): Promise<void> {\n if (!this.isDraft()) {\n throw new Error('Only draft journals can be posted');\n }\n\n const balanced = await this.isBalanced();\n if (!balanced) {\n const debits = await this.getTotalDebits();\n const credits = await this.getTotalCredits();\n throw new Error(\n `Journal is not balanced. Debits: ${debits}, Credits: ${credits}`,\n );\n }\n\n const entries = await this.getEntries();\n if (entries.length === 0) {\n throw new Error('Journal must have at least one entry');\n }\n\n this.status = 'posted';\n this.postedAt = new Date();\n await this.save();\n }\n\n /**\n * Void the journal (mark as cancelled with reason)\n */\n async void(reason: string): Promise<void> {\n if (this.isVoided()) {\n throw new Error('Journal is already voided');\n }\n\n this.status = 'voided';\n this.voidedAt = new Date();\n this.voidReason = reason;\n await this.save();\n }\n\n /**\n * AI-powered: Generate a summary of this journal.\n *\n * Uses the `smrtLedgers.journal.summarize` prompt registered via\n * `@happyvertical/smrt-prompts`, allowing tenant- or instance-level\n * overrides of the template, model, and parameters at runtime.\n *\n * Only non-PII journal fields (number, date, description, status, balanced\n * flag) plus aggregate totals and entry count are sent to the AI provider.\n * Internal foreign-key fields (tenantId, sourceRef, individual entry\n * account IDs) and the extensible `metadata` blob are intentionally\n * excluded.\n *\n * @returns Generated summary text\n */\n async summarize(): Promise<string> {\n const entries = await this.getEntries();\n const debits = await this.getTotalDebits();\n const balanced = await this.isBalanced();\n\n // Resolve `db` from either the canonical `db` option or its `persistence`\n // alias. SmrtClass maps `persistence → db` lazily during `initialize()`,\n // so on a freshly-constructed Journal that has not yet been initialized,\n // `this.options.db` may be undefined while `this.options.persistence` is\n // set. Falling back here ensures stored app- and tenant-level prompt\n // overrides in `_smrt_prompt_overrides` are honored on the first call —\n // before `getAiClient()` triggers full initialization further below.\n const db = this.options.db ?? this.options.persistence;\n\n const resolvedPrompt = await resolvePrompt(\n smrtLedgersJournalSummarizePrompt.key,\n {\n db,\n tenantId: this.tenantId,\n variables: {\n journalNumber: this.number || '',\n journalDate: this.date.toISOString().split('T')[0],\n journalDescription: this.description || '',\n journalStatus: this.status || '',\n // Currency prefix folded into the value rather than the template\n // — see the `smrtLedgersJournalSummarizePrompt` comment block.\n journalTotal: `$${debits.toFixed(2)}`,\n entryCount: String(entries.length),\n journalBalanced: balanced ? 'Yes' : 'No',\n },\n },\n );\n\n const ai = await this.getAiClient();\n const response = await ai.message(\n resolvedPrompt.text,\n promptMessageOptions(resolvedPrompt.ai),\n );\n\n return response.trim();\n }\n}\n","/**\n * JournalCollection - Collection manager for Journal objects\n *\n * Provides querying and operations for financial journals.\n */\n\nimport { SmrtCollection } from '@happyvertical/smrt-core';\nimport { queryGlobal, queryWithGlobals } from '@happyvertical/smrt-tenancy';\nimport { Journal } from '../models/Journal';\nimport {\n BALANCE_EPSILON,\n type CreateJournalData,\n type JournalStatus,\n} from '../types';\n\nexport class JournalCollection extends SmrtCollection<Journal> {\n static readonly _itemClass = Journal;\n\n /**\n * Generate next journal number\n *\n * Uses timestamp and random component to avoid collisions\n * in concurrent environments without relying on shared state.\n */\n private generateJournalNumber(): string {\n const timestamp = Date.now().toString(36);\n const randomPart = Math.random().toString(36).slice(2, 6);\n return `JNL-${timestamp}-${randomPart}`;\n }\n\n /**\n * Find journal by number\n *\n * @param number - Journal number\n * @returns Journal or null\n */\n async findByNumber(number: string): Promise<Journal | null> {\n const journals = await this.list({\n where: { number },\n limit: 1,\n });\n return journals[0] || null;\n }\n\n /**\n * Find journals by date range\n *\n * @param start - Start date\n * @param end - End date\n * @returns Array of journals\n */\n async findByDateRange(start: Date, end: Date): Promise<Journal[]> {\n return await this.list({\n where: {\n 'date >=': start.toISOString(),\n 'date <=': end.toISOString(),\n },\n orderBy: 'date ASC',\n });\n }\n\n /**\n * Find journals by source module\n *\n * @param sourceModule - Source module name\n * @returns Array of journals\n */\n async findBySource(sourceModule: string): Promise<Journal[]> {\n return await this.list({\n where: { sourceModule },\n orderBy: 'date DESC',\n });\n }\n\n /**\n * Find journals by status\n *\n * @param status - Journal status\n * @returns Array of journals\n */\n async findByStatus(status: JournalStatus): Promise<Journal[]> {\n return await this.list({\n where: { status },\n orderBy: 'date DESC',\n });\n }\n\n /**\n * Find draft journals\n *\n * @returns Array of draft journals\n */\n async findDrafts(): Promise<Journal[]> {\n return await this.findByStatus('draft');\n }\n\n /**\n * Find posted journals\n *\n * @returns Array of posted journals\n */\n async findPosted(): Promise<Journal[]> {\n return await this.findByStatus('posted');\n }\n\n /**\n * Create a complete journal with entries\n *\n * @param data - Journal data with entries\n * @returns Created journal\n */\n async createWithEntries(data: CreateJournalData): Promise<Journal> {\n // Validate entries balance\n let totalDebits = 0;\n let totalCredits = 0;\n\n for (const entry of data.entries) {\n totalDebits += entry.debit || 0;\n totalCredits += entry.credit || 0;\n }\n\n if (Math.abs(totalDebits - totalCredits) >= BALANCE_EPSILON) {\n throw new Error(\n `Entries are not balanced. Debits: ${totalDebits}, Credits: ${totalCredits}`,\n );\n }\n\n if (data.entries.length === 0) {\n throw new Error('Journal must have at least one entry');\n }\n\n // Create journal\n const journalNumber = await this.generateJournalNumber();\n const journal = await this.create({\n number: journalNumber,\n date: data.date || new Date(),\n description: data.description,\n sourceModule: data.sourceModule || 'manual',\n sourceRef: data.sourceRef || null,\n metadata: data.metadata || {},\n });\n await journal.save();\n\n // Create entries\n for (const entryData of data.entries) {\n await journal.addEntry(entryData);\n }\n\n return journal;\n }\n\n /**\n * Post a journal by ID\n *\n * @param journalId - Journal ID\n * @returns Posted journal\n */\n async post(journalId: string): Promise<Journal> {\n const journal = await this.get({ id: journalId });\n if (!journal) {\n throw new Error(`Journal not found: ${journalId}`);\n }\n await journal.post();\n return journal;\n }\n\n /**\n * Void a journal by ID\n *\n * @param journalId - Journal ID\n * @param reason - Reason for voiding\n * @returns Voided journal\n */\n async void(journalId: string, reason: string): Promise<Journal> {\n const journal = await this.get({ id: journalId });\n if (!journal) {\n throw new Error(`Journal not found: ${journalId}`);\n }\n await journal.void(reason);\n return journal;\n }\n\n /**\n * Find journals by source reference\n *\n * @param sourceRef - External reference\n * @returns Array of journals\n */\n async findBySourceRef(sourceRef: string): Promise<Journal[]> {\n return await this.list({\n where: { sourceRef },\n orderBy: 'date DESC',\n });\n }\n\n /**\n * Get journals for a specific month\n *\n * @param year - Year\n * @param month - Month (1-12)\n * @returns Array of journals\n */\n async findByMonth(year: number, month: number): Promise<Journal[]> {\n const start = new Date(year, month - 1, 1);\n const end = new Date(year, month, 0, 23, 59, 59, 999);\n return await this.findByDateRange(start, end);\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Tenant Helper Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Find all journals belonging to a specific tenant\n *\n * @param tenantId - Tenant ID\n * @returns Array of tenant's journals\n */\n async findByTenant(tenantId: string): Promise<Journal[]> {\n return this.list({ where: { tenantId } });\n }\n\n /**\n * Find all global journals (no tenant association).\n *\n * Routes through the shared tenant-global helper so it does not throw under\n * an active tenant context. (#1600)\n *\n * @returns Array of global journals\n */\n async findGlobal(): Promise<Journal[]> {\n return queryGlobal<Journal>(this);\n }\n\n /**\n * Find journals for a tenant plus all global journals.\n *\n * Fails closed if an active tenant context requests a different tenant's\n * rows; the admin/system path keeps the cross-tenant capability. (#1600)\n *\n * @param tenantId - Tenant ID\n * @returns Array of tenant's journals and global journals\n */\n async findWithGlobals(tenantId: string): Promise<Journal[]> {\n return queryWithGlobals<Journal>(this, tenantId, 'Journal.findWithGlobals');\n }\n}\n","/**\n * One-time move of ledger accounts out of the shared `accounts` table (#3098).\n *\n * Until 0.51.24 the ledger `Account` derived the table name `accounts`, which\n * smrt-messages' unrelated `Account` also derives. A database may therefore\n * hold ledger accounts in `accounts` alone (ledgers only), or mixed with\n * messaging accounts in one union table (both packages, after `db:migrate`).\n * The ledger model now owns `ledger_accounts`; this migration moves the\n * existing ledger rows there, detaches the foreign keys that pointed ledger\n * references at `accounts`, and leaves messaging rows where they are.\n *\n * Operator sequence (maintenance window, PostgreSQL):\n * 1. `smrt db:migrate` — creates `ledger_accounts` from the manifest. It\n * reports, and does not apply, the retargeted `journal_entries.account_id`\n * foreign key while the old one still points at `accounts`.\n * 2. `smrt db:migrate-ledger-accounts` — this module.\n * 3. `smrt db:migrate` — adds the foreign keys onto `ledger_accounts`.\n */\n\nimport { detectEngine, ObjectRegistry } from '@happyvertical/smrt-core';\nimport {\n BackfillTracker,\n type DatabaseInterface,\n} from '@happyvertical/smrt-core/migrations';\n\nexport const LEDGER_ACCOUNTS_TABLE = 'ledger_accounts';\nexport const LEGACY_ACCOUNTS_TABLE = 'accounts';\nexport const LEDGER_ACCOUNTS_TABLE_MOVE =\n '@happyvertical/smrt-ledgers:ledger-accounts-table:v1';\n\n/**\n * Columns that only the legacy ledger model put on `accounts`. Their presence\n * identifies a table that may hold ledger rows; this is a fact about the\n * pre-#3098 data being migrated, not a schema definition.\n */\nconst LEGACY_LEDGER_SIGNATURE = ['number', 'type'] as const;\n\n/** The STI discriminator smrt-messages writes on every messaging account. */\nconst STI_DISCRIMINATOR = '_meta_type';\n\n/** Messaging columns that a ledger row never populates. */\nconst MESSAGING_MARKERS = ['provider_type', 'channel_type'] as const;\n\nexport interface LedgerAccountsTableMoveOptions {\n backfillName?: string;\n packageName?: string;\n /** PostgreSQL `lock_timeout`, milliseconds (default 30000). */\n lockTimeout?: number;\n /** PostgreSQL `statement_timeout`, milliseconds (default 60000). */\n statementTimeout?: number;\n}\n\nexport interface LedgerAccountsTableMovePlan {\n /** Whether a legacy `accounts` table with ledger columns exists. */\n legacyTable: boolean;\n /** Ledger rows still in `accounts` that this migration would move. */\n pending: number;\n /** Messaging rows that stay in `accounts`. */\n messagingRows: number;\n}\n\nexport interface LedgerAccountsTableMoveResult {\n ran: boolean;\n moved: number;\n /** Rows (messaging accounts) left in `accounts`. */\n remainingLegacyRows: number;\n /** `table.column` foreign keys detached from `accounts`. */\n detachedForeignKeys: string[];\n}\n\nexport class LedgerAccountsTableMoveError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'LedgerAccountsTableMoveError';\n }\n}\n\ntype Queryable = Pick<DatabaseInterface, 'query'>;\n\ninterface LegacyShape {\n columns: Set<string>;\n hasDiscriminator: boolean;\n}\n\nfunction quote(identifier: string): string {\n return `\"${identifier.replace(/\"/g, '\"\"')}\"`;\n}\n\nfunction timeout(value: number | undefined, fallback: number): string {\n const milliseconds = value ?? fallback;\n if (!Number.isInteger(milliseconds) || milliseconds < 0) {\n throw new LedgerAccountsTableMoveError(\n 'Migration timeout must be a non-negative integer',\n );\n }\n return `${milliseconds}ms`;\n}\n\nfunction assertPostgres(db: DatabaseInterface): void {\n const withConfig = db as DatabaseInterface & {\n type?: string;\n config?: { type?: string; url?: string };\n };\n const engine = detectEngine(\n db.url || withConfig.config?.url || '',\n withConfig.type || withConfig.config?.type,\n );\n if (engine !== 'postgres') {\n throw new LedgerAccountsTableMoveError(\n 'The ledger accounts table move supports PostgreSQL only. For a SQLite database whose `accounts` table holds only ledger accounts, run `ALTER TABLE accounts RENAME TO ledger_accounts` before `db:migrate`; see the smrt-ledgers README.',\n );\n }\n}\n\nasync function readLegacyShape(\n db: DatabaseInterface,\n): Promise<LegacyShape | null> {\n const schema = await db.getTableSchema?.(LEGACY_ACCOUNTS_TABLE);\n if (!schema) return null;\n const columns = new Set(Object.keys(schema.columns));\n if (!LEGACY_LEDGER_SIGNATURE.every((column) => columns.has(column))) {\n return null;\n }\n return { columns, hasDiscriminator: columns.has(STI_DISCRIMINATOR) };\n}\n\n/** SQL predicate selecting the ledger rows of the legacy table. */\nfunction ledgerRowPredicate(shape: LegacyShape): string {\n return shape.hasDiscriminator\n ? `(${quote(STI_DISCRIMINATOR)} IS NULL OR ${quote(STI_DISCRIMINATOR)} = '')`\n : 'TRUE';\n}\n\nasync function count(db: Queryable, where: string): Promise<number> {\n const result = await db.query(\n `SELECT COUNT(*) AS n FROM ${quote(LEGACY_ACCOUNTS_TABLE)} WHERE ${where}`,\n );\n return Number((result.rows[0] as { n: number | string }).n);\n}\n\nasync function classify(\n db: Queryable,\n shape: LegacyShape,\n): Promise<{ pending: number; messagingRows: number }> {\n const ledger = ledgerRowPredicate(shape);\n const pending = await count(db, ledger);\n const messagingRows = shape.hasDiscriminator\n ? await count(db, `NOT ${ledger}`)\n : 0;\n\n // Refuse rows whose owner is not certain rather than guess. A messaging\n // row never carries a ledger account number; a ledger row never carries a\n // messaging provider or channel.\n if (shape.hasDiscriminator) {\n const ledgerLooking = await count(\n db,\n `NOT ${ledger} AND COALESCE(${quote('number')}, '') <> ''`,\n );\n const markers = MESSAGING_MARKERS.filter((column) =>\n shape.columns.has(column),\n );\n const messagingLooking =\n markers.length === 0\n ? 0\n : await count(\n db,\n `${ledger} AND (${markers\n .map((column) => `COALESCE(${quote(column)}, '') <> ''`)\n .join(' OR ')})`,\n );\n if (ledgerLooking > 0 || messagingLooking > 0) {\n throw new LedgerAccountsTableMoveError(\n `Refusing to move ledger accounts: ${ledgerLooking} messaging row(s) carry a ledger account number and ${messagingLooking} ledger row(s) carry a messaging provider or channel in \"${LEGACY_ACCOUNTS_TABLE}\". Resolve their ownership by hand, then rerun.`,\n );\n }\n }\n return { pending, messagingRows };\n}\n\n/**\n * Registered foreign keys by the table they reference: `table.column` keys\n * the manifests point at `ledger_accounts` (the references that pointed at\n * `accounts` before #3098) and at `accounts` (messaging's own references).\n */\nexport function registeredReferenceColumns(): RegisteredReferences {\n const ledger = new Set<string>();\n const accounts = new Set<string>();\n const schemas = ObjectRegistry.getAllSchemasAsDefinitions();\n for (const [tableName, schema] of Object.entries(schemas)) {\n for (const [columnName, column] of Object.entries(schema.columns ?? {})) {\n const target = (column as { foreignKey?: { table?: string } }).foreignKey\n ?.table;\n if (target === LEDGER_ACCOUNTS_TABLE) {\n ledger.add(`${tableName}.${columnName}`);\n } else if (target === LEGACY_ACCOUNTS_TABLE) {\n accounts.add(`${tableName}.${columnName}`);\n }\n }\n }\n return { ledger, accounts };\n}\n\n/** Registered `table.column` references, by the table they point at. */\nexport interface RegisteredReferences {\n ledger: Set<string>;\n accounts: Set<string>;\n}\n\n/** One foreign key into the legacy table (`column` is its first column). */\nexport interface LegacyForeignKey {\n constraint: string;\n table: string;\n column: string;\n arity: number;\n}\n\n/** What the move does with each foreign key into the legacy table. */\nexport interface ForeignKeyDisposition {\n /** Composite keys: never a registered single-column reference. */\n composite: LegacyForeignKey[];\n /** Single-column keys no registered model declares. */\n undeclared: LegacyForeignKey[];\n /** Ledger references: detached, re-added against ledger_accounts. */\n detach: LegacyForeignKey[];\n /** Kept (messaging's and the table's own parent link): must not reference a moving row. */\n keep: LegacyForeignKey[];\n}\n\n/**\n * Sort every foreign key into the legacy table before anything is written.\n * A constraint no registered model declares would keep pointing at accounts\n * after the move (blocking later writes), and a CASCADE or SET NULL action on\n * it would delete or clear rows instead of refusing, so the move refuses\n * `composite` and `undeclared` outright (#3098).\n */\nexport function classifyForeignKeys(\n inbound: readonly LegacyForeignKey[],\n references: RegisteredReferences,\n): ForeignKeyDisposition {\n const disposition: ForeignKeyDisposition = {\n composite: [],\n undeclared: [],\n detach: [],\n keep: [],\n };\n for (const fk of inbound) {\n const key = `${fk.table}.${fk.column}`;\n if (fk.arity > 1) disposition.composite.push(fk);\n else if (references.ledger.has(key)) disposition.detach.push(fk);\n else if (fk.table === LEGACY_ACCOUNTS_TABLE || references.accounts.has(key))\n disposition.keep.push(fk);\n else disposition.undeclared.push(fk);\n }\n return disposition;\n}\n\n/** The refusal for foreign keys the move cannot account for, if any. */\nexport function foreignKeyRefusal(\n disposition: ForeignKeyDisposition,\n): string | undefined {\n if (disposition.composite.length > 0) {\n return `Composite foreign key(s) ${disposition.composite.map((fk) => `${fk.constraint} on ${fk.table} (${fk.arity} columns)`).join(', ')} reference \"${LEGACY_ACCOUNTS_TABLE}\"; no model can declare one, so the move cannot carry it. Nothing was moved. Drop it, or replace it with a single-column reference, then rerun.`;\n }\n if (disposition.undeclared.length > 0) {\n return `Foreign key(s) ${disposition.undeclared.map((fk) => `${fk.table}.${fk.column}`).join(', ')} reference \"${LEGACY_ACCOUNTS_TABLE}\" but no registered model declares them; nothing was moved. Run the move from the application whose models declare them, or retarget each to \"${LEDGER_ACCOUNTS_TABLE}\" (or drop it) by hand, then rerun.`;\n }\n return undefined;\n}\n\n/**\n * The SELECT list copying legacy columns into ledger_accounts: values as they\n * are, converting through text only a column whose legacy type differs from\n * the manifest's (e.g. TEXT ids where ledger_accounts declares UUID).\n */\nexport function copySelectList(\n columns: readonly string[],\n targetTypes: Readonly<Record<string, string | undefined>>,\n legacyTypes: Readonly<Record<string, string | undefined>>,\n): string {\n return columns\n .map((column) => {\n const to = targetTypes[column];\n return sameType(legacyTypes[column], to)\n ? quote(column)\n : `CAST(CAST(${quote(column)} AS TEXT) AS ${targetType(to)})`;\n })\n .join(', ');\n}\n\n/**\n * Every foreign key into the legacy table, composite ones included (`arity`\n * > 1): the move must account for all of them before it writes (#3098).\n */\nasync function legacyForeignKeys(db: Queryable): Promise<LegacyForeignKey[]> {\n const result = await db.query(\n `SELECT con.conname AS constraint_name,\n rel.relname AS table_name,\n att.attname AS column_name,\n array_length(con.conkey, 1) AS arity\n FROM pg_constraint con\n JOIN pg_class rel ON rel.oid = con.conrelid\n JOIN pg_attribute att\n ON att.attrelid = con.conrelid AND att.attnum = con.conkey[1]\n WHERE con.contype = 'f'\n AND con.confrelid = to_regclass(?)\n ORDER BY rel.relname, con.conname`,\n quote(LEGACY_ACCOUNTS_TABLE),\n );\n return (\n result.rows as Array<{\n constraint_name: string;\n table_name: string;\n column_name: string;\n arity: number | string;\n }>\n ).map((row) => ({\n constraint: row.constraint_name,\n table: row.table_name,\n column: row.column_name,\n arity: Number(row.arity),\n }));\n}\n\n/**\n * Inspect the legacy table without changing anything. Read-only portable SQL,\n * so it also reports what a SQLite database would need moved.\n */\nexport async function planLedgerAccountsTableMove(\n db: DatabaseInterface,\n): Promise<LedgerAccountsTableMovePlan> {\n const shape = await readLegacyShape(db);\n if (!shape) return { legacyTable: false, pending: 0, messagingRows: 0 };\n return { legacyTable: true, ...(await classify(db, shape)) };\n}\n\n/**\n * Move ledger accounts from `accounts` into `ledger_accounts` in one\n * transaction under an exclusive lock. Operator-invoked and idempotent: a\n * rerun, or a database that never had ledger rows in `accounts`, is a no-op.\n */\nexport async function migrateLedgerAccountsTable(\n db: DatabaseInterface,\n options: LedgerAccountsTableMoveOptions = {},\n): Promise<LedgerAccountsTableMoveResult> {\n assertPostgres(db);\n if (!db.transaction) {\n throw new LedgerAccountsTableMoveError(\n 'The ledger accounts table move requires a transaction-capable PostgreSQL adapter',\n );\n }\n const noop = (remainingLegacyRows = 0): LedgerAccountsTableMoveResult => ({\n ran: false,\n moved: 0,\n remainingLegacyRows,\n detachedForeignKeys: [],\n });\n\n const shape = await readLegacyShape(db);\n if (!shape) return noop();\n const target = await db.getTableSchema?.(LEDGER_ACCOUNTS_TABLE);\n if (!target) {\n throw new LedgerAccountsTableMoveError(\n `\"${LEDGER_ACCOUNTS_TABLE}\" does not exist; run db:migrate before moving ledger accounts`,\n );\n }\n const legacy = await db.getTableSchema?.(LEGACY_ACCOUNTS_TABLE);\n const copyColumns = Object.keys(target.columns).filter((column) =>\n shape.columns.has(column),\n );\n const references = registeredReferenceColumns();\n\n const tracker = new BackfillTracker({ db });\n await tracker.initialize();\n const backfillName = options.backfillName ?? LEDGER_ACCOUNTS_TABLE_MOVE;\n\n return db.transaction(async (tx) => {\n BackfillTracker.inheritInitialization(tx, db);\n const transactionTracker = new BackfillTracker({ db: tx });\n await tx.query(\n `SET LOCAL lock_timeout = '${timeout(options.lockTimeout, 30_000)}'`,\n );\n await tx.query(\n `SET LOCAL statement_timeout = '${timeout(options.statementTimeout, 60_000)}'`,\n );\n await tx.query(\n `LOCK TABLE ${quote(LEGACY_ACCOUNTS_TABLE)}, ${quote(LEDGER_ACCOUNTS_TABLE)} IN ACCESS EXCLUSIVE MODE`,\n );\n\n const { pending, messagingRows } = await classify(tx, shape);\n if (await transactionTracker.isApplied(backfillName)) {\n if (pending > 0) {\n throw new LedgerAccountsTableMoveError(\n `The ledger accounts table move is recorded as applied but \"${LEGACY_ACCOUNTS_TABLE}\" still holds ${pending} ledger row(s); refusing inconsistent state`,\n );\n }\n return noop(messagingRows);\n }\n\n const ledger = ledgerRowPredicate(shape);\n // Compare through text: a legacy table may still carry TEXT ids where\n // ledger_accounts declares UUID (the copy below converts the same way).\n const clash = await tx.query(\n `SELECT COUNT(*) AS n FROM ${quote(LEGACY_ACCOUNTS_TABLE)} legacy\n WHERE ${ledger}\n AND EXISTS (SELECT 1 FROM ${quote(LEDGER_ACCOUNTS_TABLE)} moved\n WHERE CAST(moved.id AS TEXT) = CAST(legacy.id AS TEXT))`,\n );\n if (Number((clash.rows[0] as { n: number | string }).n) > 0) {\n throw new LedgerAccountsTableMoveError(\n `\"${LEDGER_ACCOUNTS_TABLE}\" already holds ids of ledger rows still in \"${LEGACY_ACCOUNTS_TABLE}\"; refusing to overwrite`,\n );\n }\n\n // Account for every foreign key into accounts before writing anything:\n // refuse what the move cannot carry, and a kept constraint may not\n // reference a row that moves.\n const disposition = classifyForeignKeys(\n await legacyForeignKeys(tx),\n references,\n );\n const refusal = foreignKeyRefusal(disposition);\n if (refusal) throw new LedgerAccountsTableMoveError(refusal);\n for (const fk of disposition.keep) {\n const survivor =\n fk.table === LEGACY_ACCOUNTS_TABLE ? ` AND NOT ${ledger}` : '';\n const pointing = await tx.query(\n `SELECT COUNT(*) AS n FROM ${quote(fk.table)}\n WHERE ${quote(fk.column)} IN\n (SELECT id FROM ${quote(LEGACY_ACCOUNTS_TABLE)} WHERE ${ledger})${survivor}`,\n );\n if (Number((pointing.rows[0] as { n: number | string }).n) > 0) {\n throw new LedgerAccountsTableMoveError(\n `${fk.table}.${fk.column} references ledger accounts in \"${LEGACY_ACCOUNTS_TABLE}\" but is not a ledger reference; nothing was moved. Resolve those rows by hand, then rerun.`,\n );\n }\n }\n\n const selectList = copySelectList(\n copyColumns,\n columnTypes(target),\n columnTypes(legacy),\n );\n await tx.query(\n `INSERT INTO ${quote(LEDGER_ACCOUNTS_TABLE)} (${copyColumns\n .map(quote)\n .join(', ')})\n SELECT ${selectList} FROM ${quote(LEGACY_ACCOUNTS_TABLE)} WHERE ${ledger}`,\n );\n\n // Detach the ledger references (journal entries, and anything else the\n // manifests now point at ledger_accounts) from the legacy table. The\n // next db:migrate adds them against ledger_accounts. References owned by\n // messaging (emails, messages, routes) keep pointing at accounts.\n const detached: string[] = [];\n for (const foreignKey of disposition.detach) {\n await tx.query(\n `ALTER TABLE ${quote(foreignKey.table)} DROP CONSTRAINT ${quote(foreignKey.constraint)}`,\n );\n detached.push(`${foreignKey.table}.${foreignKey.column}`);\n }\n\n // Every remaining constraint was checked above; a violation here is a\n // concurrent change the lock did not cover and rolls the move back.\n await tx.query(\n `DELETE FROM ${quote(LEGACY_ACCOUNTS_TABLE)} WHERE ${ledger}`,\n );\n\n await transactionTracker.recordApplied(backfillName, {\n description:\n 'Moved ledger accounts from the shared accounts table to ledger_accounts (#3098).',\n packageName: options.packageName ?? '@happyvertical/smrt-ledgers',\n });\n return {\n ran: true,\n moved: pending,\n remainingLegacyRows: messagingRows,\n detachedForeignKeys: detached,\n };\n });\n}\n\nconst SQL_TYPE = /^[A-Za-z][A-Za-z0-9 _]*(\\(\\d+(,\\s*\\d+)?\\))?(\\[\\])?$/;\n\nfunction columnTypes(\n schema: { columns: Record<string, { type?: string }> } | null | undefined,\n): Record<string, string | undefined> {\n return Object.fromEntries(\n Object.entries(schema?.columns ?? {}).map(([name, column]) => [\n name,\n column.type,\n ]),\n );\n}\n\nfunction sameType(from: string | undefined, to: string | undefined): boolean {\n return (\n from !== undefined &&\n to !== undefined &&\n from.trim().toLowerCase() === to.trim().toLowerCase()\n );\n}\n\nfunction targetType(declared: string | undefined): string {\n const type = declared?.trim();\n if (!type || !SQL_TYPE.test(type)) {\n throw new LedgerAccountsTableMoveError(\n `Cannot copy into \"${LEDGER_ACCOUNTS_TABLE}\": unsupported live column type ${JSON.stringify(type)}`,\n );\n }\n return type;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AC8BO,IAAM,oCAAoC,aAAa;CAC5D,KAAK;CACL,UAAU;;;;;;;;CAQV,UAAU;EACR,UAAU;EACV,SAAS;EACT,OAAO;EACP,QAAQ;CACV;AACF,CAAC;AAEM,SAAS,qBAAqB,IAAsB;CACzD,OAAO;EACL,GAAI,GAAG,UAAU,CAAC;EAClB,GAAI,GAAG,QAAQ,EAAE,OAAO,GAAG,MAAM,IAAI,CAAC;EACtC,GAAI,OAAO,GAAG,gBAAgB,WAC1B,EAAE,aAAa,GAAG,YAAY,IAC9B,CAAC;EACL,GAAI,OAAO,GAAG,cAAc,WAAW,EAAE,WAAW,GAAG,UAAU,IAAI,CAAC;CACxE;AACF;;;;AC9CO,IAAM,oBAAN,cAAgC,eAAwB;CAC7D,OAAgB,aAAa;;;;;;;CAQ7B,MAAM,aAAa,QAAyC;EAK1D,QAAO,MAJgB,KAAK,KAAK;GAC/B,OAAO,EAAE,OAAO;GAChB,OAAO;EACT,CAAC,EAAA,CACe,MAAM;CACxB;;;;;;;CAQA,MAAM,WA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AM,WAAW,KAAK,EAAC,mBAAoB,MAAM,WAAW,UAAU,GACvF;GACA,SAAS,KAAK,GAAG,WAAW,MAAK,GAAI,WAAW,QAAQ;EAC1D;EAIA,MAAM,GAAG,MACP,eAAe,MAAM,qBAAqB,EAAC,SAAU,QACvD;EAEA,MAAM,mBAAmB,cAAc,cAAc;GACnD,aACE;GACF,aAAa,QAAQ,eAAe;EACtC,CAAC;EACD,OAAO;GACL,KAAK;GACL,OAAO;GACP,qBAAqB;GACrB,qBAAqB;EACvB;CACF,CAAC;AACH;AAEA,IAAM,WAAW;AAEjB,SAAS,YACP,QACoC;CACpC,OAAO,OAAO,YACZ,OAAO,QAAQ,QAAQ,WAAW,CAAC,CAAC,CAAA,CAAE,KAAK,CAAC,MAAM,YAAY,CAC5D,MACA,OAAO,IACT,CAAC,CACH;AACF;AAEA,SAAS,SAAS,MAA0B,IAAiC;CAC3E,OACE,SAAS,KAAA,KACT,OAAO,KAAA,KACP,KAAK,KAAK,CAAA,CAAE,YAAY,MAAM,GAAG,KAAK,CAAA,CAAE,YAAY;AAExD;AAEA,SAAS,WAAW,UAAsC;CACxD,MAAM,OAAO,UAAU,KAAK;CAC5B,IAAI,CAAC,QAAQ,CAAC,SAAS,KAAK,IAAI,GAC9B,MAAM,IAAI,6BACR,qBAAqB,sBAAqB,kCAAmC,KAAK,UAAU,IAAI,GAClG;CAEF,OAAO;AACT"}
@@ -2,7 +2,7 @@
2
2
  "version": "1.0.0",
3
3
  "timestamp": 0,
4
4
  "packageName": "@happyvertical/smrt-ledgers",
5
- "packageVersion": "0.51.23",
5
+ "packageVersion": "0.51.25",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-ledgers:AccountCollection": {
8
8
  "name": "accountcollection",
@@ -162,14 +162,16 @@
162
162
  "isPublic": true
163
163
  }
164
164
  },
165
- "decoratorConfig": {},
165
+ "decoratorConfig": {
166
+ "tableName": "ledger_accounts"
167
+ },
166
168
  "extends": "SmrtCollection",
167
169
  "extendsTypeArg": "Account",
168
170
  "exportName": "AccountCollection",
169
171
  "collectionExportName": "AccountCollectionCollection",
170
172
  "schema": {
171
- "tableName": "accounts",
172
- "ddl": "CREATE TABLE IF NOT EXISTS \"accounts\" (\n \"id\" UUID PRIMARY KEY NOT NULL,\n \"slug\" TEXT NOT NULL,\n \"context\" TEXT NOT NULL DEFAULT '',\n \"created_at\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\n \"updated_at\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\n \"parent_id\" UUID,\n \"tenant_id\" UUID,\n \"number\" TEXT DEFAULT '',\n \"name\" TEXT DEFAULT '',\n \"description\" TEXT DEFAULT '',\n \"type\" TEXT DEFAULT 'asset',\n \"active\" BOOLEAN DEFAULT TRUE,\n \"metadata\" JSON DEFAULT '{}'\n);",
173
+ "tableName": "ledger_accounts",
174
+ "ddl": "CREATE TABLE IF NOT EXISTS \"ledger_accounts\" (\n \"id\" UUID PRIMARY KEY NOT NULL,\n \"slug\" TEXT NOT NULL,\n \"context\" TEXT NOT NULL DEFAULT '',\n \"created_at\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\n \"updated_at\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\n \"parent_id\" UUID,\n \"tenant_id\" UUID,\n \"number\" TEXT DEFAULT '',\n \"name\" TEXT DEFAULT '',\n \"description\" TEXT DEFAULT '',\n \"type\" TEXT DEFAULT 'asset',\n \"active\" BOOLEAN DEFAULT TRUE,\n \"metadata\" JSON DEFAULT '{}'\n);",
173
175
  "columns": {
174
176
  "id": {
175
177
  "type": "UUID",
@@ -202,7 +204,7 @@
202
204
  "notNull": false,
203
205
  "unique": false,
204
206
  "foreignKey": {
205
- "table": "accounts",
207
+ "table": "ledger_accounts",
206
208
  "column": "id",
207
209
  "onDelete": "NO ACTION",
208
210
  "onUpdate": "CASCADE"
@@ -253,7 +255,7 @@
253
255
  },
254
256
  "indexes": [
255
257
  {
256
- "name": "accounts_slug_context_idx",
258
+ "name": "ledger_accounts_slug_context_idx",
257
259
  "columns": [
258
260
  "tenant_id",
259
261
  "slug",
@@ -263,20 +265,20 @@
263
265
  "nullsNotDistinct": true
264
266
  },
265
267
  {
266
- "name": "accounts_tenant_id_created_at_idx",
268
+ "name": "ledger_accounts_tenant_id_created_at_idx",
267
269
  "columns": [
268
270
  "tenant_id",
269
271
  "created_at"
270
272
  ]
271
273
  },
272
274
  {
273
- "name": "accounts_parent_id_idx",
275
+ "name": "ledger_accounts_parent_id_idx",
274
276
  "columns": [
275
277
  "parent_id"
276
278
  ]
277
279
  }
278
280
  ],
279
- "version": "62bb562a"
281
+ "version": "49630dae"
280
282
  },
281
283
  "importPath": "@happyvertical/smrt-ledgers"
282
284
  },
@@ -492,7 +494,7 @@
492
494
  "notNull": false,
493
495
  "unique": false,
494
496
  "foreignKey": {
495
- "table": "accounts",
497
+ "table": "ledger_accounts",
496
498
  "column": "id",
497
499
  "onDelete": "NO ACTION",
498
500
  "onUpdate": "CASCADE"
@@ -566,7 +568,7 @@
566
568
  ]
567
569
  }
568
570
  ],
569
- "version": "0457e0e4"
571
+ "version": "93cdc848"
570
572
  },
571
573
  "importPath": "@happyvertical/smrt-ledgers"
572
574
  },
@@ -1093,6 +1095,7 @@
1093
1095
  }
1094
1096
  },
1095
1097
  "decoratorConfig": {
1098
+ "tableName": "ledger_accounts",
1096
1099
  "api": {
1097
1100
  "include": [
1098
1101
  "list",
@@ -1125,8 +1128,8 @@
1125
1128
  "exportName": "Account",
1126
1129
  "collectionExportName": "AccountCollection",
1127
1130
  "schema": {
1128
- "tableName": "accounts",
1129
- "ddl": "CREATE TABLE IF NOT EXISTS \"accounts\" (\n \"id\" UUID PRIMARY KEY NOT NULL,\n \"slug\" TEXT NOT NULL,\n \"context\" TEXT NOT NULL DEFAULT '',\n \"created_at\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\n \"updated_at\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\n \"parent_id\" UUID,\n \"tenant_id\" UUID,\n \"number\" TEXT DEFAULT '',\n \"name\" TEXT DEFAULT '',\n \"description\" TEXT DEFAULT '',\n \"type\" TEXT DEFAULT 'asset',\n \"active\" BOOLEAN DEFAULT TRUE,\n \"metadata\" JSON DEFAULT '{}'\n);",
1131
+ "tableName": "ledger_accounts",
1132
+ "ddl": "CREATE TABLE IF NOT EXISTS \"ledger_accounts\" (\n \"id\" UUID PRIMARY KEY NOT NULL,\n \"slug\" TEXT NOT NULL,\n \"context\" TEXT NOT NULL DEFAULT '',\n \"created_at\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\n \"updated_at\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\n \"parent_id\" UUID,\n \"tenant_id\" UUID,\n \"number\" TEXT DEFAULT '',\n \"name\" TEXT DEFAULT '',\n \"description\" TEXT DEFAULT '',\n \"type\" TEXT DEFAULT 'asset',\n \"active\" BOOLEAN DEFAULT TRUE,\n \"metadata\" JSON DEFAULT '{}'\n);",
1130
1133
  "columns": {
1131
1134
  "id": {
1132
1135
  "type": "UUID",
@@ -1159,7 +1162,7 @@
1159
1162
  "notNull": false,
1160
1163
  "unique": false,
1161
1164
  "foreignKey": {
1162
- "table": "accounts",
1165
+ "table": "ledger_accounts",
1163
1166
  "column": "id",
1164
1167
  "onDelete": "NO ACTION",
1165
1168
  "onUpdate": "CASCADE"
@@ -1210,7 +1213,7 @@
1210
1213
  },
1211
1214
  "indexes": [
1212
1215
  {
1213
- "name": "accounts_slug_context_idx",
1216
+ "name": "ledger_accounts_slug_context_idx",
1214
1217
  "columns": [
1215
1218
  "tenant_id",
1216
1219
  "slug",
@@ -1220,20 +1223,20 @@
1220
1223
  "nullsNotDistinct": true
1221
1224
  },
1222
1225
  {
1223
- "name": "accounts_tenant_id_created_at_idx",
1226
+ "name": "ledger_accounts_tenant_id_created_at_idx",
1224
1227
  "columns": [
1225
1228
  "tenant_id",
1226
1229
  "created_at"
1227
1230
  ]
1228
1231
  },
1229
1232
  {
1230
- "name": "accounts_parent_id_idx",
1233
+ "name": "ledger_accounts_parent_id_idx",
1231
1234
  "columns": [
1232
1235
  "parent_id"
1233
1236
  ]
1234
1237
  }
1235
1238
  ],
1236
- "version": "62bb562a"
1239
+ "version": "49630dae"
1237
1240
  },
1238
1241
  "importPath": "@happyvertical/smrt-ledgers"
1239
1242
  },
@@ -1769,7 +1772,7 @@
1769
1772
  "notNull": false,
1770
1773
  "unique": false,
1771
1774
  "foreignKey": {
1772
- "table": "accounts",
1775
+ "table": "ledger_accounts",
1773
1776
  "column": "id",
1774
1777
  "onDelete": "NO ACTION",
1775
1778
  "onUpdate": "CASCADE"
@@ -1843,7 +1846,7 @@
1843
1846
  ]
1844
1847
  }
1845
1848
  ],
1846
- "version": "0457e0e4"
1849
+ "version": "93cdc848"
1847
1850
  },
1848
1851
  "importPath": "@happyvertical/smrt-ledgers"
1849
1852
  }
@@ -3,13 +3,13 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-ledgers",
6
- "packageVersion": "0.51.23",
6
+ "packageVersion": "0.51.25",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "f69d4643948b6de64bf899fcee6bb4f7c5aef4c18066e316dff201a6cbbbb193",
11
- "packageJson": "3bbc8779ea1b1f316ba42ee501c84475662ad84eb8e4c8fc24d4f250cdc7f65f",
12
- "agents": "6fa28e0fe0c03c7a9c201154f935286ca0e72fd59f7e3fa24b440f87e687d7c8"
10
+ "manifest": "c49f8bf171ef683cc3c56d9438399621dae853fe8798274f1b3446973d656dcb",
11
+ "packageJson": "c679ca2d87cc4125877daecad26f59aac005447c330084fdf2cbe24c17822ec7",
12
+ "agents": "ae2190496d153852ff73d18f871a829303927e1c65053b5325b02c0d9f470bfe"
13
13
  },
14
14
  "exports": [
15
15
  ".",
@@ -51,7 +51,7 @@
51
51
  "name": "AccountCollection",
52
52
  "qualifiedName": "@happyvertical/smrt-ledgers:AccountCollection",
53
53
  "collection": "accounts",
54
- "tableName": "accounts",
54
+ "tableName": "ledger_accounts",
55
55
  "packageName": "@happyvertical/smrt-ledgers",
56
56
  "extends": "SmrtCollection",
57
57
  "fields": [],
@@ -1137,7 +1137,7 @@
1137
1137
  "name": "Account",
1138
1138
  "qualifiedName": "@happyvertical/smrt-ledgers:Account",
1139
1139
  "collection": "accounts",
1140
- "tableName": "accounts",
1140
+ "tableName": "ledger_accounts",
1141
1141
  "packageName": "@happyvertical/smrt-ledgers",
1142
1142
  "extends": "SmrtHierarchical",
1143
1143
  "fields": [
@@ -3425,5 +3425,5 @@
3425
3425
  "polymorphicAssociations": 0,
3426
3426
  "uuidColumns": 18
3427
3427
  },
3428
- "agentDoc": "# @happyvertical/smrt-ledgers\n\nDouble-entry accounting with chart of accounts, journal lifecycle, and balance enforcement.\n\n## Models\n\n- **Account**: 5 types (asset/liability/equity/revenue/expense). Hierarchical via `parentId`. Debit-normal (asset, expense) vs credit-normal (liability, equity, revenue). Methods: `getAncestors()`, `getFullPath()`, `toTreeNode()`, `getBalance(asOfDate?)`.\n- **Journal**: lifecycle `draft → posted → voided`. **Immutable after posting** (can only void, not edit). `sourceModule`/`sourceRef` for cross-package attribution. Auto-numbered (e.g., \"JNL-0001\"). `summarize()` is AI-powered via the smrt-prompts registry (see Prompt Registry below).\n- **JournalEntry**: debit XOR credit (not both, validated on save). Multi-currency via `exchangeRate`. Non-negative amounts required.\n\n## Key Methods\n\n- **`Journal.summarize()`**: Generates a natural-language summary via the registered `smrtLedgers.journal.summarize` prompt, resolved through `@happyvertical/smrt-prompts`. Tenants can override the template, model, temperature, or other params via `_smrt_prompt_overrides` without code changes. Only non-PII fields (number, date, description, status, aggregate total, entry count, balanced flag) reach the AI provider.\n\n## Prompt Registry\n\nRegistered at module-load time via `definePrompt()` in `src/prompts.ts`. Side-effect imported from `src/index.ts` so consumers automatically see the prompts after importing any export from this package.\n\n| Key | Method | Variables |\n|-----|--------|-----------|\n| `smrtLedgers.journal.summarize` | `Journal.summarize()` | `journalNumber`, `journalDate`, `journalDescription`, `journalStatus`, `journalTotal`, `entryCount`, `journalBalanced` |\n\nPII-conscious variable selection: `tenantId`, `sourceRef` (may reference customer/vendor identifiers), per-entry `accountId`/`id`, and the extensible `metadata` blob are intentionally NOT exposed as prompt variables. Tenants who need richer context should override the template via `PromptOverride` and supply their own variables through a custom call site.\n\n## Balance Enforcement\n\n`journal.post()` validates `Math.abs(totalDebits - totalCredits) < BALANCE_EPSILON` where `BALANCE_EPSILON = 0.01` (float rounding tolerance). Unbalanced journals cannot be posted.\n\n**This package is unit-agnostic** — `debit` / `credit` are plain DECIMAL numbers and the balance check only compares the two sides, so it holds for whatever unit the posting module uses. As of #2401, journals posted from `@happyvertical/smrt-commerce` (`Payment.recordPayment()`, `Invoice.recognizeRevenue()`) carry **integer minor units**, which balance exactly rather than merely within the epsilon. A consumer mixing modules that post in different units will get arithmetically balanced but semantically meaningless journals; pick one unit per ledger.\n\n## Gotchas\n\n- **Float tolerance**: 0.01 epsilon for balance check — not exact equality\n- **Entry requires journalId**: save Journal first, then add entries\n- **Posted journals cannot be modified**: only voided (`voidReason`, `voidedAt`)\n- **Account types inherited by children**: child cannot differ from parent type\n- **getBalance() is async**: requires JournalEntryCollection query (not stored on Account)\n- **Optional tenancy** on all models\n"
3428
+ "agentDoc": "# @happyvertical/smrt-ledgers\n\nDouble-entry accounting with chart of accounts, journal lifecycle, and balance enforcement.\n\n## Models\n\n- **Account**: 5 types (asset/liability/equity/revenue/expense). Hierarchical via `parentId`. Debit-normal (asset, expense) vs credit-normal (liability, equity, revenue). Methods: `getAncestors()`, `getFullPath()`, `toTreeNode()`, `getBalance(asOfDate?)`. Stored in `ledger_accounts` (explicit `tableName`), never the derived `accounts`: smrt-messages declares an unrelated `Account` on that table (#3098). `src/migrations/ledger-accounts-table.ts` (`smrt db:migrate-ledger-accounts`) moves pre-#3098 rows; the README has the operator sequence.\n- **Journal**: lifecycle `draft → posted → voided`. **Immutable after posting** (can only void, not edit). `sourceModule`/`sourceRef` for cross-package attribution. Auto-numbered (e.g., \"JNL-0001\"). `summarize()` is AI-powered via the smrt-prompts registry (see Prompt Registry below).\n- **JournalEntry**: debit XOR credit (not both, validated on save). Multi-currency via `exchangeRate`. Non-negative amounts required.\n\n## Key Methods\n\n- **`Journal.summarize()`**: Generates a natural-language summary via the registered `smrtLedgers.journal.summarize` prompt, resolved through `@happyvertical/smrt-prompts`. Tenants can override the template, model, temperature, or other params via `_smrt_prompt_overrides` without code changes. Only non-PII fields (number, date, description, status, aggregate total, entry count, balanced flag) reach the AI provider.\n\n## Prompt Registry\n\nRegistered at module-load time via `definePrompt()` in `src/prompts.ts`. Side-effect imported from `src/index.ts` so consumers automatically see the prompts after importing any export from this package.\n\n| Key | Method | Variables |\n|-----|--------|-----------|\n| `smrtLedgers.journal.summarize` | `Journal.summarize()` | `journalNumber`, `journalDate`, `journalDescription`, `journalStatus`, `journalTotal`, `entryCount`, `journalBalanced` |\n\nPII-conscious variable selection: `tenantId`, `sourceRef` (may reference customer/vendor identifiers), per-entry `accountId`/`id`, and the extensible `metadata` blob are intentionally NOT exposed as prompt variables. Tenants who need richer context should override the template via `PromptOverride` and supply their own variables through a custom call site.\n\n## Balance Enforcement\n\n`journal.post()` validates `Math.abs(totalDebits - totalCredits) < BALANCE_EPSILON` where `BALANCE_EPSILON = 0.01` (float rounding tolerance). Unbalanced journals cannot be posted.\n\n**This package is unit-agnostic** — `debit` / `credit` are plain DECIMAL numbers and the balance check only compares the two sides, so it holds for whatever unit the posting module uses. As of #2401, journals posted from `@happyvertical/smrt-commerce` (`Payment.recordPayment()`, `Invoice.recognizeRevenue()`) carry **integer minor units**, which balance exactly rather than merely within the epsilon. A consumer mixing modules that post in different units will get arithmetically balanced but semantically meaningless journals; pick one unit per ledger.\n\n## Gotchas\n\n- **Float tolerance**: 0.01 epsilon for balance check — not exact equality\n- **Entry requires journalId**: save Journal first, then add entries\n- **Posted journals cannot be modified**: only voided (`voidReason`, `voidedAt`)\n- **Account types inherited by children**: child cannot differ from parent type\n- **getBalance() is async**: requires JournalEntryCollection query (not stored on Account)\n- **Optional tenancy** on all models\n- **Same-named `Account`**: reference the ledger model by constructor (`@foreignKey(Account)`) or qualified name (`@happyvertical/smrt-ledgers:Account`), never the bare string. The PostgreSQL lanes are `pnpm test:postgres` here (ledgers alone) and in smrt-messages (both packages loaded)\n"
3429
3429
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-ledgers",
3
- "version": "0.51.23",
3
+ "version": "0.51.25",
4
4
  "description": "Double-entry accounting ledger for the SMRT framework",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -38,12 +38,12 @@
38
38
  "access": "public"
39
39
  },
40
40
  "dependencies": {
41
- "@happyvertical/smrt-core": "0.51.23",
42
- "@happyvertical/smrt-prompts": "0.51.23",
43
- "@happyvertical/smrt-tenancy": "0.51.23"
41
+ "@happyvertical/smrt-core": "0.51.25",
42
+ "@happyvertical/smrt-prompts": "0.51.25",
43
+ "@happyvertical/smrt-tenancy": "0.51.25"
44
44
  },
45
45
  "devDependencies": {
46
- "@happyvertical/smrt-vitest": "0.51.23",
46
+ "@happyvertical/smrt-vitest": "0.51.25",
47
47
  "@types/node": "24.13.6",
48
48
  "fast-glob": "^3.3.3",
49
49
  "typescript": "5.9.3",
@@ -54,6 +54,7 @@
54
54
  "build": "vite build --mode library",
55
55
  "dev": "vite build --watch",
56
56
  "test": "vitest run",
57
+ "test:postgres": "node ../../scripts/run-with-ci-postgres.mjs -- pnpm exec vitest run optional.test.ts",
57
58
  "typecheck": "tsc -p tsconfig.typecheck.json"
58
59
  }
59
60
  }