From b6735b5a9c98c1742041a1faeee9c876cce1d439 Mon Sep 17 00:00:00 2001 From: devops Date: Wed, 14 Oct 2026 19:44:16 +0000 Subject: [PATCH] feat(support-chat): add admin smart chat settings --- backend/src/settings/settings.service.ts | 3 +- .../support-chat-settings.controller.ts | 17 ++++++ .../support-chat-settings.service.ts | 51 ++++++++++++++++ .../support-chat-settings.spec.ts | 42 +++++++++++++ .../support-chat/support-chat.http.spec.ts | 3 +- .../src/support-chat/support-chat.module.ts | 4 +- .../support-chat/support-chat.service.spec.ts | 4 +- .../src/support-chat/support-chat.service.ts | 10 +++- frontend/admin-panel/src/pages/Settings.tsx | 1 + .../src/pages/SmartChatSettingsPage.tsx | 59 +++++++++++++++++++ .../admin-panel/src/routes/adminRoutes.tsx | 2 + .../application/components/SupportChat.tsx | 31 ++++++++-- scripts/support-chat/provider_catalog.py | 52 ++++++++++++++++ scripts/support-chat/server.py | 31 ++++++---- 14 files changed, 285 insertions(+), 25 deletions(-) create mode 100644 backend/src/support-chat/support-chat-settings.controller.ts create mode 100644 backend/src/support-chat/support-chat-settings.service.ts create mode 100644 backend/src/support-chat/support-chat-settings.spec.ts create mode 100644 frontend/admin-panel/src/pages/SmartChatSettingsPage.tsx create mode 100644 scripts/support-chat/provider_catalog.py 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/components/SupportChat.tsx b/frontend/application/components/SupportChat.tsx index d496c942..22425594 100644 --- a/frontend/application/components/SupportChat.tsx +++ b/frontend/application/components/SupportChat.tsx @@ -11,7 +11,26 @@ 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 [busy, setBusy] = useState(false); const [rows, setRows] = useState<{ question: string; answer: string }[]>([]); @@ -49,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([]); @@ -88,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 (