@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.
- package/LICENSE +21 -0
- package/README.md +212 -2
- package/config.d.ts +77 -0
- package/config.js +118 -0
- package/gateway/fake-gateway.d.ts +144 -0
- package/gateway/fake-gateway.js +805 -0
- package/gateway/gateway-registry.d.ts +99 -0
- package/gateway/gateway-registry.js +275 -0
- package/gateway/payment-gateway.d.ts +68 -0
- package/gateway/payment-gateway.js +82 -0
- package/index.d.ts +16 -0
- package/index.js +51 -0
- package/locales/en.json +47 -0
- package/maintenance/payment-maintenance-jobs.d.ts +5 -0
- package/maintenance/payment-maintenance-jobs.js +38 -0
- package/module.d.ts +8 -0
- package/module.js +85 -0
- package/package.json +67 -3
- package/resources/model-util.d.ts +40 -0
- package/resources/model-util.js +30 -0
- package/resources/payment/model.d.ts +2 -0
- package/resources/payment/model.js +106 -0
- package/resources/payment-customer/model.d.ts +2 -0
- package/resources/payment-customer/model.js +53 -0
- package/resources/payment-event/model.d.ts +2 -0
- package/resources/payment-event/model.js +31 -0
- package/resources/payment-invoice/model.d.ts +2 -0
- package/resources/payment-invoice/model.js +55 -0
- package/resources/payment-method/model.d.ts +2 -0
- package/resources/payment-method/model.js +37 -0
- package/resources/payment-plan/model.d.ts +2 -0
- package/resources/payment-plan/model.js +37 -0
- package/resources/payment-subscription/model.d.ts +2 -0
- package/resources/payment-subscription/model.js +82 -0
- package/resources/payment-transaction/model.d.ts +2 -0
- package/resources/payment-transaction/model.js +43 -0
- package/resources/payment-webhook-event/model.d.ts +2 -0
- package/resources/payment-webhook-event/model.js +32 -0
- package/resources/policies.d.ts +15 -0
- package/resources/policies.js +36 -0
- package/resources/services.d.ts +6 -0
- package/resources/services.js +19 -0
- package/resources/subscriptions.d.ts +9 -0
- package/resources/subscriptions.js +30 -0
- package/resources.d.ts +8 -0
- package/resources.js +34 -0
- package/service/payment-emails.d.ts +12 -0
- package/service/payment-emails.js +145 -0
- package/service/payment-events.d.ts +90 -0
- package/service/payment-events.js +472 -0
- package/service/payment-handlers.d.ts +26 -0
- package/service/payment-handlers.js +42 -0
- package/service/payment-store.d.ts +50 -0
- package/service/payment-store.js +95 -0
- package/service/payment-sync.d.ts +113 -0
- package/service/payment-sync.js +745 -0
- package/service/payments-service.d.ts +307 -0
- package/service/payments-service.js +747 -0
- package/service/subscriptions-service.d.ts +178 -0
- package/service/subscriptions-service.js +433 -0
- package/tasks/payments-replay.d.ts +10 -0
- package/tasks/payments-replay.js +36 -0
- package/tasks/payments-sync-plans.d.ts +10 -0
- package/tasks/payments-sync-plans.js +24 -0
- package/templates/emails/payment-action-required.html.hbs +28 -0
- package/templates/emails/payment-action-required.subject.hbs +1 -0
- package/templates/emails/payment-failed.html.hbs +37 -0
- package/templates/emails/payment-failed.subject.hbs +1 -0
- package/templates/emails/payment-receipt.html.hbs +45 -0
- package/templates/emails/payment-receipt.subject.hbs +1 -0
- package/templates/emails/payment-refunded.html.hbs +37 -0
- package/templates/emails/payment-refunded.subject.hbs +1 -0
- package/templates/emails/subscription-canceled.html.hbs +24 -0
- package/templates/emails/subscription-canceled.subject.hbs +1 -0
- package/templates/emails/subscription-trial-ending.html.hbs +25 -0
- package/templates/emails/subscription-trial-ending.subject.hbs +1 -0
- package/templates/layouts/email.html.hbs +36 -0
- package/templates/partials/email-button.html.hbs +15 -0
- package/tsconfig.build.tsbuildinfo +1 -0
- package/types.d.ts +488 -0
- package/types.js +2 -0
- package/utils/money-util.d.ts +61 -0
- package/utils/money-util.js +124 -0
- package/utils/status-util.d.ts +29 -0
- package/utils/status-util.js +93 -0
- package/utils/telemetry.d.ts +16 -0
- package/utils/telemetry.js +69 -0
- package/web/payment-routes.d.ts +7 -0
- package/web/payment-routes.js +410 -0
- package/web/payment-schemas.d.ts +70 -0
- package/web/payment-schemas.js +101 -0
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const data_1 = require("@appweaver/data");
|
|
4
|
+
const model_util_1 = require("../model-util");
|
|
5
|
+
// A subscription of a gateway, renewed by it and moved by its webhooks
|
|
6
|
+
exports.default = (0, data_1.createModel)({
|
|
7
|
+
name: 'PaymentSubscription',
|
|
8
|
+
id: { type: 'string', generator: 'uuid(7)' },
|
|
9
|
+
audit: model_util_1.audit,
|
|
10
|
+
scalars: {
|
|
11
|
+
provider: model_util_1.provider,
|
|
12
|
+
providerSubscriptionId: (0, model_util_1.text)(255),
|
|
13
|
+
status: {
|
|
14
|
+
type: 'enum',
|
|
15
|
+
values: [
|
|
16
|
+
'incomplete',
|
|
17
|
+
'trialing',
|
|
18
|
+
'active',
|
|
19
|
+
'pastDue',
|
|
20
|
+
'unpaid',
|
|
21
|
+
'paused',
|
|
22
|
+
'canceled'
|
|
23
|
+
],
|
|
24
|
+
default: 'incomplete'
|
|
25
|
+
},
|
|
26
|
+
userId: (0, model_util_1.text)(255),
|
|
27
|
+
// The key of its plan, kept when the plan is removed
|
|
28
|
+
planKey: (0, model_util_1.text)(255),
|
|
29
|
+
providerPriceId: { type: 'string', maxLength: 255 },
|
|
30
|
+
quantity: { type: 'int', default: 1, minimum: 1 },
|
|
31
|
+
cancelAtPeriodEnd: { type: 'boolean', default: false },
|
|
32
|
+
livemode: { type: 'boolean', default: false },
|
|
33
|
+
currentPeriodStart: { type: 'dateTime', required: false },
|
|
34
|
+
currentPeriodEnd: { type: 'dateTime', required: false },
|
|
35
|
+
trialEnd: { type: 'dateTime', required: false },
|
|
36
|
+
canceledAt: { type: 'dateTime', required: false },
|
|
37
|
+
endedAt: { type: 'dateTime', required: false },
|
|
38
|
+
// Since when a renewal is unpaid, the start of the grace period
|
|
39
|
+
pastDueAt: { type: 'dateTime', required: false },
|
|
40
|
+
metadata: { type: 'json', required: false }
|
|
41
|
+
},
|
|
42
|
+
relations: {
|
|
43
|
+
customer: {
|
|
44
|
+
model: 'PaymentCustomer',
|
|
45
|
+
type: 'manyToOne',
|
|
46
|
+
mappedBy: 'subscriptions',
|
|
47
|
+
onDelete: 'restrict',
|
|
48
|
+
...model_util_1.internal,
|
|
49
|
+
output: { type: 'none' }
|
|
50
|
+
},
|
|
51
|
+
plan: {
|
|
52
|
+
model: 'PaymentPlan',
|
|
53
|
+
type: 'manyToOne',
|
|
54
|
+
mappedBy: 'subscriptions',
|
|
55
|
+
required: false,
|
|
56
|
+
onDelete: 'setNull',
|
|
57
|
+
...model_util_1.internal,
|
|
58
|
+
output: { type: 'always' }
|
|
59
|
+
},
|
|
60
|
+
payments: {
|
|
61
|
+
model: 'Payment',
|
|
62
|
+
type: 'oneToMany',
|
|
63
|
+
mappedBy: 'subscription',
|
|
64
|
+
required: false,
|
|
65
|
+
...model_util_1.internal,
|
|
66
|
+
output: { type: 'none' }
|
|
67
|
+
},
|
|
68
|
+
invoices: {
|
|
69
|
+
model: 'PaymentInvoice',
|
|
70
|
+
type: 'oneToMany',
|
|
71
|
+
mappedBy: 'subscription',
|
|
72
|
+
required: false,
|
|
73
|
+
...model_util_1.internal,
|
|
74
|
+
output: { type: 'none' }
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
unique: [['provider', 'providerSubscriptionId']],
|
|
78
|
+
index: [
|
|
79
|
+
['userId', 'status'],
|
|
80
|
+
['status', 'updatedAt']
|
|
81
|
+
]
|
|
82
|
+
});
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const data_1 = require("@appweaver/data");
|
|
4
|
+
const model_util_1 = require("../model-util");
|
|
5
|
+
// An entry of the ledger of a payment, appended by the module and never changed by a user
|
|
6
|
+
exports.default = (0, data_1.createModel)({
|
|
7
|
+
name: 'PaymentTransaction',
|
|
8
|
+
id: { type: 'string', generator: 'uuid(7)' },
|
|
9
|
+
audit: { updatedAt: false, createdById: false },
|
|
10
|
+
scalars: {
|
|
11
|
+
provider: model_util_1.provider,
|
|
12
|
+
// The ID of the charge, the refund or the dispute at the gateway
|
|
13
|
+
providerTransactionId: { type: 'string', maxLength: 255 },
|
|
14
|
+
userId: (0, model_util_1.text)(255),
|
|
15
|
+
type: {
|
|
16
|
+
type: 'enum',
|
|
17
|
+
values: ['authorization', 'capture', 'charge', 'refund', 'dispute']
|
|
18
|
+
},
|
|
19
|
+
status: {
|
|
20
|
+
type: 'enum',
|
|
21
|
+
values: ['pending', 'succeeded', 'failed', 'canceled', 'won', 'lost']
|
|
22
|
+
},
|
|
23
|
+
amount: { ...model_util_1.amount, default: undefined },
|
|
24
|
+
currency: model_util_1.currency,
|
|
25
|
+
// What the gateway keeps of the amount, once it is known
|
|
26
|
+
fee: { type: 'bigInt', required: false, minimum: 0 },
|
|
27
|
+
reason: (0, model_util_1.text)(255),
|
|
28
|
+
failureReason: (0, model_util_1.text)(1000),
|
|
29
|
+
occurredAt: { type: 'dateTime' }
|
|
30
|
+
},
|
|
31
|
+
relations: {
|
|
32
|
+
payment: {
|
|
33
|
+
model: 'Payment',
|
|
34
|
+
type: 'manyToOne',
|
|
35
|
+
mappedBy: 'transactions',
|
|
36
|
+
onDelete: 'restrict',
|
|
37
|
+
...model_util_1.internal,
|
|
38
|
+
output: { type: 'none' }
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
unique: [['provider', 'type', 'providerTransactionId']],
|
|
42
|
+
index: [['userId', '-occurredAt']]
|
|
43
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const data_1 = require("@appweaver/data");
|
|
4
|
+
const model_util_1 = require("../model-util");
|
|
5
|
+
// A webhook event received from a gateway, stored once by its ID and processed by a worker
|
|
6
|
+
exports.default = (0, data_1.createModel)({
|
|
7
|
+
name: 'PaymentWebhookEvent',
|
|
8
|
+
id: { type: 'string', generator: 'uuid(7)' },
|
|
9
|
+
audit: { createdById: false },
|
|
10
|
+
scalars: {
|
|
11
|
+
provider: model_util_1.provider,
|
|
12
|
+
providerEventId: { type: 'string', maxLength: 255 },
|
|
13
|
+
// The type of the event as the gateway names it, i.e. `payment_intent.succeeded`
|
|
14
|
+
type: { type: 'string', maxLength: 255 },
|
|
15
|
+
// What the event is about, i.e. `payment`
|
|
16
|
+
kind: { type: 'string', maxLength: 32 },
|
|
17
|
+
status: {
|
|
18
|
+
type: 'enum',
|
|
19
|
+
values: ['received', 'processed', 'failed', 'ignored'],
|
|
20
|
+
default: 'received'
|
|
21
|
+
},
|
|
22
|
+
attempts: { type: 'int', default: 0, minimum: 0 },
|
|
23
|
+
livemode: { type: 'boolean', default: false },
|
|
24
|
+
lastError: (0, model_util_1.text)(2000),
|
|
25
|
+
// The normalized object of the event, without the secrets the client confirms a payment with
|
|
26
|
+
payload: { type: 'json', required: false },
|
|
27
|
+
occurredAt: { type: 'dateTime' },
|
|
28
|
+
processedAt: { type: 'dateTime', required: false }
|
|
29
|
+
},
|
|
30
|
+
unique: [['provider', 'providerEventId']],
|
|
31
|
+
index: [['status', 'createdAt']]
|
|
32
|
+
});
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { ActionType, AuthUser } from '@appweaver/common';
|
|
2
|
+
export declare const READ_ACTIONS: ActionType[];
|
|
3
|
+
/** Tells whether a user reads the payment records of every user, and captures and refunds the payments. */
|
|
4
|
+
export declare function isPaymentAdmin(user: AuthUser | null | undefined): boolean;
|
|
5
|
+
/**
|
|
6
|
+
* The policy of the records of a user: read by their user and the admin roles, and written by the module only, never
|
|
7
|
+
* through a route.
|
|
8
|
+
*/
|
|
9
|
+
export declare function ownerPolicy(modelName: string): import("@appweaver/common").ResourcePolicyConfig<Record<string, any>>;
|
|
10
|
+
export declare const paymentPolicy: import("@appweaver/common").ResourcePolicyConfig<Record<string, any>>;
|
|
11
|
+
export declare const paymentMethodPolicy: import("@appweaver/common").ResourcePolicyConfig<Record<string, any>>;
|
|
12
|
+
export declare const paymentTransactionPolicy: import("@appweaver/common").ResourcePolicyConfig<Record<string, any>>;
|
|
13
|
+
export declare const paymentCustomerPolicy: import("@appweaver/common").ResourcePolicyConfig<Record<string, any>>;
|
|
14
|
+
export declare const paymentEventPolicy: import("@appweaver/common").ResourcePolicyConfig<Record<string, any>>;
|
|
15
|
+
export declare const paymentWebhookEventPolicy: import("@appweaver/common").ResourcePolicyConfig<Record<string, any>>;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.paymentWebhookEventPolicy = exports.paymentEventPolicy = exports.paymentCustomerPolicy = exports.paymentTransactionPolicy = exports.paymentMethodPolicy = exports.paymentPolicy = exports.READ_ACTIONS = void 0;
|
|
4
|
+
exports.isPaymentAdmin = isPaymentAdmin;
|
|
5
|
+
exports.ownerPolicy = ownerPolicy;
|
|
6
|
+
const data_1 = require("@appweaver/data");
|
|
7
|
+
const config_1 = require("../config");
|
|
8
|
+
exports.READ_ACTIONS = ['find', 'query', 'aggregate'];
|
|
9
|
+
/** Tells whether a user reads the payment records of every user, and captures and refunds the payments. */
|
|
10
|
+
function isPaymentAdmin(user) {
|
|
11
|
+
return !!user && (0, data_1.hasRoles)(user, config_1.paymentsRoutesConfig.ADMIN_ROLES);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The policy of the records of a user: read by their user and the admin roles, and written by the module only, never
|
|
15
|
+
* through a route.
|
|
16
|
+
*/
|
|
17
|
+
function ownerPolicy(modelName) {
|
|
18
|
+
return (0, data_1.createPolicy)({
|
|
19
|
+
modelName,
|
|
20
|
+
checkAccess: (_user, _resource, action) => exports.READ_ACTIONS.includes(action),
|
|
21
|
+
readRestrictions: (user) => isPaymentAdmin(user) ? {} : { userId: String(user?.id ?? '') }
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
exports.paymentPolicy = ownerPolicy('Payment');
|
|
25
|
+
exports.paymentMethodPolicy = ownerPolicy('PaymentMethod');
|
|
26
|
+
exports.paymentTransactionPolicy = ownerPolicy('PaymentTransaction');
|
|
27
|
+
/** The policy of the records of the module itself, read by the admin roles. */
|
|
28
|
+
function adminPolicy(modelName) {
|
|
29
|
+
return (0, data_1.createPolicy)({
|
|
30
|
+
modelName,
|
|
31
|
+
checkAccess: (user, _resource, action) => exports.READ_ACTIONS.includes(action) && isPaymentAdmin(user)
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
exports.paymentCustomerPolicy = adminPolicy('PaymentCustomer');
|
|
35
|
+
exports.paymentEventPolicy = adminPolicy('PaymentEvent');
|
|
36
|
+
exports.paymentWebhookEventPolicy = adminPolicy('PaymentWebhookEvent');
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare const paymentCustomerService: import("@appweaver/common").Ctor<import("@appweaver/data").ResourceService<any, any, any, any, import("@appweaver/common").QueryFilter<any>, any>> & import("@appweaver/common").ResourceMarks;
|
|
2
|
+
export declare const paymentMethodService: import("@appweaver/common").Ctor<import("@appweaver/data").ResourceService<any, any, any, any, import("@appweaver/common").QueryFilter<any>, any>> & import("@appweaver/common").ResourceMarks;
|
|
3
|
+
export declare const paymentService: import("@appweaver/common").Ctor<import("@appweaver/data").ResourceService<any, any, any, any, import("@appweaver/common").QueryFilter<any>, any>> & import("@appweaver/common").ResourceMarks;
|
|
4
|
+
export declare const paymentTransactionService: import("@appweaver/common").Ctor<import("@appweaver/data").ResourceService<any, any, any, any, import("@appweaver/common").QueryFilter<any>, any>> & import("@appweaver/common").ResourceMarks;
|
|
5
|
+
export declare const paymentEventService: import("@appweaver/common").Ctor<import("@appweaver/data").ResourceService<any, any, any, any, import("@appweaver/common").QueryFilter<any>, any>> & import("@appweaver/common").ResourceMarks;
|
|
6
|
+
export declare const paymentWebhookEventService: import("@appweaver/common").Ctor<import("@appweaver/data").ResourceService<any, any, any, any, import("@appweaver/common").QueryFilter<any>, any>> & import("@appweaver/common").ResourceMarks;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.paymentWebhookEventService = exports.paymentEventService = exports.paymentTransactionService = exports.paymentService = exports.paymentMethodService = exports.paymentCustomerService = void 0;
|
|
4
|
+
const data_1 = require("@appweaver/data");
|
|
5
|
+
// The services of the payment models: the module writes through their database client, the routes read through them
|
|
6
|
+
exports.paymentCustomerService = (0, data_1.createService)({
|
|
7
|
+
modelName: 'PaymentCustomer'
|
|
8
|
+
});
|
|
9
|
+
exports.paymentMethodService = (0, data_1.createService)({
|
|
10
|
+
modelName: 'PaymentMethod'
|
|
11
|
+
});
|
|
12
|
+
exports.paymentService = (0, data_1.createService)({ modelName: 'Payment' });
|
|
13
|
+
exports.paymentTransactionService = (0, data_1.createService)({
|
|
14
|
+
modelName: 'PaymentTransaction'
|
|
15
|
+
});
|
|
16
|
+
exports.paymentEventService = (0, data_1.createService)({ modelName: 'PaymentEvent' });
|
|
17
|
+
exports.paymentWebhookEventService = (0, data_1.createService)({
|
|
18
|
+
modelName: 'PaymentWebhookEvent'
|
|
19
|
+
});
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { default as paymentPlan } from './payment-plan/model';
|
|
2
|
+
export { default as paymentSubscription } from './payment-subscription/model';
|
|
3
|
+
export { default as paymentInvoice } from './payment-invoice/model';
|
|
4
|
+
export declare const paymentPlanService: import("@appweaver/common").Ctor<import("@appweaver/data").ResourceService<any, any, any, any, import("@appweaver/common").QueryFilter<any>, any>> & import("@appweaver/common").ResourceMarks;
|
|
5
|
+
export declare const paymentSubscriptionService: import("@appweaver/common").Ctor<import("@appweaver/data").ResourceService<any, any, any, any, import("@appweaver/common").QueryFilter<any>, any>> & import("@appweaver/common").ResourceMarks;
|
|
6
|
+
export declare const paymentInvoiceService: import("@appweaver/common").Ctor<import("@appweaver/data").ResourceService<any, any, any, any, import("@appweaver/common").QueryFilter<any>, any>> & import("@appweaver/common").ResourceMarks;
|
|
7
|
+
export declare const paymentSubscriptionPolicy: import("@appweaver/common").ResourcePolicyConfig<Record<string, any>>;
|
|
8
|
+
export declare const paymentInvoicePolicy: import("@appweaver/common").ResourcePolicyConfig<Record<string, any>>;
|
|
9
|
+
export declare const paymentPlanPolicy: import("@appweaver/common").ResourcePolicyConfig<Record<string, any>>;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.paymentPlanPolicy = exports.paymentInvoicePolicy = exports.paymentSubscriptionPolicy = exports.paymentInvoiceService = exports.paymentSubscriptionService = exports.paymentPlanService = exports.paymentInvoice = exports.paymentSubscription = exports.paymentPlan = void 0;
|
|
7
|
+
const data_1 = require("@appweaver/data");
|
|
8
|
+
const policies_1 = require("./policies");
|
|
9
|
+
// The resources of the recurring payments, loaded with `payments.subscriptions.enabled` only
|
|
10
|
+
var model_1 = require("./payment-plan/model");
|
|
11
|
+
Object.defineProperty(exports, "paymentPlan", { enumerable: true, get: function () { return __importDefault(model_1).default; } });
|
|
12
|
+
var model_2 = require("./payment-subscription/model");
|
|
13
|
+
Object.defineProperty(exports, "paymentSubscription", { enumerable: true, get: function () { return __importDefault(model_2).default; } });
|
|
14
|
+
var model_3 = require("./payment-invoice/model");
|
|
15
|
+
Object.defineProperty(exports, "paymentInvoice", { enumerable: true, get: function () { return __importDefault(model_3).default; } });
|
|
16
|
+
exports.paymentPlanService = (0, data_1.createService)({ modelName: 'PaymentPlan' });
|
|
17
|
+
exports.paymentSubscriptionService = (0, data_1.createService)({
|
|
18
|
+
modelName: 'PaymentSubscription'
|
|
19
|
+
});
|
|
20
|
+
exports.paymentInvoiceService = (0, data_1.createService)({
|
|
21
|
+
modelName: 'PaymentInvoice'
|
|
22
|
+
});
|
|
23
|
+
exports.paymentSubscriptionPolicy = (0, policies_1.ownerPolicy)('PaymentSubscription');
|
|
24
|
+
exports.paymentInvoicePolicy = (0, policies_1.ownerPolicy)('PaymentInvoice');
|
|
25
|
+
// The plans are read by everyone, the inactive ones by the admin roles only
|
|
26
|
+
exports.paymentPlanPolicy = (0, data_1.createPolicy)({
|
|
27
|
+
modelName: 'PaymentPlan',
|
|
28
|
+
checkAccess: (_user, _resource, action) => policies_1.READ_ACTIONS.includes(action),
|
|
29
|
+
readRestrictions: (user) => (0, policies_1.isPaymentAdmin)(user) ? {} : { active: true }
|
|
30
|
+
});
|
package/resources.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { default as paymentCustomer } from './resources/payment-customer/model';
|
|
2
|
+
export { default as paymentMethod } from './resources/payment-method/model';
|
|
3
|
+
export { default as payment } from './resources/payment/model';
|
|
4
|
+
export { default as paymentTransaction } from './resources/payment-transaction/model';
|
|
5
|
+
export { default as paymentEvent } from './resources/payment-event/model';
|
|
6
|
+
export { default as paymentWebhookEvent } from './resources/payment-webhook-event/model';
|
|
7
|
+
export * from './resources/services';
|
|
8
|
+
export * from './resources/policies';
|
package/resources.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
17
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
18
|
+
};
|
|
19
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
+
exports.paymentWebhookEvent = exports.paymentEvent = exports.paymentTransaction = exports.payment = exports.paymentMethod = exports.paymentCustomer = void 0;
|
|
21
|
+
var model_1 = require("./resources/payment-customer/model");
|
|
22
|
+
Object.defineProperty(exports, "paymentCustomer", { enumerable: true, get: function () { return __importDefault(model_1).default; } });
|
|
23
|
+
var model_2 = require("./resources/payment-method/model");
|
|
24
|
+
Object.defineProperty(exports, "paymentMethod", { enumerable: true, get: function () { return __importDefault(model_2).default; } });
|
|
25
|
+
var model_3 = require("./resources/payment/model");
|
|
26
|
+
Object.defineProperty(exports, "payment", { enumerable: true, get: function () { return __importDefault(model_3).default; } });
|
|
27
|
+
var model_4 = require("./resources/payment-transaction/model");
|
|
28
|
+
Object.defineProperty(exports, "paymentTransaction", { enumerable: true, get: function () { return __importDefault(model_4).default; } });
|
|
29
|
+
var model_5 = require("./resources/payment-event/model");
|
|
30
|
+
Object.defineProperty(exports, "paymentEvent", { enumerable: true, get: function () { return __importDefault(model_5).default; } });
|
|
31
|
+
var model_6 = require("./resources/payment-webhook-event/model");
|
|
32
|
+
Object.defineProperty(exports, "paymentWebhookEvent", { enumerable: true, get: function () { return __importDefault(model_6).default; } });
|
|
33
|
+
__exportStar(require("./resources/services"), exports);
|
|
34
|
+
__exportStar(require("./resources/policies"), exports);
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { PaymentEvent } from '../types';
|
|
2
|
+
/**
|
|
3
|
+
* Sends the email of an event of the payments to its customer, in their locale: the receipt of a payment, a failed
|
|
4
|
+
* payment, a refund, a renewal the bank wants confirmed, a canceled subscription, a trial about to end. The email
|
|
5
|
+
* is rendered from its template, the one of the application replacing the one of the module, otherwise as the plain
|
|
6
|
+
* text of its translations. Nothing is sent without a mailer, an address of the customer or of the payment, or with
|
|
7
|
+
* the email turned off in the `payments.emails` config.
|
|
8
|
+
*
|
|
9
|
+
* @param {PaymentEvent} event - The event, with the records it is about.
|
|
10
|
+
* @return {Promise<boolean>} `true` when an email was queued.
|
|
11
|
+
*/
|
|
12
|
+
export declare function sendPaymentEmail(event: PaymentEvent): Promise<boolean>;
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.sendPaymentEmail = sendPaymentEmail;
|
|
4
|
+
const common_1 = require("@appweaver/common");
|
|
5
|
+
const core_1 = require("@appweaver/core");
|
|
6
|
+
const config_1 = require("../config");
|
|
7
|
+
const money_util_1 = require("../utils/money-util");
|
|
8
|
+
const payment_store_1 = require("./payment-store");
|
|
9
|
+
const logger = (0, common_1.createLogger)('payments');
|
|
10
|
+
const EMAILS = {
|
|
11
|
+
'payment.succeeded': {
|
|
12
|
+
enabled: () => config_1.paymentsEmailsConfig.RECEIPT,
|
|
13
|
+
template: 'emails/payment-receipt',
|
|
14
|
+
key: 'emails.payments.receipt',
|
|
15
|
+
lines: ['description', 'plan', 'reference', 'method', 'date', 'receipt']
|
|
16
|
+
},
|
|
17
|
+
'payment.failed': {
|
|
18
|
+
enabled: () => config_1.paymentsEmailsConfig.FAILED,
|
|
19
|
+
template: 'emails/payment-failed',
|
|
20
|
+
key: 'emails.payments.failed',
|
|
21
|
+
lines: ['description', 'plan', 'reason', 'retry']
|
|
22
|
+
},
|
|
23
|
+
'refund.succeeded': {
|
|
24
|
+
enabled: () => config_1.paymentsEmailsConfig.REFUNDED,
|
|
25
|
+
template: 'emails/payment-refunded',
|
|
26
|
+
key: 'emails.payments.refunded',
|
|
27
|
+
lines: ['description', 'reference', 'method', 'date']
|
|
28
|
+
},
|
|
29
|
+
'payment.requiresAction': {
|
|
30
|
+
enabled: () => config_1.paymentsEmailsConfig.ACTION_REQUIRED,
|
|
31
|
+
template: 'emails/payment-action-required',
|
|
32
|
+
key: 'emails.payments.actionRequired',
|
|
33
|
+
lines: ['description', 'plan', 'link'],
|
|
34
|
+
// A payment the customer is making is confirmed on the page they are on
|
|
35
|
+
applies: (event) => !!event.payment?.subscriptionId
|
|
36
|
+
},
|
|
37
|
+
'subscription.canceled': {
|
|
38
|
+
enabled: () => config_1.paymentsEmailsConfig.SUBSCRIPTION_CANCELED,
|
|
39
|
+
template: 'emails/subscription-canceled',
|
|
40
|
+
key: 'emails.payments.subscriptionCanceled',
|
|
41
|
+
lines: ['plan', 'date']
|
|
42
|
+
},
|
|
43
|
+
'subscription.trialWillEnd': {
|
|
44
|
+
enabled: () => config_1.paymentsEmailsConfig.TRIAL_ENDING,
|
|
45
|
+
template: 'emails/subscription-trial-ending',
|
|
46
|
+
key: 'emails.payments.trialEnding',
|
|
47
|
+
lines: ['plan', 'date']
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Sends the email of an event of the payments to its customer, in their locale: the receipt of a payment, a failed
|
|
52
|
+
* payment, a refund, a renewal the bank wants confirmed, a canceled subscription, a trial about to end. The email
|
|
53
|
+
* is rendered from its template, the one of the application replacing the one of the module, otherwise as the plain
|
|
54
|
+
* text of its translations. Nothing is sent without a mailer, an address of the customer or of the payment, or with
|
|
55
|
+
* the email turned off in the `payments.emails` config.
|
|
56
|
+
*
|
|
57
|
+
* @param {PaymentEvent} event - The event, with the records it is about.
|
|
58
|
+
* @return {Promise<boolean>} `true` when an email was queued.
|
|
59
|
+
*/
|
|
60
|
+
async function sendPaymentEmail(event) {
|
|
61
|
+
const email = EMAILS[event.type];
|
|
62
|
+
const emailService = (0, core_1.inject)(core_1.EmailService, false);
|
|
63
|
+
// A payment of a guest has no customer, only the address it was created with
|
|
64
|
+
const to = event.customer?.email ?? event.payment?.email;
|
|
65
|
+
if (!email ||
|
|
66
|
+
!config_1.paymentsEmailsConfig.ENABLED ||
|
|
67
|
+
!email.enabled() ||
|
|
68
|
+
email.applies?.(event) === false ||
|
|
69
|
+
!emailService ||
|
|
70
|
+
!to) {
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
const localeService = (0, core_1.inject)(core_1.LocaleService);
|
|
74
|
+
const locale = event.customer?.locale ?? undefined;
|
|
75
|
+
const t = (key, params) => localeService.translate(key, locale, params);
|
|
76
|
+
const data = await emailData(event, locale ?? localeService.defaultLocale);
|
|
77
|
+
const subject = t(`${email.key}.subject`, data);
|
|
78
|
+
const engine = (0, core_1.inject)(common_1.TemplateEngine, false);
|
|
79
|
+
const formats = engine
|
|
80
|
+
? await Promise.all(['html', 'txt', 'subject'].map((format) => engine.hasTemplate(`${email.template}.${format}`, locale)))
|
|
81
|
+
: [];
|
|
82
|
+
if (formats[0] || formats[1]) {
|
|
83
|
+
await emailService.sendEmail({
|
|
84
|
+
to,
|
|
85
|
+
template: email.template,
|
|
86
|
+
data,
|
|
87
|
+
locale,
|
|
88
|
+
...(formats[2] ? {} : { subject })
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
await emailService.sendEmail({
|
|
93
|
+
to,
|
|
94
|
+
subject,
|
|
95
|
+
text: [
|
|
96
|
+
t('emails.greeting'),
|
|
97
|
+
t(`${email.key}.message`, data),
|
|
98
|
+
...email.lines
|
|
99
|
+
.filter((line) => data[line])
|
|
100
|
+
.map((line) => `${t(`emails.payments.labels.${line}`)}: ${data[line]}`),
|
|
101
|
+
`--\n${t('emails.footer', { appName: common_1.appConfig.NAME })}`
|
|
102
|
+
].join('\n\n')
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
logger.debug({ event: event.id, type: event.type }, 'Payment email queued');
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
/** The values of the templates and the translations of an email, the amounts and the dates formatted. */
|
|
109
|
+
async function emailData(event, locale) {
|
|
110
|
+
const store = new payment_store_1.PaymentStore();
|
|
111
|
+
const { payment, subscription, transaction, paymentMethod } = event;
|
|
112
|
+
const plan = subscription?.planId
|
|
113
|
+
? await store.plans.findById(subscription.planId)
|
|
114
|
+
: null;
|
|
115
|
+
const invoice = event.invoice ??
|
|
116
|
+
(payment && config_1.paymentsSubscriptionsConfig.ENABLED
|
|
117
|
+
? await store.invoices.find({ paymentId: payment.id })
|
|
118
|
+
: null);
|
|
119
|
+
const date = (value) => value
|
|
120
|
+
? new Intl.DateTimeFormat(locale, { dateStyle: 'long' }).format(value)
|
|
121
|
+
: '';
|
|
122
|
+
const money = transaction ?? payment;
|
|
123
|
+
const data = {
|
|
124
|
+
appName: common_1.appConfig.NAME,
|
|
125
|
+
amount: money ? (0, money_util_1.formatAmount)(money.amount, money.currency, locale) : '',
|
|
126
|
+
description: payment?.description ?? '',
|
|
127
|
+
reference: payment?.reference ?? '',
|
|
128
|
+
plan: plan?.name ?? plan?.key ?? subscription?.planKey ?? '',
|
|
129
|
+
method: paymentMethod
|
|
130
|
+
? [paymentMethod.brand ?? paymentMethod.type, paymentMethod.last4]
|
|
131
|
+
.filter(Boolean)
|
|
132
|
+
.join(' •••• ')
|
|
133
|
+
: '',
|
|
134
|
+
reason: payment?.failureMessage ?? '',
|
|
135
|
+
receipt: payment?.receiptUrl ?? '',
|
|
136
|
+
link: invoice?.hostedUrl ?? config_1.paymentsConfig.SUCCESS_URL ?? common_1.appConfig.HOSTNAME,
|
|
137
|
+
date: date(event.type === 'subscription.trialWillEnd'
|
|
138
|
+
? subscription?.trialEnd
|
|
139
|
+
: event.type === 'subscription.canceled'
|
|
140
|
+
? (subscription?.endedAt ?? subscription?.currentPeriodEnd)
|
|
141
|
+
: (transaction?.occurredAt ?? payment?.paidAt ?? event.createdAt)),
|
|
142
|
+
retry: date(invoice?.nextAttemptAt)
|
|
143
|
+
};
|
|
144
|
+
return data;
|
|
145
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { LIFECYCLE, OnInit } from '@appweaver/common';
|
|
2
|
+
import { GatewayEvent, PaymentEvent, PaymentEventRecord, PaymentWebhookEventRecord, WebhookHeaders } from '../types';
|
|
3
|
+
/**
|
|
4
|
+
* The inbox of the webhook events and the outbox of the events of the payments. A webhook request is verified,
|
|
5
|
+
* stored once by the ID of its event and answered at once; a job of the `payments` queue then applies it to the
|
|
6
|
+
* records, in one transaction with the events telling of the change, which other jobs deliver to the handlers of
|
|
7
|
+
* `onPaymentEvent` and to the emails.
|
|
8
|
+
*/
|
|
9
|
+
export declare class PaymentEvents implements OnInit {
|
|
10
|
+
static [LIFECYCLE]: boolean;
|
|
11
|
+
constructor();
|
|
12
|
+
/** Receives the events of the built-in `fake` gateway, which calls no webhook. */
|
|
13
|
+
onInit(): void;
|
|
14
|
+
/**
|
|
15
|
+
* Receives a webhook request of a gateway: verifies its signature, stores its event and queues its processing.
|
|
16
|
+
*
|
|
17
|
+
* @param {string} gateway - The name of the gateway, the end of the URL of the request.
|
|
18
|
+
* @param {Buffer} body - The body of the request as it was received.
|
|
19
|
+
* @param {WebhookHeaders} headers - The headers of the request.
|
|
20
|
+
* @return {Promise<PaymentWebhookEventRecord | null>} The stored event, `null` for one received before.
|
|
21
|
+
* @throws {PaymentError} `PAYMENT_GATEWAY_UNKNOWN` for a gateway that is not configured, `PAYMENT_WEBHOOK_INVALID`
|
|
22
|
+
* for a missing or wrong signature.
|
|
23
|
+
*/
|
|
24
|
+
receiveWebhook(gateway: string, body: Buffer, headers: WebhookHeaders): Promise<PaymentWebhookEventRecord | null>;
|
|
25
|
+
/**
|
|
26
|
+
* Stores a verified event of a gateway once, by its ID, and queues its processing.
|
|
27
|
+
*
|
|
28
|
+
* @param {string} gateway - The name of the gateway.
|
|
29
|
+
* @param {GatewayEvent} event - The event.
|
|
30
|
+
* @param {boolean} [queue=true] - Queue the processing, `false` when the caller processes the event itself.
|
|
31
|
+
* @return {Promise<PaymentWebhookEventRecord | null>} The stored event, `null` for one received before.
|
|
32
|
+
*/
|
|
33
|
+
receive(gateway: string, event: GatewayEvent, queue?: boolean): Promise<PaymentWebhookEventRecord | null>;
|
|
34
|
+
/**
|
|
35
|
+
* Applies a stored webhook event to the records, once: the object of the event is read from its gateway again
|
|
36
|
+
* (`payments.webhooks.refetch`), so an event delivered late cannot move a record back, then applied in one
|
|
37
|
+
* transaction with the events of the change.
|
|
38
|
+
*
|
|
39
|
+
* @param {string} id - The ID of the stored event.
|
|
40
|
+
* @return {Promise<PaymentWebhookEventRecord | null>} The event, `null` for an unknown one.
|
|
41
|
+
* @throws The error of the processing, which is tried again up to `payments.webhooks.maxAttempts` times.
|
|
42
|
+
*/
|
|
43
|
+
processWebhook(id: string): Promise<PaymentWebhookEventRecord | null>;
|
|
44
|
+
/**
|
|
45
|
+
* Processes a stored webhook event again, i.e. a failed one once its cause is fixed.
|
|
46
|
+
*
|
|
47
|
+
* @param {string} id - The ID of the stored event.
|
|
48
|
+
* @return {Promise<PaymentWebhookEventRecord>} The processed event.
|
|
49
|
+
* @throws {PaymentError} `PAYMENT_NOT_FOUND` for an unknown event.
|
|
50
|
+
*/
|
|
51
|
+
replayWebhook(id: string): Promise<PaymentWebhookEventRecord>;
|
|
52
|
+
/**
|
|
53
|
+
* Queues the delivery of events of the payments, once the transaction that wrote them is committed.
|
|
54
|
+
*
|
|
55
|
+
* @param {PaymentEventRecord[]} events - The stored events.
|
|
56
|
+
*/
|
|
57
|
+
dispatch(events: PaymentEventRecord[]): Promise<void>;
|
|
58
|
+
/**
|
|
59
|
+
* Delivers a stored event to the handlers of `onPaymentEvent`, then sends its email.
|
|
60
|
+
*
|
|
61
|
+
* @param {string} id - The ID of the event.
|
|
62
|
+
* @return {Promise<boolean>} `true` when the event was delivered by this call.
|
|
63
|
+
* @throws The error of a handler, which has the event delivered again up to `payments.eventMaxAttempts` times.
|
|
64
|
+
*/
|
|
65
|
+
deliver(id: string): Promise<boolean>;
|
|
66
|
+
/**
|
|
67
|
+
* Queues the stored work no job finished, i.e. after a crash or a queue that lost its jobs: the received webhook
|
|
68
|
+
* events and the pending events of the payments older than a minute.
|
|
69
|
+
*
|
|
70
|
+
* @param {Date} now - The current time.
|
|
71
|
+
* @param {number} limit - The most records of each kind to queue.
|
|
72
|
+
* @return {Promise<number>} The number of queued jobs.
|
|
73
|
+
*/
|
|
74
|
+
requeue(now: Date, limit: number): Promise<number>;
|
|
75
|
+
/**
|
|
76
|
+
* Deletes the processed webhook events and the delivered events of the payments older than their retention. The
|
|
77
|
+
* failed ones are kept.
|
|
78
|
+
*
|
|
79
|
+
* @param {Date} now - The current time.
|
|
80
|
+
* @return {Promise<number>} The number of deleted records.
|
|
81
|
+
*/
|
|
82
|
+
prune(now: Date): Promise<number>;
|
|
83
|
+
/**
|
|
84
|
+
* Loads the records an event is about.
|
|
85
|
+
*
|
|
86
|
+
* @param {PaymentEventRecord} record - The stored event.
|
|
87
|
+
* @return {Promise<PaymentEvent>} The event as the handlers receive it.
|
|
88
|
+
*/
|
|
89
|
+
load(record: PaymentEventRecord): Promise<PaymentEvent>;
|
|
90
|
+
}
|