96 lines
10 KiB
TypeScript
96 lines
10 KiB
TypeScript
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';
|
|
|
|
export const UNAVAILABLE = 'پشتیبان هوشمند فعلاً در دسترس نیست. لطفاً کمی بعد دوباره تلاش کنید یا تیکت پشتیبانی ثبت کنید.';
|
|
const MAX_HISTORY = 20;
|
|
const safePath = (v?: string) => v?.split('?')[0].slice(0, 512);
|
|
const safeBrowserId = (v?: string) => v && /^[A-Za-z0-9_-]{1,64}$/.test(v) ? v : undefined;
|
|
const resolvePageContext = async (db: any, entryPath?: string) => {
|
|
const path = safePath(entryPath);
|
|
if (!path || !path.startsWith('/') || path.includes('..') || /[?#]/.test(path)) return { type: 'unknown', path: path || '/' };
|
|
const match = path.match(/^\/(shop|blog|wiki)\/([A-Za-z0-9_-]+)$/);
|
|
if (!match) return { type: path === '/contact' ? 'contact' : 'other', path };
|
|
const [type, slug] = match.slice(1);
|
|
if (type === 'shop') {
|
|
const row = await db.product.findFirst({ where: { slug }, select: { slug: true, nameFa: true, shortDescription: true, description: true } });
|
|
return row ? { type: 'product', slug: row.slug, title: row.nameFa, contentExcerpt: String(row.shortDescription || row.description || '').slice(0, 1200), path } : { type: 'product', slug, path };
|
|
}
|
|
if (type === 'blog') {
|
|
const row = await db.blog.findFirst({ where: { slug, status: 'PUBLISHED' }, select: { slug: true, title: true, excerpt: true, content: true } });
|
|
return row ? { type: 'blog', slug: row.slug, title: row.title, contentExcerpt: String(row.excerpt || row.content || '').replace(/<[^>]*>/g, '').slice(0, 1200), path } : { type: 'blog', slug, path };
|
|
}
|
|
const row = await db.wiki.findFirst({ where: { key: slug }, select: { key: true, term: true, description: true } });
|
|
return row ? { type: 'wiki', slug: row.key, title: row.term, contentExcerpt: String(row.description || '').slice(0, 1200), path } : { type: 'wiki', slug, path };
|
|
};
|
|
|
|
const extract = (question: string, answer: string, products: any[]) => {
|
|
const q = question.toLowerCase();
|
|
const topics = ['nutrition','supplement','health','order','wallet','product','shipping'].filter(x => q.includes(x));
|
|
if (/تغذ|غذا|مکمل|ویتامین/.test(q)) topics.push('nutrition');
|
|
if (/سلامت|بیمار|دامپزشک/.test(q)) topics.push('health');
|
|
if (/سفارش|ارسال/.test(q)) topics.push('order');
|
|
const productSlugs = (products || []).filter(p => p.slug && (q.includes(String(p.slug).toLowerCase()) || q.includes(String(p.nameFa || '').toLowerCase()))).map(p => p.slug).slice(0, 20);
|
|
const uniqueTopics = [...new Set(topics)].slice(0, 20);
|
|
const unanswered = /نمی.?دانم|اطلاعاتی ندارم|پاسخ ندارم|متوجه نشدم/i.test(answer);
|
|
const needsFollowup = unanswered || /دامپزشک|پشتیبانی|تیکت|پیگیری/i.test(answer);
|
|
const escalationSignal = /فوری|شکایت|مشکل جدی|خطر|اورژانس/i.test(question + ' ' + answer);
|
|
const summary = `موضوع: ${uniqueTopics.join(', ') || 'عمومی'}؛ محصولات: ${productSlugs.join(', ') || 'ندارد'}؛ نیاز به پیگیری: ${needsFollowup ? 'بله' : 'خیر'}`;
|
|
return { productSlugs, topics: uniqueTopics, unanswered, needsFollowup, escalationSignal, summary };
|
|
};
|
|
@Injectable()
|
|
export class SupportChatService {
|
|
constructor(private readonly prisma: PrismaService, private readonly settings: SupportChatSettingsService) {}
|
|
private db() { return this.prisma as any; }
|
|
async history(id: string, user?: { id: string }) {
|
|
const row = await this.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 = this.db(); let conversation: any;
|
|
if (input.conversationId) {
|
|
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 {
|
|
conversation = await db.supportConversation.create({ data: { id: randomUUID(), userId: user?.id ?? null, anonymousBrowserId: safeBrowserId(input.anonymousBrowserId), entryPath: safePath(input.entryPath), expiresAt: new Date(Date.now() + 90 * 86400000) }, include: { messages: true } });
|
|
}
|
|
const conversationHistory = (conversation.messages || []).slice(-MAX_HISTORY).map((m: any) => ({ role: m.role, content: m.content }));
|
|
const selection = { provider: config.provider, model: config.model };
|
|
const pageContext = await resolvePageContext(db, input.entryPath); const url = process.env.SUPPORT_CHAT_URL; const key = process.env.SUPPORT_CHAT_KEY;
|
|
const pets = user && db.pet?.findMany ? await db.pet.findMany({ where: { userId: user.id }, select: { id: true, name: true, type: true, breed: true, age: true, weight: true, activityLevel: true, medicalConditions: { select: { condition: true } } }, take: 20, orderBy: { createdAt: 'asc' } }) : [];
|
|
const petContext = pets.map((pet: any) => ({ ...pet, medicalConditions: pet.medicalConditions.map((item: any) => item.condition) }));
|
|
let intent: 'public' | 'orders' | 'wallet' | 'profile';
|
|
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, conversation_history: conversationHistory, pet_context: petContext, selection }) });
|
|
if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ میدهم.' };
|
|
if (!response.ok) throw new Error('upstream'); const data = await response.json();
|
|
if (!data || Object.keys(data).length !== 1 || !['public','orders','wallet','profile'].includes(data.intent)) throw new Error('intent'); intent = data.intent;
|
|
} catch { throw new ServiceUnavailableException(UNAVAILABLE); }
|
|
if (intent !== 'public' && !user) return { answer: 'برای مشاهده اطلاعات حساب، سفارشها یا کیف پول خود ابتدا وارد حساب کاربری شوید.', conversationId: conversation.id, contextLimited: conversationHistory.length >= MAX_HISTORY };
|
|
let answer: string; let products: any[] = [];
|
|
try {
|
|
if (intent === 'wallet') { const row = await this.prisma.user.findUnique({ where: { id: user!.id }, select: { walletBalance: true } }); if (!row) throw new Error('missing'); answer = `موجودی کیف پول شما: ${row.walletBalance.toString()} تومان.`; } else if (intent === 'profile') { const row = await this.prisma.user.findUnique({ where: { id: user!.id }, select: { firstName: true, lastName: true, mobile: true, email: true } }); if (!row) throw new Error('missing'); answer = `اطلاعات تماس ثبتشده برای حساب شما:
|
|
شماره موبایل: ${row.mobile || 'ثبت نشده'}
|
|
ایمیل: ${row.email || 'ثبت نشده'}.`; }
|
|
else if (intent === 'orders') { const rows = await this.prisma.order.findMany({ where: { userId: user!.id }, select: { id: true, status: true, totalAmount: true }, take: 5, orderBy: { createdAt: 'desc' } }); answer = rows.length ? rows.map(r => `سفارش ${r.id}: ${r.status} — ${r.totalAmount.toString()} تومان`).join('\n') : 'سفارشی برای حساب شما ثبت نشده است.'; }
|
|
else {
|
|
products = await this.prisma.product.findMany({ take: 80, orderBy: { nameFa: 'asc' }, select: { nameFa: true, nameEn: true, slug: true, priceValue: true, stock: true, stockStatus: true, suitableFor: true, shortDescription: true } });
|
|
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: conversationHistory, page_context: pageContext, pet_context: petContext, selection }) });
|
|
if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ میدهم.', conversationId: conversation.id };
|
|
if (!response.ok) throw new Error('upstream'); const data = await response.json(); answer = data.answer;
|
|
if (typeof answer !== 'string' || !answer.trim() || answer.length > 6000 || /traceback|api.?key|provider|rate.?limit|hermes|authentication|exception|https?:\/\/(?:localhost|127\.)/i.test(answer)) throw new Error('unsafe');
|
|
}
|
|
} catch { throw new ServiceUnavailableException(UNAVAILABLE); }
|
|
const analytics = extract(input.message + ' ' + JSON.stringify(pageContext), answer!, products);
|
|
analytics.summary = `${analytics.summary}; صفحه: ${pageContext.type} ${pageContext.slug || pageContext.path || ''}`.slice(0, 1000);
|
|
await db.supportConversationMessage.createMany({ data: [{ conversationId: conversation.id, role: 'user', content: input.message, sequence: conversationHistory.length }, { conversationId: conversation.id, role: 'assistant', content: answer!, sequence: conversationHistory.length + 1 }] });
|
|
await db.supportConversation.update({ where: { id: conversation.id }, data: { productSlugs: analytics.productSlugs, topics: analytics.topics, unanswered: analytics.unanswered, needsFollowup: analytics.needsFollowup, escalationSignal: analytics.escalationSignal, summary: analytics.summary, summaryStatus: 'completed' } });
|
|
return { answer: answer!, conversationId: conversation.id, contextLimited: conversationHistory.length + 2 >= MAX_HISTORY };
|
|
}
|
|
}
|