@wopr-network/platform-core 1.47.0 → 1.48.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.
@@ -105,6 +105,8 @@ export interface IPaymentProcessor {
105
105
  charge(opts: ChargeOpts): Promise<ChargeResult>;
106
106
  /** Detach a payment method from the tenant's account. */
107
107
  detachPaymentMethod(tenant: string, paymentMethodId: string): Promise<void>;
108
+ /** Set a payment method as the tenant's default for future invoices. */
109
+ setDefaultPaymentMethod(tenant: string, paymentMethodId: string): Promise<void>;
108
110
  /** Get the billing email for a tenant's customer account. Returns "" if no customer exists. */
109
111
  getCustomerEmail(tenantId: string): Promise<string>;
110
112
  /** Update the billing email for a tenant's customer account. */
@@ -45,6 +45,7 @@ describe("IPaymentProcessor types", () => {
45
45
  setupPaymentMethod: async () => ({ clientSecret: "cs" }),
46
46
  listPaymentMethods: async () => [],
47
47
  detachPaymentMethod: async () => undefined,
48
+ setDefaultPaymentMethod: async () => undefined,
48
49
  charge: async () => ({ success: true }),
49
50
  getCustomerEmail: async () => "",
50
51
  updateCustomerEmail: async () => undefined,
@@ -41,6 +41,7 @@ export declare class StripePaymentProcessor implements IPaymentProcessor {
41
41
  }>;
42
42
  setupPaymentMethod(tenant: string): Promise<SetupResult>;
43
43
  listPaymentMethods(tenant: string): Promise<SavedPaymentMethod[]>;
44
+ setDefaultPaymentMethod(tenant: string, paymentMethodId: string): Promise<void>;
44
45
  detachPaymentMethod(tenant: string, paymentMethodId: string): Promise<void>;
45
46
  getCustomerEmail(tenantId: string): Promise<string>;
46
47
  updateCustomerEmail(tenantId: string, email: string): Promise<void>;
@@ -86,20 +86,43 @@ export class StripePaymentProcessor {
86
86
  if (!mapping) {
87
87
  return [];
88
88
  }
89
- const methods = await this.stripe.customers.listPaymentMethods(mapping.processor_customer_id);
90
- return methods.data.map((pm, index) => ({
89
+ const [methods, customer] = await Promise.all([
90
+ this.stripe.customers.listPaymentMethods(mapping.processor_customer_id),
91
+ this.stripe.customers.retrieve(mapping.processor_customer_id),
92
+ ]);
93
+ const defaultPmId = !customer.deleted && customer.invoice_settings?.default_payment_method
94
+ ? typeof customer.invoice_settings.default_payment_method === "string"
95
+ ? customer.invoice_settings.default_payment_method
96
+ : customer.invoice_settings.default_payment_method.id
97
+ : null;
98
+ return methods.data.map((pm) => ({
91
99
  id: pm.id,
92
100
  label: formatPaymentMethodLabel(pm),
93
- isDefault: index === 0,
101
+ isDefault: defaultPmId ? pm.id === defaultPmId : false,
94
102
  }));
95
103
  }
104
+ async setDefaultPaymentMethod(tenant, paymentMethodId) {
105
+ const mapping = await this.tenantRepo.getByTenant(tenant);
106
+ if (!mapping) {
107
+ throw new Error(`No Stripe customer found for tenant: ${tenant}`);
108
+ }
109
+ const pm = await this.stripe.paymentMethods.retrieve(paymentMethodId);
110
+ const pmCustomerId = typeof pm.customer === "string" ? pm.customer : (pm.customer?.id ?? null);
111
+ if (!pmCustomerId || pmCustomerId !== mapping.processor_customer_id) {
112
+ throw new PaymentMethodOwnershipError();
113
+ }
114
+ await this.stripe.customers.update(mapping.processor_customer_id, {
115
+ invoice_settings: { default_payment_method: paymentMethodId },
116
+ });
117
+ }
96
118
  async detachPaymentMethod(tenant, paymentMethodId) {
97
119
  const mapping = await this.tenantRepo.getByTenant(tenant);
98
120
  if (!mapping) {
99
121
  throw new Error(`No Stripe customer found for tenant: ${tenant}`);
100
122
  }
101
123
  const pm = await this.stripe.paymentMethods.retrieve(paymentMethodId);
102
- if (!pm.customer || pm.customer !== mapping.processor_customer_id) {
124
+ const pmCustomerId = typeof pm.customer === "string" ? pm.customer : (pm.customer?.id ?? null);
125
+ if (!pmCustomerId || pmCustomerId !== mapping.processor_customer_id) {
103
126
  throw new PaymentMethodOwnershipError();
104
127
  }
105
128
  await this.stripe.paymentMethods.detach(paymentMethodId);
@@ -96,7 +96,7 @@ describe("StripePaymentProcessor", () => {
96
96
  const result = await processor.listPaymentMethods("tenant-1");
97
97
  expect(result).toEqual([]);
98
98
  });
99
- it("returns formatted payment methods with card label", async () => {
99
+ it("returns formatted payment methods with card label and reads actual Stripe default", async () => {
100
100
  vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
101
101
  vi.mocked(mocks.stripe.customers.listPaymentMethods).mockResolvedValue({
102
102
  data: [
@@ -104,17 +104,55 @@ describe("StripePaymentProcessor", () => {
104
104
  { id: "pm_2", card: { brand: "mastercard", last4: "5555" } },
105
105
  ],
106
106
  });
107
+ vi.mocked(mocks.stripe.customers.retrieve).mockResolvedValue({
108
+ deleted: false,
109
+ invoice_settings: { default_payment_method: "pm_1" },
110
+ });
107
111
  const result = await processor.listPaymentMethods("tenant-1");
108
112
  expect(result).toEqual([
109
113
  { id: "pm_1", label: "Visa ending 4242", isDefault: true },
110
114
  { id: "pm_2", label: "Mastercard ending 5555", isDefault: false },
111
115
  ]);
112
116
  });
117
+ it("marks second PM as default when Stripe says so", async () => {
118
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
119
+ vi.mocked(mocks.stripe.customers.listPaymentMethods).mockResolvedValue({
120
+ data: [
121
+ { id: "pm_1", card: { brand: "visa", last4: "4242" } },
122
+ { id: "pm_2", card: { brand: "mastercard", last4: "5555" } },
123
+ ],
124
+ });
125
+ vi.mocked(mocks.stripe.customers.retrieve).mockResolvedValue({
126
+ deleted: false,
127
+ invoice_settings: { default_payment_method: "pm_2" },
128
+ });
129
+ const result = await processor.listPaymentMethods("tenant-1");
130
+ expect(result).toEqual([
131
+ { id: "pm_1", label: "Visa ending 4242", isDefault: false },
132
+ { id: "pm_2", label: "Mastercard ending 5555", isDefault: true },
133
+ ]);
134
+ });
135
+ it("marks no PM as default when customer has no default set", async () => {
136
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
137
+ vi.mocked(mocks.stripe.customers.listPaymentMethods).mockResolvedValue({
138
+ data: [{ id: "pm_1", card: { brand: "visa", last4: "4242" } }],
139
+ });
140
+ vi.mocked(mocks.stripe.customers.retrieve).mockResolvedValue({
141
+ deleted: false,
142
+ invoice_settings: { default_payment_method: null },
143
+ });
144
+ const result = await processor.listPaymentMethods("tenant-1");
145
+ expect(result).toEqual([{ id: "pm_1", label: "Visa ending 4242", isDefault: false }]);
146
+ });
113
147
  it("uses generic label for non-card payment methods", async () => {
114
148
  vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
115
149
  vi.mocked(mocks.stripe.customers.listPaymentMethods).mockResolvedValue({
116
150
  data: [{ id: "pm_bank", card: undefined }],
117
151
  });
152
+ vi.mocked(mocks.stripe.customers.retrieve).mockResolvedValue({
153
+ deleted: false,
154
+ invoice_settings: { default_payment_method: "pm_bank" },
155
+ });
118
156
  const result = await processor.listPaymentMethods("tenant-1");
119
157
  expect(result).toEqual([{ id: "pm_bank", label: "Payment method pm_bank", isDefault: true }]);
120
158
  });
@@ -152,6 +190,62 @@ describe("StripePaymentProcessor", () => {
152
190
  expect(mocks.stripe.paymentMethods.detach).toHaveBeenCalledWith("pm_1");
153
191
  });
154
192
  });
193
+ // --- setDefaultPaymentMethod ---
194
+ describe("setDefaultPaymentMethod", () => {
195
+ it("throws when tenant has no Stripe customer", async () => {
196
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(null);
197
+ await expect(processor.setDefaultPaymentMethod("tenant-1", "pm_1")).rejects.toThrow("No Stripe customer found for tenant: tenant-1");
198
+ });
199
+ it("throws PaymentMethodOwnershipError when PM belongs to different customer", async () => {
200
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
201
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
202
+ id: "pm_1",
203
+ customer: "cus_OTHER",
204
+ });
205
+ await expect(processor.setDefaultPaymentMethod("tenant-1", "pm_1")).rejects.toThrow(PaymentMethodOwnershipError);
206
+ });
207
+ it("throws PaymentMethodOwnershipError when PM has no customer", async () => {
208
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
209
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
210
+ id: "pm_1",
211
+ customer: null,
212
+ });
213
+ await expect(processor.setDefaultPaymentMethod("tenant-1", "pm_1")).rejects.toThrow(PaymentMethodOwnershipError);
214
+ });
215
+ it("calls stripe.customers.update with invoice_settings when ownership matches", async () => {
216
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
217
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
218
+ id: "pm_1",
219
+ customer: "cus_123",
220
+ });
221
+ vi.mocked(mocks.stripe.customers.update).mockResolvedValue({});
222
+ await processor.setDefaultPaymentMethod("tenant-1", "pm_1");
223
+ expect(mocks.stripe.customers.update).toHaveBeenCalledWith("cus_123", {
224
+ invoice_settings: { default_payment_method: "pm_1" },
225
+ });
226
+ });
227
+ it("succeeds when PM customer is an expanded Customer object", async () => {
228
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
229
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
230
+ id: "pm_1",
231
+ customer: { id: "cus_123", object: "customer" },
232
+ });
233
+ vi.mocked(mocks.stripe.customers.update).mockResolvedValue({});
234
+ await processor.setDefaultPaymentMethod("tenant-1", "pm_1");
235
+ expect(mocks.stripe.customers.update).toHaveBeenCalledWith("cus_123", {
236
+ invoice_settings: { default_payment_method: "pm_1" },
237
+ });
238
+ });
239
+ it("propagates Stripe API errors", async () => {
240
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
241
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
242
+ id: "pm_1",
243
+ customer: "cus_123",
244
+ });
245
+ vi.mocked(mocks.stripe.customers.update).mockRejectedValue(new Error("Stripe API error"));
246
+ await expect(processor.setDefaultPaymentMethod("tenant-1", "pm_1")).rejects.toThrow("Stripe API error");
247
+ });
248
+ });
155
249
  // --- getCustomerEmail ---
156
250
  describe("getCustomerEmail", () => {
157
251
  it("returns empty string when tenant has no Stripe customer", async () => {
@@ -33,6 +33,7 @@ export declare class StripePaymentProcessor implements IPaymentProcessor {
33
33
  }>;
34
34
  setupPaymentMethod(tenant: string): Promise<SetupResult>;
35
35
  listPaymentMethods(tenant: string): Promise<SavedPaymentMethod[]>;
36
+ setDefaultPaymentMethod(tenant: string, paymentMethodId: string): Promise<void>;
36
37
  detachPaymentMethod(tenant: string, paymentMethodId: string): Promise<void>;
37
38
  getCustomerEmail(tenantId: string): Promise<string>;
38
39
  updateCustomerEmail(tenantId: string, email: string): Promise<void>;
@@ -89,13 +89,35 @@ export class StripePaymentProcessor {
89
89
  if (!mapping) {
90
90
  return [];
91
91
  }
92
- const methods = await this.stripe.customers.listPaymentMethods(mapping.processor_customer_id);
93
- return methods.data.map((pm, index) => ({
92
+ const [methods, customer] = await Promise.all([
93
+ this.stripe.customers.listPaymentMethods(mapping.processor_customer_id),
94
+ this.stripe.customers.retrieve(mapping.processor_customer_id),
95
+ ]);
96
+ const defaultPmId = !customer.deleted && customer.invoice_settings?.default_payment_method
97
+ ? typeof customer.invoice_settings.default_payment_method === "string"
98
+ ? customer.invoice_settings.default_payment_method
99
+ : customer.invoice_settings.default_payment_method.id
100
+ : null;
101
+ return methods.data.map((pm) => ({
94
102
  id: pm.id,
95
103
  label: formatPaymentMethodLabel(pm),
96
- isDefault: index === 0,
104
+ isDefault: defaultPmId ? pm.id === defaultPmId : false,
97
105
  }));
98
106
  }
107
+ async setDefaultPaymentMethod(tenant, paymentMethodId) {
108
+ const mapping = await this.tenantRepo.getByTenant(tenant);
109
+ if (!mapping) {
110
+ throw new Error(`No Stripe customer found for tenant: ${tenant}`);
111
+ }
112
+ const pm = await this.stripe.paymentMethods.retrieve(paymentMethodId);
113
+ const pmCustomerId = typeof pm.customer === "string" ? pm.customer : (pm.customer?.id ?? null);
114
+ if (!pmCustomerId || pmCustomerId !== mapping.processor_customer_id) {
115
+ throw new PaymentMethodOwnershipError();
116
+ }
117
+ await this.stripe.customers.update(mapping.processor_customer_id, {
118
+ invoice_settings: { default_payment_method: paymentMethodId },
119
+ });
120
+ }
99
121
  async detachPaymentMethod(tenant, paymentMethodId) {
100
122
  const mapping = await this.tenantRepo.getByTenant(tenant);
101
123
  if (!mapping) {
@@ -102,7 +102,7 @@ describe("StripePaymentProcessor", () => {
102
102
  const result = await processor.listPaymentMethods("tenant-1");
103
103
  expect(result).toEqual([]);
104
104
  });
105
- it("returns formatted payment methods with card label", async () => {
105
+ it("returns formatted payment methods with card label and reads actual Stripe default", async () => {
106
106
  vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
107
107
  vi.mocked(mocks.stripe.customers.listPaymentMethods).mockResolvedValue({
108
108
  data: [
@@ -110,6 +110,10 @@ describe("StripePaymentProcessor", () => {
110
110
  { id: "pm_2", card: { brand: "mastercard", last4: "5555" } },
111
111
  ],
112
112
  });
113
+ vi.mocked(mocks.stripe.customers.retrieve).mockResolvedValue({
114
+ deleted: false,
115
+ invoice_settings: { default_payment_method: "pm_1" },
116
+ });
113
117
  const result = await processor.listPaymentMethods("tenant-1");
114
118
  expect(result).toEqual([
115
119
  { id: "pm_1", label: "Visa ending 4242", isDefault: true },
@@ -121,6 +125,10 @@ describe("StripePaymentProcessor", () => {
121
125
  vi.mocked(mocks.stripe.customers.listPaymentMethods).mockResolvedValue({
122
126
  data: [{ id: "pm_bank", card: undefined }],
123
127
  });
128
+ vi.mocked(mocks.stripe.customers.retrieve).mockResolvedValue({
129
+ deleted: false,
130
+ invoice_settings: { default_payment_method: "pm_bank" },
131
+ });
124
132
  const result = await processor.listPaymentMethods("tenant-1");
125
133
  expect(result).toEqual([{ id: "pm_bank", label: "Payment method pm_bank", isDefault: true }]);
126
134
  });
@@ -158,6 +166,70 @@ describe("StripePaymentProcessor", () => {
158
166
  expect(mocks.stripe.paymentMethods.detach).toHaveBeenCalledWith("pm_1");
159
167
  });
160
168
  });
169
+ // --- setDefaultPaymentMethod ---
170
+ describe("setDefaultPaymentMethod", () => {
171
+ it("throws when tenant has no Stripe customer", async () => {
172
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(null);
173
+ await expect(processor.setDefaultPaymentMethod("tenant-1", "pm_1")).rejects.toThrow("No Stripe customer found for tenant: tenant-1");
174
+ });
175
+ it("throws PaymentMethodOwnershipError when PM has no customer", async () => {
176
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
177
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
178
+ id: "pm_1",
179
+ customer: null,
180
+ });
181
+ await expect(processor.setDefaultPaymentMethod("tenant-1", "pm_1")).rejects.toThrow(PaymentMethodOwnershipError);
182
+ });
183
+ it("throws PaymentMethodOwnershipError when PM belongs to different customer", async () => {
184
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
185
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
186
+ id: "pm_1",
187
+ customer: "cus_OTHER",
188
+ });
189
+ await expect(processor.setDefaultPaymentMethod("tenant-1", "pm_1")).rejects.toThrow(PaymentMethodOwnershipError);
190
+ });
191
+ it("throws PaymentMethodOwnershipError when PM customer is an expanded object with different id", async () => {
192
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
193
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
194
+ id: "pm_1",
195
+ customer: { id: "cus_OTHER", object: "customer" },
196
+ });
197
+ await expect(processor.setDefaultPaymentMethod("tenant-1", "pm_1")).rejects.toThrow(PaymentMethodOwnershipError);
198
+ });
199
+ it("sets default when ownership matches (string customer)", async () => {
200
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
201
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
202
+ id: "pm_1",
203
+ customer: "cus_123",
204
+ });
205
+ vi.mocked(mocks.stripe.customers.update).mockResolvedValue({});
206
+ await processor.setDefaultPaymentMethod("tenant-1", "pm_1");
207
+ expect(mocks.stripe.customers.update).toHaveBeenCalledWith("cus_123", {
208
+ invoice_settings: { default_payment_method: "pm_1" },
209
+ });
210
+ });
211
+ it("sets default when ownership matches (expanded Customer object)", async () => {
212
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
213
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
214
+ id: "pm_1",
215
+ customer: { id: "cus_123", object: "customer" },
216
+ });
217
+ vi.mocked(mocks.stripe.customers.update).mockResolvedValue({});
218
+ await processor.setDefaultPaymentMethod("tenant-1", "pm_1");
219
+ expect(mocks.stripe.customers.update).toHaveBeenCalledWith("cus_123", {
220
+ invoice_settings: { default_payment_method: "pm_1" },
221
+ });
222
+ });
223
+ it("propagates Stripe errors", async () => {
224
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
225
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
226
+ id: "pm_1",
227
+ customer: "cus_123",
228
+ });
229
+ vi.mocked(mocks.stripe.customers.update).mockRejectedValue(new Error("Stripe network error"));
230
+ await expect(processor.setDefaultPaymentMethod("tenant-1", "pm_1")).rejects.toThrow("Stripe network error");
231
+ });
232
+ });
161
233
  // --- getCustomerEmail ---
162
234
  describe("getCustomerEmail", () => {
163
235
  it("returns empty string when tenant has no Stripe customer", async () => {
@@ -38,6 +38,7 @@ function makeMockProcessor(methods) {
38
38
  getCustomerEmail: vi.fn().mockResolvedValue(""),
39
39
  updateCustomerEmail: vi.fn(),
40
40
  listInvoices: vi.fn().mockResolvedValue([]),
41
+ setDefaultPaymentMethod: vi.fn().mockResolvedValue(undefined),
41
42
  };
42
43
  }
43
44
  function makeMockAutoTopupSettings(overrides) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wopr-network/platform-core",
3
- "version": "1.47.0",
3
+ "version": "1.48.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -63,6 +63,7 @@ describe("IPaymentProcessor types", () => {
63
63
  setupPaymentMethod: async () => ({ clientSecret: "cs" }),
64
64
  listPaymentMethods: async () => [],
65
65
  detachPaymentMethod: async () => undefined,
66
+ setDefaultPaymentMethod: async () => undefined,
66
67
  charge: async () => ({ success: true }),
67
68
  getCustomerEmail: async () => "",
68
69
  updateCustomerEmail: async () => undefined,
@@ -125,6 +125,9 @@ export interface IPaymentProcessor {
125
125
  /** Detach a payment method from the tenant's account. */
126
126
  detachPaymentMethod(tenant: string, paymentMethodId: string): Promise<void>;
127
127
 
128
+ /** Set a payment method as the tenant's default for future invoices. */
129
+ setDefaultPaymentMethod(tenant: string, paymentMethodId: string): Promise<void>;
130
+
128
131
  /** Get the billing email for a tenant's customer account. Returns "" if no customer exists. */
129
132
  getCustomerEmail(tenantId: string): Promise<string>;
130
133
 
@@ -120,7 +120,7 @@ describe("StripePaymentProcessor", () => {
120
120
  expect(result).toEqual([]);
121
121
  });
122
122
 
123
- it("returns formatted payment methods with card label", async () => {
123
+ it("returns formatted payment methods with card label and reads actual Stripe default", async () => {
124
124
  vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
125
125
  vi.mocked(mocks.stripe.customers.listPaymentMethods).mockResolvedValue({
126
126
  data: [
@@ -128,6 +128,10 @@ describe("StripePaymentProcessor", () => {
128
128
  { id: "pm_2", card: { brand: "mastercard", last4: "5555" } },
129
129
  ],
130
130
  } as unknown as Stripe.Response<Stripe.ApiList<Stripe.PaymentMethod>>);
131
+ vi.mocked(mocks.stripe.customers.retrieve).mockResolvedValue({
132
+ deleted: false,
133
+ invoice_settings: { default_payment_method: "pm_1" },
134
+ } as unknown as Stripe.Response<Stripe.Customer>);
131
135
 
132
136
  const result = await processor.listPaymentMethods("tenant-1");
133
137
  expect(result).toEqual([
@@ -136,11 +140,49 @@ describe("StripePaymentProcessor", () => {
136
140
  ]);
137
141
  });
138
142
 
143
+ it("marks second PM as default when Stripe says so", async () => {
144
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
145
+ vi.mocked(mocks.stripe.customers.listPaymentMethods).mockResolvedValue({
146
+ data: [
147
+ { id: "pm_1", card: { brand: "visa", last4: "4242" } },
148
+ { id: "pm_2", card: { brand: "mastercard", last4: "5555" } },
149
+ ],
150
+ } as unknown as Stripe.Response<Stripe.ApiList<Stripe.PaymentMethod>>);
151
+ vi.mocked(mocks.stripe.customers.retrieve).mockResolvedValue({
152
+ deleted: false,
153
+ invoice_settings: { default_payment_method: "pm_2" },
154
+ } as unknown as Stripe.Response<Stripe.Customer>);
155
+
156
+ const result = await processor.listPaymentMethods("tenant-1");
157
+ expect(result).toEqual([
158
+ { id: "pm_1", label: "Visa ending 4242", isDefault: false },
159
+ { id: "pm_2", label: "Mastercard ending 5555", isDefault: true },
160
+ ]);
161
+ });
162
+
163
+ it("marks no PM as default when customer has no default set", async () => {
164
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
165
+ vi.mocked(mocks.stripe.customers.listPaymentMethods).mockResolvedValue({
166
+ data: [{ id: "pm_1", card: { brand: "visa", last4: "4242" } }],
167
+ } as unknown as Stripe.Response<Stripe.ApiList<Stripe.PaymentMethod>>);
168
+ vi.mocked(mocks.stripe.customers.retrieve).mockResolvedValue({
169
+ deleted: false,
170
+ invoice_settings: { default_payment_method: null },
171
+ } as unknown as Stripe.Response<Stripe.Customer>);
172
+
173
+ const result = await processor.listPaymentMethods("tenant-1");
174
+ expect(result).toEqual([{ id: "pm_1", label: "Visa ending 4242", isDefault: false }]);
175
+ });
176
+
139
177
  it("uses generic label for non-card payment methods", async () => {
140
178
  vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
141
179
  vi.mocked(mocks.stripe.customers.listPaymentMethods).mockResolvedValue({
142
180
  data: [{ id: "pm_bank", card: undefined }],
143
181
  } as unknown as Stripe.Response<Stripe.ApiList<Stripe.PaymentMethod>>);
182
+ vi.mocked(mocks.stripe.customers.retrieve).mockResolvedValue({
183
+ deleted: false,
184
+ invoice_settings: { default_payment_method: "pm_bank" },
185
+ } as unknown as Stripe.Response<Stripe.Customer>);
144
186
 
145
187
  const result = await processor.listPaymentMethods("tenant-1");
146
188
  expect(result).toEqual([{ id: "pm_bank", label: "Payment method pm_bank", isDefault: true }]);
@@ -192,6 +234,76 @@ describe("StripePaymentProcessor", () => {
192
234
  });
193
235
  });
194
236
 
237
+ // --- setDefaultPaymentMethod ---
238
+
239
+ describe("setDefaultPaymentMethod", () => {
240
+ it("throws when tenant has no Stripe customer", async () => {
241
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(null);
242
+ await expect(processor.setDefaultPaymentMethod("tenant-1", "pm_1")).rejects.toThrow(
243
+ "No Stripe customer found for tenant: tenant-1",
244
+ );
245
+ });
246
+
247
+ it("throws PaymentMethodOwnershipError when PM belongs to different customer", async () => {
248
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
249
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
250
+ id: "pm_1",
251
+ customer: "cus_OTHER",
252
+ } as unknown as Stripe.Response<Stripe.PaymentMethod>);
253
+
254
+ await expect(processor.setDefaultPaymentMethod("tenant-1", "pm_1")).rejects.toThrow(PaymentMethodOwnershipError);
255
+ });
256
+
257
+ it("throws PaymentMethodOwnershipError when PM has no customer", async () => {
258
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
259
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
260
+ id: "pm_1",
261
+ customer: null,
262
+ } as unknown as Stripe.Response<Stripe.PaymentMethod>);
263
+
264
+ await expect(processor.setDefaultPaymentMethod("tenant-1", "pm_1")).rejects.toThrow(PaymentMethodOwnershipError);
265
+ });
266
+
267
+ it("calls stripe.customers.update with invoice_settings when ownership matches", async () => {
268
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
269
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
270
+ id: "pm_1",
271
+ customer: "cus_123",
272
+ } as unknown as Stripe.Response<Stripe.PaymentMethod>);
273
+ vi.mocked(mocks.stripe.customers.update).mockResolvedValue({} as unknown as Stripe.Response<Stripe.Customer>);
274
+
275
+ await processor.setDefaultPaymentMethod("tenant-1", "pm_1");
276
+ expect(mocks.stripe.customers.update).toHaveBeenCalledWith("cus_123", {
277
+ invoice_settings: { default_payment_method: "pm_1" },
278
+ });
279
+ });
280
+
281
+ it("succeeds when PM customer is an expanded Customer object", async () => {
282
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
283
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
284
+ id: "pm_1",
285
+ customer: { id: "cus_123", object: "customer" },
286
+ } as unknown as Stripe.Response<Stripe.PaymentMethod>);
287
+ vi.mocked(mocks.stripe.customers.update).mockResolvedValue({} as unknown as Stripe.Response<Stripe.Customer>);
288
+
289
+ await processor.setDefaultPaymentMethod("tenant-1", "pm_1");
290
+ expect(mocks.stripe.customers.update).toHaveBeenCalledWith("cus_123", {
291
+ invoice_settings: { default_payment_method: "pm_1" },
292
+ });
293
+ });
294
+
295
+ it("propagates Stripe API errors", async () => {
296
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
297
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
298
+ id: "pm_1",
299
+ customer: "cus_123",
300
+ } as unknown as Stripe.Response<Stripe.PaymentMethod>);
301
+ vi.mocked(mocks.stripe.customers.update).mockRejectedValue(new Error("Stripe API error"));
302
+
303
+ await expect(processor.setDefaultPaymentMethod("tenant-1", "pm_1")).rejects.toThrow("Stripe API error");
304
+ });
305
+ });
306
+
195
307
  // --- getCustomerEmail ---
196
308
 
197
309
  describe("getCustomerEmail", () => {
@@ -154,15 +154,42 @@ export class StripePaymentProcessor implements IPaymentProcessor {
154
154
  return [];
155
155
  }
156
156
 
157
- const methods = await this.stripe.customers.listPaymentMethods(mapping.processor_customer_id);
158
-
159
- return methods.data.map((pm, index) => ({
157
+ const [methods, customer] = await Promise.all([
158
+ this.stripe.customers.listPaymentMethods(mapping.processor_customer_id),
159
+ this.stripe.customers.retrieve(mapping.processor_customer_id),
160
+ ]);
161
+
162
+ const defaultPmId =
163
+ !customer.deleted && customer.invoice_settings?.default_payment_method
164
+ ? typeof customer.invoice_settings.default_payment_method === "string"
165
+ ? customer.invoice_settings.default_payment_method
166
+ : customer.invoice_settings.default_payment_method.id
167
+ : null;
168
+
169
+ return methods.data.map((pm) => ({
160
170
  id: pm.id,
161
171
  label: formatPaymentMethodLabel(pm),
162
- isDefault: index === 0,
172
+ isDefault: defaultPmId ? pm.id === defaultPmId : false,
163
173
  }));
164
174
  }
165
175
 
176
+ async setDefaultPaymentMethod(tenant: string, paymentMethodId: string): Promise<void> {
177
+ const mapping = await this.tenantRepo.getByTenant(tenant);
178
+ if (!mapping) {
179
+ throw new Error(`No Stripe customer found for tenant: ${tenant}`);
180
+ }
181
+
182
+ const pm = await this.stripe.paymentMethods.retrieve(paymentMethodId);
183
+ const pmCustomerId = typeof pm.customer === "string" ? pm.customer : (pm.customer?.id ?? null);
184
+ if (!pmCustomerId || pmCustomerId !== mapping.processor_customer_id) {
185
+ throw new PaymentMethodOwnershipError();
186
+ }
187
+
188
+ await this.stripe.customers.update(mapping.processor_customer_id, {
189
+ invoice_settings: { default_payment_method: paymentMethodId },
190
+ });
191
+ }
192
+
166
193
  async detachPaymentMethod(tenant: string, paymentMethodId: string): Promise<void> {
167
194
  const mapping = await this.tenantRepo.getByTenant(tenant);
168
195
  if (!mapping) {
@@ -170,7 +197,8 @@ export class StripePaymentProcessor implements IPaymentProcessor {
170
197
  }
171
198
 
172
199
  const pm = await this.stripe.paymentMethods.retrieve(paymentMethodId);
173
- if (!pm.customer || pm.customer !== mapping.processor_customer_id) {
200
+ const pmCustomerId = typeof pm.customer === "string" ? pm.customer : (pm.customer?.id ?? null);
201
+ if (!pmCustomerId || pmCustomerId !== mapping.processor_customer_id) {
174
202
  throw new PaymentMethodOwnershipError();
175
203
  }
176
204
 
@@ -129,7 +129,7 @@ describe("StripePaymentProcessor", () => {
129
129
  expect(result).toEqual([]);
130
130
  });
131
131
 
132
- it("returns formatted payment methods with card label", async () => {
132
+ it("returns formatted payment methods with card label and reads actual Stripe default", async () => {
133
133
  vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
134
134
  vi.mocked(mocks.stripe.customers.listPaymentMethods).mockResolvedValue({
135
135
  data: [
@@ -137,6 +137,10 @@ describe("StripePaymentProcessor", () => {
137
137
  { id: "pm_2", card: { brand: "mastercard", last4: "5555" } },
138
138
  ],
139
139
  } as unknown as Stripe.Response<Stripe.ApiList<Stripe.PaymentMethod>>);
140
+ vi.mocked(mocks.stripe.customers.retrieve).mockResolvedValue({
141
+ deleted: false,
142
+ invoice_settings: { default_payment_method: "pm_1" },
143
+ } as unknown as Stripe.Response<Stripe.Customer>);
140
144
 
141
145
  const result = await processor.listPaymentMethods("tenant-1");
142
146
  expect(result).toEqual([
@@ -150,6 +154,10 @@ describe("StripePaymentProcessor", () => {
150
154
  vi.mocked(mocks.stripe.customers.listPaymentMethods).mockResolvedValue({
151
155
  data: [{ id: "pm_bank", card: undefined }],
152
156
  } as unknown as Stripe.Response<Stripe.ApiList<Stripe.PaymentMethod>>);
157
+ vi.mocked(mocks.stripe.customers.retrieve).mockResolvedValue({
158
+ deleted: false,
159
+ invoice_settings: { default_payment_method: "pm_bank" },
160
+ } as unknown as Stripe.Response<Stripe.Customer>);
153
161
 
154
162
  const result = await processor.listPaymentMethods("tenant-1");
155
163
  expect(result).toEqual([{ id: "pm_bank", label: "Payment method pm_bank", isDefault: true }]);
@@ -201,6 +209,86 @@ describe("StripePaymentProcessor", () => {
201
209
  });
202
210
  });
203
211
 
212
+ // --- setDefaultPaymentMethod ---
213
+
214
+ describe("setDefaultPaymentMethod", () => {
215
+ it("throws when tenant has no Stripe customer", async () => {
216
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(null);
217
+ await expect(processor.setDefaultPaymentMethod("tenant-1", "pm_1")).rejects.toThrow(
218
+ "No Stripe customer found for tenant: tenant-1",
219
+ );
220
+ });
221
+
222
+ it("throws PaymentMethodOwnershipError when PM has no customer", async () => {
223
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
224
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
225
+ id: "pm_1",
226
+ customer: null,
227
+ } as unknown as Stripe.Response<Stripe.PaymentMethod>);
228
+
229
+ await expect(processor.setDefaultPaymentMethod("tenant-1", "pm_1")).rejects.toThrow(PaymentMethodOwnershipError);
230
+ });
231
+
232
+ it("throws PaymentMethodOwnershipError when PM belongs to different customer", async () => {
233
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
234
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
235
+ id: "pm_1",
236
+ customer: "cus_OTHER",
237
+ } as unknown as Stripe.Response<Stripe.PaymentMethod>);
238
+
239
+ await expect(processor.setDefaultPaymentMethod("tenant-1", "pm_1")).rejects.toThrow(PaymentMethodOwnershipError);
240
+ });
241
+
242
+ it("throws PaymentMethodOwnershipError when PM customer is an expanded object with different id", async () => {
243
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
244
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
245
+ id: "pm_1",
246
+ customer: { id: "cus_OTHER", object: "customer" },
247
+ } as unknown as Stripe.Response<Stripe.PaymentMethod>);
248
+
249
+ await expect(processor.setDefaultPaymentMethod("tenant-1", "pm_1")).rejects.toThrow(PaymentMethodOwnershipError);
250
+ });
251
+
252
+ it("sets default when ownership matches (string customer)", async () => {
253
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
254
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
255
+ id: "pm_1",
256
+ customer: "cus_123",
257
+ } as unknown as Stripe.Response<Stripe.PaymentMethod>);
258
+ vi.mocked(mocks.stripe.customers.update).mockResolvedValue({} as unknown as Stripe.Response<Stripe.Customer>);
259
+
260
+ await processor.setDefaultPaymentMethod("tenant-1", "pm_1");
261
+ expect(mocks.stripe.customers.update).toHaveBeenCalledWith("cus_123", {
262
+ invoice_settings: { default_payment_method: "pm_1" },
263
+ });
264
+ });
265
+
266
+ it("sets default when ownership matches (expanded Customer object)", async () => {
267
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
268
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
269
+ id: "pm_1",
270
+ customer: { id: "cus_123", object: "customer" },
271
+ } as unknown as Stripe.Response<Stripe.PaymentMethod>);
272
+ vi.mocked(mocks.stripe.customers.update).mockResolvedValue({} as unknown as Stripe.Response<Stripe.Customer>);
273
+
274
+ await processor.setDefaultPaymentMethod("tenant-1", "pm_1");
275
+ expect(mocks.stripe.customers.update).toHaveBeenCalledWith("cus_123", {
276
+ invoice_settings: { default_payment_method: "pm_1" },
277
+ });
278
+ });
279
+
280
+ it("propagates Stripe errors", async () => {
281
+ vi.mocked(mocks.tenantRepo.getByTenant).mockResolvedValue(makeTenantRow());
282
+ vi.mocked(mocks.stripe.paymentMethods.retrieve).mockResolvedValue({
283
+ id: "pm_1",
284
+ customer: "cus_123",
285
+ } as unknown as Stripe.Response<Stripe.PaymentMethod>);
286
+ vi.mocked(mocks.stripe.customers.update).mockRejectedValue(new Error("Stripe network error"));
287
+
288
+ await expect(processor.setDefaultPaymentMethod("tenant-1", "pm_1")).rejects.toThrow("Stripe network error");
289
+ });
290
+ });
291
+
204
292
  // --- getCustomerEmail ---
205
293
 
206
294
  describe("getCustomerEmail", () => {
@@ -154,15 +154,42 @@ export class StripePaymentProcessor implements IPaymentProcessor {
154
154
  return [];
155
155
  }
156
156
 
157
- const methods = await this.stripe.customers.listPaymentMethods(mapping.processor_customer_id);
158
-
159
- return methods.data.map((pm, index) => ({
157
+ const [methods, customer] = await Promise.all([
158
+ this.stripe.customers.listPaymentMethods(mapping.processor_customer_id),
159
+ this.stripe.customers.retrieve(mapping.processor_customer_id),
160
+ ]);
161
+
162
+ const defaultPmId =
163
+ !customer.deleted && customer.invoice_settings?.default_payment_method
164
+ ? typeof customer.invoice_settings.default_payment_method === "string"
165
+ ? customer.invoice_settings.default_payment_method
166
+ : customer.invoice_settings.default_payment_method.id
167
+ : null;
168
+
169
+ return methods.data.map((pm) => ({
160
170
  id: pm.id,
161
171
  label: formatPaymentMethodLabel(pm),
162
- isDefault: index === 0,
172
+ isDefault: defaultPmId ? pm.id === defaultPmId : false,
163
173
  }));
164
174
  }
165
175
 
176
+ async setDefaultPaymentMethod(tenant: string, paymentMethodId: string): Promise<void> {
177
+ const mapping = await this.tenantRepo.getByTenant(tenant);
178
+ if (!mapping) {
179
+ throw new Error(`No Stripe customer found for tenant: ${tenant}`);
180
+ }
181
+
182
+ const pm = await this.stripe.paymentMethods.retrieve(paymentMethodId);
183
+ const pmCustomerId = typeof pm.customer === "string" ? pm.customer : (pm.customer?.id ?? null);
184
+ if (!pmCustomerId || pmCustomerId !== mapping.processor_customer_id) {
185
+ throw new PaymentMethodOwnershipError();
186
+ }
187
+
188
+ await this.stripe.customers.update(mapping.processor_customer_id, {
189
+ invoice_settings: { default_payment_method: paymentMethodId },
190
+ });
191
+ }
192
+
166
193
  async detachPaymentMethod(tenant: string, paymentMethodId: string): Promise<void> {
167
194
  const mapping = await this.tenantRepo.getByTenant(tenant);
168
195
  if (!mapping) {
@@ -44,6 +44,7 @@ function makeMockProcessor(methods: SavedPaymentMethod[]): IPaymentProcessor {
44
44
  getCustomerEmail: vi.fn().mockResolvedValue(""),
45
45
  updateCustomerEmail: vi.fn(),
46
46
  listInvoices: vi.fn().mockResolvedValue([]),
47
+ setDefaultPaymentMethod: vi.fn().mockResolvedValue(undefined),
47
48
  };
48
49
  }
49
50