@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,948 +0,0 @@
|
|
|
1
|
-
import Decimal from "decimal.js";
|
|
2
|
-
import { StoreError } from "../errors.js";
|
|
3
|
-
import { resolveCalendarWindow } from "../allowance.js";
|
|
4
|
-
import { CreditStore } from "./credit-store.js";
|
|
5
|
-
const ZERO = new Decimal(0);
|
|
6
|
-
/**
|
|
7
|
-
* Parse a JSON money value into an exact `Decimal`. Supabase returns NUMERIC as
|
|
8
|
-
* a JSON number or string; we coerce via `String(x)` so binary-float precision
|
|
9
|
-
* is never introduced (contract §1). `null`/`undefined` → fallback.
|
|
10
|
-
*/
|
|
11
|
-
function dec(value, fallback = ZERO) {
|
|
12
|
-
if (value === null || value === undefined)
|
|
13
|
-
return fallback;
|
|
14
|
-
if (value instanceof Decimal)
|
|
15
|
-
return value;
|
|
16
|
-
try {
|
|
17
|
-
return new Decimal(String(value));
|
|
18
|
-
}
|
|
19
|
-
catch {
|
|
20
|
-
return fallback;
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
/** A money serialized for a JSON RPC parameter: send as a decimal string. */
|
|
24
|
-
function decParam(value) {
|
|
25
|
-
return value.toString();
|
|
26
|
-
}
|
|
27
|
-
/**
|
|
28
|
-
* Derive the feature-limit window END from its (already calendar-aligned)
|
|
29
|
-
* START — the manager only resolves/threads the start (mirrors Python
|
|
30
|
-
* `base.py`); the RPC needs an explicit end for its `WHERE` clause, so this
|
|
31
|
-
* store computes it via `resolveCalendarWindow` (idempotent on an aligned
|
|
32
|
-
* start — re-resolving it yields the identical window).
|
|
33
|
-
*/
|
|
34
|
-
function featureWindowEnd(start, period) {
|
|
35
|
-
return resolveCalendarWindow(start, period).end;
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Parse a JSON `{tier_key: "3.0000", ...}` object (e.g. `tier_breakdown`,
|
|
39
|
-
* `expired_by_tier`) into `Record<string, Decimal>`, converting every value
|
|
40
|
-
* the same way scalar money fields are (never left as a raw string/number).
|
|
41
|
-
* Returns `null` when `raw` is not an object (absent/error responses).
|
|
42
|
-
*/
|
|
43
|
-
function decRecord(raw) {
|
|
44
|
-
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
45
|
-
return null;
|
|
46
|
-
const out = {};
|
|
47
|
-
for (const [k, v] of Object.entries(raw)) {
|
|
48
|
-
out[k] = dec(v);
|
|
49
|
-
}
|
|
50
|
-
return out;
|
|
51
|
-
}
|
|
52
|
-
/** Parse the ``feature_limits`` JSONB map into typed `FeatureLimit` records. */
|
|
53
|
-
function parseFeatureLimits(raw) {
|
|
54
|
-
if (!raw || typeof raw !== "object")
|
|
55
|
-
return {};
|
|
56
|
-
const out = {};
|
|
57
|
-
for (const [k, v] of Object.entries(raw)) {
|
|
58
|
-
const fl = (v ?? {});
|
|
59
|
-
out[k] = {
|
|
60
|
-
maxCalls: Number(fl.max_calls ?? fl.maxCalls ?? 0),
|
|
61
|
-
period: String(fl.period ?? "monthly") ?? "monthly",
|
|
62
|
-
action: String(fl.action ?? "deny") ?? "deny",
|
|
63
|
-
};
|
|
64
|
-
}
|
|
65
|
-
return out;
|
|
66
|
-
}
|
|
67
|
-
/** Parse the ``per_operation`` JSONB map into typed `OperationPolicy` records. */
|
|
68
|
-
function parsePerOperation(raw) {
|
|
69
|
-
if (!raw || typeof raw !== "object")
|
|
70
|
-
return {};
|
|
71
|
-
const out = {};
|
|
72
|
-
for (const [k, v] of Object.entries(raw)) {
|
|
73
|
-
const op = (v ?? {});
|
|
74
|
-
out[k] = {
|
|
75
|
-
billingMode: String(op.billing_mode ?? op.billingMode ?? "strict") ?? "strict",
|
|
76
|
-
maxConcurrent: op.max_concurrent != null
|
|
77
|
-
? Number(op.max_concurrent)
|
|
78
|
-
: op.maxConcurrent != null
|
|
79
|
-
? Number(op.maxConcurrent)
|
|
80
|
-
: null,
|
|
81
|
-
overdraftFloor: op.overdraft_floor != null
|
|
82
|
-
? dec(op.overdraft_floor)
|
|
83
|
-
: op.overdraftFloor != null
|
|
84
|
-
? dec(op.overdraftFloor)
|
|
85
|
-
: null,
|
|
86
|
-
};
|
|
87
|
-
}
|
|
88
|
-
return out;
|
|
89
|
-
}
|
|
90
|
-
/**
|
|
91
|
-
* Credit store backed by Supabase RPCs via raw HTTP (fetch).
|
|
92
|
-
*
|
|
93
|
-
* No supabase-js dependency — makes direct POST requests to the Supabase REST API.
|
|
94
|
-
*
|
|
95
|
-
* Error handling (M10 parity): network/fetch failures and JSON-decode errors are
|
|
96
|
-
* wrapped in `StoreError`; a non-2xx HTTP response throws `StoreError`. *Business*
|
|
97
|
-
* outcomes that the RPC returns as a `{"error": code}` envelope (insufficient
|
|
98
|
-
* credits, cap reached, over-refund, …) are NOT thrown — they are surfaced on the
|
|
99
|
-
* result model's `.error` field (e.g. `DeductionResult.error`), consistent with
|
|
100
|
-
* how the Postgres store and the Python SDK behave. The manager maps codes to
|
|
101
|
-
* typed exceptions.
|
|
102
|
-
*
|
|
103
|
-
* Args:
|
|
104
|
-
* url: Supabase project URL (e.g. ``https://<project>.supabase.co``).
|
|
105
|
-
* key: Supabase ``service_role`` key.
|
|
106
|
-
*/
|
|
107
|
-
export class HttpxSupabaseStore extends CreditStore {
|
|
108
|
-
url;
|
|
109
|
-
key;
|
|
110
|
-
constructor(url, key, pricingCacheTtl = 300) {
|
|
111
|
-
super(pricingCacheTtl);
|
|
112
|
-
this.url = url.replace(/\/+$/, "");
|
|
113
|
-
this.key = key;
|
|
114
|
-
}
|
|
115
|
-
/** POST to an RPC, returning the parsed JSON body. Wraps transport/parse errors. */
|
|
116
|
-
async post(fn, params) {
|
|
117
|
-
let resp;
|
|
118
|
-
try {
|
|
119
|
-
resp = await fetch(`${this.url}/rest/v1/rpc/${fn}`, {
|
|
120
|
-
method: "POST",
|
|
121
|
-
headers: {
|
|
122
|
-
apikey: this.key,
|
|
123
|
-
authorization: `Bearer ${this.key}`,
|
|
124
|
-
"content-type": "application/json",
|
|
125
|
-
},
|
|
126
|
-
body: JSON.stringify(params),
|
|
127
|
-
});
|
|
128
|
-
}
|
|
129
|
-
catch (err) {
|
|
130
|
-
// Network / DNS / connection-refused etc.
|
|
131
|
-
throw new StoreError(`Supabase RPC ${fn} request failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
132
|
-
}
|
|
133
|
-
if (!resp.ok) {
|
|
134
|
-
let text = "";
|
|
135
|
-
try {
|
|
136
|
-
text = await resp.text();
|
|
137
|
-
}
|
|
138
|
-
catch {
|
|
139
|
-
// ignore body-read failures
|
|
140
|
-
}
|
|
141
|
-
throw new StoreError(`Supabase RPC ${fn} failed (${resp.status}): ${text}`);
|
|
142
|
-
}
|
|
143
|
-
try {
|
|
144
|
-
return await resp.json();
|
|
145
|
-
}
|
|
146
|
-
catch (err) {
|
|
147
|
-
throw new StoreError(`Supabase RPC ${fn} returned invalid JSON: ${err instanceof Error ? err.message : String(err)}`);
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
/**
|
|
151
|
-
* GET a table row from the Supabase REST API.
|
|
152
|
-
* Uses URL query params for filtering (Supabase REST-style syntax).
|
|
153
|
-
*/
|
|
154
|
-
async restGet(table, params) {
|
|
155
|
-
const qs = new URLSearchParams(params).toString();
|
|
156
|
-
let resp;
|
|
157
|
-
try {
|
|
158
|
-
resp = await fetch(`${this.url}/rest/v1/${table}?${qs}`, {
|
|
159
|
-
method: "GET",
|
|
160
|
-
headers: {
|
|
161
|
-
apikey: this.key,
|
|
162
|
-
authorization: `Bearer ${this.key}`,
|
|
163
|
-
},
|
|
164
|
-
});
|
|
165
|
-
}
|
|
166
|
-
catch (err) {
|
|
167
|
-
throw new StoreError(`Supabase GET ${table} failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
168
|
-
}
|
|
169
|
-
if (!resp.ok) {
|
|
170
|
-
let text = "";
|
|
171
|
-
try {
|
|
172
|
-
text = await resp.text();
|
|
173
|
-
}
|
|
174
|
-
catch {
|
|
175
|
-
// ignore
|
|
176
|
-
}
|
|
177
|
-
throw new StoreError(`Supabase GET ${table} failed (${resp.status}): ${text}`);
|
|
178
|
-
}
|
|
179
|
-
try {
|
|
180
|
-
return (await resp.json());
|
|
181
|
-
}
|
|
182
|
-
catch (err) {
|
|
183
|
-
throw new StoreError(`Supabase GET ${table} returned invalid JSON: ${err instanceof Error ? err.message : String(err)}`);
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
/** RPC returning a single JSONB object. */
|
|
187
|
-
async rpc(fn, params) {
|
|
188
|
-
const data = await this.post(fn, params);
|
|
189
|
-
if (data === null || data === undefined)
|
|
190
|
-
return {};
|
|
191
|
-
if (Array.isArray(data)) {
|
|
192
|
-
const first = data[0];
|
|
193
|
-
return first != null && typeof first === "object" ? first : {};
|
|
194
|
-
}
|
|
195
|
-
if (typeof data === "object")
|
|
196
|
-
return data;
|
|
197
|
-
return { value: data };
|
|
198
|
-
}
|
|
199
|
-
/** RPC returning a set of rows. Always returns ALL rows. */
|
|
200
|
-
async rpcAll(fn, params) {
|
|
201
|
-
const data = await this.post(fn, params);
|
|
202
|
-
if (data === null || data === undefined)
|
|
203
|
-
return [];
|
|
204
|
-
if (!Array.isArray(data))
|
|
205
|
-
return [data];
|
|
206
|
-
return data.filter((r) => r != null);
|
|
207
|
-
}
|
|
208
|
-
/**
|
|
209
|
-
* Return the business-error code if `row` is an `{"error": code}` envelope,
|
|
210
|
-
* else null. An unexpected `error` value that is not a known business code is
|
|
211
|
-
* still surfaced (callers decide), but recognised codes are the contract set.
|
|
212
|
-
*/
|
|
213
|
-
errorCode(row) {
|
|
214
|
-
if ("error" in row && row.error) {
|
|
215
|
-
return String(row.error);
|
|
216
|
-
}
|
|
217
|
-
return null;
|
|
218
|
-
}
|
|
219
|
-
async setup(_databaseUrl) {
|
|
220
|
-
throw new StoreError("HttpxSupabaseStore.setup() cannot run migrations over the REST API. Apply the " +
|
|
221
|
-
"bundled SQL migrations via the Python CLI (`bursar migrate`) or by executing " +
|
|
222
|
-
"`python/src/bursar/sql/*.sql` (in filename order) against your database.");
|
|
223
|
-
}
|
|
224
|
-
async getBalance(userId) {
|
|
225
|
-
const row = await this.rpc("get_credits_balance", { p_user_id: userId });
|
|
226
|
-
const code = this.errorCode(row);
|
|
227
|
-
if (code)
|
|
228
|
-
throw new StoreError(`get_credits_balance: ${code}`);
|
|
229
|
-
return {
|
|
230
|
-
userId: String(row.user_id ?? userId),
|
|
231
|
-
balance: dec(row.balance),
|
|
232
|
-
lifetimePurchased: dec(row.lifetime_purchased),
|
|
233
|
-
};
|
|
234
|
-
}
|
|
235
|
-
async addCredits(userId, amount, type = "adjustment", metadata, expiresAt, tier,
|
|
236
|
-
// NOTE: threaded through defensively as a new named param to the
|
|
237
|
-
// `credits_add` RPC. Confirm the SQL migration adds a `p_idempotency_key`
|
|
238
|
-
// parameter (with a default) before relying on this against a real
|
|
239
|
-
// database (see 011_lazy_expiry.sql).
|
|
240
|
-
idempotencyKey) {
|
|
241
|
-
const meta = { ...(metadata ?? {}) };
|
|
242
|
-
if (expiresAt) {
|
|
243
|
-
meta.expires_at = expiresAt instanceof Date ? expiresAt.toISOString() : String(expiresAt);
|
|
244
|
-
}
|
|
245
|
-
const row = await this.rpc("credits_add", {
|
|
246
|
-
p_user_id: userId,
|
|
247
|
-
p_amount: decParam(amount),
|
|
248
|
-
p_type: type,
|
|
249
|
-
p_metadata: meta,
|
|
250
|
-
p_tier: tier ?? null,
|
|
251
|
-
p_idempotency_key: idempotencyKey ?? null,
|
|
252
|
-
});
|
|
253
|
-
const code = this.errorCode(row);
|
|
254
|
-
if (code)
|
|
255
|
-
throw new StoreError(`credits_add: ${code}`);
|
|
256
|
-
return {
|
|
257
|
-
transactionId: String(row.id ?? ""),
|
|
258
|
-
userId: String(row.user_id ?? userId),
|
|
259
|
-
amount: dec(row.amount, amount),
|
|
260
|
-
newBalance: dec(row.new_balance),
|
|
261
|
-
lifetimePurchased: dec(row.lifetime_purchased),
|
|
262
|
-
tier: String(row.tier ?? tier ?? "default"),
|
|
263
|
-
idempotent: Boolean(row.idempotent),
|
|
264
|
-
};
|
|
265
|
-
}
|
|
266
|
-
async deductWithAllowance(userId, amount, options) {
|
|
267
|
-
const idempotencyKey = options?.idempotencyKey ?? null;
|
|
268
|
-
const minBalance = options?.minBalance ?? ZERO;
|
|
269
|
-
const model = options?.model ?? null;
|
|
270
|
-
const metadata = options?.metadata ?? {};
|
|
271
|
-
const periodStart = options?.periodStart ?? null;
|
|
272
|
-
const feature = options?.feature ?? null;
|
|
273
|
-
const featureLimit = options?.featureLimit ?? null;
|
|
274
|
-
const featurePeriodStart = options?.featurePeriodStart ?? null;
|
|
275
|
-
const featurePeriodEnd = featureLimit != null && featurePeriodStart != null
|
|
276
|
-
? featureWindowEnd(featurePeriodStart, featureLimit.period)
|
|
277
|
-
: null;
|
|
278
|
-
const row = await this.rpc("deduct_with_allowance", {
|
|
279
|
-
p_user_id: userId,
|
|
280
|
-
p_amount: decParam(amount),
|
|
281
|
-
p_idempotency_key: idempotencyKey,
|
|
282
|
-
p_min_balance: decParam(minBalance),
|
|
283
|
-
p_model: model,
|
|
284
|
-
p_metadata: metadata ?? {},
|
|
285
|
-
p_period_start: periodStart != null ? periodStart.toISOString().slice(0, 10) : null,
|
|
286
|
-
p_feature: feature,
|
|
287
|
-
p_feature_max_calls: featureLimit != null ? featureLimit.maxCalls : null,
|
|
288
|
-
p_feature_action: featureLimit != null ? featureLimit.action : null,
|
|
289
|
-
p_feature_period_start: featurePeriodStart != null ? featurePeriodStart.toISOString().slice(0, 10) : null,
|
|
290
|
-
p_feature_period_end: featurePeriodEnd != null ? featurePeriodEnd.toISOString().slice(0, 10) : null,
|
|
291
|
-
});
|
|
292
|
-
const code = this.errorCode(row);
|
|
293
|
-
if (code) {
|
|
294
|
-
return {
|
|
295
|
-
transactionId: "",
|
|
296
|
-
userId,
|
|
297
|
-
amount: ZERO,
|
|
298
|
-
allowanceConsumed: ZERO,
|
|
299
|
-
balanceAfter: dec(row.balance_after),
|
|
300
|
-
idempotent: false,
|
|
301
|
-
capWarning: null,
|
|
302
|
-
featureLimitWarning: null,
|
|
303
|
-
error: code,
|
|
304
|
-
};
|
|
305
|
-
}
|
|
306
|
-
return {
|
|
307
|
-
transactionId: String(row.transaction_id ?? ""),
|
|
308
|
-
userId,
|
|
309
|
-
amount: dec(row.amount),
|
|
310
|
-
allowanceConsumed: dec(row.allowance_consumed),
|
|
311
|
-
balanceAfter: dec(row.balance_after),
|
|
312
|
-
idempotent: Boolean(row.idempotent),
|
|
313
|
-
capWarning: row.cap_warning != null ? String(row.cap_warning) : null,
|
|
314
|
-
featureLimitWarning: row.feature_limit_warning != null ? String(row.feature_limit_warning) : null,
|
|
315
|
-
tierBreakdown: decRecord(row.tier_breakdown),
|
|
316
|
-
};
|
|
317
|
-
}
|
|
318
|
-
// ── Lease lifecycle (atomic admission) ─────────────────────────────
|
|
319
|
-
async createLease(userId, amount, operationType, options) {
|
|
320
|
-
const billingMode = options?.billingMode ?? "strict";
|
|
321
|
-
const floor = options?.floor ?? ZERO;
|
|
322
|
-
const overdraftFloor = options?.overdraftFloor ?? null;
|
|
323
|
-
const periodStart = options?.periodStart ?? null;
|
|
324
|
-
const feature = options?.feature ?? null;
|
|
325
|
-
const featureLimit = options?.featureLimit ?? null;
|
|
326
|
-
const featurePeriodStart = options?.featurePeriodStart ?? null;
|
|
327
|
-
const featurePeriodEnd = featureLimit != null && featurePeriodStart != null
|
|
328
|
-
? featureWindowEnd(featurePeriodStart, featureLimit.period)
|
|
329
|
-
: null;
|
|
330
|
-
const row = await this.rpc("create_lease", {
|
|
331
|
-
p_user_id: userId,
|
|
332
|
-
p_amount: decParam(amount),
|
|
333
|
-
p_operation_type: operationType,
|
|
334
|
-
p_billing_mode: billingMode,
|
|
335
|
-
p_floor: decParam(floor),
|
|
336
|
-
p_max_concurrent: options?.maxConcurrent ?? null,
|
|
337
|
-
p_ttl_seconds: options?.ttlSeconds ?? 600,
|
|
338
|
-
p_model: options?.model ?? null,
|
|
339
|
-
p_overdraft_floor: overdraftFloor != null ? decParam(overdraftFloor) : null,
|
|
340
|
-
p_metadata: options?.metadata ?? {},
|
|
341
|
-
p_period_start: periodStart != null ? periodStart.toISOString().slice(0, 10) : null,
|
|
342
|
-
p_feature: feature,
|
|
343
|
-
p_feature_max_calls: featureLimit != null ? featureLimit.maxCalls : null,
|
|
344
|
-
p_feature_action: featureLimit != null ? featureLimit.action : null,
|
|
345
|
-
p_feature_period_start: featurePeriodStart != null ? featurePeriodStart.toISOString().slice(0, 10) : null,
|
|
346
|
-
p_feature_period_end: featurePeriodEnd != null ? featurePeriodEnd.toISOString().slice(0, 10) : null,
|
|
347
|
-
});
|
|
348
|
-
const code = this.errorCode(row);
|
|
349
|
-
if (code) {
|
|
350
|
-
return {
|
|
351
|
-
leaseId: "",
|
|
352
|
-
userId,
|
|
353
|
-
amount: ZERO,
|
|
354
|
-
available: dec(row.available),
|
|
355
|
-
reservedTotal: dec(row.reserved),
|
|
356
|
-
billingMode,
|
|
357
|
-
expiresAt: "",
|
|
358
|
-
error: code,
|
|
359
|
-
};
|
|
360
|
-
}
|
|
361
|
-
return {
|
|
362
|
-
leaseId: String(row.lease_id ?? ""),
|
|
363
|
-
userId: String(row.user_id ?? userId),
|
|
364
|
-
amount: dec(row.amount),
|
|
365
|
-
available: dec(row.available),
|
|
366
|
-
reservedTotal: dec(row.reserved),
|
|
367
|
-
billingMode: String(row.billing_mode ?? billingMode) ?? billingMode,
|
|
368
|
-
expiresAt: String(row.expires_at ?? ""),
|
|
369
|
-
};
|
|
370
|
-
}
|
|
371
|
-
async settleLease(userId, leaseId, amount, options) {
|
|
372
|
-
const minBalance = options?.minBalance ?? ZERO;
|
|
373
|
-
const periodStart = options?.periodStart ?? null;
|
|
374
|
-
const feature = options?.feature ?? null;
|
|
375
|
-
const featureLimit = options?.featureLimit ?? null;
|
|
376
|
-
const featurePeriodStart = options?.featurePeriodStart ?? null;
|
|
377
|
-
const featurePeriodEnd = featureLimit != null && featurePeriodStart != null
|
|
378
|
-
? featureWindowEnd(featurePeriodStart, featureLimit.period)
|
|
379
|
-
: null;
|
|
380
|
-
const row = await this.rpc("settle_lease", {
|
|
381
|
-
p_user_id: userId,
|
|
382
|
-
p_lease_id: leaseId,
|
|
383
|
-
p_amount: decParam(amount),
|
|
384
|
-
p_idempotency_key: options?.idempotencyKey ?? null,
|
|
385
|
-
p_min_balance: decParam(minBalance),
|
|
386
|
-
p_model: options?.model ?? null,
|
|
387
|
-
p_metadata: options?.metadata ?? {},
|
|
388
|
-
p_period_start: periodStart != null ? periodStart.toISOString().slice(0, 10) : null,
|
|
389
|
-
p_feature: feature,
|
|
390
|
-
p_feature_max_calls: featureLimit != null ? featureLimit.maxCalls : null,
|
|
391
|
-
p_feature_action: featureLimit != null ? featureLimit.action : null,
|
|
392
|
-
p_feature_period_start: featurePeriodStart != null ? featurePeriodStart.toISOString().slice(0, 10) : null,
|
|
393
|
-
p_feature_period_end: featurePeriodEnd != null ? featurePeriodEnd.toISOString().slice(0, 10) : null,
|
|
394
|
-
});
|
|
395
|
-
const code = this.errorCode(row);
|
|
396
|
-
if (code) {
|
|
397
|
-
return {
|
|
398
|
-
transactionId: "",
|
|
399
|
-
userId,
|
|
400
|
-
amount: ZERO,
|
|
401
|
-
allowanceConsumed: ZERO,
|
|
402
|
-
balanceAfter: dec(row.balance_after),
|
|
403
|
-
idempotent: false,
|
|
404
|
-
capWarning: null,
|
|
405
|
-
featureLimitWarning: null,
|
|
406
|
-
error: code,
|
|
407
|
-
};
|
|
408
|
-
}
|
|
409
|
-
return {
|
|
410
|
-
transactionId: String(row.transaction_id ?? ""),
|
|
411
|
-
userId,
|
|
412
|
-
amount: dec(row.amount),
|
|
413
|
-
allowanceConsumed: dec(row.allowance_consumed),
|
|
414
|
-
balanceAfter: dec(row.balance_after),
|
|
415
|
-
idempotent: Boolean(row.idempotent),
|
|
416
|
-
capWarning: row.cap_warning != null ? String(row.cap_warning) : null,
|
|
417
|
-
featureLimitWarning: row.feature_limit_warning != null ? String(row.feature_limit_warning) : null,
|
|
418
|
-
tierBreakdown: decRecord(row.tier_breakdown),
|
|
419
|
-
};
|
|
420
|
-
}
|
|
421
|
-
async releaseLease(userId, leaseId) {
|
|
422
|
-
const row = await this.rpc("release_lease", { p_user_id: userId, p_lease_id: leaseId });
|
|
423
|
-
return {
|
|
424
|
-
leaseId,
|
|
425
|
-
userId,
|
|
426
|
-
released: Boolean(row.released),
|
|
427
|
-
reason: row.reason != null ? String(row.reason) : null,
|
|
428
|
-
};
|
|
429
|
-
}
|
|
430
|
-
async renewLease(userId, leaseId, ttlSeconds) {
|
|
431
|
-
const row = await this.rpc("renew_lease", {
|
|
432
|
-
p_user_id: userId,
|
|
433
|
-
p_lease_id: leaseId,
|
|
434
|
-
p_ttl_seconds: ttlSeconds,
|
|
435
|
-
});
|
|
436
|
-
const code = this.errorCode(row);
|
|
437
|
-
if (code) {
|
|
438
|
-
return {
|
|
439
|
-
leaseId,
|
|
440
|
-
userId,
|
|
441
|
-
amount: ZERO,
|
|
442
|
-
available: ZERO,
|
|
443
|
-
reservedTotal: ZERO,
|
|
444
|
-
billingMode: "strict",
|
|
445
|
-
expiresAt: "",
|
|
446
|
-
error: code,
|
|
447
|
-
};
|
|
448
|
-
}
|
|
449
|
-
return {
|
|
450
|
-
leaseId: String(row.lease_id ?? leaseId),
|
|
451
|
-
userId,
|
|
452
|
-
amount: dec(row.amount),
|
|
453
|
-
available: dec(row.available),
|
|
454
|
-
reservedTotal: dec(row.reserved),
|
|
455
|
-
billingMode: String(row.billing_mode ?? "strict"),
|
|
456
|
-
expiresAt: String(row.expires_at ?? ""),
|
|
457
|
-
};
|
|
458
|
-
}
|
|
459
|
-
async getAvailable(userId) {
|
|
460
|
-
const row = await this.rpc("get_available_credits", { p_user_id: userId });
|
|
461
|
-
return {
|
|
462
|
-
userId,
|
|
463
|
-
balance: dec(row.balance),
|
|
464
|
-
reserved: dec(row.reserved),
|
|
465
|
-
available: dec(row.available),
|
|
466
|
-
};
|
|
467
|
-
}
|
|
468
|
-
async getActivePricing() {
|
|
469
|
-
return this._getCachedPricing(() => this._loadActivePricing());
|
|
470
|
-
}
|
|
471
|
-
async _loadActivePricing() {
|
|
472
|
-
const row = await this.rpc("get_active_pricing_config", {});
|
|
473
|
-
if (!row || Object.keys(row).length === 0)
|
|
474
|
-
return null;
|
|
475
|
-
const code = this.errorCode(row);
|
|
476
|
-
if (code)
|
|
477
|
-
throw new StoreError(`get_active_pricing_config: ${code}`);
|
|
478
|
-
return row;
|
|
479
|
-
}
|
|
480
|
-
async setActivePricing(config, label) {
|
|
481
|
-
const row = await this.rpc("set_active_pricing_config", {
|
|
482
|
-
p_config: config,
|
|
483
|
-
p_label: label ?? null,
|
|
484
|
-
});
|
|
485
|
-
const code = this.errorCode(row);
|
|
486
|
-
if (code)
|
|
487
|
-
throw new StoreError(`set_active_pricing_config: ${code}`);
|
|
488
|
-
this.invalidatePricingCache();
|
|
489
|
-
return String(row.id ?? "");
|
|
490
|
-
}
|
|
491
|
-
// H8: pricing history / activation — mirrors Python base.py:293-312.
|
|
492
|
-
async getPricingHistory() {
|
|
493
|
-
const rows = await this.rpc("get_pricing_history", {});
|
|
494
|
-
if (!rows)
|
|
495
|
-
return [];
|
|
496
|
-
const arr = Array.isArray(rows) ? rows : [rows];
|
|
497
|
-
return arr.map((r) => ({
|
|
498
|
-
id: String(r.id ?? ""),
|
|
499
|
-
version: Number(r.version ?? 0),
|
|
500
|
-
label: r.label ?? null,
|
|
501
|
-
active: Boolean(r.active ?? false),
|
|
502
|
-
createdAt: String(r.created_at ?? ""),
|
|
503
|
-
}));
|
|
504
|
-
}
|
|
505
|
-
async getPricingConfig(version) {
|
|
506
|
-
const row = await this.rpc("get_pricing_config", { p_version: version });
|
|
507
|
-
if (!row || Object.keys(row).length === 0)
|
|
508
|
-
return null;
|
|
509
|
-
const code = this.errorCode(row);
|
|
510
|
-
if (code)
|
|
511
|
-
throw new StoreError(`get_pricing_config: ${code}`);
|
|
512
|
-
return {
|
|
513
|
-
id: String(row.id ?? ""),
|
|
514
|
-
config: row.config,
|
|
515
|
-
version: Number(row.version ?? version),
|
|
516
|
-
};
|
|
517
|
-
}
|
|
518
|
-
async activatePricing(version) {
|
|
519
|
-
const row = await this.rpc("activate_pricing", { p_version: version });
|
|
520
|
-
const code = this.errorCode(row);
|
|
521
|
-
if (code)
|
|
522
|
-
throw new StoreError(`activate_pricing: ${code}`);
|
|
523
|
-
this.invalidatePricingCache();
|
|
524
|
-
return String(row.id ?? "");
|
|
525
|
-
}
|
|
526
|
-
// ── Plan management ────────────────────────────────────────────────
|
|
527
|
-
async getUserPlan(userId) {
|
|
528
|
-
const row = await this.rpc("get_user_plan", { p_user_id: userId });
|
|
529
|
-
if (!row || Object.keys(row).length === 0) {
|
|
530
|
-
return { userId, planId: null, planName: null, freeAllowance: ZERO, features: {} };
|
|
531
|
-
}
|
|
532
|
-
const code = this.errorCode(row);
|
|
533
|
-
if (code)
|
|
534
|
-
throw new StoreError(`get_user_plan: ${code}`);
|
|
535
|
-
return {
|
|
536
|
-
userId: String(row.user_id ?? userId),
|
|
537
|
-
planId: row.plan_id ?? null,
|
|
538
|
-
planName: row.plan_name ?? null,
|
|
539
|
-
freeAllowance: dec(row.free_allowance),
|
|
540
|
-
features: row.features ?? {},
|
|
541
|
-
featureLimits: parseFeatureLimits(row.feature_limits),
|
|
542
|
-
defaultBillingMode: String(row.default_billing_mode ?? "strict") ?? "strict",
|
|
543
|
-
perOperation: parsePerOperation(row.per_operation),
|
|
544
|
-
maxConcurrent: row.max_concurrent != null ? Number(row.max_concurrent) : null,
|
|
545
|
-
overdraftFloor: row.overdraft_floor != null ? dec(row.overdraft_floor) : null,
|
|
546
|
-
allowancePeriod: row.allowance_period ?? "calendar_month",
|
|
547
|
-
planAssignedAt: row.plan_assigned_at != null ? new Date(String(row.plan_assigned_at)) : null,
|
|
548
|
-
};
|
|
549
|
-
}
|
|
550
|
-
async checkFeature(userId, feature) {
|
|
551
|
-
const plan = await this.getUserPlan(userId);
|
|
552
|
-
const present = Object.prototype.hasOwnProperty.call(plan.features, feature);
|
|
553
|
-
const value = present ? plan.features[feature] : null;
|
|
554
|
-
return {
|
|
555
|
-
userId,
|
|
556
|
-
feature,
|
|
557
|
-
value,
|
|
558
|
-
// M6: presence-vs-truthiness — numeric 0 / "" count as present.
|
|
559
|
-
hasFeature: present && value !== null && value !== undefined && value !== false,
|
|
560
|
-
};
|
|
561
|
-
}
|
|
562
|
-
async setUserPlan(userId, planId, planAssignedAt) {
|
|
563
|
-
const params = {
|
|
564
|
-
p_user_id: userId,
|
|
565
|
-
p_plan_key: planId,
|
|
566
|
-
};
|
|
567
|
-
if (planAssignedAt != null) {
|
|
568
|
-
params.p_plan_assigned_at = planAssignedAt.toISOString();
|
|
569
|
-
}
|
|
570
|
-
const row = await this.rpc("set_user_plan", params);
|
|
571
|
-
const code = this.errorCode(row);
|
|
572
|
-
if (code)
|
|
573
|
-
throw new StoreError(`set_user_plan: ${code}`);
|
|
574
|
-
return {
|
|
575
|
-
userId: String(row.user_id ?? userId),
|
|
576
|
-
planId: String(row.plan_id ?? planId),
|
|
577
|
-
planAssignedAt: row.plan_assigned_at != null ? String(row.plan_assigned_at) : null,
|
|
578
|
-
};
|
|
579
|
-
}
|
|
580
|
-
async unsetUserPlan(userId) {
|
|
581
|
-
const row = await this.rpc("unset_user_plan", { p_user_id: userId });
|
|
582
|
-
return { userId: String(row?.user_id ?? userId) };
|
|
583
|
-
}
|
|
584
|
-
async checkAllowance(userId, periodStart) {
|
|
585
|
-
const row = await this.rpc("check_plan_allowance", {
|
|
586
|
-
p_user_id: userId,
|
|
587
|
-
p_period_start: periodStart != null ? periodStart.toISOString().slice(0, 10) : null,
|
|
588
|
-
});
|
|
589
|
-
if (!row || Object.keys(row).length === 0) {
|
|
590
|
-
return { planId: "", allowanceRemaining: ZERO, periodStart: "", periodEnd: "" };
|
|
591
|
-
}
|
|
592
|
-
const code = this.errorCode(row);
|
|
593
|
-
if (code)
|
|
594
|
-
throw new StoreError(`check_plan_allowance: ${code}`);
|
|
595
|
-
return {
|
|
596
|
-
planId: String(row.plan_id ?? ""),
|
|
597
|
-
allowanceRemaining: dec(row.allowance_remaining),
|
|
598
|
-
periodStart: String(row.period_start ?? ""),
|
|
599
|
-
periodEnd: String(row.period_end ?? ""),
|
|
600
|
-
};
|
|
601
|
-
}
|
|
602
|
-
async incrementUsageWindow(userId, planId, amount) {
|
|
603
|
-
const row = await this.rpc("increment_usage_window", {
|
|
604
|
-
p_user_id: userId,
|
|
605
|
-
p_plan_id: planId,
|
|
606
|
-
p_amount: decParam(amount),
|
|
607
|
-
});
|
|
608
|
-
const code = this.errorCode(row);
|
|
609
|
-
if (code)
|
|
610
|
-
throw new StoreError(`increment_usage_window: ${code}`);
|
|
611
|
-
}
|
|
612
|
-
/** Advisory, non-locking read of invocation-count usage (UI only). Mirrors `checkSpendCap`. */
|
|
613
|
-
async checkFeatureLimit(userId, feature, maxCalls, periodStart, periodEnd) {
|
|
614
|
-
const row = await this.rpc("check_feature_limit", {
|
|
615
|
-
p_user_id: userId,
|
|
616
|
-
p_feature: feature,
|
|
617
|
-
p_max_calls: maxCalls,
|
|
618
|
-
p_period_start: periodStart.toISOString().slice(0, 10),
|
|
619
|
-
p_period_end: periodEnd.toISOString().slice(0, 10),
|
|
620
|
-
});
|
|
621
|
-
if (!row || Object.keys(row).length === 0) {
|
|
622
|
-
return {
|
|
623
|
-
userId,
|
|
624
|
-
feature,
|
|
625
|
-
limited: false,
|
|
626
|
-
limit: 0,
|
|
627
|
-
used: 0,
|
|
628
|
-
remaining: 0,
|
|
629
|
-
periodStart: "",
|
|
630
|
-
periodEnd: "",
|
|
631
|
-
action: null,
|
|
632
|
-
};
|
|
633
|
-
}
|
|
634
|
-
const code = this.errorCode(row);
|
|
635
|
-
if (code)
|
|
636
|
-
throw new StoreError(`check_feature_limit: ${code}`);
|
|
637
|
-
return {
|
|
638
|
-
userId: String(row.user_id ?? userId),
|
|
639
|
-
feature: String(row.feature ?? feature),
|
|
640
|
-
limited: Boolean(row.limited ?? true),
|
|
641
|
-
limit: Number(row.limit ?? maxCalls),
|
|
642
|
-
used: Number(row.used ?? 0),
|
|
643
|
-
remaining: Number(row.remaining ?? Math.max(maxCalls - Number(row.used ?? 0), 0)),
|
|
644
|
-
periodStart: String(row.period_start ?? ""),
|
|
645
|
-
periodEnd: String(row.period_end ?? ""),
|
|
646
|
-
action: row.action ?? null,
|
|
647
|
-
};
|
|
648
|
-
}
|
|
649
|
-
// ── Spend caps and rate limiting ──────────────────────────────────────
|
|
650
|
-
async checkSpendCap(userId, model, amount) {
|
|
651
|
-
const row = await this.rpc("check_spend_cap", {
|
|
652
|
-
p_user_id: userId,
|
|
653
|
-
p_model: model ?? null,
|
|
654
|
-
p_amount: decParam(amount ?? ZERO),
|
|
655
|
-
});
|
|
656
|
-
if (!row || Object.keys(row).length === 0) {
|
|
657
|
-
return { capped: false, currentSpend: ZERO, limit: ZERO, action: null };
|
|
658
|
-
}
|
|
659
|
-
return {
|
|
660
|
-
capped: Boolean(row.capped),
|
|
661
|
-
currentSpend: dec(row.current_spend),
|
|
662
|
-
limit: dec(row.cap_limit),
|
|
663
|
-
action: row.action ?? null,
|
|
664
|
-
model: row.model ? String(row.model) : undefined,
|
|
665
|
-
};
|
|
666
|
-
}
|
|
667
|
-
// ── Revoke credits by tx type ──────────────────────────────────────────
|
|
668
|
-
async revokeCreditsByTxType(userId, txType) {
|
|
669
|
-
const row = await this.rpc("revoke_credits_by_tx_type", {
|
|
670
|
-
p_user_id: userId,
|
|
671
|
-
p_tx_type: txType,
|
|
672
|
-
});
|
|
673
|
-
const code = this.errorCode(row);
|
|
674
|
-
if (code)
|
|
675
|
-
throw new StoreError(`revoke_credits_by_tx_type: ${code}`);
|
|
676
|
-
return row;
|
|
677
|
-
}
|
|
678
|
-
// ── Refunds ──────────────────────────────────────────────────────────
|
|
679
|
-
async refundCredits(transactionId, amount, reason, metadata) {
|
|
680
|
-
const row = await this.rpc("refund_credits", {
|
|
681
|
-
p_transaction_id: transactionId,
|
|
682
|
-
p_amount: amount != null ? decParam(amount) : null,
|
|
683
|
-
p_reason: reason ?? null,
|
|
684
|
-
p_metadata: metadata ?? {},
|
|
685
|
-
});
|
|
686
|
-
const code = this.errorCode(row);
|
|
687
|
-
if (code) {
|
|
688
|
-
return {
|
|
689
|
-
refundTransactionId: "",
|
|
690
|
-
originalTransactionId: transactionId,
|
|
691
|
-
userId: String(row.user_id ?? ""),
|
|
692
|
-
amount: ZERO,
|
|
693
|
-
newBalance: dec(row.new_balance),
|
|
694
|
-
error: code,
|
|
695
|
-
};
|
|
696
|
-
}
|
|
697
|
-
return {
|
|
698
|
-
refundTransactionId: String(row.refund_transaction_id ?? ""),
|
|
699
|
-
originalTransactionId: transactionId,
|
|
700
|
-
userId: String(row.user_id ?? ""),
|
|
701
|
-
amount: dec(row.amount),
|
|
702
|
-
newBalance: dec(row.new_balance),
|
|
703
|
-
tierBreakdown: decRecord(row.tier_breakdown),
|
|
704
|
-
};
|
|
705
|
-
}
|
|
706
|
-
// ── Usage analytics ──────────────────────────────────────────────────
|
|
707
|
-
async spendByUser(start, end) {
|
|
708
|
-
const rows = await this.rpcAll("spend_by_user", {
|
|
709
|
-
p_start: start.toISOString(),
|
|
710
|
-
p_end: end.toISOString(),
|
|
711
|
-
});
|
|
712
|
-
return rows.map((row) => ({
|
|
713
|
-
userId: String(row.user_id ?? ""),
|
|
714
|
-
totalSpend: dec(row.total_spend),
|
|
715
|
-
transactionCount: Number(row.transaction_count ?? 0),
|
|
716
|
-
}));
|
|
717
|
-
}
|
|
718
|
-
async spendByModel(start, end) {
|
|
719
|
-
const rows = await this.rpcAll("spend_by_model", {
|
|
720
|
-
p_start: start.toISOString(),
|
|
721
|
-
p_end: end.toISOString(),
|
|
722
|
-
});
|
|
723
|
-
return rows.map((row) => ({
|
|
724
|
-
model: String(row.model ?? ""),
|
|
725
|
-
totalSpend: dec(row.total_spend),
|
|
726
|
-
transactionCount: Number(row.transaction_count ?? 0),
|
|
727
|
-
}));
|
|
728
|
-
}
|
|
729
|
-
async topUsers(limit, start, end) {
|
|
730
|
-
const rows = await this.rpcAll("top_users", {
|
|
731
|
-
p_limit: limit,
|
|
732
|
-
p_start: start.toISOString(),
|
|
733
|
-
p_end: end.toISOString(),
|
|
734
|
-
});
|
|
735
|
-
return rows.map((row) => ({
|
|
736
|
-
userId: String(row.user_id ?? ""),
|
|
737
|
-
totalSpend: dec(row.total_spend),
|
|
738
|
-
}));
|
|
739
|
-
}
|
|
740
|
-
async dailySpend(start, end) {
|
|
741
|
-
const rows = await this.rpcAll("daily_spend", {
|
|
742
|
-
p_start: start.toISOString(),
|
|
743
|
-
p_end: end.toISOString(),
|
|
744
|
-
});
|
|
745
|
-
return rows.map((row) => ({
|
|
746
|
-
date: String(row.date ?? ""),
|
|
747
|
-
totalSpend: dec(row.total_spend),
|
|
748
|
-
transactionCount: Number(row.transaction_count ?? 0),
|
|
749
|
-
}));
|
|
750
|
-
}
|
|
751
|
-
// ── Transaction listing ─────────────────────────────────────────────
|
|
752
|
-
async listUserTransactions(userId, options) {
|
|
753
|
-
const rows = await this.rpcAll("list_user_transactions", {
|
|
754
|
-
p_user_id: userId,
|
|
755
|
-
p_types: options?.types ?? null,
|
|
756
|
-
p_from_date: options?.fromDate?.toISOString() ?? null,
|
|
757
|
-
p_to_date: options?.toDate?.toISOString() ?? null,
|
|
758
|
-
p_limit: options?.limit ?? 50,
|
|
759
|
-
p_offset: options?.offset ?? 0,
|
|
760
|
-
});
|
|
761
|
-
const items = rows.map((r) => ({
|
|
762
|
-
id: String(r.id ?? ""),
|
|
763
|
-
userId: String(r.user_id ?? ""),
|
|
764
|
-
amount: dec(r.amount),
|
|
765
|
-
type: String(r.type ?? ""),
|
|
766
|
-
referenceType: r.reference_type != null ? String(r.reference_type) : null,
|
|
767
|
-
referenceId: r.reference_id != null ? String(r.reference_id) : null,
|
|
768
|
-
metadata: r.metadata ?? null,
|
|
769
|
-
createdAt: String(r.created_at ?? ""),
|
|
770
|
-
}));
|
|
771
|
-
const total = rows.length > 0 ? Number(rows[0].total_count ?? 0) : 0;
|
|
772
|
-
return { items, total };
|
|
773
|
-
}
|
|
774
|
-
async listUsageEvents(userId, options) {
|
|
775
|
-
const rows = await this.rpcAll("list_usage_events", {
|
|
776
|
-
p_user_id: userId,
|
|
777
|
-
p_from_date: options?.fromDate?.toISOString() ?? null,
|
|
778
|
-
p_to_date: options?.toDate?.toISOString() ?? null,
|
|
779
|
-
p_limit: options?.limit ?? 50,
|
|
780
|
-
p_offset: options?.offset ?? 0,
|
|
781
|
-
});
|
|
782
|
-
const items = rows.map((r) => ({
|
|
783
|
-
id: String(r.id ?? ""),
|
|
784
|
-
userId: String(r.user_id ?? ""),
|
|
785
|
-
amount: dec(r.amount),
|
|
786
|
-
type: String(r.type ?? ""),
|
|
787
|
-
referenceType: r.reference_type != null ? String(r.reference_type) : null,
|
|
788
|
-
referenceId: r.reference_id != null ? String(r.reference_id) : null,
|
|
789
|
-
metadata: r.metadata ?? null,
|
|
790
|
-
createdAt: String(r.created_at ?? ""),
|
|
791
|
-
}));
|
|
792
|
-
const total = rows.length > 0 ? Number(rows[0].total_count ?? 0) : 0;
|
|
793
|
-
return { items, total };
|
|
794
|
-
}
|
|
795
|
-
// ── Aggregate stats ────────────────────────────────────────────────
|
|
796
|
-
async aggregateStats(start, end) {
|
|
797
|
-
const row = await this.rpc("aggregate_stats", {
|
|
798
|
-
p_start: start.toISOString(),
|
|
799
|
-
p_end: end.toISOString(),
|
|
800
|
-
});
|
|
801
|
-
return {
|
|
802
|
-
totalCreditsConsumed: dec(row.total_credits_consumed),
|
|
803
|
-
activeUsers: Number(row.active_users ?? 0),
|
|
804
|
-
avgDailySpend: dec(row.avg_daily_spend),
|
|
805
|
-
topModel: String(row.top_model ?? ""),
|
|
806
|
-
topUser: String(row.top_user ?? ""),
|
|
807
|
-
};
|
|
808
|
-
}
|
|
809
|
-
// ── Team/shared balance pools ────────────────────────────────────────
|
|
810
|
-
async createTeam(name, initialBalance = ZERO) {
|
|
811
|
-
const row = await this.rpc("create_team", {
|
|
812
|
-
p_name: name,
|
|
813
|
-
p_initial_balance: decParam(initialBalance),
|
|
814
|
-
});
|
|
815
|
-
const code = this.errorCode(row);
|
|
816
|
-
if (code)
|
|
817
|
-
throw new StoreError(`create_team: ${code}`);
|
|
818
|
-
return {
|
|
819
|
-
teamId: String(row.team_id ?? ""),
|
|
820
|
-
name: String(row.name ?? name),
|
|
821
|
-
};
|
|
822
|
-
}
|
|
823
|
-
async getTeamBalance(teamId) {
|
|
824
|
-
const row = await this.rpc("get_team_balance", { p_team_id: teamId });
|
|
825
|
-
if (!row || Object.keys(row).length === 0 || ("error" in row && row.error)) {
|
|
826
|
-
return { teamId, name: "", balance: ZERO, memberCount: 0 };
|
|
827
|
-
}
|
|
828
|
-
return {
|
|
829
|
-
teamId: String(row.team_id ?? teamId),
|
|
830
|
-
name: String(row.name ?? ""),
|
|
831
|
-
balance: dec(row.balance),
|
|
832
|
-
memberCount: Number(row.member_count ?? 0),
|
|
833
|
-
};
|
|
834
|
-
}
|
|
835
|
-
async addTeamMember(teamId, userId, role = "member", spendCap) {
|
|
836
|
-
const row = await this.rpc("add_team_member", {
|
|
837
|
-
p_team_id: teamId,
|
|
838
|
-
p_user_id: userId,
|
|
839
|
-
p_role: role,
|
|
840
|
-
p_spend_cap: spendCap != null ? decParam(spendCap) : null,
|
|
841
|
-
});
|
|
842
|
-
const code = this.errorCode(row);
|
|
843
|
-
if (code)
|
|
844
|
-
throw new StoreError(`add_team_member: ${code}`);
|
|
845
|
-
return {
|
|
846
|
-
teamId: String(row.team_id ?? teamId),
|
|
847
|
-
userId: String(row.user_id ?? userId),
|
|
848
|
-
role: String(row.role ?? role),
|
|
849
|
-
};
|
|
850
|
-
}
|
|
851
|
-
async getTeamMembers(teamId) {
|
|
852
|
-
const rows = await this.rpcAll("get_team_members", { p_team_id: teamId });
|
|
853
|
-
return rows.map((row) => ({
|
|
854
|
-
userId: String(row.user_id ?? ""),
|
|
855
|
-
role: String(row.role ?? "member"),
|
|
856
|
-
spendCap: row.spend_cap != null ? dec(row.spend_cap) : null,
|
|
857
|
-
totalSpent: dec(row.total_spent),
|
|
858
|
-
}));
|
|
859
|
-
}
|
|
860
|
-
async deductTeam(teamId, userId, amount, metadata, idempotencyKey) {
|
|
861
|
-
const meta = { ...(metadata ?? {}) };
|
|
862
|
-
if (idempotencyKey)
|
|
863
|
-
meta.idempotency_key = idempotencyKey;
|
|
864
|
-
const row = await this.rpc("deduct_team", {
|
|
865
|
-
p_team_id: teamId,
|
|
866
|
-
p_user_id: userId,
|
|
867
|
-
p_amount: decParam(amount),
|
|
868
|
-
p_metadata: meta,
|
|
869
|
-
});
|
|
870
|
-
const code = this.errorCode(row);
|
|
871
|
-
if (code) {
|
|
872
|
-
return {
|
|
873
|
-
transactionId: "",
|
|
874
|
-
teamId,
|
|
875
|
-
userId,
|
|
876
|
-
amount: ZERO,
|
|
877
|
-
teamBalanceAfter: dec(row.team_balance_after),
|
|
878
|
-
error: code,
|
|
879
|
-
};
|
|
880
|
-
}
|
|
881
|
-
return {
|
|
882
|
-
transactionId: String(row.transaction_id ?? ""),
|
|
883
|
-
teamId: String(row.team_id ?? teamId),
|
|
884
|
-
userId: String(row.user_id ?? userId),
|
|
885
|
-
amount: dec(row.amount, amount.negated()),
|
|
886
|
-
teamBalanceAfter: dec(row.team_balance_after),
|
|
887
|
-
};
|
|
888
|
-
}
|
|
889
|
-
// ── Credit expiry ────────────────────────────────────────────────────
|
|
890
|
-
async sweepExpiredCredits(dryRun = false, userId) {
|
|
891
|
-
// NOTE: `userId` is threaded through defensively as a new named param to
|
|
892
|
-
// `expire_credits`. Confirm the SQL migration adds a `p_user_id` parameter
|
|
893
|
-
// (with a default of NULL, meaning "global sweep") before relying on this
|
|
894
|
-
// against a real database (see 011_lazy_expiry.sql).
|
|
895
|
-
const row = await this.rpc("expire_credits", {
|
|
896
|
-
p_dry_run: dryRun,
|
|
897
|
-
p_user_id: userId ?? null,
|
|
898
|
-
});
|
|
899
|
-
const code = this.errorCode(row);
|
|
900
|
-
if (code)
|
|
901
|
-
throw new StoreError(`expire_credits: ${code}`);
|
|
902
|
-
return {
|
|
903
|
-
expiredCount: Number(row.expired_count ?? 0),
|
|
904
|
-
expiredAmount: dec(row.expired_amount),
|
|
905
|
-
dryRun,
|
|
906
|
-
expiredByTier: decRecord(row.expired_by_tier),
|
|
907
|
-
};
|
|
908
|
-
}
|
|
909
|
-
// ── Credit tiers ─────────────────────────────────────────────────────
|
|
910
|
-
// ── Transaction lookup ────────────────────────────────────────────────
|
|
911
|
-
async getTransaction(userId, transactionId) {
|
|
912
|
-
const rows = await this.restGet("credit_transactions", {
|
|
913
|
-
id: `eq.${transactionId}`,
|
|
914
|
-
user_id: `eq.${userId}`,
|
|
915
|
-
select: "*",
|
|
916
|
-
limit: "1",
|
|
917
|
-
});
|
|
918
|
-
if (!rows || rows.length === 0)
|
|
919
|
-
return null;
|
|
920
|
-
const r = rows[0];
|
|
921
|
-
return {
|
|
922
|
-
id: String(r.id ?? ""),
|
|
923
|
-
userId: String(r.user_id ?? userId),
|
|
924
|
-
amount: dec(r.amount),
|
|
925
|
-
type: String(r.type ?? ""),
|
|
926
|
-
referenceType: r.reference_type != null ? String(r.reference_type) : null,
|
|
927
|
-
referenceId: r.reference_id != null ? String(r.reference_id) : null,
|
|
928
|
-
metadata: r.metadata ?? null,
|
|
929
|
-
createdAt: String(r.created_at ?? ""),
|
|
930
|
-
};
|
|
931
|
-
}
|
|
932
|
-
async getCreditTiers(userId) {
|
|
933
|
-
// get_user_credit_tiers returns one JSONB envelope object (not a rowset):
|
|
934
|
-
// {user_id, tiers: [...], total_balance} — use rpc() (single-object), not
|
|
935
|
-
// rpcAll() (which is for genuine SETOF/TABLE-returning functions).
|
|
936
|
-
const envelope = await this.rpc("get_user_credit_tiers", { p_user_id: userId });
|
|
937
|
-
const tierRows = envelope.tiers ?? [];
|
|
938
|
-
const tiers = tierRows.map((row) => ({
|
|
939
|
-
tierKey: String(row.tier_key ?? ""),
|
|
940
|
-
name: String(row.name ?? ""),
|
|
941
|
-
priority: Number(row.priority ?? 0),
|
|
942
|
-
expires: Boolean(row.expires ?? false),
|
|
943
|
-
balance: dec(row.balance),
|
|
944
|
-
}));
|
|
945
|
-
return { userId, tiers, totalBalance: dec(envelope.total_balance) };
|
|
946
|
-
}
|
|
947
|
-
}
|
|
948
|
-
//# sourceMappingURL=supabase-store.js.map
|