After correcting the chat issue1

This commit is contained in:
Your Name 2026-09-24 14:41:37 +02:00
parent 904a1e59ca
commit f25d004007
10 changed files with 253 additions and 71 deletions

View File

@ -32,13 +32,44 @@ function handleError(res: Response, e: unknown): void {
export async function getOrCreateConversation(req: AuthRequest, res: Response): Promise<void> {
try {
const conv = await supportService.getOrCreateConversation(buildCtx(req));
const conv = await supportService.findCurrentConversation(buildCtx(req));
res.json(conv);
} catch (e) {
handleError(res, e);
}
}
export async function postCurrentMessage(req: AuthRequest, res: Response): Promise<void> {
try {
const body = typeof req.body?.body === 'string' ? req.body.body : undefined;
const msg = await supportService.sendToCurrentConversation(buildCtx(req), { body });
res.status(201).json(msg);
} catch (e) {
handleError(res, e);
}
}
export async function userSendCurrentWithAttachment(req: AuthRequest, res: Response): Promise<void> {
try {
const body = typeof req.body?.body === 'string' ? req.body.body : undefined;
const attachmentUrl =
typeof req.body?.attachmentUrl === 'string' ? req.body.attachmentUrl : undefined;
const attachmentName =
typeof req.body?.attachmentName === 'string' ? req.body.attachmentName : undefined;
const attachmentMime =
typeof req.body?.attachmentMime === 'string' ? req.body.attachmentMime : undefined;
const msg = await supportService.sendToCurrentConversation(buildCtx(req), {
body,
attachmentUrl,
attachmentName,
attachmentMime,
});
res.status(201).json(msg);
} catch (e) {
handleError(res, e);
}
}
export async function listMyConversations(req: AuthRequest, res: Response): Promise<void> {
try {
const items = await supportService.listUserConversations(buildCtx(req));
@ -82,6 +113,33 @@ export async function postTyping(req: AuthRequest, res: Response): Promise<void>
}
}
export async function uploadCurrentAttachment(req: AuthRequest, res: Response): Promise<void> {
try {
if (!req.file) {
res.status(400).json({ error: 'No file uploaded' });
return;
}
const filePath = supportService.resolveUploadPath(req.file.filename);
try {
await validateUploadedFile(filePath, SUPPORT_ALLOWED_MIMES);
} catch (e) {
removeUploadedFile(filePath);
const msg = e instanceof Error ? e.message : 'File validation failed';
res.status(msg.includes('virus') ? 422 : 400).json({ error: msg });
return;
}
const url = supportService.publicAttachmentUrl(req.file.filename);
await recordUploadedFile(FILE_INTEGRITY_ROOTS.support, req.file.filename);
res.status(201).json({
attachmentUrl: url,
attachmentName: req.file.originalname,
attachmentMime: req.file.mimetype,
});
} catch (e) {
handleError(res, e);
}
}
export async function uploadAttachment(req: AuthRequest, res: Response): Promise<void> {
try {
if (!req.file) {

View File

@ -105,6 +105,7 @@ export async function listConversationsAdmin(
i++;
}
conditions.push('c.last_message_at IS NOT NULL');
const where = conditions.join(' AND ');
const limit = Math.min(filters.limit ?? 50, 100);
const offset = filters.offset ?? 0;

View File

@ -175,6 +175,23 @@ router.get('/share-cards/verify/:token', shareCardController.verifyShareCard);
/** Support messaging — guests (visitor token) and optional authenticated users. */
router.get('/support/files/:filename', supportController.getAttachment);
router.post('/support/conversations/current', optionalAuthMiddleware, supportController.getOrCreateConversation);
router.post(
'/support/conversations/current/messages',
optionalAuthMiddleware,
validateBody(supportMessageBodySchema),
supportController.postCurrentMessage
);
router.post(
'/support/conversations/current/messages/attachment',
optionalAuthMiddleware,
supportController.userSendCurrentWithAttachment
);
router.post(
'/support/conversations/current/upload',
optionalAuthMiddleware,
supportUpload.single('file'),
supportController.uploadCurrentAttachment
);
router.get('/support/conversations', optionalAuthMiddleware, supportController.listMyConversations);
router.get('/support/conversations/:id/messages', optionalAuthMiddleware, supportController.getMessages);
router.post('/support/conversations/:id/messages', optionalAuthMiddleware, validateBody(supportMessageBodySchema), supportController.postMessage);

View File

@ -100,7 +100,14 @@ export async function assertConversationAccess(
throw new Error('Forbidden');
}
export async function getOrCreateConversation(ctx: SupportAccessContext) {
export async function findCurrentConversation(ctx: SupportAccessContext) {
const conv = await findActiveConversationRow(ctx);
return conv ? mapConversation(conv) : null;
}
async function findActiveConversationRow(
ctx: SupportAccessContext
): Promise<SupportConversationRow | null> {
if (ctx.userId) {
let conv = await repo.findActiveConversationForUser(ctx.userId);
if (!conv && ctx.visitorToken) {
@ -109,21 +116,36 @@ export async function getOrCreateConversation(ctx: SupportAccessContext) {
conv = await repo.attachVisitorConversationToUser(visitorConv.id, ctx.userId);
}
}
if (!conv) {
conv = await repo.createConversation({ userId: ctx.userId });
}
return mapConversation(conv);
return conv;
}
if (!ctx.visitorToken) return null;
return repo.findActiveConversationForVisitor(ctx.visitorToken);
}
async function ensureConversationRow(
ctx: SupportAccessContext
): Promise<SupportConversationRow> {
const existing = await findActiveConversationRow(ctx);
if (existing) return existing;
if (ctx.userId) {
return repo.createConversation({ userId: ctx.userId });
}
if (!ctx.visitorToken) {
throw new Error('Visitor token is required for anonymous support');
}
return repo.createConversation({ visitorToken: ctx.visitorToken });
}
let conv = await repo.findActiveConversationForVisitor(ctx.visitorToken);
if (!conv) {
conv = await repo.createConversation({ visitorToken: ctx.visitorToken });
}
return mapConversation(conv);
export async function ensureCurrentConversation(ctx: SupportAccessContext) {
return mapConversation(await ensureConversationRow(ctx));
}
export async function sendToCurrentConversation(
ctx: SupportAccessContext,
input: { body?: string; attachmentUrl?: string; attachmentName?: string; attachmentMime?: string }
) {
const conv = await ensureConversationRow(ctx);
return sendMessage(conv.id, ctx, input);
}
export async function listUserConversations(ctx: SupportAccessContext) {

View File

@ -33,14 +33,16 @@ class SupportRepository {
});
}
Future<SupportConversationModel> getOrCreateConversation() async {
Future<SupportConversationModel?> findCurrentConversation() async {
try {
final res = await _api.dio.post<Map<String, dynamic>>(
final res = await _api.dio.post<dynamic>(
'/api/v1/support/conversations/current',
data: const {},
options: await _options(),
);
return SupportConversationModel.fromJson(res.data!);
final data = res.data;
if (data is! Map<String, dynamic> || data['id'] == null) return null;
return SupportConversationModel.fromJson(data);
} on DioException catch (e) {
throw AppException.fromDio(e, fallback: 'Failed to open support chat');
}
@ -65,10 +67,13 @@ class SupportRepository {
}
}
Future<SupportMessageModel> sendMessage(String conversationId, String body) async {
Future<SupportMessageModel> sendMessage(String? conversationId, String body) async {
try {
final path = conversationId == null || conversationId.isEmpty
? '/api/v1/support/conversations/current/messages'
: '/api/v1/support/conversations/$conversationId/messages';
final res = await _api.dio.post<Map<String, dynamic>>(
'/api/v1/support/conversations/$conversationId/messages',
path,
data: {'body': body},
options: await _options(),
);
@ -78,13 +83,16 @@ class SupportRepository {
}
}
Future<SupportMessageModel> sendImage(String conversationId, String filePath) async {
Future<SupportMessageModel> sendImage(String? conversationId, String filePath) async {
try {
final form = FormData.fromMap({
'file': await MultipartFile.fromFile(filePath),
});
final uploadPath = conversationId == null || conversationId.isEmpty
? '/api/v1/support/conversations/current/upload'
: '/api/v1/support/conversations/$conversationId/upload';
final uploaded = await _api.dio.post<Map<String, dynamic>>(
'/api/v1/support/conversations/$conversationId/upload',
uploadPath,
data: form,
options: Options(
headers: {
@ -94,8 +102,11 @@ class SupportRepository {
),
);
final data = uploaded.data!;
final attachPath = conversationId == null || conversationId.isEmpty
? '/api/v1/support/conversations/current/messages/attachment'
: '/api/v1/support/conversations/$conversationId/messages/attachment';
final res = await _api.dio.post<Map<String, dynamic>>(
'/api/v1/support/conversations/$conversationId/messages/attachment',
attachPath,
data: {
'attachmentUrl': data['attachmentUrl'],
'attachmentName': data['attachmentName'],

View File

@ -49,10 +49,22 @@ class SupportBloc extends Bloc<SupportEvent, SupportState> {
emit(state.copyWith(loading: true));
}
try {
final conv = state.conversation ?? await _repo.getOrCreateConversation();
final conv = state.conversation ?? await _repo.findCurrentConversation();
if (_socket.isEnabled) {
await _socket.connect();
_socket.subscribe(conv.id);
if (conv != null) {
_socket.subscribe(conv.id);
}
}
if (conv == null) {
emit(state.copyWith(
loading: false,
messages: const [],
staffTyping: false,
wsConnected: _socket.isConnected,
));
_startPoll();
return;
}
final page = await _repo.getMessages(conv.id);
emit(state.copyWith(
@ -96,10 +108,12 @@ class SupportBloc extends Bloc<SupportEvent, SupportState> {
if (body.isEmpty || state.sending) return;
emit(state.copyWith(sending: true, clearError: true));
try {
var conv = state.conversation;
conv ??= await _repo.getOrCreateConversation();
unawaited(_repo.setTyping(conv.id, false));
final msg = await _repo.sendMessage(conv.id, body);
final existing = state.conversation;
if (existing != null) {
unawaited(_repo.setTyping(existing.id, false));
}
final msg = await _repo.sendMessage(existing?.id, body);
final conv = await _conversationAfterSend(existing, msg);
emit(state.copyWith(
sending: false,
conversation: conv,
@ -117,9 +131,9 @@ class SupportBloc extends Bloc<SupportEvent, SupportState> {
if (state.sending) return;
emit(state.copyWith(sending: true, clearError: true));
try {
var conv = state.conversation;
conv ??= await _repo.getOrCreateConversation();
final msg = await _repo.sendImage(conv.id, event.filePath);
final existing = state.conversation;
final msg = await _repo.sendImage(existing?.id, event.filePath);
final conv = await _conversationAfterSend(existing, msg);
emit(state.copyWith(
sending: false,
conversation: conv,
@ -182,6 +196,19 @@ class SupportBloc extends Bloc<SupportEvent, SupportState> {
} catch (_) {}
}
Future<SupportConversationModel> _conversationAfterSend(
SupportConversationModel? existing,
SupportMessageModel msg,
) async {
if (existing != null) return existing;
final conv = SupportConversationModel(id: msg.conversationId, status: 'open');
if (_socket.isEnabled) {
await _socket.connect();
_socket.subscribe(conv.id);
}
return conv;
}
static bool _isTruthy(dynamic value) {
return value == true || value == 1 || value == 'true';
}

View File

@ -89,11 +89,12 @@ class _SupportChatHostState extends State<SupportChatHost> {
context: navContext,
useRootNavigator: true,
isScrollControlled: true,
useSafeArea: true,
useSafeArea: false,
backgroundColor: Colors.transparent,
builder: (ctx) {
final mq = MediaQuery.of(ctx);
return Padding(
padding: EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(ctx).bottom),
padding: EdgeInsets.only(bottom: mq.viewInsets.bottom),
child: const _SupportSheet(),
);
},
@ -197,15 +198,16 @@ class _SupportSheet extends StatelessWidget {
@override
Widget build(BuildContext context) {
final s = context.strings;
final maxHeight =
(MediaQuery.sizeOf(context).height * 0.62).clamp(320.0, 520.0);
final mq = MediaQuery.of(context);
final available = mq.size.height - mq.padding.top - 12;
final height = (available * 0.72).clamp(280.0, available);
return Material(
elevation: 12,
color: AppColors.surfaceCard,
borderRadius: BorderRadius.circular(16),
borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
clipBehavior: Clip.antiAlias,
child: SizedBox(
height: maxHeight,
height: height,
child: Column(
children: [
Container(
@ -231,9 +233,7 @@ class _SupportSheet extends StatelessWidget {
buildWhen: (p, c) => p.staffTyping != c.staffTyping,
builder: (context, state) {
return Text(
state.staffTyping
? s.supportTyping
: '${s.supportSubtitle} · 2.0.2',
state.staffTyping ? s.supportTyping : s.supportSubtitle,
style: TextStyle(
color: const Color(0xFF0B0F1A).withValues(alpha: 0.8),
fontSize: 11,
@ -253,7 +253,7 @@ class _SupportSheet extends StatelessWidget {
),
),
const Expanded(child: _SupportMessages()),
const _SupportComposer(),
const SafeArea(top: false, child: _SupportComposer()),
],
),
),

View File

@ -60,7 +60,7 @@ function AdminMessageList({
t: (key: string) => string;
}) {
return (
<Box sx={{ flex: 1, overflowY: 'auto', p: 2 }}>
<Box sx={{ flex: 1, minHeight: 0, overflowY: 'auto', p: 2 }}>
{messages.map((msg) => {
const isStaff = msg.senderType === 'staff';
return (
@ -244,8 +244,16 @@ export function SupportAdminPage() {
const user = detailQ.data?.user;
return (
<Box>
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', mb: 2 }}>
<Box
sx={{
display: 'flex',
flexDirection: 'column',
height: { lg: 'calc(100vh - 120px)' },
minHeight: 0,
overflow: { lg: 'hidden' },
}}
>
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', mb: 2, flexShrink: 0 }}>
<HeadsetMicRoundedIcon color="primary" />
<Typography variant="h4" sx={{ fontWeight: 900, flex: 1 }}>
{t('admin.supportAdmin.title')}
@ -260,11 +268,25 @@ export function SupportAdminPage() {
display: 'grid',
gridTemplateColumns: { xs: '1fr', lg: '320px 1fr 280px' },
gap: 2,
minHeight: 'calc(100vh - 180px)',
flex: { lg: 1 },
minHeight: 0,
alignItems: 'stretch',
overflow: { lg: 'hidden' },
}}
>
{/* Conversation list */}
<Paper sx={{ p: 2, borderRadius: 2, display: 'flex', flexDirection: 'column', minHeight: 400 }}>
<Paper
sx={{
p: 2,
borderRadius: 2,
display: 'flex',
flexDirection: 'column',
height: { xs: 420, lg: '100%' },
maxHeight: { xs: '70vh', lg: '100%' },
minHeight: 0,
overflow: 'hidden',
}}
>
<TextField
size="small"
placeholder={t('admin.supportAdmin.searchPlaceholder')}
@ -293,7 +315,7 @@ export function SupportAdminPage() {
</Select>
</FormControl>
<Box sx={{ flex: 1, overflowY: 'auto' }}>
<Box sx={{ flex: 1, minHeight: 0, overflowY: 'auto' }}>
{(listQ.data?.items ?? []).map((c: SupportConversation) => (
<Box
key={c.id}
@ -351,7 +373,17 @@ export function SupportAdminPage() {
</Paper>
{/* Chat */}
<Paper sx={{ borderRadius: 2, display: 'flex', flexDirection: 'column', minHeight: 400 }}>
<Paper
sx={{
borderRadius: 2,
display: 'flex',
flexDirection: 'column',
height: { xs: 520, lg: '100%' },
maxHeight: { xs: '80vh', lg: '100%' },
minHeight: 0,
overflow: 'hidden',
}}
>
{!selectedId ? (
<Typography sx={{ p: 3, opacity: 0.6 }}>{t('admin.supportAdmin.selectConversation')}</Typography>
) : (
@ -458,7 +490,16 @@ export function SupportAdminPage() {
</Paper>
{/* User context */}
<Paper sx={{ p: 2, borderRadius: 2, display: { xs: 'none', lg: 'block' } }}>
<Paper
sx={{
p: 2,
borderRadius: 2,
display: { xs: 'none', lg: 'block' },
height: '100%',
minHeight: 0,
overflowY: 'auto',
}}
>
<Typography variant="h6" sx={{ fontWeight: 800, mb: 1 }}>
{t('admin.supportAdmin.contextTitle')}
</Typography>

View File

@ -23,14 +23,14 @@ function requestConfig(extra?: { params?: Record<string, string> }) {
};
}
export async function fetchCurrentConversation(): Promise<SupportConversation> {
export async function fetchCurrentConversation(): Promise<SupportConversation | null> {
const client = supportClient();
const res = await client.post<SupportConversation>(
const res = await client.post<SupportConversation | null>(
'/api/v1/support/conversations/current',
{},
requestConfig()
);
return res.data;
return res.data?.id ? res.data : null;
}
export async function fetchMessages(
@ -45,18 +45,17 @@ export async function fetchMessages(
return res.data;
}
export async function sendSupportMessage(conversationId: string, body: string): Promise<SupportMessage> {
export async function sendSupportMessage(conversationId: string | undefined, body: string): Promise<SupportMessage> {
const client = supportClient();
const res = await client.post<SupportMessage>(
`/api/v1/support/conversations/${conversationId}/messages`,
{ body },
requestConfig()
);
const path = conversationId
? `/api/v1/support/conversations/${conversationId}/messages`
: '/api/v1/support/conversations/current/messages';
const res = await client.post<SupportMessage>(path, { body }, requestConfig());
return res.data;
}
export async function sendSupportAttachmentMessage(
conversationId: string,
conversationId: string | undefined,
payload: {
body?: string;
attachmentUrl: string;
@ -65,23 +64,25 @@ export async function sendSupportAttachmentMessage(
}
): Promise<SupportMessage> {
const client = supportClient();
const res = await client.post<SupportMessage>(
`/api/v1/support/conversations/${conversationId}/messages/attachment`,
payload,
requestConfig()
);
const path = conversationId
? `/api/v1/support/conversations/${conversationId}/messages/attachment`
: '/api/v1/support/conversations/current/messages/attachment';
const res = await client.post<SupportMessage>(path, payload, requestConfig());
return res.data;
}
export async function uploadSupportFile(conversationId: string, file: File) {
export async function uploadSupportFile(conversationId: string | undefined, file: File) {
const client = supportClient();
const form = new FormData();
form.append('file', file);
const path = conversationId
? `/api/v1/support/conversations/${conversationId}/upload`
: '/api/v1/support/conversations/current/upload';
const res = await client.post<{
attachmentUrl: string;
attachmentName: string;
attachmentMime: string;
}>(`/api/v1/support/conversations/${conversationId}/upload`, form, {
}>(path, form, {
headers: supportVisitorHeaders(),
});
return res.data;

View File

@ -216,20 +216,24 @@ export function SupportChatPanel({ widgetOpen = true, onOpenWidget }: Props) {
}, [messages, staffTyping]);
const sendMut = useMutation({
mutationFn: (body: string) => sendSupportMessage(conversationId!, body),
onSuccess: () => {
mutationFn: (body: string) => sendSupportMessage(conversationId, body),
onSuccess: (msg) => {
setDraft('');
void qc.invalidateQueries({ queryKey: ['support-messages', conversationId] });
setMessages((prev) => (prev.some((m) => m.id === msg.id) ? prev : [...prev, msg]));
void qc.invalidateQueries({ queryKey: ['support-conversation'] });
void qc.invalidateQueries({ queryKey: ['support-messages'] });
},
});
const attachMut = useMutation({
mutationFn: async (file: File) => {
const uploaded = await uploadSupportFile(conversationId!, file);
return sendSupportAttachmentMessage(conversationId!, uploaded);
const uploaded = await uploadSupportFile(conversationId, file);
return sendSupportAttachmentMessage(conversationId, uploaded);
},
onSuccess: () => {
void qc.invalidateQueries({ queryKey: ['support-messages', conversationId] });
onSuccess: (msg) => {
setMessages((prev) => (prev.some((m) => m.id === msg.id) ? prev : [...prev, msg]));
void qc.invalidateQueries({ queryKey: ['support-conversation'] });
void qc.invalidateQueries({ queryKey: ['support-messages'] });
},
});
@ -250,7 +254,7 @@ export function SupportChatPanel({ widgetOpen = true, onOpenWidget }: Props) {
const handleSend = () => {
const text = draft.trim();
if (!text || !conversationId || sendMut.isPending) return;
if (!text || sendMut.isPending) return;
notifyTyping(false);
sendMut.mutate(text);
};