Files
telegram-shop/src/admin/routes/locations.js

44 lines
1.5 KiB
JavaScript

import { Router } from 'express';
import db from '../../config/database.js';
import { asyncHandler } from '../errorHandler.js';
const router = Router();
router.get('/', asyncHandler(async (req, res) => {
const locations = await db.allAsync(`SELECT l.*,
(SELECT COUNT(*) FROM categories WHERE location_id = l.id) as category_count,
(SELECT COUNT(*) FROM products WHERE location_id = l.id) as product_count
FROM locations l ORDER BY l.country, l.city, l.district`);
res.render('locations', { title: 'Locations', locations });
}));
router.post('/', asyncHandler(async (req, res) => {
const { country, city, district } = req.body;
await db.runAsync(
'INSERT INTO locations (country, city, district) VALUES (?, ?, ?)',
[country, city, district || '']
);
res.redirect('/locations');
}));
router.post('/:id/delete', asyncHandler(async (req, res) => {
const count = await db.getAsync(
'SELECT COUNT(*) as cnt FROM categories WHERE location_id = ?',
[req.params.id]
);
if (count && count.cnt > 0) {
return res.redirect('/locations?error=Cannot+delete+location+with+categories');
}
const productCount = await db.getAsync(
'SELECT COUNT(*) as cnt FROM products WHERE location_id = ?',
[req.params.id]
);
if (productCount && productCount.cnt > 0) {
return res.redirect('/locations?error=Cannot+delete+location+with+products');
}
await db.runAsync('DELETE FROM locations WHERE id = ?', [req.params.id]);
res.redirect('/locations');
}));
export default router;