@wopr-network/platform-core 1.45.0 → 1.47.0

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.
Files changed (50) hide show
  1. package/dist/billing/stripe/billing-period-summary-repository.d.ts +22 -0
  2. package/dist/billing/stripe/billing-period-summary-repository.js +14 -0
  3. package/dist/billing/stripe/index.d.ts +10 -0
  4. package/dist/billing/stripe/index.js +5 -0
  5. package/dist/billing/stripe/metered-price-map.d.ts +26 -0
  6. package/dist/billing/stripe/metered-price-map.js +75 -0
  7. package/dist/billing/stripe/stripe-payment-processor.test.js +1 -0
  8. package/dist/billing/stripe/stripe-usage-reconciliation.d.ts +31 -0
  9. package/dist/billing/stripe/stripe-usage-reconciliation.js +84 -0
  10. package/dist/billing/stripe/stripe-usage-reconciliation.test.d.ts +1 -0
  11. package/dist/billing/stripe/stripe-usage-reconciliation.test.js +109 -0
  12. package/dist/billing/stripe/tenant-store.d.ts +9 -0
  13. package/dist/billing/stripe/tenant-store.js +7 -0
  14. package/dist/billing/stripe/usage-report-repository.d.ts +39 -0
  15. package/dist/billing/stripe/usage-report-repository.js +30 -0
  16. package/dist/billing/stripe/usage-report-repository.test.d.ts +1 -0
  17. package/dist/billing/stripe/usage-report-repository.test.js +77 -0
  18. package/dist/billing/stripe/usage-report-writer.d.ts +41 -0
  19. package/dist/billing/stripe/usage-report-writer.js +95 -0
  20. package/dist/billing/stripe/usage-report-writer.test.d.ts +1 -0
  21. package/dist/billing/stripe/usage-report-writer.test.js +167 -0
  22. package/dist/gateway/credit-gate.js +5 -0
  23. package/dist/gateway/credit-gate.test.js +53 -0
  24. package/dist/gateway/types.d.ts +2 -0
  25. package/dist/monetization/stripe/stripe-payment-processor.test.js +1 -0
  26. package/dist/trpc/index.d.ts +1 -0
  27. package/dist/trpc/index.js +1 -0
  28. package/dist/trpc/org-remove-payment-method-router.d.ts +23 -0
  29. package/dist/trpc/org-remove-payment-method-router.js +61 -0
  30. package/dist/trpc/org-remove-payment-method-router.test.d.ts +1 -0
  31. package/dist/trpc/org-remove-payment-method-router.test.js +166 -0
  32. package/package.json +1 -1
  33. package/src/billing/stripe/billing-period-summary-repository.ts +32 -0
  34. package/src/billing/stripe/index.ts +17 -0
  35. package/src/billing/stripe/metered-price-map.ts +95 -0
  36. package/src/billing/stripe/stripe-payment-processor.test.ts +1 -0
  37. package/src/billing/stripe/stripe-usage-reconciliation.test.ts +127 -0
  38. package/src/billing/stripe/stripe-usage-reconciliation.ts +129 -0
  39. package/src/billing/stripe/tenant-store.ts +9 -0
  40. package/src/billing/stripe/usage-report-repository.test.ts +87 -0
  41. package/src/billing/stripe/usage-report-repository.ts +77 -0
  42. package/src/billing/stripe/usage-report-writer.test.ts +194 -0
  43. package/src/billing/stripe/usage-report-writer.ts +139 -0
  44. package/src/gateway/credit-gate.test.ts +62 -0
  45. package/src/gateway/credit-gate.ts +6 -0
  46. package/src/gateway/types.ts +2 -0
  47. package/src/monetization/stripe/stripe-payment-processor.test.ts +1 -0
  48. package/src/trpc/index.ts +4 -0
  49. package/src/trpc/org-remove-payment-method-router.test.ts +188 -0
  50. package/src/trpc/org-remove-payment-method-router.ts +80 -0
@@ -0,0 +1,95 @@
1
+ import crypto from "node:crypto";
2
+ import { logger } from "../../config/logger.js";
3
+ import { Credit } from "../../credits/credit.js";
4
+ /**
5
+ * Report metered usage to Stripe for all metered tenants in a given billing period.
6
+ *
7
+ * Uses Stripe's Billing Meters API (stripe.billing.meterEvents.create) — the v20
8
+ * replacement for the legacy subscriptionItems.createUsageRecord API.
9
+ *
10
+ * Flow:
11
+ * 1. Query billingPeriodSummaries for the period window
12
+ * 2. Filter to tenants with inferenceMode === "metered"
13
+ * 3. For each (tenant, capability, provider) tuple:
14
+ * a. Check if already reported (idempotent via stripeUsageReports unique index)
15
+ * b. Submit meter event to Stripe with idempotency identifier
16
+ * c. Insert into stripeUsageReports
17
+ */
18
+ export async function runUsageReportWriter(cfg) {
19
+ const result = {
20
+ tenantsProcessed: 0,
21
+ reportsCreated: 0,
22
+ reportsSkipped: 0,
23
+ errors: [],
24
+ };
25
+ // 1. Find all metered tenants
26
+ const meteredTenants = await cfg.tenantRepo.listMetered();
27
+ if (meteredTenants.length === 0)
28
+ return result;
29
+ const meteredTenantIds = new Set(meteredTenants.map((t) => t.tenant));
30
+ const customerIdMap = new Map(meteredTenants.map((t) => [t.tenant, t.processorCustomerId]));
31
+ // 2. Query billing period summaries for this period
32
+ const summaries = await cfg.billingPeriodSummaryRepo.listByPeriodWindow(cfg.periodStart, cfg.periodEnd);
33
+ // 3. Filter to metered tenants only
34
+ const meteredSummaries = summaries.filter((s) => meteredTenantIds.has(s.tenant));
35
+ const processedTenants = new Set();
36
+ for (const summary of meteredSummaries) {
37
+ const { tenant, capability, provider, totalCharge } = summary;
38
+ // Skip zero usage
39
+ if (totalCharge <= 0)
40
+ continue;
41
+ // Skip capabilities without a metered price config
42
+ const priceConfig = cfg.meteredPriceMap.get(capability);
43
+ if (!priceConfig)
44
+ continue;
45
+ processedTenants.add(tenant);
46
+ try {
47
+ // Check if already reported (idempotent)
48
+ const existing = await cfg.usageReportRepo.getByTenantAndPeriod(tenant, capability, provider, summary.periodStart);
49
+ if (existing) {
50
+ result.reportsSkipped++;
51
+ continue;
52
+ }
53
+ // Look up Stripe customer ID
54
+ const customerId = customerIdMap.get(tenant);
55
+ if (!customerId) {
56
+ result.errors.push({ tenant, capability, error: "No Stripe customer ID" });
57
+ continue;
58
+ }
59
+ // Convert nanodollars to cents
60
+ const valueCents = Credit.fromRaw(totalCharge).toCentsRounded();
61
+ // Build a stable idempotency identifier: tenant + capability + provider + periodStart
62
+ const identifier = `${tenant}:${capability}:${provider}:${summary.periodStart}`;
63
+ // Submit to Stripe Billing Meters API (v20+)
64
+ await cfg.stripe.billing.meterEvents.create({
65
+ event_name: priceConfig.eventName,
66
+ payload: {
67
+ stripe_customer_id: customerId,
68
+ value: String(valueCents),
69
+ },
70
+ identifier,
71
+ timestamp: Math.floor(summary.periodStart / 1000),
72
+ });
73
+ // Insert local record
74
+ await cfg.usageReportRepo.insert({
75
+ id: crypto.randomUUID(),
76
+ tenant,
77
+ capability,
78
+ provider,
79
+ periodStart: summary.periodStart,
80
+ periodEnd: summary.periodEnd,
81
+ eventName: priceConfig.eventName,
82
+ valueCents,
83
+ reportedAt: Date.now(),
84
+ });
85
+ result.reportsCreated++;
86
+ }
87
+ catch (err) {
88
+ const msg = err instanceof Error ? err.message : String(err);
89
+ logger.error("Failed to report usage to Stripe", { tenant, capability, error: msg });
90
+ result.errors.push({ tenant, capability, error: msg });
91
+ }
92
+ }
93
+ result.tenantsProcessed = processedTenants.size;
94
+ return result;
95
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,167 @@
1
+ import crypto from "node:crypto";
2
+ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
3
+ import { Credit } from "../../credits/credit.js";
4
+ import { billingPeriodSummaries } from "../../db/schema/meter-events.js";
5
+ import { tenantCustomers } from "../../db/schema/tenant-customers.js";
6
+ import { createTestDb, truncateAllTables } from "../../test/db.js";
7
+ import { DrizzleBillingPeriodSummaryRepository } from "./billing-period-summary-repository.js";
8
+ import { DrizzleTenantCustomerRepository } from "./tenant-store.js";
9
+ import { DrizzleStripeUsageReportRepository } from "./usage-report-repository.js";
10
+ import { runUsageReportWriter } from "./usage-report-writer.js";
11
+ vi.mock("../../config/logger.js", () => ({
12
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() },
13
+ }));
14
+ describe("runUsageReportWriter", () => {
15
+ let db;
16
+ let pool;
17
+ let reportRepo;
18
+ let tenantRepo;
19
+ let billingPeriodSummaryRepo;
20
+ const NOW = Date.now();
21
+ const PERIOD_START = 1700000000000;
22
+ const PERIOD_END = 1700003600000;
23
+ const mockCreateMeterEvent = vi.fn().mockResolvedValue({ identifier: "evt_xxx" });
24
+ const mockStripe = {
25
+ billing: {
26
+ meterEvents: { create: mockCreateMeterEvent },
27
+ },
28
+ };
29
+ const priceMap = new Map([["chat-completions", { eventName: "chat_completions_usage" }]]);
30
+ beforeAll(async () => {
31
+ const t = await createTestDb();
32
+ pool = t.pool;
33
+ db = t.db;
34
+ reportRepo = new DrizzleStripeUsageReportRepository(db);
35
+ tenantRepo = new DrizzleTenantCustomerRepository(db);
36
+ billingPeriodSummaryRepo = new DrizzleBillingPeriodSummaryRepository(db);
37
+ });
38
+ beforeEach(async () => {
39
+ await truncateAllTables(pool);
40
+ vi.clearAllMocks();
41
+ });
42
+ afterAll(async () => {
43
+ await pool.close();
44
+ });
45
+ async function seedMeteredTenant(tenant) {
46
+ await db.insert(tenantCustomers).values({
47
+ tenant,
48
+ processorCustomerId: `cus_${tenant}`,
49
+ processor: "stripe",
50
+ inferenceMode: "metered",
51
+ createdAt: NOW,
52
+ updatedAt: NOW,
53
+ });
54
+ }
55
+ async function seedBillingPeriod(tenant, opts) {
56
+ await db.insert(billingPeriodSummaries).values({
57
+ id: crypto.randomUUID(),
58
+ tenant,
59
+ capability: opts?.capability ?? "chat-completions",
60
+ provider: "openrouter",
61
+ eventCount: 10,
62
+ totalCost: opts?.totalCharge ?? Credit.fromCents(100).toRaw(),
63
+ totalCharge: opts?.totalCharge ?? Credit.fromCents(100).toRaw(),
64
+ totalDuration: 0,
65
+ periodStart: PERIOD_START,
66
+ periodEnd: PERIOD_END,
67
+ updatedAt: NOW,
68
+ });
69
+ }
70
+ it("reports usage for metered tenants to Stripe and inserts local record", async () => {
71
+ await seedMeteredTenant("t1");
72
+ await seedBillingPeriod("t1");
73
+ const result = await runUsageReportWriter({
74
+ stripe: mockStripe,
75
+ tenantRepo,
76
+ billingPeriodSummaryRepo,
77
+ usageReportRepo: reportRepo,
78
+ meteredPriceMap: priceMap,
79
+ periodStart: PERIOD_START,
80
+ periodEnd: PERIOD_END,
81
+ });
82
+ expect(result.reportsCreated).toBe(1);
83
+ expect(result.errors).toHaveLength(0);
84
+ expect(mockCreateMeterEvent).toHaveBeenCalledOnce();
85
+ const stored = await reportRepo.getByTenantAndPeriod("t1", "chat-completions", "openrouter", PERIOD_START);
86
+ expect(stored).toBeTruthy();
87
+ expect(stored?.valueCents).toBe(100);
88
+ });
89
+ it("skips non-metered tenants", async () => {
90
+ // Insert a managed-mode tenant
91
+ await db.insert(tenantCustomers).values({
92
+ tenant: "t2",
93
+ processorCustomerId: "cus_t2",
94
+ processor: "stripe",
95
+ inferenceMode: "managed",
96
+ createdAt: NOW,
97
+ updatedAt: NOW,
98
+ });
99
+ await seedBillingPeriod("t2");
100
+ const result = await runUsageReportWriter({
101
+ stripe: mockStripe,
102
+ tenantRepo,
103
+ billingPeriodSummaryRepo,
104
+ usageReportRepo: reportRepo,
105
+ meteredPriceMap: priceMap,
106
+ periodStart: PERIOD_START,
107
+ periodEnd: PERIOD_END,
108
+ });
109
+ expect(result.tenantsProcessed).toBe(0);
110
+ expect(mockCreateMeterEvent).not.toHaveBeenCalled();
111
+ });
112
+ it("skips already-reported periods (idempotent)", async () => {
113
+ await seedMeteredTenant("t1");
114
+ await seedBillingPeriod("t1");
115
+ // Pre-insert a report for this period
116
+ await reportRepo.insert({
117
+ id: crypto.randomUUID(),
118
+ tenant: "t1",
119
+ capability: "chat-completions",
120
+ provider: "openrouter",
121
+ periodStart: PERIOD_START,
122
+ periodEnd: PERIOD_END,
123
+ eventName: "chat_completions_usage",
124
+ valueCents: 100,
125
+ reportedAt: NOW,
126
+ });
127
+ const result = await runUsageReportWriter({
128
+ stripe: mockStripe,
129
+ tenantRepo,
130
+ billingPeriodSummaryRepo,
131
+ usageReportRepo: reportRepo,
132
+ meteredPriceMap: priceMap,
133
+ periodStart: PERIOD_START,
134
+ periodEnd: PERIOD_END,
135
+ });
136
+ expect(result.reportsSkipped).toBe(1);
137
+ expect(result.reportsCreated).toBe(0);
138
+ expect(mockCreateMeterEvent).not.toHaveBeenCalled();
139
+ });
140
+ it("skips zero-usage periods", async () => {
141
+ await seedMeteredTenant("t1");
142
+ await db.insert(billingPeriodSummaries).values({
143
+ id: crypto.randomUUID(),
144
+ tenant: "t1",
145
+ capability: "chat-completions",
146
+ provider: "openrouter",
147
+ eventCount: 0,
148
+ totalCost: 0,
149
+ totalCharge: 0,
150
+ totalDuration: 0,
151
+ periodStart: PERIOD_START,
152
+ periodEnd: PERIOD_END,
153
+ updatedAt: NOW,
154
+ });
155
+ const result = await runUsageReportWriter({
156
+ stripe: mockStripe,
157
+ tenantRepo,
158
+ billingPeriodSummaryRepo,
159
+ usageReportRepo: reportRepo,
160
+ meteredPriceMap: priceMap,
161
+ periodStart: PERIOD_START,
162
+ periodEnd: PERIOD_END,
163
+ });
164
+ expect(result.reportsCreated).toBe(0);
165
+ expect(mockCreateMeterEvent).not.toHaveBeenCalled();
166
+ });
167
+ });
@@ -26,6 +26,11 @@ export async function creditBalanceCheck(c, deps, estimatedCostCents = 0) {
26
26
  if (tenant.type === "platform_service") {
27
27
  return null;
28
28
  }
29
+ // Metered tenants are invoiced via Stripe subscription, not prepaid credits.
30
+ // Skip balance enforcement but still allow debit (for P&L tracking).
31
+ if (tenant.inferenceMode === "metered") {
32
+ return null;
33
+ }
29
34
  const balance = await deps.creditLedger.balance(tenant.id);
30
35
  const required = Math.max(0, estimatedCostCents);
31
36
  const graceBuffer = deps.graceBufferCents ?? 50; // default -$0.50
@@ -165,3 +165,56 @@ describe("debitCredits with allowNegative and onBalanceExhausted", () => {
165
165
  expect(onBalanceExhausted).not.toHaveBeenCalled();
166
166
  });
167
167
  });
168
+ // ---------------------------------------------------------------------------
169
+ // creditBalanceCheck — metered tenant bypass
170
+ // ---------------------------------------------------------------------------
171
+ async function buildHonoContextWithMode(tenantId, inferenceMode) {
172
+ let capturedCtx;
173
+ const app = new Hono();
174
+ app.get("/test", (c) => {
175
+ c.set("gatewayTenant", {
176
+ id: tenantId,
177
+ spendLimits: { maxSpendPerHour: null, maxSpendPerMonth: null },
178
+ inferenceMode,
179
+ });
180
+ capturedCtx = c;
181
+ return c.json({});
182
+ });
183
+ await app.request("/test");
184
+ return capturedCtx;
185
+ }
186
+ describe("creditBalanceCheck metered tenant bypass", () => {
187
+ beforeEach(async () => {
188
+ await truncateAllTables(pool);
189
+ await new DrizzleLedger(db).seedSystemAccounts();
190
+ });
191
+ it("skips balance check for metered tenants even with zero balance", async () => {
192
+ const ledger = new DrizzleLedger(db);
193
+ // No credits — would normally fail with credits_exhausted
194
+ const c = await buildHonoContextWithMode("metered-t1", "metered");
195
+ const deps = { creditLedger: ledger, topUpUrl: "/billing" };
196
+ const error = await creditBalanceCheck(c, deps, 0);
197
+ expect(error).toBeNull();
198
+ });
199
+ it("still debits metered tenants for P&L tracking", async () => {
200
+ const ledger = new DrizzleLedger(db);
201
+ await ledger.credit("metered-t1", Credit.fromCents(0), "purchase", { description: "setup" }).catch(() => { });
202
+ const mockLedger = {
203
+ debit: vi.fn().mockResolvedValue(undefined),
204
+ balance: vi.fn(),
205
+ credit: vi.fn(),
206
+ };
207
+ const deps = { creditLedger: mockLedger, topUpUrl: "/billing" };
208
+ await debitCredits(deps, "metered-tenant", 0.05, 1.5, "chat-completions", "openrouter");
209
+ expect(mockLedger.debit).toHaveBeenCalled();
210
+ });
211
+ it("non-metered (managed) tenant still gets balance checked", async () => {
212
+ const ledger = new DrizzleLedger(db);
213
+ // No credits seeded — should fail
214
+ const c = await buildHonoContextWithMode("managed-t1", "managed");
215
+ const deps = { creditLedger: ledger, topUpUrl: "/billing" };
216
+ const error = await creditBalanceCheck(c, deps, 0);
217
+ // Balance is 0, within grace buffer — passes
218
+ expect(error).toBeNull();
219
+ });
220
+ });
@@ -44,6 +44,8 @@ export interface GatewayTenant {
44
44
  instanceId?: string;
45
45
  /** User-configured spending caps (null fields = no cap). */
46
46
  spendingCaps?: SpendingCaps;
47
+ /** Billing mode — "metered" tenants are invoiced via Stripe, not prepaid credits. */
48
+ inferenceMode?: "metered" | "managed" | "byok";
47
49
  }
48
50
  /** Fetch function type for dependency injection in tests. */
49
51
  export type FetchFn = (url: string, init?: RequestInit) => Promise<Response>;
@@ -43,6 +43,7 @@ function createMocks() {
43
43
  setInferenceMode: vi.fn(),
44
44
  list: vi.fn(),
45
45
  buildCustomerIdMap: vi.fn(),
46
+ listMetered: vi.fn(),
46
47
  };
47
48
  const creditLedger = {
48
49
  post: vi.fn(),
@@ -2,3 +2,4 @@ export { createAdminFleetUpdateRouter } from "./admin-fleet-update-router.js";
2
2
  export { createFleetUpdateConfigRouter } from "./fleet-update-config-router.js";
3
3
  export { adminProcedure, createCallerFactory, orgAdminProcedure, orgMemberProcedure, protectedProcedure, publicProcedure, router, setTrpcOrgMemberRepo, type TRPCContext, tenantProcedure, } from "./init.js";
4
4
  export { createNotificationTemplateRouter } from "./notification-template-router.js";
5
+ export { createOrgRemovePaymentMethodRouter, type OrgRemovePaymentMethodDeps, } from "./org-remove-payment-method-router.js";
@@ -2,3 +2,4 @@ export { createAdminFleetUpdateRouter } from "./admin-fleet-update-router.js";
2
2
  export { createFleetUpdateConfigRouter } from "./fleet-update-config-router.js";
3
3
  export { adminProcedure, createCallerFactory, orgAdminProcedure, orgMemberProcedure, protectedProcedure, publicProcedure, router, setTrpcOrgMemberRepo, tenantProcedure, } from "./init.js";
4
4
  export { createNotificationTemplateRouter } from "./notification-template-router.js";
5
+ export { createOrgRemovePaymentMethodRouter, } from "./org-remove-payment-method-router.js";
@@ -0,0 +1,23 @@
1
+ import type { IPaymentProcessor } from "../billing/payment-processor.js";
2
+ import type { IAutoTopupSettingsRepository } from "../credits/auto-topup-settings-repository.js";
3
+ export interface OrgRemovePaymentMethodDeps {
4
+ processor: IPaymentProcessor;
5
+ autoTopupSettingsStore?: IAutoTopupSettingsRepository;
6
+ }
7
+ export declare function createOrgRemovePaymentMethodRouter(getDeps: () => OrgRemovePaymentMethodDeps): import("@trpc/server").TRPCBuiltRouter<{
8
+ ctx: import("./init.js").TRPCContext;
9
+ meta: object;
10
+ errorShape: import("@trpc/server").TRPCDefaultErrorShape;
11
+ transformer: false;
12
+ }, import("@trpc/server").TRPCDecorateCreateRouterOptions<{
13
+ orgRemovePaymentMethod: import("@trpc/server").TRPCMutationProcedure<{
14
+ input: {
15
+ orgId: string;
16
+ paymentMethodId: string;
17
+ };
18
+ output: {
19
+ removed: boolean;
20
+ };
21
+ meta: object;
22
+ }>;
23
+ }>>;
@@ -0,0 +1,61 @@
1
+ import { TRPCError } from "@trpc/server";
2
+ import { z } from "zod";
3
+ import { PaymentMethodOwnershipError } from "../billing/payment-processor.js";
4
+ import { orgAdminProcedure, router } from "./init.js";
5
+ export function createOrgRemovePaymentMethodRouter(getDeps) {
6
+ return router({
7
+ orgRemovePaymentMethod: orgAdminProcedure
8
+ .input(z.object({
9
+ orgId: z.string().min(1),
10
+ paymentMethodId: z.string().min(1),
11
+ }))
12
+ .mutation(async ({ input }) => {
13
+ const { processor, autoTopupSettingsStore } = getDeps();
14
+ if (!autoTopupSettingsStore) {
15
+ console.warn("orgRemovePaymentMethod: autoTopupSettingsStore not provided — last-payment-method guard is inactive");
16
+ }
17
+ // Guard: prevent removing the last payment method when auto-topup is enabled
18
+ if (autoTopupSettingsStore) {
19
+ const methods = await processor.listPaymentMethods(input.orgId);
20
+ if (methods.length <= 1) {
21
+ const settings = await autoTopupSettingsStore.getByTenant(input.orgId);
22
+ if (settings && (settings.usageEnabled || settings.scheduleEnabled)) {
23
+ throw new TRPCError({
24
+ code: "FORBIDDEN",
25
+ message: "Cannot remove last payment method while auto-topup is enabled. Disable auto-topup first.",
26
+ });
27
+ }
28
+ }
29
+ }
30
+ try {
31
+ await processor.detachPaymentMethod(input.orgId, input.paymentMethodId);
32
+ }
33
+ catch (err) {
34
+ if (err instanceof PaymentMethodOwnershipError) {
35
+ throw new TRPCError({
36
+ code: "FORBIDDEN",
37
+ message: "Payment method does not belong to this organization",
38
+ });
39
+ }
40
+ throw new TRPCError({
41
+ code: "INTERNAL_SERVER_ERROR",
42
+ message: "Failed to remove payment method. Please try again.",
43
+ });
44
+ }
45
+ // TOCTOU guard: re-check count after detach. A concurrent request
46
+ // may have already removed another payment method between our pre-check
47
+ // and this detach, leaving the org with 0 methods while auto-topup is
48
+ // still enabled. Warn operators — the method is already gone.
49
+ if (autoTopupSettingsStore) {
50
+ const remaining = await processor.listPaymentMethods(input.orgId);
51
+ if (remaining.length === 0) {
52
+ const settings = await autoTopupSettingsStore.getByTenant(input.orgId);
53
+ if (settings && (settings.usageEnabled || settings.scheduleEnabled)) {
54
+ console.warn("orgRemovePaymentMethod: TOCTOU — org %s now has 0 payment methods with auto-topup enabled. Operator must add a payment method or disable auto-topup.", input.orgId);
55
+ }
56
+ }
57
+ }
58
+ return { removed: true };
59
+ }),
60
+ });
61
+ }
@@ -0,0 +1,166 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { createCallerFactory, router, setTrpcOrgMemberRepo } from "./init.js";
3
+ import { createOrgRemovePaymentMethodRouter } from "./org-remove-payment-method-router.js";
4
+ // ---------------------------------------------------------------------------
5
+ // Mock helpers
6
+ // ---------------------------------------------------------------------------
7
+ function makeMockOrgMemberRepo(overrides) {
8
+ return {
9
+ listMembers: vi.fn().mockResolvedValue([]),
10
+ addMember: vi.fn().mockResolvedValue(undefined),
11
+ updateMemberRole: vi.fn().mockResolvedValue(undefined),
12
+ removeMember: vi.fn().mockResolvedValue(undefined),
13
+ findMember: vi.fn().mockResolvedValue({ userId: "u1", role: "owner" }),
14
+ countAdminsAndOwners: vi.fn().mockResolvedValue(1),
15
+ listInvites: vi.fn().mockResolvedValue([]),
16
+ createInvite: vi.fn().mockResolvedValue(undefined),
17
+ findInviteById: vi.fn().mockResolvedValue(null),
18
+ findInviteByToken: vi.fn().mockResolvedValue(null),
19
+ deleteInvite: vi.fn().mockResolvedValue(undefined),
20
+ deleteAllMembers: vi.fn().mockResolvedValue(undefined),
21
+ deleteAllInvites: vi.fn().mockResolvedValue(undefined),
22
+ listOrgsByUser: vi.fn().mockResolvedValue([]),
23
+ markInviteAccepted: vi.fn().mockResolvedValue(undefined),
24
+ ...overrides,
25
+ };
26
+ }
27
+ function makeMockProcessor(methods) {
28
+ return {
29
+ name: "mock",
30
+ createCheckoutSession: vi.fn(),
31
+ handleWebhook: vi.fn(),
32
+ supportsPortal: vi.fn().mockReturnValue(false),
33
+ createPortalSession: vi.fn(),
34
+ setupPaymentMethod: vi.fn(),
35
+ listPaymentMethods: vi.fn().mockResolvedValue(methods),
36
+ charge: vi.fn(),
37
+ detachPaymentMethod: vi.fn().mockResolvedValue(undefined),
38
+ getCustomerEmail: vi.fn().mockResolvedValue(""),
39
+ updateCustomerEmail: vi.fn(),
40
+ listInvoices: vi.fn().mockResolvedValue([]),
41
+ };
42
+ }
43
+ function makeMockAutoTopupSettings(overrides) {
44
+ const settings = overrides
45
+ ? {
46
+ tenantId: "org-1",
47
+ usageEnabled: false,
48
+ usageThreshold: { toCentsRounded: () => 0 },
49
+ usageTopup: { toCentsRounded: () => 0 },
50
+ usageConsecutiveFailures: 0,
51
+ usageChargeInFlight: false,
52
+ scheduleEnabled: false,
53
+ scheduleAmount: { toCentsRounded: () => 0 },
54
+ scheduleIntervalHours: 0,
55
+ scheduleNextAt: null,
56
+ scheduleConsecutiveFailures: 0,
57
+ createdAt: new Date().toISOString(),
58
+ updatedAt: new Date().toISOString(),
59
+ ...overrides,
60
+ }
61
+ : null;
62
+ return {
63
+ getByTenant: vi.fn().mockResolvedValue(settings),
64
+ upsert: vi.fn(),
65
+ setUsageChargeInFlight: vi.fn(),
66
+ tryAcquireUsageInFlight: vi.fn(),
67
+ incrementUsageFailures: vi.fn(),
68
+ resetUsageFailures: vi.fn(),
69
+ disableUsage: vi.fn(),
70
+ incrementScheduleFailures: vi.fn(),
71
+ resetScheduleFailures: vi.fn(),
72
+ disableSchedule: vi.fn(),
73
+ advanceScheduleNextAt: vi.fn(),
74
+ listDueScheduled: vi.fn().mockResolvedValue([]),
75
+ getMaxConsecutiveFailures: vi.fn().mockResolvedValue(0),
76
+ };
77
+ }
78
+ function authedContext() {
79
+ return { user: { id: "u1", roles: ["user"] }, tenantId: "org-1" };
80
+ }
81
+ function unauthedContext() {
82
+ return { user: undefined, tenantId: undefined };
83
+ }
84
+ // ---------------------------------------------------------------------------
85
+ // Tests
86
+ // ---------------------------------------------------------------------------
87
+ describe("orgRemovePaymentMethod router", () => {
88
+ let processor;
89
+ let autoTopupStore;
90
+ beforeEach(() => {
91
+ processor = makeMockProcessor([{ id: "pm_1", label: "Visa ending 4242", isDefault: true }]);
92
+ autoTopupStore = makeMockAutoTopupSettings();
93
+ setTrpcOrgMemberRepo(makeMockOrgMemberRepo());
94
+ });
95
+ function buildCaller(deps) {
96
+ const subRouter = createOrgRemovePaymentMethodRouter(() => ({
97
+ processor: deps.processor,
98
+ autoTopupSettingsStore: deps.autoTopupSettingsStore,
99
+ }));
100
+ const appRouter = router({ org: subRouter });
101
+ return createCallerFactory(appRouter);
102
+ }
103
+ it("successfully removes a payment method", async () => {
104
+ const caller = buildCaller({ processor, autoTopupSettingsStore: autoTopupStore })(authedContext());
105
+ const result = await caller.org.orgRemovePaymentMethod({
106
+ orgId: "org-1",
107
+ paymentMethodId: "pm_1",
108
+ });
109
+ expect(result).toEqual({ removed: true });
110
+ expect(processor.detachPaymentMethod).toHaveBeenCalledWith("org-1", "pm_1");
111
+ });
112
+ it("rejects unauthenticated users", async () => {
113
+ const caller = buildCaller({ processor, autoTopupSettingsStore: autoTopupStore })(unauthedContext());
114
+ await expect(caller.org.orgRemovePaymentMethod({ orgId: "org-1", paymentMethodId: "pm_1" })).rejects.toMatchObject({
115
+ code: "UNAUTHORIZED",
116
+ });
117
+ });
118
+ it("rejects when removing last PM with auto-topup usage enabled", async () => {
119
+ const usageStore = makeMockAutoTopupSettings({ usageEnabled: true });
120
+ const caller = buildCaller({
121
+ processor,
122
+ autoTopupSettingsStore: usageStore,
123
+ })(authedContext());
124
+ await expect(caller.org.orgRemovePaymentMethod({ orgId: "org-1", paymentMethodId: "pm_1" })).rejects.toMatchObject({
125
+ code: "FORBIDDEN",
126
+ });
127
+ });
128
+ it("rejects when removing last PM with auto-topup schedule enabled", async () => {
129
+ const scheduleStore = makeMockAutoTopupSettings({ scheduleEnabled: true });
130
+ const caller = buildCaller({
131
+ processor,
132
+ autoTopupSettingsStore: scheduleStore,
133
+ })(authedContext());
134
+ await expect(caller.org.orgRemovePaymentMethod({ orgId: "org-1", paymentMethodId: "pm_1" })).rejects.toMatchObject({
135
+ code: "FORBIDDEN",
136
+ });
137
+ });
138
+ it("allows removing non-last PM even with auto-topup enabled", async () => {
139
+ const multiProcessor = makeMockProcessor([
140
+ { id: "pm_1", label: "Visa ending 4242", isDefault: true },
141
+ { id: "pm_2", label: "Mastercard ending 5555", isDefault: false },
142
+ ]);
143
+ const usageStore = makeMockAutoTopupSettings({ usageEnabled: true });
144
+ const caller = buildCaller({
145
+ processor: multiProcessor,
146
+ autoTopupSettingsStore: usageStore,
147
+ })(authedContext());
148
+ const result = await caller.org.orgRemovePaymentMethod({
149
+ orgId: "org-1",
150
+ paymentMethodId: "pm_1",
151
+ });
152
+ expect(result).toEqual({ removed: true });
153
+ });
154
+ it("returns FORBIDDEN when detachPaymentMethod throws PaymentMethodOwnershipError", async () => {
155
+ const { PaymentMethodOwnershipError } = await import("../billing/payment-processor.js");
156
+ const ownershipErrorProcessor = makeMockProcessor([]);
157
+ ownershipErrorProcessor.detachPaymentMethod.mockRejectedValue(new PaymentMethodOwnershipError());
158
+ const caller = buildCaller({
159
+ processor: ownershipErrorProcessor,
160
+ autoTopupSettingsStore: autoTopupStore,
161
+ })(authedContext());
162
+ await expect(caller.org.orgRemovePaymentMethod({ orgId: "org-1", paymentMethodId: "pm_1" })).rejects.toMatchObject({
163
+ code: "FORBIDDEN",
164
+ });
165
+ });
166
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wopr-network/platform-core",
3
- "version": "1.45.0",
3
+ "version": "1.47.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -0,0 +1,32 @@
1
+ import { and, gte, lte } from "drizzle-orm";
2
+ import type { PlatformDb } from "../../db/index.js";
3
+ import { billingPeriodSummaries } from "../../db/schema/meter-events.js";
4
+
5
+ export interface BillingPeriodSummaryRow {
6
+ id: string;
7
+ tenant: string;
8
+ capability: string;
9
+ provider: string;
10
+ eventCount: number;
11
+ totalCost: number;
12
+ totalCharge: number;
13
+ totalDuration: number;
14
+ periodStart: number;
15
+ periodEnd: number;
16
+ updatedAt: number;
17
+ }
18
+
19
+ export interface IBillingPeriodSummaryRepository {
20
+ listByPeriodWindow(start: number, end: number): Promise<BillingPeriodSummaryRow[]>;
21
+ }
22
+
23
+ export class DrizzleBillingPeriodSummaryRepository implements IBillingPeriodSummaryRepository {
24
+ constructor(private readonly db: PlatformDb) {}
25
+
26
+ async listByPeriodWindow(start: number, end: number): Promise<BillingPeriodSummaryRow[]> {
27
+ return this.db
28
+ .select()
29
+ .from(billingPeriodSummaries)
30
+ .where(and(gte(billingPeriodSummaries.periodStart, start), lte(billingPeriodSummaries.periodEnd, end)));
31
+ }
32
+ }