@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
|
@@ -13,7 +13,39 @@ const BillingEventRowSchema = z
|
|
|
13
13
|
event_id: postgresUuid.nullable(),
|
|
14
14
|
claim_token: postgresUuid.nullable(),
|
|
15
15
|
})
|
|
16
|
-
.strict()
|
|
16
|
+
.strict()
|
|
17
|
+
.superRefine((row, ctx) => {
|
|
18
|
+
if (row.status === "claimed") {
|
|
19
|
+
if (row.event_id === null || row.claim_token === null) {
|
|
20
|
+
ctx.addIssue({
|
|
21
|
+
code: z.ZodIssueCode.custom,
|
|
22
|
+
message: "claimed billing event requires event_id and claim_token",
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
if (row.claim_token !== null) {
|
|
28
|
+
ctx.addIssue({
|
|
29
|
+
code: z.ZodIssueCode.custom,
|
|
30
|
+
message: "unclaimed billing event cannot expose a claim_token",
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
if (row.status === "invalid_request") {
|
|
34
|
+
if (row.event_id !== null) {
|
|
35
|
+
ctx.addIssue({
|
|
36
|
+
code: z.ZodIssueCode.custom,
|
|
37
|
+
message: "invalid billing event request cannot identify a stored event",
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (row.event_id === null) {
|
|
43
|
+
ctx.addIssue({
|
|
44
|
+
code: z.ZodIssueCode.custom,
|
|
45
|
+
message: "stored billing event outcome requires event_id",
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
});
|
|
17
49
|
function booleanResult(rows, key, context) {
|
|
18
50
|
return requireResultField(rows, key, pgBoolean, context);
|
|
19
51
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/event.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EACL,SAAS,EACT,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,qBAAqB,GAAG,CAAC;KAC5B,MAAM,CAAC;IACN,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC;QACb,SAAS;QACT,WAAW;QACX,MAAM;QACN,iBAAiB;QACjB,sBAAsB;QACtB,sBAAsB;KACvB,CAAC;IACF,QAAQ,EAAE,YAAY,CAAC,QAAQ,EAAE;IACjC,WAAW,EAAE,YAAY,CAAC,QAAQ,EAAE;CACrC,CAAC;KACD,MAAM,EAAE,CAAC;
|
|
1
|
+
{"version":3,"file":"event.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/event.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EACL,SAAS,EACT,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,qBAAqB,GAAG,CAAC;KAC5B,MAAM,CAAC;IACN,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC;QACb,SAAS;QACT,WAAW;QACX,MAAM;QACN,iBAAiB;QACjB,sBAAsB;QACtB,sBAAsB;KACvB,CAAC;IACF,QAAQ,EAAE,YAAY,CAAC,QAAQ,EAAE;IACjC,WAAW,EAAE,YAAY,CAAC,QAAQ,EAAE;CACrC,CAAC;KACD,MAAM,EAAE;KACR,WAAW,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;IACxB,IAAI,GAAG,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;QAC7B,IAAI,GAAG,CAAC,QAAQ,KAAK,IAAI,IAAI,GAAG,CAAC,WAAW,KAAK,IAAI,EAAE,CAAC;YACtD,GAAG,CAAC,QAAQ,CAAC;gBACX,IAAI,EAAE,CAAC,CAAC,YAAY,CAAC,MAAM;gBAC3B,OAAO,EAAE,yDAAyD;aACnE,CAAC,CAAC;QACL,CAAC;QACD,OAAO;IACT,CAAC;IACD,IAAI,GAAG,CAAC,WAAW,KAAK,IAAI,EA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AE,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,WAAW,EAAE,GAAG,CAAC,WAAW,EAAE,EAC5E,8BAA8B,EAC9B,EAAE,aAAa,EAAE,IAAI,EAAE,CACxB,CAAC;IACJ,CAAC;IAED,yCAAyC;IACzC,KAAK,CAAC,QAAQ,CAAC,QAAgB,EAAE,OAAe,EAAE,UAAkB;QAClE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,qEAAqE,EACrE,CAAC,QAAQ,EAAE,OAAO,EAAE,UAAU,CAAC,CAChC,CAAC;QACF,OAAO,aAAa,CAAC,IAAI,EAAE,WAAW,EAAE,iCAAiC,CAAC,CAAC;IAC7E,CAAC;IAED,sCAAsC;IACtC,KAAK,CAAC,IAAI,CACR,QAAgB,EAChB,OAAe,EACf,UAAkB,EAClB,KAAc;QAEd,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,kEAAkE,EAClE,CAAC,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,KAAK,IAAI,IAAI,CAAC,CAC/C,CAAC;QACF,OAAO,aAAa,CAAC,IAAI,EAAE,QAAQ,EAAE,6BAA6B,CAAC,CAAC;IACtE,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport {\n pgBoolean,\n postgresUuid,\n requireRecordRow,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst BillingEventRowSchema = z\n .object({\n status: z.enum([\n \"claimed\",\n \"duplicate\",\n \"busy\",\n \"invalid_request\",\n \"idempotency_conflict\",\n \"max_retries_exceeded\",\n ]),\n event_id: postgresUuid.nullable(),\n claim_token: postgresUuid.nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.status === \"claimed\") {\n if (row.event_id === null || row.claim_token === null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"claimed billing event requires event_id and claim_token\",\n });\n }\n return;\n }\n if (row.claim_token !== null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"unclaimed billing event cannot expose a claim_token\",\n });\n }\n if (row.status === \"invalid_request\") {\n if (row.event_id !== null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"invalid billing event request cannot identify a stored event\",\n });\n }\n return;\n }\n if (row.event_id === null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"stored billing event outcome requires event_id\",\n });\n }\n });\n\nexport type BillingEventRow = z.infer<typeof BillingEventRowSchema>;\n\nfunction booleanResult(rows: unknown[], key: string, context: string): boolean {\n return requireResultField(rows, key, pgBoolean, context);\n}\n\n/** Repository for billing event lifecycle operations. */\nexport class BillingEventRepository {\n constructor(private query: QueryFn) {}\n\n /** Claim a billing event for processing (idempotent claim). */\n async claim(\n provider: string,\n eventId: string,\n eventType: string,\n metadata: string,\n ): Promise<BillingEventRow> {\n const rows = await this.query(\"SELECT * FROM bursar.claim_billing_event($1, $2, $3, $4)\", [\n provider,\n eventId,\n eventType,\n metadata,\n ]);\n const row = requireRecordRow(rows, \"BillingEventRepository.claim\");\n return safeParse(\n BillingEventRowSchema,\n { event_id: row.event_id, status: row.result, claim_token: row.claim_token },\n \"BillingEventRepository.claim\",\n { indeterminate: true },\n );\n }\n\n /** Mark a billing event as completed. */\n async complete(provider: string, eventId: string, claimToken: string): Promise<boolean> {\n const rows = await this.query(\n \"SELECT bursar.complete_billing_event($1, $2, $3::uuid) AS completed\",\n [provider, eventId, claimToken],\n );\n return booleanResult(rows, \"completed\", \"BillingEventRepository.complete\");\n }\n\n /** Mark a billing event as failed. */\n async fail(\n provider: string,\n eventId: string,\n claimToken: string,\n error?: string,\n ): Promise<boolean> {\n const rows = await this.query(\n \"SELECT bursar.fail_billing_event($1, $2, $3::uuid, $4) AS failed\",\n [provider, eventId, claimToken, error ?? null],\n );\n return booleanResult(rows, \"failed\", \"BillingEventRepository.fail\");\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"offer.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/offer.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"offer.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/offer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAGrC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAgDjE,UAAU,mBAAmB;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,KAAK,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;IAC5C,aAAa,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,MAAM,eAAe,GAAG,mBAAmB,GAC/C,CACI;IACE,YAAY,EAAE,IAAI,CAAC;IACnB,WAAW,EAAE,IAAI,CAAC;IAClB,iBAAiB,EAAE,KAAK,CAAC;CAC1B,GACD;IACE,YAAY,EAAE,OAAO,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,EAAE,OAAO,CAAC;CAC5B,CACJ,CAAC;AAEJ,+CAA+C;AAC/C,qBAAa,sBAAsB;IACrB,OAAO,CAAC,QAAQ,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAErC,cAAc,CAClB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,GAAG,IAAI,EACtB,SAAS,EAAE,MAAM,GAAG,IAAI,GACvB,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;IAK5B,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;YAI7E,OAAO;CAkGt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"zod\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport { postgresUuid, safeParse, unwrapJsonb } from \"../../../shared/postgres-validation.js\";\n\nconst PositiveDecimalSchema = z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .transform((value) => new Decimal(value))\n .refine((value) => value.isFinite() && value.gt(0), \"expected a finite positive decimal\");\n\nconst CatalogOfferRowSchema = z\n .object({\n id: postgresUuid,\n catalog_revision_id: postgresUuid,\n offer_key: z.string().min(1),\n plan_key: z.string().min(1),\n billing_unit: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n billing_count: z.number().int().positive(),\n cycle_grant_amount: PositiveDecimalSchema.nullable(),\n cycle_grant_bucket_key: z.string().min(1).nullable(),\n cycle_grant_renewal: z.enum([\"replace_previous\", \"accumulate\"]).nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n const grantFields = [\n row.cycle_grant_amount,\n row.cycle_grant_bucket_key,\n row.cycle_grant_renewal,\n ];\n if (\n grantFields.some((value) => value !== null) &&\n grantFields.some((value) => value === null)\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"cycle grant fields must either all be set or all be null\",\n });\n }\n });\n\nconst OfferContextRowSchema = z\n .object({\n offer_key: z.string().min(1),\n plan_id: postgresUuid,\n plan_key: z.string().min(1),\n billing_unit: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n billing_count: z.number().int().positive(),\n })\n .strict();\n\ninterface BillingOfferRowBase {\n id: string;\n planId: string;\n offerKey: string;\n plan: string;\n interval: \"day\" | \"week\" | \"month\" | \"year\";\n intervalCount: number;\n}\n\nexport type BillingOfferRow = BillingOfferRowBase &\n (\n | {\n grantCredits: null;\n grantBucket: null;\n grantReplacePrior: false;\n }\n | {\n grantCredits: Decimal;\n grantBucket: string;\n grantReplacePrior: boolean;\n }\n );\n\n/** Repository for billing offer resolution. */\nexport class BillingOfferRepository {\n constructor(private readonly query: QueryFn) {}\n\n async resolveByPrice(\n provider: string,\n priceId: string | null,\n productId: string | null,\n ): Promise<BillingOfferRow | null> {\n const lookupType = priceId !== null ? \"price_id\" : \"product_id\";\n return this.resolve(provider, lookupType, priceId ?? productId, \"resolveByPrice\");\n }\n\n async resolveByLookup(provider: string, lookupKey: string): Promise<BillingOfferRow | null> {\n return this.resolve(provider, \"external_id\", lookupKey, \"resolveByLookup\");\n }\n\n private async resolve(\n provider: string,\n lookupType: \"price_id\" | \"product_id\" | \"external_id\",\n lookupValue: string | null,\n operation: string,\n ): Promise<BillingOfferRow | null> {\n if (!provider.trim()) throw new TypeError(\"provider must not be empty\");\n if (!lookupValue?.trim()) return null;\n\n const context = `BillingOfferRepository.${operation}`;\n const rows = await this.query(\"SELECT * FROM bursar.resolve_catalog_offer($1, $2, $3)\", [\n provider,\n lookupType,\n lookupValue,\n ]);\n if (rows.length > 1) {\n throw new StoreError(`${context}: expected at most one offer`, {\n details: { rowCount: rows.length },\n });\n }\n const raw = unwrapJsonb(rows);\n if (raw?.id == null) return null;\n const offer = safeParse(\n CatalogOfferRowSchema,\n {\n id: raw.id,\n catalog_revision_id: raw.catalog_revision_id,\n offer_key: raw.offer_key,\n plan_key: raw.plan_key,\n billing_unit: raw.billing_unit,\n billing_count: raw.billing_count,\n cycle_grant_amount: raw.cycle_grant_amount,\n cycle_grant_bucket_key: raw.cycle_grant_bucket_key,\n cycle_grant_renewal: raw.cycle_grant_renewal,\n },\n context,\n );\n\n const contextRows = await this.query(\n \"SELECT * FROM bursar.get_catalog_offer_context($1::uuid, $2::uuid)\",\n [offer.id, offer.catalog_revision_id],\n );\n if (contextRows.length !== 1) {\n throw new StoreError(`${context}: catalog plan context is missing`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n const rawContext = contextRows[0] as Record<string, unknown>;\n const offerContext = safeParse(\n OfferContextRowSchema,\n {\n offer_key: rawContext.offer_key,\n plan_id: rawContext.plan_id,\n plan_key: rawContext.plan_key,\n billing_unit: rawContext.billing_unit,\n billing_count: rawContext.billing_count,\n },\n `${context}.context`,\n );\n if (\n offerContext.offer_key !== offer.offer_key ||\n offerContext.plan_key !== offer.plan_key ||\n offerContext.billing_unit !== offer.billing_unit ||\n offerContext.billing_count !== offer.billing_count\n ) {\n throw new StoreError(`${context}: catalog plan context does not match the resolved offer`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n\n const resolvedOffer: BillingOfferRowBase = {\n id: offer.id,\n planId: offerContext.plan_id,\n offerKey: offer.offer_key,\n plan: offer.plan_key,\n interval: offer.billing_unit,\n intervalCount: offer.billing_count,\n };\n if (offer.cycle_grant_amount === null) {\n return {\n ...resolvedOffer,\n grantCredits: null,\n grantBucket: null,\n grantReplacePrior: false,\n };\n }\n if (offer.cycle_grant_bucket_key === null || offer.cycle_grant_renewal === null) {\n throw new StoreError(`${context}: resolved offer has an incomplete cycle grant`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n return {\n ...resolvedOffer,\n grantCredits: offer.cycle_grant_amount,\n grantBucket: offer.cycle_grant_bucket_key,\n grantReplacePrior: offer.cycle_grant_renewal === \"replace_previous\",\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"offer.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/offer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,wCAAwC,CAAC;AAE9F,MAAM,qBAAqB,GAAG,CAAC;KAC5B,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC;KACtD,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AAE,KAAK,CAAC,aAAa;SACnC,CAAC;QACF,IAAI,KAAK,CAAC,kBAAkB,KAAK,IAAI,EAAE,CAAC;YACtC,OAAO;gBACL,GAAG,aAAa;gBAChB,YAAY,EAAE,IAAI;gBAClB,WAAW,EAAE,IAAI;gBACjB,iBAAiB,EAAE,KAAK;aACzB,CAAC;QACJ,CAAC;QACD,IAAI,KAAK,CAAC,sBAAsB,KAAK,IAAI,IAAI,KAAK,CAAC,mBAAmB,KAAK,IAAI,EAAE,CAAC;YAChF,MAAM,IAAI,UAAU,CAAC,GAAG,OAAO,gDAAgD,EAAE;gBAC/E,OAAO,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,EAAE,iBAAiB,EAAE,KAAK,CAAC,mBAAmB,EAAE;aAC7E,CAAC,CAAC;QACL,CAAC;QACD,OAAO;YACL,GAAG,aAAa;YAChB,YAAY,EAAE,KAAK,CAAC,kBAAkB;YACtC,WAAW,EAAE,KAAK,CAAC,sBAAsB;YACzC,iBAAiB,EAAE,KAAK,CAAC,mBAAmB,KAAK,kBAAkB;SACpE,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { z } from \"zod\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport { postgresUuid, safeParse, unwrapJsonb } from \"../../../shared/postgres-validation.js\";\n\nconst PositiveDecimalSchema = z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .transform((value) => new Decimal(value))\n .refine((value) => value.isFinite() && value.gt(0), \"expected a finite positive decimal\");\n\nconst CatalogOfferRowSchema = z\n .object({\n id: postgresUuid,\n catalog_revision_id: postgresUuid,\n offer_key: z.string().min(1),\n plan_key: z.string().min(1),\n billing_unit: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n billing_count: z.number().int().positive(),\n cycle_grant_amount: PositiveDecimalSchema.nullable(),\n cycle_grant_bucket_key: z.string().min(1).nullable(),\n cycle_grant_renewal: z.enum([\"replace_previous\", \"accumulate\"]).nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n const grantFields = [\n row.cycle_grant_amount,\n row.cycle_grant_bucket_key,\n row.cycle_grant_renewal,\n ];\n if (\n grantFields.some((value) => value !== null) &&\n grantFields.some((value) => value === null)\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"cycle grant fields must either all be set or all be null\",\n });\n }\n });\n\nconst OfferContextRowSchema = z\n .object({\n offer_key: z.string().min(1),\n plan_id: postgresUuid,\n plan_key: z.string().min(1),\n billing_unit: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n billing_count: z.number().int().positive(),\n })\n .strict();\n\ninterface BillingOfferRowBase {\n id: string;\n planId: string;\n offerKey: string;\n plan: string;\n interval: \"day\" | \"week\" | \"month\" | \"year\";\n intervalCount: number;\n}\n\nexport type BillingOfferRow = BillingOfferRowBase &\n (\n | {\n grantCredits: null;\n grantBucket: null;\n grantReplacePrior: false;\n }\n | {\n grantCredits: Decimal;\n grantBucket: string;\n grantReplacePrior: boolean;\n }\n );\n\n/** Repository for billing offer resolution. */\nexport class BillingOfferRepository {\n constructor(private readonly query: QueryFn) {}\n\n async resolveByPrice(\n provider: string,\n priceId: string | null,\n productId: string | null,\n ): Promise<BillingOfferRow | null> {\n const lookupType = priceId !== null ? \"price_id\" : \"product_id\";\n return this.resolve(provider, lookupType, priceId ?? productId, \"resolveByPrice\");\n }\n\n async resolveByLookup(provider: string, lookupKey: string): Promise<BillingOfferRow | null> {\n return this.resolve(provider, \"external_id\", lookupKey, \"resolveByLookup\");\n }\n\n private async resolve(\n provider: string,\n lookupType: \"price_id\" | \"product_id\" | \"external_id\",\n lookupValue: string | null,\n operation: string,\n ): Promise<BillingOfferRow | null> {\n if (!provider.trim()) throw new TypeError(\"provider must not be empty\");\n if (!lookupValue?.trim()) return null;\n\n const context = `BillingOfferRepository.${operation}`;\n const rows = await this.query(\"SELECT * FROM bursar.resolve_catalog_offer($1, $2, $3)\", [\n provider,\n lookupType,\n lookupValue,\n ]);\n if (rows.length > 1) {\n throw new StoreError(`${context}: expected at most one offer`, {\n details: { rowCount: rows.length },\n });\n }\n const raw = unwrapJsonb(rows);\n if (raw?.id == null) return null;\n const offer = safeParse(\n CatalogOfferRowSchema,\n {\n id: raw.id,\n catalog_revision_id: raw.catalog_revision_id,\n offer_key: raw.offer_key,\n plan_key: raw.plan_key,\n billing_unit: raw.billing_unit,\n billing_count: raw.billing_count,\n cycle_grant_amount: raw.cycle_grant_amount,\n cycle_grant_bucket_key: raw.cycle_grant_bucket_key,\n cycle_grant_renewal: raw.cycle_grant_renewal,\n },\n context,\n );\n\n const contextRows = await this.query(\n \"SELECT * FROM bursar.get_catalog_offer_context($1::uuid, $2::uuid)\",\n [offer.id, offer.catalog_revision_id],\n );\n if (contextRows.length !== 1) {\n throw new StoreError(`${context}: catalog plan context is missing`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n const rawContext = contextRows[0] as Record<string, unknown>;\n const offerContext = safeParse(\n OfferContextRowSchema,\n {\n offer_key: rawContext.offer_key,\n plan_id: rawContext.plan_id,\n plan_key: rawContext.plan_key,\n billing_unit: rawContext.billing_unit,\n billing_count: rawContext.billing_count,\n },\n `${context}.context`,\n );\n if (\n offerContext.offer_key !== offer.offer_key ||\n offerContext.plan_key !== offer.plan_key ||\n offerContext.billing_unit !== offer.billing_unit ||\n offerContext.billing_count !== offer.billing_count\n ) {\n throw new StoreError(`${context}: catalog plan context does not match the resolved offer`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n\n const resolvedOffer: BillingOfferRowBase = {\n id: offer.id,\n planId: offerContext.plan_id,\n offerKey: offer.offer_key,\n plan: offer.plan_key,\n interval: offer.billing_unit,\n intervalCount: offer.billing_count,\n };\n if (offer.cycle_grant_amount === null) {\n return {\n ...resolvedOffer,\n grantCredits: null,\n grantBucket: null,\n grantReplacePrior: false,\n };\n }\n if (offer.cycle_grant_bucket_key === null || offer.cycle_grant_renewal === null) {\n throw new StoreError(`${context}: resolved offer has an incomplete cycle grant`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n return {\n ...resolvedOffer,\n grantCredits: offer.cycle_grant_amount,\n grantBucket: offer.cycle_grant_bucket_key,\n grantReplacePrior: offer.cycle_grant_renewal === \"replace_previous\",\n };\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"topup.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/topup.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"topup.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/topup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAajE,QAAA,MAAM,qBAAqB;;;;;;;;;;kBAuBvB,CAAC;AAEL,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAEpE,+CAA+C;AAC/C,qBAAa,sBAAsB;IACrB,OAAO,CAAC,QAAQ,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAErC,cAAc,CAClB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,GAAG,IAAI,EACtB,SAAS,EAAE,MAAM,GAAG,IAAI,GACvB,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;IAK5B,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;YAI7E,OAAO;CAsCtB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"topup.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/topup.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"topup.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/topup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,wCAAwC,CAAC;AAE9F,MAAM,qBAAqB,GAAG,CAAC;KAC5B,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC;KACtD,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC;KACxC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,EAAE,IAAI,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,oCAAoC,CAAC,CAAC;AAE5F,MAAM,oBAAoB,GAAG,CAAC;KAC3B,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;KACzE,SAAS,CAAC,MAAM,CAAC;KACjB,MAAM,CAAC,MAAM,CAAC,aAAa,EAAE,2DAA2D,CAAC,CAAC;AAE7F,MAAM,qBAAqB,GAAG,CAAC;KAC5B,MAAM,CAAC;IACN,EAAE,EAAE,YAAY;IAChB,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;I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,UAAU;YAC1B,YAAY,EAAE,GAAG,CAAC,YAAY;YAC9B,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,YAAY,EAAE,GAAG,CAAC,YAAY;YAC9B,YAAY,EAAE,GAAG,CAAC,YAAY;YAC9B,gBAAgB,EAAE,GAAG,CAAC,gBAAgB;SACvC,EACD,OAAO,CACR,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { z } from \"zod\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport { postgresUuid, safeParse, unwrapJsonb } from \"../../../shared/postgres-validation.js\";\n\nconst PositiveDecimalSchema = z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .transform((value) => new Decimal(value))\n .refine((value) => value.isFinite() && value.gt(0), \"expected a finite positive decimal\");\n\nconst SafeMinorUnitsSchema = z\n .union([z.string().regex(/^\\d+$/), z.number().int().nonnegative().safe()])\n .transform(Number)\n .refine(Number.isSafeInteger, \"minor-unit amount exceeds JavaScript's safe integer range\");\n\nconst BillingTopupRowSchema = z\n .object({\n id: postgresUuid,\n topup_key: z.string().min(1),\n credits_per_unit: PositiveDecimalSchema,\n bucket_key: z.string().min(1),\n amount_minor: SafeMinorUnitsSchema,\n currency: z.string().regex(/^[A-Z]{3}$/),\n min_quantity: z.number().int().positive(),\n max_quantity: z.number().int().positive(),\n default_quantity: z.number().int().positive(),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.max_quantity < row.min_quantity) {\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: \"max_quantity is below min_quantity\" });\n }\n if (row.default_quantity < row.min_quantity || row.default_quantity > row.max_quantity) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"default_quantity is outside the configured range\",\n });\n }\n });\n\nexport type BillingTopupRow = z.infer<typeof BillingTopupRowSchema>;\n\n/** Repository for credit top-up resolution. */\nexport class BillingTopupRepository {\n constructor(private readonly query: QueryFn) {}\n\n async resolveByPrice(\n provider: string,\n priceId: string | null,\n productId: string | null,\n ): Promise<BillingTopupRow | null> {\n const lookupType = priceId !== null ? \"price_id\" : \"product_id\";\n return this.resolve(provider, lookupType, priceId ?? productId, \"resolveByPrice\");\n }\n\n async resolveByLookup(provider: string, lookupKey: string): Promise<BillingTopupRow | null> {\n return this.resolve(provider, \"external_id\", lookupKey, \"resolveByLookup\");\n }\n\n private async resolve(\n provider: string,\n lookupType: \"price_id\" | \"product_id\" | \"external_id\",\n lookupValue: string | null,\n operation: string,\n ): Promise<BillingTopupRow | null> {\n if (!provider.trim()) throw new TypeError(\"provider must not be empty\");\n if (!lookupValue?.trim()) return null;\n\n const context = `BillingTopupRepository.${operation}`;\n const rows = await this.query(\"SELECT * FROM bursar.resolve_catalog_topup($1, $2, $3)\", [\n provider,\n lookupType,\n lookupValue,\n ]);\n if (rows.length > 1) {\n throw new StoreError(`${context}: expected at most one top-up`, {\n details: { rowCount: rows.length },\n });\n }\n const raw = unwrapJsonb(rows);\n if (raw?.id == null) return null;\n return safeParse(\n BillingTopupRowSchema,\n {\n id: raw.id,\n topup_key: raw.topup_key,\n credits_per_unit: raw.credits_per_unit,\n bucket_key: raw.bucket_key,\n amount_minor: raw.amount_minor,\n currency: raw.currency,\n min_quantity: raw.min_quantity,\n max_quantity: raw.max_quantity,\n default_quantity: raw.default_quantity,\n },\n context,\n );\n }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import Decimal from "decimal.js";
|
|
1
|
+
import { Decimal } from "decimal.js";
|
|
2
2
|
import type { BillingAutoRechargeAttempt, BillingAutoRechargeProfile, BillingCreditPostingResult, BillingCustomerRecord, BillingEventClaim, BillingOfferResult, BillingPaymentRecord, BillingPreferences, BillingSubscriptionChange, BillingSubscriptionChangeInput, BillingSubscriptionState, CheckoutIntent, BillingTopupResult } from "../types/index.js";
|
|
3
3
|
import { BillingStore } from "../billing-store.js";
|
|
4
4
|
import type { AutoRechargeAttemptClaim, AutoRechargeAttemptUpdate, AutoRechargeProviderPaymentUpdate, BillingCreditGrantCreate, BillingDisputeUpsert, BillingInvoiceUpsert, BillingPaymentUpsert, BillingRefundUpsert, BillingSubscriptionChangeUpdate, BillingSubscriptionConflictCreate, CheckoutIntentCreate, CheckoutIntentUpdate } from "../contracts.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/billing/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/billing/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,KAAK,EACV,0BAA0B,EAC1B,0BAA0B,EAC1B,0BAA0B,EAC1B,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EAClB,oBAAoB,EACpB,kBAAkB,EAClB,yBAAyB,EACzB,8BAA8B,EAC9B,wBAAwB,EACxB,cAAc,EACd,kBAAkB,EACnB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EACV,wBAAwB,EACxB,yBAAyB,EACzB,iCAAiC,EACjC,wBAAwB,EACxB,oBAAoB,EACpB,oBAAoB,EACpB,oBAAoB,EACpB,mBAAmB,EACnB,+BAA+B,EAC/B,iCAAiC,EACjC,oBAAoB,EACpB,oBAAoB,EACrB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAEL,KAAK,yBAAyB,EAC9B,KAAK,YAAY,EACjB,KAAK,uBAAuB,EAC7B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAEL,KAAK,mBAAmB,EACzB,MAAM,gCAAgC,CAAC;AA4FxC,MAAM,WAAW,2BAA4B,SAAQ,IAAI,CACvD,yBAAyB,EACzB,qBAAqB,CACtB;IACC,iEAAiE;IACjE,QAAQ,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AO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IAenE,4BAA4B,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAa9D,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAIzE,wBAAwB,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC;IAIlE,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,0BAA0B,GAAG,IAAI,CAAC;IAIlF,yBAAyB,CAC7B,OAAO,EAAE,0BAA0B,EACnC,OAAO,CAAC,EAAE;QAAE,aAAa,CAAC,EAAE,OAAO,CAAA;KAAE,GACpC,OAAO,CAAC,IAAI,CAAC;IAIV,wBAAwB,CAC5B,KAAK,EAAE,wBAAwB,GAC9B,OAAO,CAAC,0BAA0B,GAAG,IAAI,CAAC;IAIvC,yBAAyB,CAAC,KAAK,EAAE,yBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC;IAI1E,0CAA0C,CAC9C,KAAK,EAAE,iCAAiC,GACvC,OAAO,CAAC,IAAI,CAAC;IAIV,yBAAyB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC;IAIhF,0BAA0B,CAC9B,MAAM,EAAE,MAAM,EACd,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GACvB,OAAO,CAAC,qBAAqB,GAAG,IAAI,CAAC;CAQzC"}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import Decimal from "decimal.js";
|
|
1
|
+
import { Decimal } from "decimal.js";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { BillingStore } from "../billing-store.js";
|
|
4
4
|
import { PostgresClient, } from "../../shared/postgres-client.js";
|
|
5
5
|
import { normalizeProviderEnvironment, } from "../../providers/environment.js";
|
|
6
6
|
import { StoreClosedError, StoreError } from "../../errors.js";
|
|
7
7
|
import { optionalBoundedDiagnosticMessage } from "../../shared/diagnostics.js";
|
|
8
|
+
import { requireStableKey } from "../../shared/idempotency.js";
|
|
8
9
|
import { optionalRecordRow, pgBoolean, postgresUuid, requireRecordRow, requireResultField, safeParse, } from "../../shared/postgres-validation.js";
|
|
9
10
|
import { BillingOfferRepository } from "./repositories/offer.js";
|
|
10
11
|
import { BillingTopupRepository } from "./repositories/topup.js";
|
|
@@ -178,12 +179,16 @@ export class PostgresBillingStore extends BillingStore {
|
|
|
178
179
|
return this._subscriptionChange;
|
|
179
180
|
}
|
|
180
181
|
async createOrGetCheckoutIntent(input) {
|
|
182
|
+
const operationKey = requireStableKey(input.operationKey, "operationKey");
|
|
181
183
|
if (!/^[0-9a-fA-F]{64}$/.test(input.requestDigest)) {
|
|
182
184
|
throw new TypeError("requestDigest must be a 32-byte hex string");
|
|
183
185
|
}
|
|
184
|
-
const rows = await this.queryFn(`SELECT bursar.create_checkout_intent(
|
|
186
|
+
const rows = await this.queryFn(`SELECT bursar.create_checkout_intent(
|
|
187
|
+
$1::uuid, $2, $3, $4, $5, decode($6, 'hex'), $7::timestamptz
|
|
188
|
+
) AS id`, [
|
|
185
189
|
input.subjectId,
|
|
186
190
|
input.provider,
|
|
191
|
+
operationKey,
|
|
187
192
|
input.checkoutKind,
|
|
188
193
|
input.productKey,
|
|
189
194
|
input.requestDigest,
|
|
@@ -290,10 +295,15 @@ export class PostgresBillingStore extends BillingStore {
|
|
|
290
295
|
return { status: "duplicate" };
|
|
291
296
|
if (result.status === "busy")
|
|
292
297
|
return { status: "busy" };
|
|
293
|
-
if (result.status === "invalid_request"
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
298
|
+
if (result.status === "invalid_request")
|
|
299
|
+
return { status: "invalid_request" };
|
|
300
|
+
if (result.status === "idempotency_conflict" || result.status === "max_retries_exceeded") {
|
|
301
|
+
if (result.event_id === null) {
|
|
302
|
+
throw new StoreError("Billing event terminal claim returned no event identifier", {
|
|
303
|
+
details: { provider, eventId, status: result.status },
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
return { status: result.status, billingEventId: result.event_id };
|
|
297
307
|
}
|
|
298
308
|
throw new StoreError("Billing event claim returned an unsupported status", {
|
|
299
309
|
details: { provider, eventId, status: result.status },
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.js","sourceRoot":"","sources":["../../../src/billing/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAgBxB,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAgBnD,OAAO,EACL,cAAc,GAIf,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,4BAA4B,GAE7B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC/D,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,SAAS,GACV,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,sBAAsB,EAAwB,MAAM,yBAAyB,CAAC;AACvF,OAAO,EAAE,sBAAsB,EAAwB,MAAM,yBAAyB,CAAC;AACvF,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EACL,6BAA6B,GAE9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AACjE,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO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AC,KAAgC;QAC9D,OAAO,IAAI,CAAC,mBAAmB,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;IACvD,CAAC;IAED,KAAK,CAAC,0CAA0C,CAC9C,KAAwC;QAExC,OAAO,IAAI,CAAC,mBAAmB,CAAC,8BAA8B,CAAC,KAAK,CAAC,CAAC;IACxE,CAAC;IAED,KAAK,CAAC,yBAAyB,CAAC,MAAc,EAAE,KAAoB;QAClE,OAAO,IAAI,CAAC,mBAAmB,CAAC,aAAa,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC/D,CAAC;IAED,KAAK,CAAC,0BAA0B,CAC9B,MAAc,EACd,QAAwB;QAExB,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,WAAW,CAAC,MAAM,EAAE,QAAQ,IAAI,IAAI,CAAC,CAAC;QAChF,IAAI,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QACzB,OAAO;YACL,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,kBAAkB,EAAE,MAAM,CAAC,kBAAkB;SAC9C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\nimport { z } from \"zod\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeProfile,\n BillingCreditPostingResult,\n BillingCustomerRecord,\n BillingEventClaim,\n BillingOfferResult,\n BillingPaymentRecord,\n BillingPreferences,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionState,\n CheckoutIntent,\n BillingTopupResult,\n} from \"../types/index.js\";\nimport { BillingStore } from \"../billing-store.js\";\nimport type {\n AutoRechargeAttemptClaim,\n AutoRechargeAttemptUpdate,\n AutoRechargeProviderPaymentUpdate,\n BillingCreditGrantCreate,\n BillingDisputeUpsert,\n BillingInvoiceUpsert,\n BillingPaymentUpsert,\n BillingRefundUpsert,\n BillingSubscriptionChangeUpdate,\n BillingSubscriptionConflictCreate,\n CheckoutIntentCreate,\n CheckoutIntentUpdate,\n} from \"../contracts.js\";\nimport type { QueryFn } from \"../../shared/postgres-types.js\";\nimport {\n PostgresClient,\n type PostgresConnectionOptions,\n type PostgresPool,\n type PostgresPoolConstructor,\n} from \"../../shared/postgres-client.js\";\nimport {\n normalizeProviderEnvironment,\n type ProviderEnvironment,\n} from \"../../providers/environment.js\";\nimport { StoreClosedError, StoreError } from \"../../errors.js\";\nimport { optionalBoundedDiagnosticMessage } from \"../../shared/diagnostics.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireRecordRow,\n requireResultField,\n safeParse,\n} from \"../../shared/postgres-validation.js\";\nimport { BillingOfferRepository, type BillingOfferRow } from \"./repositories/offer.js\";\nimport { BillingTopupRepository, type BillingTopupRow } from \"./repositories/topup.js\";\nimport { BillingCustomerRepository } from \"./repositories/customer.js\";\nimport {\n BillingSubscriptionRepository,\n type SubscriptionRow,\n} from \"./repositories/subscription.js\";\nimport { BillingEventRepository } from \"./repositories/event.js\";\nimport { BillingPaymentRepository } from \"./repositories/payment.js\";\nimport { BillingRefundRepository } from \"./repositories/refund.js\";\nimport { BillingInvoiceRepository } from \"./repositories/invoice.js\";\nimport { BillingDisputeRepository } from \"./repositories/dispute.js\";\nimport { BillingPreferencesRepository } from \"./repositories/preferences.js\";\nimport { BillingAutoRechargeRepository } from \"./repositories/auto-recharge.js\";\nimport { BillingSubscriptionChangeRepository } from \"./repositories/subscription-change.js\";\n\nconst PgSafeMinorUnitsSchema = z\n .union([z.string().regex(/^\\d+$/), z.number().int().nonnegative().safe()])\n .transform(Number)\n .refine(Number.isSafeInteger, \"minor-unit amount exceeds JavaScript's safe integer range\");\n\nconst BillingCreditPostingRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n balance_after: z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .nullable()\n .transform((value) => (value === null ? null : new Decimal(value))),\n replayed: pgBoolean,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.error_code === null && (row.ledger_entry_id === null || row.balance_after === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"successful posting requires ledger_entry_id and balance_after\",\n });\n }\n });\n\nconst CheckoutIntentRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n checkout_kind: z.enum([\"subscription\", \"credit_topup\"]),\n product_key: z.string().min(1),\n request_digest: z.instanceof(Uint8Array).refine((value) => value.byteLength === 32),\n status: z.enum([\"open\", \"completed\", \"failed\", \"expired\"]),\n provider_session_id: z.string().min(1).nullable(),\n checkout_url: z.string().min(1).nullable(),\n expires_at: z.union([z.string().datetime({ offset: true }), z.date()]),\n })\n .strict();\n\nfunction billingCreditPostingResult(\n rows: readonly unknown[] | null | undefined,\n context: string,\n): BillingCreditPostingResult {\n const raw = requireRecordRow(rows, context);\n const row = safeParse(\n BillingCreditPostingRowSchema,\n {\n ledger_entry_id: raw.ledger_entry_id,\n balance_after: raw.balance_after,\n replayed: raw.replayed,\n error_code: raw.error_code,\n },\n context,\n { indeterminate: true },\n );\n return {\n ledgerEntryId: row.ledger_entry_id,\n balanceAfter: row.balance_after,\n replayed: row.replayed,\n errorCode: row.error_code,\n };\n}\n\nexport interface PostgresBillingStoreOptions extends Omit<\n PostgresConnectionOptions,\n \"providerEnvironment\"\n> {\n /** PostgreSQL connection string or an application-owned pool. */\n postgres: PostgresPool | string;\n /** Tenant UUID bound to every store transaction. */\n tenantId: string;\n /** Explicit financial namespace; billing stores never guess live vs test. */\n providerEnvironment: ProviderEnvironment;\n /** Injectable `pg.Pool` constructor for custom runtimes and tests. */\n poolConstructor?: PostgresPoolConstructor;\n billingPayloadBackend?: \"postgres\" | \"s3\";\n}\n\nexport class PostgresBillingStore extends BillingStore {\n private readonly postgres: PostgresClient;\n readonly providerEnvironment: ProviderEnvironment;\n\n private _offer: BillingOfferRepository | null = null;\n private _topup: BillingTopupRepository | null = null;\n private _customer: BillingCustomerRepository | null = null;\n private _subscription: BillingSubscriptionRepository | null = null;\n private _event: BillingEventRepository | null = null;\n private _payment: BillingPaymentRepository | null = null;\n private _refund: BillingRefundRepository | null = null;\n private _invoice: BillingInvoiceRepository | null = null;\n private _dispute: BillingDisputeRepository | null = null;\n private _preferences: BillingPreferencesRepository | null = null;\n private _autoRecharge: BillingAutoRechargeRepository | null = null;\n private _subscriptionChange: BillingSubscriptionChangeRepository | null = null;\n constructor(options: PostgresBillingStoreOptions) {\n super();\n if (typeof options !== \"object\" || options === null) {\n throw new TypeError(\"PostgresBillingStore options are required\");\n }\n if (typeof options.postgres !== \"string\" && options.poolConstructor !== undefined) {\n throw new TypeError(\"poolConstructor cannot be used with an existing PostgreSQL pool\");\n }\n const providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);\n this.providerEnvironment = providerEnvironment;\n this.postgres = new PostgresClient(options.postgres, {\n tenantId: options.tenantId,\n providerEnvironment,\n poolConstructor: options.poolConstructor,\n billingPayloadBackend: options.billingPayloadBackend,\n connectionTimeoutMs: options.connectionTimeoutMs,\n statementTimeoutMs: options.statementTimeoutMs,\n idleTransactionTimeoutMs: options.idleTransactionTimeoutMs,\n idleTimeoutMs: options.idleTimeoutMs,\n maxConnections: options.maxConnections,\n applicationName: options.applicationName,\n onPoolError: options.onPoolError,\n closedError: () => new StoreClosedError(\"Billing store has been closed\"),\n });\n }\n\n async close(): Promise<void> {\n await this.postgres.close();\n }\n\n private get queryFn(): QueryFn {\n return this.postgres.query;\n }\n\n private get billingOffer(): BillingOfferRepository {\n if (!this._offer) this._offer = new BillingOfferRepository(this.queryFn);\n return this._offer;\n }\n\n private get billingTopup(): BillingTopupRepository {\n if (!this._topup) this._topup = new BillingTopupRepository(this.queryFn);\n return this._topup;\n }\n\n private get billingCustomer(): BillingCustomerRepository {\n if (!this._customer) this._customer = new BillingCustomerRepository(this.queryFn);\n return this._customer;\n }\n\n private get billingSubscription(): BillingSubscriptionRepository {\n if (!this._subscription) this._subscription = new BillingSubscriptionRepository(this.queryFn);\n return this._subscription;\n }\n\n private get billingEvent(): BillingEventRepository {\n if (!this._event) this._event = new BillingEventRepository(this.queryFn);\n return this._event;\n }\n\n private get billingPayment(): BillingPaymentRepository {\n if (!this._payment) this._payment = new BillingPaymentRepository(this.queryFn);\n return this._payment;\n }\n\n private get billingRefund(): BillingRefundRepository {\n if (!this._refund) this._refund = new BillingRefundRepository(this.queryFn);\n return this._refund;\n }\n\n private get billingInvoice(): BillingInvoiceRepository {\n if (!this._invoice) this._invoice = new BillingInvoiceRepository(this.queryFn);\n return this._invoice;\n }\n\n private get billingDispute(): BillingDisputeRepository {\n if (!this._dispute) this._dispute = new BillingDisputeRepository(this.queryFn);\n return this._dispute;\n }\n\n private get billingPreferences(): BillingPreferencesRepository {\n if (!this._preferences) this._preferences = new BillingPreferencesRepository(this.queryFn);\n return this._preferences;\n }\n\n private get billingAutoRecharge(): BillingAutoRechargeRepository {\n if (!this._autoRecharge) this._autoRecharge = new BillingAutoRechargeRepository(this.queryFn);\n return this._autoRecharge;\n }\n\n private get billingSubscriptionChange(): BillingSubscriptionChangeRepository {\n if (!this._subscriptionChange) {\n this._subscriptionChange = new BillingSubscriptionChangeRepository(this.queryFn);\n }\n return this._subscriptionChange;\n }\n\n async createOrGetCheckoutIntent(input: CheckoutIntentCreate): Promise<CheckoutIntent> {\n if (!/^[0-9a-fA-F]{64}$/.test(input.requestDigest)) {\n throw new TypeError(\"requestDigest must be a 32-byte hex string\");\n }\n const rows = await this.queryFn(\n `SELECT bursar.create_checkout_intent($1::uuid, $2, $3, $4, decode($5, 'hex'), $6::timestamptz) AS id`,\n [\n input.subjectId,\n input.provider,\n input.checkoutKind,\n input.productKey,\n input.requestDigest,\n input.expiresAt,\n ],\n );\n const id = requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createOrGetCheckoutIntent\",\n );\n const intent = await this.getCheckoutIntent(id, input.subjectId);\n if (!intent) {\n throw new StoreError(\"checkout intent could not be read after creation\", {\n indeterminate: true,\n details: { checkoutIntentId: id },\n });\n }\n return intent;\n }\n\n async updateCheckoutIntent(id: string, update: CheckoutIntentUpdate): Promise<void> {\n const rows = await this.queryFn(\n `SELECT bursar.advance_checkout_intent($1::uuid, $2, $3, $4) AS advanced`,\n [id, update.status ?? null, update.providerSessionId ?? null, update.checkoutUrl ?? null],\n );\n if (\n !requireResultField(rows, \"advanced\", pgBoolean, \"PostgresBillingStore.updateCheckoutIntent\")\n ) {\n throw new StoreError(`checkout intent transition rejected: ${id}`, {\n details: { checkoutIntentId: id },\n });\n }\n }\n\n async getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_checkout_intent($1::uuid, $2::uuid)`,\n [id, subjectId],\n );\n if (rows.length === 0) return null;\n if (rows.length !== 1) {\n throw new StoreError(\"getCheckoutIntent: expected at most one row\", {\n details: { rowCount: rows.length, checkoutIntentId: id },\n });\n }\n const row = rows[0] as Record<string, unknown>;\n return this.rowToCheckoutIntent(\n safeParse(\n CheckoutIntentRowSchema,\n {\n id: row.id,\n subject_id: row.subject_id,\n provider: row.provider,\n checkout_kind: row.checkout_kind,\n product_key: row.product_key,\n request_digest: row.request_digest,\n status: row.status,\n provider_session_id: row.provider_session_id,\n checkout_url: row.checkout_url,\n expires_at: row.expires_at,\n },\n \"PostgresBillingStore.getCheckoutIntent\",\n ),\n );\n }\n\n private rowToCheckoutIntent(row: z.infer<typeof CheckoutIntentRowSchema>): CheckoutIntent {\n return {\n id: row.id,\n subjectId: row.subject_id,\n provider: row.provider,\n checkoutKind: row.checkout_kind,\n productKey: row.product_key,\n requestDigest: Buffer.from(row.request_digest).toString(\"hex\"),\n status: row.status,\n providerSessionId: row.provider_session_id,\n checkoutUrl: row.checkout_url,\n expiresAt: row.expires_at instanceof Date ? row.expires_at.toISOString() : row.expires_at,\n };\n }\n\n private rowToOffer(row: BillingOfferRow | null): BillingOfferResult | null {\n if (!row) return null;\n return {\n offerId: row.id,\n offerKey: row.offerKey,\n planId: row.planId,\n plan: row.plan,\n interval: row.interval,\n intervalCount: row.intervalCount,\n grant:\n row.grantCredits === null\n ? null\n : {\n mode: \"cycle_grant\",\n credits: row.grantCredits,\n bucket: row.grantBucket,\n replacePrior: row.grantReplacePrior,\n },\n };\n }\n\n async resolveBillingOffer(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByPrice(provider, priceId ?? null, productId ?? null);\n return this.rowToOffer(r);\n }\n\n async resolveBillingOfferByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByLookup(provider, lookupKey);\n return this.rowToOffer(r);\n }\n\n async claimBillingEvent(\n provider: string,\n eventId: string,\n eventType: string,\n envelope?: Record<string, unknown>,\n ): Promise<BillingEventClaim> {\n const result = await this.billingEvent.claim(\n provider,\n eventId,\n eventType,\n JSON.stringify(envelope ?? { eventType }),\n );\n if (result.status === \"claimed\") {\n if (result.claim_token === null || result.event_id === null) {\n throw new StoreError(\"Billing event claim returned no claim identifiers\", {\n details: { provider, eventId },\n });\n }\n return {\n status: \"claimed\" as const,\n claimToken: result.claim_token,\n billingEventId: result.event_id,\n };\n }\n if (result.status === \"duplicate\") return { status: \"duplicate\" as const };\n if (result.status === \"busy\") return { status: \"busy\" as const };\n if (\n result.status === \"invalid_request\" ||\n result.status === \"idempotency_conflict\" ||\n result.status === \"max_retries_exceeded\"\n ) {\n return { status: \"retry\" as const };\n }\n throw new StoreError(\"Billing event claim returned an unsupported status\", {\n details: { provider, eventId, status: result.status },\n });\n }\n\n async completeBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n ): Promise<boolean> {\n return this.billingEvent.complete(provider, eventId, claimToken);\n }\n\n async failBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n error?: string,\n ): Promise<boolean> {\n return this.billingEvent.fail(\n provider,\n eventId,\n claimToken,\n optionalBoundedDiagnosticMessage(error) ?? undefined,\n );\n }\n\n async upsertBillingCustomer(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email?: string | null,\n ): Promise<void> {\n await this.billingCustomer.upsert(provider, providerCustomerId, userId, email ?? null);\n }\n\n async upsertBillingSubscription(state: BillingSubscriptionState): Promise<void> {\n await this.billingSubscription.upsert(state);\n }\n\n async getBillingCustomer(provider: string, providerCustomerId: string): Promise<string | null> {\n return this.billingCustomer.get(provider, providerCustomerId);\n }\n\n async getBillingSubscription(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.get(provider, providerSubscriptionId);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async createBillingSubscriptionChange(\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n const subscription = await this.billingSubscription.get(\n input.provider,\n input.providerSubscriptionId,\n );\n if (!subscription?.id) {\n throw new StoreError(\"subscription change requires a persisted subscription\", {\n retryable: true,\n details: {\n provider: input.provider,\n providerSubscriptionId: input.providerSubscriptionId,\n },\n });\n }\n return this.billingSubscriptionChange.create(subscription.id, input);\n }\n\n async getOpenBillingSubscriptionChange(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.billingSubscriptionChange.getOpen(provider, providerSubscriptionId);\n }\n\n async listExpiredGraceSubscriptions(\n now: string,\n limit = 100,\n ): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.listExpiredGraceSubscriptions(now, limit);\n return rows.map((row) => this.rowToSubscriptionState(row));\n }\n\n async markSubscriptionGraceExpired(\n subscriptionId: string,\n expectedGraceEndsAt: string,\n expiredAt = new Date().toISOString(),\n ): Promise<boolean> {\n return this.billingSubscription.markGraceExpired(\n subscriptionId,\n expectedGraceEndsAt,\n expiredAt,\n );\n }\n\n async updateBillingSubscriptionChange(\n id: string,\n update: BillingSubscriptionChangeUpdate,\n ): Promise<void> {\n await this.billingSubscriptionChange.update(id, update);\n }\n\n async getUserSubscription(\n userId: string,\n statuses?: string[],\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.getUserSubscription(userId, statuses);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async getUserSubscriptions(userId: string): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.getUserSubscriptions(userId);\n return rows.map((r) => this.rowToSubscriptionState(r));\n }\n\n async recordSubscriptionConflict(input: BillingSubscriptionConflictCreate): Promise<void> {\n await this.billingSubscription.recordConflict(input);\n }\n\n async selectSubscriptionEntitlementSource(\n userId: string,\n provider: string,\n providerSubscriptionId?: string | null,\n ): Promise<boolean> {\n return this.billingSubscription.selectEntitlementSource(\n userId,\n provider,\n providerSubscriptionId,\n );\n }\n\n private rowToTopup(r: BillingTopupRow | null): BillingTopupResult | null {\n if (!r) return null;\n const minAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.min_quantity,\n \"PostgresBillingStore.rowToTopup.minAmountMinor\",\n );\n const maxAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.max_quantity,\n \"PostgresBillingStore.rowToTopup.maxAmountMinor\",\n );\n return {\n topupId: r.id,\n topupKey: r.topup_key,\n creditsPerUnit: r.credits_per_unit,\n depositTo: r.bucket_key,\n amountMinor: r.amount_minor,\n currency: r.currency,\n minQuantity: r.min_quantity,\n maxQuantity: r.max_quantity,\n defaultQuantity: r.default_quantity,\n minAmountMinor,\n maxAmountMinor,\n };\n }\n\n async resolveCreditTopup(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByPrice(provider, priceId ?? null, productId ?? null);\n return this.rowToTopup(r);\n }\n\n async resolveCreditTopupByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByLookup(provider, lookupKey);\n return this.rowToTopup(r);\n }\n\n async computeTopupCredits(\n amountMinor: number,\n topupConfig: BillingTopupResult,\n ): Promise<Decimal> {\n if (!Number.isSafeInteger(amountMinor) || amountMinor < 0) {\n throw new TypeError(\"amountMinor must be a non-negative safe integer\");\n }\n const unitAmount = topupConfig.amountMinor;\n if (unitAmount <= 0 || amountMinor % unitAmount !== 0) return new Decimal(0);\n const quantity = amountMinor / unitAmount;\n if (quantity < topupConfig.minQuantity || quantity > topupConfig.maxQuantity) {\n return new Decimal(0);\n }\n return topupConfig.creditsPerUnit.mul(quantity);\n }\n\n async upsertBillingPayment(options: BillingPaymentUpsert): Promise<string> {\n return this.billingPayment.upsert(\n options.provider,\n options.providerPaymentId,\n options.providerInvoiceId ?? null,\n options.userId,\n options.amountMinor,\n options.taxMinor,\n options.currency,\n options.purpose,\n options.metadata ? JSON.stringify(options.metadata) : null,\n options.status,\n options.providerUpdatedAt,\n );\n }\n\n async createBillingCreditGrant(input: BillingCreditGrantCreate): Promise<string> {\n const rows = await this.queryFn(\n \"SELECT bursar.create_billing_credit_grant($1::uuid, $2::uuid, $3::uuid, $4, $5, $6::uuid) AS id\",\n [\n input.paymentId ?? null,\n input.subscriptionId ?? null,\n input.topupId ?? null,\n input.configuredCredits.toString(),\n input.quantity,\n input.billingEventId ?? null,\n ],\n );\n return requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createBillingCreditGrant\",\n );\n }\n\n async grantBillingCredit(\n grantId: string,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.grant_billing_credit($1::uuid, $2)\", [\n grantId,\n idempotencyKey,\n ]);\n return billingCreditPostingResult(rows, \"PostgresBillingStore.grantBillingCredit\");\n }\n\n async getBillingCreditGrantByPayment(paymentId: string): Promise<string | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_billing_credit_grant_by_payment($1::uuid)`,\n [paymentId],\n );\n const row = optionalRecordRow(rows, \"PostgresBillingStore.getBillingCreditGrantByPayment\");\n return row === null\n ? null\n : safeParse(postgresUuid, row.id, \"PostgresBillingStore.getBillingCreditGrantByPayment.id\");\n }\n\n async postBillingRefund(\n refundId: string,\n grantId: string,\n amountMinor: number,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\n \"SELECT * FROM bursar.post_billing_refund($1::uuid, $2::uuid, $3, $4)\",\n [refundId, grantId, amountMinor, idempotencyKey],\n );\n return billingCreditPostingResult(rows, \"PostgresBillingStore.postBillingRefund\");\n }\n\n async upsertBillingRefund(options: BillingRefundUpsert): Promise<string> {\n return this.billingRefund.upsert(\n options.provider,\n options.providerRefundId,\n options.providerPaymentId,\n options.userId,\n options.amountMinor,\n options.currency,\n options.reason ?? null,\n options.metadata ? JSON.stringify(options.metadata) : null,\n options.status,\n options.providerUpdatedAt,\n );\n }\n\n async upsertBillingInvoice(options: BillingInvoiceUpsert): Promise<void> {\n const subscription = options.providerSubscriptionId\n ? await this.billingSubscription.get(options.provider, options.providerSubscriptionId)\n : null;\n if (options.providerSubscriptionId && !subscription) {\n throw new StoreError(\"invoice subscription is not available\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerInvoiceId: options.providerInvoiceId,\n providerSubscriptionId: options.providerSubscriptionId ?? null,\n },\n });\n }\n await this.billingInvoice.upsert(\n options.userId,\n options.provider,\n options.providerInvoiceId,\n subscription?.id ? String(subscription.id) : null,\n options.status,\n options.amountDueMinor,\n options.amountPaidMinor,\n options.currency,\n options.periodStart ?? null,\n options.periodEnd ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async listBillingInvoices(userId: string) {\n return this.billingInvoice.listForUser(userId);\n }\n\n async upsertBillingDispute(options: BillingDisputeUpsert): Promise<void> {\n const payment = await this.billingPayment.getForRefund(\n options.provider,\n options.providerPaymentId,\n );\n if (!payment?.id) {\n throw new StoreError(\"dispute payment is required\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerDisputeId: options.providerDisputeId,\n providerPaymentId: options.providerPaymentId ?? null,\n },\n });\n }\n await this.billingDispute.upsert(\n options.provider,\n options.providerDisputeId,\n String(payment.id),\n options.status,\n options.reason ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async getBillingPayment(\n provider: string,\n providerPaymentId: string,\n ): Promise<BillingPaymentRecord | null> {\n const row = await this.billingPayment.getForRefund(provider, providerPaymentId);\n if (!row) return null;\n return {\n id: row.id,\n provider: row.provider,\n providerPaymentId: row.provider_payment_id,\n providerInvoiceId: row.provider_invoice_id,\n userId: row.subject_id,\n amountMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.amount_minor,\n \"PostgresBillingStore.getBillingPayment.amountMinor\",\n ),\n taxMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.tax_minor,\n \"PostgresBillingStore.getBillingPayment.taxMinor\",\n ),\n currency: row.currency,\n purpose: row.purpose,\n status: row.status,\n providerUpdatedAt:\n row.provider_updated_at instanceof Date\n ? row.provider_updated_at.toISOString()\n : row.provider_updated_at,\n metadata: row.metadata,\n };\n }\n\n private rowToSubscriptionState(r: SubscriptionRow): BillingSubscriptionState {\n return {\n subscriptionId: r.id,\n userId: r.user_id,\n provider: r.provider,\n providerSubscriptionId: r.provider_subscription_id,\n providerCustomerId: r.provider_customer_id,\n offerId: r.offer_id,\n offerKey: r.offer_key,\n planId: r.plan_id,\n plan: r.plan,\n status: r.status,\n currentPeriodStart: r.current_period_start,\n currentPeriodEnd: r.current_period_end,\n trialEnd: r.trial_end,\n cancelAt: r.cancel_at,\n endedAt: r.ended_at,\n graceEndsAt: r.grace_ends_at,\n graceExpiredAt: r.grace_expired_at,\n providerUpdatedAt: r.provider_updated_at,\n cancelAtPeriodEnd: r.cancel_at_period_end,\n interval: r.interval,\n intervalCount: r.interval_count,\n metadata: r.metadata,\n };\n }\n\n async getActiveCatalogDocument(): Promise<Record<string, unknown> | null> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.active_catalog_revision()\", []);\n if (rows.length === 0) return null;\n if (rows.length !== 1 || typeof rows[0] !== \"object\" || rows[0] === null) {\n throw new StoreError(\"active catalog revision returned a malformed row\", {\n details: { rowCount: rows.length },\n });\n }\n return safeParse(\n z.record(z.string(), z.unknown()),\n (rows[0] as Record<string, unknown>).source_document,\n \"PostgresBillingStore.getActiveCatalogDocument\",\n );\n }\n\n async pseudonymizeFinancialSubject(userId: string): Promise<boolean> {\n const rows = await this.queryFn(\n `SELECT bursar.pseudonymize_financial_subject($1::uuid) AS pseudonymized`,\n [userId],\n );\n return requireResultField(\n rows,\n \"pseudonymized\",\n pgBoolean,\n \"PostgresBillingStore.pseudonymizeFinancialSubject\",\n );\n }\n\n async getBillingPreferences(userId: string): Promise<BillingPreferences | null> {\n return this.billingPreferences.get(userId);\n }\n\n async upsertBillingPreferences(prefs: BillingPreferences): Promise<void> {\n await this.billingPreferences.upsert(prefs);\n }\n\n async getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n return this.billingAutoRecharge.getProfile(userId);\n }\n\n async upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void> {\n return this.billingAutoRecharge.upsertProfile(profile, options);\n }\n\n async claimAutoRechargeAttempt(\n input: AutoRechargeAttemptClaim,\n ): Promise<BillingAutoRechargeAttempt | null> {\n return this.billingAutoRecharge.claimAttempt(input);\n }\n\n async updateAutoRechargeAttempt(input: AutoRechargeAttemptUpdate): Promise<void> {\n return this.billingAutoRecharge.updateAttempt(input);\n }\n\n async updateAutoRechargeAttemptByProviderPayment(\n input: AutoRechargeProviderPaymentUpdate,\n ): Promise<void> {\n return this.billingAutoRecharge.updateAttemptByProviderPayment(input);\n }\n\n async countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number> {\n return this.billingAutoRecharge.countAttempts(userId, since);\n }\n\n async getBillingCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null> {\n const result = await this.billingCustomer.getByUserId(userId, provider ?? null);\n if (!result) return null;\n return {\n provider: result.provider,\n providerCustomerId: result.providerCustomerId,\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"store.js","sourceRoot":"","sources":["../../../src/billing/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAgBxB,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAgBnD,OAAO,EACL,cAAc,GAIf,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,4BAA4B,GAE7B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC/D,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAC/D,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,SAAS,GACV,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,sBAAsB,EAAwB,MAAM,yBAAyB,CAAC;AACvF,OAAO,EAAE,sBAAsB,EAAwB,MAAM,yBAAyB,CAAC;AACvF,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EACL,6BAA6B,GAE9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AACjE,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,4BAA4B,EAAE,MAAM,+BAA+B,CAAC;AAC7E,OAAO,EAAE,6BAA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;IAED,KAAK,CAAC,yBAAyB,CAC7B,OAAmC,EACnC,OAAqC;QAErC,OAAO,IAAI,CAAC,mBAAmB,CAAC,aAAa,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;IAED,KAAK,CAAC,wBAAwB,CAC5B,KAA+B;QAE/B,OAAO,IAAI,CAAC,mBAAmB,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;IACtD,CAAC;IAED,KAAK,CAAC,yBAAyB,CAAC,KAAgC;QAC9D,OAAO,IAAI,CAAC,mBAAmB,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;IACvD,CAAC;IAED,KAAK,CAAC,0CAA0C,CAC9C,KAAwC;QAExC,OAAO,IAAI,CAAC,mBAAmB,CAAC,8BAA8B,CAAC,KAAK,CAAC,CAAC;IACxE,CAAC;IAED,KAAK,CAAC,yBAAyB,CAAC,MAAc,EAAE,KAAoB;QAClE,OAAO,IAAI,CAAC,mBAAmB,CAAC,aAAa,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC/D,CAAC;IAED,KAAK,CAAC,0BAA0B,CAC9B,MAAc,EACd,QAAwB;QAExB,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,WAAW,CAAC,MAAM,EAAE,QAAQ,IAAI,IAAI,CAAC,CAAC;QAChF,IAAI,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QACzB,OAAO;YACL,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,kBAAkB,EAAE,MAAM,CAAC,kBAAkB;SAC9C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { z } from \"zod\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeProfile,\n BillingCreditPostingResult,\n BillingCustomerRecord,\n BillingEventClaim,\n BillingOfferResult,\n BillingPaymentRecord,\n BillingPreferences,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionState,\n CheckoutIntent,\n BillingTopupResult,\n} from \"../types/index.js\";\nimport { BillingStore } from \"../billing-store.js\";\nimport type {\n AutoRechargeAttemptClaim,\n AutoRechargeAttemptUpdate,\n AutoRechargeProviderPaymentUpdate,\n BillingCreditGrantCreate,\n BillingDisputeUpsert,\n BillingInvoiceUpsert,\n BillingPaymentUpsert,\n BillingRefundUpsert,\n BillingSubscriptionChangeUpdate,\n BillingSubscriptionConflictCreate,\n CheckoutIntentCreate,\n CheckoutIntentUpdate,\n} from \"../contracts.js\";\nimport type { QueryFn } from \"../../shared/postgres-types.js\";\nimport {\n PostgresClient,\n type PostgresConnectionOptions,\n type PostgresPool,\n type PostgresPoolConstructor,\n} from \"../../shared/postgres-client.js\";\nimport {\n normalizeProviderEnvironment,\n type ProviderEnvironment,\n} from \"../../providers/environment.js\";\nimport { StoreClosedError, StoreError } from \"../../errors.js\";\nimport { optionalBoundedDiagnosticMessage } from \"../../shared/diagnostics.js\";\nimport { requireStableKey } from \"../../shared/idempotency.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireRecordRow,\n requireResultField,\n safeParse,\n} from \"../../shared/postgres-validation.js\";\nimport { BillingOfferRepository, type BillingOfferRow } from \"./repositories/offer.js\";\nimport { BillingTopupRepository, type BillingTopupRow } from \"./repositories/topup.js\";\nimport { BillingCustomerRepository } from \"./repositories/customer.js\";\nimport {\n BillingSubscriptionRepository,\n type SubscriptionRow,\n} from \"./repositories/subscription.js\";\nimport { BillingEventRepository } from \"./repositories/event.js\";\nimport { BillingPaymentRepository } from \"./repositories/payment.js\";\nimport { BillingRefundRepository } from \"./repositories/refund.js\";\nimport { BillingInvoiceRepository } from \"./repositories/invoice.js\";\nimport { BillingDisputeRepository } from \"./repositories/dispute.js\";\nimport { BillingPreferencesRepository } from \"./repositories/preferences.js\";\nimport { BillingAutoRechargeRepository } from \"./repositories/auto-recharge.js\";\nimport { BillingSubscriptionChangeRepository } from \"./repositories/subscription-change.js\";\n\nconst PgSafeMinorUnitsSchema = z\n .union([z.string().regex(/^\\d+$/), z.number().int().nonnegative().safe()])\n .transform(Number)\n .refine(Number.isSafeInteger, \"minor-unit amount exceeds JavaScript's safe integer range\");\n\nconst BillingCreditPostingRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n balance_after: z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .nullable()\n .transform((value) => (value === null ? null : new Decimal(value))),\n replayed: pgBoolean,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.error_code === null && (row.ledger_entry_id === null || row.balance_after === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"successful posting requires ledger_entry_id and balance_after\",\n });\n }\n });\n\nconst CheckoutIntentRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n checkout_kind: z.enum([\"subscription\", \"credit_topup\"]),\n product_key: z.string().min(1),\n request_digest: z.instanceof(Uint8Array).refine((value) => value.byteLength === 32),\n status: z.enum([\"open\", \"completed\", \"failed\", \"expired\"]),\n provider_session_id: z.string().min(1).nullable(),\n checkout_url: z.string().min(1).nullable(),\n expires_at: z.union([z.string().datetime({ offset: true }), z.date()]),\n })\n .strict();\n\nfunction billingCreditPostingResult(\n rows: readonly unknown[] | null | undefined,\n context: string,\n): BillingCreditPostingResult {\n const raw = requireRecordRow(rows, context);\n const row = safeParse(\n BillingCreditPostingRowSchema,\n {\n ledger_entry_id: raw.ledger_entry_id,\n balance_after: raw.balance_after,\n replayed: raw.replayed,\n error_code: raw.error_code,\n },\n context,\n { indeterminate: true },\n );\n return {\n ledgerEntryId: row.ledger_entry_id,\n balanceAfter: row.balance_after,\n replayed: row.replayed,\n errorCode: row.error_code,\n };\n}\n\nexport interface PostgresBillingStoreOptions extends Omit<\n PostgresConnectionOptions,\n \"providerEnvironment\"\n> {\n /** PostgreSQL connection string or an application-owned pool. */\n postgres: PostgresPool | string;\n /** Tenant UUID bound to every store transaction. */\n tenantId: string;\n /** Explicit financial namespace; billing stores never guess live vs test. */\n providerEnvironment: ProviderEnvironment;\n /** Injectable `pg.Pool` constructor for custom runtimes and tests. */\n poolConstructor?: PostgresPoolConstructor;\n billingPayloadBackend?: \"postgres\" | \"s3\";\n}\n\nexport class PostgresBillingStore extends BillingStore {\n private readonly postgres: PostgresClient;\n readonly providerEnvironment: ProviderEnvironment;\n\n private _offer: BillingOfferRepository | null = null;\n private _topup: BillingTopupRepository | null = null;\n private _customer: BillingCustomerRepository | null = null;\n private _subscription: BillingSubscriptionRepository | null = null;\n private _event: BillingEventRepository | null = null;\n private _payment: BillingPaymentRepository | null = null;\n private _refund: BillingRefundRepository | null = null;\n private _invoice: BillingInvoiceRepository | null = null;\n private _dispute: BillingDisputeRepository | null = null;\n private _preferences: BillingPreferencesRepository | null = null;\n private _autoRecharge: BillingAutoRechargeRepository | null = null;\n private _subscriptionChange: BillingSubscriptionChangeRepository | null = null;\n constructor(options: PostgresBillingStoreOptions) {\n super();\n if (typeof options !== \"object\" || options === null) {\n throw new TypeError(\"PostgresBillingStore options are required\");\n }\n if (typeof options.postgres !== \"string\" && options.poolConstructor !== undefined) {\n throw new TypeError(\"poolConstructor cannot be used with an existing PostgreSQL pool\");\n }\n const providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);\n this.providerEnvironment = providerEnvironment;\n this.postgres = new PostgresClient(options.postgres, {\n tenantId: options.tenantId,\n providerEnvironment,\n poolConstructor: options.poolConstructor,\n billingPayloadBackend: options.billingPayloadBackend,\n connectionTimeoutMs: options.connectionTimeoutMs,\n statementTimeoutMs: options.statementTimeoutMs,\n idleTransactionTimeoutMs: options.idleTransactionTimeoutMs,\n idleTimeoutMs: options.idleTimeoutMs,\n maxConnections: options.maxConnections,\n applicationName: options.applicationName,\n onPoolError: options.onPoolError,\n closedError: () => new StoreClosedError(\"Billing store has been closed\"),\n });\n }\n\n async close(): Promise<void> {\n await this.postgres.close();\n }\n\n private get queryFn(): QueryFn {\n return this.postgres.query;\n }\n\n private get billingOffer(): BillingOfferRepository {\n if (!this._offer) this._offer = new BillingOfferRepository(this.queryFn);\n return this._offer;\n }\n\n private get billingTopup(): BillingTopupRepository {\n if (!this._topup) this._topup = new BillingTopupRepository(this.queryFn);\n return this._topup;\n }\n\n private get billingCustomer(): BillingCustomerRepository {\n if (!this._customer) this._customer = new BillingCustomerRepository(this.queryFn);\n return this._customer;\n }\n\n private get billingSubscription(): BillingSubscriptionRepository {\n if (!this._subscription) this._subscription = new BillingSubscriptionRepository(this.queryFn);\n return this._subscription;\n }\n\n private get billingEvent(): BillingEventRepository {\n if (!this._event) this._event = new BillingEventRepository(this.queryFn);\n return this._event;\n }\n\n private get billingPayment(): BillingPaymentRepository {\n if (!this._payment) this._payment = new BillingPaymentRepository(this.queryFn);\n return this._payment;\n }\n\n private get billingRefund(): BillingRefundRepository {\n if (!this._refund) this._refund = new BillingRefundRepository(this.queryFn);\n return this._refund;\n }\n\n private get billingInvoice(): BillingInvoiceRepository {\n if (!this._invoice) this._invoice = new BillingInvoiceRepository(this.queryFn);\n return this._invoice;\n }\n\n private get billingDispute(): BillingDisputeRepository {\n if (!this._dispute) this._dispute = new BillingDisputeRepository(this.queryFn);\n return this._dispute;\n }\n\n private get billingPreferences(): BillingPreferencesRepository {\n if (!this._preferences) this._preferences = new BillingPreferencesRepository(this.queryFn);\n return this._preferences;\n }\n\n private get billingAutoRecharge(): BillingAutoRechargeRepository {\n if (!this._autoRecharge) this._autoRecharge = new BillingAutoRechargeRepository(this.queryFn);\n return this._autoRecharge;\n }\n\n private get billingSubscriptionChange(): BillingSubscriptionChangeRepository {\n if (!this._subscriptionChange) {\n this._subscriptionChange = new BillingSubscriptionChangeRepository(this.queryFn);\n }\n return this._subscriptionChange;\n }\n\n async createOrGetCheckoutIntent(input: CheckoutIntentCreate): Promise<CheckoutIntent> {\n const operationKey = requireStableKey(input.operationKey, \"operationKey\");\n if (!/^[0-9a-fA-F]{64}$/.test(input.requestDigest)) {\n throw new TypeError(\"requestDigest must be a 32-byte hex string\");\n }\n const rows = await this.queryFn(\n `SELECT bursar.create_checkout_intent(\n $1::uuid, $2, $3, $4, $5, decode($6, 'hex'), $7::timestamptz\n ) AS id`,\n [\n input.subjectId,\n input.provider,\n operationKey,\n input.checkoutKind,\n input.productKey,\n input.requestDigest,\n input.expiresAt,\n ],\n );\n const id = requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createOrGetCheckoutIntent\",\n );\n const intent = await this.getCheckoutIntent(id, input.subjectId);\n if (!intent) {\n throw new StoreError(\"checkout intent could not be read after creation\", {\n indeterminate: true,\n details: { checkoutIntentId: id },\n });\n }\n return intent;\n }\n\n async updateCheckoutIntent(id: string, update: CheckoutIntentUpdate): Promise<void> {\n const rows = await this.queryFn(\n `SELECT bursar.advance_checkout_intent($1::uuid, $2, $3, $4) AS advanced`,\n [id, update.status ?? null, update.providerSessionId ?? null, update.checkoutUrl ?? null],\n );\n if (\n !requireResultField(rows, \"advanced\", pgBoolean, \"PostgresBillingStore.updateCheckoutIntent\")\n ) {\n throw new StoreError(`checkout intent transition rejected: ${id}`, {\n details: { checkoutIntentId: id },\n });\n }\n }\n\n async getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_checkout_intent($1::uuid, $2::uuid)`,\n [id, subjectId],\n );\n if (rows.length === 0) return null;\n if (rows.length !== 1) {\n throw new StoreError(\"getCheckoutIntent: expected at most one row\", {\n details: { rowCount: rows.length, checkoutIntentId: id },\n });\n }\n const row = rows[0] as Record<string, unknown>;\n return this.rowToCheckoutIntent(\n safeParse(\n CheckoutIntentRowSchema,\n {\n id: row.id,\n subject_id: row.subject_id,\n provider: row.provider,\n checkout_kind: row.checkout_kind,\n product_key: row.product_key,\n request_digest: row.request_digest,\n status: row.status,\n provider_session_id: row.provider_session_id,\n checkout_url: row.checkout_url,\n expires_at: row.expires_at,\n },\n \"PostgresBillingStore.getCheckoutIntent\",\n ),\n );\n }\n\n private rowToCheckoutIntent(row: z.infer<typeof CheckoutIntentRowSchema>): CheckoutIntent {\n return {\n id: row.id,\n subjectId: row.subject_id,\n provider: row.provider,\n checkoutKind: row.checkout_kind,\n productKey: row.product_key,\n requestDigest: Buffer.from(row.request_digest).toString(\"hex\"),\n status: row.status,\n providerSessionId: row.provider_session_id,\n checkoutUrl: row.checkout_url,\n expiresAt: row.expires_at instanceof Date ? row.expires_at.toISOString() : row.expires_at,\n };\n }\n\n private rowToOffer(row: BillingOfferRow | null): BillingOfferResult | null {\n if (!row) return null;\n return {\n offerId: row.id,\n offerKey: row.offerKey,\n planId: row.planId,\n plan: row.plan,\n interval: row.interval,\n intervalCount: row.intervalCount,\n grant:\n row.grantCredits === null\n ? null\n : {\n mode: \"cycle_grant\",\n credits: row.grantCredits,\n bucket: row.grantBucket,\n replacePrior: row.grantReplacePrior,\n },\n };\n }\n\n async resolveBillingOffer(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByPrice(provider, priceId ?? null, productId ?? null);\n return this.rowToOffer(r);\n }\n\n async resolveBillingOfferByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByLookup(provider, lookupKey);\n return this.rowToOffer(r);\n }\n\n async claimBillingEvent(\n provider: string,\n eventId: string,\n eventType: string,\n envelope?: Record<string, unknown>,\n ): Promise<BillingEventClaim> {\n const result = await this.billingEvent.claim(\n provider,\n eventId,\n eventType,\n JSON.stringify(envelope ?? { eventType }),\n );\n if (result.status === \"claimed\") {\n if (result.claim_token === null || result.event_id === null) {\n throw new StoreError(\"Billing event claim returned no claim identifiers\", {\n details: { provider, eventId },\n });\n }\n return {\n status: \"claimed\" as const,\n claimToken: result.claim_token,\n billingEventId: result.event_id,\n };\n }\n if (result.status === \"duplicate\") return { status: \"duplicate\" as const };\n if (result.status === \"busy\") return { status: \"busy\" as const };\n if (result.status === \"invalid_request\") return { status: \"invalid_request\" as const };\n if (result.status === \"idempotency_conflict\" || result.status === \"max_retries_exceeded\") {\n if (result.event_id === null) {\n throw new StoreError(\"Billing event terminal claim returned no event identifier\", {\n details: { provider, eventId, status: result.status },\n });\n }\n return { status: result.status, billingEventId: result.event_id };\n }\n throw new StoreError(\"Billing event claim returned an unsupported status\", {\n details: { provider, eventId, status: result.status },\n });\n }\n\n async completeBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n ): Promise<boolean> {\n return this.billingEvent.complete(provider, eventId, claimToken);\n }\n\n async failBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n error?: string,\n ): Promise<boolean> {\n return this.billingEvent.fail(\n provider,\n eventId,\n claimToken,\n optionalBoundedDiagnosticMessage(error) ?? undefined,\n );\n }\n\n async upsertBillingCustomer(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email?: string | null,\n ): Promise<void> {\n await this.billingCustomer.upsert(provider, providerCustomerId, userId, email ?? null);\n }\n\n async upsertBillingSubscription(state: BillingSubscriptionState): Promise<void> {\n await this.billingSubscription.upsert(state);\n }\n\n async getBillingCustomer(provider: string, providerCustomerId: string): Promise<string | null> {\n return this.billingCustomer.get(provider, providerCustomerId);\n }\n\n async getBillingSubscription(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.get(provider, providerSubscriptionId);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async createBillingSubscriptionChange(\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n const subscription = await this.billingSubscription.get(\n input.provider,\n input.providerSubscriptionId,\n );\n if (!subscription?.id) {\n throw new StoreError(\"subscription change requires a persisted subscription\", {\n retryable: true,\n details: {\n provider: input.provider,\n providerSubscriptionId: input.providerSubscriptionId,\n },\n });\n }\n return this.billingSubscriptionChange.create(subscription.id, input);\n }\n\n async getOpenBillingSubscriptionChange(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.billingSubscriptionChange.getOpen(provider, providerSubscriptionId);\n }\n\n async listExpiredGraceSubscriptions(\n now: string,\n limit = 100,\n ): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.listExpiredGraceSubscriptions(now, limit);\n return rows.map((row) => this.rowToSubscriptionState(row));\n }\n\n async markSubscriptionGraceExpired(\n subscriptionId: string,\n expectedGraceEndsAt: string,\n expiredAt = new Date().toISOString(),\n ): Promise<boolean> {\n return this.billingSubscription.markGraceExpired(\n subscriptionId,\n expectedGraceEndsAt,\n expiredAt,\n );\n }\n\n async updateBillingSubscriptionChange(\n id: string,\n update: BillingSubscriptionChangeUpdate,\n ): Promise<void> {\n await this.billingSubscriptionChange.update(id, update);\n }\n\n async getUserSubscription(\n userId: string,\n statuses?: string[],\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.getUserSubscription(userId, statuses);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async getUserSubscriptions(userId: string): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.getUserSubscriptions(userId);\n return rows.map((r) => this.rowToSubscriptionState(r));\n }\n\n async recordSubscriptionConflict(input: BillingSubscriptionConflictCreate): Promise<void> {\n await this.billingSubscription.recordConflict(input);\n }\n\n async selectSubscriptionEntitlementSource(\n userId: string,\n provider: string,\n providerSubscriptionId?: string | null,\n ): Promise<boolean> {\n return this.billingSubscription.selectEntitlementSource(\n userId,\n provider,\n providerSubscriptionId,\n );\n }\n\n private rowToTopup(r: BillingTopupRow | null): BillingTopupResult | null {\n if (!r) return null;\n const minAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.min_quantity,\n \"PostgresBillingStore.rowToTopup.minAmountMinor\",\n );\n const maxAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.max_quantity,\n \"PostgresBillingStore.rowToTopup.maxAmountMinor\",\n );\n return {\n topupId: r.id,\n topupKey: r.topup_key,\n creditsPerUnit: r.credits_per_unit,\n depositTo: r.bucket_key,\n amountMinor: r.amount_minor,\n currency: r.currency,\n minQuantity: r.min_quantity,\n maxQuantity: r.max_quantity,\n defaultQuantity: r.default_quantity,\n minAmountMinor,\n maxAmountMinor,\n };\n }\n\n async resolveCreditTopup(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByPrice(provider, priceId ?? null, productId ?? null);\n return this.rowToTopup(r);\n }\n\n async resolveCreditTopupByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByLookup(provider, lookupKey);\n return this.rowToTopup(r);\n }\n\n async computeTopupCredits(\n amountMinor: number,\n topupConfig: BillingTopupResult,\n ): Promise<Decimal> {\n if (!Number.isSafeInteger(amountMinor) || amountMinor < 0) {\n throw new TypeError(\"amountMinor must be a non-negative safe integer\");\n }\n const unitAmount = topupConfig.amountMinor;\n if (unitAmount <= 0 || amountMinor % unitAmount !== 0) return new Decimal(0);\n const quantity = amountMinor / unitAmount;\n if (quantity < topupConfig.minQuantity || quantity > topupConfig.maxQuantity) {\n return new Decimal(0);\n }\n return topupConfig.creditsPerUnit.mul(quantity);\n }\n\n async upsertBillingPayment(options: BillingPaymentUpsert): Promise<string> {\n return this.billingPayment.upsert(\n options.provider,\n options.providerPaymentId,\n options.providerInvoiceId ?? null,\n options.userId,\n options.amountMinor,\n options.taxMinor,\n options.currency,\n options.purpose,\n options.metadata ? JSON.stringify(options.metadata) : null,\n options.status,\n options.providerUpdatedAt,\n );\n }\n\n async createBillingCreditGrant(input: BillingCreditGrantCreate): Promise<string> {\n const rows = await this.queryFn(\n \"SELECT bursar.create_billing_credit_grant($1::uuid, $2::uuid, $3::uuid, $4, $5, $6::uuid) AS id\",\n [\n input.paymentId ?? null,\n input.subscriptionId ?? null,\n input.topupId ?? null,\n input.configuredCredits.toString(),\n input.quantity,\n input.billingEventId ?? null,\n ],\n );\n return requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createBillingCreditGrant\",\n );\n }\n\n async grantBillingCredit(\n grantId: string,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.grant_billing_credit($1::uuid, $2)\", [\n grantId,\n idempotencyKey,\n ]);\n return billingCreditPostingResult(rows, \"PostgresBillingStore.grantBillingCredit\");\n }\n\n async getBillingCreditGrantByPayment(paymentId: string): Promise<string | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_billing_credit_grant_by_payment($1::uuid)`,\n [paymentId],\n );\n const row = optionalRecordRow(rows, \"PostgresBillingStore.getBillingCreditGrantByPayment\");\n return row === null\n ? null\n : safeParse(postgresUuid, row.id, \"PostgresBillingStore.getBillingCreditGrantByPayment.id\");\n }\n\n async postBillingRefund(\n refundId: string,\n grantId: string,\n amountMinor: number,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\n \"SELECT * FROM bursar.post_billing_refund($1::uuid, $2::uuid, $3, $4)\",\n [refundId, grantId, amountMinor, idempotencyKey],\n );\n return billingCreditPostingResult(rows, \"PostgresBillingStore.postBillingRefund\");\n }\n\n async upsertBillingRefund(options: BillingRefundUpsert): Promise<string> {\n return this.billingRefund.upsert(\n options.provider,\n options.providerRefundId,\n options.providerPaymentId,\n options.userId,\n options.amountMinor,\n options.currency,\n options.reason ?? null,\n options.metadata ? JSON.stringify(options.metadata) : null,\n options.status,\n options.providerUpdatedAt,\n );\n }\n\n async upsertBillingInvoice(options: BillingInvoiceUpsert): Promise<void> {\n const subscription = options.providerSubscriptionId\n ? await this.billingSubscription.get(options.provider, options.providerSubscriptionId)\n : null;\n if (options.providerSubscriptionId && !subscription) {\n throw new StoreError(\"invoice subscription is not available\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerInvoiceId: options.providerInvoiceId,\n providerSubscriptionId: options.providerSubscriptionId ?? null,\n },\n });\n }\n await this.billingInvoice.upsert(\n options.userId,\n options.provider,\n options.providerInvoiceId,\n subscription?.id ? String(subscription.id) : null,\n options.status,\n options.amountDueMinor,\n options.amountPaidMinor,\n options.currency,\n options.periodStart ?? null,\n options.periodEnd ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async listBillingInvoices(userId: string) {\n return this.billingInvoice.listForUser(userId);\n }\n\n async upsertBillingDispute(options: BillingDisputeUpsert): Promise<void> {\n const payment = await this.billingPayment.getForRefund(\n options.provider,\n options.providerPaymentId,\n );\n if (!payment?.id) {\n throw new StoreError(\"dispute payment is required\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerDisputeId: options.providerDisputeId,\n providerPaymentId: options.providerPaymentId ?? null,\n },\n });\n }\n await this.billingDispute.upsert(\n options.provider,\n options.providerDisputeId,\n String(payment.id),\n options.status,\n options.reason ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async getBillingPayment(\n provider: string,\n providerPaymentId: string,\n ): Promise<BillingPaymentRecord | null> {\n const row = await this.billingPayment.getForRefund(provider, providerPaymentId);\n if (!row) return null;\n return {\n id: row.id,\n provider: row.provider,\n providerPaymentId: row.provider_payment_id,\n providerInvoiceId: row.provider_invoice_id,\n userId: row.subject_id,\n amountMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.amount_minor,\n \"PostgresBillingStore.getBillingPayment.amountMinor\",\n ),\n taxMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.tax_minor,\n \"PostgresBillingStore.getBillingPayment.taxMinor\",\n ),\n currency: row.currency,\n purpose: row.purpose,\n status: row.status,\n providerUpdatedAt:\n row.provider_updated_at instanceof Date\n ? row.provider_updated_at.toISOString()\n : row.provider_updated_at,\n metadata: row.metadata,\n };\n }\n\n private rowToSubscriptionState(r: SubscriptionRow): BillingSubscriptionState {\n return {\n subscriptionId: r.id,\n userId: r.user_id,\n provider: r.provider,\n providerSubscriptionId: r.provider_subscription_id,\n providerCustomerId: r.provider_customer_id,\n offerId: r.offer_id,\n offerKey: r.offer_key,\n planId: r.plan_id,\n plan: r.plan,\n status: r.status,\n currentPeriodStart: r.current_period_start,\n currentPeriodEnd: r.current_period_end,\n trialEnd: r.trial_end,\n cancelAt: r.cancel_at,\n endedAt: r.ended_at,\n graceEndsAt: r.grace_ends_at,\n graceExpiredAt: r.grace_expired_at,\n providerUpdatedAt: r.provider_updated_at,\n cancelAtPeriodEnd: r.cancel_at_period_end,\n interval: r.interval,\n intervalCount: r.interval_count,\n metadata: r.metadata,\n };\n }\n\n async getActiveCatalogDocument(): Promise<Record<string, unknown> | null> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.active_catalog_revision()\", []);\n if (rows.length === 0) return null;\n if (rows.length !== 1 || typeof rows[0] !== \"object\" || rows[0] === null) {\n throw new StoreError(\"active catalog revision returned a malformed row\", {\n details: { rowCount: rows.length },\n });\n }\n return safeParse(\n z.record(z.string(), z.unknown()),\n (rows[0] as Record<string, unknown>).source_document,\n \"PostgresBillingStore.getActiveCatalogDocument\",\n );\n }\n\n async pseudonymizeFinancialSubject(userId: string): Promise<boolean> {\n const rows = await this.queryFn(\n `SELECT bursar.pseudonymize_financial_subject($1::uuid) AS pseudonymized`,\n [userId],\n );\n return requireResultField(\n rows,\n \"pseudonymized\",\n pgBoolean,\n \"PostgresBillingStore.pseudonymizeFinancialSubject\",\n );\n }\n\n async getBillingPreferences(userId: string): Promise<BillingPreferences | null> {\n return this.billingPreferences.get(userId);\n }\n\n async upsertBillingPreferences(prefs: BillingPreferences): Promise<void> {\n await this.billingPreferences.upsert(prefs);\n }\n\n async getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n return this.billingAutoRecharge.getProfile(userId);\n }\n\n async upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void> {\n return this.billingAutoRecharge.upsertProfile(profile, options);\n }\n\n async claimAutoRechargeAttempt(\n input: AutoRechargeAttemptClaim,\n ): Promise<BillingAutoRechargeAttempt | null> {\n return this.billingAutoRecharge.claimAttempt(input);\n }\n\n async updateAutoRechargeAttempt(input: AutoRechargeAttemptUpdate): Promise<void> {\n return this.billingAutoRecharge.updateAttempt(input);\n }\n\n async updateAutoRechargeAttemptByProviderPayment(\n input: AutoRechargeProviderPaymentUpdate,\n ): Promise<void> {\n return this.billingAutoRecharge.updateAttemptByProviderPayment(input);\n }\n\n async countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number> {\n return this.billingAutoRecharge.countAttempts(userId, since);\n }\n\n async getBillingCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null> {\n const result = await this.billingCustomer.getByUserId(userId, provider ?? null);\n if (!result) return null;\n return {\n provider: result.provider,\n providerCustomerId: result.providerCustomerId,\n };\n }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type Decimal from "decimal.js";
|
|
1
|
+
import type { Decimal } from "decimal.js";
|
|
2
2
|
export declare const AUTO_RECHARGE_STATES: readonly ["disabled", "active", "paused"];
|
|
3
3
|
export type BillingAutoRechargeState = (typeof AUTO_RECHARGE_STATES)[number];
|
|
4
4
|
export type BillingAutoRechargeAttemptState = "claimed" | "submitted" | "processing" | "unknown" | "succeeded" | "failed" | "action_required";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auto-recharge.d.ts","sourceRoot":"","sources":["../../../src/billing/types/auto-recharge.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"auto-recharge.d.ts","sourceRoot":"","sources":["../../../src/billing/types/auto-recharge.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1C,eAAO,MAAM,oBAAoB,2CAA4C,CAAC;AAC9E,MAAM,MAAM,wBAAwB,GAAG,CAAC,OAAO,oBAAoB,CAAC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3B,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,yBAAyB;IACxC,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,EAAE,wBAAwB,CAAC;IAChC,gBAAgB,EAAE,OAAO,CAAC;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,kBAAkB,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,kBAAkB,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;CAC9B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auto-recharge.js","sourceRoot":"","sources":["../../../src/billing/types/auto-recharge.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,UAAU,EAAE,QAAQ,EAAE,QAAQ,CAAU,CAAC","sourcesContent":["import type Decimal from \"decimal.js\";\n\nexport const AUTO_RECHARGE_STATES = [\"disabled\", \"active\", \"paused\"] as const;\nexport type BillingAutoRechargeState = (typeof AUTO_RECHARGE_STATES)[number];\n\nexport type BillingAutoRechargeAttemptState =\n \"claimed\" | \"submitted\" | \"processing\" | \"unknown\" | \"succeeded\" | \"failed\" | \"action_required\";\n\nexport interface BillingAutoRechargeProfile {\n userId: string;\n enabled: boolean;\n state: BillingAutoRechargeState;\n armed?: boolean;\n provider: string | null;\n topupId: string | null;\n quantity: number;\n threshold: Decimal;\n maxChargesPerWindow: number | null;\n windowUnit: \"second\" | \"minute\" | \"hour\" | \"day\" | \"week\" | \"month\" | \"year\";\n windowCount: number;\n windowAnchor: \"calendar\" | \"rolling\";\n windowTimezone: string;\n updatedAt?: string | null;\n}\n\nexport interface BillingAutoRechargeAttempt {\n id: string;\n userId: string;\n provider: string;\n idempotencyKey: string;\n providerAttemptId: string | null;\n topupId: string;\n quantity: number;\n state: BillingAutoRechargeAttemptState;\n windowStart: string;\n windowEnd: string;\n quotedAmountMinor: number | null;\n currency: string | null;\n failureCode: string | null;\n failureMessage: string | null;\n metadata: Record<string, unknown>;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface BillingAutoRechargeStatus {\n enabled: boolean;\n state: BillingAutoRechargeState;\n thresholdCredits: Decimal;\n topupKey: string;\n quantity: number;\n maxRecharges: number;\n windowStart: string;\n windowEnd: string;\n rechargesInWindow: number;\n paymentMethodId: string | null;\n paymentMethodLast4: string | null;\n paymentMethodBrand: string | null;\n suspendedReason: string | null;\n pendingAttemptId: string | null;\n quoteAmountMinor: number | null;\n quoteCurrency: string | null;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"auto-recharge.js","sourceRoot":"","sources":["../../../src/billing/types/auto-recharge.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,UAAU,EAAE,QAAQ,EAAE,QAAQ,CAAU,CAAC","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\nexport const AUTO_RECHARGE_STATES = [\"disabled\", \"active\", \"paused\"] as const;\nexport type BillingAutoRechargeState = (typeof AUTO_RECHARGE_STATES)[number];\n\nexport type BillingAutoRechargeAttemptState =\n \"claimed\" | \"submitted\" | \"processing\" | \"unknown\" | \"succeeded\" | \"failed\" | \"action_required\";\n\nexport interface BillingAutoRechargeProfile {\n userId: string;\n enabled: boolean;\n state: BillingAutoRechargeState;\n armed?: boolean;\n provider: string | null;\n topupId: string | null;\n quantity: number;\n threshold: Decimal;\n maxChargesPerWindow: number | null;\n windowUnit: \"second\" | \"minute\" | \"hour\" | \"day\" | \"week\" | \"month\" | \"year\";\n windowCount: number;\n windowAnchor: \"calendar\" | \"rolling\";\n windowTimezone: string;\n updatedAt?: string | null;\n}\n\nexport interface BillingAutoRechargeAttempt {\n id: string;\n userId: string;\n provider: string;\n idempotencyKey: string;\n providerAttemptId: string | null;\n topupId: string;\n quantity: number;\n state: BillingAutoRechargeAttemptState;\n windowStart: string;\n windowEnd: string;\n quotedAmountMinor: number | null;\n currency: string | null;\n failureCode: string | null;\n failureMessage: string | null;\n metadata: Record<string, unknown>;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface BillingAutoRechargeStatus {\n enabled: boolean;\n state: BillingAutoRechargeState;\n thresholdCredits: Decimal;\n topupKey: string;\n quantity: number;\n maxRecharges: number;\n windowStart: string;\n windowEnd: string;\n rechargesInWindow: number;\n paymentMethodId: string | null;\n paymentMethodLast4: string | null;\n paymentMethodBrand: string | null;\n suspendedReason: string | null;\n pendingAttemptId: string | null;\n quoteAmountMinor: number | null;\n quoteCurrency: string | null;\n}\n"]}
|