backend-manager 5.9.7 → 5.9.9

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 (216) hide show
  1. package/package.json +5 -3
  2. package/src/cli/commands/setup-tests/bem-config.js +3 -2
  3. package/src/cli/commands/setup-tests/helpers.js +5 -0
  4. package/src/cli/commands/setup-tests/project-id-consistency.js +2 -1
  5. package/src/test/fixtures/firebase-project/.temp/test-mode.json +1 -1
  6. package/src/test/fixtures/firebase-project/database-debug.log +8 -8
  7. package/src/test/fixtures/firebase-project/firestore-debug.log +57 -55
  8. package/src/test/fixtures/firebase-project/pubsub-debug.log +3 -3
  9. package/templates/_.env +42 -0
  10. package/templates/_.gitignore +60 -0
  11. package/templates/backend-manager-config.json +249 -0
  12. package/templates/database.rules.json +83 -0
  13. package/templates/firebase.json +66 -0
  14. package/templates/firestore.indexes.json +4 -0
  15. package/templates/firestore.rules +112 -0
  16. package/templates/public/404.html +26 -0
  17. package/templates/public/index.html +24 -0
  18. package/templates/remoteconfig.template.json +1 -0
  19. package/templates/storage-lifecycle-config-1-day.json +9 -0
  20. package/templates/storage-lifecycle-config-30-days.json +9 -0
  21. package/templates/storage.rules +8 -0
  22. package/test/_init/accounts-validation.js +58 -0
  23. package/test/_legacy/ai/index.js +231 -0
  24. package/test/_legacy/ai/test.jpg +0 -0
  25. package/test/_legacy/ai/test.pdf +0 -0
  26. package/test/_legacy/index.js +31 -0
  27. package/test/_legacy/payment-resolver/chargebee/orders/refunded.json +0 -0
  28. package/test/_legacy/payment-resolver/chargebee/orders/unpaid.json +98 -0
  29. package/test/_legacy/payment-resolver/chargebee/subscriptions/active.json +578 -0
  30. package/test/_legacy/payment-resolver/chargebee/subscriptions/trial-in-trial.json +38 -0
  31. package/test/_legacy/payment-resolver/chargebee/subscriptions/trial-skipped-to-active.json +135 -0
  32. package/test/_legacy/payment-resolver/chargebee/subscriptions/trial-to-active-to-cancelled.json +42 -0
  33. package/test/_legacy/payment-resolver/chargebee/subscriptions/trial-to-active.json +44 -0
  34. package/test/_legacy/payment-resolver/chargebee/subscriptions/trial-to-cancelled.json +39 -0
  35. package/test/_legacy/payment-resolver/chargebee/subscriptions/trial-to-refund.json +143 -0
  36. package/test/_legacy/payment-resolver/chargebee/subscriptions/trial-to-suspended.json +48 -0
  37. package/test/_legacy/payment-resolver/coinbase/orders/regular.json +204 -0
  38. package/test/_legacy/payment-resolver/coinbase/subscriptions/cancelled.json +204 -0
  39. package/test/_legacy/payment-resolver/coinbase/subscriptions/paid-2.json +125 -0
  40. package/test/_legacy/payment-resolver/index.js +1558 -0
  41. package/test/_legacy/payment-resolver/paypal/orders/refunded.json +0 -0
  42. package/test/_legacy/payment-resolver/paypal/orders/regular.json +120 -0
  43. package/test/_legacy/payment-resolver/paypal/subscriptions/active-refund-previous-stmnt.json +323 -0
  44. package/test/_legacy/payment-resolver/paypal/subscriptions/active.json +192 -0
  45. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-in-trial.json +125 -0
  46. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-payment-not-complete.json +76 -0
  47. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-payment-overdue-2.json +114 -0
  48. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-payment-overdue.json +114 -0
  49. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-to-active-to-cancelled.json +111 -0
  50. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-to-active.json +132 -0
  51. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-to-cancelled.json +107 -0
  52. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-to-expired.json +91 -0
  53. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-to-refund.json +147 -0
  54. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-to-suspended.json +120 -0
  55. package/test/_legacy/payment-resolver/stripe/orders/refunded.json +0 -0
  56. package/test/_legacy/payment-resolver/stripe/orders/regular.json +91 -0
  57. package/test/_legacy/payment-resolver/stripe/subscriptions/active.json +421 -0
  58. package/test/_legacy/payment-resolver/stripe/subscriptions/trial-in-trial.json +349 -0
  59. package/test/_legacy/payment-resolver/stripe/subscriptions/trial-to-active-failed-authorization.json +430 -0
  60. package/test/_legacy/payment-resolver/stripe/subscriptions/trial-to-active.json +319 -0
  61. package/test/_legacy/payment-resolver/stripe/subscriptions/trial-to-cancelled.json +319 -0
  62. package/test/_legacy/payment-resolver/stripe/subscriptions/trial-to-refund.json +414 -0
  63. package/test/_legacy/payment-resolver/stripe/subscriptions/trial-to-suspended.json +319 -0
  64. package/test/_legacy/payment-resolver/stripe/subscriptions/unsure.json +339 -0
  65. package/test/_legacy/test-new +1178 -0
  66. package/test/_legacy/test.md +89 -0
  67. package/test/_legacy/usage.js +175 -0
  68. package/test/_legacy/user.js +31 -0
  69. package/test/ai/tools-live.js +170 -0
  70. package/test/boot/emulator-boots.js +37 -0
  71. package/test/content/blog-generate.js +160 -0
  72. package/test/email/campaign-send.js +45 -0
  73. package/test/email/consent-lifecycle.js +257 -0
  74. package/test/email/feedback-and-plain-send.js +52 -0
  75. package/test/email/fixtures/clean.json +30 -0
  76. package/test/email/fixtures/editorial.json +30 -0
  77. package/test/email/fixtures/field-report.json +53 -0
  78. package/test/email/marketing-lifecycle.js +132 -0
  79. package/test/email/newsletter-generate.js +819 -0
  80. package/test/email/newsletter-templates.js +491 -0
  81. package/test/email/templates.js +207 -0
  82. package/test/email/transactional-send.js +34 -0
  83. package/test/email/transactional.js +560 -0
  84. package/test/email/validation.js +710 -0
  85. package/test/events/auth-delete-race.js +201 -0
  86. package/test/events/payments/journey-payments-cancel-endpoint.js +100 -0
  87. package/test/events/payments/journey-payments-cancel.js +182 -0
  88. package/test/events/payments/journey-payments-discount.js +89 -0
  89. package/test/events/payments/journey-payments-failure.js +146 -0
  90. package/test/events/payments/journey-payments-legacy-product.js +149 -0
  91. package/test/events/payments/journey-payments-one-time-failure.js +111 -0
  92. package/test/events/payments/journey-payments-one-time.js +136 -0
  93. package/test/events/payments/journey-payments-plan-change.js +144 -0
  94. package/test/events/payments/journey-payments-refund-webhook.js +180 -0
  95. package/test/events/payments/journey-payments-suspend.js +181 -0
  96. package/test/events/payments/journey-payments-trial-cancel.js +130 -0
  97. package/test/events/payments/journey-payments-trial.js +171 -0
  98. package/test/events/payments/journey-payments-uid-resolution.js +132 -0
  99. package/test/events/payments/journey-payments-upgrade.js +135 -0
  100. package/test/fixtures/chargebee/invoice-one-time.json +27 -0
  101. package/test/fixtures/chargebee/subscription-active.json +44 -0
  102. package/test/fixtures/chargebee/subscription-cancelled.json +42 -0
  103. package/test/fixtures/chargebee/subscription-in-trial.json +41 -0
  104. package/test/fixtures/chargebee/subscription-legacy-plan.json +41 -0
  105. package/test/fixtures/chargebee/subscription-non-renewing.json +41 -0
  106. package/test/fixtures/chargebee/subscription-paused.json +42 -0
  107. package/test/fixtures/chargebee/webhook-payment-failed.json +51 -0
  108. package/test/fixtures/chargebee/webhook-subscription-created.json +47 -0
  109. package/test/fixtures/paypal/order-approved.json +62 -0
  110. package/test/fixtures/paypal/order-completed.json +110 -0
  111. package/test/fixtures/paypal/subscription-active.json +76 -0
  112. package/test/fixtures/paypal/subscription-cancelled.json +50 -0
  113. package/test/fixtures/paypal/subscription-suspended.json +65 -0
  114. package/test/fixtures/stripe/checkout-session-completed.json +130 -0
  115. package/test/fixtures/stripe/invoice-payment-failed.json +148 -0
  116. package/test/fixtures/stripe/invoice-subscription-payment-failed.json +28 -0
  117. package/test/fixtures/stripe/subscription-active.json +161 -0
  118. package/test/fixtures/stripe/subscription-canceled.json +161 -0
  119. package/test/fixtures/stripe/subscription-trialing.json +161 -0
  120. package/test/functions/admin/database-read.js +134 -0
  121. package/test/functions/admin/database-write.js +159 -0
  122. package/test/functions/admin/edit-post.js +366 -0
  123. package/test/functions/admin/firestore-query.js +207 -0
  124. package/test/functions/admin/firestore-read.js +129 -0
  125. package/test/functions/admin/firestore-write.js +105 -0
  126. package/test/functions/admin/get-stats.js +115 -0
  127. package/test/functions/admin/send-email.js +119 -0
  128. package/test/functions/admin/send-notification.js +208 -0
  129. package/test/functions/admin/write-repo-content.js +223 -0
  130. package/test/functions/general/add-marketing-contact.js +335 -0
  131. package/test/functions/general/fetch-post.js +54 -0
  132. package/test/functions/general/generate-uuid.js +114 -0
  133. package/test/functions/test/authenticate.js +64 -0
  134. package/test/functions/user/create-custom-token.js +73 -0
  135. package/test/functions/user/delete.js +135 -0
  136. package/test/functions/user/get-active-sessions.js +111 -0
  137. package/test/functions/user/get-subscription-info.js +99 -0
  138. package/test/functions/user/regenerate-api-keys.js +156 -0
  139. package/test/functions/user/resolve.js +52 -0
  140. package/test/functions/user/sign-out-all-sessions.js +94 -0
  141. package/test/functions/user/sign-up.js +252 -0
  142. package/test/functions/user/submit-feedback.js +104 -0
  143. package/test/functions/user/validate-settings.js +82 -0
  144. package/test/helpers/ai-request-payload.js +300 -0
  145. package/test/helpers/ai-test-provider.js +202 -0
  146. package/test/helpers/ai-tools-format.js +383 -0
  147. package/test/helpers/content/blog-auto-publisher.js +484 -0
  148. package/test/helpers/content/feed-parser.js +528 -0
  149. package/test/helpers/content/ghostii-blocks.js +134 -0
  150. package/test/helpers/content/ghostii-feed-integration.js +404 -0
  151. package/test/helpers/content/ghostii-write-article.js +243 -0
  152. package/test/helpers/environment.js +230 -0
  153. package/test/helpers/infer-contact.js +113 -0
  154. package/test/helpers/merge-line-files.js +271 -0
  155. package/test/helpers/payment/chargebee/parse-webhook.js +413 -0
  156. package/test/helpers/payment/chargebee/to-unified-one-time.js +147 -0
  157. package/test/helpers/payment/chargebee/to-unified-subscription.js +648 -0
  158. package/test/helpers/payment/paypal/parse-webhook.js +539 -0
  159. package/test/helpers/payment/paypal/to-unified-one-time.js +382 -0
  160. package/test/helpers/payment/paypal/to-unified-subscription.js +820 -0
  161. package/test/helpers/payment/stripe/parse-webhook.js +447 -0
  162. package/test/helpers/payment/stripe/to-unified-one-time.js +306 -0
  163. package/test/helpers/payment/stripe/to-unified-subscription.js +708 -0
  164. package/test/helpers/sanitize.js +222 -0
  165. package/test/helpers/slugify.js +394 -0
  166. package/test/helpers/storage.js +194 -0
  167. package/test/helpers/user.js +755 -0
  168. package/test/helpers/webhook-forward.js +418 -0
  169. package/test/mcp/discovery.js +53 -0
  170. package/test/mcp/oauth.js +161 -0
  171. package/test/mcp/protocol.js +268 -0
  172. package/test/mcp/roles.js +188 -0
  173. package/test/mcp/utils.js +245 -0
  174. package/test/routes/admin/create-post.js +364 -0
  175. package/test/routes/admin/database.js +131 -0
  176. package/test/routes/admin/deduplicate-image-alts.js +190 -0
  177. package/test/routes/admin/email.js +114 -0
  178. package/test/routes/admin/firestore-query.js +204 -0
  179. package/test/routes/admin/firestore.js +127 -0
  180. package/test/routes/admin/infer-contact.js +218 -0
  181. package/test/routes/admin/notification.js +198 -0
  182. package/test/routes/admin/post-resize-image.js +184 -0
  183. package/test/routes/admin/post.js +368 -0
  184. package/test/routes/admin/repo-content.js +223 -0
  185. package/test/routes/admin/stats.js +112 -0
  186. package/test/routes/content/post.js +54 -0
  187. package/test/routes/general/uuid.js +115 -0
  188. package/test/routes/marketing/campaign.js +125 -0
  189. package/test/routes/marketing/contact.js +370 -0
  190. package/test/routes/marketing/email-preferences.js +292 -0
  191. package/test/routes/marketing/push-send.js +32 -0
  192. package/test/routes/marketing/webhook-forward.js +61 -0
  193. package/test/routes/marketing/webhook.js +639 -0
  194. package/test/routes/payments/cancel.js +163 -0
  195. package/test/routes/payments/discount.js +80 -0
  196. package/test/routes/payments/dispute-alert.js +320 -0
  197. package/test/routes/payments/intent.js +336 -0
  198. package/test/routes/payments/portal.js +92 -0
  199. package/test/routes/payments/refund.js +179 -0
  200. package/test/routes/payments/trial-eligibility.js +71 -0
  201. package/test/routes/payments/webhook.js +107 -0
  202. package/test/routes/test/authenticate.js +59 -0
  203. package/test/routes/test/schema.js +554 -0
  204. package/test/routes/test/usage.js +342 -0
  205. package/test/routes/user/api-keys.js +156 -0
  206. package/test/routes/user/delete.js +136 -0
  207. package/test/routes/user/feedback.js +104 -0
  208. package/test/routes/user/sessions.js +199 -0
  209. package/test/routes/user/settings-validate.js +82 -0
  210. package/test/routes/user/signup.js +542 -0
  211. package/test/routes/user/subscription.js +99 -0
  212. package/test/routes/user/token.js +73 -0
  213. package/test/routes/user/user.js +157 -0
  214. package/test/rules/notifications.js +410 -0
  215. package/test/rules/payments-carts.js +371 -0
  216. package/test/rules/user.js +396 -0
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Test: Payment Journey - Refund Webhook
3
+ * Simulates: basic → paid active → pending cancel → charge.refunded webhook → payment-refunded transition
4
+ *
5
+ * Verifies that refund webhook events:
6
+ * 1. Flow through the pipeline correctly
7
+ * 2. Trigger the payment-refunded transition (not subscription-cancelled)
8
+ * 3. Extract refundDetails via the processor library's getRefundDetails()
9
+ * 4. Record the transition name on the webhook doc for auditing
10
+ *
11
+ * Product-agnostic: resolves the first paid product from config.payment.products
12
+ */
13
+ module.exports = {
14
+ description: 'Payment journey: paid → refund webhook → payment-refunded transition',
15
+ type: 'suite',
16
+ timeout: 30000,
17
+
18
+ tests: [
19
+ {
20
+ name: 'setup-paid-subscription',
21
+ async run({ accounts, firestore, assert, state, config, http, waitFor, skip, payments }) {
22
+ const uid = accounts['journey-payments-refund-webhook'].uid;
23
+
24
+ // Resolve a paid product with a monthly price. If the brand has none configured,
25
+ // skip the entire journey — this is a config-gap, not a code failure.
26
+ const paidProduct = config.payment.products.find(p => p.id !== 'basic' && p.prices?.monthly);
27
+ if (!paidProduct) {
28
+ skip('No paid product with monthly price configured in this brand');
29
+ }
30
+
31
+ state.uid = uid;
32
+ state.paidProductId = paidProduct.id;
33
+ state.product = payments.products[paidProduct.id];
34
+ // Create subscription via test intent
35
+ const response = await http.as('journey-payments-refund-webhook').post('backend-manager/payments/intent', {
36
+ processor: 'test',
37
+ productId: paidProduct.id,
38
+ frequency: state.product.frequency,
39
+ });
40
+ assert.isSuccess(response, 'Intent should succeed');
41
+ state.orderId = response.data.orderId;
42
+
43
+ // Wait for subscription to activate
44
+ await waitFor(async () => {
45
+ const userDoc = await firestore.get(`users/${uid}`);
46
+ return userDoc?.subscription?.product?.id === paidProduct.id
47
+ && userDoc?.subscription?.status === 'active';
48
+ }, 15000, 500);
49
+
50
+ const userDoc = await firestore.get(`users/${uid}`);
51
+ assert.equal(userDoc.subscription?.product?.id, paidProduct.id, `Should be ${paidProduct.id}`);
52
+ assert.equal(userDoc.subscription?.status, 'active', 'Should be active');
53
+
54
+ state.subscriptionId = userDoc.subscription.payment.resourceId;
55
+ },
56
+ },
57
+
58
+ {
59
+ name: 'send-pending-cancel-webhook',
60
+ async run({ http, assert, state, config, payments }) {
61
+ const futureDate = new Date();
62
+ futureDate.setMonth(futureDate.getMonth() + 1);
63
+
64
+ state.cancelEventId = `_test-evt-journey-refund-cancel-${Date.now()}`;
65
+
66
+ const response = await http.as('none').post(`backend-manager/payments/webhook?processor=test&key=${config.backendManagerWebhookKey}`, {
67
+ id: state.cancelEventId,
68
+ type: 'customer.subscription.updated',
69
+ data: {
70
+ object: {
71
+ id: state.subscriptionId,
72
+ object: 'subscription',
73
+ status: 'active',
74
+ metadata: { uid: state.uid, orderId: state.orderId },
75
+ cancel_at_period_end: true,
76
+ cancel_at: Math.floor(futureDate.getTime() / 1000),
77
+ canceled_at: null,
78
+ current_period_end: Math.floor(futureDate.getTime() / 1000),
79
+ current_period_start: Math.floor(Date.now() / 1000),
80
+ start_date: Math.floor(Date.now() / 1000) - 86400 * 30,
81
+ trial_start: null,
82
+ trial_end: null,
83
+ plan: { product: payments.stripeProductIds[state.paidProductId], interval: state.product.interval },
84
+ },
85
+ },
86
+ });
87
+
88
+ assert.isSuccess(response, 'Cancel webhook should be accepted');
89
+ },
90
+ },
91
+
92
+ {
93
+ name: 'cancellation-pending-confirmed',
94
+ async run({ firestore, assert, state, waitFor }) {
95
+ await waitFor(async () => {
96
+ const doc = await firestore.get(`payments-webhooks/${state.cancelEventId}`);
97
+ return doc?.status === 'completed';
98
+ }, 15000, 500);
99
+
100
+ const webhookDoc = await firestore.get(`payments-webhooks/${state.cancelEventId}`);
101
+ assert.equal(webhookDoc.transition, 'cancellation-requested', 'Should detect cancellation-requested');
102
+
103
+ const userDoc = await firestore.get(`users/${state.uid}`);
104
+ assert.equal(userDoc.subscription.status, 'active', 'Status should still be active');
105
+ assert.equal(userDoc.subscription.cancellation.pending, true, 'Cancellation should be pending');
106
+ },
107
+ },
108
+
109
+ {
110
+ name: 'send-charge-refunded-webhook',
111
+ async run({ http, assert, state, config }) {
112
+ // Simulate a charge.refunded event (Stripe-shaped, used by test processor)
113
+ // This carries refund amount data that getRefundDetails() extracts
114
+ state.refundEventId = `_test-evt-journey-refund-charge-${Date.now()}`;
115
+ state.refundAmountCents = 2800; // $28.00
116
+
117
+ const response = await http.as('none').post(`backend-manager/payments/webhook?processor=test&key=${config.backendManagerWebhookKey}`, {
118
+ id: state.refundEventId,
119
+ type: 'charge.refunded',
120
+ data: {
121
+ object: {
122
+ id: `ch_test_${Date.now()}`,
123
+ object: 'charge',
124
+ amount: state.refundAmountCents,
125
+ amount_refunded: state.refundAmountCents,
126
+ currency: 'usd',
127
+ subscription: state.subscriptionId,
128
+ metadata: { uid: state.uid, orderId: state.orderId },
129
+ refunds: {
130
+ data: [
131
+ {
132
+ id: `re_test_${Date.now()}`,
133
+ amount: state.refundAmountCents,
134
+ currency: 'usd',
135
+ reason: 'requested_by_customer',
136
+ },
137
+ ],
138
+ },
139
+ },
140
+ },
141
+ });
142
+
143
+ assert.isSuccess(response, 'Refund webhook should be accepted');
144
+ },
145
+ },
146
+
147
+ {
148
+ name: 'payment-refunded-transition-detected',
149
+ async run({ firestore, assert, state, waitFor }) {
150
+ // Wait for the refund webhook to be processed
151
+ await waitFor(async () => {
152
+ const doc = await firestore.get(`payments-webhooks/${state.refundEventId}`);
153
+ return doc?.status === 'completed';
154
+ }, 15000, 500);
155
+
156
+ const webhookDoc = await firestore.get(`payments-webhooks/${state.refundEventId}`);
157
+
158
+ // Core assertion: refund events trigger payment-refunded, not subscription-cancelled
159
+ assert.equal(webhookDoc.status, 'completed', 'Webhook should complete successfully');
160
+ assert.equal(webhookDoc.transition, 'payment-refunded', 'Transition should be payment-refunded (not subscription-cancelled)');
161
+ assert.equal(webhookDoc.owner, state.uid, 'Owner should match');
162
+ assert.equal(webhookDoc.orderId, state.orderId, 'Order ID should match');
163
+ },
164
+ },
165
+
166
+ {
167
+ name: 'order-doc-updated',
168
+ async run({ firestore, assert, state }) {
169
+ const orderDoc = await firestore.get(`payments-orders/${state.orderId}`);
170
+
171
+ assert.ok(orderDoc, 'Order doc should exist');
172
+ assert.equal(orderDoc.type, 'subscription', 'Type should be subscription');
173
+ assert.equal(orderDoc.owner, state.uid, 'Owner should match');
174
+
175
+ // The order was last updated by the refund webhook event
176
+ assert.equal(orderDoc.metadata?.updatedBy?.event?.name, 'charge.refunded', 'Last event should be charge.refunded');
177
+ },
178
+ },
179
+ ],
180
+ };
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Test: Payment Journey - Suspend & Recover
3
+ * Simulates: paid active → payment fails → suspended → payment succeeds → active again
4
+ *
5
+ * Uses test intent for initial subscription, then manual webhooks for suspend/recover
6
+ * Product-agnostic: resolves the first paid product from config.payment.products
7
+ */
8
+ module.exports = {
9
+ description: 'Payment journey: paid → suspended → recovered via test processor',
10
+ type: 'suite',
11
+ timeout: 30000,
12
+
13
+ tests: [
14
+ {
15
+ name: 'setup-paid-subscription',
16
+ async run({ accounts, firestore, assert, state, config, http, waitFor, skip, payments }) {
17
+ const uid = accounts['journey-payments-suspend'].uid;
18
+
19
+ // Resolve first paid product from config. If the brand has none configured,
20
+ // skip the entire journey — this is a config-gap, not a code failure.
21
+ const paidProduct = config.payment.products.find(p => p.id !== 'basic' && p.prices);
22
+ if (!paidProduct) {
23
+ skip('No paid product configured in this brand');
24
+ }
25
+
26
+ state.uid = uid;
27
+ state.paidProductId = paidProduct.id;
28
+ state.product = payments.products[paidProduct.id];
29
+
30
+ state.paidProductName = paidProduct.name;
31
+
32
+ // Create subscription via test intent
33
+ const response = await http.as('journey-payments-suspend').post('backend-manager/payments/intent', {
34
+ processor: 'test',
35
+ productId: paidProduct.id,
36
+ frequency: state.product.frequency,
37
+ });
38
+ assert.isSuccess(response, 'Intent should succeed');
39
+ state.orderId = response.data.orderId;
40
+
41
+ // Wait for subscription to activate
42
+ await waitFor(async () => {
43
+ const userDoc = await firestore.get(`users/${uid}`);
44
+ return userDoc?.subscription?.product?.id === paidProduct.id;
45
+ }, 15000, 500);
46
+
47
+ const userDoc = await firestore.get(`users/${uid}`);
48
+ assert.equal(userDoc.subscription?.product?.id, paidProduct.id, `Should start as ${paidProduct.id}`);
49
+ assert.equal(userDoc.subscription?.status, 'active', 'Should be active');
50
+ assert.equal(userDoc.subscription?.payment?.orderId, state.orderId, 'Order ID should match intent');
51
+
52
+ state.subscriptionId = userDoc.subscription.payment.resourceId;
53
+ },
54
+ },
55
+
56
+ {
57
+ name: 'send-past-due-webhook',
58
+ async run({ http, assert, state, config, payments }) {
59
+ state.eventId1 = `_test-evt-journey-suspend-fail-${Date.now()}`;
60
+
61
+ const response = await http.as('none').post(`backend-manager/payments/webhook?processor=test&key=${config.backendManagerWebhookKey}`, {
62
+ id: state.eventId1,
63
+ type: 'customer.subscription.updated',
64
+ data: {
65
+ object: {
66
+ id: state.subscriptionId,
67
+ object: 'subscription',
68
+ status: 'past_due',
69
+ metadata: { uid: state.uid, orderId: state.orderId },
70
+ cancel_at_period_end: false,
71
+ canceled_at: null,
72
+ current_period_end: Math.floor(Date.now() / 1000) + 86400,
73
+ current_period_start: Math.floor(Date.now() / 1000) - 86400 * 29,
74
+ start_date: Math.floor(Date.now() / 1000) - 86400 * 60,
75
+ trial_start: null,
76
+ trial_end: null,
77
+ plan: { product: payments.stripeProductIds[state.paidProductId], interval: state.product.interval },
78
+ },
79
+ },
80
+ });
81
+
82
+ assert.isSuccess(response, 'Webhook should be accepted');
83
+ },
84
+ },
85
+
86
+ {
87
+ name: 'subscription-suspended',
88
+ async run({ firestore, assert, state, waitFor }) {
89
+ await waitFor(async () => {
90
+ const doc = await firestore.get(`payments-webhooks/${state.eventId1}`);
91
+ return doc?.status === 'completed';
92
+ }, 15000, 500);
93
+
94
+ const webhookDoc = await firestore.get(`payments-webhooks/${state.eventId1}`);
95
+ assert.equal(webhookDoc.transition, 'payment-failed', 'Transition should be payment-failed');
96
+
97
+ const userDoc = await firestore.get(`users/${state.uid}`);
98
+
99
+ assert.equal(userDoc.subscription.status, 'suspended', 'Status should be suspended');
100
+ assert.equal(userDoc.subscription.product.id, state.paidProductId, `Product should still be ${state.paidProductId}`);
101
+ },
102
+ },
103
+
104
+ {
105
+ name: 'send-recovery-webhook',
106
+ async run({ http, assert, state, config, payments }) {
107
+ const futureDate = new Date();
108
+ futureDate.setMonth(futureDate.getMonth() + 1);
109
+
110
+ state.eventId2 = `_test-evt-journey-suspend-recover-${Date.now()}`;
111
+
112
+ const response = await http.as('none').post(`backend-manager/payments/webhook?processor=test&key=${config.backendManagerWebhookKey}`, {
113
+ id: state.eventId2,
114
+ type: 'customer.subscription.updated',
115
+ data: {
116
+ object: {
117
+ id: state.subscriptionId,
118
+ object: 'subscription',
119
+ status: 'active',
120
+ metadata: { uid: state.uid, orderId: state.orderId },
121
+ cancel_at_period_end: false,
122
+ canceled_at: null,
123
+ current_period_end: Math.floor(futureDate.getTime() / 1000),
124
+ current_period_start: Math.floor(Date.now() / 1000),
125
+ start_date: Math.floor(Date.now() / 1000) - 86400 * 60,
126
+ trial_start: null,
127
+ trial_end: null,
128
+ plan: { product: payments.stripeProductIds[state.paidProductId], interval: state.product.interval },
129
+ },
130
+ },
131
+ });
132
+
133
+ assert.isSuccess(response, 'Webhook should be accepted');
134
+ },
135
+ },
136
+
137
+ {
138
+ name: 'subscription-recovered',
139
+ async run({ firestore, assert, state, waitFor }) {
140
+ await waitFor(async () => {
141
+ const doc = await firestore.get(`payments-webhooks/${state.eventId2}`);
142
+ return doc?.status === 'completed';
143
+ }, 15000, 500);
144
+
145
+ const webhookDoc = await firestore.get(`payments-webhooks/${state.eventId2}`);
146
+ assert.equal(webhookDoc.transition, 'payment-recovered', 'Transition should be payment-recovered');
147
+
148
+ const userDoc = await firestore.get(`users/${state.uid}`);
149
+
150
+ assert.equal(userDoc.subscription.status, 'active', 'Status should be active again');
151
+ assert.equal(userDoc.subscription.product.id, state.paidProductId, `Product should still be ${state.paidProductId}`);
152
+ },
153
+ },
154
+
155
+ {
156
+ name: 'order-doc-verified',
157
+ async run({ firestore, assert, state }) {
158
+ const orderDoc = await firestore.get(`payments-orders/${state.orderId}`);
159
+
160
+ assert.ok(orderDoc, 'Order doc should exist');
161
+ assert.equal(orderDoc.type, 'subscription', 'Type should be subscription');
162
+ assert.equal(orderDoc.owner, state.uid, 'Owner should match');
163
+ assert.ok(orderDoc.requests !== undefined, 'requests field should exist');
164
+ assert.equal(orderDoc.requests.cancellation, null, 'requests.cancellation should be null');
165
+ assert.equal(orderDoc.requests.refund, null, 'requests.refund should be null');
166
+ },
167
+ },
168
+
169
+ {
170
+ name: 'intent-doc-completed',
171
+ async run({ firestore, assert, state }) {
172
+ const intentDoc = await firestore.get(`payments-intents/${state.orderId}`);
173
+
174
+ assert.ok(intentDoc, 'Intent doc should exist');
175
+ assert.equal(intentDoc.id, state.orderId, 'ID should match orderId');
176
+ assert.equal(intentDoc.status, 'completed', 'Intent status should be completed after webhook processing');
177
+ assert.ok(intentDoc.metadata?.completed?.timestampUNIX > 0, 'Completed timestamp should be set');
178
+ },
179
+ },
180
+ ],
181
+ };
@@ -0,0 +1,130 @@
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, skip, payments }) {
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. If the brand has none
28
+ // configured, skip the entire journey — this is a config-gap, not a code failure.
29
+ const trialProduct = config.payment.products.find(p => p.id !== 'basic' && p.prices && p.trial?.days);
30
+ if (!trialProduct) {
31
+ skip('No paid product with trial configured in this brand');
32
+ }
33
+
34
+ state.uid = uid;
35
+ state.paidProductId = trialProduct.id;
36
+ state.paidProductName = trialProduct.name;
37
+ state.product = payments.products[trialProduct.id];
38
+ },
39
+ },
40
+
41
+ {
42
+ name: 'create-trial-intent',
43
+ async run({ http, assert, state }) {
44
+ const response = await http.as('journey-payments-trial-cancel').post('backend-manager/payments/intent', {
45
+ processor: 'test',
46
+ productId: state.paidProductId,
47
+ frequency: state.product.frequency,
48
+ trial: true,
49
+ });
50
+
51
+ assert.isSuccess(response, 'Intent should succeed');
52
+ assert.ok(response.data.id, 'Should return intent ID');
53
+ assert.ok(response.data.orderId, 'Should return orderId');
54
+
55
+ state.intentId = response.data.id;
56
+ state.orderId = response.data.orderId;
57
+ state.eventId = response.data.id.replace('_test-cs-', '_test-evt-');
58
+ },
59
+ },
60
+
61
+ {
62
+ name: 'trial-activated',
63
+ async run({ firestore, assert, state, waitFor }) {
64
+ await waitFor(async () => {
65
+ const userDoc = await firestore.get(`users/${state.uid}`);
66
+ return userDoc?.subscription?.trial?.claimed === true;
67
+ }, 15000, 500);
68
+
69
+ const userDoc = await firestore.get(`users/${state.uid}`);
70
+
71
+ assert.equal(userDoc.subscription.product.id, state.paidProductId, `Product should be ${state.paidProductId}`);
72
+ assert.equal(userDoc.subscription.status, 'active', 'Status should be active');
73
+ assert.equal(userDoc.subscription.trial.claimed, true, 'Trial should be claimed');
74
+ assert.equal(userDoc.subscription.trial.expires.timestampUNIX, userDoc.subscription.expires.timestampUNIX, 'Trial expires should match subscription expires (still in trial period)');
75
+
76
+ state.subscriptionId = userDoc.subscription.payment.resourceId;
77
+ },
78
+ },
79
+
80
+ {
81
+ name: 'cancel-during-trial',
82
+ async run({ http, assert }) {
83
+ // Cancel via endpoint — test processor should detect trial and simulate immediate cancel.
84
+ // skipGuards bypasses the 24-hour subscription-age guard.
85
+ const response = await http.as('journey-payments-trial-cancel').post('backend-manager/payments/cancel', {
86
+ confirmed: true,
87
+ reason: 'Changed my mind during trial',
88
+ feedback: 'Testing trial cancellation',
89
+ skipGuards: true,
90
+ });
91
+
92
+ assert.isSuccess(response, 'Cancel endpoint should succeed');
93
+ assert.equal(response.data.success, true, 'Should return { success: true }');
94
+ },
95
+ },
96
+
97
+ {
98
+ name: 'verify-immediate-cancellation',
99
+ async run({ firestore, assert, state, waitFor }) {
100
+ // Poll until subscription is cancelled (NOT just pending)
101
+ await waitFor(async () => {
102
+ const userDoc = await firestore.get(`users/${state.uid}`);
103
+ return userDoc?.subscription?.status === 'cancelled';
104
+ }, 15000, 500);
105
+
106
+ const userDoc = await firestore.get(`users/${state.uid}`);
107
+
108
+ // During trial cancel: subscription should be immediately cancelled, not pending
109
+ assert.equal(userDoc.subscription.status, 'cancelled', 'Status should be cancelled (not active with pending)');
110
+ assert.equal(userDoc.subscription.cancellation.pending, false, 'Should NOT be pending — should be fully cancelled');
111
+ assert.equal(userDoc.subscription.product.id, state.paidProductId, `Product should still be ${state.paidProductId}`);
112
+ },
113
+ },
114
+
115
+ {
116
+ name: 'cancellation-request-stored',
117
+ async run({ firestore, assert, state }) {
118
+ const orderDoc = await firestore.get(`payments-orders/${state.orderId}`);
119
+
120
+ assert.ok(orderDoc, 'Order doc should exist');
121
+ assert.ok(orderDoc.requests, 'requests field should exist');
122
+ assert.ok(orderDoc.requests.cancellation, 'requests.cancellation should be populated');
123
+ assert.equal(orderDoc.requests.cancellation.reason, 'Changed my mind during trial', 'Cancellation reason should match');
124
+ assert.equal(orderDoc.requests.cancellation.feedback, 'Testing trial cancellation', 'Cancellation feedback should match');
125
+ assert.ok(orderDoc.requests.cancellation.date.timestampUNIX > 0, 'Cancellation date should be set');
126
+ assert.equal(orderDoc.requests.refund, null, 'requests.refund should still be null');
127
+ },
128
+ },
129
+ ],
130
+ };
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Test: Payment Journey - Trial
3
+ * Simulates: basic user → trial activation via test intent → trial ends → active paid
4
+ *
5
+ * Uses the test processor for initial trial, then manual webhook for trial-to-active
6
+ * Product-agnostic: resolves the first paid product from config.payment.products
7
+ */
8
+ module.exports = {
9
+ description: 'Payment journey: basic → trial → active paid via test processor',
10
+ type: 'suite',
11
+ timeout: 30000,
12
+
13
+ tests: [
14
+ {
15
+ name: 'verify-starts-as-basic',
16
+ async run({ accounts, firestore, assert, state, config, skip, payments }) {
17
+ const uid = accounts['journey-payments-trial'].uid;
18
+ const userDoc = await firestore.get(`users/${uid}`);
19
+
20
+ assert.ok(userDoc, 'User doc should exist');
21
+ assert.equal(userDoc.subscription?.product?.id, 'basic', 'Should start as basic');
22
+ assert.equal(userDoc.subscription?.trial?.claimed, false, 'Trial should not be claimed');
23
+
24
+ // Resolve first paid product WITH a trial from config. The test processor
25
+ // only creates a trialing subscription when product.trial.days > 0, so a
26
+ // brand whose paid products all have trial.days: 0 (e.g. trials disabled)
27
+ // has nothing to exercise here — skip the journey. This is a config-gap,
28
+ // not a code failure, and mirrors journey-payments-trial-cancel.js.
29
+ const paidProduct = config.payment.products.find(p => p.id !== 'basic' && p.prices && p.trial?.days);
30
+ if (!paidProduct) {
31
+ skip('No paid product with trial configured in this brand');
32
+ }
33
+
34
+ state.uid = uid;
35
+ state.paidProductId = paidProduct.id;
36
+ state.product = payments.products[paidProduct.id];
37
+ },
38
+ },
39
+
40
+ {
41
+ name: 'create-trial-intent',
42
+ async run({ http, assert, state }) {
43
+ const response = await http.as('journey-payments-trial').post('backend-manager/payments/intent', {
44
+ processor: 'test',
45
+ productId: state.paidProductId,
46
+ frequency: state.product.frequency,
47
+ trial: true,
48
+ });
49
+
50
+ assert.isSuccess(response, 'Intent should succeed');
51
+ assert.ok(response.data.id, 'Should return intent ID');
52
+ assert.ok(response.data.orderId, 'Should return orderId');
53
+
54
+ state.intentId = response.data.id;
55
+ state.orderId = response.data.orderId;
56
+
57
+ // Derive webhook event ID from intent ID (same timestamp)
58
+ state.eventId = response.data.id.replace('_test-cs-', '_test-evt-');
59
+ },
60
+ },
61
+
62
+ {
63
+ name: 'trial-activated',
64
+ async run({ firestore, assert, state, waitFor }) {
65
+ // Poll until trial subscription appears
66
+ await waitFor(async () => {
67
+ const userDoc = await firestore.get(`users/${state.uid}`);
68
+ return userDoc?.subscription?.trial?.claimed === true;
69
+ }, 15000, 500);
70
+
71
+ const userDoc = await firestore.get(`users/${state.uid}`);
72
+
73
+ assert.equal(userDoc.subscription.product.id, state.paidProductId, `Product should be ${state.paidProductId}`);
74
+ assert.equal(userDoc.subscription.status, 'active', 'Status should be active');
75
+ assert.equal(userDoc.subscription.trial.claimed, true, 'Trial should be claimed');
76
+ assert.equal(userDoc.subscription.payment.orderId, state.orderId, 'Order ID should match intent');
77
+
78
+ state.subscriptionId = userDoc.subscription.payment.resourceId;
79
+
80
+ // Verify the auto-fired webhook triggered new-subscription (trial is a property, not a separate transition)
81
+ const webhookDoc = await firestore.get(`payments-webhooks/${state.eventId}`);
82
+ assert.ok(webhookDoc, 'Webhook doc should exist');
83
+ assert.equal(webhookDoc.transition, 'new-subscription', 'Transition should be new-subscription (trial detected inside handler)');
84
+ assert.equal(webhookDoc.orderId, state.orderId, 'Webhook doc orderId should match intent');
85
+ },
86
+ },
87
+
88
+ {
89
+ name: 'intent-doc-completed',
90
+ async run({ firestore, assert, state }) {
91
+ const intentDoc = await firestore.get(`payments-intents/${state.orderId}`);
92
+
93
+ assert.ok(intentDoc, 'Intent doc should exist');
94
+ assert.equal(intentDoc.id, state.orderId, 'ID should match orderId');
95
+ assert.equal(intentDoc.status, 'completed', 'Intent status should be completed after webhook processing');
96
+ assert.ok(intentDoc.metadata?.completed?.timestampUNIX > 0, 'Completed timestamp should be set');
97
+ },
98
+ },
99
+
100
+ {
101
+ name: 'order-doc-created',
102
+ async run({ firestore, assert, state }) {
103
+ const orderDoc = await firestore.get(`payments-orders/${state.orderId}`);
104
+
105
+ assert.ok(orderDoc, 'Order doc should exist');
106
+ assert.equal(orderDoc.id, state.orderId, 'ID should match orderId');
107
+ assert.equal(orderDoc.type, 'subscription', 'Type should be subscription');
108
+ assert.equal(orderDoc.owner, state.uid, 'Owner should match');
109
+ assert.equal(orderDoc.unified.product.id, state.paidProductId, `Product should be ${state.paidProductId}`);
110
+ assert.equal(orderDoc.unified.trial.claimed, true, 'Trial should be claimed');
111
+ assert.ok(orderDoc.requests !== undefined, 'requests field should exist');
112
+ assert.equal(orderDoc.requests.cancellation, null, 'requests.cancellation should be null');
113
+ assert.equal(orderDoc.requests.refund, null, 'requests.refund should be null');
114
+ },
115
+ },
116
+
117
+ {
118
+ name: 'send-trial-to-active-webhook',
119
+ async run({ http, assert, state, config, payments }) {
120
+ const futureDate = new Date();
121
+ futureDate.setMonth(futureDate.getMonth() + 1);
122
+
123
+ state.eventId2 = `_test-evt-journey-trial-active-${Date.now()}`;
124
+
125
+ const response = await http.as('none').post(`backend-manager/payments/webhook?processor=test&key=${config.backendManagerWebhookKey}`, {
126
+ id: state.eventId2,
127
+ type: 'customer.subscription.updated',
128
+ data: {
129
+ object: {
130
+ id: state.subscriptionId,
131
+ object: 'subscription',
132
+ status: 'active',
133
+ metadata: { uid: state.uid, orderId: state.orderId },
134
+ cancel_at_period_end: false,
135
+ canceled_at: null,
136
+ current_period_end: Math.floor(futureDate.getTime() / 1000),
137
+ current_period_start: Math.floor(Date.now() / 1000),
138
+ start_date: Math.floor(Date.now() / 1000) - 86400 * 14,
139
+ trial_start: Math.floor(Date.now() / 1000) - 86400 * 14,
140
+ trial_end: Math.floor(Date.now() / 1000),
141
+ plan: { product: payments.stripeProductIds[state.paidProductId], interval: state.product.interval },
142
+ },
143
+ },
144
+ });
145
+
146
+ assert.isSuccess(response, 'Webhook should be accepted');
147
+ },
148
+ },
149
+
150
+ {
151
+ name: 'trial-transitioned-to-active',
152
+ async run({ firestore, assert, state, waitFor }) {
153
+ await waitFor(async () => {
154
+ const doc = await firestore.get(`payments-webhooks/${state.eventId2}`);
155
+ return doc?.status === 'completed';
156
+ }, 15000, 500);
157
+
158
+ // Trial → active paid is the same status/product, so no transition fires
159
+ const webhookDoc = await firestore.get(`payments-webhooks/${state.eventId2}`);
160
+ assert.equal(webhookDoc.transition, null, 'No transition (same status/product, trial already claimed)');
161
+
162
+ const userDoc = await firestore.get(`users/${state.uid}`);
163
+
164
+ assert.equal(userDoc.subscription.product.id, state.paidProductId, `Product should be ${state.paidProductId}`);
165
+ assert.equal(userDoc.subscription.status, 'active', 'Status should be active');
166
+ assert.equal(userDoc.subscription.trial.claimed, true, 'Trial should remain claimed (historical)');
167
+ assert.equal(userDoc.subscription.payment.frequency, state.product.frequency, `Frequency should be ${state.product.frequency}`);
168
+ },
169
+ },
170
+ ],
171
+ };