routers.ts 59 KB

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