nexushub-commands 2.9.2 → 2.9.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.
@@ -265,27 +265,13 @@ tslib_1.__decorate([
265
265
  if (config.currency.toUpperCase() === 'RUB' && minDepositByMethod && minDepositByMethod[args.method] !== undefined && (yield minAmount.convert({ from: config.currency, to: 'RUB' })) < minDepositByMethod[args.method])
266
266
  minAmount = yield minDepositByMethod[args.method].convert({ from: 'RUB', to: config.currency });
267
267
  validateArgs.minAmount = minAmount;
268
- // Функция для красивого округления суммы
268
+ // Округление: малые суммы по magnitude, от 1000 — по 500
269
269
  const roundToNiceNumber = (amount) => {
270
270
  if (amount <= 0)
271
271
  return amount;
272
- // Для больших сумм (от 1000) округляем по тысячам
273
- if (amount >= 1000) {
274
- const thousands = amount / 1000;
275
- const magnitude = Math.pow(10, Math.floor(Math.log10(thousands)));
276
- const normalized = thousands / magnitude;
277
- let multiplier;
278
- if (normalized <= 1.5)
279
- multiplier = 1;
280
- else if (normalized <= 3)
281
- multiplier = 2;
282
- else if (normalized <= 7)
283
- multiplier = 5;
284
- else
285
- multiplier = 10;
286
- return Math.round((thousands / (magnitude * multiplier)) * (magnitude * multiplier)) * 1000;
287
- }
288
- // Для малых сумм используем оригинальную логику
272
+ if (amount >= 1000)
273
+ return Math.round(amount / 500) * 500;
274
+ // Для малых сумм «красивые» числа (1, 2, 5, 10 * 10^n)
289
275
  const magnitude = Math.pow(10, Math.floor(Math.log10(amount)));
290
276
  const normalized = amount / magnitude;
291
277
  let multiplier;
@@ -299,17 +285,31 @@ tslib_1.__decorate([
299
285
  multiplier = 10;
300
286
  return Math.round((amount / (magnitude * multiplier)) * (magnitude * multiplier));
301
287
  };
288
+ // Минимальное «красивое» число >= amount (для первой кнопки)
289
+ const ceilToNiceNumber = (amount) => {
290
+ const r = roundToNiceNumber(amount);
291
+ if (r >= amount)
292
+ return r;
293
+ return amount >= 1000 ? r + 500 : 1000;
294
+ };
295
+ // Максимальное «красивое» число <= amount (для последней кнопки)
296
+ const floorToNiceNumber = (amount) => {
297
+ const r = roundToNiceNumber(amount);
298
+ if (r <= amount)
299
+ return r;
300
+ return amount >= 1000 ? r - 500 : roundToNiceNumber(amount - 1);
301
+ };
302
302
  // Генерация промежуточных сумм
303
303
  const min = Number(minAmount);
304
304
  const max = Number(maxDeposit);
305
305
  const amounts = [];
306
306
  if (max <= min) {
307
307
  // Если максимум не больше минимума, показываем только минимум
308
- amounts.push(min);
308
+ amounts.push(roundToNiceNumber(min));
309
309
  }
310
310
  else {
311
- // Добавляем минимум
312
- amounts.push(Math.ceil(min));
311
+ // Первая кнопка — красивое число не ниже минимума
312
+ amounts.push(Math.max(min, ceilToNiceNumber(min)));
313
313
  // Вычисляем 4 промежуточные суммы
314
314
  const range = max - min;
315
315
  const step = range / 5;
@@ -323,12 +323,15 @@ tslib_1.__decorate([
323
323
  intermediateAmounts.add(finalAmount);
324
324
  }
325
325
  }
326
- // Добавляем промежуточные суммы, убирая дубликаты
327
- const sortedIntermediate = Array.from(intermediateAmounts).sort((a, b) => a - b);
326
+ // Добавляем промежуточные суммы (без дубликатов с первой кнопкой)
327
+ const sortedIntermediate = Array.from(intermediateAmounts)
328
+ .sort((a, b) => a - b)
329
+ .filter((x) => x > amounts[0]);
328
330
  amounts.push(...sortedIntermediate);
329
- // Добавляем максимум
330
- if (max > amounts[amounts.length - 1])
331
- amounts.push(Math.ceil(max));
331
+ // Последняя кнопка — красивое число не выше максимума
332
+ const niceMax = Math.min(max, floorToNiceNumber(max));
333
+ if (niceMax > amounts[amounts.length - 1])
334
+ amounts.push(niceMax);
332
335
  // Ограничиваем до 6 сумм максимум
333
336
  if (amounts.length > 6) {
334
337
  // Берем минимум, максимум и равномерно распределенные промежуточные
@@ -23,35 +23,40 @@ let SendChequeCommand = SendChequeCommand_1 = class SendChequeCommand extends mi
23
23
  header: '<blockquote><b>🧾 Подтверждение оплаты счета</b></blockquote>',
24
24
  footer: '<i>Пожалуйста, отправьте квитанцию, подтверждающую оплату счета в следующем сообщении</i>',
25
25
  }, undefined, (msg) => tslib_1.__awaiter(this, void 0, void 0, function* () {
26
- var _a, _b;
27
- let url = null;
26
+ var _a, _b, _c, _d;
27
+ let url = null, isPDF = false;
28
28
  if ((_a = msg.attachments.photo) === null || _a === void 0 ? void 0 : _a.length) {
29
29
  url = `https://api.telegram.org/file/bot${this.client.params.token}/${(yield this.client.api.getFile({ file_id: msg.attachments.photo.at(-1).file_id })).file_path}`;
30
30
  }
31
31
  else if (msg.attachments.document) {
32
- if (!((_b = msg.attachments.document.mime_type) === null || _b === void 0 ? void 0 : _b.startsWith('image/')))
33
- throw new Error('Ваш файл не является изображением');
32
+ if (!((_b = msg.attachments.document.mime_type) === null || _b === void 0 ? void 0 : _b.startsWith('image/')) && msg.attachments.document.mime_type !== 'application/pdf')
33
+ throw new Error('Ваш файл не является изображением или PDF файлом');
34
+ isPDF = msg.attachments.document.mime_type === 'application/pdf';
34
35
  url = `https://api.telegram.org/file/bot${this.client.params.token}/${(yield this.client.api.getFile({ file_id: msg.attachments.document.file_id })).file_path}`;
35
36
  }
36
37
  if (!url)
37
38
  throw new Error('Пожалуйста, отправьте изображение с квитанцией в следующем сообщении');
39
+ if (!isPDF && ((_d = (_c = order === null || order === void 0 ? void 0 : order.qrcode) === null || _c === void 0 ? void 0 : _c.aggregator) === null || _d === void 0 ? void 0 : _d.name) === 'paynova-qrcode')
40
+ throw new Error('Пожалуйста, отправьте PDF файл с квитанцией в следующем сообщении');
38
41
  try {
39
- const worker = yield SendChequeCommand_1.WORKER;
40
- const { data } = yield worker.recognize(url);
41
- const noSuccess = !!['Ожидает подтверждения', обработке'].find((x) => data.text.includes(x));
42
- if (noSuccess) {
43
- return context.sendFormatted({
44
- designImages: order.method === 'card' ? ['deposit-card', 'deposit'] : order.method === 'cryptoBot' ? ['deposit-crypto-bot', 'deposit-crypto', 'deposit'] : [`deposit-crypto-${order.currency.toLowerCase()}`, 'deposit-crypto-wallet', 'deposit-crypto', 'deposit'],
45
- photo: config.images.depositCard,
46
- // prettier-ignore
47
- header: '<blockquote><b>🧾 Подтверждение оплаты счета</b></blockquote>\n\n' +
48
- '<i>Система определила, что ваша транзакция на данный момент находится в обработке банка. Пожалуйста, дождитесь подтверждения оплаты и повторите попытку</i>\n\n' +
49
- '<b>ℹ️ Как только транзакция будет подтверждена, в квитанции появится статус Подтвержден</b>',
50
- }, {
51
- reply_markup: {
52
- inline_keyboard: [[{ text: '🔄 Повторить попытку', command: SendChequeCommand_1, payload: { orderId } }]],
53
- },
54
- });
42
+ if (!isPDF) {
43
+ const worker = yield SendChequeCommand_1.WORKER;
44
+ const { data } = yield worker.recognize(url);
45
+ const noSuccess = !!['Ожидает подтверждения', 'В обработке'].find((x) => data.text.includes(x));
46
+ if (noSuccess) {
47
+ return context.sendFormatted({
48
+ designImages: order.method === 'card' ? ['deposit-card', 'deposit'] : order.method === 'cryptoBot' ? ['deposit-crypto-bot', 'deposit-crypto', 'deposit'] : [`deposit-crypto-${order.currency.toLowerCase()}`, 'deposit-crypto-wallet', 'deposit-crypto', 'deposit'],
49
+ photo: config.images.depositCard,
50
+ // prettier-ignore
51
+ header: '<blockquote><b>🧾 Подтверждение оплаты счета</b></blockquote>\n\n' +
52
+ '<i>Система определила, что ваша транзакция на данный момент находится в обработке банка. Пожалуйста, дождитесь подтверждения оплаты и повторите попытку</i>\n\n' +
53
+ '<b>ℹ️ Как только транзакция будет подтверждена, в квитанции появится статус Подтвержден</b>',
54
+ }, {
55
+ reply_markup: {
56
+ inline_keyboard: [[{ text: '🔄 Повторить попытку', command: SendChequeCommand_1, payload: { orderId } }]],
57
+ },
58
+ });
59
+ }
55
60
  }
56
61
  }
57
62
  catch (error) {
@@ -80,7 +85,7 @@ let SendChequeCommand = SendChequeCommand_1 = class SendChequeCommand extends mi
80
85
  photo: photoURL,
81
86
  });
82
87
  return context.sendFormatted({
83
- photo: photoURL,
88
+ photo: photoURL.endsWith('.pdf') ? config.images.depositPDF : photoURL,
84
89
  header: '<blockquote><b>🧾 Подтверждение оплаты счета</b></blockquote>',
85
90
  footer: '<i>Ваш чек был успешно отправлен, ожидайте подтверждения. Вы получите уведомление, как только оплата будет подтверждена</i>',
86
91
  }, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nexushub-commands",
3
- "version": "2.9.2",
3
+ "version": "2.9.3",
4
4
  "main": "./lib/index.js",
5
5
  "license": "MIT",
6
6
  "dependencies": {
@@ -150,37 +150,33 @@ export class DepositCommand extends Command {
150
150
 
151
151
  validateArgs.minAmount = minAmount
152
152
 
153
- // Функция для красивого округления суммы
153
+ // Округление: малые суммы по magnitude, от 1000 — по 500
154
154
  const roundToNiceNumber = (amount: number): number => {
155
155
  if (amount <= 0) return amount
156
+ if (amount >= 1000) return Math.round(amount / 500) * 500
156
157
 
157
- // Для больших сумм (от 1000) округляем по тысячам
158
- if (amount >= 1000) {
159
- const thousands = amount / 1000
160
- const magnitude = Math.pow(10, Math.floor(Math.log10(thousands)))
161
- const normalized = thousands / magnitude
162
-
163
- let multiplier: number
164
- if (normalized <= 1.5) multiplier = 1
165
- else if (normalized <= 3) multiplier = 2
166
- else if (normalized <= 7) multiplier = 5
167
- else multiplier = 10
168
-
169
- return Math.round((thousands / (magnitude * multiplier)) * (magnitude * multiplier)) * 1000
170
- }
171
-
172
- // Для малых сумм используем оригинальную логику
158
+ // Для малых сумм — «красивые» числа (1, 2, 5, 10 * 10^n)
173
159
  const magnitude = Math.pow(10, Math.floor(Math.log10(amount)))
174
160
  const normalized = amount / magnitude
175
-
176
161
  let multiplier: number
177
162
  if (normalized <= 1.5) multiplier = 1
178
163
  else if (normalized <= 3) multiplier = 2
179
164
  else if (normalized <= 7) multiplier = 5
180
165
  else multiplier = 10
181
-
182
166
  return Math.round((amount / (magnitude * multiplier)) * (magnitude * multiplier))
183
167
  }
168
+ // Минимальное «красивое» число >= amount (для первой кнопки)
169
+ const ceilToNiceNumber = (amount: number): number => {
170
+ const r = roundToNiceNumber(amount)
171
+ if (r >= amount) return r
172
+ return amount >= 1000 ? r + 500 : 1000
173
+ }
174
+ // Максимальное «красивое» число <= amount (для последней кнопки)
175
+ const floorToNiceNumber = (amount: number): number => {
176
+ const r = roundToNiceNumber(amount)
177
+ if (r <= amount) return r
178
+ return amount >= 1000 ? r - 500 : roundToNiceNumber(amount - 1)
179
+ }
184
180
 
185
181
  // Генерация промежуточных сумм
186
182
  const min = Number(minAmount)
@@ -189,10 +185,10 @@ export class DepositCommand extends Command {
189
185
 
190
186
  if (max <= min) {
191
187
  // Если максимум не больше минимума, показываем только минимум
192
- amounts.push(min)
188
+ amounts.push(roundToNiceNumber(min))
193
189
  } else {
194
- // Добавляем минимум
195
- amounts.push(Math.ceil(min))
190
+ // Первая кнопка — красивое число не ниже минимума
191
+ amounts.push(Math.max(min, ceilToNiceNumber(min)))
196
192
 
197
193
  // Вычисляем 4 промежуточные суммы
198
194
  const range = max - min
@@ -210,12 +206,15 @@ export class DepositCommand extends Command {
210
206
  }
211
207
  }
212
208
 
213
- // Добавляем промежуточные суммы, убирая дубликаты
214
- const sortedIntermediate = Array.from(intermediateAmounts).sort((a, b) => a - b)
209
+ // Добавляем промежуточные суммы (без дубликатов с первой кнопкой)
210
+ const sortedIntermediate = Array.from(intermediateAmounts)
211
+ .sort((a, b) => a - b)
212
+ .filter((x) => x > amounts[0])
215
213
  amounts.push(...sortedIntermediate)
216
214
 
217
- // Добавляем максимум
218
- if (max > amounts[amounts.length - 1]) amounts.push(Math.ceil(max))
215
+ // Последняя кнопка — красивое число не выше максимума
216
+ const niceMax = Math.min(max, floorToNiceNumber(max))
217
+ if (niceMax > amounts[amounts.length - 1]) amounts.push(niceMax)
219
218
 
220
219
  // Ограничиваем до 6 сумм максимум
221
220
  if (amounts.length > 6) {
@@ -26,42 +26,47 @@ export class SendChequeCommand extends Command {
26
26
  },
27
27
  undefined,
28
28
  async (msg) => {
29
- let url: any = null
29
+ let url: any = null,
30
+ isPDF = false
30
31
  if (msg.attachments.photo?.length) {
31
32
  url = `https://api.telegram.org/file/bot${this.client.params.token}/${(await this.client.api.getFile({ file_id: msg.attachments.photo.at(-1)!.file_id })).file_path}`
32
33
  } else if (msg.attachments.document) {
33
- if (!msg.attachments.document.mime_type?.startsWith('image/')) throw new Error('Ваш файл не является изображением')
34
+ if (!msg.attachments.document.mime_type?.startsWith('image/') && msg.attachments.document.mime_type !== 'application/pdf') throw new Error('Ваш файл не является изображением или PDF файлом')
35
+ isPDF = msg.attachments.document.mime_type === 'application/pdf'
34
36
 
35
37
  url = `https://api.telegram.org/file/bot${this.client.params.token}/${(await this.client.api.getFile({ file_id: msg.attachments.document.file_id })).file_path}`
36
38
  }
37
39
 
38
40
  if (!url) throw new Error('Пожалуйста, отправьте изображение с квитанцией в следующем сообщении')
41
+ if (!isPDF && order?.qrcode?.aggregator?.name === 'paynova-qrcode') throw new Error('Пожалуйста, отправьте PDF файл с квитанцией в следующем сообщении')
39
42
 
40
43
  try {
41
- const worker = await SendChequeCommand.WORKER
44
+ if (!isPDF) {
45
+ const worker = await SendChequeCommand.WORKER
42
46
 
43
- const { data } = await worker.recognize(url)
44
- const noSuccess = !!['Ожидает подтверждения', 'В обработке'].find((x) => data.text.includes(x))
47
+ const { data } = await worker.recognize(url)
48
+ const noSuccess = !!['Ожидает подтверждения', 'В обработке'].find((x) => data.text.includes(x))
45
49
 
46
- if (noSuccess) {
47
- return context.sendFormatted(
48
- {
49
- designImages: order.method === 'card' ? ['deposit-card', 'deposit'] : order.method === 'cryptoBot' ? ['deposit-crypto-bot', 'deposit-crypto', 'deposit'] : [`deposit-crypto-${order.currency.toLowerCase()}`, 'deposit-crypto-wallet', 'deposit-crypto', 'deposit'],
50
- photo: config.images.depositCard,
51
- // prettier-ignore
52
- header:
53
- '<blockquote><b>🧾 Подтверждение оплаты счета</b></blockquote>\n\n' +
54
-
55
- '<i>Система определила, что ваша транзакция на данный момент находится в обработке банка. Пожалуйста, дождитесь подтверждения оплаты и повторите попытку</i>\n\n' +
56
-
57
- '<b>ℹ️ Как только транзакция будет подтверждена, в квитанции появится статус Подтвержден</b>',
58
- },
59
- {
60
- reply_markup: {
61
- inline_keyboard: [[{ text: '🔄 Повторить попытку', command: SendChequeCommand, payload: { orderId } }]],
50
+ if (noSuccess) {
51
+ return context.sendFormatted(
52
+ {
53
+ designImages: order.method === 'card' ? ['deposit-card', 'deposit'] : order.method === 'cryptoBot' ? ['deposit-crypto-bot', 'deposit-crypto', 'deposit'] : [`deposit-crypto-${order.currency.toLowerCase()}`, 'deposit-crypto-wallet', 'deposit-crypto', 'deposit'],
54
+ photo: config.images.depositCard,
55
+ // prettier-ignore
56
+ header:
57
+ '<blockquote><b>🧾 Подтверждение оплаты счета</b></blockquote>\n\n' +
58
+
59
+ '<i>Система определила, что ваша транзакция на данный момент находится в обработке банка. Пожалуйста, дождитесь подтверждения оплаты и повторите попытку</i>\n\n' +
60
+
61
+ '<b>ℹ️ Как только транзакция будет подтверждена, в квитанции появится статус Подтвержден</b>',
62
+ },
63
+ {
64
+ reply_markup: {
65
+ inline_keyboard: [[{ text: '🔄 Повторить попытку', command: SendChequeCommand, payload: { orderId } }]],
66
+ },
62
67
  },
63
- }
64
- )
68
+ )
69
+ }
65
70
  }
66
71
  } catch (error: any) {
67
72
  console.error(error)
@@ -93,15 +98,15 @@ export class SendChequeCommand extends Command {
93
98
 
94
99
  return context.sendFormatted(
95
100
  {
96
- photo: photoURL,
101
+ photo: photoURL.endsWith('.pdf') ? config.images.depositPDF : photoURL,
97
102
  header: '<blockquote><b>🧾 Подтверждение оплаты счета</b></blockquote>',
98
103
  footer: '<i>Ваш чек был успешно отправлен, ожидайте подтверждения. Вы получите уведомление, как только оплата будет подтверждена</i>',
99
104
  },
100
105
  {
101
106
  noBackButton: true,
102
- }
107
+ },
103
108
  )
104
- }
109
+ },
105
110
  )
106
111
  }
107
112
  }