After correcting the chat issue3
This commit is contained in:
parent
66a5ac6050
commit
3e8210c87e
@ -23,10 +23,18 @@ function handleError(res: Response, e: unknown): void {
|
||||
res.status(403).json({ error: msg });
|
||||
return;
|
||||
}
|
||||
if (msg === 'Conversation not found' || msg === 'Not found') {
|
||||
if (msg === 'Conversation not found' || msg === 'Not found' || msg === 'Message not found') {
|
||||
res.status(404).json({ error: msg });
|
||||
return;
|
||||
}
|
||||
if (
|
||||
msg === 'Edit window expired' ||
|
||||
msg === 'Delete window expired' ||
|
||||
msg === 'Message already deleted'
|
||||
) {
|
||||
res.status(409).json({ error: msg });
|
||||
return;
|
||||
}
|
||||
res.status(400).json({ error: msg });
|
||||
}
|
||||
|
||||
@ -93,6 +101,34 @@ export async function getMessages(req: AuthRequest, res: Response): Promise<void
|
||||
}
|
||||
}
|
||||
|
||||
export async function patchMessage(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const body = typeof req.body?.body === 'string' ? req.body.body : '';
|
||||
const msg = await supportService.editMessage(
|
||||
req.params.id,
|
||||
req.params.messageId,
|
||||
buildCtx(req),
|
||||
body
|
||||
);
|
||||
res.json(msg);
|
||||
} catch (e) {
|
||||
handleError(res, e);
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeMessage(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const msg = await supportService.deleteMessage(
|
||||
req.params.id,
|
||||
req.params.messageId,
|
||||
buildCtx(req)
|
||||
);
|
||||
res.json(msg);
|
||||
} catch (e) {
|
||||
handleError(res, e);
|
||||
}
|
||||
}
|
||||
|
||||
export async function postMessage(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const body = typeof req.body?.body === 'string' ? req.body.body : undefined;
|
||||
|
||||
@ -2167,10 +2167,33 @@ CREATE TABLE IF NOT EXISTS support_messages (
|
||||
attachment_name VARCHAR(255),
|
||||
attachment_mime VARCHAR(128),
|
||||
read_at TIMESTAMPTZ,
|
||||
edited_at TIMESTAMPTZ,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
CHECK (body IS NOT NULL OR attachment_url IS NOT NULL)
|
||||
CHECK (body IS NOT NULL OR attachment_url IS NOT NULL OR deleted_at IS NOT NULL)
|
||||
);
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema = 'public' AND table_name = 'support_messages' AND column_name = 'edited_at'
|
||||
) THEN
|
||||
ALTER TABLE support_messages ADD COLUMN edited_at TIMESTAMPTZ;
|
||||
END IF;
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema = 'public' AND table_name = 'support_messages' AND column_name = 'deleted_at'
|
||||
) THEN
|
||||
ALTER TABLE support_messages ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
INSERT INTO system_settings (key, value) VALUES
|
||||
('support_message_edit_window_minutes', '15'),
|
||||
('support_message_delete_window_minutes', '15')
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_support_msg_conv ON support_messages(conversation_id, created_at ASC);
|
||||
CREATE INDEX IF NOT EXISTS idx_support_msg_unread ON support_messages(conversation_id, read_at) WHERE read_at IS NULL;
|
||||
|
||||
|
||||
@ -54,4 +54,8 @@ export interface SystemSettings {
|
||||
login_risk_auto_suspend_accounts: boolean;
|
||||
/** Minimum login risk score (0–100) to trigger auto-suspend when enabled. */
|
||||
login_risk_auto_suspend_threshold: number;
|
||||
/** Minutes after send during which the author may edit a support message (0 = disabled). */
|
||||
support_message_edit_window_minutes: number;
|
||||
/** Minutes after send during which the author may delete a support message (0 = disabled). */
|
||||
support_message_delete_window_minutes: number;
|
||||
}
|
||||
|
||||
@ -27,5 +27,7 @@ export type SupportMessageRow = {
|
||||
attachment_name: string | null;
|
||||
attachment_mime: string | null;
|
||||
read_at: Date | null;
|
||||
edited_at: Date | null;
|
||||
deleted_at: Date | null;
|
||||
created_at: Date;
|
||||
};
|
||||
|
||||
@ -91,6 +91,10 @@ function buildDefaults(): SystemSettings {
|
||||
|
||||
login_risk_auto_suspend_threshold: 70,
|
||||
|
||||
support_message_edit_window_minutes: 15,
|
||||
|
||||
support_message_delete_window_minutes: 15,
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
@ -167,6 +171,10 @@ const INTEGER_KEYS = new Set([
|
||||
|
||||
'login_risk_auto_suspend_threshold',
|
||||
|
||||
'support_message_edit_window_minutes',
|
||||
|
||||
'support_message_delete_window_minutes',
|
||||
|
||||
]);
|
||||
|
||||
|
||||
@ -313,6 +321,10 @@ const UPDATABLE_KEYS = [
|
||||
|
||||
'max_concurrent_sessions',
|
||||
|
||||
'support_message_edit_window_minutes',
|
||||
|
||||
'support_message_delete_window_minutes',
|
||||
|
||||
] as const;
|
||||
|
||||
|
||||
|
||||
@ -242,6 +242,67 @@ export async function listMessages(
|
||||
);
|
||||
}
|
||||
|
||||
export async function findMessageById(id: string): Promise<SupportMessageRow | null> {
|
||||
const rows = await query<SupportMessageRow[]>(
|
||||
'SELECT * FROM support_messages WHERE id = $1',
|
||||
[id]
|
||||
);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
export async function findLatestVisibleMessage(
|
||||
conversationId: string
|
||||
): Promise<SupportMessageRow | null> {
|
||||
const rows = await query<SupportMessageRow[]>(
|
||||
`SELECT * FROM support_messages
|
||||
WHERE conversation_id = $1 AND deleted_at IS NULL
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1`,
|
||||
[conversationId]
|
||||
);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
export async function updateMessageBody(
|
||||
id: string,
|
||||
body: string
|
||||
): Promise<SupportMessageRow | null> {
|
||||
const rows = await query<SupportMessageRow[]>(
|
||||
`UPDATE support_messages
|
||||
SET body = $2, edited_at = NOW()
|
||||
WHERE id = $1 AND deleted_at IS NULL
|
||||
RETURNING *`,
|
||||
[id, body]
|
||||
);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
export async function softDeleteMessage(id: string): Promise<SupportMessageRow | null> {
|
||||
const rows = await query<SupportMessageRow[]>(
|
||||
`UPDATE support_messages
|
||||
SET deleted_at = NOW()
|
||||
WHERE id = $1 AND deleted_at IS NULL
|
||||
RETURNING *`,
|
||||
[id]
|
||||
);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
export async function updateConversationPreview(
|
||||
id: string,
|
||||
preview: string,
|
||||
lastMessageAt: Date | null
|
||||
): Promise<void> {
|
||||
await query(
|
||||
`UPDATE support_conversations SET
|
||||
last_message_preview = $2,
|
||||
last_message_at = $3,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[id, preview.slice(0, 500), lastMessageAt]
|
||||
);
|
||||
}
|
||||
|
||||
export async function createMessage(input: {
|
||||
conversationId: string;
|
||||
senderType: SupportSenderType;
|
||||
|
||||
@ -195,6 +195,17 @@ router.post(
|
||||
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);
|
||||
router.patch(
|
||||
'/support/conversations/:id/messages/:messageId',
|
||||
optionalAuthMiddleware,
|
||||
validateBody(supportMessageBodySchema),
|
||||
supportController.patchMessage
|
||||
);
|
||||
router.delete(
|
||||
'/support/conversations/:id/messages/:messageId',
|
||||
optionalAuthMiddleware,
|
||||
supportController.removeMessage
|
||||
);
|
||||
router.post(
|
||||
'/support/conversations/:id/messages/attachment',
|
||||
optionalAuthMiddleware,
|
||||
@ -546,6 +557,17 @@ router.get('/admin/support/conversations/:id', requireStaff(), supportController
|
||||
router.patch('/admin/support/conversations/:id', requireStaff(), validateBody(supportConversationUpdateBodySchema), supportController.adminUpdateConversation);
|
||||
router.get('/admin/support/conversations/:id/messages', requireStaff(), supportController.adminGetMessages);
|
||||
router.post('/admin/support/conversations/:id/messages', requireStaff(), validateBody(supportMessageBodySchema), supportController.adminPostMessage);
|
||||
router.patch(
|
||||
'/admin/support/conversations/:id/messages/:messageId',
|
||||
requireStaff(),
|
||||
validateBody(supportMessageBodySchema),
|
||||
supportController.patchMessage
|
||||
);
|
||||
router.delete(
|
||||
'/admin/support/conversations/:id/messages/:messageId',
|
||||
requireStaff(),
|
||||
supportController.removeMessage
|
||||
);
|
||||
router.post(
|
||||
'/admin/support/conversations/:id/messages/attachment',
|
||||
requireStaff(),
|
||||
|
||||
@ -179,6 +179,34 @@ function validateUpdates(updates: Partial<SystemSettings>): void {
|
||||
|
||||
}
|
||||
|
||||
if (updates.support_message_edit_window_minutes !== undefined) {
|
||||
|
||||
updates.support_message_edit_window_minutes = clampInt(
|
||||
|
||||
updates.support_message_edit_window_minutes,
|
||||
|
||||
0,
|
||||
|
||||
10_080
|
||||
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
if (updates.support_message_delete_window_minutes !== undefined) {
|
||||
|
||||
updates.support_message_delete_window_minutes = clampInt(
|
||||
|
||||
updates.support_message_delete_window_minutes,
|
||||
|
||||
0,
|
||||
|
||||
10_080
|
||||
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@ -384,6 +412,18 @@ export function parseSettingsUpdates(body: Record<string, unknown>): Partial<Sys
|
||||
|
||||
}
|
||||
|
||||
if (typeof body.support_message_edit_window_minutes === 'number') {
|
||||
|
||||
updates.support_message_edit_window_minutes = body.support_message_edit_window_minutes;
|
||||
|
||||
}
|
||||
|
||||
if (typeof body.support_message_delete_window_minutes === 'number') {
|
||||
|
||||
updates.support_message_delete_window_minutes = body.support_message_delete_window_minutes;
|
||||
|
||||
}
|
||||
|
||||
return updates;
|
||||
|
||||
}
|
||||
|
||||
98
backend/src/services/supportMessagePolicy.ts
Normal file
98
backend/src/services/supportMessagePolicy.ts
Normal file
@ -0,0 +1,98 @@
|
||||
/**
|
||||
* Pure rules for support message edit/delete windows.
|
||||
* Window duration comes from system settings; callers enforce ownership separately.
|
||||
*/
|
||||
|
||||
export type SupportMessageAction = 'edit' | 'delete';
|
||||
|
||||
export type SupportMessageActionWindows = {
|
||||
editWindowMinutes: number;
|
||||
deleteWindowMinutes: number;
|
||||
};
|
||||
|
||||
export type SupportMessageActionFlags = {
|
||||
canEdit: boolean;
|
||||
canDelete: boolean;
|
||||
editAvailableUntil: string | null;
|
||||
deleteAvailableUntil: string | null;
|
||||
};
|
||||
|
||||
export function clampSupportWindowMinutes(value: number): number {
|
||||
if (!Number.isFinite(value)) return 0;
|
||||
return Math.min(10_080, Math.max(0, Math.trunc(value)));
|
||||
}
|
||||
|
||||
export function computeActionWindow(
|
||||
createdAt: Date,
|
||||
windowMinutes: number,
|
||||
now: Date = new Date()
|
||||
): { allowed: boolean; availableUntil: Date | null } {
|
||||
const minutes = clampSupportWindowMinutes(windowMinutes);
|
||||
if (minutes <= 0) {
|
||||
return { allowed: false, availableUntil: null };
|
||||
}
|
||||
const until = new Date(createdAt.getTime() + minutes * 60_000);
|
||||
return { allowed: now.getTime() < until.getTime(), availableUntil: until };
|
||||
}
|
||||
|
||||
export function resolveSupportMessageActions(input: {
|
||||
createdAt: Date;
|
||||
deleted: boolean;
|
||||
isOwner: boolean;
|
||||
editWindowMinutes: number;
|
||||
deleteWindowMinutes: number;
|
||||
now?: Date;
|
||||
}): SupportMessageActionFlags {
|
||||
if (input.deleted || !input.isOwner) {
|
||||
return {
|
||||
canEdit: false,
|
||||
canDelete: false,
|
||||
editAvailableUntil: null,
|
||||
deleteAvailableUntil: null,
|
||||
};
|
||||
}
|
||||
const now = input.now ?? new Date();
|
||||
const edit = computeActionWindow(input.createdAt, input.editWindowMinutes, now);
|
||||
const del = computeActionWindow(input.createdAt, input.deleteWindowMinutes, now);
|
||||
return {
|
||||
canEdit: edit.allowed,
|
||||
canDelete: del.allowed,
|
||||
editAvailableUntil: edit.availableUntil?.toISOString() ?? null,
|
||||
deleteAvailableUntil: del.availableUntil?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function assertSupportMessageAction(
|
||||
action: SupportMessageAction,
|
||||
input: Parameters<typeof resolveSupportMessageActions>[0]
|
||||
): SupportMessageActionFlags {
|
||||
const flags = resolveSupportMessageActions(input);
|
||||
if (action === 'edit' && flags.canEdit) return flags;
|
||||
if (action === 'delete' && flags.canDelete) return flags;
|
||||
|
||||
if (!input.isOwner) {
|
||||
throw new Error('Forbidden');
|
||||
}
|
||||
if (input.deleted) {
|
||||
throw new Error('Message already deleted');
|
||||
}
|
||||
throw new Error(action === 'edit' ? 'Edit window expired' : 'Delete window expired');
|
||||
}
|
||||
|
||||
export function isSupportMessageOwner(input: {
|
||||
senderType: 'user' | 'visitor' | 'staff';
|
||||
senderUserId: string | null;
|
||||
conversationVisitorToken: string | null;
|
||||
actorUserId?: string;
|
||||
actorVisitorToken?: string | null;
|
||||
}): boolean {
|
||||
if (input.senderType === 'staff' || input.senderType === 'user') {
|
||||
return !!input.actorUserId && input.senderUserId === input.actorUserId;
|
||||
}
|
||||
return (
|
||||
input.senderType === 'visitor' &&
|
||||
!!input.actorVisitorToken &&
|
||||
!!input.conversationVisitorToken &&
|
||||
input.actorVisitorToken === input.conversationVisitorToken
|
||||
);
|
||||
}
|
||||
@ -9,6 +9,12 @@ export type SupportRealtimeEvent =
|
||||
message?: Record<string, unknown>;
|
||||
}
|
||||
| { type: 'message.read'; conversationId: string }
|
||||
| {
|
||||
type: 'message.updated' | 'message.deleted';
|
||||
conversationId: string;
|
||||
messageId: string;
|
||||
message?: Record<string, unknown>;
|
||||
}
|
||||
| { type: 'conversation.updated'; conversationId: string }
|
||||
| { type: 'typing'; conversationId: string; party: 'user' | 'staff'; active: boolean };
|
||||
|
||||
|
||||
@ -12,6 +12,13 @@ import {
|
||||
publishSupportEvent,
|
||||
setTypingIndicator,
|
||||
} from './supportRealtimeService';
|
||||
import * as settingsRepository from '../repositories/settingsRepository';
|
||||
import {
|
||||
assertSupportMessageAction,
|
||||
isSupportMessageOwner,
|
||||
resolveSupportMessageActions,
|
||||
type SupportMessageActionFlags,
|
||||
} from './supportMessagePolicy';
|
||||
|
||||
const STAFF_ROLES = new Set(['admin', 'moderator', 'super_admin']);
|
||||
|
||||
@ -25,26 +32,87 @@ function previewForMessage(body: string | null, attachmentName: string | null):
|
||||
return 'Message';
|
||||
}
|
||||
|
||||
function mapMessage(row: SupportMessageRow, staffNames?: Map<string, string>) {
|
||||
function mapMessage(
|
||||
row: SupportMessageRow,
|
||||
staffNames?: Map<string, string>,
|
||||
actions?: SupportMessageActionFlags
|
||||
) {
|
||||
const staffName =
|
||||
row.sender_type === 'staff' && row.sender_user_id
|
||||
? staffNames?.get(row.sender_user_id) ?? null
|
||||
: null;
|
||||
const deleted = !!row.deleted_at;
|
||||
return {
|
||||
id: row.id,
|
||||
conversationId: row.conversation_id,
|
||||
senderType: row.sender_type,
|
||||
senderUserId: row.sender_user_id,
|
||||
senderDisplayName: staffName,
|
||||
body: row.body,
|
||||
attachmentUrl: row.attachment_url,
|
||||
attachmentName: row.attachment_name,
|
||||
attachmentMime: row.attachment_mime,
|
||||
body: deleted ? null : row.body,
|
||||
attachmentUrl: deleted ? null : row.attachment_url,
|
||||
attachmentName: deleted ? null : row.attachment_name,
|
||||
attachmentMime: deleted ? null : row.attachment_mime,
|
||||
readAt: row.read_at?.toISOString() ?? null,
|
||||
editedAt: row.edited_at?.toISOString() ?? null,
|
||||
deletedAt: row.deleted_at?.toISOString() ?? null,
|
||||
createdAt: row.created_at.toISOString(),
|
||||
canEdit: actions?.canEdit ?? false,
|
||||
canDelete: actions?.canDelete ?? false,
|
||||
editAvailableUntil: actions?.editAvailableUntil ?? null,
|
||||
deleteAvailableUntil: actions?.deleteAvailableUntil ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
async function loadActionWindows() {
|
||||
const settings = await settingsRepository.getSettings();
|
||||
return {
|
||||
editWindowMinutes: settings.support_message_edit_window_minutes,
|
||||
deleteWindowMinutes: settings.support_message_delete_window_minutes,
|
||||
};
|
||||
}
|
||||
|
||||
function ownerFlags(
|
||||
row: SupportMessageRow,
|
||||
conv: SupportConversationRow,
|
||||
ctx: SupportAccessContext
|
||||
): boolean {
|
||||
return isSupportMessageOwner({
|
||||
senderType: row.sender_type,
|
||||
senderUserId: row.sender_user_id,
|
||||
conversationVisitorToken: conv.visitor_token,
|
||||
actorUserId: ctx.userId,
|
||||
actorVisitorToken: ctx.visitorToken,
|
||||
});
|
||||
}
|
||||
|
||||
function messageActions(
|
||||
row: SupportMessageRow,
|
||||
conv: SupportConversationRow,
|
||||
ctx: SupportAccessContext,
|
||||
windows: { editWindowMinutes: number; deleteWindowMinutes: number }
|
||||
): SupportMessageActionFlags {
|
||||
return resolveSupportMessageActions({
|
||||
createdAt: row.created_at,
|
||||
deleted: !!row.deleted_at,
|
||||
isOwner: ownerFlags(row, conv, ctx),
|
||||
editWindowMinutes: windows.editWindowMinutes,
|
||||
deleteWindowMinutes: windows.deleteWindowMinutes,
|
||||
});
|
||||
}
|
||||
|
||||
async function refreshConversationPreview(conversationId: string): Promise<void> {
|
||||
const latest = await repo.findLatestVisibleMessage(conversationId);
|
||||
if (!latest) {
|
||||
await repo.updateConversationPreview(conversationId, '', null);
|
||||
return;
|
||||
}
|
||||
await repo.updateConversationPreview(
|
||||
conversationId,
|
||||
previewForMessage(latest.body, latest.attachment_name),
|
||||
latest.created_at
|
||||
);
|
||||
}
|
||||
|
||||
function mapConversation(row: SupportConversationRow) {
|
||||
return {
|
||||
id: row.id,
|
||||
@ -163,7 +231,7 @@ export async function getConversationMessages(
|
||||
ctx: SupportAccessContext,
|
||||
after?: string
|
||||
) {
|
||||
await assertConversationAccess(conversationId, ctx);
|
||||
const conv = await assertConversationAccess(conversationId, ctx);
|
||||
const rows = await repo.listMessages(conversationId, after);
|
||||
const staffIds = rows
|
||||
.filter((m) => m.sender_type === 'staff' && m.sender_user_id)
|
||||
@ -184,9 +252,10 @@ export async function getConversationMessages(
|
||||
});
|
||||
|
||||
const typing = await getTypingIndicators(conversationId);
|
||||
const windows = await loadActionWindows();
|
||||
|
||||
return {
|
||||
messages: rows.map((r) => mapMessage(r, staffNames)),
|
||||
messages: rows.map((r) => mapMessage(r, staffNames, messageActions(r, conv, ctx, windows))),
|
||||
typing,
|
||||
};
|
||||
}
|
||||
@ -238,14 +307,95 @@ export async function sendMessage(
|
||||
await repo.updateConversation(conversationId, { status: 'open' });
|
||||
}
|
||||
|
||||
const windows = await loadActionWindows();
|
||||
const mapped = mapMessage(msg, undefined, messageActions(msg, conv, ctx, windows));
|
||||
|
||||
await publishSupportEvent(conversationId, {
|
||||
type: 'message.new',
|
||||
conversationId,
|
||||
messageId: msg.id,
|
||||
message: mapMessage(msg) as unknown as Record<string, unknown>,
|
||||
message: mapped as unknown as Record<string, unknown>,
|
||||
});
|
||||
|
||||
return mapMessage(msg);
|
||||
return mapped;
|
||||
}
|
||||
|
||||
export async function editMessage(
|
||||
conversationId: string,
|
||||
messageId: string,
|
||||
ctx: SupportAccessContext,
|
||||
body: string
|
||||
) {
|
||||
const conv = await assertConversationAccess(conversationId, ctx);
|
||||
const row = await repo.findMessageById(messageId);
|
||||
if (!row || row.conversation_id !== conversationId) {
|
||||
throw new Error('Message not found');
|
||||
}
|
||||
|
||||
const windows = await loadActionWindows();
|
||||
assertSupportMessageAction('edit', {
|
||||
createdAt: row.created_at,
|
||||
deleted: !!row.deleted_at,
|
||||
isOwner: ownerFlags(row, conv, ctx),
|
||||
editWindowMinutes: windows.editWindowMinutes,
|
||||
deleteWindowMinutes: windows.deleteWindowMinutes,
|
||||
});
|
||||
|
||||
const trimmed = body.trim();
|
||||
if (!trimmed && !row.attachment_url) {
|
||||
throw new Error('Message body or attachment is required');
|
||||
}
|
||||
|
||||
const updated = await repo.updateMessageBody(messageId, trimmed);
|
||||
if (!updated) {
|
||||
throw new Error('Message already deleted');
|
||||
}
|
||||
|
||||
await refreshConversationPreview(conversationId);
|
||||
const mapped = mapMessage(updated, undefined, messageActions(updated, conv, ctx, windows));
|
||||
await publishSupportEvent(conversationId, {
|
||||
type: 'message.updated',
|
||||
conversationId,
|
||||
messageId: updated.id,
|
||||
message: mapped as unknown as Record<string, unknown>,
|
||||
});
|
||||
return mapped;
|
||||
}
|
||||
|
||||
export async function deleteMessage(
|
||||
conversationId: string,
|
||||
messageId: string,
|
||||
ctx: SupportAccessContext
|
||||
) {
|
||||
const conv = await assertConversationAccess(conversationId, ctx);
|
||||
const row = await repo.findMessageById(messageId);
|
||||
if (!row || row.conversation_id !== conversationId) {
|
||||
throw new Error('Message not found');
|
||||
}
|
||||
|
||||
const windows = await loadActionWindows();
|
||||
assertSupportMessageAction('delete', {
|
||||
createdAt: row.created_at,
|
||||
deleted: !!row.deleted_at,
|
||||
isOwner: ownerFlags(row, conv, ctx),
|
||||
editWindowMinutes: windows.editWindowMinutes,
|
||||
deleteWindowMinutes: windows.deleteWindowMinutes,
|
||||
});
|
||||
|
||||
const updated = await repo.softDeleteMessage(messageId);
|
||||
if (!updated) {
|
||||
throw new Error('Message already deleted');
|
||||
}
|
||||
|
||||
await refreshConversationPreview(conversationId);
|
||||
const mapped = mapMessage(updated, undefined, messageActions(updated, conv, ctx, windows));
|
||||
await publishSupportEvent(conversationId, {
|
||||
type: 'message.deleted',
|
||||
conversationId,
|
||||
messageId: updated.id,
|
||||
message: mapped as unknown as Record<string, unknown>,
|
||||
});
|
||||
return mapped;
|
||||
}
|
||||
|
||||
export async function setTyping(
|
||||
|
||||
192
backend/src/tests/supportMessagePolicy.test.ts
Normal file
192
backend/src/tests/supportMessagePolicy.test.ts
Normal file
@ -0,0 +1,192 @@
|
||||
import { describe, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { parseSettingsUpdates } from '../services/settingsService';
|
||||
import {
|
||||
assertSupportMessageAction,
|
||||
clampSupportWindowMinutes,
|
||||
computeActionWindow,
|
||||
isSupportMessageOwner,
|
||||
resolveSupportMessageActions,
|
||||
} from '../services/supportMessagePolicy';
|
||||
|
||||
const createdAt = new Date('2026-09-24T10:00:00.000Z');
|
||||
|
||||
describe('clampSupportWindowMinutes', () => {
|
||||
test('truncates and clamps to 0–7 days', () => {
|
||||
assert.equal(clampSupportWindowMinutes(-3), 0);
|
||||
assert.equal(clampSupportWindowMinutes(15.9), 15);
|
||||
assert.equal(clampSupportWindowMinutes(20_000), 10_080);
|
||||
});
|
||||
});
|
||||
|
||||
describe('computeActionWindow', () => {
|
||||
test('allows edits inside the configured window', () => {
|
||||
const at1010 = new Date('2026-09-24T10:10:00.000Z');
|
||||
const result = computeActionWindow(createdAt, 15, at1010);
|
||||
assert.equal(result.allowed, true);
|
||||
assert.equal(result.availableUntil?.toISOString(), '2026-09-24T10:15:00.000Z');
|
||||
});
|
||||
|
||||
test('rejects edits after the window', () => {
|
||||
const at1016 = new Date('2026-09-24T10:16:00.000Z');
|
||||
const result = computeActionWindow(createdAt, 15, at1016);
|
||||
assert.equal(result.allowed, false);
|
||||
});
|
||||
|
||||
test('disables the action when the window is 0', () => {
|
||||
const result = computeActionWindow(createdAt, 0, createdAt);
|
||||
assert.equal(result.allowed, false);
|
||||
assert.equal(result.availableUntil, null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveSupportMessageActions', () => {
|
||||
test('uses independent edit and delete windows', () => {
|
||||
const at1008 = new Date('2026-09-24T10:08:00.000Z');
|
||||
const flags = resolveSupportMessageActions({
|
||||
createdAt,
|
||||
deleted: false,
|
||||
isOwner: true,
|
||||
editWindowMinutes: 5,
|
||||
deleteWindowMinutes: 15,
|
||||
now: at1008,
|
||||
});
|
||||
assert.equal(flags.canEdit, false);
|
||||
assert.equal(flags.canDelete, true);
|
||||
assert.equal(flags.deleteAvailableUntil, '2026-09-24T10:15:00.000Z');
|
||||
});
|
||||
|
||||
test('hides both actions for non-owners', () => {
|
||||
const flags = resolveSupportMessageActions({
|
||||
createdAt,
|
||||
deleted: false,
|
||||
isOwner: false,
|
||||
editWindowMinutes: 15,
|
||||
deleteWindowMinutes: 15,
|
||||
now: createdAt,
|
||||
});
|
||||
assert.equal(flags.canEdit, false);
|
||||
assert.equal(flags.canDelete, false);
|
||||
});
|
||||
|
||||
test('hides both actions after soft-delete', () => {
|
||||
const flags = resolveSupportMessageActions({
|
||||
createdAt,
|
||||
deleted: true,
|
||||
isOwner: true,
|
||||
editWindowMinutes: 15,
|
||||
deleteWindowMinutes: 15,
|
||||
now: createdAt,
|
||||
});
|
||||
assert.equal(flags.canEdit, false);
|
||||
assert.equal(flags.canDelete, false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('assertSupportMessageAction', () => {
|
||||
test('allows an in-window owner edit', () => {
|
||||
const flags = assertSupportMessageAction('edit', {
|
||||
createdAt,
|
||||
deleted: false,
|
||||
isOwner: true,
|
||||
editWindowMinutes: 15,
|
||||
deleteWindowMinutes: 15,
|
||||
now: new Date('2026-09-24T10:14:59.000Z'),
|
||||
});
|
||||
assert.equal(flags.canEdit, true);
|
||||
});
|
||||
|
||||
test('rejects a late API edit even if the client still shows the button', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
assertSupportMessageAction('edit', {
|
||||
createdAt,
|
||||
deleted: false,
|
||||
isOwner: true,
|
||||
editWindowMinutes: 15,
|
||||
deleteWindowMinutes: 15,
|
||||
now: new Date('2026-09-24T10:15:00.000Z'),
|
||||
}),
|
||||
/Edit window expired/
|
||||
);
|
||||
});
|
||||
|
||||
test('rejects delete after the delete window', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
assertSupportMessageAction('delete', {
|
||||
createdAt,
|
||||
deleted: false,
|
||||
isOwner: true,
|
||||
editWindowMinutes: 60,
|
||||
deleteWindowMinutes: 15,
|
||||
now: new Date('2026-09-24T10:16:00.000Z'),
|
||||
}),
|
||||
/Delete window expired/
|
||||
);
|
||||
});
|
||||
|
||||
test('rejects mutation of someone else\'s message', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
assertSupportMessageAction('delete', {
|
||||
createdAt,
|
||||
deleted: false,
|
||||
isOwner: false,
|
||||
editWindowMinutes: 15,
|
||||
deleteWindowMinutes: 15,
|
||||
now: createdAt,
|
||||
}),
|
||||
/Forbidden/
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('settings parse for support windows', () => {
|
||||
test('accepts independent edit and delete durations', () => {
|
||||
const updates = parseSettingsUpdates({
|
||||
support_message_edit_window_minutes: 15,
|
||||
support_message_delete_window_minutes: 30,
|
||||
});
|
||||
assert.equal(updates.support_message_edit_window_minutes, 15);
|
||||
assert.equal(updates.support_message_delete_window_minutes, 30);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isSupportMessageOwner', () => {
|
||||
test('matches a logged-in user to their own message', () => {
|
||||
assert.equal(
|
||||
isSupportMessageOwner({
|
||||
senderType: 'user',
|
||||
senderUserId: 'user-1',
|
||||
conversationVisitorToken: null,
|
||||
actorUserId: 'user-1',
|
||||
}),
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
test('matches a visitor token to an anonymous message', () => {
|
||||
assert.equal(
|
||||
isSupportMessageOwner({
|
||||
senderType: 'visitor',
|
||||
senderUserId: null,
|
||||
conversationVisitorToken: 'visitor-token-16+',
|
||||
actorVisitorToken: 'visitor-token-16+',
|
||||
}),
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
test('does not let a visitor claim a user message', () => {
|
||||
assert.equal(
|
||||
isSupportMessageOwner({
|
||||
senderType: 'user',
|
||||
senderUserId: 'user-1',
|
||||
conversationVisitorToken: 'visitor-token-16+',
|
||||
actorVisitorToken: 'visitor-token-16+',
|
||||
}),
|
||||
false
|
||||
);
|
||||
});
|
||||
});
|
||||
@ -30,6 +30,12 @@ class SupportMessageModel {
|
||||
this.attachmentName,
|
||||
this.attachmentMime,
|
||||
this.readAt,
|
||||
this.editedAt,
|
||||
this.deletedAt,
|
||||
this.canEdit = false,
|
||||
this.canDelete = false,
|
||||
this.editAvailableUntil,
|
||||
this.deleteAvailableUntil,
|
||||
});
|
||||
|
||||
final String id;
|
||||
@ -42,6 +48,24 @@ class SupportMessageModel {
|
||||
final String? attachmentName;
|
||||
final String? attachmentMime;
|
||||
final String? readAt;
|
||||
final String? editedAt;
|
||||
final String? deletedAt;
|
||||
final bool canEdit;
|
||||
final bool canDelete;
|
||||
final String? editAvailableUntil;
|
||||
final String? deleteAvailableUntil;
|
||||
|
||||
bool get isDeleted => deletedAt != null;
|
||||
|
||||
bool actionOpen(String? until, bool allowed) {
|
||||
if (!allowed || until == null || until.isEmpty) return false;
|
||||
final dt = DateTime.tryParse(until);
|
||||
if (dt == null) return false;
|
||||
return dt.isAfter(DateTime.now());
|
||||
}
|
||||
|
||||
bool get editOpen => actionOpen(editAvailableUntil, canEdit);
|
||||
bool get deleteOpen => actionOpen(deleteAvailableUntil, canDelete);
|
||||
|
||||
bool get isMine => senderType == 'user' || senderType == 'visitor';
|
||||
bool get isImage {
|
||||
@ -56,18 +80,34 @@ class SupportMessageModel {
|
||||
name.endsWith('.bmp');
|
||||
}
|
||||
|
||||
SupportMessageModel copyWith({String? readAt}) {
|
||||
SupportMessageModel copyWith({
|
||||
String? body,
|
||||
String? readAt,
|
||||
String? editedAt,
|
||||
String? deletedAt,
|
||||
bool? canEdit,
|
||||
bool? canDelete,
|
||||
String? editAvailableUntil,
|
||||
String? deleteAvailableUntil,
|
||||
bool clearAttachment = false,
|
||||
}) {
|
||||
return SupportMessageModel(
|
||||
id: id,
|
||||
conversationId: conversationId,
|
||||
senderType: senderType,
|
||||
createdAt: createdAt,
|
||||
senderDisplayName: senderDisplayName,
|
||||
body: body,
|
||||
attachmentUrl: attachmentUrl,
|
||||
attachmentName: attachmentName,
|
||||
attachmentMime: attachmentMime,
|
||||
body: body ?? this.body,
|
||||
attachmentUrl: clearAttachment ? null : attachmentUrl,
|
||||
attachmentName: clearAttachment ? null : attachmentName,
|
||||
attachmentMime: clearAttachment ? null : attachmentMime,
|
||||
readAt: readAt ?? this.readAt,
|
||||
editedAt: editedAt ?? this.editedAt,
|
||||
deletedAt: deletedAt ?? this.deletedAt,
|
||||
canEdit: canEdit ?? this.canEdit,
|
||||
canDelete: canDelete ?? this.canDelete,
|
||||
editAvailableUntil: editAvailableUntil ?? this.editAvailableUntil,
|
||||
deleteAvailableUntil: deleteAvailableUntil ?? this.deleteAvailableUntil,
|
||||
);
|
||||
}
|
||||
|
||||
@ -83,6 +123,12 @@ class SupportMessageModel {
|
||||
attachmentName: json['attachmentName'] as String?,
|
||||
attachmentMime: json['attachmentMime'] as String?,
|
||||
readAt: json['readAt'] as String?,
|
||||
editedAt: json['editedAt'] as String?,
|
||||
deletedAt: json['deletedAt'] as String?,
|
||||
canEdit: json['canEdit'] == true,
|
||||
canDelete: json['canDelete'] == true,
|
||||
editAvailableUntil: json['editAvailableUntil'] as String?,
|
||||
deleteAvailableUntil: json['deleteAvailableUntil'] as String?,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -132,6 +132,38 @@ class SupportRepository {
|
||||
}
|
||||
}
|
||||
|
||||
Future<SupportMessageModel> editMessage(
|
||||
String conversationId,
|
||||
String messageId,
|
||||
String body,
|
||||
) async {
|
||||
try {
|
||||
final res = await _api.dio.patch<Map<String, dynamic>>(
|
||||
'/api/v1/support/conversations/$conversationId/messages/$messageId',
|
||||
data: {'body': body},
|
||||
options: await _options(),
|
||||
);
|
||||
return SupportMessageModel.fromJson(res.data!);
|
||||
} on DioException catch (e) {
|
||||
throw AppException.fromDio(e, fallback: 'Failed to edit message');
|
||||
}
|
||||
}
|
||||
|
||||
Future<SupportMessageModel> deleteMessage(
|
||||
String conversationId,
|
||||
String messageId,
|
||||
) async {
|
||||
try {
|
||||
final res = await _api.dio.delete<Map<String, dynamic>>(
|
||||
'/api/v1/support/conversations/$conversationId/messages/$messageId',
|
||||
options: await _options(),
|
||||
);
|
||||
return SupportMessageModel.fromJson(res.data!);
|
||||
} on DioException catch (e) {
|
||||
throw AppException.fromDio(e, fallback: 'Failed to delete message');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setTyping(String conversationId, bool active) async {
|
||||
try {
|
||||
await _api.dio.post<void>(
|
||||
|
||||
@ -17,6 +17,8 @@ class SupportBloc extends Bloc<SupportEvent, SupportState> {
|
||||
on<SupportWsMessageReceived>(_onWs);
|
||||
on<SupportPollTick>(_onPoll);
|
||||
on<SupportIdentityReset>(_onIdentityReset);
|
||||
on<SupportMessageEditRequested>(_onEdit);
|
||||
on<SupportMessageDeleteRequested>(_onDelete);
|
||||
_socket.addListener(_handleSocket);
|
||||
}
|
||||
|
||||
@ -159,6 +161,17 @@ class SupportBloc extends Bloc<SupportEvent, SupportState> {
|
||||
if (msg['party'] == 'staff') {
|
||||
emit(state.copyWith(staffTyping: _isTruthy(msg['active'])));
|
||||
}
|
||||
case 'message.updated':
|
||||
case 'message.deleted':
|
||||
final rawUpdated = msg['message'];
|
||||
final updated = rawUpdated is Map
|
||||
? SupportMessageModel.fromJson(Map<String, dynamic>.from(rawUpdated))
|
||||
: null;
|
||||
if (updated != null) {
|
||||
emit(state.copyWith(messages: _replace(state.messages, updated)));
|
||||
} else {
|
||||
add(const SupportPollTick());
|
||||
}
|
||||
case 'message.new':
|
||||
final raw = msg['message'];
|
||||
final incoming = raw is Map
|
||||
@ -196,6 +209,37 @@ class SupportBloc extends Bloc<SupportEvent, SupportState> {
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> _onEdit(
|
||||
SupportMessageEditRequested event,
|
||||
Emitter<SupportState> emit,
|
||||
) async {
|
||||
final conv = state.conversation;
|
||||
final body = event.body.trim();
|
||||
if (conv == null || body.isEmpty || state.sending) return;
|
||||
emit(state.copyWith(sending: true, clearError: true));
|
||||
try {
|
||||
final msg = await _repo.editMessage(conv.id, event.messageId, body);
|
||||
emit(state.copyWith(sending: false, messages: _replace(state.messages, msg)));
|
||||
} catch (e) {
|
||||
emit(state.copyWith(sending: false, errorMessage: e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _onDelete(
|
||||
SupportMessageDeleteRequested event,
|
||||
Emitter<SupportState> emit,
|
||||
) async {
|
||||
final conv = state.conversation;
|
||||
if (conv == null || state.sending) return;
|
||||
emit(state.copyWith(sending: true, clearError: true));
|
||||
try {
|
||||
final msg = await _repo.deleteMessage(conv.id, event.messageId);
|
||||
emit(state.copyWith(sending: false, messages: _replace(state.messages, msg)));
|
||||
} catch (e) {
|
||||
emit(state.copyWith(sending: false, errorMessage: e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
Future<SupportConversationModel> _conversationAfterSend(
|
||||
SupportConversationModel? existing,
|
||||
SupportMessageModel msg,
|
||||
@ -221,6 +265,17 @@ class SupportBloc extends Bloc<SupportEvent, SupportState> {
|
||||
return [...current, incoming];
|
||||
}
|
||||
|
||||
static List<SupportMessageModel> _replace(
|
||||
List<SupportMessageModel> current,
|
||||
SupportMessageModel incoming,
|
||||
) {
|
||||
final index = current.indexWhere((m) => m.id == incoming.id);
|
||||
if (index < 0) return [...current, incoming];
|
||||
final next = [...current];
|
||||
next[index] = incoming;
|
||||
return next;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
_stopPoll();
|
||||
|
||||
@ -42,3 +42,18 @@ class SupportPollTick extends SupportEvent {
|
||||
class SupportIdentityReset extends SupportEvent {
|
||||
const SupportIdentityReset();
|
||||
}
|
||||
|
||||
class SupportMessageEditRequested extends SupportEvent {
|
||||
const SupportMessageEditRequested(this.messageId, this.body);
|
||||
final String messageId;
|
||||
final String body;
|
||||
@override
|
||||
List<Object?> get props => [messageId, body];
|
||||
}
|
||||
|
||||
class SupportMessageDeleteRequested extends SupportEvent {
|
||||
const SupportMessageDeleteRequested(this.messageId);
|
||||
final String messageId;
|
||||
@override
|
||||
List<Object?> get props => [messageId];
|
||||
}
|
||||
|
||||
@ -270,9 +270,19 @@ class _SupportMessages extends StatefulWidget {
|
||||
|
||||
class _SupportMessagesState extends State<_SupportMessages> {
|
||||
final _scroll = ScrollController();
|
||||
Timer? _windowTick;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_windowTick = Timer.periodic(const Duration(seconds: 5), (_) {
|
||||
if (mounted) setState(() {});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_windowTick?.cancel();
|
||||
_scroll.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
@ -492,10 +502,13 @@ class _MessageBubble extends StatelessWidget {
|
||||
final mine = message.isMine;
|
||||
final repo = context.read<SupportRepository>();
|
||||
final time = _formatTime(message.createdAt);
|
||||
final canAct = mine && !message.isDeleted && (message.editOpen || message.deleteOpen);
|
||||
|
||||
return Align(
|
||||
alignment: mine ? Alignment.centerRight : Alignment.centerLeft,
|
||||
child: Container(
|
||||
child: GestureDetector(
|
||||
onLongPress: canAct ? () => _showActions(context) : null,
|
||||
child: Container(
|
||||
constraints: BoxConstraints(
|
||||
maxWidth: MediaQuery.sizeOf(context).width * 0.72,
|
||||
),
|
||||
@ -528,7 +541,16 @@ class _MessageBubble extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
),
|
||||
if ((message.body ?? '').isNotEmpty)
|
||||
if (message.isDeleted)
|
||||
Text(
|
||||
s.supportDeleted,
|
||||
style: TextStyle(
|
||||
color: mine ? const Color(0xFF0B0F1A) : Colors.white,
|
||||
fontStyle: FontStyle.italic,
|
||||
height: 1.35,
|
||||
),
|
||||
)
|
||||
else if ((message.body ?? '').isNotEmpty)
|
||||
Text(
|
||||
message.body!,
|
||||
style: TextStyle(
|
||||
@ -536,7 +558,7 @@ class _MessageBubble extends StatelessWidget {
|
||||
height: 1.35,
|
||||
),
|
||||
),
|
||||
if (message.attachmentUrl != null) ...[
|
||||
if (!message.isDeleted && message.attachmentUrl != null) ...[
|
||||
if ((message.body ?? '').isNotEmpty) const SizedBox(height: 8),
|
||||
if (message.isImage)
|
||||
ClipRRect(
|
||||
@ -566,6 +588,17 @@ class _MessageBubble extends StatelessWidget {
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (message.editedAt != null && !message.isDeleted)
|
||||
Text(
|
||||
'${s.supportEdited} · ',
|
||||
style: TextStyle(
|
||||
fontSize: 10,
|
||||
fontStyle: FontStyle.italic,
|
||||
color: mine
|
||||
? const Color(0xFF0B0F1A).withValues(alpha: 0.7)
|
||||
: AppColors.textMuted,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
time,
|
||||
style: TextStyle(
|
||||
@ -589,10 +622,93 @@ class _MessageBubble extends StatelessWidget {
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _showActions(BuildContext context) async {
|
||||
final s = context.strings;
|
||||
final action = await showModalBottomSheet<String>(
|
||||
context: context,
|
||||
backgroundColor: AppColors.surfaceElevated,
|
||||
builder: (ctx) {
|
||||
return SafeArea(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (message.editOpen)
|
||||
ListTile(
|
||||
leading: const Icon(Icons.edit_outlined, color: Colors.white),
|
||||
title: Text(s.supportEdit, style: const TextStyle(color: Colors.white)),
|
||||
onTap: () => Navigator.pop(ctx, 'edit'),
|
||||
),
|
||||
if (message.deleteOpen)
|
||||
ListTile(
|
||||
leading: const Icon(Icons.delete_outline, color: Colors.white),
|
||||
title: Text(s.supportDelete, style: const TextStyle(color: Colors.white)),
|
||||
onTap: () => Navigator.pop(ctx, 'delete'),
|
||||
),
|
||||
ListTile(
|
||||
title: Text(s.cancel, style: const TextStyle(color: AppColors.textMuted)),
|
||||
onTap: () => Navigator.pop(ctx),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
if (!context.mounted || action == null) return;
|
||||
if (action == 'delete') {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: Text(s.supportDelete),
|
||||
content: Text(s.supportConfirmDelete),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text(s.cancel)),
|
||||
TextButton(onPressed: () => Navigator.pop(ctx, true), child: Text(s.supportDelete)),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed == true && context.mounted) {
|
||||
context.read<SupportBloc>().add(SupportMessageDeleteRequested(message.id));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (action == 'edit') {
|
||||
await _editMessage(context);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _editMessage(BuildContext context) async {
|
||||
final s = context.strings;
|
||||
final controller = TextEditingController(text: message.body ?? '');
|
||||
final saved = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: Text(s.supportEditHint),
|
||||
content: TextField(
|
||||
controller: controller,
|
||||
autofocus: true,
|
||||
maxLines: 4,
|
||||
decoration: InputDecoration(hintText: s.supportPlaceholder),
|
||||
),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(ctx), child: Text(s.cancel)),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx, controller.text.trim()),
|
||||
child: Text(s.supportSaveEdit),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
controller.dispose();
|
||||
if (saved != null && saved.isNotEmpty && context.mounted) {
|
||||
context.read<SupportBloc>().add(SupportMessageEditRequested(message.id, saved));
|
||||
}
|
||||
}
|
||||
|
||||
String _formatTime(String iso) {
|
||||
final dt = DateTime.tryParse(iso)?.toLocal();
|
||||
if (dt == null) return '';
|
||||
|
||||
@ -662,6 +662,13 @@ class AppStrings {
|
||||
'Could not open support chat. Please try again.',
|
||||
'Impossible d’ouvrir le chat support. Réessayez.',
|
||||
);
|
||||
String get supportEdit => t('Edit', 'Modifier');
|
||||
String get supportDelete => t('Delete', 'Supprimer');
|
||||
String get supportSaveEdit => t('Save', 'Enregistrer');
|
||||
String get supportEdited => t('edited', 'modifié');
|
||||
String get supportDeleted => t('This message was deleted', 'Ce message a été supprimé');
|
||||
String get supportConfirmDelete => t('Delete this message?', 'Supprimer ce message ?');
|
||||
String get supportEditHint => t('Edit message', 'Modifier le message');
|
||||
|
||||
// Common
|
||||
String get cancel => t('Cancel', 'Annuler');
|
||||
|
||||
@ -12,6 +12,7 @@ import {
|
||||
Card,
|
||||
CardContent,
|
||||
Checkbox,
|
||||
Chip,
|
||||
FormControlLabel,
|
||||
Stack,
|
||||
TextField,
|
||||
@ -62,6 +63,8 @@ export function SettingsPage() {
|
||||
candle_predict_backfill_seed_max: number;
|
||||
engine_audit_log_retention_days: number;
|
||||
withdrawal_network_fee_usdt_micro: number;
|
||||
support_message_edit_window_minutes: number;
|
||||
support_message_delete_window_minutes: number;
|
||||
};
|
||||
|
||||
const q = useQuery({
|
||||
@ -620,6 +623,72 @@ export function SettingsPage() {
|
||||
</AccordionDetails>
|
||||
</Accordion>
|
||||
|
||||
<Accordion defaultExpanded={false} sx={{ borderRadius: 2, overflow: 'hidden' }}>
|
||||
<AccordionSummary expandIcon={<ExpandMoreRoundedIcon />}>
|
||||
<Box>
|
||||
<Typography sx={{ fontWeight: 900 }}>
|
||||
{t('admin.settings.sections.supportMessages.title')}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7 }}>
|
||||
{t('admin.settings.sections.supportMessages.subtitle')}
|
||||
</Typography>
|
||||
</Box>
|
||||
</AccordionSummary>
|
||||
<AccordionDetails>
|
||||
<Stack spacing={2}>
|
||||
<Typography variant="body2" sx={{ opacity: 0.75 }}>
|
||||
{t('admin.settings.sections.supportMessages.hint')}
|
||||
</Typography>
|
||||
{(
|
||||
[
|
||||
[
|
||||
'support_message_edit_window_minutes',
|
||||
'admin.settings.sections.supportMessages.editWindow',
|
||||
'admin.settings.sections.supportMessages.editWindowHelper',
|
||||
],
|
||||
[
|
||||
'support_message_delete_window_minutes',
|
||||
'admin.settings.sections.supportMessages.deleteWindow',
|
||||
'admin.settings.sections.supportMessages.deleteWindowHelper',
|
||||
],
|
||||
] as const
|
||||
).map(([key, labelKey, helperKey]) => (
|
||||
<Box key={key}>
|
||||
<TextField
|
||||
label={t(labelKey)}
|
||||
helperText={t(helperKey)}
|
||||
type="number"
|
||||
value={effective[key]}
|
||||
onChange={(e) => set(key, parseNum(e.target.value))}
|
||||
fullWidth
|
||||
slotProps={{ htmlInput: { min: 0, max: 10080 } }}
|
||||
/>
|
||||
<Stack direction="row" spacing={1} sx={{ mt: 1, flexWrap: 'wrap' }}>
|
||||
{[1, 5, 15, 30, 60, 0].map((minutes) => (
|
||||
<Chip
|
||||
key={`${key}-${minutes}`}
|
||||
size="small"
|
||||
label={
|
||||
minutes === 0
|
||||
? t('admin.settings.sections.supportMessages.disabled')
|
||||
: minutes === 60
|
||||
? t('admin.settings.sections.supportMessages.oneHour')
|
||||
: t('admin.settings.sections.supportMessages.minutes', {
|
||||
count: minutes,
|
||||
})
|
||||
}
|
||||
color={effective[key] === minutes ? 'primary' : 'default'}
|
||||
variant={effective[key] === minutes ? 'filled' : 'outlined'}
|
||||
onClick={() => set(key, minutes)}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
</Box>
|
||||
))}
|
||||
</Stack>
|
||||
</AccordionDetails>
|
||||
</Accordion>
|
||||
|
||||
<PermissionGate permission="admin.settings.edit">
|
||||
<Stack direction="row" spacing={1} sx={{ justifyContent: 'flex-end', pt: 0.5 }}>
|
||||
<Button
|
||||
|
||||
@ -34,8 +34,11 @@ import {
|
||||
adminSetTyping,
|
||||
adminUpdateConversation,
|
||||
adminUploadFile,
|
||||
adminDeleteMessage,
|
||||
adminEditMessage,
|
||||
attachmentFullUrl,
|
||||
isSupportImage,
|
||||
supportActionOpen,
|
||||
} from './api/supportApi';
|
||||
import { useSupportSocket } from './hooks/useSupportSocket';
|
||||
import { notifySupportMessage, requestSupportNotificationPermission } from './utils/notifications';
|
||||
@ -55,15 +58,37 @@ function AdminMessageList({
|
||||
messages,
|
||||
staffTyping,
|
||||
t,
|
||||
nowMs,
|
||||
editingId,
|
||||
editDraft,
|
||||
onEditDraft,
|
||||
onStartEdit,
|
||||
onCancelEdit,
|
||||
onSaveEdit,
|
||||
onDelete,
|
||||
busy,
|
||||
}: {
|
||||
messages: SupportMessage[];
|
||||
staffTyping?: boolean;
|
||||
t: (key: string) => string;
|
||||
nowMs: number;
|
||||
editingId: string | null;
|
||||
editDraft: string;
|
||||
onEditDraft: (value: string) => void;
|
||||
onStartEdit: (msg: SupportMessage) => void;
|
||||
onCancelEdit: () => void;
|
||||
onSaveEdit: () => void;
|
||||
onDelete: (msg: SupportMessage) => void;
|
||||
busy: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Box sx={{ flex: 1, minHeight: 0, overflowY: 'auto', p: 2 }}>
|
||||
{messages.map((msg) => {
|
||||
const isStaff = msg.senderType === 'staff';
|
||||
const deleted = !!msg.deletedAt;
|
||||
const editing = editingId === msg.id;
|
||||
const canEdit = supportActionOpen(msg.canEdit, msg.editAvailableUntil, nowMs);
|
||||
const canDelete = supportActionOpen(msg.canDelete, msg.deleteAvailableUntil, nowMs);
|
||||
return (
|
||||
<Box key={msg.id} sx={{ display: 'flex', justifyContent: isStaff ? 'flex-end' : 'flex-start', mb: 1 }}>
|
||||
<Paper
|
||||
@ -80,12 +105,36 @@ function AdminMessageList({
|
||||
{msg.senderType === 'visitor' ? t('admin.supportAdmin.visitor') : t('admin.supportAdmin.user')}
|
||||
</Typography>
|
||||
)}
|
||||
{msg.body && (
|
||||
<Typography variant="body2" sx={{ whiteSpace: 'pre-wrap' }}>
|
||||
{msg.body}
|
||||
{deleted ? (
|
||||
<Typography variant="body2" sx={{ fontStyle: 'italic', opacity: 0.7 }}>
|
||||
{t('admin.supportAdmin.deleted')}
|
||||
</Typography>
|
||||
) : editing ? (
|
||||
<Stack spacing={1}>
|
||||
<TextField
|
||||
size="small"
|
||||
multiline
|
||||
maxRows={4}
|
||||
value={editDraft}
|
||||
onChange={(e) => onEditDraft(e.target.value)}
|
||||
/>
|
||||
<Stack direction="row" spacing={1} justifyContent="flex-end">
|
||||
<Button size="small" onClick={onCancelEdit} disabled={busy}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button size="small" variant="contained" onClick={onSaveEdit} disabled={busy || !editDraft.trim()}>
|
||||
{t('admin.supportAdmin.edit')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Stack>
|
||||
) : (
|
||||
msg.body && (
|
||||
<Typography variant="body2" sx={{ whiteSpace: 'pre-wrap' }}>
|
||||
{msg.body}
|
||||
</Typography>
|
||||
)
|
||||
)}
|
||||
{msg.attachmentUrl &&
|
||||
{!deleted && msg.attachmentUrl &&
|
||||
(isSupportImage(msg) ? (
|
||||
<Box
|
||||
component="a"
|
||||
@ -118,10 +167,27 @@ function AdminMessageList({
|
||||
📎 {msg.attachmentName}
|
||||
</Typography>
|
||||
))}
|
||||
<Typography variant="caption" sx={{ opacity: 0.6, display: 'block', textAlign: 'right' }}>
|
||||
{new Date(msg.createdAt).toLocaleString()}
|
||||
{msg.readAt ? t('admin.supportAdmin.read') : ''}
|
||||
</Typography>
|
||||
<Stack direction="row" spacing={0.5} sx={{ alignItems: 'center', justifyContent: 'flex-end', mt: 0.5 }}>
|
||||
{isStaff && !deleted && (canEdit || canDelete) && !editing && (
|
||||
<>
|
||||
{canEdit && (
|
||||
<Button size="small" onClick={() => onStartEdit(msg)} disabled={busy}>
|
||||
{t('admin.supportAdmin.edit')}
|
||||
</Button>
|
||||
)}
|
||||
{canDelete && (
|
||||
<Button size="small" color="error" onClick={() => onDelete(msg)} disabled={busy}>
|
||||
{t('admin.supportAdmin.delete')}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<Typography variant="caption" sx={{ opacity: 0.6 }}>
|
||||
{msg.editedAt && !deleted ? `${t('admin.supportAdmin.edited')} · ` : ''}
|
||||
{new Date(msg.createdAt).toLocaleString()}
|
||||
{msg.readAt ? t('admin.supportAdmin.read') : ''}
|
||||
</Typography>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
@ -146,16 +212,37 @@ export function SupportAdminPage() {
|
||||
const [page, setPage] = useState(1);
|
||||
const [draft, setDraft] = useState('');
|
||||
const [messages, setMessages] = useState<SupportMessage[]>([]);
|
||||
const [nowMs, setNowMs] = useState(() => Date.now());
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [editDraft, setEditDraft] = useState('');
|
||||
const [userTyping, setUserTyping] = useState(false);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const typingTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const handleWsEvent = useCallback(
|
||||
(msg: SupportWsServerMessage) => {
|
||||
if (msg.type === 'conversation.updated' || msg.type === 'message.new') {
|
||||
if (
|
||||
msg.type === 'conversation.updated' ||
|
||||
msg.type === 'message.new' ||
|
||||
msg.type === 'message.updated' ||
|
||||
msg.type === 'message.deleted'
|
||||
) {
|
||||
void qc.invalidateQueries({ queryKey: ['admin-support-conversations'] });
|
||||
void qc.invalidateQueries({ queryKey: ['admin-support-unread'] });
|
||||
}
|
||||
if (
|
||||
(msg.type === 'message.updated' || msg.type === 'message.deleted') &&
|
||||
msg.conversationId === selectedId &&
|
||||
msg.message
|
||||
) {
|
||||
setMessages((prev) => {
|
||||
const index = prev.findIndex((m) => m.id === msg.message!.id);
|
||||
if (index === -1) return [...prev, msg.message!];
|
||||
const copy = [...prev];
|
||||
copy[index] = msg.message!;
|
||||
return copy;
|
||||
});
|
||||
}
|
||||
if (msg.type === 'message.new') {
|
||||
if (msg.conversationId === selectedId && msg.message) {
|
||||
setMessages((prev) => {
|
||||
@ -190,6 +277,11 @@ export function SupportAdminPage() {
|
||||
void requestSupportNotificationPermission();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const id = window.setInterval(() => setNowMs(Date.now()), 5000);
|
||||
return () => window.clearInterval(id);
|
||||
}, []);
|
||||
|
||||
const listQ = useQuery({
|
||||
queryKey: ['admin-support-conversations', statusFilter, search, page],
|
||||
queryFn: () =>
|
||||
@ -254,6 +346,24 @@ export function SupportAdminPage() {
|
||||
},
|
||||
});
|
||||
|
||||
const editMut = useMutation({
|
||||
mutationFn: (input: { messageId: string; body: string }) =>
|
||||
adminEditMessage(selectedId!, input.messageId, input.body),
|
||||
onSuccess: (msg) => {
|
||||
setEditingId(null);
|
||||
setMessages((prev) => prev.map((m) => (m.id === msg.id ? msg : m)));
|
||||
void qc.invalidateQueries({ queryKey: ['admin-support-conversations'] });
|
||||
},
|
||||
});
|
||||
|
||||
const deleteMut = useMutation({
|
||||
mutationFn: (messageId: string) => adminDeleteMessage(selectedId!, messageId),
|
||||
onSuccess: (msg) => {
|
||||
setMessages((prev) => prev.map((m) => (m.id === msg.id ? msg : m)));
|
||||
void qc.invalidateQueries({ queryKey: ['admin-support-conversations'] });
|
||||
},
|
||||
});
|
||||
|
||||
const notifyTyping = useCallback(
|
||||
(active: boolean) => {
|
||||
if (!selectedId) return;
|
||||
@ -442,7 +552,30 @@ export function SupportAdminPage() {
|
||||
</Stack>
|
||||
</PermissionGate>
|
||||
|
||||
<AdminMessageList messages={messages} staffTyping={userTyping} t={t} />
|
||||
<AdminMessageList
|
||||
messages={messages}
|
||||
staffTyping={userTyping}
|
||||
t={t}
|
||||
nowMs={nowMs}
|
||||
editingId={editingId}
|
||||
editDraft={editDraft}
|
||||
onEditDraft={setEditDraft}
|
||||
onStartEdit={(msg) => {
|
||||
setEditingId(msg.id);
|
||||
setEditDraft(msg.body ?? '');
|
||||
}}
|
||||
onCancelEdit={() => setEditingId(null)}
|
||||
onSaveEdit={() => {
|
||||
if (!editingId || !editDraft.trim()) return;
|
||||
editMut.mutate({ messageId: editingId, body: editDraft.trim() });
|
||||
}}
|
||||
onDelete={(msg) => {
|
||||
if (window.confirm(t('admin.supportAdmin.confirmDelete'))) {
|
||||
deleteMut.mutate(msg.id);
|
||||
}
|
||||
}}
|
||||
busy={editMut.isPending || deleteMut.isPending}
|
||||
/>
|
||||
|
||||
<PermissionGate
|
||||
permission="admin.support.manage"
|
||||
|
||||
@ -185,6 +185,64 @@ export function attachmentFullUrl(relativeUrl: string): string {
|
||||
|
||||
const IMAGE_EXT = /\.(jpe?g|png|gif|webp|bmp|heic)$/i;
|
||||
|
||||
export async function editSupportMessage(
|
||||
conversationId: string,
|
||||
messageId: string,
|
||||
body: string
|
||||
): Promise<SupportMessage> {
|
||||
const client = supportClient();
|
||||
const res = await client.patch<SupportMessage>(
|
||||
`/api/v1/support/conversations/${conversationId}/messages/${messageId}`,
|
||||
{ body },
|
||||
requestConfig()
|
||||
);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function deleteSupportMessage(
|
||||
conversationId: string,
|
||||
messageId: string
|
||||
): Promise<SupportMessage> {
|
||||
const client = supportClient();
|
||||
const res = await client.delete<SupportMessage>(
|
||||
`/api/v1/support/conversations/${conversationId}/messages/${messageId}`,
|
||||
requestConfig()
|
||||
);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function adminEditMessage(
|
||||
conversationId: string,
|
||||
messageId: string,
|
||||
body: string
|
||||
): Promise<SupportMessage> {
|
||||
const res = await api.patch<SupportMessage>(
|
||||
`/api/v1/admin/support/conversations/${conversationId}/messages/${messageId}`,
|
||||
{ body }
|
||||
);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function adminDeleteMessage(
|
||||
conversationId: string,
|
||||
messageId: string
|
||||
): Promise<SupportMessage> {
|
||||
const res = await api.delete<SupportMessage>(
|
||||
`/api/v1/admin/support/conversations/${conversationId}/messages/${messageId}`
|
||||
);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export function supportActionOpen(
|
||||
allowed: boolean | undefined,
|
||||
until: string | null | undefined,
|
||||
nowMs = Date.now()
|
||||
): boolean {
|
||||
if (!allowed) return false;
|
||||
if (!until) return false;
|
||||
return new Date(until).getTime() > nowMs;
|
||||
}
|
||||
|
||||
export function isSupportImage(msg: {
|
||||
attachmentMime?: string | null;
|
||||
attachmentName?: string | null;
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
CircularProgress,
|
||||
IconButton,
|
||||
InputAdornment,
|
||||
@ -9,20 +10,25 @@ import {
|
||||
Typography,
|
||||
} from '@mui/material';
|
||||
import AttachFileRoundedIcon from '@mui/icons-material/AttachFileRounded';
|
||||
import DeleteOutlineRoundedIcon from '@mui/icons-material/DeleteOutlineRounded';
|
||||
import DoneAllRoundedIcon from '@mui/icons-material/DoneAllRounded';
|
||||
import DoneRoundedIcon from '@mui/icons-material/DoneRounded';
|
||||
import EditOutlinedIcon from '@mui/icons-material/EditOutlined';
|
||||
import SendRoundedIcon from '@mui/icons-material/SendRounded';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
attachmentFullUrl,
|
||||
deleteSupportMessage,
|
||||
editSupportMessage,
|
||||
isSupportImage,
|
||||
fetchCurrentConversation,
|
||||
fetchMessages,
|
||||
sendSupportAttachmentMessage,
|
||||
sendSupportMessage,
|
||||
setSupportTyping,
|
||||
supportActionOpen,
|
||||
uploadSupportFile,
|
||||
} from '../api/supportApi';
|
||||
import { useSupportSocket } from '../hooks/useSupportSocket';
|
||||
@ -52,16 +58,45 @@ function ReadIndicator({ readAt }: { readAt: string | null }) {
|
||||
return <DoneRoundedIcon sx={{ fontSize: 14, opacity: 0.5 }} />;
|
||||
}
|
||||
|
||||
function upsertMessage(prev: SupportMessage[], next: SupportMessage) {
|
||||
const index = prev.findIndex((m) => m.id === next.id);
|
||||
if (index === -1) return [...prev, next];
|
||||
const copy = [...prev];
|
||||
copy[index] = next;
|
||||
return copy;
|
||||
}
|
||||
|
||||
function MessageBubble({
|
||||
msg,
|
||||
isMine,
|
||||
t,
|
||||
nowMs,
|
||||
editing,
|
||||
editDraft,
|
||||
onEditDraft,
|
||||
onStartEdit,
|
||||
onCancelEdit,
|
||||
onSaveEdit,
|
||||
onDelete,
|
||||
busy,
|
||||
}: {
|
||||
msg: SupportMessage;
|
||||
isMine: boolean;
|
||||
t: (key: string) => string;
|
||||
nowMs: number;
|
||||
editing: boolean;
|
||||
editDraft: string;
|
||||
onEditDraft: (value: string) => void;
|
||||
onStartEdit: () => void;
|
||||
onCancelEdit: () => void;
|
||||
onSaveEdit: () => void;
|
||||
onDelete: () => void;
|
||||
busy: boolean;
|
||||
}) {
|
||||
const isImage = isSupportImage(msg);
|
||||
const canEdit = supportActionOpen(msg.canEdit, msg.editAvailableUntil, nowMs);
|
||||
const canDelete = supportActionOpen(msg.canDelete, msg.deleteAvailableUntil, nowMs);
|
||||
const deleted = !!msg.deletedAt;
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
@ -88,12 +123,37 @@ function MessageBubble({
|
||||
{msg.senderDisplayName}
|
||||
</Typography>
|
||||
)}
|
||||
{msg.body && (
|
||||
<Typography variant="body2" sx={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
|
||||
{msg.body}
|
||||
{deleted ? (
|
||||
<Typography variant="body2" sx={{ fontStyle: 'italic', opacity: 0.75 }}>
|
||||
{t('support.chat.deleted')}
|
||||
</Typography>
|
||||
) : editing ? (
|
||||
<Stack spacing={1}>
|
||||
<TextField
|
||||
size="small"
|
||||
multiline
|
||||
maxRows={4}
|
||||
value={editDraft}
|
||||
onChange={(e) => onEditDraft(e.target.value)}
|
||||
autoFocus
|
||||
/>
|
||||
<Stack direction="row" spacing={1} justifyContent="flex-end">
|
||||
<Button size="small" onClick={onCancelEdit} disabled={busy}>
|
||||
{t('support.chat.cancelEdit')}
|
||||
</Button>
|
||||
<Button size="small" variant="contained" onClick={onSaveEdit} disabled={busy || !editDraft.trim()}>
|
||||
{t('support.chat.saveEdit')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Stack>
|
||||
) : (
|
||||
msg.body && (
|
||||
<Typography variant="body2" sx={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
|
||||
{msg.body}
|
||||
</Typography>
|
||||
)
|
||||
)}
|
||||
{msg.attachmentUrl && (
|
||||
{!deleted && msg.attachmentUrl && (
|
||||
<Box sx={{ mt: msg.body ? 1 : 0 }}>
|
||||
{isImage ? (
|
||||
<Box
|
||||
@ -117,6 +177,25 @@ function MessageBubble({
|
||||
</Box>
|
||||
)}
|
||||
<Stack direction="row" spacing={0.5} sx={{ alignItems: 'center', justifyContent: 'flex-end', mt: 0.5 }}>
|
||||
{isMine && !deleted && (canEdit || canDelete) && !editing && (
|
||||
<>
|
||||
{canEdit && (
|
||||
<IconButton size="small" onClick={onStartEdit} disabled={busy} sx={{ color: 'inherit', p: 0.25 }}>
|
||||
<EditOutlinedIcon sx={{ fontSize: 14 }} />
|
||||
</IconButton>
|
||||
)}
|
||||
{canDelete && (
|
||||
<IconButton size="small" onClick={onDelete} disabled={busy} sx={{ color: 'inherit', p: 0.25 }}>
|
||||
<DeleteOutlineRoundedIcon sx={{ fontSize: 14 }} />
|
||||
</IconButton>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{msg.editedAt && !deleted && (
|
||||
<Typography variant="caption" sx={{ opacity: 0.65, fontSize: '0.6rem' }}>
|
||||
{t('support.chat.edited')}
|
||||
</Typography>
|
||||
)}
|
||||
<Typography variant="caption" sx={{ opacity: 0.75, fontSize: '0.65rem' }}>
|
||||
{formatMessageTime(msg.createdAt)}
|
||||
</Typography>
|
||||
@ -138,6 +217,9 @@ export function SupportChatPanel({ widgetOpen = true, onOpenWidget }: Props) {
|
||||
const qc = useQueryClient();
|
||||
const [draft, setDraft] = useState('');
|
||||
const [messages, setMessages] = useState<SupportMessage[]>([]);
|
||||
const [nowMs, setNowMs] = useState(() => Date.now());
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [editDraft, setEditDraft] = useState('');
|
||||
const [staffTyping, setStaffTyping] = useState(false);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const typingTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
@ -174,6 +256,14 @@ export function SupportChatPanel({ widgetOpen = true, onOpenWidget }: Props) {
|
||||
void qc.invalidateQueries({ queryKey: ['support-messages', conversationId] });
|
||||
}
|
||||
}
|
||||
if (
|
||||
(msg.type === 'message.updated' || msg.type === 'message.deleted') &&
|
||||
msg.conversationId === conversationId &&
|
||||
msg.message
|
||||
) {
|
||||
setMessages((prev) => upsertMessage(prev, msg.message!));
|
||||
return;
|
||||
}
|
||||
if (msg.type === 'message.read' && msg.conversationId === conversationId) {
|
||||
setMessages((prev) =>
|
||||
prev.map((m) =>
|
||||
@ -216,6 +306,11 @@ export function SupportChatPanel({ widgetOpen = true, onOpenWidget }: Props) {
|
||||
scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' });
|
||||
}, [messages, staffTyping]);
|
||||
|
||||
useEffect(() => {
|
||||
const id = window.setInterval(() => setNowMs(Date.now()), 5000);
|
||||
return () => window.clearInterval(id);
|
||||
}, []);
|
||||
|
||||
const sendMut = useMutation({
|
||||
mutationFn: (body: string) => sendSupportMessage(conversationId, body),
|
||||
onSuccess: (msg) => {
|
||||
@ -226,6 +321,22 @@ export function SupportChatPanel({ widgetOpen = true, onOpenWidget }: Props) {
|
||||
},
|
||||
});
|
||||
|
||||
const editMut = useMutation({
|
||||
mutationFn: (input: { messageId: string; body: string }) =>
|
||||
editSupportMessage(conversationId!, input.messageId, input.body),
|
||||
onSuccess: (msg) => {
|
||||
setEditingId(null);
|
||||
setMessages((prev) => upsertMessage(prev, msg));
|
||||
},
|
||||
});
|
||||
|
||||
const deleteMut = useMutation({
|
||||
mutationFn: (messageId: string) => deleteSupportMessage(conversationId!, messageId),
|
||||
onSuccess: (msg) => {
|
||||
setMessages((prev) => upsertMessage(prev, msg));
|
||||
},
|
||||
});
|
||||
|
||||
const attachMut = useMutation({
|
||||
mutationFn: async (file: File) => {
|
||||
const uploaded = await uploadSupportFile(conversationId, file);
|
||||
@ -305,7 +416,31 @@ export function SupportChatPanel({ widgetOpen = true, onOpenWidget }: Props) {
|
||||
{day}
|
||||
</Typography>
|
||||
)}
|
||||
<MessageBubble msg={msg} isMine={isMine} t={t} />
|
||||
<MessageBubble
|
||||
msg={msg}
|
||||
isMine={isMine}
|
||||
t={t}
|
||||
nowMs={nowMs}
|
||||
editing={editingId === msg.id}
|
||||
editDraft={editingId === msg.id ? editDraft : ''}
|
||||
onEditDraft={setEditDraft}
|
||||
onStartEdit={() => {
|
||||
setEditingId(msg.id);
|
||||
setEditDraft(msg.body ?? '');
|
||||
}}
|
||||
onCancelEdit={() => setEditingId(null)}
|
||||
onSaveEdit={() => {
|
||||
if (!conversationId || !editDraft.trim()) return;
|
||||
editMut.mutate({ messageId: msg.id, body: editDraft.trim() });
|
||||
}}
|
||||
onDelete={() => {
|
||||
if (!conversationId) return;
|
||||
if (window.confirm(t('support.chat.confirmDelete'))) {
|
||||
deleteMut.mutate(msg.id);
|
||||
}
|
||||
}}
|
||||
busy={editMut.isPending || deleteMut.isPending}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
|
||||
@ -27,7 +27,13 @@ export type SupportMessage = {
|
||||
attachmentName: string | null;
|
||||
attachmentMime: string | null;
|
||||
readAt: string | null;
|
||||
editedAt?: string | null;
|
||||
deletedAt?: string | null;
|
||||
createdAt: string;
|
||||
canEdit?: boolean;
|
||||
canDelete?: boolean;
|
||||
editAvailableUntil?: string | null;
|
||||
deleteAvailableUntil?: string | null;
|
||||
};
|
||||
|
||||
export type SupportUserContext = {
|
||||
|
||||
@ -19,6 +19,13 @@ export type SupportWsServerMessage =
|
||||
ts?: number;
|
||||
}
|
||||
| { type: 'message.read'; conversationId: string; ts?: number }
|
||||
| {
|
||||
type: 'message.updated' | 'message.deleted';
|
||||
conversationId: string;
|
||||
messageId: string;
|
||||
message?: SupportMessage;
|
||||
ts?: number;
|
||||
}
|
||||
| { type: 'conversation.updated'; conversationId: string; ts?: number }
|
||||
| { type: 'typing'; conversationId: string; party: 'user' | 'staff'; active: boolean; ts?: number }
|
||||
| { type: 'error'; code: string; message: string };
|
||||
|
||||
@ -947,6 +947,15 @@ export const en = {
|
||||
newMessage: 'New message',
|
||||
file: 'File',
|
||||
attachment: 'attachment',
|
||||
edit: 'Edit',
|
||||
delete: 'Delete',
|
||||
saveEdit: 'Save',
|
||||
cancelEdit: 'Cancel',
|
||||
edited: 'edited',
|
||||
deleted: 'This message was deleted',
|
||||
confirmDelete: 'Delete this message?',
|
||||
editExpired: 'The edit window has expired.',
|
||||
deleteExpired: 'The delete window has expired.',
|
||||
},
|
||||
},
|
||||
admin: {
|
||||
@ -1961,6 +1970,18 @@ export const en = {
|
||||
captchaAfterHint:
|
||||
'0 = disable. Built-in math captcha is used by default; set TURNSTILE_SITE_KEY / TURNSTILE_SECRET_KEY for Cloudflare Turnstile.',
|
||||
},
|
||||
supportMessages: {
|
||||
title: 'Support messages',
|
||||
subtitle: 'How long users may edit or delete their own support messages after sending.',
|
||||
hint: '0 disables the action. Changes apply immediately, without redeploying.',
|
||||
editWindow: 'Edit window (minutes)',
|
||||
editWindowHelper: 'Author can edit their message during this time after send (0–10080).',
|
||||
deleteWindow: 'Delete window (minutes)',
|
||||
deleteWindowHelper: 'Author can delete their message during this time after send (0–10080).',
|
||||
minutes: '{{count}} min',
|
||||
oneHour: '1 hour',
|
||||
disabled: 'Disabled',
|
||||
},
|
||||
candlePredict: {
|
||||
title: 'Candle Predict engine',
|
||||
subtitle: 'Tick interval and backfill pacing (lower backfill = less DB load at scale).',
|
||||
@ -2434,6 +2455,11 @@ export const en = {
|
||||
},
|
||||
visitor: 'Visitor',
|
||||
user: 'User',
|
||||
edit: 'Edit',
|
||||
delete: 'Delete',
|
||||
edited: 'edited',
|
||||
deleted: 'This message was deleted',
|
||||
confirmDelete: 'Delete this message?',
|
||||
},
|
||||
dashboard: {
|
||||
title: 'Admin Dashboard',
|
||||
|
||||
@ -961,6 +961,15 @@ export const fr = {
|
||||
newMessage: 'Nouveau message',
|
||||
file: 'Fichier',
|
||||
attachment: 'pièce jointe',
|
||||
edit: 'Modifier',
|
||||
delete: 'Supprimer',
|
||||
saveEdit: 'Enregistrer',
|
||||
cancelEdit: 'Annuler',
|
||||
edited: 'modifié',
|
||||
deleted: 'Ce message a été supprimé',
|
||||
confirmDelete: 'Supprimer ce message ?',
|
||||
editExpired: 'Le délai de modification est dépassé.',
|
||||
deleteExpired: 'Le délai de suppression est dépassé.',
|
||||
},
|
||||
},
|
||||
admin: {
|
||||
@ -1978,6 +1987,18 @@ export const fr = {
|
||||
captchaAfterHint:
|
||||
'0 = désactivé. Captcha mathématique intégré par défaut ; définissez TURNSTILE_SITE_KEY / TURNSTILE_SECRET_KEY pour Cloudflare Turnstile.',
|
||||
},
|
||||
supportMessages: {
|
||||
title: 'Messages support',
|
||||
subtitle: 'Durée pendant laquelle un utilisateur peut modifier ou supprimer son message après l’envoi.',
|
||||
hint: '0 désactive l’action. Les changements s’appliquent immédiatement, sans redéploiement.',
|
||||
editWindow: 'Délai de modification (minutes)',
|
||||
editWindowHelper: 'L’auteur peut modifier son message pendant cette durée après l’envoi (0–10080).',
|
||||
deleteWindow: 'Délai de suppression (minutes)',
|
||||
deleteWindowHelper: 'L’auteur peut supprimer son message pendant cette durée après l’envoi (0–10080).',
|
||||
minutes: '{{count}} min',
|
||||
oneHour: '1 heure',
|
||||
disabled: 'Désactivé',
|
||||
},
|
||||
candlePredict: {
|
||||
title: 'Moteur Candle Predict',
|
||||
subtitle: 'Intervalle de tick et rythme de backfill (backfill plus bas = moins de charge DB à l’échelle).',
|
||||
@ -2454,6 +2475,11 @@ export const fr = {
|
||||
},
|
||||
visitor: 'Visiteur',
|
||||
user: 'Utilisateur',
|
||||
edit: 'Modifier',
|
||||
delete: 'Supprimer',
|
||||
edited: 'modifié',
|
||||
deleted: 'Ce message a été supprimé',
|
||||
confirmDelete: 'Supprimer ce message ?',
|
||||
},
|
||||
dashboard: {
|
||||
title: 'Dashboard administrateur',
|
||||
|
||||
Loading…
Reference in New Issue
Block a user