@zonastery/bursar 0.0.2 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +118 -333
- package/dist/billing/auto-recharge-port.d.ts +27 -0
- package/dist/billing/auto-recharge-port.d.ts.map +1 -0
- package/dist/billing/auto-recharge-port.js +2 -0
- package/dist/billing/auto-recharge-port.js.map +1 -0
- package/dist/billing/auto-recharge-service.d.ts +43 -0
- package/dist/billing/auto-recharge-service.d.ts.map +1 -0
- package/dist/billing/auto-recharge-service.js +218 -0
- package/dist/billing/auto-recharge-service.js.map +1 -0
- package/dist/billing/billing-service.d.ts +71 -0
- package/dist/billing/billing-service.d.ts.map +1 -0
- package/dist/billing/billing-service.js +172 -0
- package/dist/billing/billing-service.js.map +1 -0
- package/dist/billing/billing-store.d.ts +45 -13
- 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 +149 -0
- package/dist/billing/contracts.d.ts.map +1 -0
- package/dist/billing/contracts.js +2 -0
- package/dist/billing/contracts.js.map +1 -0
- package/dist/billing/event-handlers.d.ts +57 -0
- package/dist/billing/event-handlers.d.ts.map +1 -0
- package/dist/billing/event-handlers.js +684 -0
- package/dist/billing/event-handlers.js.map +1 -0
- package/dist/billing/event-processor.d.ts +20 -0
- package/dist/billing/event-processor.d.ts.map +1 -0
- package/dist/billing/event-processor.js +131 -0
- package/dist/billing/event-processor.js.map +1 -0
- package/dist/billing/financial-event-handlers.d.ts +26 -0
- package/dist/billing/financial-event-handlers.d.ts.map +1 -0
- package/dist/billing/financial-event-handlers.js +241 -0
- package/dist/billing/financial-event-handlers.js.map +1 -0
- package/dist/billing/index.d.ts +9 -5
- package/dist/billing/index.d.ts.map +1 -1
- package/dist/billing/index.js +4 -4
- package/dist/billing/index.js.map +1 -1
- package/dist/billing/management.d.ts +59 -0
- package/dist/billing/management.d.ts.map +1 -0
- package/dist/billing/management.js +113 -0
- package/dist/billing/management.js.map +1 -0
- package/dist/billing/policy-window.d.ts +24 -0
- package/dist/billing/policy-window.d.ts.map +1 -0
- package/dist/billing/policy-window.js +88 -0
- package/dist/billing/policy-window.js.map +1 -0
- package/dist/billing/postgres/repositories/auto-recharge.d.ts +32 -0
- package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/auto-recharge.js +180 -0
- package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -0
- package/dist/billing/postgres/repositories/customer.d.ts +12 -0
- package/dist/billing/postgres/repositories/customer.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/customer.js +33 -0
- package/dist/billing/postgres/repositories/customer.js.map +1 -0
- package/dist/billing/postgres/repositories/dispute.d.ts +7 -0
- package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/dispute.js +18 -0
- package/dist/billing/postgres/repositories/dispute.js.map +1 -0
- package/dist/billing/postgres/repositories/event.d.ts +21 -0
- package/dist/billing/postgres/repositories/event.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/event.js +45 -0
- package/dist/billing/postgres/repositories/event.js.map +1 -0
- package/dist/billing/postgres/repositories/invoice.d.ts +9 -0
- package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/invoice.js +36 -0
- package/dist/billing/postgres/repositories/invoice.js.map +1 -0
- package/dist/billing/postgres/repositories/offer.d.ts +26 -0
- package/dist/billing/postgres/repositories/offer.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/offer.js +73 -0
- package/dist/billing/postgres/repositories/offer.js.map +1 -0
- package/dist/billing/postgres/repositories/payment.d.ts +32 -0
- package/dist/billing/postgres/repositories/payment.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/payment.js +78 -0
- package/dist/billing/postgres/repositories/payment.js.map +1 -0
- package/dist/billing/postgres/repositories/preferences.d.ts +15 -0
- package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/preferences.js +23 -0
- package/dist/billing/postgres/repositories/preferences.js.map +1 -0
- package/dist/billing/postgres/repositories/refund.d.ts +7 -0
- package/dist/billing/postgres/repositories/refund.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/refund.js +32 -0
- package/dist/billing/postgres/repositories/refund.js.map +1 -0
- package/dist/billing/postgres/repositories/subscription.d.ts +46 -0
- package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/subscription.js +187 -0
- package/dist/billing/postgres/repositories/subscription.js.map +1 -0
- package/dist/billing/postgres/repositories/topup.d.ts +27 -0
- package/dist/billing/postgres/repositories/topup.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/topup.js +51 -0
- package/dist/billing/postgres/repositories/topup.js.map +1 -0
- package/dist/billing/postgres/store.d.ts +89 -0
- package/dist/billing/postgres/store.d.ts.map +1 -0
- package/dist/billing/postgres/store.js +542 -0
- package/dist/billing/postgres/store.js.map +1 -0
- package/dist/billing/service-types.d.ts +37 -0
- package/dist/billing/service-types.d.ts.map +1 -0
- package/dist/billing/service-types.js +2 -0
- package/dist/billing/service-types.js.map +1 -0
- package/dist/billing/types/auto-recharge.d.ts +56 -0
- package/dist/billing/types/auto-recharge.d.ts.map +1 -0
- package/dist/billing/types/auto-recharge.js +2 -0
- package/dist/billing/types/auto-recharge.js.map +1 -0
- package/dist/billing/types/catalog.d.ts +47 -0
- package/dist/billing/types/catalog.d.ts.map +1 -0
- package/dist/billing/types/catalog.js +2 -0
- package/dist/billing/types/catalog.js.map +1 -0
- package/dist/billing/types/common.d.ts +16 -0
- package/dist/billing/types/common.d.ts.map +1 -0
- package/dist/billing/types/common.js +2 -0
- package/dist/billing/types/common.js.map +1 -0
- package/dist/billing/types/documents.d.ts +39 -0
- package/dist/billing/types/documents.d.ts.map +1 -0
- package/dist/billing/types/documents.js +2 -0
- package/dist/billing/types/documents.js.map +1 -0
- package/dist/billing/types/events.d.ts +75 -0
- package/dist/billing/types/events.d.ts.map +1 -0
- package/dist/billing/types/events.js +38 -0
- package/dist/billing/types/events.js.map +1 -0
- package/dist/billing/types/index.d.ts +8 -0
- package/dist/billing/types/index.d.ts.map +1 -0
- package/dist/billing/types/index.js +8 -0
- package/dist/billing/types/index.js.map +1 -0
- package/dist/billing/types/preferences.d.ts +13 -0
- package/dist/billing/types/preferences.d.ts.map +1 -0
- package/dist/billing/types/preferences.js +2 -0
- package/dist/billing/types/preferences.js.map +1 -0
- package/dist/billing/types/subscriptions.d.ts +97 -0
- package/dist/billing/types/subscriptions.d.ts.map +1 -0
- package/dist/billing/types/subscriptions.js +12 -0
- package/dist/billing/types/subscriptions.js.map +1 -0
- package/dist/breakdown.d.ts +3 -1
- package/dist/breakdown.d.ts.map +1 -1
- package/dist/breakdown.js +4 -1
- package/dist/breakdown.js.map +1 -1
- package/dist/browser.d.ts +8 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +7 -0
- package/dist/browser.js.map +1 -0
- package/dist/bursar.d.ts +84 -0
- package/dist/bursar.d.ts.map +1 -0
- package/dist/bursar.js +137 -0
- package/dist/bursar.js.map +1 -0
- package/dist/catalog.d.ts +62 -0
- package/dist/catalog.d.ts.map +1 -0
- package/dist/catalog.js +96 -0
- package/dist/catalog.js.map +1 -0
- package/dist/commerce/errors.d.ts +68 -0
- package/dist/commerce/errors.d.ts.map +1 -0
- package/dist/commerce/errors.js +105 -0
- package/dist/commerce/errors.js.map +1 -0
- package/dist/commerce/index.d.ts +6 -0
- package/dist/commerce/index.d.ts.map +1 -0
- package/dist/commerce/index.js +6 -0
- package/dist/commerce/index.js.map +1 -0
- package/dist/commerce/plan-change.d.ts +10 -0
- package/dist/commerce/plan-change.d.ts.map +1 -0
- package/dist/commerce/plan-change.js +42 -0
- package/dist/commerce/plan-change.js.map +1 -0
- package/dist/commerce/provider-registry.d.ts +18 -0
- package/dist/commerce/provider-registry.d.ts.map +1 -0
- package/dist/commerce/provider-registry.js +70 -0
- package/dist/commerce/provider-registry.js.map +1 -0
- package/dist/commerce/service.d.ts +73 -0
- package/dist/commerce/service.d.ts.map +1 -0
- package/dist/commerce/service.js +1016 -0
- package/dist/commerce/service.js.map +1 -0
- package/dist/commerce/types.d.ts +225 -0
- package/dist/commerce/types.d.ts.map +1 -0
- package/dist/commerce/types.js.map +1 -0
- package/dist/config/parse-access.d.ts +6 -0
- package/dist/config/parse-access.d.ts.map +1 -0
- package/dist/config/parse-access.js +72 -0
- package/dist/config/parse-access.js.map +1 -0
- package/dist/config/parse-commerce.d.ts +3 -0
- package/dist/config/parse-commerce.d.ts.map +1 -0
- package/dist/config/parse-commerce.js +236 -0
- package/dist/config/parse-commerce.js.map +1 -0
- package/dist/config/parse-credits.d.ts +3 -0
- package/dist/config/parse-credits.d.ts.map +1 -0
- package/dist/config/parse-credits.js +99 -0
- package/dist/config/parse-credits.js.map +1 -0
- package/dist/config/parse-plans.d.ts +5 -0
- package/dist/config/parse-plans.d.ts.map +1 -0
- package/dist/config/parse-plans.js +142 -0
- package/dist/config/parse-plans.js.map +1 -0
- package/dist/config/parse-pricing.d.ts +4 -0
- package/dist/config/parse-pricing.d.ts.map +1 -0
- package/dist/config/parse-pricing.js +252 -0
- package/dist/config/parse-pricing.js.map +1 -0
- package/dist/config/parse-utils.d.ts +18 -0
- package/dist/config/parse-utils.d.ts.map +1 -0
- package/dist/config/parse-utils.js +118 -0
- package/dist/config/parse-utils.js.map +1 -0
- package/dist/config/types.d.ts +340 -0
- package/dist/config/types.d.ts.map +1 -0
- package/dist/config/types.js +2 -0
- package/dist/config/types.js.map +1 -0
- package/dist/config.d.ts +12 -23
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +141 -377
- package/dist/config.js.map +1 -1
- package/dist/{stores → credits}/events.d.ts +6 -6
- package/dist/credits/events.d.ts.map +1 -0
- package/dist/{stores → credits}/events.js +5 -5
- package/dist/credits/events.js.map +1 -0
- package/dist/credits/lease-workflow.d.ts +90 -0
- package/dist/credits/lease-workflow.d.ts.map +1 -0
- package/dist/credits/lease-workflow.js +378 -0
- package/dist/credits/lease-workflow.js.map +1 -0
- package/dist/credits/low-balance-monitor.d.ts +26 -0
- package/dist/credits/low-balance-monitor.d.ts.map +1 -0
- package/dist/credits/low-balance-monitor.js +110 -0
- package/dist/credits/low-balance-monitor.js.map +1 -0
- package/dist/credits/postgres/repositories/analytics.d.ts +81 -0
- package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/analytics.js +153 -0
- package/dist/credits/postgres/repositories/analytics.js.map +1 -0
- package/dist/credits/postgres/repositories/balance.d.ts +66 -0
- package/dist/credits/postgres/repositories/balance.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/balance.js +139 -0
- package/dist/credits/postgres/repositories/balance.js.map +1 -0
- package/dist/credits/postgres/repositories/bucket.d.ts +25 -0
- package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/bucket.js +52 -0
- package/dist/credits/postgres/repositories/bucket.js.map +1 -0
- package/dist/credits/postgres/repositories/deduction.d.ts +64 -0
- package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/deduction.js +154 -0
- package/dist/credits/postgres/repositories/deduction.js.map +1 -0
- package/dist/credits/postgres/repositories/lease.d.ts +69 -0
- package/dist/credits/postgres/repositories/lease.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/lease.js +148 -0
- package/dist/credits/postgres/repositories/lease.js.map +1 -0
- package/dist/credits/postgres/repositories/plan.d.ts +110 -0
- package/dist/credits/postgres/repositories/plan.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/plan.js +194 -0
- package/dist/credits/postgres/repositories/plan.js.map +1 -0
- package/dist/credits/postgres/repositories/pricing.d.ts +28 -0
- package/dist/credits/postgres/repositories/pricing.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/pricing.js +76 -0
- package/dist/credits/postgres/repositories/pricing.js.map +1 -0
- package/dist/credits/postgres/repositories/team.d.ts +63 -0
- package/dist/credits/postgres/repositories/team.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/team.js +120 -0
- package/dist/credits/postgres/repositories/team.js.map +1 -0
- package/dist/credits/postgres/store.d.ts +89 -0
- package/dist/credits/postgres/store.d.ts.map +1 -0
- package/dist/credits/postgres/store.js +838 -0
- package/dist/credits/postgres/store.js.map +1 -0
- package/dist/credits/postgres/value-mappers.d.ts +17 -0
- package/dist/credits/postgres/value-mappers.d.ts.map +1 -0
- package/dist/credits/postgres/value-mappers.js +102 -0
- package/dist/credits/postgres/value-mappers.js.map +1 -0
- package/dist/credits/pricing-runtime.d.ts +35 -0
- package/dist/credits/pricing-runtime.d.ts.map +1 -0
- package/dist/credits/pricing-runtime.js +141 -0
- package/dist/credits/pricing-runtime.js.map +1 -0
- package/dist/credits/queries.d.ts +33 -0
- package/dist/credits/queries.d.ts.map +1 -0
- package/dist/credits/queries.js +71 -0
- package/dist/credits/queries.js.map +1 -0
- package/dist/credits/service-errors.d.ts +4 -0
- package/dist/credits/service-errors.d.ts.map +1 -0
- package/dist/credits/service-errors.js +57 -0
- package/dist/credits/service-errors.js.map +1 -0
- package/dist/credits/service-types.d.ts +122 -0
- package/dist/credits/service-types.d.ts.map +1 -0
- package/dist/credits/service-types.js +2 -0
- package/dist/credits/service-types.js.map +1 -0
- package/dist/credits/service.d.ts +220 -0
- package/dist/credits/service.d.ts.map +1 -0
- package/dist/credits/service.js +640 -0
- package/dist/credits/service.js.map +1 -0
- package/dist/credits/store.d.ts +172 -0
- package/dist/credits/store.d.ts.map +1 -0
- package/dist/{stores/credit-store.js → credits/store.js} +27 -43
- package/dist/credits/store.js.map +1 -0
- package/dist/credits/types/account.d.ts +82 -0
- package/dist/credits/types/account.d.ts.map +1 -0
- package/dist/credits/types/account.js +2 -0
- package/dist/credits/types/account.js.map +1 -0
- package/dist/credits/types/admission.d.ts +39 -0
- package/dist/credits/types/admission.d.ts.map +1 -0
- package/dist/credits/types/admission.js +2 -0
- package/dist/credits/types/admission.js.map +1 -0
- package/dist/credits/types/analytics.d.ts +52 -0
- package/dist/credits/types/analytics.d.ts.map +1 -0
- package/dist/credits/types/analytics.js +2 -0
- package/dist/credits/types/analytics.js.map +1 -0
- package/dist/credits/types/catalog.d.ts +71 -0
- package/dist/credits/types/catalog.d.ts.map +1 -0
- package/dist/credits/types/catalog.js +2 -0
- package/dist/credits/types/catalog.js.map +1 -0
- package/dist/credits/types/grants.d.ts +24 -0
- package/dist/credits/types/grants.d.ts.map +1 -0
- package/dist/credits/types/grants.js +2 -0
- package/dist/credits/types/grants.js.map +1 -0
- package/dist/credits/types/index.d.ts +9 -0
- package/dist/credits/types/index.d.ts.map +1 -0
- package/dist/credits/types/index.js +2 -0
- package/dist/credits/types/index.js.map +1 -0
- package/dist/credits/types/ledger.d.ts +87 -0
- package/dist/credits/types/ledger.d.ts.map +1 -0
- package/dist/credits/types/ledger.js +2 -0
- package/dist/credits/types/ledger.js.map +1 -0
- package/dist/credits/types/quotas.d.ts +40 -0
- package/dist/credits/types/quotas.d.ts.map +1 -0
- package/dist/credits/types/quotas.js +2 -0
- package/dist/credits/types/quotas.js.map +1 -0
- package/dist/credits/types/teams.d.ts +44 -0
- package/dist/credits/types/teams.d.ts.map +1 -0
- package/dist/credits/types/teams.js +2 -0
- package/dist/credits/types/teams.js.map +1 -0
- package/dist/engine.d.ts +18 -39
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +169 -145
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts +133 -25
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +173 -24
- package/dist/errors.js.map +1 -1
- package/dist/expr/ast.d.ts +46 -0
- package/dist/expr/ast.d.ts.map +1 -0
- package/dist/expr/ast.js +18 -0
- package/dist/expr/ast.js.map +1 -0
- package/dist/expr/evaluator.d.ts +4 -0
- package/dist/expr/evaluator.d.ts.map +1 -0
- package/dist/expr/evaluator.js +144 -0
- package/dist/expr/evaluator.js.map +1 -0
- package/dist/expr/language.d.ts +5 -0
- package/dist/expr/language.d.ts.map +1 -0
- package/dist/expr/language.js +73 -0
- package/dist/expr/language.js.map +1 -0
- package/dist/expr/parser.d.ts +24 -0
- package/dist/expr/parser.d.ts.map +1 -0
- package/dist/expr/parser.js +175 -0
- package/dist/expr/parser.js.map +1 -0
- package/dist/expr/tokenizer.d.ts +7 -0
- package/dist/expr/tokenizer.d.ts.map +1 -0
- package/dist/expr/tokenizer.js +85 -0
- package/dist/expr/tokenizer.js.map +1 -0
- package/dist/expr.d.ts +7 -58
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +41 -640
- package/dist/expr.js.map +1 -1
- package/dist/generated/pricing-config.schema.json +2792 -0
- package/dist/generated/pricing-config.types.d.ts +685 -0
- package/dist/generated/pricing-config.types.d.ts.map +1 -0
- package/dist/generated/pricing-config.types.js +8 -0
- package/dist/generated/pricing-config.types.js.map +1 -0
- package/dist/index.d.ts +23 -17
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -10
- package/dist/index.js.map +1 -1
- package/dist/load-pricing-file.d.ts.map +1 -1
- package/dist/load-pricing-file.js +8 -4
- package/dist/load-pricing-file.js.map +1 -1
- package/dist/metrics.d.ts +6 -16
- package/dist/metrics.d.ts.map +1 -1
- package/dist/metrics.js.map +1 -1
- package/dist/node.d.ts +9 -2
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +6 -2
- package/dist/node.js.map +1 -1
- package/dist/providers/_shared.d.ts +9 -0
- package/dist/providers/_shared.d.ts.map +1 -0
- package/dist/providers/_shared.js +52 -0
- package/dist/providers/_shared.js.map +1 -0
- package/dist/providers/dodo/client-contract.d.ts +106 -0
- package/dist/providers/dodo/client-contract.d.ts.map +1 -0
- package/dist/providers/dodo/client-contract.js +2 -0
- package/dist/providers/dodo/client-contract.js.map +1 -0
- package/dist/providers/dodo/event-mapper.d.ts +5 -3
- package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
- package/dist/providers/dodo/event-mapper.js +213 -38
- package/dist/providers/dodo/event-mapper.js.map +1 -1
- package/dist/providers/dodo/index.d.ts +1 -0
- package/dist/providers/dodo/index.d.ts.map +1 -1
- package/dist/providers/dodo/index.js.map +1 -1
- package/dist/providers/dodo/provider.d.ts +24 -14
- package/dist/providers/dodo/provider.d.ts.map +1 -1
- package/dist/providers/dodo/provider.js +249 -31
- package/dist/providers/dodo/provider.js.map +1 -1
- package/dist/providers/index.d.ts +3 -1
- package/dist/providers/index.d.ts.map +1 -1
- package/dist/providers/index.js +1 -0
- package/dist/providers/index.js.map +1 -1
- package/dist/providers/mock/index.js.map +1 -1
- package/dist/providers/mock/provider.d.ts +14 -10
- package/dist/providers/mock/provider.d.ts.map +1 -1
- package/dist/providers/mock/provider.js +78 -10
- package/dist/providers/mock/provider.js.map +1 -1
- package/dist/providers/stripe/event-mapper.d.ts +3 -3
- package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
- package/dist/providers/stripe/event-mapper.js +139 -30
- package/dist/providers/stripe/event-mapper.js.map +1 -1
- package/dist/providers/stripe/index.js.map +1 -1
- package/dist/providers/stripe/provider.d.ts +21 -12
- package/dist/providers/stripe/provider.d.ts.map +1 -1
- package/dist/providers/stripe/provider.js +175 -17
- package/dist/providers/stripe/provider.js.map +1 -1
- package/dist/providers/types.d.ts +128 -32
- package/dist/providers/types.d.ts.map +1 -1
- package/dist/providers/types.js +17 -1
- package/dist/providers/types.js.map +1 -1
- package/dist/retry.d.ts +35 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +70 -0
- package/dist/retry.js.map +1 -0
- package/dist/shared/diagnostics.d.ts +7 -0
- package/dist/shared/diagnostics.d.ts.map +1 -0
- package/dist/shared/diagnostics.js +18 -0
- package/dist/shared/diagnostics.js.map +1 -0
- package/dist/shared/logger.d.ts +10 -0
- package/dist/shared/logger.d.ts.map +1 -0
- package/dist/shared/logger.js +15 -0
- package/dist/shared/logger.js.map +1 -0
- package/dist/shared/postgres-client.d.ts +84 -0
- package/dist/shared/postgres-client.d.ts.map +1 -0
- package/dist/shared/postgres-client.js +337 -0
- package/dist/shared/postgres-client.js.map +1 -0
- package/dist/shared/postgres-errors.d.ts +11 -0
- package/dist/shared/postgres-errors.d.ts.map +1 -0
- package/dist/shared/postgres-errors.js +105 -0
- package/dist/shared/postgres-errors.js.map +1 -0
- package/dist/shared/postgres-types.d.ts +7 -0
- package/dist/shared/postgres-types.d.ts.map +1 -0
- package/dist/shared/postgres-types.js +2 -0
- package/dist/shared/postgres-types.js.map +1 -0
- package/dist/shared/postgres-validation.d.ts +8 -0
- package/dist/shared/postgres-validation.d.ts.map +1 -0
- package/dist/shared/postgres-validation.js +40 -0
- package/dist/shared/postgres-validation.js.map +1 -0
- package/dist/storage/adapters/clickhouse.d.ts +61 -0
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -0
- package/dist/storage/adapters/clickhouse.js +347 -0
- package/dist/storage/adapters/clickhouse.js.map +1 -0
- package/dist/storage/adapters/s3.d.ts +35 -0
- package/dist/storage/adapters/s3.d.ts.map +1 -0
- package/dist/storage/adapters/s3.js +100 -0
- package/dist/storage/adapters/s3.js.map +1 -0
- package/dist/storage/outbox-worker.d.ts +41 -0
- package/dist/storage/outbox-worker.d.ts.map +1 -0
- package/dist/storage/outbox-worker.js +146 -0
- package/dist/storage/outbox-worker.js.map +1 -0
- package/dist/storage/ports.d.ts +78 -0
- package/dist/storage/ports.d.ts.map +1 -0
- package/dist/storage/ports.js +2 -0
- package/dist/storage/ports.js.map +1 -0
- package/dist/storage/postgres-repository.d.ts +14 -0
- package/dist/storage/postgres-repository.d.ts.map +1 -0
- package/dist/storage/postgres-repository.js +140 -0
- package/dist/storage/postgres-repository.js.map +1 -0
- package/dist/storage/runtime.d.ts +77 -0
- package/dist/storage/runtime.d.ts.map +1 -0
- package/dist/storage/runtime.js +369 -0
- package/dist/storage/runtime.js.map +1 -0
- package/package.json +43 -21
- package/dist/allowance.d.ts +0 -48
- package/dist/allowance.d.ts.map +0 -1
- package/dist/allowance.js +0 -140
- package/dist/allowance.js.map +0 -1
- package/dist/billing/billing-manager.d.ts +0 -66
- package/dist/billing/billing-manager.d.ts.map +0 -1
- package/dist/billing/billing-manager.js +0 -560
- package/dist/billing/billing-manager.js.map +0 -1
- package/dist/billing/billing-types.d.ts +0 -203
- package/dist/billing/billing-types.d.ts.map +0 -1
- package/dist/billing/billing-types.js +0 -6
- package/dist/billing/billing-types.js.map +0 -1
- package/dist/billing/memory-billing-store.d.ts +0 -37
- package/dist/billing/memory-billing-store.d.ts.map +0 -1
- package/dist/billing/memory-billing-store.js +0 -197
- package/dist/billing/memory-billing-store.js.map +0 -1
- package/dist/billing/postgres-billing-store.d.ts +0 -35
- package/dist/billing/postgres-billing-store.d.ts.map +0 -1
- package/dist/billing/postgres-billing-store.js +0 -274
- package/dist/billing/postgres-billing-store.js.map +0 -1
- package/dist/billing/supabase-billing-store.d.ts +0 -29
- package/dist/billing/supabase-billing-store.d.ts.map +0 -1
- package/dist/billing/supabase-billing-store.js +0 -250
- package/dist/billing/supabase-billing-store.js.map +0 -1
- package/dist/manager.d.ts +0 -444
- package/dist/manager.d.ts.map +0 -1
- package/dist/manager.js +0 -1153
- package/dist/manager.js.map +0 -1
- package/dist/stores/credit-store.d.ts +0 -198
- package/dist/stores/credit-store.d.ts.map +0 -1
- package/dist/stores/credit-store.js.map +0 -1
- package/dist/stores/events.d.ts.map +0 -1
- package/dist/stores/events.js.map +0 -1
- package/dist/stores/memory-store.d.ts +0 -187
- package/dist/stores/memory-store.d.ts.map +0 -1
- package/dist/stores/memory-store.js +0 -1890
- package/dist/stores/memory-store.js.map +0 -1
- package/dist/stores/postgres-store.d.ts +0 -100
- package/dist/stores/postgres-store.d.ts.map +0 -1
- package/dist/stores/postgres-store.js +0 -891
- package/dist/stores/postgres-store.js.map +0 -1
- package/dist/stores/supabase-store.d.ts +0 -87
- package/dist/stores/supabase-store.d.ts.map +0 -1
- package/dist/stores/supabase-store.js +0 -948
- package/dist/stores/supabase-store.js.map +0 -1
- package/dist/types.d.ts +0 -463
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js.map +0 -1
- /package/dist/{types.js → commerce/types.js} +0 -0
|
@@ -1,1890 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from "crypto";
|
|
2
|
-
import Decimal from "decimal.js";
|
|
3
|
-
import { quantizeMoney } from "../expr.js";
|
|
4
|
-
import { StoreError } from "../errors.js";
|
|
5
|
-
import { resolveAllowanceWindow, resolveCalendarWindow } from "../allowance.js";
|
|
6
|
-
import { CreditStore } from "./credit-store.js";
|
|
7
|
-
const ZERO = new Decimal(0);
|
|
8
|
-
/** Coerce a presence-or-truthiness feature value per contract §5 (M6). */
|
|
9
|
-
function featurePresent(value) {
|
|
10
|
-
// Identity form: numeric 0 / "" count as present. Matches Python
|
|
11
|
-
// `value is not None and value is not False`. Do NOT use Boolean(value).
|
|
12
|
-
return value !== null && value !== undefined && value !== false;
|
|
13
|
-
}
|
|
14
|
-
/**
|
|
15
|
-
* Normalise a raw plan object (possibly snake_case from a JSON fixture or raw dict)
|
|
16
|
-
* into a proper PlanDefinition with Decimal fields. Accepts both camelCase and
|
|
17
|
-
* snake_case keys so configs written in either style work without preprocessing.
|
|
18
|
-
*/
|
|
19
|
-
function normalisePlanDefinition(planKey, raw) {
|
|
20
|
-
const p = raw;
|
|
21
|
-
const freeAllowanceRaw = (p["freeAllowance"] ?? p["free_allowance"]);
|
|
22
|
-
const defaultBillingModeRaw = (p["defaultBillingMode"] ??
|
|
23
|
-
p["billingMode"] ??
|
|
24
|
-
p["default_billing_mode"] ??
|
|
25
|
-
p["billing_mode"]);
|
|
26
|
-
const overdraftFloorRaw = (p["overdraftFloor"] ?? p["overdraft_floor"]);
|
|
27
|
-
const rateOverridesRaw = (p["rateOverrides"] ?? p["rate_overrides"]);
|
|
28
|
-
const perOperationRaw = (p["perOperation"] ?? p["per_operation"]);
|
|
29
|
-
const maxConcurrentRaw = (p["maxConcurrent"] ?? p["max_concurrent"]);
|
|
30
|
-
const allowancePeriodRaw = (p["allowancePeriod"] ?? p["allowance_period"]);
|
|
31
|
-
const featureLimitsRaw = (p["featureLimits"] ?? p["feature_limits"]);
|
|
32
|
-
const billingMode = (defaultBillingModeRaw === "overdraft" ? "overdraft" : "strict");
|
|
33
|
-
return {
|
|
34
|
-
id: p["id"] ?? planKey,
|
|
35
|
-
name: p["name"] ?? planKey,
|
|
36
|
-
freeAllowance: freeAllowanceRaw != null ? new Decimal(freeAllowanceRaw) : ZERO,
|
|
37
|
-
rateOverrides: rateOverridesRaw ?? null,
|
|
38
|
-
features: p["features"] ?? null,
|
|
39
|
-
featureLimits: normaliseFeatureLimitsMap(featureLimitsRaw),
|
|
40
|
-
defaultBillingMode: billingMode,
|
|
41
|
-
overdraftFloor: overdraftFloorRaw != null ? new Decimal(overdraftFloorRaw) : null,
|
|
42
|
-
maxConcurrent: maxConcurrentRaw ?? null,
|
|
43
|
-
perOperation: perOperationRaw ?? undefined,
|
|
44
|
-
allowancePeriod: allowancePeriodRaw ?? "calendar_month",
|
|
45
|
-
};
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* Normalise a raw `featureLimits`/`feature_limits` map (possibly snake_case,
|
|
49
|
-
* from a JSON fixture or raw dict) into typed `FeatureLimit` records. Mirrors
|
|
50
|
-
* `normalisePlanDefinition`'s camelCase/snake_case tolerance.
|
|
51
|
-
*/
|
|
52
|
-
function normaliseFeatureLimitsMap(raw) {
|
|
53
|
-
if (!raw)
|
|
54
|
-
return null;
|
|
55
|
-
const out = {};
|
|
56
|
-
for (const [featureKey, rawLimit] of Object.entries(raw)) {
|
|
57
|
-
const l = (rawLimit ?? {});
|
|
58
|
-
const maxCallsRaw = (l["maxCalls"] ?? l["max_calls"]);
|
|
59
|
-
out[featureKey] = {
|
|
60
|
-
maxCalls: maxCallsRaw != null ? Number(maxCallsRaw) : 0,
|
|
61
|
-
period: l["period"] ?? "monthly",
|
|
62
|
-
action: l["action"] ?? "deny",
|
|
63
|
-
};
|
|
64
|
-
}
|
|
65
|
-
return out;
|
|
66
|
-
}
|
|
67
|
-
/**
|
|
68
|
-
* Normalise a raw tier definition object (possibly snake_case from a JSON
|
|
69
|
-
* fixture or raw dict) into a proper `TierDefinition`. Accepts both camelCase
|
|
70
|
-
* and snake_case keys, mirroring `normalisePlanDefinition` (credit tiers).
|
|
71
|
-
*/
|
|
72
|
-
function normaliseTierDefinition(tierKey, raw) {
|
|
73
|
-
const t = raw;
|
|
74
|
-
const defaultTtlDaysRaw = (t["defaultTtlDays"] ?? t["default_ttl_days"]);
|
|
75
|
-
const allowOverdraftRaw = (t["allowOverdraft"] ?? t["allow_overdraft"]);
|
|
76
|
-
const isDefaultRaw = (t["isDefault"] ?? t["is_default"]);
|
|
77
|
-
return {
|
|
78
|
-
name: t["name"] ?? tierKey,
|
|
79
|
-
priority: Number(t["priority"] ?? 0),
|
|
80
|
-
expires: Boolean(t["expires"] ?? false),
|
|
81
|
-
defaultTtlDays: defaultTtlDaysRaw != null ? Number(defaultTtlDaysRaw) : null,
|
|
82
|
-
allowOverdraft: Boolean(allowOverdraftRaw ?? false),
|
|
83
|
-
isDefault: Boolean(isDefaultRaw ?? false),
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
/** Default lease TTL (seconds) for the lease lifecycle (interface plan §3). */
|
|
87
|
-
const DEFAULT_LEASE_TTL_SECONDS = 600;
|
|
88
|
-
/**
|
|
89
|
-
* Credit store backed by in-memory maps.
|
|
90
|
-
* Zero dependencies. Useful for unit testing and local development.
|
|
91
|
-
*
|
|
92
|
-
* Money is exact `Decimal` everywhere (contract §1). Because JavaScript is
|
|
93
|
-
* single-threaded, every mutating method performs its read-modify-write
|
|
94
|
-
* **synchronously** (no `await` between reading a balance and writing it back),
|
|
95
|
-
* so a `Promise.all` of concurrent deductions cannot interleave and double-spend
|
|
96
|
-
* (C2). A test-only injectable clock is exposed for deterministic time tests.
|
|
97
|
-
*/
|
|
98
|
-
export class MemoryStore extends CreditStore {
|
|
99
|
-
balances = new Map();
|
|
100
|
-
lifetime = new Map();
|
|
101
|
-
transactions = [];
|
|
102
|
-
reservations = new Map();
|
|
103
|
-
pricingVersion = 0;
|
|
104
|
-
pricingLabel = null;
|
|
105
|
-
pricingHistory = [];
|
|
106
|
-
planDefinitions = new Map();
|
|
107
|
-
// Credit tiers: definitions keyed by tier key (config key); balances keyed by
|
|
108
|
-
// a composite `${userId}:${tierKey}` string — JS Maps compare object/tuple
|
|
109
|
-
// keys by reference, so a plain string key is required (repo CLAUDE.md).
|
|
110
|
-
tierDefinitions = new Map();
|
|
111
|
-
tierBalances = new Map();
|
|
112
|
-
userPlanMap = new Map();
|
|
113
|
-
/** Timestamp each user's CURRENT plan was assigned — anchor for WS9 non-calendar periods. */
|
|
114
|
-
userPlanAssignedAt = new Map();
|
|
115
|
-
usageWindows = [];
|
|
116
|
-
spendCaps = [];
|
|
117
|
-
teams = new Map();
|
|
118
|
-
teamMembers = new Map();
|
|
119
|
-
/**
|
|
120
|
-
* Injectable clock for deterministic time-dependent tests. Defaults to the
|
|
121
|
-
* real wall clock. Tests set this to a fixed `Date` to avoid `setTimeout`
|
|
122
|
-
* sleeps (contract §8).
|
|
123
|
-
*/
|
|
124
|
-
clock = () => new Date();
|
|
125
|
-
/** Override the clock used for all time comparisons (test-only). */
|
|
126
|
-
setClock(clock) {
|
|
127
|
-
this.clock = clock;
|
|
128
|
-
}
|
|
129
|
-
now() {
|
|
130
|
-
return this.clock();
|
|
131
|
-
}
|
|
132
|
-
balance(userId) {
|
|
133
|
-
return this.balances.get(userId) ?? ZERO;
|
|
134
|
-
}
|
|
135
|
-
// ── Credit tiers: per-(user, tier) balance map ──────────────────────
|
|
136
|
-
tierBalanceKey(userId, tierKey) {
|
|
137
|
-
return `${userId}:${tierKey}`;
|
|
138
|
-
}
|
|
139
|
-
getTierBalance(userId, tierKey) {
|
|
140
|
-
return this.tierBalances.get(this.tierBalanceKey(userId, tierKey)) ?? ZERO;
|
|
141
|
-
}
|
|
142
|
-
adjustTierBalance(userId, tierKey, delta) {
|
|
143
|
-
const key = this.tierBalanceKey(userId, tierKey);
|
|
144
|
-
this.tierBalances.set(key, (this.tierBalances.get(key) ?? ZERO).plus(delta));
|
|
145
|
-
}
|
|
146
|
-
/**
|
|
147
|
-
* The tier-priority walk order (plan §4): configured tiers ascending by
|
|
148
|
-
* priority (ties broken by tier key ascending), or the synthetic
|
|
149
|
-
* `[{"default", priority: 0, allowOverdraft: true}]` when no tiers are
|
|
150
|
-
* configured — PLUS any tier keys not in that list, appended last (the
|
|
151
|
-
* config-drift safety net). `extraKeys`, when supplied, is the exact set of
|
|
152
|
-
* "orphaned" keys to consider (e.g. a debit's own tier_breakdown keys, for
|
|
153
|
-
* refund restoration); when omitted, orphaned keys are discovered from any
|
|
154
|
-
* nonzero balance the user currently holds under an unconfigured tier key.
|
|
155
|
-
*/
|
|
156
|
-
tierWalkOrder(userId, extraKeys) {
|
|
157
|
-
const configured = [...this.tierDefinitions.entries()]
|
|
158
|
-
.map(([tierKey, def]) => ({
|
|
159
|
-
tierKey,
|
|
160
|
-
priority: def.priority,
|
|
161
|
-
allowOverdraft: def.allowOverdraft ?? false,
|
|
162
|
-
}))
|
|
163
|
-
.sort((a, b) => a.priority - b.priority || a.tierKey.localeCompare(b.tierKey));
|
|
164
|
-
const base = configured.length > 0
|
|
165
|
-
? configured
|
|
166
|
-
: [{ tierKey: "default", priority: 0, allowOverdraft: true }];
|
|
167
|
-
const known = new Set(base.map((t) => t.tierKey));
|
|
168
|
-
const orphaned = new Set();
|
|
169
|
-
if (extraKeys) {
|
|
170
|
-
for (const k of extraKeys)
|
|
171
|
-
if (!known.has(k))
|
|
172
|
-
orphaned.add(k);
|
|
173
|
-
}
|
|
174
|
-
else {
|
|
175
|
-
const prefix = `${userId}:`;
|
|
176
|
-
for (const [key, bal] of this.tierBalances) {
|
|
177
|
-
if (!key.startsWith(prefix))
|
|
178
|
-
continue;
|
|
179
|
-
const tierKey = key.slice(prefix.length);
|
|
180
|
-
if (!known.has(tierKey) && !bal.isZero())
|
|
181
|
-
orphaned.add(tierKey);
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
return [
|
|
185
|
-
...base,
|
|
186
|
-
...[...orphaned]
|
|
187
|
-
.sort()
|
|
188
|
-
.map((tierKey) => ({ tierKey, priority: Number.MAX_SAFE_INTEGER, allowOverdraft: false })),
|
|
189
|
-
];
|
|
190
|
-
}
|
|
191
|
-
/**
|
|
192
|
-
* Resolve the `addCredits` target tier (plan §3):
|
|
193
|
-
* - no tiers configured ⇒ `tier` must be omitted/null/`"default"`.
|
|
194
|
-
* - tiers configured + explicit `tier` ⇒ must be a known key.
|
|
195
|
-
* - tiers configured + omitted `tier` ⇒ resolve via the `isDefault: true`
|
|
196
|
-
* tier, else throw (deliberately strict — never silently misroute money).
|
|
197
|
-
*/
|
|
198
|
-
resolveAddCreditsTier(tier) {
|
|
199
|
-
if (this.tierDefinitions.size === 0) {
|
|
200
|
-
if (tier != null && tier !== "default") {
|
|
201
|
-
throw new StoreError(`tier_not_found: ${tier}`);
|
|
202
|
-
}
|
|
203
|
-
return "default";
|
|
204
|
-
}
|
|
205
|
-
if (tier != null) {
|
|
206
|
-
if (!this.tierDefinitions.has(tier)) {
|
|
207
|
-
throw new StoreError(`tier_not_found: ${tier}`);
|
|
208
|
-
}
|
|
209
|
-
return tier;
|
|
210
|
-
}
|
|
211
|
-
for (const [key, def] of this.tierDefinitions) {
|
|
212
|
-
if (def.isDefault)
|
|
213
|
-
return key;
|
|
214
|
-
}
|
|
215
|
-
throw new StoreError("tier_required");
|
|
216
|
-
}
|
|
217
|
-
/**
|
|
218
|
-
* Reconcile a caller-supplied `expiresAt` against the resolved tier's
|
|
219
|
-
* `expires` flag (plan §3):
|
|
220
|
-
* - no tiers configured ⇒ unchanged existing behaviour (no restriction).
|
|
221
|
-
* - non-expiring tier + explicit `expiresAt` ⇒ throw.
|
|
222
|
-
* - expiring tier + explicit `expiresAt` ⇒ validate `> now`, use it.
|
|
223
|
-
* - expiring tier + omitted `expiresAt` ⇒ use `defaultTtlDays` if set,
|
|
224
|
-
* else throw.
|
|
225
|
-
*/
|
|
226
|
-
resolveAddCreditsExpiry(tierKey, expiresAt) {
|
|
227
|
-
if (this.tierDefinitions.size === 0) {
|
|
228
|
-
return expiresAt ?? null;
|
|
229
|
-
}
|
|
230
|
-
const def = this.tierDefinitions.get(tierKey);
|
|
231
|
-
if (!def)
|
|
232
|
-
return expiresAt ?? null;
|
|
233
|
-
if (!def.expires) {
|
|
234
|
-
if (expiresAt != null) {
|
|
235
|
-
throw new StoreError(`tier_does_not_expire: ${tierKey}`);
|
|
236
|
-
}
|
|
237
|
-
return null;
|
|
238
|
-
}
|
|
239
|
-
if (expiresAt != null) {
|
|
240
|
-
if (expiresAt <= this.now()) {
|
|
241
|
-
throw new StoreError(`invalid_expires_at: ${expiresAt.toISOString()} must be in the future`);
|
|
242
|
-
}
|
|
243
|
-
return expiresAt;
|
|
244
|
-
}
|
|
245
|
-
if (def.defaultTtlDays != null) {
|
|
246
|
-
return new Date(this.now().getTime() + def.defaultTtlDays * 86_400_000);
|
|
247
|
-
}
|
|
248
|
-
throw new StoreError("expires_at_required");
|
|
249
|
-
}
|
|
250
|
-
/**
|
|
251
|
-
* Billing-period key (YYYY-MM-DD) used as the in-memory usage-window bucket.
|
|
252
|
-
*
|
|
253
|
-
* When an explicit ``periodStart`` is supplied (WS9 — a non-calendar-month
|
|
254
|
-
* allowance window resolved by the manager), it is used directly. Otherwise
|
|
255
|
-
* falls back to the UTC calendar-month start for the current clock, exactly
|
|
256
|
-
* matching pre-WS9 behaviour.
|
|
257
|
-
*/
|
|
258
|
-
billingPeriod(periodStart) {
|
|
259
|
-
if (periodStart)
|
|
260
|
-
return periodStart.toISOString().slice(0, 10);
|
|
261
|
-
const now = this.now();
|
|
262
|
-
return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1))
|
|
263
|
-
.toISOString()
|
|
264
|
-
.slice(0, 10);
|
|
265
|
-
}
|
|
266
|
-
async setup(_databaseUrl) {
|
|
267
|
-
return {
|
|
268
|
-
tablesCreated: [
|
|
269
|
-
"001_core_schema.sql",
|
|
270
|
-
"002_credit_rpcs.sql",
|
|
271
|
-
"003_pricing_config.sql",
|
|
272
|
-
"004_plans.sql",
|
|
273
|
-
"005_spend_caps.sql",
|
|
274
|
-
"006_refunds_and_expiry.sql",
|
|
275
|
-
"007_analytics.sql",
|
|
276
|
-
"008_teams.sql",
|
|
277
|
-
"009_deduct_and_leases.sql",
|
|
278
|
-
"010_credit_tiers.sql",
|
|
279
|
-
// NOTE: the contract doc for this feature named this migration
|
|
280
|
-
// "011_feature_limits.sql", but "011_lazy_expiry.sql" already occupies
|
|
281
|
-
// that slot in python/src/bursar/sql/ (a numbering collision between two
|
|
282
|
-
// parallel work tracks) — using the next free number here instead.
|
|
283
|
-
"012_feature_limits.sql",
|
|
284
|
-
],
|
|
285
|
-
rpcsCreated: [],
|
|
286
|
-
errors: [],
|
|
287
|
-
success: true,
|
|
288
|
-
};
|
|
289
|
-
}
|
|
290
|
-
async getBalance(userId) {
|
|
291
|
-
return {
|
|
292
|
-
userId,
|
|
293
|
-
balance: this.balance(userId),
|
|
294
|
-
lifetimePurchased: this.lifetime.get(userId) ?? ZERO,
|
|
295
|
-
};
|
|
296
|
-
}
|
|
297
|
-
async addCredits(userId, amount, type = "adjustment", metadata, expiresAt, tier, idempotencyKey) {
|
|
298
|
-
// Idempotency (user-scoped): replay the original result, mirroring the
|
|
299
|
-
// idiom used by deductWithAllowance/settleLease/refundCredits — scan for an
|
|
300
|
-
// existing transaction for this user whose metadata.idempotencyKey matches.
|
|
301
|
-
if (idempotencyKey) {
|
|
302
|
-
const existing = this.transactions.find((t) => t.userId === userId && t.metadata?.["idempotencyKey"] === idempotencyKey);
|
|
303
|
-
if (existing) {
|
|
304
|
-
return {
|
|
305
|
-
transactionId: existing.id,
|
|
306
|
-
userId,
|
|
307
|
-
amount: existing.amount,
|
|
308
|
-
newBalance: this.balance(userId),
|
|
309
|
-
lifetimePurchased: this.lifetime.get(userId) ?? ZERO,
|
|
310
|
-
tier: existing.metadata?.["tier"] ?? "default",
|
|
311
|
-
idempotent: true,
|
|
312
|
-
};
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
// L2: reject non-finite amounts always, and non-positive amounts unless this
|
|
316
|
-
// is an explicit `adjustment` (parity with SQL `credits_add`). A negative or
|
|
317
|
-
// zero purchase/grant must never drive the balance below the floor.
|
|
318
|
-
if (!amount.isFinite()) {
|
|
319
|
-
throw new StoreError(`addCredits: amount must be finite, got ${amount.toString()}`);
|
|
320
|
-
}
|
|
321
|
-
if (type !== "adjustment" && amount.lte(0)) {
|
|
322
|
-
throw new StoreError(`addCredits: ${type} amount must be > 0, got ${amount.toString()} (use type='adjustment' for negative/zero)`);
|
|
323
|
-
}
|
|
324
|
-
// Credit tiers: resolve the target tier and reconcile expiresAt against it.
|
|
325
|
-
const resolvedTier = this.resolveAddCreditsTier(tier);
|
|
326
|
-
const resolvedExpiresAt = this.resolveAddCreditsExpiry(resolvedTier, expiresAt);
|
|
327
|
-
const amt = quantizeMoney(amount);
|
|
328
|
-
const current = this.balance(userId);
|
|
329
|
-
this.balances.set(userId, current.plus(amt));
|
|
330
|
-
this.adjustTierBalance(userId, resolvedTier, amt);
|
|
331
|
-
const lifetimeAdd = type === "purchase" ? amt : ZERO;
|
|
332
|
-
this.lifetime.set(userId, (this.lifetime.get(userId) ?? ZERO).plus(lifetimeAdd));
|
|
333
|
-
const txId = randomUUID();
|
|
334
|
-
const txMeta = metadata ? this.cleanMetadata(metadata) : {};
|
|
335
|
-
txMeta["tier"] = resolvedTier;
|
|
336
|
-
if (idempotencyKey)
|
|
337
|
-
txMeta["idempotencyKey"] = idempotencyKey;
|
|
338
|
-
const tx = {
|
|
339
|
-
id: txId,
|
|
340
|
-
userId,
|
|
341
|
-
amount: amt,
|
|
342
|
-
type,
|
|
343
|
-
metadata: txMeta,
|
|
344
|
-
createdAt: this.now(),
|
|
345
|
-
expiresAt: resolvedExpiresAt,
|
|
346
|
-
};
|
|
347
|
-
this.transactions.push(tx);
|
|
348
|
-
return {
|
|
349
|
-
transactionId: txId,
|
|
350
|
-
userId,
|
|
351
|
-
amount: amt,
|
|
352
|
-
newBalance: this.balance(userId),
|
|
353
|
-
lifetimePurchased: this.lifetime.get(userId) ?? ZERO,
|
|
354
|
-
tier: resolvedTier,
|
|
355
|
-
idempotent: false,
|
|
356
|
-
};
|
|
357
|
-
}
|
|
358
|
-
cleanMetadata(metadata) {
|
|
359
|
-
const out = {};
|
|
360
|
-
for (const [k, v] of Object.entries(metadata)) {
|
|
361
|
-
if (v != null)
|
|
362
|
-
out[k] = v;
|
|
363
|
-
}
|
|
364
|
-
return out;
|
|
365
|
-
}
|
|
366
|
-
/**
|
|
367
|
-
* Tier-priority walk (plan §4), shared by `deductWithAllowance` and
|
|
368
|
-
* `settleLease`: drains `net` from tier balances in priority order (exact
|
|
369
|
-
* greedy Decimal walk, never a proportional split). If `net` exceeds the
|
|
370
|
-
* sum of configured-tier balances (only reachable under a negative floor /
|
|
371
|
-
* overdraft — the floor check already guarantees coverage otherwise), the
|
|
372
|
-
* remainder routes to the `allowOverdraft` tier, else the max-priority
|
|
373
|
-
* tier, else `"default"`. Returns a breakdown whose values sum exactly to
|
|
374
|
-
* `net`.
|
|
375
|
-
*/
|
|
376
|
-
walkTiers(userId, net) {
|
|
377
|
-
const order = this.tierWalkOrder(userId);
|
|
378
|
-
const breakdown = {};
|
|
379
|
-
let remaining = net;
|
|
380
|
-
for (const t of order) {
|
|
381
|
-
if (remaining.lte(0))
|
|
382
|
-
break;
|
|
383
|
-
const bal = this.getTierBalance(userId, t.tierKey);
|
|
384
|
-
const take = Decimal.min(bal, remaining);
|
|
385
|
-
if (take.gt(0)) {
|
|
386
|
-
breakdown[t.tierKey] = (breakdown[t.tierKey] ?? ZERO).plus(take);
|
|
387
|
-
this.adjustTierBalance(userId, t.tierKey, take.negated());
|
|
388
|
-
remaining = remaining.minus(take);
|
|
389
|
-
}
|
|
390
|
-
}
|
|
391
|
-
if (remaining.gt(0)) {
|
|
392
|
-
const overdraftTier = order.find((t) => t.allowOverdraft);
|
|
393
|
-
const sink = overdraftTier
|
|
394
|
-
? overdraftTier.tierKey
|
|
395
|
-
: order.length > 0
|
|
396
|
-
? order.reduce((best, t) => (t.priority > best.priority ? t : best)).tierKey
|
|
397
|
-
: "default";
|
|
398
|
-
breakdown[sink] = (breakdown[sink] ?? ZERO).plus(remaining);
|
|
399
|
-
this.adjustTierBalance(userId, sink, remaining.negated());
|
|
400
|
-
}
|
|
401
|
-
return breakdown;
|
|
402
|
-
}
|
|
403
|
-
/**
|
|
404
|
-
* Atomic "calculate-then-charge" in a single synchronous critical section
|
|
405
|
-
* (contract §2). Mirrors the SQL `deduct_with_allowance` RPC:
|
|
406
|
-
* idempotency-first → consume allowance → cap on net → balance floor → debit.
|
|
407
|
-
* A `deny` cap or floor breach consumes NO allowance.
|
|
408
|
-
*/
|
|
409
|
-
async deductWithAllowance(userId, amount, options) {
|
|
410
|
-
const idempotencyKey = options?.idempotencyKey ?? null;
|
|
411
|
-
const minBalance = options?.minBalance ?? ZERO;
|
|
412
|
-
const model = options?.model ?? null;
|
|
413
|
-
const metadata = options?.metadata ?? null;
|
|
414
|
-
const periodStart = options?.periodStart ?? null;
|
|
415
|
-
const feature = options?.feature ?? null;
|
|
416
|
-
const featureLimit = options?.featureLimit ?? null;
|
|
417
|
-
const featurePeriodStart = options?.featurePeriodStart ?? null;
|
|
418
|
-
// ── critical section (synchronous; no awaits) ──
|
|
419
|
-
// Reject non-finite / negative amounts. Zero is a valid no-op charge.
|
|
420
|
-
if (!amount.isFinite() || amount.lt(0)) {
|
|
421
|
-
return {
|
|
422
|
-
transactionId: "",
|
|
423
|
-
userId,
|
|
424
|
-
amount: ZERO,
|
|
425
|
-
allowanceConsumed: ZERO,
|
|
426
|
-
balanceAfter: this.balance(userId),
|
|
427
|
-
idempotent: false,
|
|
428
|
-
capWarning: null,
|
|
429
|
-
featureLimitWarning: null,
|
|
430
|
-
error: "invalid_amount",
|
|
431
|
-
};
|
|
432
|
-
}
|
|
433
|
-
// (2) Idempotency (user-scoped): replay the original result.
|
|
434
|
-
if (idempotencyKey) {
|
|
435
|
-
const existing = this.transactions.find((t) => t.userId === userId && t.metadata?.["idempotencyKey"] === idempotencyKey);
|
|
436
|
-
if (existing) {
|
|
437
|
-
const consumed = existing.metadata?.["allowanceConsumed"];
|
|
438
|
-
return {
|
|
439
|
-
transactionId: existing.id,
|
|
440
|
-
userId,
|
|
441
|
-
amount: existing.amount.abs(),
|
|
442
|
-
allowanceConsumed: consumed instanceof Decimal ? consumed : new Decimal(String(consumed ?? 0)),
|
|
443
|
-
balanceAfter: this.balance(userId),
|
|
444
|
-
idempotent: true,
|
|
445
|
-
capWarning: null,
|
|
446
|
-
featureLimitWarning: null,
|
|
447
|
-
// Idempotent replay echoes the ORIGINAL tier breakdown — never recomputed.
|
|
448
|
-
tierBreakdown: existing.metadata?.["tierBreakdown"] ?? null,
|
|
449
|
-
};
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
const gross = quantizeMoney(amount);
|
|
453
|
-
// (3) Allowance: consume as much of the cost as remaining free allowance covers.
|
|
454
|
-
let consume = ZERO;
|
|
455
|
-
const planId = this.userPlanMap.get(userId);
|
|
456
|
-
const planDef = planId ? this.planDefinitions.get(planId) : undefined;
|
|
457
|
-
if (planId && planDef) {
|
|
458
|
-
const billingPeriod = this.billingPeriod(periodStart);
|
|
459
|
-
let used = ZERO;
|
|
460
|
-
for (const w of this.usageWindows) {
|
|
461
|
-
if (w.userId === userId && w.planId === planId && w.billingPeriod === billingPeriod) {
|
|
462
|
-
used = used.plus(w.usage);
|
|
463
|
-
}
|
|
464
|
-
}
|
|
465
|
-
const remaining = Decimal.max(ZERO, planDef.freeAllowance.minus(used));
|
|
466
|
-
consume = Decimal.min(remaining, gross);
|
|
467
|
-
}
|
|
468
|
-
const net = gross.minus(consume);
|
|
469
|
-
// (4) Spend cap on the NET amount. Deny aborts WITHOUT consuming allowance.
|
|
470
|
-
let capWarning = null;
|
|
471
|
-
const userCaps = this.spendCaps.filter((c) => c.userId === userId && (c.model == null || c.model === model));
|
|
472
|
-
// Deny caps first (most restrictive), then soft caps.
|
|
473
|
-
const ordered = [...userCaps].sort((a, b) => (a.action === "deny" ? 0 : 1) - (b.action === "deny" ? 0 : 1));
|
|
474
|
-
for (const cap of ordered) {
|
|
475
|
-
const windowStart = this.capWindowStart(cap.type);
|
|
476
|
-
const currentSpend = this.spendInWindow(userId, windowStart, cap.model);
|
|
477
|
-
if (currentSpend.plus(net).gt(cap.limit)) {
|
|
478
|
-
if (cap.action === "deny") {
|
|
479
|
-
// Abort: no allowance consumed, no balance change.
|
|
480
|
-
return {
|
|
481
|
-
transactionId: "",
|
|
482
|
-
userId,
|
|
483
|
-
amount: ZERO,
|
|
484
|
-
allowanceConsumed: ZERO,
|
|
485
|
-
balanceAfter: this.balance(userId),
|
|
486
|
-
idempotent: false,
|
|
487
|
-
capWarning: null,
|
|
488
|
-
featureLimitWarning: null,
|
|
489
|
-
error: "cap_reached",
|
|
490
|
-
};
|
|
491
|
-
}
|
|
492
|
-
if (capWarning === null)
|
|
493
|
-
capWarning = cap.action;
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
// (4b) Feature limit: ledger-derived count of prior committed `usage`
|
|
497
|
-
// transactions tagged metadata.feature === feature within
|
|
498
|
-
// [featurePeriodStart, featurePeriodEnd). Skipped entirely when no
|
|
499
|
-
// feature/limit was resolved by the caller (manager).
|
|
500
|
-
let featureLimitWarning = null;
|
|
501
|
-
if (feature != null && featureLimit != null && featurePeriodStart != null) {
|
|
502
|
-
const featurePeriodEnd = resolveCalendarWindow(featurePeriodStart, featureLimit.period).end;
|
|
503
|
-
const count = this.featureUsageCount(userId, feature, featurePeriodStart, featurePeriodEnd);
|
|
504
|
-
if (count >= featureLimit.maxCalls) {
|
|
505
|
-
if (featureLimit.action === "deny") {
|
|
506
|
-
return {
|
|
507
|
-
transactionId: "",
|
|
508
|
-
userId,
|
|
509
|
-
amount: ZERO,
|
|
510
|
-
allowanceConsumed: ZERO,
|
|
511
|
-
balanceAfter: this.balance(userId),
|
|
512
|
-
idempotent: false,
|
|
513
|
-
capWarning: null,
|
|
514
|
-
featureLimitWarning: null,
|
|
515
|
-
error: "feature_limit_reached",
|
|
516
|
-
};
|
|
517
|
-
}
|
|
518
|
-
featureLimitWarning = featureLimit.action;
|
|
519
|
-
}
|
|
520
|
-
}
|
|
521
|
-
// (5) Balance floor on the NET amount.
|
|
522
|
-
const current = this.balance(userId);
|
|
523
|
-
if (current.minus(net).lt(minBalance)) {
|
|
524
|
-
return {
|
|
525
|
-
transactionId: "",
|
|
526
|
-
userId,
|
|
527
|
-
amount: ZERO,
|
|
528
|
-
allowanceConsumed: ZERO,
|
|
529
|
-
balanceAfter: current,
|
|
530
|
-
idempotent: false,
|
|
531
|
-
capWarning: null,
|
|
532
|
-
featureLimitWarning: null,
|
|
533
|
-
error: "insufficient_credits",
|
|
534
|
-
};
|
|
535
|
-
}
|
|
536
|
-
// (6) Commit: consume allowance, debit balance, insert ledger row.
|
|
537
|
-
if (consume.gt(0) && planId) {
|
|
538
|
-
this.incrementUsageWindowSync(userId, planId, consume, periodStart);
|
|
539
|
-
}
|
|
540
|
-
this.balances.set(userId, current.minus(net));
|
|
541
|
-
const tierBreakdown = this.walkTiers(userId, net);
|
|
542
|
-
const txMeta = metadata ? this.cleanMetadata(metadata) : {};
|
|
543
|
-
if (idempotencyKey)
|
|
544
|
-
txMeta["idempotencyKey"] = idempotencyKey;
|
|
545
|
-
if (model != null)
|
|
546
|
-
txMeta["model"] = model;
|
|
547
|
-
// Tag metadata.feature whenever `feature` is given, regardless of whether a
|
|
548
|
-
// limit is currently configured — this is what makes the ledger-derived
|
|
549
|
-
// count accurate once a limit is enabled later.
|
|
550
|
-
if (feature != null)
|
|
551
|
-
txMeta["feature"] = feature;
|
|
552
|
-
txMeta["allowanceConsumed"] = consume;
|
|
553
|
-
txMeta["tierBreakdown"] = tierBreakdown;
|
|
554
|
-
const txId = randomUUID();
|
|
555
|
-
this.transactions.push({
|
|
556
|
-
id: txId,
|
|
557
|
-
userId,
|
|
558
|
-
amount: net.negated(),
|
|
559
|
-
type: "usage",
|
|
560
|
-
metadata: txMeta,
|
|
561
|
-
createdAt: this.now(),
|
|
562
|
-
});
|
|
563
|
-
return {
|
|
564
|
-
transactionId: txId,
|
|
565
|
-
userId,
|
|
566
|
-
amount: net,
|
|
567
|
-
allowanceConsumed: consume,
|
|
568
|
-
balanceAfter: current.minus(net),
|
|
569
|
-
idempotent: false,
|
|
570
|
-
capWarning,
|
|
571
|
-
featureLimitWarning,
|
|
572
|
-
tierBreakdown,
|
|
573
|
-
};
|
|
574
|
-
}
|
|
575
|
-
// ── Lease lifecycle (atomic admission) ─────────────────────────────
|
|
576
|
-
/** Active, unexpired holds for a user (synchronous — no awaits in callers). */
|
|
577
|
-
activeLeases(userId, operationType) {
|
|
578
|
-
const now = this.now();
|
|
579
|
-
const out = [];
|
|
580
|
-
for (const r of this.reservations.values()) {
|
|
581
|
-
if (r.userId === userId &&
|
|
582
|
-
r.status === "active" &&
|
|
583
|
-
r.expiresAt > now &&
|
|
584
|
-
(operationType === undefined || r.operationType === operationType)) {
|
|
585
|
-
out.push(r);
|
|
586
|
-
}
|
|
587
|
-
}
|
|
588
|
-
return out;
|
|
589
|
-
}
|
|
590
|
-
async createLease(userId, amount, operationType, options) {
|
|
591
|
-
const billingMode = options?.billingMode ?? "strict";
|
|
592
|
-
const floor = options?.floor ?? ZERO;
|
|
593
|
-
const maxConcurrent = options?.maxConcurrent ?? null;
|
|
594
|
-
const ttlSeconds = options?.ttlSeconds ?? DEFAULT_LEASE_TTL_SECONDS;
|
|
595
|
-
const model = options?.model ?? null;
|
|
596
|
-
const overdraftFloor = options?.overdraftFloor ?? null;
|
|
597
|
-
const metadata = options?.metadata ?? null;
|
|
598
|
-
const feature = options?.feature ?? null;
|
|
599
|
-
const featureLimit = options?.featureLimit ?? null;
|
|
600
|
-
const featurePeriodStart = options?.featurePeriodStart ?? null;
|
|
601
|
-
// ── critical section (synchronous; no awaits) ──
|
|
602
|
-
if (!amount.isFinite() || amount.lte(0)) {
|
|
603
|
-
return {
|
|
604
|
-
leaseId: "",
|
|
605
|
-
userId,
|
|
606
|
-
amount: ZERO,
|
|
607
|
-
available: ZERO,
|
|
608
|
-
reservedTotal: ZERO,
|
|
609
|
-
billingMode,
|
|
610
|
-
expiresAt: "",
|
|
611
|
-
error: "invalid_amount",
|
|
612
|
-
};
|
|
613
|
-
}
|
|
614
|
-
// Ensure a balance row exists (overdraft admits brand-new users at 0).
|
|
615
|
-
const balance = this.balance(userId);
|
|
616
|
-
if (!this.balances.has(userId))
|
|
617
|
-
this.balances.set(userId, balance);
|
|
618
|
-
// (2) Concurrency: count active leases for this operation type.
|
|
619
|
-
if (maxConcurrent !== null &&
|
|
620
|
-
this.activeLeases(userId, operationType).length >= maxConcurrent) {
|
|
621
|
-
return {
|
|
622
|
-
leaseId: "",
|
|
623
|
-
userId,
|
|
624
|
-
amount: ZERO,
|
|
625
|
-
available: ZERO,
|
|
626
|
-
reservedTotal: ZERO,
|
|
627
|
-
billingMode,
|
|
628
|
-
expiresAt: "",
|
|
629
|
-
error: "concurrency_limit",
|
|
630
|
-
};
|
|
631
|
-
}
|
|
632
|
-
// (3) Deny spend cap at admission: a blocked user can't even start.
|
|
633
|
-
const userCaps = this.spendCaps.filter((c) => c.userId === userId && (c.model == null || c.model === model));
|
|
634
|
-
for (const cap of userCaps) {
|
|
635
|
-
if (cap.action !== "deny")
|
|
636
|
-
continue;
|
|
637
|
-
const windowStart = this.capWindowStart(cap.type);
|
|
638
|
-
const spend = this.spendInWindow(userId, windowStart, cap.model);
|
|
639
|
-
if (spend.plus(amount).gt(cap.limit)) {
|
|
640
|
-
return {
|
|
641
|
-
leaseId: "",
|
|
642
|
-
userId,
|
|
643
|
-
amount: ZERO,
|
|
644
|
-
available: ZERO,
|
|
645
|
-
reservedTotal: ZERO,
|
|
646
|
-
billingMode,
|
|
647
|
-
expiresAt: "",
|
|
648
|
-
error: "cap_reached",
|
|
649
|
-
};
|
|
650
|
-
}
|
|
651
|
-
}
|
|
652
|
-
// (3b) Deny-only feature limit at admission — same ledger-derived count as
|
|
653
|
-
// deductWithAllowance/settleLease, but only ever enforces 'deny' (warn/notify
|
|
654
|
-
// are not checked here: nothing has been charged yet, so there is nothing to
|
|
655
|
-
// warn about). Skipped when no feature/limit was resolved by the caller.
|
|
656
|
-
if (feature != null &&
|
|
657
|
-
featureLimit != null &&
|
|
658
|
-
featureLimit.action === "deny" &&
|
|
659
|
-
featurePeriodStart != null) {
|
|
660
|
-
const featurePeriodEnd = resolveCalendarWindow(featurePeriodStart, featureLimit.period).end;
|
|
661
|
-
const count = this.featureUsageCount(userId, feature, featurePeriodStart, featurePeriodEnd);
|
|
662
|
-
if (count >= featureLimit.maxCalls) {
|
|
663
|
-
return {
|
|
664
|
-
leaseId: "",
|
|
665
|
-
userId,
|
|
666
|
-
amount: ZERO,
|
|
667
|
-
available: ZERO,
|
|
668
|
-
reservedTotal: ZERO,
|
|
669
|
-
billingMode,
|
|
670
|
-
expiresAt: "",
|
|
671
|
-
error: "feature_limit_reached",
|
|
672
|
-
};
|
|
673
|
-
}
|
|
674
|
-
}
|
|
675
|
-
// (4) available = balance − Σ active holds; reject if floor breached.
|
|
676
|
-
let reservedTotal = ZERO;
|
|
677
|
-
for (const r of this.activeLeases(userId))
|
|
678
|
-
reservedTotal = reservedTotal.plus(r.amount);
|
|
679
|
-
const available = balance.minus(reservedTotal);
|
|
680
|
-
if (available.minus(amount).lt(floor)) {
|
|
681
|
-
return {
|
|
682
|
-
leaseId: "",
|
|
683
|
-
userId,
|
|
684
|
-
amount: ZERO,
|
|
685
|
-
available,
|
|
686
|
-
reservedTotal,
|
|
687
|
-
billingMode,
|
|
688
|
-
expiresAt: "",
|
|
689
|
-
error: "insufficient_credits",
|
|
690
|
-
};
|
|
691
|
-
}
|
|
692
|
-
// (5) Insert the active lease.
|
|
693
|
-
const lid = randomUUID();
|
|
694
|
-
const expiresAt = new Date(this.now().getTime() + ttlSeconds * 1000);
|
|
695
|
-
this.reservations.set(lid, {
|
|
696
|
-
id: lid,
|
|
697
|
-
userId,
|
|
698
|
-
amount,
|
|
699
|
-
operationType,
|
|
700
|
-
metadata: metadata ? this.cleanMetadata(metadata) : undefined,
|
|
701
|
-
expiresAt,
|
|
702
|
-
status: "active",
|
|
703
|
-
billingMode,
|
|
704
|
-
overdraftFloor,
|
|
705
|
-
settleTxId: null,
|
|
706
|
-
});
|
|
707
|
-
return {
|
|
708
|
-
leaseId: lid,
|
|
709
|
-
userId,
|
|
710
|
-
amount,
|
|
711
|
-
available: available.minus(amount),
|
|
712
|
-
reservedTotal: reservedTotal.plus(amount),
|
|
713
|
-
billingMode,
|
|
714
|
-
expiresAt: expiresAt.toISOString(),
|
|
715
|
-
};
|
|
716
|
-
}
|
|
717
|
-
/** Build an idempotent-replay `DeductionResult` from a ledger row (synchronous). */
|
|
718
|
-
replayDeduction(tx, userId, balance) {
|
|
719
|
-
const consumed = tx.metadata?.["allowanceConsumed"];
|
|
720
|
-
return {
|
|
721
|
-
transactionId: tx.id,
|
|
722
|
-
userId,
|
|
723
|
-
amount: tx.amount.abs(),
|
|
724
|
-
allowanceConsumed: consumed instanceof Decimal ? consumed : new Decimal(String(consumed ?? 0)),
|
|
725
|
-
balanceAfter: balance,
|
|
726
|
-
idempotent: true,
|
|
727
|
-
capWarning: null,
|
|
728
|
-
featureLimitWarning: null,
|
|
729
|
-
// Idempotent replay echoes the ORIGINAL tier breakdown — never recomputed.
|
|
730
|
-
tierBreakdown: tx.metadata?.["tierBreakdown"] ?? null,
|
|
731
|
-
};
|
|
732
|
-
}
|
|
733
|
-
/**
|
|
734
|
-
* Validate a lease for settle. Returns a short-circuit result, or `null` to
|
|
735
|
-
* proceed (synchronous):
|
|
736
|
-
* - missing / other-user / released → ``lease_not_found``
|
|
737
|
-
* - already settled → idempotent replay of the original charge
|
|
738
|
-
* - TTL elapsed → mark ``expired`` and return ``lease_expired``
|
|
739
|
-
*/
|
|
740
|
-
settleLeaseState(lease, userId, balance) {
|
|
741
|
-
const now = this.now();
|
|
742
|
-
if (!lease || lease.userId !== userId || lease.status === "released") {
|
|
743
|
-
return {
|
|
744
|
-
transactionId: "",
|
|
745
|
-
userId,
|
|
746
|
-
amount: ZERO,
|
|
747
|
-
allowanceConsumed: ZERO,
|
|
748
|
-
balanceAfter: balance,
|
|
749
|
-
idempotent: false,
|
|
750
|
-
capWarning: null,
|
|
751
|
-
featureLimitWarning: null,
|
|
752
|
-
error: "lease_not_found",
|
|
753
|
-
};
|
|
754
|
-
}
|
|
755
|
-
if (lease.status === "settled") {
|
|
756
|
-
if (lease.settleTxId) {
|
|
757
|
-
const tx = this.transactions.find((t) => t.id === lease.settleTxId);
|
|
758
|
-
if (tx)
|
|
759
|
-
return this.replayDeduction(tx, userId, balance);
|
|
760
|
-
}
|
|
761
|
-
return {
|
|
762
|
-
transactionId: "",
|
|
763
|
-
userId,
|
|
764
|
-
amount: ZERO,
|
|
765
|
-
allowanceConsumed: ZERO,
|
|
766
|
-
balanceAfter: balance,
|
|
767
|
-
idempotent: true,
|
|
768
|
-
capWarning: null,
|
|
769
|
-
featureLimitWarning: null,
|
|
770
|
-
};
|
|
771
|
-
}
|
|
772
|
-
if (lease.status === "expired" || lease.expiresAt <= now) {
|
|
773
|
-
lease.status = "expired";
|
|
774
|
-
return {
|
|
775
|
-
transactionId: "",
|
|
776
|
-
userId,
|
|
777
|
-
amount: ZERO,
|
|
778
|
-
allowanceConsumed: ZERO,
|
|
779
|
-
balanceAfter: balance,
|
|
780
|
-
idempotent: false,
|
|
781
|
-
capWarning: null,
|
|
782
|
-
featureLimitWarning: null,
|
|
783
|
-
error: "lease_expired",
|
|
784
|
-
};
|
|
785
|
-
}
|
|
786
|
-
return null;
|
|
787
|
-
}
|
|
788
|
-
async settleLease(userId, leaseId, amount, options) {
|
|
789
|
-
const idempotencyKey = options?.idempotencyKey ?? null;
|
|
790
|
-
const model = options?.model ?? null;
|
|
791
|
-
const metadata = options?.metadata ?? null;
|
|
792
|
-
const periodStart = options?.periodStart ?? null;
|
|
793
|
-
const feature = options?.feature ?? null;
|
|
794
|
-
const featureLimit = options?.featureLimit ?? null;
|
|
795
|
-
const featurePeriodStart = options?.featurePeriodStart ?? null;
|
|
796
|
-
// ── critical section (synchronous; no awaits) ──
|
|
797
|
-
if (!amount.isFinite() || amount.lt(0)) {
|
|
798
|
-
return {
|
|
799
|
-
transactionId: "",
|
|
800
|
-
userId,
|
|
801
|
-
amount: ZERO,
|
|
802
|
-
allowanceConsumed: ZERO,
|
|
803
|
-
balanceAfter: this.balance(userId),
|
|
804
|
-
idempotent: false,
|
|
805
|
-
capWarning: null,
|
|
806
|
-
featureLimitWarning: null,
|
|
807
|
-
error: "invalid_amount",
|
|
808
|
-
};
|
|
809
|
-
}
|
|
810
|
-
const balance = this.balance(userId);
|
|
811
|
-
// Idempotency replay (user-scoped).
|
|
812
|
-
if (idempotencyKey) {
|
|
813
|
-
const existing = this.transactions.find((t) => t.userId === userId && t.metadata?.["idempotencyKey"] === idempotencyKey);
|
|
814
|
-
if (existing)
|
|
815
|
-
return this.replayDeduction(existing, userId, balance);
|
|
816
|
-
}
|
|
817
|
-
const lease = this.reservations.get(leaseId);
|
|
818
|
-
const precheck = this.settleLeaseState(lease, userId, balance);
|
|
819
|
-
if (precheck !== null)
|
|
820
|
-
return precheck;
|
|
821
|
-
// settleLeaseState returns early on a missing lease, so `lease` is defined.
|
|
822
|
-
const activeLease = lease;
|
|
823
|
-
// Active & unexpired → settle. De-clamped: charge the ACTUAL cost (D5), never
|
|
824
|
-
// clamp to the lease hold.
|
|
825
|
-
// Zero-cost: release the lease without charging (resolves M3).
|
|
826
|
-
if (amount.eq(0)) {
|
|
827
|
-
activeLease.status = "settled";
|
|
828
|
-
return {
|
|
829
|
-
transactionId: "",
|
|
830
|
-
userId,
|
|
831
|
-
amount: ZERO,
|
|
832
|
-
allowanceConsumed: ZERO,
|
|
833
|
-
balanceAfter: balance,
|
|
834
|
-
idempotent: false,
|
|
835
|
-
capWarning: null,
|
|
836
|
-
featureLimitWarning: null,
|
|
837
|
-
};
|
|
838
|
-
}
|
|
839
|
-
// Allowance consume on the actual cost.
|
|
840
|
-
let consume = ZERO;
|
|
841
|
-
const planId = this.userPlanMap.get(userId);
|
|
842
|
-
const planDef = planId ? this.planDefinitions.get(planId) : undefined;
|
|
843
|
-
if (planId && planDef) {
|
|
844
|
-
const billingPeriod = this.billingPeriod(periodStart);
|
|
845
|
-
let used = ZERO;
|
|
846
|
-
for (const w of this.usageWindows) {
|
|
847
|
-
if (w.userId === userId && w.planId === planId && w.billingPeriod === billingPeriod) {
|
|
848
|
-
used = used.plus(w.usage);
|
|
849
|
-
}
|
|
850
|
-
}
|
|
851
|
-
const remaining = Decimal.max(ZERO, planDef.freeAllowance.minus(used));
|
|
852
|
-
consume = Decimal.min(remaining, amount);
|
|
853
|
-
}
|
|
854
|
-
// Floor enforcement (C1): clamp net so balance stays ≥ floor.
|
|
855
|
-
// The floor is derived from the lease's persisted billingMode and
|
|
856
|
-
// overdraftFloor; options.minBalance is the engine's strict-mode floor.
|
|
857
|
-
const settleFloor = activeLease.billingMode === "strict"
|
|
858
|
-
? (options?.minBalance ?? ZERO)
|
|
859
|
-
: (activeLease.overdraftFloor ?? ZERO);
|
|
860
|
-
const maxDebit = Decimal.max(ZERO, balance.minus(settleFloor));
|
|
861
|
-
let net = amount.minus(consume);
|
|
862
|
-
if (net.gt(maxDebit)) {
|
|
863
|
-
net = maxDebit;
|
|
864
|
-
// Re-clamp consume so it never exceeds amount - net.
|
|
865
|
-
if (net.lt(amount)) {
|
|
866
|
-
consume = Decimal.min(consume, amount.minus(net));
|
|
867
|
-
}
|
|
868
|
-
}
|
|
869
|
-
// Spend cap is ADVISORY at settle (work is done): record the strongest
|
|
870
|
-
// breaching action, never block (interface plan §7). 'deny' surfaces as a
|
|
871
|
-
// non-blocking signal the manager re-emits as credits.cap_reached.
|
|
872
|
-
let capWarning = null;
|
|
873
|
-
const userCaps = this.spendCaps
|
|
874
|
-
.filter((c) => c.userId === userId && (c.model == null || c.model === model))
|
|
875
|
-
.sort((a, b) => (a.action === "deny" ? 0 : 1) - (b.action === "deny" ? 0 : 1));
|
|
876
|
-
for (const cap of userCaps) {
|
|
877
|
-
const windowStart = this.capWindowStart(cap.type);
|
|
878
|
-
const spend = this.spendInWindow(userId, windowStart, cap.model);
|
|
879
|
-
if (spend.plus(net).gt(cap.limit) &&
|
|
880
|
-
(capWarning === null || (capWarning !== "deny" && cap.action === "deny"))) {
|
|
881
|
-
capWarning = cap.action;
|
|
882
|
-
}
|
|
883
|
-
}
|
|
884
|
-
// Feature limit is ADVISORY at settle (work is done, never blocks): a
|
|
885
|
-
// breach — even a configured 'deny' — only sets featureLimitWarning
|
|
886
|
-
// ("prefer deny", mirroring capWarning's resolution above).
|
|
887
|
-
let featureLimitWarning = null;
|
|
888
|
-
if (feature != null && featureLimit != null && featurePeriodStart != null) {
|
|
889
|
-
const featurePeriodEnd = resolveCalendarWindow(featurePeriodStart, featureLimit.period).end;
|
|
890
|
-
const count = this.featureUsageCount(userId, feature, featurePeriodStart, featurePeriodEnd);
|
|
891
|
-
if (count >= featureLimit.maxCalls) {
|
|
892
|
-
featureLimitWarning = featureLimit.action;
|
|
893
|
-
}
|
|
894
|
-
}
|
|
895
|
-
if (consume.gt(0) && planId) {
|
|
896
|
-
this.incrementUsageWindowSync(userId, planId, consume, periodStart);
|
|
897
|
-
}
|
|
898
|
-
this.balances.set(userId, balance.minus(net));
|
|
899
|
-
const tierBreakdown = this.walkTiers(userId, net);
|
|
900
|
-
const txMeta = metadata ? this.cleanMetadata(metadata) : {};
|
|
901
|
-
if (model != null)
|
|
902
|
-
txMeta["model"] = model;
|
|
903
|
-
if (idempotencyKey)
|
|
904
|
-
txMeta["idempotencyKey"] = idempotencyKey;
|
|
905
|
-
// Tag metadata.feature whenever `feature` is given — this is what makes
|
|
906
|
-
// this call countable by future checks (settle_lease is the ONLY place a
|
|
907
|
-
// leased operation's usage transaction is inserted).
|
|
908
|
-
if (feature != null)
|
|
909
|
-
txMeta["feature"] = feature;
|
|
910
|
-
txMeta["allowanceConsumed"] = consume;
|
|
911
|
-
txMeta["tierBreakdown"] = tierBreakdown;
|
|
912
|
-
const txId = randomUUID();
|
|
913
|
-
this.transactions.push({
|
|
914
|
-
id: txId,
|
|
915
|
-
userId,
|
|
916
|
-
amount: net.negated(),
|
|
917
|
-
type: "usage",
|
|
918
|
-
metadata: txMeta,
|
|
919
|
-
createdAt: this.now(),
|
|
920
|
-
});
|
|
921
|
-
activeLease.status = "settled";
|
|
922
|
-
activeLease.settleTxId = txId;
|
|
923
|
-
return {
|
|
924
|
-
transactionId: txId,
|
|
925
|
-
userId,
|
|
926
|
-
amount: net,
|
|
927
|
-
allowanceConsumed: consume,
|
|
928
|
-
balanceAfter: balance.minus(net),
|
|
929
|
-
idempotent: false,
|
|
930
|
-
capWarning,
|
|
931
|
-
featureLimitWarning,
|
|
932
|
-
tierBreakdown,
|
|
933
|
-
};
|
|
934
|
-
}
|
|
935
|
-
async releaseLease(userId, leaseId) {
|
|
936
|
-
const lease = this.reservations.get(leaseId);
|
|
937
|
-
if (!lease || lease.userId !== userId) {
|
|
938
|
-
return { leaseId, userId, released: false, reason: "not_found" };
|
|
939
|
-
}
|
|
940
|
-
if (lease.status === "settled") {
|
|
941
|
-
return { leaseId, userId, released: false, reason: "already_settled" };
|
|
942
|
-
}
|
|
943
|
-
if (lease.status === "released") {
|
|
944
|
-
return { leaseId, userId, released: false, reason: "already_released" };
|
|
945
|
-
}
|
|
946
|
-
lease.status = "released";
|
|
947
|
-
return { leaseId, userId, released: true, reason: "released" };
|
|
948
|
-
}
|
|
949
|
-
async renewLease(userId, leaseId, ttlSeconds) {
|
|
950
|
-
const now = this.now();
|
|
951
|
-
const lease = this.reservations.get(leaseId);
|
|
952
|
-
if (!lease ||
|
|
953
|
-
lease.userId !== userId ||
|
|
954
|
-
lease.status === "released" ||
|
|
955
|
-
lease.status === "settled") {
|
|
956
|
-
return {
|
|
957
|
-
leaseId,
|
|
958
|
-
userId,
|
|
959
|
-
amount: ZERO,
|
|
960
|
-
available: ZERO,
|
|
961
|
-
reservedTotal: ZERO,
|
|
962
|
-
billingMode: "strict",
|
|
963
|
-
expiresAt: "",
|
|
964
|
-
error: "lease_not_found",
|
|
965
|
-
};
|
|
966
|
-
}
|
|
967
|
-
if (lease.status === "expired" || lease.expiresAt <= now) {
|
|
968
|
-
lease.status = "expired";
|
|
969
|
-
return {
|
|
970
|
-
leaseId,
|
|
971
|
-
userId,
|
|
972
|
-
amount: ZERO,
|
|
973
|
-
available: ZERO,
|
|
974
|
-
reservedTotal: ZERO,
|
|
975
|
-
billingMode: lease.billingMode,
|
|
976
|
-
expiresAt: "",
|
|
977
|
-
error: "lease_expired",
|
|
978
|
-
};
|
|
979
|
-
}
|
|
980
|
-
lease.expiresAt = new Date(now.getTime() + ttlSeconds * 1000);
|
|
981
|
-
let reservedTotal = ZERO;
|
|
982
|
-
for (const r of this.activeLeases(userId))
|
|
983
|
-
reservedTotal = reservedTotal.plus(r.amount);
|
|
984
|
-
const balance = this.balance(userId);
|
|
985
|
-
return {
|
|
986
|
-
leaseId,
|
|
987
|
-
userId,
|
|
988
|
-
amount: lease.amount,
|
|
989
|
-
available: balance.minus(reservedTotal),
|
|
990
|
-
reservedTotal,
|
|
991
|
-
billingMode: lease.billingMode,
|
|
992
|
-
expiresAt: lease.expiresAt.toISOString(),
|
|
993
|
-
};
|
|
994
|
-
}
|
|
995
|
-
async getAvailable(userId) {
|
|
996
|
-
const balance = this.balance(userId);
|
|
997
|
-
let reserved = ZERO;
|
|
998
|
-
for (const r of this.activeLeases(userId))
|
|
999
|
-
reserved = reserved.plus(r.amount);
|
|
1000
|
-
return { userId, balance, reserved, available: balance.minus(reserved) };
|
|
1001
|
-
}
|
|
1002
|
-
async getActivePricing() {
|
|
1003
|
-
// LOW hygiene fix: return the stored record id (stable), not a fresh randomUUID()
|
|
1004
|
-
// every call. A fresh id breaks any caching keyed on config id.
|
|
1005
|
-
const active = [...this.pricingHistory].reverse().find((h) => h.active);
|
|
1006
|
-
if (!active)
|
|
1007
|
-
return null;
|
|
1008
|
-
return { id: active.id, config: active.config, version: active.version };
|
|
1009
|
-
}
|
|
1010
|
-
async setActivePricing(config, label) {
|
|
1011
|
-
// Deactivate all previous versions, then insert a new active entry.
|
|
1012
|
-
for (const h of this.pricingHistory)
|
|
1013
|
-
h.active = false;
|
|
1014
|
-
this.pricingVersion += 1;
|
|
1015
|
-
this.pricingLabel = label ?? null;
|
|
1016
|
-
const id = randomUUID();
|
|
1017
|
-
this.pricingHistory.push({
|
|
1018
|
-
id,
|
|
1019
|
-
version: this.pricingVersion,
|
|
1020
|
-
label: this.pricingLabel,
|
|
1021
|
-
active: true,
|
|
1022
|
-
config,
|
|
1023
|
-
createdAt: new Date().toISOString(),
|
|
1024
|
-
});
|
|
1025
|
-
// H1 fix: key planDefinitions by the config dict key (plan_key), not plan.id.
|
|
1026
|
-
// Python MemoryStore and SQL both resolve setUserPlan("u1","pro") by looking up
|
|
1027
|
-
// the dict key "pro"; JS must match or setUserPlan resolves to null/planless.
|
|
1028
|
-
if ("plans" in config && config.plans) {
|
|
1029
|
-
for (const [planKey, planData] of Object.entries(config.plans)) {
|
|
1030
|
-
this.planDefinitions.set(planKey, normalisePlanDefinition(planKey, planData));
|
|
1031
|
-
}
|
|
1032
|
-
}
|
|
1033
|
-
if ("tiers" in config && config.tiers) {
|
|
1034
|
-
for (const [tierKey, tierData] of Object.entries(config.tiers)) {
|
|
1035
|
-
this.tierDefinitions.set(tierKey, normaliseTierDefinition(tierKey, tierData));
|
|
1036
|
-
}
|
|
1037
|
-
}
|
|
1038
|
-
return id;
|
|
1039
|
-
}
|
|
1040
|
-
// H8: pricing history / activation — parity with Python base.py:293-312.
|
|
1041
|
-
async getPricingHistory() {
|
|
1042
|
-
return this.pricingHistory
|
|
1043
|
-
.slice()
|
|
1044
|
-
.reverse()
|
|
1045
|
-
.map((h) => ({
|
|
1046
|
-
id: h.id,
|
|
1047
|
-
version: h.version,
|
|
1048
|
-
label: h.label,
|
|
1049
|
-
active: h.active,
|
|
1050
|
-
createdAt: h.createdAt,
|
|
1051
|
-
}));
|
|
1052
|
-
}
|
|
1053
|
-
async getPricingConfig(version) {
|
|
1054
|
-
const entry = this.pricingHistory.find((h) => h.version === version);
|
|
1055
|
-
if (!entry)
|
|
1056
|
-
return null;
|
|
1057
|
-
return { id: entry.id, config: entry.config, version: entry.version };
|
|
1058
|
-
}
|
|
1059
|
-
async activatePricing(version) {
|
|
1060
|
-
const entry = this.pricingHistory.find((h) => h.version === version);
|
|
1061
|
-
if (!entry)
|
|
1062
|
-
throw new Error(`pricing version ${version} not found`);
|
|
1063
|
-
for (const h of this.pricingHistory)
|
|
1064
|
-
h.active = false;
|
|
1065
|
-
entry.active = true;
|
|
1066
|
-
this.pricingVersion = entry.version;
|
|
1067
|
-
if ("plans" in entry.config && entry.config.plans) {
|
|
1068
|
-
for (const [planKey, planData] of Object.entries(entry.config.plans)) {
|
|
1069
|
-
this.planDefinitions.set(planKey, normalisePlanDefinition(planKey, planData));
|
|
1070
|
-
}
|
|
1071
|
-
}
|
|
1072
|
-
if ("tiers" in entry.config && entry.config.tiers) {
|
|
1073
|
-
for (const [tierKey, tierData] of Object.entries(entry.config.tiers)) {
|
|
1074
|
-
this.tierDefinitions.set(tierKey, normaliseTierDefinition(tierKey, tierData));
|
|
1075
|
-
}
|
|
1076
|
-
}
|
|
1077
|
-
return entry.id;
|
|
1078
|
-
}
|
|
1079
|
-
// ── Plan management ────────────────────────────────────────────────
|
|
1080
|
-
async getUserPlan(userId) {
|
|
1081
|
-
const planId = this.userPlanMap.get(userId) ?? null;
|
|
1082
|
-
const planDef = planId ? this.planDefinitions.get(planId) : null;
|
|
1083
|
-
return {
|
|
1084
|
-
userId,
|
|
1085
|
-
planId,
|
|
1086
|
-
planName: planDef?.name ?? null,
|
|
1087
|
-
freeAllowance: planDef?.freeAllowance ?? ZERO,
|
|
1088
|
-
features: planDef?.features ?? {},
|
|
1089
|
-
featureLimits: planDef?.featureLimits ?? {},
|
|
1090
|
-
defaultBillingMode: planDef?.defaultBillingMode ?? "strict",
|
|
1091
|
-
perOperation: planDef?.perOperation ?? {},
|
|
1092
|
-
maxConcurrent: planDef?.maxConcurrent ?? null,
|
|
1093
|
-
overdraftFloor: planDef?.overdraftFloor ?? null,
|
|
1094
|
-
allowancePeriod: planDef?.allowancePeriod ?? "calendar_month",
|
|
1095
|
-
planAssignedAt: planId ? (this.userPlanAssignedAt.get(userId) ?? null) : null,
|
|
1096
|
-
};
|
|
1097
|
-
}
|
|
1098
|
-
async checkFeature(userId, feature) {
|
|
1099
|
-
const plan = await this.getUserPlan(userId);
|
|
1100
|
-
const present = Object.prototype.hasOwnProperty.call(plan.features, feature);
|
|
1101
|
-
const value = present ? plan.features[feature] : null;
|
|
1102
|
-
return {
|
|
1103
|
-
userId,
|
|
1104
|
-
feature,
|
|
1105
|
-
value,
|
|
1106
|
-
// M6: presence-vs-truthiness — numeric 0 / "" count as present.
|
|
1107
|
-
hasFeature: present && featurePresent(value),
|
|
1108
|
-
};
|
|
1109
|
-
}
|
|
1110
|
-
async setUserPlan(userId, planId, planAssignedAt) {
|
|
1111
|
-
this.userPlanMap.set(userId, planId);
|
|
1112
|
-
const assigned = planAssignedAt ?? this.now();
|
|
1113
|
-
this.userPlanAssignedAt.set(userId, assigned);
|
|
1114
|
-
return { userId, planId, planAssignedAt: assigned.toISOString() };
|
|
1115
|
-
}
|
|
1116
|
-
async unsetUserPlan(userId) {
|
|
1117
|
-
this.userPlanMap.delete(userId);
|
|
1118
|
-
this.userPlanAssignedAt.delete(userId);
|
|
1119
|
-
return { userId };
|
|
1120
|
-
}
|
|
1121
|
-
async checkAllowance(userId, periodStart) {
|
|
1122
|
-
// periodStart is unused here: MemoryStore already has direct access to
|
|
1123
|
-
// planAssignedAt and its own (injectable, test-controllable) clock, so it
|
|
1124
|
-
// self-resolves the window rather than trusting a caller-supplied date that
|
|
1125
|
-
// may have been computed against the manager's wall clock instead.
|
|
1126
|
-
void periodStart;
|
|
1127
|
-
const planId = this.userPlanMap.get(userId);
|
|
1128
|
-
if (!planId) {
|
|
1129
|
-
return { planId: "", allowanceRemaining: ZERO, periodStart: "", periodEnd: "" };
|
|
1130
|
-
}
|
|
1131
|
-
const planDef = this.planDefinitions.get(planId);
|
|
1132
|
-
if (!planDef) {
|
|
1133
|
-
return { planId: "", allowanceRemaining: ZERO, periodStart: "", periodEnd: "" };
|
|
1134
|
-
}
|
|
1135
|
-
const now = this.now();
|
|
1136
|
-
const allowancePeriod = planDef.allowancePeriod ?? "calendar_month";
|
|
1137
|
-
const anchor = this.userPlanAssignedAt.get(userId) ?? null;
|
|
1138
|
-
const { start, end: exclusiveEnd } = resolveAllowanceWindow(now, allowancePeriod, anchor);
|
|
1139
|
-
// Preserve the pre-WS9 display convention: periodEnd is the LAST DAY of the
|
|
1140
|
-
// window (inclusive), i.e. one day before the resolver's exclusive end.
|
|
1141
|
-
const periodEnd = new Date(exclusiveEnd.getTime() - 86_400_000);
|
|
1142
|
-
const billingPeriod = start.toISOString().slice(0, 10);
|
|
1143
|
-
let usage = ZERO;
|
|
1144
|
-
for (const w of this.usageWindows) {
|
|
1145
|
-
if (w.userId === userId && w.planId === planId && w.billingPeriod === billingPeriod) {
|
|
1146
|
-
usage = usage.plus(w.usage);
|
|
1147
|
-
}
|
|
1148
|
-
}
|
|
1149
|
-
return {
|
|
1150
|
-
planId,
|
|
1151
|
-
allowanceRemaining: Decimal.max(planDef.freeAllowance.minus(usage), ZERO),
|
|
1152
|
-
periodStart: start.toISOString(),
|
|
1153
|
-
periodEnd: periodEnd.toISOString(),
|
|
1154
|
-
};
|
|
1155
|
-
}
|
|
1156
|
-
incrementUsageWindowSync(userId, planId, amount, periodStart) {
|
|
1157
|
-
const billingPeriod = this.billingPeriod(periodStart);
|
|
1158
|
-
const existing = this.usageWindows.find((w) => w.userId === userId && w.planId === planId && w.billingPeriod === billingPeriod);
|
|
1159
|
-
if (existing) {
|
|
1160
|
-
existing.usage = existing.usage.plus(amount);
|
|
1161
|
-
}
|
|
1162
|
-
else {
|
|
1163
|
-
this.usageWindows.push({ userId, planId, billingPeriod, usage: amount });
|
|
1164
|
-
}
|
|
1165
|
-
}
|
|
1166
|
-
async incrementUsageWindow(userId, planId, amount) {
|
|
1167
|
-
this.incrementUsageWindowSync(userId, planId, amount);
|
|
1168
|
-
}
|
|
1169
|
-
// ── Revoke credits by tx type ─────────────────────────────────────────
|
|
1170
|
-
async revokeCreditsByTxType(userId, txType) {
|
|
1171
|
-
const userTxns = this.transactions.filter((t) => t.userId === userId);
|
|
1172
|
-
let totalToRevoke = ZERO;
|
|
1173
|
-
let revokeTier = null;
|
|
1174
|
-
for (const txn of userTxns) {
|
|
1175
|
-
if (txn.type === txType && txn.amount.gt(0)) {
|
|
1176
|
-
const tier = txn.metadata?.["tier"] ?? "default";
|
|
1177
|
-
const revokedAmount = userTxns
|
|
1178
|
-
.filter((t) => t.type === txType + "_revoke" &&
|
|
1179
|
-
t.metadata?.["tier"] === tier)
|
|
1180
|
-
.reduce((sum, t) => sum.add(t.amount.abs()), ZERO);
|
|
1181
|
-
const unrevoked = txn.amount.sub(revokedAmount);
|
|
1182
|
-
if (unrevoked.gt(0)) {
|
|
1183
|
-
totalToRevoke = unrevoked;
|
|
1184
|
-
revokeTier = tier;
|
|
1185
|
-
break;
|
|
1186
|
-
}
|
|
1187
|
-
}
|
|
1188
|
-
}
|
|
1189
|
-
if (totalToRevoke.gt(0) && revokeTier != null) {
|
|
1190
|
-
const currentBalance = this.getTierBalance(userId, revokeTier);
|
|
1191
|
-
const revokeAmt = Decimal.min(totalToRevoke, currentBalance);
|
|
1192
|
-
if (revokeAmt.gt(0)) {
|
|
1193
|
-
this.adjustTierBalance(userId, revokeTier, revokeAmt.negated());
|
|
1194
|
-
this.balances.set(userId, (this.balances.get(userId) ?? ZERO).sub(revokeAmt));
|
|
1195
|
-
const txId = randomUUID();
|
|
1196
|
-
this.transactions.push({
|
|
1197
|
-
id: txId,
|
|
1198
|
-
userId,
|
|
1199
|
-
amount: revokeAmt.negated(),
|
|
1200
|
-
type: txType + "_revoke",
|
|
1201
|
-
metadata: { tier: revokeTier },
|
|
1202
|
-
createdAt: this.now(),
|
|
1203
|
-
});
|
|
1204
|
-
return {
|
|
1205
|
-
userId,
|
|
1206
|
-
amount: revokeAmt.negated().toString(),
|
|
1207
|
-
newBalance: this.balance(userId).toString(),
|
|
1208
|
-
tier: revokeTier,
|
|
1209
|
-
};
|
|
1210
|
-
}
|
|
1211
|
-
}
|
|
1212
|
-
const bal = this.balance(userId);
|
|
1213
|
-
return { userId, amount: "0", newBalance: bal.toString(), tier: null };
|
|
1214
|
-
}
|
|
1215
|
-
// ── Refunds ──────────────────────────────────────────────────────────
|
|
1216
|
-
async refundCredits(transactionId, amount, reason, metadata) {
|
|
1217
|
-
// ── critical section (synchronous; no awaits) ──
|
|
1218
|
-
const origTx = this.transactions.find((t) => t.id === transactionId);
|
|
1219
|
-
if (!origTx) {
|
|
1220
|
-
return {
|
|
1221
|
-
refundTransactionId: "",
|
|
1222
|
-
originalTransactionId: transactionId,
|
|
1223
|
-
userId: "",
|
|
1224
|
-
amount: ZERO,
|
|
1225
|
-
newBalance: ZERO,
|
|
1226
|
-
error: "not_found",
|
|
1227
|
-
};
|
|
1228
|
-
}
|
|
1229
|
-
// Only a usage/team_usage debit (negative amount) is refundable. Anything
|
|
1230
|
-
// else (purchase/refund/adjustment/bonus) has zero refundable amount, so any
|
|
1231
|
-
// refund over-refunds (parity with SQL refund RPC).
|
|
1232
|
-
if ((origTx.type !== "usage" && origTx.type !== "team_usage") || origTx.amount.gte(0)) {
|
|
1233
|
-
return {
|
|
1234
|
-
refundTransactionId: "",
|
|
1235
|
-
originalTransactionId: transactionId,
|
|
1236
|
-
userId: origTx.userId,
|
|
1237
|
-
amount: ZERO,
|
|
1238
|
-
newBalance: this.balance(origTx.userId),
|
|
1239
|
-
error: "over_refund",
|
|
1240
|
-
};
|
|
1241
|
-
}
|
|
1242
|
-
const originalDebit = origTx.amount.abs();
|
|
1243
|
-
// Back-compat: an exact duplicate of a prior FULL refund → already_refunded.
|
|
1244
|
-
const fullRefundExists = this.transactions.some((t) => t.type === "refund" && t.referenceId === transactionId && t.amount.eq(originalDebit));
|
|
1245
|
-
if (fullRefundExists) {
|
|
1246
|
-
return {
|
|
1247
|
-
refundTransactionId: "",
|
|
1248
|
-
originalTransactionId: transactionId,
|
|
1249
|
-
userId: origTx.userId,
|
|
1250
|
-
amount: ZERO,
|
|
1251
|
-
newBalance: this.balance(origTx.userId),
|
|
1252
|
-
error: "already_refunded",
|
|
1253
|
-
};
|
|
1254
|
-
}
|
|
1255
|
-
// Sum prior refunds for cumulative-partial over-refund detection.
|
|
1256
|
-
let priorRefunded = ZERO;
|
|
1257
|
-
for (const t of this.transactions) {
|
|
1258
|
-
if (t.type === "refund" && t.referenceId === transactionId) {
|
|
1259
|
-
priorRefunded = priorRefunded.plus(t.amount);
|
|
1260
|
-
}
|
|
1261
|
-
}
|
|
1262
|
-
const remaining = originalDebit.minus(priorRefunded);
|
|
1263
|
-
const refundAmount = quantizeMoney(amount ?? remaining);
|
|
1264
|
-
// Over-refund: non-positive request, or one exceeding what remains.
|
|
1265
|
-
if (refundAmount.lte(0) || refundAmount.gt(remaining)) {
|
|
1266
|
-
return {
|
|
1267
|
-
refundTransactionId: "",
|
|
1268
|
-
originalTransactionId: transactionId,
|
|
1269
|
-
userId: origTx.userId,
|
|
1270
|
-
amount: ZERO,
|
|
1271
|
-
newBalance: this.balance(origTx.userId),
|
|
1272
|
-
error: "over_refund",
|
|
1273
|
-
};
|
|
1274
|
-
}
|
|
1275
|
-
// Restore balance and append the refund ledger row.
|
|
1276
|
-
const current = this.balance(origTx.userId);
|
|
1277
|
-
this.balances.set(origTx.userId, current.plus(refundAmount));
|
|
1278
|
-
// Credit tiers: LIFO restoration (plan §5). The original debit's per-tier
|
|
1279
|
-
// breakdown drives allocation; legacy debits without a stored breakdown
|
|
1280
|
-
// (pre-tiers) fall back to the whole amount landing in "default".
|
|
1281
|
-
const originalBreakdown = origTx.metadata?.["tierBreakdown"] ?? { default: originalDebit };
|
|
1282
|
-
// tierRemaining[t] = original[t] - Σ(all PRIOR refunds' own breakdown[t]) —
|
|
1283
|
-
// derived fresh each time so repeated partial refunds compose correctly
|
|
1284
|
-
// without a separate running counter.
|
|
1285
|
-
const priorBreakdowns = [];
|
|
1286
|
-
for (const t of this.transactions) {
|
|
1287
|
-
if (t.type === "refund" && t.referenceId === transactionId) {
|
|
1288
|
-
const b = t.metadata?.["tierBreakdown"];
|
|
1289
|
-
if (b)
|
|
1290
|
-
priorBreakdowns.push(b);
|
|
1291
|
-
}
|
|
1292
|
-
}
|
|
1293
|
-
const tierRemaining = {};
|
|
1294
|
-
for (const [t, orig] of Object.entries(originalBreakdown)) {
|
|
1295
|
-
let consumed = ZERO;
|
|
1296
|
-
for (const b of priorBreakdowns)
|
|
1297
|
-
consumed = consumed.plus(b[t] ?? ZERO);
|
|
1298
|
-
tierRemaining[t] = orig.minus(consumed);
|
|
1299
|
-
}
|
|
1300
|
-
// Walk tiers in REVERSE priority order (highest-priority-number/last-drained
|
|
1301
|
-
// tier first), restoring only the tiers actually present in the original
|
|
1302
|
-
// breakdown.
|
|
1303
|
-
let toAllocate = refundAmount;
|
|
1304
|
-
const newBreakdown = {};
|
|
1305
|
-
const reverseOrder = [
|
|
1306
|
-
...this.tierWalkOrder(origTx.userId, Object.keys(originalBreakdown)),
|
|
1307
|
-
].reverse();
|
|
1308
|
-
for (const t of reverseOrder) {
|
|
1309
|
-
if (toAllocate.lte(0))
|
|
1310
|
-
break;
|
|
1311
|
-
const give = Decimal.min(tierRemaining[t.tierKey] ?? ZERO, toAllocate);
|
|
1312
|
-
if (give.gt(0)) {
|
|
1313
|
-
newBreakdown[t.tierKey] = give;
|
|
1314
|
-
toAllocate = toAllocate.minus(give);
|
|
1315
|
-
this.adjustTierBalance(origTx.userId, t.tierKey, give);
|
|
1316
|
-
}
|
|
1317
|
-
}
|
|
1318
|
-
const txMeta = metadata ? this.cleanMetadata(metadata) : {};
|
|
1319
|
-
if (reason)
|
|
1320
|
-
txMeta["reason"] = reason;
|
|
1321
|
-
txMeta["tierBreakdown"] = newBreakdown;
|
|
1322
|
-
const txId = randomUUID();
|
|
1323
|
-
this.transactions.push({
|
|
1324
|
-
id: txId,
|
|
1325
|
-
userId: origTx.userId,
|
|
1326
|
-
amount: refundAmount,
|
|
1327
|
-
type: "refund",
|
|
1328
|
-
referenceType: reason ?? null,
|
|
1329
|
-
referenceId: transactionId,
|
|
1330
|
-
metadata: txMeta,
|
|
1331
|
-
createdAt: this.now(),
|
|
1332
|
-
});
|
|
1333
|
-
return {
|
|
1334
|
-
refundTransactionId: txId,
|
|
1335
|
-
originalTransactionId: transactionId,
|
|
1336
|
-
userId: origTx.userId,
|
|
1337
|
-
amount: refundAmount,
|
|
1338
|
-
newBalance: current.plus(refundAmount),
|
|
1339
|
-
tierBreakdown: newBreakdown,
|
|
1340
|
-
};
|
|
1341
|
-
}
|
|
1342
|
-
// ── Credit expiry ─────────────────────────────────────────────────────
|
|
1343
|
-
async sweepExpiredCredits(dryRun = false, userId) {
|
|
1344
|
-
// ── critical section (synchronous; no awaits) ──
|
|
1345
|
-
const now = this.now();
|
|
1346
|
-
// Credit tiers: re-scoped from per-userId to per-(userId, tierKey), reading
|
|
1347
|
-
// `metadata.tier` off each grant (legacy records without it default to
|
|
1348
|
-
// "default"). Grouping key: `${userId} ${tierKey}`.
|
|
1349
|
-
const expiredByUserTier = new Map();
|
|
1350
|
-
const expiredTxsByUserTier = new Map();
|
|
1351
|
-
// Find all expired, not-yet-swept grant transactions. When `userId` is
|
|
1352
|
-
// given (lazy-on-read expiry), restrict the scan to that user only —
|
|
1353
|
-
// omitted preserves the original global-sweep behaviour exactly.
|
|
1354
|
-
for (const tx of this.transactions) {
|
|
1355
|
-
if (userId !== undefined && tx.userId !== userId)
|
|
1356
|
-
continue;
|
|
1357
|
-
if (tx.expiresAt &&
|
|
1358
|
-
!tx.sweptAt && // H4: never re-sweep a previously swept grant
|
|
1359
|
-
(tx.type === "purchase" ||
|
|
1360
|
-
tx.type === "subscription" ||
|
|
1361
|
-
tx.type === "signup_bonus" ||
|
|
1362
|
-
tx.type === "adjustment")) {
|
|
1363
|
-
if (tx.expiresAt <= now) {
|
|
1364
|
-
const tierKey = tx.metadata?.["tier"] ?? "default";
|
|
1365
|
-
const key = `${tx.userId} ${tierKey}`;
|
|
1366
|
-
expiredByUserTier.set(key, (expiredByUserTier.get(key) ?? ZERO).plus(tx.amount));
|
|
1367
|
-
const list = expiredTxsByUserTier.get(key) ?? [];
|
|
1368
|
-
list.push(tx);
|
|
1369
|
-
expiredTxsByUserTier.set(key, list);
|
|
1370
|
-
}
|
|
1371
|
-
}
|
|
1372
|
-
}
|
|
1373
|
-
let expiredCount = 0;
|
|
1374
|
-
let expiredAmount = ZERO;
|
|
1375
|
-
const expiredByTier = {};
|
|
1376
|
-
for (const [key, totalExpired] of expiredByUserTier) {
|
|
1377
|
-
const sep = key.indexOf(" ");
|
|
1378
|
-
const userId = key.slice(0, sep);
|
|
1379
|
-
const tierKey = key.slice(sep + 1);
|
|
1380
|
-
// Clamp per-TIER balance (not aggregate) — the existing LEAST(...) clamp,
|
|
1381
|
-
// just re-scoped.
|
|
1382
|
-
const currentTierBalance = this.getTierBalance(userId, tierKey);
|
|
1383
|
-
const toExpire = Decimal.min(totalExpired, currentTierBalance);
|
|
1384
|
-
if (toExpire.gt(0)) {
|
|
1385
|
-
expiredCount++;
|
|
1386
|
-
expiredAmount = expiredAmount.plus(toExpire);
|
|
1387
|
-
expiredByTier[tierKey] = (expiredByTier[tierKey] ?? ZERO).plus(toExpire);
|
|
1388
|
-
if (!dryRun) {
|
|
1389
|
-
this.adjustTierBalance(userId, tierKey, toExpire.negated());
|
|
1390
|
-
this.balances.set(userId, this.balance(userId).minus(toExpire));
|
|
1391
|
-
// H4: mark swept grants so a second sweep reports zero.
|
|
1392
|
-
const txs = expiredTxsByUserTier.get(key) ?? [];
|
|
1393
|
-
for (const et of txs) {
|
|
1394
|
-
et.sweptAt = now;
|
|
1395
|
-
et.expiresAt = null;
|
|
1396
|
-
}
|
|
1397
|
-
const txId = randomUUID();
|
|
1398
|
-
this.transactions.push({
|
|
1399
|
-
id: txId,
|
|
1400
|
-
userId,
|
|
1401
|
-
amount: toExpire.negated(),
|
|
1402
|
-
type: "adjustment",
|
|
1403
|
-
metadata: { reason: "credit_expired", expiredAmount: toExpire, tier: tierKey },
|
|
1404
|
-
createdAt: now,
|
|
1405
|
-
});
|
|
1406
|
-
}
|
|
1407
|
-
}
|
|
1408
|
-
}
|
|
1409
|
-
return {
|
|
1410
|
-
expiredCount,
|
|
1411
|
-
expiredAmount,
|
|
1412
|
-
dryRun,
|
|
1413
|
-
expiredByTier: Object.keys(expiredByTier).length > 0 ? expiredByTier : null,
|
|
1414
|
-
};
|
|
1415
|
-
}
|
|
1416
|
-
// ── Credit tiers ─────────────────────────────────────────────────────
|
|
1417
|
-
async getCreditTiers(userId) {
|
|
1418
|
-
if (this.tierDefinitions.size === 0) {
|
|
1419
|
-
// No tiers configured: synthesize a single "default" entry from the
|
|
1420
|
-
// aggregate balance so the API shape is uniform either way.
|
|
1421
|
-
return {
|
|
1422
|
-
userId,
|
|
1423
|
-
tiers: [
|
|
1424
|
-
{
|
|
1425
|
-
tierKey: "default",
|
|
1426
|
-
name: "default",
|
|
1427
|
-
priority: 0,
|
|
1428
|
-
expires: false,
|
|
1429
|
-
balance: this.balance(userId),
|
|
1430
|
-
},
|
|
1431
|
-
],
|
|
1432
|
-
totalBalance: this.balance(userId),
|
|
1433
|
-
};
|
|
1434
|
-
}
|
|
1435
|
-
const tiers = [...this.tierDefinitions.entries()]
|
|
1436
|
-
.map(([tierKey, def]) => ({
|
|
1437
|
-
tierKey,
|
|
1438
|
-
name: def.name,
|
|
1439
|
-
priority: def.priority,
|
|
1440
|
-
expires: def.expires,
|
|
1441
|
-
balance: this.getTierBalance(userId, tierKey),
|
|
1442
|
-
}))
|
|
1443
|
-
.sort((a, b) => a.priority - b.priority || a.tierKey.localeCompare(b.tierKey));
|
|
1444
|
-
return { userId, tiers, totalBalance: this.balance(userId) };
|
|
1445
|
-
}
|
|
1446
|
-
// ── Usage analytics ──────────────────────────────────────────────────
|
|
1447
|
-
/**
|
|
1448
|
-
* Filter transactions to usage records in the time window. Half-open
|
|
1449
|
-
* [start, end) — matches the SQL analytics RPCs (007_analytics.sql) and the
|
|
1450
|
-
* allowance/feature-limit windows elsewhere, so a transaction lands in
|
|
1451
|
-
* exactly one of two adjacent windows, never both.
|
|
1452
|
-
*/
|
|
1453
|
-
_usageInWindow(start, end) {
|
|
1454
|
-
return this.transactions.filter((t) => t.type === "usage" && t.amount.lt(0) && t.createdAt >= start && t.createdAt < end);
|
|
1455
|
-
}
|
|
1456
|
-
async spendByUser(start, end) {
|
|
1457
|
-
const usage = this._usageInWindow(start, end);
|
|
1458
|
-
const byUser = new Map();
|
|
1459
|
-
for (const t of usage) {
|
|
1460
|
-
const entry = byUser.get(t.userId) ?? { total: ZERO, count: 0 };
|
|
1461
|
-
entry.total = entry.total.plus(t.amount.abs());
|
|
1462
|
-
entry.count++;
|
|
1463
|
-
byUser.set(t.userId, entry);
|
|
1464
|
-
}
|
|
1465
|
-
return Array.from(byUser.entries())
|
|
1466
|
-
.sort(([a], [b]) => a.localeCompare(b))
|
|
1467
|
-
.map(([userId, { total, count }]) => ({
|
|
1468
|
-
userId,
|
|
1469
|
-
totalSpend: total,
|
|
1470
|
-
transactionCount: count,
|
|
1471
|
-
}));
|
|
1472
|
-
}
|
|
1473
|
-
async spendByModel(start, end) {
|
|
1474
|
-
const usage = this._usageInWindow(start, end);
|
|
1475
|
-
const byModel = new Map();
|
|
1476
|
-
for (const t of usage) {
|
|
1477
|
-
const model = t.metadata?.model ?? "unknown";
|
|
1478
|
-
const entry = byModel.get(model) ?? { total: ZERO, count: 0 };
|
|
1479
|
-
entry.total = entry.total.plus(t.amount.abs());
|
|
1480
|
-
entry.count++;
|
|
1481
|
-
byModel.set(model, entry);
|
|
1482
|
-
}
|
|
1483
|
-
return Array.from(byModel.entries())
|
|
1484
|
-
.sort(([a], [b]) => a.localeCompare(b))
|
|
1485
|
-
.map(([model, { total, count }]) => ({
|
|
1486
|
-
model,
|
|
1487
|
-
totalSpend: total,
|
|
1488
|
-
transactionCount: count,
|
|
1489
|
-
}));
|
|
1490
|
-
}
|
|
1491
|
-
async topUsers(limit, start, end) {
|
|
1492
|
-
const byUser = await this.spendByUser(start, end);
|
|
1493
|
-
return byUser
|
|
1494
|
-
.sort((a, b) => b.totalSpend.comparedTo(a.totalSpend))
|
|
1495
|
-
.slice(0, limit)
|
|
1496
|
-
.map((r) => ({ userId: r.userId, totalSpend: r.totalSpend }));
|
|
1497
|
-
}
|
|
1498
|
-
// ── Transaction listing ─────────────────────────────────────────────
|
|
1499
|
-
async listUserTransactions(userId, options) {
|
|
1500
|
-
const limit = options?.limit ?? 50;
|
|
1501
|
-
const offset = options?.offset ?? 0;
|
|
1502
|
-
const filtered = this.transactions.filter((t) => {
|
|
1503
|
-
if (t.userId !== userId)
|
|
1504
|
-
return false;
|
|
1505
|
-
if (options?.types && !options.types.includes(t.type))
|
|
1506
|
-
return false;
|
|
1507
|
-
if (options?.fromDate && t.createdAt < options.fromDate)
|
|
1508
|
-
return false;
|
|
1509
|
-
if (options?.toDate && t.createdAt > options.toDate)
|
|
1510
|
-
return false;
|
|
1511
|
-
return true;
|
|
1512
|
-
});
|
|
1513
|
-
// Sort newest first
|
|
1514
|
-
filtered.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
|
|
1515
|
-
const total = filtered.length;
|
|
1516
|
-
const items = filtered.slice(offset, offset + limit);
|
|
1517
|
-
return {
|
|
1518
|
-
total,
|
|
1519
|
-
items: items.map((t) => ({
|
|
1520
|
-
id: t.id,
|
|
1521
|
-
userId: t.userId,
|
|
1522
|
-
amount: t.amount,
|
|
1523
|
-
type: t.type,
|
|
1524
|
-
referenceType: t.referenceType ?? null,
|
|
1525
|
-
referenceId: t.referenceId ?? null,
|
|
1526
|
-
metadata: t.metadata ?? null,
|
|
1527
|
-
createdAt: t.createdAt.toISOString(),
|
|
1528
|
-
})),
|
|
1529
|
-
};
|
|
1530
|
-
}
|
|
1531
|
-
async listUsageEvents(userId, options) {
|
|
1532
|
-
let items = this.transactions.filter((t) => t.userId === userId && t.type === "usage");
|
|
1533
|
-
if (options?.fromDate) {
|
|
1534
|
-
const from = options.fromDate;
|
|
1535
|
-
items = items.filter((t) => t.createdAt >= from);
|
|
1536
|
-
}
|
|
1537
|
-
if (options?.toDate) {
|
|
1538
|
-
const to = options.toDate;
|
|
1539
|
-
items = items.filter((t) => t.createdAt <= to);
|
|
1540
|
-
}
|
|
1541
|
-
const total = items.length;
|
|
1542
|
-
const offset = options?.offset ?? 0;
|
|
1543
|
-
const limit = options?.limit ?? 50;
|
|
1544
|
-
const page = items
|
|
1545
|
-
.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
|
|
1546
|
-
.slice(offset, offset + limit);
|
|
1547
|
-
return {
|
|
1548
|
-
total,
|
|
1549
|
-
items: page.map((t) => ({
|
|
1550
|
-
id: t.id,
|
|
1551
|
-
userId: t.userId,
|
|
1552
|
-
amount: t.amount,
|
|
1553
|
-
type: t.type,
|
|
1554
|
-
referenceType: t.referenceType ?? null,
|
|
1555
|
-
referenceId: t.referenceId ?? null,
|
|
1556
|
-
metadata: t.metadata ?? null,
|
|
1557
|
-
createdAt: t.createdAt.toISOString(),
|
|
1558
|
-
})),
|
|
1559
|
-
};
|
|
1560
|
-
}
|
|
1561
|
-
// ── Aggregate stats ──────────────────────────────────────────────────
|
|
1562
|
-
async aggregateStats(start, end) {
|
|
1563
|
-
const usage = this._usageInWindow(start, end);
|
|
1564
|
-
if (usage.length === 0) {
|
|
1565
|
-
return {
|
|
1566
|
-
totalCreditsConsumed: ZERO,
|
|
1567
|
-
activeUsers: 0,
|
|
1568
|
-
avgDailySpend: ZERO,
|
|
1569
|
-
topModel: "",
|
|
1570
|
-
topUser: "",
|
|
1571
|
-
};
|
|
1572
|
-
}
|
|
1573
|
-
let total = ZERO;
|
|
1574
|
-
for (const t of usage)
|
|
1575
|
-
total = total.plus(t.amount.abs());
|
|
1576
|
-
const activeUsers = new Set(usage.map((t) => t.userId)).size;
|
|
1577
|
-
const days = new Set(usage.map((t) => t.createdAt.toISOString().slice(0, 10))).size;
|
|
1578
|
-
// NUMERIC division (no integer truncation) — quantize to 4dp.
|
|
1579
|
-
const avgDailySpend = days > 0 ? quantizeMoney(total.div(days)) : ZERO;
|
|
1580
|
-
const byModel = new Map();
|
|
1581
|
-
const byUser = new Map();
|
|
1582
|
-
for (const t of usage) {
|
|
1583
|
-
const model = t.metadata?.model ?? "unknown";
|
|
1584
|
-
byModel.set(model, (byModel.get(model) ?? ZERO).plus(t.amount.abs()));
|
|
1585
|
-
byUser.set(t.userId, (byUser.get(t.userId) ?? ZERO).plus(t.amount.abs()));
|
|
1586
|
-
}
|
|
1587
|
-
const topModel = byModel.size > 0
|
|
1588
|
-
? [...byModel.entries()].reduce((best, curr) => (curr[1].gt(best[1]) ? curr : best))[0]
|
|
1589
|
-
: "";
|
|
1590
|
-
const topUser = byUser.size > 0
|
|
1591
|
-
? [...byUser.entries()].reduce((best, curr) => (curr[1].gt(best[1]) ? curr : best))[0]
|
|
1592
|
-
: "";
|
|
1593
|
-
return { totalCreditsConsumed: total, activeUsers, avgDailySpend, topModel, topUser };
|
|
1594
|
-
}
|
|
1595
|
-
// ── Spend caps and rate limiting ─────────────────────────────────────
|
|
1596
|
-
/** Configure a spend cap (MemoryStore-only helper for testing). */
|
|
1597
|
-
setSpendCap(cap) {
|
|
1598
|
-
this.spendCaps.push(cap);
|
|
1599
|
-
}
|
|
1600
|
-
capWindowStart(type) {
|
|
1601
|
-
const now = this.now();
|
|
1602
|
-
if (type === "daily") {
|
|
1603
|
-
return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
|
|
1604
|
-
}
|
|
1605
|
-
return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
|
|
1606
|
-
}
|
|
1607
|
-
/** Monthly team spend for a specific member: sum of team_usage debits this UTC month (H3). */
|
|
1608
|
-
teamMonthSpent(teamId, userId) {
|
|
1609
|
-
const now = this.now();
|
|
1610
|
-
const windowStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
|
|
1611
|
-
let total = ZERO;
|
|
1612
|
-
for (const t of this.transactions) {
|
|
1613
|
-
if (t.userId !== userId)
|
|
1614
|
-
continue;
|
|
1615
|
-
if (t.type !== "team_usage")
|
|
1616
|
-
continue;
|
|
1617
|
-
if (t.amount.gte(0))
|
|
1618
|
-
continue;
|
|
1619
|
-
if (t.metadata?.["teamId"] !== teamId)
|
|
1620
|
-
continue;
|
|
1621
|
-
if (t.createdAt >= windowStart)
|
|
1622
|
-
total = total.plus(t.amount.abs());
|
|
1623
|
-
}
|
|
1624
|
-
return total;
|
|
1625
|
-
}
|
|
1626
|
-
/** Sum spend (positive magnitude) in a window, optionally restricted to a model. */
|
|
1627
|
-
spendInWindow(userId, windowStart, capModel) {
|
|
1628
|
-
let total = ZERO;
|
|
1629
|
-
for (const t of this.transactions) {
|
|
1630
|
-
if (t.userId !== userId)
|
|
1631
|
-
continue;
|
|
1632
|
-
if (t.type !== "usage" && t.type !== "team_usage")
|
|
1633
|
-
continue;
|
|
1634
|
-
if (t.amount.gte(0))
|
|
1635
|
-
continue;
|
|
1636
|
-
if (capModel != null && t.metadata?.model !== capModel)
|
|
1637
|
-
continue;
|
|
1638
|
-
if (t.createdAt >= windowStart)
|
|
1639
|
-
total = total.plus(t.amount.abs());
|
|
1640
|
-
}
|
|
1641
|
-
return total;
|
|
1642
|
-
}
|
|
1643
|
-
/**
|
|
1644
|
-
* Ledger-derived count of committed `usage` transactions tagged
|
|
1645
|
-
* `metadata.feature === feature` in `[periodStart, periodEnd)` — the
|
|
1646
|
-
* counting primitive shared by `deductWithAllowance`/`createLease`/
|
|
1647
|
-
* `settleLease`'s feature-limit enforcement and `checkFeatureLimit`.
|
|
1648
|
-
* Mirrors `spendInWindow`, replacing "sum of amount" with "count of rows".
|
|
1649
|
-
*
|
|
1650
|
-
* Deliberately does NOT filter on `amount < 0` (unlike `spendInWindow`,
|
|
1651
|
-
* which only cares about actual dollars spent): a call fully covered by
|
|
1652
|
-
* free allowance nets to `amount === 0` but is still one invocation of the
|
|
1653
|
-
* feature and must still count.
|
|
1654
|
-
*
|
|
1655
|
-
* `release_lease` never inserts a `usage` row (nothing to count) and
|
|
1656
|
-
* `refund_credits` never deletes the original row (the count is
|
|
1657
|
-
* unaffected) — both intentional, matching the SQL/Python design.
|
|
1658
|
-
*/
|
|
1659
|
-
featureUsageCount(userId, feature, periodStart, periodEnd) {
|
|
1660
|
-
let count = 0;
|
|
1661
|
-
for (const t of this.transactions) {
|
|
1662
|
-
if (t.userId !== userId)
|
|
1663
|
-
continue;
|
|
1664
|
-
if (t.type !== "usage")
|
|
1665
|
-
continue;
|
|
1666
|
-
if ((t.metadata ?? {})["feature"] !== feature)
|
|
1667
|
-
continue;
|
|
1668
|
-
if (t.createdAt >= periodStart && t.createdAt < periodEnd)
|
|
1669
|
-
count += 1;
|
|
1670
|
-
}
|
|
1671
|
-
return count;
|
|
1672
|
-
}
|
|
1673
|
-
async checkFeatureLimit(userId, feature, maxCalls, periodStart, periodEnd) {
|
|
1674
|
-
const used = this.featureUsageCount(userId, feature, periodStart, periodEnd);
|
|
1675
|
-
return {
|
|
1676
|
-
userId,
|
|
1677
|
-
feature,
|
|
1678
|
-
limited: true,
|
|
1679
|
-
limit: maxCalls,
|
|
1680
|
-
used,
|
|
1681
|
-
remaining: Math.max(maxCalls - used, 0),
|
|
1682
|
-
periodStart: periodStart.toISOString(),
|
|
1683
|
-
periodEnd: periodEnd.toISOString(),
|
|
1684
|
-
// The manager overwrites `action` with the resolved FeatureLimit.action.
|
|
1685
|
-
action: null,
|
|
1686
|
-
};
|
|
1687
|
-
}
|
|
1688
|
-
async checkSpendCap(userId, model, amount) {
|
|
1689
|
-
const amt = amount ?? ZERO;
|
|
1690
|
-
const userCaps = this.spendCaps.filter((c) => c.userId === userId);
|
|
1691
|
-
if (userCaps.length === 0) {
|
|
1692
|
-
return { capped: false, currentSpend: ZERO, limit: ZERO, action: null };
|
|
1693
|
-
}
|
|
1694
|
-
// Check deny caps first — most restrictive
|
|
1695
|
-
for (const cap of userCaps) {
|
|
1696
|
-
if (cap.model && cap.model !== model)
|
|
1697
|
-
continue;
|
|
1698
|
-
if (cap.action !== "deny")
|
|
1699
|
-
continue;
|
|
1700
|
-
const windowStart = this.capWindowStart(cap.type);
|
|
1701
|
-
const currentSpend = this.spendInWindow(userId, windowStart, cap.model);
|
|
1702
|
-
if (currentSpend.plus(amt).gt(cap.limit)) {
|
|
1703
|
-
return {
|
|
1704
|
-
capped: true,
|
|
1705
|
-
currentSpend,
|
|
1706
|
-
limit: cap.limit,
|
|
1707
|
-
action: "deny",
|
|
1708
|
-
model: cap.model,
|
|
1709
|
-
};
|
|
1710
|
-
}
|
|
1711
|
-
}
|
|
1712
|
-
// Check warn/notify caps
|
|
1713
|
-
for (const cap of userCaps) {
|
|
1714
|
-
if (cap.model && cap.model !== model)
|
|
1715
|
-
continue;
|
|
1716
|
-
if (cap.action === "deny")
|
|
1717
|
-
continue;
|
|
1718
|
-
const windowStart = this.capWindowStart(cap.type);
|
|
1719
|
-
const currentSpend = this.spendInWindow(userId, windowStart, cap.model);
|
|
1720
|
-
if (currentSpend.plus(amt).gt(cap.limit)) {
|
|
1721
|
-
return {
|
|
1722
|
-
capped: false,
|
|
1723
|
-
currentSpend,
|
|
1724
|
-
limit: cap.limit,
|
|
1725
|
-
action: cap.action,
|
|
1726
|
-
model: cap.model,
|
|
1727
|
-
};
|
|
1728
|
-
}
|
|
1729
|
-
}
|
|
1730
|
-
return { capped: false, currentSpend: ZERO, limit: ZERO, action: null };
|
|
1731
|
-
}
|
|
1732
|
-
// ── Team/shared balance pools ────────────────────────────────────────
|
|
1733
|
-
async createTeam(name, initialBalance = ZERO) {
|
|
1734
|
-
const teamId = randomUUID();
|
|
1735
|
-
this.teams.set(teamId, {
|
|
1736
|
-
id: teamId,
|
|
1737
|
-
name,
|
|
1738
|
-
balance: initialBalance,
|
|
1739
|
-
memberCount: 0,
|
|
1740
|
-
createdAt: this.now(),
|
|
1741
|
-
});
|
|
1742
|
-
this.teamMembers.set(teamId, new Map());
|
|
1743
|
-
return { teamId, name };
|
|
1744
|
-
}
|
|
1745
|
-
async getTeamBalance(teamId) {
|
|
1746
|
-
const team = this.teams.get(teamId);
|
|
1747
|
-
if (!team) {
|
|
1748
|
-
return { teamId, name: "", balance: ZERO, memberCount: 0 };
|
|
1749
|
-
}
|
|
1750
|
-
return {
|
|
1751
|
-
teamId: team.id,
|
|
1752
|
-
name: team.name,
|
|
1753
|
-
balance: team.balance,
|
|
1754
|
-
memberCount: team.memberCount,
|
|
1755
|
-
};
|
|
1756
|
-
}
|
|
1757
|
-
async addTeamMember(teamId, userId, role = "member", spendCap) {
|
|
1758
|
-
const members = this.teamMembers.get(teamId);
|
|
1759
|
-
if (!members) {
|
|
1760
|
-
return { teamId, userId, role: "" };
|
|
1761
|
-
}
|
|
1762
|
-
members.set(userId, { userId, role, spendCap: spendCap ?? null, totalSpent: ZERO });
|
|
1763
|
-
const team = this.teams.get(teamId);
|
|
1764
|
-
if (team) {
|
|
1765
|
-
team.memberCount = members.size;
|
|
1766
|
-
}
|
|
1767
|
-
return { teamId, userId, role };
|
|
1768
|
-
}
|
|
1769
|
-
async getTeamMembers(teamId) {
|
|
1770
|
-
const members = this.teamMembers.get(teamId);
|
|
1771
|
-
if (!members)
|
|
1772
|
-
return [];
|
|
1773
|
-
return Array.from(members.values());
|
|
1774
|
-
}
|
|
1775
|
-
async deductTeam(teamId, userId, amount, metadata, idempotencyKey) {
|
|
1776
|
-
// ── critical section (synchronous; no awaits) ──
|
|
1777
|
-
const team = this.teams.get(teamId);
|
|
1778
|
-
if (!team) {
|
|
1779
|
-
return {
|
|
1780
|
-
transactionId: "",
|
|
1781
|
-
teamId,
|
|
1782
|
-
userId,
|
|
1783
|
-
amount: ZERO,
|
|
1784
|
-
teamBalanceAfter: ZERO,
|
|
1785
|
-
error: "team_not_found",
|
|
1786
|
-
};
|
|
1787
|
-
}
|
|
1788
|
-
// Idempotency-first (user/team-scoped): replay the original team debit.
|
|
1789
|
-
if (idempotencyKey) {
|
|
1790
|
-
const existing = this.transactions.find((t) => t.type === "team_usage" &&
|
|
1791
|
-
t.metadata?.["teamId"] === teamId &&
|
|
1792
|
-
t.metadata?.["idempotencyKey"] === idempotencyKey);
|
|
1793
|
-
if (existing) {
|
|
1794
|
-
return {
|
|
1795
|
-
transactionId: existing.id,
|
|
1796
|
-
teamId,
|
|
1797
|
-
userId: existing.userId,
|
|
1798
|
-
amount: existing.amount,
|
|
1799
|
-
teamBalanceAfter: team.balance,
|
|
1800
|
-
};
|
|
1801
|
-
}
|
|
1802
|
-
}
|
|
1803
|
-
const members = this.teamMembers.get(teamId);
|
|
1804
|
-
const member = members?.get(userId);
|
|
1805
|
-
if (!member) {
|
|
1806
|
-
return {
|
|
1807
|
-
transactionId: "",
|
|
1808
|
-
teamId,
|
|
1809
|
-
userId,
|
|
1810
|
-
amount: ZERO,
|
|
1811
|
-
teamBalanceAfter: team.balance,
|
|
1812
|
-
error: "user_not_in_team",
|
|
1813
|
-
};
|
|
1814
|
-
}
|
|
1815
|
-
if (!amount.isFinite() || amount.lte(0)) {
|
|
1816
|
-
return {
|
|
1817
|
-
transactionId: "",
|
|
1818
|
-
teamId,
|
|
1819
|
-
userId,
|
|
1820
|
-
amount: ZERO,
|
|
1821
|
-
teamBalanceAfter: team.balance,
|
|
1822
|
-
error: "invalid_amount",
|
|
1823
|
-
};
|
|
1824
|
-
}
|
|
1825
|
-
// H3 fix: enforce spend cap against the monthly window, not lifetime totalSpent.
|
|
1826
|
-
// Python MemoryStore and SQL both use a monthly window (first day of UTC month).
|
|
1827
|
-
if (member.spendCap != null) {
|
|
1828
|
-
const monthSpent = this.teamMonthSpent(teamId, userId);
|
|
1829
|
-
if (monthSpent.plus(amount).gt(member.spendCap)) {
|
|
1830
|
-
return {
|
|
1831
|
-
transactionId: "",
|
|
1832
|
-
teamId,
|
|
1833
|
-
userId,
|
|
1834
|
-
amount: ZERO,
|
|
1835
|
-
teamBalanceAfter: team.balance,
|
|
1836
|
-
error: "spend_cap_exceeded",
|
|
1837
|
-
};
|
|
1838
|
-
}
|
|
1839
|
-
}
|
|
1840
|
-
if (team.balance.lt(amount)) {
|
|
1841
|
-
return {
|
|
1842
|
-
transactionId: "",
|
|
1843
|
-
teamId,
|
|
1844
|
-
userId,
|
|
1845
|
-
amount: ZERO,
|
|
1846
|
-
teamBalanceAfter: team.balance,
|
|
1847
|
-
error: "insufficient_team_balance",
|
|
1848
|
-
};
|
|
1849
|
-
}
|
|
1850
|
-
team.balance = team.balance.minus(amount);
|
|
1851
|
-
member.totalSpent = member.totalSpent.plus(amount);
|
|
1852
|
-
const txMeta = {
|
|
1853
|
-
...(metadata ? this.cleanMetadata(metadata) : {}),
|
|
1854
|
-
teamId,
|
|
1855
|
-
};
|
|
1856
|
-
if (idempotencyKey)
|
|
1857
|
-
txMeta["idempotencyKey"] = idempotencyKey;
|
|
1858
|
-
const txId = randomUUID();
|
|
1859
|
-
this.transactions.push({
|
|
1860
|
-
id: txId,
|
|
1861
|
-
userId,
|
|
1862
|
-
amount: amount.negated(),
|
|
1863
|
-
type: "team_usage",
|
|
1864
|
-
metadata: txMeta,
|
|
1865
|
-
createdAt: this.now(),
|
|
1866
|
-
});
|
|
1867
|
-
return {
|
|
1868
|
-
transactionId: txId,
|
|
1869
|
-
teamId,
|
|
1870
|
-
userId,
|
|
1871
|
-
amount: amount.negated(),
|
|
1872
|
-
teamBalanceAfter: team.balance,
|
|
1873
|
-
};
|
|
1874
|
-
}
|
|
1875
|
-
async dailySpend(start, end) {
|
|
1876
|
-
const usage = this._usageInWindow(start, end);
|
|
1877
|
-
const byDay = new Map();
|
|
1878
|
-
for (const t of usage) {
|
|
1879
|
-
const date = t.createdAt.toISOString().slice(0, 10);
|
|
1880
|
-
const entry = byDay.get(date) ?? { total: ZERO, count: 0 };
|
|
1881
|
-
entry.total = entry.total.plus(t.amount.abs());
|
|
1882
|
-
entry.count++;
|
|
1883
|
-
byDay.set(date, entry);
|
|
1884
|
-
}
|
|
1885
|
-
return Array.from(byDay.entries())
|
|
1886
|
-
.sort(([a], [b]) => a.localeCompare(b))
|
|
1887
|
-
.map(([date, { total, count }]) => ({ date, totalSpend: total, transactionCount: count }));
|
|
1888
|
-
}
|
|
1889
|
-
}
|
|
1890
|
-
//# sourceMappingURL=memory-store.js.map
|