@zonastery/bursar 2.0.2 → 2.0.3
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/README.md +1 -0
- package/dist/billing/auto-recharge-service.d.ts +1 -1
- package/dist/billing/auto-recharge-service.d.ts.map +1 -1
- package/dist/billing/auto-recharge-service.js +3 -2
- package/dist/billing/auto-recharge-service.js.map +1 -1
- package/dist/billing/billing-store.d.ts +1 -1
- package/dist/billing/billing-store.d.ts.map +1 -1
- package/dist/billing/billing-store.js.map +1 -1
- package/dist/billing/contracts.d.ts +2 -1
- package/dist/billing/contracts.d.ts.map +1 -1
- package/dist/billing/contracts.js.map +1 -1
- package/dist/billing/event-processor.d.ts.map +1 -1
- package/dist/billing/event-processor.js +18 -6
- package/dist/billing/event-processor.js.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.js +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
- package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/event.js +33 -1
- package/dist/billing/postgres/repositories/event.js.map +1 -1
- package/dist/billing/postgres/repositories/offer.d.ts +1 -1
- package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/offer.js +1 -1
- package/dist/billing/postgres/repositories/offer.js.map +1 -1
- package/dist/billing/postgres/repositories/topup.d.ts +1 -1
- package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/topup.js +1 -1
- package/dist/billing/postgres/repositories/topup.js.map +1 -1
- package/dist/billing/postgres/store.d.ts +1 -1
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +16 -6
- package/dist/billing/postgres/store.js.map +1 -1
- package/dist/billing/types/auto-recharge.d.ts +1 -1
- package/dist/billing/types/auto-recharge.d.ts.map +1 -1
- package/dist/billing/types/auto-recharge.js.map +1 -1
- package/dist/billing/types/catalog.d.ts +1 -1
- package/dist/billing/types/catalog.d.ts.map +1 -1
- package/dist/billing/types/catalog.js.map +1 -1
- package/dist/billing/types/documents.d.ts +1 -1
- package/dist/billing/types/documents.d.ts.map +1 -1
- package/dist/billing/types/documents.js.map +1 -1
- package/dist/billing/types/events.d.ts +8 -0
- package/dist/billing/types/events.d.ts.map +1 -1
- package/dist/billing/types/events.js.map +1 -1
- package/dist/breakdown.d.ts +1 -1
- package/dist/breakdown.d.ts.map +1 -1
- package/dist/breakdown.js +1 -1
- package/dist/breakdown.js.map +1 -1
- package/dist/commerce/service.d.ts.map +1 -1
- package/dist/commerce/service.js +58 -50
- package/dist/commerce/service.js.map +1 -1
- package/dist/commerce/types.d.ts +1 -1
- package/dist/commerce/types.d.ts.map +1 -1
- package/dist/commerce/types.js.map +1 -1
- package/dist/config/parse-utils.d.ts +1 -1
- package/dist/config/parse-utils.d.ts.map +1 -1
- package/dist/config/parse-utils.js +1 -1
- package/dist/config/parse-utils.js.map +1 -1
- package/dist/config/types.d.ts +1 -1
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/config.js +1 -1
- package/dist/config.js.map +1 -1
- package/dist/credits/amount.d.ts +1 -1
- package/dist/credits/amount.d.ts.map +1 -1
- package/dist/credits/amount.js +1 -1
- package/dist/credits/amount.js.map +1 -1
- package/dist/credits/catalog-runtime.d.ts +1 -1
- package/dist/credits/catalog-runtime.d.ts.map +1 -1
- package/dist/credits/catalog-runtime.js +1 -1
- package/dist/credits/catalog-runtime.js.map +1 -1
- package/dist/credits/lease-workflow.d.ts +1 -1
- package/dist/credits/lease-workflow.d.ts.map +1 -1
- package/dist/credits/lease-workflow.js +1 -1
- package/dist/credits/lease-workflow.js.map +1 -1
- package/dist/credits/low-balance-monitor.d.ts +1 -1
- package/dist/credits/low-balance-monitor.d.ts.map +1 -1
- package/dist/credits/low-balance-monitor.js +1 -1
- package/dist/credits/low-balance-monitor.js.map +1 -1
- package/dist/credits/postgres/repositories/balance.js +1 -1
- package/dist/credits/postgres/repositories/balance.js.map +1 -1
- package/dist/credits/postgres/repositories/bucket.js +1 -1
- package/dist/credits/postgres/repositories/bucket.js.map +1 -1
- package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/lease.js +4 -2
- package/dist/credits/postgres/repositories/lease.js.map +1 -1
- package/dist/credits/postgres/repositories/team.d.ts +2 -1
- package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/team.js +19 -5
- package/dist/credits/postgres/repositories/team.js.map +1 -1
- package/dist/credits/postgres/store.d.ts +3 -3
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +6 -3
- package/dist/credits/postgres/store.js.map +1 -1
- package/dist/credits/postgres/value-mappers.d.ts +1 -1
- package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
- package/dist/credits/postgres/value-mappers.js +1 -1
- package/dist/credits/postgres/value-mappers.js.map +1 -1
- package/dist/credits/service-errors.d.ts +1 -1
- package/dist/credits/service-errors.d.ts.map +1 -1
- package/dist/credits/service-errors.js +1 -1
- package/dist/credits/service-errors.js.map +1 -1
- package/dist/credits/service-types.d.ts +4 -1
- package/dist/credits/service-types.d.ts.map +1 -1
- package/dist/credits/service-types.js.map +1 -1
- package/dist/credits/service.d.ts +5 -0
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/service.js +20 -5
- package/dist/credits/service.js.map +1 -1
- package/dist/credits/store.d.ts +10 -1
- package/dist/credits/store.d.ts.map +1 -1
- package/dist/credits/store.js +1 -1
- package/dist/credits/store.js.map +1 -1
- package/dist/credits/types/teams.d.ts +1 -0
- package/dist/credits/types/teams.d.ts.map +1 -1
- package/dist/credits/types/teams.js.map +1 -1
- package/dist/engine.js +1 -1
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts +4 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +34 -0
- package/dist/errors.js.map +1 -1
- package/dist/expr/evaluator.d.ts +1 -1
- package/dist/expr/evaluator.d.ts.map +1 -1
- package/dist/expr/evaluator.js +1 -1
- package/dist/expr/evaluator.js.map +1 -1
- package/dist/expr.d.ts +1 -1
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +1 -1
- package/dist/expr.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/metrics.d.ts +1 -1
- package/dist/metrics.d.ts.map +1 -1
- package/dist/metrics.js.map +1 -1
- package/dist/node.d.ts +6 -3
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +1 -0
- package/dist/node.js.map +1 -1
- package/dist/providers/_shared.d.ts +3 -3
- package/dist/providers/_shared.d.ts.map +1 -1
- package/dist/providers/_shared.js +11 -6
- package/dist/providers/_shared.js.map +1 -1
- package/dist/providers/dodo/client-contract.d.ts +8 -15
- package/dist/providers/dodo/client-contract.d.ts.map +1 -1
- package/dist/providers/dodo/client-contract.js.map +1 -1
- package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
- package/dist/providers/dodo/event-mapper.js +18 -2
- package/dist/providers/dodo/event-mapper.js.map +1 -1
- package/dist/providers/dodo/provider.d.ts.map +1 -1
- package/dist/providers/dodo/provider.js +37 -26
- package/dist/providers/dodo/provider.js.map +1 -1
- package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
- package/dist/providers/stripe/event-mapper.js +71 -3
- package/dist/providers/stripe/event-mapper.js.map +1 -1
- package/dist/providers/types.d.ts +0 -1
- package/dist/providers/types.d.ts.map +1 -1
- package/dist/providers/types.js.map +1 -1
- package/dist/shared/diagnostics.d.ts +8 -0
- package/dist/shared/diagnostics.d.ts.map +1 -1
- package/dist/shared/diagnostics.js +49 -0
- package/dist/shared/diagnostics.js.map +1 -1
- package/dist/shared/postgres-client.d.ts +3 -0
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +15 -2
- package/dist/shared/postgres-client.js.map +1 -1
- package/dist/storage/adapters/clickhouse.d.ts +9 -2
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
- package/dist/storage/adapters/clickhouse.js +142 -36
- package/dist/storage/adapters/clickhouse.js.map +1 -1
- package/dist/storage/adapters/s3.d.ts +44 -6
- package/dist/storage/adapters/s3.d.ts.map +1 -1
- package/dist/storage/adapters/s3.js +59 -21
- package/dist/storage/adapters/s3.js.map +1 -1
- package/dist/storage/diagnostics.d.ts +105 -0
- package/dist/storage/diagnostics.d.ts.map +1 -0
- package/dist/storage/diagnostics.js +227 -0
- package/dist/storage/diagnostics.js.map +1 -0
- package/dist/storage/maintenance.d.ts +88 -0
- package/dist/storage/maintenance.d.ts.map +1 -0
- package/dist/storage/maintenance.js +266 -0
- package/dist/storage/maintenance.js.map +1 -0
- package/dist/storage/outbox-worker.d.ts +20 -0
- package/dist/storage/outbox-worker.d.ts.map +1 -1
- package/dist/storage/outbox-worker.js +152 -23
- package/dist/storage/outbox-worker.js.map +1 -1
- package/dist/storage/ports.d.ts +43 -1
- package/dist/storage/ports.d.ts.map +1 -1
- package/dist/storage/ports.js.map +1 -1
- package/dist/storage/postgres-repository.d.ts +7 -2
- package/dist/storage/postgres-repository.d.ts.map +1 -1
- package/dist/storage/postgres-repository.js +88 -8
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/runtime.d.ts +19 -2
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +216 -29
- package/dist/storage/runtime.js.map +1 -1
- package/dist/telemetry/index.d.ts +37 -0
- package/dist/telemetry/index.d.ts.map +1 -0
- package/dist/telemetry/index.js +115 -0
- package/dist/telemetry/index.js.map +1 -0
- package/dist/telemetry/opentelemetry.d.ts +25 -0
- package/dist/telemetry/opentelemetry.d.ts.map +1 -0
- package/dist/telemetry/opentelemetry.js +74 -0
- package/dist/telemetry/opentelemetry.js.map +1 -0
- package/package.json +11 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"low-balance-monitor.js","sourceRoot":"","sources":["../../src/credits/low-balance-monitor.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"low-balance-monitor.js","sourceRoot":"","sources":["../../src/credits/low-balance-monitor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAMrC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,MAAM,yBAAyB,GAAG,OAAO,CAAC;AAQ1C;;;;;GAKG;AACH,MAAM,OAAO,iBAAiB;IAOT;IACA;IAPF,UAAU,CAAmB;IAC7B,OAAO,CAAwD;IAC/D,cAAc,CAAgC;IAE/D,YACE,MAA2C,EAC1B,IAAqB,EACrB,MAAwB;QADxB,SAAI,GAAJ,IAAI,CAAiB;QACrB,WAAM,GAAN,MAAM,CAAkB;QAEzC,IAAI,CAAC,UAAU,GAAG,MAAM,EAAE,UAAU,EAAE,MAAM;YAC1C,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YAChF,CAAC,CAAC,IAAI,CAAC;QACT,IAAI,CAAC,OAAO,GAAG,MAAM,EAAE,SAAS,IAAI,IAAI,CAAC;QACzC,MAAM,eAAe,GAAG,MAAM,EAAE,eAAe,IAAI,yBAAyB,CAAC;QAC7E,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,eAAe,CAAC,IAAI,eAAe,GAAG,CAAC,EAAE,CAAC;YAClE,MAAM,IAAI,UAAU,CAAC,4DAA4D,CAAC,CAAC;QACrF,CAAC;QACD,IAAI,CAAC,cAAc,GAAG,IAAI,QAAQ,CAAC,EAAE,GAAG,EAAE,eAAe,EAAE,CA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CACxD,SAAS,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAC5C,CAAC;YACF,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,CAAC,CAAC;QAChD,CAAC;IACH,CAAC;IAEO,KAAK,CAAC,IAAI,CAAC,MAAc,EAAE,OAAgB,EAAE,SAAkB;QACrE,MAAM,IAAI,GAAG,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;QACpC,IAAI,CAAC,IAAI,CAAC,qBAAqB,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;QAC/C,IAAI,CAAC,IAAI,CAAC,OAAO;YAAE,OAAO;QAE1B,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,OAAO,CAAC;gBACjB,IAAI,EAAE,qBAAqB;gBAC3B,SAAS,EAAE,IAAI,IAAI,EAAE;gBACrB,MAAM;gBACN,IAAI;aACL,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,8CAA8C,EAAE;gBAChE,MAAM;gBACN,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;aAC9D,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { LRUCache } from \"lru-cache\";\n\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditEvent, CreditEventType } from \"./events.js\";\nimport type { DeductionSuccess } from \"./types/index.js\";\nimport type { LowBalanceConfig } from \"./service-types.js\";\nimport { toDecimal } from \"./amount.js\";\n\nconst DEFAULT_MAX_TRACKED_USERS = 100_000;\n\ntype EmitCreditEvent = (\n type: CreditEventType,\n userId: string,\n data?: Record<string, unknown>,\n) => void;\n\n/**\n * Owns edge-trigger state for low-balance and overdraft notifications.\n *\n * Keeping this state outside CreditsService makes the event semantics\n * independently testable and keeps the service focused on orchestration.\n */\nexport class LowBalanceMonitor {\n private readonly thresholds: Decimal[] | null;\n private readonly handler: ((event: CreditEvent) => void | Promise<void>) | null;\n private readonly breachedByUser: LRUCache<string, Set<string>>;\n\n constructor(\n config: LowBalanceConfig | null | undefined,\n private readonly emit: EmitCreditEvent,\n private readonly logger: NormalizedLogger,\n ) {\n this.thresholds = config?.thresholds?.length\n ? config.thresholds.map(toDecimal).sort((left, right) => right.comparedTo(left))\n : null;\n this.handler = config?.onTrigger ?? null;\n const maxTrackedUsers = config?.maxTrackedUsers ?? DEFAULT_MAX_TRACKED_USERS;\n if (!Number.isSafeInteger(maxTrackedUsers) || maxTrackedUsers < 1) {\n throw new RangeError(\"lowBalance.maxTrackedUsers must be a positive safe integer\");\n }\n this.breachedByUser = new LRUCache({ max: maxTrackedUsers });\n }\n\n rearmAfterCredit(userId: string, balance: Decimal): void {\n if (!this.thresholds) return;\n const breached = this.breachedByUser.get(userId) ?? new Set<string>();\n for (const threshold of this.thresholds) {\n if (balance.gt(threshold)) breached.delete(threshold.toString());\n }\n if (breached.size === 0) {\n this.breachedByUser.delete(userId);\n } else {\n this.breachedByUser.set(userId, breached);\n }\n }\n\n async afterCharge(userId: string, result: DeductionSuccess): Promise<void> {\n if (result.idempotent) return;\n if (result.balanceAfter.lt(0)) {\n this.emit(\"credits.overdraft\", userId, {\n balance: result.balanceAfter,\n amount: result.amount,\n });\n }\n await this.signalCrossing(userId, result.balanceAfter.plus(result.amount), result.balanceAfter);\n }\n\n async signalCrossing(\n userId: string,\n balanceBefore: Decimal,\n balanceAfter: Decimal,\n ): Promise<void> {\n if (!this.thresholds) {\n const threshold = new Decimal(0);\n if (balanceBefore.gt(threshold) && balanceAfter.lte(threshold)) {\n await this.fire(userId, balanceAfter, threshold);\n }\n return;\n }\n\n const breached = this.breachedByUser.get(userId) ?? new Set<string>();\n const newlyCrossed: Decimal[] = [];\n for (const threshold of this.thresholds) {\n if (balanceAfter.lte(threshold)) {\n if (!breached.has(threshold.toString())) {\n breached.add(threshold.toString());\n newlyCrossed.push(threshold);\n }\n } else {\n breached.delete(threshold.toString());\n }\n }\n if (breached.size === 0) {\n this.breachedByUser.delete(userId);\n } else {\n this.breachedByUser.set(userId, breached);\n }\n if (newlyCrossed.length > 0) {\n const lowest = newlyCrossed.reduce((minimum, threshold) =>\n threshold.lt(minimum) ? threshold : minimum,\n );\n await this.fire(userId, balanceAfter, lowest);\n }\n }\n\n private async fire(userId: string, balance: Decimal, threshold: Decimal): Promise<void> {\n const data = { balance, threshold };\n this.emit(\"credits.low_balance\", userId, data);\n if (!this.handler) return;\n\n try {\n await this.handler({\n type: \"credits.low_balance\",\n timestamp: new Date(),\n userId,\n data,\n });\n } catch (error) {\n this.logger.error(\"[CreditsService] onLowBalance handler failed\", {\n userId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import Decimal from "decimal.js";
|
|
2
|
+
import { Decimal } from "decimal.js";
|
|
3
3
|
import { pgBoolean, postgresUuid, requireRow, safeParse, } from "../../../shared/postgres-validation.js";
|
|
4
4
|
const decimal = z.union([z.string().min(1), z.number().finite()]);
|
|
5
5
|
const BalanceRowSchema = z
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"balance.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/balance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,OAAO,MAAM,YAAY,CAAC;AAEjC,OAAO,EACL,SAAS,EACT,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAA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G,MAAM,IAAI,CAAC,QAAQ,CAAC,uBAAuB,EAAE;YACxD,MAAM,CAAC,OAAO;YACd,MAAM,CAAC,UAAU;YACjB,MAAM,CAAC,SAAS;YAChB,MAAM,CAAC,QAAQ;YACf,MAAM,CAAC,iBAAiB;YACxB,MAAM,CAAC,MAAM;YACb,MAAM,CAAC,QAAQ;SAChB,CAAC,CAAC;QACH,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC9B,SAAS,CAAC,0BAA0B,EAAE,GAAG,EAAE,uCAAuC,CAAC,CACpF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport Decimal from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n pgBoolean,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\n\nconst BalanceRowSchema = z\n .object({\n user_id: z.string().min(1),\n balance: decimal,\n lifetime_purchased: decimal,\n })\n .strict();\n\nconst AddCreditsRowSchema = z\n .object({\n entry_id: z.string().nullable(),\n user_id: z.string().min(1),\n amount: decimal,\n new_balance: decimal.nullable(),\n lifetime_purchased: decimal.nullable(),\n bucket: z.string().min(1).nullable(),\n idempotent: pgBoolean,\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.entry_id === null || row.new_balance === null || row.lifetime_purchased === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful credit postings require entry and balance fields\",\n });\n }\n const amount = new Decimal(row.amount);\n if (row.error === null && amount.isPositive() && row.bucket === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful positive credit postings require a destination bucket\",\n });\n }\n if (row.error === null && !amount.isPositive() && row.bucket !== null) {\n context.addIssue({\n code: \"custom\",\n message: \"debit postings cannot claim a single destination bucket\",\n });\n }\n if (\n row.error !== null &&\n (row.entry_id !== null ||\n row.new_balance !== null ||\n row.lifetime_purchased !== null ||\n row.bucket !== null ||\n row.idempotent)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed credit postings cannot expose committed result fields\",\n });\n }\n });\n\nconst AvailableRowSchema = z\n .object({\n balance: decimal,\n reserved: decimal,\n available: decimal,\n })\n .strict();\n\nconst GrantProgramAwardRowSchema = z\n .object({\n grant_event_id: postgresUuid.nullable(),\n grant_award_id: postgresUuid.nullable(),\n recipient_subject_id: postgresUuid.nullable(),\n ledger_entry_id: postgresUuid.nullable(),\n amount: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n const award = [\n row.grant_event_id,\n row.grant_award_id,\n row.recipient_subject_id,\n row.ledger_entry_id,\n row.amount,\n ];\n if (row.error_code === null && award.some((value) => value === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful grant awards require committed fields\",\n });\n }\n if (row.error_code !== null && (award.some((value) => value !== null) || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed grant awards cannot expose committed fields\",\n });\n }\n });\n\nexport type BalanceRow = z.infer<typeof BalanceRowSchema>;\nexport type AddCreditsRow = z.infer<typeof AddCreditsRowSchema>;\nexport type AvailableRow = z.infer<typeof AvailableRowSchema>;\nexport type GrantProgramAwardRow = z.infer<typeof GrantProgramAwardRowSchema>;\n\n/** Repository for user credit balance operations.\n *\n * All methods call Postgres RPCs via the callproc function.\n *\n * Reads may return no row for a new account. Mutations require the database's\n * single-row result envelope and fail closed when that contract is violated.\n */\nexport class BalanceRepository {\n constructor(private callproc: CallProc) {}\n\n /** Fetch a user's credit balance. Returns null for new users with no balance row. */\n async getBalance(userId: string): Promise<BalanceRow | null> {\n const rows = await this.callproc(\"get_credit_state\", [userId]);\n if (!rows || rows.length === 0) return null;\n const row = requireRow(rows, \"BalanceRepository.getBalance\") as Record<string, unknown>;\n return safeParse(\n BalanceRowSchema,\n {\n user_id: userId,\n balance: row.balance,\n lifetime_purchased: row.lifetime_purchased,\n },\n \"BalanceRepository.getBalance\",\n );\n }\n\n /** Add credits to a user's account. */\n async addCredits(\n userId: string,\n amount: string,\n type: string,\n metadata: string,\n expiresAt: string | null,\n bucket: string | null,\n idempotencyKey: string | null,\n ): Promise<AddCreditsRow> {\n const decimalAmount = new Decimal(amount);\n const rows = await this.callproc(\"post_credit\", [\n userId,\n decimalAmount.isNegative() ? \"adjustment\" : type === \"purchase\" ? \"purchase\" : \"grant\",\n amount,\n type,\n idempotencyKey,\n metadata,\n bucket,\n null,\n expiresAt,\n \"0\",\n ]);\n const row = requireRow(rows, \"BalanceRepository.addCredits\") as Record<string, unknown>;\n const state =\n row.error_code == null\n ? ((await this.callproc(\"get_credit_state\", [userId]))[0] as\n Record<string, unknown> | undefined)\n : undefined;\n const grant =\n row.error_code == null && decimalAmount.isPositive() && row.entry_id != null\n ? ((await this.callproc(\"get_credit_grant_details\", [userId, row.entry_id]))[0] as\n Record<string, unknown> | undefined)\n : undefined;\n return safeParse(\n AddCreditsRowSchema,\n {\n entry_id: row.entry_id ?? null,\n user_id: userId,\n amount,\n new_balance: row.balance_after ?? null,\n lifetime_purchased: state?.lifetime_purchased ?? null,\n bucket: decimalAmount.isPositive() ? (grant?.bucket_key ?? null) : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"BalanceRepository.addCredits\",\n );\n }\n\n /** Fetch available balance (balance minus reserved holds). */\n async getAvailable(userId: string): Promise<AvailableRow | null> {\n const rows = await this.callproc(\"get_credit_state\", [userId]);\n if (!rows || rows.length === 0) {\n return null;\n }\n const row = requireRow(rows, \"BalanceRepository.getAvailable\") as Record<string, unknown>;\n return safeParse(\n AvailableRowSchema,\n {\n balance: row.balance,\n reserved: row.reserved,\n available: row.available,\n },\n \"BalanceRepository.getAvailable\",\n );\n }\n\n /** Execute a configured grant-program event and return every award row. */\n async executeGrantProgram(params: {\n trigger: string;\n programKey: string;\n subjectId: string;\n eventKey: string;\n referrerSubjectId: string | null;\n region: string | null;\n metadata: string;\n }): Promise<GrantProgramAwardRow[]> {\n const rows = await this.callproc(\"execute_grant_program\", [\n params.trigger,\n params.programKey,\n params.subjectId,\n params.eventKey,\n params.referrerSubjectId,\n params.region,\n params.metadata,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(GrantProgramAwardRowSchema, row, \"BalanceRepository.executeGrantProgram\"),\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"balance.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/balance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,EACL,SAAS,EACT,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAE3E,MAAM,gBAAgB,GAAG,CAAC;KACvB,MAAM,CAAC;IACN,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC1B,OAAO,EAAE,OAAO;IAChB,kBAAkB,EAAE,OAAO;CAC5B,CAAC;KACD,MAAM,EAAE,CAAC;AAEZ,MAAM,mBAAmB,GAAG,CAAC;KAC1B,MAAM,CAAC;IACN,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC/B,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC1B,MAAM,EAAE,OAAO;IACf,WAAW,EAAE,OAAO,CAAC,QAAQ,EAAE;IAC/B,kBAAkB,EAAE,OAAO,CAAC,QAAQ,EAAE;IACtC,MAAM,E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AU;SACtB,EACD,8BAA8B,CAC/B,CAAC;IACJ,CAAC;IAED,8DAA8D;IAC9D,KAAK,CAAC,YAAY,CAAC,MAAc;QAC/B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,kBAAkB,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;QAC/D,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC/B,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,GAAG,GAAG,UAAU,CAAC,IAAI,EAAE,gCAAgC,CAA4B,CAAC;QAC1F,OAAO,SAAS,CACd,kBAAkB,EAClB;YACE,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,SAAS,EAAE,GAAG,CAAC,SAAS;SACzB,EACD,gCAAgC,CACjC,CAAC;IACJ,CAAC;IAED,2EAA2E;IAC3E,KAAK,CAAC,mBAAmB,CAAC,MAQzB;QACC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,uBAAuB,EAAE;YACxD,MAAM,CAAC,OAAO;YACd,MAAM,CAAC,UAAU;YACjB,MAAM,CAAC,SAAS;YAChB,MAAM,CAAC,QAAQ;YACf,MAAM,CAAC,iBAAiB;YACxB,MAAM,CAAC,MAAM;YACb,MAAM,CAAC,QAAQ;SAChB,CAAC,CAAC;QACH,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC9B,SAAS,CAAC,0BAA0B,EAAE,GAAG,EAAE,uCAAuC,CAAC,CACpF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { Decimal } from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n pgBoolean,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\n\nconst BalanceRowSchema = z\n .object({\n user_id: z.string().min(1),\n balance: decimal,\n lifetime_purchased: decimal,\n })\n .strict();\n\nconst AddCreditsRowSchema = z\n .object({\n entry_id: z.string().nullable(),\n user_id: z.string().min(1),\n amount: decimal,\n new_balance: decimal.nullable(),\n lifetime_purchased: decimal.nullable(),\n bucket: z.string().min(1).nullable(),\n idempotent: pgBoolean,\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.entry_id === null || row.new_balance === null || row.lifetime_purchased === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful credit postings require entry and balance fields\",\n });\n }\n const amount = new Decimal(row.amount);\n if (row.error === null && amount.isPositive() && row.bucket === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful positive credit postings require a destination bucket\",\n });\n }\n if (row.error === null && !amount.isPositive() && row.bucket !== null) {\n context.addIssue({\n code: \"custom\",\n message: \"debit postings cannot claim a single destination bucket\",\n });\n }\n if (\n row.error !== null &&\n (row.entry_id !== null ||\n row.new_balance !== null ||\n row.lifetime_purchased !== null ||\n row.bucket !== null ||\n row.idempotent)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed credit postings cannot expose committed result fields\",\n });\n }\n });\n\nconst AvailableRowSchema = z\n .object({\n balance: decimal,\n reserved: decimal,\n available: decimal,\n })\n .strict();\n\nconst GrantProgramAwardRowSchema = z\n .object({\n grant_event_id: postgresUuid.nullable(),\n grant_award_id: postgresUuid.nullable(),\n recipient_subject_id: postgresUuid.nullable(),\n ledger_entry_id: postgresUuid.nullable(),\n amount: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n const award = [\n row.grant_event_id,\n row.grant_award_id,\n row.recipient_subject_id,\n row.ledger_entry_id,\n row.amount,\n ];\n if (row.error_code === null && award.some((value) => value === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful grant awards require committed fields\",\n });\n }\n if (row.error_code !== null && (award.some((value) => value !== null) || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed grant awards cannot expose committed fields\",\n });\n }\n });\n\nexport type BalanceRow = z.infer<typeof BalanceRowSchema>;\nexport type AddCreditsRow = z.infer<typeof AddCreditsRowSchema>;\nexport type AvailableRow = z.infer<typeof AvailableRowSchema>;\nexport type GrantProgramAwardRow = z.infer<typeof GrantProgramAwardRowSchema>;\n\n/** Repository for user credit balance operations.\n *\n * All methods call Postgres RPCs via the callproc function.\n *\n * Reads may return no row for a new account. Mutations require the database's\n * single-row result envelope and fail closed when that contract is violated.\n */\nexport class BalanceRepository {\n constructor(private callproc: CallProc) {}\n\n /** Fetch a user's credit balance. Returns null for new users with no balance row. */\n async getBalance(userId: string): Promise<BalanceRow | null> {\n const rows = await this.callproc(\"get_credit_state\", [userId]);\n if (!rows || rows.length === 0) return null;\n const row = requireRow(rows, \"BalanceRepository.getBalance\") as Record<string, unknown>;\n return safeParse(\n BalanceRowSchema,\n {\n user_id: userId,\n balance: row.balance,\n lifetime_purchased: row.lifetime_purchased,\n },\n \"BalanceRepository.getBalance\",\n );\n }\n\n /** Add credits to a user's account. */\n async addCredits(\n userId: string,\n amount: string,\n type: string,\n metadata: string,\n expiresAt: string | null,\n bucket: string | null,\n idempotencyKey: string | null,\n ): Promise<AddCreditsRow> {\n const decimalAmount = new Decimal(amount);\n const rows = await this.callproc(\"post_credit\", [\n userId,\n decimalAmount.isNegative() ? \"adjustment\" : type === \"purchase\" ? \"purchase\" : \"grant\",\n amount,\n type,\n idempotencyKey,\n metadata,\n bucket,\n null,\n expiresAt,\n \"0\",\n ]);\n const row = requireRow(rows, \"BalanceRepository.addCredits\") as Record<string, unknown>;\n const state =\n row.error_code == null\n ? ((await this.callproc(\"get_credit_state\", [userId]))[0] as\n Record<string, unknown> | undefined)\n : undefined;\n const grant =\n row.error_code == null && decimalAmount.isPositive() && row.entry_id != null\n ? ((await this.callproc(\"get_credit_grant_details\", [userId, row.entry_id]))[0] as\n Record<string, unknown> | undefined)\n : undefined;\n return safeParse(\n AddCreditsRowSchema,\n {\n entry_id: row.entry_id ?? null,\n user_id: userId,\n amount,\n new_balance: row.balance_after ?? null,\n lifetime_purchased: state?.lifetime_purchased ?? null,\n bucket: decimalAmount.isPositive() ? (grant?.bucket_key ?? null) : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"BalanceRepository.addCredits\",\n );\n }\n\n /** Fetch available balance (balance minus reserved holds). */\n async getAvailable(userId: string): Promise<AvailableRow | null> {\n const rows = await this.callproc(\"get_credit_state\", [userId]);\n if (!rows || rows.length === 0) {\n return null;\n }\n const row = requireRow(rows, \"BalanceRepository.getAvailable\") as Record<string, unknown>;\n return safeParse(\n AvailableRowSchema,\n {\n balance: row.balance,\n reserved: row.reserved,\n available: row.available,\n },\n \"BalanceRepository.getAvailable\",\n );\n }\n\n /** Execute a configured grant-program event and return every award row. */\n async executeGrantProgram(params: {\n trigger: string;\n programKey: string;\n subjectId: string;\n eventKey: string;\n referrerSubjectId: string | null;\n region: string | null;\n metadata: string;\n }): Promise<GrantProgramAwardRow[]> {\n const rows = await this.callproc(\"execute_grant_program\", [\n params.trigger,\n params.programKey,\n params.subjectId,\n params.eventKey,\n params.referrerSubjectId,\n params.region,\n params.metadata,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(GrantProgramAwardRowSchema, row, \"BalanceRepository.executeGrantProgram\"),\n );\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import Decimal from "decimal.js";
|
|
2
|
+
import { Decimal } from "decimal.js";
|
|
3
3
|
import { postgresUuid, requireRow, safeParse } from "../../../shared/postgres-validation.js";
|
|
4
4
|
const decimal = z.union([z.string().min(1), z.number().finite()]);
|
|
5
5
|
const BucketRowSchema = z
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bucket.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/bucket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,OAAO,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"bucket.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/bucket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,wCAAwC,CAAC;AAE7F,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAE3E,MAAM,eAAe,GAAG,CAAC;KACtB,MAAM,CAAC;IACN,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC7B,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IACxB,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE;IACxC,OAAO,EAAE,CAAC,CAAC,OAAO,EAAE;IACpB,OAAO,EAAE,OAAO;CACjB,CAAC;KACD,MAAM,EAAE,CAAC;AAEZ,MAAM,uBAAuB,GAAG,CAAC;KAC9B,MAAM,CAAC;IACN,OAAO,EAAE,YAAY;IACrB,OAAO,EAAE,CAAC,CAAC,KAAK,CAAC,eAAe,CAAC;IACjC,aAAa,EAAE,OAAO;CACvB,CAAC;KACD,MAAM,EAAE,CAAC;AAEZ,MAAM,cAAc,GAAG,CAAC;KACrB,MAAM,CAAC;IACN,aAAa,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAA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AAU,CAAC,IAAI,EAAE,sCAAsC,CAAC,EACxD,sCAAsC,CACvC,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { Decimal } from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { postgresUuid, requireRow, safeParse } from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\n\nconst BucketRowSchema = z\n .object({\n bucket_key: z.string().min(1),\n label: z.string().min(1),\n priority: z.number().int().nonnegative(),\n expires: z.boolean(),\n balance: decimal,\n })\n .strict();\n\nconst BucketEnvelopeRowSchema = z\n .object({\n user_id: postgresUuid,\n buckets: z.array(BucketRowSchema),\n total_balance: decimal,\n })\n .strict();\n\nconst SweepRowSchema = z\n .object({\n expired_count: z.number().int().nonnegative(),\n expired_amount: decimal,\n expired_by_bucket: z.record(z.string().min(1), decimal),\n })\n .strict();\n\nexport type BucketEnvelopeRow = z.infer<typeof BucketEnvelopeRowSchema>;\nexport type SweepRow = z.infer<typeof SweepRowSchema>;\n\n/** Repository for credit bucket operations. */\nexport class BucketRepository {\n constructor(private callproc: CallProc) {}\n\n /** Fetch per-bucket credit balances for a user. */\n async getBucketBalances(userId: string): Promise<BucketEnvelopeRow> {\n const rows = await this.callproc(\"get_credit_bucket_balances\", [userId]);\n const buckets = (rows ?? []).map((row) =>\n safeParse(BucketRowSchema, row, \"BucketRepository.getBucketBalances\"),\n );\n const totalBalance = buckets\n .reduce((total, row) => total.plus(row.balance), new Decimal(0))\n .toString();\n return safeParse(\n BucketEnvelopeRowSchema,\n {\n user_id: userId,\n buckets,\n total_balance: totalBalance,\n },\n \"BucketRepository.getBucketBalances\",\n );\n }\n\n /** Sweep expired credit grants. */\n async sweepExpiredCredits(dryRun = false, userId?: string, limit = 100): Promise<SweepRow> {\n const rows = await this.callproc(\"sweep_expired_lots\", [limit, userId ?? null, dryRun]);\n return safeParse(\n SweepRowSchema,\n requireRow(rows, \"BucketRepository.sweepExpiredCredits\"),\n \"BucketRepository.sweepExpiredCredits\",\n );\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lease.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/lease.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAElE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"lease.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/lease.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAElE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAsEnD,QAAA,MAAM,cAAc;;;;;;;kBAmChB,CAAC;AAEL,QAAA,MAAM,gBAAgB;;;;;;;;;kBAKX,CAAC;AAEZ,QAAA,MAAM,4BAA4B;;;;;kBAY9B,CAAC;AAEL,MAAM,MAAM,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,cAAc,CAAC,CAAC;AACtD,MAAM,MAAM,UAAU,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAC1D,MAAM,MAAM,sBAAsB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,4BAA4B,CAAC,CAAC;AAElF,qEAAqE;AACrE,qBAAa,eAAe;IACd,OAAO,CAAC,QAAQ;gBAAR,QAAQ,EAAE,QAAQ;IAEtC,6DAA6D;IACvD,WAAW,CAAC,MAAM,EAAE;QACxB,MAAM,EAAE,MAAM,CAAC;QACf,MAAM,EAAE,MAAM,CAAC;QACf,aAAa,EAAE,MAAM,CAAC;QACtB,cAAc,EAAE,MAAM,CAAC;QACvB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.js";
|
|
3
3
|
import { optionalRecordRow, postgresUuid, requireRow, safeParse, } from "../../../shared/postgres-validation.js";
|
|
4
4
|
import { StoreError } from "../../../errors.js";
|
|
5
|
-
import Decimal from "decimal.js";
|
|
5
|
+
import { Decimal } from "decimal.js";
|
|
6
|
+
import { quantizeMoney } from "../../../expr.js";
|
|
6
7
|
const decimal = z.union([z.string().min(1), z.number().finite()]);
|
|
7
8
|
const timestamp = z.union([z.string().min(1), z.date()]).transform((value, context) => {
|
|
8
9
|
const parsed = value instanceof Date ? value : new Date(value);
|
|
@@ -165,7 +166,8 @@ export class LeaseRepository {
|
|
|
165
166
|
params.metadata,
|
|
166
167
|
]);
|
|
167
168
|
const row = safeParse(SettleLeaseRpcRowSchema, requireRow(rows, "LeaseRepository.settleLease"), "LeaseRepository.settleLease");
|
|
168
|
-
if (row.error_code === null &&
|
|
169
|
+
if (row.error_code === null &&
|
|
170
|
+
!new Decimal(row.settled_amount).equals(quantizeMoney(new Decimal(params.amount)))) {
|
|
169
171
|
throw new StoreError("LeaseRepository.settleLease: committed amount differs from the request", {
|
|
170
172
|
indeterminate: true,
|
|
171
173
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lease.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/lease.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,OAAO,MAAM,YAAY,CAAC;AAEjC,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,C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GAAG,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAC9D,UAAU,CAAC,IAAI,EAAE,8BAA8B,CAAC,EAChD,8BAA8B,CAC/B,CAAC;QACF,OAAO,GAAG,CAAC,OAAO,CAAC;IACrB,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { DeductionRowSchema } from \"./deduction.js\";\nimport type { DeductionRow } from \"./deduction.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport Decimal from \"decimal.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst timestamp = z.union([z.string().min(1), z.date()] as const).transform((value, context) => {\n const parsed = value instanceof Date ? value : new Date(value);\n if (Number.isNaN(parsed.getTime())) {\n context.addIssue({ code: \"custom\", message: \"expected a valid timestamp\" });\n return z.NEVER;\n }\n return parsed.toISOString();\n});\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst leaseStatus = z.enum([\"active\", \"settling\", \"settled\", \"released\", \"expired\"]);\n\nconst LeaseMutationRpcRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n status: leaseStatus,\n reserved_amount: decimal,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && (row.lease_id === null || row.status !== \"active\")) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease mutations require an active lease\",\n });\n }\n });\n\nconst SettleLeaseRpcRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n charge_id: postgresUuid.nullable(),\n settled_amount: decimal,\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && row.charge_id === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease settlement requires a charge receipt\",\n });\n }\n if (\n row.error_code !== null &&\n (row.ledger_entry_id !== null || row.charge_id !== null || row.replayed)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease settlement cannot expose committed fields\",\n });\n }\n });\n\nconst LeaseRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n user_id: postgresUuid,\n amount: decimal.nullable(),\n minimum_balance: decimal.nullable(),\n expires_at: timestamp.nullable(),\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.lease_id === null ||\n row.amount === null ||\n row.minimum_balance === null ||\n row.expires_at === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease acquisition requires lease and policy fields\",\n });\n }\n if (\n row.error !== null &&\n (row.lease_id !== null ||\n row.amount !== null ||\n row.minimum_balance !== null ||\n row.expires_at !== null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease mutations cannot expose committed fields\",\n });\n }\n });\n\nconst ReleaseRowSchema = z\n .object({\n released: z.boolean(),\n reason: leaseStatus.or(z.literal(\"missing_lease\")).nullable(),\n })\n .strict();\n\nconst LeasePricingContextRowSchema = z\n .object({\n catalog_revision_no: safeInteger,\n plan_id: postgresUuid.nullable(),\n plan_key: z.string().min(1).nullable(),\n rate_card: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if ((row.plan_id === null) !== (row.plan_key === null)) {\n context.addIssue({ code: \"custom\", message: \"lease plan identity fields are inconsistent\" });\n }\n });\n\nexport type LeaseRow = z.infer<typeof LeaseRowSchema>;\nexport type ReleaseRow = z.infer<typeof ReleaseRowSchema>;\nexport type LeasePricingContextRow = z.infer<typeof LeasePricingContextRowSchema>;\n\n/** Repository for lease lifecycle operations (admission control). */\nexport class LeaseRepository {\n constructor(private callproc: CallProc) {}\n\n /** Atomically acquire a lease (hold) — admission control. */\n async createLease(params: {\n userId: string;\n amount: string;\n operationType: string;\n idempotencyKey: string;\n ttlSeconds: number;\n metadata: string;\n feature: string | null;\n measures: string;\n dimensions: string;\n minimumBalance: string | null;\n maxConcurrent: number | null;\n }): Promise<LeaseRow> {\n const rows = await this.callproc(\"create_lease_for_operation\", [\n params.userId,\n params.operationType,\n params.amount,\n params.idempotencyKey,\n `${params.ttlSeconds} seconds`,\n params.metadata,\n params.feature,\n params.measures,\n params.dimensions,\n params.minimumBalance,\n params.maxConcurrent,\n ]);\n const row = safeParse(\n LeaseMutationRpcRowSchema,\n requireRow(rows, \"LeaseRepository.createLease\"),\n \"LeaseRepository.createLease\",\n );\n if (row.error_code !== null) {\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: params.userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error: row.error_code,\n },\n \"LeaseRepository.createLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [params.userId, row.lease_id]),\n \"LeaseRepository.createLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: params.userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.createLease\",\n );\n }\n\n /** Charge the actual cost against a lease and mark it settled. */\n async settleLease(params: {\n userId: string;\n leaseId: string;\n amount: string;\n idempotencyKey: string;\n feature: string | null;\n model: string | null;\n region: string | null;\n measures: string;\n dimensions: string;\n metadata: string;\n }): Promise<DeductionRow> {\n const rows = await this.callproc(\"settle_lease\", [\n params.userId,\n params.leaseId,\n params.amount,\n params.idempotencyKey,\n params.feature,\n params.model,\n params.region,\n params.measures,\n params.dimensions,\n params.metadata,\n ]);\n const row = safeParse(\n SettleLeaseRpcRowSchema,\n requireRow(rows, \"LeaseRepository.settleLease\"),\n \"LeaseRepository.settleLease\",\n );\n if (row.error_code === null && !new Decimal(row.settled_amount).equals(params.amount)) {\n throw new StoreError(\n \"LeaseRepository.settleLease: committed amount differs from the request\",\n {\n indeterminate: true,\n },\n );\n }\n const charge =\n row.error_code == null\n ? optionalRecordRow(\n await this.callproc(\"get_credit_operation_details\", [\n params.userId,\n row.ledger_entry_id ?? null,\n params.idempotencyKey,\n ]),\n \"LeaseRepository.settleLease.details\",\n )\n : null;\n return safeParse(\n DeductionRowSchema,\n {\n charge_id: row.charge_id,\n user_id: params.userId,\n entry_id: row.ledger_entry_id,\n amount: row.error_code === null ? row.settled_amount : params.amount,\n allowance_consumed: row.error_code === null ? charge?.allowance_covered : \"0\",\n balance_after: row.error_code === null ? charge?.balance_after : null,\n bucket_breakdown: row.error_code === null ? charge?.bucket_breakdown : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"LeaseRepository.settleLease\",\n );\n }\n\n /** Return the immutable pricing context captured at lease admission. */\n async getPricingContext(userId: string, leaseId: string): Promise<LeasePricingContextRow | null> {\n const rows = await this.callproc(\"get_credit_lease_pricing_context\", [userId, leaseId]);\n const row = optionalRecordRow(rows, \"LeaseRepository.getPricingContext\");\n return row === null\n ? null\n : safeParse(LeasePricingContextRowSchema, row, \"LeaseRepository.getPricingContext\");\n }\n\n /** Release a lease without charging — idempotent. */\n async releaseLease(userId: string, leaseId: string): Promise<ReleaseRow> {\n const rows = await this.callproc(\"release_lease\", [userId, leaseId]);\n const status = safeParse(\n leaseStatus.or(z.literal(\"missing_lease\")),\n requireRow(rows, \"LeaseRepository.releaseLease\"),\n \"LeaseRepository.releaseLease\",\n );\n return safeParse(\n ReleaseRowSchema,\n {\n released: status === \"released\",\n reason: status === \"released\" ? null : status,\n },\n \"LeaseRepository.releaseLease\",\n );\n }\n\n /** Extend an active lease without changing its captured policy snapshot. */\n async renewLease(userId: string, leaseId: string, ttlSeconds: number): Promise<LeaseRow> {\n const rows = await this.callproc(\"renew_lease\", [userId, leaseId, `${ttlSeconds} seconds`]);\n const row = safeParse(\n LeaseMutationRpcRowSchema,\n requireRow(rows, \"LeaseRepository.renewLease\"),\n \"LeaseRepository.renewLease\",\n );\n if (row.error_code !== null) {\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error: row.error_code,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [userId, row.lease_id]),\n \"LeaseRepository.renewLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n\n /** Expire a bounded batch of leases and release their reservations. */\n async expireLeases(limit: number): Promise<number> {\n const rows = await this.callproc(\"expire_leases\", [limit]);\n const row = safeParse(\n z.object({ expired: z.number().int().nonnegative() }).strict(),\n requireRow(rows, \"LeaseRepository.expireLeases\"),\n \"LeaseRepository.expireLeases\",\n );\n return row.expired;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"lease.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/lease.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAC3E,MAAM,SAAS,GAAG,CAAC,CA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,EAAE,CAAC,CAAC,MAAM,EAAE,EAC9D,UAAU,CAAC,IAAI,EAAE,8BAA8B,CAAC,EAChD,8BAA8B,CAC/B,CAAC;QACF,OAAO,GAAG,CAAC,OAAO,CAAC;IACrB,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { DeductionRowSchema } from \"./deduction.js\";\nimport type { DeductionRow } from \"./deduction.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport { Decimal } from \"decimal.js\";\nimport { quantizeMoney } from \"../../../expr.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst timestamp = z.union([z.string().min(1), z.date()] as const).transform((value, context) => {\n const parsed = value instanceof Date ? value : new Date(value);\n if (Number.isNaN(parsed.getTime())) {\n context.addIssue({ code: \"custom\", message: \"expected a valid timestamp\" });\n return z.NEVER;\n }\n return parsed.toISOString();\n});\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst leaseStatus = z.enum([\"active\", \"settling\", \"settled\", \"released\", \"expired\"]);\n\nconst LeaseMutationRpcRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n status: leaseStatus,\n reserved_amount: decimal,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && (row.lease_id === null || row.status !== \"active\")) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease mutations require an active lease\",\n });\n }\n });\n\nconst SettleLeaseRpcRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n charge_id: postgresUuid.nullable(),\n settled_amount: decimal,\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && row.charge_id === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease settlement requires a charge receipt\",\n });\n }\n if (\n row.error_code !== null &&\n (row.ledger_entry_id !== null || row.charge_id !== null || row.replayed)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease settlement cannot expose committed fields\",\n });\n }\n });\n\nconst LeaseRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n user_id: postgresUuid,\n amount: decimal.nullable(),\n minimum_balance: decimal.nullable(),\n expires_at: timestamp.nullable(),\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.lease_id === null ||\n row.amount === null ||\n row.minimum_balance === null ||\n row.expires_at === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease acquisition requires lease and policy fields\",\n });\n }\n if (\n row.error !== null &&\n (row.lease_id !== null ||\n row.amount !== null ||\n row.minimum_balance !== null ||\n row.expires_at !== null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease mutations cannot expose committed fields\",\n });\n }\n });\n\nconst ReleaseRowSchema = z\n .object({\n released: z.boolean(),\n reason: leaseStatus.or(z.literal(\"missing_lease\")).nullable(),\n })\n .strict();\n\nconst LeasePricingContextRowSchema = z\n .object({\n catalog_revision_no: safeInteger,\n plan_id: postgresUuid.nullable(),\n plan_key: z.string().min(1).nullable(),\n rate_card: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if ((row.plan_id === null) !== (row.plan_key === null)) {\n context.addIssue({ code: \"custom\", message: \"lease plan identity fields are inconsistent\" });\n }\n });\n\nexport type LeaseRow = z.infer<typeof LeaseRowSchema>;\nexport type ReleaseRow = z.infer<typeof ReleaseRowSchema>;\nexport type LeasePricingContextRow = z.infer<typeof LeasePricingContextRowSchema>;\n\n/** Repository for lease lifecycle operations (admission control). */\nexport class LeaseRepository {\n constructor(private callproc: CallProc) {}\n\n /** Atomically acquire a lease (hold) — admission control. */\n async createLease(params: {\n userId: string;\n amount: string;\n operationType: string;\n idempotencyKey: string;\n ttlSeconds: number;\n metadata: string;\n feature: string | null;\n measures: string;\n dimensions: string;\n minimumBalance: string | null;\n maxConcurrent: number | null;\n }): Promise<LeaseRow> {\n const rows = await this.callproc(\"create_lease_for_operation\", [\n params.userId,\n params.operationType,\n params.amount,\n params.idempotencyKey,\n `${params.ttlSeconds} seconds`,\n params.metadata,\n params.feature,\n params.measures,\n params.dimensions,\n params.minimumBalance,\n params.maxConcurrent,\n ]);\n const row = safeParse(\n LeaseMutationRpcRowSchema,\n requireRow(rows, \"LeaseRepository.createLease\"),\n \"LeaseRepository.createLease\",\n );\n if (row.error_code !== null) {\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: params.userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error: row.error_code,\n },\n \"LeaseRepository.createLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [params.userId, row.lease_id]),\n \"LeaseRepository.createLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: params.userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.createLease\",\n );\n }\n\n /** Charge the actual cost against a lease and mark it settled. */\n async settleLease(params: {\n userId: string;\n leaseId: string;\n amount: string;\n idempotencyKey: string;\n feature: string | null;\n model: string | null;\n region: string | null;\n measures: string;\n dimensions: string;\n metadata: string;\n }): Promise<DeductionRow> {\n const rows = await this.callproc(\"settle_lease\", [\n params.userId,\n params.leaseId,\n params.amount,\n params.idempotencyKey,\n params.feature,\n params.model,\n params.region,\n params.measures,\n params.dimensions,\n params.metadata,\n ]);\n const row = safeParse(\n SettleLeaseRpcRowSchema,\n requireRow(rows, \"LeaseRepository.settleLease\"),\n \"LeaseRepository.settleLease\",\n );\n if (\n row.error_code === null &&\n !new Decimal(row.settled_amount).equals(quantizeMoney(new Decimal(params.amount)))\n ) {\n throw new StoreError(\n \"LeaseRepository.settleLease: committed amount differs from the request\",\n {\n indeterminate: true,\n },\n );\n }\n const charge =\n row.error_code == null\n ? optionalRecordRow(\n await this.callproc(\"get_credit_operation_details\", [\n params.userId,\n row.ledger_entry_id ?? null,\n params.idempotencyKey,\n ]),\n \"LeaseRepository.settleLease.details\",\n )\n : null;\n return safeParse(\n DeductionRowSchema,\n {\n charge_id: row.charge_id,\n user_id: params.userId,\n entry_id: row.ledger_entry_id,\n amount: row.error_code === null ? row.settled_amount : params.amount,\n allowance_consumed: row.error_code === null ? charge?.allowance_covered : \"0\",\n balance_after: row.error_code === null ? charge?.balance_after : null,\n bucket_breakdown: row.error_code === null ? charge?.bucket_breakdown : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"LeaseRepository.settleLease\",\n );\n }\n\n /** Return the immutable pricing context captured at lease admission. */\n async getPricingContext(userId: string, leaseId: string): Promise<LeasePricingContextRow | null> {\n const rows = await this.callproc(\"get_credit_lease_pricing_context\", [userId, leaseId]);\n const row = optionalRecordRow(rows, \"LeaseRepository.getPricingContext\");\n return row === null\n ? null\n : safeParse(LeasePricingContextRowSchema, row, \"LeaseRepository.getPricingContext\");\n }\n\n /** Release a lease without charging — idempotent. */\n async releaseLease(userId: string, leaseId: string): Promise<ReleaseRow> {\n const rows = await this.callproc(\"release_lease\", [userId, leaseId]);\n const status = safeParse(\n leaseStatus.or(z.literal(\"missing_lease\")),\n requireRow(rows, \"LeaseRepository.releaseLease\"),\n \"LeaseRepository.releaseLease\",\n );\n return safeParse(\n ReleaseRowSchema,\n {\n released: status === \"released\",\n reason: status === \"released\" ? null : status,\n },\n \"LeaseRepository.releaseLease\",\n );\n }\n\n /** Extend an active lease without changing its captured policy snapshot. */\n async renewLease(userId: string, leaseId: string, ttlSeconds: number): Promise<LeaseRow> {\n const rows = await this.callproc(\"renew_lease\", [userId, leaseId, `${ttlSeconds} seconds`]);\n const row = safeParse(\n LeaseMutationRpcRowSchema,\n requireRow(rows, \"LeaseRepository.renewLease\"),\n \"LeaseRepository.renewLease\",\n );\n if (row.error_code !== null) {\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error: row.error_code,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [userId, row.lease_id]),\n \"LeaseRepository.renewLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n\n /** Expire a bounded batch of leases and release their reservations. */\n async expireLeases(limit: number): Promise<number> {\n const rows = await this.callproc(\"expire_leases\", [limit]);\n const row = safeParse(\n z.object({ expired: z.number().int().nonnegative() }).strict(),\n requireRow(rows, \"LeaseRepository.expireLeases\"),\n \"LeaseRepository.expireLeases\",\n );\n return row.expired;\n }\n}\n"]}
|
|
@@ -5,6 +5,7 @@ declare const CreateTeamRowSchema: z.ZodObject<{
|
|
|
5
5
|
name: z.ZodNullable<z.ZodString>;
|
|
6
6
|
team_subject_id: z.ZodNullable<z.ZodString>;
|
|
7
7
|
account_id: z.ZodNullable<z.ZodString>;
|
|
8
|
+
idempotent: z.ZodBoolean;
|
|
8
9
|
error_code: z.ZodNullable<z.ZodString>;
|
|
9
10
|
}, z.core.$strict>;
|
|
10
11
|
declare const TeamBalanceRowSchema: z.ZodObject<{
|
|
@@ -56,7 +57,7 @@ export declare class TeamRepository {
|
|
|
56
57
|
private callproc;
|
|
57
58
|
constructor(callproc: CallProc);
|
|
58
59
|
/** Create a new team with an initial balance. */
|
|
59
|
-
createTeam(ownerSubjectId: string, name: string, initialBalance: string): Promise<CreateTeamRow>;
|
|
60
|
+
createTeam(ownerSubjectId: string, name: string, idempotencyKey: string, initialBalance: string): Promise<CreateTeamRow>;
|
|
60
61
|
/** Fetch a team's balance and member count. Returns null if the team does not exist. */
|
|
61
62
|
getTeamBalance(teamId: string): Promise<TeamBalanceRow | null>;
|
|
62
63
|
/** Add a member to a team with an optional spend cap. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"team.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/team.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;
|
|
1
|
+
{"version":3,"file":"team.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/team.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAiBlE,QAAA,MAAM,mBAAmB;;;;;;;kBA8BrB,CAAC;AAEL,QAAA,MAAM,oBAAoB;;;;;kBAOf,CAAC;AAEZ,QAAA,MAAM,sBAAsB;;;;;;;;kBAMjB,CAAC;AAEZ,QAAA,MAAM,mBAAmB;;;;;;;;;kBAOd,CAAC;AAcZ,QAAA,MAAM,sBAAsB;;;;;;;;kBAwBxB,CAAC;AAEL,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAChE,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC;AAClE,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AACtE,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAChE,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAEtE;;;;;GAKG;AACH,qBAAa,cAAc;IACb,OAAO,CAAC,QAAQ;gBAAR,QAAQ,EAAE,QAAQ;IAEtC,iDAAiD;IAC3C,UAAU,CACd,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,MAAM,EACtB,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC,aAAa,CAAC;IAczB,wFAAwF;IAClF,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC;IAQpE,yDAAyD;IACnD,aAAa,CACjB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,MAAM,GAAG,IAAI,GACtB,OAAO,CAAC,gBAAgB,CAAC;IAiB5B,mEAAmE;IAC7D,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC;IAO9D,4EAA4E;IACtE,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IASxE,gEAAgE;IAC1D,UAAU,CACd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,MAAM,EACtB,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,gBAAgB,CAAC;CAoC7B"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import Decimal from "decimal.js";
|
|
2
|
+
import { Decimal } from "decimal.js";
|
|
3
3
|
import { optionalRecordRow, postgresUuid, requireRow, safeParse, } from "../../../shared/postgres-validation.js";
|
|
4
4
|
import { StoreError } from "../../../errors.js";
|
|
5
|
+
import { quantizeMoney } from "../../../expr.js";
|
|
5
6
|
const decimal = z.union([z.string().min(1), z.number().finite()]);
|
|
6
7
|
const safeInteger = z
|
|
7
8
|
.union([z.number().int(), z.string().regex(/^\d+$/)])
|
|
@@ -14,6 +15,7 @@ const CreateTeamRowSchema = z
|
|
|
14
15
|
name: z.string().min(1).nullable(),
|
|
15
16
|
team_subject_id: postgresUuid.nullable(),
|
|
16
17
|
account_id: postgresUuid.nullable(),
|
|
18
|
+
idempotent: z.boolean(),
|
|
17
19
|
error_code: z.string().min(1).nullable(),
|
|
18
20
|
})
|
|
19
21
|
.strict()
|
|
@@ -31,6 +33,12 @@ const CreateTeamRowSchema = z
|
|
|
31
33
|
message: "failed team creation cannot expose identity fields",
|
|
32
34
|
});
|
|
33
35
|
}
|
|
36
|
+
if (row.error_code !== null && row.idempotent) {
|
|
37
|
+
context.addIssue({
|
|
38
|
+
code: "custom",
|
|
39
|
+
message: "failed team creation cannot be idempotent",
|
|
40
|
+
});
|
|
41
|
+
}
|
|
34
42
|
});
|
|
35
43
|
const TeamBalanceRowSchema = z
|
|
36
44
|
.object({
|
|
@@ -103,8 +111,13 @@ export class TeamRepository {
|
|
|
103
111
|
this.callproc = callproc;
|
|
104
112
|
}
|
|
105
113
|
/** Create a new team with an initial balance. */
|
|
106
|
-
async createTeam(ownerSubjectId, name, initialBalance) {
|
|
107
|
-
const rows = await this.callproc("create_team", [
|
|
114
|
+
async createTeam(ownerSubjectId, name, idempotencyKey, initialBalance) {
|
|
115
|
+
const rows = await this.callproc("create_team", [
|
|
116
|
+
ownerSubjectId,
|
|
117
|
+
name,
|
|
118
|
+
idempotencyKey,
|
|
119
|
+
initialBalance,
|
|
120
|
+
]);
|
|
108
121
|
return safeParse(CreateTeamRowSchema, requireRow(rows, "TeamRepository.createTeam"), "TeamRepository.createTeam");
|
|
109
122
|
}
|
|
110
123
|
/** Fetch a team's balance and member count. Returns null if the team does not exist. */
|
|
@@ -145,7 +158,8 @@ export class TeamRepository {
|
|
|
145
158
|
metadata,
|
|
146
159
|
]);
|
|
147
160
|
const row = safeParse(TeamDeductionRpcRowSchema, requireRow(rows, "TeamRepository.deductTeam"), "TeamRepository.deductTeam");
|
|
148
|
-
if (row.error_code === null &&
|
|
161
|
+
if (row.error_code === null &&
|
|
162
|
+
!new Decimal(row.amount).equals(quantizeMoney(new Decimal(amount)))) {
|
|
149
163
|
throw new StoreError("TeamRepository.deductTeam: committed amount differs from the request", {
|
|
150
164
|
indeterminate: true,
|
|
151
165
|
});
|
|
@@ -154,7 +168,7 @@ export class TeamRepository {
|
|
|
154
168
|
entry_id: row.entry_id,
|
|
155
169
|
team_id: row.team_id,
|
|
156
170
|
user_id: row.subject_id,
|
|
157
|
-
amount,
|
|
171
|
+
amount: row.error_code === null ? row.amount : amount,
|
|
158
172
|
team_balance_after: row.balance_after,
|
|
159
173
|
replayed: row.replayed,
|
|
160
174
|
error: row.error_code,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"team.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/team.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,OAAO,MAAM,YAAY,CAAC;AAEjC,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAC3E,MAAM,WAAW,GAAG,CAAC;KAClB,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAU,CAAC;KAC7D,SAAS,CAAC,MAAM,CAAC;KACjB,MAAM,CAAC,MAAM,CAAC,aAAa,EAAE,yBAAyB,CAAC,CAAC;AAC3D,MAAM,QAAQ,GAAG,CAAC,CAAC,IAAI,CAAC,CA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M,CAAC,CAAC,CAAC;QACzE,OAAO,SAAS,CACd,CAAC,CAAC,OAAO,EAAE,EACX,UAAU,CAAC,IAAI,EAAE,iCAAiC,CAAC,EACnD,iCAAiC,CAClC,CAAC;IACJ,CAAC;IAED,gEAAgE;IAChE,KAAK,CAAC,UAAU,CACd,MAAc,EACd,MAAc,EACd,MAAc,EACd,cAAsB,EACtB,SAAiB,EACjB,QAAgB;QAEhB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,aAAa,EAAE;YAC9C,MAAM;YACN,MAAM;YACN,MAAM;YACN,cAAc;YACd,SAAS;YACT,QAAQ;SACT,CAAC,CAAC;QACH,MAAM,GAAG,GAAG,SAAS,CACnB,yBAAyB,EACzB,UAAU,CAAC,IAAI,EAAE,2BAA2B,CAAC,EAC7C,2BAA2B,CAC5B,CAAC;QACF,IAAI,GAAG,CAAC,UAAU,KAAK,IAAI,IAAI,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;YACvE,MAAM,IAAI,UAAU,CAAC,sEAAsE,EAAE;gBAC3F,aAAa,EAAE,IAAI;aACpB,CAAC,CAAC;QACL,CAAC;QACD,OAAO,SAAS,CACd,sBAAsB,EACtB;YACE,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,OAAO,EAAE,GAAG,CAAC,UAAU;YACvB,MAAM;YACN,kBAAkB,EAAE,GAAG,CAAC,aAAa;YACrC,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,KAAK,EAAE,GAAG,CAAC,UAAU;SACtB,EACD,2BAA2B,CAC5B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport Decimal from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst teamRole = z.enum([\"owner\", \"admin\", \"member\"]);\n\nconst CreateTeamRowSchema = z\n .object({\n team_id: postgresUuid.nullable(),\n name: z.string().min(1).nullable(),\n team_subject_id: postgresUuid.nullable(),\n account_id: postgresUuid.nullable(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n const identifiers = [row.team_id, row.name, row.team_subject_id, row.account_id];\n if (row.error_code === null && identifiers.some((value) => value === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team creation requires identity fields\",\n });\n }\n if (row.error_code !== null && identifiers.some((value) => value !== null)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team creation cannot expose identity fields\",\n });\n }\n });\n\nconst TeamBalanceRowSchema = z\n .object({\n team_id: postgresUuid,\n name: z.string().min(1),\n balance: decimal,\n member_count: safeInteger,\n })\n .strict();\n\nconst AddTeamMemberRowSchema = z\n .object({\n team_id: postgresUuid,\n user_id: postgresUuid,\n role: teamRole,\n })\n .strict();\n\nconst TeamMemberRowSchema = z\n .object({\n user_id: postgresUuid,\n role: teamRole,\n spend_cap: decimal.nullable(),\n total_spent: decimal,\n })\n .strict();\n\nconst TeamDeductionRpcRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n subject_id: postgresUuid,\n amount: decimal,\n balance_after: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict();\n\nconst TeamDeductionRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n user_id: postgresUuid,\n amount: decimal,\n team_balance_after: decimal.nullable(),\n error: z.string().min(1).nullable(),\n replayed: z.boolean(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error === null && (row.entry_id == null || row.team_balance_after === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team deductions require entry and balance fields\",\n });\n }\n if (row.error !== null && (row.entry_id !== null || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team deductions cannot be replayed or committed\",\n });\n }\n });\n\nexport type CreateTeamRow = z.infer<typeof CreateTeamRowSchema>;\nexport type TeamBalanceRow = z.infer<typeof TeamBalanceRowSchema>;\nexport type AddTeamMemberRow = z.infer<typeof AddTeamMemberRowSchema>;\nexport type TeamMemberRow = z.infer<typeof TeamMemberRowSchema>;\nexport type TeamDeductionRow = z.infer<typeof TeamDeductionRowSchema>;\n\n/** Repository for team credit operations.\n *\n * All methods call Postgres RPCs via the callproc function.\n * Returns None when the RPC returns no rows.\n * Returns typed models for successful results.\n */\nexport class TeamRepository {\n constructor(private callproc: CallProc) {}\n\n /** Create a new team with an initial balance. */\n async createTeam(\n ownerSubjectId: string,\n name: string,\n initialBalance: string,\n ): Promise<CreateTeamRow> {\n const rows = await this.callproc(\"create_team\", [ownerSubjectId, name, initialBalance]);\n return safeParse(\n CreateTeamRowSchema,\n requireRow(rows, \"TeamRepository.createTeam\"),\n \"TeamRepository.createTeam\",\n );\n }\n\n /** Fetch a team's balance and member count. Returns null if the team does not exist. */\n async getTeamBalance(teamId: string): Promise<TeamBalanceRow | null> {\n const rows = await this.callproc(\"get_team_balance\", [teamId]);\n const row = optionalRecordRow(rows, \"TeamRepository.getTeamBalance\");\n return row === null\n ? null\n : safeParse(TeamBalanceRowSchema, row, \"TeamRepository.getTeamBalance\");\n }\n\n /** Add a member to a team with an optional spend cap. */\n async addTeamMember(\n teamId: string,\n userId: string,\n role: string,\n spendCap: string | null,\n ): Promise<AddTeamMemberRow> {\n const rows = await this.callproc(\"set_team_member\", [teamId, userId, role, spendCap]);\n const added = safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.addTeamMember\"),\n \"TeamRepository.addTeamMember\",\n );\n if (!added) {\n throw new StoreError(\"TeamRepository.addTeamMember: set_team_member returned false\");\n }\n return safeParse(\n AddTeamMemberRowSchema,\n { team_id: teamId, user_id: userId, role },\n \"TeamRepository.addTeamMember\",\n );\n }\n\n /** List all members of a team with their spend caps and totals. */\n async getTeamMembers(teamId: string): Promise<TeamMemberRow[]> {\n const rows = await this.callproc(\"list_team_members\", [teamId]);\n return (rows ?? []).map((r) =>\n safeParse(TeamMemberRowSchema, r, \"TeamRepository.getTeamMembers\"),\n );\n }\n\n /** Remove a team member, returning false when absent or the final owner. */\n async removeTeamMember(teamId: string, userId: string): Promise<boolean> {\n const rows = await this.callproc(\"remove_team_member\", [teamId, userId]);\n return safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.removeTeamMember\"),\n \"TeamRepository.removeTeamMember\",\n );\n }\n\n /** Deduct credits from a team's balance on behalf of a user. */\n async deductTeam(\n teamId: string,\n userId: string,\n amount: string,\n idempotencyKey: string,\n operation: string,\n metadata: string,\n ): Promise<TeamDeductionRow> {\n const rows = await this.callproc(\"deduct_team\", [\n teamId,\n userId,\n amount,\n idempotencyKey,\n operation,\n metadata,\n ]);\n const row = safeParse(\n TeamDeductionRpcRowSchema,\n requireRow(rows, \"TeamRepository.deductTeam\"),\n \"TeamRepository.deductTeam\",\n );\n if (row.error_code === null && !new Decimal(row.amount).equals(amount)) {\n throw new StoreError(\"TeamRepository.deductTeam: committed amount differs from the request\", {\n indeterminate: true,\n });\n }\n return safeParse(\n TeamDeductionRowSchema,\n {\n entry_id: row.entry_id,\n team_id: row.team_id,\n user_id: row.subject_id,\n amount,\n team_balance_after: row.balance_after,\n replayed: row.replayed,\n error: row.error_code,\n },\n \"TeamRepository.deductTeam\",\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"team.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/team.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAA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,IAAI,CAAC,QAAQ,CAAC,aAAa,EAAE;YAC9C,MAAM;YACN,MAAM;YACN,MAAM;YACN,cAAc;YACd,SAAS;YACT,QAAQ;SACT,CAAC,CAAC;QACH,MAAM,GAAG,GAAG,SAAS,CACnB,yBAAyB,EACzB,UAAU,CAAC,IAAI,EAAE,2BAA2B,CAAC,EAC7C,2BAA2B,CAC5B,CAAC;QACF,IACE,GAAG,CAAC,UAAU,KAAK,IAAI;YACvB,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EACnE,CAAC;YACD,MAAM,IAAI,UAAU,CAAC,sEAAsE,EAAE;gBAC3F,aAAa,EAAE,IAAI;aACpB,CAAC,CAAC;QACL,CAAC;QACD,OAAO,SAAS,CACd,sBAAsB,EACtB;YACE,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,OAAO,EAAE,GAAG,CAAC,UAAU;YACvB,MAAM,EAAE,GAAG,CAAC,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM;YACrD,kBAAkB,EAAE,GAAG,CAAC,aAAa;YACrC,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,KAAK,EAAE,GAAG,CAAC,UAAU;SACtB,EACD,2BAA2B,CAC5B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { Decimal } from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport { quantizeMoney } from \"../../../expr.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst teamRole = z.enum([\"owner\", \"admin\", \"member\"]);\n\nconst CreateTeamRowSchema = z\n .object({\n team_id: postgresUuid.nullable(),\n name: z.string().min(1).nullable(),\n team_subject_id: postgresUuid.nullable(),\n account_id: postgresUuid.nullable(),\n idempotent: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n const identifiers = [row.team_id, row.name, row.team_subject_id, row.account_id];\n if (row.error_code === null && identifiers.some((value) => value === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team creation requires identity fields\",\n });\n }\n if (row.error_code !== null && identifiers.some((value) => value !== null)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team creation cannot expose identity fields\",\n });\n }\n if (row.error_code !== null && row.idempotent) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team creation cannot be idempotent\",\n });\n }\n });\n\nconst TeamBalanceRowSchema = z\n .object({\n team_id: postgresUuid,\n name: z.string().min(1),\n balance: decimal,\n member_count: safeInteger,\n })\n .strict();\n\nconst AddTeamMemberRowSchema = z\n .object({\n team_id: postgresUuid,\n user_id: postgresUuid,\n role: teamRole,\n })\n .strict();\n\nconst TeamMemberRowSchema = z\n .object({\n user_id: postgresUuid,\n role: teamRole,\n spend_cap: decimal.nullable(),\n total_spent: decimal,\n })\n .strict();\n\nconst TeamDeductionRpcRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n subject_id: postgresUuid,\n amount: decimal,\n balance_after: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict();\n\nconst TeamDeductionRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n user_id: postgresUuid,\n amount: decimal,\n team_balance_after: decimal.nullable(),\n error: z.string().min(1).nullable(),\n replayed: z.boolean(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error === null && (row.entry_id == null || row.team_balance_after === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team deductions require entry and balance fields\",\n });\n }\n if (row.error !== null && (row.entry_id !== null || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team deductions cannot be replayed or committed\",\n });\n }\n });\n\nexport type CreateTeamRow = z.infer<typeof CreateTeamRowSchema>;\nexport type TeamBalanceRow = z.infer<typeof TeamBalanceRowSchema>;\nexport type AddTeamMemberRow = z.infer<typeof AddTeamMemberRowSchema>;\nexport type TeamMemberRow = z.infer<typeof TeamMemberRowSchema>;\nexport type TeamDeductionRow = z.infer<typeof TeamDeductionRowSchema>;\n\n/** Repository for team credit operations.\n *\n * All methods call Postgres RPCs via the callproc function.\n * Returns None when the RPC returns no rows.\n * Returns typed models for successful results.\n */\nexport class TeamRepository {\n constructor(private callproc: CallProc) {}\n\n /** Create a new team with an initial balance. */\n async createTeam(\n ownerSubjectId: string,\n name: string,\n idempotencyKey: string,\n initialBalance: string,\n ): Promise<CreateTeamRow> {\n const rows = await this.callproc(\"create_team\", [\n ownerSubjectId,\n name,\n idempotencyKey,\n initialBalance,\n ]);\n return safeParse(\n CreateTeamRowSchema,\n requireRow(rows, \"TeamRepository.createTeam\"),\n \"TeamRepository.createTeam\",\n );\n }\n\n /** Fetch a team's balance and member count. Returns null if the team does not exist. */\n async getTeamBalance(teamId: string): Promise<TeamBalanceRow | null> {\n const rows = await this.callproc(\"get_team_balance\", [teamId]);\n const row = optionalRecordRow(rows, \"TeamRepository.getTeamBalance\");\n return row === null\n ? null\n : safeParse(TeamBalanceRowSchema, row, \"TeamRepository.getTeamBalance\");\n }\n\n /** Add a member to a team with an optional spend cap. */\n async addTeamMember(\n teamId: string,\n userId: string,\n role: string,\n spendCap: string | null,\n ): Promise<AddTeamMemberRow> {\n const rows = await this.callproc(\"set_team_member\", [teamId, userId, role, spendCap]);\n const added = safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.addTeamMember\"),\n \"TeamRepository.addTeamMember\",\n );\n if (!added) {\n throw new StoreError(\"TeamRepository.addTeamMember: set_team_member returned false\");\n }\n return safeParse(\n AddTeamMemberRowSchema,\n { team_id: teamId, user_id: userId, role },\n \"TeamRepository.addTeamMember\",\n );\n }\n\n /** List all members of a team with their spend caps and totals. */\n async getTeamMembers(teamId: string): Promise<TeamMemberRow[]> {\n const rows = await this.callproc(\"list_team_members\", [teamId]);\n return (rows ?? []).map((r) =>\n safeParse(TeamMemberRowSchema, r, \"TeamRepository.getTeamMembers\"),\n );\n }\n\n /** Remove a team member, returning false when absent or the final owner. */\n async removeTeamMember(teamId: string, userId: string): Promise<boolean> {\n const rows = await this.callproc(\"remove_team_member\", [teamId, userId]);\n return safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.removeTeamMember\"),\n \"TeamRepository.removeTeamMember\",\n );\n }\n\n /** Deduct credits from a team's balance on behalf of a user. */\n async deductTeam(\n teamId: string,\n userId: string,\n amount: string,\n idempotencyKey: string,\n operation: string,\n metadata: string,\n ): Promise<TeamDeductionRow> {\n const rows = await this.callproc(\"deduct_team\", [\n teamId,\n userId,\n amount,\n idempotencyKey,\n operation,\n metadata,\n ]);\n const row = safeParse(\n TeamDeductionRpcRowSchema,\n requireRow(rows, \"TeamRepository.deductTeam\"),\n \"TeamRepository.deductTeam\",\n );\n if (\n row.error_code === null &&\n !new Decimal(row.amount).equals(quantizeMoney(new Decimal(amount)))\n ) {\n throw new StoreError(\"TeamRepository.deductTeam: committed amount differs from the request\", {\n indeterminate: true,\n });\n }\n return safeParse(\n TeamDeductionRowSchema,\n {\n entry_id: row.entry_id,\n team_id: row.team_id,\n user_id: row.subject_id,\n amount: row.error_code === null ? row.amount : amount,\n team_balance_after: row.balance_after,\n replayed: row.replayed,\n error: row.error_code,\n },\n \"TeamRepository.deductTeam\",\n );\n }\n}\n"]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import Decimal from "decimal.js";
|
|
1
|
+
import { Decimal } from "decimal.js";
|
|
2
2
|
import { type BursarConfigData, type CatalogRollout } from "../../config.js";
|
|
3
3
|
import { type PostgresConnectionOptions, type PostgresPool, type PostgresPoolConstructor } from "../../shared/postgres-client.js";
|
|
4
4
|
import type { AddCreditsResult, AddTeamMemberResult, AggregateStats, AllowanceResult, AvailableResult, BalanceResult, CheckFeatureResult, CreateTeamResult, DailySpendRow, DeductionResult, DeductWithAllowanceOptions, ExecuteGrantProgramRequest, GrantProgramAwardResult, GetUserPlanResult, LeaseResult, LeasePricingContext, ListLedgerEntriesOptions, ListUsageChargesOptions, ListQuotaEventsOptions, ListUsageEntriesOptions, PlanMigrationBatchResult, PlanMigrationStartResult, QuotaEvent, QuotaState, LedgerPage, UsageChargePage, UsageRecordResult, CatalogRevisionSummary, CatalogRevision, RefundResult, RevokeCreditsResult, ReleaseResult, SetUserPlanResult, SpendByModelRow, SpendByUserRow, SweepResult, TeamBalanceResult, TeamDeductionResult, TeamMember, TeamRole, BucketBalancesResult, TopUserRow, UnsetUserPlanResult, LedgerEntry } from "../types/index.js";
|
|
5
5
|
import type { AddCreditsOptions, DeductTeamOptions, RefundCreditsOptions } from "../service-types.js";
|
|
6
6
|
import { CreditStore } from "../store.js";
|
|
7
|
-
import type { CreateLeaseOptions, SettleLeaseOptions } from "../store.js";
|
|
7
|
+
import type { CreateLeaseOptions, CreateTeamOptions, SettleLeaseOptions } from "../store.js";
|
|
8
8
|
export type PgPool = PostgresPool;
|
|
9
9
|
export type PgPoolConstructor = PostgresPoolConstructor;
|
|
10
10
|
/** Construction options for the PostgreSQL credit store. */
|
|
@@ -85,7 +85,7 @@ export declare class PostgresStore extends CreditStore {
|
|
|
85
85
|
listLedgerEntries(userId: string, options?: ListLedgerEntriesOptions): Promise<LedgerPage>;
|
|
86
86
|
listUsageEntries(userId: string, options?: ListUsageEntriesOptions): Promise<LedgerPage>;
|
|
87
87
|
listUsageCharges(userId: string, options?: ListUsageChargesOptions): Promise<UsageChargePage>;
|
|
88
|
-
createTeam(ownerSubjectId: string, name: string,
|
|
88
|
+
createTeam(ownerSubjectId: string, name: string, options: CreateTeamOptions): Promise<CreateTeamResult>;
|
|
89
89
|
getTeamBalance(teamId: string): Promise<TeamBalanceResult | null>;
|
|
90
90
|
addTeamMember(teamId: string, userId: string, role?: TeamRole, spendCap?: Decimal | null): Promise<AddTeamMemberResult>;
|
|
91
91
|
getTeamMembers(teamId: string): Promise<TeamMember[]>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/credits/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/credits/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,EAML,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAEL,KAAK,yBAAyB,EAC9B,KAAK,YAAY,EACjB,KAAK,uBAAuB,EAC7B,MAAM,iCAAiC,CAAC;AACzC,OAAO,KAAK,EACV,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,eAAe,EACf,aAAa,EACb,kBAAkB,EAClB,gBAAgB,EAChB,aAAa,EACb,eAAe,EACf,0BAA0B,EAC1B,0BAA0B,EAC1B,uBAAuB,EACvB,iBAAiB,EACjB,WAAW,EACX,mBAAmB,EACnB,wBAAwB,EACxB,uBAAuB,EACvB,sBAAsB,EACtB,uBAAuB,EACvB,wBAAwB,EACxB,wBAAwB,EACxB,UAAU,EACV,UAAU,EACV,UAAU,EACV,eAAe,EACf,iBAAiB,EACjB,sBAAsB,EACtB,eAAe,EACf,YAAY,EACZ,mBAAmB,EACnB,aAAa,EACb,iBAAiB,EACjB,eAAe,EACf,cAAc,EACd,WAAW,EACX,iBAAiB,EACjB,mBAAmB,EACnB,UAAU,EACV,QAAQ,EAER,oBA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AO,EACf,OAAO,EAAE,iBAAiB,GACzB,OAAO,CAAC,mBAAmB,CAAC;IAsCzB,mBAAmB,CAAC,MAAM,UAAQ,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,KAAK,SAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IAYvF,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAYhE,mBAAmB,CACvB,OAAO,EAAE,0BAA0B,GAClC,OAAO,CAAC,uBAAuB,EAAE,CAAC;CAiCtC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import Decimal from "decimal.js";
|
|
1
|
+
import { Decimal } from "decimal.js";
|
|
2
2
|
import { StoreClosedError, StoreError } from "../../errors.js";
|
|
3
3
|
import { canonicalBursarConfigDict, canonicalCatalogRolloutDict, loadCatalogRollout, loadConfigFromDict, validateCatalogRollout, } from "../../config.js";
|
|
4
4
|
import { PostgresClient, } from "../../shared/postgres-client.js";
|
|
@@ -738,13 +738,16 @@ export class PostgresStore extends CreditStore {
|
|
|
738
738
|
nextCursor: hasMore && last ? { eventAt: last.eventAt, usageId: last.usageId } : null,
|
|
739
739
|
};
|
|
740
740
|
}
|
|
741
|
-
async createTeam(ownerSubjectId, name,
|
|
742
|
-
const
|
|
741
|
+
async createTeam(ownerSubjectId, name, options) {
|
|
742
|
+
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
743
|
+
const initialBalance = options?.initialBalance ?? ZERO;
|
|
744
|
+
const row = await this.teamRepo.createTeam(ownerSubjectId, name, idempotencyKey, decParam(initialBalance));
|
|
743
745
|
if (row.error_code !== null)
|
|
744
746
|
throw new StoreError(row.error_code);
|
|
745
747
|
return {
|
|
746
748
|
teamId: requireText(row.team_id, "create_team"),
|
|
747
749
|
name: requireText(row.name, "create_team"),
|
|
750
|
+
idempotent: row.idempotent,
|
|
748
751
|
};
|
|
749
752
|
}
|
|
750
753
|
async getTeamBalance(teamId) {
|