payment-kit 1.15.27 β†’ 1.15.29

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.
@@ -462,12 +462,14 @@ export async function getUpcomingInvoiceAmount(subscriptionId: string) {
462
462
  const expanded = await Price.expand(items.map((x) => x.toJSON()));
463
463
 
464
464
  let amount = new BN(0);
465
+ let minExpectedAmount = new BN(0);
465
466
  for (const item of expanded) {
466
467
  const price = getSubscriptionItemPrice(item);
467
468
  if (price.type === 'recurring') {
468
469
  const unit = getPriceUintAmountByCurrency(price, subscription.currency_id);
469
470
  if (price.recurring?.usage_type === 'licensed') {
470
471
  amount = amount.add(new BN(unit).mul(new BN(item.quantity)));
472
+ minExpectedAmount = minExpectedAmount.add(new BN(unit).mul(new BN(item.quantity)));
471
473
  }
472
474
  if (price.recurring?.usage_type === 'metered') {
473
475
  const rawQuantity = await UsageRecord.getSummary({
@@ -481,12 +483,14 @@ export async function getUpcomingInvoiceAmount(subscriptionId: string) {
481
483
  // @ts-ignore
482
484
  const quantity = price.transformQuantity(rawQuantity);
483
485
  amount = amount.add(new BN(unit).mul(new BN(quantity)));
486
+ minExpectedAmount = minExpectedAmount.add(new BN(unit).mul(new BN(item.quantity)));
484
487
  }
485
488
  }
486
489
  }
487
490
 
488
491
  return {
489
492
  amount: amount.toString(),
493
+ minExpectedAmount: minExpectedAmount.toString(),
490
494
  start: subscription.current_period_start,
491
495
  end: subscription.current_period_end,
492
496
  currency,
@@ -11,12 +11,25 @@ import { authenticate } from '../libs/security';
11
11
  import { usageRecordQueue } from '../queues/usage-record';
12
12
  import { Invoice, Price, Subscription, SubscriptionItem, UsageRecord } from '../store/models';
13
13
  import logger from '../libs/logger';
14
+ import { getLock } from '../libs/lock';
14
15
 
15
16
  const router = Router();
16
17
  const auth = authenticate<UsageRecord>({ component: true, roles: ['owner', 'admin'] });
17
18
 
19
+ const UsageReportScheme = Joi.object({
20
+ subscription_item_id: Joi.string().required(),
21
+ quantity: Joi.number().required(),
22
+ action: Joi.string().valid('increment', 'set').optional(),
23
+ timestamp: Joi.number().optional(),
24
+ livemode: Joi.boolean().optional(),
25
+ }).unknown(true);
26
+
18
27
  // @link https://stripe.com/docs/api/usage_records/create
19
28
  router.post('/', auth, async (req, res) => {
29
+ const { error } = UsageReportScheme.validate(req.body);
30
+ if (error) {
31
+ return res.status(400).json({ error: error.message });
32
+ }
20
33
  const raw: Partial<UsageRecord> = pick(req.body, ['timestamp', 'quantity', 'subscription_item_id']);
21
34
  const item = await SubscriptionItem.findByPk(raw.subscription_item_id);
22
35
  if (!item) {
@@ -38,73 +51,89 @@ router.post('/', auth, async (req, res) => {
38
51
  raw.timestamp = dayjs().unix();
39
52
  }
40
53
 
41
- logger.info('Usage reporting', { subscriptionId: item.subscription_id, subscriptionItemId: item.id, body: req.body });
42
-
43
- let doc = await UsageRecord.findOne({
44
- where: { timestamp: raw.timestamp, subscription_item_id: raw.subscription_item_id },
45
- });
46
- if (doc) {
47
- if (doc.billed) {
48
- logger.info('UsageRecord updated', {
49
- subscriptionItemId: raw.subscription_item_id,
50
- timestamp: raw.timestamp,
51
- newQuantity: raw.quantity,
52
- });
53
- return res.status(400).json({ error: 'UsageRecord is immutable because already billed' });
54
- }
55
- if (req.body.action === 'increment') {
56
- await doc.increment('quantity', { by: raw.quantity });
57
- logger.info('UsageRecord incremented', {
58
- subscriptionItemId: raw.subscription_item_id,
59
- timestamp: raw.timestamp,
60
- incrementBy: raw.quantity,
61
- });
62
- } else {
63
- if (subscription.billing_thresholds?.amount_gte) {
64
- logger.warn('Invalid action for subscription with billing_thresholds', {
65
- subscriptionId: subscription.id,
66
- action: req.body.action,
54
+ const lock = getLock(`usage-record:${item.id}:${raw.timestamp}`);
55
+ try {
56
+ await lock.acquire();
57
+ logger.info('Usage reporting', {
58
+ subscriptionId: item.subscription_id,
59
+ subscriptionItemId: item.id,
60
+ body: req.body,
61
+ });
62
+
63
+ let doc = await UsageRecord.findOne({
64
+ where: { timestamp: raw.timestamp, subscription_item_id: raw.subscription_item_id },
65
+ });
66
+
67
+ const action = req.body.action || 'increment';
68
+ if (doc) {
69
+ if (doc.billed) {
70
+ logger.info('UsageRecord updated', {
71
+ subscriptionItemId: raw.subscription_item_id,
72
+ timestamp: raw.timestamp,
73
+ newQuantity: raw.quantity,
67
74
  });
68
- return res
69
- .status(400)
70
- .json({ error: 'UsageRecord action must be `increment` for subscriptions with billing_thresholds' });
75
+ return res.status(400).json({ error: 'UsageRecord is immutable because already billed' });
71
76
  }
72
- await doc.update({ quantity: raw.quantity });
73
- logger.info('UsageRecord updated', {
74
- subscriptionItemId: raw.subscription_item_id,
75
- timestamp: raw.timestamp,
76
- newQuantity: raw.quantity,
77
- });
77
+ if (action === 'increment') {
78
+ await doc.increment('quantity', { by: raw.quantity });
79
+ logger.info('UsageRecord incremented', {
80
+ subscriptionItemId: raw.subscription_item_id,
81
+ timestamp: raw.timestamp,
82
+ incrementBy: raw.quantity,
83
+ action,
84
+ });
85
+ } else {
86
+ if (subscription.billing_thresholds?.amount_gte) {
87
+ logger.warn('Invalid action for subscription with billing_thresholds', {
88
+ subscriptionId: subscription.id,
89
+ action,
90
+ });
91
+ return res
92
+ .status(400)
93
+ .json({ error: 'UsageRecord action must be `increment` for subscriptions with billing_thresholds' });
94
+ }
95
+ await doc.update({ quantity: raw.quantity });
96
+ logger.info('UsageRecord updated', {
97
+ subscriptionItemId: raw.subscription_item_id,
98
+ timestamp: raw.timestamp,
99
+ newQuantity: raw.quantity,
100
+ action,
101
+ });
102
+ }
103
+ } else {
104
+ raw.livemode = req.livemode;
105
+ doc = await UsageRecord.create(raw as UsageRecord);
78
106
  }
79
- } else {
80
- raw.livemode = req.livemode;
81
- doc = await UsageRecord.create(raw as UsageRecord);
82
- }
83
107
 
84
- if (subscription.billing_thresholds?.amount_gte) {
85
- usageRecordQueue.push({
86
- id: `usage-${subscription.id}`,
87
- job: { subscriptionId: subscription.id, subscriptionItemId: item.id },
108
+ if (subscription.billing_thresholds?.amount_gte) {
109
+ usageRecordQueue.push({
110
+ id: `usage-${subscription.id}`,
111
+ job: { subscriptionId: subscription.id, subscriptionItemId: item.id },
112
+ });
113
+ logger.info('UsageRecord pushed to queue', {
114
+ subscriptionId: subscription.id,
115
+ subscriptionItemId: item.id,
116
+ });
117
+ }
118
+ await forwardUsageRecordToStripe(item, {
119
+ quantity: Number(raw.quantity),
120
+ timestamp: raw.timestamp,
121
+ action,
88
122
  });
89
- logger.info('UsageRecord pushed to queue', {
90
- subscriptionId: subscription.id,
123
+ logger.info('UsageRecord forwarded to Stripe', {
91
124
  subscriptionItemId: item.id,
125
+ quantity: Number(raw.quantity),
126
+ timestamp: raw.timestamp,
127
+ action,
92
128
  });
129
+ await doc.reload();
130
+ return res.json(doc);
131
+ } catch (err) {
132
+ logger.error('Error in usage-records', { error: err });
133
+ return res.status(400).json({ error: err.message || 'UsageRecord creation failed' });
134
+ } finally {
135
+ lock.release();
93
136
  }
94
-
95
- await forwardUsageRecordToStripe(item, {
96
- quantity: Number(raw.quantity),
97
- timestamp: raw.timestamp,
98
- action: req.body.action,
99
- });
100
-
101
- logger.info('UsageRecord forwarded to Stripe', {
102
- subscriptionItemId: item.id,
103
- quantity: Number(raw.quantity),
104
- timestamp: raw.timestamp,
105
- action: req.body.action,
106
- });
107
- return res.json(doc);
108
137
  });
109
138
 
110
139
  // @link https://stripe.com/docs/api/usage_records/subscription_item_summary_list
@@ -179,7 +208,7 @@ const UsageRecordScheme = Joi.object({
179
208
 
180
209
  export function createUsageRecordQueryFn(doc?: Subscription) {
181
210
  return async (req: Request, res: Response) => {
182
- const { error, value: query } = await UsageRecordScheme.validate(req.query, { stripUnknown: true });
211
+ const { error, value: query } = UsageRecordScheme.validate(req.query, { stripUnknown: true });
183
212
  if (error) {
184
213
  return res.status(400).json({ error: `usage record request query invalid: ${error.message}` });
185
214
  }
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.15.27
17
+ version: 1.15.29
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.15.27",
3
+ "version": "1.15.29",
4
4
  "scripts": {
5
5
  "dev": "blocklet dev --open",
6
6
  "eject": "vite eject",
@@ -53,7 +53,7 @@
53
53
  "@arcblock/validator": "^1.18.137",
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.15.27",
56
+ "@blocklet/payment-react": "1.15.29",
57
57
  "@blocklet/sdk": "1.16.33-beta-20241031-073543-49b1ff9b",
58
58
  "@blocklet/ui-react": "^2.10.55",
59
59
  "@blocklet/uploader": "^0.1.51",
@@ -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.15.27",
123
+ "@blocklet/payment-types": "1.15.29",
124
124
  "@types/cookie-parser": "^1.4.7",
125
125
  "@types/cors": "^2.8.17",
126
126
  "@types/debug": "^4.1.12",
@@ -165,5 +165,5 @@
165
165
  "parser": "typescript"
166
166
  }
167
167
  },
168
- "gitHead": "8946aa1f48babb0f4c9da6d21ebd5025d6c91597"
168
+ "gitHead": "74c394cd2a81792ea30fdf019aafb7b4e2400373"
169
169
  }
package/scripts/sdk.js CHANGED
@@ -138,5 +138,24 @@ const payment = require('@blocklet/payment-js').default;
138
138
  // });
139
139
  // console.log('πŸš€ ~ paymentPrice:', paymentPrice);
140
140
 
141
+ // ζ΅‹θ―•δΈ‹εΉΆε‘δΈŠζŠ₯
142
+ // const promises = [
143
+ // {
144
+ // subscription_item_id: 'si_Tq4c2KsC40uPq7',
145
+ // quantity: 1,
146
+ // action: 'increment',
147
+ // livemode: false,
148
+ // timestamp: 1730692388,
149
+ // },
150
+ // // {
151
+ // // subscription_item_id: 'si_Tq4c2KsC40uPq7',
152
+ // // quantity: 2,
153
+ // // action: 'increment',
154
+ // // livemode: false,
155
+ // // timestamp: 1730692388,
156
+ // // },
157
+ // ];
158
+ // const results = await Promise.allSettled(promises.map((p) => payment.subscriptionItems.createUsageRecord(p)));
159
+ // console.log('πŸš€ ~ results:', results);
141
160
  process.exit(0);
142
161
  })();
@@ -100,7 +100,9 @@ export default function RechargePage() {
100
100
  // Calculate preset amounts
101
101
  const getCycleAmount = (cycles: number) =>
102
102
  fromUnitToToken(
103
- new BN(upcomingRes.data.amount).mul(new BN(cycles)).toString(),
103
+ new BN(upcomingRes.data.amount === '0' ? upcomingRes.data.minExpectedAmount : upcomingRes.data.amount)
104
+ .mul(new BN(cycles))
105
+ .toString(),
104
106
  upcomingRes.data?.currency?.decimal
105
107
  );
106
108
  setPresetAmounts([