Merge branch 'alpha' of github.com:Tria-plc/edr-platform into alpha

This commit is contained in:
Stephanos A
2026-07-07 22:58:11 +03:00
32 changed files with 2736 additions and 297 deletions

View File

@@ -1,66 +1,362 @@
'use client';
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Download } from 'lucide-react';
import DataTable from '@/components/ui/DataTable';
import Badge from '@/components/ui/Badge';
import ActionButton from '@/components/ui/ActionButton';
import { supportApi } from '@/lib/api';
import { formatDateTime, formatCurrency } from '@/lib/utils';
import { Passenger } from '@edr/types';
import { Headset, Search, Send, User } from 'lucide-react';
import { useEffect, useMemo, useRef, useState } from 'react';
import {
useConversations,
useMarkRead,
useMessages,
useSendMessage,
useSetStatus,
} from '@/features/support/useSupport';
import { useSupportSocket } from '@/features/support/useSupportSocket';
const GREEN = 'rgb(20 113 76)';
type ConversationDto = Passenger.PassengerSupportConversationDto;
type MessageDto = Passenger.PassengerSupportMessageDto;
const STATUS_CLASS: Record<string, string> = {
OPEN: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300',
RESOLVED: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300',
CLOSED: 'bg-gray-200 text-gray-600 dark:bg-slate-700 dark:text-slate-300',
};
const FILTERS = ['ALL', 'OPEN', 'RESOLVED', 'CLOSED'] as const;
function formatTime(iso?: string | null): string {
if (!iso) return '';
const d = new Date(iso);
const now = new Date();
return d.toDateString() === now.toDateString()
? d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
: d.toLocaleDateString([], { month: 'short', day: 'numeric' });
}
export default function SupportPage() {
const [filters, setFilters] = useState({ search: '', status: '' });
const [status, setStatus] = useState<(typeof FILTERS)[number]>('ALL');
const [search, setSearch] = useState('');
const [selectedId, setSelectedId] = useState<string | null>(null);
const { data, isLoading } = useQuery({
queryKey: ['support', filters],
queryFn: () => supportApi.getConversations(filters),
});
const { data, isLoading } = useConversations(
status === 'ALL' ? { search } : { status, search },
);
const items = data?.items ?? [];
const columns = [
{ key: 'subject', label: 'Subject', render: (conv: any) => conv.subject || 'No Subject' },
{ key: 'passenger', label: 'Passenger', render: (conv: any) => conv.passenger?.fullName || 'N/A' },
{ key: 'status', label: 'Status', render: (conv: any) => <Badge variant="status" status={conv.status}>{conv.status}</Badge> },
{ key: 'createdAt', label: 'Created', render: (conv: any) => formatDateTime(conv.createdAt) },
];
useSupportSocket(true);
const selected = useMemo(
() => items.find((c) => c.id === selectedId) ?? null,
[items, selectedId],
);
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div className="space-y-4">
<div className="flex items-center gap-3">
<span
className="flex h-10 w-10 items-center justify-center rounded-lg"
style={{ background: 'rgba(20,113,76,0.1)', color: GREEN }}
>
<Headset size={20} />
</span>
<div>
<h1 className="text-2xl font-bold text-foreground">Support Center</h1>
<p className="text-muted-foreground">Manage customer support conversations</p>
</div>
<ActionButton icon={Download} variant="secondary">Export</ActionButton>
</div>
<div className="card">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<label className="label">Search</label>
<input type="text" placeholder="Search..." className="input" value={filters.search} onChange={(e) => setFilters({ ...filters, search: e.target.value })} />
</div>
<div>
<label className="label">Status</label>
<select className="input" value={filters.status} onChange={(e) => setFilters({ ...filters, status: e.target.value })}>
<option value="">All Status</option>
<option value="OPEN">Open</option>
<option value="IN_PROGRESS">In Progress</option>
<option value="RESOLVED">Resolved</option>
<option value="CLOSED">Closed</option>
</select>
</div>
<p className="text-sm text-muted-foreground">
Shared inbox respond to passenger requests in real time
</p>
</div>
</div>
<DataTable
data={data?.items || data || []}
columns={columns}
loading={isLoading}
emptyMessage="No support center found"
/>
<div className="flex h-[calc(100vh-220px)] overflow-hidden rounded-xl border border-border bg-card">
{/* Conversation list */}
<div className="flex w-[340px] shrink-0 flex-col border-r border-border">
<div className="space-y-2 border-b border-border p-3">
<div className="relative">
<Search
size={16}
className="absolute left-3 top-2.5 text-muted-foreground"
/>
<input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search subject or passenger"
className="w-full rounded-lg border border-border bg-background py-2 pl-9 pr-3 text-sm outline-none focus:border-emerald-500"
/>
</div>
<div className="flex gap-1">
{FILTERS.map((f) => (
<button
key={f}
onClick={() => setStatus(f)}
className={`flex-1 rounded-md px-2 py-1 text-xs font-medium capitalize transition ${
status === f
? 'text-white'
: 'bg-muted text-muted-foreground hover:bg-muted/70'
}`}
style={status === f ? { background: GREEN } : undefined}
>
{f.toLowerCase()}
</button>
))}
</div>
</div>
<div className="flex-1 overflow-y-auto">
{isLoading ? (
<div className="p-6 text-center text-sm text-muted-foreground">
Loading
</div>
) : items.length === 0 ? (
<div className="p-6 text-center text-sm text-muted-foreground">
No conversations.
</div>
) : (
items.map((c) => (
<InboxRow
key={c.id}
c={c}
active={c.id === selectedId}
onClick={() => setSelectedId(c.id)}
/>
))
)}
</div>
</div>
{/* Thread */}
<div className="min-w-0 flex-1">
{selected ? (
<ConversationThread conversation={selected} />
) : (
<div className="flex h-full flex-col items-center justify-center gap-2 text-muted-foreground">
<span
className="flex h-14 w-14 items-center justify-center rounded-full"
style={{ background: 'rgba(20,113,76,0.1)', color: GREEN }}
>
<Headset size={28} />
</span>
<p className="text-sm">Select a conversation to start replying.</p>
</div>
)}
</div>
</div>
</div>
);
}
function InboxRow({
c,
active,
onClick,
}: {
c: ConversationDto;
active: boolean;
onClick: () => void;
}) {
const unread = c.unreadCount > 0;
return (
<button
onClick={onClick}
className={`block w-full border-b border-border px-4 py-3 text-left transition hover:bg-muted/50 ${
active ? 'bg-muted/70' : ''
}`}
style={active ? { borderLeft: `3px solid ${GREEN}` } : { borderLeft: '3px solid transparent' }}
>
<div className="flex items-center justify-between gap-2">
<span
className={`truncate text-sm ${
unread ? 'font-bold text-foreground' : 'font-semibold text-foreground/90'
}`}
>
{c.subject || 'Support request'}
</span>
<span className="shrink-0 text-xs text-muted-foreground">
{formatTime(c.lastMessageAt)}
</span>
</div>
<p className="mt-0.5 truncate text-xs text-muted-foreground">
{c.passengerName || 'Passenger'}
</p>
<div className="mt-1 flex items-center justify-between gap-2">
<span className="truncate text-xs text-muted-foreground">
{c.lastMessageSender === 'AGENT' ? 'You: ' : ''}
{c.lastMessagePreview ?? '—'}
</span>
{unread ? (
<span
className="flex h-5 min-w-5 items-center justify-center rounded-full px-1.5 text-xs font-semibold text-white"
style={{ background: GREEN }}
>
{c.unreadCount}
</span>
) : (
<span
className={`rounded-full px-2 py-0.5 text-[10px] font-medium capitalize ${
STATUS_CLASS[c.status] ?? ''
}`}
>
{c.status.toLowerCase()}
</span>
)}
</div>
</button>
);
}
function ConversationThread({ conversation }: { conversation: ConversationDto }) {
const { data: messages, isLoading } = useMessages(conversation.id);
const send = useSendMessage(conversation.id);
const setStatus = useSetStatus();
const markRead = useMarkRead();
const [draft, setDraft] = useState('');
const viewport = useRef<HTMLDivElement>(null);
useEffect(() => {
markRead.mutate(conversation.id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [conversation.id, messages?.length]);
useEffect(() => {
viewport.current?.scrollTo({ top: viewport.current.scrollHeight });
}, [messages?.length, conversation.id]);
const submit = async () => {
const text = draft.trim();
if (!text) return;
setDraft('');
await send.mutateAsync(text);
};
const changeStatus = (status: string) =>
setStatus.mutate({ id: conversation.id, status });
return (
<div className="flex h-full flex-col">
<div className="flex items-center justify-between gap-2 border-b border-border p-4">
<div className="min-w-0">
<div className="flex items-center gap-2">
<span className="truncate font-bold text-foreground">
{conversation.subject || 'Conversation'}
</span>
<span
className={`rounded-full px-2 py-0.5 text-[10px] font-medium capitalize ${
STATUS_CLASS[conversation.status] ?? ''
}`}
>
{conversation.status.toLowerCase()}
</span>
</div>
<p className="truncate text-xs text-muted-foreground">
{conversation.passengerName || 'Passenger'}
{conversation.guestId ? ' · Guest' : ''}
{conversation.guestEmail ? ` · ${conversation.guestEmail}` : ''}
{conversation.guestPhone ? ` · ${conversation.guestPhone}` : ''}
</p>
</div>
<div className="flex shrink-0 gap-2">
{conversation.status !== 'OPEN' && (
<button
onClick={() => changeStatus('OPEN')}
className="rounded-md px-3 py-1.5 text-xs font-medium text-white"
style={{ background: GREEN }}
>
Reopen
</button>
)}
{conversation.status === 'OPEN' && (
<button
onClick={() => changeStatus('RESOLVED')}
className="rounded-md bg-blue-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-blue-700"
>
Resolve
</button>
)}
{conversation.status !== 'CLOSED' && (
<button
onClick={() => changeStatus('CLOSED')}
className="rounded-md bg-muted px-3 py-1.5 text-xs font-medium text-muted-foreground hover:bg-muted/70"
>
Close
</button>
)}
</div>
</div>
<div ref={viewport} className="flex-1 space-y-3 overflow-y-auto p-4">
{isLoading ? (
<div className="p-6 text-center text-sm text-muted-foreground">
Loading
</div>
) : (
(messages ?? []).map((m) => <AgentBubble key={m.id} m={m} />)
)}
</div>
<div className="border-t border-border p-3">
<div className="flex items-end gap-2">
<textarea
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
submit();
}
}}
rows={1}
placeholder="Type your reply… (Enter to send, Shift+Enter for newline)"
className="max-h-28 flex-1 resize-none rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none focus:border-emerald-500"
/>
<button
onClick={submit}
disabled={!draft.trim() || send.isPending}
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-white transition hover:opacity-90 disabled:opacity-50"
style={{ background: GREEN }}
aria-label="Send"
>
<Send size={18} />
</button>
</div>
</div>
</div>
);
}
function AgentBubble({ m }: { m: MessageDto }) {
const mine = m.sender === 'AGENT';
return (
<div className={`flex ${mine ? 'justify-end' : 'justify-start'} items-end gap-2`}>
{!mine && (
<span className="flex h-7 w-7 items-center justify-center rounded-full bg-muted text-muted-foreground">
<User size={14} />
</span>
)}
<div className="max-w-[70%]">
<p
className={`mb-0.5 text-xs text-muted-foreground ${
mine ? 'text-right' : 'text-left'
}`}
>
{mine ? m.authorName || 'You' : m.authorName || 'Passenger'}
</p>
<div
className={`whitespace-pre-wrap break-words rounded-2xl px-3 py-2 text-sm ${
mine
? 'rounded-br-sm text-white'
: 'rounded-bl-sm bg-muted text-foreground'
}`}
style={mine ? { background: GREEN } : undefined}
>
{m.text}
</div>
<p
className={`mt-0.5 text-[10px] text-muted-foreground ${
mine ? 'text-right' : 'text-left'
}`}
>
{formatTime(m.createdAt)}
</p>
</div>
</div>
);
}

View File

@@ -104,7 +104,7 @@ const navigationSections: { title: string; items: NavItem[] }[] = [
title: 'Customer Services',
items: [
{ name: 'Loyalty Program', href: '/loyalty', icon: Gift, permission: PERMS.passengers.view },
// { name: 'Support Center', href: '/support', icon: MessageSquare, permission: PERMS.bookings.view },
{ name: 'Support Center', href: '/support', icon: MessageSquare, permission: PERMS.bookings.view },
{ name: 'Notifications', href: '/notifications', icon: Bell, permission: PERMS.notifications.send },
]
},

View File

@@ -0,0 +1,36 @@
import type { Passenger } from '@edr/types';
import { apiClient } from '@/lib/api-client';
type ConversationDto = Passenger.PassengerSupportConversationDto;
type MessageDto = Passenger.PassengerSupportMessageDto;
type ListResult = Passenger.PassengerSupportConversationListResult;
export interface ListParams {
status?: string;
search?: string;
}
/** 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>(
`/support/agent/conversations/${id}/messages`,
{ text },
),
setStatus: (id: string, status: string) =>
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'),
};

View File

@@ -0,0 +1,65 @@
'use client';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { supportApi, type ListParams } from './supportApi';
export const SUPPORT_CONVERSATIONS_KEY = ['support', 'conversations'];
export const SUPPORT_UNREAD_KEY = ['support', 'unread'];
export const supportMessagesKey = (id: string) => ['support', 'messages', id];
export function useConversations(params: ListParams = {}) {
return useQuery({
queryKey: [...SUPPORT_CONVERSATIONS_KEY, params],
queryFn: () => supportApi.listConversations(params),
});
}
export function useMessages(conversationId: string | null) {
return useQuery({
queryKey: supportMessagesKey(conversationId ?? ''),
queryFn: () => supportApi.listMessages(conversationId as string),
enabled: !!conversationId,
});
}
export function useUnreadCount(enabled = true) {
return useQuery({
queryKey: SUPPORT_UNREAD_KEY,
queryFn: () => supportApi.unreadCount(),
enabled,
refetchInterval: 60_000,
});
}
export function useSendMessage(conversationId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: (text: string) => supportApi.sendMessage(conversationId, text),
onSuccess: () => {
qc.invalidateQueries({ queryKey: supportMessagesKey(conversationId) });
qc.invalidateQueries({ queryKey: SUPPORT_CONVERSATIONS_KEY });
},
});
}
export function useSetStatus() {
const qc = useQueryClient();
return useMutation({
mutationFn: ({ id, status }: { id: string; status: string }) =>
supportApi.setStatus(id, status),
onSuccess: () =>
qc.invalidateQueries({ queryKey: SUPPORT_CONVERSATIONS_KEY }),
});
}
export function useMarkRead() {
const qc = useQueryClient();
return useMutation({
mutationFn: (id: string) => supportApi.markRead(id),
onSuccess: () => {
qc.invalidateQueries({ queryKey: SUPPORT_CONVERSATIONS_KEY });
qc.invalidateQueries({ queryKey: SUPPORT_UNREAD_KEY });
},
});
}

View File

@@ -0,0 +1,67 @@
'use client';
import { Passenger } from '@edr/types';
import { useQueryClient } from '@tanstack/react-query';
import { useEffect, useRef } from 'react';
import { io } from 'socket.io-client';
import {
SUPPORT_CONVERSATIONS_KEY,
SUPPORT_UNREAD_KEY,
supportMessagesKey,
} from './useSupport';
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
* inbox. Any new message / conversation change refreshes the thread, the inbox
* list, and the unread badge; `onMessage` fires for optional toasts.
*/
export function useSupportSocket(
enabled: boolean,
onMessage?: (event: Passenger.PassengerSupportMessageEvent) => void,
) {
const qc = useQueryClient();
const onMessageRef = useRef(onMessage);
onMessageRef.current = onMessage;
useEffect(() => {
if (!enabled || typeof window === 'undefined') return;
const token = localStorage.getItem('auth_token');
if (!token) return;
const socket = io(
`${SOCKET_ORIGIN}/${Passenger.PASSENGER_SUPPORT_WS_NAMESPACE}`,
{
auth: { token },
transports: ['websocket'],
withCredentials: true,
},
);
socket.on(
Passenger.PASSENGER_SUPPORT_WS_EVENTS.MESSAGE_NEW,
(event: Passenger.PassengerSupportMessageEvent) => {
qc.invalidateQueries({
queryKey: supportMessagesKey(event.message.conversationId),
});
qc.invalidateQueries({ queryKey: SUPPORT_CONVERSATIONS_KEY });
qc.invalidateQueries({ queryKey: SUPPORT_UNREAD_KEY });
onMessageRef.current?.(event);
},
);
socket.on(Passenger.PASSENGER_SUPPORT_WS_EVENTS.CONVERSATION_UPDATED, () => {
qc.invalidateQueries({ queryKey: SUPPORT_CONVERSATIONS_KEY });
qc.invalidateQueries({ queryKey: SUPPORT_UNREAD_KEY });
});
return () => {
socket.off();
socket.disconnect();
};
}, [enabled, qc]);
}