Files
co-lite/solvway-admin-portal/app/components/messages/MessageThreadDrawer.tsx
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session,
api-gateway, mobile-api, services-auth, services-system,
services-counter, services-member, services-log, services-email.
solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal
from tastefully 8bd93d15. Copied as tracked files only.

Literal secrets replaced with environment placeholders:
- services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY,
  MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default)
- services-system: JUMIO_TOKEN, JUMIO_SECRET (optional)
- services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed
- core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default
  removed, ipgeolocation key read from IPGEOLOCATION_API_KEY
- services-system EkycAppConfig: commented Jumio credentials removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 15:55:45 +08:00

216 lines
8.5 KiB
TypeScript

"use client";
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { KycDrawer } from "@/app/components/kyc/KycDrawer";
import { Button } from "@/app/components/ui/button";
import { ErrorState } from "@/app/components/ui/states";
import { Textarea } from "@/app/components/ui/textarea";
import { ImageAttachments, useAttachments } from "@/app/components/messages/ImageAttachments";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { formatDateTime } from "@/app/lib/format";
import {
MAX_BODY,
adminMessageImageUrl,
getAdminConversation,
listAdminMessages,
markAdminRead,
messageErrorText,
sendAdminMessage,
type ConversationView,
type MessageView,
} from "@/app/lib/services/adminMessages";
const POLL_MS = 15_000;
/** Merge by uuid (a poll and an in-flight send can both return the same message), oldest first. */
export function mergeMessages(cur: MessageView[], incoming: MessageView[]): MessageView[] {
const byId = new Map(cur.map((m) => [m.uuid, m]));
for (const m of incoming) byId.set(m.uuid, m);
return [...byId.values()].sort((a, b) => a.seq - b.seq); // seq, not createdAt: whole seconds, ties are common
}
const oldestFirst = (items: MessageView[]) => [...items].reverse(); // the API returns newest first
export function MessageThreadDrawer({ uuid, onClose, onChanged, initialDraft }: { uuid: string; onClose: () => void; onChanged: () => void; initialDraft?: string }) {
const t = useT();
const [head, setHead] = useState<ConversationView | null>(null);
const [messages, setMessages] = useState<MessageView[]>([]);
const [hasMore, setHasMore] = useState(false);
const [error, setError] = useState<string | null>(null);
const [body, setBody] = useState(initialDraft ?? "");
const [sending, setSending] = useState(false);
const [sendError, setSendError] = useState<string | null>(null);
const [loadingOlder, setLoadingOlder] = useState(false);
const [olderError, setOlderError] = useState<string | null>(null);
const attachments = useAttachments();
// `onChanged` is a fresh closure each parent render; a ref keeps the effects below from re-running.
const onChangedRef = useRef(onChanged);
useEffect(() => {
onChangedRef.current = onChanged;
}, [onChanged]);
const known = useRef(new Set<string>());
useEffect(() => {
known.current = new Set(messages.map((m) => m.uuid));
}, [messages]);
const markRead = useCallback(() => {
markAdminRead(uuid)
.then(() => onChangedRef.current())
.catch(() => {
/* the unread dot just stays until the next open */
});
}, [uuid]);
useEffect(() => {
let cancelled = false;
Promise.all([getAdminConversation(uuid), listAdminMessages(uuid)])
.then(([h, page]) => {
if (cancelled) return;
setHead(h);
setMessages((cur) => mergeMessages(cur, oldestFirst(page.items)));
setHasMore(page.hasMore);
markRead();
})
.catch(() => {
if (!cancelled) setError(t("MsgThreadFailed"));
});
return () => {
cancelled = true;
};
}, [uuid, markRead]);
// Poll only while the tab is visible; merge by uuid; clear unread when a member message arrives.
useEffect(() => {
const id = setInterval(() => {
if (document.visibilityState !== "visible") return;
listAdminMessages(uuid)
.then((page) => {
const fresh = page.items.filter((m) => !known.current.has(m.uuid));
if (fresh.length === 0) return;
setMessages((cur) => mergeMessages(cur, oldestFirst(page.items)));
if (fresh.some((m) => m.senderType === "M")) markRead();
})
.catch(() => {
/* transient: the next tick retries */
});
}, POLL_MS);
return () => clearInterval(id);
}, [uuid, markRead]);
const loadOlder = () => {
const oldest = messages[0];
if (!oldest || loadingOlder) return;
setLoadingOlder(true);
setOlderError(null);
listAdminMessages(uuid, oldest.uuid)
.then((page) => {
setMessages((cur) => mergeMessages(cur, oldestFirst(page.items)));
setHasMore(page.hasMore);
})
// Inline and retryable: a failed older page must not replace the thread or the reply box.
.catch(() => setOlderError(t("MsgThreadFailed")))
.finally(() => setLoadingOlder(false));
};
// Scroll only the message pane: keep the reader's place when older messages load above, and follow new
// messages only when they are mine (admin) or the reader is already near the bottom.
const pane = useRef<HTMLDivElement>(null);
const nearBottom = useRef(true);
const lastHeight = useRef(0);
const oldestUuid = messages[0]?.uuid;
const newest = messages[messages.length - 1];
useLayoutEffect(() => {
const el = pane.current;
if (el && lastHeight.current) el.scrollTop += el.scrollHeight - lastHeight.current;
}, [oldestUuid]);
useLayoutEffect(() => {
const el = pane.current;
if (el && (nearBottom.current || newest?.senderType === "A")) el.scrollTop = el.scrollHeight;
}, [newest?.uuid]); // eslint-disable-line react-hooks/exhaustive-deps -- only a new newest message scrolls
useLayoutEffect(() => {
if (pane.current) lastHeight.current = pane.current.scrollHeight;
});
const canSend = !sending && !attachments.busy && body.length <= MAX_BODY && (body.trim() !== "" || attachments.refs.length > 0);
const send = async () => {
setSending(true);
setSendError(null);
const refs = attachments.refs; // snapshot: only these went out
try {
const m = await sendAdminMessage(uuid, body.trim(), refs);
setMessages((cur) => mergeMessages(cur, [m]));
setBody("");
attachments.removeSent(refs);
onChangedRef.current();
} catch (e) {
setSendError(messageErrorText(e, t));
} finally {
setSending(false);
}
};
const composer = (
<div className="space-y-2">
<Textarea aria-label={t("MsgReplyLabel")} value={body} maxLength={MAX_BODY} readOnly={sending} onChange={(e) => setBody(e.target.value)} />
<div className="text-xs text-muted-foreground">
{body.length}/{MAX_BODY}
</div>
<ImageAttachments attachments={attachments} disabled={sending} />
{sendError && <p role="alert" className="text-sm text-destructive">{sendError}</p>}
<Button onClick={send} disabled={!canSend}>{t("MsgSend")}</Button>
</div>
);
return (
<KycDrawer
title={head ? (head.counterpartName ?? head.counterpartCode ?? t("MsgThread")) : t("MsgThread")}
description={head ? [head.counterpartCode, head.subject].filter(Boolean).join(" · ") : undefined}
onClose={onClose}
footer={error ? undefined : composer}
>
{error ? (
<ErrorState message={error} />
) : (
<div
ref={pane}
data-testid="message-pane"
/* bounded by the drawer body, not the viewport, so there is one scroll container */
className="h-full min-h-0 space-y-3 overflow-y-auto"
onScroll={(e) => {
const el = e.currentTarget;
nearBottom.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
}}
>
{hasMore && (
<Button variant="ghost" size="sm" disabled={loadingOlder} onClick={loadOlder}>{t("MsgLoadOlder")}</Button>
)}
{olderError && <p role="alert" className="text-sm text-destructive">{olderError}</p>}
{messages.map((m) => {
const admin = m.senderType === "A";
return (
<div key={m.uuid} className={"flex flex-col " + (admin ? "items-end" : "items-start")}>
<div className={"max-w-[85%] space-y-2 rounded-lg px-3 py-2 text-sm " + (admin ? "bg-primary text-primary-foreground" : "bg-muted")}>
{m.body && <p className="break-words whitespace-pre-wrap">{m.body}</p>}
{Array.from({ length: m.imageCount }, (_, i) => {
const src = adminMessageImageUrl(uuid, m.uuid, i);
return (
<a key={i} href={src} target="_blank" rel="noreferrer">
<img src={src} alt={t("MsgAttachmentAlt", { n: i + 1 })} className="max-h-48 rounded" />
</a>
);
})}
</div>
<span className="mt-1 text-xs text-muted-foreground">
{m.senderCode ? `${m.senderCode} · ` : ""}
{formatDateTime(m.createdAt)}
</span>
</div>
);
})}
</div>
)}
</KycDrawer>
);
}