Files
canina/backend/src/products/products.service.ts
T

373 lines
9.9 KiB
TypeScript

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";
import {
createPaginationMeta,
extractSearchTokens,
calculateRelevanceScore,
} from "../common/utils/search.utils";
@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) } });
}
const tokens = extractSearchTokens(search);
if (tokens.length > 0) {
const mode = "insensitive" as const;
const searchConditions: Prisma.ProductWhereInput[] = [
{ artNo: { contains: search, mode } },
{ barcode: { contains: search, mode } },
{ slug: { contains: search, mode } },
{ nameFa: { contains: search, mode } },
{ nameEn: { contains: search, mode } },
{ shortDescription: { contains: search, mode } },
];
for (const token of tokens) {
searchConditions.push(
{ nameFa: { contains: token, mode } },
{ nameEn: { contains: token, mode } },
{
ingredientList: {
some: {
OR: [
{ ingredient: { contains: token, mode } },
{ ingredientCardSlug: { contains: token, mode } },
],
},
},
},
{
symptoms: {
some: {
symptom: { contains: token, mode },
},
},
},
);
}
andConditions.push({
OR: searchConditions,
});
}
const whereClause: Prisma.ProductWhereInput =
andConditions.length > 0 ? { AND: andConditions } : {};
const safePage = Math.max(1, Number(page) || 1);
const safeLimit = Math.max(1, Number(limit) || 50);
const skip = (safePage - 1) * safeLimit;
// 1. Fetch products with lean relations
const [rawProducts, total] = await Promise.all([
this.prisma.product.findMany({
where: whereClause,
skip: tokens.length > 0 ? undefined : skip,
take: tokens.length > 0 ? 100 : safeLimit,
orderBy: { [sortBy]: sortOrder },
include: {
ingredientList: true,
symptoms: true,
},
}),
this.prisma.product.count({ where: whereClause }),
]);
// Rank by relevance if searching
let candidateProducts = rawProducts;
if (tokens.length > 0 && search) {
candidateProducts = [...rawProducts]
.map((p) => ({
product: p,
score: calculateRelevanceScore(
{
artNo: p.artNo,
barcode: p.barcode,
slug: p.slug,
title: p.nameFa || p.nameEn,
shortDescription: p.shortDescription,
description: p.description,
ingredients: p.ingredientList,
symptoms: p.symptoms,
},
search,
tokens,
),
}))
.sort((a, b) => b.score - a.score)
.map((item) => item.product)
.slice(skip, skip + safeLimit);
}
// 2. Efficient single aggregate query for total sold counts for the current page slice
const productIds = candidateProducts.map((p) => p.id);
let salesMap: Record<string, number> = {};
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<string, number>);
}
const isWholesaleOrAdmin =
userRole === "User_Wholesale" ||
userRole === "User_Partner" ||
userRole === "ADMIN" ||
userRole === "SuperAdmin";
const isAdmin = userRole === "ADMIN" || userRole === "SuperAdmin";
const data = candidateProducts.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: createPaginationMeta(total, safePage, safeLimit),
};
}
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<string>();
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;
}
}