@happyvertical/smrt-cli 0.57.2 → 0.57.4
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/{AuditLogCollection-WDHL-_AF-D_hrLrOn.js → AuditLogCollection-WDHL-_AF-gc0Iv4_E.js} +1 -1
- package/dist/{OidcIdentity-BUblgQLs-IuNMIhQo.js → OidcIdentity-BUblgQLs-Dg2mVf5h.js} +2 -2
- package/dist/{OidcIdentityCollection-ClOyaHeF-CuqXh-3X.js → OidcIdentityCollection-ClOyaHeF-hBdJRdUh.js} +1 -1
- package/dist/{ProfileAssetCollection-CRMcjLJ--2KIsnsmv.js → ProfileAssetCollection-CRMcjLJ--BWHEJu4G.js} +3 -3
- package/dist/{ProfileCollection-C4INKh7Y-YAMDqm4j.js → ProfileCollection-C4INKh7Y-BsGUGXgw.js} +17 -17
- package/dist/{ProfileLinkCollection-DFfZRsgv-DIqttvfN.js → ProfileLinkCollection-DFfZRsgv-BtX9clCV.js} +2 -2
- package/dist/{ProfileMetadataCollection-BIYKy4Y3-Bdd-IgcJ.js → ProfileMetadataCollection-BIYKy4Y3-qLgwjlxn.js} +1 -1
- package/dist/{ProfileMetafieldCollection-Buz7gzag-DI1MBIU1.js → ProfileMetafieldCollection-Buz7gzag-B0gJh1bX.js} +1 -1
- package/dist/{ProfileRelationshipCollection-C4g_QLI4-iAgf6Fs6.js → ProfileRelationshipCollection-C4g_QLI4-Cij-0usm.js} +1 -1
- package/dist/{ProfileTypeCollection-B7kwi1mU-D5hvWjoz.js → ProfileTypeCollection-B7kwi1mU-Bf8CNnRn.js} +2 -2
- package/dist/commands/export.d.ts.map +1 -1
- package/dist/{commands-C1vFtitF.js → commands-BtwiH2Di.js} +4 -3
- package/dist/dist-BtMsAWU5.js +1633 -0
- package/dist/{dist-DJVDHkyS.js → dist-C123280d.js} +3 -3
- package/dist/{dist-DZJVt05S.js → dist-CgWPpK0g.js} +3 -3
- package/dist/dist-ChF1Ci9J.js +21 -0
- package/dist/{dist-DDj_dW2s.js → dist-D3OnNl1S.js} +333 -27
- package/dist/index.js +11 -11
- package/dist/{oidcProvisioningPrimitives-DNP9EZlU-DZ9CeZNd.js → oidcProvisioningPrimitives-DNP9EZlU-CTpeZu8G.js} +3 -3
- package/dist/{resolveIdentity-CkyqvctR-BzWkMn3m.js → resolveIdentity-CkyqvctR-BKbrXMqj.js} +14 -14
- package/package.json +15 -15
- package/dist/dist-C1lMm9x_.js +0 -21
- package/dist/dist-CRW60XkI.js +0 -1278
package/dist/dist-CRW60XkI.js
DELETED
|
@@ -1,1278 +0,0 @@
|
|
|
1
|
-
import { a as queryGlobal, i as tenantId, n as resolvePrompt, o as queryWithGlobals, r as TenantScoped, t as definePrompt } from "./dist-DJVDHkyS.js";
|
|
2
|
-
import { ObjectRegistry, SmrtCollection, SmrtHierarchical, SmrtObject, detectEngine, field, foreignKey, smrt } from "@happyvertical/smrt-core";
|
|
3
|
-
import { BackfillTracker } from "@happyvertical/smrt-core/migrations";
|
|
4
|
-
//#region ../ledgers/dist/chunks/Account-b0RgfbjM.js
|
|
5
|
-
var __defProp$3 = Object.defineProperty;
|
|
6
|
-
var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
|
|
7
|
-
var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$3(obj, key, {
|
|
8
|
-
enumerable: true,
|
|
9
|
-
configurable: true,
|
|
10
|
-
writable: true,
|
|
11
|
-
value
|
|
12
|
-
}) : obj[key] = value;
|
|
13
|
-
var __decorateClass$2 = (decorators, target, key, kind) => {
|
|
14
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target;
|
|
15
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
16
|
-
if (kind && result) __defProp$3(target, key, result);
|
|
17
|
-
return result;
|
|
18
|
-
};
|
|
19
|
-
var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
20
|
-
var Account = class extends SmrtHierarchical {
|
|
21
|
-
tenantId = null;
|
|
22
|
-
number = "";
|
|
23
|
-
name = "";
|
|
24
|
-
description = "";
|
|
25
|
-
type = "asset";
|
|
26
|
-
active = true;
|
|
27
|
-
/**
|
|
28
|
-
* Extensible metadata
|
|
29
|
-
*/
|
|
30
|
-
metadata = {};
|
|
31
|
-
constructor(options = {}) {
|
|
32
|
-
super(options);
|
|
33
|
-
if (options.number !== void 0) this.number = options.number;
|
|
34
|
-
if (options.name !== void 0) this.name = options.name;
|
|
35
|
-
if (options.description !== void 0) this.description = options.description;
|
|
36
|
-
if (options.type !== void 0) this.type = options.type;
|
|
37
|
-
if (options.parentId !== void 0) this.parentId = options.parentId;
|
|
38
|
-
if (options.active !== void 0) this.active = options.active;
|
|
39
|
-
if (options.metadata !== void 0) this.metadata = options.metadata;
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* Check if this is a top-level account (no parent)
|
|
43
|
-
*/
|
|
44
|
-
isTopLevel() {
|
|
45
|
-
return this.parentId === null;
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* Check if this is a debit-normal account (Asset, Expense)
|
|
49
|
-
* Debit-normal accounts increase with debits
|
|
50
|
-
*/
|
|
51
|
-
isDebitNormal() {
|
|
52
|
-
return this.type === "asset" || this.type === "expense";
|
|
53
|
-
}
|
|
54
|
-
/**
|
|
55
|
-
* Check if this is a credit-normal account (Liability, Equity, Revenue)
|
|
56
|
-
* Credit-normal accounts increase with credits
|
|
57
|
-
*/
|
|
58
|
-
isCreditNormal() {
|
|
59
|
-
return this.type === "liability" || this.type === "equity" || this.type === "revenue";
|
|
60
|
-
}
|
|
61
|
-
/**
|
|
62
|
-
* Get full account path (e.g., "Assets > Current > Cash")
|
|
63
|
-
*/
|
|
64
|
-
async getFullPath() {
|
|
65
|
-
return [...(await this.getAncestors()).map((a) => a.name), this.name].join(" > ");
|
|
66
|
-
}
|
|
67
|
-
/**
|
|
68
|
-
* Build tree node for this account and its children
|
|
69
|
-
*/
|
|
70
|
-
async toTreeNode() {
|
|
71
|
-
const children = await this.getChildren();
|
|
72
|
-
const childNodes = await Promise.all(children.map((c) => c.toTreeNode()));
|
|
73
|
-
return {
|
|
74
|
-
account: this,
|
|
75
|
-
children: childNodes
|
|
76
|
-
};
|
|
77
|
-
}
|
|
78
|
-
/**
|
|
79
|
-
* Get the current balance of this account
|
|
80
|
-
*/
|
|
81
|
-
async getBalance(asOfDate) {
|
|
82
|
-
if (!this.id) return 0;
|
|
83
|
-
const { JournalEntryCollection } = await import("./dist-CRW60XkI.js").then((n) => n.t);
|
|
84
|
-
return await (await JournalEntryCollection.create(this.options)).getAccountBalance(this.id, asOfDate);
|
|
85
|
-
}
|
|
86
|
-
/**
|
|
87
|
-
* Create a sub-account under this account
|
|
88
|
-
*/
|
|
89
|
-
async createChild(options) {
|
|
90
|
-
if (!this.id) throw new Error("Account must be saved before creating children");
|
|
91
|
-
const { AccountCollection } = await import("./dist-CRW60XkI.js").then((n) => n.n);
|
|
92
|
-
const account = await (await AccountCollection.create(this.options)).create({
|
|
93
|
-
...options,
|
|
94
|
-
parentId: this.id,
|
|
95
|
-
type: this.type
|
|
96
|
-
});
|
|
97
|
-
await account.save();
|
|
98
|
-
return account;
|
|
99
|
-
}
|
|
100
|
-
};
|
|
101
|
-
__publicField$2(Account, "__smrtPackage__", "@happyvertical/smrt-ledgers");
|
|
102
|
-
__decorateClass$2([tenantId({ nullable: true })], Account.prototype, "tenantId", 2);
|
|
103
|
-
__decorateClass$2([field({ description: "The account number in your chart of accounts." })], Account.prototype, "number", 2);
|
|
104
|
-
__decorateClass$2([field({ description: "What the account is called." })], Account.prototype, "name", 2);
|
|
105
|
-
__decorateClass$2([field({ description: "What the account is used for." })], Account.prototype, "description", 2);
|
|
106
|
-
__decorateClass$2([field({ description: "asset, liability, equity, revenue or expense." })], Account.prototype, "type", 2);
|
|
107
|
-
__decorateClass$2([field({ description: "Whether the account is in use; deactivate it instead of deleting it." })], Account.prototype, "active", 2);
|
|
108
|
-
Account = __decorateClass$2([TenantScoped({ mode: "optional" }), smrt({
|
|
109
|
-
tableName: "ledger_accounts",
|
|
110
|
-
api: { include: [
|
|
111
|
-
"list",
|
|
112
|
-
"get",
|
|
113
|
-
"create",
|
|
114
|
-
"update",
|
|
115
|
-
"delete"
|
|
116
|
-
] },
|
|
117
|
-
mcp: { include: [
|
|
118
|
-
"list",
|
|
119
|
-
"get",
|
|
120
|
-
"create"
|
|
121
|
-
] },
|
|
122
|
-
cli: { skipApiCheck: true }
|
|
123
|
-
})], Account);
|
|
124
|
-
//#endregion
|
|
125
|
-
//#region ../ledgers/dist/types.js
|
|
126
|
-
var BALANCE_EPSILON = .001;
|
|
127
|
-
//#endregion
|
|
128
|
-
//#region ../ledgers/dist/index.js
|
|
129
|
-
var __defProp$2 = Object.defineProperty;
|
|
130
|
-
var __exportAll = (all, no_symbols) => {
|
|
131
|
-
let target = {};
|
|
132
|
-
for (var name in all) __defProp$2(target, name, {
|
|
133
|
-
get: all[name],
|
|
134
|
-
enumerable: true
|
|
135
|
-
});
|
|
136
|
-
if (!no_symbols) __defProp$2(target, Symbol.toStringTag, { value: "Module" });
|
|
137
|
-
return target;
|
|
138
|
-
};
|
|
139
|
-
ObjectRegistry.registerPackageManifest(JSON.parse(`{"version":"1.0.0","timestamp":0,"packageName":"@happyvertical/smrt-ledgers","packageVersion":"0.57.2","objects":{"@happyvertical/smrt-ledgers:AccountCollection":{"name":"accountcollection","className":"AccountCollection","qualifiedName":"@happyvertical/smrt-ledgers:AccountCollection","collection":"accounts","filePath":"/home/runner/work/smrt/smrt/packages/ledgers/src/collections/Accounts.ts","packageName":"@happyvertical/smrt-ledgers","fields":{},"methods":{"findByNumber":{"name":"findByNumber","async":true,"parameters":[{"name":"number","type":"string","optional":false}],"returnType":"Promise<Account | null>","isStatic":false,"isPublic":true},"findByType":{"name":"findByType","async":true,"parameters":[{"name":"type","type":"AccountType","optional":false}],"returnType":"Promise<Account[]>","isStatic":false,"isPublic":true},"findActive":{"name":"findActive","async":true,"parameters":[],"returnType":"Promise<Account[]>","isStatic":false,"isPublic":true},"findTopLevel":{"name":"findTopLevel","async":true,"parameters":[],"returnType":"Promise<Account[]>","isStatic":false,"isPublic":true},"findChildren":{"name":"findChildren","async":true,"parameters":[{"name":"parentId","type":"string","optional":false}],"returnType":"Promise<Account[]>","isStatic":false,"isPublic":true},"getTree":{"name":"getTree","async":true,"parameters":[],"returnType":"Promise<AccountTree>","isStatic":false,"isPublic":true},"getOrCreateByNumber":{"name":"getOrCreateByNumber","async":true,"parameters":[{"name":"number","type":"string","optional":false},{"name":"defaults","type":"Partial<object>","optional":true,"memberTypes":["string","AccountType","string | null"]}],"returnType":"Promise<Account>","isStatic":false,"isPublic":true},"groupByType":{"name":"groupByType","async":true,"parameters":[],"returnType":"Promise<Record<AccountType, Account[]>>","isStatic":false,"isPublic":true},"getDescendants":{"name":"getDescendants","async":true,"parameters":[{"name":"accountId","type":"string","optional":false}],"returnType":"Promise<Account[]>","isStatic":false,"isPublic":true},"findByTenant":{"name":"findByTenant","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Account[]>","isStatic":false,"isPublic":true},"findGlobal":{"name":"findGlobal","async":true,"parameters":[],"returnType":"Promise<Account[]>","isStatic":false,"isPublic":true},"findWithGlobals":{"name":"findWithGlobals","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Account[]>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"ledger_accounts","api":{"include":["list","get","create","update","delete"]},"mcp":{"include":["list","get","create"]}},"extends":"SmrtCollection","extendsTypeArg":"Account","exportName":"AccountCollection","collectionExportName":"AccountCollectionCollection","schema":{"tableName":"ledger_accounts","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);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"parent_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"ledger_accounts","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"number":{"type":"TEXT","notNull":false,"unique":false,"default":""},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"description":{"type":"TEXT","notNull":false,"unique":false,"default":""},"type":{"type":"TEXT","notNull":false,"unique":false,"default":"asset"},"active":{"type":"BOOLEAN","notNull":false,"unique":false,"default":true},"metadata":{"type":"JSON","notNull":false,"unique":false,"default":{}}},"indexes":[{"name":"ledger_accounts_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"ledger_accounts_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"ledger_accounts_parent_id_idx","columns":["parent_id"]}],"version":"49630dae"},"importPath":"@happyvertical/smrt-ledgers"},"@happyvertical/smrt-ledgers:JournalEntryCollection":{"name":"journalentrycollection","className":"JournalEntryCollection","qualifiedName":"@happyvertical/smrt-ledgers:JournalEntryCollection","collection":"journalentries","filePath":"/home/runner/work/smrt/smrt/packages/ledgers/src/collections/JournalEntries.ts","packageName":"@happyvertical/smrt-ledgers","fields":{},"methods":{"findByJournal":{"name":"findByJournal","async":true,"parameters":[{"name":"journalId","type":"string","optional":false}],"returnType":"Promise<JournalEntry[]>","isStatic":false,"isPublic":true},"findByAccount":{"name":"findByAccount","async":true,"parameters":[{"name":"accountId","type":"string","optional":false}],"returnType":"Promise<JournalEntry[]>","isStatic":false,"isPublic":true},"getAccountBalance":{"name":"getAccountBalance","async":true,"parameters":[{"name":"accountId","type":"string","optional":false},{"name":"asOfDate","type":"Date","optional":true}],"returnType":"Promise<number>","isStatic":false,"isPublic":true},"getTrialBalance":{"name":"getTrialBalance","async":true,"parameters":[{"name":"asOfDate","type":"Date","optional":true}],"returnType":"Promise<TrialBalanceRow[]>","isStatic":false,"isPublic":true},"getTotalsForDateRange":{"name":"getTotalsForDateRange","async":true,"parameters":[{"name":"start","type":"Date","optional":false},{"name":"end","type":"Date","optional":false}],"returnType":"Promise<object>","isStatic":false,"isPublic":true},"findByAccounts":{"name":"findByAccounts","async":true,"parameters":[{"name":"accountIds","type":"string[]","optional":false}],"returnType":"Promise<JournalEntry[]>","isStatic":false,"isPublic":true},"listPostedMovements":{"name":"listPostedMovements","async":true,"parameters":[{"name":"options","type":"PostedJournalMovementOptions","optional":false}],"returnType":"Promise<PostedJournalMovement[]>","isStatic":false,"isPublic":true},"getAccountLedger":{"name":"getAccountLedger","async":true,"parameters":[{"name":"accountId","type":"string","optional":false}],"returnType":"Promise<Array<object>>","isStatic":false,"isPublic":true},"findByTenant":{"name":"findByTenant","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<JournalEntry[]>","isStatic":false,"isPublic":true},"findGlobal":{"name":"findGlobal","async":true,"parameters":[],"returnType":"Promise<JournalEntry[]>","isStatic":false,"isPublic":true},"findWithGlobals":{"name":"findWithGlobals","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<JournalEntry[]>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"JournalEntry","exportName":"JournalEntryCollection","collectionExportName":"JournalEntryCollectionCollection","schema":{"tableName":"journal_entries","ddl":"CREATE TABLE IF NOT EXISTS \\"journal_entries\\" (\\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 \\"tenant_id\\" UUID,\\n \\"journal_id\\" UUID,\\n \\"account_id\\" UUID,\\n \\"debit\\" REAL DEFAULT 0,\\n \\"credit\\" REAL DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"exchange_rate\\" REAL DEFAULT 1,\\n \\"memo\\" TEXT DEFAULT '',\\n \\"metadata\\" JSON DEFAULT '{}'\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"journal_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"journals","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"account_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"ledger_accounts","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"debit":{"type":"REAL","notNull":false,"unique":false,"default":0},"credit":{"type":"REAL","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"exchange_rate":{"type":"REAL","notNull":false,"unique":false,"default":1},"memo":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metadata":{"type":"JSON","notNull":false,"unique":false,"default":{}}},"indexes":[{"name":"journal_entries_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"journal_entries_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"journal_entries_journal_id_idx","columns":["journal_id"]},{"name":"journal_entries_account_id_idx","columns":["account_id"]}],"version":"93cdc848"},"importPath":"@happyvertical/smrt-ledgers"},"@happyvertical/smrt-ledgers:JournalCollection":{"name":"journalcollection","className":"JournalCollection","qualifiedName":"@happyvertical/smrt-ledgers:JournalCollection","collection":"journals","filePath":"/home/runner/work/smrt/smrt/packages/ledgers/src/collections/Journals.ts","packageName":"@happyvertical/smrt-ledgers","fields":{},"methods":{"findByNumber":{"name":"findByNumber","async":true,"parameters":[{"name":"number","type":"string","optional":false}],"returnType":"Promise<Journal | null>","isStatic":false,"isPublic":true},"findByDateRange":{"name":"findByDateRange","async":true,"parameters":[{"name":"start","type":"Date","optional":false},{"name":"end","type":"Date","optional":false}],"returnType":"Promise<Journal[]>","isStatic":false,"isPublic":true},"findBySource":{"name":"findBySource","async":true,"parameters":[{"name":"sourceModule","type":"string","optional":false}],"returnType":"Promise<Journal[]>","isStatic":false,"isPublic":true},"findByStatus":{"name":"findByStatus","async":true,"parameters":[{"name":"status","type":"JournalStatus","optional":false}],"returnType":"Promise<Journal[]>","isStatic":false,"isPublic":true},"findDrafts":{"name":"findDrafts","async":true,"parameters":[],"returnType":"Promise<Journal[]>","isStatic":false,"isPublic":true},"findPosted":{"name":"findPosted","async":true,"parameters":[],"returnType":"Promise<Journal[]>","isStatic":false,"isPublic":true},"createWithEntries":{"name":"createWithEntries","async":true,"parameters":[{"name":"data","type":"CreateJournalData","optional":false}],"returnType":"Promise<Journal>","isStatic":false,"isPublic":true},"post":{"name":"post","async":true,"parameters":[{"name":"journalId","type":"string","optional":false}],"returnType":"Promise<Journal>","isStatic":false,"isPublic":true},"void":{"name":"void","async":true,"parameters":[{"name":"journalId","type":"string","optional":false},{"name":"reason","type":"string","optional":false}],"returnType":"Promise<Journal>","isStatic":false,"isPublic":true},"findBySourceRef":{"name":"findBySourceRef","async":true,"parameters":[{"name":"sourceRef","type":"string","optional":false}],"returnType":"Promise<Journal[]>","isStatic":false,"isPublic":true},"findByMonth":{"name":"findByMonth","async":true,"parameters":[{"name":"year","type":"number","optional":false},{"name":"month","type":"number","optional":false}],"returnType":"Promise<Journal[]>","isStatic":false,"isPublic":true},"findByTenant":{"name":"findByTenant","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Journal[]>","isStatic":false,"isPublic":true},"findGlobal":{"name":"findGlobal","async":true,"parameters":[],"returnType":"Promise<Journal[]>","isStatic":false,"isPublic":true},"findWithGlobals":{"name":"findWithGlobals","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Journal[]>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get","create"]},"mcp":{"include":["list","get","create"]}},"extends":"SmrtCollection","extendsTypeArg":"Journal","exportName":"JournalCollection","collectionExportName":"JournalCollectionCollection","schema":{"tableName":"journals","ddl":"CREATE TABLE IF NOT EXISTS \\"journals\\" (\\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 \\"tenant_id\\" UUID,\\n \\"number\\" TEXT DEFAULT '',\\n \\"date\\" TIMESTAMP,\\n \\"description\\" TEXT DEFAULT '',\\n \\"source_module\\" TEXT DEFAULT '',\\n \\"source_ref\\" TEXT,\\n \\"status\\" TEXT DEFAULT 'draft',\\n \\"posted_at\\" TIMESTAMP,\\n \\"voided_at\\" TIMESTAMP,\\n \\"void_reason\\" TEXT,\\n \\"metadata\\" JSON DEFAULT '{}'\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"number":{"type":"TEXT","notNull":false,"unique":false,"default":""},"date":{"type":"TIMESTAMP","notNull":false,"unique":false},"description":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source_module":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source_ref":{"type":"TEXT","notNull":false,"unique":false},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"draft"},"posted_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"voided_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"void_reason":{"type":"TEXT","notNull":false,"unique":false},"metadata":{"type":"JSON","notNull":false,"unique":false,"default":{}}},"indexes":[{"name":"journals_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"journals_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"4b51d204"},"importPath":"@happyvertical/smrt-ledgers"},"@happyvertical/smrt-ledgers:Account":{"name":"account","className":"Account","qualifiedName":"@happyvertical/smrt-ledgers:Account","collection":"accounts","filePath":"/home/runner/work/smrt/smrt/packages/ledgers/src/models/Account.ts","packageName":"@happyvertical/smrt-ledgers","fields":{"parentId":{"type":"foreignKey","required":false,"related":"Account","_meta":{"nullable":true}},"tenantId":{"type":"text","required":false,"_meta":{"sqlType":"UUID","nullable":true,"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false}}},"number":{"type":"text","required":false,"default":"","description":"The account number in your chart of accounts.","_meta":{"description":"The account number in your chart of accounts."}},"name":{"type":"text","required":false,"default":"","description":"What the account is called.","_meta":{"description":"What the account is called."}},"description":{"type":"text","required":false,"default":"","description":"What the account is used for.","_meta":{"description":"What the account is used for."}},"type":{"type":"text","required":false,"default":"asset","description":"asset, liability, equity, revenue or expense.","_meta":{"description":"asset, liability, equity, revenue or expense."},"enum":["asset","liability","equity","revenue","expense"]},"active":{"type":"boolean","required":false,"default":true,"description":"Whether the account is in use; deactivate it instead of deleting it.","_meta":{"description":"Whether the account is in use; deactivate it instead of deleting it."}},"metadata":{"type":"json","required":false,"default":{}}},"methods":{"getParent":{"name":"getParent","async":true,"parameters":[],"returnType":"Promise<this | null>","isStatic":false,"isPublic":true},"getChildren":{"name":"getChildren","async":true,"parameters":[],"returnType":"Promise<this[]>","isStatic":false,"isPublic":true},"getAncestors":{"name":"getAncestors","async":true,"parameters":[],"returnType":"Promise<this[]>","isStatic":false,"isPublic":true},"getDescendants":{"name":"getDescendants","async":true,"parameters":[],"returnType":"Promise<this[]>","isStatic":false,"isPublic":true},"getHierarchy":{"name":"getHierarchy","async":true,"parameters":[],"returnType":"Promise<HierarchyView<this>>","isStatic":false,"isPublic":true},"moveTo":{"name":"moveTo","async":true,"parameters":[{"name":"newParent","type":"this | string | null","optional":false,"unionBranches":[{"type":"this"},{"type":"string"},{"type":"null"}]}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"isTopLevel":{"name":"isTopLevel","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isDebitNormal":{"name":"isDebitNormal","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isCreditNormal":{"name":"isCreditNormal","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"getFullPath":{"name":"getFullPath","async":true,"parameters":[],"returnType":"Promise<string>","isStatic":false,"isPublic":true},"toTreeNode":{"name":"toTreeNode","async":true,"parameters":[],"returnType":"Promise<AccountTreeNode>","isStatic":false,"isPublic":true},"getBalance":{"name":"getBalance","async":true,"parameters":[{"name":"asOfDate","type":"Date","optional":true}],"returnType":"Promise<number>","isStatic":false,"isPublic":true},"createChild":{"name":"createChild","async":true,"parameters":[{"name":"options","type":"Omit<AccountOptions, 'parentId' | 'type'>","optional":false}],"returnType":"Promise<Account>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"ledger_accounts","api":{"include":["list","get","create","update","delete"]},"mcp":{"include":["list","get","create"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"optional"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtHierarchical","exportName":"Account","collectionExportName":"AccountCollection","displayLabelField":"name","schema":{"tableName":"ledger_accounts","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);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"parent_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"ledger_accounts","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"number":{"type":"TEXT","notNull":false,"unique":false,"default":""},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"description":{"type":"TEXT","notNull":false,"unique":false,"default":""},"type":{"type":"TEXT","notNull":false,"unique":false,"default":"asset"},"active":{"type":"BOOLEAN","notNull":false,"unique":false,"default":true},"metadata":{"type":"JSON","notNull":false,"unique":false,"default":{}}},"indexes":[{"name":"ledger_accounts_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"ledger_accounts_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"ledger_accounts_parent_id_idx","columns":["parent_id"]}],"version":"49630dae"},"importPath":"@happyvertical/smrt-ledgers"},"@happyvertical/smrt-ledgers:Journal":{"name":"journal","className":"Journal","qualifiedName":"@happyvertical/smrt-ledgers:Journal","collection":"journals","filePath":"/home/runner/work/smrt/smrt/packages/ledgers/src/models/Journal.ts","packageName":"@happyvertical/smrt-ledgers","fields":{"tenantId":{"type":"text","required":false,"_meta":{"sqlType":"UUID","nullable":true,"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false}}},"number":{"type":"text","required":false,"default":"","description":"The journal's reference number.","_meta":{"description":"The journal's reference number."}},"date":{"type":"datetime","required":false,"description":"The date of the transaction.","_meta":{"description":"The date of the transaction."}},"description":{"type":"text","required":false,"default":"","description":"What the transaction was.","_meta":{"description":"What the transaction was."}},"sourceModule":{"type":"text","required":false,"default":""},"sourceRef":{"type":"text","required":false},"status":{"type":"text","required":false,"default":"draft","description":"draft until final, then posted, or voided.","_meta":{"description":"draft until final, then posted, or voided."},"enum":["draft","posted","voided"]},"postedAt":{"type":"datetime","required":false,"description":"When it was posted.","_meta":{"description":"When it was posted."}},"voidedAt":{"type":"datetime","required":false},"voidReason":{"type":"text","required":false},"metadata":{"type":"json","required":false,"default":{}}},"methods":{"isDraft":{"name":"isDraft","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isPosted":{"name":"isPosted","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isVoided":{"name":"isVoided","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isEditable":{"name":"isEditable","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"getEntries":{"name":"getEntries","async":true,"parameters":[],"returnType":"any","isStatic":false,"isPublic":true},"getTotalDebits":{"name":"getTotalDebits","async":true,"parameters":[],"returnType":"Promise<number>","isStatic":false,"isPublic":true},"getTotalCredits":{"name":"getTotalCredits","async":true,"parameters":[],"returnType":"Promise<number>","isStatic":false,"isPublic":true},"isBalanced":{"name":"isBalanced","async":true,"parameters":[],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"addEntry":{"name":"addEntry","async":true,"parameters":[{"name":"data","type":"JournalEntryData","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"post":{"name":"post","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"void":{"name":"void","async":true,"parameters":[{"name":"reason","type":"string","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"summarize":{"name":"summarize","async":true,"parameters":[],"returnType":"Promise<string>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get","create"]},"mcp":{"include":["list","get","create"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"optional"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"Journal","collectionExportName":"JournalCollection","schema":{"tableName":"journals","ddl":"CREATE TABLE IF NOT EXISTS \\"journals\\" (\\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 \\"tenant_id\\" UUID,\\n \\"number\\" TEXT DEFAULT '',\\n \\"date\\" TIMESTAMP,\\n \\"description\\" TEXT DEFAULT '',\\n \\"source_module\\" TEXT DEFAULT '',\\n \\"source_ref\\" TEXT,\\n \\"status\\" TEXT DEFAULT 'draft',\\n \\"posted_at\\" TIMESTAMP,\\n \\"voided_at\\" TIMESTAMP,\\n \\"void_reason\\" TEXT,\\n \\"metadata\\" JSON DEFAULT '{}'\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"number":{"type":"TEXT","notNull":false,"unique":false,"default":""},"date":{"type":"TIMESTAMP","notNull":false,"unique":false},"description":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source_module":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source_ref":{"type":"TEXT","notNull":false,"unique":false},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"draft"},"posted_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"voided_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"void_reason":{"type":"TEXT","notNull":false,"unique":false},"metadata":{"type":"JSON","notNull":false,"unique":false,"default":{}}},"indexes":[{"name":"journals_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"journals_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"4b51d204"},"importPath":"@happyvertical/smrt-ledgers"},"@happyvertical/smrt-ledgers:JournalEntry":{"name":"journalentry","className":"JournalEntry","qualifiedName":"@happyvertical/smrt-ledgers:JournalEntry","collection":"journalentries","filePath":"/home/runner/work/smrt/smrt/packages/ledgers/src/models/JournalEntry.ts","packageName":"@happyvertical/smrt-ledgers","fields":{"tenantId":{"type":"text","required":false,"_meta":{"sqlType":"UUID","nullable":true,"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false}}},"journalId":{"type":"foreignKey","required":false,"related":"Journal","description":"The journal this entry belongs to.","_meta":{"description":"The journal this entry belongs to."}},"accountId":{"type":"foreignKey","required":false,"related":"Account","description":"The account this entry changes.","_meta":{"description":"The account this entry changes."}},"debit":{"type":"decimal","required":false,"default":0,"description":"The amount debited. Zero on a credit entry.","_meta":{"description":"The amount debited. Zero on a credit entry."}},"credit":{"type":"decimal","required":false,"default":0,"description":"The amount credited. Zero on a debit entry.","_meta":{"description":"The amount credited. Zero on a debit entry."}},"currency":{"type":"text","required":false,"default":"USD","description":"The currency of the amounts.","_meta":{"description":"The currency of the amounts."}},"exchangeRate":{"type":"decimal","required":false,"default":1},"memo":{"type":"text","required":false,"default":"","description":"A note on this entry.","_meta":{"description":"A note on this entry."}},"metadata":{"type":"json","required":false,"default":{}}},"methods":{"isDebit":{"name":"isDebit","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isCredit":{"name":"isCredit","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"getAmount":{"name":"getAmount","async":false,"parameters":[],"returnType":"number","isStatic":false,"isPublic":true},"getBaseAmount":{"name":"getBaseAmount","async":false,"parameters":[],"returnType":"number","isStatic":false,"isPublic":true},"getJournal":{"name":"getJournal","async":true,"parameters":[],"returnType":"any","isStatic":false,"isPublic":true},"getAccount":{"name":"getAccount","async":true,"parameters":[],"returnType":"any","isStatic":false,"isPublic":true},"getDescription":{"name":"getDescription","async":true,"parameters":[],"returnType":"Promise<string>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"optional"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"JournalEntry","collectionExportName":"JournalEntryCollection","schema":{"tableName":"journal_entries","ddl":"CREATE TABLE IF NOT EXISTS \\"journal_entries\\" (\\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 \\"tenant_id\\" UUID,\\n \\"journal_id\\" UUID,\\n \\"account_id\\" UUID,\\n \\"debit\\" REAL DEFAULT 0,\\n \\"credit\\" REAL DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"exchange_rate\\" REAL DEFAULT 1,\\n \\"memo\\" TEXT DEFAULT '',\\n \\"metadata\\" JSON DEFAULT '{}'\\n);","columns":{"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"journal_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"journals","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"account_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"ledger_accounts","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"debit":{"type":"REAL","notNull":false,"unique":false,"default":0},"credit":{"type":"REAL","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"exchange_rate":{"type":"REAL","notNull":false,"unique":false,"default":1},"memo":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metadata":{"type":"JSON","notNull":false,"unique":false,"default":{}}},"indexes":[{"name":"journal_entries_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"journal_entries_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"journal_entries_journal_id_idx","columns":["journal_id"]},{"name":"journal_entries_account_id_idx","columns":["account_id"]}],"version":"93cdc848"},"importPath":"@happyvertical/smrt-ledgers"}},"moduleType":"smrt","recipes":[{"id":"ledgers.bookkeeping","className":"BookkeepingRecipe","label":"Bookkeeping","summary":"Keep your books: a chart of accounts and double-entry journals.","synonyms":["accounting","ledger","general ledger","journals","chart of accounts"],"models":["@happyvertical/smrt-ledgers:Account","@happyvertical/smrt-ledgers:Journal","@happyvertical/smrt-ledgers:JournalEntry"],"nav":[{"label":"Accounts","model":"@happyvertical/smrt-ledgers:Account","icon":"bank","description":"The accounts your books are kept in, like sales, rent and bank."},{"label":"Journals","model":"@happyvertical/smrt-ledgers:Journal","icon":"book","description":"The entries behind your accounts, so every dollar has a trail."}],"requires":[],"section":{"id":"accounting","label":"Accounting","icon":"bank","description":"Your books: accounts, journals and balances."},"options":{"@happyvertical/smrt-ledgers:Account":{"fields":{"metadata":{"visibility":"hidden"},"parentId":{"visibility":"hidden"}}},"@happyvertical/smrt-ledgers:Journal":{"fields":{"sourceModule":{"visibility":"hidden"},"sourceRef":{"visibility":"hidden"},"voidedAt":{"visibility":"hidden"},"voidReason":{"visibility":"hidden"},"metadata":{"visibility":"hidden"}}},"@happyvertical/smrt-ledgers:JournalEntry":{"fields":{"exchangeRate":{"visibility":"hidden"},"metadata":{"visibility":"hidden"}}}},"help":{"markdown":"## Overview\\n\\nBookkeeping keeps your accounts. You list the accounts you use (your chart of\\naccounts) and record each transaction as a journal whose entries debit and\\ncredit those accounts.\\n\\n## Tasks\\n\\n### Set up your accounts\\n\\n1. Create a new account.\\n2. Give it a **{field:number}** and a **{field:name}**.\\n3. Choose its **{field:type}**: asset, liability, equity, revenue or expense.\\n\\n### Record a transaction\\n\\n1. Create a new journal and add a **{field:description}**.\\n2. Add entries: pick the account on each and enter a **{field:debit}** or a\\n **{field:credit}**. They must add up to the same total.\\n3. Set the journal's **{field:status}** to posted when it is final. A posted\\n journal is voided, not edited.\\n","fieldRefs":["credit","debit","description","name","number","status","type"]},"demo":{"mode":"server","reasons":["Needs a server because its package does not build for a browser: core migrations (node:os, node:crypto); and its package depends on @happyvertical/smrt-tenancy, which do not build for a browser (#3624, #3626)."]}}],"smrtDependencies":["@happyvertical/smrt-core","@happyvertical/smrt-prompts","@happyvertical/smrt-tenancy"],"browser":{"status":"server-only","issues":["#3624","#3626"],"reason":"core migrations (node:os, node:crypto)","via":["@happyvertical/smrt-tenancy"]},"stampsConstructors":true}`));
|
|
140
|
-
var smrtLedgersJournalSummarizePrompt = definePrompt({
|
|
141
|
-
key: "smrtLedgers.journal.summarize",
|
|
142
|
-
template: `Summarize this accounting journal entry:
|
|
143
|
-
Number: {journalNumber}
|
|
144
|
-
Date: {journalDate}
|
|
145
|
-
Description: {journalDescription}
|
|
146
|
-
Status: {journalStatus}
|
|
147
|
-
Total: {journalTotal}
|
|
148
|
-
Entries: {entryCount}
|
|
149
|
-
Balanced: {journalBalanced}`,
|
|
150
|
-
editable: {
|
|
151
|
-
template: true,
|
|
152
|
-
profile: true,
|
|
153
|
-
model: true,
|
|
154
|
-
params: true
|
|
155
|
-
}
|
|
156
|
-
});
|
|
157
|
-
function promptMessageOptions(ai) {
|
|
158
|
-
return {
|
|
159
|
-
...ai.params || {},
|
|
160
|
-
...ai.model ? { model: ai.model } : {},
|
|
161
|
-
...typeof ai.temperature === "number" ? { temperature: ai.temperature } : {},
|
|
162
|
-
...typeof ai.maxTokens === "number" ? { maxTokens: ai.maxTokens } : {}
|
|
163
|
-
};
|
|
164
|
-
}
|
|
165
|
-
var Accounts_exports = /* @__PURE__ */ __exportAll({ AccountCollection: () => AccountCollection });
|
|
166
|
-
var AccountCollection = class extends SmrtCollection {
|
|
167
|
-
static _itemClass = Account;
|
|
168
|
-
/**
|
|
169
|
-
* Find account by number
|
|
170
|
-
*
|
|
171
|
-
* @param number - Account number
|
|
172
|
-
* @returns Account or null
|
|
173
|
-
*/
|
|
174
|
-
async findByNumber(number) {
|
|
175
|
-
return (await this.list({
|
|
176
|
-
where: { number },
|
|
177
|
-
limit: 1
|
|
178
|
-
}))[0] || null;
|
|
179
|
-
}
|
|
180
|
-
/**
|
|
181
|
-
* Find accounts by type
|
|
182
|
-
*
|
|
183
|
-
* @param type - Account type
|
|
184
|
-
* @returns Array of accounts
|
|
185
|
-
*/
|
|
186
|
-
async findByType(type) {
|
|
187
|
-
return await this.list({
|
|
188
|
-
where: { type },
|
|
189
|
-
orderBy: "number ASC"
|
|
190
|
-
});
|
|
191
|
-
}
|
|
192
|
-
/**
|
|
193
|
-
* Find all active accounts
|
|
194
|
-
*
|
|
195
|
-
* @returns Array of active accounts
|
|
196
|
-
*/
|
|
197
|
-
async findActive() {
|
|
198
|
-
return await this.list({
|
|
199
|
-
where: { active: true },
|
|
200
|
-
orderBy: "number ASC"
|
|
201
|
-
});
|
|
202
|
-
}
|
|
203
|
-
/**
|
|
204
|
-
* Find top-level accounts (no parent)
|
|
205
|
-
*
|
|
206
|
-
* @returns Array of top-level accounts
|
|
207
|
-
*/
|
|
208
|
-
async findTopLevel() {
|
|
209
|
-
return await this.list({
|
|
210
|
-
where: { parentId: null },
|
|
211
|
-
orderBy: "number ASC"
|
|
212
|
-
});
|
|
213
|
-
}
|
|
214
|
-
/**
|
|
215
|
-
* Find direct children of an account
|
|
216
|
-
*
|
|
217
|
-
* @param parentId - Parent account ID
|
|
218
|
-
* @returns Array of child accounts
|
|
219
|
-
*/
|
|
220
|
-
async findChildren(parentId) {
|
|
221
|
-
return await this.list({
|
|
222
|
-
where: { parentId },
|
|
223
|
-
orderBy: "number ASC"
|
|
224
|
-
});
|
|
225
|
-
}
|
|
226
|
-
/**
|
|
227
|
-
* Get the complete account tree
|
|
228
|
-
*
|
|
229
|
-
* @returns AccountTree structure
|
|
230
|
-
*/
|
|
231
|
-
async getTree() {
|
|
232
|
-
const allAccounts = await this.list({ orderBy: "number ASC" });
|
|
233
|
-
const accountMap = /* @__PURE__ */ new Map();
|
|
234
|
-
const childrenMap = /* @__PURE__ */ new Map();
|
|
235
|
-
for (const account of allAccounts) {
|
|
236
|
-
if (account.id) accountMap.set(account.id, account);
|
|
237
|
-
if (!childrenMap.has(account.parentId || "")) childrenMap.set(account.parentId || "", []);
|
|
238
|
-
childrenMap.get(account.parentId || "")?.push(account);
|
|
239
|
-
}
|
|
240
|
-
const buildNode = (account) => {
|
|
241
|
-
return {
|
|
242
|
-
account,
|
|
243
|
-
children: ((account.id ? childrenMap.get(account.id) : []) || []).map(buildNode)
|
|
244
|
-
};
|
|
245
|
-
};
|
|
246
|
-
return { roots: (childrenMap.get("") || []).map(buildNode) };
|
|
247
|
-
}
|
|
248
|
-
/**
|
|
249
|
-
* Get or create an account by number
|
|
250
|
-
*
|
|
251
|
-
* @param number - Account number
|
|
252
|
-
* @param defaults - Default values if creating
|
|
253
|
-
* @returns Account
|
|
254
|
-
*/
|
|
255
|
-
async getOrCreateByNumber(number, defaults = {}) {
|
|
256
|
-
const existing = await this.findByNumber(number);
|
|
257
|
-
if (existing) return existing;
|
|
258
|
-
const account = await this.create({
|
|
259
|
-
number,
|
|
260
|
-
name: defaults.name || number,
|
|
261
|
-
description: defaults.description || "",
|
|
262
|
-
type: defaults.type || "asset",
|
|
263
|
-
parentId: defaults.parentId || null
|
|
264
|
-
});
|
|
265
|
-
await account.save();
|
|
266
|
-
return account;
|
|
267
|
-
}
|
|
268
|
-
/**
|
|
269
|
-
* Find accounts grouped by type
|
|
270
|
-
*
|
|
271
|
-
* @returns Record of type to accounts array
|
|
272
|
-
*/
|
|
273
|
-
async groupByType() {
|
|
274
|
-
const accounts = await this.findActive();
|
|
275
|
-
const grouped = {
|
|
276
|
-
asset: [],
|
|
277
|
-
liability: [],
|
|
278
|
-
equity: [],
|
|
279
|
-
revenue: [],
|
|
280
|
-
expense: []
|
|
281
|
-
};
|
|
282
|
-
for (const account of accounts) grouped[account.type].push(account);
|
|
283
|
-
return grouped;
|
|
284
|
-
}
|
|
285
|
-
/**
|
|
286
|
-
* Get all descendants of an account recursively
|
|
287
|
-
*
|
|
288
|
-
* @param accountId - Account ID
|
|
289
|
-
* @returns Array of all descendant accounts
|
|
290
|
-
*/
|
|
291
|
-
async getDescendants(accountId) {
|
|
292
|
-
const descendants = [];
|
|
293
|
-
const queue = [accountId];
|
|
294
|
-
while (queue.length > 0) {
|
|
295
|
-
const currentId = queue.shift();
|
|
296
|
-
if (!currentId) continue;
|
|
297
|
-
const children = await this.findChildren(currentId);
|
|
298
|
-
for (const child of children) {
|
|
299
|
-
descendants.push(child);
|
|
300
|
-
if (child.id) queue.push(child.id);
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
return descendants;
|
|
304
|
-
}
|
|
305
|
-
/**
|
|
306
|
-
* Find all accounts belonging to a specific tenant
|
|
307
|
-
*
|
|
308
|
-
* @param tenantId - Tenant ID
|
|
309
|
-
* @returns Array of tenant's accounts
|
|
310
|
-
*/
|
|
311
|
-
async findByTenant(tenantId) {
|
|
312
|
-
return this.list({ where: { tenantId } });
|
|
313
|
-
}
|
|
314
|
-
/**
|
|
315
|
-
* Find all global accounts (no tenant association).
|
|
316
|
-
*
|
|
317
|
-
* Routes through the shared tenant-global helper so it does not throw under
|
|
318
|
-
* an active tenant context (an explicit `tenant_id IS NULL` filter would be
|
|
319
|
-
* flagged as an isolation violation). (#1600)
|
|
320
|
-
*
|
|
321
|
-
* @returns Array of global accounts
|
|
322
|
-
*/
|
|
323
|
-
async findGlobal() {
|
|
324
|
-
return queryGlobal(this);
|
|
325
|
-
}
|
|
326
|
-
/**
|
|
327
|
-
* Find accounts for a tenant plus all global accounts.
|
|
328
|
-
*
|
|
329
|
-
* Fails closed if an active tenant context requests a different tenant's
|
|
330
|
-
* rows; the admin/system path keeps the cross-tenant capability. (#1600)
|
|
331
|
-
*
|
|
332
|
-
* @param tenantId - Tenant ID
|
|
333
|
-
* @returns Array of tenant's accounts and global accounts
|
|
334
|
-
*/
|
|
335
|
-
async findWithGlobals(tenantId) {
|
|
336
|
-
return queryWithGlobals(this, tenantId, "Account.findWithGlobals");
|
|
337
|
-
}
|
|
338
|
-
};
|
|
339
|
-
var __defProp$1 = Object.defineProperty;
|
|
340
|
-
var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
|
|
341
|
-
var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, {
|
|
342
|
-
enumerable: true,
|
|
343
|
-
configurable: true,
|
|
344
|
-
writable: true,
|
|
345
|
-
value
|
|
346
|
-
}) : obj[key] = value;
|
|
347
|
-
var __decorateClass$1 = (decorators, target, key, kind) => {
|
|
348
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
|
|
349
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
350
|
-
if (kind && result) __defProp$1(target, key, result);
|
|
351
|
-
return result;
|
|
352
|
-
};
|
|
353
|
-
var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
354
|
-
var JournalEntry = class extends SmrtObject {
|
|
355
|
-
tenantId = null;
|
|
356
|
-
journalId = "";
|
|
357
|
-
accountId = "";
|
|
358
|
-
debit = 0;
|
|
359
|
-
credit = 0;
|
|
360
|
-
currency = "USD";
|
|
361
|
-
/**
|
|
362
|
-
* Exchange rate to base currency
|
|
363
|
-
*/
|
|
364
|
-
exchangeRate = 1;
|
|
365
|
-
memo = "";
|
|
366
|
-
/**
|
|
367
|
-
* Extensible metadata
|
|
368
|
-
*/
|
|
369
|
-
metadata = {};
|
|
370
|
-
constructor(options = {}) {
|
|
371
|
-
super(options);
|
|
372
|
-
if (options.journalId !== void 0) this.journalId = options.journalId;
|
|
373
|
-
if (options.accountId !== void 0) this.accountId = options.accountId;
|
|
374
|
-
if (options.debit !== void 0) this.debit = options.debit;
|
|
375
|
-
if (options.credit !== void 0) this.credit = options.credit;
|
|
376
|
-
if (options.currency !== void 0) this.currency = options.currency;
|
|
377
|
-
if (options.exchangeRate !== void 0) this.exchangeRate = options.exchangeRate;
|
|
378
|
-
if (options.memo !== void 0) this.memo = options.memo;
|
|
379
|
-
if (options.metadata !== void 0) this.metadata = options.metadata;
|
|
380
|
-
}
|
|
381
|
-
/**
|
|
382
|
-
* Validate entry before save
|
|
383
|
-
*/
|
|
384
|
-
async validateBeforeSave() {
|
|
385
|
-
await super.validateBeforeSave();
|
|
386
|
-
if (this.debit < 0) throw new Error("Debit amount cannot be negative");
|
|
387
|
-
if (this.credit < 0) throw new Error("Credit amount cannot be negative");
|
|
388
|
-
if (this.debit > 0 && this.credit > 0) throw new Error("Entry cannot have both debit and credit amounts");
|
|
389
|
-
if (this.debit === 0 && this.credit === 0) throw new Error("Entry must have either a debit or credit amount");
|
|
390
|
-
if (this.exchangeRate <= 0) throw new Error("Exchange rate must be positive");
|
|
391
|
-
}
|
|
392
|
-
/**
|
|
393
|
-
* Check if this is a debit entry
|
|
394
|
-
*/
|
|
395
|
-
isDebit() {
|
|
396
|
-
return this.debit > 0;
|
|
397
|
-
}
|
|
398
|
-
/**
|
|
399
|
-
* Check if this is a credit entry
|
|
400
|
-
*/
|
|
401
|
-
isCredit() {
|
|
402
|
-
return this.credit > 0;
|
|
403
|
-
}
|
|
404
|
-
/**
|
|
405
|
-
* Get the entry amount (positive value regardless of debit/credit)
|
|
406
|
-
*/
|
|
407
|
-
getAmount() {
|
|
408
|
-
return this.debit > 0 ? this.debit : this.credit;
|
|
409
|
-
}
|
|
410
|
-
/**
|
|
411
|
-
* Get the amount in base currency
|
|
412
|
-
*/
|
|
413
|
-
getBaseAmount() {
|
|
414
|
-
return this.getAmount() * this.exchangeRate;
|
|
415
|
-
}
|
|
416
|
-
/**
|
|
417
|
-
* Get the parent journal
|
|
418
|
-
*/
|
|
419
|
-
async getJournal() {
|
|
420
|
-
if (!this.journalId) return null;
|
|
421
|
-
const { JournalCollection } = await Promise.resolve().then(() => Journals_exports);
|
|
422
|
-
return await (await JournalCollection.create(this.options)).get({ id: this.journalId });
|
|
423
|
-
}
|
|
424
|
-
/**
|
|
425
|
-
* Get the account
|
|
426
|
-
*/
|
|
427
|
-
async getAccount() {
|
|
428
|
-
if (!this.accountId) return null;
|
|
429
|
-
const { AccountCollection } = await Promise.resolve().then(() => Accounts_exports);
|
|
430
|
-
return await (await AccountCollection.create(this.options)).get({ id: this.accountId });
|
|
431
|
-
}
|
|
432
|
-
/**
|
|
433
|
-
* Get a formatted description of this entry
|
|
434
|
-
*/
|
|
435
|
-
async getDescription() {
|
|
436
|
-
const accountName = (await this.getAccount())?.name || "Unknown Account";
|
|
437
|
-
return `${this.isDebit() ? "DR" : "CR"} ${accountName}: $${this.getAmount().toFixed(2)}${this.memo ? ` - ${this.memo}` : ""}`;
|
|
438
|
-
}
|
|
439
|
-
};
|
|
440
|
-
__publicField$1(JournalEntry, "__smrtPackage__", "@happyvertical/smrt-ledgers");
|
|
441
|
-
__decorateClass$1([tenantId({ nullable: true })], JournalEntry.prototype, "tenantId", 2);
|
|
442
|
-
__decorateClass$1([field({ description: "The journal this entry belongs to." }), foreignKey("Journal")], JournalEntry.prototype, "journalId", 2);
|
|
443
|
-
__decorateClass$1([field({ description: "The account this entry changes." }), foreignKey(Account)], JournalEntry.prototype, "accountId", 2);
|
|
444
|
-
__decorateClass$1([field({ description: "The amount debited. Zero on a credit entry." })], JournalEntry.prototype, "debit", 2);
|
|
445
|
-
__decorateClass$1([field({ description: "The amount credited. Zero on a debit entry." })], JournalEntry.prototype, "credit", 2);
|
|
446
|
-
__decorateClass$1([field({ description: "The currency of the amounts." })], JournalEntry.prototype, "currency", 2);
|
|
447
|
-
__decorateClass$1([field({ description: "A note on this entry." })], JournalEntry.prototype, "memo", 2);
|
|
448
|
-
JournalEntry = __decorateClass$1([TenantScoped({ mode: "optional" }), smrt({
|
|
449
|
-
api: { include: ["list", "get"] },
|
|
450
|
-
mcp: { include: ["list", "get"] },
|
|
451
|
-
cli: { skipApiCheck: true }
|
|
452
|
-
})], JournalEntry);
|
|
453
|
-
var JournalEntries_exports = /* @__PURE__ */ __exportAll({ JournalEntryCollection: () => JournalEntryCollection });
|
|
454
|
-
var MAX_MOVEMENT_ACCOUNTS = 1e3;
|
|
455
|
-
function storedUnit(value, label) {
|
|
456
|
-
const number = typeof value === "number" ? value : Number(value);
|
|
457
|
-
if (!Number.isFinite(number) || Math.abs(number) > Number.MAX_SAFE_INTEGER) throw new RangeError(`Posted journal ${label} is outside the supported numeric range.`);
|
|
458
|
-
return number;
|
|
459
|
-
}
|
|
460
|
-
var JournalEntryCollection = class extends SmrtCollection {
|
|
461
|
-
static _itemClass = JournalEntry;
|
|
462
|
-
/**
|
|
463
|
-
* Find entries by journal
|
|
464
|
-
*
|
|
465
|
-
* @param journalId - Journal ID
|
|
466
|
-
* @returns Array of entries
|
|
467
|
-
*/
|
|
468
|
-
async findByJournal(journalId) {
|
|
469
|
-
return await this.list({ where: { journalId } });
|
|
470
|
-
}
|
|
471
|
-
/**
|
|
472
|
-
* Find entries by account
|
|
473
|
-
*
|
|
474
|
-
* @param accountId - Account ID
|
|
475
|
-
* @returns Array of entries
|
|
476
|
-
*/
|
|
477
|
-
async findByAccount(accountId) {
|
|
478
|
-
return await this.list({ where: { accountId } });
|
|
479
|
-
}
|
|
480
|
-
/**
|
|
481
|
-
* Get account balance
|
|
482
|
-
*
|
|
483
|
-
* For debit-normal accounts (Asset, Expense): balance = debits - credits
|
|
484
|
-
* For credit-normal accounts (Liability, Equity, Revenue): balance = credits - debits
|
|
485
|
-
*
|
|
486
|
-
* @param accountId - Account ID
|
|
487
|
-
* @param asOfDate - Optional date to calculate balance as of
|
|
488
|
-
* @returns Account balance
|
|
489
|
-
*/
|
|
490
|
-
async getAccountBalance(accountId, asOfDate) {
|
|
491
|
-
const { JournalCollection } = await Promise.resolve().then(() => Journals_exports);
|
|
492
|
-
const journalCollection = await JournalCollection.create(this.options);
|
|
493
|
-
const { AccountCollection } = await Promise.resolve().then(() => Accounts_exports);
|
|
494
|
-
const account = await (await AccountCollection.create(this.options)).get({ id: accountId });
|
|
495
|
-
if (!account) throw new Error(`Account not found: ${accountId}`);
|
|
496
|
-
const allEntries = await this.findByAccount(accountId);
|
|
497
|
-
let totalDebits = 0;
|
|
498
|
-
let totalCredits = 0;
|
|
499
|
-
for (const entry of allEntries) {
|
|
500
|
-
const journal = await journalCollection.get({ id: entry.journalId });
|
|
501
|
-
if (!journal) continue;
|
|
502
|
-
if (!journal.isPosted()) continue;
|
|
503
|
-
if (asOfDate && journal.date > asOfDate) continue;
|
|
504
|
-
totalDebits += entry.debit;
|
|
505
|
-
totalCredits += entry.credit;
|
|
506
|
-
}
|
|
507
|
-
if (account.isDebitNormal()) return totalDebits - totalCredits;
|
|
508
|
-
else return totalCredits - totalDebits;
|
|
509
|
-
}
|
|
510
|
-
/**
|
|
511
|
-
* Get trial balance
|
|
512
|
-
*
|
|
513
|
-
* @param asOfDate - Optional date for trial balance
|
|
514
|
-
* @returns Array of trial balance rows
|
|
515
|
-
*/
|
|
516
|
-
async getTrialBalance(asOfDate) {
|
|
517
|
-
const { AccountCollection } = await Promise.resolve().then(() => Accounts_exports);
|
|
518
|
-
const accounts = await (await AccountCollection.create(this.options)).findActive();
|
|
519
|
-
const rows = [];
|
|
520
|
-
for (const account of accounts) {
|
|
521
|
-
if (!account.id) continue;
|
|
522
|
-
const balance = await this.getAccountBalance(account.id, asOfDate);
|
|
523
|
-
if (Math.abs(balance) < .001) continue;
|
|
524
|
-
rows.push({
|
|
525
|
-
accountId: account.id,
|
|
526
|
-
accountNumber: account.number,
|
|
527
|
-
accountName: account.name,
|
|
528
|
-
accountType: account.type,
|
|
529
|
-
debitBalance: account.isDebitNormal() && balance > 0 ? balance : 0,
|
|
530
|
-
creditBalance: account.isCreditNormal() && balance > 0 ? balance : 0
|
|
531
|
-
});
|
|
532
|
-
}
|
|
533
|
-
rows.sort((a, b) => a.accountNumber.localeCompare(b.accountNumber));
|
|
534
|
-
return rows;
|
|
535
|
-
}
|
|
536
|
-
/**
|
|
537
|
-
* Get total debits and credits for a date range
|
|
538
|
-
*
|
|
539
|
-
* @param start - Start date
|
|
540
|
-
* @param end - End date
|
|
541
|
-
* @returns Object with totalDebits and totalCredits
|
|
542
|
-
*/
|
|
543
|
-
async getTotalsForDateRange(start, end) {
|
|
544
|
-
const { JournalCollection } = await Promise.resolve().then(() => Journals_exports);
|
|
545
|
-
const journals = await (await JournalCollection.create(this.options)).findByDateRange(start, end);
|
|
546
|
-
let totalDebits = 0;
|
|
547
|
-
let totalCredits = 0;
|
|
548
|
-
for (const journal of journals) {
|
|
549
|
-
if (!journal.isPosted()) continue;
|
|
550
|
-
const entries = await this.findByJournal(journal.id);
|
|
551
|
-
for (const entry of entries) {
|
|
552
|
-
totalDebits += entry.debit;
|
|
553
|
-
totalCredits += entry.credit;
|
|
554
|
-
}
|
|
555
|
-
}
|
|
556
|
-
return {
|
|
557
|
-
totalDebits,
|
|
558
|
-
totalCredits
|
|
559
|
-
};
|
|
560
|
-
}
|
|
561
|
-
/**
|
|
562
|
-
* Get entries for multiple accounts
|
|
563
|
-
*
|
|
564
|
-
* @param accountIds - Array of account IDs
|
|
565
|
-
* @returns Array of entries
|
|
566
|
-
*/
|
|
567
|
-
async findByAccounts(accountIds) {
|
|
568
|
-
if (accountIds.length === 0) return [];
|
|
569
|
-
return await this.list({ where: { accountId: accountIds } });
|
|
570
|
-
}
|
|
571
|
-
/**
|
|
572
|
-
* Read tenant-owned movements from posted journals only. Amounts deliberately
|
|
573
|
-
* remain raw ledger units; commerce validates its minor-unit convention at
|
|
574
|
-
* the reporting boundary.
|
|
575
|
-
*/
|
|
576
|
-
async listPostedMovements(options) {
|
|
577
|
-
const accountIds = [...new Set(options.accountIds)];
|
|
578
|
-
if (!options.tenantId?.trim() || !options.currency?.trim() || !(options.from instanceof Date) || !(options.to instanceof Date) || !Number.isFinite(options.from.getTime()) || !Number.isFinite(options.to.getTime()) || options.from > options.to) throw new Error("Posted movements require tenant, currency and ordered dates.");
|
|
579
|
-
if (accountIds.length === 0) return [];
|
|
580
|
-
if (accountIds.length > MAX_MOVEMENT_ACCOUNTS) throw new RangeError(`Posted movements allow at most ${MAX_MOVEMENT_ACCOUNTS} accounts per query.`);
|
|
581
|
-
if (accountIds.some((id) => typeof id !== "string" || !id || id.trim() !== id)) throw new Error("Posted movement account IDs must be nonempty.");
|
|
582
|
-
const placeholders = accountIds.map(() => "?").join(", ");
|
|
583
|
-
return (await this.db.query(`SELECT e.id AS entry_id, e.journal_id, e.account_id, e.currency,
|
|
584
|
-
e.debit, e.credit, j.date AS journal_date, j.number AS journal_number,
|
|
585
|
-
j.source_module, j.source_ref
|
|
586
|
-
FROM journal_entries e
|
|
587
|
-
JOIN journals j ON j.id = e.journal_id AND j.tenant_id = e.tenant_id
|
|
588
|
-
WHERE e.tenant_id = ? AND e.account_id IN (${placeholders})
|
|
589
|
-
AND e.currency = ? AND j.status = 'posted'
|
|
590
|
-
AND j.date >= ? AND j.date <= ?
|
|
591
|
-
ORDER BY j.date ASC, j.id ASC, e.id ASC`, options.tenantId, ...accountIds, options.currency, options.from.toISOString(), options.to.toISOString())).rows.map((row) => {
|
|
592
|
-
const debit = storedUnit(row.debit, "debit");
|
|
593
|
-
const credit = storedUnit(row.credit, "credit");
|
|
594
|
-
const movement = credit - debit;
|
|
595
|
-
if (!Number.isFinite(movement) || Math.abs(movement) > Number.MAX_SAFE_INTEGER) throw new RangeError("Posted journal movement is outside the supported numeric range.");
|
|
596
|
-
return {
|
|
597
|
-
tenantId: options.tenantId,
|
|
598
|
-
entryId: String(row.entry_id),
|
|
599
|
-
journalId: String(row.journal_id),
|
|
600
|
-
accountId: String(row.account_id),
|
|
601
|
-
journalDate: new Date(String(row.journal_date)),
|
|
602
|
-
journalNumber: String(row.journal_number),
|
|
603
|
-
sourceModule: String(row.source_module),
|
|
604
|
-
sourceRef: row.source_ref == null ? null : String(row.source_ref),
|
|
605
|
-
currency: String(row.currency),
|
|
606
|
-
debit,
|
|
607
|
-
credit,
|
|
608
|
-
creditMinusDebit: movement
|
|
609
|
-
};
|
|
610
|
-
});
|
|
611
|
-
}
|
|
612
|
-
/**
|
|
613
|
-
* Get the running balance for an account (list of entries with running total)
|
|
614
|
-
*
|
|
615
|
-
* @param accountId - Account ID
|
|
616
|
-
* @returns Array of entries with running balance
|
|
617
|
-
*/
|
|
618
|
-
async getAccountLedger(accountId) {
|
|
619
|
-
const { JournalCollection } = await Promise.resolve().then(() => Journals_exports);
|
|
620
|
-
const { AccountCollection } = await Promise.resolve().then(() => Accounts_exports);
|
|
621
|
-
const journalCollection = await JournalCollection.create(this.options);
|
|
622
|
-
const account = await (await AccountCollection.create(this.options)).get({ id: accountId });
|
|
623
|
-
if (!account) throw new Error(`Account not found: ${accountId}`);
|
|
624
|
-
const entries = await this.findByAccount(accountId);
|
|
625
|
-
const ledger = [];
|
|
626
|
-
let runningBalance = 0;
|
|
627
|
-
const entriesWithJournals = await Promise.all(entries.map(async (entry) => ({
|
|
628
|
-
entry,
|
|
629
|
-
journal: await journalCollection.get({ id: entry.journalId })
|
|
630
|
-
})));
|
|
631
|
-
entriesWithJournals.sort((a, b) => {
|
|
632
|
-
if (!a.journal || !b.journal) return 0;
|
|
633
|
-
return a.journal.date.getTime() - b.journal.date.getTime();
|
|
634
|
-
});
|
|
635
|
-
for (const { entry, journal } of entriesWithJournals) {
|
|
636
|
-
if (!journal?.isPosted()) continue;
|
|
637
|
-
if (account.isDebitNormal()) runningBalance += entry.debit - entry.credit;
|
|
638
|
-
else runningBalance += entry.credit - entry.debit;
|
|
639
|
-
ledger.push({
|
|
640
|
-
entry,
|
|
641
|
-
runningBalance
|
|
642
|
-
});
|
|
643
|
-
}
|
|
644
|
-
return ledger;
|
|
645
|
-
}
|
|
646
|
-
/**
|
|
647
|
-
* Find all journal entries belonging to a specific tenant
|
|
648
|
-
*
|
|
649
|
-
* @param tenantId - Tenant ID
|
|
650
|
-
* @returns Array of tenant's journal entries
|
|
651
|
-
*/
|
|
652
|
-
async findByTenant(tenantId) {
|
|
653
|
-
return this.list({ where: { tenantId } });
|
|
654
|
-
}
|
|
655
|
-
/**
|
|
656
|
-
* Find all global journal entries (no tenant association).
|
|
657
|
-
*
|
|
658
|
-
* Routes through the shared tenant-global helper so it does not throw under
|
|
659
|
-
* an active tenant context. (#1600)
|
|
660
|
-
*
|
|
661
|
-
* @returns Array of global journal entries
|
|
662
|
-
*/
|
|
663
|
-
async findGlobal() {
|
|
664
|
-
return queryGlobal(this);
|
|
665
|
-
}
|
|
666
|
-
/**
|
|
667
|
-
* Find journal entries for a tenant plus all global entries.
|
|
668
|
-
*
|
|
669
|
-
* Fails closed if an active tenant context requests a different tenant's
|
|
670
|
-
* rows; the admin/system path keeps the cross-tenant capability. (#1600)
|
|
671
|
-
*
|
|
672
|
-
* @param tenantId - Tenant ID
|
|
673
|
-
* @returns Array of tenant's entries and global entries
|
|
674
|
-
*/
|
|
675
|
-
async findWithGlobals(tenantId) {
|
|
676
|
-
return queryWithGlobals(this, tenantId, "JournalEntry.findWithGlobals");
|
|
677
|
-
}
|
|
678
|
-
};
|
|
679
|
-
var __defProp = Object.defineProperty;
|
|
680
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
681
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
|
|
682
|
-
enumerable: true,
|
|
683
|
-
configurable: true,
|
|
684
|
-
writable: true,
|
|
685
|
-
value
|
|
686
|
-
}) : obj[key] = value;
|
|
687
|
-
var __decorateClass = (decorators, target, key, kind) => {
|
|
688
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
689
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
690
|
-
if (kind && result) __defProp(target, key, result);
|
|
691
|
-
return result;
|
|
692
|
-
};
|
|
693
|
-
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
694
|
-
var Journal = class extends SmrtObject {
|
|
695
|
-
tenantId = null;
|
|
696
|
-
number = "";
|
|
697
|
-
date = /* @__PURE__ */ new Date();
|
|
698
|
-
description = "";
|
|
699
|
-
/**
|
|
700
|
-
* Source module that created this journal (e.g., "smrt-commerce", "manual")
|
|
701
|
-
*/
|
|
702
|
-
sourceModule = "";
|
|
703
|
-
/**
|
|
704
|
-
* External reference (e.g., order ID, invoice number)
|
|
705
|
-
*/
|
|
706
|
-
sourceRef = null;
|
|
707
|
-
status = "draft";
|
|
708
|
-
postedAt = null;
|
|
709
|
-
/**
|
|
710
|
-
* When the journal was voided
|
|
711
|
-
*/
|
|
712
|
-
voidedAt = null;
|
|
713
|
-
/**
|
|
714
|
-
* Reason for voiding (if voided)
|
|
715
|
-
*/
|
|
716
|
-
voidReason = null;
|
|
717
|
-
/**
|
|
718
|
-
* Extensible metadata
|
|
719
|
-
*/
|
|
720
|
-
metadata = {};
|
|
721
|
-
constructor(options = {}) {
|
|
722
|
-
super(options);
|
|
723
|
-
if (options.number !== void 0) this.number = options.number;
|
|
724
|
-
if (options.date !== void 0) this.date = options.date;
|
|
725
|
-
if (options.description !== void 0) this.description = options.description;
|
|
726
|
-
if (options.sourceModule !== void 0) this.sourceModule = options.sourceModule;
|
|
727
|
-
if (options.sourceRef !== void 0) this.sourceRef = options.sourceRef;
|
|
728
|
-
if (options.status !== void 0) this.status = options.status;
|
|
729
|
-
if (options.postedAt !== void 0) this.postedAt = options.postedAt;
|
|
730
|
-
if (options.voidedAt !== void 0) this.voidedAt = options.voidedAt;
|
|
731
|
-
if (options.voidReason !== void 0) this.voidReason = options.voidReason;
|
|
732
|
-
if (options.metadata !== void 0) this.metadata = options.metadata;
|
|
733
|
-
}
|
|
734
|
-
/**
|
|
735
|
-
* Check if journal is in draft status
|
|
736
|
-
*/
|
|
737
|
-
isDraft() {
|
|
738
|
-
return this.status === "draft";
|
|
739
|
-
}
|
|
740
|
-
/**
|
|
741
|
-
* Check if journal has been posted
|
|
742
|
-
*/
|
|
743
|
-
isPosted() {
|
|
744
|
-
return this.status === "posted";
|
|
745
|
-
}
|
|
746
|
-
/**
|
|
747
|
-
* Check if journal has been voided
|
|
748
|
-
*/
|
|
749
|
-
isVoided() {
|
|
750
|
-
return this.status === "voided";
|
|
751
|
-
}
|
|
752
|
-
/**
|
|
753
|
-
* Check if journal can be modified
|
|
754
|
-
*/
|
|
755
|
-
isEditable() {
|
|
756
|
-
return this.status === "draft";
|
|
757
|
-
}
|
|
758
|
-
/**
|
|
759
|
-
* Get all entries for this journal
|
|
760
|
-
*/
|
|
761
|
-
async getEntries() {
|
|
762
|
-
if (!this.id) return [];
|
|
763
|
-
const { JournalEntryCollection } = await Promise.resolve().then(() => JournalEntries_exports);
|
|
764
|
-
return await (await JournalEntryCollection.create(this.options)).findByJournal(this.id);
|
|
765
|
-
}
|
|
766
|
-
/**
|
|
767
|
-
* Calculate total debits
|
|
768
|
-
*/
|
|
769
|
-
async getTotalDebits() {
|
|
770
|
-
return (await this.getEntries()).reduce((sum, entry) => sum + entry.debit, 0);
|
|
771
|
-
}
|
|
772
|
-
/**
|
|
773
|
-
* Calculate total credits
|
|
774
|
-
*/
|
|
775
|
-
async getTotalCredits() {
|
|
776
|
-
return (await this.getEntries()).reduce((sum, entry) => sum + entry.credit, 0);
|
|
777
|
-
}
|
|
778
|
-
/**
|
|
779
|
-
* Check if journal entries are balanced (debits = credits)
|
|
780
|
-
*/
|
|
781
|
-
async isBalanced() {
|
|
782
|
-
const debits = await this.getTotalDebits();
|
|
783
|
-
const credits = await this.getTotalCredits();
|
|
784
|
-
return Math.abs(debits - credits) < BALANCE_EPSILON;
|
|
785
|
-
}
|
|
786
|
-
/**
|
|
787
|
-
* Add an entry to this journal (only if draft)
|
|
788
|
-
*/
|
|
789
|
-
async addEntry(data) {
|
|
790
|
-
if (!this.id) throw new Error("Journal must be saved before adding entries");
|
|
791
|
-
if (!this.isEditable()) throw new Error("Cannot add entries to a posted or voided journal");
|
|
792
|
-
const { JournalEntryCollection } = await Promise.resolve().then(() => JournalEntries_exports);
|
|
793
|
-
await (await (await JournalEntryCollection.create(this.options)).create({
|
|
794
|
-
journalId: this.id,
|
|
795
|
-
accountId: data.accountId,
|
|
796
|
-
debit: data.debit || 0,
|
|
797
|
-
credit: data.credit || 0,
|
|
798
|
-
currency: data.currency || "USD",
|
|
799
|
-
exchangeRate: data.exchangeRate || 1,
|
|
800
|
-
memo: data.memo || ""
|
|
801
|
-
})).save();
|
|
802
|
-
}
|
|
803
|
-
/**
|
|
804
|
-
* Post the journal (finalize and make immutable)
|
|
805
|
-
*/
|
|
806
|
-
async post() {
|
|
807
|
-
if (!this.isDraft()) throw new Error("Only draft journals can be posted");
|
|
808
|
-
if (!await this.isBalanced()) {
|
|
809
|
-
const debits = await this.getTotalDebits();
|
|
810
|
-
const credits = await this.getTotalCredits();
|
|
811
|
-
throw new Error(`Journal is not balanced. Debits: ${debits}, Credits: ${credits}`);
|
|
812
|
-
}
|
|
813
|
-
if ((await this.getEntries()).length === 0) throw new Error("Journal must have at least one entry");
|
|
814
|
-
this.status = "posted";
|
|
815
|
-
this.postedAt = /* @__PURE__ */ new Date();
|
|
816
|
-
await this.save();
|
|
817
|
-
}
|
|
818
|
-
/**
|
|
819
|
-
* Void the journal (mark as cancelled with reason)
|
|
820
|
-
*/
|
|
821
|
-
async void(reason) {
|
|
822
|
-
if (this.isVoided()) throw new Error("Journal is already voided");
|
|
823
|
-
this.status = "voided";
|
|
824
|
-
this.voidedAt = /* @__PURE__ */ new Date();
|
|
825
|
-
this.voidReason = reason;
|
|
826
|
-
await this.save();
|
|
827
|
-
}
|
|
828
|
-
/**
|
|
829
|
-
* AI-powered: Generate a summary of this journal.
|
|
830
|
-
*
|
|
831
|
-
* Uses the `smrtLedgers.journal.summarize` prompt registered via
|
|
832
|
-
* `@happyvertical/smrt-prompts`, allowing tenant- or instance-level
|
|
833
|
-
* overrides of the template, model, and parameters at runtime.
|
|
834
|
-
*
|
|
835
|
-
* Only non-PII journal fields (number, date, description, status, balanced
|
|
836
|
-
* flag) plus aggregate totals and entry count are sent to the AI provider.
|
|
837
|
-
* Internal foreign-key fields (tenantId, sourceRef, individual entry
|
|
838
|
-
* account IDs) and the extensible `metadata` blob are intentionally
|
|
839
|
-
* excluded.
|
|
840
|
-
*
|
|
841
|
-
* @returns Generated summary text
|
|
842
|
-
*/
|
|
843
|
-
async summarize() {
|
|
844
|
-
const entries = await this.getEntries();
|
|
845
|
-
const debits = await this.getTotalDebits();
|
|
846
|
-
const balanced = await this.isBalanced();
|
|
847
|
-
const db = this.options.db ?? this.options.persistence;
|
|
848
|
-
const resolvedPrompt = await resolvePrompt(smrtLedgersJournalSummarizePrompt.key, {
|
|
849
|
-
db,
|
|
850
|
-
tenantId: this.tenantId,
|
|
851
|
-
variables: {
|
|
852
|
-
journalNumber: this.number || "",
|
|
853
|
-
journalDate: this.date.toISOString().split("T")[0],
|
|
854
|
-
journalDescription: this.description || "",
|
|
855
|
-
journalStatus: this.status || "",
|
|
856
|
-
journalTotal: `$${debits.toFixed(2)}`,
|
|
857
|
-
entryCount: String(entries.length),
|
|
858
|
-
journalBalanced: balanced ? "Yes" : "No"
|
|
859
|
-
}
|
|
860
|
-
});
|
|
861
|
-
return (await (await this.getAiClient()).message(resolvedPrompt.text, promptMessageOptions(resolvedPrompt.ai))).trim();
|
|
862
|
-
}
|
|
863
|
-
};
|
|
864
|
-
__publicField(Journal, "__smrtPackage__", "@happyvertical/smrt-ledgers");
|
|
865
|
-
__decorateClass([tenantId({ nullable: true })], Journal.prototype, "tenantId", 2);
|
|
866
|
-
__decorateClass([field({ description: "The journal's reference number." })], Journal.prototype, "number", 2);
|
|
867
|
-
__decorateClass([field({ description: "The date of the transaction." })], Journal.prototype, "date", 2);
|
|
868
|
-
__decorateClass([field({ description: "What the transaction was." })], Journal.prototype, "description", 2);
|
|
869
|
-
__decorateClass([field({ description: "draft until final, then posted, or voided." })], Journal.prototype, "status", 2);
|
|
870
|
-
__decorateClass([field({ description: "When it was posted." })], Journal.prototype, "postedAt", 2);
|
|
871
|
-
Journal = __decorateClass([TenantScoped({ mode: "optional" }), smrt({
|
|
872
|
-
api: { include: [
|
|
873
|
-
"list",
|
|
874
|
-
"get",
|
|
875
|
-
"create"
|
|
876
|
-
] },
|
|
877
|
-
mcp: { include: [
|
|
878
|
-
"list",
|
|
879
|
-
"get",
|
|
880
|
-
"create"
|
|
881
|
-
] },
|
|
882
|
-
cli: { skipApiCheck: true }
|
|
883
|
-
})], Journal);
|
|
884
|
-
var Journals_exports = /* @__PURE__ */ __exportAll({ JournalCollection: () => JournalCollection });
|
|
885
|
-
var JournalCollection = class extends SmrtCollection {
|
|
886
|
-
static _itemClass = Journal;
|
|
887
|
-
/**
|
|
888
|
-
* Generate next journal number
|
|
889
|
-
*
|
|
890
|
-
* Uses timestamp and random component to avoid collisions
|
|
891
|
-
* in concurrent environments without relying on shared state.
|
|
892
|
-
*/
|
|
893
|
-
generateJournalNumber() {
|
|
894
|
-
return `JNL-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
|
|
895
|
-
}
|
|
896
|
-
/**
|
|
897
|
-
* Find journal by number
|
|
898
|
-
*
|
|
899
|
-
* @param number - Journal number
|
|
900
|
-
* @returns Journal or null
|
|
901
|
-
*/
|
|
902
|
-
async findByNumber(number) {
|
|
903
|
-
return (await this.list({
|
|
904
|
-
where: { number },
|
|
905
|
-
limit: 1
|
|
906
|
-
}))[0] || null;
|
|
907
|
-
}
|
|
908
|
-
/**
|
|
909
|
-
* Find journals by date range
|
|
910
|
-
*
|
|
911
|
-
* @param start - Start date
|
|
912
|
-
* @param end - End date
|
|
913
|
-
* @returns Array of journals
|
|
914
|
-
*/
|
|
915
|
-
async findByDateRange(start, end) {
|
|
916
|
-
return await this.list({
|
|
917
|
-
where: {
|
|
918
|
-
"date >=": start.toISOString(),
|
|
919
|
-
"date <=": end.toISOString()
|
|
920
|
-
},
|
|
921
|
-
orderBy: "date ASC"
|
|
922
|
-
});
|
|
923
|
-
}
|
|
924
|
-
/**
|
|
925
|
-
* Find journals by source module
|
|
926
|
-
*
|
|
927
|
-
* @param sourceModule - Source module name
|
|
928
|
-
* @returns Array of journals
|
|
929
|
-
*/
|
|
930
|
-
async findBySource(sourceModule) {
|
|
931
|
-
return await this.list({
|
|
932
|
-
where: { sourceModule },
|
|
933
|
-
orderBy: "date DESC"
|
|
934
|
-
});
|
|
935
|
-
}
|
|
936
|
-
/**
|
|
937
|
-
* Find journals by status
|
|
938
|
-
*
|
|
939
|
-
* @param status - Journal status
|
|
940
|
-
* @returns Array of journals
|
|
941
|
-
*/
|
|
942
|
-
async findByStatus(status) {
|
|
943
|
-
return await this.list({
|
|
944
|
-
where: { status },
|
|
945
|
-
orderBy: "date DESC"
|
|
946
|
-
});
|
|
947
|
-
}
|
|
948
|
-
/**
|
|
949
|
-
* Find draft journals
|
|
950
|
-
*
|
|
951
|
-
* @returns Array of draft journals
|
|
952
|
-
*/
|
|
953
|
-
async findDrafts() {
|
|
954
|
-
return await this.findByStatus("draft");
|
|
955
|
-
}
|
|
956
|
-
/**
|
|
957
|
-
* Find posted journals
|
|
958
|
-
*
|
|
959
|
-
* @returns Array of posted journals
|
|
960
|
-
*/
|
|
961
|
-
async findPosted() {
|
|
962
|
-
return await this.findByStatus("posted");
|
|
963
|
-
}
|
|
964
|
-
/**
|
|
965
|
-
* Create a complete journal with entries
|
|
966
|
-
*
|
|
967
|
-
* @param data - Journal data with entries
|
|
968
|
-
* @returns Created journal
|
|
969
|
-
*/
|
|
970
|
-
async createWithEntries(data) {
|
|
971
|
-
let totalDebits = 0;
|
|
972
|
-
let totalCredits = 0;
|
|
973
|
-
for (const entry of data.entries) {
|
|
974
|
-
totalDebits += entry.debit || 0;
|
|
975
|
-
totalCredits += entry.credit || 0;
|
|
976
|
-
}
|
|
977
|
-
if (Math.abs(totalDebits - totalCredits) >= .001) throw new Error(`Entries are not balanced. Debits: ${totalDebits}, Credits: ${totalCredits}`);
|
|
978
|
-
if (data.entries.length === 0) throw new Error("Journal must have at least one entry");
|
|
979
|
-
const journalNumber = await this.generateJournalNumber();
|
|
980
|
-
const journal = await this.create({
|
|
981
|
-
number: journalNumber,
|
|
982
|
-
date: data.date || /* @__PURE__ */ new Date(),
|
|
983
|
-
description: data.description,
|
|
984
|
-
sourceModule: data.sourceModule || "manual",
|
|
985
|
-
sourceRef: data.sourceRef || null,
|
|
986
|
-
metadata: data.metadata || {}
|
|
987
|
-
});
|
|
988
|
-
await journal.save();
|
|
989
|
-
for (const entryData of data.entries) await journal.addEntry(entryData);
|
|
990
|
-
return journal;
|
|
991
|
-
}
|
|
992
|
-
/**
|
|
993
|
-
* Post a journal by ID
|
|
994
|
-
*
|
|
995
|
-
* @param journalId - Journal ID
|
|
996
|
-
* @returns Posted journal
|
|
997
|
-
*/
|
|
998
|
-
async post(journalId) {
|
|
999
|
-
const journal = await this.get({ id: journalId });
|
|
1000
|
-
if (!journal) throw new Error(`Journal not found: ${journalId}`);
|
|
1001
|
-
await journal.post();
|
|
1002
|
-
return journal;
|
|
1003
|
-
}
|
|
1004
|
-
/**
|
|
1005
|
-
* Void a journal by ID
|
|
1006
|
-
*
|
|
1007
|
-
* @param journalId - Journal ID
|
|
1008
|
-
* @param reason - Reason for voiding
|
|
1009
|
-
* @returns Voided journal
|
|
1010
|
-
*/
|
|
1011
|
-
async void(journalId, reason) {
|
|
1012
|
-
const journal = await this.get({ id: journalId });
|
|
1013
|
-
if (!journal) throw new Error(`Journal not found: ${journalId}`);
|
|
1014
|
-
await journal.void(reason);
|
|
1015
|
-
return journal;
|
|
1016
|
-
}
|
|
1017
|
-
/**
|
|
1018
|
-
* Find journals by source reference
|
|
1019
|
-
*
|
|
1020
|
-
* @param sourceRef - External reference
|
|
1021
|
-
* @returns Array of journals
|
|
1022
|
-
*/
|
|
1023
|
-
async findBySourceRef(sourceRef) {
|
|
1024
|
-
return await this.list({
|
|
1025
|
-
where: { sourceRef },
|
|
1026
|
-
orderBy: "date DESC"
|
|
1027
|
-
});
|
|
1028
|
-
}
|
|
1029
|
-
/**
|
|
1030
|
-
* Get journals for a specific month
|
|
1031
|
-
*
|
|
1032
|
-
* @param year - Year
|
|
1033
|
-
* @param month - Month (1-12)
|
|
1034
|
-
* @returns Array of journals
|
|
1035
|
-
*/
|
|
1036
|
-
async findByMonth(year, month) {
|
|
1037
|
-
const start = new Date(year, month - 1, 1);
|
|
1038
|
-
const end = new Date(year, month, 0, 23, 59, 59, 999);
|
|
1039
|
-
return await this.findByDateRange(start, end);
|
|
1040
|
-
}
|
|
1041
|
-
/**
|
|
1042
|
-
* Find all journals belonging to a specific tenant
|
|
1043
|
-
*
|
|
1044
|
-
* @param tenantId - Tenant ID
|
|
1045
|
-
* @returns Array of tenant's journals
|
|
1046
|
-
*/
|
|
1047
|
-
async findByTenant(tenantId) {
|
|
1048
|
-
return this.list({ where: { tenantId } });
|
|
1049
|
-
}
|
|
1050
|
-
/**
|
|
1051
|
-
* Find all global journals (no tenant association).
|
|
1052
|
-
*
|
|
1053
|
-
* Routes through the shared tenant-global helper so it does not throw under
|
|
1054
|
-
* an active tenant context. (#1600)
|
|
1055
|
-
*
|
|
1056
|
-
* @returns Array of global journals
|
|
1057
|
-
*/
|
|
1058
|
-
async findGlobal() {
|
|
1059
|
-
return queryGlobal(this);
|
|
1060
|
-
}
|
|
1061
|
-
/**
|
|
1062
|
-
* Find journals for a tenant plus all global journals.
|
|
1063
|
-
*
|
|
1064
|
-
* Fails closed if an active tenant context requests a different tenant's
|
|
1065
|
-
* rows; the admin/system path keeps the cross-tenant capability. (#1600)
|
|
1066
|
-
*
|
|
1067
|
-
* @param tenantId - Tenant ID
|
|
1068
|
-
* @returns Array of tenant's journals and global journals
|
|
1069
|
-
*/
|
|
1070
|
-
async findWithGlobals(tenantId) {
|
|
1071
|
-
return queryWithGlobals(this, tenantId, "Journal.findWithGlobals");
|
|
1072
|
-
}
|
|
1073
|
-
};
|
|
1074
|
-
var LEDGER_ACCOUNTS_TABLE = "ledger_accounts";
|
|
1075
|
-
var LEGACY_ACCOUNTS_TABLE = "accounts";
|
|
1076
|
-
var LEGACY_LEDGER_SIGNATURE = ["number", "type"];
|
|
1077
|
-
var STI_DISCRIMINATOR = "_meta_type";
|
|
1078
|
-
var MESSAGING_MARKERS = ["provider_type", "channel_type"];
|
|
1079
|
-
var LedgerAccountsTableMoveError = class extends Error {
|
|
1080
|
-
constructor(message) {
|
|
1081
|
-
super(message);
|
|
1082
|
-
this.name = "LedgerAccountsTableMoveError";
|
|
1083
|
-
}
|
|
1084
|
-
};
|
|
1085
|
-
function quote(identifier) {
|
|
1086
|
-
return `"${identifier.replace(/"/g, "\"\"")}"`;
|
|
1087
|
-
}
|
|
1088
|
-
function timeout(value, fallback) {
|
|
1089
|
-
const milliseconds = value ?? fallback;
|
|
1090
|
-
if (!Number.isInteger(milliseconds) || milliseconds < 0) throw new LedgerAccountsTableMoveError("Migration timeout must be a non-negative integer");
|
|
1091
|
-
return `${milliseconds}ms`;
|
|
1092
|
-
}
|
|
1093
|
-
function assertPostgres(db) {
|
|
1094
|
-
const withConfig = db;
|
|
1095
|
-
if (detectEngine(db.url || withConfig.config?.url || "", withConfig.type || withConfig.config?.type) !== "postgres") throw new LedgerAccountsTableMoveError("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.");
|
|
1096
|
-
}
|
|
1097
|
-
async function readLegacyShape(db) {
|
|
1098
|
-
const schema = await db.getTableSchema?.(LEGACY_ACCOUNTS_TABLE);
|
|
1099
|
-
if (!schema) return null;
|
|
1100
|
-
const columns = new Set(Object.keys(schema.columns));
|
|
1101
|
-
if (!LEGACY_LEDGER_SIGNATURE.every((column) => columns.has(column))) return null;
|
|
1102
|
-
return {
|
|
1103
|
-
columns,
|
|
1104
|
-
hasDiscriminator: columns.has(STI_DISCRIMINATOR)
|
|
1105
|
-
};
|
|
1106
|
-
}
|
|
1107
|
-
function ledgerRowPredicate(shape) {
|
|
1108
|
-
return shape.hasDiscriminator ? `(${quote(STI_DISCRIMINATOR)} IS NULL OR ${quote(STI_DISCRIMINATOR)} = '')` : "TRUE";
|
|
1109
|
-
}
|
|
1110
|
-
async function count(db, where) {
|
|
1111
|
-
const result = await db.query(`SELECT COUNT(*) AS n FROM ${quote(LEGACY_ACCOUNTS_TABLE)} WHERE ${where}`);
|
|
1112
|
-
return Number(result.rows[0].n);
|
|
1113
|
-
}
|
|
1114
|
-
async function classify(db, shape) {
|
|
1115
|
-
const ledger = ledgerRowPredicate(shape);
|
|
1116
|
-
const pending = await count(db, ledger);
|
|
1117
|
-
const messagingRows = shape.hasDiscriminator ? await count(db, `NOT ${ledger}`) : 0;
|
|
1118
|
-
if (shape.hasDiscriminator) {
|
|
1119
|
-
const ledgerLooking = await count(db, `NOT ${ledger} AND COALESCE(${quote("number")}, '') <> ''`);
|
|
1120
|
-
const markers = MESSAGING_MARKERS.filter((column) => shape.columns.has(column));
|
|
1121
|
-
const messagingLooking = markers.length === 0 ? 0 : await count(db, `${ledger} AND (${markers.map((column) => `COALESCE(${quote(column)}, '') <> ''`).join(" OR ")})`);
|
|
1122
|
-
if (ledgerLooking > 0 || messagingLooking > 0) throw new LedgerAccountsTableMoveError(`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.`);
|
|
1123
|
-
}
|
|
1124
|
-
return {
|
|
1125
|
-
pending,
|
|
1126
|
-
messagingRows
|
|
1127
|
-
};
|
|
1128
|
-
}
|
|
1129
|
-
function registeredReferenceColumns() {
|
|
1130
|
-
const ledger = /* @__PURE__ */ new Set();
|
|
1131
|
-
const accounts = /* @__PURE__ */ new Set();
|
|
1132
|
-
const schemas = ObjectRegistry.getAllSchemasAsDefinitions();
|
|
1133
|
-
for (const [tableName, schema] of Object.entries(schemas)) for (const [columnName, column] of Object.entries(schema.columns ?? {})) {
|
|
1134
|
-
const target = column.foreignKey?.table;
|
|
1135
|
-
if (target === "ledger_accounts") ledger.add(`${tableName}.${columnName}`);
|
|
1136
|
-
else if (target === "accounts") accounts.add(`${tableName}.${columnName}`);
|
|
1137
|
-
}
|
|
1138
|
-
return {
|
|
1139
|
-
ledger,
|
|
1140
|
-
accounts
|
|
1141
|
-
};
|
|
1142
|
-
}
|
|
1143
|
-
function classifyForeignKeys(inbound, references) {
|
|
1144
|
-
const disposition = {
|
|
1145
|
-
composite: [],
|
|
1146
|
-
undeclared: [],
|
|
1147
|
-
detach: [],
|
|
1148
|
-
keep: []
|
|
1149
|
-
};
|
|
1150
|
-
for (const fk of inbound) {
|
|
1151
|
-
const key = `${fk.table}.${fk.column}`;
|
|
1152
|
-
if (fk.arity > 1) disposition.composite.push(fk);
|
|
1153
|
-
else if (references.ledger.has(key)) disposition.detach.push(fk);
|
|
1154
|
-
else if (fk.table === "accounts" || references.accounts.has(key)) disposition.keep.push(fk);
|
|
1155
|
-
else disposition.undeclared.push(fk);
|
|
1156
|
-
}
|
|
1157
|
-
return disposition;
|
|
1158
|
-
}
|
|
1159
|
-
function foreignKeyRefusal(disposition) {
|
|
1160
|
-
if (disposition.composite.length > 0) 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.`;
|
|
1161
|
-
if (disposition.undeclared.length > 0) 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.`;
|
|
1162
|
-
}
|
|
1163
|
-
function copySelectList(columns, targetTypes, legacyTypes) {
|
|
1164
|
-
return columns.map((column) => {
|
|
1165
|
-
const to = targetTypes[column];
|
|
1166
|
-
return sameType(legacyTypes[column], to) ? quote(column) : `CAST(CAST(${quote(column)} AS TEXT) AS ${targetType(to)})`;
|
|
1167
|
-
}).join(", ");
|
|
1168
|
-
}
|
|
1169
|
-
async function legacyForeignKeys(db) {
|
|
1170
|
-
return (await db.query(`SELECT con.conname AS constraint_name,
|
|
1171
|
-
rel.relname AS table_name,
|
|
1172
|
-
att.attname AS column_name,
|
|
1173
|
-
array_length(con.conkey, 1) AS arity
|
|
1174
|
-
FROM pg_constraint con
|
|
1175
|
-
JOIN pg_class rel ON rel.oid = con.conrelid
|
|
1176
|
-
JOIN pg_attribute att
|
|
1177
|
-
ON att.attrelid = con.conrelid AND att.attnum = con.conkey[1]
|
|
1178
|
-
WHERE con.contype = 'f'
|
|
1179
|
-
AND con.confrelid = to_regclass(?)
|
|
1180
|
-
ORDER BY rel.relname, con.conname`, quote(LEGACY_ACCOUNTS_TABLE))).rows.map((row) => ({
|
|
1181
|
-
constraint: row.constraint_name,
|
|
1182
|
-
table: row.table_name,
|
|
1183
|
-
column: row.column_name,
|
|
1184
|
-
arity: Number(row.arity)
|
|
1185
|
-
}));
|
|
1186
|
-
}
|
|
1187
|
-
async function planLedgerAccountsTableMove(db) {
|
|
1188
|
-
const shape = await readLegacyShape(db);
|
|
1189
|
-
if (!shape) return {
|
|
1190
|
-
legacyTable: false,
|
|
1191
|
-
pending: 0,
|
|
1192
|
-
messagingRows: 0
|
|
1193
|
-
};
|
|
1194
|
-
return {
|
|
1195
|
-
legacyTable: true,
|
|
1196
|
-
...await classify(db, shape)
|
|
1197
|
-
};
|
|
1198
|
-
}
|
|
1199
|
-
async function migrateLedgerAccountsTable(db, options = {}) {
|
|
1200
|
-
assertPostgres(db);
|
|
1201
|
-
if (!db.transaction) throw new LedgerAccountsTableMoveError("The ledger accounts table move requires a transaction-capable PostgreSQL adapter");
|
|
1202
|
-
const noop = (remainingLegacyRows = 0) => ({
|
|
1203
|
-
ran: false,
|
|
1204
|
-
moved: 0,
|
|
1205
|
-
remainingLegacyRows,
|
|
1206
|
-
detachedForeignKeys: []
|
|
1207
|
-
});
|
|
1208
|
-
const shape = await readLegacyShape(db);
|
|
1209
|
-
if (!shape) return noop();
|
|
1210
|
-
const target = await db.getTableSchema?.(LEDGER_ACCOUNTS_TABLE);
|
|
1211
|
-
if (!target) throw new LedgerAccountsTableMoveError(`"${LEDGER_ACCOUNTS_TABLE}" does not exist; run db:migrate before moving ledger accounts`);
|
|
1212
|
-
const legacy = await db.getTableSchema?.(LEGACY_ACCOUNTS_TABLE);
|
|
1213
|
-
const copyColumns = Object.keys(target.columns).filter((column) => shape.columns.has(column));
|
|
1214
|
-
const references = registeredReferenceColumns();
|
|
1215
|
-
await new BackfillTracker({ db }).initialize();
|
|
1216
|
-
const backfillName = options.backfillName ?? "@happyvertical/smrt-ledgers:ledger-accounts-table:v1";
|
|
1217
|
-
return db.transaction(async (tx) => {
|
|
1218
|
-
BackfillTracker.inheritInitialization(tx, db);
|
|
1219
|
-
const transactionTracker = new BackfillTracker({ db: tx });
|
|
1220
|
-
await tx.query(`SET LOCAL lock_timeout = '${timeout(options.lockTimeout, 3e4)}'`);
|
|
1221
|
-
await tx.query(`SET LOCAL statement_timeout = '${timeout(options.statementTimeout, 6e4)}'`);
|
|
1222
|
-
await tx.query(`LOCK TABLE ${quote(LEGACY_ACCOUNTS_TABLE)}, ${quote(LEDGER_ACCOUNTS_TABLE)} IN ACCESS EXCLUSIVE MODE`);
|
|
1223
|
-
const { pending, messagingRows } = await classify(tx, shape);
|
|
1224
|
-
if (await transactionTracker.isApplied(backfillName)) {
|
|
1225
|
-
if (pending > 0) throw new LedgerAccountsTableMoveError(`The ledger accounts table move is recorded as applied but "${LEGACY_ACCOUNTS_TABLE}" still holds ${pending} ledger row(s); refusing inconsistent state`);
|
|
1226
|
-
return noop(messagingRows);
|
|
1227
|
-
}
|
|
1228
|
-
const ledger = ledgerRowPredicate(shape);
|
|
1229
|
-
const clash = await tx.query(`SELECT COUNT(*) AS n FROM ${quote(LEGACY_ACCOUNTS_TABLE)} legacy
|
|
1230
|
-
WHERE ${ledger}
|
|
1231
|
-
AND EXISTS (SELECT 1 FROM ${quote(LEDGER_ACCOUNTS_TABLE)} moved
|
|
1232
|
-
WHERE CAST(moved.id AS TEXT) = CAST(legacy.id AS TEXT))`);
|
|
1233
|
-
if (Number(clash.rows[0].n) > 0) throw new LedgerAccountsTableMoveError(`"${LEDGER_ACCOUNTS_TABLE}" already holds ids of ledger rows still in "${LEGACY_ACCOUNTS_TABLE}"; refusing to overwrite`);
|
|
1234
|
-
const disposition = classifyForeignKeys(await legacyForeignKeys(tx), references);
|
|
1235
|
-
const refusal = foreignKeyRefusal(disposition);
|
|
1236
|
-
if (refusal) throw new LedgerAccountsTableMoveError(refusal);
|
|
1237
|
-
for (const fk of disposition.keep) {
|
|
1238
|
-
const survivor = fk.table === "accounts" ? ` AND NOT ${ledger}` : "";
|
|
1239
|
-
const pointing = await tx.query(`SELECT COUNT(*) AS n FROM ${quote(fk.table)}
|
|
1240
|
-
WHERE ${quote(fk.column)} IN
|
|
1241
|
-
(SELECT id FROM ${quote(LEGACY_ACCOUNTS_TABLE)} WHERE ${ledger})${survivor}`);
|
|
1242
|
-
if (Number(pointing.rows[0].n) > 0) throw new LedgerAccountsTableMoveError(`${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.`);
|
|
1243
|
-
}
|
|
1244
|
-
const selectList = copySelectList(copyColumns, columnTypes(target), columnTypes(legacy));
|
|
1245
|
-
await tx.query(`INSERT INTO ${quote(LEDGER_ACCOUNTS_TABLE)} (${copyColumns.map(quote).join(", ")})
|
|
1246
|
-
SELECT ${selectList} FROM ${quote(LEGACY_ACCOUNTS_TABLE)} WHERE ${ledger}`);
|
|
1247
|
-
const detached = [];
|
|
1248
|
-
for (const foreignKey of disposition.detach) {
|
|
1249
|
-
await tx.query(`ALTER TABLE ${quote(foreignKey.table)} DROP CONSTRAINT ${quote(foreignKey.constraint)}`);
|
|
1250
|
-
detached.push(`${foreignKey.table}.${foreignKey.column}`);
|
|
1251
|
-
}
|
|
1252
|
-
await tx.query(`DELETE FROM ${quote(LEGACY_ACCOUNTS_TABLE)} WHERE ${ledger}`);
|
|
1253
|
-
await transactionTracker.recordApplied(backfillName, {
|
|
1254
|
-
description: "Moved ledger accounts from the shared accounts table to ledger_accounts (#3098).",
|
|
1255
|
-
packageName: options.packageName ?? "@happyvertical/smrt-ledgers"
|
|
1256
|
-
});
|
|
1257
|
-
return {
|
|
1258
|
-
ran: true,
|
|
1259
|
-
moved: pending,
|
|
1260
|
-
remainingLegacyRows: messagingRows,
|
|
1261
|
-
detachedForeignKeys: detached
|
|
1262
|
-
};
|
|
1263
|
-
});
|
|
1264
|
-
}
|
|
1265
|
-
var SQL_TYPE = /^[A-Za-z][A-Za-z0-9 _]*(\(\d+(,\s*\d+)?\))?(\[\])?$/;
|
|
1266
|
-
function columnTypes(schema) {
|
|
1267
|
-
return Object.fromEntries(Object.entries(schema?.columns ?? {}).map(([name, column]) => [name, column.type]));
|
|
1268
|
-
}
|
|
1269
|
-
function sameType(from, to) {
|
|
1270
|
-
return from !== void 0 && to !== void 0 && from.trim().toLowerCase() === to.trim().toLowerCase();
|
|
1271
|
-
}
|
|
1272
|
-
function targetType(declared) {
|
|
1273
|
-
const type = declared?.trim();
|
|
1274
|
-
if (!type || !SQL_TYPE.test(type)) throw new LedgerAccountsTableMoveError(`Cannot copy into "${LEDGER_ACCOUNTS_TABLE}": unsupported live column type ${JSON.stringify(type)}`);
|
|
1275
|
-
return type;
|
|
1276
|
-
}
|
|
1277
|
-
//#endregion
|
|
1278
|
-
export { migrateLedgerAccountsTable, Accounts_exports as n, planLedgerAccountsTableMove, JournalEntries_exports as t };
|