sequelize-game-bank 1.0.0 → 1.0.1

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 (69) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +40 -0
  3. package/database/models/Account.js +1 -4
  4. package/database/models/Credit.js +1 -4
  5. package/database/models/Transaction.js +2 -4
  6. package/database/models/User.js +6 -9
  7. package/database/services/account/add-manny.js +2 -6
  8. package/database/services/account/change-pincode.js +1 -6
  9. package/database/services/account/create-credit.js +49 -100
  10. package/database/services/account/create.js +2 -6
  11. package/database/services/account/find-manny.js +1 -3
  12. package/database/services/account/logs.js +3 -10
  13. package/database/services/account/remove-manny.js +2 -5
  14. package/database/services/account/transfer.js +39 -37
  15. package/database/services/bot/bot.js +5 -20
  16. package/database/services/bot/cron-schedule.js +122 -0
  17. package/database/services/bot/write.js +3 -12
  18. package/database/services/user/change-avatar.js +1 -5
  19. package/database/services/user/change-gmail.js +1 -3
  20. package/database/services/user/change-password.js +1 -3
  21. package/database/services/user/create.js +1 -9
  22. package/database/services/user/delete.js +1 -3
  23. package/database/services/user/disable-2FA.js +2 -5
  24. package/database/services/user/enable-2FA.js +1 -4
  25. package/database/services/user/login.js +3 -15
  26. package/database/services/user/math-manny.js +1 -2
  27. package/index.js +20 -42
  28. package/package.json +21 -5
  29. package/public/credit.html +26 -0
  30. package/public/js/js.js +160 -26
  31. package/public/transfer.html +41 -39
  32. package/public/uploads/avatars/default.png +0 -0
  33. package/server/middleware/auth.js +1 -6
  34. package/server/server.js +3 -20
  35. package/src/logo/icon.png +0 -0
  36. package/.env +0 -114
  37. package/database/citybank.db +0 -0
  38. package/database/config/init-db.js +0 -33
  39. package/database/services/bot/generators/ban-bot.html +0 -1
  40. package/database/services/bot/generators/ban-bot.txt +0 -1
  41. package/database/services/bot/generators/disable-2FA-bot.html +0 -1
  42. package/database/services/bot/generators/disable-2FA-bot.txt +0 -1
  43. package/database/services/bot/generators/enable-2FA-bot.html +0 -1
  44. package/database/services/bot/generators/enable-2FA-bot.txt +0 -1
  45. package/database/services/bot/generators/login-bot.html +0 -1
  46. package/database/services/bot/generators/login-bot.txt +0 -1
  47. package/database/services/bot/generators/register-bot.html +0 -1
  48. package/database/services/bot/generators/register-bot.txt +0 -7
  49. package/database/services/bot/generators/transfer-from-bot.html +0 -1
  50. package/database/services/bot/generators/transfer-from-bot.txt +0 -1
  51. package/database/services/bot/generators/transfer-to-bot.html +0 -1
  52. package/database/services/bot/generators/transfer-to-bot.txt +0 -1
  53. package/database/services/bot/generators/unban-bot.html +0 -1
  54. package/database/services/bot/generators/unban-bot.txt +0 -1
  55. package/logs/errors.log +0 -14
  56. package/public/uploads/avatars/Pavel_1790269874496.png +0 -0
  57. package/public/uploads/avatars/Pavel_1790275457821.png +0 -0
  58. package/public/uploads/avatars/Pavel_1790867570006.png +0 -0
  59. package/public/uploads/avatars/Romanenko_1790270954677.png +0 -0
  60. package/public/uploads/avatars/root_1790275537324.png +0 -0
  61. package/public/uploads/avatars/root_1790275537381.png +0 -0
  62. package/public/uploads/avatars/root_1790349234549.png +0 -0
  63. package/public/uploads/avatars/root_1790519734671.png +0 -0
  64. package/public/uploads/avatars/root_1790879784620.png +0 -0
  65. package/public/uploads/avatars/root_1790879790948.png +0 -0
  66. package/public/uploads/avatars/root_1790879796755.png +0 -0
  67. package/public/uploads/avatars/root_1790962800544.png +0 -0
  68. package/public/uploads/avatars/root_1791009911239.png +0 -0
  69. package/test.js +0 -20
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026, RPM-programmer (GitHub) / prm-programer (npm)
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,40 @@
1
+ > # sequelize-game-bank
2
+
3
+ <img src="./src/logo/icon.png" alt="sequelize-game-bank logo" width="160" height="160" style="border-radius: 12%; margin-bottom: 20px;" />
4
+
5
+ ## npm модуль для создания полноценного банка на express, sequelize (sqlite).
6
+
7
+ ## О проекте
8
+
9
+ **sequelize-game-bank** — это готовый бэкенд-модуль, который за пару строк кода разворачивает изолированную банковскую систему для вашей игры или тестовой среды. Он автоматически создает базу данных SQLite через Sequelize и монтирует защищенные REST API роуты для Express.
10
+
11
+ * **Изолированная песочница:** Идеально для безопасной симуляции балансов, переводов и транзакций без риска реальных денег.
12
+ * **Всё включено:** База данных (SQLite), модели (Sequelize) и готовые эндпоинты (Express) поставляются в одном пакете.
13
+ * **Быстрый старт:** Не требует настройки внешних баз данных — всё работает "из коробки" в локальном файле или памяти.
14
+ * **Поддержка Nodemailer** Возможность отправлять сообщения на gmail
15
+
16
+ ## 🚀 Установка
17
+
18
+ Установите пакет через ваш любимый менеджер пакетов:
19
+
20
+ ```bash
21
+ npm install sequelize-game-bank
22
+ ```
23
+
24
+ ## 💻 Быстрый старт
25
+
26
+ Просто подключите модуль в ваше существующее Express-приложение:
27
+
28
+ ```javascript
29
+ const BANK = require('./index.js');
30
+
31
+ const app = (async function initBank(){
32
+ try {
33
+ return await BANK();
34
+ } catch {
35
+ console.log("Ошибка при инициализации банка!");
36
+ }
37
+ })();
38
+
39
+ // Далее ваш код
40
+ ```
@@ -1,7 +1,6 @@
1
1
  const { DataTypes } = require('sequelize');
2
2
  const sequelize = require('../config/init-db');
3
3
  const User = require('./User');
4
-
5
4
  const Account = sequelize.define('account', {
6
5
  id: {
7
6
  type: DataTypes.INTEGER,
@@ -37,8 +36,6 @@ const Account = sequelize.define('account', {
37
36
  field: '2FA-status'
38
37
  }
39
38
  });
40
-
41
39
  User.hasMany(Account, { foreignKey: 'user', sourceKey: 'name' });
42
40
  Account.belongsTo(User, { foreignKey: 'user', targetKey: 'name', as: 'owner' });
43
-
44
- module.exports = Account;
41
+ module.exports = Account;
@@ -1,7 +1,6 @@
1
1
  const { DataTypes } = require('sequelize');
2
2
  const sequelize = require('../config/init-db');
3
3
  const Account = require('./Account');
4
-
5
4
  const Credit = sequelize.define('credit', {
6
5
  id: {
7
6
  type: DataTypes.INTEGER,
@@ -32,8 +31,6 @@ const Credit = sequelize.define('credit', {
32
31
  defaultValue: false
33
32
  }
34
33
  });
35
-
36
34
  Account.hasMany(Credit, { foreignKey: 'account_id' });
37
35
  Credit.belongsTo(Account, { foreignKey: 'account_id', as: 'linkedAccount' });
38
-
39
- module.exports = Credit;
36
+ module.exports = Credit;
@@ -1,7 +1,5 @@
1
- // database/models/Transaction.js
2
1
  const { DataTypes } = require('sequelize');
3
2
  const sequelize = require('../config/init-db');
4
-
5
3
  module.exports = sequelize.define('transaction_log', {
6
4
  id: {
7
5
  type: DataTypes.INTEGER,
@@ -17,11 +15,11 @@ module.exports = sequelize.define('transaction_log', {
17
15
  allowNull: false
18
16
  },
19
17
  sender_or_receiver: {
20
- type: DataTypes.STRING, // Никнейм контрагента (для переводов) или описание
18
+ type: DataTypes.STRING,
21
19
  allowNull: true
22
20
  },
23
21
  amount: {
24
22
  type: DataTypes.DECIMAL(15, 2),
25
23
  allowNull: false
26
24
  }
27
- });
25
+ });
@@ -1,6 +1,5 @@
1
1
  const { DataTypes } = require('sequelize');
2
2
  const sequelize = require('../config/init-db');
3
-
4
3
  const User = sequelize.define('user', {
5
4
  name: {
6
5
  type: DataTypes.STRING,
@@ -8,11 +7,11 @@ const User = sequelize.define('user', {
8
7
  allowNull: false
9
8
  },
10
9
  user_name: {
11
- type: DataTypes.STRING, // Настоящее имя (bcrypt)
10
+ type: DataTypes.STRING,
12
11
  allowNull: false
13
12
  },
14
13
  user_surname: {
15
- type: DataTypes.STRING, // Настоящая фамилия (bcrypt)
14
+ type: DataTypes.STRING,
16
15
  allowNull: false
17
16
  },
18
17
  user_gmail: {
@@ -27,12 +26,12 @@ const User = sequelize.define('user', {
27
26
  field: '2FA-status'
28
27
  },
29
28
  two_fa_token: {
30
- type: DataTypes.STRING, // Хешированный секрет аутентификатора
29
+ type: DataTypes.STRING,
31
30
  allowNull: true,
32
31
  field: '2FA-token'
33
32
  },
34
33
  token: {
35
- type: DataTypes.STRING, // Хешированный токен аварийного входа
34
+ type: DataTypes.STRING,
36
35
  allowNull: false
37
36
  },
38
37
  password: {
@@ -42,9 +41,7 @@ const User = sequelize.define('user', {
42
41
  avatar: {
43
42
  type: DataTypes.STRING,
44
43
  allowNull: true,
45
- defaultValue: '/uploads/avatars/default.png' // Стандартная аватарка для всех
44
+ defaultValue: '/uploads/avatars/default.png'
46
45
  }
47
-
48
46
  });
49
-
50
- module.exports = User;
47
+ module.exports = User;
@@ -1,19 +1,15 @@
1
1
  const Account = require('../../models/Account');
2
-
2
+ const Transaction = require('../../models/Transaction');
3
3
  module.exports = async function addManny(accountId, amount) {
4
4
  try {
5
5
  const acc = await Account.findByPk(accountId);
6
6
  if (!acc) return { status: false, statusCode: -2, message: 'Счет не найден' };
7
-
8
7
  const numericAmount = parseFloat(amount);
9
8
  if (isNaN(numericAmount) || numericAmount <= 0) return { status: false, statusCode: -2 };
10
-
11
9
  await acc.increment('manny', { by: numericAmount });
12
- const Transaction = require('../../models/Transaction');
13
10
  await Transaction.create({ account_id: accountId, type: 'DEPOSIT', sender_or_receiver: 'Администрация (ROOT)', amount: numericAmount });
14
-
15
11
  return { status: true, statusCode: 1 };
16
12
  } catch (err) {
17
13
  return { status: false, statusCode: -10 };
18
14
  }
19
- };
15
+ };
@@ -1,23 +1,18 @@
1
1
  const bcrypt = require('bcrypt');
2
2
  const Account = require('../../models/Account');
3
-
4
3
  module.exports = async function changePincode(accountId, oldPin, newPin) {
5
4
  try {
6
5
  const acc = await Account.findByPk(accountId);
7
6
  if (!acc) return { status: false, statusCode: -2, message: 'Счет не найден' };
8
-
9
7
  const isPinValid = await bcrypt.compare(oldPin, acc.pin_code);
10
8
  if (!isPinValid) return { status: false, statusCode: -2, message: 'Неверный текущий пин-код' };
11
-
12
9
  if (!newPin || newPin.length > 8) {
13
10
  return { status: false, statusCode: -2, message: 'Новый пин-код должен быть до 8 символов' };
14
11
  }
15
-
16
12
  acc.pin_code = await bcrypt.hash(newPin, 10);
17
13
  await acc.save();
18
-
19
14
  return { status: true, statusCode: 1 };
20
15
  } catch (err) {
21
16
  return { status: false, statusCode: -10 };
22
17
  }
23
- };
18
+ };
@@ -1,106 +1,55 @@
1
- const bcrypt = require('bcrypt');
2
- const Account = require('../../models/Account');
3
- const Credit = require('../../models/Credit');
4
- const User = require('../../models/User');
5
- const nodemailer = require('nodemailer');
6
-
7
- module.exports = async function creatCredit(username, targetAccountId, amount, pinCode, paymentsCount, autoWithdrawal) {
1
+ const Account = require('./../../models/Account');
2
+ const Credit = require('./../../models/Credit');
3
+ const sequelize = require('./../../config/init-db');
4
+ async function createCredit({ accountId, amount, autoRepay = false, rate = 0.1, termMonths = 12 }) {
5
+ const numericAmount = parseFloat(amount);
6
+ const numericRate = parseFloat(rate);
7
+ const numericTerm = parseInt(termMonths, 10);
8
+ if (!accountId || isNaN(numericAmount) || numericAmount <= 0) {
9
+ return { success: false, error: 'Некорректные параметры для создания кредита' };
10
+ }
11
+ if (isNaN(numericRate) || numericRate < 0 || isNaN(numericTerm) || numericTerm <= 0) {
12
+ return { success: false, error: 'Некорректная процентная ставка или срок кредитования' };
13
+ }
14
+ const transaction = await sequelize.transaction();
8
15
  try {
9
- const targetAcc = await Account.findByPk(targetAccountId);
10
- if (!targetAcc || targetAcc.user !== username) {
11
- return { status: false, statusCode: -2, message: 'Целевой счет не найден' };
12
- }
13
-
14
- // Проверка пин-кода (-23)
15
- const isPinValid = await bcrypt.compare(pinCode, targetAcc.pin_code);
16
- if (!isPinValid) return { status: false, statusCode: -23, message: 'Неверный пин-код счета' };
17
-
18
- const creditAmount = parseFloat(amount);
19
- if (isNaN(creditAmount) || creditAmount <= 0) return { status: false, statusCode: -2 };
20
-
21
- const paymentAmount = parseFloat((creditAmount / paymentsCount).toFixed(2));
22
-
23
- // 1. Создаем технический счет кредита, куда начисляются заемные деньги
24
- const creditAccount = await Account.create({
25
- user: username,
26
- pin_code: targetAcc.pin_code,
27
- manny: creditAmount,
28
- active: true,
29
- two_fa_status: false
16
+ const account = await Account.findOne({
17
+ where: { id: accountId },
18
+ lock: transaction.LOCK.UPDATE,
19
+ transaction
30
20
  });
31
-
32
- // 2. Регистрируем кредит в таблице мониторинга
33
- const newCredit = await Credit.create({
34
- account_id: creditAccount.id,
35
- total_payments: paymentsCount,
36
- remaining_payments: paymentsCount,
37
- payment_amount: paymentAmount,
38
- auto_withdrawal: autoWithdrawal
21
+ if (!account) throw new Error('Аккаунт не найден');
22
+ if (account.status === 'blocked') throw new Error('Аккаунт заблокирован');
23
+ const existingCredit = await Credit.findOne({
24
+ where: { accountId: account.id, status: 'active' },
25
+ transaction,
26
+ lock: transaction.LOCK.UPDATE
39
27
  });
40
-
41
- /**
42
- * Автономный метод обработки биллинга (вызывать раз в период через крон / интервал)
43
- */
44
- async function processCreditBilling(creditId) {
45
- try {
46
- const credit = await Credit.findByPk(creditId, { include: [{ model: Account, as: 'linkedAccount' }] });
47
- if (!credit) return;
48
-
49
- const linkedAcc = credit.linkedAccount;
50
- const owner = await User.findByPk(username);
51
-
52
- let paymentSuccess = false;
53
-
54
- // Если автономное списание разрешено ТЗ
55
- if (credit.auto_withdrawal && linkedAcc) {
56
- if (parseFloat(linkedAcc.manny) >= parseFloat(credit.payment_amount)) {
57
- await linkedAcc.decrement('manny', { by: credit.payment_amount });
58
- credit.remaining_payments -= 1;
59
- await credit.save();
60
- paymentSuccess = true;
61
- } else {
62
- // Если денег не хватило, переводим в ручной режим для отправки предупреждений
63
- credit.auto_withdrawal = false;
64
- await credit.save();
65
- }
66
- }
67
-
68
- // Если автосписание выключено или не удалось — отправляем предупреждение на почту по ТЗ
69
- if (!paymentSuccess && owner) {
70
- const transporter = nodemailer.createTransport({
71
- service: 'gmail',
72
- auth: { user: process.env.GMAIL, pass: process.env.GOOGLE_APP_PASSWORD }
73
- });
74
-
75
- await transporter.sendMail({
76
- from: `"City-bank Биллинг" <${process.env.GMAIL}>`,
77
- to: owner.user_gmail,
78
- subject: '⚠️ Требуется оплата по кредиту | City-bank',
79
- text: `Уважаемый клиент! По вашему кредитному счету #${credit.account_id} зафиксирован обязательный платеж. Вам необходимо внести ${credit.payment_amount} руб.`
80
- });
81
- }
82
-
83
- // Если все платежи закрыты — полностью удаляем и закрываем кредит и технический счет по ТЗ
84
- if (credit.remaining_payments <= 0) {
85
- if (linkedAcc) await linkedAcc.destroy();
86
- await credit.destroy();
87
- console.log(`🎉 Кредит #${creditId} полностью погашен и закрыт.`);
88
- }
89
- } catch (billingErr) {
90
- console.error("Ошибка процессинга кредита:", billingErr.message);
91
- }
28
+ if (existingCredit) {
29
+ throw new Error('У этого аккаунта уже есть активный кредит');
92
30
  }
93
-
94
- // Сохраняем ссылку на обработчик в глобальный крон или интервал (в рамках игровой сессии)
95
- // Для симуляции можно вызывать функцию через setInterval()
96
-
97
- return {
98
- status: true,
99
- statusCode: 1,
100
- creditAccountId: creditAccount.id,
101
- password: pinCode
31
+ const totalRepay = numericAmount * (1 + numericRate);
32
+ const credit = await Credit.create({
33
+ accountId: account.id,
34
+ amount: numericAmount,
35
+ totalRepay: totalRepay,
36
+ remainingRepay: totalRepay,
37
+ status: 'active',
38
+ autoRepay: !!autoRepay,
39
+ termMonths: numericTerm
40
+ }, { transaction });
41
+ await account.increment('balance', { by: numericAmount, transaction });
42
+ await transaction.commit();
43
+ return {
44
+ success: true,
45
+ message: 'Кредит успешно оформлен',
46
+ creditId: credit.id
102
47
  };
103
- } catch (err) {
104
- return { status: false, statusCode: -10, message: err.message };
48
+ } catch (error) {
49
+ if (transaction && !transaction.finished) {
50
+ await transaction.rollback();
51
+ }
52
+ return { success: false, error: error.message };
105
53
  }
106
- };
54
+ }
55
+ module.exports = createCredit;
@@ -1,24 +1,20 @@
1
1
  const bcrypt = require('bcrypt');
2
2
  const Account = require('../../models/Account');
3
-
4
3
  module.exports = async function createAccount(username, pinCode, enable2FA) {
5
4
  try {
6
- // Валидация длины пин-кода (до 8 символов по ТЗ)
7
5
  if (!pinCode || pinCode.length > 8) {
8
6
  return { status: false, statusCode: -2, message: 'Пин-код должен быть до 8 символов' };
9
7
  }
10
-
11
8
  const hashedPin = await bcrypt.hash(pinCode, 10);
12
9
  const newAccount = await Account.create({
13
10
  user: username,
14
11
  pin_code: hashedPin,
15
- manny: 0.00, // Строго нулевой баланс для игроков
12
+ manny: 0.00,
16
13
  active: true,
17
14
  two_fa_status: enable2FA
18
15
  });
19
-
20
16
  return { status: true, statusCode: 1, accountId: newAccount.id };
21
17
  } catch (err) {
22
18
  return { status: false, statusCode: -10, message: err.message };
23
19
  }
24
- };
20
+ };
@@ -1,12 +1,10 @@
1
1
  const Account = require('../../models/Account');
2
-
3
2
  module.exports = async function findManny(accountId) {
4
3
  try {
5
4
  const acc = await Account.findByPk(accountId);
6
5
  if (!acc) return { status: false, statusCode: -2, message: 'Счет не найден' };
7
-
8
6
  return { status: true, statusCode: 1, manny: parseFloat(acc.manny) };
9
7
  } catch (err) {
10
8
  return { status: false, statusCode: -10 };
11
9
  }
12
- };
10
+ };
@@ -1,26 +1,19 @@
1
- // database/services/account/logs.js
2
1
  const Account = require('../../models/Account');
3
2
  const Transaction = require('../../models/Transaction');
4
-
5
3
  module.exports = async function getAccountLogs(username) {
6
4
  try {
7
- // Находим все ID счетов, принадлежащих этому пользователю
8
5
  const myAccounts = await Account.findAll({
9
6
  where: { user: username },
10
7
  attributes: ['id']
11
8
  });
12
-
13
9
  const accountIds = myAccounts.map(acc => acc.id);
14
-
15
- // Запрашиваем логи по этим счетам
16
10
  const logs = await Transaction.findAll({
17
11
  where: { account_id: accountIds },
18
- order: [['createdAt', 'DESC']], // Сначала самые свежие
19
- limit: 50 // Ограничим вывод последними 50 операциями
12
+ order: [['createdAt', 'DESC']],
13
+ limit: 50
20
14
  });
21
-
22
15
  return { status: true, statusCode: 1, logs };
23
16
  } catch (err) {
24
17
  return { status: false, statusCode: -10, message: err.message };
25
18
  }
26
- };
19
+ };
@@ -1,18 +1,15 @@
1
1
  const Account = require('../../models/Account');
2
-
2
+ const Transaction = require('../../models/Transaction');
3
3
  module.exports = async function removeManny(accountId, amount) {
4
4
  try {
5
5
  const acc = await Account.findByPk(accountId);
6
6
  if (!acc) return { status: false, statusCode: -2, message: 'Счет не найден' };
7
-
8
7
  const numericAmount = parseFloat(amount);
9
8
  if (isNaN(numericAmount) || numericAmount <= 0) return { status: false, statusCode: -2 };
10
-
11
9
  await acc.decrement('manny', { by: numericAmount });
12
- const Transaction = require('../../models/Transaction');
13
10
  await Transaction.create({ account_id: accountId, type: 'WITHDRAW', sender_or_receiver: 'Администрация (ROOT)', amount: numericAmount });
14
11
  return { status: true, statusCode: 1 };
15
12
  } catch (err) {
16
13
  return { status: false, statusCode: -10 };
17
14
  }
18
- };
15
+ };
@@ -1,49 +1,46 @@
1
1
  const bcrypt = require('bcrypt');
2
2
  const Account = require('../../models/Account');
3
3
  const User = require('../../models/User');
4
+ const Transaction = require('../../models/Transaction');
4
5
  const sequelize = require('../../config/init-db');
5
6
  const { sendBotNotification } = require('../bot/bot');
6
-
7
+ const logger = require("custom-color-logs").print;
7
8
  module.exports = async function transferManny(fromId, toId, amount, pinCode, totpCode = null) {
8
9
  const t = await sequelize.transaction();
9
10
  try {
10
- // Подгружаем счета с блокировкой строк для обновления (FOR UPDATE)
11
- const fromAcc = await Account.findByPk(fromId, { transaction: t });
12
- const toAcc = await Account.findByPk(toId, { transaction: t });
13
-
11
+ const numericAmount = parseFloat(amount);
12
+ if (isNaN(numericAmount) || numericAmount <= 0) {
13
+ await t.rollback();
14
+ return { status: false, statusCode: -2, message: 'Некорректная сумма перевода' };
15
+ }
16
+ const fromAcc = await Account.findByPk(fromId, {
17
+ transaction: t,
18
+ lock: t.LOCK.UPDATE
19
+ });
20
+ const toAcc = await Account.findByPk(toId, {
21
+ transaction: t,
22
+ lock: t.LOCK.UPDATE
23
+ });
14
24
  if (!fromAcc || !toAcc) {
15
25
  await t.rollback();
16
26
  return { status: false, statusCode: -2, message: 'Один из счетов не найден' };
17
27
  }
18
-
19
28
  if (!fromAcc.active || !toAcc.active) {
20
29
  await t.rollback();
21
30
  return { status: false, statusCode: -11, message: 'Один из счетов заблокирован' };
22
31
  }
23
-
24
- // Проверка пин-кода отправителя по вашему ТЗ (-23)
25
32
  const isPinValid = await bcrypt.compare(pinCode, fromAcc.pin_code);
26
33
  if (!isPinValid) {
27
34
  await t.rollback();
28
- return { status: false, statusCode: -23, message: 'Неверный пароль щета отправителя' };
35
+ return { status: false, statusCode: -23, message: 'Неверный пароль счета отправителя' };
29
36
  }
30
-
31
- const numericAmount = parseFloat(amount);
32
- if (isNaN(numericAmount) || numericAmount <= 0) {
33
- await t.rollback();
34
- return { status: false, statusCode: -2, message: 'Некорректная сумма перевода' };
35
- }
36
-
37
- // Проверка баланса (root-пользователь игнорирует лимиты средств)
38
37
  if (fromAcc.user !== 'root' && parseFloat(fromAcc.manny) < numericAmount) {
39
38
  await t.rollback();
40
39
  return { status: false, statusCode: -11, message: 'Недостаточно средств на счете' };
41
40
  }
42
-
43
- // Если на счете включена индивидуальная проверка 2FA
44
41
  if (fromAcc.two_fa_status) {
45
42
  const owner = await User.findByPk(fromAcc.user, { transaction: t });
46
- if (owner.two_fa_status) {
43
+ if (owner && owner.two_fa_status) {
47
44
  if (!totpCode) {
48
45
  await t.rollback();
49
46
  return { status: false, statusCode: -2, message: 'Требуется токен подтверждения 2FA' };
@@ -55,29 +52,34 @@ module.exports = async function transferManny(fromId, toId, amount, pinCode, tot
55
52
  }
56
53
  }
57
54
  }
58
-
59
- // Проведение атомарного перевода
60
55
  await fromAcc.decrement('manny', { by: numericAmount, transaction: t });
61
56
  await toAcc.increment('manny', { by: numericAmount, transaction: t });
62
- const Transaction = require('../../models/Transaction'); // Импорт в начало файла
63
-
64
- // Вставить перед t.commit():
65
- await Transaction.create({ account_id: fromId, type: 'TRANSFER_OUT', sender_or_receiver: `На счет #${toId} (${to.user})`, amount: numAmount }, { transaction: t });
66
- await Transaction.create({ account_id: toId, type: 'TRANSFER_IN', sender_or_receiver: `Со счета #${fromId} (${from.user})`, amount: numAmount }, { transaction: t });
67
-
57
+ await Transaction.create({
58
+ account_id: fromId,
59
+ type: 'TRANSFER_OUT',
60
+ sender_or_receiver: `На счет #${toId} (${toAcc.user})`,
61
+ amount: numericAmount
62
+ }, { transaction: t });
63
+ await Transaction.create({
64
+ account_id: toId,
65
+ type: 'TRANSFER_IN',
66
+ sender_or_receiver: `Со счета #${fromId} (${fromAcc.user})`,
67
+ amount: numericAmount
68
+ }, { transaction: t });
68
69
  await t.commit();
69
-
70
- // Обновляем модели для считывания актуального баланса ботом
71
70
  await fromAcc.reload();
72
71
  await toAcc.reload();
73
-
74
- // Асинхронные уведомления через шаблоны бота
75
- await sendBotNotification('transfer-from-bot', { fromId, toId, amount: numericAmount, balance: fromAcc.manny });
76
- await sendBotNotification('transfer-to-bot', { toId, fromId, amount: numericAmount, balance: toAcc.manny });
77
-
72
+ try {
73
+ await sendBotNotification('transfer-from-bot', { fromId, toId, amount: numericAmount, balance: fromAcc.manny });
74
+ await sendBotNotification('transfer-to-bot', { toId, fromId, amount: numericAmount, balance: toAcc.manny });
75
+ } catch (botErr) {
76
+ console.log(logger.DatabaseError('Ошибка отправки уведомления боту:', botErr.message))
77
+ }
78
78
  return { status: true, statusCode: 1 };
79
79
  } catch (err) {
80
- await t.rollback();
80
+ if (!t.finished) {
81
+ await t.rollback();
82
+ }
81
83
  return { status: false, statusCode: -10, message: err.message };
82
84
  }
83
- };
85
+ };
@@ -1,38 +1,23 @@
1
- // database/services/bot/bot.js
2
1
  const fs = require('fs').promises;
3
2
  const path = require('path');
4
-
5
- /**
6
- * Вспомогательный метод для асинхронного рендеринга и подстановки данных
7
- */
3
+ const logger = require("custom-color-logs").print;
8
4
  async function renderTemplate(templateName, ext, vars) {
9
5
  try {
10
- // 🔑 СТРОГО ВЫЧИСЛЯЕМ АБСОЛЮТНЫЙ ПУТЬ к папке generators
11
6
  const filePath = path.resolve(__dirname, 'generators', `${templateName}.${ext}`);
12
-
13
- // Читаем файл с диска
14
7
  let data = await fs.readFile(filePath, 'utf-8');
15
-
16
- // Подставляем переменные
17
8
  for (const [key, value] of Object.entries(vars)) {
18
9
  data = data.replace(new RegExp(`{${key}}`, 'g'), value);
19
10
  }
20
11
  return data;
21
12
  } catch (err) {
22
- console.error(`[Bot Render Error] Не найден файл ${templateName}.${ext}:`, err.message);
23
- return ""; // Возвращаем пустую строку вместо падения или перехвата статики
13
+ console.log(logger.NodemailerError(`[Bot Render Error] Не найден файл ${templateName}.${ext}:`, err.message))
14
+ return "";
24
15
  }
25
16
  }
26
-
27
- /**
28
- * Главный движок компиляции сообщений бота
29
- */
30
17
  async function sendBotNotification(templateName, variables) {
31
18
  const txtContent = await renderTemplate(templateName, 'txt', variables);
32
19
  const htmlContent = await renderTemplate(templateName, 'html', variables);
33
-
34
- console.log(`\n🤖 [City-Bank Bot Engine]: Сгенерировано событие уведомления [${templateName}]`);
20
+ console.log(logger.NodemailerInfo(`Сгенерировано событие уведомления [${templateName}]`))
35
21
  return { txt: txtContent, html: htmlContent };
36
22
  }
37
-
38
- module.exports = { sendBotNotification };
23
+ module.exports = { sendBotNotification };