66 lines
2.7 KiB
JavaScript
66 lines
2.7 KiB
JavaScript
module.exports = (req, res, next) => {
|
||
const isReportRequest = req.url.startsWith('/report') && req.method === 'GET';
|
||
|
||
if (!isReportRequest) {
|
||
next();
|
||
return;
|
||
}
|
||
|
||
try {
|
||
const { startDate, endDate } = req.query;
|
||
const { cinemas, sessions, orders } = require('./data.json');
|
||
|
||
const start = new Date(startDate);
|
||
const end = new Date(endDate);
|
||
|
||
// Фильтруем сеансы по периоду
|
||
const filteredSessions = sessions.filter(session => {
|
||
const sessionDate = new Date(session.dateTime.replace(/(\d{2}).(\d{2}).(\d{4}) (\d{2}):(\d{2})/, '$3-$2-$1T$4:$5'));
|
||
// обнуление времени с учетом зоны времени
|
||
sessionDate.setHours(4, 0, 0, 0);
|
||
return sessionDate >= start && sessionDate <= end;
|
||
});
|
||
|
||
// Обрабатываем отфильтрованные сеансы для аналитики
|
||
const reportData = filteredSessions.map(session => {
|
||
// берем заказ, где сеанс только текущий
|
||
const relevantOrders = orders
|
||
.map(orderWithOneSession => ({
|
||
...orderWithOneSession,
|
||
sessions: orderWithOneSession.sessions.filter(orderSession => orderSession.id === session.id &&
|
||
orderSession.cinemaId === session.cinemaId && orderSession.dateTime === session.dateTime)
|
||
})).filter(order => order.sessions.length > 0);
|
||
|
||
const { totalTicketsSold, revenue } = relevantOrders.reduce((accumulator, order) => {
|
||
const session = order.sessions[0];
|
||
const tickets = session.count;
|
||
const sessionRevenue = tickets * session.frozenPrice;
|
||
|
||
return {
|
||
totalTicketsSold: accumulator.totalTicketsSold + tickets,
|
||
revenue: accumulator.revenue + sessionRevenue
|
||
};
|
||
}, { totalTicketsSold: 0, revenue: 0 });
|
||
|
||
const cinema = cinemas.find(cinema => cinema.id === session.cinemaId)
|
||
return {
|
||
cinema_name: cinema ? cinema.name : "Неизвестно",
|
||
current_ticket_date_time: session.dateTime,
|
||
current_ticket_price: session.price,
|
||
max_ticket_quantity: session.maxCount,
|
||
purchased_tickets: totalTicketsSold,
|
||
revenue: revenue
|
||
};
|
||
});
|
||
|
||
const sortedReportData = reportData.sort((a, b) => b.revenue - a.revenue);
|
||
const report = { "sortedReportData": sortedReportData,
|
||
"total_revenue": sortedReportData.reduce((a, b) => a + b.revenue, 0),
|
||
"total_purchased_tickets": sortedReportData.reduce((a, b) => a + b.purchased_tickets, 0) }
|
||
res.json(report);
|
||
} catch (error) {
|
||
console.error('Error processing report: ', error);
|
||
res.status(500).json({ message: 'Internal Server Error' });
|
||
}
|
||
};
|