payment-kit 1.16.1 → 1.16.3

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.
@@ -8,6 +8,7 @@ import {
8
8
  } from '../integrations/stripe/resource';
9
9
  import {
10
10
  expiredSessionCleanupCronTime,
11
+ meteringSubscriptionDetectionCronTime,
11
12
  notificationCronTime,
12
13
  paymentStatCronTime,
13
14
  revokeStakeCronTime,
@@ -23,6 +24,7 @@ import { createPaymentStat } from './payment-stat';
23
24
  import { SubscriptionTrialWillEndSchedule } from './subscription-trial-will-end';
24
25
  import { SubscriptionWillCanceledSchedule } from './subscription-will-canceled';
25
26
  import { SubscriptionWillRenewSchedule } from './subscription-will-renew';
27
+ import { createMeteringSubscriptionDetection } from './metering-subscription-detection';
26
28
 
27
29
  function init() {
28
30
  Cron.init({
@@ -91,6 +93,12 @@ function init() {
91
93
  fn: () => createPaymentStat(),
92
94
  options: { runOnInit: false },
93
95
  },
96
+ {
97
+ name: 'metering.subscription.detection',
98
+ time: meteringSubscriptionDetectionCronTime,
99
+ fn: () => createMeteringSubscriptionDetection(),
100
+ options: { runOnInit: true },
101
+ },
94
102
  ],
95
103
  onError: (error: Error, name: string) => {
96
104
  logger.error('run job failed', { name, error });
@@ -0,0 +1,207 @@
1
+ import { Notification } from '@blocklet/sdk';
2
+ import { Op } from 'sequelize';
3
+ import { env } from '@blocklet/sdk/lib/config';
4
+ import dayjs from '../libs/dayjs';
5
+ import logger from '../libs/logger';
6
+ import { Event, Invoice, InvoiceItem, Price, Subscription } from '../store/models';
7
+ import { getAdminBillingSubscriptionsUrl, getOwnerDid } from '../libs/util';
8
+ import { translate } from '../locales';
9
+ import type { BaseEmailTemplate, BaseEmailTemplateType } from '../libs/notification/template/base';
10
+ import { getUserLocale } from '../integrations/blocklet/notification';
11
+ import { formatTime } from '../libs/time';
12
+
13
+ function getAppName() {
14
+ return env.appName;
15
+ }
16
+ interface SubscriptionSummary {
17
+ totalCount: number;
18
+ unreportedCount: number;
19
+ discrepantCount: number;
20
+ abnormalSubscriptions: Array<Subscription>;
21
+ normalCount: number;
22
+ timeRange: {
23
+ start: number;
24
+ end: number;
25
+ };
26
+ }
27
+
28
+ interface MeteringSubscriptionDetectionContext {
29
+ locale: string;
30
+ userDid: string;
31
+ summary: SubscriptionSummary;
32
+ startTimeStr: string;
33
+ endTimeStr: string;
34
+ viewAppUrl: string;
35
+ }
36
+
37
+ export class MeteringSubscriptionDetectionTemplate implements BaseEmailTemplate<MeteringSubscriptionDetectionContext> {
38
+ private timeRange: { start: number; end: number };
39
+
40
+ constructor() {
41
+ const end = dayjs();
42
+ const start = end.subtract(24, 'hours');
43
+ this.timeRange = {
44
+ start: start.unix(),
45
+ end: end.unix(),
46
+ };
47
+ }
48
+
49
+ private async getAbnormalSubscriptions(meteringInvoiceIds: string[], meteringSubscriptionIds: string[]) {
50
+ const [unreportedEvents, discrepantEvents] = await Promise.all([
51
+ Event.findAll({
52
+ where: {
53
+ type: 'usage.report.empty',
54
+ created_at: {
55
+ [Op.between]: [this.timeRange.start * 1000, this.timeRange.end * 1000],
56
+ },
57
+ object_id: {
58
+ [Op.in]: meteringSubscriptionIds,
59
+ },
60
+ },
61
+ }),
62
+ Event.findAll({
63
+ where: {
64
+ type: 'billing.discrepancy',
65
+ created_at: {
66
+ [Op.between]: [this.timeRange.start * 1000, this.timeRange.end * 1000],
67
+ },
68
+ object_id: {
69
+ [Op.in]: meteringInvoiceIds,
70
+ },
71
+ },
72
+ }),
73
+ ]);
74
+
75
+ const abnormalSubscriptionIds = new Set([
76
+ ...unreportedEvents.map((e) => e.object_id),
77
+ ...discrepantEvents.map((e) => e.data?.object?.subscription_id),
78
+ ]);
79
+
80
+ const unreportedSubscriptionIds = Array.from(new Set(unreportedEvents.map((e) => e.object_id)));
81
+ const discrepantSubscriptionIds = Array.from(new Set(discrepantEvents.map((e) => e.data?.object?.subscription_id)));
82
+ const subscriptions = await Subscription.findAll({
83
+ where: {
84
+ id: Array.from(abnormalSubscriptionIds),
85
+ },
86
+ });
87
+
88
+ return {
89
+ unreported: unreportedSubscriptionIds,
90
+ discrepant: discrepantSubscriptionIds,
91
+ subscriptions,
92
+ };
93
+ }
94
+
95
+ async getContext(): Promise<MeteringSubscriptionDetectionContext> {
96
+ const { start, end } = this.timeRange;
97
+ const invoices = await Invoice.findAll({
98
+ where: {
99
+ created_at: {
100
+ [Op.between]: [start * 1000, end * 1000],
101
+ },
102
+ billing_reason: {
103
+ [Op.notIn]: ['stake', 'slash_stake', 'recharge'],
104
+ },
105
+ },
106
+ include: [
107
+ { model: Subscription, as: 'subscription' },
108
+ { model: InvoiceItem, as: 'lines' },
109
+ ],
110
+ });
111
+
112
+ const meteringInvoices: any[] = [];
113
+ await Promise.all(
114
+ invoices.map(async (invoice) => {
115
+ const invoiceJson = invoice.toJSON();
116
+ const prices = (await Price.findAll()).map((x) => x.toJSON());
117
+ // @ts-ignore
118
+ (invoiceJson.lines || []).forEach((item) => {
119
+ item.price = prices.find((x) => x.id === item.price_id);
120
+ });
121
+ // @ts-ignore
122
+ if ((invoiceJson.lines || []).some((line) => line.price?.recurring?.usage_type === 'metered')) {
123
+ meteringInvoices.push(invoice);
124
+ }
125
+ })
126
+ );
127
+ const meteringInvoiceIds = Array.from(new Set(meteringInvoices.map((invoice) => invoice.id)));
128
+ const meteringSubscriptionIds = Array.from(
129
+ new Set(meteringInvoices.map((invoice) => invoice?.subscription_id).filter(Boolean) as string[])
130
+ );
131
+
132
+ const abnormalSubscriptions = await this.getAbnormalSubscriptions(meteringInvoiceIds, meteringSubscriptionIds);
133
+ const userDid = await getOwnerDid();
134
+ if (!userDid) {
135
+ throw new Error('get owner did failed');
136
+ }
137
+ const locale = await getUserLocale(userDid);
138
+
139
+ const viewAppUrl = getAdminBillingSubscriptionsUrl({ locale, userDid });
140
+ return {
141
+ locale,
142
+ userDid,
143
+ summary: {
144
+ totalCount: meteringSubscriptionIds.length,
145
+ normalCount: Math.max(0, meteringSubscriptionIds.length - abnormalSubscriptions.subscriptions.length),
146
+ unreportedCount: abnormalSubscriptions.unreported.length,
147
+ discrepantCount: abnormalSubscriptions.discrepant.length,
148
+ abnormalSubscriptions: abnormalSubscriptions.subscriptions,
149
+ timeRange: this.timeRange,
150
+ },
151
+ startTimeStr: formatTime(this.timeRange.start * 1000),
152
+ endTimeStr: formatTime(this.timeRange.end * 1000),
153
+ viewAppUrl,
154
+ };
155
+ }
156
+
157
+ async getTemplate(): Promise<BaseEmailTemplateType> {
158
+ const context = await this.getContext();
159
+ // @ts-ignore
160
+ const { locale, summary, startTimeStr, endTimeStr, viewAppUrl } = context;
161
+ const body =
162
+ summary.abnormalSubscriptions.length === 0
163
+ ? translate('notification.meteringSubscriptionDetection.healthyBody', locale, {
164
+ totalCount: summary.totalCount,
165
+ startTimeStr,
166
+ endTimeStr,
167
+ })
168
+ : `${translate('notification.meteringSubscriptionDetection.body', locale, {
169
+ totalCount: summary.totalCount,
170
+ startTimeStr,
171
+ endTimeStr,
172
+ normalCount: summary.normalCount,
173
+ abnormalCount: summary.abnormalSubscriptions.length,
174
+ unreportedCount: summary.unreportedCount,
175
+ discrepantCount: summary.discrepantCount,
176
+ })}\n${summary.abnormalSubscriptions.map((sub) => `${sub.description}(${sub.id})`).join('\n')}`;
177
+ return {
178
+ title: translate('notification.meteringSubscriptionDetection.title', locale, {
179
+ appName: getAppName(),
180
+ }),
181
+ body,
182
+ // @ts-ignore
183
+ actions: [
184
+ viewAppUrl && {
185
+ name: translate('notification.meteringSubscriptionDetection.view', locale),
186
+ title: translate('notification.meteringSubscriptionDetection.view', locale),
187
+ link: viewAppUrl,
188
+ },
189
+ ].filter(Boolean),
190
+ };
191
+ }
192
+ }
193
+
194
+ export async function createMeteringSubscriptionDetection() {
195
+ logger.info('Start metering subscription detection');
196
+
197
+ try {
198
+ const template = new MeteringSubscriptionDetectionTemplate();
199
+ const context = await template.getContext();
200
+ const notification = await template.getTemplate();
201
+
202
+ await Notification.sendToUser(context.userDid, notification as any);
203
+ logger.info('Metering subscription detection created', context);
204
+ } catch (error) {
205
+ logger.error('Failed to create metering subscription detection', error);
206
+ }
207
+ }
@@ -10,6 +10,8 @@ export const stripePaymentCronTime: string = process.env.STRIPE_PAYMENT_CRON_TIM
10
10
  export const stripeSubscriptionCronTime: string = process.env.STRIPE_SUBSCRIPTION_CRON_TIME || '0 10 */8 * * *'; // 默认每 8小时 执行一次
11
11
  export const revokeStakeCronTime: string = process.env.REVOKE_STAKE_CRON_TIME || '0 */5 * * * *'; // 默认每 5 min 行一次
12
12
  export const daysUntilCancel: string | undefined = process.env.DAYS_UNTIL_CANCEL;
13
+ export const meteringSubscriptionDetectionCronTime: string =
14
+ process.env.METERING_SUBSCRIPTION_DETECTION_CRON_TIME || '0 0 10 * * *'; // 默认每天 10:00 执行
13
15
 
14
16
  export default {
15
17
  ...env,
@@ -336,3 +336,19 @@ export function getSubscriptionNotificationCustomActions(
336
336
  link: x?.link,
337
337
  }));
338
338
  }
339
+
340
+ export function getAdminBillingSubscriptionsUrl({ locale, userDid }: { locale: string; userDid: string }) {
341
+ return getUrl(withQuery('admin/billing/subscriptions', { locale, ...getConnectQueryParam({ userDid }) }));
342
+ }
343
+
344
+ export function getAdminBillingSubscriptionUrl({
345
+ locale,
346
+ userDid,
347
+ subscriptionId,
348
+ }: {
349
+ locale: string;
350
+ userDid: string;
351
+ subscriptionId: string;
352
+ }) {
353
+ return getUrl(withQuery(`admin/billing/${subscriptionId}`, { locale, ...getConnectQueryParam({ userDid }) }));
354
+ }
@@ -66,6 +66,14 @@ export default flat({
66
66
  body: 'No usage report for {productName} detected, please check.',
67
67
  },
68
68
 
69
+ meteringSubscriptionDetection: {
70
+ title: '[{appName}] Metering subscription detection',
71
+ body: 'During {startTimeStr} - {endTimeStr}, a total of {totalCount} subscriptions with usage-based billing were scanned. \nOut of these, {normalCount} were normal, while {abnormalCount} had anomalies, including {unreportedCount} unreported subscriptions and {discrepantCount} with billing discrepancies. \n\n Abnormal subscriptions:',
72
+ healthyBody:
73
+ 'During {startTimeStr} - {endTimeStr}, a total of {totalCount} subscriptions with usage-based billing were scanned, and all subscriptions were normal.',
74
+ view: 'Manage subscriptions',
75
+ },
76
+
69
77
  subscriptionTrialStart: {
70
78
  title: 'Welcome to the start of your {productName} trial',
71
79
  body: 'Congratulations on your {productName} trial! The length of the trial is {trialDuration} and will end at {subscriptionTrialEnd}. Have fun with {productName}!',
@@ -66,6 +66,13 @@ export default flat({
66
66
  body: '检测到 {productName} 账单金额核算不一致,请留意。',
67
67
  },
68
68
 
69
+ meteringSubscriptionDetection: {
70
+ title: '[{appName}] 按量计费订阅检测',
71
+ body: '在 {startTimeStr} - {endTimeStr} 期间,共扫描了 {totalCount} 份按量计费的订阅,其中 {normalCount} 份为正常订阅,{abnormalCount} 份存在异常,包括 {unreportedCount} 份未上报的订阅和 {discrepantCount} 份账单核算有问题的订阅。\n\n 异常订阅:',
72
+ healthyBody: '在 {startTimeStr} - {endTimeStr} 期间,共扫描了 {totalCount} 份按量计费的订阅,且所有订阅均正常。',
73
+ view: '管理订阅',
74
+ },
75
+
69
76
  subscriptionTrialStart: {
70
77
  title: '欢迎开始您的 {productName} 试用之旅',
71
78
  body: '恭喜您获得了 {productName} 的试用资格!试用期时长为 {trialDuration},将于 {subscriptionTrialEnd} 结束。祝您使用愉快!',
package/blocklet.yml CHANGED
@@ -14,7 +14,7 @@ repository:
14
14
  type: git
15
15
  url: git+https://github.com/blocklet/payment-kit.git
16
16
  specVersion: 1.2.8
17
- version: 1.16.1
17
+ version: 1.16.3
18
18
  logo: logo.png
19
19
  files:
20
20
  - dist
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "payment-kit",
3
- "version": "1.16.1",
3
+ "version": "1.16.3",
4
4
  "scripts": {
5
5
  "dev": "blocklet dev --open",
6
6
  "eject": "vite eject",
@@ -9,7 +9,7 @@
9
9
  "format": "prettier -w src",
10
10
  "test": "node scripts/jest.js",
11
11
  "coverage": "npm run test -- --coverage",
12
- "start": "vite-node -c vite-server.config.ts -w api/dev.ts",
12
+ "start": "tsx watch api/dev.ts",
13
13
  "clean": "node scripts/build-clean.js",
14
14
  "bundle": "tsc --noEmit && npm run bundle:client && npm run bundle:api",
15
15
  "bundle:client": "vite build",
@@ -44,29 +44,29 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@abtnode/cron": "1.16.33-beta-20241031-073543-49b1ff9b",
47
- "@arcblock/did": "^1.18.139",
47
+ "@arcblock/did": "^1.18.147",
48
48
  "@arcblock/did-auth-storage-nedb": "^1.7.1",
49
- "@arcblock/did-connect": "^2.10.65",
50
- "@arcblock/did-util": "^1.18.139",
51
- "@arcblock/jwt": "^1.18.139",
52
- "@arcblock/ux": "^2.10.65",
53
- "@arcblock/validator": "^1.18.139",
49
+ "@arcblock/did-connect": "^2.10.67",
50
+ "@arcblock/did-util": "^1.18.147",
51
+ "@arcblock/jwt": "^1.18.147",
52
+ "@arcblock/ux": "^2.10.67",
53
+ "@arcblock/validator": "^1.18.147",
54
54
  "@blocklet/js-sdk": "1.16.33-beta-20241031-073543-49b1ff9b",
55
55
  "@blocklet/logger": "1.16.33-beta-20241031-073543-49b1ff9b",
56
- "@blocklet/payment-react": "1.16.1",
56
+ "@blocklet/payment-react": "1.16.3",
57
57
  "@blocklet/sdk": "1.16.33-beta-20241031-073543-49b1ff9b",
58
- "@blocklet/ui-react": "^2.10.65",
59
- "@blocklet/uploader": "^0.1.51",
58
+ "@blocklet/ui-react": "^2.10.67",
59
+ "@blocklet/uploader": "^0.1.52",
60
60
  "@blocklet/xss": "^0.1.12",
61
61
  "@mui/icons-material": "^5.16.6",
62
62
  "@mui/lab": "^5.0.0-alpha.173",
63
63
  "@mui/material": "^5.16.6",
64
64
  "@mui/system": "^5.16.6",
65
- "@ocap/asset": "^1.18.139",
66
- "@ocap/client": "^1.18.139",
67
- "@ocap/mcrypto": "^1.18.139",
68
- "@ocap/util": "^1.18.139",
69
- "@ocap/wallet": "^1.18.139",
65
+ "@ocap/asset": "^1.18.147",
66
+ "@ocap/client": "^1.18.147",
67
+ "@ocap/mcrypto": "^1.18.147",
68
+ "@ocap/util": "^1.18.147",
69
+ "@ocap/wallet": "^1.18.147",
70
70
  "@stripe/react-stripe-js": "^2.7.3",
71
71
  "@stripe/stripe-js": "^2.4.0",
72
72
  "ahooks": "^3.8.0",
@@ -120,7 +120,7 @@
120
120
  "devDependencies": {
121
121
  "@abtnode/types": "1.16.33-beta-20241031-073543-49b1ff9b",
122
122
  "@arcblock/eslint-config-ts": "^0.3.3",
123
- "@blocklet/payment-types": "1.16.1",
123
+ "@blocklet/payment-types": "1.16.3",
124
124
  "@types/cookie-parser": "^1.4.7",
125
125
  "@types/cors": "^2.8.17",
126
126
  "@types/debug": "^4.1.12",
@@ -144,12 +144,13 @@
144
144
  "rollup-plugin-visualizer": "^5.12.0",
145
145
  "ts-jest": "^29.2.5",
146
146
  "ts-node": "^10.9.2",
147
+ "tsx": "^4.19.2",
147
148
  "type-fest": "^4.23.0",
148
149
  "typescript": "^4.9.5",
149
150
  "vite": "^5.3.5",
150
151
  "vite-node": "^2.0.4",
151
152
  "vite-plugin-babel-import": "^2.0.5",
152
- "vite-plugin-blocklet": "^0.9.12",
153
+ "vite-plugin-blocklet": "^0.9.13",
153
154
  "vite-plugin-node-polyfills": "^0.21.0",
154
155
  "vite-plugin-svgr": "^4.2.0",
155
156
  "vite-tsconfig-paths": "^4.3.2",
@@ -165,5 +166,5 @@
165
166
  "parser": "typescript"
166
167
  }
167
168
  },
168
- "gitHead": "590597d056e31eafd2b8ebd2a9d0a0c236c33440"
169
+ "gitHead": "6accc56a51e4ea0906e65f69dc5f41eaa82685fb"
169
170
  }
@@ -2,10 +2,18 @@ import { CopyButton } from '@arcblock/ux/lib/ClickToCopy';
2
2
  import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
3
3
  import { getWordBreakStyle } from '@blocklet/payment-react';
4
4
  import { Box, Stack, Typography } from '@mui/material';
5
+ import type { ReactNode } from 'react';
5
6
 
6
- export default function Copyable({ text, children, style }: { text: string; children?: React.ReactNode; style?: any }) {
7
+ interface CopyableProps {
8
+ text: string;
9
+ children?: ReactNode;
10
+ style?: React.CSSProperties;
11
+ }
12
+ export default function Copyable({ text, children, style }: CopyableProps) {
7
13
  const { locale } = useLocaleContext();
8
14
  return (
15
+ /* eslint-disable-next-line @typescript-eslint/ban-ts-comment */
16
+ // @ts-ignore
9
17
  <CopyButton
10
18
  showTooltip={false}
11
19
  content={text}
@@ -20,10 +28,6 @@ export default function Copyable({ text, children, style }: { text: string; chil
20
28
  sx={{
21
29
  mr: 0.5,
22
30
  maxWidth: 480,
23
- // overflow: 'hidden',
24
- // fontSize: 'inherit',
25
- // textOverflow: 'ellipsis',
26
- // whiteSpace: 'nowrap',
27
31
  wordBreak: getWordBreakStyle(text),
28
32
  whiteSpace: 'break-spaces',
29
33
  minWidth: '60px',