import { Injectable, ServiceUnavailableException } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { SupportChatDto } from './support-chat.dto'; export const UNAVAILABLE = 'پشتیبان هوشمند فعلاً در دسترس نیست. لطفاً کمی بعد دوباره تلاش کنید یا تیکت پشتیبانی ثبت کنید.'; @Injectable() export class SupportChatService { constructor(private readonly prisma: PrismaService) {} async ask(input: SupportChatDto, user?: { id: string }) { if (input.scope !== 'public' && !user) return { answer: 'برای مشاهده سفارش‌ها یا کیف پول خود ابتدا وارد حساب کاربری شوید.' }; if (input.scope === 'wallet') { const row = await this.prisma.user.findUnique({ where: { id: user!.id }, select: { walletBalance: true } }); if (!row) throw new ServiceUnavailableException(UNAVAILABLE); return { answer: `موجودی کیف پول شما: ${row.walletBalance.toString()} تومان.` }; } if (input.scope === 'orders') { const rows = await this.prisma.order.findMany({ where: { userId: user!.id }, select: { id: true, status: true, totalAmount: true, createdAt: true }, take: 5, orderBy: { createdAt: 'desc' } }); return { answer: rows.length ? rows.map(r => `سفارش ${r.id}: ${r.status} — ${r.totalAmount.toString()} تومان`).join('\n') : 'سفارشی برای حساب شما ثبت نشده است.' }; } // Private account rows never leave the backend, even when the model is compromised. try { const 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 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 }) }); 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 }; } catch { throw new ServiceUnavailableException(UNAVAILABLE); } } }