refactoring

This commit is contained in:
Artyom Ashirov
2024-11-23 05:03:30 +03:00
parent dcc678a42b
commit 5d4f56e265
22 changed files with 1109 additions and 1014 deletions

View File

@@ -0,0 +1,27 @@
import db from "../config/database.js";
class CategoryService {
static async getCategoriesByLocationId(locationId) {
return await db.allAsync(
'SELECT id, name FROM categories WHERE location_id = ? ORDER BY name',
[locationId]
);
}
static async getSubcategoriesByCategoryId(categoryId) {
return await db.allAsync(
'SELECT id, name FROM subcategories WHERE category_id = ? ORDER BY name',
[categoryId]
);
}
static async getCategoryById(categoryId) {
return await db.getAsync('SELECT id, name FROM categories WHERE id = ?', [categoryId]);
}
static async getSubcategoryById(subcategoryId) {
return await db.getAsync('SELECT id, name FROM subcategories WHERE id = ?', [subcategoryId]);
}
}
export default CategoryService;

View File

@@ -0,0 +1,37 @@
import db from "../config/database.js";
class LocationService {
static async getCountries() {
return await db.allAsync('SELECT DISTINCT country FROM locations ORDER BY country');
}
static async getCitiesByCountry(country) {
return await db.allAsync(
'SELECT DISTINCT city FROM locations WHERE country = ? ORDER BY city',
[country]
);
}
static async getDistrictsByCountryAndCity(country, city) {
return await db.allAsync(
'SELECT district FROM locations WHERE country = ? AND city = ? ORDER BY district',
[country, city]
);
}
static async getLocation(country, city, district) {
return await db.getAsync(
'SELECT id FROM locations WHERE country = ? AND city = ? AND district = ?',
[country, city, district]
);
}
static async getLocationById(locationId) {
return await db.getAsync(
'SELECT country, city, district FROM locations WHERE id = ?',
[locationId]
);
}
}
export default LocationService;

View File

@@ -0,0 +1,37 @@
import db from "../config/database.js";
class ProductService {
static async getProductById(productId) {
try {
return await db.getAsync(`SELECT * FROM products WHERE id = ?`, [productId]);
} catch (error) {
console.error('Error get product:', error);
throw error;
}
}
static async getDetailedProductById(productId) {
return await db.getAsync(
`SELECT p.*, c.name as category_name, s.name as subcategory_name
FROM products p
JOIN categories c ON p.category_id = c.id
JOIN subcategories s ON p.subcategory_id = s.id
WHERE p.id = ?`,
[productId]
);
}
static async getProductsByLocationAndCategory(locationId, categoryId, subcategoryId) {
return await db.allAsync(
`SELECT id, name, price, description, quantity_in_stock, photo_url
FROM products
WHERE location_id = ? AND category_id = ? AND subcategory_id = ?
AND quantity_in_stock > 0
ORDER BY name`,
[locationId, categoryId, subcategoryId]
);
}
}
export default ProductService

View File

@@ -0,0 +1,59 @@
import db from "../config/database.js";
class PurchaseService {
static async getPurchasesByUserId(userId, limit, offset) {
try {
return await db.allAsync(`
SELECT
p.*,
pr.name as product_name,
pr.description,
l.country,
l.city,
l.district
FROM purchases p
JOIN products pr ON p.product_id = pr.id
JOIN locations l ON pr.location_id = l.id
WHERE p.user_id = ?
ORDER BY p.purchase_date DESC
LIMIT ?
OFFSET ?
`, [userId, limit, offset]);
} catch (error) {
console.error('Error get purchases:', error);
throw error;
}
}
static async getPurchaseById(purchaseId) {
try {
return await db.getAsync(`
SELECT
p.*,
pr.name as product_name,
pr.description,
l.country,
l.city,
l.district
FROM purchases p
JOIN products pr ON p.product_id = pr.id
JOIN locations l ON pr.location_id = l.id
WHERE p.id = ?
`, [purchaseId]);
} catch (error) {
console.error('Error get purchase:', error);
throw error;
}
}
static async createPurchase(userId, productId, walletType, quantity, totalPrice) {
await db.runAsync(
'INSERT INTO purchases (user_id, product_id, wallet_type, tx_hash, quantity, total_price) VALUES (?, ?, ?, ?, ?, ?)',
[userId, productId, walletType, "null", quantity, totalPrice]
);
}
}
export default PurchaseService

140
src/services/userService.js Normal file
View File

@@ -0,0 +1,140 @@
import db from "../config/database.js";
import Wallet from "../models/Wallet.js";
class UserService {
static async getUserByUserId(userId) {
try {
return await db.getAsync(
'SELECT * FROM users WHERE id = ?',
[String(userId)]
);
} catch (error) {
console.error('Error getting user:', error);
throw error;
}
}
static async getUserByTelegramId(telegramId) {
try {
return await db.getAsync(
'SELECT * FROM users WHERE telegram_id = ?',
[String(telegramId)]
);
} catch (error) {
console.error('Error getting user:', error);
throw error;
}
}
static async getDetailedUserByTelegramId(telegramId) {
try {
return await db.getAsync(`
SELECT
u.*,
COUNT(DISTINCT p.id) as purchase_count,
COALESCE(SUM(p.total_price), 0) as total_spent,
COUNT(DISTINCT cw.id) as crypto_wallet_count,
COUNT(DISTINCT cw2.id) as archived_wallet_count
FROM users u
LEFT JOIN purchases p ON u.id = p.user_id
LEFT JOIN crypto_wallets cw ON u.id = cw.user_id AND cw.wallet_type NOT LIKE '%_%'
LEFT JOIN crypto_wallets cw2 ON u.id = cw2.user_id AND cw2.wallet_type LIKE '%_%'
WHERE u.telegram_id = ?
GROUP BY u.id
`, [telegramId.toString()]);
} catch (error) {
console.error('Error getting user stats:', error);
throw error;
}
}
static async createUser(userData) {
try {
const existingUser = await this.getUserByTelegramId(userData?.telegram_id);
if (existingUser) {
return existingUser.id;
}
const fields = Object.keys(userData);
const values = [];
for (const field of fields) {
values.push(userData[field]);
}
const marks = [];
for (let i = 0; i < fields.length; i++) {
marks.push("?");
}
const query = [
`INSERT INTO users (${fields.join(', ')})`,
`VALUES (${marks.join(', ')})`
].join("");
await db.runAsync('BEGIN TRANSACTION');
const result = await db.runAsync(query, [values]);
await db.runAsync('COMMIT');
return result.lastID;
} catch (error) {
await db.runAsync('ROLLBACK');
console.error('Error creating user:', error);
throw error;
}
}
static async updateUser(userId, newUserData) {}
static async deleteUser() {}
static async recalculateUserBalanceByTelegramId(telegramId) {
const user = await this.getUserByTelegramId(telegramId);
if (!user) {
return;
}
const archivedBalance = await Wallet.getArchivedWalletsBalance(user.id);
const activeBalance = await Wallet.getActiveWalletsBalance(user.id);
const purchases = await db.getAsync(
`SELECT SUM(total_price) as total_sum FROM purchases WHERE user_id = ?`,
[user.id]
);
const userTotalBalance = (activeBalance + archivedBalance) - (purchases?.total_sum || 0);
await db.runAsync(`UPDATE users SET total_balance = ? WHERE id = ?`, [userTotalBalance, user.id]);
}
static async updateUserLocation(telegramId, country, city, district) {
await db.runAsync(
'UPDATE users SET country = ?, city = ?, district = ? WHERE telegram_id = ?',
[country, city, district, telegramId.toString()]
);
}
static async updateUserStatus(telegramId, status) {
// statuses
// 0 - active
// 1 - deleted
// 2 - blocked
try {
await db.runAsync('BEGIN TRANSACTION');
// Update user status
await db.runAsync('UPDATE users SET status = ? WHERE telegram_id = ?', [status, telegramId.toString()]);
// Commit transaction
await db.runAsync('COMMIT');
} catch (e) {
await db.runAsync("ROLLBACK");
console.error('Error deleting user:', e);
throw e;
}
}
}
export default UserService;

View File

@@ -0,0 +1,3 @@
class WalletService {
}