From 5cf2863987c57ea945bae2fc2a8b935b204df6de Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 20:02:56 +0000 Subject: [PATCH] fix(seo): resolve technical SEO issues (SEO-P0-01, SEO-P0-02, SEO-P1-06, SEO-P2-15) - SEO-P0-01: prioritize options.canonicalPath in getPageMetadata over shop_canonical text - SEO-P0-02: invoke notFound() in /shop/[slug] and /wiki/[slug] when entity is missing - SEO-P1-06: package root JSON-LD Organization and WebSite into @graph structure - SEO-P2-15: add hreflang fa-IR and x-default alternates in root layout metadata - Add regression test suite lib/__tests__/seo-technical.test.ts --- frontend/application/app/layout.tsx | 11 +- frontend/application/app/shop/[slug]/page.tsx | 3 +- frontend/application/app/wiki/[slug]/page.tsx | 11 +- .../lib/__tests__/seo-technical.test.ts | 153 ++++++++++++++++++ frontend/application/lib/seo.ts | 5 +- 5 files changed, 170 insertions(+), 13 deletions(-) create mode 100644 frontend/application/lib/__tests__/seo-technical.test.ts diff --git a/frontend/application/app/layout.tsx b/frontend/application/app/layout.tsx index cce23feb..e1240ee6 100644 --- a/frontend/application/app/layout.tsx +++ b/frontend/application/app/layout.tsx @@ -71,6 +71,10 @@ export async function generateMetadata(): Promise { }, alternates: { canonical: '/', + languages: { + 'fa-IR': `${siteUrl}/`, + 'x-default': `${siteUrl}/`, + }, }, formatDetection: { email: false, @@ -148,7 +152,12 @@ export default async function RootLayout({ }, }; - const safeJsonLd = JSON.stringify([orgSchema, webSiteSchema]).replace(/; + notFound(); } const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://canina.ir'; diff --git a/frontend/application/app/wiki/[slug]/page.tsx b/frontend/application/app/wiki/[slug]/page.tsx index 3bfb031f..a2d5c530 100644 --- a/frontend/application/app/wiki/[slug]/page.tsx +++ b/frontend/application/app/wiki/[slug]/page.tsx @@ -1,3 +1,4 @@ +import { notFound } from 'next/navigation'; import Link from 'next/link'; import { ChevronRight, Sparkles, Package, ArrowLeft, ShieldCheck } from 'lucide-react'; import type { Metadata } from 'next'; @@ -81,15 +82,7 @@ export default async function WikiTermPage({ params }: { params: Promise<{ slug: const term = await getWikiTerm(slug); if (!term) { - return ( -
-

ترکیب علمی یافت نشد

- - - بازگشت به دانشنامه - -
- ); + notFound(); } const relatedProducts = await getRelatedProducts(term.term); diff --git a/frontend/application/lib/__tests__/seo-technical.test.ts b/frontend/application/lib/__tests__/seo-technical.test.ts new file mode 100644 index 00000000..5e6323f4 --- /dev/null +++ b/frontend/application/lib/__tests__/seo-technical.test.ts @@ -0,0 +1,153 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { getPageMetadata } from '../seo'; + +const mockFetch = vi.fn(); +global.fetch = mockFetch; + +// Mock next/navigation +const mockNotFound = vi.fn(); +vi.mock('next/navigation', () => ({ + notFound: () => { + mockNotFound(); + throw new Error('NEXT_NOT_FOUND'); + }, +})); + +// Mock next/font/local and next/font/google +vi.mock('next/font/local', () => ({ + default: () => ({ variable: '--font-vazir' }), +})); +vi.mock('next/font/google', () => ({ + Lalezar: () => ({ variable: '--font-lalezar' }), +})); + +// Mock productService +const mockGetProductBySlug = vi.fn(); +vi.mock('../../lib/services/productService', () => ({ + productService: { + getProductBySlug: (slug: string) => mockGetProductBySlug(slug), + }, +})); + +describe('SEO Technical Fixes (SEO-P0-01, SEO-P0-02, SEO-P1-06, SEO-P2-15)', () => { + beforeEach(() => { + vi.clearAllMocks(); + delete process.env.NEXT_PUBLIC_APP_ENV; + delete process.env.NEXT_PUBLIC_SITE_URL; + }); + + describe('SEO-P0-01: Canonical tag for category pages in lib/seo.ts', () => { + it('should NOT let global shop_canonical override options.canonicalPath', async () => { + mockFetch.mockResolvedValueOnce({ + ok: true, + json: async () => ({ + shop_canonical: 'https://canina.ir/shop', + canonicalBaseUrl: 'https://canina.ir', + }), + }); + + const metadata = await getPageMetadata('shop', { + canonicalPath: '/shop?category=joints', + }); + + expect(metadata.alternates?.canonical).toBe('https://canina.ir/shop?category=joints'); + }); + + it('should fall back to shop_canonical if options.canonicalPath is not provided', async () => { + mockFetch.mockResolvedValueOnce({ + ok: true, + json: async () => ({ + shop_canonical: 'https://canina.ir/shop-override', + canonicalBaseUrl: 'https://canina.ir', + }), + }); + + const metadata = await getPageMetadata('shop'); + expect(metadata.alternates?.canonical).toBe('https://canina.ir/shop-override'); + }); + }); + + describe('SEO-P0-02: Soft 404 handling with notFound()', () => { + it('should call notFound() in ShopProductPage when product is not found', async () => { + const { default: ShopProductPage } = await import('../../app/shop/[slug]/page'); + mockGetProductBySlug.mockResolvedValueOnce(null); + + await expect(ShopProductPage({ + params: Promise.resolve({ slug: 'non-existent-product' }) + })).rejects.toThrow('NEXT_NOT_FOUND'); + + expect(mockNotFound).toHaveBeenCalled(); + }); + + it('should call notFound() in WikiTermPage when term is not found', async () => { + const { default: WikiTermPage } = await import('../../app/wiki/[slug]/page'); + mockFetch.mockResolvedValueOnce({ + ok: false, + status: 404, + }); + + await expect(WikiTermPage({ + params: Promise.resolve({ slug: 'non-existent-term' }) + })).rejects.toThrow('NEXT_NOT_FOUND'); + + expect(mockNotFound).toHaveBeenCalled(); + }); + }); + + describe('SEO-P2-15: hreflang alternates in RootLayout metadata', () => { + it('should configure alternates with languages fa-IR and x-default in app/layout.tsx', async () => { + const { generateMetadata } = await import('../../app/layout'); + mockFetch.mockResolvedValueOnce({ + ok: true, + json: async () => ({ + canonicalBaseUrl: 'https://canina.ir', + }), + }); + + const metadata = await generateMetadata(); + expect(metadata.alternates?.languages).toBeDefined(); + expect(metadata.alternates?.languages?.['fa-IR']).toBe('https://canina.ir/'); + expect(metadata.alternates?.languages?.['x-default']).toBe('https://canina.ir/'); + }); + }); + + describe('SEO-P1-06: Schema @graph formatting in RootLayout', () => { + it('should package Organization and WebSite inside @graph structure', async () => { + const { default: RootLayout } = await import('../../app/layout'); + mockFetch.mockResolvedValueOnce({ + ok: true, + json: async () => ({ + texts: {}, + }), + }); + + const element = await RootLayout({ children: null }); + const findScript = (node: any): any => { + if (!node) return null; + if (node.type === 'script' && node.props?.type === 'application/ld+json') { + return node; + } + if (Array.isArray(node)) { + for (const item of node) { + const found = findScript(item); + if (found) return found; + } + } + if (node.props?.children) { + return findScript(node.props.children); + } + return null; + }; + + const script = findScript(element); + expect(script).toBeDefined(); + const jsonContent = JSON.parse(script.props.dangerouslySetInnerHTML.__html); + + expect(jsonContent['@context']).toBe('https://schema.org'); + expect(Array.isArray(jsonContent['@graph'])).toBe(true); + const types = jsonContent['@graph'].map((item: any) => item['@type']); + expect(types).toContain('Organization'); + expect(types).toContain('WebSite'); + }); + }); +}); diff --git a/frontend/application/lib/seo.ts b/frontend/application/lib/seo.ts index f402001b..4ea89d13 100644 --- a/frontend/application/lib/seo.ts +++ b/frontend/application/lib/seo.ts @@ -277,9 +277,10 @@ export async function getPageMetadata( ? rawKeywords.split(',').map((k) => k.trim()).filter(Boolean) : options.fallbackKeywords || config.keywords; - const explicitCanonical = texts[`${pageKey}_canonical`]; const relativePath = options.canonicalPath ?? (isHome ? '/' : `/${pageKey.replace(/_/g, '-')}`); - const canonicalUrl = explicitCanonical || `${canonicalBaseUrl.replace(/\/$/, '')}${relativePath}`; + const canonicalUrl = options.canonicalPath + ? `${canonicalBaseUrl.replace(/\/$/, '')}${options.canonicalPath.startsWith('/') ? options.canonicalPath : `/${options.canonicalPath}`}` + : (texts[`${pageKey}_canonical`] || `${canonicalBaseUrl.replace(/\/$/, '')}${relativePath}`); const image = options.ogImage || ogImageUrl;