From def903734f6b2ce6af08807ad5bff2a16913edea Mon Sep 17 00:00:00 2001 From: devops Date: Thu, 15 Oct 2026 07:28:02 +0000 Subject: [PATCH] feat(support-chat): persist conversations and analytics --- .../migration.sql | 8 ++++ backend/prisma/schema.prisma | 37 +++++++++++++++++++ .../support-chat/support-chat.controller.ts | 5 ++- backend/src/support-chat/support-chat.dto.ts | 5 ++- .../support-chat/support-chat.service.spec.ts | 24 +++++++++++- .../src/support-chat/support-chat.service.ts | 13 +++++-- .../application/components/SupportChat.tsx | 15 ++++++-- 7 files changed, 97 insertions(+), 10 deletions(-) create mode 100644 backend/prisma/migrations/20261015000000_add_support_conversations/migration.sql diff --git a/backend/prisma/migrations/20261015000000_add_support_conversations/migration.sql b/backend/prisma/migrations/20261015000000_add_support_conversations/migration.sql new file mode 100644 index 00000000..e2708911 --- /dev/null +++ b/backend/prisma/migrations/20261015000000_add_support_conversations/migration.sql @@ -0,0 +1,8 @@ +CREATE TABLE support_conversations (id UUID NOT NULL, user_id UUID, anonymous_browser_id VARCHAR(64), entry_path VARCHAR(512), product_slugs JSONB, topics JSONB, unanswered BOOLEAN NOT NULL DEFAULT false, needs_followup BOOLEAN NOT NULL DEFAULT false, escalation_signal BOOLEAN NOT NULL DEFAULT false, summary TEXT, summary_status VARCHAR(20) NOT NULL DEFAULT 'pending', created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMPTZ NOT NULL, expires_at TIMESTAMPTZ NOT NULL, CONSTRAINT support_conversations_pkey PRIMARY KEY (id)); +CREATE TABLE support_conversation_messages (id UUID NOT NULL, conversation_id UUID NOT NULL, role VARCHAR(20) NOT NULL, content TEXT NOT NULL, sequence INTEGER NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT support_conversation_messages_pkey PRIMARY KEY (id)); +CREATE UNIQUE INDEX support_conversation_messages_conversation_id_sequence_key ON support_conversation_messages(conversation_id, sequence); +CREATE INDEX support_conversations_user_id_updated_at_idx ON support_conversations(user_id, updated_at); +CREATE INDEX support_conversations_anonymous_browser_id_updated_at_idx ON support_conversations(anonymous_browser_id, updated_at); +CREATE INDEX support_conversation_messages_conversation_id_created_at_idx ON support_conversation_messages(conversation_id, created_at); +ALTER TABLE support_conversations ADD CONSTRAINT support_conversations_user_id_fkey FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE support_conversation_messages ADD CONSTRAINT support_conversation_messages_conversation_id_fkey FOREIGN KEY (conversation_id) REFERENCES support_conversations(id) ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index a9deee44..4924e805 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -32,12 +32,49 @@ model User { tickets Ticket[] reviews ProductReview[] blogComments BlogComment[] + supportConversations SupportConversation[] @@index([role]) @@index([createdAt]) @@map("users") } +model SupportConversation { + id String @id @default(uuid()) @db.Uuid + userId String? @map(user_id) @db.Uuid + anonymousBrowserId String? @map(anonymous_browser_id) @db.VarChar(64) + entryPath String? @map(entry_path) @db.VarChar(512) + productSlugs Json? @map(product_slugs) + topics Json? + unanswered Boolean @default(false) + needsFollowup Boolean @default(false) @map(needs_followup) + escalationSignal Boolean @default(false) @map(escalation_signal) + summary String? @db.Text + summaryStatus String @default(pending) @map(summary_status) @db.VarChar(20) + createdAt DateTime @default(now()) @map(created_at) @db.Timestamptz() + updatedAt DateTime @updatedAt @map(updated_at) @db.Timestamptz() + expiresAt DateTime @map(expires_at) @db.Timestamptz() + + user User? @relation(fields: [userId], references: [id], onDelete: Cascade) + messages SupportConversationMessage[] + @@index([userId, updatedAt]) + @@index([anonymousBrowserId, updatedAt]) + @@map(support_conversations) +} + +model SupportConversationMessage { + id String @id @default(uuid()) @db.Uuid + conversationId String @map(conversation_id) @db.Uuid + role String @db.VarChar(20) + content String @db.Text + sequence Int + createdAt DateTime @default(now()) @map(created_at) @db.Timestamptz() + conversation SupportConversation @relation(fields: [conversationId], references: [id], onDelete: Cascade) + @@unique([conversationId, sequence]) + @@index([conversationId, createdAt]) + @@map(support_conversation_messages) +} + model UserAddress { id String @id @default(uuid()) @db.Uuid userId String @map("user_id") @db.Uuid diff --git a/backend/src/support-chat/support-chat.controller.ts b/backend/src/support-chat/support-chat.controller.ts index ea3dc5bd..166fb717 100644 --- a/backend/src/support-chat/support-chat.controller.ts +++ b/backend/src/support-chat/support-chat.controller.ts @@ -1,4 +1,4 @@ -import { Body, Controller, Post, Req, UseGuards, Header } from '@nestjs/common'; +import { Body, Controller, Get, Param, Post, Req, UseGuards, Header } from '@nestjs/common'; import { Throttle } from '@nestjs/throttler'; import { SupportChatService } from './support-chat.service'; import { SupportChatDto } from './support-chat.dto'; @@ -6,6 +6,9 @@ import { OptionalCustomerJwtGuard } from './support-chat.guard'; @Controller('support-chat') export class SupportChatController { constructor(private readonly service: SupportChatService) {} + @Get(':id') @UseGuards(OptionalCustomerJwtGuard) + @Header('Cache-Control', 'no-store') + history(@Param('id') id: string, @Req() req: { user?: { id: string } }) { return this.service.history(id, req.user); } @Post('ask') @UseGuards(OptionalCustomerJwtGuard) @Throttle({ default: { limit: 10, ttl: 60000 } }) @Header('Cache-Control', 'no-store') diff --git a/backend/src/support-chat/support-chat.dto.ts b/backend/src/support-chat/support-chat.dto.ts index 0bfdd94e..e4b1e556 100644 --- a/backend/src/support-chat/support-chat.dto.ts +++ b/backend/src/support-chat/support-chat.dto.ts @@ -1,4 +1,7 @@ -import { IsString, Length } from 'class-validator'; +import { IsOptional, IsString, IsUrl, Length, Matches } from 'class-validator'; export class SupportChatDto { @IsString() @Length(1, 1500) message!: string; + @IsOptional() @IsString() @Length(36, 36) @Matches(/^[0-9a-f-]{36}$/i) conversationId?: string; + @IsOptional() @IsString() @Length(1, 512) entryPath?: string; + @IsOptional() @IsUrl({ require_tld: false }) @Length(1, 2048) pageUrl?: string; } diff --git a/backend/src/support-chat/support-chat.service.spec.ts b/backend/src/support-chat/support-chat.service.spec.ts index 308171c5..b44043e9 100644 --- a/backend/src/support-chat/support-chat.service.spec.ts +++ b/backend/src/support-chat/support-chat.service.spec.ts @@ -7,7 +7,29 @@ describe('model intent routing', () => { afterEach(()=>jest.restoreAllMocks()); function model(body:any) { return jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>body} as any); } it('guest model wallet does not load private rows',async()=>{model({intent:'wallet'});expect((await service.ask({message:'cheghadr etebar daram'})).answer).toContain('وارد');expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();}); - it('uses semantic model intent rather than message keywords',async()=>{const f=model({intent:'wallet'});expect((await service.ask({message:'چقدر اعتبار دارم؟'},{id:'alice'})).answer).toContain('17');expect(prisma.user.findUnique).toHaveBeenCalledWith({where:{id:'alice'},select:{walletBalance:true}});expect(JSON.parse(f.mock.calls[0][1]!.body as string)).toEqual({message:'چقدر اعتبار دارم؟',selection:{provider:'p',model:'m'}});expect(f).toHaveBeenCalledTimes(1);}); + it('uses semantic model intent rather than message keywords',async()=>{const f=model({intent:'wallet'});expect((await service.ask({message:'چقدر اعتبار دارم؟'},{id:'alice'})).answer).toContain('17');expect(prisma.user.findUnique).toHaveBeenCalledWith({where:{id:'alice'},select:{walletBalance:true}});expect(JSON.parse(f.mock.calls[0][1]!.body as string)).toEqual({message:'چقدر اعتبار دارم؟',conversation_history:[],selection:{provider:'p',model:'m'}});expect(f).toHaveBeenCalledTimes(1);}); it.each([{intent:'admin'},{intent:'wallet',userId:'bob'},{answer:'orders'},{intent:null},{}])('fails closed on invalid classifier %j',async body=>{model(body);await expect(service.ask({message:'سلام'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();expect(prisma.product.findMany).not.toHaveBeenCalled();}); it('classifier outage does not fall back to keyword routing',async()=>{jest.spyOn(global,'fetch').mockRejectedValue(new Error('secret'));await expect(service.ask({message:'کیف پول'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();}); }); + + +describe('persistent conversations', () => { + it('creates a conversation and stores both messages without blocking the answer', async () => { + const conversation = { id: '11111111-1111-4111-8111-111111111111', userId: null }; + const prisma: any = { + product: { findMany: jest.fn().mockResolvedValue([]) }, + supportConversation: { create: jest.fn().mockResolvedValue(conversation), update: jest.fn().mockResolvedValue(conversation), findUnique: jest.fn().mockResolvedValue(conversation) }, + supportConversationMessage: { createMany: jest.fn().mockResolvedValue({}) }, + }; + process.env.SUPPORT_CHAT_URL = 'http://internal/ask'; + process.env.SUPPORT_CHAT_KEY = 'test'; + jest.spyOn(global, 'fetch').mockImplementation(async (url, opts: any) => ({ + ok: true, status: 200, json: async () => String(url).endsWith('/classify') ? { intent: 'public' } : { answer: 'پاسخ' }, + }) as any); + const service = new SupportChatService(prisma, { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } as any); + const result = await service.ask({ message: 'سلام', entryPath: '/products' } as any); + expect(result).toMatchObject({ conversationId: conversation.id, answer: 'پاسخ' }); + expect(prisma.supportConversation.create).toHaveBeenCalled(); + expect(prisma.supportConversationMessage.createMany).toHaveBeenCalledTimes(1); + }); +}); diff --git a/backend/src/support-chat/support-chat.service.ts b/backend/src/support-chat/support-chat.service.ts index 3f03617c..4cdc3e9d 100644 --- a/backend/src/support-chat/support-chat.service.ts +++ b/backend/src/support-chat/support-chat.service.ts @@ -1,22 +1,27 @@ -import { Injectable, ServiceUnavailableException } from '@nestjs/common'; +import { Injectable, NotFoundException, ServiceUnavailableException } from '@nestjs/common'; +import { randomUUID } from 'crypto'; import { PrismaService } from '../prisma/prisma.service'; import { SupportChatDto } from './support-chat.dto'; import { SupportChatSettingsService } from './support-chat-settings.service'; +const MAX_HISTORY = 20; +const safePath = (v?: string) => v ? v.split('?')[0].slice(0, 512) : undefined; export const UNAVAILABLE = 'پشتیبان هوشمند فعلاً در دسترس نیست. لطفاً کمی بعد دوباره تلاش کنید یا تیکت پشتیبانی ثبت کنید.'; @Injectable() export class SupportChatService { constructor(private readonly prisma: PrismaService, private readonly settings: SupportChatSettingsService) {} + async history(id: string, user?: { id: string }) { const db: any = this.prisma as any; const row = await db.supportConversation?.findUnique({ where: { id }, include: { messages: { orderBy: { sequence: 'asc' }, take: MAX_HISTORY } } }); if (!row || (user?.id ? row.userId !== user.id : row.userId !== null)) throw new NotFoundException('گفتگو یافت نشد.'); return { conversationId: id, messages: row.messages.map((m: any) => ({ role: m.role, content: m.content, createdAt: m.createdAt })) }; } async ask(input: SupportChatDto, user?: { id: string }) { const config = await this.settings.read(); if (!config.enabled) throw new ServiceUnavailableException(UNAVAILABLE); + const db: any = this.prisma as any; let conversation: any = null; if (input.conversationId && db.supportConversation) { conversation = await db.supportConversation.findUnique({ where: { id: input.conversationId }, include: { messages: { orderBy: { sequence: 'asc' }, take: MAX_HISTORY } } }); if (!conversation || (user?.id ? conversation.userId !== user.id : conversation.userId !== null)) throw new NotFoundException('گفتگو یافت نشد.'); } else if (db.supportConversation) { conversation = await db.supportConversation.create({ data: { id: randomUUID(), userId: user?.id ?? null, entryPath: safePath(input.pageUrl || input.entryPath), expiresAt: new Date(Date.now() + 90 * 86400000) } }); conversation.messages = []; } const conversation_history = (conversation?.messages || []).slice(-MAX_HISTORY).map((m: any) => ({ role: m.role, content: m.content })); const selection = { provider: config.provider, model: config.model }; const url = process.env.SUPPORT_CHAT_URL; const key = process.env.SUPPORT_CHAT_KEY; let intent: 'public' | 'orders' | 'wallet'; try { if (!url || !key || !url.endsWith('/ask')) throw new Error('disabled'); - const response = await fetch(url.replace(/\/ask$/, '/classify'), { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(45000), body: JSON.stringify({ message: input.message, selection }) }); + const response = await fetch(url.replace(/\/ask$/, '/classify'), { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(45000), body: JSON.stringify({ message: input.message, conversation_history, selection }) }); if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ می‌دهم. پیوند دلخواه پذیرفته نمی‌شود.' }; if (!response.ok) throw new Error('upstream'); const data = await response.json(); @@ -39,12 +44,12 @@ export class SupportChatService { const url = process.env.SUPPORT_CHAT_URL; const key = process.env.SUPPORT_CHAT_KEY; if (!url || !key) throw new Error('disabled'); - const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(45000), body: JSON.stringify({ message: input.message, catalog: products, selection }) }); + const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(45000), body: JSON.stringify({ message: input.message, catalog: products, conversation_history, selection }) }); if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ می‌دهم. پیوند دلخواه یا موضوع خارج از این حوزه پذیرفته نمی‌شود.' }; if (!response.ok) throw new Error('upstream'); const data = await response.json(); if (typeof data.answer !== 'string' || !data.answer.trim() || data.answer.length > 6000 || /traceback|api.?key|provider|rate.?limit|hermes|authentication|exception|https?:\/\/(?:localhost|127\.)/i.test(data.answer)) throw new Error('unsafe'); - return { answer: data.answer }; + const answer = data.answer; if (conversation) { try { const n = conversation.messages.length; await db.supportConversationMessage.createMany({ data: [{ conversationId: conversation.id, role: 'user', content: input.message, sequence: n }, { conversationId: conversation.id, role: 'assistant', content: answer, sequence: n + 1 }] }); } catch {} } return { answer, conversationId: conversation?.id, contextLimited: conversation_history.length >= MAX_HISTORY }; } catch { throw new ServiceUnavailableException(UNAVAILABLE); } } } diff --git a/frontend/application/components/SupportChat.tsx b/frontend/application/components/SupportChat.tsx index 22425594..214701bc 100644 --- a/frontend/application/components/SupportChat.tsx +++ b/frontend/application/components/SupportChat.tsx @@ -34,15 +34,19 @@ export default function SupportChat() { 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(null); const chatScrollRef = useRef(null); useEffect(() => { identity.current = token(); + try { const saved = localStorage.getItem('canina-support-conversation'); if (saved) setConversationId(saved); } catch {} const check = () => { if (identity.current !== token()) { identity.current = token(); + try { const saved = localStorage.getItem('canina-support-conversation'); if (saved) setConversationId(saved); } catch {} pending.current?.abort(); setRows([]); setMessage(''); @@ -77,6 +81,7 @@ export default function SupportChat() { const question = message.trim(); setMessage(''); setBusy(true); + setRows((r) => [...r.slice(-9), { question, answer: 'در حال بررسی…' }]); const controller = new AbortController(); pending.current = controller; let answer = unavailable; @@ -89,7 +94,7 @@ export default function SupportChat() { ...(current ? { Authorization: `Bearer ${current}` } : {}) }, credentials: 'include', - body: JSON.stringify({ message: question }), + body: JSON.stringify({ message: question, ...(conversationId ? { conversationId } : {}), entryPath: window.location.pathname }), signal: AbortSignal.any([controller.signal, AbortSignal.timeout(50000)]) }); if (response.status === 401) { @@ -97,12 +102,14 @@ export default function SupportChat() { } else if (response.ok) { const data = await response.json(); if (typeof data.answer === 'string') answer = data.answer; + if (typeof data.conversationId === 'string') { setConversationId(data.conversationId); try { localStorage.setItem('canina-support-conversation', data.conversationId); } catch {} } + setContextLimited(data.contextLimited === true); } } catch { // safe fallback kept } if (!controller.signal.aborted && token() === current) { - setRows((r) => [...r.slice(-9), { question, answer }]); + setRows((r) => { const next = [...r]; const i = next.length - 1; if (i >= 0 && next[i].question === question && next[i].answer === 'در حال بررسی…') next[i] = { question, answer }; return next; }); } if (pending.current === controller) setBusy(false); } @@ -156,6 +163,7 @@ export default function SupportChat() { AI

راهنمای محصولات و سلامت پت

+ + {contextLimited &&
برای ادامه دقیق‌تر، گفتگوی جدیدی شروع کنید یا با پشتیبانی تماس بگیرید.
}
Shift+Enter خط جدید