-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
303 lines (254 loc) · 11.4 KB
/
server.js
File metadata and controls
303 lines (254 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
const express = require('express');
const path = require('path');
const session = require('express-session');
const bcrypt = require('bcrypt');
require('dotenv').config();
const { Pool } = require('pg');
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(session({
secret: process.env.SESSION_SECRET || 'secretkey',
resave: false,
saveUninitialized: false,
cookie: { maxAge: 1000 * 60 * 60 * 24 }
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'templates')));
app.use(express.static(path.join(__dirname, 'images')));
const pool = new Pool({
user: process.env.PG_USER,
host: process.env.PG_HOST,
database: process.env.PG_DATABASE,
password: process.env.PG_PASSWORD,
port: process.env.PG_PORT,
});
async function hashPassword(password) {
return await bcrypt.hash(password, 10);
}
app.post('/register', async (req, res) => {
const { email, password, first_name, last_name, phone } = req.body;
const userExists = await pool.query('SELECT id FROM users WHERE email = $1', [email]);
if (userExists.rows.length > 0) return res.status(400).json({ message: 'Пользователь уже существует' });
const hashedPassword = await hashPassword(password);
const newUser = await pool.query(
`INSERT INTO users (email, password, first_name, last_name, phone) VALUES ($1, $2, $3, $4, $5) RETURNING id, email`,
[email, hashedPassword, first_name, last_name, phone]
);
req.session.userId = newUser.rows[0].id;
req.session.email = newUser.rows[0].email;
res.status(201).json({ success: true });
});
app.post('/login', async (req, res) => {
const { email, password } = req.body;
const userResult = await pool.query('SELECT id, email, password FROM users WHERE email = $1', [email]);
if (userResult.rows.length === 0) return res.status(401).json({ success: false });
const user = userResult.rows[0];
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) return res.status(401).json({ success: false });
req.session.userId = user.id;
req.session.email = user.email;
res.json({ success: true });
});
app.get('/logout', (req, res) => {
req.session.destroy(() => {
res.clearCookie('connect.sid');
res.redirect('/login.html');
});
});
app.get('/api/session', (req, res) => {
if (req.session.userId && req.session.email) res.json({ userId: req.session.userId, email: req.session.email });
else res.status(401).json({ error: 'Не авторизован' });
});
app.get('/api/categories', async (req, res) => {
const result = await pool.query('SELECT * FROM categories ORDER BY name');
res.json(result.rows);
});
app.get('/api/products/popular', async (req, res) => {
const result = await pool.query(`
SELECT p.*, COALESCE((SELECT SUM(oi.quantity) FROM order_items oi WHERE oi.product_id = p.id), 0) AS total_ordered
FROM products p
ORDER BY total_ordered DESC, p.name ASC
LIMIT 4
`);
res.json(result.rows);
});
app.get('/api/products/:categoryId', async (req, res) => {
const { categoryId } = req.params;
const result = await pool.query(
`SELECT id, name, description, brand, price, quantity, image_filename, category_id
FROM products WHERE category_id = $1 ORDER BY name`,
[categoryId]
);
res.json(result.rows);
});
app.get('/api/categories/:id', async (req, res) => {
const { id } = req.params;
const result = await pool.query('SELECT * FROM categories WHERE id = $1', [id]);
if (result.rows.length === 0) return res.status(404).json({ error: 'Категория не найдена' });
res.json(result.rows[0]);
});
app.post('/api/cart', async (req, res) => {
if (!req.session.userId) return res.status(401).json({ error: 'Необходима авторизация' });
const { product_id, quantity } = req.body;
const productResult = await pool.query('SELECT quantity FROM products WHERE id = $1', [product_id]);
if (productResult.rows.length === 0 || productResult.rows[0].quantity <= 0) {
return res.status(400).json({ error: 'Товар отсутствует на складе' });
}
const requestedQty = quantity || 1;
if (productResult.rows[0].quantity < requestedQty) {
return res.status(400).json({ error: `Недостаточно товара (в наличии: ${productResult.rows[0].quantity} шт.)` });
}
const existingItem = await pool.query(
'SELECT id, quantity FROM cart_items WHERE user_id = $1 AND product_id = $2',
[req.session.userId, product_id]
);
if (existingItem.rows.length > 0) {
const newQuantity = existingItem.rows[0].quantity + requestedQty;
await pool.query('UPDATE cart_items SET quantity = $1 WHERE id = $2', [newQuantity, existingItem.rows[0].id]);
} else {
await pool.query(
'INSERT INTO cart_items (user_id, product_id, quantity) VALUES ($1, $2, $3)',
[req.session.userId, product_id, requestedQty]
);
}
res.json({ success: true });
});
app.get('/api/cart', async (req, res) => {
if (!req.session.userId) return res.status(401).json({ error: 'Необходима авторизация' });
const result = await pool.query(
`SELECT p.id, p.name, p.price, p.image_filename, c.quantity
FROM cart_items c JOIN products p ON c.product_id = p.id WHERE c.user_id = $1`,
[req.session.userId]
);
res.json(result.rows);
});
app.delete('/api/cart/:product_id', async (req, res) => {
if (!req.session.userId) return res.status(401).json({ error: 'Необходима авторизация' });
const { product_id } = req.params;
await pool.query('DELETE FROM cart_items WHERE user_id = $1 AND product_id = $2', [req.session.userId, product_id]);
res.json({ success: true });
});
app.put('/api/cart/:product_id', async (req, res) => {
if (!req.session.userId) return res.status(401).json({ error: 'Необходима авторизация' });
const { product_id } = req.params;
const { quantity } = req.body;
await pool.query(
'UPDATE cart_items SET quantity = $1 WHERE user_id = $2 AND product_id = $3',
[quantity, req.session.userId, product_id]
);
res.json({ success: true });
});
app.post('/api/orders', async (req, res) => {
if (!req.session.userId) return res.status(401).json({ error: 'Необходима авторизация' });
const { payment_method, shipping_address, contact_phone } = req.body;
const cartItems = await pool.query(
`SELECT p.id, p.price, c.quantity FROM cart_items c JOIN products p ON c.product_id = p.id WHERE c.user_id = $1`,
[req.session.userId]
);
if (cartItems.rows.length === 0) return res.status(400).json({ error: 'Корзина пуста' });
const totalAmount = cartItems.rows.reduce((sum, item) => sum + (parseFloat(item.price) * parseInt(item.quantity)), 0);
const client = await pool.connect();
try {
await client.query('BEGIN');
const orderResult = await client.query(
`INSERT INTO orders (user_id, total_amount, payment_method, shipping_address, contact_phone)
VALUES ($1, $2, $3, $4, $5) RETURNING id`,
[req.session.userId, totalAmount, payment_method, shipping_address, contact_phone]
);
const orderId = orderResult.rows[0].id;
for (const item of cartItems.rows) {
await client.query(
`INSERT INTO order_items (order_id, product_id, quantity, price) VALUES ($1, $2, $3, $4)`,
[orderId, item.id, item.quantity, item.price]
);
await client.query(
'UPDATE products SET quantity = quantity - $1 WHERE id = $2',
[item.quantity, item.id]
);
}
await client.query('DELETE FROM cart_items WHERE user_id = $1', [req.session.userId]);
await client.query('COMMIT');
res.json({ success: true, orderId: orderId });
} catch (error) {
await client.query('ROLLBACK');
console.error('Ошибка при оформлении заказа:', error);
res.status(500).json({ error: 'Ошибка сервера' });
} finally {
client.release();
}
});
app.get('/api/orders', async (req, res) => {
if (!req.session.userId) return res.status(401).json({ error: 'Необходима авторизация' });
const ordersResult = await pool.query(
`SELECT o.id, o.order_date, o.total_amount, o.status, o.payment_method
FROM orders o WHERE o.user_id = $1 ORDER BY o.order_date DESC`,
[req.session.userId]
);
const orders = await Promise.all(ordersResult.rows.map(async (order) => {
const itemsResult = await pool.query(
`SELECT p.id, p.name, p.image_filename, oi.quantity, oi.price
FROM order_items oi JOIN products p ON oi.product_id = p.id WHERE oi.order_id = $1`,
[order.id]
);
return { ...order, products: itemsResult.rows };
}));
res.json(orders);
});
app.get('/api/user', async (req, res) => {
if (!req.session.userId) return res.status(401).json({ error: 'Необходима авторизация' });
const result = await pool.query(
'SELECT id, email, first_name, last_name, phone FROM users WHERE id = $1',
[req.session.userId]
);
if (result.rows.length === 0) return res.status(404).json({ error: 'Пользователь не найден' });
res.json(result.rows[0]);
});
app.put('/api/user', async (req, res) => {
if (!req.session.userId) return res.status(401).json({ error: 'Необходима авторизация' });
const { first_name, last_name, phone } = req.body;
await pool.query(
`UPDATE users SET first_name = $1, last_name = $2, phone = $3 WHERE id = $4`,
[first_name, last_name, phone, req.session.userId]
);
res.json({ success: true });
});
app.put('/api/orders/:order_id/cancel', async (req, res) => {
if (!req.session.userId) return res.status(401).json({ error: 'Необходима авторизация' });
const { order_id } = req.params;
const orderCheck = await pool.query('SELECT id FROM orders WHERE id = $1 AND user_id = $2', [order_id, req.session.userId]);
if (orderCheck.rows.length === 0) return res.status(404).json({ error: 'Заказ не найден' });
await pool.query(`UPDATE orders SET status = 'canceled' WHERE id = $1`, [order_id]);
res.json({ success: true });
});
app.get('/api/reviews', async (req, res) => {
const result = await pool.query(`
SELECT r.id, r.rating, r.message, r.created_at, u.first_name, u.last_name
FROM reviews r JOIN users u ON r.user_id = u.id
ORDER BY r.created_at DESC
`);
res.json(result.rows);
});
app.post('/api/reviews', async (req, res) => {
if (!req.session.userId) return res.status(401).json({ error: 'Необходима авторизация' });
const { rating, message } = req.body;
await pool.query('INSERT INTO reviews (user_id, rating, message) VALUES ($1, $2, $3)', [req.session.userId, rating, message]);
res.json({ success: true });
});
app.get('/api/products/search/:query', async (req, res) => {
const { query } = req.params;
const result = await pool.query(
`SELECT id, name, description, brand, price, image_filename
FROM products WHERE name ILIKE $1 OR description ILIKE $1 OR brand ILIKE $1 LIMIT 50`,
[`%${query}%`]
);
res.json(result.rows);
});
app.get('/api/studios', async (req, res) => {
const result = await pool.query('SELECT * FROM studios ORDER BY name');
res.json(result.rows);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Сервер запущен на http://localhost:${PORT}`);
});