@classytic/ledger 0.5.0 → 0.6.0

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.
@@ -0,0 +1,228 @@
1
+ import { t as AccountType } from "./core-BkGjuVZj.mjs";
2
+
3
+ //#region src/country/index.d.ts
4
+ /**
5
+ * A single destination for a fraction of a tax amount. A `TaxCode` can declare
6
+ * multiple repartition lines so that one tax percentage produces multiple
7
+ * journal items (e.g. reverse-charge VAT books +100% to payable AND -100% to
8
+ * recoverable in the same entry). Factors sum across lines and the engine
9
+ * enforces balance inside the existing double-entry plugin.
10
+ *
11
+ * `accountRole` is a logical name looked up against the consumer's chart of
12
+ * accounts via the country pack's `resolveRepartitionAccount` helper — NOT a
13
+ * direct ObjectId, so the same country pack can drive any consumer's accounts.
14
+ * `gridCode` flows through to `taxDetails` for regulatory reporting (CRA
15
+ * schedule lines, HMRC VAT boxes, NBR Mushak grid, etc.).
16
+ */
17
+ interface TaxRepartitionLine {
18
+ /**
19
+ * Signed multiplier applied to the base tax amount. Use `1` for the
20
+ * "normal" line, `-1` for a mirror (e.g. recoverable reverse-charge).
21
+ * Fractions (e.g. `0.5`) are allowed for split-destination taxes.
22
+ */
23
+ readonly factor: number;
24
+ /**
25
+ * Logical role resolved against the country pack. Standard roles:
26
+ * - `'collected'` — tax collected from customer (liability)
27
+ * - `'recoverable'` — tax paid to supplier, recoverable (asset)
28
+ * - `'expense'` — tax paid, non-recoverable (expense)
29
+ * - `'transition'` — temporary holding account for cash-basis exigibility
30
+ * Consumers can define custom roles and wire them in their country pack.
31
+ */
32
+ readonly accountRole: string;
33
+ /** Optional reporting grid code — propagated to `taxDetails` on the item. */
34
+ readonly gridCode?: string | number;
35
+ /** Optional human label surfaced in UI and audit trails. */
36
+ readonly label?: string;
37
+ /** Optional: only apply on these document types. Default: all. */
38
+ readonly documentTypes?: readonly ('invoice' | 'refund' | 'payment')[];
39
+ }
40
+ /**
41
+ * When a tax is realized into the books:
42
+ * - `'accrual'` (default) — books at entry time (what 0.5.x did for everything)
43
+ * - `'cash'` — books into a transition account at entry time, moves to the
44
+ * real tax account when the invoice is reconciled against a payment
45
+ */
46
+ type TaxExigibility = 'accrual' | 'cash';
47
+ interface TaxCode {
48
+ readonly code: string;
49
+ readonly name: string;
50
+ readonly taxType: string;
51
+ readonly rate: number;
52
+ readonly direction: 'collected' | 'recoverable' | 'paid';
53
+ readonly province?: string;
54
+ readonly reportLines?: readonly number[];
55
+ readonly description: string;
56
+ readonly active: boolean;
57
+ /**
58
+ * Multi-line repartition — when present, `createRepartitionTaxGenerator`
59
+ * produces one journal item per line. When absent, the tax behaves as a
60
+ * single-line tax routed to the `direction`-implied account.
61
+ */
62
+ readonly repartition?: readonly TaxRepartitionLine[];
63
+ /**
64
+ * Accrual (default) or cash-basis exigibility. When `'cash'`, requires
65
+ * a `transition` repartition role in `repartition` OR a country-pack
66
+ * default transition account.
67
+ */
68
+ readonly exigibility?: TaxExigibility;
69
+ }
70
+ /**
71
+ * Declarative template that tells the engine which journals to seed for a
72
+ * new organization. Consumers call
73
+ * `engine.repositories.journals.seedDefaults(orgId)` which reads these from
74
+ * the country pack and creates one Journal document per template.
75
+ *
76
+ * Journals are *optional* — if a consumer never seeds journals, the legacy
77
+ * `journalType` enum on a journal entry still works. Consumers opting in
78
+ * get per-journal sequence prefixes, restricted payment methods, bank
79
+ * statement sources, etc.
80
+ */
81
+ interface JournalTemplate {
82
+ /** Short stable identifier — e.g. `'SALES'`, `'PURCHASE'`, `'BANK'`. */
83
+ readonly code: string;
84
+ /** Display name. */
85
+ readonly name: string;
86
+ /**
87
+ * One of the registered `JOURNAL_TYPES` codes — connects this journal to
88
+ * the engine's reference-number generator and posting-contract system.
89
+ */
90
+ readonly journalType: string;
91
+ /** Reference-number prefix — defaults to `code` when omitted. */
92
+ readonly sequencePrefix?: string;
93
+ /** First sequence number — defaults to `1`. */
94
+ readonly sequenceStartNum?: number;
95
+ /**
96
+ * Logical source — pure ledgering (`'general'`), sale-side docs (`'sale'`),
97
+ * purchase-side docs (`'purchase'`), cash/bank movement (`'bank'`, `'cash'`).
98
+ * Drives default locks (sale-lock, purchase-lock) when they're wired.
99
+ */
100
+ readonly kind?: 'general' | 'sale' | 'purchase' | 'bank' | 'cash' | string;
101
+ /** Optional default debit/credit account roles for quick data entry. */
102
+ readonly defaultDebitAccountRole?: string;
103
+ readonly defaultCreditAccountRole?: string;
104
+ }
105
+ interface TaxCodesByRegion {
106
+ readonly [region: string]: readonly string[];
107
+ }
108
+ interface TaxReportLine {
109
+ readonly line: number | string;
110
+ readonly name: string;
111
+ readonly description: string;
112
+ readonly type: 'input' | 'calculated' | 'manual';
113
+ readonly calculate?: (data: Record<string | number, number>) => number;
114
+ readonly section: string;
115
+ }
116
+ interface TaxReportTemplate {
117
+ readonly name: string;
118
+ readonly lines: Readonly<Record<string | number, TaxReportLine>>;
119
+ calculate(inputData: Record<string | number, number>, manualData?: Record<string | number, number>): Record<string | number, number>;
120
+ summarize(calculated: Record<string | number, number>): Record<string, unknown>;
121
+ }
122
+ interface CountryPack {
123
+ /** ISO 3166-1 alpha-2 code (e.g., 'CA', 'US', 'GB') */
124
+ readonly code: string;
125
+ /** Country name */
126
+ readonly name: string;
127
+ /** Default currency code */
128
+ readonly defaultCurrency: string;
129
+ /**
130
+ * Full chart of accounts template — flat array of account type definitions.
131
+ * Includes both regular accounts and virtual tax sub-accounts.
132
+ */
133
+ readonly accountTypes: readonly AccountType[];
134
+ /** Tax codes indexed by code string */
135
+ readonly taxCodes: Readonly<Record<string, TaxCode>>;
136
+ /** Tax codes grouped by region/province/state */
137
+ readonly taxCodesByRegion: TaxCodesByRegion;
138
+ /** Available regions (provinces/states) */
139
+ readonly regions: readonly string[];
140
+ /** Tax report template (e.g., CRA GST/HST return) */
141
+ readonly taxReport?: TaxReportTemplate;
142
+ /**
143
+ * Optional journal templates seeded per organization. When a consumer
144
+ * calls `engine.repositories.journals.seedDefaults(orgId)`, the engine
145
+ * creates one Journal document per template. See `JournalTemplate`.
146
+ */
147
+ readonly journalTemplates?: readonly JournalTemplate[];
148
+ /**
149
+ * Map a logical `accountRole` string (e.g. `'collected'`, `'recoverable'`,
150
+ * `'transition'`) to the actual account-type code for this country. The
151
+ * repartition tax generator calls this for each repartition line so the
152
+ * same tax definition can resolve different account codes in BD vs CA.
153
+ *
154
+ * Default behavior when omitted: maps `'collected'` → account with
155
+ * direction='collected' in `taxCodes`, `'recoverable'` →
156
+ * direction='recoverable', etc. Consumers override for custom roles.
157
+ */
158
+ readonly resolveTaxRepartitionAccountCode?: (role: string, taxCode: TaxCode) => string | undefined;
159
+ /**
160
+ * The retained earnings account code — the account that holds accumulated
161
+ * retained earnings (e.g. '3600' CA, '3310' BD).
162
+ *
163
+ * On the balance sheet, this account is excluded from normal equity grouping
164
+ * and its balance is folded into the computed "Retained Earnings" section
165
+ * (opening RE = RE account balance + prior-year unclosed P&L).
166
+ *
167
+ * Inspired by Odoo's `equity_unaffected` account type.
168
+ */
169
+ readonly retainedEarningsAccountCode?: string;
170
+ /**
171
+ * Display code for the "Previous Years Retained Earnings" line on the
172
+ * balance sheet (e.g. '3660' for CA GIFI). Defaults to retainedEarningsAccountCode.
173
+ */
174
+ readonly retainedEarningsDisplayCode?: string;
175
+ /** Display code for current year net income line (e.g. '3680' CA, '3311' BD) */
176
+ readonly currentYearEarningsCode?: string;
177
+ /** Group label code used to identify Cost of Sales in the income statement */
178
+ readonly cogsGroupCode?: string;
179
+ /** Override default English report section names */
180
+ readonly reportLabels?: {
181
+ readonly assets?: string;
182
+ readonly liabilities?: string;
183
+ readonly equity?: string;
184
+ readonly revenue?: string;
185
+ readonly expenses?: string;
186
+ };
187
+ /** Get all account types that can be posted to (not groups, not totals) */
188
+ getPostingAccountTypes(): readonly AccountType[];
189
+ /** Get account type by code */
190
+ getAccountType(code: string): AccountType | undefined;
191
+ /** Validate an account type code exists */
192
+ isValidAccountType(code: string): boolean;
193
+ /** Check if an account type can receive postings */
194
+ isPostingAccount(code: string): boolean;
195
+ /** Get tax codes for a specific region */
196
+ getTaxCodesForRegion(region: string): TaxCode[];
197
+ /** Flatten hierarchical accounts (if needed) */
198
+ flattenAccountTypes(): readonly AccountType[];
199
+ }
200
+ interface CountryPackInput {
201
+ code: string;
202
+ name: string;
203
+ defaultCurrency: string;
204
+ accountTypes: readonly AccountType[];
205
+ taxCodes: Readonly<Record<string, TaxCode>>;
206
+ taxCodesByRegion: TaxCodesByRegion;
207
+ regions: readonly string[];
208
+ taxReport?: TaxReportTemplate;
209
+ journalTemplates?: readonly JournalTemplate[];
210
+ resolveTaxRepartitionAccountCode?: (role: string, taxCode: TaxCode) => string | undefined;
211
+ retainedEarningsAccountCode?: string;
212
+ retainedEarningsDisplayCode?: string;
213
+ currentYearEarningsCode?: string;
214
+ cogsGroupCode?: string;
215
+ reportLabels?: {
216
+ readonly assets?: string;
217
+ readonly liabilities?: string;
218
+ readonly equity?: string;
219
+ readonly revenue?: string;
220
+ readonly expenses?: string;
221
+ };
222
+ }
223
+ /**
224
+ * Factory to create a CountryPack with auto-generated helper methods.
225
+ */
226
+ declare function defineCountryPack(input: CountryPackInput): CountryPack;
227
+ //#endregion
228
+ export { TaxCodesByRegion as a, TaxReportLine as c, TaxCode as i, TaxReportTemplate as l, CountryPackInput as n, TaxExigibility as o, JournalTemplate as r, TaxRepartitionLine as s, CountryPack as t, defineCountryPack as u };
package/dist/index.d.mts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { _ as TaxMetadata, a as Cents, c as DateRange, d as JournalType, f as MainType, g as TaxDetail, h as StatementType, i as CategoryKey, l as EntryState, m as ObjectId, n as CashFlowCategory, o as Currency, p as NormalBalance, s as DateOption, t as AccountType, u as JournalItem, v as TotalAccountOp } from "./core-BkGjuVZj.mjs";
2
2
  import { S as isValidCategory, a as getJournalTypeCodes, b as isBalanceSheet, c as CURRENCIES, d as isValidCurrency, f as CATEGORIES, i as getJournalType, l as getCurrency, n as JOURNAL_TYPES, o as isValidJournalType, p as CATEGORY_KEYS, r as getCustomJournalTypes, s as registerJournalType, t as JOURNAL_CODES, u as getMinorUnit, x as isIncomeStatement, y as getNormalBalance } from "./journals-C50E9mpo.mjs";
3
- import { a as TaxReportLine, i as TaxCodesByRegion, n as CountryPackInput, o as TaxReportTemplate, r as TaxCode, s as defineCountryPack, t as CountryPack } from "./index-GmfEFxVn.mjs";
3
+ import { a as TaxCodesByRegion, c as TaxReportLine, i as TaxCode, l as TaxReportTemplate, n as CountryPackInput, o as TaxExigibility, r as JournalTemplate, s as TaxRepartitionLine, t as CountryPack, u as defineCountryPack } from "./index-BthGypsI.mjs";
4
4
  import { _ as PopulatedJournalEntry, a as exportToCsv, h as FlatJournalRow, i as quickbooksFieldMap, m as ExportFieldMap, p as ExportField, r as universalFieldMap, t as flattenJournalEntries } from "./index-D1ZjgVxn.mjs";
5
5
  import { Money, abs, add, allocate, equals, format, formatPlain, fromDecimal, isNegative, isPositive, isValid, isZero, max, min, multiply, negate, parseCents, percentage, round, splitTaxExclusive, splitTaxInclusive, subtract, toDecimal } from "./money.mjs";
6
- import { $ as AgedBucketConfig, A as BudgetVsActualReport, B as IncomeStatementReport, C as DimensionBreakdownReport, D as generateCashFlow, F as BalanceSheetReport, G as TaxReport, H as ReportAccount, I as CashFlowReport, J as TrialBalanceRow, K as TaxReturnSummary, L as CashFlowSection, M as generateBudgetVsActual, O as BudgetVsActualOptions, P as generateBalanceSheet, Q as AgedBalanceRow, R as GeneralLedgerAccount, S as DimensionBreakdownParams, T as generateDimensionBreakdown, U as ReportCategory, V as LedgerEntry, W as ReportGroup, X as AgedBalanceParams, Y as AgedBalanceOptions, Z as AgedBalanceReport, a as RevaluationReport, b as reopenFiscalPeriod, c as RevaluationRate, d as computeRevaluation, et as DEFAULT_BUCKETS, h as generateGeneralLedger, i as RevaluationParams, j as BudgetVsActualRow, k as BudgetVsActualParams, l as RevaluationResult, n as generateTrialBalance, nt as Logger, o as generateRevaluation, p as generateIncomeStatement, q as TrialBalanceReport, r as RevaluationOptions, rt as defaultLogger, s as AccountForeignBalance, tt as generateAgedBalance, u as buildRevaluationEntry, w as DimensionBreakdownRow, x as DimensionBreakdownOptions, y as closeFiscalPeriod, z as GeneralLedgerReport } from "./trial-balance-BZ7yOOFD.mjs";
7
- import { c as dateLockPlugin, i as fiscalLockPlugin, n as idempotencyPlugin, o as doubleEntryPlugin } from "./idempotency.plugin-CK7LHnBn.mjs";
6
+ import { $ as TrialBalanceRow, A as generateDimensionBreakdown, B as BalanceSheetReport, D as DimensionBreakdownParams, E as DimensionBreakdownOptions, F as BudgetVsActualReport, G as IncomeStatementReport, H as CashFlowSection, I as BudgetVsActualRow, J as ReportCategory, K as LedgerEntry, L as generateBudgetVsActual, M as generateCashFlow, N as BudgetVsActualOptions, O as DimensionBreakdownReport, P as BudgetVsActualParams, Q as TrialBalanceReport, T as reopenFiscalPeriod, U as GeneralLedgerAccount, V as CashFlowReport, W as GeneralLedgerReport, X as TaxReport, Y as ReportGroup, Z as TaxReturnSummary, a as RevaluationReport, at as DEFAULT_BUCKETS, b as generateGeneralLedger, c as RevaluationRate, ct as defaultLogger, d as computeRevaluation, et as AgedBalanceOptions, f as PartnerLedgerLine, g as generatePartnerLedger, h as PartnerLedgerReport, i as RevaluationParams, it as AgedBucketConfig, k as DimensionBreakdownRow, l as RevaluationResult, m as PartnerLedgerParams, n as generateTrialBalance, nt as AgedBalanceReport, o as generateRevaluation, ot as generateAgedBalance, p as PartnerLedgerOptions, q as ReportAccount, r as RevaluationOptions, rt as AgedBalanceRow, s as AccountForeignBalance, st as Logger, tt as AgedBalanceParams, u as buildRevaluationEntry, v as generateIncomeStatement, w as closeFiscalPeriod, z as generateBalanceSheet } from "./trial-balance-s92GEvRR.mjs";
7
+ import { A as JournalEntryRepository, B as SeedResult, D as AccountRepository, E as creditLimitPlugin, F as PostOptions, I as ReconciliationRepository, L as ReverseOptions, M as JournalRepository, N as MatchInput, O as BulkCreateInput, P as OpenItem, R as ReverseResult, S as fxRealizationPlugin, T as CreditLimitPluginOptions, _ as LockResolver, a as DailyLockPluginOptions, b as idempotencyPlugin, c as dailyLockPlugin, d as PeriodResolverOptions, f as periodResolver, g as LockHit, h as LockAccountSelector, i as watermarkResolver, j as JournalItemRef, k as BulkCreateResult, l as fiscalLockPlugin, m as CreateLockPluginOptions, n as TaxLineInput, o as FiscalLockPluginOptions, p as createLockPlugin, r as WatermarkResolverOptions, s as TaxLockPluginOptions, t as TaxLineGenerator, u as taxLockPlugin, v as LockResolverContext, w as doubleEntryPlugin, x as FxRealizationPluginOptions, z as SeedOptions } from "./tax-hooks-BnVenul5.mjs";
8
8
  import { ClientSession, Connection, Model } from "mongoose";
9
9
  import { PaginationConfig, PluginType, Repository } from "@classytic/mongokit";
10
10
 
@@ -16,6 +16,7 @@ interface LedgerRepositoryPlugins {
16
16
  fiscalPeriod?: PluginType[];
17
17
  budget?: PluginType[];
18
18
  reconciliation?: PluginType[];
19
+ journal?: PluginType[];
19
20
  }
20
21
  /** Pagination caps per repository. Omit a key to use mongokit defaults. */
21
22
  interface LedgerPaginationConfig {
@@ -24,6 +25,7 @@ interface LedgerPaginationConfig {
24
25
  fiscalPeriod?: PaginationConfig;
25
26
  budget?: PaginationConfig;
26
27
  reconciliation?: PaginationConfig;
28
+ journal?: PaginationConfig;
27
29
  }
28
30
  /** Multi-tenant configuration */
29
31
  interface MultiTenantConfig {
@@ -101,6 +103,7 @@ interface ModelNames {
101
103
  fiscalPeriod?: string;
102
104
  budget?: string;
103
105
  reconciliation?: string;
106
+ journal?: string;
104
107
  }
105
108
  /** Main engine configuration */
106
109
  interface AccountingEngineConfig {
@@ -118,6 +121,7 @@ interface AccountingEngineConfig {
118
121
  fiscalPeriod?: SchemaOptions;
119
122
  budget?: SchemaOptions;
120
123
  reconciliation?: SchemaOptions;
124
+ journal?: SchemaOptions;
121
125
  };
122
126
  /** Country pack providing account types, tax codes, and templates */
123
127
  country: CountryPack;
@@ -159,6 +163,7 @@ interface LedgerModels {
159
163
  FiscalPeriod: Model<unknown>;
160
164
  Budget: Model<unknown>;
161
165
  Reconciliation: Model<unknown>;
166
+ Journal: Model<unknown>;
162
167
  }
163
168
  interface ResolvedModelNames {
164
169
  account: string;
@@ -166,110 +171,11 @@ interface ResolvedModelNames {
166
171
  fiscalPeriod: string;
167
172
  budget: string;
168
173
  reconciliation: string;
174
+ journal: string;
169
175
  }
170
176
  declare function resolveModelNames(overrides?: ModelNames): ResolvedModelNames;
171
- /**
172
- * Create (or reuse) all ledger models on the given connection.
173
- *
174
- * If a model with the same name is already registered on the connection,
175
- * the existing model is reused — this allows multiple engine instances
176
- * to share models and prevents "OverwriteModelError".
177
- */
178
177
  declare function createModels(connection: Connection, config: AccountingEngineConfig): LedgerModels;
179
178
  //#endregion
180
- //#region src/types/repositories.d.ts
181
- interface PostOptions {
182
- session?: ClientSession | null;
183
- /** Actor performing this operation (required when strictness.requireActor is enabled) */
184
- actorId?: unknown;
185
- }
186
- interface ReverseOptions extends PostOptions {
187
- /** Date for the reversal entry (defaults to now) */
188
- reversalDate?: Date;
189
- }
190
- interface SeedOptions {
191
- session?: ClientSession | null;
192
- }
193
- interface SeedResult {
194
- created: number;
195
- skipped: number;
196
- }
197
- interface BulkCreateInput {
198
- accountTypeCode?: string;
199
- accountNumber?: string;
200
- name?: string;
201
- active?: boolean;
202
- isCashAccount?: boolean;
203
- }
204
- interface BulkCreateResult {
205
- summary: {
206
- total: number;
207
- created: number;
208
- skipped: number;
209
- errors: number;
210
- };
211
- created: Array<Record<string, unknown>>;
212
- skipped: Array<Record<string, unknown>>;
213
- errors: Array<Record<string, unknown>>;
214
- }
215
- interface ReverseResult {
216
- original: Record<string, unknown>;
217
- reversal: Record<string, unknown>;
218
- }
219
- interface ReconcileParams {
220
- accountId: unknown;
221
- journalEntryIds: unknown[];
222
- organizationId?: unknown;
223
- note?: string;
224
- session?: ClientSession;
225
- }
226
- /**
227
- * Journal Entry Repository — extends mongokit Repository with accounting domain methods.
228
- *
229
- * Inherits ALL Repository<TDoc> methods: create, getById, getAll, update,
230
- * delete, count, exists, distinct, aggregate, withTransaction, etc.
231
- */
232
- interface JournalEntryRepository<TDoc = unknown> extends Repository<TDoc> {
233
- /** Post an entry (draft → posted). Validates items, balance, and accounts. */
234
- post(id: unknown, orgId?: unknown, options?: PostOptions): Promise<Record<string, unknown>>;
235
- /** Unpost an entry (posted → draft). Resets state for re-editing. */
236
- unpost(id: unknown, orgId?: unknown, options?: PostOptions): Promise<Record<string, unknown>>;
237
- /** Archive a draft entry (draft → archived). Preserves audit trail. */
238
- archive(id: unknown, orgId?: unknown, options?: PostOptions): Promise<Record<string, unknown>>;
239
- /** Duplicate an entry as a new draft. Copies items, type, and label. */
240
- duplicate(id: unknown, orgId?: unknown, options?: PostOptions): Promise<Record<string, unknown>>;
241
- /** Reverse a posted entry. Creates mirror entry with flipped debits/credits. */
242
- reverse(id: unknown, orgId?: unknown, options?: ReverseOptions): Promise<ReverseResult>;
243
- }
244
- /**
245
- * Account Repository — extends mongokit Repository with seed and bulk operations.
246
- */
247
- interface AccountRepository<TDoc = unknown> extends Repository<TDoc> {
248
- /** Seed standard posting accounts for an org from the country pack. */
249
- seedAccounts(orgId: unknown, options?: SeedOptions): Promise<SeedResult>;
250
- /** Bulk create accounts with validation and skip-if-exists logic. */
251
- bulkCreate(accounts: BulkCreateInput[], orgId: unknown): Promise<BulkCreateResult>;
252
- }
253
- /**
254
- * Reconciliation Repository — extends mongokit Repository with bank reconciliation methods.
255
- */
256
- interface ReconciliationRepository<TDoc = unknown> extends Repository<TDoc> {
257
- /** Reconcile journal entries for a specific account. */
258
- reconcile(params: ReconcileParams): Promise<Record<string, unknown>>;
259
- /** Remove a reconciliation record. */
260
- unreconcile(params: {
261
- reconciliationId: unknown;
262
- organizationId?: unknown;
263
- }): Promise<{
264
- success: boolean;
265
- }>;
266
- /** Get unreconciled journal entries for an account. */
267
- getUnreconciled(params: {
268
- accountId: unknown;
269
- organizationId?: unknown;
270
- }): Promise<Record<string, unknown>[]>;
271
- }
272
- //#endregion
273
179
  //#region src/repositories/factory.d.ts
274
180
  interface LedgerRepositories {
275
181
  accounts: AccountRepository<unknown>;
@@ -277,6 +183,7 @@ interface LedgerRepositories {
277
183
  fiscalPeriods: Repository<unknown>;
278
184
  budgets: Repository<unknown>;
279
185
  reconciliations: ReconciliationRepository<unknown>;
186
+ journals: JournalRepository<unknown>;
280
187
  }
281
188
  /**
282
189
  * Build all ledger repositories with plugins + domain methods pre-wired.
@@ -656,6 +563,39 @@ declare class AccountingEngine {
656
563
  }
657
564
  declare function createAccountingEngine(config: AccountingEngineConfig): AccountingEngine;
658
565
  //#endregion
566
+ //#region src/utils/repartition-tax.d.ts
567
+ /**
568
+ * Resolves an `accountRole` (e.g. `'collected'`, `'recoverable'`,
569
+ * `'transition'`) into the actual account ObjectId for the consumer's
570
+ * chart of accounts. Implementations typically close over an account
571
+ * cache loaded per organization at engine start.
572
+ */
573
+ type RepartitionAccountResolver = (role: string, taxCode: TaxCode, input: TaxLineInput) => unknown;
574
+ interface RepartitionGeneratorOptions {
575
+ /** Country pack — provides tax codes and optional resolver. */
576
+ country: CountryPack;
577
+ /** Required: resolve role → account id in the consumer's chart. */
578
+ resolveAccount: RepartitionAccountResolver;
579
+ /**
580
+ * Document type — determines which repartition lines apply. A line
581
+ * with `documentTypes: ['invoice']` is skipped when this is `'refund'`.
582
+ * Defaults to `'invoice'`.
583
+ */
584
+ documentType?: 'invoice' | 'refund' | 'payment';
585
+ }
586
+ /**
587
+ * Build a `TaxLineGenerator` that expands each hit `taxCode` into one
588
+ * journal item per repartition line. Taxes without `repartition` fall
589
+ * back to a single-line generator using the direction-implied account.
590
+ */
591
+ declare function createRepartitionTaxGenerator(options: RepartitionGeneratorOptions): TaxLineGenerator;
592
+ /**
593
+ * Helper for packs that want the standard "role → account-type code"
594
+ * mapping without writing their own resolver. Returns the function you
595
+ * stuff into `CountryPackInput.resolveTaxRepartitionAccountCode`.
596
+ */
597
+ declare function defaultResolveTaxRepartitionAccountCode(country: CountryPack): (role: string, tax: TaxCode) => string | undefined;
598
+ //#endregion
659
599
  //#region src/utils/account-helpers.d.ts
660
600
  /**
661
601
  * Check if an account type is a virtual tax sub-account.
@@ -789,7 +729,12 @@ declare const Errors: {
789
729
  readonly notFound: (msg: string, fields?: ReadonlyArray<FieldError>) => AccountingError;
790
730
  readonly conflict: (msg: string, fields?: ReadonlyArray<FieldError>) => AccountingError;
791
731
  readonly immutable: (msg: string, fields?: ReadonlyArray<FieldError>) => AccountingError;
792
- readonly fiscal: (msg: string, fields?: ReadonlyArray<FieldError>) => AccountingError;
732
+ /**
733
+ * Period/scope lock violation. Replaces the old `fiscal` factory — use the
734
+ * `scope` argument to distinguish fiscal / tax / daily / bank / etc. The
735
+ * resulting error code is `PERIOD_LOCKED_{SCOPE}` (e.g. `PERIOD_LOCKED_FISCAL`).
736
+ */
737
+ readonly locked: (scope: string, msg: string, fields?: ReadonlyArray<FieldError>) => AccountingError;
793
738
  };
794
739
  //#endregion
795
740
  //#region src/utils/filter-builder.d.ts
@@ -871,4 +816,4 @@ interface PostingResult {
871
816
  idempotencyKeys?: string[];
872
817
  }
873
818
  //#endregion
874
- export { type AccountCode, type AccountForeignBalance, type AccountRepository, type AccountSummary, type AccountType, AccountingEngine, type AccountingEngineConfig, AccountingError, type ActorContext, type AgedBalanceOptions, type AgedBalanceParams, type AgedBalanceReport, type AgedBalanceRow, type AgedBucketConfig, type AuditConfig, type BalanceSheetReport, type BudgetVsActualOptions, type BudgetVsActualParams, type BudgetVsActualReport, type BudgetVsActualRow, type BulkCreateInput, type BulkCreateResult, CATEGORIES, CATEGORY_KEYS, CURRENCIES, type CashFlowCategory, type CashFlowReport, type CashFlowSection, type CategoryKey, type Cents, type CountryPack, type CountryPackInput, type Currency, DEFAULT_BUCKETS, type DateOption, type DateRange, type DimensionBreakdownOptions, type DimensionBreakdownParams, type DimensionBreakdownReport, type DimensionBreakdownRow, type DimensionDefinition, type EntryState, Errors, type ExportField, type ExportFieldMap, type FieldError, type FiscalPeriodSummary, type FlatJournalRow, type GeneralLedgerAccount, type GeneralLedgerReport, type IncomeStatementReport, type IntrospectAPI, JOURNAL_CODES, JOURNAL_TYPES, type JournalEntryRepository, type JournalItem, type JournalSchemaOptions, type JournalType, type LedgerEntry, type LedgerModels, type LedgerPaginationConfig, type LedgerRepositories, type LedgerRepositoryPlugins, type Logger, type MainType, type ModelNames, Money, type MultiCurrencyConfig, type MultiTenantConfig, type NormalBalance, type PopulatedJournalEntry, type PostOptions, type PostingContract, type PostingResult, type ReconcileParams, type ReconciliationRepository, type RecordAPI, type RecordAdjustmentInput, type RecordAdjustmentLine, type RecordExpenseInput, type RecordOptions, type RecordPaymentInput, type RecordSaleInput, type RecordTransferInput, type ReportAccount, type ReportCategory, type ReportDescriptor, type ReportGroup, type ResolvedModelNames, type RevaluationOptions, type RevaluationParams, type RevaluationRate, type RevaluationReport, type RevaluationResult, type ReverseOptions, type ReverseResult, type SchemaOptions, type SeedOptions, type SeedResult, type Cents$1 as SemanticCents, type SessionResult, type StatementType, type StrictnessConfig, type SubledgerJournalItem, type SubledgerPostingInput, type TaxCode, type TaxCodesByRegion, type TaxDetail, type TaxInput, type TaxMetadata, type TaxReport, type TaxReportLine, type TaxReportTemplate, type TaxReturnSummary, type TotalAccountOp, type TrialBalanceReport, type TrialBalanceRow, acquireSession, add, allocate, buildAccountTypeMap, buildDimensionFields, buildDimensionIndexes, buildItemFilters, buildRevaluationEntry, calculateTotal, closeFiscalPeriod, computeEndingBalance, computeRevaluation, createAccountingEngine, createModels, createRepositories, dateLockPlugin, defaultLogger, defineCountryPack, doubleEntryPlugin, exportToCsv, finalizeSession, fiscalLockPlugin, flattenJournalEntries, format, formatPlain, fromDecimal, generateAgedBalance, generateBalanceSheet, generateBudgetVsActual, generateCashFlow, generateDimensionBreakdown, generateGeneralLedger, generateIncomeStatement, generateRevaluation, generateTrialBalance, getCurrency, getCustomJournalTypes, getDateRange, getFiscalYearStart, getJournalType, getJournalTypeCodes, getMinorUnit, getNormalBalance, idempotencyPlugin, isBalanceSheet, isIncomeStatement, isValidCategory, isValidCurrency, isValidJournalType, isVirtualTaxAccount, multiply, parseCents, percentage, quickbooksFieldMap, registerJournalType, reopenFiscalPeriod, resolveModelNames, splitTaxExclusive, splitTaxInclusive, subtract, toDecimal, universalFieldMap };
819
+ export { type AccountCode, type AccountForeignBalance, type AccountRepository, type AccountSummary, type AccountType, AccountingEngine, type AccountingEngineConfig, AccountingError, type ActorContext, type AgedBalanceOptions, type AgedBalanceParams, type AgedBalanceReport, type AgedBalanceRow, type AgedBucketConfig, type AuditConfig, type BalanceSheetReport, type BudgetVsActualOptions, type BudgetVsActualParams, type BudgetVsActualReport, type BudgetVsActualRow, type BulkCreateInput, type BulkCreateResult, CATEGORIES, CATEGORY_KEYS, CURRENCIES, type CashFlowCategory, type CashFlowReport, type CashFlowSection, type CategoryKey, type Cents, type CountryPack, type CountryPackInput, type CreateLockPluginOptions, type CreditLimitPluginOptions, type Currency, DEFAULT_BUCKETS, type DailyLockPluginOptions, type DateOption, type DateRange, type DimensionBreakdownOptions, type DimensionBreakdownParams, type DimensionBreakdownReport, type DimensionBreakdownRow, type DimensionDefinition, type EntryState, Errors, type ExportField, type ExportFieldMap, type FieldError, type FiscalLockPluginOptions, type FiscalPeriodSummary, type FlatJournalRow, type FxRealizationPluginOptions, type GeneralLedgerAccount, type GeneralLedgerReport, type IncomeStatementReport, type IntrospectAPI, JOURNAL_CODES, JOURNAL_TYPES, type JournalEntryRepository, type JournalItem, type JournalItemRef, type JournalRepository, type JournalSchemaOptions, type JournalTemplate, type JournalType, type LedgerEntry, type LedgerModels, type LedgerPaginationConfig, type LedgerRepositories, type LedgerRepositoryPlugins, type LockAccountSelector, type LockHit, type LockResolver, type LockResolverContext, type Logger, type MainType, type MatchInput, type ModelNames, Money, type MultiCurrencyConfig, type MultiTenantConfig, type NormalBalance, type OpenItem, type PartnerLedgerLine, type PartnerLedgerOptions, type PartnerLedgerParams, type PartnerLedgerReport, type PeriodResolverOptions, type PopulatedJournalEntry, type PostOptions, type PostingContract, type PostingResult, type ReconciliationRepository, type RecordAPI, type RecordAdjustmentInput, type RecordAdjustmentLine, type RecordExpenseInput, type RecordOptions, type RecordPaymentInput, type RecordSaleInput, type RecordTransferInput, type RepartitionAccountResolver, type RepartitionGeneratorOptions, type ReportAccount, type ReportCategory, type ReportDescriptor, type ReportGroup, type ResolvedModelNames, type RevaluationOptions, type RevaluationParams, type RevaluationRate, type RevaluationReport, type RevaluationResult, type ReverseOptions, type ReverseResult, type SchemaOptions, type SeedOptions, type SeedResult, type Cents$1 as SemanticCents, type SessionResult, type StatementType, type StrictnessConfig, type SubledgerJournalItem, type SubledgerPostingInput, type TaxCode, type TaxCodesByRegion, type TaxDetail, type TaxExigibility, type TaxInput, type TaxLockPluginOptions, type TaxMetadata, type TaxRepartitionLine, type TaxReport, type TaxReportLine, type TaxReportTemplate, type TaxReturnSummary, type TotalAccountOp, type TrialBalanceReport, type TrialBalanceRow, type WatermarkResolverOptions, acquireSession, add, allocate, buildAccountTypeMap, buildDimensionFields, buildDimensionIndexes, buildItemFilters, buildRevaluationEntry, calculateTotal, closeFiscalPeriod, computeEndingBalance, computeRevaluation, createAccountingEngine, createLockPlugin, createModels, createRepartitionTaxGenerator, createRepositories, creditLimitPlugin, dailyLockPlugin, defaultLogger, defaultResolveTaxRepartitionAccountCode, defineCountryPack, doubleEntryPlugin, exportToCsv, finalizeSession, fiscalLockPlugin, flattenJournalEntries, format, formatPlain, fromDecimal, fxRealizationPlugin, generateAgedBalance, generateBalanceSheet, generateBudgetVsActual, generateCashFlow, generateDimensionBreakdown, generateGeneralLedger, generateIncomeStatement, generatePartnerLedger, generateRevaluation, generateTrialBalance, getCurrency, getCustomJournalTypes, getDateRange, getFiscalYearStart, getJournalType, getJournalTypeCodes, getMinorUnit, getNormalBalance, idempotencyPlugin, isBalanceSheet, isIncomeStatement, isValidCategory, isValidCurrency, isValidJournalType, isVirtualTaxAccount, multiply, parseCents, percentage, periodResolver, quickbooksFieldMap, registerJournalType, reopenFiscalPeriod, resolveModelNames, splitTaxExclusive, splitTaxInclusive, subtract, taxLockPlugin, toDecimal, universalFieldMap, watermarkResolver };