599 lines
17 KiB
TypeScript
599 lines
17 KiB
TypeScript
import {
|
|
BadRequestException,
|
|
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, OnModuleDestroy {
|
|
private readonly logger = new Logger(BlogsService.name);
|
|
private schedulerTimer: NodeJS.Timeout | null = null;
|
|
|
|
constructor(
|
|
private prisma: PrismaService,
|
|
private revalidationService: RevalidationService,
|
|
) {}
|
|
|
|
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() {
|
|
try {
|
|
const defaultCategories = [
|
|
{ name: "تغذیه و رژیم غذایی", slug: "nutrition", order: 1 },
|
|
{ name: "سلامت گوارش و متابولیسم", slug: "digestion", order: 2 },
|
|
{ name: "مفاصل، استخوان و اسکلت", slug: "joints-bones", order: 3 },
|
|
{ name: "پوست، مو و آلرژی", slug: "skin-coat", order: 4 },
|
|
{
|
|
name: "ایمنی، پیشگیری و مراقبت بالینی",
|
|
slug: "health-prevention",
|
|
order: 5,
|
|
},
|
|
];
|
|
|
|
for (const cat of defaultCategories) {
|
|
await this.prisma.blogCategory.upsert({
|
|
where: { slug: cat.slug },
|
|
update: { name: cat.name, order: cat.order },
|
|
create: { name: cat.name, slug: cat.slug, order: cat.order },
|
|
});
|
|
}
|
|
} catch (err) {
|
|
console.warn(
|
|
"[BlogsService] Failed to seed default blog categories:",
|
|
err,
|
|
);
|
|
}
|
|
}
|
|
|
|
async getBlogs(
|
|
query: PaginationDto & {
|
|
status?: string;
|
|
categoryId?: string;
|
|
tagId?: string;
|
|
},
|
|
) {
|
|
const page = Number(query.page) || 1;
|
|
const limit = Number(query.limit) || 10;
|
|
const skip = (page - 1) * limit;
|
|
|
|
const where: Prisma.BlogWhereInput = {};
|
|
|
|
if (query.search) {
|
|
where.OR = [
|
|
{ title: { contains: query.search, mode: "insensitive" } },
|
|
{ excerpt: { contains: query.search, mode: "insensitive" } },
|
|
{ slug: { contains: query.search, mode: "insensitive" } },
|
|
];
|
|
}
|
|
|
|
if (query.status) {
|
|
where.status = query.status;
|
|
}
|
|
|
|
if (query.categoryId) {
|
|
where.categoryId = query.categoryId;
|
|
}
|
|
|
|
const [data, total] = await Promise.all([
|
|
this.prisma.blog.findMany({
|
|
where,
|
|
skip,
|
|
take: limit,
|
|
orderBy: { createdAt: "desc" },
|
|
include: {
|
|
author: {
|
|
select: { id: true, firstName: true, lastName: true, email: true },
|
|
},
|
|
category: { select: { id: true, name: true, slug: true } },
|
|
tags: { select: { id: true, name: true, slug: true } },
|
|
_count: { select: { comments: true } },
|
|
},
|
|
}),
|
|
this.prisma.blog.count({ where }),
|
|
]);
|
|
|
|
return {
|
|
data,
|
|
meta: {
|
|
total,
|
|
page,
|
|
limit,
|
|
lastPage: Math.ceil(total / limit) || 1,
|
|
},
|
|
};
|
|
}
|
|
|
|
async getBlogById(id: string) {
|
|
const blog = await this.prisma.blog.findUnique({
|
|
where: { id },
|
|
include: {
|
|
author: { select: { id: true, firstName: true, lastName: true } },
|
|
category: true,
|
|
tags: true,
|
|
},
|
|
});
|
|
if (!blog) throw new NotFoundException("Blog not found");
|
|
return blog;
|
|
}
|
|
|
|
async createBlog(data: any, currentUserId: string) {
|
|
const {
|
|
tagNames,
|
|
categoryId,
|
|
authorId,
|
|
publishedAt,
|
|
scheduledAt,
|
|
readingTime,
|
|
markContentUpdated,
|
|
contentUpdatedAt,
|
|
} = data;
|
|
|
|
const parseOptionalDate = (value: unknown, field: string): Date | null => {
|
|
if (value === undefined || value === null || value === "") return null;
|
|
const parsed = new Date(value as string | number | Date);
|
|
if (!Number.isFinite(parsed.getTime())) {
|
|
throw new BadRequestException(`Invalid ${field}`);
|
|
}
|
|
return parsed;
|
|
};
|
|
|
|
const parsedPublishedAt = parseOptionalDate(publishedAt, "publishedAt");
|
|
const parsedScheduledAt = parseOptionalDate(scheduledAt, "scheduledAt");
|
|
const parsedContentUpdatedAt = markContentUpdated
|
|
? new Date()
|
|
: parseOptionalDate(contentUpdatedAt, "contentUpdatedAt");
|
|
|
|
// Connect or create tags
|
|
const tagConnectOrCreate = [];
|
|
if (Array.isArray(tagNames) && tagNames.length > 0) {
|
|
for (const tName of tagNames) {
|
|
const trimmed = String(tName).trim();
|
|
if (trimmed) {
|
|
const slug = trimmed
|
|
.toLowerCase()
|
|
.replace(/\s+/g, "-")
|
|
.replace(/[^\w\u0600-\u06FF-]+/g, "");
|
|
tagConnectOrCreate.push({
|
|
where: { name: trimmed },
|
|
create: { name: trimmed, slug: slug || `tag-${Date.now()}` },
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
const targetAuthorId = authorId || currentUserId;
|
|
const now = new Date();
|
|
const isFutureSchedule = parsedScheduledAt && parsedScheduledAt > now;
|
|
|
|
let finalStatus = data.status || "PUBLISHED";
|
|
let finalIsPublished =
|
|
data.isPublished !== undefined ? data.isPublished : true;
|
|
let finalPublishedAt = parsedPublishedAt;
|
|
|
|
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 = {
|
|
title: data.title,
|
|
slug: data.slug,
|
|
content: data.content,
|
|
excerpt: data.excerpt,
|
|
authorTeam: data.authorTeam,
|
|
authorRole: data.authorRole,
|
|
imageUrl: data.imageUrl,
|
|
imageAlt: data.imageAlt,
|
|
imageCaption: data.imageCaption,
|
|
metaTitle: data.metaTitle,
|
|
metaDescription: data.metaDescription,
|
|
keywords: data.keywords,
|
|
focusKeywords: data.focusKeywords,
|
|
canonicalUrl: data.canonicalUrl,
|
|
noIndex: data.noIndex,
|
|
noFollow: data.noFollow,
|
|
schemaType: data.schemaType,
|
|
ogTitle: data.ogTitle,
|
|
ogDescription: data.ogDescription,
|
|
ogImage: data.ogImage,
|
|
status: finalStatus,
|
|
isPublished: finalIsPublished,
|
|
featured: data.featured,
|
|
allowComments: data.allowComments,
|
|
showOnHome: data.showOnHome,
|
|
homeDisplayMode: data.homeDisplayMode,
|
|
relatedProductIds: data.relatedProductIds,
|
|
relatedBlogIds: data.relatedBlogIds,
|
|
readingTime: readingTime !== undefined ? Number(readingTime) : 3,
|
|
publishedAt: finalPublishedAt,
|
|
scheduledAt: parsedScheduledAt,
|
|
contentUpdatedAt: parsedContentUpdatedAt,
|
|
author: { connect: { id: targetAuthorId } },
|
|
...(categoryId ? { category: { connect: { id: categoryId } } } : {}),
|
|
...(tagConnectOrCreate.length > 0
|
|
? { tags: { connectOrCreate: tagConnectOrCreate } }
|
|
: {}),
|
|
} satisfies Prisma.BlogCreateInput;
|
|
|
|
const created = await this.prisma.blog.create({
|
|
data: createPayload,
|
|
include: {
|
|
author: { select: { firstName: true, lastName: true } },
|
|
category: true,
|
|
tags: true,
|
|
},
|
|
});
|
|
|
|
await this.revalidationService.revalidateBlog(created.slug);
|
|
return created;
|
|
}
|
|
|
|
async updateBlog(id: string, data: any) {
|
|
const blog = await this.prisma.blog.findUnique({ where: { id } });
|
|
if (!blog) throw new NotFoundException("Blog not found");
|
|
|
|
const {
|
|
tagNames,
|
|
categoryId,
|
|
authorId,
|
|
publishedAt,
|
|
scheduledAt,
|
|
readingTime,
|
|
markContentUpdated,
|
|
contentUpdatedAt,
|
|
} = data;
|
|
|
|
const mutableScalarFields = [
|
|
"title",
|
|
"slug",
|
|
"content",
|
|
"excerpt",
|
|
"authorTeam",
|
|
"authorRole",
|
|
"imageUrl",
|
|
"imageAlt",
|
|
"imageCaption",
|
|
"metaTitle",
|
|
"metaDescription",
|
|
"keywords",
|
|
"focusKeywords",
|
|
"canonicalUrl",
|
|
"noIndex",
|
|
"noFollow",
|
|
"schemaType",
|
|
"ogTitle",
|
|
"ogDescription",
|
|
"ogImage",
|
|
"status",
|
|
"isPublished",
|
|
"featured",
|
|
"allowComments",
|
|
"showOnHome",
|
|
"homeDisplayMode",
|
|
"relatedProductIds",
|
|
"relatedBlogIds",
|
|
] as const;
|
|
const updatePayload: Prisma.BlogUpdateInput = {};
|
|
for (const field of mutableScalarFields) {
|
|
if (data[field] !== undefined) {
|
|
(updatePayload as Record<string, unknown>)[field] = data[field];
|
|
}
|
|
}
|
|
|
|
const now = new Date();
|
|
const materialContentFields = [
|
|
"title",
|
|
"content",
|
|
"excerpt",
|
|
"imageUrl",
|
|
"imageAlt",
|
|
"imageCaption",
|
|
] as const;
|
|
const hasMaterialContentChange = materialContentFields.some(
|
|
(field) => data[field] !== undefined && data[field] !== blog[field],
|
|
);
|
|
if (markContentUpdated || (contentUpdatedAt === undefined && hasMaterialContentChange)) {
|
|
(updatePayload as Record<string, unknown>).contentUpdatedAt = now;
|
|
} else if (contentUpdatedAt !== undefined) {
|
|
if (contentUpdatedAt === null || contentUpdatedAt === "") {
|
|
(updatePayload as Record<string, unknown>).contentUpdatedAt = null;
|
|
} else {
|
|
const parsedContentUpdatedAt = new Date(contentUpdatedAt);
|
|
if (!Number.isFinite(parsedContentUpdatedAt.getTime())) {
|
|
throw new BadRequestException("Invalid contentUpdatedAt");
|
|
}
|
|
(updatePayload as Record<string, unknown>).contentUpdatedAt = parsedContentUpdatedAt;
|
|
}
|
|
}
|
|
|
|
Object.assign(updatePayload, {
|
|
...(readingTime !== undefined
|
|
? { readingTime: Number(readingTime) }
|
|
: {}),
|
|
...(readingTime !== undefined
|
|
? { readingTime: Number(readingTime) }
|
|
: {}),
|
|
...(authorId ? { author: { connect: { id: authorId } } } : {}),
|
|
...(categoryId !== undefined
|
|
? categoryId
|
|
? { category: { connect: { id: categoryId } } }
|
|
: { category: { disconnect: true } }
|
|
: {}),
|
|
});
|
|
|
|
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;
|
|
}
|
|
} else if (publishedAt !== undefined) {
|
|
updatePayload.publishedAt = publishedAt ? new Date(publishedAt) : null;
|
|
}
|
|
|
|
if (Array.isArray(tagNames)) {
|
|
const tagConnectOrCreate = [];
|
|
for (const tName of tagNames) {
|
|
const trimmed = String(tName).trim();
|
|
if (trimmed) {
|
|
const slug = trimmed
|
|
.toLowerCase()
|
|
.replace(/\s+/g, "-")
|
|
.replace(/[^\w\u0600-\u06FF-]+/g, "");
|
|
tagConnectOrCreate.push({
|
|
where: { name: trimmed },
|
|
create: { name: trimmed, slug: slug || `tag-${Date.now()}` },
|
|
});
|
|
}
|
|
}
|
|
updatePayload.tags = {
|
|
set: [], // clear previous relations
|
|
connectOrCreate: tagConnectOrCreate,
|
|
};
|
|
}
|
|
|
|
const updated = await this.prisma.blog.update({
|
|
where: { id },
|
|
data: updatePayload,
|
|
include: {
|
|
author: { select: { firstName: true, lastName: true } },
|
|
category: true,
|
|
tags: true,
|
|
},
|
|
});
|
|
|
|
await this.revalidationService.revalidateBlog(updated.slug);
|
|
return updated;
|
|
}
|
|
|
|
async deleteBlog(id: string) {
|
|
const blog = await this.prisma.blog.findUnique({ where: { id } });
|
|
if (!blog) throw new NotFoundException("Blog not found");
|
|
const res = await this.prisma.blog.delete({ where: { id } });
|
|
await this.revalidationService.revalidateBlog(blog.slug);
|
|
return res;
|
|
}
|
|
|
|
// Authors (Users who can write)
|
|
async getAuthors() {
|
|
return this.prisma.user.findMany({
|
|
select: {
|
|
id: true,
|
|
firstName: true,
|
|
lastName: true,
|
|
email: true,
|
|
role: true,
|
|
},
|
|
orderBy: { firstName: "asc" },
|
|
});
|
|
}
|
|
|
|
// Blog Categories Management
|
|
async getBlogCategories() {
|
|
return this.prisma.blogCategory.findMany({
|
|
orderBy: { order: "asc" },
|
|
include: {
|
|
parent: true,
|
|
children: true,
|
|
_count: { select: { blogs: true } },
|
|
},
|
|
});
|
|
}
|
|
|
|
async createBlogCategory(data: Prisma.BlogCategoryCreateInput) {
|
|
return this.prisma.blogCategory.create({ data });
|
|
}
|
|
|
|
async updateBlogCategory(id: string, data: Prisma.BlogCategoryUpdateInput) {
|
|
return this.prisma.blogCategory.update({ where: { id }, data });
|
|
}
|
|
|
|
async deleteBlogCategory(id: string) {
|
|
return this.prisma.blogCategory.delete({ where: { id } });
|
|
}
|
|
|
|
// Blog Tags Management
|
|
async getBlogTags() {
|
|
return this.prisma.blogTag.findMany({
|
|
orderBy: { createdAt: "desc" },
|
|
include: {
|
|
_count: { select: { blogs: true } },
|
|
},
|
|
});
|
|
}
|
|
|
|
async createBlogTag(data: { name: string; slug?: string }) {
|
|
const slug =
|
|
data.slug ||
|
|
data.name
|
|
.toLowerCase()
|
|
.replace(/\s+/g, "-")
|
|
.replace(/[^\w\u0600-\u06FF-]+/g, "");
|
|
return this.prisma.blogTag.create({
|
|
data: { name: data.name, slug: slug || `tag-${Date.now()}` },
|
|
});
|
|
}
|
|
|
|
async deleteBlogTag(id: string) {
|
|
return this.prisma.blogTag.delete({ where: { id } });
|
|
}
|
|
|
|
// Blog Comments Management
|
|
async getComments(query: {
|
|
page?: number;
|
|
limit?: number;
|
|
status?: string;
|
|
blogId?: string;
|
|
}) {
|
|
const page = Number(query.page) || 1;
|
|
const limit = Number(query.limit) || 20;
|
|
const skip = (page - 1) * limit;
|
|
|
|
const where: Prisma.BlogCommentWhereInput = {};
|
|
if (query.status) where.status = query.status;
|
|
if (query.blogId) where.blogId = query.blogId;
|
|
|
|
const [data, total] = await Promise.all([
|
|
this.prisma.blogComment.findMany({
|
|
where,
|
|
skip,
|
|
take: limit,
|
|
orderBy: { createdAt: "desc" },
|
|
include: {
|
|
blog: { select: { title: true, slug: true } },
|
|
user: { select: { firstName: true, lastName: true, mobile: true } },
|
|
},
|
|
}),
|
|
this.prisma.blogComment.count({ where }),
|
|
]);
|
|
|
|
return {
|
|
data,
|
|
meta: { total, page, limit, lastPage: Math.ceil(total / limit) || 1 },
|
|
};
|
|
}
|
|
|
|
async updateCommentStatus(id: string, status: "APPROVED" | "REJECTED") {
|
|
const comment = await this.prisma.blogComment.findUnique({
|
|
where: { id },
|
|
include: { blog: { select: { slug: true } } },
|
|
});
|
|
if (!comment) throw new NotFoundException("Comment not found");
|
|
const updated = await this.prisma.blogComment.update({
|
|
where: { id },
|
|
data: { status },
|
|
});
|
|
if (comment.blog?.slug) {
|
|
await this.revalidationService.revalidateBlog(comment.blog.slug);
|
|
}
|
|
return updated;
|
|
}
|
|
|
|
async deleteComment(id: string) {
|
|
const comment = await this.prisma.blogComment.findUnique({
|
|
where: { id },
|
|
include: { blog: { select: { slug: true } } },
|
|
});
|
|
if (!comment) throw new NotFoundException("Comment not found");
|
|
const res = await this.prisma.blogComment.delete({ where: { id } });
|
|
if (comment.blog?.slug) {
|
|
await this.revalidationService.revalidateBlog(comment.blog.slug);
|
|
}
|
|
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,
|
|
},
|
|
});
|
|
|
|
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;
|
|
}
|
|
}
|