feat: add advisor/contact flow tables and make Blog.authorId required
Deploy Canina / deploy (push) Successful in 25m44s
Deploy Canina / deploy (push) Successful in 25m44s
This commit is contained in:
1 parent
bb81f2c944
commit
d881dc491e
86 files changed
+507
-4111
No files matched your search
@@ -1,64 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { extractFaqsFromHtml, generateFAQPageSchema } from '../extractFaqs';
|
||||
|
||||
describe('extractFaqsFromHtml and generateFAQPageSchema (SEO-P1-07)', () => {
|
||||
it('extracts FAQs from HTML5 details and summary tags', () => {
|
||||
const html = `
|
||||
<article>
|
||||
<h1>مراقبت از مفاصل سگ</h1>
|
||||
<details>
|
||||
<summary>آیا این مکمل برای سگ نژاد بزرگ مناسب است؟</summary>
|
||||
<p>بله، دوز مشخص بر اساس وزن روی بستهبندی درج شده است.</p>
|
||||
</details>
|
||||
<details>
|
||||
<summary>مدت دوره درمان چقدر است؟</summary>
|
||||
حداقل ۴ الی ۶ هفته مصرف مداوم توصیه میشود.
|
||||
</details>
|
||||
</article>
|
||||
`;
|
||||
const faqs = extractFaqsFromHtml(html);
|
||||
expect(faqs).toHaveLength(2);
|
||||
expect(faqs[0].question).toBe('آیا این مکمل برای سگ نژاد بزرگ مناسب است؟');
|
||||
expect(faqs[0].answer).toBe('بله، دوز مشخص بر اساس وزن روی بستهبندی درج شده است.');
|
||||
expect(faqs[1].question).toBe('مدت دوره درمان چقدر است؟');
|
||||
expect(faqs[1].answer).toBe('حداقل ۴ الی ۶ هفته مصرف مداوم توصیه میشود.');
|
||||
|
||||
const schema = generateFAQPageSchema(faqs);
|
||||
expect(schema).not.toBeNull();
|
||||
expect(schema?.['@type']).toBe('FAQPage');
|
||||
expect(schema?.mainEntity).toHaveLength(2);
|
||||
expect(schema?.mainEntity[0].name).toBe('آیا این مکمل برای سگ نژاد بزرگ مناسب است؟');
|
||||
expect(schema?.mainEntity[0].acceptedAnswer.text).toBe('بله، دوز مشخص بر اساس وزن روی بستهبندی درج شده است.');
|
||||
});
|
||||
|
||||
it('extracts FAQs from accordion or FAQ class structures', () => {
|
||||
const html = `
|
||||
<div class="faq-item">
|
||||
<h4 class="accordion-title">چگونه اصالت محصول را بررسی کنیم؟</h4>
|
||||
<div class="accordion-content">با اسکن کد QR و استعلام شماره بچ در سایت شرکت کنینا.</div>
|
||||
</div>
|
||||
`;
|
||||
const faqs = extractFaqsFromHtml(html);
|
||||
expect(faqs).toHaveLength(1);
|
||||
expect(faqs[0].question).toBe('چگونه اصالت محصول را بررسی کنیم؟');
|
||||
expect(faqs[0].answer).toBe('با اسکن کد QR و استعلام شماره بچ در سایت شرکت کنینا.');
|
||||
});
|
||||
|
||||
it('extracts FAQs from heading questions followed by paragraph answers', () => {
|
||||
const html = `
|
||||
<h2>پرسش: آیا کنینا محصولات ساخت آلمان هستند؟</h2>
|
||||
<p>تمامی محصولات در کشور آلمان تحت استانداردهای دارویی اروپا تولید و بستهبندی میشوند.</p>
|
||||
`;
|
||||
const faqs = extractFaqsFromHtml(html);
|
||||
expect(faqs).toHaveLength(1);
|
||||
expect(faqs[0].question).toBe('پرسش: آیا کنینا محصولات ساخت آلمان هستند؟');
|
||||
expect(faqs[0].answer).toContain('تمامی محصولات در کشور آلمان');
|
||||
});
|
||||
|
||||
it('returns empty array and null schema when no FAQs are found', () => {
|
||||
const html = `<p>یک مقاله بدون هرگونه بخش پرسش و پاسخ.</p>`;
|
||||
const faqs = extractFaqsFromHtml(html);
|
||||
expect(faqs).toHaveLength(0);
|
||||
expect(generateFAQPageSchema(faqs)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,29 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
|
||||
vi.mock('next/font/local', () => ({
|
||||
default: vi.fn((opts) => ({
|
||||
variable: opts.variable,
|
||||
className: 'mock-font',
|
||||
src: opts.src,
|
||||
preload: opts.preload,
|
||||
display: opts.display,
|
||||
})),
|
||||
}));
|
||||
|
||||
describe('Local font configuration and preloading (SEO-P2-16)', () => {
|
||||
it('configures Lalezar as a local font with WOFF2 and preload enabled', async () => {
|
||||
const { lalezar } = await import('../fonts');
|
||||
expect(lalezar).toBeDefined();
|
||||
expect(lalezar.variable).toBe('--font-lalezar');
|
||||
expect((lalezar as any).preload).toBe(true);
|
||||
expect((lalezar as any).display).toBe('swap');
|
||||
expect((lalezar as any).src[0].path).toContain('Lalezar-Regular.woff2');
|
||||
});
|
||||
|
||||
it('configures Vazirmatn as a local font with preload enabled', async () => {
|
||||
const { vazirmatn } = await import('../fonts');
|
||||
expect(vazirmatn).toBeDefined();
|
||||
expect(vazirmatn.variable).toBe('--font-vazir');
|
||||
expect((vazirmatn as any).preload).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,153 +0,0 @@
|
||||
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');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,101 +0,0 @@
|
||||
export interface FAQItem {
|
||||
question: string;
|
||||
answer: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts question and answer pairs from rich HTML content or structured blog data.
|
||||
* Supports HTML5 <details><summary>, CSS accordion/faq classes, and question headings with paragraph answers.
|
||||
*/
|
||||
export function extractFaqsFromHtml(html: string): FAQItem[] {
|
||||
if (!html || typeof html !== 'string') return [];
|
||||
const faqs: FAQItem[] = [];
|
||||
|
||||
// 1. HTML5 <details><summary>Question</summary>Answer...</details>
|
||||
const detailsRegex = /<details[^>]*>([\s\S]*?)<\/details>/gi;
|
||||
let detailsMatch;
|
||||
while ((detailsMatch = detailsRegex.exec(html)) !== null) {
|
||||
const block = detailsMatch[1];
|
||||
const summaryMatch = /<summary[^>]*>([\s\S]*?)<\/summary>/i.exec(block);
|
||||
if (summaryMatch) {
|
||||
const question = summaryMatch[1].replace(/<[^>]+>/g, '').trim();
|
||||
const answerHtml = block.replace(/<summary[^>]*>[\s\S]*?<\/summary>/i, '');
|
||||
const answer = answerHtml.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
|
||||
if (question && answer && !faqs.some((f) => f.question === question)) {
|
||||
faqs.push({ question, answer });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Class-based Accordion or FAQ items:
|
||||
// e.g. <div class="accordion-item"><h3 class="accordion-title">Q</h3><div class="accordion-content">A</div></div>
|
||||
// Use regex looking forward to next item or end of string
|
||||
const itemSplitRegex = /<(?:div|article|section|li)[^>]*class=["'][^"']*(?:faq-item|accordion-item|faq-box|qa-item)[^"']*["'][^>]*>/gi;
|
||||
const itemIndices: number[] = [];
|
||||
let itemMatch;
|
||||
while ((itemMatch = itemSplitRegex.exec(html)) !== null) {
|
||||
itemIndices.push(itemMatch.index);
|
||||
}
|
||||
|
||||
for (let i = 0; i < itemIndices.length; i++) {
|
||||
const start = itemIndices[i];
|
||||
const end = i + 1 < itemIndices.length ? itemIndices[i + 1] : html.length;
|
||||
const block = html.substring(start, end);
|
||||
|
||||
const qMatch =
|
||||
/<[^>]*class=["'][^"']*(?:question|faq-q|accordion-title|accordion-header|faq-header)[^"']*["'][^>]*>([\s\S]*?)<\/[^>]+>/i.exec(
|
||||
block
|
||||
);
|
||||
const aMatch =
|
||||
/<[^>]*class=["'][^"']*(?:answer|faq-a|accordion-content|accordion-body|faq-body)[^"']*["'][^>]*>([\s\S]*?)<\/[^>]+>/i.exec(
|
||||
block
|
||||
);
|
||||
if (qMatch && aMatch) {
|
||||
const question = qMatch[1].replace(/<[^>]+>/g, '').trim();
|
||||
const answer = aMatch[1].replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
|
||||
if (question && answer && !faqs.some((f) => f.question === question)) {
|
||||
faqs.push({ question, answer });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Headings with questions followed immediately by paragraph answers:
|
||||
// e.g. <h2>پرسش: آیا این مکمل برای سگ مفید است؟</h2> <p>بله، کاملاً مفید است.</p>
|
||||
const headingRegex = /<h[2-4][^>]*>([\s\S]*?)<\/h[2-4]>\s*<p[^>]*>([\s\S]*?)<\/p>/gi;
|
||||
let headingMatch;
|
||||
while ((headingMatch = headingRegex.exec(html)) !== null) {
|
||||
const rawHeading = headingMatch[1].replace(/<[^>]+>/g, '').trim();
|
||||
const rawParagraph = headingMatch[2].replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
|
||||
if (
|
||||
(rawHeading.endsWith('?') ||
|
||||
rawHeading.endsWith('؟') ||
|
||||
/^(?:پرسش|سوال|سؤال|آیا|چگونه|چرا|چه|کدام)\s*[:؛-]?/i.test(rawHeading)) &&
|
||||
rawParagraph.length > 5
|
||||
) {
|
||||
if (!faqs.some((f) => f.question === rawHeading)) {
|
||||
faqs.push({ question: rawHeading, answer: rawParagraph });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return faqs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a Schema.org FAQPage structured data entity if valid FAQs exist.
|
||||
*/
|
||||
export function generateFAQPageSchema(faqs: FAQItem[]) {
|
||||
if (!faqs || faqs.length === 0) return null;
|
||||
return {
|
||||
'@context': 'https://schema.org',
|
||||
'@type': 'FAQPage',
|
||||
mainEntity: faqs.map((faq) => ({
|
||||
'@type': 'Question',
|
||||
name: faq.question,
|
||||
acceptedAnswer: {
|
||||
'@type': 'Answer',
|
||||
text: faq.answer,
|
||||
},
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Lalezar } from 'next/font/google';
|
||||
import localFont from 'next/font/local';
|
||||
|
||||
export const vazirmatn = localFont({
|
||||
@@ -13,16 +14,10 @@ export const vazirmatn = localFont({
|
||||
preload: true,
|
||||
});
|
||||
|
||||
export const lalezar = localFont({
|
||||
src: [
|
||||
{
|
||||
path: '../public/fonts/Lalezar-Regular.woff2',
|
||||
weight: '400',
|
||||
style: 'normal',
|
||||
},
|
||||
],
|
||||
export const lalezar = Lalezar({
|
||||
weight: '400',
|
||||
subsets: ['arabic'],
|
||||
variable: '--font-lalezar',
|
||||
display: 'swap',
|
||||
fallback: ['cursive', 'system-ui', 'sans-serif'],
|
||||
preload: true,
|
||||
preload: false,
|
||||
});
|
||||
@@ -1,32 +0,0 @@
|
||||
import sanitizeHtml from "sanitize-html";
|
||||
|
||||
const allowedTags = Array.from(new Set([
|
||||
...sanitizeHtml.defaults.allowedTags,
|
||||
"img", "iframe", "figure", "figcaption", "table", "thead", "tbody", "tfoot",
|
||||
"tr", "th", "td", "video", "source", "details", "summary",
|
||||
]));
|
||||
|
||||
export function sanitizeBlogHtml(content: unknown): string {
|
||||
if (typeof content !== "string" || !content) return "";
|
||||
|
||||
return sanitizeHtml(content, {
|
||||
allowedTags,
|
||||
allowedAttributes: {
|
||||
...sanitizeHtml.defaults.allowedAttributes,
|
||||
"*": ["class", "id", "dir", "lang", "title"],
|
||||
a: ["href", "name", "target", "rel", "class", "title"],
|
||||
img: ["src", "alt", "title", "width", "height", "loading", "class"],
|
||||
iframe: ["src", "title", "width", "height", "allow", "allowfullscreen", "frameborder", "scrolling", "loading", "class"],
|
||||
video: ["src", "poster", "controls", "preload", "width", "height", "class"],
|
||||
source: ["src", "type"],
|
||||
td: ["colspan", "rowspan", "class"],
|
||||
th: ["colspan", "rowspan", "scope", "class"],
|
||||
},
|
||||
allowedSchemes: ["http", "https", "mailto", "tel"],
|
||||
allowedSchemesByTag: { img: ["http", "https", "data"] },
|
||||
allowedIframeHostnames: ["www.youtube.com", "youtube.com", "www.aparat.com", "aparat.com"],
|
||||
transformTags: {
|
||||
a: sanitizeHtml.simpleTransform("a", { rel: "noopener noreferrer" }, true),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -277,10 +277,9 @@ 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 = options.canonicalPath
|
||||
? `${canonicalBaseUrl.replace(/\/$/, '')}${options.canonicalPath.startsWith('/') ? options.canonicalPath : `/${options.canonicalPath}`}`
|
||||
: (texts[`${pageKey}_canonical`] || `${canonicalBaseUrl.replace(/\/$/, '')}${relativePath}`);
|
||||
const canonicalUrl = explicitCanonical || `${canonicalBaseUrl.replace(/\/$/, '')}${relativePath}`;
|
||||
|
||||
const image = options.ogImage || ogImageUrl;
|
||||
|
||||
|
||||
@@ -25,23 +25,3 @@ export function isProductOutOfStock(product?: {
|
||||
if (product.packageSize !== undefined && product.packageSize !== null && Number(product.packageSize) <= 0) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
export function normalizePersianText(input: string | undefined | null): string {
|
||||
if (!input) return "";
|
||||
return input
|
||||
.toString()
|
||||
.toLowerCase()
|
||||
.replace(/[\u200B-\u200D\uFEFF]/g, "")
|
||||
.replace(/[\u200C]/g, " ")
|
||||
.replace(/[يیى]/g, "ی")
|
||||
.replace(/[ك]/g, "ک")
|
||||
.replace(/[ة]/g, "ه")
|
||||
.replace(/[أإآ]/g, "ا")
|
||||
.replace(/[ؤ]/g, "و")
|
||||
.replace(/[ء]/g, "")
|
||||
.replace(/[\u064B-\u065F]/g, "")
|
||||
.replace(/[۰-۹]/g, d => "0123456789"["۰۱۲۳۴۵۶۷۸۹".indexOf(d)])
|
||||
.replace(/[٠-٩]/g, d => "0123456789"["٠١٢٣٤٥٦٧٨٩".indexOf(d)])
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
Reference in new issue
Block a user