53 lines
2.3 KiB
TypeScript
53 lines
2.3 KiB
TypeScript
import { Router } from 'express'
|
|
import { prisma } from '../lib/prisma'
|
|
import { requireCompanyAuth } from '../middleware/requireCompanyAuth'
|
|
import { requireTenant } from '../middleware/requireTenant'
|
|
import { requireSubscription } from '../middleware/requireSubscription'
|
|
import { generateFinancialReport, toCsv } from '../services/financialReportService'
|
|
|
|
const router = Router()
|
|
router.use(requireCompanyAuth, requireTenant, requireSubscription)
|
|
|
|
router.get('/summary', async (req, res, next) => {
|
|
try {
|
|
const { period = '30d' } = req.query as Record<string, string>
|
|
const days = parseInt(period.replace('d', '')) || 30
|
|
const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000)
|
|
|
|
const [totalReservations, activeVehicles, totalRevenue, totalCustomers] = await Promise.all([
|
|
prisma.reservation.count({ where: { companyId: req.companyId, createdAt: { gte: since } } }),
|
|
prisma.vehicle.count({ where: { companyId: req.companyId, status: 'AVAILABLE' } }),
|
|
prisma.reservation.aggregate({ where: { companyId: req.companyId, status: { in: ['COMPLETED'] }, createdAt: { gte: since } }, _sum: { totalAmount: true } }),
|
|
prisma.customer.count({ where: { companyId: req.companyId } }),
|
|
])
|
|
|
|
res.json({ data: { totalReservations, activeVehicles, totalRevenue: totalRevenue._sum.totalAmount ?? 0, totalCustomers, period } })
|
|
} catch (err) { next(err) }
|
|
})
|
|
|
|
router.get('/sources', async (req, res, next) => {
|
|
try {
|
|
const sources = await prisma.reservation.groupBy({ by: ['source'], where: { companyId: req.companyId }, _count: { id: true } })
|
|
res.json({ data: sources })
|
|
} catch (err) { next(err) }
|
|
})
|
|
|
|
router.get('/report', async (req, res, next) => {
|
|
try {
|
|
const { from, to, format = 'JSON' } = req.query as Record<string, string>
|
|
if (!from || !to) return res.status(400).json({ error: 'missing_params', message: 'from and to date params required', statusCode: 400 })
|
|
|
|
const report = await generateFinancialReport(req.companyId, new Date(from), new Date(to))
|
|
|
|
if (format === 'CSV') {
|
|
res.setHeader('Content-Type', 'text/csv')
|
|
res.setHeader('Content-Disposition', `attachment; filename="report-${from}-${to}.csv"`)
|
|
return res.send(toCsv(report.rows))
|
|
}
|
|
|
|
res.json({ data: report })
|
|
} catch (err) { next(err) }
|
|
})
|
|
|
|
export default router
|