From 51ca8c7e3413a7b06e3c638976fd66b2f9d25a89 Mon Sep 17 00:00:00 2001 From: devops Date: Tue, 20 Oct 2026 05:36:03 +0000 Subject: [PATCH] feat(blog): add material freshness and authorship --- .../migration.sql | 3 +++ backend/prisma/schema.prisma | 3 +++ backend/src/admin/blogs.service.spec.ts | 26 ++++++++++++++++++- backend/src/admin/blogs.service.ts | 12 +++++++-- backend/src/blogs/blogs.service.spec.ts | 20 +++++++++++++- backend/src/blogs/blogs.service.ts | 10 +++++++ frontend/admin-panel/src/pages/Blogs.test.tsx | 4 +++ frontend/admin-panel/src/pages/Blogs.tsx | 19 ++++++++++++++ .../app/blog/[slug]/blog-slug-page.test.tsx | 5 ++++ frontend/application/app/blog/[slug]/page.tsx | 12 ++++----- frontend/application/app/blog/page.tsx | 5 ++++ .../app/blog/rss.xml/route.test.ts | 4 +++ .../application/app/blog/rss.xml/route.ts | 7 +++-- .../application/app/sitemap-blog.xml/route.ts | 10 +++---- frontend/application/app/sitemap.test.ts | 4 +-- frontend/application/app/sitemap.ts | 5 ++-- frontend/application/app/sitemaps.test.ts | 5 +++- frontend/application/components/BlogPage.tsx | 25 ++++++++++-------- .../application/components/BlogPostClient.tsx | 13 ++++------ .../components/BlogPreviewSection.tsx | 17 +++++++----- .../components/__tests__/BlogPage.test.tsx | 1 + .../__tests__/BlogPostClient.test.tsx | 11 +++++++- .../__tests__/BlogPreviewSection.test.tsx | 13 ++++++++-- frontend/application/lib/blogDates.ts | 5 ++++ 24 files changed, 187 insertions(+), 52 deletions(-) create mode 100644 backend/prisma/migrations/20261020000000_add_blog_freshness_authorship/migration.sql create mode 100644 frontend/application/app/blog/rss.xml/route.test.ts create mode 100644 frontend/application/lib/blogDates.ts diff --git a/backend/prisma/migrations/20261020000000_add_blog_freshness_authorship/migration.sql b/backend/prisma/migrations/20261020000000_add_blog_freshness_authorship/migration.sql new file mode 100644 index 00000000..03cf68e9 --- /dev/null +++ b/backend/prisma/migrations/20261020000000_add_blog_freshness_authorship/migration.sql @@ -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; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 207988c8..0a9964e2 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -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") diff --git a/backend/src/admin/blogs.service.spec.ts b/backend/src/admin/blogs.service.spec.ts index 581f0859..62c9df90 100644 --- a/backend/src/admin/blogs.service.spec.ts +++ b/backend/src/admin/blogs.service.spec.ts @@ -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( diff --git a/backend/src/admin/blogs.service.ts b/backend/src/admin/blogs.service.ts index d92d67cd..e785b091 100644 --- a/backend/src/admin/blogs.service.ts +++ b/backend/src/admin/blogs.service.ts @@ -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, }, }); diff --git a/backend/src/blogs/blogs.service.spec.ts b/backend/src/blogs/blogs.service.spec.ts index df3628a8..7d2dd366 100644 --- a/backend/src/blogs/blogs.service.spec.ts +++ b/backend/src/blogs/blogs.service.spec.ts @@ -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( diff --git a/backend/src/blogs/blogs.service.ts b/backend/src/blogs/blogs.service.ts index edcbf302..67549d95 100644 --- a/backend/src/blogs/blogs.service.ts +++ b/backend/src/blogs/blogs.service.ts @@ -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 }, }, diff --git a/frontend/admin-panel/src/pages/Blogs.test.tsx b/frontend/admin-panel/src/pages/Blogs.test.tsx index 8229279c..a97f108f 100644 --- a/frontend/admin-panel/src/pages/Blogs.test.tsx +++ b/frontend/admin-panel/src/pages/Blogs.test.tsx @@ -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 } }); diff --git a/frontend/admin-panel/src/pages/Blogs.tsx b/frontend/admin-panel/src/pages/Blogs.tsx index 5f49a8c0..aa649d26 100644 --- a/frontend/admin-panel/src/pages/Blogs.tsx +++ b/frontend/admin-panel/src/pages/Blogs.tsx @@ -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() { +
+
setFormData({...formData,authorTeam:e.target.value})} className="w-full px-3 py-2.5 rounded-2xl border border-gray-200 text-xs" />
+
setFormData({...formData,authorRole:e.target.value})} className="w-full px-3 py-2.5 rounded-2xl border border-gray-200 text-xs" />
+
+ {/* Chips Tag Input */}
@@ -1161,6 +1178,8 @@ export default function Blogs() {
+ +
@@ -406,10 +411,8 @@ export default function BlogPage({
-
- - {post.date} -
+
تاریخ انتشار:
+ {validContentUpdatedAt(post) &&
آخرین به‌روزرسانی:
}
@@ -433,7 +436,7 @@ export default function BlogPage({
- {post.author} + نویسنده: {post.author}تیم: {post.authorTeam || BLOG_TEAM_FALLBACK}
مطالعه diff --git a/frontend/application/components/BlogPostClient.tsx b/frontend/application/components/BlogPostClient.tsx index 33ed2087..a6622d3d 100644 --- a/frontend/application/components/BlogPostClient.tsx +++ b/frontend/application/components/BlogPostClient.tsx @@ -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} )} - {publishedDate && ( -
- - {publishedDate} -
- )} + {publishedDate &&
تاریخ انتشار:
} + {validContentUpdatedAt(blog) &&
آخرین به‌روزرسانی:
}
{blog.readingTime || 4} دقیقه مطالعه @@ -212,9 +209,9 @@ export default function BlogPostClient({ blog, publishedDate, authorName, saniti
-
{authorName}
+
نویسنده: {authorName}
- تیم تحقیق و توسعه علمی کنینا آلمان (Canina Pharma) + تیم: {blog.authorTeam || BLOG_TEAM_FALLBACK}
diff --git a/frontend/application/components/BlogPreviewSection.tsx b/frontend/application/components/BlogPreviewSection.tsx index b45e3346..8f3ab5c6 100644 --- a/frontend/application/components/BlogPreviewSection.tsx +++ b/frontend/application/components/BlogPreviewSection.tsx @@ -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() {
- - - {toPersian(formattedDate)} - + تاریخ انتشار: + {validContentUpdatedAt(blog) && آخرین به‌روزرسانی: } {toPersian(blog.viewCount || 0)} @@ -157,8 +160,8 @@ export default function BlogPreviewSection() {
- {authorName} - + نویسنده: {authorName} + تیم: {blog.authorTeam || BLOG_TEAM_FALLBACK} vi.clearAllMocks()); describe('BlogPage',()=>{ it('renders featured and regular posts as semantic links',()=>{render();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();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();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();expect(screen.queryByText('Skin article')).not.toBeInTheDocument();view.rerender();expect(screen.queryByText('Joint article')).not.toBeInTheDocument();}); it('clears search and toggles tags off',()=>{render();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();}); diff --git a/frontend/application/components/__tests__/BlogPostClient.test.tsx b/frontend/application/components/__tests__/BlogPostClient.test.tsx index 1541b5cf..c500de33 100644 --- a/frontend/application/components/__tests__/BlogPostClient.test.tsx +++ b/frontend/application/components/__tests__/BlogPostClient.test.tsx @@ -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(); + 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( { }); // 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(); + 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(); diff --git a/frontend/application/lib/blogDates.ts b/frontend/application/lib/blogDates.ts new file mode 100644 index 00000000..9c6718d6 --- /dev/null +++ b/frontend/application/lib/blogDates.ts @@ -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") : ""; }