Files
canina/backend/src/products/torob.controller.ts
T

269 lines
8.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Controller, Get, Query } from "@nestjs/common";
import { ApiTags, ApiOperation } from "@nestjs/swagger";
import { PrismaService } from "../prisma/prisma.service";
function normalizeSuitableFor(val?: string | null): string {
if (!val) return '';
const s = String(val).trim();
const upper = s.toUpperCase();
if (['ALL', 'BOTH', 'DOG_AND_CAT', 'CAT_AND_DOG', 'DOGS_AND_CATS', 'CATS_AND_DOGS', 'هر دو', 'سگ و گربه', 'سگ، گربه', 'سگ وگربه'].includes(upper)) {
return 'سگ و گربه';
}
if (['DOG', 'DOGS', 'سگ'].includes(upper)) {
return 'سگ';
}
if (['CAT', 'CATS', 'گربه'].includes(upper)) {
return 'گربه';
}
return s;
}
function buildTorobProductTitle(product: {
nameFa?: string | null;
name?: string | null;
nameEn?: string | null;
packageSize?: unknown;
unit?: string | null;
suitableFor?: string | null;
}): string {
const nameFa = (product.nameFa || product.name || '').trim();
let nameEn = (product.nameEn || '').trim();
// Clean brand duplicate if nameEn already starts with Canina
if (/^Canina\b/i.test(nameEn)) {
nameEn = nameEn.replace(/^Canina\s*[-–:]*\s*/i, '').trim();
}
// Package size & unit deduplication
let sizePart = '';
const numSize = Number(product.packageSize);
const unit = (product.unit || '').trim();
let sizeAlreadyInNames = false;
if (numSize && numSize > 0) {
const escapedUnit = unit.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regexList = [
new RegExp(`\\b${numSize}\\s*${escapedUnit}\\b`, 'i'),
new RegExp(`\\b${numSize}${escapedUnit}\\b`, 'i'),
new RegExp(`\\b${numSize}\\s*g(r|ram)?\\b`, 'i'),
new RegExp(`\\b${numSize}g(r|ram)?\\b`, 'i'),
new RegExp(`\\b${numSize}\\s*m?l\\b`, 'i'),
new RegExp(`\\b${numSize}m?l\\b`, 'i'),
new RegExp(`\\b${numSize}\\s*میلی‌?لیتر\\b`, 'i'),
new RegExp(`\\b${numSize}\\s*گرم\\b`, 'i'),
new RegExp(`\\b${numSize}\\s*عددی?\\b`, 'i'),
new RegExp(`\\b${numSize}\\s*Tab(let)?s?\\b`, 'i'),
];
sizeAlreadyInNames = regexList.some((rgx) => rgx.test(nameFa) || rgx.test(nameEn));
if (!sizeAlreadyInNames) {
sizePart = unit ? `${numSize} ${unit}` : `${numSize}`;
}
}
// Suitable for pet
let petPart = '';
const pet = normalizeSuitableFor(product.suitableFor);
if (pet) {
petPart = `مناسب ${pet}`;
}
const parts: string[] = [];
if (nameFa) parts.push(nameFa);
// Brand part
if (!nameFa.includes('کنینا') && !nameFa.includes('Canina')) {
parts.push('برند کنینا Canina');
} else if (!nameFa.includes('Canina')) {
parts.push('Canina');
}
if (nameEn && nameEn.toLowerCase() !== nameFa.toLowerCase()) {
parts.push(nameEn);
}
if (sizePart && !nameFa.includes(sizePart) && !nameEn.includes(sizePart)) {
parts.push(sizePart);
}
if (petPart && !nameFa.includes(petPart)) {
parts.push(petPart);
}
return parts.join(' ').replace(/\s+/g, ' ').trim();
}
function buildTorobProductSpec(product: {
packageSize?: unknown;
unit?: string | null;
suitableFor?: string | null;
artNo?: string | null;
category?: string | { name?: string } | null;
}): Record<string, string> {
const spec: Record<string, string> = {
'برند': 'کنینا (Canina Pharma Germany)',
'کشور سازنده': 'آلمان',
'ضمانت': 'اصالت ۱۰۰٪ کالای آلمانی، سلامت فیزیکی و تاریخ انقضای به‌روز',
};
const pet = normalizeSuitableFor(product.suitableFor);
if (pet) {
spec['گونه هدف'] = pet;
}
const numSize = Number(product.packageSize);
const unit = (product.unit || '').trim();
if (numSize && numSize > 0) {
spec['حجم / وزن / تعداد'] = unit ? `${numSize} ${unit}` : `${numSize}`;
}
if (product.artNo) {
spec['کد محصول (Art.No)'] = product.artNo;
}
const catName = typeof product.category === 'object' ? product.category?.name : product.category;
if (catName) {
spec['دسته دارویی و درمانی'] = catName;
}
return spec;
}
@ApiTags("Torob Integration - وب‌سرویس اتصال به ترب")
@Controller("torob")
export class TorobController {
constructor(private readonly prisma: PrismaService) {}
@Get("products")
@ApiOperation({
summary: "دریافت محصولات جهت وب‌سرویس خودکار ترب (Torob API)",
})
async getTorobProducts(
@Query("page") pageQuery?: string,
@Query("page_size") pageSizeQuery?: string,
) {
const parsedPage = parseInt(pageQuery || "1", 10);
const parsedSize = parseInt(pageSizeQuery || "100", 10);
const page = Math.max(1, Number.isFinite(parsedPage) ? parsedPage : 1);
const pageSize = Math.min(
100,
Math.max(10, Number.isFinite(parsedSize) ? parsedSize : 100),
);
const baseUrl = (process.env.FRONTEND_URL || "https://canina.ir").replace(
/\/$/,
"",
);
const whereCondition = {
noIndex: false,
stockStatus: { not: "DISCONTINUED" as const },
};
const [totalCount, products] = await Promise.all([
this.prisma.product.count({ where: whereCondition }),
this.prisma.product.findMany({
where: whereCondition,
skip: (page - 1) * pageSize,
take: pageSize,
include: {
category: { select: { name: true } },
},
orderBy: { createdAt: "desc" },
}),
]);
const maxPages = Math.ceil(totalCount / pageSize) || 1;
const results = products.map((product) => {
const slug = product.slug || product.artNo || product.id;
const pageUrl = `${baseUrl}/shop/${slug}`;
const productId = String(product.artNo || product.id || slug);
const title = buildTorobProductTitle(product);
const spec = buildTorobProductSpec(product);
// Construct pure English subtitle
const rawEn = (product.nameEn || "").trim();
const numSize = Number(product.packageSize);
const unit = (product.unit || "").trim();
let subtitle = rawEn.startsWith("Canina")
? rawEn
: `Canina ${rawEn}`.trim();
// Check if size is already present in subtitle
let sizeAlreadyInSubtitle = false;
if (numSize && numSize > 0) {
const escapedUnit = unit.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regexList = [
new RegExp(`\\b${numSize}\\s*${escapedUnit}\\b`, 'i'),
new RegExp(`\\b${numSize}${escapedUnit}\\b`, 'i'),
new RegExp(`\\b${numSize}\\s*g(r|ram)?\\b`, 'i'),
new RegExp(`\\b${numSize}g(r|ram)?\\b`, 'i'),
new RegExp(`\\b${numSize}\\s*m?l\\b`, 'i'),
new RegExp(`\\b${numSize}m?l\\b`, 'i'),
new RegExp(`\\b${numSize}\\s*Tab(let)?s?\\b`, 'i'),
];
sizeAlreadyInSubtitle = regexList.some((rgx) => rgx.test(subtitle));
}
if (!sizeAlreadyInSubtitle && numSize && numSize > 0) {
const sizeStr = unit ? `${numSize} ${unit}` : `${numSize}`;
subtitle = `${subtitle} - ${sizeStr}`;
}
const rawImage = product.ogImage || product.imageUrl || "";
let imageLink = "";
if (rawImage) {
const cleanImage = rawImage
.trim()
.replace(/^https?:\/\/api\.canina\.ir/i, "")
.replace(/^https?:\/\/localhost:\d+/i, "")
.replace(/^https?:\/\/127\.0\.0\.1:\d+/i, "");
if (
cleanImage.startsWith("http://") ||
cleanImage.startsWith("https://")
) {
imageLink = cleanImage;
} else {
const cleanPath = cleanImage.replace(/^\/?(api\/)?(uploads\/)?/, "");
imageLink = `${baseUrl}/api/uploads/${cleanPath}`;
}
}
const isInStock =
product.stockStatus !== "DISCONTINUED" &&
product.stockStatus !== "OUT_OF_STOCK" &&
(product.stock === undefined || product.stock > 0) &&
String(product.stockStatus || "")
.toLowerCase()
.includes("in");
const price = Number(product.priceValue || 0);
const oldPrice = Number(product.priceValue || 0);
return {
product_id: productId,
page_unique_code: productId,
title,
subtitle,
page_url: pageUrl,
price,
old_price: oldPrice,
availability: isInStock ? "instock" : "outofstock",
image_link: imageLink,
guarantee: "ضمانت اصالت ۱۰۰٪ کالای آلمانی، سلامت فیزیکی و تاریخ مصرف به‌روز",
category_name:
product.category?.name ||
product.categorySlug ||
"مکمل حیوانات خانگی",
spec,
};
});
return {
count: totalCount,
max_pages: maxPages,
results,
};
}
}