feat(blog): add material freshness and authorship

This commit is contained in:
devops committed 2026-10-20 05:36:03 +00:00
1 parent 3f5258a76c
commit 51ca8c7e34
24 files changed
+187 -52

No files matched your search

@@ -0,0 +1,3 @@
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_team VARCHAR(200);
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_role VARCHAR(200);
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS content_updated_at TIMESTAMPTZ;
+3
View File
@@ -179,6 +179,8 @@ model Blog {
content String @db.Text
excerpt String? @db.Text
authorId String? @map("author_id") @db.Uuid
authorTeam String? @map("author_team") @db.VarChar(200)
authorRole String? @map("author_role") @db.VarChar(200)
categoryId String? @map("category_id") @db.Uuid
imageUrl String? @map("image_url") @db.Text
imageAlt String? @map("image_alt") @db.VarChar(255)
@@ -198,6 +200,7 @@ model Blog {
isPublished Boolean @default(true) @map("is_published")
publishedAt DateTime? @map("published_at") @db.Timestamptz()
scheduledAt DateTime? @map("scheduled_at") @db.Timestamptz()
contentUpdatedAt DateTime? @map("content_updated_at") @db.Timestamptz()
readingTime Int @default(3) @map("reading_time")
featured Boolean @default(false)
allowComments Boolean @default(true) @map("allow_comments")
+25 -1
View File
@@ -274,6 +274,31 @@ describe("Admin BlogsService", () => {
});
});
describe("material freshness and scheduled publishing", () => {
it("sets contentUpdatedAt intentionally and never rewrites createdAt", async () => {
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", createdAt: new Date("2025-01-01") });
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
await service.updateBlog("b1", { title: "Material edit", markContentUpdated: true });
const payload = mockPrisma.blog.update.mock.calls[0][0].data;
expect(payload.contentUpdatedAt).toEqual(expect.any(Date));
expect(payload).not.toHaveProperty("markContentUpdated");
expect(payload).not.toHaveProperty("createdAt");
});
it("allows explicitly clearing contentUpdatedAt", async () => {
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post" });
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
await service.updateBlog("b1", { contentUpdatedAt: null });
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toBeNull();
});
it("publishes due posts without rewriting createdAt", async () => {
const scheduledAt = new Date("2025-02-01T10:00:00Z");
mockPrisma.blog.findMany.mockResolvedValue([{ id: "b1", slug: "post", title: "Post", scheduledAt }]);
mockPrisma.blog.update.mockResolvedValue({});
await service.publishDueScheduledBlogs();
expect(mockPrisma.blog.update).toHaveBeenCalledWith({ where: { id: "b1" }, data: { status: "PUBLISHED", isPublished: true, publishedAt: scheduledAt } });
});
});
describe("deleteBlog", () => {
it("should throw NotFoundException if blog not found", async () => {
mockPrisma.blog.findUnique.mockResolvedValue(null);
@@ -468,7 +493,6 @@ describe("Admin BlogsService", () => {
status: "PUBLISHED",
isPublished: true,
publishedAt: scheduledDate,
createdAt: scheduledDate,
},
});
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
+10 -2
View File
@@ -148,6 +148,8 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
publishedAt,
scheduledAt,
readingTime,
markContentUpdated,
contentUpdatedAt,
...rest
} = data;
@@ -198,6 +200,7 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
readingTime: readingTime ? Number(readingTime) : 3,
publishedAt: finalPublishedAt,
scheduledAt: parsedScheduledAt,
contentUpdatedAt: markContentUpdated ? now : contentUpdatedAt ? new Date(contentUpdatedAt) : null,
author: { connect: { id: targetAuthorId } },
...(categoryId ? { category: { connect: { id: categoryId } } } : {}),
...(tagConnectOrCreate.length > 0
@@ -230,12 +233,19 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
publishedAt,
scheduledAt,
readingTime,
markContentUpdated,
contentUpdatedAt,
...rest
} = data;
const now = new Date();
const updatePayload: Prisma.BlogUpdateInput = {
...rest,
...(markContentUpdated
? { contentUpdatedAt: now }
: contentUpdatedAt !== undefined
? { contentUpdatedAt: contentUpdatedAt ? new Date(contentUpdatedAt) : null }
: {}),
...(readingTime !== undefined
? { readingTime: Number(readingTime) }
: {}),
@@ -259,7 +269,6 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
updatePayload.status = "PUBLISHED";
updatePayload.isPublished = true;
updatePayload.publishedAt = parsedScheduledAt;
updatePayload.createdAt = parsedScheduledAt;
}
} else if (publishedAt !== undefined) {
updatePayload.publishedAt = publishedAt ? new Date(publishedAt) : null;
@@ -472,7 +481,6 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
status: "PUBLISHED",
isPublished: true,
publishedAt: publishDate,
createdAt: publishDate,
},
});
+19 -1
View File
@@ -50,7 +50,7 @@ describe("BlogsService", () => {
expect(result.data).toEqual(blogs);
expect(result.meta.total).toBe(1);
const query = mockPrisma.blog.findMany.mock.calls[0][0];
expect(query.include.author).toBeUndefined();
expect(query.include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
});
it("should filter by categorySlug and search term", async () => {
@@ -69,7 +69,19 @@ describe("BlogsService", () => {
});
});
it("selects the minimal public author identity for list results", async () => {
mockPrisma.blog.findMany.mockResolvedValue([]); mockPrisma.blog.count.mockResolvedValue(0);
await service.findAll({});
expect(mockPrisma.blog.findMany.mock.calls[0][0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
});
describe("findHomepage", () => {
it("selects the minimal public author identity for homepage results", async () => {
mockPrisma.blog.findMany.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
await service.findHomepage();
for (const call of mockPrisma.blog.findMany.mock.calls.slice(0, 2)) expect(call[0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
});
it("should return selected blogs if showOnHome posts exist", async () => {
const selected = [{ id: "b1", title: "Hero Blog", showOnHome: true }];
mockPrisma.blog.findMany.mockResolvedValueOnce(selected);
@@ -92,6 +104,12 @@ describe("BlogsService", () => {
});
describe("findOneBySlug", () => {
it("selects the minimal public author identity for detail results", async () => {
mockPrisma.blog.findFirst.mockResolvedValue(null);
await expect(service.findOneBySlug("missing")).rejects.toThrow(NotFoundException);
expect(mockPrisma.blog.findFirst.mock.calls[0][0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
});
it("should throw NotFoundException if slug is empty or blog not found", async () => {
mockPrisma.blog.findFirst.mockResolvedValue(null);
await expect(service.findOneBySlug("unknown-slug")).rejects.toThrow(
+10
View File
@@ -68,6 +68,9 @@ export class BlogsService {
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
},
include: {
author: {
select: { id: true, firstName: true, lastName: true },
},
category: {
select: { id: true, name: true, slug: true },
},
@@ -107,6 +110,9 @@ export class BlogsService {
take: 4,
orderBy: { publishedAt: "desc" },
include: {
author: {
select: { id: true, firstName: true, lastName: true },
},
category: { select: { id: true, name: true, slug: true } },
tags: { select: { id: true, name: true, slug: true } },
_count: { select: { comments: { where: { status: "APPROVED" } } } },
@@ -123,6 +129,9 @@ export class BlogsService {
take: 4,
orderBy: { publishedAt: "desc" },
include: {
author: {
select: { id: true, firstName: true, lastName: true },
},
category: { select: { id: true, name: true, slug: true } },
tags: { select: { id: true, name: true, slug: true } },
_count: { select: { comments: { where: { status: "APPROVED" } } } },
@@ -158,6 +167,7 @@ export class BlogsService {
],
},
include: {
author: { select: { id: true, firstName: true, lastName: true } },
category: {
select: { id: true, name: true, slug: true },
},
@@ -251,6 +251,10 @@ describe("Blogs Page Component", () => {
});
});
it("submits authorship fields and intentional material update control", async () => {
renderComponent(); await screen.findByText("راهنمای جامع نگهداری سگ پامرانین"); fireEvent.click(screen.getAllByTitle("ویرایش مقاله")[0]); fireEvent.change(screen.getByLabelText("تیم نویسندگی"),{target:{value:"Science"}}); fireEvent.change(screen.getByLabelText("نقش نویسنده"),{target:{value:"Vet"}}); fireEvent.click(screen.getByText("۳. زمان‌بندی و انتشار")); fireEvent.click(screen.getByLabelText("ثبت به‌روزرسانی محتوایی مهم")); fireEvent.click(screen.getByTestId("blog-save-btn")); await waitFor(()=>expect(api.put).toHaveBeenCalledWith("/admin/blogs/blog-1",expect.objectContaining({authorTeam:"Science",authorRole:"Vet",markContentUpdated:true})));
});
it("shows delete confirmation and deletes blog article", async () => {
vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } });
+19
View File
@@ -70,6 +70,9 @@ export interface BlogPost {
content: string;
excerpt?: string;
authorId?: string;
authorTeam?: string;
authorRole?: string;
contentUpdatedAt?: string | null;
author?: {
id?: string;
firstName?: string;
@@ -168,6 +171,9 @@ export default function Blogs() {
content: '',
excerpt: '',
authorId: '',
authorTeam: '',
authorRole: '',
markContentUpdated: false,
categoryId: '',
tagNames: [] as string[],
imageUrl: '',
@@ -245,6 +251,9 @@ export default function Blogs() {
content: blog.content || '',
excerpt: blog.excerpt || '',
authorId: blog.authorId || (blog.author?.id || ''),
authorTeam: blog.authorTeam || '',
authorRole: blog.authorRole || '',
markContentUpdated: false,
categoryId: blog.categoryId || '',
tagNames: blog.tags ? blog.tags.map((t) => t.name) : [],
imageUrl: blog.imageUrl || '',
@@ -281,6 +290,9 @@ export default function Blogs() {
content: '',
excerpt: '',
authorId: authors[0]?.id || '',
authorTeam: '',
authorRole: '',
markContentUpdated: false,
categoryId: '',
tagNames: [],
imageUrl: '',
@@ -1003,6 +1015,11 @@ export default function Blogs() {
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div><label htmlFor="author-team" className="text-xs font-bold text-gray-700">تیم نویسندگی</label><input id="author-team" value={formData.authorTeam} onChange={(e)=>setFormData({...formData,authorTeam:e.target.value})} className="w-full px-3 py-2.5 rounded-2xl border border-gray-200 text-xs" /></div>
<div><label htmlFor="author-role" className="text-xs font-bold text-gray-700">نقش نویسنده</label><input id="author-role" value={formData.authorRole} onChange={(e)=>setFormData({...formData,authorRole:e.target.value})} className="w-full px-3 py-2.5 rounded-2xl border border-gray-200 text-xs" /></div>
</div>
{/* Chips Tag Input */}
<div className="space-y-2 p-3.5 bg-gray-50/70 border border-gray-200 rounded-2xl">
<label className="text-xs font-bold text-gray-700 block">برچسب‌ها و تگ‌های مقاله (Tag Input)</label>
@@ -1161,6 +1178,8 @@ export default function Blogs() {
</div>
</div>
<label className="flex items-center gap-3 p-4 border border-blue-200 rounded-2xl bg-blue-50 cursor-pointer"><input type="checkbox" aria-label="ثبت به‌روزرسانی محتوایی مهم" checked={formData.markContentUpdated} onChange={(e)=>setFormData({...formData,markContentUpdated:e.target.checked})}/><span className="text-xs font-black">ثبت به‌روزرسانی محتوایی مهم</span></label>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
<label className="flex items-center gap-3 p-4 border border-gray-200 rounded-2xl bg-white hover:bg-gray-50 transition-colors cursor-pointer">
<input
@@ -74,6 +74,11 @@ describe('BlogPostPage FAQPage Schema injection (SEO-P1-07)', () => {
expect(faqJson.mainEntity[0].name).toBe('آیا این مکمل برای سگ مسن مناسب است؟');
});
it('omits dateModified for invalid technical updates and uses matching Organization fallback author', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ok:true,json:async()=>({slug:'fresh',title:'Fresh',content:'<p>x</p>',publishedAt:'2026-01-01T01:00:00Z',contentUpdatedAt:'2026-01-01T12:00:00Z'})}));
const jsx=await BlogPostPage({params:Promise.resolve({slug:'fresh'})}); const script:any=React.Children.toArray(jsx.props.children)[0]; const json=JSON.parse(script.props.dangerouslySetInnerHTML.__html); expect(json.dateModified).toBeUndefined(); expect(json.author['@type']).toBe('Organization'); expect(json.author.name).toBe('تیم پژوهش و محتوای علمی کنینا');
});
it('does not inject FAQPage schema when article does not have FAQs', async () => {
const blogData = {
slug: 'nutrition',
@@ -1,3 +1,4 @@
import { BLOG_TEAM_FALLBACK, validContentUpdatedAt } from "../../../lib/blogDates";
import React from "react";
import { notFound } from 'next/navigation';
import type { Metadata } from 'next';
@@ -95,7 +96,7 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
: 'نویسنده و پژوهشگر کنینا';
const publishedTime = safeIso(blog.publishedAt) || safeIso(blog.createdAt);
const modifiedTime = safeIso(blog.updatedAt) || publishedTime;
const modifiedTime = safeIso(validContentUpdatedAt(blog));
const keywordsList = blog.focusKeywords
? blog.focusKeywords.split(',').map((k: string) => k.trim())
@@ -147,7 +148,7 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
siteName: config.brandNameFa,
type: "article",
publishedTime,
modifiedTime,
...(modifiedTime ? { modifiedTime } : {}),
authors: [authorName],
tags: blog.tags?.map((t: any) => typeof t === 'string' ? t : t?.name).filter(Boolean) || [],
},
@@ -182,7 +183,7 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
: `${siteUrl}/blog/${slug}`;
const publishedIso = safeIso(blog.publishedAt) || safeIso(blog.createdAt) || new Date().toISOString();
const modifiedIso = safeIso(blog.updatedAt) || publishedIso;
const modifiedIso = safeIso(validContentUpdatedAt(blog));
const sanitizedContent = sanitizeBlogHtml(blog.content);
const schemaType = blog.schemaType || 'BlogPosting';
@@ -191,11 +192,10 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
? {
'@type': 'Person',
name: authorName,
url: `${siteUrl}/about`,
}
: {
'@type': 'Organization',
name: config.brandNameFa || 'کنینا ایران',
name: blog.authorTeam || BLOG_TEAM_FALLBACK,
url: siteUrl,
};
@@ -212,7 +212,7 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
? [blog.imageUrl.startsWith('http') ? blog.imageUrl : `${siteUrl}${blog.imageUrl.startsWith('/') ? '' : '/'}${blog.imageUrl}`]
: [config.ogImageUrl.startsWith('http') ? config.ogImageUrl : `${siteUrl}${config.ogImageUrl.startsWith('/') ? '' : '/'}${config.ogImageUrl}`],
datePublished: publishedIso,
dateModified: modifiedIso,
...(modifiedIso ? { dateModified: modifiedIso } : {}),
author: authorSchema,
publisher: {
'@type': 'Organization',
+5
View File
@@ -53,6 +53,11 @@ async function getBlogs() {
category: b.category?.name || 'دانشنامه و سلامت',
categoryId: b.categoryId || undefined,
tags: b.tags || [],
publishedAt: b.publishedAt,
createdAt: b.createdAt,
contentUpdatedAt: b.contentUpdatedAt,
authorTeam: b.authorTeam,
authorRole: b.authorRole,
date: b.publishedAt
? new Date(String(b.publishedAt)).toLocaleDateString('fa-IR')
: b.createdAt
@@ -0,0 +1,4 @@
import { afterEach,describe,expect,it,vi } from "vitest";
import { GET } from "./route";
afterEach(()=>{vi.unstubAllGlobals();vi.unstubAllEnvs()});
describe("blog RSS dates",()=>{it("keeps pubDate immutable and derives lastBuildDate from real valid dates",async()=>{vi.stubEnv("NEXT_PUBLIC_SITE_URL","https://canina.ir");vi.stubGlobal("fetch",vi.fn().mockResolvedValue({ok:true,json:async()=>({data:[{slug:"a",title:"A",status:"PUBLISHED",publishedAt:"2026-01-01T00:00:00Z",contentUpdatedAt:"2026-01-03T00:00:00Z",updatedAt:"2026-01-04T00:00:00Z"}]})}));const xml=await (await GET()).text();expect(xml).toContain(`<pubDate>${new Date("2026-01-01T00:00:00Z").toUTCString()}</pubDate>`);expect(xml).toContain(`<lastBuildDate>${new Date("2026-01-03T00:00:00Z").toUTCString()}</lastBuildDate>`);});});
@@ -1,3 +1,4 @@
import { validContentUpdatedAt, publicationDate } from '../../../lib/blogDates';
import { NextResponse } from 'next/server';
export const dynamic = 'force-dynamic';
@@ -23,7 +24,7 @@ export async function GET() {
const title = escapeXml(b.title || '');
const link = `${baseUrl}/blog/${b.slug}`;
const description = escapeXml(b.excerpt || b.metaDescription || '');
const pubDate = b.publishedAt ? new Date(b.publishedAt).toUTCString() : b.createdAt ? new Date(b.createdAt).toUTCString() : new Date().toUTCString();
const pubDate = new Date(publicationDate(b)!).toUTCString();
const author = escapeXml(b.author ? `${b.author.firstName || ''} ${b.author.lastName || ''}`.trim() : 'کنینا فارما');
const category = escapeXml(b.category?.name || 'دانشنامه سلامت حیوانات');
@@ -41,6 +42,8 @@ export async function GET() {
})
.join('');
const realDates = blogs.map((b) => validContentUpdatedAt(b) || publicationDate(b)).filter((d): d is string => Boolean(d)).map((d) => new Date(d).getTime());
const lastBuildDate = realDates.length ? new Date(Math.max(...realDates)).toUTCString() : undefined;
const rssFeed = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
@@ -48,7 +51,7 @@ export async function GET() {
<link>${baseUrl}/blog</link>
<description>جدیدترین مقالات علمی در زمینه مکمل‌های تخصصی، تغذیه و سلامت سگ و گربه از داروسازی کنینا آلمان</description>
<language>fa-ir</language>
<lastBuildDate>${new Date().toUTCString()}</lastBuildDate>
${lastBuildDate ? `<lastBuildDate>${lastBuildDate}</lastBuildDate>` : ""}
<atom:link href="${baseUrl}/blog/rss.xml" rel="self" type="application/rss+xml"/>
${itemsXml}
</channel>
@@ -1,3 +1,4 @@
import { validContentUpdatedAt, publicationDate } from '../../lib/blogDates';
import { NextResponse } from 'next/server';
export const dynamic = 'force-dynamic';
@@ -7,7 +8,8 @@ type SitemapBlog = {
slug: string;
noIndex?: boolean;
status: string;
updatedAt?: string;
publishedAt?: string;
contentUpdatedAt?: string;
createdAt?: string;
featured?: boolean;
title?: string;
@@ -47,11 +49,7 @@ export async function GET() {
const urlsXml = blogRoutes
.map((blog) => {
const loc = `${baseUrl}/blog/${encodeURIComponent(blog.slug)}`;
const lastmod = blog.updatedAt
? new Date(blog.updatedAt).toISOString()
: blog.createdAt
? new Date(blog.createdAt).toISOString()
: new Date().toISOString();
const lastmod = new Date(validContentUpdatedAt(blog) || publicationDate(blog)!).toISOString();
const priority = blog.featured ? '0.9' : '0.7';
const primaryImg = blog.ogImage || blog.imageUrl;
const title = blog.title || 'مقاله وبلاگ تخصصی کنینا';
+2 -2
View File
@@ -16,7 +16,7 @@ describe('sitemap blog retrieval', () => {
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://stage.canina.ir');
const fetchMock = vi.fn()
.mockResolvedValueOnce({ ok: true, json: async () => ({ data: [
{ slug: 'first', status: 'PUBLISHED', updatedAt: '2026-10-01', featured: true },
{ slug: 'first', status: 'PUBLISHED', publishedAt: '2026-10-01', contentUpdatedAt: '2026-10-02', updatedAt: '2026-10-03', featured: true },
{ slug: 'hidden', status: 'PUBLISHED', noIndex: true },
{ slug: 'draft', status: 'DRAFT' },
], meta: { lastPage: 2 } }) })
@@ -32,7 +32,7 @@ describe('sitemap blog retrieval', () => {
const blogs = routes.filter(r => r.url.includes('/blog/'));
expect(blogs.map(r => r.url)).toEqual(['https://stage.canina.ir/blog/first', 'https://stage.canina.ir/blog/last']);
expect(blogs[0].priority).toBe(0.9);
expect(blogs[0].lastModified).toEqual(new Date('2026-10-01'));
expect(blogs[0].lastModified).toEqual(new Date('2026-10-02'));
});
it('terminates on an empty page even when pagination metadata is stale', async () => {
+3 -2
View File
@@ -1,4 +1,5 @@
import { MetadataRoute } from 'next';
import { validContentUpdatedAt, publicationDate } from '../lib/blogDates';
import { productService } from '../lib/services/productService';
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
@@ -86,7 +87,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const apiUrl = process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api';
const normalizedApiUrl = apiUrl.replace(/\/$/, '');
const apiBase = normalizedApiUrl.endsWith('/api') ? normalizedApiUrl : `${normalizedApiUrl}/api`;
type SitemapBlog = { slug: string; noIndex?: boolean; status: string; updatedAt?: string; featured?: boolean };
type SitemapBlog = { slug:string; noIndex?:boolean; status:string; publishedAt?:string; createdAt?:string; contentUpdatedAt?:string; featured?:boolean };
// The public list includes article bodies. Keep requests small and bypass
// Next's 2MB per-entry data cache, even for an unusually large article.
let page = 1;
@@ -101,7 +102,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
.filter((b) => !b.noIndex && b.status === 'PUBLISHED')
.map((b): MetadataRoute.Sitemap[number] => ({
url: `${baseUrl}/blog/${b.slug}`,
lastModified: b.updatedAt ? new Date(b.updatedAt) : new Date(),
lastModified: new Date(validContentUpdatedAt(b) || publicationDate(b)!),
changeFrequency: 'weekly',
priority: b.featured ? 0.9 : 0.7,
})));
+4 -1
View File
@@ -36,7 +36,9 @@ describe('Sub-sitemaps and robots.ts integration (SEO-P1-10)', () => {
slug: 'puppy-nutrition',
title: 'تغذیه توله سگ',
status: 'PUBLISHED',
updatedAt: '2026-10-10T12:00:00.000Z',
updatedAt: '2026-10-12T12:00:00.000Z',
publishedAt: '2026-10-10T12:00:00.000Z',
contentUpdatedAt: '2026-10-11T12:00:00.000Z',
featured: true,
imageUrl: '/uploads/puppy.jpg',
},
@@ -57,6 +59,7 @@ describe('Sub-sitemaps and robots.ts integration (SEO-P1-10)', () => {
expect(xml).toContain('<loc>https://canina.ir/blog/puppy-nutrition</loc>');
expect(xml).toContain('<priority>0.9</priority>');
expect(xml).toContain('<lastmod>2026-10-11T12:00:00.000Z</lastmod>');
expect(xml).toContain('<image:loc>https://canina.ir/uploads/puppy.jpg</image:loc>');
expect(xml).toContain('تغذیه توله سگ');
expect(xml).not.toContain('hidden-blog');
+14 -11
View File
@@ -26,6 +26,7 @@ import { productService } from "../lib/services/productService";
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import SafeImage from './SafeImage';
import { BLOG_TEAM_FALLBACK, publicationDate, validContentUpdatedAt, persianDate } from '../lib/blogDates';
export interface BlogCategory {
id: string;
@@ -42,6 +43,11 @@ export interface BlogPostItem {
imageAlt?: string;
date: string;
author: string;
authorTeam?: string;
authorRole?: string;
publishedAt?: string;
createdAt?: string;
contentUpdatedAt?: string;
content: string;
category?: string;
categoryId?: string;
@@ -324,10 +330,8 @@ export default function BlogPage({
<div className="bg-canina-blue/10 px-3.5 py-1 rounded-full uppercase tracking-wider">
{featuredPost.category || "پژوهش بالینی"}
</div>
<div className="flex items-center gap-1 text-medical-gray-400">
<Calendar className="w-3.5 h-3.5" />
{featuredPost.date}
</div>
<div className="flex items-center gap-1 text-medical-gray-400"><Calendar className="w-3.5 h-3.5" />تاریخ انتشار: <time dateTime={publicationDate(featuredPost)}>{persianDate(publicationDate(featuredPost))}</time></div>
{validContentUpdatedAt(featuredPost) && <div className="text-medical-gray-400">آخرین به‌روزرسانی: <time dateTime={validContentUpdatedAt(featuredPost)}>{persianDate(validContentUpdatedAt(featuredPost))}</time></div>}
<div className="flex items-center gap-1 text-medical-gray-400">
<Clock className="w-3.5 h-3.5" />
{featuredPost.readingTime || 4} دقیقه مطالعه
@@ -349,8 +353,9 @@ export default function BlogPage({
<User className="w-5 h-5" />
</div>
<div className="text-xs">
<div className="font-black text-medical-gray-900">{featuredPost.author}</div>
<div className="font-bold text-medical-gray-400">تیم پژوهش کنینا</div>
<div className="font-black text-medical-gray-900">نویسنده: {featuredPost.author}</div>
<div className="font-bold text-medical-gray-400">تیم: {featuredPost.authorTeam || BLOG_TEAM_FALLBACK}</div>
{featuredPost.authorRole && <div className="font-bold text-medical-gray-400">{featuredPost.authorRole}</div>}
</div>
</div>
<div className="flex items-center gap-2 text-canina-blue font-black text-sm">
@@ -406,10 +411,8 @@ export default function BlogPage({
</div>
<div className="p-4 sm:p-7">
<div className="flex items-center justify-between text-[11px] font-bold text-medical-gray-400 mb-3">
<div className="flex items-center gap-1">
<Calendar className="w-3 h-3" />
{post.date}
</div>
<div className="flex items-center gap-1"><Calendar className="w-3 h-3" />تاریخ انتشار: <time dateTime={publicationDate(post)}>{persianDate(publicationDate(post))}</time></div>
{validContentUpdatedAt(post) && <div>آخرین به‌روزرسانی: <time dateTime={validContentUpdatedAt(post)}>{persianDate(validContentUpdatedAt(post))}</time></div>}
<div className="flex items-center gap-3">
<div className="flex items-center gap-1">
<Clock className="w-3 h-3" />
@@ -433,7 +436,7 @@ export default function BlogPage({
<div className="px-4 sm:px-7 pb-4 sm:pb-6 pt-2.5 border-t border-medical-gray-100 flex items-center justify-between">
<div className="text-[11px] font-bold text-medical-gray-500 flex items-center gap-1.5">
<User className="w-3.5 h-3.5 text-medical-gray-400" />
<span>{post.author}</span>
<span>نویسنده: {post.author}</span><span>تیم: {post.authorTeam || BLOG_TEAM_FALLBACK}</span>
</div>
<div className="flex items-center gap-1 text-canina-blue font-black text-xs group-hover:underline">
<span>مطالعه</span>
@@ -1,4 +1,5 @@
"use client";
import { BLOG_TEAM_FALLBACK, publicationDate, validContentUpdatedAt, persianDate } from "../lib/blogDates";
import React, { useState, useEffect } from "react";
import {
ChevronRight,
@@ -147,12 +148,8 @@ export default function BlogPostClient({ blog, publishedDate, authorName, saniti
{blog.category.name}
</span>
)}
{publishedDate && (
<div className="flex items-center gap-1">
<Calendar className="w-3.5 h-3.5 text-canina-blue" />
<span>{publishedDate}</span>
</div>
)}
{publishedDate && <div className="flex items-center gap-1"><Calendar className="w-3.5 h-3.5 text-canina-blue" />تاریخ انتشار: <time dateTime={publicationDate(blog)}>{publishedDate}</time></div>}
{validContentUpdatedAt(blog) && <div>آخرین به‌روزرسانی: <time dateTime={validContentUpdatedAt(blog)}>{persianDate(validContentUpdatedAt(blog))}</time></div>}
<div className="flex items-center gap-1">
<Clock className="w-3.5 h-3.5 text-canina-blue" />
<span>{blog.readingTime || 4} دقیقه مطالعه</span>
@@ -212,9 +209,9 @@ export default function BlogPostClient({ blog, publishedDate, authorName, saniti
<User className="w-7 h-7" />
</div>
<div>
<div className="font-black text-medical-gray-900 text-base">{authorName}</div>
<div className="font-black text-medical-gray-900 text-base">نویسنده: {authorName}</div>
<div className="font-bold text-xs text-medical-gray-400 mt-0.5">
تیم تحقیق و توسعه علمی کنینا آلمان (Canina Pharma)
تیم: {blog.authorTeam || BLOG_TEAM_FALLBACK}
</div>
</div>
</div>
@@ -7,6 +7,7 @@ import SafeImage from "./SafeImage";
import { useSettingsStore } from "../lib/store/settingsStore";
import api, { BASE_DOMAIN } from "../lib/services/api";
import { toPersian } from "../lib/utils";
import { BLOG_TEAM_FALLBACK, publicationDate, validContentUpdatedAt, persianDate } from "../lib/blogDates";
export interface BlogPost {
id: string;
@@ -16,6 +17,10 @@ export interface BlogPost {
imageUrl?: string;
viewCount: number;
createdAt: string;
publishedAt?: string;
contentUpdatedAt?: string;
authorTeam?: string;
authorRole?: string;
author?: {
firstName: string;
lastName: string;
@@ -108,7 +113,7 @@ export default function BlogPreviewSection() {
? `${blog.author.firstName || ""} ${blog.author.lastName || ""}`.trim()
: "تحریریه کنینا";
const formattedDate = new Date(blog.createdAt).toLocaleDateString("fa-IR");
const blogHref = `/blog/${encodeURIComponent(blog.slug || blog.id)}`;
@@ -134,10 +139,8 @@ export default function BlogPreviewSection() {
<div className="p-3.5 sm:p-6 flex-1 flex flex-col justify-between space-y-3 sm:space-y-4">
<div className="space-y-1.5 sm:space-y-2">
<div className="flex items-center gap-2.5 sm:gap-4 text-[10px] sm:text-xs text-medical-gray-400 font-medium">
<span className="flex items-center gap-1">
<Calendar className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
{toPersian(formattedDate)}
</span>
<span className="flex items-center gap-1"><Calendar className="w-3 h-3 sm:w-3.5 sm:h-3.5" />تاریخ انتشار: <time dateTime={publicationDate(blog)}>{persianDate(publicationDate(blog))}</time></span>
{validContentUpdatedAt(blog) && <span>آخرین به‌روزرسانی: <time dateTime={validContentUpdatedAt(blog)}>{persianDate(validContentUpdatedAt(blog))}</time></span>}
<span className="flex items-center gap-1">
<Eye className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
{toPersian(blog.viewCount || 0)}
@@ -157,8 +160,8 @@ export default function BlogPreviewSection() {
<div className="pt-2.5 sm:pt-4 border-t border-medical-gray-200/60 flex items-center justify-between">
<span className="text-[10px] sm:text-xs font-bold text-medical-gray-500 truncate max-w-[100px] sm:max-w-none">
{authorName}
</span>
نویسنده: {authorName}
</span><span className="text-[10px] sm:text-xs font-bold text-medical-gray-500">تیم: {blog.authorTeam || BLOG_TEAM_FALLBACK}</span>
<Link
href={blogHref}
aria-label={`مطالعه مقاله: ${blog.title}`}
@@ -21,6 +21,7 @@ const categories=[{id:'joints',name:'Joints',slug:'joints'},{id:'skin',name:'Ski
beforeEach(()=>vi.clearAllMocks());
describe('BlogPage',()=>{
it('renders featured and regular posts as semantic links',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);expect(screen.getAllByRole('heading',{level:2})[0]).toHaveTextContent('Skin article');expect(screen.getByRole('link',{name:/Skin article/})).toHaveAttribute('href','/blog/skin');expect(screen.getByRole('link',{name:/Joint article/})).toHaveAttribute('href','/blog/joint');});
it('labels publication, valid material update, author and stable team on featured and regular cards',()=>{const fresh=[{...blogs[0],publishedAt:'2026-01-01T08:00:00Z',contentUpdatedAt:'2026-01-02T08:00:00Z',authorTeam:'Clinical'}, {...blogs[1],publishedAt:'2026-01-02T08:00:00Z',contentUpdatedAt:'2026-01-02T12:00:00Z'}];render(<BlogPage blogs={fresh} categories={categories}/>);expect(screen.getAllByText(/تاریخ انتشار/)).toHaveLength(2);expect(screen.getByText(/آخرین به‌روزرسانی/)).toBeInTheDocument();expect(screen.getAllByText(/نویسنده:/)).toHaveLength(2);expect(screen.getByText(/تیم: Clinical/)).toBeInTheDocument();expect(screen.getByText(/تیم: تیم پژوهش و محتوای علمی کنینا/)).toBeInTheDocument();expect(document.querySelectorAll('time[datetime]').length).toBeGreaterThanOrEqual(3);});
it('combines category, excerpt search and tags then resets empty intersection',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);fireEvent.click(screen.getByRole('button',{name:'Joints'}));expect(h.replace).toHaveBeenCalledWith('/blog?categoryId=joints',{scroll:false});expect(screen.queryByText('Skin article')).not.toBeInTheDocument();fireEvent.change(screen.getByPlaceholderText('جستجو در موضوعات، بیماری‌ها، ویتامین‌ها...'),{target:{value:'MOBILITY'}});expect(screen.getByText('Joint article')).toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:'#coat'}));expect(screen.getByText('هیچ مقاله‌ای با معیارهای جستجوی شما یافت نشد.')).toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:'پاکسازی همه فیلترها'}));expect(screen.getByText('Skin article')).toBeInTheDocument();expect(screen.getByText('Joint article')).toBeInTheDocument();});
it('syncs category with route props',()=>{const view=render(<BlogPage blogs={blogs} categories={categories} initialCategoryId="joints"/>);expect(screen.queryByText('Skin article')).not.toBeInTheDocument();view.rerender(<BlogPage blogs={blogs} categories={categories} initialCategoryId="skin"/>);expect(screen.queryByText('Joint article')).not.toBeInTheDocument();});
it('clears search and toggles tags off',()=>{render(<BlogPage blogs={blogs}/>);fireEvent.click(screen.getByRole('button',{name:'#health'}));expect(screen.queryByText('Skin article')).not.toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:'#health'}));expect(screen.getByText('Skin article')).toBeInTheDocument();fireEvent.change(screen.getByPlaceholderText('جستجو در موضوعات، بیماری‌ها، ویتامین‌ها...'),{target:{value:'missing'}});fireEvent.click(screen.getByRole('button',{name:'پاک کردن'}));expect(screen.getByText('Skin article')).toBeInTheDocument();});
@@ -89,7 +89,7 @@ describe("BlogPostClient Component", () => {
// Breadcrumb and headers
expect(screen.getByRole("heading", { level: 1, name: /راهنمای جامع کانی‌هیدروکس GAG/ })).toBeInTheDocument();
expect(screen.getAllByText("سلامت استخوان و مفاصل").length).toBeGreaterThan(0);
expect(screen.getByText("دکتر توماس بکر")).toBeInTheDocument();
expect(screen.getByText("نویسنده: دکتر توماس بکر")).toBeInTheDocument();
expect(screen.getByText("۱۵ فروردین ۱۴۰۵")).toBeInTheDocument();
expect(screen.getAllByText(/دقیقه مطالعه/).length).toBeGreaterThan(0);
@@ -110,6 +110,15 @@ describe("BlogPostClient Component", () => {
expect(screen.getByText("بسته‌بندی قوطی کانی‌هیدروکس")).toBeInTheDocument();
});
it("renders semantic publication, valid update and explicit author/team labels", () => {
render(<BlogPostClient blog={{...mockBlog,publishedAt:"2026-01-01T00:00:00Z",contentUpdatedAt:"2026-01-02T00:00:00Z",authorTeam:"Science"}} sanitizedContent={mockBlog.content} publishedDate="۱۲ دی ۱۴۰۴" authorName="دکتر بکر" />);
expect(screen.getByText(/تاریخ انتشار/)).toBeInTheDocument();
expect(screen.getByText(/آخرین به‌روزرسانی/)).toBeInTheDocument();
expect(screen.getByText(/نویسنده: دکتر بکر/)).toBeInTheDocument();
expect(screen.getByText(/تیم: Science/)).toBeInTheDocument();
expect(document.querySelectorAll("time[datetime]").length).toBe(2);
});
it("registers blog view count on mount via API", async () => {
render(
<BlogPostClient
@@ -110,9 +110,9 @@ describe("BlogPreviewSection Component", () => {
});
// Author display
expect(screen.getByText("دکتر مریم اکبری")).toBeInTheDocument();
expect(screen.getByText("نویسنده: دکتر مریم اکبری")).toBeInTheDocument();
// Default fallback author
expect(screen.getByText("تحریریه کنینا")).toBeInTheDocument();
expect(screen.getByText("نویسنده: تحریریه کنینا")).toBeInTheDocument();
// Verify aria-label links with full title context
const link1 = screen.getByLabelText("مطالعه مقاله: اهمیت کلسیم و مفاصل در رشد توله سگ ژرمن شپرد");
@@ -122,6 +122,15 @@ describe("BlogPreviewSection Component", () => {
expect(link2).toHaveAttribute("href", "/blog/cat-hair-loss-solutions");
});
it("uses publication freshness and explicit byline labels on homepage cards", async () => {
vi.mocked(api.get).mockResolvedValueOnce({ data: { blogs: [{ id:"b",slug:"b",title:"B",content:"",viewCount:0,createdAt:"2026-01-01T00:00:00Z",publishedAt:"2026-01-01T00:00:00Z",contentUpdatedAt:"2026-01-02T00:00:00Z",authorTeam:"Science" }] } });
render(<BlogPreviewSection />);
expect(await screen.findByText(/تاریخ انتشار/)).toBeInTheDocument();
expect(screen.getByText(/آخرین به‌روزرسانی/)).toBeInTheDocument();
expect(screen.getByText(/نویسنده:/)).toBeInTheDocument();
expect(screen.getByText(/تیم: Science/)).toBeInTheDocument();
});
it("handles api errors gracefully and renders null", async () => {
vi.mocked(api.get).mockRejectedValueOnce(new Error("Failed to load"));
const { container } = render(<BlogPreviewSection />);
+5
View File
@@ -0,0 +1,5 @@
export const BLOG_TEAM_FALLBACK = "تیم پژوهش و محتوای علمی کنینا";
export function publicationDate(blog:any): string | undefined { return blog?.publishedAt || blog?.createdAt; }
function persianDay(value:string): string { return new Intl.DateTimeFormat("fa-IR-u-ca-persian-nu-latn",{year:"numeric",month:"2-digit",day:"2-digit",timeZone:"Asia/Tehran"}).format(new Date(value)); }
export function validContentUpdatedAt(blog:any): string | undefined { const published=publicationDate(blog), updated=blog?.contentUpdatedAt; if(!published||!updated) return undefined; const p=new Date(published),u=new Date(updated); return Number.isFinite(p.getTime())&&Number.isFinite(u.getTime())&&u>p&&persianDay(updated)!==persianDay(published)?updated:undefined; }
export function persianDate(value?:string): string { return value ? new Date(value).toLocaleDateString("fa-IR") : ""; }