mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-29 07:10:57 +00:00
feat: setup the attachment to the passenger clients
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
'use client';
|
||||
|
||||
import { FileText, X } from 'lucide-react';
|
||||
|
||||
import { formatBytes } from './MessageAttachments';
|
||||
import type { PendingAttachment } from './useAttachmentDraft';
|
||||
|
||||
/**
|
||||
* The staged-files strip above the composer. Shows what will be sent and lets
|
||||
* the agent drop any of it before hitting send.
|
||||
*/
|
||||
export function AttachmentDraftBar({
|
||||
attachments,
|
||||
onRemove,
|
||||
}: {
|
||||
attachments: PendingAttachment[];
|
||||
onRemove: (id: string) => void;
|
||||
}) {
|
||||
if (attachments.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="mb-2 flex flex-wrap gap-2">
|
||||
{attachments.map((a) => (
|
||||
<div
|
||||
key={a.id}
|
||||
className="relative flex items-center gap-1.5 rounded-lg border border-border bg-background p-1 pr-4"
|
||||
>
|
||||
{a.previewUrl ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={a.previewUrl}
|
||||
alt={a.file.name}
|
||||
className="h-9 w-9 shrink-0 rounded object-cover"
|
||||
/>
|
||||
) : (
|
||||
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded bg-muted text-muted-foreground">
|
||||
<FileText size={16} />
|
||||
</span>
|
||||
)}
|
||||
<span className="min-w-0 max-w-[120px]">
|
||||
<span className="block truncate text-xs font-semibold text-foreground">
|
||||
{a.file.name}
|
||||
</span>
|
||||
<span className="block text-[10px] text-muted-foreground">
|
||||
{formatBytes(a.file.size)}
|
||||
</span>
|
||||
</span>
|
||||
<button
|
||||
onClick={() => onRemove(a.id)}
|
||||
aria-label={`Remove ${a.file.name}`}
|
||||
className="absolute -right-1.5 -top-1.5 flex h-4 w-4 items-center justify-center rounded-full bg-gray-600 text-white transition hover:bg-gray-700"
|
||||
>
|
||||
<X size={10} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
'use client';
|
||||
|
||||
import { isSupportAttachmentImage, type Passenger } from '@edr/types';
|
||||
import { FileText, ImageOff } from 'lucide-react';
|
||||
|
||||
import { useAttachmentObjectUrl } from './useAttachmentObjectUrl';
|
||||
|
||||
type AttachmentDto = Passenger.PassengerSupportAttachmentDto;
|
||||
|
||||
/** Human-readable size — kept coarse; nobody needs bytes in a chat bubble. */
|
||||
export function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
/**
|
||||
* One image attachment. Its own component because the bytes are fetched through
|
||||
* the authenticated client (see {@link useAttachmentObjectUrl}) and a hook can't
|
||||
* be called from inside a `.map()`.
|
||||
*/
|
||||
function ImageAttachment({
|
||||
a,
|
||||
onView,
|
||||
}: {
|
||||
a: AttachmentDto;
|
||||
onView: (a: AttachmentDto, src: string) => void;
|
||||
}) {
|
||||
const { src, failed } = useAttachmentObjectUrl(a.url);
|
||||
|
||||
if (failed) {
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 text-xs opacity-75">
|
||||
<ImageOff size={14} className="shrink-0" />
|
||||
Couldn't load {a.name}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (!src) {
|
||||
return (
|
||||
<div className="h-[120px] w-[200px] animate-pulse rounded-lg bg-black/10 dark:bg-white/10" />
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={() => onView(a, src)}
|
||||
className="cursor-zoom-in overflow-hidden rounded-lg"
|
||||
aria-label={`View ${a.name}`}
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={src}
|
||||
alt={a.name}
|
||||
// Cap the bubble: a tall screenshot would otherwise push the
|
||||
// whole conversation off-screen.
|
||||
className="max-h-[220px] max-w-[260px] rounded-lg object-cover"
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Attachments inside a message bubble: images as thumbnails, everything else as
|
||||
* a labelled file row. Non-images are not fetched until opened — pulling every
|
||||
* document in a thread just to draw a filename would be wasteful.
|
||||
*/
|
||||
export function MessageAttachments({
|
||||
attachments,
|
||||
mine,
|
||||
onView,
|
||||
onOpenFile,
|
||||
}: {
|
||||
attachments: AttachmentDto[];
|
||||
mine: boolean;
|
||||
onView: (a: AttachmentDto, src: string) => void;
|
||||
onOpenFile: (a: AttachmentDto) => void;
|
||||
}) {
|
||||
if (attachments.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="mt-1.5 flex flex-col gap-1.5">
|
||||
{attachments.map((a) =>
|
||||
isSupportAttachmentImage(a.mimeType) ? (
|
||||
<ImageAttachment key={a.id} a={a} onView={onView} />
|
||||
) : (
|
||||
<button
|
||||
key={a.id}
|
||||
onClick={() => onOpenFile(a)}
|
||||
className={`flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left transition hover:opacity-90 ${
|
||||
mine ? 'bg-white/20' : 'border border-border bg-background'
|
||||
}`}
|
||||
>
|
||||
<FileText size={16} className="shrink-0" />
|
||||
<span className="min-w-0">
|
||||
<span className="block truncate text-xs font-semibold">{a.name}</span>
|
||||
<span className="block text-[10px] opacity-75">{formatBytes(a.size)}</span>
|
||||
</span>
|
||||
</button>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -5,32 +5,78 @@ import { apiClient } from '@/lib/api-client';
|
||||
type ConversationDto = Passenger.PassengerSupportConversationDto;
|
||||
type MessageDto = Passenger.PassengerSupportMessageDto;
|
||||
type ListResult = Passenger.PassengerSupportConversationListResult;
|
||||
type MessageListResult = Passenger.PassengerSupportMessageListResult;
|
||||
|
||||
export interface ListParams {
|
||||
status?: string;
|
||||
search?: string;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface ListMessagesParams {
|
||||
/** Opaque cursor from the previous page's `nextCursor`. */
|
||||
before?: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
/** What the composer hands over: text, files, or both (never neither). */
|
||||
export interface SendMessageInput {
|
||||
text?: string;
|
||||
attachments?: File[];
|
||||
}
|
||||
|
||||
/**
|
||||
* A message with files goes as multipart so the server can persist them against
|
||||
* the message it creates in the same request; text-only stays JSON.
|
||||
*/
|
||||
function toRequestBody(input: SendMessageInput): FormData | { text?: string } {
|
||||
if (!input.attachments?.length) return { text: input.text };
|
||||
|
||||
const form = new FormData();
|
||||
if (input.text) form.append('text', input.text);
|
||||
for (const file of input.attachments) form.append('attachments', file);
|
||||
return form;
|
||||
}
|
||||
|
||||
/**
|
||||
* `apiClient` pins `Content-Type: application/json` on every request. Axios
|
||||
* reads that header in `transformRequest` and, seeing JSON, runs FormData
|
||||
* through `formDataToJSON` — the files would be silently dropped and the server
|
||||
* would store an empty message. Clearing the header (rather than setting
|
||||
* `multipart/form-data` by hand, which omits the boundary) is what lets the
|
||||
* browser generate a proper boundary of its own.
|
||||
*/
|
||||
const multipartConfig = { headers: { 'Content-Type': undefined } };
|
||||
|
||||
/** Passenger backoffice (agent) support-chat REST calls (client unwraps envelope). */
|
||||
export const supportApi = {
|
||||
listConversations: (params: ListParams = {}) =>
|
||||
apiClient.get<ListResult>('/support/agent/conversations', { params }),
|
||||
listMessages: (id: string) =>
|
||||
apiClient.get<MessageDto[]>(`/support/agent/conversations/${id}/messages`),
|
||||
sendMessage: (id: string, text: string) =>
|
||||
apiClient.post<MessageDto>(
|
||||
listMessages: (id: string, params: ListMessagesParams = {}) =>
|
||||
apiClient.get<MessageListResult>(`/support/agent/conversations/${id}/messages`, { params }),
|
||||
sendMessage: (id: string, input: SendMessageInput) => {
|
||||
const body = toRequestBody(input);
|
||||
return apiClient.post<MessageDto>(
|
||||
`/support/agent/conversations/${id}/messages`,
|
||||
{ text },
|
||||
),
|
||||
body,
|
||||
body instanceof FormData ? multipartConfig : undefined,
|
||||
);
|
||||
},
|
||||
/**
|
||||
* Attachment bytes, fetched through this client so the bearer token rides along
|
||||
* — the guard reads `Authorization` only, so a direct `<img src>` would 401.
|
||||
*
|
||||
* `relativeUrl` is the DTO's `url` (`/support/attachments/:id`); the passenger
|
||||
* API has no global prefix, so it appends to the client's baseURL as-is.
|
||||
*/
|
||||
fetchAttachment: async (relativeUrl: string): Promise<Blob> => {
|
||||
const data = await apiClient.getRaw<Blob>(relativeUrl, { responseType: 'blob' });
|
||||
return data;
|
||||
},
|
||||
setStatus: (id: string, status: string) =>
|
||||
apiClient.patch<ConversationDto>(
|
||||
`/support/agent/conversations/${id}/status`,
|
||||
{ status },
|
||||
),
|
||||
apiClient.patch<ConversationDto>(`/support/agent/conversations/${id}/status`, { status }),
|
||||
markRead: (id: string) =>
|
||||
apiClient.post<{ unreadCount: number }>(
|
||||
`/support/agent/conversations/${id}/read`,
|
||||
),
|
||||
unreadCount: () =>
|
||||
apiClient.get<{ unreadCount: number }>('/support/agent/unread-count'),
|
||||
apiClient.post<{ unreadCount: number }>(`/support/agent/conversations/${id}/read`),
|
||||
unreadCount: () => apiClient.get<{ unreadCount: number }>('/support/agent/unread-count'),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
isSupportAttachmentAllowed,
|
||||
isSupportAttachmentImage,
|
||||
SUPPORT_ATTACHMENT_MAX_BYTES,
|
||||
SUPPORT_ATTACHMENT_MAX_PER_MESSAGE,
|
||||
} from '@edr/types';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
/** A file staged in the composer, not yet sent. */
|
||||
export interface PendingAttachment {
|
||||
/** Local-only id; the server id doesn't exist until the message is sent. */
|
||||
id: string;
|
||||
file: File;
|
||||
/** Object URL, images only. Revoked when the entry goes away. */
|
||||
previewUrl?: string;
|
||||
}
|
||||
|
||||
let nextId = 0;
|
||||
|
||||
/**
|
||||
* Staging area for files being attached to a message.
|
||||
*
|
||||
* Files are held client-side until send, then posted alongside the text in one
|
||||
* multipart request — there's no upload-then-reference step, so nothing to
|
||||
* garbage-collect if the agent changes their mind.
|
||||
*
|
||||
* Object URLs for image previews are revoked on removal and unmount; without
|
||||
* that, pasting screenshots into a long-lived chat page leaks the full bytes of
|
||||
* every image for the life of the tab.
|
||||
*/
|
||||
export function useAttachmentDraft(onReject?: (reason: string) => void) {
|
||||
const [attachments, setAttachments] = useState<PendingAttachment[]>([]);
|
||||
const rejectRef = useRef(onReject);
|
||||
rejectRef.current = onReject;
|
||||
|
||||
// Read from a ref in the unmount cleanup so it doesn't re-run (and revoke
|
||||
// still-live URLs) on every change to the list.
|
||||
const attachmentsRef = useRef(attachments);
|
||||
attachmentsRef.current = attachments;
|
||||
useEffect(
|
||||
() => () => {
|
||||
for (const a of attachmentsRef.current) {
|
||||
if (a.previewUrl) URL.revokeObjectURL(a.previewUrl);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const add = useCallback((files: File[]) => {
|
||||
if (files.length === 0) return;
|
||||
setAttachments((current) => {
|
||||
const accepted: PendingAttachment[] = [];
|
||||
for (const file of files) {
|
||||
if (current.length + accepted.length >= SUPPORT_ATTACHMENT_MAX_PER_MESSAGE) {
|
||||
rejectRef.current?.(`Up to ${SUPPORT_ATTACHMENT_MAX_PER_MESSAGE} files per message.`);
|
||||
break;
|
||||
}
|
||||
if (!isSupportAttachmentAllowed(file.type)) {
|
||||
rejectRef.current?.(`${file.name}: that file type isn't supported.`);
|
||||
continue;
|
||||
}
|
||||
if (file.size > SUPPORT_ATTACHMENT_MAX_BYTES) {
|
||||
rejectRef.current?.(
|
||||
`${file.name} is over the ${SUPPORT_ATTACHMENT_MAX_BYTES / (1024 * 1024)}MB limit.`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
accepted.push({
|
||||
id: `pending-${nextId++}`,
|
||||
file,
|
||||
previewUrl: isSupportAttachmentImage(file.type) ? URL.createObjectURL(file) : undefined,
|
||||
});
|
||||
}
|
||||
return accepted.length ? [...current, ...accepted] : current;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const remove = useCallback((id: string) => {
|
||||
setAttachments((current) => {
|
||||
const target = current.find((a) => a.id === id);
|
||||
if (target?.previewUrl) URL.revokeObjectURL(target.previewUrl);
|
||||
return current.filter((a) => a.id !== id);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const clear = useCallback(() => {
|
||||
setAttachments((current) => {
|
||||
for (const a of current) {
|
||||
if (a.previewUrl) URL.revokeObjectURL(a.previewUrl);
|
||||
}
|
||||
return [];
|
||||
});
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Pull files off a paste. Returns true if anything was taken, so the caller
|
||||
* can suppress the default paste — otherwise pasting a screenshot also drops
|
||||
* its filename (or nothing) into the textarea.
|
||||
*
|
||||
* Copying an image in most apps puts BOTH the bitmap and some text/html on
|
||||
* the clipboard, so check for files first and only then let the text through.
|
||||
*/
|
||||
const addFromPaste = useCallback(
|
||||
(clipboard: DataTransfer | null): boolean => {
|
||||
const files = Array.from(clipboard?.files ?? []);
|
||||
if (files.length === 0) return false;
|
||||
add(files);
|
||||
return true;
|
||||
},
|
||||
[add],
|
||||
);
|
||||
|
||||
return {
|
||||
attachments,
|
||||
files: attachments.map((a) => a.file),
|
||||
add,
|
||||
addFromPaste,
|
||||
remove,
|
||||
clear,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
import { supportApi } from './supportApi';
|
||||
|
||||
/**
|
||||
* Blob object URL for an attachment, or `undefined` while it loads / on failure.
|
||||
*
|
||||
* Chat attachments cannot be rendered with a direct `<img src={a.url}>`. The API
|
||||
* guard takes the bearer token from the `Authorization` header and has no cookie
|
||||
* fallback, and an `<img>` request cannot carry that header — a direct src is an
|
||||
* unavoidable 401. So the bytes are fetched through the authenticated client and
|
||||
* handed to the browser as an object URL.
|
||||
*
|
||||
* The URL is revoked on unmount and whenever the attachment changes, so a thread
|
||||
* scrolled through hundreds of images doesn't pin all of them in memory.
|
||||
*/
|
||||
export function useAttachmentObjectUrl(relativeUrl: string): {
|
||||
src?: string;
|
||||
failed: boolean;
|
||||
} {
|
||||
const [src, setSrc] = useState<string>();
|
||||
const [failed, setFailed] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let created: string | undefined;
|
||||
|
||||
setSrc(undefined);
|
||||
setFailed(false);
|
||||
|
||||
supportApi
|
||||
.fetchAttachment(relativeUrl)
|
||||
.then((blob) => {
|
||||
// The component may have unmounted mid-flight; creating a URL then would
|
||||
// leak it, since the cleanup below has already run.
|
||||
if (cancelled) return;
|
||||
created = URL.createObjectURL(blob);
|
||||
setSrc(created);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setFailed(true);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (created) URL.revokeObjectURL(created);
|
||||
};
|
||||
}, [relativeUrl]);
|
||||
|
||||
return { src, failed };
|
||||
}
|
||||
|
||||
/**
|
||||
* On-demand variant for files that aren't previewed inline (documents): fetch
|
||||
* only when the user actually opens one, rather than pulling every attachment in
|
||||
* the thread down just to render a filename row.
|
||||
*
|
||||
* Holds a single slot — opening another file revokes the previous URL, as does
|
||||
* unmounting.
|
||||
*/
|
||||
export function useLazyAttachmentObjectUrl(): (relativeUrl: string) => Promise<string> {
|
||||
const current = useRef<string>();
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (current.current) URL.revokeObjectURL(current.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return useCallback(async (relativeUrl: string) => {
|
||||
const blob = await supportApi.fetchAttachment(relativeUrl);
|
||||
if (current.current) URL.revokeObjectURL(current.current);
|
||||
current.current = URL.createObjectURL(blob);
|
||||
return current.current;
|
||||
}, []);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
'use client';
|
||||
|
||||
import { isSupportAttachmentImage } from '@edr/types';
|
||||
import { Download, ExternalLink, FileText } from 'lucide-react';
|
||||
import { useCallback, useState } from 'react';
|
||||
|
||||
import Modal from '@/components/ui/Modal';
|
||||
|
||||
/** The minimal file shape the preview needs. */
|
||||
export interface PreviewableFile {
|
||||
name: string;
|
||||
/**
|
||||
* A blob object URL, not the attachment's API path — the API guard reads the
|
||||
* bearer token from the `Authorization` header, which `<img>` and `<a>` can't
|
||||
* send. Callers fetch the bytes first (see `useAttachmentObjectUrl`).
|
||||
*/
|
||||
url: string;
|
||||
mimeType: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drives a single shared preview modal for the page: call `view(file)` from any
|
||||
* attachment, render `viewer` once near the page root.
|
||||
*
|
||||
* Mirrors the shape of `useFileViewer` from `@edr/ui-common`, which the freight
|
||||
* backoffice uses. That hook can't be used here: it renders `@mantine/core`
|
||||
* components, and this app is Tailwind-only with no `MantineProvider` mounted —
|
||||
* its Modal would throw at runtime. Kept deliberately narrow (images inline,
|
||||
* everything else handed to the browser) rather than reimplementing the shared
|
||||
* viewer's pdf/office/video handling; swap this for the shared hook if this app
|
||||
* ever adopts Mantine.
|
||||
*/
|
||||
export function useFilePreview() {
|
||||
const [file, setFile] = useState<PreviewableFile | null>(null);
|
||||
|
||||
const view = useCallback((f: PreviewableFile) => setFile(f), []);
|
||||
const close = useCallback(() => setFile(null), []);
|
||||
|
||||
const viewer = (
|
||||
<Modal isOpen={file !== null} onClose={close} title={file?.name ?? ''} size="xl">
|
||||
{file && (
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
{isSupportAttachmentImage(file.mimeType) ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={file.url}
|
||||
alt={file.name}
|
||||
className="max-h-[70vh] w-auto max-w-full rounded-lg object-contain"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex flex-col items-center gap-3 py-10 text-muted-foreground">
|
||||
<FileText size={48} />
|
||||
<p className="text-sm">No inline preview for this file type.</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<a
|
||||
href={file.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2 rounded-lg border border-border px-3 py-1.5 text-xs font-medium text-foreground transition hover:bg-muted"
|
||||
>
|
||||
<ExternalLink size={14} />
|
||||
Open in new tab
|
||||
</a>
|
||||
<a
|
||||
href={file.url}
|
||||
download={file.name}
|
||||
className="flex items-center gap-2 rounded-lg px-3 py-1.5 text-xs font-medium text-white transition hover:opacity-90"
|
||||
style={{ background: 'rgb(20 113 76)' }}
|
||||
>
|
||||
<Download size={14} />
|
||||
Download
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
|
||||
return { view, close, viewer };
|
||||
}
|
||||
@@ -1,26 +1,161 @@
|
||||
'use client';
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import type { Passenger } from '@edr/types';
|
||||
import {
|
||||
useInfiniteQuery,
|
||||
useMutation,
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
type InfiniteData,
|
||||
type QueryClient,
|
||||
} from '@tanstack/react-query';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { supportApi, type ListParams } from './supportApi';
|
||||
import { supportApi, type ListParams, type SendMessageInput } from './supportApi';
|
||||
|
||||
type MessageDto = Passenger.PassengerSupportMessageDto;
|
||||
type MessageListResult = Passenger.PassengerSupportMessageListResult;
|
||||
|
||||
export const SUPPORT_CONVERSATIONS_KEY = ['support', 'conversations'];
|
||||
export const SUPPORT_UNREAD_KEY = ['support', 'unread'];
|
||||
export const supportMessagesKey = (id: string) => ['support', 'messages', id];
|
||||
|
||||
/** Threads per page in the inbox. */
|
||||
const CONVERSATIONS_PAGE_SIZE = 20;
|
||||
/** Messages per page in a thread. */
|
||||
const MESSAGES_PAGE_SIZE = 30;
|
||||
|
||||
/**
|
||||
* Shared inbox: every thread, filterable by status + subject/passenger search.
|
||||
*
|
||||
* Pages on scroll. This previously fetched one unbounded page and rendered
|
||||
* whatever came back, which silently truncated the inbox at the server's own
|
||||
* default of 100 with no way to reach the rest.
|
||||
*/
|
||||
export function useConversations(params: ListParams = {}) {
|
||||
return useQuery({
|
||||
const query = useInfiniteQuery({
|
||||
queryKey: [...SUPPORT_CONVERSATIONS_KEY, params],
|
||||
queryFn: () => supportApi.listConversations(params),
|
||||
queryFn: ({ pageParam }) =>
|
||||
supportApi.listConversations({
|
||||
...params,
|
||||
page: pageParam,
|
||||
limit: CONVERSATIONS_PAGE_SIZE,
|
||||
}),
|
||||
initialPageParam: 1,
|
||||
getNextPageParam: (lastPage, allPages) => {
|
||||
const loaded = allPages.reduce((n, page) => n + page.items.length, 0);
|
||||
return loaded < lastPage.count ? allPages.length + 1 : undefined;
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Flatten for rendering, keeping the page-level fields (count/unreadCount)
|
||||
* from the first fetch so badges don't go stale as more pages load.
|
||||
*
|
||||
* De-duplicated by id because this list pages by OFFSET over a sort key that
|
||||
* moves: a thread jumps to rank 1 the moment it gets a message, shifting
|
||||
* everything down, so a row already shown on page 1 can be served again on
|
||||
* page 2 — and React would then see two children with the same key. The
|
||||
* conversations invalidate that rides along with every such event heals the
|
||||
* ordering a beat later; this just stops the intervening render from breaking.
|
||||
*
|
||||
* Keyset wouldn't help here, unlike the message list: the sort key itself
|
||||
* mutates, so no cursor over it is stable either.
|
||||
*/
|
||||
const items = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
const flat: Passenger.PassengerSupportConversationDto[] = [];
|
||||
for (const page of query.data?.pages ?? []) {
|
||||
for (const conversation of page.items) {
|
||||
if (seen.has(conversation.id)) continue;
|
||||
seen.add(conversation.id);
|
||||
flat.push(conversation);
|
||||
}
|
||||
}
|
||||
return flat;
|
||||
}, [query.data]);
|
||||
|
||||
return {
|
||||
...query,
|
||||
items,
|
||||
count: query.data?.pages[0]?.count ?? 0,
|
||||
unreadCount: query.data?.pages[0]?.unreadCount ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A thread's messages, paged backwards from newest.
|
||||
*
|
||||
* react-query's "next page" is *older* history here, so `pages` runs
|
||||
* newest-block-first and has to be reversed to render top-to-bottom in time
|
||||
* order. Cursor-based rather than offset so a message arriving mid-scroll
|
||||
* doesn't shift the pages already loaded.
|
||||
*/
|
||||
export function useMessages(conversationId: string | null) {
|
||||
return useQuery({
|
||||
const query = useInfiniteQuery({
|
||||
queryKey: supportMessagesKey(conversationId ?? ''),
|
||||
queryFn: () => supportApi.listMessages(conversationId as string),
|
||||
queryFn: ({ pageParam }) =>
|
||||
supportApi.listMessages(conversationId as string, {
|
||||
before: pageParam,
|
||||
limit: MESSAGES_PAGE_SIZE,
|
||||
}),
|
||||
initialPageParam: undefined as string | undefined,
|
||||
getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
|
||||
enabled: !!conversationId,
|
||||
});
|
||||
|
||||
const messages = useMemo(
|
||||
() => [...(query.data?.pages ?? [])].reverse().flatMap((p) => p.items),
|
||||
[query.data],
|
||||
);
|
||||
|
||||
// Exposed so the view can tell a prepended history page from a message
|
||||
// appended at the bottom — `messages` changing says nothing about which.
|
||||
return { ...query, messages, pageCount: query.data?.pages.length ?? 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Splice a newly-arrived message into a cached thread.
|
||||
*
|
||||
* Deliberately not `invalidateQueries`: that refetches *every* page the agent
|
||||
* has scrolled back through, so the cost of each inbound message would grow
|
||||
* with how far they've read. Page 0 is the newest block and its items are
|
||||
* oldest-first within the block, so the new message belongs on its end.
|
||||
*
|
||||
* No-ops when the thread isn't cached — nothing is rendering it, and seeding a
|
||||
* partial cache here would leave a thread whose "first page" is one message and
|
||||
* whose `nextCursor` is missing.
|
||||
*/
|
||||
/**
|
||||
* Why this reports an outcome rather than a boolean: the two ways it can decline
|
||||
* to append need opposite handling. A duplicate is the sender's own echo and must
|
||||
* be ignored — refetching there would undo the whole point. "Uncached" means the
|
||||
* thread's first page is still in flight and may have been read on the server
|
||||
* *before* this message existed, so dropping it silently would lose it until
|
||||
* something else happened to refetch; the caller refetches instead. That's cheap
|
||||
* precisely because nothing is loaded yet.
|
||||
*/
|
||||
export type AppendOutcome = 'appended' | 'duplicate' | 'uncached';
|
||||
|
||||
export function appendMessageToCache(qc: QueryClient, message: MessageDto): AppendOutcome {
|
||||
let outcome: AppendOutcome = 'uncached';
|
||||
qc.setQueryData<InfiniteData<MessageListResult>>(
|
||||
supportMessagesKey(message.conversationId),
|
||||
(current) => {
|
||||
if (!current?.pages.length) return current;
|
||||
const [newest, ...rest] = current.pages;
|
||||
if (newest.items.some((m) => m.id === message.id)) {
|
||||
outcome = 'duplicate';
|
||||
return current;
|
||||
}
|
||||
outcome = 'appended';
|
||||
return {
|
||||
...current,
|
||||
pages: [{ ...newest, items: [...newest.items, message] }, ...rest],
|
||||
};
|
||||
},
|
||||
);
|
||||
return outcome;
|
||||
}
|
||||
|
||||
export function useUnreadCount(enabled = true) {
|
||||
@@ -35,9 +170,12 @@ export function useUnreadCount(enabled = true) {
|
||||
export function useSendMessage(conversationId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (text: string) => supportApi.sendMessage(conversationId, text),
|
||||
mutationFn: (input: SendMessageInput) => supportApi.sendMessage(conversationId, input),
|
||||
// The gateway echoes our own message back over the socket, which appends it
|
||||
// to the cache — so don't invalidate the thread here or every send would
|
||||
// refetch every page the agent has scrolled through. The conversation list
|
||||
// still needs a refresh for its last-message preview and ordering.
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: supportMessagesKey(conversationId) });
|
||||
qc.invalidateQueries({ queryKey: SUPPORT_CONVERSATIONS_KEY });
|
||||
},
|
||||
});
|
||||
@@ -48,8 +186,7 @@ export function useSetStatus() {
|
||||
return useMutation({
|
||||
mutationFn: ({ id, status }: { id: string; status: string }) =>
|
||||
supportApi.setStatus(id, status),
|
||||
onSuccess: () =>
|
||||
qc.invalidateQueries({ queryKey: SUPPORT_CONVERSATIONS_KEY }),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: SUPPORT_CONVERSATIONS_KEY }),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -6,14 +6,16 @@ import { useEffect, useRef } from 'react';
|
||||
import { io } from 'socket.io-client';
|
||||
|
||||
import {
|
||||
appendMessageToCache,
|
||||
SUPPORT_CONVERSATIONS_KEY,
|
||||
SUPPORT_UNREAD_KEY,
|
||||
supportMessagesKey,
|
||||
} from './useSupport';
|
||||
|
||||
const SOCKET_ORIGIN = String(
|
||||
process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000',
|
||||
).replace(/\/api\/?$/, '');
|
||||
const SOCKET_ORIGIN = String(process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000').replace(
|
||||
/\/api\/?$/,
|
||||
'',
|
||||
);
|
||||
|
||||
/**
|
||||
* Subscribes the signed-in agent to live support pushes for the whole shared
|
||||
@@ -33,37 +35,39 @@ export function useSupportSocket(
|
||||
const token = localStorage.getItem('auth_token');
|
||||
if (!token) return;
|
||||
|
||||
const socket = io(
|
||||
`${SOCKET_ORIGIN}/${Passenger.PASSENGER_SUPPORT_WS_NAMESPACE}`,
|
||||
{
|
||||
auth: { token },
|
||||
// Prefer WebSocket, fall back to HTTP long-polling if the proxy blocks
|
||||
// the upgrade (polling rides normal HTTPS, already CSP-allowed).
|
||||
transports: ['websocket', 'polling'],
|
||||
withCredentials: true,
|
||||
},
|
||||
);
|
||||
const socket = io(`${SOCKET_ORIGIN}/${Passenger.PASSENGER_SUPPORT_WS_NAMESPACE}`, {
|
||||
auth: { token },
|
||||
// Prefer WebSocket, fall back to HTTP long-polling if the proxy blocks
|
||||
// the upgrade (polling rides normal HTTPS, already CSP-allowed).
|
||||
transports: ['websocket', 'polling'],
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
// Temporary diagnostics — remove once live delivery is confirmed.
|
||||
socket.on('connect', () =>
|
||||
console.warn('[support] agent socket connected', socket.id),
|
||||
);
|
||||
socket.on('connect', () => console.warn('[support] agent socket connected', socket.id));
|
||||
socket.on('connect_error', (err) =>
|
||||
console.warn('[support] agent socket connect_error:', err.message),
|
||||
);
|
||||
socket.on('disconnect', (reason) =>
|
||||
console.warn('[support] agent socket disconnected:', reason),
|
||||
);
|
||||
socket.on('support:hello', (info) =>
|
||||
console.warn('[support] server assigned:', info),
|
||||
);
|
||||
socket.on('support:hello', (info) => console.warn('[support] server assigned:', info));
|
||||
|
||||
socket.on(
|
||||
Passenger.PASSENGER_SUPPORT_WS_EVENTS.MESSAGE_NEW,
|
||||
(event: Passenger.PassengerSupportMessageEvent) => {
|
||||
qc.invalidateQueries({
|
||||
queryKey: supportMessagesKey(event.message.conversationId),
|
||||
});
|
||||
// Append rather than invalidate: the thread is paginated, and
|
||||
// invalidating it would refetch every page the agent has scrolled back
|
||||
// through on every single inbound message.
|
||||
if (appendMessageToCache(qc, event.message) === 'uncached') {
|
||||
// The thread's first page is still loading and may have been read
|
||||
// before this message existed — without this it would go missing
|
||||
// until some unrelated refetch. Cheap: there are no pages to
|
||||
// re-fetch yet.
|
||||
qc.invalidateQueries({
|
||||
queryKey: supportMessagesKey(event.message.conversationId),
|
||||
});
|
||||
}
|
||||
qc.invalidateQueries({ queryKey: SUPPORT_CONVERSATIONS_KEY });
|
||||
qc.invalidateQueries({ queryKey: SUPPORT_UNREAD_KEY });
|
||||
onMessageRef.current?.(event);
|
||||
|
||||
Reference in New Issue
Block a user