fix(blog): project truthful publication and substantive edit timestamps

This commit is contained in:
Canina Hermes committed 2026-10-30 13:21:07 +00:00
1 parent 00ba4360cf
commit c97ea01ba9
8 files changed
+140 -8

No files matched your search

@@ -82,9 +82,9 @@ describe('BlogPostPage FAQPage Schema injection (SEO-P1-07)', () => {
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).toBe('2026-01-01T12:00:00.000Z'); expect(json.author['@type']).toBe('Organization'); expect(json.author.name).toBe('کنینا'); 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).toBe('2026-01-01T12:00:00.000Z'); expect(json.author['@type']).toBe('Organization'); expect(json.author.name).toBe('کنینا');
}); });
it('omits dateModified when only technical updatedAt exists', async () => { it('uses publication as dateModified when only technical updatedAt exists', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ok:true,json:async()=>({slug:'technical',title:'Technical',content:'<p>x</p>',publishedAt:'2026-01-01T01:00:00Z',updatedAt:'2026-01-01T12:00:00Z',contentUpdatedAt:null})})); vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ok:true,json:async()=>({slug:'technical',title:'Technical',content:'<p>x</p>',publishedAt:'2026-01-01T01:00:00Z',updatedAt:'2026-01-01T12:00:00Z',contentUpdatedAt:null})}));
const jsx=await BlogPostPage({params:Promise.resolve({slug:'technical'})}); const script:any=React.Children.toArray(jsx.props.children)[0]; const json=JSON.parse(script.props.dangerouslySetInnerHTML.__html); expect(json.dateModified).toBeUndefined(); const jsx=await BlogPostPage({params:Promise.resolve({slug:'technical'})}); const script:any=React.Children.toArray(jsx.props.children)[0]; const json=JSON.parse(script.props.dangerouslySetInnerHTML.__html); expect(json.dateModified).toBe('2026-01-01T01:00:00.000Z');
}); });
it('uses the stable Organization fallback visibly and in metadata', async () => { it('uses the stable Organization fallback visibly and in metadata', async () => {
@@ -1,4 +1,4 @@
import { validContentUpdatedAt } from "../../../lib/blogDates"; import { persianDate, validContentUpdatedAt } from "../../../lib/blogDates";
import { resolveBlogAuthorIdentity } from "../../../lib/blogAuthor"; import { resolveBlogAuthorIdentity } from "../../../lib/blogAuthor";
import React from "react"; import React from "react";
import { notFound } from 'next/navigation'; import { notFound } from 'next/navigation';
@@ -23,7 +23,7 @@ function safeLocalDate(val: any): string {
if (!val) return ''; if (!val) return '';
try { try {
const d = new Date(val); const d = new Date(val);
return isNaN(d.getTime()) ? '' : d.toLocaleDateString('fa-IR'); return isNaN(d.getTime()) ? '' : persianDate(d.toISOString());
} catch { } catch {
return ''; return '';
} }
@@ -95,7 +95,8 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
const resolvedAuthor = resolveBlogAuthorIdentity(blog); const resolvedAuthor = resolveBlogAuthorIdentity(blog);
const publishedTime = safeIso(blog.publishedAt) || safeIso(blog.createdAt); const publishedTime = safeIso(blog.publishedAt) || safeIso(blog.createdAt);
const modifiedTime = safeIso(validContentUpdatedAt(blog)); // Technical writes are not substantive edits; unedited articles retain the real publication date.
const modifiedTime = safeIso(validContentUpdatedAt(blog)) || publishedTime;
const keywordsList = blog.focusKeywords const keywordsList = blog.focusKeywords
? blog.focusKeywords.split(',').map((k: string) => k.trim()) ? blog.focusKeywords.split(',').map((k: string) => k.trim())
@@ -181,8 +182,8 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
? blog.canonicalUrl.replace(/\/+$/, '') ? blog.canonicalUrl.replace(/\/+$/, '')
: `${siteUrl}/blog/${slug}`; : `${siteUrl}/blog/${slug}`;
const publishedIso = safeIso(blog.publishedAt) || safeIso(blog.createdAt) || new Date().toISOString(); const publishedIso = safeIso(blog.publishedAt) || safeIso(blog.createdAt);
const modifiedIso = safeIso(validContentUpdatedAt(blog)); const modifiedIso = safeIso(validContentUpdatedAt(blog)) || publishedIso;
const sanitizedContent = sanitizeBlogHtml(blog.content); const sanitizedContent = sanitizeBlogHtml(blog.content);
const schemaType = blog.schemaType || 'BlogPosting'; const schemaType = blog.schemaType || 'BlogPosting';
@@ -210,7 +211,7 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
image: blog.imageUrl image: blog.imageUrl
? [blog.imageUrl.startsWith('http') ? blog.imageUrl : `${siteUrl}${blog.imageUrl.startsWith('/') ? '' : '/'}${blog.imageUrl}`] ? [blog.imageUrl.startsWith('http') ? blog.imageUrl : `${siteUrl}${blog.imageUrl.startsWith('/') ? '' : '/'}${blog.imageUrl}`]
: [config.ogImageUrl.startsWith('http') ? config.ogImageUrl : `${siteUrl}${config.ogImageUrl.startsWith('/') ? '' : '/'}${config.ogImageUrl}`], : [config.ogImageUrl.startsWith('http') ? config.ogImageUrl : `${siteUrl}${config.ogImageUrl.startsWith('/') ? '' : '/'}${config.ogImageUrl}`],
datePublished: publishedIso, ...(publishedIso ? { datePublished: publishedIso } : {}),
...(modifiedIso ? { dateModified: modifiedIso } : {}), ...(modifiedIso ? { dateModified: modifiedIso } : {}),
author: authorSchema, author: authorSchema,
publisher: { publisher: {
@@ -0,0 +1,73 @@
import React from 'react';
import { afterEach, expect, it, vi } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
import BlogPostPage, { generateMetadata } from './page';
import { validContentUpdatedAt } from '../../../lib/blogDates';
vi.mock('../../../lib/seo', () => ({
getSeoConfig: async () => ({ brandNameFa: 'کنینا', canonicalBaseUrl: 'https://canina.ir', ogImageUrl: 'https://canina.ir/default.webp' }),
formatPageTitle: (title: string) => title,
}));
vi.mock('../../../components/BlogPostClient', () => ({
default: ({ blog, publishedDate }: { blog: any; publishedDate: string }) => <div>
<span>تاریخ انتشار: {publishedDate}</span>
{validContentUpdatedAt(blog) && <span>آخرین به‌روزرسانی</span>}
</div>,
}));
afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); });
const published = '2026-10-29T07:11:40.925Z';
async function readDates(fields: Record<string, unknown>) {
vi.stubEnv('NEXT_PUBLIC_APP_ENV', 'staging');
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({
title: 'Timestamp contract', content: '<p>Article</p>', ...fields,
}) }));
const params = Promise.resolve({ slug: 'timestamp-contract' });
const metadata = await generateMetadata({ params });
const jsx = await BlogPostPage({ params });
const script: any = React.Children.toArray(jsx.props.children)[0];
return { og: metadata.openGraph as any, robots: metadata.robots,
article: JSON.parse(script.props.dangerouslySetInnerHTML.__html), html: renderToStaticMarkup(jsx) };
}
it.each([null, undefined, 'invalid', published, '2026-10-28T00:00:00Z'])(
'uses real publication for unedited/invalid/chronologically inapplicable content date %s', async (contentUpdatedAt) => {
const { og, article, html, robots } = await readDates({ publishedAt: published,
contentUpdatedAt, updatedAt: '2026-10-30T09:00:00Z', imageUrl: '/attached.webp' });
expect(og.publishedTime).toBe(published);
expect(og.modifiedTime).toBe(published);
expect(article.datePublished).toBe(published);
expect(article.dateModified).toBe(published);
expect(html).not.toContain('آخرین به‌روزرسانی');
// Stage noindex remains an independent HTTP acceptance check; no robots change in this slice.
});
it('uses actual substantive update consistently without changing publication', async () => {
const modified = '2026-10-29T12:00:00.000Z';
const { og, article, html } = await readDates({ publishedAt: published, contentUpdatedAt: modified });
expect(og.modifiedTime).toBe(modified);
expect(article.dateModified).toBe(modified);
expect(article.datePublished).toBe(published);
expect(html).toContain('آخرین به‌روزرسانی');
});
it.each([null, 'invalid'])('uses the valid existing createdAt fallback when publishedAt is %s', async (publishedAt) => {
const { og, article } = await readDates({ publishedAt, createdAt: published });
expect(og.publishedTime).toBe(published);
expect(og.modifiedTime).toBe(published);
expect(article.datePublished).toBe(published);
expect(article.dateModified).toBe(published);
});
it.each([{}, { publishedAt: 'invalid', createdAt: 'invalid', contentUpdatedAt: '2026-10-30T00:00:00Z' }])(
'does not invent rendering-time publication or modification when unknown: %j', async (fields) => {
const { og, article } = await readDates(fields);
expect(og.publishedTime).toBeUndefined();
expect(og.modifiedTime).toBeUndefined();
expect(article).not.toHaveProperty('datePublished');
expect(article).not.toHaveProperty('dateModified');
});
it('formats visible publication using Persian calendar and Tehran rather than server timezone', async () => {
const { html } = await readDates({ publishedAt: '2026-10-29T21:00:00Z' });
const expected = new Intl.DateTimeFormat('fa-IR-u-ca-persian', {
year: 'numeric', month: 'numeric', day: 'numeric', timeZone: 'Asia/Tehran',
}).format(new Date('2026-10-29T21:00:00Z'));
expect(html).toContain(`تاریخ انتشار: ${expected}`);
});
@@ -0,0 +1,17 @@
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, it } from 'vitest';
import BlogPostClient from '../../../components/BlogPostClient';
it.each([null, undefined, 'invalid', '2026-10-29T07:11:40.925Z', '2026-10-28T00:00:00Z'])(
'actual client keeps publication but no visible update for %s despite later technical writes', (contentUpdatedAt) => {
const html = renderToStaticMarkup(<BlogPostClient
blog={{ id: 'timestamp-fixture', slug: 'timestamp-fixture', title: 'Timestamp',
publishedAt: '2026-10-29T07:11:40.925Z', contentUpdatedAt,
updatedAt: '2026-10-30T10:00:00Z', imageUrl: '/attached.webp' }}
publishedDate="۱۴۰۵/۸/۷" sanitizedContent="<p>Article</p>" authorName="کنینا"
/>);
expect(html).toContain('تاریخ انتشار');
expect(html).toContain('۱۴۰۵/۸/۷');
expect(html).not.toContain('آخرین به‌روزرسانی');
});
+24
View File
@@ -0,0 +1,24 @@
# Limited release receipt
Base and observed running production frontend/backend OCI revision: `00ba4360cf7b161995ee94f220b61f9547e01723`, both running, restartCount 0. Official main matches. Mixed develop `216e05ba258cf7882350f00da9d9b659885d9816` is NOT this release.
Only timestamp hunks ported; production imagery unchanged. Existing blogDates helper and BlogPostClient identical across main and mixed develop; no scoped dependency needed. All corporate, SEO-tracking, schema/migration, publisher, analytics, null-image work excluded.
Evidence directory `/opt/data/content-maintenance/recovery-evidence-20261030/`:
- `limited-timestamp-red.log`: initial ported tests fail; 11 failures includes missing fixture ogImageUrl (source main retains imagery fallback). Genuine metadata missing-fallback and clock/timezone failures present. Not all failures behavioral.
- `limited-timestamp-focused.log`: 3 files / 22 tests pass exit0.
- `limited-timestamp-full.log`: 100 files / 518 tests pass exit0, duration279.52 seconds.
- `limited-timestamp-typecheck.log`: typecheck exit0 (dedicated rerun; initial combined command hit external300s deadline after full suite passed).
- `limited-timestamp-lint.log`: scoped ESLint exit0. Full lint not rerun on limited base; prior mixed-branch lib/slug.ts error must not be represented as this artifact's complete lint result.
- `limited-timestamp-build.log`: first build fails because shared node_modules symlink lies outside Turbopack workspace.
- `limited-timestamp-build-localdeps.log`: build exit0 after reflink/copy existing dependencies inside worktree. No source config workaround. Warnings: multiple lockfiles and no local API on127.0.0.1:4400 during prerender. Not live API acceptance.
No backend/admin source changed; no claim their baseline tests certify a new SHA. Official CI rebuild and exact-SHA Stage runtime acceptance remain mandatory.
Existing Stage receipt `stage-216e05ba-release-receipt.json` reviewed: run1355 attests mixed SHA216e05ba and corporate acceptance only; cannot certify limited release. Its 52 Stage articles all have actual contentUpdatedAt later than publication, so an unedited fallback requires a suitable real record or authorized fixture; do not resave records merely to manufacture timestamps.
Release owner must resolve develop ref safely: current develop is mixed and limited branch from main is not a fast-forward. Do NOT merge current develop to main. Do NOT silently force/reset develop. Official workflow triggers only develop/main; parent must choose explicit authorized branch-ref reconciliation preserving mixed work before Stage push. Production promotion only after exact limited SHA Stage CI + container revision + HTTP HTML/JSON-LD/visible dates/noindex/canonical/image + unchanged source dates accepted.
Cause: null contentUpdatedAt correctly means no substantive edit, but renderer omitted modified metadata rather than falling back to real publication; visible formatting used host timezone; unknown publication schema fallback invented render-clock date. Technical updatedAt is not contentUpdatedAt. This changes projections only, never business timestamps or data.
Publisher remains untouched and gated until parent confirms production acceptance.
+4
View File
@@ -0,0 +1,4 @@
# Plan
Port only timestamp hunks from 216e05ba onto production main, not entire page from mixed branch. blogDates helper and BlogPostClient are identical across base and mixed source, no dependency port needed.
Graphify navigation graph hash 6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af, bound to older e7ded849f6b1e3bdab2a20d89b3ec7dd0df79cab: stale navigation only. Existing edges show BlogPostPage -> safeLocalDate/safeIso/getBlog and generateMetadata -> getBlog; confirm direct source/tests at base before editing.
+5
View File
@@ -0,0 +1,5 @@
# Limited timestamp rendering release
Base official main and running production: 00ba4360cf7b161995ee94f220b61f9547e01723. Scope only article timestamp projection, tests and specifications. No corporate, SEO tracking, imagery, data/schema/migration, seed, publisher or cron changes.
Acceptance: metadata modified date uses real substantive contentUpdatedAt only when valid and later than publication; otherwise real publication/createdAt. Never invent dates from render clock. Visible update label requires genuine substantive timestamp; Persian dates use Tehran timezone. Preserve all article imagery and canonical behavior. Stage exact limited SHA must pass official CI and live HTML/read-only source-date acceptance before promotion. Parent exclusively owns pushes.
+8
View File
@@ -0,0 +1,8 @@
# Tasks
- [x] Verify official main, deployed production revision and scoped dependencies.
- [ ] Execute newly ported tests RED on production base.
- [ ] Apply only timestamp hunks and update existing assertion.
- [ ] Run focused/full storefront tests, typecheck, build, scoped lint.
- [ ] Commit limited artifact; parent pushes exact SHA to Stage, validates it, then promotes to main.
- [ ] After production accepted, independent publisher may continue.