update check ETH USDT USDC balance function

This commit is contained in:
NW
2025-01-08 12:01:02 +00:00
parent e64f185eda
commit 66f5251795
8 changed files with 686 additions and 304 deletions

View File

@@ -94,7 +94,9 @@ class UserService {
SELECT
u.*,
COUNT(DISTINCT p.id) as purchase_count,
COALESCE(SUM(p.total_price), 0) as total_spent,
(SELECT COALESCE(SUM(p2.total_price), 0)
FROM purchases p2
WHERE p2.user_id = u.id) as total_spent,
COUNT(DISTINCT cw.id) as crypto_wallet_count,
COUNT(DISTINCT cw2.id) as archived_wallet_count
FROM users u
@@ -162,19 +164,28 @@ class UserService {
static async getUserBalance(userId) {
try {
const user = await db.getAsync(
// Пересчитываем баланс перед получением
const user = await this.getUserByUserId(userId);
if (!user) {
throw new Error('User not found');
}
await this.recalculateUserBalanceByTelegramId(user.telegram_id);
// Получаем обновленный баланс
const updatedUser = await db.getAsync(
`SELECT total_balance, bonus_balance
FROM users
WHERE id = ?`,
[userId]
);
if (!user) {
if (!updatedUser) {
throw new Error('User not found');
}
// Возвращаем сумму основного и бонусного баланса
return user.total_balance + user.bonus_balance;
return updatedUser.total_balance + updatedUser.bonus_balance;
} catch (error) {
console.error('Error getting user balance:', error);
throw error;

View File

@@ -1,24 +1,87 @@
// walletService.js
import db from "../config/database.js";
import WalletUtils from "../utils/walletUtils.js";
class WalletService {
static async getArchivedWalletsCount(user) {
try {
// Получаем количество архивных кошельков пользователя
const archivedWallets = await db.getAsync(
`SELECT COUNT(*) AS total
FROM crypto_wallets
WHERE user_id = ? AND wallet_type LIKE '%#_%' ESCAPE '#'`, // Считаем только архивные кошельки
WHERE user_id = ? AND wallet_type LIKE '%#_%' ESCAPE '#'`,
[user.id]
);
console.log('[SERVICE] Fetching archived wallets for user:', user.id, 'with telegramId:', user.telegram_id, ' and tolal arhived wallet: ', archivedWallets.total);
// Возвращаем количество архивных кошельков
return archivedWallets.total;
} catch (error) {
console.error('Error fetching archived wallets count:', error);
throw new Error('Failed to fetch archived wallets count');
}
}
// Добавляем метод для получения кошельков по типу
static async getActiveWalletsBalance(userId) {
try {
const wallets = await db.allAsync(
`SELECT wallet_type, address
FROM crypto_wallets
WHERE user_id = ? AND wallet_type NOT LIKE '%#_%' ESCAPE '#'`,
[userId]
);
let totalBalance = 0;
for (const wallet of wallets) {
const walletUtils = new WalletUtils(
wallet.wallet_type === 'BTC' ? wallet.address : null,
wallet.wallet_type === 'LTC' ? wallet.address : null,
wallet.wallet_type === 'ETH' ? wallet.address : null,
wallet.wallet_type === 'USDT' ? wallet.address : null,
wallet.wallet_type === 'USDC' ? wallet.address : null,
userId
);
const balances = await walletUtils.getAllBalances();
totalBalance += balances[wallet.wallet_type]?.usdValue || 0;
}
return totalBalance;
} catch (error) {
console.error('Error fetching active wallets balance:', error);
throw new Error('Failed to fetch active wallets balance');
}
}
static async getArchivedWalletsBalance(userId) {
try {
const wallets = await db.allAsync(
`SELECT wallet_type, address
FROM crypto_wallets
WHERE user_id = ? AND wallet_type LIKE '%#_%' ESCAPE '#'`,
[userId]
);
let totalBalance = 0;
for (const wallet of wallets) {
const walletUtils = new WalletUtils(
wallet.wallet_type === 'BTC' ? wallet.address : null,
wallet.wallet_type === 'LTC' ? wallet.address : null,
wallet.wallet_type === 'ETH' ? wallet.address : null,
wallet.wallet_type === 'USDT' ? wallet.address : null,
wallet.wallet_type === 'USDC' ? wallet.address : null,
userId
);
const balances = await walletUtils.getAllBalances();
totalBalance += balances[wallet.wallet_type]?.usdValue || 0;
}
return totalBalance;
} catch (error) {
console.error('Error fetching archived wallets balance:', error);
throw new Error('Failed to fetch archived wallets balance');
}
}
// Метод для получения кошельков по типу
static async getWalletsByType(walletType) {
try {
const wallets = await db.allAsync(
@@ -27,7 +90,7 @@ class WalletService {
WHERE wallet_type = ?`,
[walletType]
);
return wallets;
} catch (error) {
console.error('Error fetching wallets by type:', error);