After correcting the chat issue4

This commit is contained in:
Your Name 2026-09-24 15:40:35 +02:00
parent 3e8210c87e
commit 6512d4cf6f
10 changed files with 201 additions and 46 deletions

View File

@ -55,6 +55,7 @@ function mapMessage(
readAt: row.read_at?.toISOString() ?? null,
editedAt: row.edited_at?.toISOString() ?? null,
deletedAt: row.deleted_at?.toISOString() ?? null,
deleted,
createdAt: row.created_at.toISOString(),
canEdit: actions?.canEdit ?? false,
canDelete: actions?.canDelete ?? false,
@ -257,6 +258,7 @@ export async function getConversationMessages(
return {
messages: rows.map((r) => mapMessage(r, staffNames, messageActions(r, conv, ctx, windows))),
typing,
policy: windows,
};
}

View File

@ -18,6 +18,24 @@ class SupportConversationModel {
}
}
class SupportActionPolicy {
const SupportActionPolicy({
this.editWindowMinutes = 15,
this.deleteWindowMinutes = 15,
});
final int editWindowMinutes;
final int deleteWindowMinutes;
factory SupportActionPolicy.fromJson(Map<String, dynamic>? json) {
if (json == null) return const SupportActionPolicy();
return SupportActionPolicy(
editWindowMinutes: (json['editWindowMinutes'] as num?)?.toInt() ?? 15,
deleteWindowMinutes: (json['deleteWindowMinutes'] as num?)?.toInt() ?? 15,
);
}
}
class SupportMessageModel {
const SupportMessageModel({
required this.id,
@ -55,18 +73,12 @@ class SupportMessageModel {
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 isDeleted {
if (deletedAt != null && deletedAt!.isNotEmpty) return true;
final emptyBody = body == null || body!.trim().isEmpty;
return emptyBody && (attachmentUrl == null || attachmentUrl!.isEmpty);
}
bool get editOpen => actionOpen(editAvailableUntil, canEdit);
bool get deleteOpen => actionOpen(deleteAvailableUntil, canDelete);
bool get isMine => senderType == 'user' || senderType == 'visitor';
bool get isImage {
if (attachmentMime?.startsWith('image/') == true) return true;
@ -80,6 +92,41 @@ class SupportMessageModel {
name.endsWith('.bmp');
}
bool editOpen([SupportActionPolicy? policy]) {
return _actionOpen(
allowed: canEdit,
until: editAvailableUntil,
windowMinutes: policy?.editWindowMinutes,
);
}
bool deleteOpen([SupportActionPolicy? policy]) {
return _actionOpen(
allowed: canDelete,
until: deleteAvailableUntil,
windowMinutes: policy?.deleteWindowMinutes,
);
}
bool _actionOpen({
required bool allowed,
required String? until,
int? windowMinutes,
}) {
if (isDeleted || !isMine) return false;
if (until != null && until.isNotEmpty) {
final dt = DateTime.tryParse(until);
if (dt != null) return dt.toUtc().isAfter(DateTime.now().toUtc());
}
if (allowed) return true;
if (windowMinutes != null && windowMinutes > 0) {
final created = DateTime.tryParse(createdAt);
if (created == null) return false;
return created.toUtc().add(Duration(minutes: windowMinutes)).isAfter(DateTime.now().toUtc());
}
return false;
}
SupportMessageModel copyWith({
String? body,
String? readAt,
@ -114,31 +161,61 @@ class SupportMessageModel {
factory SupportMessageModel.fromJson(Map<String, dynamic> json) {
return SupportMessageModel(
id: json['id'] as String,
conversationId: (json['conversationId'] ?? '').toString(),
senderType: (json['senderType'] ?? 'staff').toString(),
createdAt: (json['createdAt'] ?? '').toString(),
senderDisplayName: json['senderDisplayName'] as String?,
body: json['body'] as String?,
attachmentUrl: json['attachmentUrl'] as String?,
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?,
conversationId: (json['conversationId'] ?? json['conversation_id'] ?? '').toString(),
senderType: (json['senderType'] ?? json['sender_type'] ?? 'staff').toString(),
createdAt: _readDate(json, 'createdAt', 'created_at'),
senderDisplayName: _readString(json, 'senderDisplayName', 'sender_display_name'),
body: _readString(json, 'body'),
attachmentUrl: _readString(json, 'attachmentUrl', 'attachment_url'),
attachmentName: _readString(json, 'attachmentName', 'attachment_name'),
attachmentMime: _readString(json, 'attachmentMime', 'attachment_mime'),
readAt: _readDate(json, 'readAt', 'read_at'),
editedAt: _readDate(json, 'editedAt', 'edited_at'),
deletedAt: _readDeletedAt(json),
canEdit: _readBool(json, 'canEdit'),
canDelete: _readBool(json, 'canDelete'),
editAvailableUntil: _readDate(json, 'editAvailableUntil'),
deleteAvailableUntil: _readDate(json, 'deleteAvailableUntil'),
);
}
static String _readDate(Map<String, dynamic> json, String camel, [String? snake]) {
final value = json[camel] ?? (snake == null ? null : json[snake]);
if (value == null) return '';
return value.toString();
}
static String? _readString(Map<String, dynamic> json, String camel, [String? snake]) {
final value = json[camel] ?? (snake == null ? null : json[snake]);
if (value == null) return null;
final text = value.toString();
return text.isEmpty ? null : text;
}
static String? _readDeletedAt(Map<String, dynamic> json) {
if (json['deleted'] == true || json['deleted'] == 1 || json['deleted'] == 'true') {
return _readDate(json, 'deletedAt', 'deleted_at').isEmpty
? DateTime.now().toUtc().toIso8601String()
: _readDate(json, 'deletedAt', 'deleted_at');
}
final value = _readDate(json, 'deletedAt', 'deleted_at');
return value.isEmpty ? null : value;
}
static bool _readBool(Map<String, dynamic> json, String key) {
final value = json[key];
return value == true || value == 1 || value == 'true';
}
}
class SupportMessagesPage {
const SupportMessagesPage({
required this.messages,
required this.staffTyping,
this.policy = const SupportActionPolicy(),
});
final List<SupportMessageModel> messages;
final bool staffTyping;
final SupportActionPolicy policy;
}

View File

@ -58,9 +58,13 @@ class SupportRepository {
.map((e) => SupportMessageModel.fromJson(e as Map<String, dynamic>))
.toList();
final typing = res.data?['typing'] as Map<String, dynamic>?;
final policy = res.data?['policy'];
return SupportMessagesPage(
messages: items,
staffTyping: typing?['staffTyping'] == true,
policy: SupportActionPolicy.fromJson(
policy is Map<String, dynamic> ? policy : null,
),
);
} on DioException catch (e) {
throw AppException.fromDio(e, fallback: 'Failed to load messages');

View File

@ -74,6 +74,7 @@ class SupportBloc extends Bloc<SupportEvent, SupportState> {
conversation: conv,
messages: page.messages,
staffTyping: page.staffTyping,
policy: page.policy,
wsConnected: _socket.isConnected,
));
_startPoll();
@ -204,6 +205,7 @@ class SupportBloc extends Bloc<SupportEvent, SupportState> {
emit(state.copyWith(
messages: page.messages,
staffTyping: page.staffTyping,
policy: page.policy,
wsConnected: _socket.isConnected,
));
} catch (_) {}

View File

@ -9,6 +9,7 @@ class SupportState extends Equatable {
this.staffTyping = false,
this.conversation,
this.messages = const [],
this.policy = const SupportActionPolicy(),
this.errorMessage,
});
@ -19,6 +20,7 @@ class SupportState extends Equatable {
final bool staffTyping;
final SupportConversationModel? conversation;
final List<SupportMessageModel> messages;
final SupportActionPolicy policy;
final String? errorMessage;
SupportState copyWith({
@ -29,6 +31,7 @@ class SupportState extends Equatable {
bool? staffTyping,
SupportConversationModel? conversation,
List<SupportMessageModel>? messages,
SupportActionPolicy? policy,
String? errorMessage,
bool clearError = false,
}) {
@ -40,6 +43,7 @@ class SupportState extends Equatable {
staffTyping: staffTyping ?? this.staffTyping,
conversation: conversation ?? this.conversation,
messages: messages ?? this.messages,
policy: policy ?? this.policy,
errorMessage: clearError ? null : (errorMessage ?? this.errorMessage),
);
}
@ -53,6 +57,7 @@ class SupportState extends Equatable {
staffTyping,
conversation,
messages,
policy,
errorMessage,
];
}

View File

@ -386,7 +386,7 @@ class _SupportMessagesState extends State<_SupportMessages> {
),
),
),
_MessageBubble(message: msg),
_MessageBubble(message: msg, policy: state.policy),
],
);
},
@ -491,10 +491,43 @@ class _StaffTypingBubbleState extends State<_StaffTypingBubble>
}
}
class _BubbleAction extends StatelessWidget {
const _BubbleAction({
required this.icon,
required this.onTap,
required this.dark,
});
final IconData icon;
final VoidCallback onTap;
final bool dark;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(right: 2),
child: InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.all(2),
child: Icon(
icon,
size: 15,
color: dark
? const Color(0xFF0B0F1A).withValues(alpha: 0.75)
: AppColors.textMuted,
),
),
),
);
}
}
class _MessageBubble extends StatelessWidget {
const _MessageBubble({required this.message});
const _MessageBubble({required this.message, required this.policy});
final SupportMessageModel message;
final SupportActionPolicy policy;
@override
Widget build(BuildContext context) {
@ -502,7 +535,9 @@ 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);
final canEdit = message.editOpen(policy);
final canDelete = message.deleteOpen(policy);
final canAct = canEdit || canDelete;
return Align(
alignment: mine ? Alignment.centerRight : Alignment.centerLeft,
@ -588,6 +623,18 @@ class _MessageBubble extends StatelessWidget {
Row(
mainAxisSize: MainAxisSize.min,
children: [
if (canEdit)
_BubbleAction(
icon: Icons.edit_outlined,
onTap: () => _editMessage(context),
dark: mine,
),
if (canDelete)
_BubbleAction(
icon: Icons.delete_outline,
onTap: () => _confirmDelete(context),
dark: mine,
),
if (message.editedAt != null && !message.isDeleted)
Text(
'${s.supportEdited} · ',
@ -637,13 +684,13 @@ class _MessageBubble extends StatelessWidget {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (message.editOpen)
if (message.editOpen(policy))
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)
if (message.deleteOpen(policy))
ListTile(
leading: const Icon(Icons.delete_outline, color: Colors.white),
title: Text(s.supportDelete, style: const TextStyle(color: Colors.white)),
@ -660,20 +707,7 @@ class _MessageBubble extends StatelessWidget {
);
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));
}
await _confirmDelete(context);
return;
}
if (action == 'edit') {
@ -681,6 +715,24 @@ class _MessageBubble extends StatelessWidget {
}
}
Future<void> _confirmDelete(BuildContext context) async {
final s = context.strings;
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));
}
}
Future<void> _editMessage(BuildContext context) async {
final s = context.strings;
final controller = TextEditingController(text: message.body ?? '');

View File

@ -37,6 +37,7 @@ import {
adminDeleteMessage,
adminEditMessage,
attachmentFullUrl,
isSupportDeleted,
isSupportImage,
supportActionOpen,
} from './api/supportApi';
@ -85,7 +86,7 @@ function AdminMessageList({
<Box sx={{ flex: 1, minHeight: 0, overflowY: 'auto', p: 2 }}>
{messages.map((msg) => {
const isStaff = msg.senderType === 'staff';
const deleted = !!msg.deletedAt;
const deleted = isSupportDeleted(msg);
const editing = editingId === msg.id;
const canEdit = supportActionOpen(msg.canEdit, msg.editAvailableUntil, nowMs);
const canDelete = supportActionOpen(msg.canDelete, msg.deleteAvailableUntil, nowMs);

View File

@ -233,6 +233,16 @@ export async function adminDeleteMessage(
return res.data;
}
export function isSupportDeleted(msg: {
deleted?: boolean | null;
deletedAt?: string | null;
body?: string | null;
attachmentUrl?: string | null;
}): boolean {
if (msg.deleted || msg.deletedAt) return true;
return !msg.body?.trim() && !msg.attachmentUrl;
}
export function supportActionOpen(
allowed: boolean | undefined,
until: string | null | undefined,

View File

@ -28,6 +28,7 @@ import {
sendSupportAttachmentMessage,
sendSupportMessage,
setSupportTyping,
isSupportDeleted,
supportActionOpen,
uploadSupportFile,
} from '../api/supportApi';
@ -96,7 +97,7 @@ function MessageBubble({
const isImage = isSupportImage(msg);
const canEdit = supportActionOpen(msg.canEdit, msg.editAvailableUntil, nowMs);
const canDelete = supportActionOpen(msg.canDelete, msg.deleteAvailableUntil, nowMs);
const deleted = !!msg.deletedAt;
const deleted = isSupportDeleted(msg);
return (
<Box
sx={{

View File

@ -29,6 +29,7 @@ export type SupportMessage = {
readAt: string | null;
editedAt?: string | null;
deletedAt?: string | null;
deleted?: boolean;
createdAt: string;
canEdit?: boolean;
canDelete?: boolean;