221 lines
6.4 KiB
TypeScript
221 lines
6.4 KiB
TypeScript
import { Controller, Get, Query } from '@nestjs/common';
|
||
import { ApiTags, ApiOperation } from '@nestjs/swagger';
|
||
import { PrismaService } from '../prisma/prisma.service';
|
||
|
||
function buildTorobProductTitle(product: {
|
||
nameFa?: string | null;
|
||
nameEn?: string | null;
|
||
packageSize?: unknown;
|
||
unit?: string | null;
|
||
suitableFor?: string | null;
|
||
}): string {
|
||
const nameFa = (product.nameFa || '').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
|
||
let sizePart = '';
|
||
const numSize = Number(product.packageSize);
|
||
const unit = (product.unit || '').trim();
|
||
if (numSize && numSize > 0) {
|
||
sizePart = unit ? `${numSize} ${unit}` : `${numSize}`;
|
||
}
|
||
|
||
// Suitable for pet
|
||
let petPart = '';
|
||
if (product.suitableFor) {
|
||
const pet = product.suitableFor.trim();
|
||
if (pet === 'هر دو' || pet === 'سگ و گربه' || pet === 'سگ، گربه') {
|
||
petPart = 'مناسب سگ و گربه';
|
||
} else 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?: { name?: string } | null;
|
||
}): Record<string, string> {
|
||
const spec: Record<string, string> = {
|
||
برند: 'کنینا (Canina Pharma Germany)',
|
||
'کشور سازنده': 'آلمان',
|
||
ضمانت: 'اصالت ۱۰۰٪ کالای آلمانی و سلامت فیزیکی',
|
||
};
|
||
|
||
if (product.suitableFor) {
|
||
spec['گونه هدف'] =
|
||
product.suitableFor === 'هر دو' ? 'سگ و گربه' : product.suitableFor;
|
||
}
|
||
|
||
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;
|
||
}
|
||
|
||
if (product.category?.name) {
|
||
spec['دسته دارویی و درمانی'] = product.category.name;
|
||
}
|
||
|
||
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 page = Math.max(1, parseInt(pageQuery || '1', 10));
|
||
const pageSize = Math.min(
|
||
100,
|
||
Math.max(10, parseInt(pageSizeQuery || '100', 10)),
|
||
);
|
||
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();
|
||
const sizeStr =
|
||
numSize && numSize > 0
|
||
? unit
|
||
? `${numSize} ${unit}`
|
||
: `${numSize}`
|
||
: '';
|
||
let subtitle = rawEn.startsWith('Canina')
|
||
? rawEn
|
||
: `Canina ${rawEn}`.trim();
|
||
if (sizeStr && !subtitle.includes(sizeStr)) {
|
||
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' &&
|
||
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: 'ضمانت اصالت ۱۰۰٪ کمپانی Canina آلمان و اصالت کالا',
|
||
category_name:
|
||
product.category?.name ||
|
||
product.categorySlug ||
|
||
'مکمل حیوانات خانگی',
|
||
spec,
|
||
};
|
||
});
|
||
|
||
return {
|
||
count: totalCount,
|
||
max_pages: maxPages,
|
||
results,
|
||
};
|
||
}
|
||
}
|