Files
canina/backend/src/admin/reports.service.ts
T

213 lines
6.3 KiB
TypeScript

import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class ReportsService {
constructor(private prisma: PrismaService) {}
async getDashboardReports(query?: {
startDate?: string;
endDate?: string;
role?: string;
}) {
const whereClause: any = { status: { not: 'cancelled' } };
if (query?.startDate || query?.endDate) {
whereClause.createdAt = {};
if (query.startDate) {
whereClause.createdAt.gte = new Date(query.startDate);
}
if (query.endDate) {
const end = new Date(query.endDate);
end.setHours(23, 59, 59, 999);
whereClause.createdAt.lte = end;
}
}
if (query?.role && query.role !== 'ALL') {
whereClause.user = { role: query.role };
}
// 1. Fetch filtered orders with items and coupons for accurate breakdown
const orders = await this.prisma.order.findMany({
where: whereClause,
include: {
user: { select: { role: true } },
coupon: true,
orderItems: {
include: {
product: {
select: {
id: true,
buyPrice: true,
priceValue: true,
},
},
},
},
},
orderBy: { createdAt: 'asc' },
});
let totalRevenue = 0; // Total paid/deposited by users
let totalCharity = 0; // Charity portion
let b2bRevenue = 0;
let b2cRevenue = 0;
let totalTax = 0;
const totalShipping = 0;
let totalDiscounts = 0;
let totalCostOfGoods = 0; // COGS (مجموع قیمت خرید کالاها)
const salesByDate: Record<
string,
{ total: number; charity: number; sales: number }
> = {};
for (const order of orders) {
const amount = Number(order.totalAmount || 0);
const charity = Number(order.charityDonation || 0);
const productSales = Math.max(0, amount - charity);
totalRevenue += amount;
totalCharity += charity;
if (order.user?.role === 'B2B') {
b2bRevenue += amount;
} else {
b2cRevenue += amount;
}
// Calculate cost of goods (COGS) from order items
let orderCOGS = 0;
let orderItemSubtotal = 0;
if (order.orderItems && order.orderItems.length > 0) {
for (const item of order.orderItems) {
const qty = item.quantity || 1;
const buyPrice = Number(item.product?.buyPrice || 0);
const salePrice = Number(item.product?.priceValue || 0);
orderCOGS += buyPrice * qty;
orderItemSubtotal += salePrice * qty;
}
}
totalCostOfGoods += orderCOGS;
// Discount calculation (if coupon was used or total discount applied)
if (order.coupon) {
if (
order.coupon.type === 'percent' ||
order.coupon.type === 'PERCENTAGE'
) {
const discountVal =
(orderItemSubtotal * Number(order.coupon.value)) / 100;
totalDiscounts += discountVal;
} else {
totalDiscounts += Number(order.coupon.value || 0);
}
}
// Standard VAT / Tax (approx 10% on product sales if configured)
const taxRate = 0.1;
const orderTax = Math.round(productSales * (taxRate / (1 + taxRate)));
totalTax += orderTax;
// Format date YYYY-MM-DD
const dateKey = order.createdAt.toISOString().split('T')[0];
if (!salesByDate[dateKey]) {
salesByDate[dateKey] = { total: 0, charity: 0, sales: 0 };
}
salesByDate[dateKey].total += amount;
salesByDate[dateKey].charity += charity;
salesByDate[dateKey].sales += productSales;
}
// Product Sales Revenue (excluding charity)
const productSalesRevenue = Math.max(0, totalRevenue - totalCharity);
// Net profit = Product Sales - COGS - Tax - Discounts
const netProfit = Math.max(
0,
productSalesRevenue - totalCostOfGoods - totalTax - totalDiscounts,
);
// Format sales timeline for charts
const salesTimeline = Object.entries(salesByDate)
.map(([date, data]) => ({
date,
amount: data.total,
charity: data.charity,
sales: data.sales,
}))
.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
// 2. Best selling products (by quantity) in the selected range
const orderItems = await this.prisma.orderItem.groupBy({
by: ['productId'],
_sum: { quantity: true },
where: {
order: whereClause,
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 in range
const topCoupons = await this.prisma.coupon.findMany({
orderBy: { usedCount: 'desc' },
take: 5,
select: { code: true, usedCount: true },
});
return {
overview: {
totalRevenue,
totalCharity,
productSalesRevenue,
totalOrders: orders.length,
b2bRevenue,
b2cRevenue,
totalTax,
totalShipping,
totalDiscounts,
totalCostOfGoods,
netProfit,
},
salesTimeline,
bestSellers,
categoryDistribution: catSalesDist,
topCoupons: topCoupons.map((c) => ({ name: c.code, value: c.usedCount })),
};
}
}