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

+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 و داخلی مجاز نیستند.',
});
}