Selaa lähdekoodia

fix: add ctx to sendMessage handler and use optional chaining for ctx.user

sendMessage is a publicProcedure — ctx.user is null for unauthenticated
visitors. Previously ctx was not destructured at all, causing ReferenceError.
Now uses ctx.user?.role and ctx.user?.erpContactCid with null fallbacks.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Tony T 6 päivää sitten
vanhempi
commit
237056dc57
1 muutettua tiedostoa jossa 5 lisäystä ja 5 poistoa
  1. 5 5
      server/routers.ts

+ 5 - 5
server/routers.ts

@@ -257,7 +257,7 @@ export const appRouter = router({
         sessionId: z.string(),
         content: z.string().min(1).max(2000),
       }))
-      .mutation(async ({ input }) => {
+      .mutation(async ({ input, ctx }) => {
         const conversation = await getConversationBySessionId(input.sessionId);
         if (!conversation) throw new Error("Conversation not found");
 
@@ -343,8 +343,8 @@ export const appRouter = router({
             // Build user context for permission-scoped ERP queries.
             // Dealers (role="user") are automatically scoped to their own CID by the bridge.
             const userCtx = {
-              role: ctx.user.role,
-              erpContactCid: ctx.user.erpContactCid,
+              role: ctx.user?.role ?? "user",
+              erpContactCid: ctx.user?.erpContactCid ?? null,
             };
 
             // 1. Single order lookup
@@ -362,7 +362,7 @@ export const appRouter = router({
 
             // 2. "my orders" / "recent orders" — needs customer CID on conversation
             } else if (/\b(my orders?|recent orders?|order history|order status)\b/.test(msgLower)) {
-              const cid = ctx.user.erpContactCid ?? (conversation as any).customerId as string | undefined;
+              const cid = ctx.user?.erpContactCid ?? (conversation as any).customerId as string | undefined;
               if (cid) {
                 erpContext = await lookupOrdersByCustomer(cid, 5, userCtx);
               }
@@ -400,7 +400,7 @@ export const appRouter = router({
             }
 
             // 6. Customer / dealer lookup (admin/agent only — dealers see their own record via CID)
-            if (!erpContext && ctx.user.role !== "user" && /\b(customer|dealer|account|contact|company)\b/.test(msgLower)) {
+            if (!erpContext && ctx.user?.role !== "user" && /\b(customer|dealer|account|contact|company)\b/.test(msgLower)) {
               const nameMatch = msg.match(/(?:customer|dealer|account|contact|company)[:\s]+([A-Za-z &'.-]{3,40})/i);
               if (nameMatch) {
                 erpContext = await lookupContact({ company: nameMatch[1].trim() }, userCtx);