backend-manager 5.0.108 → 5.0.109

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "backend-manager",
3
- "version": "5.0.108",
3
+ "version": "5.0.109",
4
4
  "description": "Quick tools for developing Firebase functions",
5
5
  "main": "src/manager/index.js",
6
6
  "bin": {
@@ -31,6 +31,9 @@ module.exports = async ({ assistant, change, context }) => {
31
31
  // Set status to processing
32
32
  await webhookRef.set({ status: 'processing' }, { merge: true });
33
33
 
34
+ // Hoisted so orderId is available in catch block for audit trail
35
+ let orderId = null;
36
+
34
37
  try {
35
38
  const processor = dataAfter.processor;
36
39
  const uid = dataAfter.owner;
@@ -73,7 +76,7 @@ module.exports = async ({ assistant, change, context }) => {
73
76
  const webhookReceivedUNIX = dataAfter.metadata?.received?.timestampUNIX || nowUNIX;
74
77
 
75
78
  // Extract orderId from resource (processor-agnostic)
76
- const orderId = library.getOrderId(resource);
79
+ orderId = library.getOrderId(resource);
77
80
 
78
81
  // Process the payment event (subscription or one-time)
79
82
  if (category !== 'subscription' && category !== 'one-time') {
@@ -100,11 +103,28 @@ module.exports = async ({ assistant, change, context }) => {
100
103
  } catch (e) {
101
104
  assistant.error(`Webhook ${eventId} failed: ${e.message}`, e);
102
105
 
106
+ const now = powertools.timestamp(new Date(), { output: 'string' });
107
+ const nowUNIX = powertools.timestamp(now, { output: 'unix' });
108
+
103
109
  // Mark as failed with error message
104
110
  await webhookRef.set({
105
111
  status: 'failed',
106
112
  error: e.message || String(e),
107
113
  }, { merge: true });
114
+
115
+ // Mark intent as failed if we resolved the orderId before the error
116
+ if (orderId) {
117
+ await admin.firestore().doc(`payments-intents/${orderId}`).set({
118
+ status: 'failed',
119
+ error: e.message || String(e),
120
+ metadata: {
121
+ completed: {
122
+ timestamp: now,
123
+ timestampUNIX: nowUNIX,
124
+ },
125
+ },
126
+ }, { merge: true });
127
+ }
108
128
  }
109
129
  };
110
130
 
@@ -220,6 +240,20 @@ async function processPaymentEvent({ category, library, resource, resourceType,
220
240
  assistant.log(`Updated payments-orders/${orderId}: type=${category}, uid=${uid}, eventType=${eventType}`);
221
241
  }
222
242
 
243
+ // Update payments-intents/{orderId} status to match webhook outcome
244
+ if (orderId) {
245
+ await admin.firestore().doc(`payments-intents/${orderId}`).set({
246
+ status: 'completed',
247
+ metadata: {
248
+ completed: {
249
+ timestamp: now,
250
+ timestampUNIX: nowUNIX,
251
+ },
252
+ },
253
+ }, { merge: true });
254
+ assistant.log(`Updated payments-intents/${orderId}: status=completed`);
255
+ }
256
+
223
257
  return transitionName;
224
258
  }
225
259
 
@@ -1,22 +1,35 @@
1
1
  /**
2
2
  * Stripe cancel processor
3
- * Sets a subscription to cancel at the end of the current billing period
3
+ * Cancels a subscription immediately if trialing, at period end otherwise.
4
4
  */
5
5
  module.exports = {
6
6
  /**
7
- * Cancel a Stripe subscription at period end
7
+ * Cancel a Stripe subscription
8
+ *
9
+ * If the subscription is currently trialing, cancel immediately to avoid
10
+ * giving free premium access for the remainder of the trial.
11
+ * Otherwise, cancel at the end of the current billing period.
8
12
  *
9
13
  * @param {object} options
10
14
  * @param {string} options.resourceId - Stripe subscription ID (e.g., 'sub_xxx')
11
15
  * @param {string} options.uid - User's UID (for logging)
16
+ * @param {object} options.subscription - User's current subscription object
12
17
  * @param {object} options.assistant - Assistant instance for logging
13
18
  */
14
- async cancelAtPeriodEnd({ resourceId, uid, assistant }) {
19
+ async cancelAtPeriodEnd({ resourceId, uid, subscription, assistant }) {
15
20
  const StripeLib = require('../../../../libraries/payment/processors/stripe.js');
16
21
  const stripe = StripeLib.init();
17
22
 
18
- await stripe.subscriptions.update(resourceId, { cancel_at_period_end: true });
23
+ const isTrialing = subscription?.trial?.claimed
24
+ && subscription?.status === 'active'
25
+ && subscription?.trial?.expires?.timestampUNIX === subscription?.expires?.timestampUNIX;
19
26
 
20
- assistant.log(`Stripe cancel at period end: sub=${resourceId}, uid=${uid}`);
27
+ if (isTrialing) {
28
+ await stripe.subscriptions.cancel(resourceId);
29
+ assistant.log(`Stripe cancel immediate (trialing): sub=${resourceId}, uid=${uid}`);
30
+ } else {
31
+ await stripe.subscriptions.update(resourceId, { cancel_at_period_end: true });
32
+ assistant.log(`Stripe cancel at period end: sub=${resourceId}, uid=${uid}`);
33
+ }
21
34
  },
22
35
  };
@@ -2,9 +2,13 @@ const powertools = require('node-powertools');
2
2
 
3
3
  /**
4
4
  * Test cancel processor
5
- * Simulates the Stripe webhook that results from cancel_at_period_end=true
5
+ * Simulates the Stripe webhook that results from cancellation
6
6
  * by writing directly to payments-webhooks/{eventId} with status=pending.
7
7
  * The on-write trigger picks it up and runs the full pipeline.
8
+ *
9
+ * If the user is trialing, simulates immediate cancellation (customer.subscription.deleted).
10
+ * Otherwise, simulates cancel at period end (customer.subscription.updated with cancel_at_period_end=true).
11
+ *
8
12
  * Only available in non-production environments.
9
13
  */
10
14
  module.exports = {
@@ -16,7 +20,6 @@ module.exports = {
16
20
  const admin = assistant.Manager.libraries.admin;
17
21
 
18
22
  const timestamp = Date.now();
19
- const eventId = `_test-evt-cancel-${timestamp}`;
20
23
  const now = Math.floor(timestamp / 1000);
21
24
  const periodEnd = now + (30 * 86400);
22
25
 
@@ -35,21 +38,31 @@ module.exports = {
35
38
  }
36
39
  }
37
40
 
38
- // Build a Stripe-shaped customer.subscription.updated payload
39
- // with cancel_at_period_end=true — mirrors what Stripe sends after cancellation
41
+ // Detect if user is on a trial
42
+ const isTrialing = subscription?.trial?.claimed
43
+ && subscription?.status === 'active'
44
+ && subscription?.trial?.expires?.timestampUNIX === subscription?.expires?.timestampUNIX;
45
+
46
+ // Trialing: immediate cancel (customer.subscription.deleted)
47
+ // Non-trialing: cancel at period end (customer.subscription.updated)
48
+ const eventType = isTrialing
49
+ ? 'customer.subscription.deleted'
50
+ : 'customer.subscription.updated';
51
+ const eventId = `_test-evt-cancel-${timestamp}`;
52
+
40
53
  const subscriptionObj = {
41
54
  id: resourceId,
42
55
  object: 'subscription',
43
- status: 'active',
56
+ status: isTrialing ? 'canceled' : 'active',
44
57
  metadata: { uid, orderId },
45
- cancel_at_period_end: true,
46
- cancel_at: periodEnd,
47
- canceled_at: null,
48
- current_period_end: periodEnd,
58
+ cancel_at_period_end: !isTrialing,
59
+ cancel_at: isTrialing ? now : periodEnd,
60
+ canceled_at: isTrialing ? now : null,
61
+ current_period_end: isTrialing ? now : periodEnd,
49
62
  current_period_start: now - (30 * 86400),
50
63
  start_date: now - (30 * 86400),
51
- trial_start: null,
52
- trial_end: null,
64
+ trial_start: isTrialing ? (now - 86400) : null,
65
+ trial_end: isTrialing ? now : null,
53
66
  plan: { product: stripeProductId, interval: 'month' },
54
67
  };
55
68
 
@@ -64,11 +77,11 @@ module.exports = {
64
77
  owner: uid,
65
78
  raw: {
66
79
  id: eventId,
67
- type: 'customer.subscription.updated',
80
+ type: eventType,
68
81
  data: { object: subscriptionObj },
69
82
  },
70
83
  event: {
71
- type: 'customer.subscription.updated',
84
+ type: eventType,
72
85
  category: 'subscription',
73
86
  resourceType: 'subscription',
74
87
  resourceId: resourceId,
@@ -86,6 +99,6 @@ module.exports = {
86
99
  },
87
100
  });
88
101
 
89
- assistant.log(`Test cancel processor: wrote payments-webhooks/${eventId} for sub=${resourceId}, uid=${uid}`);
102
+ assistant.log(`Test cancel processor: wrote payments-webhooks/${eventId} (${eventType}) for sub=${resourceId}, uid=${uid}, trialing=${isTrialing}`);
90
103
  },
91
104
  };
@@ -166,6 +166,15 @@ const JOURNEY_ACCOUNTS = {
166
166
  subscription: { product: { id: 'basic' }, status: 'active' }, // Starts as basic, upgraded via trial webhook
167
167
  },
168
168
  },
169
+ 'journey-payments-trial-cancel': {
170
+ id: 'journey-payments-trial-cancel',
171
+ uid: '_test-journey-payments-trial-cancel',
172
+ email: '_test.journey-payments-trial-cancel@{domain}',
173
+ properties: {
174
+ roles: {},
175
+ subscription: { product: { id: 'basic' }, status: 'active' }, // Starts as basic, trial then immediate cancel
176
+ },
177
+ },
169
178
  'journey-payments-failure': {
170
179
  id: 'journey-payments-failure',
171
180
  uid: '_test-journey-payments-failure',
@@ -112,7 +112,7 @@ module.exports = {
112
112
  },
113
113
 
114
114
  {
115
- name: 'intent-doc-created',
115
+ name: 'intent-doc-completed',
116
116
  async run({ firestore, assert, state }) {
117
117
  const intentDoc = await firestore.get(`payments-intents/${state.orderId}`);
118
118
 
@@ -121,7 +121,9 @@ module.exports = {
121
121
  assert.equal(intentDoc.intentId, state.intentId, 'Intent ID should match processor session ID');
122
122
  assert.equal(intentDoc.owner, state.uid, 'Owner should match');
123
123
  assert.equal(intentDoc.processor, 'test', 'Processor should be test');
124
+ assert.equal(intentDoc.status, 'completed', 'Intent status should be completed after webhook processing');
124
125
  assert.equal(intentDoc.productId, state.productId, `Product should be ${state.productId}`);
126
+ assert.ok(intentDoc.metadata?.completed?.timestampUNIX > 0, 'Completed timestamp should be set');
125
127
  },
126
128
  },
127
129
  ],
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Test: Payment Journey - Trial Cancel
3
+ * Simulates: basic user → trial activation → cancel during trial → immediate cancellation
4
+ *
5
+ * When a user cancels during a free trial, the subscription should be cancelled immediately
6
+ * (not scheduled for period end) to avoid giving free premium access for the remainder of the trial.
7
+ *
8
+ * Uses the test processor for initial trial, then cancel endpoint for cancellation.
9
+ * Product-agnostic: resolves the first paid product from config.payment.products
10
+ */
11
+ module.exports = {
12
+ description: 'Payment journey: trial → cancel during trial → immediate cancellation',
13
+ type: 'suite',
14
+ timeout: 30000,
15
+
16
+ tests: [
17
+ {
18
+ name: 'verify-starts-as-basic',
19
+ async run({ accounts, firestore, assert, state, config }) {
20
+ const uid = accounts['journey-payments-trial-cancel'].uid;
21
+ const userDoc = await firestore.get(`users/${uid}`);
22
+
23
+ assert.ok(userDoc, 'User doc should exist');
24
+ assert.equal(userDoc.subscription?.product?.id, 'basic', 'Should start as basic');
25
+ assert.equal(userDoc.subscription?.trial?.claimed, false, 'Trial should not be claimed');
26
+
27
+ // Resolve first paid product with trial from config
28
+ const trialProduct = config.payment.products.find(p => p.id !== 'basic' && p.prices && p.trial?.days);
29
+ assert.ok(trialProduct, 'Config should have at least one paid product with trial');
30
+
31
+ state.uid = uid;
32
+ state.paidProductId = trialProduct.id;
33
+ state.paidProductName = trialProduct.name;
34
+ },
35
+ },
36
+
37
+ {
38
+ name: 'create-trial-intent',
39
+ async run({ http, assert, state }) {
40
+ const response = await http.as('journey-payments-trial-cancel').post('payments/intent', {
41
+ processor: 'test',
42
+ productId: state.paidProductId,
43
+ frequency: 'monthly',
44
+ trial: true,
45
+ });
46
+
47
+ assert.isSuccess(response, 'Intent should succeed');
48
+ assert.ok(response.data.id, 'Should return intent ID');
49
+ assert.ok(response.data.orderId, 'Should return orderId');
50
+
51
+ state.intentId = response.data.id;
52
+ state.orderId = response.data.orderId;
53
+ state.eventId = response.data.id.replace('_test-cs-', '_test-evt-');
54
+ },
55
+ },
56
+
57
+ {
58
+ name: 'trial-activated',
59
+ async run({ firestore, assert, state, waitFor }) {
60
+ await waitFor(async () => {
61
+ const userDoc = await firestore.get(`users/${state.uid}`);
62
+ return userDoc?.subscription?.trial?.claimed === true;
63
+ }, 15000, 500);
64
+
65
+ const userDoc = await firestore.get(`users/${state.uid}`);
66
+
67
+ assert.equal(userDoc.subscription.product.id, state.paidProductId, `Product should be ${state.paidProductId}`);
68
+ assert.equal(userDoc.subscription.status, 'active', 'Status should be active');
69
+ assert.equal(userDoc.subscription.trial.claimed, true, 'Trial should be claimed');
70
+ assert.equal(userDoc.subscription.trial.expires.timestampUNIX, userDoc.subscription.expires.timestampUNIX, 'Trial expires should match subscription expires (still in trial period)');
71
+
72
+ state.subscriptionId = userDoc.subscription.payment.resourceId;
73
+ },
74
+ },
75
+
76
+ {
77
+ name: 'cancel-during-trial',
78
+ async run({ http, assert }) {
79
+ // Cancel via endpoint — test processor should detect trial and simulate immediate cancel
80
+ const response = await http.as('journey-payments-trial-cancel').post('payments/cancel', {
81
+ confirmed: true,
82
+ reason: 'Changed my mind during trial',
83
+ feedback: 'Testing trial cancellation',
84
+ });
85
+
86
+ assert.isSuccess(response, 'Cancel endpoint should succeed');
87
+ assert.equal(response.data.success, true, 'Should return { success: true }');
88
+ },
89
+ },
90
+
91
+ {
92
+ name: 'verify-immediate-cancellation',
93
+ async run({ firestore, assert, state, waitFor }) {
94
+ // Poll until subscription is cancelled (NOT just pending)
95
+ await waitFor(async () => {
96
+ const userDoc = await firestore.get(`users/${state.uid}`);
97
+ return userDoc?.subscription?.status === 'cancelled';
98
+ }, 15000, 500);
99
+
100
+ const userDoc = await firestore.get(`users/${state.uid}`);
101
+
102
+ // During trial cancel: subscription should be immediately cancelled, not pending
103
+ assert.equal(userDoc.subscription.status, 'cancelled', 'Status should be cancelled (not active with pending)');
104
+ assert.equal(userDoc.subscription.cancellation.pending, false, 'Should NOT be pending — should be fully cancelled');
105
+ assert.equal(userDoc.subscription.product.id, state.paidProductId, `Product should still be ${state.paidProductId}`);
106
+ },
107
+ },
108
+ ],
109
+ };
@@ -79,6 +79,18 @@ module.exports = {
79
79
  },
80
80
  },
81
81
 
82
+ {
83
+ name: 'intent-doc-completed',
84
+ async run({ firestore, assert, state }) {
85
+ const intentDoc = await firestore.get(`payments-intents/${state.orderId}`);
86
+
87
+ assert.ok(intentDoc, 'Intent doc should exist');
88
+ assert.equal(intentDoc.id, state.orderId, 'ID should match orderId');
89
+ assert.equal(intentDoc.status, 'completed', 'Intent status should be completed after webhook processing');
90
+ assert.ok(intentDoc.metadata?.completed?.timestampUNIX > 0, 'Completed timestamp should be set');
91
+ },
92
+ },
93
+
82
94
  {
83
95
  name: 'send-trial-to-active-webhook',
84
96
  async run({ http, assert, state, config }) {
@@ -109,7 +109,7 @@ module.exports = {
109
109
  },
110
110
 
111
111
  {
112
- name: 'intent-doc-created',
112
+ name: 'intent-doc-completed',
113
113
  async run({ firestore, assert, state }) {
114
114
  const intentDoc = await firestore.get(`payments-intents/${state.orderId}`);
115
115
 
@@ -118,8 +118,9 @@ module.exports = {
118
118
  assert.equal(intentDoc.intentId, state.intentId, 'Intent ID should match processor session ID');
119
119
  assert.equal(intentDoc.owner, state.uid, 'Owner should match');
120
120
  assert.equal(intentDoc.processor, 'test', 'Processor should be test');
121
- assert.equal(intentDoc.status, 'pending', 'Intent status should be pending');
121
+ assert.equal(intentDoc.status, 'completed', 'Intent status should be completed after webhook processing');
122
122
  assert.equal(intentDoc.productId, state.paidProductId, `Product should be ${state.paidProductId}`);
123
+ assert.ok(intentDoc.metadata?.completed?.timestampUNIX > 0, 'Completed timestamp should be set');
123
124
  },
124
125
  },
125
126
  ],