@happyvertical/smrt-expenses 0.60.18 → 0.61.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/dist/chunks/{Expense-Deq19w2r.js → Expense-BMVkoxm_.js} +4 -5
- package/dist/chunks/Expense-BMVkoxm_.js.map +1 -0
- package/dist/chunks/{ExpenseReceiptCollection-D4Na93BF.js → ExpenseReceiptCollection-CaVPOnIl.js} +2 -2
- package/dist/chunks/{ExpenseReceiptCollection-D4Na93BF.js.map → ExpenseReceiptCollection-CaVPOnIl.js.map} +1 -1
- package/dist/chunks/{expense-actions-DszuHacx.js → expense-actions-B6A8fu37.js} +2 -2
- package/dist/chunks/{expense-actions-DszuHacx.js.map → expense-actions-B6A8fu37.js.map} +1 -1
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +4 -4
- package/dist/models/Expense.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +9 -9
- package/dist/smrt-knowledge.okf.md +1 -1
- package/package.json +9 -9
- package/dist/chunks/Expense-Deq19w2r.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"expense-actions-DszuHacx.js","names":[],"sources":["../../src/actions/expense-actions.ts"],"sourcesContent":["/**\n * Service-backed write actions for `Expense` and `ExpenseReceipt` (#4001).\n *\n * The generated CRUD surface stays closed: these are the only generated\n * writes, and each delegates to the existing domain flow — `Expense.save()`\n * with its review lock and refund/commitment/vendor guards, the method-only\n * `review()` / `reject()` / `markReimbursed()`, and\n * `ExpenseReceiptCollection.attachReceipt()` with its hash deduplication.\n * The thin `ExpenseCollection` methods call in here.\n */\nimport type { SmrtClassOptions } from '@happyvertical/smrt-core';\nimport type { ExpenseCollection } from '../collections/ExpenseCollection.js';\nimport { ExpenseReceiptCollection } from '../collections/ExpenseReceiptCollection.js';\nimport type { Expense } from '../models/Expense.js';\nimport type { ExpenseReceipt } from '../models/ExpenseReceipt.js';\nimport {\n ExpenseError,\n type ExpenseErrorCode,\n type ExpenseFinancialBreakdown,\n type ExpensePayer,\n} from '../types.js';\nimport {\n authorizeExpenseAction,\n ExpenseActionError,\n type ExpenseActionPrincipal,\n principalHolds,\n withActionPrincipal,\n} from './principal.js';\n\n/** Body of the `record` action. Tenant and recorder come from the session. */\nexport interface RecordExpenseActionInput {\n costObjectType?: string;\n costObjectId?: string;\n category?: string;\n description?: string;\n /** Integer minor units of `currency`. */\n amount: number;\n currency: string;\n /** `YYYY-MM-DD`. */\n incurredOn: string;\n paidBy?: ExpensePayer;\n /** Defaults to the signed-in person when `paidBy` is `person`. */\n paidByProfileId?: string | null;\n paidByName?: string | null;\n vendorId?: string | null;\n commitmentId?: string | null;\n commitmentLineId?: string | null;\n refundOfId?: string | null;\n reimbursable?: boolean;\n financialBreakdown?: ExpenseFinancialBreakdown | null;\n}\n\n/** Body of the `attachReceipt` action. */\nexport interface AttachExpenseReceiptActionInput {\n expenseId: string;\n assetId: string;\n contentSha256: string;\n filename?: string;\n mimeType?: string;\n byteCount?: number;\n}\n\n/** Body of the `recordReview` action. */\nexport interface ReviewExpenseActionInput {\n expenseId: string;\n /** `approve` accepts the cost; `reject` refuses it and needs a `reason`. */\n decision: 'approve' | 'reject';\n note?: string;\n reason?: string;\n}\n\n/** Body of the `recordReimbursement` action. */\nexport interface MarkExpenseReimbursedActionInput {\n expenseId: string;\n /** Optional expected full remaining reimbursement in minor units. */\n amount?: number;\n /** Payroll line, payables reference, or transfer id of the payback. */\n reference?: string;\n}\n\n/** `record` fields copied onto the new expense; everything else is ignored. */\nconst RECORD_FIELDS = [\n 'costObjectType',\n 'costObjectId',\n 'category',\n 'description',\n 'amount',\n 'currency',\n 'incurredOn',\n 'paidByName',\n 'vendorId',\n 'commitmentId',\n 'commitmentLineId',\n 'refundOfId',\n 'reimbursable',\n] as const;\n\nconst CONFLICT_CODES = new Set<ExpenseErrorCode>([\n 'EXPENSE_REVIEW_TRANSITION',\n 'EXPENSE_REVIEW_FIELDS_LOCKED',\n 'EXPENSE_IDENTITY_CONFLICT',\n 'EXPENSE_RECEIPT_DUPLICATE',\n]);\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new ExpenseActionError(\n 400,\n 'invalid_request',\n 'The action body must be a JSON object.',\n );\n }\n return value as Record<string, unknown>;\n}\n\nfunction optionalString(\n body: Record<string, unknown>,\n key: string,\n): string | undefined {\n const value = body[key];\n if (value === undefined || value === null) return undefined;\n if (typeof value !== 'string') {\n throw new ExpenseActionError(\n 400,\n 'invalid_request',\n `${key} must be a string.`,\n );\n }\n return value;\n}\n\nfunction requiredString(body: Record<string, unknown>, key: string): string {\n const value = optionalString(body, key)?.trim();\n if (!value) {\n throw new ExpenseActionError(400, 'invalid_request', `${key} is required.`);\n }\n return value;\n}\n\n/** Domain refusals become 4xx with their stable code; others pass through. */\nasync function domainCall<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n if (error instanceof ExpenseError) {\n throw new ExpenseActionError(\n CONFLICT_CODES.has(error.code) ? 409 : 400,\n error.code,\n error.message,\n );\n }\n throw error;\n }\n}\n\nfunction itemClass(expenses: ExpenseCollection) {\n return (expenses.constructor as unknown as { _itemClass: unknown })\n ._itemClass as typeof Expense;\n}\n\nfunction options(expenses: ExpenseCollection): SmrtClassOptions {\n return expenses.options;\n}\n\nasync function loadExpense(\n expenses: ExpenseCollection,\n principal: ExpenseActionPrincipal,\n body: Record<string, unknown>,\n): Promise<Expense> {\n const expenseId = requiredString(body, 'expenseId');\n const expense = await expenses.get({ id: expenseId });\n // Optional tenancy also admits global (NULL-tenant) rows in a tenant\n // context; a write must land on the principal's own tenant only.\n if (!expense || (expense.tenantId ?? null) !== principal.tenantId) {\n throw new ExpenseActionError(\n 404,\n 'not_found',\n `Expense ${expenseId} was not found.`,\n );\n }\n return expense;\n}\n\n/**\n * `record`: a new `unreviewed` expense, recorded by the signed-in person in\n * their tenant. Review, reimbursement and duplicate fields are never taken\n * from the body. Paying on someone else's behalf needs `expenses.recordReview`.\n */\nexport async function recordExpenseAction(\n expenses: ExpenseCollection,\n input: unknown,\n): Promise<Expense> {\n const body = asRecord(input);\n const principal = await authorizeExpenseAction(\n itemClass(expenses),\n 'record',\n options(expenses),\n { allowSuperAdminBypass: true },\n );\n const paidBy = (optionalString(body, 'paidBy') ?? 'company') as ExpensePayer;\n let paidByProfileId: string | null = null;\n if (paidBy === 'person') {\n paidByProfileId =\n optionalString(body, 'paidByProfileId')?.trim() || principal.profileId;\n if (\n paidByProfileId !== principal.profileId &&\n !(await principalHolds(\n itemClass(expenses),\n 'recordReview',\n options(expenses),\n ))\n ) {\n throw new ExpenseActionError(\n 403,\n 'permission_denied',\n \"Recording another person's expense needs the recordReview permission.\",\n );\n }\n }\n const fields: Record<string, unknown> = {};\n for (const key of RECORD_FIELDS) {\n if (body[key] !== undefined) fields[key] = body[key];\n }\n const breakdown = body.financialBreakdown;\n if (\n breakdown !== undefined &&\n breakdown !== null &&\n (typeof breakdown !== 'object' || Array.isArray(breakdown))\n ) {\n throw new ExpenseActionError(\n 400,\n 'invalid_request',\n 'financialBreakdown must be an object or null.',\n );\n }\n return withActionPrincipal(principal, () =>\n // One create: `collection.create()` saves, and `Expense.save()` validates\n // the facts (`validateShape()` parses them) before its first INSERT, so an\n // invalid breakdown never leaves a half-recorded row behind.\n domainCall(() =>\n expenses.create({\n ...fields,\n ...(breakdown !== undefined\n ? {\n financialBreakdown:\n breakdown === null ? null : JSON.stringify(breakdown),\n }\n : {}),\n tenantId: principal.tenantId,\n paidBy,\n paidByProfileId,\n recordedByProfileId: principal.profileId,\n recordedAt: null,\n }),\n ),\n );\n}\n\n/**\n * `attachReceipt`: link a stored asset to an expense as its receipt through\n * `ExpenseReceiptCollection.attachReceipt()`. The uploader is the signed-in\n * person, who must have recorded or paid the expense unless they hold\n * `expenses.recordReview`.\n */\nexport async function attachExpenseReceiptAction(\n expenses: ExpenseCollection,\n input: unknown,\n): Promise<ExpenseReceipt> {\n const body = asRecord(input);\n const principal = await authorizeExpenseAction(\n itemClass(expenses),\n 'attachReceipt',\n options(expenses),\n { allowSuperAdminBypass: true },\n );\n return withActionPrincipal(principal, async () => {\n const expense = await loadExpense(expenses, principal, body);\n if (\n expense.recordedByProfileId !== principal.profileId &&\n expense.paidByProfileId !== principal.profileId &&\n !(await principalHolds(\n itemClass(expenses),\n 'recordReview',\n options(expenses),\n ))\n ) {\n throw new ExpenseActionError(\n 403,\n 'permission_denied',\n \"Attaching a receipt to another person's expense needs the recordReview permission.\",\n );\n }\n const byteCount = body.byteCount;\n if (byteCount !== undefined && typeof byteCount !== 'number') {\n throw new ExpenseActionError(\n 400,\n 'invalid_request',\n 'byteCount must be a number.',\n );\n }\n const receipts = await ExpenseReceiptCollection.create(options(expenses));\n return domainCall(() =>\n receipts.attachReceipt({\n expenseId: expense.id as string,\n assetId: requiredString(body, 'assetId'),\n contentSha256: requiredString(body, 'contentSha256'),\n uploadedByProfileId: principal.profileId,\n ...(optionalString(body, 'filename') !== undefined\n ? { filename: optionalString(body, 'filename') }\n : {}),\n ...(optionalString(body, 'mimeType') !== undefined\n ? { mimeType: optionalString(body, 'mimeType') }\n : {}),\n ...(byteCount !== undefined ? { byteCount: byteCount as number } : {}),\n }),\n );\n });\n}\n\n/**\n * `recordReview`: accept (`Expense.review()`) or refuse with a reason\n * (`Expense.reject()`), attributed to the signed-in reviewer. Money: needs an\n * explicit `expenses.recordReview` grant, super-admin bypass does not apply.\n * Named apart from `Expense.review()` so allowlisting the collection action\n * never opens the instance method, which takes the reviewer from its input.\n */\nexport async function reviewExpenseAction(\n expenses: ExpenseCollection,\n input: unknown,\n): Promise<Expense> {\n const body = asRecord(input);\n const principal = await authorizeExpenseAction(\n itemClass(expenses),\n 'recordReview',\n options(expenses),\n { allowSuperAdminBypass: false },\n );\n const decision = optionalString(body, 'decision');\n if (decision !== 'approve' && decision !== 'reject') {\n throw new ExpenseActionError(\n 400,\n 'invalid_request',\n \"decision must be 'approve' or 'reject'.\",\n );\n }\n return withActionPrincipal(principal, async () => {\n const expense = await loadExpense(expenses, principal, body);\n return domainCall(() =>\n decision === 'approve'\n ? expense.review({\n reviewerProfileId: principal.profileId,\n note: optionalString(body, 'note') ?? '',\n })\n : expense.reject({\n reviewerProfileId: principal.profileId,\n reason: optionalString(body, 'reason') ?? '',\n }),\n );\n });\n}\n\n/**\n * `recordReimbursement`: record that the person who paid has been paid back\n * (`Expense.markReimbursed()`); never changes the review state. Money: needs\n * an explicit `expenses.recordReimbursement` grant.\n */\nexport async function markExpenseReimbursedAction(\n expenses: ExpenseCollection,\n input: unknown,\n): Promise<Expense> {\n const body = asRecord(input);\n const principal = await authorizeExpenseAction(\n itemClass(expenses),\n 'recordReimbursement',\n options(expenses),\n { allowSuperAdminBypass: false },\n );\n return withActionPrincipal(principal, async () => {\n const expense = await loadExpense(expenses, principal, body);\n const reference = optionalString(body, 'reference');\n const amount = body.amount;\n if (\n amount !== undefined &&\n (typeof amount !== 'number' ||\n !Number.isSafeInteger(amount) ||\n amount <= 0)\n ) {\n throw new ExpenseActionError(\n 400,\n 'invalid_request',\n 'amount must be a positive safe integer.',\n );\n }\n return domainCall(() =>\n expense.markReimbursed({\n ...(reference !== undefined ? { reference } : {}),\n ...(amount !== undefined ? { amount: amount as number } : {}),\n }),\n );\n });\n}\n"],"mappings":";;;;AAiFA,IAAM,gBAAgB;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,IAAM,iCAAiB,IAAI,IAAsB;CAC/C;CACA;CACA;CACA;AACF,CAAC;AAED,SAAS,SAAS,OAAyC;CACzD,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAC5D,MAAM,IAAI,mBACR,KACA,mBACA,wCACF;CAEF,OAAO;AACT;AAEA,SAAS,eACP,MACA,KACoB;CACpB,MAAM,QAAQ,KAAK;CACnB,IAAI,UAAU,KAAA,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WAAW,KAAA,MACV,OAAO,WAAW,YACjB,CAAC,OAAO,cAAc,MAAM,KAC5B,UAAU,IAEZ,MAAM,IAAI,mBACR,KACA,mBACA,yCACF;EAEF,OAAO,iBACL,QAAQ,eAAe;GACrB,GAAI,cAAc,KAAA,IAAY,EAAE,UAAU,IAAI,CAAC;GAC/C,GAAI,WAAW,KAAA,IAAY,EAAE,OAAyB,IAAI,CAAC;EAC7D,CAAC,CACH;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"expense-actions-B6A8fu37.js","names":[],"sources":["../../src/actions/expense-actions.ts"],"sourcesContent":["/**\n * Service-backed write actions for `Expense` and `ExpenseReceipt` (#4001).\n *\n * The generated CRUD surface stays closed: these are the only generated\n * writes, and each delegates to the existing domain flow — `Expense.save()`\n * with its review lock and refund/commitment/vendor guards, the method-only\n * `review()` / `reject()` / `markReimbursed()`, and\n * `ExpenseReceiptCollection.attachReceipt()` with its hash deduplication.\n * The thin `ExpenseCollection` methods call in here.\n */\nimport type { SmrtClassOptions } from '@happyvertical/smrt-core';\nimport type { ExpenseCollection } from '../collections/ExpenseCollection.js';\nimport { ExpenseReceiptCollection } from '../collections/ExpenseReceiptCollection.js';\nimport type { Expense } from '../models/Expense.js';\nimport type { ExpenseReceipt } from '../models/ExpenseReceipt.js';\nimport {\n ExpenseError,\n type ExpenseErrorCode,\n type ExpenseFinancialBreakdown,\n type ExpensePayer,\n} from '../types.js';\nimport {\n authorizeExpenseAction,\n ExpenseActionError,\n type ExpenseActionPrincipal,\n principalHolds,\n withActionPrincipal,\n} from './principal.js';\n\n/** Body of the `record` action. Tenant and recorder come from the session. */\nexport interface RecordExpenseActionInput {\n costObjectType?: string;\n costObjectId?: string;\n category?: string;\n description?: string;\n /** Integer minor units of `currency`. */\n amount: number;\n currency: string;\n /** `YYYY-MM-DD`. */\n incurredOn: string;\n paidBy?: ExpensePayer;\n /** Defaults to the signed-in person when `paidBy` is `person`. */\n paidByProfileId?: string | null;\n paidByName?: string | null;\n vendorId?: string | null;\n commitmentId?: string | null;\n commitmentLineId?: string | null;\n refundOfId?: string | null;\n reimbursable?: boolean;\n financialBreakdown?: ExpenseFinancialBreakdown | null;\n}\n\n/** Body of the `attachReceipt` action. */\nexport interface AttachExpenseReceiptActionInput {\n expenseId: string;\n assetId: string;\n contentSha256: string;\n filename?: string;\n mimeType?: string;\n byteCount?: number;\n}\n\n/** Body of the `recordReview` action. */\nexport interface ReviewExpenseActionInput {\n expenseId: string;\n /** `approve` accepts the cost; `reject` refuses it and needs a `reason`. */\n decision: 'approve' | 'reject';\n note?: string;\n reason?: string;\n}\n\n/** Body of the `recordReimbursement` action. */\nexport interface MarkExpenseReimbursedActionInput {\n expenseId: string;\n /** Optional expected full remaining reimbursement in minor units. */\n amount?: number;\n /** Payroll line, payables reference, or transfer id of the payback. */\n reference?: string;\n}\n\n/** `record` fields copied onto the new expense; everything else is ignored. */\nconst RECORD_FIELDS = [\n 'costObjectType',\n 'costObjectId',\n 'category',\n 'description',\n 'amount',\n 'currency',\n 'incurredOn',\n 'paidByName',\n 'vendorId',\n 'commitmentId',\n 'commitmentLineId',\n 'refundOfId',\n 'reimbursable',\n] as const;\n\nconst CONFLICT_CODES = new Set<ExpenseErrorCode>([\n 'EXPENSE_REVIEW_TRANSITION',\n 'EXPENSE_REVIEW_FIELDS_LOCKED',\n 'EXPENSE_IDENTITY_CONFLICT',\n 'EXPENSE_RECEIPT_DUPLICATE',\n]);\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new ExpenseActionError(\n 400,\n 'invalid_request',\n 'The action body must be a JSON object.',\n );\n }\n return value as Record<string, unknown>;\n}\n\nfunction optionalString(\n body: Record<string, unknown>,\n key: string,\n): string | undefined {\n const value = body[key];\n if (value === undefined || value === null) return undefined;\n if (typeof value !== 'string') {\n throw new ExpenseActionError(\n 400,\n 'invalid_request',\n `${key} must be a string.`,\n );\n }\n return value;\n}\n\nfunction requiredString(body: Record<string, unknown>, key: string): string {\n const value = optionalString(body, key)?.trim();\n if (!value) {\n throw new ExpenseActionError(400, 'invalid_request', `${key} is required.`);\n }\n return value;\n}\n\n/** Domain refusals become 4xx with their stable code; others pass through. */\nasync function domainCall<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n if (error instanceof ExpenseError) {\n throw new ExpenseActionError(\n CONFLICT_CODES.has(error.code) ? 409 : 400,\n error.code,\n error.message,\n );\n }\n throw error;\n }\n}\n\nfunction itemClass(expenses: ExpenseCollection) {\n return (expenses.constructor as unknown as { _itemClass: unknown })\n ._itemClass as typeof Expense;\n}\n\nfunction options(expenses: ExpenseCollection): SmrtClassOptions {\n return expenses.options;\n}\n\nasync function loadExpense(\n expenses: ExpenseCollection,\n principal: ExpenseActionPrincipal,\n body: Record<string, unknown>,\n): Promise<Expense> {\n const expenseId = requiredString(body, 'expenseId');\n const expense = await expenses.get({ id: expenseId });\n // Optional tenancy also admits global (NULL-tenant) rows in a tenant\n // context; a write must land on the principal's own tenant only.\n if (!expense || (expense.tenantId ?? null) !== principal.tenantId) {\n throw new ExpenseActionError(\n 404,\n 'not_found',\n `Expense ${expenseId} was not found.`,\n );\n }\n return expense;\n}\n\n/**\n * `record`: a new `unreviewed` expense, recorded by the signed-in person in\n * their tenant. Review, reimbursement and duplicate fields are never taken\n * from the body. Paying on someone else's behalf needs `expenses.recordReview`.\n */\nexport async function recordExpenseAction(\n expenses: ExpenseCollection,\n input: unknown,\n): Promise<Expense> {\n const body = asRecord(input);\n const principal = await authorizeExpenseAction(\n itemClass(expenses),\n 'record',\n options(expenses),\n { allowSuperAdminBypass: true },\n );\n const paidBy = (optionalString(body, 'paidBy') ?? 'company') as ExpensePayer;\n let paidByProfileId: string | null = null;\n if (paidBy === 'person') {\n paidByProfileId =\n optionalString(body, 'paidByProfileId')?.trim() || principal.profileId;\n if (\n paidByProfileId !== principal.profileId &&\n !(await principalHolds(\n itemClass(expenses),\n 'recordReview',\n options(expenses),\n ))\n ) {\n throw new ExpenseActionError(\n 403,\n 'permission_denied',\n \"Recording another person's expense needs the recordReview permission.\",\n );\n }\n }\n const fields: Record<string, unknown> = {};\n for (const key of RECORD_FIELDS) {\n if (body[key] !== undefined) fields[key] = body[key];\n }\n const breakdown = body.financialBreakdown;\n if (\n breakdown !== undefined &&\n breakdown !== null &&\n (typeof breakdown !== 'object' || Array.isArray(breakdown))\n ) {\n throw new ExpenseActionError(\n 400,\n 'invalid_request',\n 'financialBreakdown must be an object or null.',\n );\n }\n return withActionPrincipal(principal, () =>\n // One create: `collection.create()` saves, and `Expense.save()` validates\n // the facts (`validateShape()` parses them) before its first INSERT, so an\n // invalid breakdown never leaves a half-recorded row behind.\n domainCall(() =>\n expenses.create({\n ...fields,\n ...(breakdown !== undefined\n ? {\n financialBreakdown:\n breakdown === null ? null : JSON.stringify(breakdown),\n }\n : {}),\n tenantId: principal.tenantId,\n paidBy,\n paidByProfileId,\n recordedByProfileId: principal.profileId,\n recordedAt: null,\n }),\n ),\n );\n}\n\n/**\n * `attachReceipt`: link a stored asset to an expense as its receipt through\n * `ExpenseReceiptCollection.attachReceipt()`. The uploader is the signed-in\n * person, who must have recorded or paid the expense unless they hold\n * `expenses.recordReview`.\n */\nexport async function attachExpenseReceiptAction(\n expenses: ExpenseCollection,\n input: unknown,\n): Promise<ExpenseReceipt> {\n const body = asRecord(input);\n const principal = await authorizeExpenseAction(\n itemClass(expenses),\n 'attachReceipt',\n options(expenses),\n { allowSuperAdminBypass: true },\n );\n return withActionPrincipal(principal, async () => {\n const expense = await loadExpense(expenses, principal, body);\n if (\n expense.recordedByProfileId !== principal.profileId &&\n expense.paidByProfileId !== principal.profileId &&\n !(await principalHolds(\n itemClass(expenses),\n 'recordReview',\n options(expenses),\n ))\n ) {\n throw new ExpenseActionError(\n 403,\n 'permission_denied',\n \"Attaching a receipt to another person's expense needs the recordReview permission.\",\n );\n }\n const byteCount = body.byteCount;\n if (byteCount !== undefined && typeof byteCount !== 'number') {\n throw new ExpenseActionError(\n 400,\n 'invalid_request',\n 'byteCount must be a number.',\n );\n }\n const receipts = await ExpenseReceiptCollection.create(options(expenses));\n return domainCall(() =>\n receipts.attachReceipt({\n expenseId: expense.id as string,\n assetId: requiredString(body, 'assetId'),\n contentSha256: requiredString(body, 'contentSha256'),\n uploadedByProfileId: principal.profileId,\n ...(optionalString(body, 'filename') !== undefined\n ? { filename: optionalString(body, 'filename') }\n : {}),\n ...(optionalString(body, 'mimeType') !== undefined\n ? { mimeType: optionalString(body, 'mimeType') }\n : {}),\n ...(byteCount !== undefined ? { byteCount: byteCount as number } : {}),\n }),\n );\n });\n}\n\n/**\n * `recordReview`: accept (`Expense.review()`) or refuse with a reason\n * (`Expense.reject()`), attributed to the signed-in reviewer. Money: needs an\n * explicit `expenses.recordReview` grant, super-admin bypass does not apply.\n * Named apart from `Expense.review()` so allowlisting the collection action\n * never opens the instance method, which takes the reviewer from its input.\n */\nexport async function reviewExpenseAction(\n expenses: ExpenseCollection,\n input: unknown,\n): Promise<Expense> {\n const body = asRecord(input);\n const principal = await authorizeExpenseAction(\n itemClass(expenses),\n 'recordReview',\n options(expenses),\n { allowSuperAdminBypass: false },\n );\n const decision = optionalString(body, 'decision');\n if (decision !== 'approve' && decision !== 'reject') {\n throw new ExpenseActionError(\n 400,\n 'invalid_request',\n \"decision must be 'approve' or 'reject'.\",\n );\n }\n return withActionPrincipal(principal, async () => {\n const expense = await loadExpense(expenses, principal, body);\n return domainCall(() =>\n decision === 'approve'\n ? expense.review({\n reviewerProfileId: principal.profileId,\n note: optionalString(body, 'note') ?? '',\n })\n : expense.reject({\n reviewerProfileId: principal.profileId,\n reason: optionalString(body, 'reason') ?? '',\n }),\n );\n });\n}\n\n/**\n * `recordReimbursement`: record that the person who paid has been paid back\n * (`Expense.markReimbursed()`); never changes the review state. Money: needs\n * an explicit `expenses.recordReimbursement` grant.\n */\nexport async function markExpenseReimbursedAction(\n expenses: ExpenseCollection,\n input: unknown,\n): Promise<Expense> {\n const body = asRecord(input);\n const principal = await authorizeExpenseAction(\n itemClass(expenses),\n 'recordReimbursement',\n options(expenses),\n { allowSuperAdminBypass: false },\n );\n return withActionPrincipal(principal, async () => {\n const expense = await loadExpense(expenses, principal, body);\n const reference = optionalString(body, 'reference');\n const amount = body.amount;\n if (\n amount !== undefined &&\n (typeof amount !== 'number' ||\n !Number.isSafeInteger(amount) ||\n amount <= 0)\n ) {\n throw new ExpenseActionError(\n 400,\n 'invalid_request',\n 'amount must be a positive safe integer.',\n );\n }\n return domainCall(() =>\n expense.markReimbursed({\n ...(reference !== undefined ? { reference } : {}),\n ...(amount !== undefined ? { amount: amount as number } : {}),\n }),\n );\n });\n}\n"],"mappings":";;;;AAiFA,IAAM,gBAAgB;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,IAAM,iCAAiB,IAAI,IAAsB;CAC/C;CACA;CACA;CACA;AACF,CAAC;AAED,SAAS,SAAS,OAAyC;CACzD,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAC5D,MAAM,IAAI,mBACR,KACA,mBACA,wCACF;CAEF,OAAO;AACT;AAEA,SAAS,eACP,MACA,KACoB;CACpB,MAAM,QAAQ,KAAK;CACnB,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO,KAAA;CAClD,IAAI,OAAO,UAAU,UACnB,MAAM,IAAI,mBACR,KACA,mBACA,GAAG,IAAG,mBACR;CAEF,OAAO;AACT;AAEA,SAAS,eAAe,MAA+B,KAAqB;CAC1E,MAAM,QAAQ,eAAe,MAAM,GAAG,CAAA,EAAG,KAAK;CAC9C,IAAI,CAAC,OACH,MAAM,IAAI,mBAAmB,KAAK,mBAAmB,GAAG,IAAG,cAAe;CAE5E,OAAO;AACT;AAGA,eAAe,WAAc,IAAkC;CAC7D,IAAI;EACF,OAAO,MAAM,GAAG;CAClB,SAAS,OAAO;EACd,IAAI,iBAAiB,cACnB,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