79 lines
3.0 KiB
JavaScript
79 lines
3.0 KiB
JavaScript
const express = require('express');
|
||
const router = express.Router();
|
||
const db = require('../config/database');
|
||
const { requireAdmin } = require('../middleware/auth');
|
||
|
||
// GET /admin/contracts
|
||
router.get('/', requireAdmin, async (req, res) => {
|
||
try {
|
||
// Verträge nach Kategorie
|
||
const [byCategory] = await db.query(`
|
||
SELECT
|
||
c.name as category_name,
|
||
COUNT(m.id) as total,
|
||
SUM(CASE WHEN m.status='active' THEN 1 ELSE 0 END) as active,
|
||
SUM(CASE WHEN m.status='paused' THEN 1 ELSE 0 END) as paused,
|
||
SUM(CASE WHEN m.status='inactive' THEN 1 ELSE 0 END) as inactive,
|
||
SUM(COALESCE(m.agreed_price, t.price_monthly)) as monthly_revenue
|
||
FROM memberships m
|
||
JOIN tariffs t ON m.tariff_id = t.id
|
||
LEFT JOIN categories c ON t.category_id = c.id
|
||
GROUP BY c.id, c.name
|
||
ORDER BY total DESC
|
||
`);
|
||
|
||
// Verträge nach Tarif
|
||
const [byTariff] = await db.query(`
|
||
SELECT
|
||
t.name as tariff_name, t.price_monthly, t.duration_months, t.active as tariff_active,
|
||
COUNT(m.id) as total,
|
||
SUM(CASE WHEN m.status='active' THEN 1 ELSE 0 END) as active,
|
||
SUM(COALESCE(m.agreed_price, t.price_monthly)) as monthly_revenue
|
||
FROM memberships m
|
||
JOIN tariffs t ON m.tariff_id = t.id
|
||
GROUP BY t.id, t.name, t.price_monthly, t.duration_months, t.active
|
||
ORDER BY active DESC, total DESC
|
||
`);
|
||
|
||
// Gesamtübersicht
|
||
const [totals] = await db.query(`
|
||
SELECT
|
||
COUNT(*) as total,
|
||
SUM(CASE WHEN status='active' THEN 1 ELSE 0 END) as active,
|
||
SUM(CASE WHEN status='paused' THEN 1 ELSE 0 END) as paused,
|
||
SUM(CASE WHEN status='inactive' THEN 1 ELSE 0 END) as inactive,
|
||
SUM(CASE WHEN is_minor=1 THEN 1 ELSE 0 END) as minors,
|
||
SUM(COALESCE(agreed_price, 0)) as total_monthly
|
||
FROM memberships
|
||
`);
|
||
|
||
// Auslaufende Verträge – 3 Monate
|
||
const [expiring] = await db.query(`
|
||
SELECT m.*, t.name as tariff_name, t.price_monthly,
|
||
COALESCE(m.agreed_price, t.price_monthly) as agreed_price
|
||
FROM memberships m
|
||
JOIN tariffs t ON m.tariff_id = t.id
|
||
WHERE m.status = 'active'
|
||
AND m.effective_end BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 3 MONTH)
|
||
ORDER BY m.effective_end ASC
|
||
`);
|
||
|
||
// Alle aktiven Tarife für Dropdown
|
||
const [tariffs] = await db.query('SELECT * FROM tariffs WHERE active=1 ORDER BY name ASC');
|
||
|
||
res.render('admin/contracts', {
|
||
admin: req.session.adminUser,
|
||
byCategory, byTariff,
|
||
totals: totals[0],
|
||
expiring, tariffs,
|
||
success: req.query.success || null,
|
||
error: req.query.error || null
|
||
});
|
||
} catch (err) {
|
||
console.error(err);
|
||
res.redirect('/admin?error=Fehler+in+Vertragsübersicht:+' + encodeURIComponent(err.message));
|
||
}
|
||
});
|
||
|
||
module.exports = router;
|