Pārlūkot izejas kodu

improved links between notification and pages (#14)

Bernt Christian Egeland 8 mēneši atpakaļ
vecāks
revīzija
59c9391a8f

+ 1 - 1
src/app/(authenticated)/dashboard-client.tsx

@@ -480,7 +480,7 @@ export function DashboardClient({
                   <div
                     key={thread.customerId}
                     className="flex items-center justify-between px-5 py-3 cursor-pointer hover:bg-muted/50 transition-colors"
-                    onClick={() => router.push("/messages")}
+                    onClick={() => router.push(`/messages?customerId=${thread.customerId}`)}
                   >
                     <div className="flex items-center gap-3 min-w-0">
                       <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10">

+ 4 - 1
src/app/(authenticated)/messages/page.tsx

@@ -1,3 +1,4 @@
+import { Suspense } from "react";
 import { getAuthContext } from "@/lib/get-auth-context";
 import { getFeatures, isCloudMode } from "@/lib/features";
 import { redirect } from "next/navigation";
@@ -54,7 +55,9 @@ export default async function MessagesPage() {
     <>
       <PageHeader />
       <div className="flex flex-1 flex-col p-4 pt-0">
-        <MessagesPageClient initialThreads={threads} initialHasMore={hasMore} />
+        <Suspense>
+          <MessagesPageClient initialThreads={threads} initialHasMore={hasMore} />
+        </Suspense>
       </div>
     </>
   );

+ 1 - 1
src/app/api/webhooks/sms/telnyx/route.ts

@@ -89,7 +89,7 @@ export async function POST(request: Request) {
       entityType: "sms_message",
       entityId: message.id,
       entityUrl: customer
-        ? `/customers/${customer.id}?tab=messages`
+        ? `/messages?customerId=${customer.id}`
         : "/settings/sms",
     });
 

+ 1 - 1
src/app/api/webhooks/sms/twilio/route.ts

@@ -72,7 +72,7 @@ export async function POST(request: Request) {
       entityType: "sms_message",
       entityId: message.id,
       entityUrl: customer
-        ? `/customers/${customer.id}?tab=messages`
+        ? `/messages?customerId=${customer.id}`
         : "/settings/sms",
     });
 

+ 1 - 1
src/app/api/webhooks/sms/vonage/route.ts

@@ -71,7 +71,7 @@ export async function POST(request: Request) {
       entityType: "sms_message",
       entityId: message.id,
       entityUrl: customer
-        ? `/customers/${customer.id}?tab=messages`
+        ? `/messages?customerId=${customer.id}`
         : "/settings/sms",
     });
 

+ 3 - 1
src/features/notifications/hooks/useNotificationWebSocket.ts

@@ -48,7 +48,7 @@ export function useNotificationWebSocket() {
             if (
               activeSmsCid &&
               data.type === "sms_inbound" &&
-              data.entityUrl === `/customers/${activeSmsCid}?tab=messages`
+              data.entityUrl === `/messages?customerId=${activeSmsCid}`
             ) {
               // Still add it to the store but immediately mark as read
               const added = { ...data, read: true };
@@ -62,8 +62,10 @@ export function useNotificationWebSocket() {
             }
 
             useNotificationStore.getState().addNotification(data);
+            const isSms = data.type === "sms_inbound";
             toast(data.title, {
               description: data.message,
+              ...(isSms && { duration: 5 * 60 * 1000 }),
               action: {
                 label: "View",
                 onClick: () => {

+ 24 - 2
src/features/sms/Components/MessagesPageClient.tsx

@@ -1,6 +1,7 @@
 "use client";
 
-import { useState, useEffect, useCallback, useTransition } from "react";
+import { useState, useEffect, useCallback, useTransition, useRef } from "react";
+import { useSearchParams, useRouter } from "next/navigation";
 import { cn } from "@/lib/utils";
 import { Button } from "@/components/ui/button";
 import {
@@ -57,9 +58,13 @@ export function MessagesPageClient({
   initialThreads: SmsThread[];
   initialHasMore?: boolean;
 }) {
+  const searchParams = useSearchParams();
+  const router = useRouter();
   const [threads, setThreads] = useState<SmsThread[]>(initialThreads);
   const [hasMore, setHasMore] = useState(initialHasMore);
-  const [selectedCustomerId, setSelectedCustomerId] = useState<string | null>(null);
+  const [selectedCustomerId, setSelectedCustomerId] = useState<string | null>(
+    searchParams.get("customerId"),
+  );
   const [conversation, setConversation] = useState<{
     messages: Message[];
     nextCursor: string | null;
@@ -89,9 +94,23 @@ export function MessagesPageClient({
     setLoadingConversation(false);
   }, [threads]);
 
+  // Load conversation from URL param on mount
+  const initialLoadDone = useRef(false);
+  useEffect(() => {
+    if (initialLoadDone.current) return;
+    initialLoadDone.current = true;
+    const convId = searchParams.get("customerId");
+    if (convId) {
+      loadConversation(convId);
+    }
+  }, [searchParams, loadConversation]);
+
   const handleSelectThread = (customerId: string) => {
     setSelectedCustomerId(customerId);
     loadConversation(customerId);
+    const params = new URLSearchParams(searchParams.toString());
+    params.set("customerId", customerId);
+    router.replace(`?${params.toString()}`, { scroll: false });
   };
 
   const handleLoadMore = () => {
@@ -123,6 +142,9 @@ export function MessagesPageClient({
       if (selectedCustomerId === deleteThreadTarget.customerId) {
         setSelectedCustomerId(null);
         setConversation(null);
+        const params = new URLSearchParams(searchParams.toString());
+        params.delete("customerId");
+        router.replace(`?${params.toString()}`, { scroll: false });
       }
     } else {
       toast.error(result.error || "Failed to delete conversation");

+ 18 - 3
src/features/sms/Components/SmsConversation.tsx

@@ -59,6 +59,7 @@ export function SmsConversation({
   }, []);
   const [isSending, startSend] = useTransition();
   const [isLoadingMore, startLoadMore] = useTransition();
+  const scrollAreaRef = useRef<HTMLDivElement>(null);
   const bottomRef = useRef<HTMLDivElement>(null);
 
   useEffect(() => {
@@ -66,8 +67,22 @@ export function SmsConversation({
     return () => setActiveSmsCustomerId(null);
   }, [customerId]);
 
+  const initialScrollDone = useRef(false);
   useEffect(() => {
-    bottomRef.current?.scrollIntoView({ behavior: "smooth" });
+    const el = scrollAreaRef.current;
+    if (!el) return;
+
+    if (!initialScrollDone.current) {
+      initialScrollDone.current = true;
+      // Wait for layout to settle before scrolling to bottom
+      requestAnimationFrame(() => {
+        requestAnimationFrame(() => {
+          el.scrollTop = el.scrollHeight;
+        });
+      });
+    } else {
+      el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
+    }
   }, [messages.length]);
 
   // Refetch conversation when a matching inbound SMS notification arrives via WS
@@ -98,7 +113,7 @@ export function SmsConversation({
       const latest = notifications[0];
       if (
         latest?.type === "sms_inbound" &&
-        latest.entityUrl === `/customers/${customerId}?tab=messages`
+        latest.entityUrl === `/messages?customerId=${customerId}`
       ) {
         refreshConversation();
       }
@@ -181,7 +196,7 @@ export function SmsConversation({
   return (
     <div className={cn("flex flex-col h-[500px]", className)}>
       {/* Messages area — scrollable, fills available space */}
-      <div className="min-h-0 flex-1 overflow-y-auto p-4 space-y-3">
+      <div ref={scrollAreaRef} className="min-h-0 flex-1 overflow-y-auto p-4 space-y-3">
         {nextCursor && (
           <div className="flex justify-center">
             <Button