diff --git a/.gitea/workflows/torob.yml b/.gitea/workflows/torob.yml new file mode 100644 index 00000000..e4a24995 --- /dev/null +++ b/.gitea/workflows/torob.yml @@ -0,0 +1,32 @@ +name: Torob regression +on: + push: + branches: [develop, main] + pull_request: + branches: [develop, main] +jobs: + torob-regression: + runs-on: ubuntu-latest + services: + torob-test-db: + image: postgres:16-alpine + env: + POSTGRES_USER: torob + POSTGRES_PASSWORD: disposable-fixture-only + POSTGRES_DB: torob_test + options: >- + --health-cmd "pg_isready -U torob -d torob_test" + --health-interval 5s + --health-timeout 5s + --health-retries 10 + container: node:20 + env: + DATABASE_URL: postgresql://torob:disposable-fixture-only@torob-test-db:5432/torob_test + steps: + - uses: actions/checkout@v4 + - name: Install and generate isolated client + run: cd backend && npm ci && npx prisma generate + - name: Unit regressions + run: cd backend && npm test -- --runInBand src/products/torob.controller.spec.ts + - name: Disposable PostgreSQL integration + run: cd backend && npx prisma db push --skip-generate && npx jest --config test/jest-torob.json --runInBand diff --git a/backend/src/products/torob.controller.spec.ts b/backend/src/products/torob.controller.spec.ts index 37cc2c4c..b56153cf 100644 --- a/backend/src/products/torob.controller.spec.ts +++ b/backend/src/products/torob.controller.spec.ts @@ -140,6 +140,18 @@ describe("TorobController", () => { expect(result.max_pages).toBe(1); }); + it.each([['garbage', 'garbage', 100], ['2', 'garbage', 100], ['garbage', '20', 20]])( + "defaults nonnumeric pagination safely (%s, %s)", async (page, size, take) => { + mockPrismaService.product.count.mockResolvedValue(0); + mockPrismaService.product.findMany.mockResolvedValue([]); + const result = await controller.getTorobProducts(page, size); + expect(mockPrismaService.product.findMany).toHaveBeenCalledWith( + expect.objectContaining({ skip: page === '2' ? 100 : 0, take }), + ); + expect(result.max_pages).toBe(1); + }, + ); + it("should correctly mark out-of-stock products", async () => { const mockOutOfStock = [ { diff --git a/backend/src/products/torob.controller.ts b/backend/src/products/torob.controller.ts index 33726b9f..c23f1f98 100644 --- a/backend/src/products/torob.controller.ts +++ b/backend/src/products/torob.controller.ts @@ -141,10 +141,12 @@ export class TorobController { @Query("page") pageQuery?: string, @Query("page_size") pageSizeQuery?: string, ) { - const page = Math.max(1, parseInt(pageQuery || "1", 10)); + const parsedPage = parseInt(pageQuery || "1", 10); + const parsedSize = parseInt(pageSizeQuery || "100", 10); + const page = Math.max(1, Number.isFinite(parsedPage) ? parsedPage : 1); const pageSize = Math.min( 100, - Math.max(10, parseInt(pageSizeQuery || "100", 10)), + Math.max(10, Number.isFinite(parsedSize) ? parsedSize : 100), ); const baseUrl = (process.env.FRONTEND_URL || "https://canina.ir").replace( /\/$/, diff --git a/backend/src/settings/settings.service.ts b/backend/src/settings/settings.service.ts index 032224a1..df63c507 100644 --- a/backend/src/settings/settings.service.ts +++ b/backend/src/settings/settings.service.ts @@ -247,7 +247,7 @@ export class SettingsService implements OnModuleInit { }); // 2. Add from settings and unpack object keys - settings.forEach((s) => { + settings.filter((s) => s.key !== "support_chat").forEach((s) => { const valStr = typeof s.value === "string" ? s.value : JSON.stringify(s.value); mergedMap.set(s.key, valStr); @@ -276,6 +276,7 @@ export class SettingsService implements OnModuleInit { } async updateUiText(key: string, value: string) { + if (key === "support_chat") throw new Error("Use support-chat settings API"); const strVal = String(value ?? ""); const allKeysToUpdate = new Set([key]); const aliases = CANONICAL_ALIASES[key] || []; diff --git a/backend/src/support-chat/support-chat-settings.controller.ts b/backend/src/support-chat/support-chat-settings.controller.ts new file mode 100644 index 00000000..a8d3cec1 --- /dev/null +++ b/backend/src/support-chat/support-chat-settings.controller.ts @@ -0,0 +1,17 @@ +import { Body, Controller, Get, Put, UseGuards, Header } from '@nestjs/common'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { RolesGuard } from '../common/guards/roles.guard'; +import { Roles } from '../common/decorators/roles.decorator'; +import { SupportChatSettingsService } from './support-chat-settings.service'; +@Controller('support-chat') +export class SupportChatSettingsController { + constructor(private readonly settings: SupportChatSettingsService) {} + @Get('config') @Header('Cache-Control', 'no-store') + config() { return this.settings.publicConfig(); } + @Get('settings') @UseGuards(JwtAuthGuard, RolesGuard) @Roles('Admin') @Header('Cache-Control', 'no-store') + read() { return this.settings.read(); } + @Get('catalog') @UseGuards(JwtAuthGuard, RolesGuard) @Roles('Admin') @Header('Cache-Control', 'no-store') + catalog() { return this.settings.catalog(); } + @Put('settings') @UseGuards(JwtAuthGuard, RolesGuard) @Roles('Admin') + save(@Body() body: unknown) { return this.settings.save(body); } +} diff --git a/backend/src/support-chat/support-chat-settings.service.ts b/backend/src/support-chat/support-chat-settings.service.ts new file mode 100644 index 00000000..dc5a4de1 --- /dev/null +++ b/backend/src/support-chat/support-chat-settings.service.ts @@ -0,0 +1,51 @@ +import { BadRequestException, Injectable, ServiceUnavailableException } from '@nestjs/common'; +import { PrismaService } from '../prisma/prisma.service'; + +export const CHAT_SETTINGS_KEY = 'support_chat'; +export type ChatSettings = { enabled: boolean; provider: string; model: string; label: string; icon: string }; +const fail = () => new ServiceUnavailableException('تنظیمات پشتیبان هوشمند در دسترس نیست.'); +export const ICONS = ['chat', 'paw', 'bot'] as const; +export function validateSettings(value: any): ChatSettings { + if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).sort().join(',') !== 'enabled,icon,label,model,provider' || typeof value.enabled !== 'boolean' || typeof value.provider !== 'string' || typeof value.model !== 'string' || value.provider.length > 100 || value.model.length > 160 || typeof value.label !== 'string' || !value.label.trim() || value.label.length > 60 || /[<>\x00-\x1f]/.test(value.label) || !ICONS.includes(value.icon)) throw new BadRequestException('تنظیمات پشتیبان نامعتبر است.'); + return { enabled: value.enabled, provider: value.provider, model: value.model, label: value.label.trim(), icon: value.icon }; +} +@Injectable() +export class SupportChatSettingsService { + constructor(private readonly prisma: PrismaService) {} + async read(): Promise { + try { + const row = await this.prisma.setting.findUnique({ where: { key: CHAT_SETTINGS_KEY } }); + if (!row) throw fail(); + return validateSettings(row.value); + } catch { throw fail(); } + } + async publicConfig() { + const { enabled, label, icon } = await this.read(); + return { enabled, label, icon }; + } + async catalog(): Promise<{ providers: { id: string; label: string; models: string[] }[] }> { + try { + const url = process.env.SUPPORT_CHAT_URL; + const key = process.env.SUPPORT_CHAT_KEY; + if (!url?.endsWith('/ask') || !key) throw fail(); + const response = await fetch(url.replace(/\/ask$/, '/catalog'), { headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(100000), redirect: 'error' }); + if (!response.ok) throw fail(); + const data = await response.json(); + if (!Array.isArray(data.providers) || !data.providers.length || data.providers.length > 50) throw fail(); + const safe = (s: any) => typeof s === 'string' && s.length > 0 && s.length <= 160 && /^[\w .:/@+\[\]()-]+$/.test(s) && !s.includes('://'); + return { providers: data.providers.map((p: any) => { + if (!/^configured-[a-f0-9]{16}$/.test(p.id) || !safe(p.label) || !Array.isArray(p.models) || !p.models.length || p.models.length > 2000 || !p.models.every(safe)) throw fail(); + return { id: p.id, label: p.label, models: p.models }; + }) }; + } catch { throw fail(); } + } + async save(input: unknown) { + const value = validateSettings(input); + if (value.provider || value.model || value.enabled) { + const catalog = await this.catalog(); + if (!catalog.providers.some(p => p.id === value.provider && p.models.includes(value.model))) throw new BadRequestException('مدل متعلق به ارائه‌دهنده انتخاب‌شده نیست.'); + } + await this.prisma.setting.upsert({ where: { key: CHAT_SETTINGS_KEY }, create: { key: CHAT_SETTINGS_KEY, category: 'support-chat', value }, update: { value } }); + return this.read(); + } +} diff --git a/backend/src/support-chat/support-chat-settings.spec.ts b/backend/src/support-chat/support-chat-settings.spec.ts new file mode 100644 index 00000000..742c802d --- /dev/null +++ b/backend/src/support-chat/support-chat-settings.spec.ts @@ -0,0 +1,42 @@ +import { SupportChatSettingsService, validateSettings } from './support-chat-settings.service'; +import { SupportChatService } from './support-chat.service'; +import { SupportChatSettingsController } from './support-chat-settings.controller'; +import { Test } from '@nestjs/testing'; +import { PassportModule, PassportStrategy } from '@nestjs/passport'; +import { ExtractJwt, Strategy } from 'passport-jwt'; +import { JwtService } from '@nestjs/jwt'; +import request from 'supertest'; +class TestJwt extends PassportStrategy(Strategy) { + constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey:'test' }); } + validate(p: any) { return { id:p.sub, role:p.role }; } +} +const selected = { enabled:true, provider:'configured-1234567890abcdef', model:'real-model', label:'پشتیبان تست', icon:'paw' }; +describe('smart chat settings', () => { + let stored:any = null; + const prisma:any = { setting:{ findUnique:jest.fn(async()=>stored), upsert:jest.fn(async(q:any)=>{stored={value:q.create.value};return stored;}) }, product:{findMany:jest.fn(async()=>[])}, user:{findUnique:jest.fn()}, order:{findMany:jest.fn()} }; + let service:SupportChatSettingsService; + beforeEach(()=>{stored=null;jest.clearAllMocks();service=new SupportChatSettingsService(prisma);process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='key';}); + afterEach(()=>jest.restoreAllMocks()); + const catalog=()=>jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>({providers:[{id:selected.provider,label:'Configured',models:[selected.model]}]})} as any); + it('persists and reads exact fields and projects safe public config',async()=>{catalog();expect(await service.save(selected)).toEqual(selected);expect(await service.read()).toEqual(selected);expect(await service.publicConfig()).toEqual({enabled:true,label:selected.label,icon:'paw'});}); + it.each([{...selected,model:'unknown'},{...selected,provider:'http://127.0.0.1'},{...selected,provider:'configured-ffffffffffffffff'}])('rejects invalid combination %j',async s=>{catalog();await expect(service.save(s)).rejects.toThrow();expect(prisma.setting.upsert).not.toHaveBeenCalled();}); + it.each(['https://evil/a.svg','','data:image/svg+xml,abc','/uploads/x.svg'])('rejects unsafe icon %s',icon=>{expect(()=>validateSettings({...selected,icon})).toThrow();}); + it('rejects unknown fields and invalid label',()=>{expect(()=>validateSettings({...selected,baseUrl:'https://evil'})).toThrow();expect(()=>validateSettings({...selected,label:'
+ ← تنظیمات فروشگاه +

پشتیبان هوشمند سایت

+

انتخاب مدل برای تشخیص درخواست و پاسخ‌گویی یکسان است. اطلاعات حساب مشتری به مدل ارسال نمی‌شود.

+ {error &&
{error}
} + {!settings ? : +
+ + + + + +

برای امنیت سایت فقط آیکون‌های داخلی قابل انتخاب هستند؛ نشانی یا SVG دلخواه پذیرفته نمی‌شود.

+
{icons[settings.icon]}{settings.label}
+
+
} +
; +} diff --git a/frontend/admin-panel/src/routes/adminRoutes.tsx b/frontend/admin-panel/src/routes/adminRoutes.tsx index cda50df4..9d94ea3d 100644 --- a/frontend/admin-panel/src/routes/adminRoutes.tsx +++ b/frontend/admin-panel/src/routes/adminRoutes.tsx @@ -12,6 +12,7 @@ const Users = lazyWithRetry(() => import('../pages/Users')); const Products = lazyWithRetry(() => import('../pages/Products')); const Orders = lazyWithRetry(() => import('../pages/Orders')); const Coupons = lazyWithRetry(() => import('../pages/Coupons')); +const SmartChatSettingsPage = lazyWithRetry(() => import('../pages/SmartChatSettingsPage')); const Settings = lazyWithRetry(() => import('../pages/Settings')); const Reports = lazyWithRetry(() => import('../pages/Reports')); const Categories = lazyWithRetry(() => import('../pages/Categories')); @@ -79,6 +80,7 @@ export const router = createBrowserRouter([ { path: 'zibal-portal/*', element: }, { path: 'coupons/*', element: }, { path: 'settings', element: }, + { path: 'settings/smart-chat', element: }, { path: 'settings/payment-methods', element: }, { path: 'settings/shipping', element: }, { path: 'settings/ssl', element: }, diff --git a/frontend/application/app/sitemap.test.ts b/frontend/application/app/sitemap.test.ts new file mode 100644 index 00000000..6a20e044 --- /dev/null +++ b/frontend/application/app/sitemap.test.ts @@ -0,0 +1,53 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import sitemap from './sitemap'; + +vi.mock('../lib/services/productService', () => ({ + productService: { + getProducts: vi.fn().mockResolvedValue({ data: [] }), + getActiveFilters: vi.fn().mockResolvedValue({ categories: [] }), + }, +})); + +afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); }); + +describe('sitemap blog retrieval', () => { + it('retrieves every page without putting full blog content in the Next data cache', async () => { + vi.stubEnv('INTERNAL_API_URL', 'http://backend:3000/api/'); + vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://stage.canina.ir'); + const fetchMock = vi.fn() + .mockResolvedValueOnce({ ok: true, json: async () => ({ data: [ + { slug: 'first', status: 'PUBLISHED', updatedAt: '2026-10-01', featured: true }, + { slug: 'hidden', status: 'PUBLISHED', noIndex: true }, + { slug: 'draft', status: 'DRAFT' }, + ], meta: { lastPage: 2 } }) }) + .mockResolvedValueOnce({ ok: true, json: async () => ({ data: [ + { slug: 'last', status: 'PUBLISHED' }, + ], meta: { lastPage: 2 } }) }); + vi.stubGlobal('fetch', fetchMock); + const routes = await sitemap(); + expect(fetchMock.mock.calls).toEqual([ + ['http://backend:3000/api/blogs?page=1&limit=10', { cache: 'no-store' }], + ['http://backend:3000/api/blogs?page=2&limit=10', { cache: 'no-store' }], + ]); + const blogs = routes.filter(r => r.url.includes('/blog/')); + expect(blogs.map(r => r.url)).toEqual(['https://stage.canina.ir/blog/first', 'https://stage.canina.ir/blog/last']); + expect(blogs[0].priority).toBe(0.9); + expect(blogs[0].lastModified).toEqual(new Date('2026-10-01')); + }); + + it('terminates on an empty page even when pagination metadata is stale', async () => { + const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: [], meta: { lastPage: 999 } }) }); + vi.stubGlobal('fetch', fetchMock); + expect((await sitemap()).filter(r => r.url.includes('/blog/'))).toEqual([]); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('falls back without publishing a partial blog sitemap when a later page fails', async () => { + vi.stubGlobal('fetch', vi.fn() + .mockResolvedValueOnce({ ok: true, json: async () => ({ data: [{ slug: 'first', status: 'PUBLISHED' }], meta: { lastPage: 2 } }) }) + .mockResolvedValueOnce({ ok: false, status: 503 })); + const routes = await sitemap(); + expect(routes.filter(r => r.url.includes('/blog/'))).toEqual([]); + expect(routes.some(r => r.url.endsWith('/shop'))).toBe(true); + }); +}); diff --git a/frontend/application/app/sitemap.ts b/frontend/application/app/sitemap.ts index 7868a4f8..2ecfa395 100644 --- a/frontend/application/app/sitemap.ts +++ b/frontend/application/app/sitemap.ts @@ -89,20 +89,30 @@ export default async function sitemap(): Promise { let blogRoutes: MetadataRoute.Sitemap = []; try { const apiUrl = process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api'; - const apiBase = apiUrl.endsWith('/api') ? apiUrl : `${apiUrl.replace(/\/$/, '')}/api`; - const res = await fetch(`${apiBase}/blogs?page=1&limit=999`, { next: { revalidate: 3600 } }); - if (res.ok) { + const normalizedApiUrl = apiUrl.replace(/\/$/, ''); + const apiBase = normalizedApiUrl.endsWith('/api') ? normalizedApiUrl : `${normalizedApiUrl}/api`; + type SitemapBlog = { slug: string; noIndex?: boolean; status: string; updatedAt?: string; featured?: boolean }; + // The public list includes article bodies. Keep requests small and bypass + // Next's 2MB per-entry data cache, even for an unusually large article. + let page = 1; + let lastPage = 1; + do { + const res = await fetch(`${apiBase}/blogs?page=${page}&limit=10`, { cache: 'no-store' }); + if (!res.ok) throw new Error(`Blog sitemap request failed: ${res.status}`); const data = await res.json(); - const blogsList = data.data || []; - blogRoutes = blogsList - .filter((b: any) => !b.noIndex && b.status === 'PUBLISHED') - .map((b: any) => ({ + const blogsList: SitemapBlog[] = data.data || []; + if (!blogsList.length) break; + blogRoutes.push(...blogsList + .filter((b) => !b.noIndex && b.status === 'PUBLISHED') + .map((b): MetadataRoute.Sitemap[number] => ({ url: `${baseUrl}/blog/${b.slug}`, lastModified: b.updatedAt ? new Date(b.updatedAt) : new Date(), changeFrequency: 'weekly', priority: b.featured ? 0.9 : 0.7, - })); - } + }))); + lastPage = Number(data.meta?.lastPage) || 1; + page += 1; + } while (page <= lastPage); } catch { // Fallback if backend not reachable at build time blogRoutes = []; diff --git a/frontend/application/components/SupportChat.test.tsx b/frontend/application/components/SupportChat.test.tsx index d32e4c2a..6e65b327 100644 --- a/frontend/application/components/SupportChat.test.tsx +++ b/frontend/application/components/SupportChat.test.tsx @@ -5,13 +5,14 @@ import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/re import SupportChat from './SupportChat'; afterEach(() => { cleanup(); vi.restoreAllMocks(); localStorage.clear(); }); describe('support widget', () => { - it('submits only message and explicit scope, renders text safely', async () => { + it('submits only message without scope tabs, renders text safely', async () => { const fetcher=vi.spyOn(globalThis,'fetch').mockResolvedValue({ok:true,json:async()=>({answer:''})} as Response); render(); fireEvent.click(screen.getByRole('button',{name:/گفتگو با پشتیبان/})); fireEvent.change(screen.getByLabelText('پیام شما'),{target:{value:'مکمل سگ'}}); fireEvent.click(screen.getByRole('button',{name:'ارسال'})); await waitFor(()=>expect(screen.getByText('')).toBeTruthy()); - expect(JSON.parse(fetcher.mock.calls[0][1]!.body as string)).toEqual({message:'مکمل سگ',scope:'public'}); + expect(JSON.parse(fetcher.mock.calls[0][1]!.body as string)).toEqual({message:'مکمل سگ'}); expect(document.querySelector('script')).toBeNull(); + for (const label of ['محصولات و عمومی','سفارش‌های من','کیف پول']) expect(screen.queryByRole('button',{name:label})).toBeNull(); }); it('does not expose upstream errors', async()=> { vi.spyOn(globalThis,'fetch').mockResolvedValue({ok:false,status:503,json:async()=>({message:'secret-provider'})} as Response); diff --git a/frontend/application/components/SupportChat.tsx b/frontend/application/components/SupportChat.tsx index 57f72732..22425594 100644 --- a/frontend/application/components/SupportChat.tsx +++ b/frontend/application/components/SupportChat.tsx @@ -11,9 +11,27 @@ const token = () => { }; 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); + useEffect(() => { + let active = true; + const refresh = async () => { + try { + const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL || '/api'}/support-chat/config`, { cache: 'no-store' }); + if (!response.ok) throw new Error('config'); + const raw = await response.json(); + const value = raw.data ?? raw; + if (typeof value.enabled !== 'boolean' || typeof value.label !== 'string' || !['chat', 'paw', 'bot'].includes(value.icon)) throw new Error('config'); + if (active) { setConfig(value); setConfigError(false); if (!value.enabled) { setOpen(false); pending.current?.abort(); setRows([]); } } + } catch { if (active) { setConfig(null); setConfigError(true); setOpen(false); pending.current?.abort(); setRows([]); } } + }; + void refresh(); + const timer = window.setInterval(refresh, 10000); + window.addEventListener('focus', refresh); + return () => { active = false; clearInterval(timer); window.removeEventListener('focus', refresh); }; + }, []); const [message, setMessage] = useState(''); - const [scope, setScope] = useState<'public' | 'orders' | 'wallet'>('public'); const [busy, setBusy] = useState(false); const [rows, setRows] = useState<{ question: string; answer: string }[]>([]); const identity = useRef(''); @@ -28,7 +46,6 @@ export default function SupportChat() { pending.current?.abort(); setRows([]); setMessage(''); - setScope('public'); setBusy(false); } }; @@ -51,7 +68,7 @@ export default function SupportChat() { async function send(event: FormEvent) { event.preventDefault(); - if (busy || !message.trim()) return; + if (busy || !message.trim() || !config?.enabled) return; const current = token(); if (current !== identity.current) { setRows([]); @@ -72,7 +89,7 @@ export default function SupportChat() { ...(current ? { Authorization: `Bearer ${current}` } : {}) }, credentials: 'include', - body: JSON.stringify({ message: question, scope }), + body: JSON.stringify({ message: question }), signal: AbortSignal.any([controller.signal, AbortSignal.timeout(50000)]) }); if (response.status === 401) { @@ -90,6 +107,8 @@ export default function SupportChat() { if (pending.current === controller) setBusy(false); } + if (!config?.enabled) return configError ? تنظیمات پشتیبان هوشمند در دسترس نیست. : null; + const botIcon = { chat: '💬', paw: '🐾', bot: '🤖' }[config.icon]; return (