feat(support-chat): persist conversations and analytics
Deploy Canina / deploy (push) Failing after 28s

This commit is contained in:
devops committed 2026-10-15 07:28:02 +00:00
1 parent 59ab154d0f
commit def903734f
7 files changed
+97 -10

No files matched your search

@@ -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;
+37
View File
@@ -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
@@ -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')
+4 -1
View File
@@ -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;
}
@@ -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);
});
});
@@ -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); }
}
}
@@ -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<AbortController | null>(null);
const chatScrollRef = useRef<HTMLDivElement | null>(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() {
<span className="text-[10px] bg-canina-gold/20 text-canina-gold px-1.5 py-0.5 rounded border border-canina-gold/30">AI</span>
</h3>
<p className="text-[11px] text-white/70">راهنمای محصولات و سلامت پت</p>
<button type="button" className="text-[11px] text-canina-gold hover:underline" onClick={() => { setRows([]); setConversationId(''); setContextLimited(false); try { localStorage.removeItem('canina-support-conversation'); } catch {} }}>گفتگوی جدید</button>
</div>
</div>
<button
@@ -180,7 +188,7 @@ export default function SupportChat() {
<svg className="h-4 w-4 text-canina-blue shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
</svg>
<span>پشتیبان هوشمند کنینا · هر پیام مستقل است. اطلاعات تغذیه و مکمل‌ها جایگزین تشخیص دامپزشک نیست.</span>
<span>پشتیبان هوشمند کنینا · پیام‌ها در همین گفت‌وگو حفظ می‌شوند. اطلاعات تغذیه و مکمل‌ها جایگزین تشخیص دامپزشک نیست.</span>
</div>
{rows.length === 0 && (
@@ -252,6 +260,7 @@ export default function SupportChat() {
</button>
</form>
{contextLimited && <div role="status" className="mb-2 rounded bg-amber-50 p-2 text-[11px] text-amber-800">برای ادامه دقیق‌تر، گفتگوی جدیدی شروع کنید یا با پشتیبانی تماس بگیرید.</div>}
<div className="mt-2 flex items-center justify-between px-1 text-[11px] text-medical-gray-500">
<span>Shift+Enter خط جدید</span>
<a