routers.ts 54 KB

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