import { Injectable } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; @Injectable() export class ReportsService { constructor(private prisma: PrismaService) {} async getDashboardReports() { // 1. Total revenue and charity const orders = await this.prisma.order.findMany({ where: { status: { not: 'cancelled' } }, select: { totalAmount: true, charityDonation: true, createdAt: true, user: { select: { role: true } }, }, }); let totalRevenue = 0; let totalCharity = 0; let b2bRevenue = 0; let b2cRevenue = 0; const salesByDate: Record = {}; for (const order of orders) { const amount = Number(order.totalAmount); totalRevenue += amount; totalCharity += Number(order.charityDonation); if (order.user?.role === 'B2B') { b2bRevenue += amount; } else { b2cRevenue += amount; } // Format date YYYY-MM-DD const dateKey = order.createdAt.toISOString().split('T')[0]; if (!salesByDate[dateKey]) salesByDate[dateKey] = 0; salesByDate[dateKey] += amount; } // Format sales timeline for charts const salesTimeline = Object.entries(salesByDate) .map(([date, amount]) => ({ date, amount })) .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()); // 2. Best selling products (by quantity) const orderItems = await this.prisma.orderItem.groupBy({ by: ['productId'], _sum: { quantity: true }, where: { order: { status: { not: 'cancelled' } }, productId: { not: null }, }, orderBy: { _sum: { quantity: 'desc' } }, take: 5, }); // Fetch product names for top 5 const topProductsIds = orderItems .map((item) => item.productId) .filter(Boolean) as string[]; const productsInfo = await this.prisma.product.findMany({ where: { id: { in: topProductsIds } }, select: { id: true, nameFa: true, nameEn: true }, }); const bestSellers = orderItems.map((item) => { const p = productsInfo.find((prod) => prod.id === item.productId); return { name: p ? `${p.nameFa} (${p.nameEn})` : 'محصول نامشخص', quantity: item._sum.quantity || 0, }; }); // 3. Category Distribution const categories = await this.prisma.category.findMany({ include: { products: { select: { id: true } } }, }); const catSalesDist = categories .map((cat) => { const pIds = cat.products.map((p) => p.id); const catSales = orderItems .filter((oi) => oi.productId && pIds.includes(oi.productId)) .reduce((sum, oi) => sum + (oi._sum.quantity || 0), 0); return { name: cat.name, value: catSales }; }) .filter((c) => c.value > 0); // 4. Coupons Usage const topCoupons = await this.prisma.coupon.findMany({ orderBy: { usedCount: 'desc' }, take: 5, select: { code: true, usedCount: true }, }); return { overview: { totalRevenue, totalCharity, totalOrders: orders.length, b2bRevenue, b2cRevenue, }, salesTimeline, bestSellers, categoryDistribution: catSalesDist, topCoupons: topCoupons.map((c) => ({ name: c.code, value: c.usedCount })), }; } }