@appweaver/payments 0.0.0-stage → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +212 -2
  3. package/config.d.ts +77 -0
  4. package/config.js +118 -0
  5. package/gateway/fake-gateway.d.ts +144 -0
  6. package/gateway/fake-gateway.js +805 -0
  7. package/gateway/gateway-registry.d.ts +99 -0
  8. package/gateway/gateway-registry.js +275 -0
  9. package/gateway/payment-gateway.d.ts +68 -0
  10. package/gateway/payment-gateway.js +82 -0
  11. package/index.d.ts +16 -0
  12. package/index.js +51 -0
  13. package/locales/en.json +47 -0
  14. package/maintenance/payment-maintenance-jobs.d.ts +5 -0
  15. package/maintenance/payment-maintenance-jobs.js +38 -0
  16. package/module.d.ts +8 -0
  17. package/module.js +85 -0
  18. package/package.json +67 -3
  19. package/resources/model-util.d.ts +40 -0
  20. package/resources/model-util.js +30 -0
  21. package/resources/payment/model.d.ts +2 -0
  22. package/resources/payment/model.js +106 -0
  23. package/resources/payment-customer/model.d.ts +2 -0
  24. package/resources/payment-customer/model.js +53 -0
  25. package/resources/payment-event/model.d.ts +2 -0
  26. package/resources/payment-event/model.js +31 -0
  27. package/resources/payment-invoice/model.d.ts +2 -0
  28. package/resources/payment-invoice/model.js +55 -0
  29. package/resources/payment-method/model.d.ts +2 -0
  30. package/resources/payment-method/model.js +37 -0
  31. package/resources/payment-plan/model.d.ts +2 -0
  32. package/resources/payment-plan/model.js +37 -0
  33. package/resources/payment-subscription/model.d.ts +2 -0
  34. package/resources/payment-subscription/model.js +82 -0
  35. package/resources/payment-transaction/model.d.ts +2 -0
  36. package/resources/payment-transaction/model.js +43 -0
  37. package/resources/payment-webhook-event/model.d.ts +2 -0
  38. package/resources/payment-webhook-event/model.js +32 -0
  39. package/resources/policies.d.ts +15 -0
  40. package/resources/policies.js +36 -0
  41. package/resources/services.d.ts +6 -0
  42. package/resources/services.js +19 -0
  43. package/resources/subscriptions.d.ts +9 -0
  44. package/resources/subscriptions.js +30 -0
  45. package/resources.d.ts +8 -0
  46. package/resources.js +34 -0
  47. package/service/payment-emails.d.ts +12 -0
  48. package/service/payment-emails.js +145 -0
  49. package/service/payment-events.d.ts +90 -0
  50. package/service/payment-events.js +472 -0
  51. package/service/payment-handlers.d.ts +26 -0
  52. package/service/payment-handlers.js +42 -0
  53. package/service/payment-store.d.ts +50 -0
  54. package/service/payment-store.js +95 -0
  55. package/service/payment-sync.d.ts +113 -0
  56. package/service/payment-sync.js +745 -0
  57. package/service/payments-service.d.ts +307 -0
  58. package/service/payments-service.js +747 -0
  59. package/service/subscriptions-service.d.ts +178 -0
  60. package/service/subscriptions-service.js +433 -0
  61. package/tasks/payments-replay.d.ts +10 -0
  62. package/tasks/payments-replay.js +36 -0
  63. package/tasks/payments-sync-plans.d.ts +10 -0
  64. package/tasks/payments-sync-plans.js +24 -0
  65. package/templates/emails/payment-action-required.html.hbs +28 -0
  66. package/templates/emails/payment-action-required.subject.hbs +1 -0
  67. package/templates/emails/payment-failed.html.hbs +37 -0
  68. package/templates/emails/payment-failed.subject.hbs +1 -0
  69. package/templates/emails/payment-receipt.html.hbs +45 -0
  70. package/templates/emails/payment-receipt.subject.hbs +1 -0
  71. package/templates/emails/payment-refunded.html.hbs +37 -0
  72. package/templates/emails/payment-refunded.subject.hbs +1 -0
  73. package/templates/emails/subscription-canceled.html.hbs +24 -0
  74. package/templates/emails/subscription-canceled.subject.hbs +1 -0
  75. package/templates/emails/subscription-trial-ending.html.hbs +25 -0
  76. package/templates/emails/subscription-trial-ending.subject.hbs +1 -0
  77. package/templates/layouts/email.html.hbs +36 -0
  78. package/templates/partials/email-button.html.hbs +15 -0
  79. package/tsconfig.build.tsbuildinfo +1 -0
  80. package/types.d.ts +488 -0
  81. package/types.js +2 -0
  82. package/utils/money-util.d.ts +61 -0
  83. package/utils/money-util.js +124 -0
  84. package/utils/status-util.d.ts +29 -0
  85. package/utils/status-util.js +93 -0
  86. package/utils/telemetry.d.ts +16 -0
  87. package/utils/telemetry.js +69 -0
  88. package/web/payment-routes.d.ts +7 -0
  89. package/web/payment-routes.js +410 -0
  90. package/web/payment-schemas.d.ts +70 -0
  91. package/web/payment-schemas.js +101 -0
@@ -0,0 +1,178 @@
1
+ import { PaymentInvoiceRecord, PaymentMetadata, PaymentNextAction, PaymentPlanRecord, PaymentSubscriptionRecord } from '../types';
2
+ import { PaymentCustomerInput } from './payments-service';
3
+ export type SubscribeInput = PaymentCustomerInput & {
4
+ /** The key of the plan */
5
+ plan: string;
6
+ quantity?: number;
7
+ /** The days of the trial. Default: the ones of the plan. */
8
+ trialDays?: number;
9
+ /** The ID of a saved payment method to charge. Default: the default one of the customer. */
10
+ paymentMethodId?: string;
11
+ metadata?: PaymentMetadata;
12
+ };
13
+ export type SubscriptionCheckoutInput = Omit<SubscribeInput, 'paymentMethodId'> & {
14
+ /** Where the customer lands once they subscribed. Default: `payments.successUrl`. */
15
+ successUrl?: string;
16
+ /** Where the customer lands when leaving the page. Default: `payments.cancelUrl`. */
17
+ cancelUrl?: string;
18
+ };
19
+ /** A subscription with what its client does next: nothing, confirm its first payment, or follow a redirect. */
20
+ export type SubscriptionResult = {
21
+ subscription: PaymentSubscriptionRecord;
22
+ nextAction: PaymentNextAction;
23
+ };
24
+ export type ChangePlanOptions = {
25
+ quantity?: number;
26
+ /** Charge or credit the difference for the rest of the period. Default: `payments.subscriptions.prorate`. */
27
+ prorate?: boolean;
28
+ };
29
+ /**
30
+ * The recurring payments: the plans, synchronized from the recurring prices of the gateways, and the subscriptions
31
+ * of the users to them. The gateway renews a subscription and retries a failed renewal on its own; its webhooks
32
+ * move the records, announced as `subscription.*` and `invoice.*` events. With `payments.subscriptions.enabled` off
33
+ * every call but `createPortalSession` fails with `PAYMENT_SUBSCRIPTIONS_DISABLED`.
34
+ *
35
+ * @example
36
+ * const subscriptions = inject(SubscriptionsService);
37
+ * const { subscription, nextAction } = await subscriptions.subscribe({
38
+ * userId: user.id,
39
+ * email: user.email,
40
+ * plan: 'pro-monthly'
41
+ * });
42
+ * if (await subscriptions.isActive(user.id, 'pro-monthly')) { ... }
43
+ */
44
+ export declare class SubscriptionsService {
45
+ /**
46
+ * Reads the recurring prices of a gateway into the plans: a price is the plan of its key (its lookup key at the
47
+ * gateway, otherwise its ID), and a price that is gone makes its plan inactive.
48
+ *
49
+ * @param {string} [gateway] - The name of the gateway. Default: every gateway with prices.
50
+ * @return {Promise<PaymentPlanRecord[]>} The plans of the gateways read.
51
+ * @throws {PaymentError} `PAYMENT_SUBSCRIPTIONS_DISABLED` with `payments.subscriptions.enabled` off, as every
52
+ * method reading or writing a plan, a subscription or an invoice.
53
+ */
54
+ syncPlans(gateway?: string): Promise<PaymentPlanRecord[]>;
55
+ /**
56
+ * Lists the plans users can subscribe to.
57
+ *
58
+ * @param {string} [gateway] - The name of a gateway. Default: the plans of every gateway.
59
+ * @return {Promise<PaymentPlanRecord[]>} The active plans, the cheapest first.
60
+ */
61
+ listPlans(gateway?: string): Promise<PaymentPlanRecord[]>;
62
+ /**
63
+ * Returns the plan of a key at a gateway.
64
+ *
65
+ * @param {string} key - The key of the plan.
66
+ * @param {string} gateway - The name of the gateway.
67
+ * @return {Promise<PaymentPlanRecord>} The plan.
68
+ * @throws {PaymentError} `PAYMENT_PLAN_UNKNOWN` for no active plan of the key at the gateway.
69
+ */
70
+ getPlan(key: string, gateway: string): Promise<PaymentPlanRecord>;
71
+ /**
72
+ * Subscribes a user to a plan, charged to a saved payment method. Without one, or when the bank wants the first
73
+ * payment confirmed, the subscription stays `incomplete` until the client confirms the `clientSecret` of the next
74
+ * action.
75
+ *
76
+ * @param {SubscribeInput} input - The user, the plan, and the gateway or the country and currency selecting it.
77
+ * @return {Promise<SubscriptionResult>} The subscription and what its client does next.
78
+ * @throws {PaymentError} `PAYMENT_PLAN_UNKNOWN`, `PAYMENT_METHOD_NOT_FOUND`, `PAYMENT_CAPABILITY_UNSUPPORTED`, or
79
+ * the error of the gateway.
80
+ */
81
+ subscribe(input: SubscribeInput): Promise<SubscriptionResult>;
82
+ /**
83
+ * Starts a subscription on a hosted page of the gateway, where the customer is sent with the `redirect` of the
84
+ * next action and enters their payment method. The subscription starts with the webhook of the completed page.
85
+ *
86
+ * @param {SubscriptionCheckoutInput} input - The user, the plan, and where the customer lands afterwards.
87
+ * @return {Promise<SubscriptionResult>} The subscription, `incomplete`, and the redirect to its page.
88
+ * @throws {PaymentError} `PAYMENT_PLAN_UNKNOWN`, `PAYMENT_CAPABILITY_UNSUPPORTED`, or the error of the gateway.
89
+ */
90
+ createCheckout(input: SubscriptionCheckoutInput): Promise<SubscriptionResult>;
91
+ /**
92
+ * Returns a subscription.
93
+ *
94
+ * @param {string} id - The ID of the subscription.
95
+ * @return {Promise<PaymentSubscriptionRecord>} The subscription.
96
+ * @throws {PaymentError} `PAYMENT_SUBSCRIPTION_NOT_FOUND` for an unknown subscription.
97
+ */
98
+ getSubscription(id: string): Promise<PaymentSubscriptionRecord>;
99
+ /**
100
+ * Finds the subscription of a user that is not canceled, the newest one.
101
+ *
102
+ * @param {string | number} userId - The ID of the user.
103
+ * @param {string} [plan] - The key of a plan. Default: any plan.
104
+ * @return {Promise<PaymentSubscriptionRecord | null>} The subscription, `null` without one.
105
+ */
106
+ findSubscription(userId: string | number, plan?: string): Promise<PaymentSubscriptionRecord | null>;
107
+ /**
108
+ * Tells whether a user has what a subscription pays for: one that is active or in its trial, or one whose renewal
109
+ * failed less than `payments.subscriptions.gracePeriod` ago, while the gateway retries the payment.
110
+ *
111
+ * @param {string | number} userId - The ID of the user.
112
+ * @param {string} [plan] - The key of a plan. Default: any plan.
113
+ * @param {Date} [now] - The current time.
114
+ * @return {Promise<boolean>} `true` with such a subscription.
115
+ */
116
+ isActive(userId: string | number, plan?: string, now?: Date): Promise<boolean>;
117
+ /**
118
+ * Cancels a subscription: with the period the customer paid for, or at once.
119
+ *
120
+ * @param {string} id - The ID of the subscription.
121
+ * @param {boolean} [atPeriodEnd=true] - Keep it until the end of its period, `false` to end it at once.
122
+ * @return {Promise<PaymentSubscriptionRecord>} The subscription.
123
+ * @throws {PaymentError} `PAYMENT_SUBSCRIPTION_NOT_FOUND`, `PAYMENT_INVALID_STATE` for a canceled subscription.
124
+ */
125
+ cancel(id: string, atPeriodEnd?: boolean): Promise<PaymentSubscriptionRecord>;
126
+ /**
127
+ * Keeps a subscription that was canceled with the end of its period.
128
+ *
129
+ * @param {string} id - The ID of the subscription.
130
+ * @return {Promise<PaymentSubscriptionRecord>} The subscription.
131
+ * @throws {PaymentError} `PAYMENT_SUBSCRIPTION_NOT_FOUND`, `PAYMENT_INVALID_STATE` for a subscription that ended.
132
+ */
133
+ resume(id: string): Promise<PaymentSubscriptionRecord>;
134
+ /**
135
+ * Moves a subscription to another plan of its gateway.
136
+ *
137
+ * @param {string} id - The ID of the subscription.
138
+ * @param {string} plan - The key of the new plan.
139
+ * @param {ChangePlanOptions} [options] - The quantity, and whether the difference is charged.
140
+ * @return {Promise<PaymentSubscriptionRecord>} The subscription.
141
+ * @throws {PaymentError} `PAYMENT_SUBSCRIPTION_NOT_FOUND`, `PAYMENT_INVALID_STATE`, `PAYMENT_PLAN_UNKNOWN`.
142
+ */
143
+ changePlan(id: string, plan: string, options?: ChangePlanOptions): Promise<PaymentSubscriptionRecord>;
144
+ /**
145
+ * Reads a subscription from its gateway and applies its state.
146
+ *
147
+ * @param {string} id - The ID of the subscription.
148
+ * @return {Promise<SubscriptionResult>} The subscription and what its client does next.
149
+ * @throws {PaymentError} `PAYMENT_SUBSCRIPTION_NOT_FOUND` for an unknown subscription.
150
+ */
151
+ sync(id: string): Promise<SubscriptionResult>;
152
+ /**
153
+ * Lists the invoices of a subscription, the newest first.
154
+ *
155
+ * @param {string} id - The ID of the subscription.
156
+ * @return {Promise<PaymentInvoiceRecord[]>} The invoices.
157
+ */
158
+ listInvoices(id: string): Promise<PaymentInvoiceRecord[]>;
159
+ /**
160
+ * Creates a session of the page of the gateway where a user manages their payment methods, subscriptions and
161
+ * invoices.
162
+ *
163
+ * @param {PaymentCustomerInput} input - The user, and the gateway or the country and currency selecting it.
164
+ * @param {string} [returnUrl] - Where the page sends the user back. Default: `payments.successUrl`.
165
+ * @return {Promise<string>} The URL of the session.
166
+ * @throws {PaymentError} `PAYMENT_CAPABILITY_UNSUPPORTED` for a gateway without such a page.
167
+ */
168
+ createPortalSession(input: PaymentCustomerInput, returnUrl?: string): Promise<string>;
169
+ /**
170
+ * Reads the subscriptions whose period ended, or that never completed, from their gateways again, catching the
171
+ * webhooks never received, and gives up the ones left `incomplete` longer than `payments.pendingTtl`.
172
+ *
173
+ * @param {Date} now - The current time.
174
+ * @param {number} limit - The most subscriptions to read.
175
+ * @return {Promise<number>} The number of subscriptions read.
176
+ */
177
+ reconcile(now: Date, limit: number): Promise<number>;
178
+ }
@@ -0,0 +1,433 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SubscriptionsService = void 0;
4
+ const common_1 = require("@appweaver/common");
5
+ const core_1 = require("@appweaver/core");
6
+ const config_1 = require("../config");
7
+ const gateway_registry_1 = require("../gateway/gateway-registry");
8
+ const status_util_1 = require("../utils/status-util");
9
+ const payment_events_1 = require("./payment-events");
10
+ const payment_store_1 = require("./payment-store");
11
+ const payment_sync_1 = require("./payment-sync");
12
+ const payments_service_1 = require("./payments-service");
13
+ const logger = (0, common_1.createLogger)('payments');
14
+ /**
15
+ * The recurring payments: the plans, synchronized from the recurring prices of the gateways, and the subscriptions
16
+ * of the users to them. The gateway renews a subscription and retries a failed renewal on its own; its webhooks
17
+ * move the records, announced as `subscription.*` and `invoice.*` events. With `payments.subscriptions.enabled` off
18
+ * every call but `createPortalSession` fails with `PAYMENT_SUBSCRIPTIONS_DISABLED`.
19
+ *
20
+ * @example
21
+ * const subscriptions = inject(SubscriptionsService);
22
+ * const { subscription, nextAction } = await subscriptions.subscribe({
23
+ * userId: user.id,
24
+ * email: user.email,
25
+ * plan: 'pro-monthly'
26
+ * });
27
+ * if (await subscriptions.isActive(user.id, 'pro-monthly')) { ... }
28
+ */
29
+ class SubscriptionsService {
30
+ /** @internal */
31
+ _store = new payment_store_1.PaymentStore();
32
+ /** @internal */
33
+ _sync = new payment_sync_1.PaymentSync(this._store);
34
+ /** @internal */
35
+ _registry = (0, gateway_registry_1.gatewayRegistry)();
36
+ /** @internal */
37
+ _events = (0, core_1.inject)(payment_events_1.PaymentEvents);
38
+ /** @internal */
39
+ _payments = (0, core_1.inject)(payments_service_1.PaymentsService);
40
+ /**
41
+ * Reads the recurring prices of a gateway into the plans: a price is the plan of its key (its lookup key at the
42
+ * gateway, otherwise its ID), and a price that is gone makes its plan inactive.
43
+ *
44
+ * @param {string} [gateway] - The name of the gateway. Default: every gateway with prices.
45
+ * @return {Promise<PaymentPlanRecord[]>} The plans of the gateways read.
46
+ * @throws {PaymentError} `PAYMENT_SUBSCRIPTIONS_DISABLED` with `payments.subscriptions.enabled` off, as every
47
+ * method reading or writing a plan, a subscription or an invoice.
48
+ */
49
+ async syncPlans(gateway) {
50
+ this.enabled();
51
+ const plans = [];
52
+ for (const provider of gateway ? [gateway] : this._registry.names()) {
53
+ const driver = await this._registry.gateway(provider);
54
+ if (!driver.supports('prices')) {
55
+ continue;
56
+ }
57
+ const prices = await this._payments.call(provider, 'listPrices', () => driver.listPrices());
58
+ for (const price of prices) {
59
+ const data = {
60
+ key: price.key ?? price.id,
61
+ name: price.name ?? null,
62
+ amount: price.amount,
63
+ currency: price.currency,
64
+ interval: price.interval,
65
+ intervalCount: price.intervalCount,
66
+ trialDays: price.trialDays ?? null,
67
+ active: price.active
68
+ };
69
+ const where = { provider, providerPriceId: price.id };
70
+ const existing = await this._store.plans.find(where);
71
+ plans.push(existing
72
+ ? await this._store.plans.update(existing.id, data)
73
+ : await this._store.plans.create({ ...where, ...data }));
74
+ }
75
+ await this._store.plans.updateWhere({
76
+ provider,
77
+ active: true,
78
+ providerPriceId: { notIn: prices.map((price) => price.id) }
79
+ }, { active: false });
80
+ logger.debug({ gateway: provider, plans: prices.length }, 'Plans read');
81
+ }
82
+ return plans;
83
+ }
84
+ /**
85
+ * Lists the plans users can subscribe to.
86
+ *
87
+ * @param {string} [gateway] - The name of a gateway. Default: the plans of every gateway.
88
+ * @return {Promise<PaymentPlanRecord[]>} The active plans, the cheapest first.
89
+ */
90
+ async listPlans(gateway) {
91
+ this.enabled();
92
+ return this._store.plans.list({ active: true, ...(gateway ? { provider: gateway } : {}) }, { orderBy: { amount: 'asc' } });
93
+ }
94
+ /**
95
+ * Returns the plan of a key at a gateway.
96
+ *
97
+ * @param {string} key - The key of the plan.
98
+ * @param {string} gateway - The name of the gateway.
99
+ * @return {Promise<PaymentPlanRecord>} The plan.
100
+ * @throws {PaymentError} `PAYMENT_PLAN_UNKNOWN` for no active plan of the key at the gateway.
101
+ */
102
+ async getPlan(key, gateway) {
103
+ this.enabled();
104
+ const plan = await this._store.plans.find({
105
+ key,
106
+ provider: gateway,
107
+ active: true
108
+ });
109
+ if (!plan) {
110
+ throw new common_1.PaymentError(common_1.ErrorCode.PaymentPlanUnknown, `No plan '${key}' of the '${gateway}' gateway, read its prices with the payments-sync-plans task`, { plan: key });
111
+ }
112
+ return plan;
113
+ }
114
+ /**
115
+ * Subscribes a user to a plan, charged to a saved payment method. Without one, or when the bank wants the first
116
+ * payment confirmed, the subscription stays `incomplete` until the client confirms the `clientSecret` of the next
117
+ * action.
118
+ *
119
+ * @param {SubscribeInput} input - The user, the plan, and the gateway or the country and currency selecting it.
120
+ * @return {Promise<SubscriptionResult>} The subscription and what its client does next.
121
+ * @throws {PaymentError} `PAYMENT_PLAN_UNKNOWN`, `PAYMENT_METHOD_NOT_FOUND`, `PAYMENT_CAPABILITY_UNSUPPORTED`, or
122
+ * the error of the gateway.
123
+ */
124
+ async subscribe(input) {
125
+ this.enabled();
126
+ const customer = await this._payments.ensureCustomer(input);
127
+ const { provider } = customer;
128
+ await this._payments.require(provider, 'subscriptions');
129
+ const plan = await this.getPlan(input.plan, provider);
130
+ const method = input.paymentMethodId
131
+ ? await this._payments.getPaymentMethod(input.paymentMethodId)
132
+ : null;
133
+ if (method && method.customerId !== customer.id) {
134
+ throw new common_1.PaymentError(common_1.ErrorCode.PaymentMethodNotFound, `No payment method '${method.id}' of the customer found`, { id: method.id });
135
+ }
136
+ const record = await this.createRecord(input, customer.id, plan);
137
+ let subscription;
138
+ try {
139
+ subscription = await this._payments.call(provider, 'createSubscription', (gateway) => gateway.createSubscription({
140
+ customerId: customer.providerCustomerId,
141
+ priceId: plan.providerPriceId,
142
+ quantity: input.quantity,
143
+ trialDays: input.trialDays ?? plan.trialDays ?? undefined,
144
+ paymentMethodId: method?.providerPaymentMethodId,
145
+ idempotencyKey: `subscription-${record.id}`,
146
+ metadata: {
147
+ ...input.metadata,
148
+ [payment_sync_1.SUBSCRIPTION_METADATA_KEY]: record.id
149
+ }
150
+ }));
151
+ }
152
+ catch (e) {
153
+ await this.abandon(record);
154
+ throw e;
155
+ }
156
+ return this.applied(provider, subscription, record.id);
157
+ }
158
+ /**
159
+ * Starts a subscription on a hosted page of the gateway, where the customer is sent with the `redirect` of the
160
+ * next action and enters their payment method. The subscription starts with the webhook of the completed page.
161
+ *
162
+ * @param {SubscriptionCheckoutInput} input - The user, the plan, and where the customer lands afterwards.
163
+ * @return {Promise<SubscriptionResult>} The subscription, `incomplete`, and the redirect to its page.
164
+ * @throws {PaymentError} `PAYMENT_PLAN_UNKNOWN`, `PAYMENT_CAPABILITY_UNSUPPORTED`, or the error of the gateway.
165
+ */
166
+ async createCheckout(input) {
167
+ this.enabled();
168
+ const customer = await this._payments.ensureCustomer(input);
169
+ const { provider } = customer;
170
+ await this._payments.require(provider, 'subscriptions');
171
+ await this._payments.require(provider, 'checkout');
172
+ const plan = await this.getPlan(input.plan, provider);
173
+ const record = await this.createRecord(input, customer.id, plan);
174
+ const successUrl = input.successUrl ?? config_1.paymentsConfig.SUCCESS_URL ?? common_1.appConfig.HOSTNAME;
175
+ try {
176
+ const checkout = await this._payments.call(provider, 'createCheckout', (gateway) => gateway.createCheckout({
177
+ mode: 'subscription',
178
+ priceId: plan.providerPriceId,
179
+ quantity: input.quantity,
180
+ trialDays: input.trialDays ?? plan.trialDays ?? undefined,
181
+ customerId: customer.providerCustomerId,
182
+ locale: input.locale,
183
+ idempotencyKey: `checkout-${record.id}`,
184
+ successUrl,
185
+ cancelUrl: input.cancelUrl ?? config_1.paymentsConfig.CANCEL_URL ?? successUrl,
186
+ metadata: {
187
+ ...input.metadata,
188
+ [payment_sync_1.SUBSCRIPTION_METADATA_KEY]: record.id
189
+ }
190
+ }));
191
+ return {
192
+ subscription: record,
193
+ nextAction: checkout.url
194
+ ? { type: 'redirect', url: checkout.url }
195
+ : { type: 'none' }
196
+ };
197
+ }
198
+ catch (e) {
199
+ await this.abandon(record);
200
+ throw e;
201
+ }
202
+ }
203
+ /**
204
+ * Returns a subscription.
205
+ *
206
+ * @param {string} id - The ID of the subscription.
207
+ * @return {Promise<PaymentSubscriptionRecord>} The subscription.
208
+ * @throws {PaymentError} `PAYMENT_SUBSCRIPTION_NOT_FOUND` for an unknown subscription.
209
+ */
210
+ async getSubscription(id) {
211
+ this.enabled();
212
+ const subscription = await this._store.subscriptions.findById(id);
213
+ if (!subscription) {
214
+ throw new common_1.PaymentError(common_1.ErrorCode.PaymentSubscriptionNotFound, `No subscription '${id}' found`, { id });
215
+ }
216
+ return subscription;
217
+ }
218
+ /**
219
+ * Finds the subscription of a user that is not canceled, the newest one.
220
+ *
221
+ * @param {string | number} userId - The ID of the user.
222
+ * @param {string} [plan] - The key of a plan. Default: any plan.
223
+ * @return {Promise<PaymentSubscriptionRecord | null>} The subscription, `null` without one.
224
+ */
225
+ async findSubscription(userId, plan) {
226
+ this.enabled();
227
+ return this._store.subscriptions.find({
228
+ userId: String(userId),
229
+ status: { notIn: ['canceled', 'incomplete'] },
230
+ ...(plan ? { planKey: plan } : {})
231
+ }, { createdAt: 'desc' });
232
+ }
233
+ /**
234
+ * Tells whether a user has what a subscription pays for: one that is active or in its trial, or one whose renewal
235
+ * failed less than `payments.subscriptions.gracePeriod` ago, while the gateway retries the payment.
236
+ *
237
+ * @param {string | number} userId - The ID of the user.
238
+ * @param {string} [plan] - The key of a plan. Default: any plan.
239
+ * @param {Date} [now] - The current time.
240
+ * @return {Promise<boolean>} `true` with such a subscription.
241
+ */
242
+ async isActive(userId, plan, now = new Date()) {
243
+ this.enabled();
244
+ const graceStart = new Date(now.valueOf() - config_1.paymentsSubscriptionsConfig.GRACE_PERIOD);
245
+ const count = await this._store.subscriptions.count({
246
+ userId: String(userId),
247
+ ...(plan ? { planKey: plan } : {}),
248
+ OR: [
249
+ { status: { in: status_util_1.ACTIVE_SUBSCRIPTION_STATUSES } },
250
+ { status: 'pastDue', pastDueAt: { gt: graceStart } }
251
+ ]
252
+ });
253
+ return count > 0;
254
+ }
255
+ /**
256
+ * Cancels a subscription: with the period the customer paid for, or at once.
257
+ *
258
+ * @param {string} id - The ID of the subscription.
259
+ * @param {boolean} [atPeriodEnd=true] - Keep it until the end of its period, `false` to end it at once.
260
+ * @return {Promise<PaymentSubscriptionRecord>} The subscription.
261
+ * @throws {PaymentError} `PAYMENT_SUBSCRIPTION_NOT_FOUND`, `PAYMENT_INVALID_STATE` for a canceled subscription.
262
+ */
263
+ async cancel(id, atPeriodEnd = true) {
264
+ const record = await this.started(id, 'cancel');
265
+ const subscription = await this._payments.call(record.provider, atPeriodEnd ? 'updateSubscription' : 'cancelSubscription', (gateway) => atPeriodEnd
266
+ ? gateway.updateSubscription(record.providerSubscriptionId, {
267
+ cancelAtPeriodEnd: true
268
+ })
269
+ : gateway.cancelSubscription(record.providerSubscriptionId));
270
+ return (await this.applied(record.provider, subscription, id)).subscription;
271
+ }
272
+ /**
273
+ * Keeps a subscription that was canceled with the end of its period.
274
+ *
275
+ * @param {string} id - The ID of the subscription.
276
+ * @return {Promise<PaymentSubscriptionRecord>} The subscription.
277
+ * @throws {PaymentError} `PAYMENT_SUBSCRIPTION_NOT_FOUND`, `PAYMENT_INVALID_STATE` for a subscription that ended.
278
+ */
279
+ async resume(id) {
280
+ const record = await this.started(id, 'resume');
281
+ const subscription = await this._payments.call(record.provider, 'updateSubscription', (gateway) => gateway.updateSubscription(record.providerSubscriptionId, {
282
+ cancelAtPeriodEnd: false
283
+ }));
284
+ return (await this.applied(record.provider, subscription, id)).subscription;
285
+ }
286
+ /**
287
+ * Moves a subscription to another plan of its gateway.
288
+ *
289
+ * @param {string} id - The ID of the subscription.
290
+ * @param {string} plan - The key of the new plan.
291
+ * @param {ChangePlanOptions} [options] - The quantity, and whether the difference is charged.
292
+ * @return {Promise<PaymentSubscriptionRecord>} The subscription.
293
+ * @throws {PaymentError} `PAYMENT_SUBSCRIPTION_NOT_FOUND`, `PAYMENT_INVALID_STATE`, `PAYMENT_PLAN_UNKNOWN`.
294
+ */
295
+ async changePlan(id, plan, options = {}) {
296
+ const record = await this.started(id, 'change the plan of');
297
+ const next = await this.getPlan(plan, record.provider);
298
+ const subscription = await this._payments.call(record.provider, 'updateSubscription', (gateway) => gateway.updateSubscription(record.providerSubscriptionId, {
299
+ priceId: next.providerPriceId,
300
+ quantity: options.quantity,
301
+ prorate: options.prorate ?? config_1.paymentsSubscriptionsConfig.PRORATE
302
+ }));
303
+ return (await this.applied(record.provider, subscription, id)).subscription;
304
+ }
305
+ /**
306
+ * Reads a subscription from its gateway and applies its state.
307
+ *
308
+ * @param {string} id - The ID of the subscription.
309
+ * @return {Promise<SubscriptionResult>} The subscription and what its client does next.
310
+ * @throws {PaymentError} `PAYMENT_SUBSCRIPTION_NOT_FOUND` for an unknown subscription.
311
+ */
312
+ async sync(id) {
313
+ const record = await this.getSubscription(id);
314
+ if (!record.providerSubscriptionId) {
315
+ return { subscription: record, nextAction: { type: 'none' } };
316
+ }
317
+ const subscription = await this._payments.call(record.provider, 'getSubscription', (gateway) => gateway.getSubscription(record.providerSubscriptionId));
318
+ return this.applied(record.provider, subscription, id);
319
+ }
320
+ /**
321
+ * Lists the invoices of a subscription, the newest first.
322
+ *
323
+ * @param {string} id - The ID of the subscription.
324
+ * @return {Promise<PaymentInvoiceRecord[]>} The invoices.
325
+ */
326
+ async listInvoices(id) {
327
+ this.enabled();
328
+ return this._store.invoices.list({ subscriptionId: id }, { orderBy: { createdAt: 'desc' } });
329
+ }
330
+ /**
331
+ * Creates a session of the page of the gateway where a user manages their payment methods, subscriptions and
332
+ * invoices.
333
+ *
334
+ * @param {PaymentCustomerInput} input - The user, and the gateway or the country and currency selecting it.
335
+ * @param {string} [returnUrl] - Where the page sends the user back. Default: `payments.successUrl`.
336
+ * @return {Promise<string>} The URL of the session.
337
+ * @throws {PaymentError} `PAYMENT_CAPABILITY_UNSUPPORTED` for a gateway without such a page.
338
+ */
339
+ async createPortalSession(input, returnUrl) {
340
+ const customer = await this._payments.ensureCustomer(input);
341
+ await this._payments.require(customer.provider, 'portal');
342
+ const session = await this._payments.call(customer.provider, 'createPortalSession', (gateway) => gateway.createPortalSession(customer.providerCustomerId, returnUrl ?? config_1.paymentsConfig.SUCCESS_URL ?? common_1.appConfig.HOSTNAME));
343
+ return session.url;
344
+ }
345
+ /**
346
+ * Reads the subscriptions whose period ended, or that never completed, from their gateways again, catching the
347
+ * webhooks never received, and gives up the ones left `incomplete` longer than `payments.pendingTtl`.
348
+ *
349
+ * @param {Date} now - The current time.
350
+ * @param {number} limit - The most subscriptions to read.
351
+ * @return {Promise<number>} The number of subscriptions read.
352
+ */
353
+ async reconcile(now, limit) {
354
+ this.enabled();
355
+ const before = new Date(now.valueOf() - config_1.paymentsConfig.RECONCILE_AFTER);
356
+ const stale = await this._store.subscriptions.list({
357
+ updatedAt: { lt: before },
358
+ OR: [
359
+ { status: { in: ['incomplete', 'pastDue', 'unpaid'] } },
360
+ {
361
+ status: { in: ['active', 'trialing'] },
362
+ currentPeriodEnd: { lt: before }
363
+ }
364
+ ]
365
+ }, { orderBy: { updatedAt: 'asc' }, take: limit });
366
+ let handled = 0;
367
+ for (const record of stale) {
368
+ try {
369
+ const { subscription } = await this.sync(record.id);
370
+ const expired = config_1.paymentsConfig.PENDING_TTL > 0 &&
371
+ subscription.status === 'incomplete' &&
372
+ subscription.createdAt.valueOf() <
373
+ now.valueOf() - config_1.paymentsConfig.PENDING_TTL;
374
+ if (expired && !subscription.providerSubscriptionId) {
375
+ await this.abandon(subscription);
376
+ }
377
+ else if (subscription.status === record.status) {
378
+ await this._store.subscriptions.update(record.id, { updatedAt: now });
379
+ }
380
+ handled++;
381
+ }
382
+ catch (e) {
383
+ logger.warn({ err: e, subscription: record.id, gateway: record.provider }, 'Subscription not reconciled');
384
+ }
385
+ }
386
+ return handled;
387
+ }
388
+ /** Fails a call needing the models of the subscriptions, which have no tables when they are off. @internal */
389
+ enabled() {
390
+ if (!config_1.paymentsSubscriptionsConfig.ENABLED) {
391
+ throw new common_1.PaymentError(common_1.ErrorCode.PaymentSubscriptionsDisabled, 'The subscriptions are disabled, enable them with the payments.subscriptions.enabled config');
392
+ }
393
+ }
394
+ /** Stores the subscription before the gateway is called, so its webhooks always find it. @internal */
395
+ createRecord(input, customerId, plan) {
396
+ return this._store.subscriptions.create({
397
+ provider: plan.provider,
398
+ status: 'incomplete',
399
+ userId: String(input.userId),
400
+ customerId,
401
+ planId: plan.id,
402
+ planKey: plan.key,
403
+ providerPriceId: plan.providerPriceId,
404
+ quantity: input.quantity ?? 1,
405
+ metadata: input.metadata ?? null
406
+ });
407
+ }
408
+ /** Ends the record of a subscription the gateway never created. @internal */
409
+ async abandon(record) {
410
+ const now = new Date();
411
+ await this._store.subscriptions.updateWhere({ id: record.id, status: 'incomplete', providerSubscriptionId: null }, { status: 'canceled', canceledAt: now, endedAt: now });
412
+ }
413
+ /** @internal */
414
+ async started(id, action) {
415
+ const record = await this.getSubscription(id);
416
+ if (record.status === 'canceled' || !record.providerSubscriptionId) {
417
+ throw new common_1.PaymentError(common_1.ErrorCode.PaymentInvalidState, `Cannot ${action} the subscription '${id}', it is ${record.status}`, { id, status: record.status, action });
418
+ }
419
+ return record;
420
+ }
421
+ /** Applies a subscription of a gateway to its record, and announces what changed. @internal */
422
+ async applied(provider, subscription, recordId) {
423
+ const applied = await this._sync.applySubscription(provider, subscription, {
424
+ recordId
425
+ });
426
+ await this._events.dispatch(applied.events);
427
+ return {
428
+ subscription: applied.record ?? (await this.getSubscription(recordId)),
429
+ nextAction: this._payments.withPublicKey(provider, subscription.nextAction)
430
+ };
431
+ }
432
+ }
433
+ exports.SubscriptionsService = SubscriptionsService;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Processes the failed webhook events again, once their cause is fixed: `weaver run payments-replay` for all of
3
+ * them, or `weaver run payments-replay <id>` for one stored event.
4
+ */
5
+ declare const _default: import("@appweaver/core").Task<{
6
+ readonly id: {
7
+ readonly description: "The ID of a stored webhook event, every failed one without it.";
8
+ };
9
+ }, Record<never, import("@appweaver/core").TaskOption>>;
10
+ export default _default;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const core_1 = require("@appweaver/core");
4
+ const payment_events_1 = require("../service/payment-events");
5
+ const payment_store_1 = require("../service/payment-store");
6
+ /**
7
+ * Processes the failed webhook events again, once their cause is fixed: `weaver run payments-replay` for all of
8
+ * them, or `weaver run payments-replay <id>` for one stored event.
9
+ */
10
+ exports.default = (0, core_1.createTask)({
11
+ description: 'Processes the failed webhook events of the payment gateways again.',
12
+ arguments: {
13
+ id: {
14
+ description: 'The ID of a stored webhook event, every failed one without it.'
15
+ }
16
+ },
17
+ run: async ({ args }) => {
18
+ const events = (0, core_1.inject)(payment_events_1.PaymentEvents);
19
+ const ids = args.id
20
+ ? [args.id]
21
+ : (await new payment_store_1.PaymentStore().webhookEvents.list({ status: 'failed' }, { orderBy: { createdAt: 'asc' }, take: 1000 })).map((event) => event.id);
22
+ let failed = 0;
23
+ for (const id of ids) {
24
+ try {
25
+ const event = await events.replayWebhook(id);
26
+ console.log(`${id} ${event.type}: ${event.status}`);
27
+ }
28
+ catch (e) {
29
+ failed++;
30
+ console.error(`${id}: ${e.message}`);
31
+ }
32
+ }
33
+ console.log(`${ids.length - failed} of ${ids.length} events processed`);
34
+ return failed ? 1 : 0;
35
+ }
36
+ });
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Reads the recurring prices of the gateways into the plans users subscribe to: `weaver run payments-sync-plans`,
3
+ * or `weaver run payments-sync-plans stripe` for one gateway.
4
+ */
5
+ declare const _default: import("@appweaver/core").Task<{
6
+ readonly gateway: {
7
+ readonly description: "The name of a gateway, every gateway without one.";
8
+ };
9
+ }, Record<never, import("@appweaver/core").TaskOption>>;
10
+ export default _default;