routers.ts 55 KB

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