@classytic/ledger 0.5.1 → 0.7.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.
@@ -1,254 +0,0 @@
1
- import { n as Errors } from "./errors-BmRjW38t.mjs";
2
- //#region src/plugins/double-entry.plugin.ts
3
- function doubleEntryPlugin(options = {}) {
4
- const { onlyOnPost = true, JournalEntryModel, AccountModel, orgField } = options;
5
- function validateItems(items, data) {
6
- const lineErrors = [];
7
- for (let i = 0; i < items.length; i++) {
8
- const d = items[i].debit ?? 0;
9
- const c = items[i].credit ?? 0;
10
- if (d > 0 && c > 0) lineErrors.push({
11
- path: `journalItems.${i}`,
12
- issue: "line cannot have both debit and credit greater than zero",
13
- value: {
14
- debit: d,
15
- credit: c
16
- }
17
- });
18
- if (d === 0 && c === 0) lineErrors.push({
19
- path: `journalItems.${i}`,
20
- issue: "line cannot have both debit and credit equal to zero",
21
- value: {
22
- debit: 0,
23
- credit: 0
24
- }
25
- });
26
- }
27
- if (lineErrors.length > 0) throw Errors.validation(`Invalid journal line(s): ${lineErrors.map((e) => `${e.path} — ${e.issue}`).join("; ")}`, lineErrors);
28
- const totalDebit = items.reduce((s, i) => s + (i.debit ?? 0), 0);
29
- const totalCredit = items.reduce((s, i) => s + (i.credit ?? 0), 0);
30
- if (totalDebit !== totalCredit) throw Errors.validation(`Double-entry violation: debits (${totalDebit}) ≠ credits (${totalCredit}). Difference: ${Math.abs(totalDebit - totalCredit)}`, [{
31
- path: "journalItems",
32
- issue: "debits must equal credits",
33
- value: {
34
- totalDebit,
35
- totalCredit,
36
- difference: totalDebit - totalCredit
37
- }
38
- }]);
39
- data.totalDebit = totalDebit;
40
- data.totalCredit = totalCredit;
41
- }
42
- return {
43
- name: "accounting:double-entry",
44
- apply(repo) {
45
- const validate = async (context) => {
46
- const data = context.data;
47
- if (!data) return;
48
- if (onlyOnPost && data.state !== "posted") return;
49
- const items = data.journalItems;
50
- if (data.state === "posted" && (!items || items.length < 2)) throw Errors.validation(`Cannot post entry: at least 2 journal items required, got ${items?.length ?? 0}.`);
51
- if (!items || items.length === 0) return;
52
- validateItems(items, data);
53
- if (data.state === "posted") {
54
- if (!AccountModel) throw new Error("doubleEntryPlugin: AccountModel is required to validate posted entries. Pass AccountModel in plugin options to enable account existence and tenant integrity checks.");
55
- await validateAccounts(items, data, context);
56
- }
57
- };
58
- /** Verify all journal item accounts exist and belong to the same org */
59
- const validateAccounts = async (items, data, context) => {
60
- const missingIdxs = [];
61
- items.forEach((item, idx) => {
62
- if (item.account == null || item.account === "") missingIdxs.push(idx);
63
- });
64
- if (missingIdxs.length > 0) throw Errors.validation(`Posted entry has items with missing accounts at index(es): ${missingIdxs.join(", ")}.`, missingIdxs.map((i) => ({
65
- path: `journalItems.${i}.account`,
66
- issue: "account is required on posted entries"
67
- })));
68
- const accountIds = items.map((i) => i.account);
69
- const selectFields = orgField ? `_id ${orgField}` : "_id";
70
- const accounts = await AccountModel?.find({ _id: { $in: accountIds } }).select(selectFields).session(context.session ?? null).lean();
71
- const foundIds = new Set(accounts.map((a) => String(a._id)));
72
- const missingFieldErrors = [];
73
- items.forEach((item, idx) => {
74
- if (!foundIds.has(String(item.account))) missingFieldErrors.push({
75
- path: `journalItems.${idx}.account`,
76
- issue: "account does not exist",
77
- value: item.account
78
- });
79
- });
80
- if (missingFieldErrors.length > 0) throw Errors.validation(`${missingFieldErrors.length} item(s) reference non-existent accounts.`, missingFieldErrors);
81
- if (orgField && data[orgField] != null) {
82
- const dataOrg = String(data[orgField]);
83
- const accountOrgById = new Map(accounts.map((a) => [String(a._id), String(a[orgField])]));
84
- const crossTenantFieldErrors = [];
85
- items.forEach((item, idx) => {
86
- const acctOrg = accountOrgById.get(String(item.account));
87
- if (acctOrg !== void 0 && acctOrg !== dataOrg) crossTenantFieldErrors.push({
88
- path: `journalItems.${idx}.account`,
89
- issue: "account belongs to another organization",
90
- value: {
91
- account: item.account,
92
- expectedOrg: dataOrg,
93
- actualOrg: acctOrg
94
- }
95
- });
96
- });
97
- if (crossTenantFieldErrors.length > 0) throw Errors.validation(`${crossTenantFieldErrors.length} item(s) reference accounts from another organization.`, crossTenantFieldErrors);
98
- }
99
- };
100
- const validateUpdate = async (context) => {
101
- const data = context.data;
102
- if (!data) return;
103
- const internalOp = context._ledgerInternal;
104
- if (JournalEntryModel && !internalOp) {
105
- const id = context.id;
106
- if (id) {
107
- if ((await JournalEntryModel.findById(id).select("state").session(context.session ?? null).lean())?.state === "posted") {
108
- if (data.state !== void 0 && data.state !== "posted") throw Errors.immutable("Cannot change state of a posted journal entry. Posted entries are immutable.");
109
- const allowedKeys = new Set(["state"]);
110
- if (Object.keys(data).some((k) => !allowedKeys.has(k))) throw Errors.immutable("Cannot modify a posted journal entry. Use reverse() to create a correcting entry instead.");
111
- }
112
- }
113
- }
114
- if (onlyOnPost && data.state !== "posted") return;
115
- const items = data.journalItems;
116
- if (items !== void 0) {
117
- if (items.length < 2) throw Errors.validation(`Cannot post entry: at least 2 journal items required, got ${items.length}.`);
118
- validateItems(items, data);
119
- if (AccountModel) await validateAccounts(items, data, context);
120
- return;
121
- }
122
- if (!JournalEntryModel) throw new Error("doubleEntryPlugin: JournalEntryModel is required to validate partial updates that set state to \"posted\". Pass JournalEntryModel in plugin options.");
123
- const id = context.id;
124
- if (!id) throw new Error("doubleEntryPlugin: update context is missing \"id\". Cannot validate partial post without document ID.");
125
- const existing = await JournalEntryModel.findById(id).select("journalItems").session(context.session ?? null).lean();
126
- if (!existing) return;
127
- const persistedItems = existing.journalItems;
128
- if (!persistedItems || persistedItems.length < 2) throw Errors.validation(`Cannot post entry: at least 2 journal items required, got ${persistedItems?.length ?? 0}.`);
129
- validateItems(persistedItems, data);
130
- if (AccountModel) await validateAccounts(persistedItems, {
131
- ...data,
132
- ...existing
133
- }, context);
134
- };
135
- repo.on("before:create", validate);
136
- repo.on("before:update", validateUpdate);
137
- }
138
- };
139
- }
140
- //#endregion
141
- //#region src/plugins/fiscal-lock.plugin.ts
142
- function fiscalLockPlugin(options) {
143
- const { FiscalPeriodModel, JournalEntryModel, orgField } = options;
144
- return {
145
- name: "accounting:fiscal-lock",
146
- apply(repo) {
147
- const checkPeriod = async (context, isUpdate) => {
148
- const data = context.data;
149
- if (!data) return;
150
- if (data.state !== "posted") return;
151
- const session = context.session ?? null;
152
- let entryDate;
153
- let persistedDoc = null;
154
- if (data.date) entryDate = new Date(data.date);
155
- else if (!isUpdate) entryDate = /* @__PURE__ */ new Date();
156
- else {
157
- if (!context.id) throw new Error("fiscalLockPlugin: update context is missing \"id\". Cannot validate fiscal lock without document ID.");
158
- if (!JournalEntryModel) throw new Error("fiscalLockPlugin: JournalEntryModel is required to validate partial updates that set state to \"posted\". Pass JournalEntryModel in plugin options.");
159
- const selectFields = orgField ? `date ${orgField}` : "date";
160
- persistedDoc = await JournalEntryModel.findById(context.id).select(selectFields).session(session).lean();
161
- if (persistedDoc?.date) entryDate = new Date(persistedDoc.date);
162
- }
163
- if (!entryDate) return;
164
- const query = {
165
- startDate: { $lte: entryDate },
166
- endDate: { $gte: entryDate },
167
- closed: true
168
- };
169
- if (orgField) {
170
- let orgValue = data[orgField] ?? context[orgField];
171
- if (!orgValue && isUpdate) {
172
- if (persistedDoc) orgValue = persistedDoc[orgField];
173
- else if (context.id && JournalEntryModel) {
174
- const persisted = await JournalEntryModel.findById(context.id).select(orgField).session(session).lean();
175
- if (persisted) orgValue = persisted[orgField];
176
- }
177
- }
178
- if (!orgValue) throw new Error(`fiscalLockPlugin: orgField "${orgField}" is configured but could not be resolved from payload, context, or persisted document. Refusing to run unscoped fiscal period query.`);
179
- query[orgField] = orgValue;
180
- }
181
- const closedPeriod = await FiscalPeriodModel.findOne(query).session(session).lean();
182
- if (closedPeriod) {
183
- const period = closedPeriod;
184
- throw Errors.fiscal(`Cannot post entry dated ${entryDate.toISOString().split("T")[0]}: fiscal period "${period.name}" is closed.`);
185
- }
186
- };
187
- repo.on("before:create", (ctx) => checkPeriod(ctx, false));
188
- repo.on("before:update", (ctx) => checkPeriod(ctx, true));
189
- }
190
- };
191
- }
192
- //#endregion
193
- //#region src/plugins/idempotency.plugin.ts
194
- function idempotencyPlugin(options) {
195
- const { JournalEntryModel, orgField } = options;
196
- return {
197
- name: "accounting:idempotency",
198
- apply(repo) {
199
- repo.on("before:create", async (context) => {
200
- const data = context.data;
201
- if (!data?.idempotencyKey) return;
202
- const query = { idempotencyKey: data.idempotencyKey };
203
- if (orgField && data[orgField]) query[orgField] = data[orgField];
204
- const existing = await JournalEntryModel.findOne(query).select("_id").session(context.session ?? null).lean();
205
- if (existing) throw Errors.conflict(`Duplicate idempotency key: "${data.idempotencyKey}". Existing entry: ${existing._id}`);
206
- });
207
- }
208
- };
209
- }
210
- //#endregion
211
- //#region src/plugins/date-lock.plugin.ts
212
- function dateLockPlugin(options) {
213
- const { getLockDate, JournalEntryModel, orgField } = options;
214
- return {
215
- name: "accounting:date-lock",
216
- apply(repo) {
217
- const checkLock = async (context, isUpdate) => {
218
- const data = context.data;
219
- if (!data) return;
220
- if (data.state !== "posted") return;
221
- const session = context.session ?? null;
222
- let entryDate;
223
- let persistedDoc = null;
224
- if (data.date) entryDate = new Date(data.date);
225
- else if (!isUpdate) entryDate = /* @__PURE__ */ new Date();
226
- else {
227
- if (!context.id) throw new Error("dateLockPlugin: update context is missing \"id\". Cannot validate date lock without document ID.");
228
- const selectFields = orgField ? `date ${orgField}` : "date";
229
- persistedDoc = await JournalEntryModel.findById(context.id).select(selectFields).session(session).lean();
230
- if (persistedDoc?.date) entryDate = new Date(persistedDoc.date);
231
- }
232
- if (!entryDate) return;
233
- let orgValue;
234
- if (orgField) {
235
- orgValue = data[orgField] ?? context[orgField];
236
- if (!orgValue && isUpdate) {
237
- if (persistedDoc) orgValue = persistedDoc[orgField];
238
- else if (context.id) {
239
- const persisted = await JournalEntryModel.findById(context.id).select(orgField).session(session).lean();
240
- if (persisted) orgValue = persisted[orgField];
241
- }
242
- }
243
- }
244
- const lockDate = await getLockDate(orgValue, session ?? void 0);
245
- if (!lockDate) return;
246
- if (entryDate < lockDate) throw Errors.fiscal(`Cannot post entry dated ${entryDate.toISOString().split("T")[0]}: date is before lock date ${lockDate.toISOString().split("T")[0]}.`);
247
- };
248
- repo.on("before:create", (ctx) => checkLock(ctx, false));
249
- repo.on("before:update", (ctx) => checkLock(ctx, true));
250
- }
251
- };
252
- }
253
- //#endregion
254
- export { doubleEntryPlugin as i, idempotencyPlugin as n, fiscalLockPlugin as r, dateLockPlugin as t };
@@ -1,98 +0,0 @@
1
- import { ClientSession, Model } from "mongoose";
2
- import { RepositoryInstance } from "@classytic/mongokit";
3
-
4
- //#region src/plugins/date-lock.plugin.d.ts
5
- interface DateLockPluginOptions {
6
- /** Async function to resolve the lock date for a given org. Return null for no lock. */
7
- getLockDate: (orgId?: unknown, session?: ClientSession) => Promise<Date | null>;
8
- /** Mongoose model for journal entries (needed for partial updates) */
9
- JournalEntryModel: Model<unknown>;
10
- /** Org field name */
11
- orgField?: string;
12
- }
13
- declare function dateLockPlugin(options: DateLockPluginOptions): {
14
- name: string;
15
- apply(repo: RepositoryInstance): void;
16
- };
17
- //#endregion
18
- //#region src/types/mongokit-augmentation.d.ts
19
- /**
20
- * Module augmentation for `@classytic/mongokit`.
21
- *
22
- * Ledger's state-transition methods (post, unpost, archive, reverseMark) tag
23
- * their `repository.update()` call with a `_ledgerInternal` flag so the
24
- * double-entry immutability guard can distinguish legitimate transitions from
25
- * arbitrary edits. This file types that flag onto both `RepositoryContext`
26
- * (what plugins observe) and `SessionOptions` (what callers pass) so consumers
27
- * and plugin authors get full IntelliSense without casts.
28
- *
29
- * This file is side-effect only — importing it anywhere in the package is
30
- * enough to activate the augmentation. `src/types/index.ts` re-exports it.
31
- */
32
- type LedgerInternalOp = 'post' | 'unpost' | 'archive' | 'reverseMark';
33
- declare module '@classytic/mongokit' {
34
- interface RepositoryContext {
35
- /**
36
- * Set by ledger's repository methods (post, unpost, archive, reverseMark)
37
- * to signal a legitimate internal state transition. Plugins observing
38
- * `before:update` can read this to distinguish from arbitrary edits.
39
- *
40
- * External `repository.update()` callers cannot spoof this flag because
41
- * it is only set by ledger's own repo methods, never surfaced in the
42
- * public API.
43
- */
44
- _ledgerInternal?: LedgerInternalOp;
45
- }
46
- interface SessionOptions {
47
- /**
48
- * Ledger-internal flag — see `RepositoryContext._ledgerInternal`.
49
- * Typed here so ledger's repo methods can pass it without casts.
50
- * Consumers should never set this directly.
51
- */
52
- _ledgerInternal?: LedgerInternalOp;
53
- }
54
- }
55
- //#endregion
56
- //#region src/plugins/double-entry.plugin.d.ts
57
- interface DoubleEntryPluginOptions {
58
- /** Only enforce on posted entries (default: true) */
59
- onlyOnPost?: boolean;
60
- /** Mongoose model — required to validate partial updates that only set state */
61
- JournalEntryModel?: Model<unknown>;
62
- /** Account model — when provided, posted creates verify account existence + tenant scoping */
63
- AccountModel?: Model<unknown>;
64
- /** Multi-tenant org field name (e.g. 'business'). Required for tenant-account integrity checks. */
65
- orgField?: string;
66
- }
67
- declare function doubleEntryPlugin(options?: DoubleEntryPluginOptions): {
68
- name: string;
69
- apply(repo: RepositoryInstance): void;
70
- };
71
- //#endregion
72
- //#region src/plugins/fiscal-lock.plugin.d.ts
73
- interface FiscalLockPluginOptions {
74
- /** Mongoose model for fiscal periods */
75
- FiscalPeriodModel: Model<unknown>;
76
- /** Mongoose model for journal entries — needed to look up persisted date on partial updates */
77
- JournalEntryModel?: Model<unknown>;
78
- /** Organization field name (for multi-tenant) */
79
- orgField?: string;
80
- }
81
- declare function fiscalLockPlugin(options: FiscalLockPluginOptions): {
82
- name: string;
83
- apply(repo: RepositoryInstance): void;
84
- };
85
- //#endregion
86
- //#region src/plugins/idempotency.plugin.d.ts
87
- interface IdempotencyPluginOptions {
88
- /** Mongoose model for journal entries */
89
- JournalEntryModel: Model<unknown>;
90
- /** Multi-tenant org field name */
91
- orgField?: string;
92
- }
93
- declare function idempotencyPlugin(options: IdempotencyPluginOptions): {
94
- name: string;
95
- apply(repo: RepositoryInstance): void;
96
- };
97
- //#endregion
98
- export { DoubleEntryPluginOptions as a, dateLockPlugin as c, fiscalLockPlugin as i, idempotencyPlugin as n, doubleEntryPlugin as o, FiscalLockPluginOptions as r, DateLockPluginOptions as s, IdempotencyPluginOptions as t };