@happyvertical/smrt-expenses 0.56.0 → 0.56.1
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/AGENTS.md +35 -4
- package/README.md +18 -4
- package/dist/actions/expense-actions.d.ts +77 -0
- package/dist/actions/expense-actions.d.ts.map +1 -0
- package/dist/actions/principal.d.ts +54 -0
- package/dist/actions/principal.d.ts.map +1 -0
- package/dist/chunks/{Expense-i8NeN2D3.js → Expense-7afLcUTn.js} +10 -5
- package/dist/chunks/Expense-7afLcUTn.js.map +1 -0
- package/dist/chunks/ExpenseReceiptCollection-y1SlmnBS.js +304 -0
- package/dist/chunks/ExpenseReceiptCollection-y1SlmnBS.js.map +1 -0
- package/dist/chunks/expense-actions-Ce5CBaBE.js +132 -0
- package/dist/chunks/expense-actions-Ce5CBaBE.js.map +1 -0
- package/dist/chunks/principal-_1CdcvvW.js +107 -0
- package/dist/chunks/principal-_1CdcvvW.js.map +1 -0
- package/dist/collections/ExpenseCollection.d.ts +55 -3
- package/dist/collections/ExpenseCollection.d.ts.map +1 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +178 -310
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +269 -7
- package/dist/models/Expense.d.ts +7 -3
- package/dist/models/Expense.d.ts.map +1 -1
- package/dist/recipes.d.ts +118 -0
- package/dist/recipes.d.ts.map +1 -0
- package/dist/smrt-knowledge.json +275 -8
- package/package.json +9 -8
- package/dist/chunks/Expense-i8NeN2D3.js.map +0 -1
package/AGENTS.md
CHANGED
|
@@ -18,6 +18,16 @@ review, reimbursement recording, and smrt-commerce commitment drawdown (#3289).
|
|
|
18
18
|
`filename`, `mimeType`, `byteCount`, `contentSha256`. Collection extends
|
|
19
19
|
`SmrtJunction` (left expense, right asset, ordered by `created_at`).
|
|
20
20
|
|
|
21
|
+
## Recipe
|
|
22
|
+
|
|
23
|
+
`src/recipes.ts` declares one `SmrtRecipe`, `expenses.tracking` (label
|
|
24
|
+
"Expenses", section `accounting`, shared with `ledgers.bookkeeping`), emitted
|
|
25
|
+
into the built `manifest.json` and `smrt-knowledge.json` `recipes`. It brings
|
|
26
|
+
`Expense` with `ExpenseReceipt` as a child model, hides the cost-object type,
|
|
27
|
+
commitment and reviewer plumbing, and leaves the read-only review fields as
|
|
28
|
+
they are (review is method-only; see below). Help lives in
|
|
29
|
+
`src/tracking.recipe.md` (#3591). See [core recipes](../core/agents/recipes.md).
|
|
30
|
+
|
|
21
31
|
## Invariants
|
|
22
32
|
|
|
23
33
|
- **Review is method-only.** `review()`, `reject()`, `markDuplicate()`,
|
|
@@ -89,10 +99,24 @@ review, reimbursement recording, and smrt-commerce commitment drawdown (#3289).
|
|
|
89
99
|
Consumers make it required with a qualified
|
|
90
100
|
`registerTenantScopedClass(…, { mode: 'required' })`.
|
|
91
101
|
- **Closed generated surface.** Models AND collections declare
|
|
92
|
-
`
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
102
|
+
`mcp: { include: [] }`, `cli: false` and no generated CRUD or reads
|
|
103
|
+
(generated reads check no read permission, and cost visibility is
|
|
104
|
+
permission-gated). Collection classes are registered too: an undecorated
|
|
105
|
+
collection publishes its CRUD and public methods as MCP tools. Core has no
|
|
106
|
+
consumer-side switch to reopen a package model's surface.
|
|
107
|
+
- **Generated write actions (#4001).** `ExpenseCollection` hosts the only
|
|
108
|
+
generated writes, on REST: `record`, `attachReceipt`, `recordReview`
|
|
109
|
+
(`decision: 'approve' | 'reject'`, reject needs `reason`) and
|
|
110
|
+
`recordReimbursement`. `Expense` and `ExpenseCollection` both list them in
|
|
111
|
+
`api.include` (runtime REST gates on the item, SvelteKit on the collection).
|
|
112
|
+
Their names differ from `Expense.review()` / `markReimbursed()` on purpose:
|
|
113
|
+
allowlisting a collection action must never open an instance method that
|
|
114
|
+
takes the actor from its input. `src/actions/` delegates to the guarded
|
|
115
|
+
model flow; identity comes from the tenancy/session ALS, never the body;
|
|
116
|
+
each authorizes `expenses.<action>` via `assertOperationPermission` (system
|
|
117
|
+
context never bypasses; review and reimbursement refuse super-admin bypass).
|
|
118
|
+
Acting on someone else's expense needs `recordReview`. There is no submit
|
|
119
|
+
state: a recorded expense is `unreviewed`, i.e. awaiting review.
|
|
96
120
|
- **Cost object is not dereferenced on save.** `getCostObject()` resolves it
|
|
97
121
|
through the registry and returns `null` for a foreign-tenant row. One cost
|
|
98
122
|
object per expense (columns, not a `SmrtPolymorphicAssociation` join) so a
|
|
@@ -113,6 +137,13 @@ source in id order before either refund check, while SQLite serializes writes.
|
|
|
113
137
|
The inbound projected lookup uses the existing `refund_of_id` index and an
|
|
114
138
|
explicit owner filter. Keep caller transaction affinity and per-row revision
|
|
115
139
|
checks; neither an unlocked lookup nor revision CAS alone protects this pair.
|
|
140
|
+
|
|
141
|
+
`ExpenseCollection.listReviewedTaxFacts({ tenantId, from, to, currency? })`
|
|
142
|
+
is the reporting input for supplier facts: it returns only that tenant's reviewed,
|
|
143
|
+
non-duplicate expenses in the inclusive calendar-date range. A null
|
|
144
|
+
`financialBreakdown` remains an unknown legacy fact, never zero tax.
|
|
145
|
+
Each fact carries `expenseId` as the commerce reporting identity; `id` remains
|
|
146
|
+
the compatible owner alias.
|
|
116
147
|
All three fields participate in the reviewed-money freeze. See the README and
|
|
117
148
|
[financial facts test matrix](agents/financial-facts-test-matrix.md).
|
|
118
149
|
|
package/README.md
CHANGED
|
@@ -126,10 +126,24 @@ it is payroll's or payables' job (#3292).
|
|
|
126
126
|
|
|
127
127
|
## Consumer controls
|
|
128
128
|
|
|
129
|
-
- **Closed generated surface.**
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
129
|
+
- **Closed generated surface.** No generated CRUD, read, MCP or CLI
|
|
130
|
+
operation reaches cost data (generated reads check no read permission). List
|
|
131
|
+
expenses through your own permission-checked routes.
|
|
132
|
+
- **Generated write actions (#4001).** `ExpenseCollection` publishes four
|
|
133
|
+
service-backed REST actions, each guarded inside the action by its
|
|
134
|
+
`expenses.<action>` permission, with the tenant and acting profile taken
|
|
135
|
+
from the session:
|
|
136
|
+
|
|
137
|
+
| Route | Body |
|
|
138
|
+
|---|---|
|
|
139
|
+
| `POST /expenses/record` | expense fields (`amount` minor units, `currency`, `incurredOn`, cost object, payer, …) |
|
|
140
|
+
| `POST /expenses/attachReceipt` | `{ expenseId, assetId, contentSha256, filename?, mimeType?, byteCount? }` |
|
|
141
|
+
| `POST /expenses/recordReview` | `{ expenseId, decision: 'approve' \| 'reject', note?, reason? }` |
|
|
142
|
+
| `POST /expenses/recordReimbursement` | `{ expenseId, reference? }` |
|
|
143
|
+
|
|
144
|
+
`recordReview` and `recordReimbursement` refuse super-admin bypass. Acting
|
|
145
|
+
on another person's expense needs `expenses.recordReview`. A recorded
|
|
146
|
+
expense is `unreviewed` (awaiting review); there is no separate submit.
|
|
133
147
|
- **Required tenancy.** Tenancy is optional by default, like smrt-commerce.
|
|
134
148
|
To require a tenant context for every read and write:
|
|
135
149
|
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { ExpenseCollection } from '../collections/ExpenseCollection.js';
|
|
2
|
+
import type { Expense } from '../models/Expense.js';
|
|
3
|
+
import type { ExpenseReceipt } from '../models/ExpenseReceipt.js';
|
|
4
|
+
import { type ExpenseFinancialBreakdown, type ExpensePayer } from '../types.js';
|
|
5
|
+
/** Body of the `record` action. Tenant and recorder come from the session. */
|
|
6
|
+
export interface RecordExpenseActionInput {
|
|
7
|
+
costObjectType?: string;
|
|
8
|
+
costObjectId?: string;
|
|
9
|
+
category?: string;
|
|
10
|
+
description?: string;
|
|
11
|
+
/** Integer minor units of `currency`. */
|
|
12
|
+
amount: number;
|
|
13
|
+
currency: string;
|
|
14
|
+
/** `YYYY-MM-DD`. */
|
|
15
|
+
incurredOn: string;
|
|
16
|
+
paidBy?: ExpensePayer;
|
|
17
|
+
/** Defaults to the signed-in person when `paidBy` is `person`. */
|
|
18
|
+
paidByProfileId?: string | null;
|
|
19
|
+
paidByName?: string | null;
|
|
20
|
+
vendorId?: string | null;
|
|
21
|
+
commitmentId?: string | null;
|
|
22
|
+
commitmentLineId?: string | null;
|
|
23
|
+
refundOfId?: string | null;
|
|
24
|
+
reimbursable?: boolean;
|
|
25
|
+
financialBreakdown?: ExpenseFinancialBreakdown | null;
|
|
26
|
+
}
|
|
27
|
+
/** Body of the `attachReceipt` action. */
|
|
28
|
+
export interface AttachExpenseReceiptActionInput {
|
|
29
|
+
expenseId: string;
|
|
30
|
+
assetId: string;
|
|
31
|
+
contentSha256: string;
|
|
32
|
+
filename?: string;
|
|
33
|
+
mimeType?: string;
|
|
34
|
+
byteCount?: number;
|
|
35
|
+
}
|
|
36
|
+
/** Body of the `recordReview` action. */
|
|
37
|
+
export interface ReviewExpenseActionInput {
|
|
38
|
+
expenseId: string;
|
|
39
|
+
/** `approve` accepts the cost; `reject` refuses it and needs a `reason`. */
|
|
40
|
+
decision: 'approve' | 'reject';
|
|
41
|
+
note?: string;
|
|
42
|
+
reason?: string;
|
|
43
|
+
}
|
|
44
|
+
/** Body of the `recordReimbursement` action. */
|
|
45
|
+
export interface MarkExpenseReimbursedActionInput {
|
|
46
|
+
expenseId: string;
|
|
47
|
+
/** Payroll line, payables reference, or transfer id of the payback. */
|
|
48
|
+
reference?: string;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* `record`: a new `unreviewed` expense, recorded by the signed-in person in
|
|
52
|
+
* their tenant. Review, reimbursement and duplicate fields are never taken
|
|
53
|
+
* from the body. Paying on someone else's behalf needs `expenses.recordReview`.
|
|
54
|
+
*/
|
|
55
|
+
export declare function recordExpenseAction(expenses: ExpenseCollection, input: unknown): Promise<Expense>;
|
|
56
|
+
/**
|
|
57
|
+
* `attachReceipt`: link a stored asset to an expense as its receipt through
|
|
58
|
+
* `ExpenseReceiptCollection.attachReceipt()`. The uploader is the signed-in
|
|
59
|
+
* person, who must have recorded or paid the expense unless they hold
|
|
60
|
+
* `expenses.recordReview`.
|
|
61
|
+
*/
|
|
62
|
+
export declare function attachExpenseReceiptAction(expenses: ExpenseCollection, input: unknown): Promise<ExpenseReceipt>;
|
|
63
|
+
/**
|
|
64
|
+
* `recordReview`: accept (`Expense.review()`) or refuse with a reason
|
|
65
|
+
* (`Expense.reject()`), attributed to the signed-in reviewer. Money: needs an
|
|
66
|
+
* explicit `expenses.recordReview` grant, super-admin bypass does not apply.
|
|
67
|
+
* Named apart from `Expense.review()` so allowlisting the collection action
|
|
68
|
+
* never opens the instance method, which takes the reviewer from its input.
|
|
69
|
+
*/
|
|
70
|
+
export declare function reviewExpenseAction(expenses: ExpenseCollection, input: unknown): Promise<Expense>;
|
|
71
|
+
/**
|
|
72
|
+
* `recordReimbursement`: record that the person who paid has been paid back
|
|
73
|
+
* (`Expense.markReimbursed()`); never changes the review state. Money: needs
|
|
74
|
+
* an explicit `expenses.recordReimbursement` grant.
|
|
75
|
+
*/
|
|
76
|
+
export declare function markExpenseReimbursedAction(expenses: ExpenseCollection, input: unknown): Promise<Expense>;
|
|
77
|
+
//# sourceMappingURL=expense-actions.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"expense-actions.d.ts","sourceRoot":"","sources":["../../src/actions/expense-actions.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAE7E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAClE,OAAO,EAGL,KAAK,yBAAyB,EAC9B,KAAK,YAAY,EAClB,MAAM,aAAa,CAAC;AASrB,8EAA8E;AAC9E,MAAM,WAAW,wBAAwB;IACvC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,y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b,OAAO,CAAC,OAAO,CAAC,CAiElB;AAED;;;;;GAKG;AACH,wBAAsB,0BAA0B,CAC9C,QAAQ,EAAE,iBAAiB,EAC3B,KAAK,EAAE,OAAO,GACb,OAAO,CAAC,cAAc,CAAC,CAkDzB;AAED;;;;;;GAMG;AACH,wBAAsB,mBAAmB,CACvC,QAAQ,EAAE,iBAAiB,EAC3B,KAAK,EAAE,OAAO,GACb,OAAO,CAAC,OAAO,CAAC,CA8BlB;AAED;;;;GAIG;AACH,wBAAsB,2BAA2B,CAC/C,QAAQ,EAAE,iBAAiB,EAC3B,KAAK,EAAE,OAAO,GACb,OAAO,CAAC,OAAO,CAAC,CAelB"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The acting principal for the generated service-backed expense actions
|
|
3
|
+
* (#4001).
|
|
4
|
+
*
|
|
5
|
+
* Identity always comes from the ambient request context, never from the
|
|
6
|
+
* request body: the tenancy ALS (`withTenant`, the SvelteKit/Express
|
|
7
|
+
* adapters) first, then the authenticated smrt-users session-permission ALS
|
|
8
|
+
* (`createSessionHandler()` without `enterTenantContext`). This is the
|
|
9
|
+
* smrt-fields / smrt-preferences precedent. Authorization goes through
|
|
10
|
+
* smrt-users' `assertOperationPermission()` against the principal's published
|
|
11
|
+
* permission snapshot, so ceilings, super-admin and catalog presence behave
|
|
12
|
+
* exactly as they do for every other guarded operation.
|
|
13
|
+
*/
|
|
14
|
+
import type { SmrtClassOptions } from '@happyvertical/smrt-core';
|
|
15
|
+
import { type OperationPermissionCollectionInput } from '@happyvertical/smrt-users';
|
|
16
|
+
/** A refused action with a 4xx status the generated transports serialize. */
|
|
17
|
+
export declare class ExpenseActionError extends Error {
|
|
18
|
+
readonly status: number;
|
|
19
|
+
readonly code: string;
|
|
20
|
+
readonly publicMessage: string;
|
|
21
|
+
constructor(status: number, code: string, message: string);
|
|
22
|
+
}
|
|
23
|
+
/** Who is acting, resolved from the ambient context. */
|
|
24
|
+
export interface ExpenseActionPrincipal {
|
|
25
|
+
tenantId: string;
|
|
26
|
+
userId: string;
|
|
27
|
+
permissions: ReadonlySet<string>;
|
|
28
|
+
/** smrt-profiles Profile linked to the user; stamped into audit fields. */
|
|
29
|
+
profileId: string;
|
|
30
|
+
/** True when the tenancy ALS already carries this principal. */
|
|
31
|
+
fromTenancy: boolean;
|
|
32
|
+
}
|
|
33
|
+
/** True when the ambient principal holds `<collection>.<action>`. */
|
|
34
|
+
export declare function principalHolds(collection: OperationPermissionCollectionInput, action: string, options: SmrtClassOptions): Promise<boolean>;
|
|
35
|
+
/**
|
|
36
|
+
* Authorize `<collection>.<action>` for the ambient principal and resolve the
|
|
37
|
+
* profile it acts as. Fails closed (403) without an authenticated,
|
|
38
|
+
* tenant-bound principal, without the permission, or without a linked
|
|
39
|
+
* profile — an action always records who took it.
|
|
40
|
+
*
|
|
41
|
+
* System context never bypasses: trusted server code without a person calls
|
|
42
|
+
* the `Expense` methods directly. `allowSuperAdminBypass: false` is for
|
|
43
|
+
* money and separation-of-duties operations that need an explicit grant.
|
|
44
|
+
*/
|
|
45
|
+
export declare function authorizeExpenseAction(collection: OperationPermissionCollectionInput, action: string, options: SmrtClassOptions, guard: {
|
|
46
|
+
allowSuperAdminBypass: boolean;
|
|
47
|
+
}): Promise<ExpenseActionPrincipal>;
|
|
48
|
+
/**
|
|
49
|
+
* Run `fn` with the tenancy ALS carrying `principal`, so the tenancy
|
|
50
|
+
* interceptor scopes every read and write. A session-only principal is
|
|
51
|
+
* entered with the same tenant, user and permissions; nothing is widened.
|
|
52
|
+
*/
|
|
53
|
+
export declare function withActionPrincipal<T>(principal: ExpenseActionPrincipal, fn: () => Promise<T>): Promise<T>;
|
|
54
|
+
//# sourceMappingURL=principal.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"principal.d.ts","sourceRoot":"","sources":["../../src/actions/principal.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,KAAK,EAAE,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ackageRef, field, foreignKey, isPostgresDatabase, isUniqueViolationError, smrt } from "@happyvertical/smrt-core";
|
|
3
|
-
import { ContractLineItemCollection, PurchaseContractCollection, VendorCollection } from "@happyvertical/smrt-commerce";
|
|
4
3
|
import { TenantScoped, getTenantId, tenantId } from "@happyvertical/smrt-tenancy";
|
|
4
|
+
import { ContractLineItemCollection, PurchaseContractCollection, VendorCollection } from "@happyvertical/smrt-commerce";
|
|
5
5
|
import { createHash } from "node:crypto";
|
|
6
6
|
//#region src/validation.ts
|
|
7
7
|
var CATEGORY_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
@@ -207,7 +207,6 @@ var Expense = class extends SmrtObject {
|
|
|
207
207
|
paidByName = null;
|
|
208
208
|
refundOfId = null;
|
|
209
209
|
incurredOn = "";
|
|
210
|
-
/** When the expense was recorded; set on first save when empty. */
|
|
211
210
|
recordedAt = null;
|
|
212
211
|
recordedByProfileId = null;
|
|
213
212
|
paidBy = "company";
|
|
@@ -221,7 +220,6 @@ var Expense = class extends SmrtObject {
|
|
|
221
220
|
reviewNote = "";
|
|
222
221
|
duplicateOfId = null;
|
|
223
222
|
reimbursable = false;
|
|
224
|
-
/** When the person was paid back; set by {@link Expense.markReimbursed}. */
|
|
225
223
|
reimbursedAt = null;
|
|
226
224
|
reimbursementReference = "";
|
|
227
225
|
constructor(options = {}) {
|
|
@@ -604,6 +602,7 @@ __decorateClass([field({ type: "text" })], Expense.prototype, "financialBreakdow
|
|
|
604
602
|
__decorateClass([field({ type: "text" })], Expense.prototype, "paidByName", 2);
|
|
605
603
|
__decorateClass([foreignKey("Expense", { onDelete: "RESTRICT" })], Expense.prototype, "refundOfId", 2);
|
|
606
604
|
__decorateClass([field({ type: "text" })], Expense.prototype, "incurredOn", 2);
|
|
605
|
+
__decorateClass([field({ type: "datetime" })], Expense.prototype, "recordedAt", 2);
|
|
607
606
|
__decorateClass([crossPackageRef(PROFILE)], Expense.prototype, "recordedByProfileId", 2);
|
|
608
607
|
__decorateClass([field({ type: "text" })], Expense.prototype, "paidBy", 2);
|
|
609
608
|
__decorateClass([crossPackageRef(PROFILE)], Expense.prototype, "paidByProfileId", 2);
|
|
@@ -628,10 +627,16 @@ __decorateClass([foreignKey("Expense", {
|
|
|
628
627
|
onDelete: "SET NULL"
|
|
629
628
|
})], Expense.prototype, "duplicateOfId", 2);
|
|
630
629
|
__decorateClass([field({ type: "boolean" })], Expense.prototype, "reimbursable", 2);
|
|
630
|
+
__decorateClass([field({ type: "datetime" })], Expense.prototype, "reimbursedAt", 2);
|
|
631
631
|
__decorateClass([field({ type: "text" })], Expense.prototype, "reimbursementReference", 2);
|
|
632
632
|
Expense = __decorateClass([TenantScoped({ mode: "optional" }), smrt({
|
|
633
633
|
tableName: "expenses",
|
|
634
|
-
api: { include: [
|
|
634
|
+
api: { include: [
|
|
635
|
+
"record",
|
|
636
|
+
"attachReceipt",
|
|
637
|
+
"recordReview",
|
|
638
|
+
"recordReimbursement"
|
|
639
|
+
] },
|
|
635
640
|
mcp: { include: [] },
|
|
636
641
|
cli: false,
|
|
637
642
|
indexes: [
|
|
@@ -673,4 +678,4 @@ function sameTenant(a, b) {
|
|
|
673
678
|
//#endregion
|
|
674
679
|
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 };
|
|
675
680
|
|
|
676
|
-
//# sourceMappingURL=Expense-
|
|
681
|
+
//# sourceMappingURL=Expense-7afLcUTn.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Expense-7afLcUTn.js","names":[],"sources":["../../src/validation.ts","../../src/financial-facts.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","/** Exact validation of optional supplier facts. No tax policy is inferred. */\nimport {\n type ExpenseCostBasis,\n ExpenseError,\n type ExpenseFinancialBreakdown,\n} from './types.js';\nimport { assertIsoCurrency } from './validation.js';\n\nfunction invalid(message: string): never {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n `Expense financial breakdown: ${message}`,\n );\n}\n\nfunction record(value: unknown, keys: string[]): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return invalid('expected an object.');\n }\n const object = value as Record<string, unknown>;\n if (\n Object.keys(object).length !== keys.length ||\n keys.some((key) => !Object.hasOwn(object, key))\n ) {\n return invalid('missing or unknown fields.');\n }\n return object;\n}\n\nfunction minor(value: unknown): bigint {\n if (typeof value !== 'number' || !Number.isSafeInteger(value)) {\n return invalid('amounts must be safe integer minor units.');\n }\n return BigInt(value);\n}\n\nfunction safe(value: bigint): number {\n const result = Number(value);\n if (!Number.isSafeInteger(result))\n return invalid('unsafe calculated amount.');\n return result;\n}\n\n/** Validate facts and derive an exact signed basis, without rounding or defaults. */\nexport function expenseCostBasis(\n value: unknown,\n amount: number,\n currency: string,\n): ExpenseCostBasis {\n const facts = record(value, ['currency', 'subtotal', 'taxes', 'total']);\n if (typeof facts.currency !== 'string' || facts.currency !== currency) {\n return invalid('currency must match the expense.');\n }\n assertIsoCurrency('Expense', '<financial-breakdown>', facts.currency);\n const total = minor(facts.total);\n const subtotal = minor(facts.subtotal);\n if (total !== minor(amount))\n return invalid('total must match the expense amount.');\n const consistent = (part: bigint) =>\n part === 0n || (total > 0n ? part > 0n : total < 0n && part < 0n);\n if (!consistent(subtotal)) return invalid('subtotal sign must match total.');\n if (!Array.isArray(facts.taxes))\n return invalid('taxes must be an explicit array.');\n let tax = 0n;\n let recoverable = 0n;\n const codes = new Set<string>();\n for (const item of facts.taxes) {\n const component = record(item, ['code', 'amount', 'recoverableAmount']);\n if (\n typeof component.code !== 'string' ||\n !/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(component.code) ||\n component.code.length > 64 ||\n codes.has(component.code)\n ) {\n return invalid(\n 'tax codes must be unique lower-case kebab-case identifiers.',\n );\n }\n codes.add(component.code);\n const charged = minor(component.amount);\n const recovered = minor(component.recoverableAmount);\n const chargedMagnitude = charged < 0n ? -charged : charged;\n const recoveredMagnitude = recovered < 0n ? -recovered : recovered;\n if (\n !consistent(charged) ||\n !consistent(recovered) ||\n recoveredMagnitude > chargedMagnitude\n ) {\n return invalid(\n 'tax and recovery must share the total sign, with recovery bounded by tax.',\n );\n }\n tax += charged;\n recoverable += recovered;\n }\n if (subtotal + tax !== total)\n return invalid('subtotal plus taxes must equal total.');\n return {\n currency,\n subtotal: safe(subtotal),\n taxTotal: safe(tax),\n recoverableTax: safe(recoverable),\n nonRecoverableTax: safe(tax - recoverable),\n total: safe(total),\n costBasis: safe(total - recoverable),\n };\n}\n\n/** Decode stored facts, failing closed for corrupt or unknown persisted values. */\nexport function parseExpenseFinancialBreakdown(\n stored: string | null,\n amount: number,\n currency: string,\n): ExpenseFinancialBreakdown | null {\n if (stored === '' || stored === null || stored === undefined) return null;\n if (typeof stored !== 'string') return invalid('storage must be JSON text.');\n let parsed: unknown;\n try {\n parsed = JSON.parse(stored);\n } catch {\n return invalid('invalid JSON.');\n }\n expenseCostBasis(parsed, amount, currency);\n return parsed as ExpenseFinancialBreakdown;\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 ContractLineItemCollection,\n PurchaseContractCollection,\n VendorCollection,\n} from '@happyvertical/smrt-commerce';\nimport {\n crossPackageRef,\n field,\n foreignKey,\n isPostgresDatabase,\n isUniqueViolationError,\n ObjectRegistry,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport {\n expenseCostBasis,\n parseExpenseFinancialBreakdown,\n} from '../financial-facts.js';\nimport {\n type ExpenseCostBasis,\n ExpenseError,\n type ExpenseFinancialBreakdown,\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 ['financialBreakdown', 'financial_breakdown'],\n ['paidByName', 'paid_by_name'],\n ['refundOfId', 'refund_of_id'],\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 CRUD surface is closed: cost visibility is permission-gated\n * by every consumer, and generated reads check no read permission, so hosts\n * list expenses through their own routes. The only generated writes are the\n * service-backed actions on {@link ExpenseCollection} (#4001); the runtime\n * REST transport gates a collection-hosted action on this item allowlist.\n * Their names differ from this class's own methods, so allowlisting them never\n * opens `review()` or `markReimbursed()`, which take the actor as input.\n */\n@TenantScoped({ mode: 'optional' })\n@smrt({\n tableName: 'expenses',\n api: {\n include: ['record', 'attachReceipt', 'recordReview', 'recordReimbursement'],\n },\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 { static __smrtPackage__ = \"@happyvertical/smrt-expenses\";\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 /** Integer minor units; negative only for a refund linked by refundOfId. */\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 /** Optional supplier facts as guarded JSON text; null or empty means unknown. */\n @field({ type: 'text' })\n financialBreakdown: string | null = null;\n\n /** Name of the third party who paid; no employee reimbursement is implied. */\n @field({ type: 'text' })\n paidByName: string | null = null;\n\n /** Positive source expense reversed by this negative refund; no settlement. */\n @foreignKey('Expense', { onDelete: 'RESTRICT' })\n refundOfId: string | null = null;\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 @field({ type: 'datetime' })\n recordedAt: Date | null = null;\n\n /** Profile that recorded the expense. */\n @crossPackageRef(PROFILE)\n recordedByProfileId: string | null = null;\n\n /** Company, named person (profile), or named third party (paidByName). */\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 purchase commitment this actual draws down (normally a\n * `PurchaseOrder`). Must be in the same currency and tenant.\n */\n @crossPackageRef('@happyvertical/smrt-commerce:PurchaseContract', {\n validateSubtype: true,\n })\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 @field({ type: 'datetime' })\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.financialBreakdown !== undefined)\n this.financialBreakdown = options.financialBreakdown;\n if (options.paidByName !== undefined) this.paidByName = options.paidByName;\n if (options.refundOfId !== undefined) this.refundOfId = options.refundOfId;\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 /** Read validated supplier facts, or null when none were recorded. */\n getFinancialBreakdown(): ExpenseFinancialBreakdown | null {\n return parseExpenseFinancialBreakdown(\n this.financialBreakdown,\n this.amount,\n this.currency,\n );\n }\n\n /** Set complete supplier facts; null explicitly clears facts on an unreviewed row. */\n setFinancialBreakdown(value: ExpenseFinancialBreakdown | null): void {\n if (value === null) {\n this.financialBreakdown = null;\n return;\n }\n expenseCostBasis(value, this.amount, this.currency);\n this.financialBreakdown = JSON.stringify(value);\n }\n\n /** Return exact retained purchase cost; legacy unknown tax facts return null. */\n getCostBasis(): ExpenseCostBasis | null {\n const facts = this.getFinancialBreakdown();\n return facts === null\n ? null\n : expenseCostBasis(facts, this.amount, this.currency);\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 return this.withTransaction(() => this.saveValidated());\n }\n\n /** Keep both directions of refund validation and the write on one executor. */\n private async saveValidated(): Promise<this> {\n await this.lockRefundRows();\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 await this.assertInboundRefunds(persisted);\n await this.assertRefund(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(\n 'Expense',\n label,\n 'amount',\n this.refundOfId && typeof this.amount === 'number'\n ? Math.abs(this.amount)\n : this.amount,\n );\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 this.getFinancialBreakdown();\n if (\n this.paidBy === 'third-party'\n ? typeof this.paidByName !== 'string' || !this.paidByName.trim()\n : this.paidByName !== null && this.paidByName !== ''\n ) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n 'Only a third-party payer requires paidByName.',\n );\n }\n if (\n this.refundOfId !== null &&\n (typeof this.refundOfId !== 'string' || !this.refundOfId.trim())\n ) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n 'refundOfId must name a source expense or be null.',\n );\n }\n if (\n this.paidBy !== 'company' &&\n this.paidBy !== 'person' &&\n this.paidBy !== 'third-party'\n ) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n `Expense ${label}: paidBy must be 'company', 'person' or 'third-party'.`,\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 !== 'person' && 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 PurchaseContractCollection.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 /**\n * Source edits and refund writes contend on the same source row. Acquire\n * rows in deterministic order before either relationship check, and hold\n * them through commit. SQLite's write transaction supplies serialization.\n */\n private async lockRefundRows(): Promise<void> {\n if (!isPostgresDatabase(this.db)) return;\n const ids = [\n ...new Set(\n [this.id, this.refundOfId].filter((id): id is string => Boolean(id)),\n ),\n ].sort();\n if (ids.length === 0) return;\n const table = `\"${this.tableName.replace(/\"/g, '\"\"')}\"`;\n await this.db.query(\n `SELECT id FROM ${table} WHERE id IN (${ids.map(() => '?').join(', ')}) ` +\n 'AND tenant_id IS NOT DISTINCT FROM ? ORDER BY id FOR UPDATE',\n ...ids,\n effectiveTenant(this.tenantId),\n );\n }\n\n /** Refuse source corrections that invalidate any same-owner refund. */\n private async assertInboundRefunds(\n persisted: PersistedRow | null,\n ): Promise<void> {\n if (\n !persisted ||\n (Number(persisted.amount) === this.amount &&\n String(persisted.currency ?? '') === this.currency &&\n asNullableString(persisted.refund_of_id) === this.refundOfId)\n )\n return;\n const { ExpenseCollection } = await import(\n '../collections/ExpenseCollection.js'\n );\n const expenses = await ExpenseCollection.create({ db: this.db });\n const invalidated = await expenses.list({\n where: {\n refundOfId: this.id,\n tenantId: effectiveTenant(this.tenantId),\n ...(this.amount > 0 && !this.refundOfId\n ? { 'currency !=': this.currency }\n : {}),\n },\n select: ['id'],\n limit: 1,\n cache: false,\n });\n if (invalidated.length > 0) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n 'A referenced refund source must remain positive, non-refund, and in the currency of its refunds.',\n );\n }\n }\n\n private async assertRefund(persisted: PersistedRow | null): Promise<void> {\n if (!this.refundOfId) return;\n if (this.refundOfId === this.id || this.amount >= 0) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n 'A refund must be negative and name a different positive source expense.',\n );\n }\n const { ExpenseCollection } = await import(\n '../collections/ExpenseCollection.js'\n );\n const expenses = await ExpenseCollection.create({ db: this.db });\n const source = await expenses.get(\n { id: this.refundOfId },\n { cache: false },\n );\n if (\n !source ||\n !sameTenant(source.tenantId, effectiveTenant(this.tenantId)) ||\n source.currency !== this.currency ||\n source.amount <= 0 ||\n source.refundOfId\n ) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n 'Refund source must be a positive non-refund expense in the same tenant and currency.',\n );\n }\n if (!persisted || persisted.refund_of_id !== this.refundOfId) {\n // A row lock alone cannot refresh an existing REPEATABLE READ snapshot.\n // Advance the source through public CAS so stale source writers abort.\n if (!source.updated_at) {\n throw new ExpenseError(\n 'EXPENSE_INVALID',\n 'Refund source has no revision.',\n );\n }\n await source.claimRevision(source.updated_at);\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,UAAS,oDACT,MAAK,GAC7B;AAEJ;AAOO,SAAS,yBACd,OACA,OACA,OACM;CACN,IAAI,CAAC,gBAAgB,KAAK,KAAK,GAC7B,MAAM,IAAI,aACR,mBACA,GAAG,MAAK,GAAI,MAAK,uGACyC,MAAK,GACjE;AAEJ;AAGO,SAAS,gBAAgB,OAAe,OAAe,OAAe;CAC3E,MAAM,SAAS,OAAO,SAAS,EAAE,CAAA,CAC9B,KAAK,CAAA,CACL,YAAY;C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