routers.ts 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519
  1. import { z } from "zod";
  2. import { nanoid } from "nanoid";
  3. import { TRPCError } from "@trpc/server";
  4. import { COOKIE_NAME } from "@shared/const";
  5. import { getSessionCookieOptions } from "./_core/cookies";
  6. import { systemRouter } from "./_core/systemRouter";
  7. import { publicProcedure, protectedProcedure, agentProcedure, adminProcedure, router } from "./_core/trpc";
  8. import { invokeLLM } from "./_core/llm";
  9. import { notifyOwner } from "./_core/notification";
  10. import bcrypt from "bcryptjs";
  11. import {
  12. createConversation, getConversations, getConversationsAdvanced, getConversationById,
  13. getConversationBySessionId, updateConversationStatus, getConversationStats,
  14. addMessage, getMessagesByConversation,
  15. getConversationMessageCounts, getAgentUsers,
  16. bulkUpdateConversationStatus, deleteConversations,
  17. saveWorkflow, getWorkflow,
  18. getWorkflowSuggestions, updateWorkflowSuggestionStatus, bulkCreateWorkflowSuggestions,
  19. getAllUsers, updateUserRole, updateUserErpContactCid, getUserById, deleteUser, getUserByEmail,
  20. getUserByEmailWithPassword, createUserWithPassword, updateUserPassword,
  21. createPasswordResetToken, getPasswordResetToken, markPasswordResetTokenUsed,
  22. createInvitation, getAllInvitations, getInvitationByToken, updateInvitationStatus,
  23. expireOldInvitations, getInvitationByEmail,
  24. createAuditLog, getAuditLogs,
  25. trackAnalyticsEvent, getAnalyticsEvents, getAnalyticsSummary, getIntentStats, getResponseTimeStats,
  26. createDataSource, getDataSources, getDataSourceById, updateDataSource, deleteDataSource,
  27. createApiConnection, getApiConnections, getApiConnectionById, updateApiConnection, deleteApiConnection, incrementApiConnectionExecution,
  28. rateConversation,
  29. searchKnowledge, incrementKnowledgeUseCount, logKnowledgeSuggestion,
  30. getKnowledgeEntries, getKnowledgeEntryById, createKnowledgeEntry,
  31. updateKnowledgeEntry, deleteKnowledgeEntry, bulkCreateKnowledgeEntries,
  32. getKnowledgeSuggestions, promoteKnowledgeSuggestion, dismissKnowledgeSuggestion,
  33. getKnowledgeProducts, bulkCreateKnowledgeProducts, deleteAllKnowledgeProducts,
  34. } from "./db";
  35. import { detectFlowIntent, executeFlow } from "./flowEngine";
  36. import { runApiConnection } from "./apiConnectionRunner";
  37. import { messages } from "../drizzle/schema";
  38. import { eq, desc } from "drizzle-orm";
  39. import { sdk } from "./_core/sdk";
  40. import { ENV } from "./_core/env";
  41. import {
  42. lookupOrder,
  43. lookupOrdersByCustomer,
  44. lookupOrdersByPO,
  45. lookupTrackingByCustomer,
  46. lookupCatalog,
  47. lookupStock,
  48. lookupContact,
  49. lookupProductImages,
  50. } from "./erpTools";
  51. /* ─── Homelegance chatbot system prompt ─── */
  52. const SYSTEM_PROMPT = `You are **Ellie**, the Homelegance AI Assistant — a warm, knowledgeable furniture expert helping visitors on homelegance.com. Always introduce yourself as Ellie when greeting new visitors.
  53. About Homelegance:
  54. - Homelegance is a leading wholesale furniture manufacturer and distributor
  55. - They offer living room, bedroom, dining room, and accent furniture
  56. - Their customers are primarily furniture retailers and dealers (B2B)
  57. - They have collections ranging from traditional to contemporary styles
  58. Your capabilities:
  59. 1. **Product Discovery**: Help users find furniture by category, style, collection, or room type
  60. 2. **Order Status**: Help dealers check order status (ask for order number)
  61. 3. **Dealer Locator**: Help find authorized Homelegance dealers by location
  62. 4. **Warranty & Returns**: Answer questions about warranty policies and return procedures
  63. 5. **General FAQ**: Answer common questions about Homelegance products and services
  64. Guidelines:
  65. - Be warm, professional, and concise
  66. - When users ask about products, suggest specific categories and collections
  67. - For order inquiries, always ask for the order number
  68. - If you cannot help with something, offer to connect them with a human agent
  69. - Keep responses under 150 words unless detailed information is needed
  70. - Use markdown formatting for lists and emphasis when helpful`;
  71. export const appRouter = router({
  72. system: systemRouter,
  73. auth: router({
  74. me: publicProcedure.query(opts => opts.ctx.user),
  75. logout: publicProcedure.mutation(({ ctx }) => {
  76. const cookieOptions = getSessionCookieOptions(ctx.req);
  77. ctx.res.clearCookie(COOKIE_NAME, { ...cookieOptions, maxAge: -1 });
  78. return { success: true } as const;
  79. }),
  80. /** Register a new user with email/password */
  81. register: publicProcedure
  82. .input(z.object({
  83. email: z.string().email(),
  84. password: z.string().min(8).max(128),
  85. name: z.string().min(1).max(100),
  86. }))
  87. .mutation(async ({ input, ctx }) => {
  88. const existing = await getUserByEmailWithPassword(input.email);
  89. if (existing) {
  90. throw new TRPCError({
  91. code: "CONFLICT",
  92. message: "An account with this email already exists",
  93. });
  94. }
  95. const passwordHash = await bcrypt.hash(input.password, 12);
  96. const user = await createUserWithPassword({
  97. email: input.email,
  98. name: input.name,
  99. passwordHash,
  100. });
  101. if (!user) {
  102. throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Failed to create account" });
  103. }
  104. // Create session
  105. const sessionToken = await sdk.createSessionToken(user.openId, {
  106. name: user.name || "",
  107. expiresInMs: 30 * 24 * 60 * 60 * 1000, // 30 days
  108. });
  109. const cookieOptions = getSessionCookieOptions(ctx.req);
  110. ctx.res.cookie(COOKIE_NAME, sessionToken, { ...cookieOptions, maxAge: 30 * 24 * 60 * 60 * 1000 });
  111. return { success: true, user: { id: user.id, name: user.name, email: user.email, role: user.role } };
  112. }),
  113. /** Login with email/password */
  114. login: publicProcedure
  115. .input(z.object({
  116. email: z.string().email(),
  117. password: z.string().min(1),
  118. }))
  119. .mutation(async ({ input, ctx }) => {
  120. const user = await getUserByEmailWithPassword(input.email);
  121. if (!user || !user.passwordHash) {
  122. throw new TRPCError({
  123. code: "UNAUTHORIZED",
  124. message: "Invalid email or password",
  125. });
  126. }
  127. const isValid = await bcrypt.compare(input.password, user.passwordHash);
  128. if (!isValid) {
  129. throw new TRPCError({
  130. code: "UNAUTHORIZED",
  131. message: "Invalid email or password",
  132. });
  133. }
  134. // Create session
  135. const sessionToken = await sdk.createSessionToken(user.openId, {
  136. name: user.name || "",
  137. expiresInMs: 30 * 24 * 60 * 60 * 1000,
  138. });
  139. const cookieOptions = getSessionCookieOptions(ctx.req);
  140. ctx.res.cookie(COOKIE_NAME, sessionToken, { ...cookieOptions, maxAge: 30 * 24 * 60 * 60 * 1000 });
  141. return { success: true, user: { id: user.id, name: user.name, email: user.email, role: user.role } };
  142. }),
  143. /** Request password reset — generates a token */
  144. forgotPassword: publicProcedure
  145. .input(z.object({ email: z.string().email() }))
  146. .mutation(async ({ input }) => {
  147. const user = await getUserByEmailWithPassword(input.email);
  148. // Always return success to prevent email enumeration
  149. if (!user || !user.passwordHash) {
  150. return { success: true, message: "If an account with that email exists, a reset link has been generated." };
  151. }
  152. const token = nanoid(32);
  153. const expiresAt = new Date(Date.now() + 60 * 60 * 1000); // 1 hour
  154. await createPasswordResetToken({
  155. userId: user.id,
  156. token,
  157. expiresAt,
  158. });
  159. // In production, you would send an email here.
  160. // For demo, we return the token (in production, NEVER return the token)
  161. try {
  162. await notifyOwner({
  163. title: "Password Reset Requested",
  164. content: `Password reset requested for ${input.email}. Reset link: /reset-password/${token}`,
  165. });
  166. } catch (e) { /* non-critical */ }
  167. return { success: true, message: "If an account with that email exists, a reset link has been generated." };
  168. }),
  169. /** Validate a password reset token */
  170. validateResetToken: publicProcedure
  171. .input(z.object({ token: z.string() }))
  172. .query(async ({ input }) => {
  173. const resetToken = await getPasswordResetToken(input.token);
  174. if (!resetToken) {
  175. return { valid: false, reason: "Invalid reset link" } as const;
  176. }
  177. if (resetToken.usedAt) {
  178. return { valid: false, reason: "This reset link has already been used" } as const;
  179. }
  180. if (new Date() > resetToken.expiresAt) {
  181. return { valid: false, reason: "This reset link has expired" } as const;
  182. }
  183. const user = await getUserById(resetToken.userId);
  184. return { valid: true, email: user?.email || "" } as const;
  185. }),
  186. /** Reset password using a valid token */
  187. resetPassword: publicProcedure
  188. .input(z.object({
  189. token: z.string(),
  190. newPassword: z.string().min(8).max(128),
  191. }))
  192. .mutation(async ({ input }) => {
  193. const resetToken = await getPasswordResetToken(input.token);
  194. if (!resetToken) {
  195. throw new TRPCError({ code: "NOT_FOUND", message: "Invalid reset link" });
  196. }
  197. if (resetToken.usedAt) {
  198. throw new TRPCError({ code: "BAD_REQUEST", message: "This reset link has already been used" });
  199. }
  200. if (new Date() > resetToken.expiresAt) {
  201. throw new TRPCError({ code: "BAD_REQUEST", message: "This reset link has expired" });
  202. }
  203. const passwordHash = await bcrypt.hash(input.newPassword, 12);
  204. await updateUserPassword(resetToken.userId, passwordHash);
  205. await markPasswordResetTokenUsed(resetToken.id);
  206. return { success: true, message: "Password has been reset successfully" };
  207. }),
  208. }),
  209. /* ─── Chat API (public — used by the chatbot widget) ─── */
  210. chat: router({
  211. startSession: publicProcedure
  212. .input(z.object({
  213. visitorName: z.string().optional(),
  214. visitorEmail: z.string().email().optional(),
  215. }).optional())
  216. .mutation(async ({ input, ctx }) => {
  217. const sessionId = nanoid(16);
  218. const conversation = await createConversation({
  219. sessionId,
  220. visitorName: ctx.user?.name || input?.visitorName || "Visitor",
  221. visitorEmail: ctx.user?.email || input?.visitorEmail,
  222. customerId: ctx.user?.erpContactCid ?? undefined,
  223. status: "active",
  224. });
  225. await addMessage({
  226. conversationId: conversation.id,
  227. sender: "bot",
  228. content: "Welcome to Homelegance! I'm **Ellie**, your AI furniture assistant.",
  229. metadata: {
  230. quickReplies: ["🔥 Hot Deals", "📦 Order Status", "🛋️ Product Catalog"],
  231. },
  232. });
  233. return { sessionId, conversationId: conversation.id };
  234. }),
  235. sendMessage: publicProcedure
  236. .input(z.object({
  237. sessionId: z.string(),
  238. content: z.string().min(1).max(2000),
  239. }))
  240. .mutation(async ({ input, ctx }) => {
  241. const conversation = await getConversationBySessionId(input.sessionId);
  242. if (!conversation) throw new Error("Conversation not found");
  243. await addMessage({
  244. conversationId: conversation.id,
  245. sender: "visitor",
  246. content: input.content,
  247. });
  248. if (conversation.status === "escalated") {
  249. // Notify owner/agents about new message in escalated conversation
  250. notifyOwner({
  251. title: `New message from ${conversation.visitorName || "Visitor"}`,
  252. content: `Customer message in escalated conversation #${conversation.id}: "${input.content.slice(0, 200)}${input.content.length > 200 ? "..." : ""}"`,
  253. }).catch(() => {}); // fire-and-forget
  254. return {
  255. reply: null,
  256. status: "escalated" as const,
  257. message: "Your conversation has been transferred to a human agent. They will respond shortly.",
  258. };
  259. }
  260. // ── Knowledge Base First ──────────────────────────────────────────────
  261. // Search Q&A knowledge base before calling LLM.
  262. let knowledgeAnswer: string | null = null;
  263. try {
  264. const kbMatch = await searchKnowledge(input.content);
  265. if (kbMatch) {
  266. knowledgeAnswer = kbMatch.answer;
  267. // Fire-and-forget: increment use count
  268. incrementKnowledgeUseCount(kbMatch.id).catch(() => {});
  269. }
  270. } catch (kbErr) {
  271. console.error("[KB] search error:", kbErr);
  272. }
  273. if (knowledgeAnswer) {
  274. await addMessage({ conversationId: conversation.id, sender: "bot", content: knowledgeAnswer });
  275. return { reply: knowledgeAnswer, status: conversation.status, source: "knowledge" as const };
  276. }
  277. // ── Workflow Flow Engine ──────────────────────────────────────────────
  278. // Check if user message triggers a live Support Flow.
  279. // Skip for authenticated dealers with erpContactCid — ERP lookup will handle it.
  280. const skipFlow = !!(ctx.user?.erpContactCid);
  281. let flowResult: { content: string; shouldEscalate?: boolean; flowId: string } | null = null;
  282. try {
  283. const matchedFlowId = skipFlow ? null : detectFlowIntent(input.content);
  284. if (matchedFlowId) {
  285. flowResult = await executeFlow(matchedFlowId, input.content);
  286. }
  287. } catch (flowErr) {
  288. console.error("[Flow] engine error:", flowErr);
  289. }
  290. if (flowResult) {
  291. trackAnalyticsEvent({
  292. conversationId: conversation.id,
  293. sessionId: input.sessionId,
  294. eventType: "flow_triggered",
  295. category: flowResult.flowId,
  296. }).catch(() => {});
  297. if (flowResult.shouldEscalate) {
  298. await updateConversationStatus(conversation.id, "escalated");
  299. await addMessage({ conversationId: conversation.id, sender: "bot", content: flowResult.content });
  300. return { reply: flowResult.content, status: "escalated" as const, source: "flow" as const };
  301. }
  302. await addMessage({ conversationId: conversation.id, sender: "bot", content: flowResult.content });
  303. return { reply: flowResult.content, status: conversation.status, source: "flow" as const };
  304. }
  305. const history = await getMessagesByConversation(conversation.id);
  306. // ── ERP intent detection & context injection ──────────────────────────
  307. // Detect what the visitor is asking about and fetch live ERP data.
  308. // The result is appended to the system prompt so Claude has real data.
  309. let erpContext = "";
  310. if (ENV.erpApiKey) {
  311. try {
  312. const msg = input.content;
  313. const msgLower = msg.toLowerCase();
  314. // Build user context for permission-scoped ERP queries.
  315. // Dealers (role="user") are automatically scoped to their own CID by the bridge.
  316. const userCtx = {
  317. role: ctx.user?.role ?? "user",
  318. erpContactCid: ctx.user?.erpContactCid ?? null,
  319. };
  320. // 1. Single order lookup
  321. // Format A: "SO: A8487", "SO# B123" — SO is a label, alphanumeric ID follows
  322. // Format B: "SO-12345", "SO 12345" — SO is part of the digits-only ID
  323. const soLabelMatch = msg.match(/\bSO[-:\s#]+([A-Z]\d{3,})\b/i);
  324. const soPrefixMatch = msg.match(/\bSO[-\s]?\d{4,}\b/i);
  325. const soId = soLabelMatch
  326. ? soLabelMatch[1].toUpperCase()
  327. : soPrefixMatch
  328. ? soPrefixMatch[0].replace(/\s/, "-").toUpperCase()
  329. : null;
  330. if (soId) {
  331. erpContext = await lookupOrder(soId, userCtx);
  332. // 2. "my orders" / "recent orders" — needs customer CID on conversation
  333. } else if (/\b(my orders?|recent orders?|order history|order status|help with my order|check.*order|view.*order|see.*order|show.*order)\b/.test(msgLower)) {
  334. const cid = ctx.user?.erpContactCid ?? (conversation as any).customerId as string | undefined;
  335. if (cid) {
  336. erpContext = await lookupOrdersByCustomer(cid, 5, userCtx);
  337. } else {
  338. erpContext = "NOTE: This user has not been linked to an ERP dealer account. Their erpContactCid is not set. Let them know they should contact support to link their dealer account before order history can be retrieved.";
  339. }
  340. // 3. Shipment tracking — "track my shipment", "tracking number", "where is my package"
  341. } else if (/\b(track|tracking|shipment|shipped|where.*order|delivery status|carrier|ship.*status)\b/.test(msgLower)) {
  342. const cid = ctx.user?.erpContactCid ?? (conversation as any).customerId as string | undefined;
  343. if (cid) {
  344. erpContext = await lookupTrackingByCustomer(cid, 5, userCtx);
  345. } else {
  346. erpContext = "NOTE: This user has not been linked to an ERP dealer account. Their erpContactCid is not set. Ask for their order number to look up tracking.";
  347. }
  348. // 4. PO number lookup — "PO-12345", "purchase order 5678"
  349. } else {
  350. const poMatch = msg.match(/\bPO[-\s]?\d{3,}\b/i);
  351. if (poMatch) {
  352. erpContext = await lookupOrdersByPO(poMatch[0], userCtx);
  353. }
  354. }
  355. // 5. Stock / inventory
  356. if (!erpContext && /\b(in stock|available|inventory|stock|availability)\b/.test(msgLower)) {
  357. // Match model numbers: letter-first (B1234-1) or digit-first (2259W-5, 1436W-6)
  358. const modelMatch = msg.match(/\b(\d{3,}(?:-\d+(?:[*]\d*)?)+|[A-Z]{1,4}\d{2,}[-\w*]*|\d{2,}[A-Z]\d*[-\w*]*)/i);
  359. if (modelMatch) {
  360. erpContext = await lookupStock({ model: modelMatch[1] }, userCtx);
  361. }
  362. }
  363. // 6. Product / catalog search
  364. if (!erpContext && /\b(product|catalog|collection|furniture|model|item|sofa|bed|table|chair|dresser|cabinet)\b/.test(msgLower)) {
  365. // Pull keywords: skip common stop words
  366. const stopWords = new Set(["the","a","an","is","are","do","you","have","i","can","tell","me","about","show","what","which"]);
  367. const keywords = msg
  368. .replace(/[^a-zA-Z0-9 ]/g, " ")
  369. .split(/\s+/)
  370. .filter(w => w.length > 2 && !stopWords.has(w.toLowerCase()))
  371. .slice(0, 4)
  372. .join(" ");
  373. if (keywords) {
  374. erpContext = await lookupCatalog({ description: keywords, limit: 8 }, userCtx);
  375. }
  376. }
  377. // 7. Product images — "show image/photo/picture of [model]" or "image for 1436W-6"
  378. if (!erpContext && /\b(image|images|photo|photos|picture|pictures|what does .* look like|show me)\b/.test(msgLower)) {
  379. const modelMatch = msg.match(/\b(\d{3,}(?:-\d+(?:[*]\d*)?)+|[A-Z]{1,4}\d{2,}[-\w*]*|\d{2,}[A-Z]\d*[-\w*]*)/i);
  380. if (modelMatch) {
  381. erpContext = await lookupProductImages(modelMatch[1], userCtx);
  382. }
  383. }
  384. // 8. Customer / dealer lookup (admin/agent only — dealers see their own record via CID)
  385. if (!erpContext && ctx.user?.role !== "user" && /\b(customer|dealer|account|contact|company)\b/.test(msgLower)) {
  386. const nameMatch = msg.match(/(?:customer|dealer|account|contact|company)[:\s]+([A-Za-z &'.-]{3,40})/i);
  387. if (nameMatch) {
  388. erpContext = await lookupContact({ company: nameMatch[1].trim() }, userCtx);
  389. }
  390. }
  391. } catch (erpErr) {
  392. console.error("[ERP] intent lookup error:", erpErr);
  393. erpContext = "NOTE: ERP data lookup failed (service temporarily unavailable). Do not mention specific order details. Let the user know order lookup is temporarily unavailable and suggest they try again shortly or contact their sales rep.";
  394. }
  395. }
  396. const systemContent = erpContext
  397. ? `${SYSTEM_PROMPT}\n\n---\n[ERP CONTEXT — live data retrieved for this query]\nIMPORTANT: The following real-time ERP data has been fetched for this user. Present it directly in your response. Do NOT ask for an order number or any information already shown below.\n${erpContext}\n---`
  398. : SYSTEM_PROMPT;
  399. const llmMessages = [
  400. { role: "system" as const, content: systemContent },
  401. ...history.map(m => ({
  402. role: (m.sender === "visitor" ? "user" : "assistant") as "user" | "assistant",
  403. content: m.content,
  404. })),
  405. ];
  406. const escalationKeywords = ["speak to human", "representative", "real person", "agent", "talk to someone", "human agent"];
  407. const shouldEscalate = escalationKeywords.some(kw =>
  408. input.content.toLowerCase().includes(kw)
  409. );
  410. if (shouldEscalate) {
  411. await updateConversationStatus(conversation.id, "escalated");
  412. const escalationMsg = "I understand you'd like to speak with a team member. I'm connecting you now — a Homelegance representative will be with you shortly. In the meantime, is there anything else I can help with?";
  413. await addMessage({
  414. conversationId: conversation.id,
  415. sender: "bot",
  416. content: escalationMsg,
  417. });
  418. // Notify owner about escalation
  419. notifyOwner({
  420. title: `Chat escalated: ${conversation.visitorName || "Visitor"}`,
  421. content: `A customer has requested to speak with a human agent. Conversation #${conversation.id}. Last message: "${input.content.slice(0, 200)}"`,
  422. }).catch(() => {}); // fire-and-forget
  423. return { reply: escalationMsg, status: "escalated" as const };
  424. }
  425. try {
  426. const llmResult = await invokeLLM({ messages: llmMessages });
  427. const botReply = llmResult.choices[0]?.message?.content as string || "I apologize, I'm having trouble processing your request. Would you like to speak with a team member?";
  428. await addMessage({
  429. conversationId: conversation.id,
  430. sender: "bot",
  431. content: botReply,
  432. });
  433. // Auto-log as suggestion for continuous improvement
  434. logKnowledgeSuggestion(input.content).catch(() => {});
  435. // Log intent for hot-topic analytics (fire-and-forget)
  436. trackAnalyticsEvent({
  437. conversationId: conversation.id,
  438. sessionId: input.sessionId,
  439. eventType: "intent_detected",
  440. category: "unclassified",
  441. metadata: { snippet: input.content.slice(0, 120) },
  442. }).catch(() => {});
  443. return { reply: botReply, status: conversation.status, source: "llm" as const };
  444. } catch (error) {
  445. console.error("[Chat] LLM error:", error);
  446. const fallback = "I apologize for the inconvenience. I'm experiencing a temporary issue. Would you like me to connect you with a human agent?";
  447. await addMessage({
  448. conversationId: conversation.id,
  449. sender: "bot",
  450. content: fallback,
  451. });
  452. return { reply: fallback, status: conversation.status };
  453. }
  454. }),
  455. rateSatisfaction: publicProcedure
  456. .input(z.object({
  457. sessionId: z.string(),
  458. rating: z.number().int().min(1).max(5),
  459. comment: z.string().max(500).optional(),
  460. }))
  461. .mutation(async ({ input }) => {
  462. return rateConversation(input.sessionId, input.rating, input.comment);
  463. }),
  464. getMessages: publicProcedure
  465. .input(z.object({ sessionId: z.string() }))
  466. .query(async ({ input }) => {
  467. const conversation = await getConversationBySessionId(input.sessionId);
  468. if (!conversation) return { messages: [], status: "closed" as const };
  469. const msgs = await getMessagesByConversation(conversation.id);
  470. return { messages: msgs, status: conversation.status, csatRating: conversation.csatRating };
  471. }),
  472. }),
  473. /* ─── Agent Dashboard API (requires agent or admin role) ─── */
  474. agent: router({
  475. /** Legacy simple list (kept for backward compat) */
  476. conversations: agentProcedure
  477. .input(z.object({ status: z.string().optional() }).optional())
  478. .query(async ({ input }) => {
  479. return getConversations(input?.status);
  480. }),
  481. /** Advanced conversation query with pagination, search, filters, sorting */
  482. conversationsAdvanced: agentProcedure
  483. .input(z.object({
  484. page: z.number().min(1).default(1),
  485. pageSize: z.number().min(5).max(100).default(20),
  486. status: z.string().optional(),
  487. search: z.string().optional(),
  488. agentId: z.number().optional(),
  489. dateFrom: z.string().optional(),
  490. dateTo: z.string().optional(),
  491. sortBy: z.enum(["updated", "created", "visitor", "status", "customerId", "salesRep", "agent"]).default("updated"),
  492. sortOrder: z.enum(["asc", "desc"]).default("desc"),
  493. }).optional())
  494. .query(async ({ input }) => {
  495. const result = await getConversationsAdvanced(input || {});
  496. // Enrich with message counts
  497. const ids = result.conversations.map((c) => c.id);
  498. const messageCounts = await getConversationMessageCounts(ids);
  499. const enriched = result.conversations.map((c) => ({
  500. ...c,
  501. messageCount: messageCounts[c.id] || 0,
  502. }));
  503. return { ...result, conversations: enriched };
  504. }),
  505. /** Get list of agents for filter dropdown */
  506. agents: agentProcedure.query(async () => {
  507. return getAgentUsers();
  508. }),
  509. stats: agentProcedure.query(async () => {
  510. return getConversationStats();
  511. }),
  512. messages: agentProcedure
  513. .input(z.object({ conversationId: z.number() }))
  514. .query(async ({ input }) => {
  515. return getMessagesByConversation(input.conversationId);
  516. }),
  517. reply: agentProcedure
  518. .input(z.object({
  519. conversationId: z.number(),
  520. content: z.string().min(1).max(5000),
  521. }))
  522. .mutation(async ({ input, ctx }) => {
  523. const conversation = await getConversationById(input.conversationId);
  524. if (!conversation) throw new Error("Conversation not found");
  525. const msg = await addMessage({
  526. conversationId: input.conversationId,
  527. sender: "agent",
  528. content: input.content,
  529. metadata: { agentName: ctx.user.name || "Agent", agentId: ctx.user.id },
  530. });
  531. if (conversation.status === "escalated") {
  532. await updateConversationStatus(input.conversationId, "escalated", ctx.user.id);
  533. }
  534. return msg;
  535. }),
  536. updateStatus: agentProcedure
  537. .input(z.object({
  538. conversationId: z.number(),
  539. status: z.enum(["active", "escalated", "resolved", "closed"]),
  540. }))
  541. .mutation(async ({ input, ctx }) => {
  542. return updateConversationStatus(input.conversationId, input.status, ctx.user.id);
  543. }),
  544. /** Bulk update conversation status */
  545. bulkUpdateStatus: agentProcedure
  546. .input(z.object({
  547. conversationIds: z.array(z.number()).min(1),
  548. status: z.enum(["active", "escalated", "resolved", "closed"]),
  549. }))
  550. .mutation(async ({ input, ctx }) => {
  551. return bulkUpdateConversationStatus(input.conversationIds, input.status, ctx.user.id);
  552. }),
  553. /** Delete conversations (admin only) */
  554. deleteConversations: adminProcedure
  555. .input(z.object({
  556. conversationIds: z.array(z.number()).min(1),
  557. }))
  558. .mutation(async ({ input, ctx }) => {
  559. const result = await deleteConversations(input.conversationIds);
  560. await createAuditLog({
  561. action: "delete_conversations",
  562. actorId: ctx.user.id,
  563. actorName: ctx.user.name || "Admin",
  564. details: { count: input.conversationIds.length, ids: input.conversationIds },
  565. });
  566. return result;
  567. }),
  568. }),
  569. /* ─── User Management API (admin only) ─── */
  570. users: router({
  571. /** List all users */
  572. list: adminProcedure.query(async () => {
  573. return getAllUsers();
  574. }),
  575. /** Update a user's role */
  576. updateRole: adminProcedure
  577. .input(z.object({
  578. userId: z.number(),
  579. role: z.enum(["user", "agent", "admin"]),
  580. }))
  581. .mutation(async ({ input, ctx }) => {
  582. if (input.userId === ctx.user.id) {
  583. throw new TRPCError({
  584. code: "BAD_REQUEST",
  585. message: "You cannot change your own role",
  586. });
  587. }
  588. const targetUser = await getUserById(input.userId);
  589. if (!targetUser) {
  590. throw new TRPCError({ code: "NOT_FOUND", message: "User not found" });
  591. }
  592. const previousRole = targetUser.role;
  593. const updated = await updateUserRole(input.userId, input.role);
  594. if (!updated) {
  595. throw new TRPCError({ code: "NOT_FOUND", message: "User not found" });
  596. }
  597. // Audit log
  598. await createAuditLog({
  599. action: "role_change",
  600. actorId: ctx.user.id,
  601. actorName: ctx.user.name || "Admin",
  602. targetId: input.userId,
  603. targetName: targetUser.name || targetUser.email || "User",
  604. details: { previousRole, newRole: input.role },
  605. });
  606. return updated;
  607. }),
  608. /** Get a single user by ID */
  609. getById: adminProcedure
  610. .input(z.object({ userId: z.number() }))
  611. .query(async ({ input }) => {
  612. return getUserById(input.userId);
  613. }),
  614. /** Set or clear the ERP ContactID linked to a user (for dealer permission scoping) */
  615. updateErpContactCid: adminProcedure
  616. .input(z.object({
  617. userId: z.number(),
  618. erpContactCid: z.string().max(64).nullable(),
  619. }))
  620. .mutation(async ({ input, ctx }) => {
  621. const targetUser = await getUserById(input.userId);
  622. if (!targetUser) {
  623. throw new TRPCError({ code: "NOT_FOUND", message: "User not found" });
  624. }
  625. const updated = await updateUserErpContactCid(input.userId, input.erpContactCid);
  626. await createAuditLog({
  627. action: "erp_contact_cid_change",
  628. actorId: ctx.user.id,
  629. actorName: ctx.user.name || "Admin",
  630. targetId: input.userId,
  631. targetName: targetUser.name || targetUser.email || "User",
  632. details: { erpContactCid: input.erpContactCid },
  633. });
  634. return updated;
  635. }),
  636. /** Delete a user */
  637. delete: adminProcedure
  638. .input(z.object({ userId: z.number() }))
  639. .mutation(async ({ input, ctx }) => {
  640. if (input.userId === ctx.user.id) {
  641. throw new TRPCError({
  642. code: "BAD_REQUEST",
  643. message: "You cannot delete your own account",
  644. });
  645. }
  646. const targetUser = await getUserById(input.userId);
  647. if (!targetUser) {
  648. throw new TRPCError({ code: "NOT_FOUND", message: "User not found" });
  649. }
  650. const deleted = await deleteUser(input.userId);
  651. // Audit log
  652. await createAuditLog({
  653. action: "user_deleted",
  654. actorId: ctx.user.id,
  655. actorName: ctx.user.name || "Admin",
  656. targetId: input.userId,
  657. targetName: targetUser.name || targetUser.email || "User",
  658. details: { deletedRole: targetUser.role, deletedEmail: targetUser.email },
  659. });
  660. return { success: true, deletedUser: deleted };
  661. }),
  662. /** Bulk update roles */
  663. bulkUpdateRole: adminProcedure
  664. .input(z.object({
  665. userIds: z.array(z.number()).min(1).max(50),
  666. role: z.enum(["user", "agent", "admin"]),
  667. }))
  668. .mutation(async ({ input, ctx }) => {
  669. const results: { userId: number; success: boolean; error?: string }[] = [];
  670. for (const userId of input.userIds) {
  671. if (userId === ctx.user.id) {
  672. results.push({ userId, success: false, error: "Cannot change own role" });
  673. continue;
  674. }
  675. try {
  676. await updateUserRole(userId, input.role);
  677. results.push({ userId, success: true });
  678. } catch (e) {
  679. results.push({ userId, success: false, error: "Failed to update" });
  680. }
  681. }
  682. await createAuditLog({
  683. action: "bulk_role_change",
  684. actorId: ctx.user.id,
  685. actorName: ctx.user.name || "Admin",
  686. details: { userIds: input.userIds, newRole: input.role, results },
  687. });
  688. return results;
  689. }),
  690. /** Bulk delete users */
  691. bulkDelete: adminProcedure
  692. .input(z.object({
  693. userIds: z.array(z.number()).min(1).max(50),
  694. }))
  695. .mutation(async ({ input, ctx }) => {
  696. const results: { userId: number; success: boolean; error?: string }[] = [];
  697. for (const userId of input.userIds) {
  698. if (userId === ctx.user.id) {
  699. results.push({ userId, success: false, error: "Cannot delete own account" });
  700. continue;
  701. }
  702. try {
  703. await deleteUser(userId);
  704. results.push({ userId, success: true });
  705. } catch (e) {
  706. results.push({ userId, success: false, error: "Failed to delete" });
  707. }
  708. }
  709. await createAuditLog({
  710. action: "bulk_delete",
  711. actorId: ctx.user.id,
  712. actorName: ctx.user.name || "Admin",
  713. details: { userIds: input.userIds, results },
  714. });
  715. return results;
  716. }),
  717. /** Export users as CSV data */
  718. exportCsv: adminProcedure.query(async () => {
  719. const allUsers = await getAllUsers();
  720. const header = "ID,Name,Email,Role,Created At,Last Signed In";
  721. const rows = allUsers.map(u =>
  722. `${u.id},"${(u.name || "").replace(/"/g, '""')}","${(u.email || "").replace(/"/g, '""')}",${u.role},${u.createdAt?.toISOString() || ""},${u.lastSignedIn?.toISOString() || ""}`
  723. );
  724. return { csv: [header, ...rows].join("\n"), count: allUsers.length };
  725. }),
  726. }),
  727. /* ─── Invitation API (admin only) ─── */
  728. invitations: router({
  729. /** List all invitations */
  730. list: adminProcedure.query(async () => {
  731. // Auto-expire old invitations
  732. await expireOldInvitations();
  733. return getAllInvitations();
  734. }),
  735. /** Send a new invitation */
  736. send: adminProcedure
  737. .input(z.object({
  738. email: z.string().email(),
  739. role: z.enum(["user", "agent", "admin"]),
  740. message: z.string().max(500).optional(),
  741. }))
  742. .mutation(async ({ input, ctx }) => {
  743. // Check if user already exists with this email
  744. const existingUser = await getUserByEmail(input.email);
  745. if (existingUser) {
  746. throw new TRPCError({
  747. code: "CONFLICT",
  748. message: `A user with email ${input.email} already exists (role: ${existingUser.role})`,
  749. });
  750. }
  751. // Check for pending invitation to same email
  752. const existingInvites = await getInvitationByEmail(input.email);
  753. const pendingInvite = existingInvites.find(i => i.status === "pending");
  754. if (pendingInvite) {
  755. throw new TRPCError({
  756. code: "CONFLICT",
  757. message: `A pending invitation already exists for ${input.email}. Revoke it first to send a new one.`,
  758. });
  759. }
  760. const token = nanoid(32);
  761. const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000); // 7 days
  762. const invitation = await createInvitation({
  763. email: input.email,
  764. role: input.role,
  765. token,
  766. status: "pending",
  767. invitedById: ctx.user.id,
  768. invitedByName: ctx.user.name || "Admin",
  769. message: input.message || null,
  770. expiresAt,
  771. });
  772. // Audit log
  773. await createAuditLog({
  774. action: "invitation_sent",
  775. actorId: ctx.user.id,
  776. actorName: ctx.user.name || "Admin",
  777. targetName: input.email,
  778. details: { role: input.role, token, expiresAt: expiresAt.toISOString() },
  779. });
  780. // Notify owner
  781. try {
  782. await notifyOwner({
  783. title: `New Invitation Sent`,
  784. content: `${ctx.user.name || "Admin"} invited ${input.email} as ${input.role}. The invitation expires on ${expiresAt.toLocaleDateString()}.`,
  785. });
  786. } catch (e) {
  787. // Non-critical, don't fail the invitation
  788. }
  789. return invitation;
  790. }),
  791. /** Resend an invitation (creates a new token, extends expiry) */
  792. resend: adminProcedure
  793. .input(z.object({ invitationId: z.number() }))
  794. .mutation(async ({ input, ctx }) => {
  795. const existing = await getAllInvitations();
  796. const invitation = existing.find(i => i.id === input.invitationId);
  797. if (!invitation) {
  798. throw new TRPCError({ code: "NOT_FOUND", message: "Invitation not found" });
  799. }
  800. if (invitation.status !== "pending" && invitation.status !== "expired") {
  801. throw new TRPCError({
  802. code: "BAD_REQUEST",
  803. message: `Cannot resend a ${invitation.status} invitation`,
  804. });
  805. }
  806. // Revoke old one
  807. await updateInvitationStatus(invitation.id, "revoked");
  808. // Create new invitation
  809. const token = nanoid(32);
  810. const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
  811. const newInvitation = await createInvitation({
  812. email: invitation.email,
  813. role: invitation.role,
  814. token,
  815. status: "pending",
  816. invitedById: ctx.user.id,
  817. invitedByName: ctx.user.name || "Admin",
  818. message: invitation.message,
  819. expiresAt,
  820. });
  821. await createAuditLog({
  822. action: "invitation_resent",
  823. actorId: ctx.user.id,
  824. actorName: ctx.user.name || "Admin",
  825. targetName: invitation.email,
  826. details: { role: invitation.role, newToken: token },
  827. });
  828. return newInvitation;
  829. }),
  830. /** Revoke a pending invitation */
  831. revoke: adminProcedure
  832. .input(z.object({ invitationId: z.number() }))
  833. .mutation(async ({ input, ctx }) => {
  834. const existing = await getAllInvitations();
  835. const invitation = existing.find(i => i.id === input.invitationId);
  836. if (!invitation) {
  837. throw new TRPCError({ code: "NOT_FOUND", message: "Invitation not found" });
  838. }
  839. if (invitation.status !== "pending") {
  840. throw new TRPCError({
  841. code: "BAD_REQUEST",
  842. message: `Cannot revoke a ${invitation.status} invitation`,
  843. });
  844. }
  845. const updated = await updateInvitationStatus(invitation.id, "revoked");
  846. await createAuditLog({
  847. action: "invitation_revoked",
  848. actorId: ctx.user.id,
  849. actorName: ctx.user.name || "Admin",
  850. targetName: invitation.email,
  851. details: { role: invitation.role },
  852. });
  853. return updated;
  854. }),
  855. /** Validate an invitation token (public — used by invite acceptance page) */
  856. validate: publicProcedure
  857. .input(z.object({ token: z.string() }))
  858. .query(async ({ input }) => {
  859. const invitation = await getInvitationByToken(input.token);
  860. if (!invitation) {
  861. return { valid: false, reason: "Invitation not found" } as const;
  862. }
  863. if (invitation.status === "revoked") {
  864. return { valid: false, reason: "This invitation has been revoked" } as const;
  865. }
  866. if (invitation.status === "accepted") {
  867. return { valid: false, reason: "This invitation has already been accepted" } as const;
  868. }
  869. if (invitation.status === "expired" || new Date() > invitation.expiresAt) {
  870. if (invitation.status !== "expired") {
  871. await updateInvitationStatus(invitation.id, "expired");
  872. }
  873. return { valid: false, reason: "This invitation has expired" } as const;
  874. }
  875. return {
  876. valid: true,
  877. email: invitation.email,
  878. role: invitation.role,
  879. invitedBy: invitation.invitedByName,
  880. message: invitation.message,
  881. expiresAt: invitation.expiresAt,
  882. } as const;
  883. }),
  884. /** Accept an invitation (requires authenticated user) */
  885. accept: protectedProcedure
  886. .input(z.object({ token: z.string() }))
  887. .mutation(async ({ input, ctx }) => {
  888. const invitation = await getInvitationByToken(input.token);
  889. if (!invitation) {
  890. throw new TRPCError({ code: "NOT_FOUND", message: "Invitation not found" });
  891. }
  892. if (invitation.status !== "pending") {
  893. throw new TRPCError({
  894. code: "BAD_REQUEST",
  895. message: `This invitation is ${invitation.status}`,
  896. });
  897. }
  898. if (new Date() > invitation.expiresAt) {
  899. await updateInvitationStatus(invitation.id, "expired");
  900. throw new TRPCError({
  901. code: "BAD_REQUEST",
  902. message: "This invitation has expired",
  903. });
  904. }
  905. // Update user role to the invited role
  906. await updateUserRole(ctx.user.id, invitation.role);
  907. // Mark invitation as accepted
  908. await updateInvitationStatus(invitation.id, "accepted", ctx.user.id);
  909. // Audit log
  910. await createAuditLog({
  911. action: "invitation_accepted",
  912. actorId: ctx.user.id,
  913. actorName: ctx.user.name || ctx.user.email || "User",
  914. targetName: invitation.email,
  915. details: { role: invitation.role, invitedBy: invitation.invitedByName },
  916. });
  917. return { success: true, role: invitation.role };
  918. }),
  919. }),
  920. /* ─── Audit Logs API (admin only) ─── */
  921. auditLogs: router({
  922. list: adminProcedure
  923. .input(z.object({ limit: z.number().min(1).max(200).optional() }).optional())
  924. .query(async ({ input }) => {
  925. return getAuditLogs(input?.limit || 50);
  926. }),
  927. }),
  928. /* ─── Workflow Designer API (admin only) ─── */
  929. workflow: router({
  930. save: adminProcedure
  931. .input(z.object({
  932. workflowId: z.string(),
  933. nodes: z.array(z.object({
  934. workflowId: z.string(),
  935. nodeId: z.string(),
  936. type: z.enum(["greeting", "intent", "response", "condition", "escalation", "action", "end", "customer_data", "sales_order", "guardrail"]),
  937. label: z.string(),
  938. config: z.any().optional(),
  939. positionX: z.number(),
  940. positionY: z.number(),
  941. })),
  942. edges: z.array(z.object({
  943. workflowId: z.string(),
  944. sourceNodeId: z.string(),
  945. targetNodeId: z.string(),
  946. label: z.string().optional(),
  947. condition: z.any().optional(),
  948. })),
  949. }))
  950. .mutation(async ({ input }) => {
  951. return saveWorkflow(input.workflowId, input.nodes, input.edges);
  952. }),
  953. load: adminProcedure
  954. .input(z.object({ workflowId: z.string() }))
  955. .query(async ({ input }) => {
  956. return getWorkflow(input.workflowId);
  957. }),
  958. /** Get AI-suggested nodes for a workflow */
  959. getSuggestions: adminProcedure
  960. .input(z.object({
  961. workflowId: z.string(),
  962. status: z.enum(["pending", "approved", "declined", "waiting"]).optional(),
  963. }))
  964. .query(async ({ input }) => {
  965. return getWorkflowSuggestions(input.workflowId, input.status);
  966. }),
  967. /** Generate AI suggestions from FAQ analysis */
  968. generateSuggestions: adminProcedure
  969. .input(z.object({ workflowId: z.string() }))
  970. .mutation(async ({ input }) => {
  971. // Analyze conversation messages to find frequently asked questions
  972. const db = await (await import("./db")).getDb();
  973. if (!db) throw new Error("Database not available");
  974. // Get recent visitor messages
  975. const recentMessages = await db.select({
  976. content: messages.content,
  977. sender: messages.sender,
  978. }).from(messages)
  979. .where(eq(messages.sender, "visitor"))
  980. .orderBy(desc(messages.createdAt))
  981. .limit(200);
  982. if (recentMessages.length < 3) {
  983. return { suggestions: [], message: "Not enough conversation data to generate suggestions. Need at least 3 visitor messages." };
  984. }
  985. // Use LLM to analyze FAQ patterns and suggest workflow nodes
  986. const msgSample = recentMessages.map(m => m.content).join("\n---\n");
  987. const llmResult = await invokeLLM({
  988. messages: [
  989. {
  990. role: "system",
  991. content: `You are a workflow optimization assistant for Homelegance, a furniture company. Analyze customer messages and identify the top 3-5 most frequently asked question patterns that could benefit from dedicated workflow nodes. For each pattern, suggest a workflow node.
  992. Return a JSON array of suggestions. Each suggestion should have:
  993. - "label": A short descriptive name for the node (e.g., "Shipping ETA Lookup")
  994. - "description": What this node would do
  995. - "nodeType": One of: "response", "action", "condition", "customer_data", "sales_order", "guardrail"
  996. - "faqQuestion": The typical customer question this addresses
  997. - "frequency": Estimated frequency (1-100)
  998. - "config": Configuration object with relevant fields (e.g., {"message": "..."} for response, {"apiEndpoint": "..."} for action, {"blockedTopics": [...]} for guardrail)
  999. Return ONLY the JSON array, no markdown or explanation.`,
  1000. },
  1001. {
  1002. role: "user",
  1003. content: `Analyze these ${recentMessages.length} recent customer messages and suggest workflow nodes:\n\n${msgSample}`,
  1004. },
  1005. ],
  1006. response_format: {
  1007. type: "json_schema",
  1008. json_schema: {
  1009. name: "workflow_suggestions",
  1010. strict: true,
  1011. schema: {
  1012. type: "object",
  1013. properties: {
  1014. suggestions: {
  1015. type: "array",
  1016. items: {
  1017. type: "object",
  1018. properties: {
  1019. label: { type: "string" },
  1020. description: { type: "string" },
  1021. nodeType: { type: "string" },
  1022. faqQuestion: { type: "string" },
  1023. frequency: { type: "integer" },
  1024. config: { type: "object", additionalProperties: true },
  1025. },
  1026. required: ["label", "description", "nodeType", "faqQuestion", "frequency", "config"],
  1027. additionalProperties: false,
  1028. },
  1029. },
  1030. },
  1031. required: ["suggestions"],
  1032. additionalProperties: false,
  1033. },
  1034. },
  1035. },
  1036. });
  1037. let parsed: any[] = [];
  1038. try {
  1039. const content = llmResult.choices[0]?.message?.content as string;
  1040. const result = JSON.parse(content);
  1041. parsed = result.suggestions || result;
  1042. } catch (e) {
  1043. console.error("[Workflow] Failed to parse LLM suggestions:", e);
  1044. return { suggestions: [], message: "Failed to analyze conversation patterns" };
  1045. }
  1046. // Save suggestions to database
  1047. const toInsert = parsed.map((s: any) => ({
  1048. workflowId: input.workflowId,
  1049. suggestedNodeType: s.nodeType || "response",
  1050. label: s.label,
  1051. description: s.description,
  1052. config: s.config || {},
  1053. faqQuestion: s.faqQuestion,
  1054. frequency: s.frequency || 0,
  1055. status: "pending" as const,
  1056. }));
  1057. await bulkCreateWorkflowSuggestions(toInsert);
  1058. return { suggestions: toInsert, message: `Generated ${toInsert.length} suggestions from ${recentMessages.length} messages` };
  1059. }),
  1060. /** Update suggestion status (approve/decline/wait) */
  1061. reviewSuggestion: adminProcedure
  1062. .input(z.object({
  1063. suggestionId: z.number(),
  1064. status: z.enum(["approved", "declined", "waiting"]),
  1065. }))
  1066. .mutation(async ({ input, ctx }) => {
  1067. return updateWorkflowSuggestionStatus(input.suggestionId, input.status, ctx.user.id);
  1068. }),
  1069. }),
  1070. /* ─── Analytics Router ─── */
  1071. analytics: router({
  1072. track: publicProcedure
  1073. .input(z.object({
  1074. conversationId: z.number().optional(),
  1075. sessionId: z.string().optional(),
  1076. eventType: z.enum([
  1077. "session_start", "message_sent", "message_received",
  1078. "intent_detected", "flow_triggered", "escalated",
  1079. "resolved_by_bot", "resolved_by_agent", "abandoned",
  1080. "button_clicked", "feedback_positive", "feedback_negative",
  1081. ]),
  1082. category: z.string().optional(),
  1083. metadata: z.any().optional(),
  1084. }))
  1085. .mutation(async ({ input }) => {
  1086. const id = await trackAnalyticsEvent(input);
  1087. return { id };
  1088. }),
  1089. summary: agentProcedure
  1090. .input(z.object({
  1091. startDate: z.string().optional(),
  1092. endDate: z.string().optional(),
  1093. }).optional())
  1094. .query(async ({ input }) => {
  1095. const startDate = input?.startDate ? new Date(input.startDate) : undefined;
  1096. const endDate = input?.endDate ? new Date(input.endDate) : undefined;
  1097. return getAnalyticsSummary(startDate, endDate);
  1098. }),
  1099. events: agentProcedure
  1100. .input(z.object({
  1101. eventType: z.string().optional(),
  1102. category: z.string().optional(),
  1103. startDate: z.string().optional(),
  1104. endDate: z.string().optional(),
  1105. }).optional())
  1106. .query(async ({ input }) => {
  1107. return getAnalyticsEvents({
  1108. eventType: input?.eventType,
  1109. category: input?.category,
  1110. startDate: input?.startDate ? new Date(input.startDate) : undefined,
  1111. endDate: input?.endDate ? new Date(input.endDate) : undefined,
  1112. });
  1113. }),
  1114. intentStats: agentProcedure
  1115. .input(z.object({ startDate: z.string().optional(), endDate: z.string().optional() }).optional())
  1116. .query(async ({ input }) => {
  1117. return getIntentStats(
  1118. input?.startDate ? new Date(input.startDate) : undefined,
  1119. input?.endDate ? new Date(input.endDate) : undefined,
  1120. );
  1121. }),
  1122. responseTime: agentProcedure
  1123. .input(z.object({ startDate: z.string().optional(), endDate: z.string().optional() }).optional())
  1124. .query(async ({ input }) => {
  1125. return getResponseTimeStats(
  1126. input?.startDate ? new Date(input.startDate) : undefined,
  1127. input?.endDate ? new Date(input.endDate) : undefined,
  1128. );
  1129. }),
  1130. }),
  1131. /* ─── Data Sources Router (Lyro-inspired) ─── */
  1132. dataSources: router({
  1133. list: adminProcedure.query(async () => {
  1134. return getDataSources();
  1135. }),
  1136. get: adminProcedure
  1137. .input(z.object({ id: z.number() }))
  1138. .query(async ({ input }) => {
  1139. return getDataSourceById(input.id);
  1140. }),
  1141. create: adminProcedure
  1142. .input(z.object({
  1143. name: z.string().min(1),
  1144. type: z.enum(["url", "file", "qa_pair", "api"]),
  1145. config: z.any().optional(),
  1146. }))
  1147. .mutation(async ({ input, ctx }) => {
  1148. const id = await createDataSource({
  1149. name: input.name,
  1150. type: input.type,
  1151. config: input.config || {},
  1152. createdById: ctx.user.id,
  1153. });
  1154. return { id };
  1155. }),
  1156. update: adminProcedure
  1157. .input(z.object({
  1158. id: z.number(),
  1159. name: z.string().optional(),
  1160. status: z.enum(["active", "inactive", "syncing", "error"]).optional(),
  1161. config: z.any().optional(),
  1162. itemCount: z.number().optional(),
  1163. }))
  1164. .mutation(async ({ input }) => {
  1165. const { id, ...updates } = input;
  1166. return updateDataSource(id, updates);
  1167. }),
  1168. delete: adminProcedure
  1169. .input(z.object({ id: z.number() }))
  1170. .mutation(async ({ input }) => {
  1171. await deleteDataSource(input.id);
  1172. return { success: true };
  1173. }),
  1174. }),
  1175. /* ─── API Connections Router (Lyro Actions) ─── */
  1176. apiConnections: router({
  1177. list: adminProcedure.query(async () => {
  1178. return getApiConnections();
  1179. }),
  1180. get: adminProcedure
  1181. .input(z.object({ id: z.number() }))
  1182. .query(async ({ input }) => {
  1183. return getApiConnectionById(input.id);
  1184. }),
  1185. create: adminProcedure
  1186. .input(z.object({
  1187. name: z.string().min(1),
  1188. description: z.string().optional(),
  1189. category: z.string().optional(),
  1190. method: z.enum(["GET", "POST", "PUT", "DELETE"]),
  1191. endpoint: z.string().min(1),
  1192. headers: z.any().optional(),
  1193. inputVariables: z.any().optional(),
  1194. outputVariables: z.any().optional(),
  1195. testPayload: z.any().optional(),
  1196. }))
  1197. .mutation(async ({ input, ctx }) => {
  1198. const id = await createApiConnection({
  1199. ...input,
  1200. createdById: ctx.user.id,
  1201. });
  1202. return { id };
  1203. }),
  1204. update: adminProcedure
  1205. .input(z.object({
  1206. id: z.number(),
  1207. name: z.string().optional(),
  1208. description: z.string().optional(),
  1209. category: z.string().optional(),
  1210. method: z.enum(["GET", "POST", "PUT", "DELETE"]).optional(),
  1211. endpoint: z.string().optional(),
  1212. headers: z.any().optional(),
  1213. inputVariables: z.any().optional(),
  1214. outputVariables: z.any().optional(),
  1215. testPayload: z.any().optional(),
  1216. isActive: z.boolean().optional(),
  1217. }))
  1218. .mutation(async ({ input }) => {
  1219. const { id, ...updates } = input;
  1220. return updateApiConnection(id, updates);
  1221. }),
  1222. delete: adminProcedure
  1223. .input(z.object({ id: z.number() }))
  1224. .mutation(async ({ input }) => {
  1225. await deleteApiConnection(input.id);
  1226. return { success: true };
  1227. }),
  1228. test: adminProcedure
  1229. .input(z.object({ id: z.number() }))
  1230. .mutation(async ({ input }) => {
  1231. const conn = await getApiConnectionById(input.id);
  1232. if (!conn) throw new TRPCError({ code: "NOT_FOUND", message: "API connection not found" });
  1233. const start = Date.now();
  1234. const result = await runApiConnection(input.id);
  1235. return {
  1236. success: result.success,
  1237. message: result.success ? `Test successful for ${conn.name}` : (result.error ?? "Unknown error"),
  1238. responseTime: Date.now() - start,
  1239. };
  1240. }),
  1241. run: adminProcedure
  1242. .input(z.object({ id: z.number() }))
  1243. .mutation(async ({ input }) => {
  1244. const result = await runApiConnection(input.id);
  1245. if (!result.success) throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: result.error });
  1246. return result;
  1247. }),
  1248. }),
  1249. /* ─── Knowledge Management Router ─── */
  1250. knowledge: router({
  1251. // Q&A Entries
  1252. listEntries: adminProcedure
  1253. .input(z.object({ status: z.string().optional() }).optional())
  1254. .query(async ({ input }) => getKnowledgeEntries(input?.status)),
  1255. getEntry: adminProcedure
  1256. .input(z.object({ id: z.number() }))
  1257. .query(async ({ input }) => getKnowledgeEntryById(input.id)),
  1258. createEntry: adminProcedure
  1259. .input(z.object({
  1260. question: z.string().min(1),
  1261. answer: z.string().min(1),
  1262. category: z.string().optional(),
  1263. }))
  1264. .mutation(async ({ input }) => {
  1265. const id = await createKnowledgeEntry({ ...input, source: "manual" });
  1266. return { id };
  1267. }),
  1268. updateEntry: adminProcedure
  1269. .input(z.object({
  1270. id: z.number(),
  1271. question: z.string().optional(),
  1272. answer: z.string().optional(),
  1273. category: z.string().optional(),
  1274. status: z.enum(["active", "inactive"]).optional(),
  1275. }))
  1276. .mutation(async ({ input }) => {
  1277. const { id, ...data } = input;
  1278. await updateKnowledgeEntry(id, data);
  1279. return { success: true };
  1280. }),
  1281. deleteEntry: adminProcedure
  1282. .input(z.object({ id: z.number() }))
  1283. .mutation(async ({ input }) => {
  1284. await deleteKnowledgeEntry(input.id);
  1285. return { success: true };
  1286. }),
  1287. importEntries: adminProcedure
  1288. .input(z.object({
  1289. entries: z.array(z.object({
  1290. question: z.string().min(1),
  1291. answer: z.string().min(1),
  1292. category: z.string().optional(),
  1293. })),
  1294. source: z.string().default("csv"),
  1295. }))
  1296. .mutation(async ({ input }) => {
  1297. return bulkCreateKnowledgeEntries(input.entries.map(e => ({ ...e, source: input.source })));
  1298. }),
  1299. // Suggestions
  1300. listSuggestions: adminProcedure
  1301. .input(z.object({ status: z.string().optional() }).optional())
  1302. .query(async ({ input }) => getKnowledgeSuggestions(input?.status)),
  1303. promoteSuggestion: adminProcedure
  1304. .input(z.object({
  1305. id: z.number(),
  1306. answer: z.string().min(1),
  1307. category: z.string().optional(),
  1308. }))
  1309. .mutation(async ({ input }) => {
  1310. const entryId = await promoteKnowledgeSuggestion(input.id, input.answer, input.category);
  1311. return { entryId };
  1312. }),
  1313. dismissSuggestion: adminProcedure
  1314. .input(z.object({ id: z.number() }))
  1315. .mutation(async ({ input }) => {
  1316. await dismissKnowledgeSuggestion(input.id);
  1317. return { success: true };
  1318. }),
  1319. // Products
  1320. listProducts: adminProcedure.query(getKnowledgeProducts),
  1321. importProducts: adminProcedure
  1322. .input(z.object({
  1323. products: z.array(z.object({
  1324. model: z.string(),
  1325. description: z.string().optional(),
  1326. categories: z.string().optional(),
  1327. collection: z.string().optional(),
  1328. price: z.string().optional(),
  1329. availability: z.string().optional(),
  1330. features: z.string().optional(),
  1331. dimensions: z.string().optional(),
  1332. imageUrl: z.string().optional(),
  1333. })),
  1334. replaceAll: z.boolean().default(false),
  1335. }))
  1336. .mutation(async ({ input }) => {
  1337. if (input.replaceAll) await deleteAllKnowledgeProducts();
  1338. return bulkCreateKnowledgeProducts(input.products);
  1339. }),
  1340. }),
  1341. /* ─── Playground Router ─── */
  1342. playground: router({
  1343. chat: agentProcedure
  1344. .input(z.object({
  1345. sessionId: z.string().optional(),
  1346. content: z.string().min(1).max(4000),
  1347. systemPrompt: z.string().max(8000).optional(),
  1348. model: z.enum([
  1349. "claude-haiku-4-5-20251001",
  1350. "claude-sonnet-4-6",
  1351. "claude-opus-4-7",
  1352. ]).default("claude-sonnet-4-6"),
  1353. temperature: z.number().min(0).max(1).optional(),
  1354. history: z.array(z.object({
  1355. role: z.enum(["user", "assistant"]),
  1356. content: z.string(),
  1357. })).default([]),
  1358. }))
  1359. .mutation(async ({ input }) => {
  1360. const systemContent = input.systemPrompt ?? SYSTEM_PROMPT;
  1361. const llmMessages = [
  1362. { role: "system" as const, content: systemContent },
  1363. ...input.history,
  1364. { role: "user" as const, content: input.content },
  1365. ];
  1366. const result = await invokeLLM({
  1367. messages: llmMessages,
  1368. model: input.model,
  1369. ...(input.temperature != null ? { temperature: input.temperature } : {}),
  1370. });
  1371. const reply = result.choices[0]?.message?.content as string
  1372. ?? "Sorry, I could not generate a response.";
  1373. return { reply, model: input.model };
  1374. }),
  1375. }),
  1376. });
  1377. export type AppRouter = typeof appRouter;