import { Injectable, NotFoundException } from "@nestjs/common"; import { PrismaService } from "../prisma/prisma.service"; import { GetProductsDto } from "./dto/get-products.dto"; import { Prisma } from "@prisma/client"; import { RevalidationService } from "../common/revalidation/revalidation.service"; @Injectable() export class ProductsService { constructor( private prisma: PrismaService, private revalidationService: RevalidationService, ) {} async findAll(filters: GetProductsDto, userRole?: string) { const { category, petType, search, symptom, requiresRx, minPrice, maxPrice, page = 1, limit = 50, sortBy = "createdAt", sortOrder = "desc", } = filters; const andConditions: Prisma.ProductWhereInput[] = []; if (requiresRx !== undefined && requiresRx !== null && requiresRx !== "") { andConditions.push({ requiresRx: requiresRx === "true" || requiresRx === "1", }); } if (category) { andConditions.push({ categorySlug: category }); } if (petType && petType !== "all") { andConditions.push({ suitableFor: { in: [petType, "سگ و گربه", "هر دو"] }, }); } if (symptom) { andConditions.push({ symptoms: { some: { symptom: { contains: symptom, mode: "insensitive" }, }, }, }); } if (minPrice) { andConditions.push({ priceValue: { gte: Number(minPrice) } }); } if (maxPrice) { andConditions.push({ priceValue: { lte: Number(maxPrice) } }); } if (search) { andConditions.push({ OR: [ { artNo: { contains: search, mode: "insensitive" } }, { barcode: { contains: search, mode: "insensitive" } }, { nameFa: { contains: search, mode: "insensitive" } }, { nameEn: { contains: search, mode: "insensitive" } }, { description: { contains: search, mode: "insensitive" } }, { shortDescription: { contains: search, mode: "insensitive" } }, { symptoms: { some: { symptom: { contains: search, mode: "insensitive" }, }, }, }, ], }); } const whereClause: Prisma.ProductWhereInput = andConditions.length > 0 ? { AND: andConditions } : {}; const skip = (page - 1) * limit; // 1. Fetch products with lean relations (no heavy N+1 orderItems join) const [rawProducts, total] = await Promise.all([ this.prisma.product.findMany({ where: whereClause, skip, take: limit, orderBy: { [sortBy]: sortOrder }, include: { ingredientList: true, symptoms: true, }, }), this.prisma.product.count({ where: whereClause }), ]); // 2. Efficient single aggregate query for total sold counts for the current page slice const productIds = rawProducts.map((p) => p.id); let salesMap: Record = {}; if (productIds.length > 0) { const salesAgg = await this.prisma.orderItem.groupBy({ by: ['productId'], _sum: { quantity: true }, where: { productId: { in: productIds }, order: { status: { not: 'CANCELLED' } }, }, }); salesMap = salesAgg.reduce((acc, row) => { if (row.productId) { acc[row.productId] = Number(row._sum.quantity) || 0; } return acc; }, {} as Record); } const isWholesaleOrAdmin = userRole === "User_Wholesale" || userRole === "User_Partner" || userRole === "ADMIN" || userRole === "SuperAdmin"; const isAdmin = userRole === "ADMIN" || userRole === "SuperAdmin"; const data = rawProducts.map((p) => { const totalSold = salesMap[p.id] || 0; const { buyPrice, wholesalePrice, ...publicProduct } = p; void buyPrice; void wholesalePrice; if (!isWholesaleOrAdmin) { return { ...publicProduct, totalSold }; } return isAdmin ? { ...p, totalSold } : { ...publicProduct, wholesalePrice: p.wholesalePrice, totalSold }; }); return { data, meta: { total, page, lastPage: Math.ceil(total / limit) || 1, limit, }, }; } async findOne(idOrSlug: string, userRole?: string) { if (!idOrSlug) return null; const decoded = decodeURIComponent(idOrSlug).trim(); const cleanId = idOrSlug.trim(); const isUuid = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test( cleanId, ); const product = await this.prisma.product.findFirst({ where: isUuid ? { id: cleanId } : { OR: [ { slug: cleanId }, { slug: decoded }, { artNo: cleanId }, { artNo: decoded }, { nameFa: cleanId }, { nameFa: decoded }, { nameEn: cleanId }, { nameEn: decoded }, ], }, include: { ingredientList: true, symptoms: true, reviews: { where: { status: "APPROVED" }, orderBy: { createdAt: "desc" }, select: { id: true, userName: true, rating: true, comment: true, status: true, createdAt: true, }, }, }, }); if (!product) return null; const isWholesaleOrAdmin = userRole === "User_Wholesale" || userRole === "User_Partner" || userRole === "ADMIN" || userRole === "SuperAdmin"; const isAdmin = userRole === "ADMIN" || userRole === "SuperAdmin"; const { buyPrice, wholesalePrice, ...publicProduct } = product; void buyPrice; void wholesalePrice; if (!isWholesaleOrAdmin) { return publicProduct; } return isAdmin ? product : { ...publicProduct, wholesalePrice: product.wholesalePrice }; } async getActiveFilters() { const [categories, symptomsDb, petTypesDb] = await Promise.all([ this.prisma.category.findMany({ where: { products: { some: {}, }, }, select: { id: true, name: true, slug: true, }, }), this.prisma.productSymptom.findMany({ distinct: ["symptom"], select: { symptom: true, }, }), this.prisma.product.findMany({ distinct: ["suitableFor"], select: { suitableFor: true, }, }), ]); return { categories, symptoms: symptomsDb.map((s) => s.symptom).filter(Boolean), petTypes: Array.from( new Set( petTypesDb .map((p) => p.suitableFor === "هر دو" ? "سگ و گربه" : p.suitableFor, ) .filter(Boolean), ), ), }; } async getNavigationFilters() { const categories = await this.prisma.category.findMany({ where: { products: { some: {}, }, }, include: { products: { include: { symptoms: true, }, }, }, }); return categories.map((cat) => { const symptomSet = new Set(); cat.products.forEach((p) => { p.symptoms.forEach((s) => { if (s.symptom) { symptomSet.add(s.symptom); } }); }); return { id: cat.id, name: cat.name, slug: cat.slug, symptoms: Array.from(symptomSet), }; }); } async getDosageConfig(id: string) { const product = await this.prisma.product.findUnique({ where: { id }, select: { dosageConfig: true, dosageLogic: true }, }); if (!product) { throw new NotFoundException(`Product with ID ${id} not found`); } return product.dosageConfig || {}; } async updateDosageConfig(id: string, dosageConfig: Prisma.InputJsonValue) { const product = await this.prisma.product.findUnique({ where: { id } }); if (!product) { throw new NotFoundException(`Product with ID ${id} not found`); } const updated = await this.prisma.product.update({ where: { id }, data: { dosageConfig }, }); await this.revalidationService.revalidateProduct( product.slug, product.artNo, ); return updated; } }