@happyvertical/smrt-expenses 0.0.0-stage → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,513 @@
1
+ import { ExpenseError } from "../types.js";
2
+ import { ObjectRegistry, SmrtObject, crossPackageRef, field, foreignKey, isUniqueViolationError, smrt } from "@happyvertical/smrt-core";
3
+ import { ContractCollection, ContractLineItemCollection, VendorCollection } from "@happyvertical/smrt-commerce";
4
+ import { TenantScoped, getTenantId, tenantId } from "@happyvertical/smrt-tenancy";
5
+ import { createHash } from "node:crypto";
6
+ //#region src/validation.ts
7
+ var CATEGORY_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
8
+ var ISO_CURRENCY = /^[A-Z]{3}$/;
9
+ var ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
10
+ var QUALIFIED_CLASS = /^[^\s:]+:[A-Za-z_$][\w$]*$/;
11
+ var SHA256_HEX = /^[0-9a-f]{64}$/;
12
+ function assertMinorUnits(model, label, fieldName, value, code = "EXPENSE_INVALID") {
13
+ if (!Number.isSafeInteger(value) || value < 0) throw new ExpenseError(code, `${model} ${label}: ${fieldName} must be a non-negative integer number of minor units (cents) \u2014 got ${value}. $19.99 is 1999.`);
14
+ }
15
+ function assertIsoCurrency(model, label, value) {
16
+ if (!ISO_CURRENCY.test(value)) throw new ExpenseError("EXPENSE_INVALID", `${model} ${label}: currency must be a three-letter ISO 4217 code (for example 'USD'), got '${value}'.`);
17
+ }
18
+ function assertIsoDate(model, label, fieldName, value) {
19
+ const match = ISO_DATE.exec(value);
20
+ if (!(match !== null && (() => {
21
+ const [year, month, day] = match.slice(1).map(Number);
22
+ const date = new Date(Date.UTC(year, month - 1, day));
23
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
24
+ })())) throw new ExpenseError("EXPENSE_INVALID", `${model} ${label}: ${fieldName} must be a calendar date written YYYY-MM-DD, got '${value}'.`);
25
+ }
26
+ function assertQualifiedClassName(model, label, value) {
27
+ if (!QUALIFIED_CLASS.test(value)) throw new ExpenseError("EXPENSE_INVALID", `${model} ${label}: costObjectType must be a qualified class name such as '@happyvertical/smrt-projects:Project', got '${value}'.`);
28
+ }
29
+ function normalizeSha256(model, label, value) {
30
+ const digest = String(value ?? "").trim().toLowerCase();
31
+ if (!SHA256_HEX.test(digest)) throw new ExpenseError("EXPENSE_RECEIPT_INVALID", `${model} ${label}: contentSha256 must be a 64-character hex SHA-256 digest of the file bytes.`);
32
+ return digest;
33
+ }
34
+ function computeContentSha256(data) {
35
+ return createHash("sha256").update(data).digest("hex");
36
+ }
37
+ function instantMs(value) {
38
+ if (value === null || value === void 0 || value === "") return null;
39
+ const ms = value instanceof Date ? value.getTime() : new Date(String(value)).getTime();
40
+ return Number.isNaN(ms) ? null : ms;
41
+ }
42
+ async function pinNaturalKey(model, object, persisted) {
43
+ await object.getSlug();
44
+ if (!object.isPersisted) {
45
+ if (persisted) throw new ExpenseError("EXPENSE_IDENTITY_CONFLICT", `${model} ${object.id} already exists; load it and save the loaded instance instead of creating one with its id.`);
46
+ object.requireInsertOnSave();
47
+ return true;
48
+ }
49
+ if (persisted && (String(persisted.slug ?? "") !== String(object.slug ?? "") || String(persisted.context ?? "") !== String(object.context ?? ""))) throw new ExpenseError("EXPENSE_IDENTITY_CONFLICT", `${model} ${object.id}: slug and context cannot change; they would point the save at a different row.`);
50
+ return false;
51
+ }
52
+ function identityConflict(model, object, cause) {
53
+ return new ExpenseError("EXPENSE_IDENTITY_CONFLICT", `${model} ${object.id}: another row already uses slug '${object.slug}' in this tenant; a new ${model} cannot take it over.`, { cause });
54
+ }
55
+ function effectiveTenant(tenantId) {
56
+ return tenantId || getTenantId() || null;
57
+ }
58
+ function normalizeTenantId(tenantId) {
59
+ return tenantId || null;
60
+ }
61
+ //#endregion
62
+ //#region src/models/Expense.ts
63
+ var __defProp = Object.defineProperty;
64
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
65
+ var __decorateClass = (decorators, target, key, kind) => {
66
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
67
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
68
+ if (kind && result) __defProp(target, key, result);
69
+ return result;
70
+ };
71
+ var PROFILE = "@happyvertical/smrt-profiles:Profile";
72
+ var REVIEW_TRANSITIONS = {
73
+ review: {
74
+ from: ["unreviewed"],
75
+ to: "reviewed"
76
+ },
77
+ reject: {
78
+ from: ["unreviewed", "reviewed"],
79
+ to: "rejected"
80
+ },
81
+ markDuplicate: {
82
+ from: ["unreviewed", "reviewed"],
83
+ to: "rejected"
84
+ },
85
+ reopen: {
86
+ from: ["reviewed", "rejected"],
87
+ to: "unreviewed"
88
+ }
89
+ };
90
+ var LOCKED_WHEN_REVIEWED = [
91
+ ["amount", "amount"],
92
+ ["currency", "currency"],
93
+ ["incurredOn", "incurred_on"],
94
+ ["recordedAt", "recorded_at"],
95
+ ["category", "category"],
96
+ ["costObjectType", "cost_object_type"],
97
+ ["costObjectId", "cost_object_id"],
98
+ ["vendorId", "vendor_id"],
99
+ ["commitmentId", "commitment_id"],
100
+ ["commitmentLineId", "commitment_line_id"],
101
+ ["paidBy", "paid_by"],
102
+ ["paidByProfileId", "paid_by_profile_id"]
103
+ ];
104
+ var authorizedTransition = /* @__PURE__ */ new WeakMap();
105
+ function sameReviewState(a, b) {
106
+ return a.status === b.status && a.reviewer === b.reviewer && a.reviewedAtMs === b.reviewedAtMs && a.note === b.note && a.duplicateOf === b.duplicateOf;
107
+ }
108
+ function asNullableString(value) {
109
+ return value === null || value === void 0 || value === "" ? null : String(value);
110
+ }
111
+ var Expense = class extends SmrtObject {
112
+ tenantId = null;
113
+ costObjectType = "";
114
+ costObjectId = "";
115
+ category = "other";
116
+ description = "";
117
+ amount = 0;
118
+ currency = "";
119
+ incurredOn = "";
120
+ /** When the expense was recorded; set on first save when empty. */
121
+ recordedAt = null;
122
+ recordedByProfileId = null;
123
+ paidBy = "company";
124
+ paidByProfileId = null;
125
+ vendorId = null;
126
+ commitmentId = null;
127
+ commitmentLineId = null;
128
+ reviewStatus = "unreviewed";
129
+ reviewedByProfileId = null;
130
+ reviewedAt = null;
131
+ reviewNote = "";
132
+ duplicateOfId = null;
133
+ reimbursable = false;
134
+ /** When the person was paid back; set by {@link Expense.markReimbursed}. */
135
+ reimbursedAt = null;
136
+ reimbursementReference = "";
137
+ constructor(options = {}) {
138
+ super(options);
139
+ if (options.tenantId !== void 0) this.tenantId = options.tenantId;
140
+ if (options.costObjectType !== void 0) this.costObjectType = options.costObjectType;
141
+ if (options.costObjectId !== void 0) this.costObjectId = options.costObjectId;
142
+ if (options.category !== void 0) this.category = options.category;
143
+ if (options.description !== void 0) this.description = options.description;
144
+ if (options.amount !== void 0) this.amount = options.amount;
145
+ if (options.currency !== void 0) this.currency = options.currency;
146
+ if (options.incurredOn !== void 0) this.incurredOn = options.incurredOn;
147
+ if (options.recordedAt !== void 0) this.recordedAt = options.recordedAt;
148
+ if (options.recordedByProfileId !== void 0) this.recordedByProfileId = options.recordedByProfileId;
149
+ if (options.paidBy !== void 0) this.paidBy = options.paidBy;
150
+ if (options.paidByProfileId !== void 0) this.paidByProfileId = options.paidByProfileId;
151
+ if (options.vendorId !== void 0) this.vendorId = options.vendorId;
152
+ if (options.commitmentId !== void 0) this.commitmentId = options.commitmentId;
153
+ if (options.commitmentLineId !== void 0) this.commitmentLineId = options.commitmentLineId;
154
+ if (options.reimbursable !== void 0) this.reimbursable = options.reimbursable;
155
+ if (options.reimbursedAt !== void 0) this.reimbursedAt = options.reimbursedAt;
156
+ if (options.reimbursementReference !== void 0) this.reimbursementReference = options.reimbursementReference;
157
+ }
158
+ /** True when the person who paid has been paid back. */
159
+ isReimbursed() {
160
+ return this.reimbursedAt !== null && this.reimbursedAt !== void 0;
161
+ }
162
+ /** True when this expense counts toward reviewed totals and drawdown. */
163
+ isCountable() {
164
+ return this.reviewStatus === "reviewed" && !this.duplicateOfId;
165
+ }
166
+ /**
167
+ * Accept the expense as a real cost: `unreviewed → reviewed`.
168
+ *
169
+ * This is the separately authorizable review action: gate it in your route
170
+ * or service (for example on `expenses.review`). The expense must already
171
+ * be saved and must not be marked a duplicate.
172
+ *
173
+ * @throws {ExpenseError} `EXPENSE_REVIEW_TRANSITION` from any other state.
174
+ */
175
+ async review(input) {
176
+ const reviewer = requireReviewer(input?.reviewerProfileId);
177
+ return this.transition("review", () => {
178
+ this.reviewStatus = "reviewed";
179
+ this.reviewedByProfileId = reviewer;
180
+ this.reviewedAt = input.at ?? /* @__PURE__ */ new Date();
181
+ this.reviewNote = input.note ?? "";
182
+ this.duplicateOfId = null;
183
+ });
184
+ }
185
+ /**
186
+ * Refuse the expense: `unreviewed | reviewed → rejected`. A rejected
187
+ * expense is kept and shown, and never counted.
188
+ *
189
+ * @throws {ExpenseError} `EXPENSE_REVIEW_TRANSITION` from `rejected`, or
190
+ * `EXPENSE_INVALID` without a reason.
191
+ */
192
+ async reject(input) {
193
+ const reviewer = requireReviewer(input?.reviewerProfileId);
194
+ const reason = (input.reason ?? "").trim();
195
+ if (!reason) throw new ExpenseError("EXPENSE_INVALID", "A rejection needs a reason.");
196
+ return this.transition("reject", () => {
197
+ this.reviewStatus = "rejected";
198
+ this.reviewedByProfileId = reviewer;
199
+ this.reviewedAt = input.at ?? /* @__PURE__ */ new Date();
200
+ this.reviewNote = reason;
201
+ this.duplicateOfId = null;
202
+ });
203
+ }
204
+ /**
205
+ * Mark this expense a duplicate of another expense in the same tenant:
206
+ * `unreviewed | reviewed → rejected` with {@link Expense.duplicateOfId}
207
+ * set. A duplicate never counts toward any total.
208
+ *
209
+ * @throws {ExpenseError} `EXPENSE_INVALID` when the target is this expense
210
+ * or is not visible in this expense's tenant.
211
+ */
212
+ async markDuplicate(input) {
213
+ const reviewer = requireReviewer(input?.reviewerProfileId);
214
+ const targetId = String(input.duplicateOfId ?? "").trim();
215
+ if (!targetId || targetId === this.id) throw new ExpenseError("EXPENSE_INVALID", "An expense can only be a duplicate of a different expense.");
216
+ const { ExpenseCollection } = await import("../index.js").then((n) => n.t);
217
+ const target = await (await ExpenseCollection.create({ db: this.db })).get({ id: targetId });
218
+ if (!target || (target.tenantId ?? null) !== (this.tenantId ?? null)) throw new ExpenseError("EXPENSE_INVALID", `Expense ${targetId} was not found in this expense's tenant.`);
219
+ return this.transition("markDuplicate", () => {
220
+ this.reviewStatus = "rejected";
221
+ this.reviewedByProfileId = reviewer;
222
+ this.reviewedAt = input.at ?? /* @__PURE__ */ new Date();
223
+ this.reviewNote = `Duplicate of expense ${targetId}`;
224
+ this.duplicateOfId = targetId;
225
+ });
226
+ }
227
+ /**
228
+ * Send the expense back for review: `reviewed | rejected → unreviewed`.
229
+ * Clears the reviewer, the review time and any duplicate marker.
230
+ *
231
+ * @throws {ExpenseError} `EXPENSE_REVIEW_TRANSITION` from `unreviewed`.
232
+ */
233
+ async reopen(input) {
234
+ requireReviewer(input?.reviewerProfileId);
235
+ return this.transition("reopen", () => {
236
+ this.reviewStatus = "unreviewed";
237
+ this.reviewedByProfileId = null;
238
+ this.reviewedAt = null;
239
+ this.reviewNote = input.note ?? "";
240
+ this.duplicateOfId = null;
241
+ });
242
+ }
243
+ /**
244
+ * Record that the person who paid has been paid back. Recording only:
245
+ * paying happens in payroll or payables, and this never changes the review
246
+ * state.
247
+ *
248
+ * @throws {ExpenseError} `EXPENSE_INVALID` unless the expense is
249
+ * `reimbursable`.
250
+ */
251
+ async markReimbursed(input = {}) {
252
+ if (!this.reimbursable) throw new ExpenseError("EXPENSE_INVALID", `Expense ${this.id} is not owed back to anyone.`);
253
+ this.reimbursedAt = input.at ?? /* @__PURE__ */ new Date();
254
+ if (input.reference !== void 0) this.reimbursementReference = input.reference;
255
+ return this.save();
256
+ }
257
+ /**
258
+ * Load the cost object this expense is charged to, through its registered
259
+ * collection (so tenant interceptors apply). Returns `null` when unset,
260
+ * when the type is not registered, when the row is gone, or when the row
261
+ * belongs to a different tenant than this expense.
262
+ */
263
+ async getCostObject() {
264
+ if (!this.costObjectType || !this.costObjectId) return null;
265
+ let registered = ObjectRegistry.getClassByQualifiedName(this.costObjectType);
266
+ if (!registered) {
267
+ if (!await ObjectRegistry.tryLoadFromExternalPackage(this.costObjectType)) return null;
268
+ registered = ObjectRegistry.getClassByQualifiedName(this.costObjectType);
269
+ }
270
+ if (!registered) return null;
271
+ const target = await (await ObjectRegistry.getCollection(registered.qualifiedName ?? this.costObjectType, { db: this.db })).get({ id: this.costObjectId });
272
+ if (!target) return null;
273
+ const targetTenant = target.tenantId;
274
+ if (targetTenant !== void 0 && targetTenant !== null && this.tenantId !== null && targetTenant !== this.tenantId) return null;
275
+ return target;
276
+ }
277
+ /**
278
+ * Validate, enforce the review and reviewed-field locks, check the
279
+ * commitment, then persist.
280
+ */
281
+ async save() {
282
+ this.normalize();
283
+ this.validateShape();
284
+ const persisted = await this.readPersisted();
285
+ const inserting = await pinNaturalKey("Expense", this, persisted);
286
+ if (persisted && String(persisted.tenant_id ?? "") !== String(effectiveTenant(this.tenantId) ?? "")) throw new ExpenseError("EXPENSE_INVALID", `Expense ${this.id}: its tenant cannot change after it is recorded.`);
287
+ this.assertReviewFields(persisted);
288
+ this.assertReviewedLock(persisted);
289
+ await this.assertCommitment(persisted);
290
+ await this.assertVendor(persisted);
291
+ if (!this.recordedAt) this.recordedAt = /* @__PURE__ */ new Date();
292
+ try {
293
+ return await super.save();
294
+ } catch (error) {
295
+ if (inserting && isUniqueViolationError(error)) throw identityConflict("Expense", this, error);
296
+ throw error;
297
+ }
298
+ }
299
+ normalize() {
300
+ this.tenantId = normalizeTenantId(this.tenantId);
301
+ this.currency = String(this.currency ?? "").trim().toUpperCase();
302
+ this.category = String(this.category ?? "").trim();
303
+ this.costObjectType = String(this.costObjectType ?? "").trim();
304
+ this.costObjectId = String(this.costObjectId ?? "").trim();
305
+ this.incurredOn = String(this.incurredOn ?? "").trim();
306
+ this.vendorId = asNullableString(this.vendorId);
307
+ this.commitmentId = asNullableString(this.commitmentId);
308
+ this.commitmentLineId = asNullableString(this.commitmentLineId);
309
+ this.paidByProfileId = asNullableString(this.paidByProfileId);
310
+ this.recordedByProfileId = asNullableString(this.recordedByProfileId);
311
+ }
312
+ validateShape() {
313
+ const label = this.id || "<new>";
314
+ assertMinorUnits("Expense", label, "amount", this.amount);
315
+ assertIsoCurrency("Expense", label, this.currency);
316
+ assertIsoDate("Expense", label, "incurredOn", this.incurredOn);
317
+ if (!CATEGORY_PATTERN.test(this.category) || this.category.length > 64) throw new ExpenseError("EXPENSE_INVALID", `Expense ${label}: category must be lowercase kebab-case (for example 'outside-service'), got '${this.category}'.`);
318
+ if (Boolean(this.costObjectType) !== Boolean(this.costObjectId)) throw new ExpenseError("EXPENSE_INVALID", `Expense ${label}: costObjectType and costObjectId are set together or not at all.`);
319
+ if (this.costObjectType) assertQualifiedClassName("Expense", label, this.costObjectType);
320
+ if (this.paidBy !== "company" && this.paidBy !== "person") throw new ExpenseError("EXPENSE_INVALID", `Expense ${label}: paidBy must be 'company' or 'person'.`);
321
+ if (this.paidBy === "person" && !this.paidByProfileId) throw new ExpenseError("EXPENSE_INVALID", `Expense ${label}: an expense paid by a person names that person (paidByProfileId).`);
322
+ if (this.paidBy === "company" && this.paidByProfileId) throw new ExpenseError("EXPENSE_INVALID", `Expense ${label}: paidByProfileId is only set when paidBy is 'person'.`);
323
+ if (this.reimbursable && this.paidBy !== "person") throw new ExpenseError("EXPENSE_INVALID", `Expense ${label}: only an expense a person paid can be owed back.`);
324
+ if (this.reimbursedAt && !this.reimbursable) throw new ExpenseError("EXPENSE_INVALID", `Expense ${label}: reimbursedAt needs reimbursable.`);
325
+ if (this.reviewStatus === "reviewed" && this.duplicateOfId) throw new ExpenseError("EXPENSE_INVALID", `Expense ${label}: a reviewed expense cannot be marked a duplicate.`);
326
+ if (this.commitmentLineId && !this.commitmentId) throw new ExpenseError("EXPENSE_INVALID", `Expense ${label}: a commitment line needs its commitment (commitmentId).`);
327
+ }
328
+ /**
329
+ * Read the stored row directly. The authoritative prior state for the
330
+ * review and lock guards: the in-memory copy may have been mass-assigned.
331
+ */
332
+ async readPersisted() {
333
+ if (!this.id) return null;
334
+ return await this.db.get(this.tableName, { id: this.id }) ?? null;
335
+ }
336
+ reviewState() {
337
+ return {
338
+ status: this.reviewStatus,
339
+ reviewer: asNullableString(this.reviewedByProfileId),
340
+ reviewedAtMs: instantMs(this.reviewedAt),
341
+ note: this.reviewNote ?? "",
342
+ duplicateOf: asNullableString(this.duplicateOfId)
343
+ };
344
+ }
345
+ /**
346
+ * Refuse any review-field change a transition did not authorize. The token
347
+ * binds the transition's complete resulting state — status, reviewer,
348
+ * time, note and duplicate marker — so a field set directly beside a
349
+ * legitimate `review()` / `reject()` cannot ride along with it.
350
+ */
351
+ assertReviewFields(persisted) {
352
+ const token = authorizedTransition.get(this);
353
+ const prior = {
354
+ status: persisted?.review_status ?? "unreviewed",
355
+ reviewer: asNullableString(persisted?.reviewed_by_profile_id),
356
+ reviewedAtMs: instantMs(persisted?.reviewed_at),
357
+ note: String(persisted?.review_note ?? ""),
358
+ duplicateOf: asNullableString(persisted?.duplicate_of_id)
359
+ };
360
+ const current = this.reviewState();
361
+ if (sameReviewState(current, prior)) return;
362
+ if (!token || token.from !== prior.status || !sameReviewState(current, token.expected)) throw new ExpenseError("EXPENSE_REVIEW_FIELDS_LOCKED", `Expense ${this.id || "<new>"}: review state changes only through review(), reject(), markDuplicate() or reopen().`);
363
+ }
364
+ assertReviewedLock(persisted) {
365
+ if (persisted?.review_status !== "reviewed") return;
366
+ const self = this;
367
+ for (const [fieldName, column] of LOCKED_WHEN_REVIEWED) {
368
+ const before = persisted[column];
369
+ const after = self[fieldName];
370
+ if (!(fieldName === "amount" ? Number(before) === Number(after) : fieldName === "recordedAt" ? instantMs(before) === instantMs(after) : asNullableString(before) === asNullableString(after))) throw new ExpenseError("EXPENSE_REVIEW_FIELDS_LOCKED", `Expense ${this.id}: ${fieldName} of a reviewed expense cannot change; reopen() it first.`);
371
+ }
372
+ }
373
+ /**
374
+ * A matched commitment must be visible in this expense's tenant, owned by
375
+ * the same tenant, and in the same currency; a matched line must belong to
376
+ * it. Mixed currencies are refused here rather than summed later.
377
+ *
378
+ * Checked when the match is made or changed, not on every save: a later
379
+ * change to the commitment (its currency, or its deletion) must not stop
380
+ * an unrelated save such as recording a reimbursement.
381
+ */
382
+ async assertCommitment(persisted) {
383
+ if (!this.commitmentId) return;
384
+ if (persisted && asNullableString(persisted.commitment_id) === this.commitmentId && asNullableString(persisted.commitment_line_id) === this.commitmentLineId && String(persisted.currency ?? "") === this.currency) return;
385
+ const commitment = await (await ContractCollection.create({ db: this.db })).get({ id: this.commitmentId });
386
+ const owner = effectiveTenant(this.tenantId);
387
+ if (!commitment || !sameTenant(commitment.tenantId, owner)) throw new ExpenseError("EXPENSE_COMMITMENT_MISMATCH", `Expense ${this.id || "<new>"}: commitment ${this.commitmentId} was not found in this expense's tenant.`);
388
+ if (String(commitment.currency).toUpperCase() !== this.currency) throw new ExpenseError("EXPENSE_COMMITMENT_MISMATCH", `Expense ${this.id || "<new>"}: currency ${this.currency} does not match commitment ${this.commitmentId} (${commitment.currency}). Amounts in different currencies are never summed.`);
389
+ if (this.commitmentLineId) {
390
+ const line = await (await ContractLineItemCollection.create({ db: this.db })).get({ id: this.commitmentLineId });
391
+ if (!line || line.contractId !== this.commitmentId) throw new ExpenseError("EXPENSE_COMMITMENT_MISMATCH", `Expense ${this.id || "<new>"}: line ${this.commitmentLineId} is not a line of commitment ${this.commitmentId}.`);
392
+ }
393
+ }
394
+ /**
395
+ * A vendor must be visible in, and owned by, the expense's tenant. A
396
+ * `crossPackageRef` neither validates its target nor creates a foreign
397
+ * key, so without this an expense in one tenant could name another
398
+ * tenant's vendor. Checked when the vendor is set or changed.
399
+ */
400
+ async assertVendor(persisted) {
401
+ if (!this.vendorId) return;
402
+ if (persisted && asNullableString(persisted.vendor_id) === this.vendorId) return;
403
+ const vendor = await (await VendorCollection.create({ db: this.db })).get({ id: this.vendorId });
404
+ const owner = effectiveTenant(this.tenantId);
405
+ if (!vendor || !sameTenant(vendor.tenantId, owner)) throw new ExpenseError("EXPENSE_VENDOR_MISMATCH", `Expense ${this.id || "<new>"}: vendor ${this.vendorId} was not found in this expense's tenant.`);
406
+ }
407
+ async transition(action, apply) {
408
+ const rule = REVIEW_TRANSITIONS[action];
409
+ const persisted = await this.readPersisted();
410
+ if (!persisted) throw new ExpenseError("EXPENSE_REVIEW_TRANSITION", `Expense ${this.id || "<new>"}: save the expense before ${action}().`);
411
+ const from = String(persisted.review_status);
412
+ if (!rule.from.includes(from)) throw new ExpenseError("EXPENSE_REVIEW_TRANSITION", `Expense ${this.id}: cannot ${action}() an expense that is ${from}.`);
413
+ if (action === "review" && persisted.duplicate_of_id) throw new ExpenseError("EXPENSE_REVIEW_TRANSITION", `Expense ${this.id}: a duplicate cannot be reviewed; reopen() it first.`);
414
+ const snapshot = {
415
+ reviewStatus: this.reviewStatus,
416
+ reviewedByProfileId: this.reviewedByProfileId,
417
+ reviewedAt: this.reviewedAt,
418
+ reviewNote: this.reviewNote,
419
+ duplicateOfId: this.duplicateOfId
420
+ };
421
+ apply();
422
+ authorizedTransition.set(this, {
423
+ from,
424
+ expected: this.reviewState()
425
+ });
426
+ try {
427
+ return await this.save();
428
+ } catch (error) {
429
+ Object.assign(this, snapshot);
430
+ throw error;
431
+ } finally {
432
+ authorizedTransition.delete(this);
433
+ }
434
+ }
435
+ };
436
+ __decorateClass([tenantId({ nullable: true })], Expense.prototype, "tenantId", 2);
437
+ __decorateClass([field({ type: "text" })], Expense.prototype, "costObjectType", 2);
438
+ __decorateClass([field({ type: "text" })], Expense.prototype, "costObjectId", 2);
439
+ __decorateClass([field({ type: "text" })], Expense.prototype, "category", 2);
440
+ __decorateClass([field({ type: "text" })], Expense.prototype, "description", 2);
441
+ __decorateClass([field({ type: "integer" })], Expense.prototype, "amount", 2);
442
+ __decorateClass([field({ type: "text" })], Expense.prototype, "currency", 2);
443
+ __decorateClass([field({ type: "text" })], Expense.prototype, "incurredOn", 2);
444
+ __decorateClass([crossPackageRef(PROFILE)], Expense.prototype, "recordedByProfileId", 2);
445
+ __decorateClass([field({ type: "text" })], Expense.prototype, "paidBy", 2);
446
+ __decorateClass([crossPackageRef(PROFILE)], Expense.prototype, "paidByProfileId", 2);
447
+ __decorateClass([crossPackageRef("@happyvertical/smrt-commerce:Vendor")], Expense.prototype, "vendorId", 2);
448
+ __decorateClass([crossPackageRef("@happyvertical/smrt-commerce:Contract")], Expense.prototype, "commitmentId", 2);
449
+ __decorateClass([crossPackageRef("@happyvertical/smrt-commerce:ContractLineItem")], Expense.prototype, "commitmentLineId", 2);
450
+ __decorateClass([field({
451
+ type: "text",
452
+ readonly: true
453
+ })], Expense.prototype, "reviewStatus", 2);
454
+ __decorateClass([crossPackageRef(PROFILE, { readonly: true })], Expense.prototype, "reviewedByProfileId", 2);
455
+ __decorateClass([field({
456
+ type: "datetime",
457
+ readonly: true
458
+ })], Expense.prototype, "reviewedAt", 2);
459
+ __decorateClass([field({
460
+ type: "text",
461
+ readonly: true
462
+ })], Expense.prototype, "reviewNote", 2);
463
+ __decorateClass([foreignKey("Expense", {
464
+ readonly: true,
465
+ onDelete: "SET NULL"
466
+ })], Expense.prototype, "duplicateOfId", 2);
467
+ __decorateClass([field({ type: "boolean" })], Expense.prototype, "reimbursable", 2);
468
+ __decorateClass([field({ type: "text" })], Expense.prototype, "reimbursementReference", 2);
469
+ Expense = __decorateClass([TenantScoped({ mode: "optional" }), smrt({
470
+ tableName: "expenses",
471
+ api: { include: [] },
472
+ mcp: { include: [] },
473
+ cli: false,
474
+ indexes: [
475
+ {
476
+ name: "expenses_cost_object_idx",
477
+ columns: [
478
+ "tenantId",
479
+ "costObjectType",
480
+ "costObjectId",
481
+ "incurredOn"
482
+ ]
483
+ },
484
+ {
485
+ name: "expenses_commitment_review_idx",
486
+ columns: [
487
+ "tenantId",
488
+ "commitmentId",
489
+ "reviewStatus"
490
+ ]
491
+ },
492
+ {
493
+ name: "expenses_review_status_idx",
494
+ columns: [
495
+ "tenantId",
496
+ "reviewStatus",
497
+ "incurredOn"
498
+ ]
499
+ }
500
+ ]
501
+ })], Expense);
502
+ function requireReviewer(reviewerProfileId) {
503
+ const reviewer = String(reviewerProfileId ?? "").trim();
504
+ if (!reviewer) throw new ExpenseError("EXPENSE_INVALID", "A review decision names its reviewer (reviewerProfileId).");
505
+ return reviewer;
506
+ }
507
+ function sameTenant(a, b) {
508
+ return (a ?? null) === (b ?? null);
509
+ }
510
+ //#endregion
511
+ export { identityConflict as a, pinNaturalKey as c, effectiveTenant as i, assertMinorUnits as n, normalizeSha256 as o, computeContentSha256 as r, normalizeTenantId as s, Expense as t };
512
+
513
+ //# sourceMappingURL=Expense-C1uUZbAr.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Expense-C1uUZbAr.js","names":[],"sources":["../../src/validation.ts","../../src/models/Expense.ts"],"sourcesContent":["/**\n * Small, pure validators shared by the expense models.\n *\n * @packageDocumentation\n */\n\nimport { createHash } from 'node:crypto';\nimport { getTenantId } from '@happyvertical/smrt-tenancy';\nimport { ExpenseError, type ExpenseErrorCode } from './types.js';\n\n/** Lowercase kebab-case: `material`, `outside-service`. */\nexport const CATEGORY_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\nconst ISO_CURRENCY = /^[A-Z]{3}$/;\nconst ISO_DATE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst QUALIFIED_CLASS = /^[^\\s:]+:[A-Za-z_$][\\w$]*$/;\nconst SHA256_HEX = /^[0-9a-f]{64}$/;\n\n/**\n * Throw unless `value` is a non-negative, JavaScript-safe integer number of\n * minor units. Money is exact: `$19.99` is `1999`, never `19.99`.\n */\nexport function assertMinorUnits(\n model: string,\n label: string,\n fieldName: string,\n value: number,\n code: ExpenseErrorCode = 'EXPENSE_INVALID',\n): void {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new ExpenseError(\n code,\n `${model} ${label}: ${fieldName} must be a non-negative integer ` +\n `number of minor units (cents) — got ${value}. $19.99 is 1999.`,\n );\n }\n}\n\n/** Throw unless `value` is an upper-case ISO 4217 code such as `USD`. */\nexport function assertIsoCurrency(\n model: string,\n label: string,\n value: string,\n): void {\n if (!ISO_CURRENCY.test(value)) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n `${model} ${label}: currency must be a three-letter ISO 4217 code ` +\n `(for example 'USD'), got '${value}'.`,\n );\n }\n}\n\n/** Throw unless `value` is a real calendar date written `YYYY-MM-DD`. */\nexport function assertIsoDate(\n model: string,\n label: string,\n fieldName: string,\n value: string,\n): void {\n const match = ISO_DATE.exec(value);\n const valid =\n match !== null &&\n (() => {\n const [year, month, day] = match.slice(1).map(Number);\n const date = new Date(Date.UTC(year, month - 1, day));\n return (\n date.getUTCFullYear() === year &&\n date.getUTCMonth() === month - 1 &&\n date.getUTCDate() === day\n );\n })();\n if (!valid) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n `${model} ${label}: ${fieldName} must be a calendar date written ` +\n `YYYY-MM-DD, got '${value}'.`,\n );\n }\n}\n\n/**\n * Throw unless `value` is a package-qualified class name such as\n * `@happyvertical/smrt-projects:Project`. A bare class name is ambiguous\n * (packages can share names) and is refused.\n */\nexport function assertQualifiedClassName(\n model: string,\n label: string,\n value: string,\n): void {\n if (!QUALIFIED_CLASS.test(value)) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n `${model} ${label}: costObjectType must be a qualified class name ` +\n `such as '@happyvertical/smrt-projects:Project', got '${value}'.`,\n );\n }\n}\n\n/** Normalize and check a SHA-256 hex digest; returns it in lower case. */\nexport function normalizeSha256(model: string, label: string, value: string) {\n const digest = String(value ?? '')\n .trim()\n .toLowerCase();\n if (!SHA256_HEX.test(digest)) {\n throw new ExpenseError(\n 'EXPENSE_RECEIPT_INVALID',\n `${model} ${label}: contentSha256 must be a 64-character hex SHA-256 ` +\n 'digest of the file bytes.',\n );\n }\n return digest;\n}\n\n/**\n * Lowercase hex SHA-256 of a file's bytes — the value\n * `ExpenseReceipt.contentSha256` expects.\n *\n * @example\n * ```typescript\n * const digest = computeContentSha256(await readFile('receipt.pdf'));\n * ```\n */\nexport function computeContentSha256(data: Uint8Array | string): string {\n return createHash('sha256').update(data).digest('hex');\n}\n\n/** Milliseconds since the epoch of a date-ish value; `null` when empty. */\nexport function instantMs(value: unknown): number | null {\n if (value === null || value === undefined || value === '') return null;\n const ms =\n value instanceof Date ? value.getTime() : new Date(String(value)).getTime();\n return Number.isNaN(ms) ? null : ms;\n}\n\n/** The slice of `SmrtObject` the natural-key identity guard needs. */\ninterface NaturalKeyed {\n id?: string | null;\n slug?: string | null;\n context?: string | null;\n readonly isPersisted: boolean;\n getSlug(): Promise<unknown>;\n requireInsertOnSave(): void;\n}\n\n/**\n * Make a save write only the row its guards checked.\n *\n * Core's natural-key save adopts any same-owner row on\n * `(tenant_id, slug, context)` and upserts it without a revision predicate,\n * and these models have no human slug. So:\n *\n * - a fresh (never loaded, never saved) instance may only INSERT\n * (`requireInsertOnSave`): naming an existing row's id is refused here, and\n * a row that appears between this check and the write makes the INSERT\n * fail rather than be adopted;\n * - an existing row is changed only through a loaded instance, whose save\n * carries core's revision compare-and-swap, and it must keep the slug and\n * context it is stored under, so the write targets that row and no other.\n *\n * @returns `true` when this save is an INSERT.\n * @throws {ExpenseError} `EXPENSE_IDENTITY_CONFLICT` when a fresh instance\n * names an existing row, or a loaded one changes its natural key.\n */\nexport async function pinNaturalKey(\n model: string,\n object: NaturalKeyed,\n persisted: Record<string, unknown> | null,\n): Promise<boolean> {\n await object.getSlug();\n if (!object.isPersisted) {\n if (persisted) {\n throw new ExpenseError(\n 'EXPENSE_IDENTITY_CONFLICT',\n `${model} ${object.id} already exists; load it and save the loaded ` +\n 'instance instead of creating one with its id.',\n );\n }\n object.requireInsertOnSave();\n return true;\n }\n if (\n persisted &&\n (String(persisted.slug ?? '') !== String(object.slug ?? '') ||\n String(persisted.context ?? '') !== String(object.context ?? ''))\n ) {\n throw new ExpenseError(\n 'EXPENSE_IDENTITY_CONFLICT',\n `${model} ${object.id}: slug and context cannot change; they would ` +\n 'point the save at a different row.',\n );\n }\n return false;\n}\n\n/** The error a refused natural-key INSERT is reported as. */\nexport function identityConflict(\n model: string,\n object: { id?: string | null; slug?: string | null },\n cause: unknown,\n): ExpenseError {\n return new ExpenseError(\n 'EXPENSE_IDENTITY_CONFLICT',\n `${model} ${object.id}: another row already uses slug ` +\n `'${object.slug}' in this tenant; a new ${model} cannot take it over.`,\n { cause },\n );\n}\n\n/**\n * The tenant a save will actually write: tenancy's `beforeSave` interceptor\n * fills an unset `tenantId` from the active tenant context, after the\n * model's own checks have run, and \"unset\" is falsy there — `''` included.\n * Compare against this, not the raw field.\n */\nexport function effectiveTenant(\n tenantId: string | null | undefined,\n): string | null {\n return tenantId || getTenantId() || null;\n}\n\n/**\n * An empty tenant id is unset, never a tenant of its own: core and tenancy\n * treat it as falsy (and real tenant ids are UUIDs), so it is stored as\n * NULL — a global row — rather than as a `''` pseudo-tenant.\n */\nexport function normalizeTenantId(\n tenantId: string | null | undefined,\n): string | null {\n return tenantId || null;\n}\n","/**\n * Expense — a cost someone incurred, against a cost object, with a review\n * state and optional reimbursement and commitment links.\n *\n * @packageDocumentation\n */\n\nimport {\n ContractCollection,\n ContractLineItemCollection,\n VendorCollection,\n} from '@happyvertical/smrt-commerce';\nimport {\n crossPackageRef,\n field,\n foreignKey,\n isUniqueViolationError,\n ObjectRegistry,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport {\n ExpenseError,\n type ExpenseOptions,\n type ExpensePayer,\n type ExpenseReviewStatus,\n type MarkDuplicateExpenseInput,\n type MarkReimbursedInput,\n type RejectExpenseInput,\n type ReopenExpenseInput,\n type ReviewExpenseInput,\n} from '../types.js';\nimport {\n assertIsoCurrency,\n assertIsoDate,\n assertMinorUnits,\n assertQualifiedClassName,\n CATEGORY_PATTERN,\n effectiveTenant,\n identityConflict,\n instantMs,\n normalizeTenantId,\n pinNaturalKey,\n} from '../validation.js';\n\nconst PROFILE = '@happyvertical/smrt-profiles:Profile';\n\n/**\n * Legal review moves, keyed by the persisted status. Only the dedicated\n * methods perform them; `save()` refuses a review-field change they did not\n * authorize.\n */\nconst REVIEW_TRANSITIONS: Record<\n 'review' | 'reject' | 'markDuplicate' | 'reopen',\n { from: readonly ExpenseReviewStatus[]; to: ExpenseReviewStatus }\n> = {\n review: { from: ['unreviewed'], to: 'reviewed' },\n reject: { from: ['unreviewed', 'reviewed'], to: 'rejected' },\n markDuplicate: { from: ['unreviewed', 'reviewed'], to: 'rejected' },\n reopen: { from: ['reviewed', 'rejected'], to: 'unreviewed' },\n};\n\n/**\n * Fields a reviewed expense freezes. Changing one needs `reopen()` first, so\n * a reviewed amount can never move without a fresh review.\n */\nconst LOCKED_WHEN_REVIEWED = [\n ['amount', 'amount'],\n ['currency', 'currency'],\n ['incurredOn', 'incurred_on'],\n ['recordedAt', 'recorded_at'],\n ['category', 'category'],\n ['costObjectType', 'cost_object_type'],\n ['costObjectId', 'cost_object_id'],\n ['vendorId', 'vendor_id'],\n ['commitmentId', 'commitment_id'],\n ['commitmentLineId', 'commitment_line_id'],\n ['paidBy', 'paid_by'],\n ['paidByProfileId', 'paid_by_profile_id'],\n] as const;\n\n/** The review transition a dedicated method has authorized for one save. */\nconst authorizedTransition = new WeakMap<\n Expense,\n { from: ExpenseReviewStatus; expected: ReviewFieldState }\n>();\n\n/** Every review field, normalized for comparison. */\ninterface ReviewFieldState {\n status: ExpenseReviewStatus;\n reviewer: string | null;\n reviewedAtMs: number | null;\n note: string;\n duplicateOf: string | null;\n}\n\nfunction sameReviewState(a: ReviewFieldState, b: ReviewFieldState): boolean {\n return (\n a.status === b.status &&\n a.reviewer === b.reviewer &&\n a.reviewedAtMs === b.reviewedAtMs &&\n a.note === b.note &&\n a.duplicateOf === b.duplicateOf\n );\n}\n\ntype PersistedRow = Record<string, unknown>;\n\nfunction asNullableString(value: unknown): string | null {\n return value === null || value === undefined || value === ''\n ? null\n : String(value);\n}\n\n/**\n * A cost someone incurred.\n *\n * - **Cost object** — polymorphic `(costObjectType, costObjectId)`: a job, a\n * work package, a project, any registered SMRT object. Exactly one per\n * expense, so a cost is never rolled up into two jobs.\n * - **Money** — `amount` in integer minor units with an ISO 4217 `currency`.\n * - **Dates** — `incurredOn` (calendar date, `YYYY-MM-DD`) is when the cost\n * happened; `recordedAt` is when it was entered.\n * - **Review** — `unreviewed → reviewed | rejected`, only through\n * {@link Expense.review}, {@link Expense.reject},\n * {@link Expense.markDuplicate} and {@link Expense.reopen}. A plain field\n * write to the review state is refused on save.\n * - **Reimbursement** — recording only: whether a person who paid is owed\n * back and when they were paid. Never changes review state.\n * - **Commitment** — optional commerce `Contract` (usually a `PurchaseOrder`)\n * or one of its lines that this actual draws down.\n *\n * The generated REST/MCP/CLI surface is closed (`api: { include: [] }`):\n * cost visibility is permission-gated by every consumer, so they expose\n * expenses through their own routes and call the domain methods here.\n */\n@TenantScoped({ mode: 'optional' })\n@smrt({\n tableName: 'expenses',\n api: { include: [] },\n mcp: { include: [] },\n cli: false,\n indexes: [\n {\n name: 'expenses_cost_object_idx',\n columns: ['tenantId', 'costObjectType', 'costObjectId', 'incurredOn'],\n },\n {\n name: 'expenses_commitment_review_idx',\n columns: ['tenantId', 'commitmentId', 'reviewStatus'],\n },\n {\n name: 'expenses_review_status_idx',\n columns: ['tenantId', 'reviewStatus', 'incurredOn'],\n },\n ],\n})\nexport class Expense extends SmrtObject {\n /** Owning tenant. Nullable: optional tenancy, like every commerce model. */\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n /**\n * Qualified class of the cost object, e.g.\n * `@happyvertical/smrt-projects:Project`. Empty only for an unallocated\n * expense (then `costObjectId` is empty too).\n */\n @field({ type: 'text' })\n costObjectType: string = '';\n\n /** Id of the cost object. Bare string: the target table is polymorphic. */\n @field({ type: 'text' })\n costObjectId: string = '';\n\n /**\n * Lowercase kebab-case category. See `SUGGESTED_EXPENSE_CATEGORIES`;\n * any value matching the pattern is accepted.\n */\n @field({ type: 'text' })\n category: string = 'other';\n\n /** What was bought or paid for. */\n @field({ type: 'text' })\n description: string = '';\n\n /** Amount in integer minor units (cents). `= 0` makes the column INTEGER. */\n @field({ type: 'integer' })\n amount: number = 0;\n\n /** ISO 4217 currency code, upper case. Required. */\n @field({ type: 'text' })\n currency: string = '';\n\n /** Calendar date the cost was incurred, `YYYY-MM-DD`. Required. */\n @field({ type: 'text' })\n incurredOn: string = '';\n\n /** When the expense was recorded; set on first save when empty. */\n recordedAt: Date | null = null;\n\n /** Profile that recorded the expense. */\n @crossPackageRef(PROFILE)\n recordedByProfileId: string | null = null;\n\n /** `company`, or `person` (then {@link Expense.paidByProfileId} is set). */\n @field({ type: 'text' })\n paidBy: ExpensePayer = 'company';\n\n /** Profile that paid out of pocket; required when `paidBy` is `person`. */\n @crossPackageRef(PROFILE)\n paidByProfileId: string | null = null;\n\n /** Optional commerce vendor the cost was paid to. */\n @crossPackageRef('@happyvertical/smrt-commerce:Vendor')\n vendorId: string | null = null;\n\n /**\n * Optional commitment this actual draws down: a commerce `Contract`\n * (normally a `PurchaseOrder`). Must be in the same currency and tenant.\n */\n @crossPackageRef('@happyvertical/smrt-commerce:Contract')\n commitmentId: string | null = null;\n\n /** Optional line of {@link Expense.commitmentId} this actual draws down. */\n @crossPackageRef('@happyvertical/smrt-commerce:ContractLineItem')\n commitmentLineId: string | null = null;\n\n /** Review state. Changed only by the review methods. */\n @field({ type: 'text', readonly: true })\n reviewStatus: ExpenseReviewStatus = 'unreviewed';\n\n /** Profile that made the current review decision. */\n @crossPackageRef(PROFILE, { readonly: true })\n reviewedByProfileId: string | null = null;\n\n /** When the current review decision was made. */\n @field({ type: 'datetime', readonly: true })\n reviewedAt: Date | null = null;\n\n /** Review note or rejection reason. */\n @field({ type: 'text', readonly: true })\n reviewNote: string = '';\n\n /**\n * Set when a reviewer marked this expense a duplicate of another one. A\n * duplicate is `rejected` and never counts toward any total.\n */\n @foreignKey('Expense', { readonly: true, onDelete: 'SET NULL' })\n duplicateOfId: string | null = null;\n\n /** Whether the person who paid is owed the amount back. */\n @field({ type: 'boolean' })\n reimbursable: boolean = false;\n\n /** When the person was paid back; set by {@link Expense.markReimbursed}. */\n reimbursedAt: Date | null = null;\n\n /** Payroll line, payables reference, or transfer id of the payback. */\n @field({ type: 'text' })\n reimbursementReference: string = '';\n\n constructor(options: ExpenseOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.costObjectType !== undefined)\n this.costObjectType = options.costObjectType;\n if (options.costObjectId !== undefined)\n this.costObjectId = options.costObjectId;\n if (options.category !== undefined) this.category = options.category;\n if (options.description !== undefined)\n this.description = options.description;\n if (options.amount !== undefined) this.amount = options.amount;\n if (options.currency !== undefined) this.currency = options.currency;\n if (options.incurredOn !== undefined) this.incurredOn = options.incurredOn;\n if (options.recordedAt !== undefined) this.recordedAt = options.recordedAt;\n if (options.recordedByProfileId !== undefined)\n this.recordedByProfileId = options.recordedByProfileId;\n if (options.paidBy !== undefined) this.paidBy = options.paidBy;\n if (options.paidByProfileId !== undefined)\n this.paidByProfileId = options.paidByProfileId;\n if (options.vendorId !== undefined) this.vendorId = options.vendorId;\n if (options.commitmentId !== undefined)\n this.commitmentId = options.commitmentId;\n if (options.commitmentLineId !== undefined)\n this.commitmentLineId = options.commitmentLineId;\n if (options.reimbursable !== undefined)\n this.reimbursable = options.reimbursable;\n if (options.reimbursedAt !== undefined)\n this.reimbursedAt = options.reimbursedAt;\n if (options.reimbursementReference !== undefined)\n this.reimbursementReference = options.reimbursementReference;\n }\n\n /** True when the person who paid has been paid back. */\n isReimbursed(): boolean {\n return this.reimbursedAt !== null && this.reimbursedAt !== undefined;\n }\n\n /** True when this expense counts toward reviewed totals and drawdown. */\n isCountable(): boolean {\n return this.reviewStatus === 'reviewed' && !this.duplicateOfId;\n }\n\n /**\n * Accept the expense as a real cost: `unreviewed → reviewed`.\n *\n * This is the separately authorizable review action: gate it in your route\n * or service (for example on `expenses.review`). The expense must already\n * be saved and must not be marked a duplicate.\n *\n * @throws {ExpenseError} `EXPENSE_REVIEW_TRANSITION` from any other state.\n */\n async review(input: ReviewExpenseInput): Promise<this> {\n const reviewer = requireReviewer(input?.reviewerProfileId);\n return this.transition('review', () => {\n this.reviewStatus = 'reviewed';\n this.reviewedByProfileId = reviewer;\n this.reviewedAt = input.at ?? new Date();\n this.reviewNote = input.note ?? '';\n this.duplicateOfId = null;\n });\n }\n\n /**\n * Refuse the expense: `unreviewed | reviewed → rejected`. A rejected\n * expense is kept and shown, and never counted.\n *\n * @throws {ExpenseError} `EXPENSE_REVIEW_TRANSITION` from `rejected`, or\n * `EXPENSE_INVALID` without a reason.\n */\n async reject(input: RejectExpenseInput): Promise<this> {\n const reviewer = requireReviewer(input?.reviewerProfileId);\n const reason = (input.reason ?? '').trim();\n if (!reason) {\n throw new ExpenseError('EXPENSE_INVALID', 'A rejection needs a reason.');\n }\n return this.transition('reject', () => {\n this.reviewStatus = 'rejected';\n this.reviewedByProfileId = reviewer;\n this.reviewedAt = input.at ?? new Date();\n this.reviewNote = reason;\n this.duplicateOfId = null;\n });\n }\n\n /**\n * Mark this expense a duplicate of another expense in the same tenant:\n * `unreviewed | reviewed → rejected` with {@link Expense.duplicateOfId}\n * set. A duplicate never counts toward any total.\n *\n * @throws {ExpenseError} `EXPENSE_INVALID` when the target is this expense\n * or is not visible in this expense's tenant.\n */\n async markDuplicate(input: MarkDuplicateExpenseInput): Promise<this> {\n const reviewer = requireReviewer(input?.reviewerProfileId);\n const targetId = String(input.duplicateOfId ?? '').trim();\n if (!targetId || targetId === this.id) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n 'An expense can only be a duplicate of a different expense.',\n );\n }\n const { ExpenseCollection } = await import(\n '../collections/ExpenseCollection.js'\n );\n const expenses = await ExpenseCollection.create({ db: this.db });\n const target = await expenses.get({ id: targetId });\n if (!target || (target.tenantId ?? null) !== (this.tenantId ?? null)) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n `Expense ${targetId} was not found in this expense's tenant.`,\n );\n }\n return this.transition('markDuplicate', () => {\n this.reviewStatus = 'rejected';\n this.reviewedByProfileId = reviewer;\n this.reviewedAt = input.at ?? new Date();\n this.reviewNote = `Duplicate of expense ${targetId}`;\n this.duplicateOfId = targetId;\n });\n }\n\n /**\n * Send the expense back for review: `reviewed | rejected → unreviewed`.\n * Clears the reviewer, the review time and any duplicate marker.\n *\n * @throws {ExpenseError} `EXPENSE_REVIEW_TRANSITION` from `unreviewed`.\n */\n async reopen(input: ReopenExpenseInput): Promise<this> {\n requireReviewer(input?.reviewerProfileId);\n return this.transition('reopen', () => {\n this.reviewStatus = 'unreviewed';\n this.reviewedByProfileId = null;\n this.reviewedAt = null;\n this.reviewNote = input.note ?? '';\n this.duplicateOfId = null;\n });\n }\n\n /**\n * Record that the person who paid has been paid back. Recording only:\n * paying happens in payroll or payables, and this never changes the review\n * state.\n *\n * @throws {ExpenseError} `EXPENSE_INVALID` unless the expense is\n * `reimbursable`.\n */\n async markReimbursed(input: MarkReimbursedInput = {}): Promise<this> {\n if (!this.reimbursable) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n `Expense ${this.id} is not owed back to anyone.`,\n );\n }\n this.reimbursedAt = input.at ?? new Date();\n if (input.reference !== undefined)\n this.reimbursementReference = input.reference;\n return this.save();\n }\n\n /**\n * Load the cost object this expense is charged to, through its registered\n * collection (so tenant interceptors apply). Returns `null` when unset,\n * when the type is not registered, when the row is gone, or when the row\n * belongs to a different tenant than this expense.\n */\n async getCostObject<T extends SmrtObject = SmrtObject>(): Promise<T | null> {\n if (!this.costObjectType || !this.costObjectId) return null;\n let registered = ObjectRegistry.getClassByQualifiedName(\n this.costObjectType,\n );\n if (!registered) {\n const loaded = await ObjectRegistry.tryLoadFromExternalPackage(\n this.costObjectType,\n );\n if (!loaded) return null;\n registered = ObjectRegistry.getClassByQualifiedName(this.costObjectType);\n }\n if (!registered) return null;\n const collection = await ObjectRegistry.getCollection<SmrtObject>(\n registered.qualifiedName ?? this.costObjectType,\n { db: this.db },\n );\n const target = await collection.get({ id: this.costObjectId });\n if (!target) return null;\n const targetTenant = (target as unknown as { tenantId?: string | null })\n .tenantId;\n if (\n targetTenant !== undefined &&\n targetTenant !== null &&\n this.tenantId !== null &&\n targetTenant !== this.tenantId\n ) {\n return null;\n }\n return target as T;\n }\n\n /**\n * Validate, enforce the review and reviewed-field locks, check the\n * commitment, then persist.\n */\n override async save(): Promise<this> {\n this.normalize();\n this.validateShape();\n\n const persisted = await this.readPersisted();\n // The guards below check `persisted`; pin the write to that row.\n const inserting = await pinNaturalKey('Expense', this, persisted);\n if (\n persisted &&\n String(persisted.tenant_id ?? '') !==\n String(effectiveTenant(this.tenantId) ?? '')\n ) {\n // Includes the quiet case: saving a global expense inside a tenant\n // context, where the interceptor would fill in that tenant and split\n // the expense from its global receipts and links.\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n `Expense ${this.id}: its tenant cannot change after it is recorded.`,\n );\n }\n this.assertReviewFields(persisted);\n this.assertReviewedLock(persisted);\n await this.assertCommitment(persisted);\n await this.assertVendor(persisted);\n\n if (!this.recordedAt) this.recordedAt = new Date();\n try {\n return await super.save();\n } catch (error) {\n // A new expense is a plain INSERT; its only unique keys are the id and\n // the natural key, so a violation means it named an existing row.\n if (inserting && isUniqueViolationError(error)) {\n throw identityConflict('Expense', this, error);\n }\n throw error;\n }\n }\n\n private normalize(): void {\n this.tenantId = normalizeTenantId(this.tenantId);\n this.currency = String(this.currency ?? '')\n .trim()\n .toUpperCase();\n this.category = String(this.category ?? '').trim();\n this.costObjectType = String(this.costObjectType ?? '').trim();\n this.costObjectId = String(this.costObjectId ?? '').trim();\n this.incurredOn = String(this.incurredOn ?? '').trim();\n this.vendorId = asNullableString(this.vendorId);\n this.commitmentId = asNullableString(this.commitmentId);\n this.commitmentLineId = asNullableString(this.commitmentLineId);\n this.paidByProfileId = asNullableString(this.paidByProfileId);\n this.recordedByProfileId = asNullableString(this.recordedByProfileId);\n }\n\n private validateShape(): void {\n const label = this.id || '<new>';\n assertMinorUnits('Expense', label, 'amount', this.amount);\n assertIsoCurrency('Expense', label, this.currency);\n assertIsoDate('Expense', label, 'incurredOn', this.incurredOn);\n if (!CATEGORY_PATTERN.test(this.category) || this.category.length > 64) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n `Expense ${label}: category must be lowercase kebab-case ` +\n `(for example 'outside-service'), got '${this.category}'.`,\n );\n }\n if (Boolean(this.costObjectType) !== Boolean(this.costObjectId)) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n `Expense ${label}: costObjectType and costObjectId are set together ` +\n 'or not at all.',\n );\n }\n if (this.costObjectType) {\n assertQualifiedClassName('Expense', label, this.costObjectType);\n }\n if (this.paidBy !== 'company' && this.paidBy !== 'person') {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n `Expense ${label}: paidBy must be 'company' or 'person'.`,\n );\n }\n if (this.paidBy === 'person' && !this.paidByProfileId) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n `Expense ${label}: an expense paid by a person names that person ` +\n '(paidByProfileId).',\n );\n }\n if (this.paidBy === 'company' && this.paidByProfileId) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n `Expense ${label}: paidByProfileId is only set when paidBy is 'person'.`,\n );\n }\n if (this.reimbursable && this.paidBy !== 'person') {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n `Expense ${label}: only an expense a person paid can be owed back.`,\n );\n }\n if (this.reimbursedAt && !this.reimbursable) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n `Expense ${label}: reimbursedAt needs reimbursable.`,\n );\n }\n if (this.reviewStatus === 'reviewed' && this.duplicateOfId) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n `Expense ${label}: a reviewed expense cannot be marked a duplicate.`,\n );\n }\n if (this.commitmentLineId && !this.commitmentId) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n `Expense ${label}: a commitment line needs its commitment ` +\n '(commitmentId).',\n );\n }\n }\n\n /**\n * Read the stored row directly. The authoritative prior state for the\n * review and lock guards: the in-memory copy may have been mass-assigned.\n */\n private async readPersisted(): Promise<PersistedRow | null> {\n if (!this.id) return null;\n const row = await this.db.get(this.tableName, { id: this.id });\n return (row as PersistedRow | null | undefined) ?? null;\n }\n\n private reviewState(): ReviewFieldState {\n return {\n status: this.reviewStatus,\n reviewer: asNullableString(this.reviewedByProfileId),\n reviewedAtMs: instantMs(this.reviewedAt),\n note: this.reviewNote ?? '',\n duplicateOf: asNullableString(this.duplicateOfId),\n };\n }\n\n /**\n * Refuse any review-field change a transition did not authorize. The token\n * binds the transition's complete resulting state — status, reviewer,\n * time, note and duplicate marker — so a field set directly beside a\n * legitimate `review()` / `reject()` cannot ride along with it.\n */\n private assertReviewFields(persisted: PersistedRow | null): void {\n const token = authorizedTransition.get(this);\n const prior: ReviewFieldState = {\n status: (persisted?.review_status ?? 'unreviewed') as ExpenseReviewStatus,\n reviewer: asNullableString(persisted?.reviewed_by_profile_id),\n reviewedAtMs: instantMs(persisted?.reviewed_at),\n note: String(persisted?.review_note ?? ''),\n duplicateOf: asNullableString(persisted?.duplicate_of_id),\n };\n const current = this.reviewState();\n if (sameReviewState(current, prior)) return;\n if (\n !token ||\n token.from !== prior.status ||\n !sameReviewState(current, token.expected)\n ) {\n throw new ExpenseError(\n 'EXPENSE_REVIEW_FIELDS_LOCKED',\n `Expense ${this.id || '<new>'}: review state changes only through ` +\n 'review(), reject(), markDuplicate() or reopen().',\n );\n }\n }\n\n private assertReviewedLock(persisted: PersistedRow | null): void {\n if (persisted?.review_status !== 'reviewed') return;\n const self = this as unknown as Record<string, unknown>;\n for (const [fieldName, column] of LOCKED_WHEN_REVIEWED) {\n const before = persisted[column];\n const after = self[fieldName];\n const same =\n fieldName === 'amount'\n ? Number(before) === Number(after)\n : fieldName === 'recordedAt'\n ? instantMs(before) === instantMs(after)\n : asNullableString(before) === asNullableString(after);\n if (!same) {\n throw new ExpenseError(\n 'EXPENSE_REVIEW_FIELDS_LOCKED',\n `Expense ${this.id}: ${fieldName} of a reviewed expense cannot ` +\n 'change; reopen() it first.',\n );\n }\n }\n }\n\n /**\n * A matched commitment must be visible in this expense's tenant, owned by\n * the same tenant, and in the same currency; a matched line must belong to\n * it. Mixed currencies are refused here rather than summed later.\n *\n * Checked when the match is made or changed, not on every save: a later\n * change to the commitment (its currency, or its deletion) must not stop\n * an unrelated save such as recording a reimbursement.\n */\n private async assertCommitment(\n persisted: PersistedRow | null,\n ): Promise<void> {\n if (!this.commitmentId) return;\n if (\n persisted &&\n asNullableString(persisted.commitment_id) === this.commitmentId &&\n asNullableString(persisted.commitment_line_id) ===\n this.commitmentLineId &&\n String(persisted.currency ?? '') === this.currency\n ) {\n return;\n }\n const contracts = await ContractCollection.create({ db: this.db });\n const commitment = await contracts.get({ id: this.commitmentId });\n // Before super.save() the tenant interceptor has not populated tenantId\n // yet, so compare against the tenant the row is about to be written in.\n const owner = effectiveTenant(this.tenantId);\n if (!commitment || !sameTenant(commitment.tenantId, owner)) {\n throw new ExpenseError(\n 'EXPENSE_COMMITMENT_MISMATCH',\n `Expense ${this.id || '<new>'}: commitment ${this.commitmentId} was ` +\n \"not found in this expense's tenant.\",\n );\n }\n if (String(commitment.currency).toUpperCase() !== this.currency) {\n throw new ExpenseError(\n 'EXPENSE_COMMITMENT_MISMATCH',\n `Expense ${this.id || '<new>'}: currency ${this.currency} does not ` +\n `match commitment ${this.commitmentId} (${commitment.currency}). ` +\n 'Amounts in different currencies are never summed.',\n );\n }\n if (this.commitmentLineId) {\n const lines = await ContractLineItemCollection.create({ db: this.db });\n const line = await lines.get({ id: this.commitmentLineId });\n if (!line || line.contractId !== this.commitmentId) {\n throw new ExpenseError(\n 'EXPENSE_COMMITMENT_MISMATCH',\n `Expense ${this.id || '<new>'}: line ${this.commitmentLineId} is ` +\n `not a line of commitment ${this.commitmentId}.`,\n );\n }\n }\n }\n\n /**\n * A vendor must be visible in, and owned by, the expense's tenant. A\n * `crossPackageRef` neither validates its target nor creates a foreign\n * key, so without this an expense in one tenant could name another\n * tenant's vendor. Checked when the vendor is set or changed.\n */\n private async assertVendor(persisted: PersistedRow | null): Promise<void> {\n if (!this.vendorId) return;\n if (persisted && asNullableString(persisted.vendor_id) === this.vendorId) {\n return;\n }\n const vendors = await VendorCollection.create({ db: this.db });\n const vendor = await vendors.get({ id: this.vendorId });\n const owner = effectiveTenant(this.tenantId);\n if (!vendor || !sameTenant(vendor.tenantId, owner)) {\n throw new ExpenseError(\n 'EXPENSE_VENDOR_MISMATCH',\n `Expense ${this.id || '<new>'}: vendor ${this.vendorId} was not ` +\n \"found in this expense's tenant.\",\n );\n }\n }\n\n private async transition(\n action: keyof typeof REVIEW_TRANSITIONS,\n apply: () => void,\n ): Promise<this> {\n const rule = REVIEW_TRANSITIONS[action];\n const persisted = await this.readPersisted();\n if (!persisted) {\n throw new ExpenseError(\n 'EXPENSE_REVIEW_TRANSITION',\n `Expense ${this.id || '<new>'}: save the expense before ${action}().`,\n );\n }\n const from = String(persisted.review_status) as ExpenseReviewStatus;\n if (!rule.from.includes(from)) {\n throw new ExpenseError(\n 'EXPENSE_REVIEW_TRANSITION',\n `Expense ${this.id}: cannot ${action}() an expense that is ${from}.`,\n );\n }\n if (action === 'review' && persisted.duplicate_of_id) {\n throw new ExpenseError(\n 'EXPENSE_REVIEW_TRANSITION',\n `Expense ${this.id}: a duplicate cannot be reviewed; reopen() it first.`,\n );\n }\n const snapshot = {\n reviewStatus: this.reviewStatus,\n reviewedByProfileId: this.reviewedByProfileId,\n reviewedAt: this.reviewedAt,\n reviewNote: this.reviewNote,\n duplicateOfId: this.duplicateOfId,\n };\n // Every transition assigns every review field, so the token below\n // describes the whole resulting review state.\n apply();\n authorizedTransition.set(this, { from, expected: this.reviewState() });\n try {\n return await this.save();\n } catch (error) {\n Object.assign(this, snapshot);\n throw error;\n } finally {\n authorizedTransition.delete(this);\n }\n }\n}\n\nfunction requireReviewer(reviewerProfileId: string | undefined): string {\n const reviewer = String(reviewerProfileId ?? '').trim();\n if (!reviewer) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n 'A review decision names its reviewer (reviewerProfileId).',\n );\n }\n return reviewer;\n}\n\nfunction sameTenant(\n a: string | null | undefined,\n b: string | null | undefined,\n): boolean {\n return (a ?? null) === (b ?? null);\n}\n"],"mappings":";;;;;;AAWO,IAAM,mBAAmB;AAEhC,IAAM,eAAe;AACrB,IAAM,WAAW;AACjB,IAAM,kBAAkB;AACxB,IAAM,aAAa;AAMZ,SAAS,iBACd,OACA,OACA,WACA,OACA,OAAyB,mBACnB;CACN,IAAI,CAAC,OAAO,cAAc,KAAK,KAAK,QAAQ,GAC1C,MAAM,IAAI,aACR,MACA,GAAG,MAAK,GAAI,MAAK,IAAK,UAAS,2EACU,MAAK,kBAChD;AAEJ;AAGO,SAAS,kBACd,OACA,OACA,OACM;CACN,IAAI,CAAC,aAAa,KAAK,KAAK,GAC1B,MAAM,IAAI,aACR,mBACA,GAAG,MAAK,GAAI,MAAK,4EACc,MAAK,GACtC;AAEJ;AAGO,SAAS,cACd,OACA,OACA,WACA,OACM;CACN,MAAM,QAAQ,SAAS,KAAK,KAAK;CAYjC,IAAI,EAVF,UAAU,eACH;EACL,MAAM,CAAC,MAAM,OAAO,OAAO,MAAM,MAAM,CAAC,CAAA,CAAE,IAAI,MAAM;EACpD,MAAM,OAAO,IAAI,KAAK,KAAK,IAAI,MAAM,QAAQ,GAAG,GAAG,CAAC;EACpD,OACE,KAAK,eAAe,MAAM,QAC1B,KAAK,YAAY,MAAM,QAAQ,KAC/B,KAAK,WAAW,MAAM;CAE1B,EAAA,CAAG,IAEH,MAAM,IAAI,aACR,mBACA,GAAG,MAAK,GAAI,MAAK,IAAK,U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