From efb3c473c452d35f9842b8b059b46963dc8a150f Mon Sep 17 00:00:00 2001 From: parsaaghayi Date: Tue, 29 Sep 2026 01:15:33 +0330 Subject: [PATCH] feat: complete scheduled publishing, security remediation and DEV_TICKETS implementation --- backend/prisma/schema.prisma | 19 ++- backend/prisma/seed-products.ts | 2 +- backend/src/admin/admin.controller.spec.ts | 6 +- backend/src/admin/admin.service.ts | 97 ++++++++++-- backend/src/admin/blogs.service.ts | 149 ++++++++++++++++-- backend/src/admin/categories.service.ts | 65 ++++++-- backend/src/admin/media.service.ts | 13 +- backend/src/admin/ssl.service.ts | 9 +- backend/src/auth/auth.controller.ts | 46 +++++- backend/src/auth/auth.service.spec.ts | 10 +- backend/src/auth/auth.service.ts | 47 ++++-- backend/src/auth/jwt.strategy.ts | 4 +- backend/src/blogs/blogs.service.ts | 11 ++ backend/src/common/guards/roles.guard.ts | 21 ++- .../revalidation/revalidation.service.ts | 13 +- backend/src/orders/orders.service.ts | 20 ++- backend/src/payment/payment.controller.ts | 13 +- backend/src/payment/payment.service.ts | 48 +++++- .../prescriptions/prescriptions.controller.ts | 7 + backend/src/products/products.service.ts | 4 +- backend/src/settings/settings.service.ts | 15 +- backend/src/users/users.controller.ts | 13 +- backend/src/users/users.service.ts | 58 ------- backend/src/videos/videos.controller.ts | 11 +- frontend/admin-panel/src/App.tsx | 32 +++- .../admin-panel/src/components/Layout.tsx | 4 +- frontend/admin-panel/src/pages/Blogs.tsx | 35 ++-- frontend/admin-panel/src/pages/Products.tsx | 4 +- frontend/application/app/blog/[slug]/page.tsx | 4 + frontend/application/app/blog/page.tsx | 15 +- .../components/AnalyticsDeferred.tsx | 16 +- frontend/application/components/BlogPage.tsx | 20 ++- .../application/components/ProductPage.tsx | 26 ++- frontend/application/lib/data/products.ts | 5 + .../lib/services/productService.ts | 8 +- 35 files changed, 685 insertions(+), 185 deletions(-) diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 0d6b9dc9..cd006589 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -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") } diff --git a/backend/prisma/seed-products.ts b/backend/prisma/seed-products.ts index 62da1853..d8deeb30 100644 --- a/backend/prisma/seed-products.ts +++ b/backend/prisma/seed-products.ts @@ -218,7 +218,7 @@ const PRODUCT_TAGLINES_MAP: Record = { 'canina-immun-booster-paste': 'تامین فوری ایمونوگلوبولین‌های آغوز و تثبیت فلور روده در زمان نقاهت', 'canina-katzenmilch': - 'شیر خشک جایگزین بچه گربه حاوی تورین و فاقد لاکتوز مزاحم', + 'شیر خشک جایگزین بچه گربه حاوی تورین بالا و پروتئین غنی‌شده', 'canina-lachs-ol': 'اسیدهای چرب ضروری امگا ۳ برای درخشش پوشش مویی و سلامت پوست', 'canina-marine-lmischung-premium': diff --git a/backend/src/admin/admin.controller.spec.ts b/backend/src/admin/admin.controller.spec.ts index 6bfb0b3a..e96665d0 100644 --- a/backend/src/admin/admin.controller.spec.ts +++ b/backend/src/admin/admin.controller.spec.ts @@ -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); diff --git a/backend/src/admin/admin.service.ts b/backend/src/admin/admin.service.ts index 5c3fd07f..60fae8a4 100644 --- a/backend/src/admin/admin.service.ts +++ b/backend/src/admin/admin.service.ts @@ -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, + }; + }); + } } diff --git a/backend/src/admin/blogs.service.ts b/backend/src/admin/blogs.service.ts index 2d4b7947..51ef0647 100644 --- a/backend/src/admin/blogs.service.ts +++ b/backend/src/admin/blogs.service.ts @@ -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 { + 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; + } } diff --git a/backend/src/admin/categories.service.ts b/backend/src/admin/categories.service.ts index a276d32c..8dc4e81e 100644 --- a/backend/src/admin/categories.service.ts +++ b/backend/src/admin/categories.service.ts @@ -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, + ); } } diff --git a/backend/src/admin/media.service.ts b/backend/src/admin/media.service.ts index 88e0e790..8abbb053 100644 --- a/backend/src/admin/media.service.ts +++ b/backend/src/admin/media.service.ts @@ -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); diff --git a/backend/src/admin/ssl.service.ts b/backend/src/admin/ssl.service.ts index eba3e089..cc6ed084 100644 --- a/backend/src/admin/ssl.service.ts +++ b/backend/src/admin/ssl.service.ts @@ -183,8 +183,10 @@ export class SslService { .toLowerCase(); // SEC-009: Strict domain validation preventing SSRF - const DOMAIN_REGEX = /^(?!-)[a-zA-Z0-9-]{1,63}(? { }); 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); diff --git a/backend/src/auth/auth.service.ts b/backend/src/auth/auth.service.ts index 714b3669..d1643ed4 100644 --- a/backend/src/auth/auth.service.ts +++ b/backend/src/auth/auth.service.ts @@ -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); diff --git a/backend/src/auth/jwt.strategy.ts b/backend/src/auth/jwt.strategy.ts index df57c2d8..7f8f0494 100644 --- a/backend/src/auth/jwt.strategy.ts +++ b/backend/src/auth/jwt.strategy.ts @@ -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( + 'این توکن باطل شده است. لطفاً مجدداً وارد شوید', + ); } } diff --git a/backend/src/blogs/blogs.service.ts b/backend/src/blogs/blogs.service.ts index 1f57f39b..8896f0cd 100644 --- a/backend/src/blogs/blogs.service.ts +++ b/backend/src/blogs/blogs.service.ts @@ -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 ( diff --git a/backend/src/common/guards/roles.guard.ts b/backend/src/common/guards/roles.guard.ts index 1ceb8134..7d9379f1 100644 --- a/backend/src/common/guards/roles.guard.ts +++ b/backend/src/common/guards/roles.guard.ts @@ -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('سطح دسترسی شما کافی نیست'); } diff --git a/backend/src/common/revalidation/revalidation.service.ts b/backend/src/common/revalidation/revalidation.service.ts index 034df758..93bb5bfe 100644 --- a/backend/src/common/revalidation/revalidation.service.ts +++ b/backend/src/common/revalidation/revalidation.service.ts @@ -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('/'), ]; diff --git a/backend/src/orders/orders.service.ts b/backend/src/orders/orders.service.ts index 755122a8..8b73efee 100644 --- a/backend/src/orders/orders.service.ts +++ b/backend/src/orders/orders.service.ts @@ -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'; diff --git a/backend/src/payment/payment.controller.ts b/backend/src/payment/payment.controller.ts index 9916f900..b7060482 100644 --- a/backend/src/payment/payment.controller.ts +++ b/backend/src/payment/payment.controller.ts @@ -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); } // ========================================== diff --git a/backend/src/payment/payment.service.ts b/backend/src/payment/payment.service.ts index c9570c17..c0b453df 100644 --- a/backend/src/payment/payment.service.ts +++ b/backend/src/payment/payment.service.ts @@ -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, + } + : {}), }; } diff --git a/backend/src/prescriptions/prescriptions.controller.ts b/backend/src/prescriptions/prescriptions.controller.ts index 4ce63836..17eb4ac6 100644 --- a/backend/src/prescriptions/prescriptions.controller.ts +++ b/backend/src/prescriptions/prescriptions.controller.ts @@ -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); } diff --git a/backend/src/products/products.service.ts b/backend/src/products/products.service.ts index c040c0b9..01c5f93c 100644 --- a/backend/src/products/products.service.ts +++ b/backend/src/products/products.service.ts @@ -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), ), ), diff --git a/backend/src/settings/settings.service.ts b/backend/src/settings/settings.service.ts index 6e473534..faefd406 100644 --- a/backend/src/settings/settings.service.ts +++ b/backend/src/settings/settings.service.ts @@ -100,9 +100,18 @@ export const CANONICAL_ALIASES: Record = { 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: [ diff --git a/backend/src/users/users.controller.ts b/backend/src/users/users.controller.ts index 5975a17a..82ebb923 100644 --- a/backend/src/users/users.controller.ts +++ b/backend/src/users/users.controller.ts @@ -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); } } diff --git a/backend/src/users/users.service.ts b/backend/src/users/users.service.ts index b567a8a2..716f6845 100644 --- a/backend/src/users/users.service.ts +++ b/backend/src/users/users.service.ts @@ -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: { diff --git a/backend/src/videos/videos.controller.ts b/backend/src/videos/videos.controller.ts index bb43d5fc..d4c1548f 100644 --- a/backend/src/videos/videos.controller.ts +++ b/backend/src/videos/videos.controller.ts @@ -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) { diff --git a/frontend/admin-panel/src/App.tsx b/frontend/admin-panel/src/App.tsx index f16bce87..ce908ab8 100644 --- a/frontend/admin-panel/src/App.tsx +++ b/frontend/admin-panel/src/App.tsx @@ -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 ( <> { + const renderStatusBadge = (status: string, isPublished: boolean, scheduledAt?: string | null) => { switch (status) { case 'PUBLISHED': return ( @@ -560,13 +565,18 @@ export default function Blogs() { منتشر شده ); - case 'SCHEDULED': + case 'SCHEDULED': { + const dateStr = scheduledAt ? new Date(scheduledAt).toLocaleDateString('fa-IR') : ''; return ( - + - زمان‌بندی شده + {dateStr ? `در صف: ${dateStr}` : 'زمان‌بندی شده'} ); + } case 'ARCHIVED': return ( @@ -764,7 +774,7 @@ export default function Blogs() { {(blog.viewCount || 0).toLocaleString('fa-IR')} بازدید - {renderStatusBadge(blog.status, blog.isPublished)} + {renderStatusBadge(blog.status, blog.isPublished, blog.scheduledAt)}
diff --git a/frontend/admin-panel/src/pages/Products.tsx b/frontend/admin-panel/src/pages/Products.tsx index abbb7f95..f3476dc2 100644 --- a/frontend/admin-panel/src/pages/Products.tsx +++ b/frontend/admin-panel/src/pages/Products.tsx @@ -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, diff --git a/frontend/application/app/blog/[slug]/page.tsx b/frontend/application/app/blog/[slug]/page.tsx index ee581e86..6053137c 100644 --- a/frontend/application/app/blog/[slug]/page.tsx +++ b/frontend/application/app/blog/[slug]/page.tsx @@ -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, + }, }; } diff --git a/frontend/application/app/blog/page.tsx b/frontend/application/app/blog/page.tsx index 168faeb2..c2aca49c 100644 --- a/frontend/application/app/blog/page.tsx +++ b/frontend/application/app/blog/page.tsx @@ -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 ; + return ( + + ); } diff --git a/frontend/application/components/AnalyticsDeferred.tsx b/frontend/application/components/AnalyticsDeferred.tsx index b3d67ac9..2f89cf8b 100644 --- a/frontend/application/components/AnalyticsDeferred.tsx +++ b/frontend/application/components/AnalyticsDeferred.tsx @@ -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 diff --git a/frontend/application/components/BlogPage.tsx b/frontend/application/components/BlogPage.tsx index dcf5c602..e6d512b6 100644 --- a/frontend/application/components/BlogPage.tsx +++ b/frontend/application/components/BlogPage.tsx @@ -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([]); - const [selectedCategory, setSelectedCategory] = useState("ALL"); + const [selectedCategory, setSelectedCategory] = useState(initialCategoryId); const [searchQuery, setSearchQuery] = useState(""); const [selectedTag, setSelectedTag] = useState(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 */}