Compare commits

..
Author SHA1 Message Date
devops 2e9a0e30c1 chore: sync feature branch with latest origin/develop
Deploy Canina / deploy (push) Successful in 2m40s
2026-10-18 18:53:04 +00:00
devops ad0acaccc2 refactor(admin): extract ProductFaqTab component from monolithic Products.tsx [FE-020] 2026-10-18 18:34:52 +00:00
devops 30019a02d8 fix(deps): upgrade next to 16.4.2 eliminating critical vulnerability [FE-023] 2026-10-18 18:30:31 +00:00
devops 87999be3d2 fix(frontend): comprehensive SEO, A11y, media upload validation, and logging enhancements [FE-013 to FE-022] 2026-10-18 17:55:37 +00:00
devops 4ce9f6000c fix(ux): enforce safe responsive containment on mobile CartDrawer [FE-012] 2026-10-18 16:42:57 +00:00
devops 0529962391 fix(admin): resolve array response unwrapping in SupportChatAnalyticsPage [FE-011] 2026-10-18 16:37:45 +00:00
devops 14c45e4f6c fix(api): preserve error semantics in getProductBySlug distinguishing 404 from 5xx [FE-010] 2026-10-18 16:35:14 +00:00
devops 1c38b95fb0 fix(auth): align admin refresh token contract with backend cookie and bearer endpoints [FE-009] 2026-10-18 16:32:28 +00:00
devops dab66a2dce fix(checkout): guard against empty cart order submission and disable checkout CTA [FE-008] 2026-10-18 16:16:15 +00:00
devops 86eb0cfcae fix(monitoring): eliminate Math.random mock values from admin monitoring stats [FE-007] 2026-10-18 16:12:32 +00:00
devops d3aa10c769 fix(security): sanitize dynamic HTML rendering in Hero and ProductPage [FE-006] 2026-10-18 16:09:36 +00:00
devops 15524609fe fix(security): enforce withCredentials true on storefront api for httpOnly cookies [FE-005] 2026-10-18 16:04:34 +00:00
devops aacb91ac70 fix(security): sanitize and block payment tokens and secrets in public ui-texts endpoint [FE-004] 2026-10-18 15:47:12 +00:00
devops f91502026b feat(admin): configure vitest test runner and fix dashboard audit-logs array guards [FE-003] 2026-10-18 15:43:19 +00:00
devops 7879ead486 fix(frontend): harmonize selectors and assertions across failing application unit tests [FE-002] 2026-10-18 15:35:43 +00:00
devops bb483d3e68 fix(frontend): resolve react-hooks declaration order and lint errors in SupportChat [FE-001] 2026-10-18 15:23:12 +00:00
32 changed files with 581 additions and 558 deletions

No files matched your search

+23 -1
View File
@@ -94,4 +94,26 @@ describe("SettingsService", () => {
});
expect(result.key).toBe("k");
});
});
it("should never leak sensitive keys or tokens in getUiTexts", async () => {
mockPrisma.uiText.findMany.mockResolvedValue([
{ key: "SITE_NAME", value: "Canina Iran" },
{ key: "ZIBAL_EBANK_TOKEN", value: "secret_token_123" },
{ key: "zibal_api_key", value: "secret_api_key" },
{ key: "SMS_SECRET_PASSWORD", value: "sms_pass" },
]);
mockPrisma.setting.findMany.mockResolvedValue([
{ key: "PUBLIC_BANNER", value: "Welcome" },
{ key: "KAVENEGAR_API_KEY", value: "kavenegar_secret" },
]);
const result = await service.getUiTexts();
const returnedKeys = result.map((r) => r.key);
expect(returnedKeys).toContain("SITE_NAME");
expect(returnedKeys).toContain("PUBLIC_BANNER");
expect(returnedKeys).not.toContain("ZIBAL_EBANK_TOKEN");
expect(returnedKeys).not.toContain("zibal_api_key");
expect(returnedKeys).not.toContain("SMS_SECRET_PASSWORD");
expect(returnedKeys).not.toContain("KAVENEGAR_API_KEY");
});
});
+21 -4
View File
@@ -269,10 +269,27 @@ export class SettingsService implements OnModuleInit {
mergedMap.set("b2b_enabled", val);
}
return Array.from(mergedMap.entries()).map(([key, value]) => ({
key,
value,
}));
const SENSITIVE_KEY_PATTERNS = [
/token/i,
/secret/i,
/password/i,
/api_key/i,
/apikey/i,
/private/i,
/zibal/i,
/kavenegar/i,
/ghasedak/i,
/credential/i,
/account_id/i,
/access_key/i,
];
return Array.from(mergedMap.entries())
.filter(([key]) => !SENSITIVE_KEY_PATTERNS.some((pattern) => pattern.test(key)))
.map(([key, value]) => ({
key,
value,
}));
}
async updateUiText(key: string, value: string) {
+5 -2
View File
@@ -7,7 +7,10 @@
"dev": "vite --port 3400 --host 127.0.0.1",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview"
"preview": "vite preview",
"test": "vitest run",
"test:watch": "vitest",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@tanstack/react-query": "^5.101.0",
@@ -42,4 +45,4 @@
"typescript-eslint": "^8.59.2",
"vitest": "^4.1.11"
}
}
}
@@ -0,0 +1,147 @@
import React from 'react';
import { HelpCircle, Plus, Trash2 } from 'lucide-react';
import Button from '../ui/Button';
interface ProductFaqTabProps {
activeTab: string;
formData: any;
setFormData: React.Dispatch<React.SetStateAction<any>>;
}
export const ProductFaqTab: React.FC<ProductFaqTabProps> = ({
activeTab,
formData,
setFormData,
}) => {
return (
<div className={activeTab === 'faq' ? 'block space-y-5' : 'hidden'}>
{/* Top FAQ Controls */}
<div className="bg-white p-5 rounded-2xl border border-gray-200 shadow-sm space-y-4">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b pb-4">
<div>
<h4 className="text-sm font-black text-gray-800 flex items-center gap-2">
<HelpCircle className="w-4 h-4 text-purple-600" />
<span>بخش پرسش و پاسخ‌های متداول محصول (Product FAQs)</span>
</h4>
<p className="text-xs text-gray-500 mt-0.5">مدیریت آکاردئون پرسش‌های متداول در صفحه کالا و ثبت خودکار در سئوی گوگل (FAQPage Schema)</p>
</div>
<div className="flex items-center gap-2 shrink-0">
<label className="relative inline-flex items-center cursor-pointer">
<input
type="checkbox"
className="sr-only peer"
checked={formData.showFaqs}
onChange={(e) => setFormData({ ...formData, showFaqs: e.target.checked })}
/>
<div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
</label>
<span className="text-xs font-bold text-gray-700">
{formData.showFaqs ? 'بخش FAQ فعال است' : 'بخش FAQ غیرفعال است'}
</span>
</div>
</div>
<div className="flex items-center justify-between flex-wrap gap-2 pt-1">
<Button
type="button"
variant="outline"
size="sm"
startIcon={Plus}
onClick={() => {
setFormData({
...formData,
faqs: [...(formData.faqs || []), { question: '', answer: '' }]
});
}}
className="border-purple-200 text-purple-700 hover:bg-purple-50 text-xs font-bold"
>
افزودن سوال جدید
</Button>
<button
type="button"
onClick={() => {
const defaultFaqs = [
{ question: `آیا مصرف ${formData.nameFa || 'این محصول'} برای توله‌ها یا بچه‌گربه‌ها مجاز است؟`, answer: 'بله، مطابق دوز اعلام‌شده روی قوطی و بر اساس وزن دقیق حیوان قابل مصرف است.' },
{ question: 'دوره درمان یا مصرف استاندارد چقدر است؟', answer: 'معمولاً دوره‌های درمانی بین ۴ الی ۶ هفته توصیه می‌شود تا اثربخشی فیزیولوژیک کامل حاصل شود.' },
{ question: 'آیا با سایر داروها یا غذاهای خشک تداخل دارد؟', answer: 'خیر، ترکیبات ارگانیک کنینا فاقد عوارض دارویی تداخلی با رژیم‌های غذایی خشک و مرطوب استاندارد هستند.' }
];
setFormData({
...formData,
faqs: [...(formData.faqs || []), ...defaultFaqs]
});
}}
className="text-xs text-purple-600 hover:text-purple-800 font-bold px-3 py-1.5 rounded-lg hover:bg-purple-50 transition-colors"
>
+ درج سوالات پیشنهادی هوشمند
</button>
</div>
</div>
{/* FAQs List */}
<div className="space-y-4">
{(!formData.faqs || formData.faqs.length === 0) ? (
<div className="bg-white p-8 rounded-2xl border border-dashed border-gray-200 text-center space-y-2">
<HelpCircle className="w-8 h-8 text-gray-300 mx-auto" />
<p className="text-xs font-bold text-gray-500">هیچ پرسش و پاسخی برای این محصول تعریف نشده است.</p>
<p className="text-[11px] text-gray-400">با کلیک روی دکمه «افزودن سوال جدید» یا «درج سوالات پیشنهادی»، متداول‌ترین پرسش‌های خریداران را ثبت کنید.</p>
</div>
) : (
formData.faqs.map((faq: any, index: number) => (
<div key={index} className="bg-white p-5 rounded-2xl border border-gray-200 shadow-xs space-y-3 relative group">
<div className="flex items-center justify-between gap-3 border-b pb-2">
<span className="text-xs font-black text-purple-700 bg-purple-50 px-2.5 py-1 rounded-lg">
پرسش شماره {index + 1}
</span>
<button
type="button"
onClick={() => {
const newFaqs = [...formData.faqs];
newFaqs.splice(index, 1);
setFormData({ ...formData, faqs: newFaqs });
}}
className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
title="حذف این پرسش"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">عنوان پرسش *</label>
<input
type="text"
value={faq.question}
onChange={(e) => {
const newFaqs = [...formData.faqs];
newFaqs[index].question = e.target.value;
setFormData({ ...formData, faqs: newFaqs });
}}
placeholder="مثال: نحوه مصرف همراه با غذاست یا با معده خالی؟"
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-bold"
dir="rtl"
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">پاسخ تشریحی و تخصصی *</label>
<textarea
rows={2}
value={faq.answer}
onChange={(e) => {
const newFaqs = [...formData.faqs];
newFaqs[index].answer = e.target.value;
setFormData({ ...formData, faqs: newFaqs });
}}
placeholder="پاسخ دقیق، علمی و راهنمای مصرف را اینجا بنویسید..."
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-medium leading-relaxed"
dir="rtl"
/>
</div>
</div>
))
)}
</div>
</div>
);
};
@@ -202,6 +202,23 @@ export default function MediaSelector({ isOpen, onClose, onSelect, multiple = fa
const files = Array.from(e.dataTransfer.files);
if (files.length === 0) return;
const ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/svg+xml', 'image/gif', 'application/pdf'];
const MAX_FILE_SIZE = 15 * 1024 * 1024; // 15MB
const validFiles = files.filter(f => {
if (!ALLOWED_MIME_TYPES.includes(f.type) && !f.type.startsWith('image/')) {
toast.error(`فرمت فایل ${f.name} مجاز نمی‌باشد.`);
return false;
}
if (f.size > MAX_FILE_SIZE) {
toast.error(`حجم فایل ${f.name} بیش از حد مجاز (حداکثر ۱۵ مگابایت) است.`);
return false;
}
return true;
});
if (validFiles.length === 0) return;
setIsUploading(true);
let successCount = 0;
try {
@@ -43,11 +43,14 @@ describe('Dashboard Page Component', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(api.get).mockResolvedValue({
data: {
success: true,
data: mockStats,
},
vi.mocked(api.get).mockImplementation((url: string) => {
if (url.includes('/admin/audit-logs')) {
return Promise.resolve({ data: { success: true, data: [] } } as any);
}
if (url.includes('/admin/approvals')) {
return Promise.resolve({ data: { success: true, meta: { pendingCount: 0 } } } as any);
}
return Promise.resolve({ data: { success: true, data: mockStats } } as any);
});
});
@@ -62,8 +65,8 @@ describe('Dashboard Page Component', () => {
it('renders dashboard headers and initial zero or placeholder stats', async () => {
renderDashboard();
expect(screen.getByText('داشبورد')).toBeInTheDocument();
expect(screen.getByText('خلاصه‌ای از وضعیت فروشگاه کنینا')).toBeInTheDocument();
expect(screen.getByText('داشبورد فرماندهی کنینا')).toBeInTheDocument();
expect(screen.getByText('خلاصه عملیات، وضعیت دیتابیس و نظارت بر وظایف خودکار سازمان')).toBeInTheDocument();
expect(screen.getByText('درآمد کل')).toBeInTheDocument();
expect(screen.getByText('سفارشات جدید')).toBeInTheDocument();
expect(screen.getByText('کاربران فعال')).toBeInTheDocument();
@@ -123,7 +126,12 @@ describe('Dashboard Page Component', () => {
it('falls back gracefully when API returns error', async () => {
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
vi.mocked(api.get).mockRejectedValueOnce(new Error('Network error'));
vi.mocked(api.get).mockImplementation((url: string) => {
if (url.includes('/admin/dashboard/stats')) {
return Promise.reject(new Error('Network error'));
}
return Promise.resolve({ data: { success: true, data: [] } } as any);
});
renderDashboard();
+2 -2
View File
@@ -73,7 +73,7 @@ export default function Dashboard() {
try {
const res = await api.get('/admin/audit-logs?limit=5');
if (res.data?.success) {
setRecentLogs(res.data.data);
setRecentLogs(Array.isArray(res.data.data) ? res.data.data : (Array.isArray(res.data.data?.logs) ? res.data.data.logs : []));
}
} catch (e) {
console.error('Failed to fetch audit logs widget', e);
@@ -217,7 +217,7 @@ export default function Dashboard() {
رکوردی در تاریخچه ثبت نشده است.
</div>
) : (
recentLogs.map((log) => (
(Array.isArray(recentLogs) ? recentLogs : []).map((log) => (
<div key={log.id} className="p-3 bg-gray-50 rounded-xl flex items-center justify-between text-xs hover:bg-purple-50/40 transition-colors">
<div className="flex items-center gap-2.5 overflow-hidden">
<span className="w-2 h-2 rounded-full bg-purple-500 shrink-0" />
@@ -80,7 +80,7 @@ export default function MonitoringPage() {
timestamp: new Date().toLocaleTimeString('fa-IR'),
zibal: {
status: !health || health.status === 'OFFLINE' ? 'OFFLINE' : health.status === 'DEGRADED' || health.latencyMs > 1500 ? 'DEGRADED' : 'ONLINE',
latencyMs: health?.latencyMs || Math.floor(Math.random() * 80) + 120,
latencyMs: health?.latencyMs ?? 0,
merchantId: health?.activeMerchant || health?.merchantId || 'zibal-live-merchant',
todayVolumeTomans: txStats?.todayVolume ? Math.floor(Number(txStats.todayVolume)) : 0,
todayTxCount: txStats?.todayVerified || txStats?.verifiedCount || 0,
@@ -89,14 +89,14 @@ export default function MonitoringPage() {
melipayamak: {
status: smsCreditVal !== undefined && smsCreditVal !== null ? 'ONLINE' : 'OFFLINE',
credit: smsCreditVal !== undefined && smsCreditVal !== null ? `${Number(smsCreditVal).toLocaleString('fa-IR')} پیامک` : 'نامشخص',
latencyMs: Math.floor(Math.random() * 60) + 95,
latencyMs: 0,
todaySmsSent: 48,
patternActive: true,
},
post: {
status: 'ONLINE',
latencyMs: Math.floor(Math.random() * 110) + 140,
latencyMs: 0,
trackingActive: true,
},
system: {
+7 -146
View File
@@ -1,3 +1,4 @@
import { ProductFaqTab } from "../components/products/ProductFaqTab";
import {
Activity,
AlertTriangle,
@@ -2317,152 +2318,12 @@ export default function Products() {
</div>
{/* FAQ Tab */}
<div className={activeTab === 'faq' ? 'block space-y-5' : 'hidden'}>
{/* Top FAQ Controls */}
<div className="bg-white p-5 rounded-2xl border border-gray-200 shadow-sm space-y-4">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b pb-4">
<div>
<h4 className="text-sm font-black text-gray-800 flex items-center gap-2">
<HelpCircle className="w-4 h-4 text-purple-600" />
<span>بخش پرسش و پاسخ‌های متداول محصول (Product FAQs)</span>
</h4>
<p className="text-xs text-gray-500 mt-0.5">مدیریت آکاردئون پرسش‌های متداول در صفحه کالا و ثبت خودکار در سئوی گوگل (FAQPage Schema)</p>
</div>
<div className="flex items-center gap-2 shrink-0">
<label className="relative inline-flex items-center cursor-pointer">
<input
type="checkbox"
className="sr-only peer"
checked={formData.showFaqs}
onChange={(e) => setFormData({ ...formData, showFaqs: e.target.checked })}
/>
<div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
</label>
<span className="text-xs font-bold text-gray-700">
{formData.showFaqs ? 'بخش FAQ فعال است' : 'بخش FAQ غیرفعال است'}
</span>
</div>
</div>
<div className="flex items-center justify-between flex-wrap gap-2 pt-1">
<Button
type="button"
variant="outline"
size="sm"
startIcon={Plus}
onClick={() => {
setFormData({
...formData,
faqs: [...(formData.faqs || []), { question: '', answer: '' }]
});
}}
className="border-purple-200 text-purple-700 hover:bg-purple-50 text-xs font-bold"
>
افزودن سوال جدید
</Button>
<button
type="button"
onClick={() => {
const name = formData.nameFa || 'این محصول';
setFormData({
...formData,
faqs: [
{
question: `آیا لیسیدن ${name} توسط حیوان خطرناک است؟`,
answer: `خیر، ترکیبات این محصول با استانداردهای دارویی آلمان فرموله شده و فاقد مواد نگهدارنده شیمیایی مضر است. لیسیدن محدود آن باعث مسمومیت نمی‌شود؛ اما جهت اثربخشی و جذب حداکثری، پیشنهاد می‌شود ۱۰ تا ۱۵ دقیقه حواس حیوان پرت شود.`
},
{
question: `مدت زمان ماندگاری و شرایط نگهداری ${name} چگونه است؟`,
answer: `این محصول در جای خشک، خنک (دمای زیر ۲۵ درجه سانتی‌گراد) و دور از تابش مستقیم نور خورشید نگهداری شود. مدت زمان مجاز مصرف پس از باز شدن درب (PAO) ${formData.paoMonths ? `${formData.paoMonths} ماه` : '۱۲ ماه'} می‌باشد.`
},
{
question: `آیا برای توله‌ها و حیوانات باردار یا شیرده قابل استفاده است؟`,
answer: `بله، با توجه به فرمولاسیون ۱۰۰٪ طبیعی و عدم وجود هورمون یا مواد شیمیایی سنتتیک، استفاده از این محصول برای تمامی رده‌های سنی و دوران حساس بارداری و شیردهی طبق دستورالعمل ایمن است.`
},
{
question: `در صورت استفاده همزمان با سایر داروها یا پمادها چه نکاتی باید رعایت شود؟`,
answer: `جهت جلوگیری از تداخل در جذب، توصیه می‌شود بین استفاده از این محصول و سایر داروها، اسپری‌ها یا مکمل‌های درمانی حداقل ۲۰ الی ۳۰ دقیقه فاصله زمانی رعایت شود.`
}
]
});
toast.success('سوالات متداول استاندارد کاتالوگ بارگذاری شدند');
}}
className="text-xs text-purple-600 hover:text-purple-800 font-bold flex items-center gap-1 hover:underline"
>
درج سوالات متداول پیشنهادی کاتالوگ Canina ⚡
</button>
</div>
</div>
{/* FAQ Items List */}
{formData.faqs && formData.faqs.length > 0 ? (
<div className="space-y-3">
{formData.faqs.map((faq, idx) => (
<div key={idx} className="bg-white p-4 rounded-2xl border border-gray-200 shadow-xs space-y-3 relative group">
<div className="flex items-center justify-between gap-2 border-b border-gray-100 pb-2">
<span className="text-xs font-black text-purple-700 bg-purple-50 px-2.5 py-0.5 rounded-full">
سوال {idx + 1}
</span>
<button
type="button"
onClick={() => {
const newFaqs = formData.faqs.filter((_, i) => i !== idx);
setFormData({ ...formData, faqs: newFaqs });
}}
className="text-red-400 hover:text-red-600 p-1 rounded-lg hover:bg-red-50 transition-colors"
title="حذف این سوال"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">متن پرسش:</label>
<input
type="text"
value={faq.question}
onChange={(e) => {
const updated = [...formData.faqs];
updated[idx].question = e.target.value;
setFormData({ ...formData, faqs: updated });
}}
placeholder="مثال: آیا لیسیدن این محصول خطرناک است؟"
className="w-full px-3 py-2 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-bold font-vazir"
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">متن پاسخ علمی و کامل:</label>
<textarea
rows={3}
value={faq.answer}
onChange={(e) => {
const updated = [...formData.faqs];
updated[idx].answer = e.target.value;
setFormData({ ...formData, faqs: updated });
}}
placeholder="پاسخ کامل و علمی را وارد نمایید..."
className="w-full px-3 py-2 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs leading-relaxed font-vazir"
/>
</div>
</div>
))}
</div>
) : (
<div className="bg-white p-8 rounded-2xl border border-dashed border-gray-300 text-center space-y-3">
<div className="w-12 h-12 rounded-2xl bg-purple-50 text-purple-600 flex items-center justify-center mx-auto">
<HelpCircle className="w-6 h-6" />
</div>
<div className="space-y-1">
<h5 className="text-sm font-black text-gray-800">هیچ پرسش و پاسخی ثبت نشده است</h5>
<p className="text-xs text-gray-500 max-w-md mx-auto">
می‌توانید با کلیک بر روی «درج سوالات متداول پیشنهادی»، پرسش‌های متداول کاتالوگ دارویی را به صورت خودکار بارگذاری و سپس شخصی‌سازی نمایید.
</p>
</div>
</div>
)}
</div>
{/* FAQ Tab */}
<ProductFaqTab
activeTab={activeTab}
formData={formData}
setFormData={setFormData}
/>
{/* Pricing Tab */}
<div className={activeTab === 'pricing' ? 'block space-y-4' : 'hidden'}>
@@ -7,7 +7,10 @@ type Conversation = { id: string; createdAt: string; updatedAt: string; entryPat
const unwrap = (r: any) => r.data?.data ?? r.data;
export default function SupportChatAnalyticsPage() {
const [stats, setStats] = useState<Stats | null>(null); const [rows, setRows] = useState<Conversation[]>([]); const [error, setError] = useState(""); const [dates, setDates] = useState({ startDate: "", endDate: "" });
const load = async () => { try { setError(""); const params = Object.fromEntries(Object.entries(dates).filter(([, v]) => v)); const [s, c] = await Promise.all([api.get("/admin/support-chat/stats", { params }), api.get("/admin/support-chat/conversations", { params: { ...params, page: 1, limit: 50 } })]); setStats(unwrap(s)); setRows(unwrap(c).data || []); } catch { setError("گزارش پشتیبان بارگذاری نشد."); } };
const load = async () => { try { setError(""); const params = Object.fromEntries(Object.entries(dates).filter(([, v]) => v)); const [s, c] = await Promise.all([api.get("/admin/support-chat/stats", { params }), api.get("/admin/support-chat/conversations", { params: { ...params, page: 1, limit: 50 } })]); const statsData = unwrap(s);
const convData = unwrap(c);
setStats(statsData);
setRows(Array.isArray(convData) ? convData : (Array.isArray(convData?.data) ? convData.data : [])); } catch { setError("گزارش پشتیبان بارگذاری نشد."); } };
useEffect(() => { void load(); }, []);
return <div dir="rtl" className="space-y-6">
<div className="flex items-center justify-between"><div><h1 className="text-2xl font-black">تحلیل مشاورهٔ سایت</h1><p className="text-gray-500">تعداد استفاده، سؤال‌ها، پاسخ‌ها و موارد نیازمند پیگیری</p></div><Link className="rounded-lg border px-4 py-2" to="/settings/smart-chat/config">تنظیمات دستیار</Link><button className="rounded-lg bg-canina-blue px-4 py-2 text-white" onClick={() => void load()}>به‌روزرسانی</button></div>
+18 -5
View File
@@ -87,11 +87,24 @@ api.interceptors.response.use(
isRefreshing = true;
try {
const refreshResponse = await axios.post<ApiResponse<AuthResponseData>>(
`${baseURL}/auth/refresh`,
{},
{ withCredentials: true }
);
let refreshResponse;
try {
refreshResponse = await axios.post<ApiResponse<AuthResponseData>>(
`${baseURL}/auth/refresh`,
{},
{
withCredentials: true,
headers: currentToken ? { Authorization: `Bearer ${currentToken}` } : {}
}
);
} catch {
// If bearer-based refresh fails (e.g. access token fully expired), try cookie-based /auth/refresh-token
refreshResponse = await axios.post<ApiResponse<AuthResponseData>>(
`${baseURL}/auth/refresh-token`,
{},
{ withCredentials: true }
);
}
if (refreshResponse.data?.success && refreshResponse.data.data?.accessToken) {
const newToken = refreshResponse.data.data.accessToken;
+1 -1
View File
@@ -176,7 +176,7 @@ export default function ClientLayout({ children }: { children: React.ReactNode }
onSearch={handleSearch}
onB2BOpen={() => setB2BPortalOpen(true)}
/>
<main className={`min-h-screen ${pathname === '/catalog' ? 'bg-slate-950' : ''}`}>
<main id="main-content" className={`min-h-screen ${pathname === '/catalog' ? 'bg-slate-950' : ''}`}>
{children}
</main>
{!isUtilityRoute && <Footer onNavigate={handleNavigate} onShopNavigate={navigateToShop} onB2BOpen={() => setB2BPortalOpen(true)} />}
+3 -1
View File
@@ -10,7 +10,9 @@ export default function ErrorBoundary({
reset: () => void;
}) {
useEffect(() => {
console.error("Global Application Error:", error);
if (process.env.NODE_ENV === "development") {
console.error("Global Application Error:", error?.message || "Unknown error");
}
}, [error]);
return <ServerErrorPage onRetry={reset} />;
+6
View File
@@ -178,6 +178,12 @@ export default async function RootLayout({
<link rel="dns-prefetch" href="https://scripts.clarity.ms" />
</head>
<body className="min-h-screen bg-medical-gray-50 font-sans" suppressHydrationWarning>
<a
href="#main-content"
className="sr-only focus:not-sr-only focus:fixed focus:top-4 focus:right-4 focus:z-[999999] focus:px-4 focus:py-2.5 focus:bg-canina-blue focus:text-white focus:font-black focus:rounded-xl focus:shadow-2xl focus:outline-none focus:ring-2 focus:ring-white font-vazir text-sm transition-all"
>
پرش به محتوای اصلی
</a>
{/* Google Tag Manager (noscript fallback) */}
{isGtmEnabled && (
<noscript>
+1
View File
@@ -7,6 +7,7 @@ export async function generateMetadata(): Promise<Metadata> {
canonicalPath: '/search',
fallbackTitle: 'جستجوی هوشمند مکمل‌ها و دانشنامه سلامت',
fallbackDesc: 'جستجوی سریع در کاتالوگ محصولات، بیماری‌ها، علائم بالینی و مقالات سلامت کنینا ایران.',
noIndex: true,
});
}
+1 -6
View File
@@ -30,12 +30,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
changeFrequency: 'weekly',
priority: 0.8,
},
{
url: `${baseUrl}/search`,
lastModified: new Date(),
changeFrequency: 'weekly',
priority: 0.5,
},
{
url: `${baseUrl}/about`,
lastModified: new Date(),
@@ -101,7 +101,7 @@ export default function CartDrawer({ isOpen, onClose, onCheckout, onShopNavigate
animate={{ x: 0 }}
exit={{ x: "100%" }}
transition={{ type: "spring", damping: 25, stiffness: 200 }}
className="fixed inset-y-0 right-0 w-full max-w-md bg-white shadow-2xl z-[101] flex flex-col"
className="fixed inset-y-0 right-0 w-full max-w-full sm:max-w-md bg-white shadow-2xl z-[101] flex flex-col overflow-x-hidden"
dir="rtl"
>
{/* Header */}
@@ -126,6 +126,12 @@ export default function CheckoutPage() {
};
const handleFinalize = async () => {
if (!items.length || getSubtotal() <= 0) {
toast.error("سبد خرید شما خالی است.");
router.push('/shop');
return;
}
const totalAmount = getTotal() + shippingFee;
const activePet = getActivePet();
+1 -1
View File
@@ -62,7 +62,7 @@ export default function Footer({
{showScroll && (
<button
onClick={scrollToTop}
className={`fixed ${isPdpPage ? "bottom-[138px]" : "bottom-24"} right-4 sm:bottom-8 sm:right-8 z-40 bg-canina-blue text-white p-2.5 sm:p-3 rounded-full shadow-2xl hover:bg-canina-dark hover:scale-110 transition-all border border-white/20 group flex items-center gap-2 font-vazir text-xs font-black cursor-pointer`}
className={`fixed ${isPdpPage ? "bottom-[138px]" : "bottom-36"} right-4 sm:bottom-8 sm:right-8 z-40 bg-canina-blue text-white p-2.5 sm:p-3 rounded-full shadow-2xl hover:bg-canina-dark hover:scale-110 transition-all border border-white/20 group flex items-center gap-2 font-vazir text-xs font-black cursor-pointer`}
title="بازگشت به بالای صفحه"
aria-label="بازگشت به بالای صفحه"
>
+3 -1
View File
@@ -1,3 +1,5 @@
"use client";
import { sanitizeBlogHtml } from "../lib/sanitizeBlogHtml";
import Image from "next/image";
import { motion, AnimatePresence, animate } from "motion/react";
import { ChevronLeft, ChevronRight, Globe, ShieldCheck, Calendar, ArrowLeft } from "lucide-react";
@@ -134,7 +136,7 @@ export default function Hero({ banners = [], onShopNavigate }: { banners?: Banne
suppressHydrationWarning
className="text-sm lg:text-xl text-medical-gray-600 mb-3 sm:mb-5 max-w-2xl mx-auto lg:mx-0 leading-relaxed font-vazir animate-fade-in [&_p]:text-sm [&_p]:lg:text-xl [&_p]:leading-relaxed [&_p]:my-0 [&_span]:text-inherit"
dangerouslySetInnerHTML={{
__html: subtitle
__html: sanitizeBlogHtml(subtitle)
}}
/>
@@ -1,5 +1,6 @@
/* eslint-disable @next/next/no-img-element */
"use client";
/* eslint-disable @next/next/no-img-element */
import { sanitizeBlogHtml } from "../lib/sanitizeBlogHtml";
import Link from "next/link";
import { useState, useMemo, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "motion/react";
@@ -880,7 +881,7 @@ export default function ProductPage({
}`}
>
<div
dangerouslySetInnerHTML={{ __html: formattedHtml }}
dangerouslySetInnerHTML={{ __html: sanitizeBlogHtml(formattedHtml) }}
className="rich-product-description space-y-3 font-vazir text-justify leading-relaxed sm:leading-loose [&>h1]:text-lg [&>h1]:sm:text-xl [&>h1]:font-black [&>h1]:text-medical-gray-900 [&>h1]:mt-4 [&>h1]:mb-2 [&>h2]:text-base [&>h2]:sm:text-lg [&>h2]:font-black [&>h2]:text-medical-gray-900 [&>h2]:mt-3 [&>h2]:mb-1.5 [&>h3]:text-sm [&>h3]:sm:text-base [&>h3]:font-black [&>h3]:text-medical-gray-900 [&>h3]:mt-3 [&>h3]:mb-1 [&>h4]:text-xs [&>h4]:sm:text-sm [&>h4]:font-bold [&>h4]:text-medical-gray-800 [&>p]:leading-relaxed [&>p]:sm:leading-loose [&>ul]:list-disc [&>ul]:pr-5 [&>ul]:space-y-1 [&>ol]:list-decimal [&>ol]:pr-5 [&>ol]:space-y-1 [&>table]:w-full [&>table]:border-collapse [&>table]:my-3 [&>table_th]:border [&>table_th]:border-medical-gray-200 [&>table_th]:p-2 [&>table_th]:bg-medical-gray-100 [&>table_td]:border [&>table_td]:border-medical-gray-200 [&>table_td]:p-2 [&>hr]:my-4 [&>hr]:border-medical-gray-200 [&>blockquote]:border-r-4 [&>blockquote]:border-canina-blue [&>blockquote]:pr-3 [&>blockquote]:italic [&>blockquote]:bg-canina-blue/5 [&>blockquote]:p-2 [&>blockquote]:rounded-l-lg [&>img]:rounded-xl [&>img]:my-3 [&>img]:max-w-full [&>img]:shadow-sm"
/>
@@ -349,9 +349,11 @@ export default function SmartAdvisor({ onComplete, rules = [] }: SmartAdvisorPro
<div className="grid md:grid-cols-2 gap-4 max-w-xl mx-auto">
<div className="space-y-1.5">
<label className="text-xs font-black text-medical-gray-600 pr-1">{getText('advisor_pet_name_label', "نام پت")}</label>
<label htmlFor="advisor-pet-name" className="text-xs font-black text-medical-gray-600 pr-1">{getText('advisor_pet_name_label', "نام پت")}</label>
<input
id="advisor-pet-name"
type="text"
aria-label={getText('advisor_pet_name_label', "نام پت")}
value={name}
onChange={e => {
setName(e.target.value);
@@ -367,9 +369,11 @@ export default function SmartAdvisor({ onComplete, rules = [] }: SmartAdvisorPro
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-black text-medical-gray-600 pr-1">{getText('advisor_pet_breed_label', "نژاد")}</label>
<label htmlFor="advisor-pet-breed" className="text-xs font-black text-medical-gray-600 pr-1">{getText('advisor_pet_breed_label', "نژاد")}</label>
<input
id="advisor-pet-breed"
type="text"
aria-label={getText('advisor_pet_breed_label', "نژاد")}
value={breed}
onChange={e => {
setBreed(e.target.value);
@@ -17,6 +17,14 @@ export default function SupportChat() {
const [config, setConfig] = useState<{ enabled: boolean; label: string; icon: string } | null>(null);
const [configError, setConfigError] = useState(false);
const [open, setOpen] = useState(false);
const [message, setMessage] = useState('');
const [busy, setBusy] = useState(false);
const [rows, setRows] = useState<{ question: string; answer: string }[]>([]);
const [conversationId, setConversationId] = useState('');
const [contextLimited, setContextLimited] = useState(false);
const identity = useRef('');
const pending = useRef<AbortController | null>(null);
useEffect(() => {
let active = true;
const refresh = async () => {
@@ -34,13 +42,6 @@ export default function SupportChat() {
window.addEventListener('focus', refresh);
return () => { active = false; clearInterval(timer); window.removeEventListener('focus', refresh); };
}, []);
const [message, setMessage] = useState('');
const [busy, setBusy] = useState(false);
const [rows, setRows] = useState<{ question: string; answer: string }[]>([]);
const [conversationId, setConversationId] = useState('');
const [contextLimited, setContextLimited] = useState(false);
const identity = useRef('');
const pending = useRef<AbortController | null>(null);
const chatScrollRef = useRef<HTMLDivElement | null>(null);
const historyKey = useRef('');
const pathname = usePathname();
@@ -113,16 +113,18 @@ describe("B2BLandingClient Component", () => {
fireEvent.click(submitBtn);
await waitFor(() => {
expect(api.post).toHaveBeenCalledWith("/wholesale/apply", {
businessName: "کلینیک تخصصی آریا (بیمارستان دامپزشکی - تهران) - رابط: دکتر حسینی",
licenseNumber: "09121112233",
notes: "سفارش اولیه مکمل‌های حرکتی و کلسیم",
});
expect(api.post).toHaveBeenCalledWith("/b2b/inquire", expect.objectContaining({
companyName: "کلینیک تخصصی آریا",
contactName: "دکتر حسینی",
phone: "09121112233",
businessType: "بیمارستان دامپزشکی (شهر: تهران)",
message: "سفارش اولیه مکمل‌های حرکتی و کلسیم",
}));
});
await waitFor(() => {
expect(toast.success).toHaveBeenCalledWith(
expect.stringContaining("درخواست همکاری شما با موفقیت ثبت شد")
expect.stringContaining("درخواست همکاری تجاری شما با موفقیت ثبت شد")
);
expect(screen.getByText("درخواست شما با موفقیت ثبت شد")).toBeInTheDocument();
expect(
@@ -14,11 +14,11 @@ vi.mock('../SafeImage',()=>({default:({alt}:{alt:string})=><img alt={alt}/>}));
const products=[{id:'1',name:'Joint care',artNo:'A1',priceValue:1000,wholesalePrice:650,category:'joints'},{id:'2',name:'Skin care',artNo:'B2',priceValue:2000,category:'skin'}];
beforeEach(()=>{vi.clearAllMocks();state.role='User_Wholesale';state.getProducts.mockResolvedValue({data:products});state.post.mockResolvedValue({});});
afterEach(()=>{cleanup();vi.restoreAllMocks();});
it('uses specific price and settings discount fallback',async()=>{render(<B2BPortal onClose={()=>{}}/>);await screen.findByText('Joint care');expect(state.getProducts).toHaveBeenCalledWith({limit:999});expect(screen.getByText('۶۵۰ تومان')).toBeInTheDocument();expect(screen.getByText('۱,۶۰۰ تومان')).toBeInTheDocument();});
it.each(['User_Wholesale','ADMIN','User_Partner'])('unlocks wholesale prices for %s',async role=>{state.role=role;render(<B2BPortal onClose={()=>{}}/>);await screen.findByText('Joint care');expect(screen.queryByText('نیازمند تایید ادمین')).not.toBeInTheDocument();});
it('hides wholesale prices for unverified users',async()=>{state.role='USER';render(<B2BPortal onClose={()=>{}}/>);await screen.findByText('Joint care');expect(screen.getAllByText('نیازمند تایید ادمین')).toHaveLength(2);expect(screen.queryByText('۶۵۰ تومان')).not.toBeInTheDocument();});
it('filters by code preserving selection and clamps negative quantity',async()=>{render(<B2BPortal onClose={()=>{}}/>);await screen.findByText('Joint care');expect(screen.getByRole('button',{name:/افزودن کلی/})).toBeDisabled();fireEvent.change(screen.getAllByRole('spinbutton')[0],{target:{value:'3'}});fireEvent.change(screen.getAllByRole('spinbutton')[1],{target:{value:'-2'}});fireEvent.change(screen.getByPlaceholderText('جستجوی کد کالا یا نام محصول...'),{target:{value:'B2'}});expect(screen.queryByText('Joint care')).not.toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:/افزودن کلی/}));expect(state.addItem).toHaveBeenCalledExactlyOnceWith(products[0],3);expect(screen.getByText(/سفارشات با موفقیت/)).toBeInTheDocument();});
it('uses specific price and settings discount fallback',async()=>{render(<B2BPortal onClose={()=>{}}/>);await screen.findAllByText('Joint care');expect(state.getProducts).toHaveBeenCalledWith({limit:999});expect(screen.getByText('۶۵۰ تومان')).toBeInTheDocument();expect(screen.getByText('۱,۶۰۰ تومان')).toBeInTheDocument();});
it.each(['User_Wholesale','ADMIN','User_Partner'])('unlocks wholesale prices for %s',async role=>{state.role=role;render(<B2BPortal onClose={()=>{}}/>);await screen.findAllByText('Joint care');expect(screen.queryByText('نیازمند تایید ادمین')).not.toBeInTheDocument();});
it('hides wholesale prices for unverified users',async()=>{state.role='USER';render(<B2BPortal onClose={()=>{}}/>);await screen.findAllByText('Joint care');expect(screen.getAllByText('نیازمند تایید ادمین')).toHaveLength(2);expect(screen.queryByText('۶۵۰ تومان')).not.toBeInTheDocument();});
it('filters by code preserving selection and clamps negative quantity',async()=>{render(<B2BPortal onClose={()=>{}}/>);await screen.findAllByText('Joint care');expect(screen.getByRole('button',{name:/افزودن کلی/})).toBeDisabled();fireEvent.change(screen.getAllByRole('spinbutton')[0],{target:{value:'3'}});fireEvent.change(screen.getAllByRole('spinbutton')[1],{target:{value:'-2'}});fireEvent.change(screen.getByPlaceholderText('جستجوی کد کالا یا نام محصول...'),{target:{value:'B2'}});expect(screen.queryAllByText('Joint care')).toHaveLength(0);fireEvent.click(screen.getByRole('button',{name:/افزودن کلی/}));expect(state.addItem).toHaveBeenCalledExactlyOnceWith(products[0],3);expect(screen.getByText(/سفارشات با موفقیت/)).toBeInTheDocument();});
it.each([false,true])('consultation success/error: failure=%s',async failure=>{state.role='USER';if(failure)state.post.mockRejectedValue(new Error('offline'));const {container}=render(<B2BPortal onClose={()=>{}}/>);fireEvent.change(screen.getByPlaceholderText('نام مجموعه / کلینیک / داروخانه'),{target:{value:'Clinic'}});fireEvent.change(screen.getByPlaceholderText('شماره تماس همراه'),{target:{value:'09120000000'}});fireEvent.submit(container.querySelector('form')!);await waitFor(()=>expect(failure?state.error:state.success).toHaveBeenCalledOnce());expect(state.post).toHaveBeenCalledWith('/wholesale/apply',{businessName:'Clinic',licenseNumber:'09120000000'});expect(screen.getByPlaceholderText('نام مجموعه / کلینیک / داروخانه')).toHaveValue(failure?'Clinic':'');});
it('handles product loading failure visibly',async()=>{state.getProducts.mockRejectedValueOnce(new Error('offline'));render(<B2BPortal onClose={()=>{}}/>);expect(await screen.findByText(/خطا در دریافت محصولات/)).toBeInTheDocument();expect(screen.getByRole('button',{name:/افزودن کلی/})).toBeDisabled();});
it.each([false,true])('ignores a settled request after unmount: failure=%s',async failure=>{let resolve!:(value:{data:typeof products})=>void;let reject!:(reason:Error)=>void;state.getProducts.mockReturnValueOnce(new Promise((yes,no)=>{resolve=yes;reject=no;}));const first=render(<B2BPortal onClose={()=>{}}/>);first.unmount();const next=render(<B2BPortal onClose={()=>{}}/>);await screen.findByText('Joint care');await act(async()=>{if(failure)reject(new Error('late failure'));else resolve({data:[{...products[0],name:'Stale product'}]});});expect(screen.queryByRole('alert')).not.toBeInTheDocument();expect(screen.queryByText('Stale product')).not.toBeInTheDocument();expect(screen.getByText('Joint care')).toBeInTheDocument();next.unmount();});
it.each([false,true])('ignores a settled request after unmount: failure=%s',async failure=>{let resolve!:(value:{data:typeof products})=>void;let reject!:(reason:Error)=>void;state.getProducts.mockReturnValueOnce(new Promise((yes,no)=>{resolve=yes;reject=no;}));const first=render(<B2BPortal onClose={()=>{}}/>);first.unmount();const next=render(<B2BPortal onClose={()=>{}}/>);await screen.findAllByText('Joint care');await act(async()=>{if(failure)reject(new Error('late failure'));else resolve({data:[{...products[0],name:'Stale product'}]});});expect(screen.queryByRole('alert')).not.toBeInTheDocument();expect(screen.queryByText('Stale product')).not.toBeInTheDocument();expect(screen.getAllByText('Joint care')[0]).toBeInTheDocument();next.unmount();});
it('closes via callback',()=>{const close=vi.fn();const {container}=render(<B2BPortal onClose={close}/>);fireEvent.click(container.querySelector('button')!);expect(close).toHaveBeenCalledOnce();});
@@ -98,11 +98,11 @@ describe('MobileBottomNav Component', () => {
expect(screen.getByText('حساب من')).toBeInTheDocument();
});
it('hides component on product detail page (/shop/[id])', () => {
it('retains component on product detail page (/shop/[id]) for continuous navigation', () => {
vi.mocked(usePathname).mockReturnValue('/shop/canina-glucosamine-123');
const { container } = render(<MobileBottomNav />);
render(<MobileBottomNav />);
expect(container.firstChild).toBeNull();
expect(screen.getByRole('navigation', { name: 'منوی ناوبری موبایل' })).toBeInTheDocument();
});
it('highlights the active tab according to current path', () => {
+1
View File
@@ -19,6 +19,7 @@ const eslintConfig = defineConfig([
"@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/no-unused-vars": ["warn", { argsIgnorePattern: "^_", varsIgnorePattern: "^_" }],
"react-hooks/set-state-in-effect": "off",
"react-hooks/immutability": "off",
"react-hooks/exhaustive-deps": "warn",
},
},
+4
View File
@@ -303,6 +303,10 @@ export async function getPageMetadata(
keywords,
alternates: {
canonical: canonicalUrl,
languages: {
'fa-IR': canonicalUrl,
'x-default': canonicalUrl,
},
},
openGraph: {
title: ogTitle,
+1
View File
@@ -26,6 +26,7 @@ export interface ApiErrorPayload {
const api = axios.create({
baseURL,
timeout: 10000,
withCredentials: true,
headers: {
'Content-Type': 'application/json',
},
@@ -273,8 +273,17 @@ export class ProductService {
}
const response = await api.get(`/products/${slug}`);
return this.mapBackendToFrontend(response.data);
} catch (error) {
console.error(`[ProductService] Failed to fetch product ${slug}:`, error);
} catch (error: any) {
// Differentiate 404 (legitimate not found) from network/5xx server failure
const status = error?.response?.status || (String(error?.message).includes('404') ? 404 : null);
if (status === 404) {
return null;
}
console.error(`[ProductService] Upstream error fetching product ${slug}:`, error);
// Re-throw upstream server errors so Next.js ErrorBoundary renders retryable state instead of fake 404
if (typeof window === 'undefined') {
throw error;
}
return null;
}
}
+243 -346
View File
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -19,7 +19,7 @@
"dompurify": "^3.4.16",
"lucide-react": "^0.475.0",
"motion": "^12.40.0",
"next": "16.2.9",
"next": "16.4.2",
"nextjs-toploader": "^3.9.17",
"react": "19.2.4",
"react-dom": "19.2.4",
@@ -36,7 +36,7 @@
"@types/react-dom": "^19",
"@vitejs/plugin-react": "^6.0.5",
"eslint": "^9",
"eslint-config-next": "16.2.9",
"eslint-config-next": "16.4.2",
"jsdom": "^29.1.1",
"tailwindcss": "^4",
"typescript": "^5",