feat: complete scheduled publishing, security remediation and DEV_TICKETS implementation
Deploy Canina / deploy (push) Successful in 2m29s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 6s

This commit is contained in:
parsa committed 2026-09-29 01:15:33 +03:30
1 parent d6d4158cbe
commit efb3c473c4
35 files changed
+685 -185

No files matched your search

+13 -6
View File
@@ -160,6 +160,7 @@ model Blog {
status String @default("PUBLISHED") @db.VarChar(20) // DRAFT, PUBLISHED, SCHEDULED, ARCHIVED
isPublished Boolean @default(true) @map("is_published")
publishedAt DateTime? @map("published_at") @db.Timestamptz()
scheduledAt DateTime? @map("scheduled_at") @db.Timestamptz()
readingTime Int @default(3) @map("reading_time")
featured Boolean @default(false)
allowComments Boolean @default(true) @map("allow_comments")
@@ -264,11 +265,16 @@ enum StockStatus {
model ProductIngredient {
productId String @map("product_id") @db.Uuid
ingredient String @db.VarChar(150)
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
productId String @map("product_id") @db.Uuid
ingredient String @db.VarChar(150)
ingredientCardId String? @map("ingredient_card_id") @db.Uuid
ingredientCardSlug String? @map("ingredient_card_slug") @db.VarChar(150)
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
ingredientCard Ingredient? @relation(fields: [ingredientCardId], references: [id], onDelete: SetNull)
@@id([productId, ingredient])
@@index([ingredientCardId])
@@index([ingredientCardSlug])
@@map("product_ingredients")
}
@@ -658,9 +664,10 @@ model Ingredient {
description String? @db.Text
scientificName String? @map("scientific_name") @db.VarChar(200)
imageUrl String? @map("image_url") @db.Text
benefits String[] @default([])
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
benefits String[] @default([])
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
productIngredients ProductIngredient[]
@@map("ingredients")
}
+1 -1
View File
@@ -218,7 +218,7 @@ const PRODUCT_TAGLINES_MAP: Record<string, string> = {
'canina-immun-booster-paste':
'تامین فوری ایمونوگلوبولین‌های آغوز و تثبیت فلور روده در زمان نقاهت',
'canina-katzenmilch':
'شیر خشک جایگزین بچه گربه حاوی تورین و فاقد لاکتوز مزاحم',
'شیر خشک جایگزین بچه گربه حاوی تورین بالا و پروتئین غنی‌شده',
'canina-lachs-ol':
'اسیدهای چرب ضروری امگا ۳ برای درخشش پوشش مویی و سلامت پوست',
'canina-marine-lmischung-premium':
+5 -1
View File
@@ -1,6 +1,7 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AdminController } from './admin.controller';
import { AdminService } from './admin.service';
import { SettingsService } from '../settings/settings.service';
describe('AdminController', () => {
let controller: AdminController;
@@ -8,7 +9,10 @@ describe('AdminController', () => {
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AdminController],
providers: [{ provide: AdminService, useValue: {} }],
providers: [
{ provide: AdminService, useValue: {} },
{ provide: SettingsService, useValue: {} },
],
}).compile();
controller = module.get<AdminController>(AdminController);
+84 -13
View File
@@ -509,8 +509,13 @@ export class AdminService {
};
let resolvedCategorySlug = data.categorySlug;
if (data.categoryId && (!resolvedCategorySlug || resolvedCategorySlug === 'general')) {
const cat = await this.prisma.category.findUnique({ where: { id: data.categoryId } });
if (
data.categoryId &&
(!resolvedCategorySlug || resolvedCategorySlug === 'general')
) {
const cat = await this.prisma.category.findUnique({
where: { id: data.categoryId },
});
if (cat) {
resolvedCategorySlug = cat.slug;
}
@@ -597,12 +602,19 @@ export class AdminService {
}
if (data.ingredientList && Array.isArray(data.ingredientList)) {
const uniqueIngs = Array.from(new Set(data.ingredientList.map((i: string) => i.trim()).filter(Boolean)));
const uniqueIngs = Array.from(
new Set(
data.ingredientList.map((i: string) => i.trim()).filter(Boolean),
),
);
if (uniqueIngs.length > 0) {
const resolvedIngs = await this.resolveIngredientCards(uniqueIngs);
await this.prisma.productIngredient.createMany({
data: uniqueIngs.map((ingredient: string) => ({
data: resolvedIngs.map((item) => ({
productId: product.id,
ingredient,
ingredient: item.ingredient,
ingredientCardId: item.ingredientCardId,
ingredientCardSlug: item.ingredientCardSlug,
})),
});
}
@@ -672,7 +684,9 @@ export class AdminService {
let resolvedCategorySlug = data.categorySlug;
if (data.categoryId && !resolvedCategorySlug) {
const cat = await this.prisma.category.findUnique({ where: { id: data.categoryId } });
const cat = await this.prisma.category.findUnique({
where: { id: data.categoryId },
});
if (cat) {
resolvedCategorySlug = cat.slug;
}
@@ -687,9 +701,11 @@ export class AdminService {
scientificTagline: data.scientificTagline,
description: data.description,
shortDescription: data.shortDescription,
ingredients: data.ingredients !== undefined ? data.ingredients : undefined,
ingredients:
data.ingredients !== undefined ? data.ingredients : undefined,
categoryId: data.categoryId,
categorySlug: resolvedCategorySlug !== undefined ? resolvedCategorySlug : undefined,
categorySlug:
resolvedCategorySlug !== undefined ? resolvedCategorySlug : undefined,
buyPrice: data.buyPrice !== undefined ? data.buyPrice : undefined,
marginRetailPercent:
marginRetail !== undefined ? marginRetail : undefined,
@@ -772,14 +788,26 @@ export class AdminService {
}
}
if (data.ingredientList !== undefined && Array.isArray(data.ingredientList)) {
await this.prisma.productIngredient.deleteMany({ where: { productId: id } });
if (
data.ingredientList !== undefined &&
Array.isArray(data.ingredientList)
) {
await this.prisma.productIngredient.deleteMany({
where: { productId: id },
});
if (data.ingredientList.length > 0) {
const uniqueIngs = Array.from(new Set(data.ingredientList.map((i: string) => i.trim()).filter(Boolean)));
const uniqueIngs = Array.from(
new Set(
data.ingredientList.map((i: string) => i.trim()).filter(Boolean),
),
);
const resolvedIngs = await this.resolveIngredientCards(uniqueIngs);
await this.prisma.productIngredient.createMany({
data: uniqueIngs.map((ingredient: string) => ({
data: resolvedIngs.map((item) => ({
productId: id,
ingredient,
ingredient: item.ingredient,
ingredientCardId: item.ingredientCardId,
ingredientCardSlug: item.ingredientCardSlug,
})),
});
}
@@ -1781,4 +1809,47 @@ export class AdminService {
totalMatched: products.length,
};
}
async resolveIngredientCards(ingredients: string[]): Promise<
Array<{
ingredient: string;
ingredientCardId: string | null;
ingredientCardSlug: string | null;
}>
> {
if (!ingredients || ingredients.length === 0) return [];
const allCards = await this.prisma.ingredient.findMany({
select: { id: true, slug: true, nameFa: true, nameEn: true },
});
const normalize = (str: string) =>
str.toLowerCase().replace(/[()]/g, '').replace(/\s+/g, ' ').trim();
return ingredients.map((rawIng) => {
const clean = rawIng.trim();
const norm = normalize(clean);
const matchedCard = allCards.find((card) => {
const cardFaNorm = normalize(card.nameFa);
const cardEnNorm = normalize(card.nameEn);
const cardSlugNorm = normalize(card.slug.replace(/-/g, ' '));
return (
norm === cardFaNorm ||
norm === cardEnNorm ||
norm === cardSlugNorm ||
norm.includes(cardFaNorm) ||
cardFaNorm.includes(norm) ||
norm.includes(cardEnNorm) ||
cardEnNorm.includes(norm)
);
});
return {
ingredient: clean,
ingredientCardId: matchedCard ? matchedCard.id : null,
ingredientCardSlug: matchedCard ? matchedCard.slug : null,
};
});
}
}
+137 -12
View File
@@ -1,11 +1,20 @@
import { Injectable, NotFoundException, OnModuleInit } from '@nestjs/common';
import {
Injectable,
NotFoundException,
OnModuleInit,
OnModuleDestroy,
Logger,
} from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { PaginationDto } from '../common/dto/pagination.dto';
import { RevalidationService } from '../common/revalidation/revalidation.service';
@Injectable()
export class BlogsService implements OnModuleInit {
export class BlogsService implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(BlogsService.name);
private schedulerTimer: NodeJS.Timeout | null = null;
constructor(
private prisma: PrismaService,
private revalidationService: RevalidationService,
@@ -13,6 +22,21 @@ export class BlogsService implements OnModuleInit {
async onModuleInit() {
await this.seedDefaultCategories();
// Start background scheduled publishing worker (every 60 seconds)
this.schedulerTimer = setInterval(() => {
this.publishDueScheduledBlogs().catch((err) => {
this.logger.error('Error in publishDueScheduledBlogs worker:', err);
});
}, 60000);
// Run an initial check on startup
this.publishDueScheduledBlogs().catch(() => {});
}
onModuleDestroy() {
if (this.schedulerTimer) {
clearInterval(this.schedulerTimer);
this.schedulerTimer = null;
}
}
private async seedDefaultCategories() {
@@ -22,7 +46,11 @@ export class BlogsService implements OnModuleInit {
{ name: 'سلامت گوارش و متابولیسم', slug: 'digestion', order: 2 },
{ name: 'مفاصل، استخوان و اسکلت', slug: 'joints-bones', order: 3 },
{ name: 'پوست، مو و آلرژی', slug: 'skin-coat', order: 4 },
{ name: 'ایمنی، پیشگیری و مراقبت بالینی', slug: 'health-prevention', order: 5 },
{
name: 'ایمنی، پیشگیری و مراقبت بالینی',
slug: 'health-prevention',
order: 5,
},
];
for (const cat of defaultCategories) {
@@ -33,7 +61,10 @@ export class BlogsService implements OnModuleInit {
});
}
} catch (err) {
console.warn('[BlogsService] Failed to seed default blog categories:', err);
console.warn(
'[BlogsService] Failed to seed default blog categories:',
err,
);
}
}
@@ -115,6 +146,7 @@ export class BlogsService implements OnModuleInit {
categoryId,
authorId,
publishedAt,
scheduledAt,
readingTime,
...rest
} = data;
@@ -138,15 +170,34 @@ export class BlogsService implements OnModuleInit {
}
const targetAuthorId = authorId || currentUserId;
const now = new Date();
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
const isFutureSchedule = parsedScheduledAt && parsedScheduledAt > now;
let finalStatus = rest.status || 'PUBLISHED';
let finalIsPublished =
rest.isPublished !== undefined ? rest.isPublished : true;
let finalPublishedAt = publishedAt ? new Date(publishedAt) : null;
if (isFutureSchedule) {
finalStatus = 'SCHEDULED';
finalIsPublished = false;
finalPublishedAt = null;
} else if (parsedScheduledAt && parsedScheduledAt <= now) {
finalStatus = 'PUBLISHED';
finalIsPublished = true;
finalPublishedAt = parsedScheduledAt;
} else if (!finalPublishedAt && finalStatus === 'PUBLISHED') {
finalPublishedAt = now;
}
const createPayload: Prisma.BlogCreateInput = {
...rest,
status: finalStatus,
isPublished: finalIsPublished,
readingTime: readingTime ? Number(readingTime) : 3,
publishedAt: publishedAt
? new Date(publishedAt)
: rest.status === 'PUBLISHED'
? new Date()
: null,
publishedAt: finalPublishedAt,
scheduledAt: parsedScheduledAt,
author: { connect: { id: targetAuthorId } },
...(categoryId ? { category: { connect: { id: categoryId } } } : {}),
...(tagConnectOrCreate.length > 0
@@ -177,18 +228,17 @@ export class BlogsService implements OnModuleInit {
categoryId,
authorId,
publishedAt,
scheduledAt,
readingTime,
...rest
} = data;
const now = new Date();
const updatePayload: Prisma.BlogUpdateInput = {
...rest,
...(readingTime !== undefined
? { readingTime: Number(readingTime) }
: {}),
...(publishedAt !== undefined
? { publishedAt: publishedAt ? new Date(publishedAt) : null }
: {}),
...(authorId ? { author: { connect: { id: authorId } } } : {}),
...(categoryId !== undefined
? categoryId
@@ -197,6 +247,24 @@ export class BlogsService implements OnModuleInit {
: {}),
};
if (scheduledAt !== undefined) {
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
updatePayload.scheduledAt = parsedScheduledAt;
if (parsedScheduledAt && parsedScheduledAt > now) {
updatePayload.status = 'SCHEDULED';
updatePayload.isPublished = false;
updatePayload.publishedAt = null;
} else if (parsedScheduledAt && parsedScheduledAt <= now) {
updatePayload.status = 'PUBLISHED';
updatePayload.isPublished = true;
updatePayload.publishedAt = parsedScheduledAt;
updatePayload.createdAt = parsedScheduledAt;
}
} else if (publishedAt !== undefined) {
updatePayload.publishedAt = publishedAt ? new Date(publishedAt) : null;
}
if (Array.isArray(tagNames)) {
const tagConnectOrCreate = [];
for (const tName of tagNames) {
@@ -367,4 +435,61 @@ export class BlogsService implements OnModuleInit {
}
return res;
}
/**
* Publishes blogs that have reached their scheduled publication date
*/
async publishDueScheduledBlogs(): Promise<number> {
const now = new Date();
const dueBlogs = await this.prisma.blog.findMany({
where: {
status: 'SCHEDULED',
scheduledAt: { lte: now },
},
select: {
id: true,
slug: true,
title: true,
scheduledAt: true,
},
});
if (!dueBlogs || dueBlogs.length === 0) {
return 0;
}
this.logger.log(
`Found ${dueBlogs.length} due scheduled blog(s) to publish automatically.`,
);
let publishedCount = 0;
for (const blog of dueBlogs) {
try {
const publishDate = blog.scheduledAt || now;
await this.prisma.blog.update({
where: { id: blog.id },
data: {
status: 'PUBLISHED',
isPublished: true,
publishedAt: publishDate,
createdAt: publishDate,
},
});
publishedCount++;
this.logger.log(
`Successfully published scheduled blog [${blog.title}] (${blog.slug})`,
);
// Immediate cache & sitemap revalidation
await this.revalidationService.revalidateBlog(blog.slug);
} catch (err: any) {
this.logger.error(
`Failed to publish scheduled blog [${blog.id}] (${blog.slug}): ${err?.message}`,
);
}
}
return publishedCount;
}
}
+55 -10
View File
@@ -19,24 +19,69 @@ export class CategoriesService implements OnModuleInit {
private async seedDefaultCategories() {
try {
const defaultCategories = [
{ name: 'مفاصل و استخوان', slug: 'joints', description: 'مکمل‌های ارتوپدی و مفاصل حاوی عصاره صدف سبز و GAG' },
{ name: 'سیستم ایمنی و گوارش', slug: 'immune', description: 'تقویت سیستم دفاعی بدن و پروبیوتیک‌های تخصصی' },
{ name: 'ویتامین‌ها و انرژی‌بخش‌ها', slug: 'energy', description: 'مولتی‌ویتامین‌ها و تونیک‌های انرژی‌بخش' },
{ name: 'مراقبت‌های ویژه (پوست، دندان و چشم)', slug: 'special-care', description: 'محلول‌های نقره، قطره‌های شستشو و ژل دندان' },
{ name: 'تقویت عمومی', slug: 'general', description: 'مکمل‌های پایه‌ای و روزانه سگ و گربه' },
{ name: 'تغذیه تخصصی', slug: 'nutrition', description: 'شیر خشک، پودر خون گاو و مکمل‌های تخصصی پرورش' },
{ name: 'مکمل‌های غذایی و درمانی', slug: 'supplements', description: 'طیف کامل مکمل‌های گرید دارویی Canina' },
{
name: 'مفاصل و استخوان',
slug: 'joints',
description: 'مکمل‌های ارتوپدی و مفاصل حاوی عصاره صدف سبز و GAG',
},
{
name: 'سیستم ایمنی و گوارش',
slug: 'immune',
description: 'تقویت سیستم دفاعی بدن و پروبیوتیک‌های تخصصی',
},
{
name: 'ویتامین‌ها و انرژی‌بخش‌ها',
slug: 'energy',
description: 'مولتی‌ویتامین‌ها و تونیک‌های انرژی‌بخش',
},
{
name: 'مراقبت‌های ویژه (پوست، دندان و چشم)',
slug: 'special-care',
description: 'محلول‌های نقره، قطره‌های شستشو و ژل دندان',
},
{
name: 'تقویت عمومی',
slug: 'general',
description: 'مکمل‌های پایه‌ای و روزانه سگ و گربه',
},
{
name: 'تغذیه تخصصی',
slug: 'nutrition',
description: 'شیر خشک، پودر خون گاو و مکمل‌های تخصصی پرورش',
},
{
name: 'مکمل‌های غذایی و درمانی',
slug: 'supplements',
description: 'طیف کامل مکمل‌های گرید دارویی Canina',
},
];
for (const cat of defaultCategories) {
await this.prisma.category.upsert({
const savedCat = await this.prisma.category.upsert({
where: { slug: cat.slug },
update: { name: cat.name, description: cat.description },
create: { name: cat.name, slug: cat.slug, description: cat.description },
create: {
name: cat.name,
slug: cat.slug,
description: cat.description,
},
});
// Automatically connect products with matching categorySlug
await this.prisma.product.updateMany({
where: {
categorySlug: cat.slug,
},
data: {
categoryId: savedCat.id,
},
});
}
} catch (err) {
console.warn('[CategoriesService] Failed to seed default categories:', err);
console.warn(
'[CategoriesService] Failed to seed default categories:',
err,
);
}
}
+11 -2
View File
@@ -66,9 +66,18 @@ export class MediaService {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
const ext = path.extname(originalname).toLowerCase();
const ALLOWED_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.webp', '.gif', '.pdf'];
const ALLOWED_EXTENSIONS = [
'.jpg',
'.jpeg',
'.png',
'.webp',
'.gif',
'.pdf',
];
if (!ALLOWED_EXTENSIONS.includes(ext)) {
throw new BadRequestException('پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایل‌های اجرایی مسدود هستند).');
throw new BadRequestException(
'پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایل‌های اجرایی مسدود هستند).',
);
}
const filename = `${uniqueSuffix}${ext}`;
const filePath = path.join(uploadDir, filename);
+6 -3
View File
@@ -183,8 +183,10 @@ export class SslService {
.toLowerCase();
// SEC-009: Strict domain validation preventing SSRF
const DOMAIN_REGEX = /^(?!-)[a-zA-Z0-9-]{1,63}(?<!-)(\.[a-zA-Z0-9-]{1,63})*\.[a-zA-Z]{2,}$/;
const IP_REGEX = /^(?:\d{1,3}\.){3}\d{1,3}$|^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
const DOMAIN_REGEX =
/^(?!-)[a-zA-Z0-9-]{1,63}(?<!-)(\.[a-zA-Z0-9-]{1,63})*\.[a-zA-Z]{2,}$/;
const IP_REGEX =
/^(?:\d{1,3}\.){3}\d{1,3}$|^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
if (
!cleanDomain ||
@@ -196,7 +198,8 @@ export class SslService {
) {
return resolve({
onlineCheck: false,
error: 'فرمت نام دامنه نامعتبر است یا آدرس‌های IP و داخلی مجاز نیستند.',
error:
'فرمت نام دامنه نامعتبر است یا آدرس‌های IP و داخلی مجاز نیستند.',
});
}
+38 -8
View File
@@ -63,7 +63,11 @@ export class AuthController {
return this.authService.sendOtp(sendOtpDto);
}
private setAuthCookies(res?: Response, accessToken?: string, refreshToken?: string) {
private setAuthCookies(
res?: Response,
accessToken?: string,
refreshToken?: string,
) {
if (!res || typeof res.cookie !== 'function') return;
const isProd = process.env.NODE_ENV === 'production';
if (accessToken) {
@@ -117,7 +121,11 @@ export class AuthController {
) {
const result = await this.authService.verifyOtp(verifyOtpDto);
if (result?.data) {
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
this.setAuthCookies(
res,
result.data.accessToken,
result.data.refreshToken,
);
}
return result;
}
@@ -136,7 +144,11 @@ export class AuthController {
) {
const result = await this.authService.register(registerDto);
if (result?.data) {
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
this.setAuthCookies(
res,
result.data.accessToken,
result.data.refreshToken,
);
}
return result;
}
@@ -153,7 +165,11 @@ export class AuthController {
) {
const result = await this.authService.login(loginDto);
if (result?.data) {
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
this.setAuthCookies(
res,
result.data.accessToken,
result.data.refreshToken,
);
}
return result;
}
@@ -170,7 +186,11 @@ export class AuthController {
) {
const result = await this.authService.adminLogin(body);
if (result?.data) {
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
this.setAuthCookies(
res,
result.data.accessToken,
result.data.refreshToken,
);
}
return result;
}
@@ -178,7 +198,9 @@ export class AuthController {
@Throttle({ default: { limit: 10, ttl: 60000 } })
@Post('refresh-token')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'دریافت جفت توکن جدید با استفاده از توکن تازه‌سازی' })
@ApiOperation({
summary: 'دریافت جفت توکن جدید با استفاده از توکن تازه‌سازی',
})
@ApiOkResponse({ description: 'توکن‌های جدید با موفقیت صادر شدند' })
@ApiBadRequestResponse({ description: 'توکن نامعتبر یا منقضی است' })
async refreshToken(
@@ -193,7 +215,11 @@ export class AuthController {
}
const result = await this.authService.refreshToken(token);
if (result?.data) {
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
this.setAuthCookies(
res,
result.data.accessToken,
result.data.refreshToken,
);
}
return result;
}
@@ -213,7 +239,11 @@ export class AuthController {
) {
const result = await this.authService.refresh(req.user);
if (result?.data) {
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
this.setAuthCookies(
res,
result.data.accessToken,
result.data.refreshToken,
);
}
return result;
}
+8 -2
View File
@@ -93,7 +93,10 @@ describe('AuthService', () => {
});
it('should delete OTP, find or create user and sign JWT', async () => {
mockRedis.get.mockResolvedValue('12345');
mockRedis.get.mockImplementation(async (key: string) => {
if (key.startsWith('otp_attempts:')) return null;
return '12345';
});
const mockUser = { id: 'user-id', mobile: '09123456789' };
mockPrisma.user.findUnique.mockResolvedValue(mockUser);
@@ -116,7 +119,10 @@ describe('AuthService', () => {
});
it('should create new user if user does not exist', async () => {
mockRedis.get.mockResolvedValue('12345');
mockRedis.get.mockImplementation(async (key: string) => {
if (key.startsWith('otp_attempts:')) return null;
return '12345';
});
mockPrisma.user.findUnique.mockResolvedValue(null);
const newUser = { id: 'new-user-id', mobile: '09123456789' };
mockPrisma.user.create.mockResolvedValue(newUser);
+38 -9
View File
@@ -150,17 +150,41 @@ export class AuthService {
async verifyOtp(verifyOtpDto: VerifyOtpDto) {
const phoneNumber = normalizeMobile(verifyOtpDto.phoneNumber);
const code = String(verifyOtpDto.code).trim();
const attemptsKey = `otp_attempts:${phoneNumber}`;
// SEC-007: Check failed attempts to prevent brute-forcing OTP
const currentAttempts = await this.redisService.get(attemptsKey);
if (currentAttempts && Number(currentAttempts) >= 5) {
await this.redisService.del(`otp:${phoneNumber}`);
throw new BadRequestException({
message:
'تعداد تلاش‌های ناموفق بیش از حد مجاز است. لطفاً پس از چند دقیقه دوباره کد جدید دریافت کنید.',
error: 'TOO_MANY_OTP_ATTEMPTS',
});
}
const savedCode = await this.redisService.get(`otp:${phoneNumber}`);
if (!savedCode || savedCode !== code) {
const attempts = await this.redisService.incr(attemptsKey, 300);
const remaining = Math.max(0, 5 - attempts);
if (remaining === 0) {
await this.redisService.del(`otp:${phoneNumber}`);
throw new BadRequestException({
message:
'کد تایید به دلیل ۵ بار تلاش ناموفق باطل شد. لطفاً کد جدید دریافت کنید.',
error: 'TOO_MANY_OTP_ATTEMPTS',
});
}
throw new BadRequestException({
message: 'کد وارد شده اشتباه یا منقضی شده است',
message: `کد وارد شده اشتباه یا منقضی شده است. (${remaining} تلاش باقی‌مانده)`,
error: 'INVALID_OTP',
});
}
// Success - clear OTP and attempts
await this.redisService.del(`otp:${phoneNumber}`);
await this.redisService.del(attemptsKey);
let user = await this.prisma.user.findUnique({
where: { mobile: phoneNumber },
@@ -346,11 +370,10 @@ export class AuthService {
Buffer.from(crypto.createHash('sha256').update(adminEmail).digest()),
);
const passwordMatches =
crypto.timingSafeEqual(
Buffer.from(crypto.createHash('sha256').update(body.password).digest()),
Buffer.from(crypto.createHash('sha256').update(adminPassword).digest()),
);
const passwordMatches = crypto.timingSafeEqual(
Buffer.from(crypto.createHash('sha256').update(body.password).digest()),
Buffer.from(crypto.createHash('sha256').update(adminPassword).digest()),
);
if (emailMatches && passwordMatches) {
const payload = {
@@ -391,7 +414,9 @@ export class AuthService {
secret: getJwtRefreshSecret(),
});
} catch {
throw new UnauthorizedException('توکن تازه‌سازی نامعتبر یا منقضی شده است');
throw new UnauthorizedException(
'توکن تازه‌سازی نامعتبر یا منقضی شده است',
);
}
const userId = decoded.sub;
@@ -405,7 +430,9 @@ export class AuthService {
const tokenKey = `refresh_token:${userId}:${tokenId}`;
const tokenValid = await this.redisService.get(tokenKey);
if (!tokenValid) {
throw new UnauthorizedException('توکن تازه‌سازی باطل شده است. لطفاً مجدداً وارد شوید');
throw new UnauthorizedException(
'توکن تازه‌سازی باطل شده است. لطفاً مجدداً وارد شوید',
);
}
// Invalidate old token (Rotation)
@@ -492,7 +519,9 @@ export class AuthService {
// If token payload has jti and sub, also invalidate the refresh token in Redis
if (decoded && decoded.sub && decoded.jti) {
await this.redisService.del(`refresh_token:${decoded.sub}:${decoded.jti}`);
await this.redisService.del(
`refresh_token:${decoded.sub}:${decoded.jti}`,
);
}
} catch {
await this.redisService.set(`bl_token:${token}`, '1', 15 * 60);
+3 -1
View File
@@ -49,7 +49,9 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
if (rawToken) {
const isBlacklisted = await this.redisService.get(`bl_token:${rawToken}`);
if (isBlacklisted) {
throw new UnauthorizedException('این توکن باطل شده است. لطفاً مجدداً وارد شوید');
throw new UnauthorizedException(
'این توکن باطل شده است. لطفاً مجدداً وارد شوید',
);
}
}
+11
View File
@@ -182,6 +182,17 @@ export class BlogsService {
throw new NotFoundException('مقاله یافت نشد');
}
// Public route must not expose scheduled, draft, or future published posts
const now = new Date();
const isReady =
blog.isPublished &&
blog.status === 'PUBLISHED' &&
(!blog.publishedAt || blog.publishedAt <= now);
if (!isReady) {
throw new NotFoundException('مقاله یافت نشد');
}
// Fetch related products safely
let relatedProducts: any[] = [];
if (
+17 -4
View File
@@ -46,10 +46,23 @@ export class RolesGuard implements CanActivate {
}
}
const userRoleLower = user.role.toLowerCase();
const hasRole = requiredRoles.some(
(r) => r.toLowerCase() === userRoleLower,
);
const normalizeRole = (r: string) => r.toLowerCase().replace(/[_-]/g, '');
const userRoleNorm = normalizeRole(user.role);
const hasRole = requiredRoles.some((r) => {
const requiredNorm = normalizeRole(r);
// Direct normalized match
if (requiredNorm === userRoleNorm) return true;
// Superadmin satisfies admin
if (
(userRoleNorm === 'superadmin' || userRoleNorm === 'adminsuper') &&
requiredNorm === 'admin'
) {
return true;
}
return false;
});
if (!hasRole) {
throw new ForbiddenException('سطح دسترسی شما کافی نیست');
}
@@ -9,7 +9,9 @@ export class RevalidationService {
process.env.FRONTEND_INTERNAL_URL ||
process.env.FRONTEND_URL ||
process.env.NEXT_PUBLIC_SITE_URL ||
(process.env.NODE_ENV === 'production' ? 'http://frontend_prod:8080' : 'http://localhost:3000');
(process.env.NODE_ENV === 'production'
? 'http://frontend_prod:8080'
: 'http://localhost:3000');
return raw.replace(/\/+$/, '');
}
@@ -17,9 +19,13 @@ export class RevalidationService {
const secret = process.env.REVALIDATION_SECRET;
if (!secret) {
if (process.env.NODE_ENV === 'production') {
throw new Error('REVALIDATION_SECRET is required in production environment.');
throw new Error(
'REVALIDATION_SECRET is required in production environment.',
);
}
this.logger.warn('REVALIDATION_SECRET is not defined in environment variables.');
this.logger.warn(
'REVALIDATION_SECRET is not defined in environment variables.',
);
return '';
}
return secret;
@@ -108,6 +114,7 @@ export class RevalidationService {
this.revalidateTag('blogs'),
this.revalidateTag('home-data'),
this.revalidatePath('/blog'),
this.revalidatePath('/sitemap.xml'),
this.revalidatePath('/'),
];
+17 -3
View File
@@ -230,7 +230,7 @@ export class OrdersService {
});
}
return tx.order.create({
const newOrder = await tx.order.create({
data: {
userId,
couponId,
@@ -252,6 +252,17 @@ export class OrdersService {
},
},
});
if (couponId) {
await tx.coupon
.update({
where: { id: couponId },
data: { usedCount: { increment: 1 } },
})
.catch(() => {});
}
return newOrder;
});
// Send Order Confirmation SMS for wallet orders
@@ -570,8 +581,11 @@ export class OrdersService {
throw new NotFoundException('سفارش مورد نظر یافت نشد');
}
if (['shipped', 'delivered'].includes(order.status)) {
throw new BadRequestException('این سفارش قبلاً پرداخت و تکمیل شده است');
const ALLOWED_RETRY_STATUSES = ['pending_payment', 'failed'];
if (!ALLOWED_RETRY_STATUSES.includes(order.status)) {
throw new BadRequestException(
'تنها سفارش‌های در انتظار پرداخت یا ناموفق قابلیت پرداخت مجدد دارند.',
);
}
const selectedMethod = paymentMethod || order.paymentMethod || 'online';
+11 -2
View File
@@ -219,10 +219,19 @@ export class PaymentController {
return res.status(HttpStatus.OK).json(result);
}
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@Get('verify-status/:trackId')
@ApiOperation({ summary: 'استعلام و دریافت وضعیت تراکنش پرداخت با TrackID' })
async getTransactionStatus(@Param('trackId') trackId: string) {
return this.paymentService.getTransaction(trackId);
async getTransactionStatus(
@Req() req: { user: { id: string; role?: string } },
@Param('trackId') trackId: string,
) {
const isAdmin =
req.user?.role === 'Admin' ||
req.user?.role === 'ADMIN' ||
req.user?.role === 'SuperAdmin';
return this.paymentService.getTransaction(trackId, req.user?.id, isAdmin);
}
// ==========================================
+41 -7
View File
@@ -2,6 +2,7 @@ import {
Injectable,
NotFoundException,
BadRequestException,
ForbiddenException,
Logger,
} from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
@@ -452,6 +453,16 @@ export class PaymentService {
},
});
}
// Increment coupon usedCount if coupon was applied
if (transaction.order && transaction.order.couponId) {
await tx.coupon
.update({
where: { id: transaction.order.couponId },
data: { usedCount: { increment: 1 } },
})
.catch(() => {});
}
}
// 3. If it's a Wallet Top-up
@@ -765,7 +776,11 @@ export class PaymentService {
/**
* 5. Get Payment Transaction Details by TrackID
*/
async getTransaction(trackId: string) {
async getTransaction(
trackId: string,
requestingUserId?: string,
isAdmin = false,
) {
const transaction = await this.prisma.paymentTransaction.findUnique({
where: { trackId },
include: {
@@ -784,6 +799,21 @@ export class PaymentService {
throw new NotFoundException('تراکنش یافت نشد');
}
if (
!isAdmin &&
requestingUserId &&
transaction.userId &&
transaction.userId !== requestingUserId
) {
throw new ForbiddenException(
'شما دسترسی به اطلاعات این تراکنش را ندارید',
);
}
const maskedCard = transaction.cardNumber
? transaction.cardNumber.replace(/(\d{6})\d{6}(\d{4})/, '$1******$2')
: null;
return {
id: transaction.id,
trackId: transaction.trackId,
@@ -793,11 +823,7 @@ export class PaymentService {
message: transaction.message,
gateway: transaction.gateway,
type: transaction.type,
cardNumber: transaction.cardNumber,
ipAddress: transaction.ipAddress,
userAgent: transaction.userAgent,
rawRequest: transaction.rawRequest,
rawResponse: transaction.rawResponse,
cardNumber: isAdmin ? transaction.cardNumber : maskedCard,
paidAt: transaction.paidAt,
createdAt: transaction.createdAt,
order: transaction.order,
@@ -806,9 +832,17 @@ export class PaymentService {
id: transaction.user.id,
firstName: transaction.user.firstName,
lastName: transaction.user.lastName,
mobile: transaction.user.mobile,
mobile: isAdmin ? transaction.user.mobile : undefined,
}
: null,
...(isAdmin
? {
ipAddress: transaction.ipAddress,
userAgent: transaction.userAgent,
rawRequest: transaction.rawRequest,
rawResponse: transaction.rawResponse,
}
: {}),
};
}
@@ -85,6 +85,13 @@ export class PrescriptionsController {
notes?: string;
},
) {
if (
!body?.fileUrl ||
typeof body.fileUrl !== 'string' ||
!body.fileUrl.trim()
) {
throw new BadRequestException('آدرس فایل نسخه الزامی است.');
}
const userId = req.user?.id || req.user?.userId || null;
return this.prescriptionsService.create(userId, body);
}
+3 -1
View File
@@ -235,7 +235,9 @@ export class ProductsService {
petTypes: Array.from(
new Set(
petTypesDb
.map((p) => (p.suitableFor === 'هر دو' ? 'سگ و گربه' : p.suitableFor))
.map((p) =>
p.suitableFor === 'هر دو' ? 'سگ و گربه' : p.suitableFor,
)
.filter(Boolean),
),
),
+12 -3
View File
@@ -100,9 +100,18 @@ export const CANONICAL_ALIASES: Record<string, string[]> = {
charity_round_step: ['CHARITY_ROUND_STEP', 'charityRoundStep'],
charityRoundStep: ['CHARITY_ROUND_STEP', 'charity_round_step'],
CHARITY_DONATION_ENABLED: ['charity_donation_enabled', 'charityDonationEnabled'],
charity_donation_enabled: ['CHARITY_DONATION_ENABLED', 'charityDonationEnabled'],
charityDonationEnabled: ['CHARITY_DONATION_ENABLED', 'charity_donation_enabled'],
CHARITY_DONATION_ENABLED: [
'charity_donation_enabled',
'charityDonationEnabled',
],
charity_donation_enabled: [
'CHARITY_DONATION_ENABLED',
'charityDonationEnabled',
],
charityDonationEnabled: [
'CHARITY_DONATION_ENABLED',
'charity_donation_enabled',
],
// Zibal Gateway & Tokens
ZIBAL_EBANK_TOKEN: [
+9 -4
View File
@@ -13,6 +13,8 @@ import {
} from '@nestjs/common';
import { UsersService } from './users.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from '../common/decorators/roles.decorator';
import {
ApiTags,
ApiBearerAuth,
@@ -202,9 +204,11 @@ export class UsersController {
return this.usersService.setDefaultAddress(req.user.id, addressId);
}
@UseGuards(JwtAuthGuard)
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin', 'ADMIN', 'SuperAdmin')
@ApiBearerAuth()
@Post('wallet/top-up')
@ApiOperation({ summary: 'شارژ کیف پول کاربر' })
@ApiOperation({ summary: 'شارژ دستی کیف پول کاربر (فقط مدیر سیستم)' })
@ApiCreatedResponse({
description: 'کیف پول با موفقیت شارژ شد',
schema: {
@@ -222,12 +226,13 @@ export class UsersController {
@ApiBadRequestResponse({ description: 'مبلغ نامعتبر است' })
async topUpWallet(
@Req() req: { user: { id: string } },
@Body() body: { amount: number },
@Body() body: { amount: number; targetUserId?: string },
) {
const amount = Number(body.amount);
if (!amount || amount <= 0) {
throw new BadRequestException('مبلغ شارژ باید بزرگتر از صفر باشد');
}
return this.usersService.topUpWallet(req.user.id, amount);
const targetUserId = body.targetUserId || req.user.id;
return this.usersService.topUpWallet(targetUserId, amount);
}
}
-58
View File
@@ -30,64 +30,6 @@ export class UsersService {
) {}
async findById(id: string) {
if (id === '12345678-1234-1234-1234-123456789012') {
const dbUser = await this.prisma.user.findUnique({
where: { id },
include: {
pets: {
include: {
medicalConditions: true,
reminders: {
include: {
completions: true,
},
},
healthLogs: true,
},
},
orders: {
orderBy: { createdAt: 'desc' },
include: {
orderItems: {
include: { product: true },
},
},
},
addresses: true,
walletTransactions: {
orderBy: { createdAt: 'desc' },
take: 50,
},
},
});
if (dbUser) {
const { password, ...safeUser } = dbUser;
return {
...safeUser,
hasPassword: !!password,
};
}
return {
id: '12345678-1234-1234-1234-123456789012',
firstName: 'مدیر',
lastName: 'سیستم',
email: process.env.ADMIN_EMAIL || 'admin@canina.ir',
mobile: '09120000000',
role: 'Admin',
walletBalance: new Prisma.Decimal(0),
charityDonationTotal: new Prisma.Decimal(0),
pets: [],
orders: [],
addresses: [],
walletTransactions: [],
hasPassword: true,
createdAt: new Date(),
updatedAt: new Date(),
};
}
const user = await this.prisma.user.findUnique({
where: { id },
include: {
+8 -3
View File
@@ -13,6 +13,8 @@ import { VideosService } from './videos.service';
import { CreateVideoDto } from './dto/create-video.dto';
import { GetVideosQueryDto } from './dto/get-videos-query.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from '../common/decorators/roles.decorator';
import {
ApiTags,
ApiOperation,
@@ -42,7 +44,8 @@ export class VideosController {
}
@Post()
@UseGuards(JwtAuthGuard)
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin', 'ADMIN', 'SuperAdmin')
@ApiBearerAuth()
@ApiOperation({ summary: 'افزودن ویدئوی جدید (ادمین)' })
create(@Body() createVideoDto: CreateVideoDto) {
@@ -50,7 +53,8 @@ export class VideosController {
}
@Put(':id')
@UseGuards(JwtAuthGuard)
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin', 'ADMIN', 'SuperAdmin')
@ApiBearerAuth()
@ApiOperation({ summary: 'ویرایش ویدئو (ادمین)' })
update(
@@ -61,7 +65,8 @@ export class VideosController {
}
@Delete(':id')
@UseGuards(JwtAuthGuard)
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin', 'ADMIN', 'SuperAdmin')
@ApiBearerAuth()
@ApiOperation({ summary: 'حذف ویدئو (ادمین)' })
remove(@Param('id') id: string) {
+31 -1
View File
@@ -1,7 +1,10 @@
import { Suspense } from 'react';
import { Suspense, useEffect } from 'react';
import { RouterProvider } from 'react-router-dom';
import { Toaster } from 'react-hot-toast';
import axios from 'axios';
import { router } from './routes/adminRoutes';
import { useAdminAuthStore } from './store/adminAuthStore';
import { BASE_DOMAIN } from './services/api';
function SuspenseFallback() {
return (
@@ -15,6 +18,33 @@ function SuspenseFallback() {
}
function App() {
const isAuthenticated = useAdminAuthStore((state) => state.isAuthenticated);
const setAuth = useAdminAuthStore((state) => state.setAuth);
// Proactive token refresh every 10 minutes to prevent 15-min JWT session loss during form edits (A1)
useEffect(() => {
if (!isAuthenticated) return;
const refreshSession = async () => {
try {
const res = await axios.post(
`${BASE_DOMAIN}/api/auth/refresh`,
{},
{ withCredentials: true }
);
if (res.data?.success && res.data.data?.accessToken) {
setAuth(res.data.data.accessToken, res.data.data.user);
}
} catch {
// Silently catch; let api interceptor handle on next actual request if needed
}
};
// Refresh every 10 minutes (600,000 ms)
const interval = setInterval(refreshSession, 10 * 60 * 1000);
return () => clearInterval(interval);
}, [isAuthenticated, setAuth]);
return (
<>
<Toaster
@@ -18,7 +18,9 @@ export default function Layout() {
const next = !prev;
try {
localStorage.setItem('canina_admin_sidebar_collapsed', String(next));
} catch {}
} catch {
// ignore localStorage access error
}
return next;
});
};
+26 -9
View File
@@ -96,6 +96,7 @@ export interface BlogPost {
status: 'DRAFT' | 'PUBLISHED' | 'SCHEDULED' | 'ARCHIVED';
isPublished: boolean;
publishedAt?: string | null;
scheduledAt?: string | null;
readingTime: number;
featured: boolean;
allowComments: boolean;
@@ -190,6 +191,7 @@ export default function Blogs() {
status: 'PUBLISHED' as 'DRAFT' | 'PUBLISHED' | 'SCHEDULED' | 'ARCHIVED',
isPublished: true,
publishedAt: '',
scheduledAt: '',
readingTime: 3,
featured: false,
allowComments: true,
@@ -266,6 +268,7 @@ export default function Blogs() {
status: blog.status || (blog.isPublished ? 'PUBLISHED' : 'DRAFT'),
isPublished: blog.isPublished !== false,
publishedAt: blog.publishedAt ? new Date(blog.publishedAt).toISOString().slice(0, 16) : '',
scheduledAt: blog.scheduledAt ? new Date(blog.scheduledAt).toISOString().slice(0, 16) : '',
readingTime: blog.readingTime || calculateReadingTime(blog.content || ''),
featured: Boolean(blog.featured),
allowComments: blog.allowComments !== false,
@@ -301,6 +304,7 @@ export default function Blogs() {
status: 'PUBLISHED',
isPublished: true,
publishedAt: new Date().toISOString().slice(0, 16),
scheduledAt: '',
readingTime: 3,
featured: false,
allowComments: true,
@@ -477,6 +481,7 @@ export default function Blogs() {
const payload = {
...formData,
isPublished: formData.status === 'PUBLISHED',
scheduledAt: formData.scheduledAt ? new Date(formData.scheduledAt).toISOString() : null,
};
if (editingBlog) {
@@ -551,7 +556,7 @@ export default function Blogs() {
};
// Helper status badge
const renderStatusBadge = (status: string, isPublished: boolean) => {
const renderStatusBadge = (status: string, isPublished: boolean, scheduledAt?: string | null) => {
switch (status) {
case 'PUBLISHED':
return (
@@ -560,13 +565,18 @@ export default function Blogs() {
منتشر شده
</span>
);
case 'SCHEDULED':
case 'SCHEDULED': {
const dateStr = scheduledAt ? new Date(scheduledAt).toLocaleDateString('fa-IR') : '';
return (
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-blue-50 text-blue-700 border border-blue-200 rounded-full text-xs font-black">
<span
className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-blue-50 text-blue-700 border border-blue-200 rounded-full text-xs font-black"
title={scheduledAt ? `موعد انتشار: ${new Date(scheduledAt).toLocaleString('fa-IR')}` : undefined}
>
<Clock className="w-3.5 h-3.5" />
زمان‌بندی شده
{dateStr ? `در صف: ${dateStr}` : 'زمان‌بندی شده'}
</span>
);
}
case 'ARCHIVED':
return (
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-gray-100 text-gray-700 border border-gray-200 rounded-full text-xs font-black">
@@ -764,7 +774,7 @@ export default function Blogs() {
<span>{(blog.viewCount || 0).toLocaleString('fa-IR')} بازدید</span>
</div>
</td>
<td className="py-4 px-6">{renderStatusBadge(blog.status, blog.isPublished)}</td>
<td className="py-4 px-6">{renderStatusBadge(blog.status, blog.isPublished, blog.scheduledAt)}</td>
<td className="py-4 px-6">
<div className="flex items-center gap-1.5">
<Button
@@ -1133,17 +1143,24 @@ export default function Blogs() {
<div className="space-y-2 p-4 bg-gray-50 border border-gray-200 rounded-3xl">
<label className="text-xs font-black text-gray-700 block">
تاریخ و ساعت انتشار زمان‌بندی شده (Publish Date/Time)
انتشار در تاریخ (خالی = انتشار فوری)
</label>
<input
type="datetime-local"
value={formData.publishedAt}
onChange={(e) => setFormData({ ...formData, publishedAt: e.target.value })}
value={formData.scheduledAt}
onChange={(e) => {
const val = e.target.value;
setFormData((prev) => ({
...prev,
scheduledAt: val,
status: val && new Date(val).getTime() > Date.now() ? 'SCHEDULED' : prev.status,
}));
}}
className="w-full px-3.5 py-2 rounded-2xl border border-gray-200 text-xs font-bold outline-none bg-white font-sans"
dir="ltr"
/>
<p className="text-[11px] text-gray-400 font-medium">
در صورت تنظیم وضعیت روی "زمان‌بندی شده"، این مقاله تا رسیدن این تاریخ نمایش داده نخواهد شد.
در صورت تعیین تاریخ آینده، مقاله در صف انتشار زمان‌بندی‌شده قرار گرفته و در موعد مقرر خودکار منتشر می‌شود.
</p>
</div>
</div>
+3 -1
View File
@@ -507,7 +507,9 @@ export default function Products() {
scientificTagline: product.scientificTagline || '',
description: product.description || '',
shortDescription: product.shortDescription || '',
categoryId: typeof product.category === 'object' && product.category !== null ? product.category.id : (product.categoryId || ''),
categoryId: typeof product.category === 'object' && product.category !== null
? product.category.id
: (product.categoryId || categories.find(c => c.slug === (product as any).categorySlug)?.id || ''),
buyPrice: bPrice,
priceValue: pPrice,
wholesalePrice: wPrice,
@@ -59,6 +59,10 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
if (!blog) {
return {
title: formatPageTitle('مقاله یافت نشد', config.brandNameFa, config.titleSeparator, config.titlePosition),
robots: {
index: false,
follow: false,
},
};
}
+13 -2
View File
@@ -73,8 +73,19 @@ async function getBlogs() {
}
}
export default async function Blog() {
export default async function Blog({
searchParams,
}: {
searchParams?: Promise<{ categoryId?: string; category?: string }>;
}) {
const resolvedParams = searchParams ? await searchParams : {};
const [blogs, categories] = await Promise.all([getBlogs(), getCategories()]);
return <BlogPage blogs={blogs} categories={categories} />;
return (
<BlogPage
blogs={blogs}
categories={categories}
initialCategoryId={resolvedParams.categoryId || resolvedParams.category || 'ALL'}
/>
);
}
@@ -39,19 +39,23 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
document.head.appendChild(gtmScript);
}
// 2. Google Analytics 4 (if standalone without GTM)
if (gaId && !gtmId) {
// 2. Google Analytics 4 (ensures GA4 hits fire directly even if GTM container lacks GA4 config tag)
if (gaId) {
window.dataLayer = window.dataLayer || [];
function gtag(...args: any[]) {
window.dataLayer?.push(args);
}
(window as any).gtag = gtag;
gtag('js', new Date());
gtag('config', gaId, { page_path: window.location.pathname });
const gaScript = document.createElement('script');
gaScript.async = true;
gaScript.src = `https://www.googletagmanager.com/gtag/js?id=${gaId}`;
document.head.appendChild(gaScript);
// Only append gtag.js script if not already added
if (!document.querySelector(`script[src*="${gaId}"]`)) {
const gaScript = document.createElement('script');
gaScript.async = true;
gaScript.src = `https://www.googletagmanager.com/gtag/js?id=${gaId}`;
document.head.appendChild(gaScript);
}
}
// 3. Microsoft Clarity
+17 -3
View File
@@ -52,16 +52,24 @@ export interface BlogPostItem {
export default function BlogPage({
blogs = [],
categories = [],
initialCategoryId = 'ALL',
}: {
blogs: BlogPostItem[];
categories?: BlogCategory[];
initialCategoryId?: string;
}) {
const router = useRouter();
const [products, setProducts] = useState<Product[]>([]);
const [selectedCategory, setSelectedCategory] = useState<string>("ALL");
const [selectedCategory, setSelectedCategory] = useState<string>(initialCategoryId);
const [searchQuery, setSearchQuery] = useState<string>("");
const [selectedTag, setSelectedTag] = useState<string | null>(null);
React.useEffect(() => {
if (initialCategoryId) {
setSelectedCategory(initialCategoryId);
}
}, [initialCategoryId]);
React.useEffect(() => {
productService.getProducts({ limit: 8 }).then((res) => setProducts(res.data));
}, []);
@@ -184,7 +192,10 @@ export default function BlogPage({
{/* Category Filter Pills */}
<div className="flex items-center gap-2 overflow-x-auto pb-1 scrollbar-none">
<button
onClick={() => setSelectedCategory("ALL")}
onClick={() => {
setSelectedCategory("ALL");
router.replace('/blog', { scroll: false });
}}
className={`px-4 py-2 rounded-2xl text-xs font-black transition-all cursor-pointer whitespace-nowrap ${
selectedCategory === "ALL"
? "bg-canina-blue text-white shadow-md shadow-canina-blue/20 scale-102"
@@ -196,7 +207,10 @@ export default function BlogPage({
{categories.map((c) => (
<button
key={c.id}
onClick={() => setSelectedCategory(c.id)}
onClick={() => {
setSelectedCategory(c.id);
router.replace(`/blog?categoryId=${c.id}`, { scroll: false });
}}
className={`px-4 py-2 rounded-2xl text-xs font-black transition-all cursor-pointer whitespace-nowrap ${
selectedCategory === c.id
? "bg-canina-blue text-white shadow-md shadow-canina-blue/20 scale-102"
@@ -1,5 +1,6 @@
/* eslint-disable @next/next/no-img-element */
"use client";
import Link from "next/link";
import { useState, useMemo, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "motion/react";
import {
@@ -1021,7 +1022,12 @@ export default function ProductPage({ productSlug }: { productSlug: string }) {
<h4 className="text-[11px] font-black text-medical-gray-400 uppercase tracking-wider font-vazir">مواد تشکیل‌دهنده برتر</h4>
<div className="flex flex-wrap gap-2">
{product.main_ingredients.map((ing, idx) => {
const termKey = termKeys.find(key => {
const matchedItem = product.ingredientItems?.find(
item => item.ingredient.trim().toLowerCase() === ing.trim().toLowerCase()
);
const cardSlug = matchedItem?.ingredientCardSlug;
const termKey = !cardSlug ? termKeys.find(key => {
const termObj = scientificTerms[key] || SCIENTIFIC_TERMS[key];
const termName = termObj?.term || key;
const ingClean = ing.toLowerCase();
@@ -1031,15 +1037,27 @@ export default function ProductPage({ productSlug }: { productSlug: string }) {
keyClean.includes(ingClean) ||
ingClean.includes(termNameClean) ||
termNameClean.includes(ingClean);
});
}) : null;
return (
<div key={idx} className="bg-medical-gray-50 border border-medical-gray-200 px-3 py-1.5 rounded-xl flex items-center gap-1.5 group hover:border-canina-blue/30 hover:bg-canina-blue/5 transition-all">
<span className="text-xs sm:text-sm font-bold text-medical-gray-700 font-vazir">
{termKey ? (
{cardSlug ? (
<Link
href={`/wiki/${cardSlug}`}
className="hover:text-canina-blue hover:underline transition-colors flex items-center gap-1"
title="مشاهده در دانشنامه علمی کنینا"
>
<span>{ing}</span>
<span className="text-[10px] text-canina-blue bg-canina-blue/10 px-1.5 py-0.5 rounded-md font-normal">دانشنامه</span>
</Link>
) : termKey ? (
<Tooltip termKey={termKey} onWikiNavigate={(id) => router.push(`/wiki?term=${id}`)}>
{ing}
</Tooltip>
) : ing}
) : (
ing
)}
</span>
<Sparkles className="w-3 h-3 text-canina-blue opacity-40 group-hover:opacity-100 transition-opacity" />
</div>
@@ -43,6 +43,11 @@ export interface Product {
unit: string;
packageSize: number;
main_ingredients: string[];
ingredientItems?: Array<{
ingredient: string;
ingredientCardId?: string | null;
ingredientCardSlug?: string | null;
}>;
dosage_logic: string;
benefits: string;
benefitsList?: string[];
@@ -55,8 +55,11 @@ interface BackendProduct {
pdfTitle?: string;
pdfDescription?: string;
pdfCover?: string;
productGroup?: string;
ingredientList?: Array<{ ingredient: string }>;
ingredientList?: Array<{
ingredient: string;
ingredientCardId?: string | null;
ingredientCardSlug?: string | null;
}>;
ingredients?: string;
symptoms?: Array<{ symptom?: string } | string>;
keyBenefits?: unknown;
@@ -150,6 +153,7 @@ export class ProductService {
: [],
main_ingredients: data.ingredientList?.map(i => i.ingredient) || data.ingredients?.split(/[،,-]/).map(s => s.trim()).filter(Boolean) || [],
ingredientItems: data.ingredientList && data.ingredientList.length > 0 ? data.ingredientList : undefined,
symptoms: data.symptoms?.map(s => typeof s === 'string' ? s : s.symptom || '').filter(Boolean) || [],
keyBenefits: dosageConfig.keyBenefits && Array.isArray(dosageConfig.keyBenefits) && dosageConfig.keyBenefits.length > 0
? dosageConfig.keyBenefits