diff --git a/Client/origin-client/scenes/account/account_screen.gd b/Client/origin-client/scenes/account/account_screen.gd index 0683fe8..316f199 100644 --- a/Client/origin-client/scenes/account/account_screen.gd +++ b/Client/origin-client/scenes/account/account_screen.gd @@ -2,16 +2,14 @@ extends Control ## Account Management screen. const NOTIF_ROW = preload("res://scenes/account/components/NotificationRow.tscn") -## Shows the player's own profile (display name, OP, rank score) -## and a mailbox tab with admin responses to bug reports. -@onready var back_btn : Button = %BackBtn -@onready var display_label : Label = %DisplayLabel -@onready var op_label : Label = %OpLabel -@onready var rank_label : Label = %RankLabel +@onready var back_btn : Button = %BackBtn +@onready var display_label : Label = %DisplayLabel +@onready var op_label : Label = %OpLabel +@onready var rank_label : Label = %RankLabel @onready var mailbox_list : VBoxContainer = %MailboxList -@onready var loading_label : Label = %LoadingLabel -@onready var empty_label : Label = %EmptyLabel +@onready var loading_label : Label = %LoadingLabel +@onready var empty_label : Label = %EmptyLabel # ── Lifecycle ───────────────────────────────────────────────────────────────── @@ -42,19 +40,21 @@ func _on_profile_ok(p: Variant) -> void: rank_label.text = "Rank Score: %d" % int(d.get("rankScore", 1000)) -# ── Notifications (mailbox) ──────────────────────────────────────────────────── +# ── Notifications (mailbox) ────────────────────────────────────────────────── func _load_notifications() -> void: loading_label.visible = true empty_label.visible = false + loading_label.text = "Loading…" for c in mailbox_list.get_children(): c.queue_free() Network.request( - "chat.get_notifications", + "chat.notifications.get", { "unreadOnly": false }, func(_type: String, p: Variant): _on_notifications_ok(p), func(_c: String, _m: String): + loading_label.visible = true loading_label.text = "Failed to load mailbox." ) @@ -71,11 +71,224 @@ func _on_notifications_ok(p: Variant) -> void: var nd := n as Dictionary var row := NOTIF_ROW.instantiate() mailbox_list.add_child(row) - row.setup( - nd.get("title", "Notification"), - nd.get("body", ""), - nd.get("readAt", null) == null + row.setup(nd) + row.open_requested.connect(_open_notification) + row.reply_requested.connect(_reply_to_notification) + row.delete_requested.connect(_delete_notification) + row.mark_read_requested.connect(_mark_notification_read) + + +func _mark_notification_read(notification_id: String) -> void: + if notification_id.is_empty(): + return + + Network.request( + "chat.notifications.read", + { "notificationIds": [notification_id] }, + func(_t: String, _p: Variant): _load_notifications(), + func(_c: String, _m: String): _load_notifications() + ) + + +func _delete_notification(notification_id: String) -> void: + if notification_id.is_empty(): + return + + Network.request( + "chat.notifications.delete", + { "notificationIds": [notification_id] }, + func(_t: String, _p: Variant): _load_notifications(), + func(_c: String, _m: String): _load_notifications() + ) + + +func _open_notification(notification: Dictionary) -> void: + var id := str(notification.get("id", "")) + if not id.is_empty() and notification.get("readAt", null) == null: + _mark_notification_read(id) + + _show_notification_dialog(notification, false) + + +func _reply_to_notification(notification: Dictionary) -> void: + _show_notification_dialog(notification, true) + + +func _show_notification_dialog(notification: Dictionary, focus_reply: bool) -> void: + var dialog := AcceptDialog.new() + dialog.title = str(notification.get("title", "Mailbox Message")) + dialog.ok_button_text = "Close" + dialog.min_size = Vector2(700, 500) + + var root := VBoxContainer.new() + root.custom_minimum_size = Vector2(660, 440) + root.add_theme_constant_override("separation", 8) + dialog.add_child(root) + + var body := RichTextLabel.new() + body.fit_content = false + body.scroll_active = true + body.custom_minimum_size = Vector2(0, 220) + body.size_flags_vertical = Control.SIZE_EXPAND_FILL + body.bbcode_enabled = true + body.text = _build_notification_text(notification) + root.add_child(body) + + var thread_status := Label.new() + thread_status.modulate = Color(0.7, 0.7, 0.75) + thread_status.text = "" + root.add_child(thread_status) + + var reply_box := TextEdit.new() + reply_box.custom_minimum_size = Vector2(0, 100) + reply_box.placeholder_text = "Write a reply to support..." + reply_box.visible = false + root.add_child(reply_box) + + var actions := HBoxContainer.new() + actions.add_theme_constant_override("separation", 8) + root.add_child(actions) + + var send_btn := Button.new() + send_btn.text = "Send Reply" + send_btn.visible = false + actions.add_child(send_btn) + + var delete_btn := Button.new() + delete_btn.text = "Delete" + delete_btn.modulate = Color(1.0, 0.5, 0.5) + delete_btn.pressed.connect(func() -> void: + var nid := str(notification.get("id", "")) + if not nid.is_empty(): + _delete_notification(nid) + dialog.queue_free()) + actions.add_child(delete_btn) + + add_child(dialog) + dialog.popup_centered() + + var parsed := _parse_payload(notification) + var bug_report_id := str(parsed.get("bugReportId", "")) + var can_reply := str(notification.get("notificationType", "")) == "admin_response" and not bug_report_id.is_empty() + + if can_reply: + reply_box.visible = true + send_btn.visible = true + thread_status.text = "Loading conversation…" + _load_bug_report_thread_into(body, thread_status, bug_report_id) + + send_btn.pressed.connect(func() -> void: + var content := reply_box.text.strip_edges() + if content.is_empty(): + thread_status.text = "Reply cannot be empty." + thread_status.modulate = Color(1.0, 0.5, 0.5) + return + send_btn.disabled = true + thread_status.text = "Sending reply…" + thread_status.modulate = Color(0.7, 0.7, 0.75) + Network.request( + "support.reply_bug_report", + { "bugReportId": bug_report_id, "content": content }, + func(_t: String, _p: Variant): + reply_box.text = "" + send_btn.disabled = false + thread_status.text = "Reply sent." + thread_status.modulate = Color(0.5, 0.9, 0.5) + _load_bug_report_thread_into(body, thread_status, bug_report_id), + func(code: String, msg: String): + send_btn.disabled = false + thread_status.text = "Reply failed (%s): %s" % [code, msg] + thread_status.modulate = Color(1.0, 0.5, 0.5) + ) ) + if focus_reply: + reply_box.grab_focus() + + +func _load_bug_report_thread_into(body: RichTextLabel, status_label: Label, bug_report_id: String) -> void: + Network.request( + "support.get_bug_report_thread", + { "bugReportId": bug_report_id }, + func(_t: String, p: Variant): + var thread := (p as Dictionary).get("thread", {}) as Dictionary + if thread.is_empty(): + status_label.text = "No conversation details available." + status_label.modulate = Color(1.0, 0.5, 0.5) + return + body.text = _build_thread_text(thread) + status_label.text = "" + , + func(code: String, msg: String): + status_label.text = "Failed to load thread (%s): %s" % [code, msg] + status_label.modulate = Color(1.0, 0.5, 0.5) + ) + + +func _build_notification_text(notification: Dictionary) -> String: + var lines: Array[String] = [] + lines.append("[b]%s[/b]" % str(notification.get("title", "Mailbox Message"))) + lines.append(str(notification.get("body", ""))) + lines.append("") + lines.append("Type: %s" % str(notification.get("notificationType", "unknown"))) + lines.append("Created: %s" % _format_timestamp(str(notification.get("createdAt", "")))) + return "\n".join(lines) + + +func _build_thread_text(thread: Dictionary) -> String: + var lines: Array[String] = [] + lines.append("[b]Support Thread[/b]") + lines.append("Subject: %s" % str(thread.get("title", ""))) + lines.append("Status: %s" % str(thread.get("status", "Open"))) + lines.append("Category: %s" % str(thread.get("category", "other"))) + lines.append("Created: %s" % _format_timestamp(str(thread.get("createdAt", "")))) + lines.append("") + lines.append("[b]Original Report[/b]") + lines.append(str(thread.get("description", ""))) + var steps := str(thread.get("stepsToReproduce", "")) + if not steps.is_empty(): + lines.append("") + lines.append("[b]Steps to Reproduce[/b]") + lines.append(steps) + + var responses : Array = thread.get("responses", []) as Array + if not responses.is_empty(): + lines.append("") + lines.append("[b]Conversation[/b]") + for r in responses: + var rd := r as Dictionary + lines.append("\n• [b]%s[/b] (%s)" % [ + str(rd.get("authorDisplayName", "Support")), + _format_timestamp(str(rd.get("createdAt", ""))) + ]) + lines.append(str(rd.get("content", ""))) + + return "\n".join(lines) + + +func _parse_payload(notification: Dictionary) -> Dictionary: + var payload_json := str(notification.get("payloadJson", "")) + if payload_json.is_empty(): + return {} + var parsed := JSON.parse_string(payload_json) + if typeof(parsed) == TYPE_DICTIONARY: + return parsed as Dictionary + return {} + + +func _format_timestamp(iso: String) -> String: + if iso.is_empty(): + return "—" + var t_idx := iso.find("T") + if t_idx < 0: + return iso + var day := iso.substr(0, t_idx) + var time_part := iso.substr(t_idx + 1) + var z_idx := time_part.find("Z") + if z_idx >= 0: + time_part = time_part.substr(0, z_idx) + if time_part.length() >= 5: + time_part = time_part.substr(0, 5) + return "%s %s" % [day, time_part] # ── Navigation ──────────────────────────────────────────────────────────────── diff --git a/Client/origin-client/scenes/account/components/notification_row.gd b/Client/origin-client/scenes/account/components/notification_row.gd index 370efaf..bc05141 100644 --- a/Client/origin-client/scenes/account/components/notification_row.gd +++ b/Client/origin-client/scenes/account/components/notification_row.gd @@ -1,12 +1,84 @@ extends PanelContainer -## Single mailbox notification row. +## Single mailbox notification row with quick actions. + +signal open_requested(notification: Dictionary) +signal reply_requested(notification: Dictionary) +signal delete_requested(notification_id: String) +signal mark_read_requested(notification_id: String) @onready var title_label : Label = %TitleLabel @onready var body_label : Label = %BodyLabel +@onready var _vbox : VBoxContainer = $Margin/VBox + +var _notification: Dictionary = {} + +func _ready() -> void: + mouse_filter = Control.MOUSE_FILTER_STOP + gui_input.connect(_on_gui_input) -func setup(title: String, body: String, is_unread: bool) -> void: +func setup(notification: Dictionary) -> void: + _notification = notification.duplicate(true) + + var title := str(_notification.get("title", "Notification")) + var body := str(_notification.get("body", "")) + var is_unread := _notification.get("readAt", null) == null + title_label.text = title body_label.text = body if is_unread: title_label.modulate = Color(0.95, 0.85, 0.30) + else: + title_label.modulate = Color(0.82, 0.82, 0.88) + + _build_actions(is_unread) + + +func _build_actions(is_unread: bool) -> void: + for c in _vbox.get_children(): + if c.name == "ActionRow": + c.queue_free() + + var action_row := HBoxContainer.new() + action_row.name = "ActionRow" + action_row.add_theme_constant_override("separation", 6) + _vbox.add_child(action_row) + + var open_btn := Button.new() + open_btn.text = "Open" + open_btn.flat = true + open_btn.pressed.connect(func() -> void: + open_requested.emit(_notification)) + action_row.add_child(open_btn) + + var notif_type := str(_notification.get("notificationType", "")) + if notif_type == "admin_response": + var reply_btn := Button.new() + reply_btn.text = "Reply" + reply_btn.flat = true + reply_btn.pressed.connect(func() -> void: + reply_requested.emit(_notification)) + action_row.add_child(reply_btn) + + if is_unread: + var mark_btn := Button.new() + mark_btn.text = "Mark read" + mark_btn.flat = true + mark_btn.pressed.connect(func() -> void: + mark_read_requested.emit(str(_notification.get("id", "")))) + action_row.add_child(mark_btn) + + var delete_btn := Button.new() + delete_btn.text = "Delete" + delete_btn.flat = true + delete_btn.modulate = Color(1.0, 0.5, 0.5) + delete_btn.pressed.connect(func() -> void: + delete_requested.emit(str(_notification.get("id", "")))) + action_row.add_child(delete_btn) + + +func _on_gui_input(event: InputEvent) -> void: + if event is InputEventMouseButton: + var mb := event as InputEventMouseButton + if mb.button_index == MOUSE_BUTTON_LEFT and mb.pressed and mb.double_click: + open_requested.emit(_notification) diff --git a/Server/src/SOR.Chat/ChatMessages.cs b/Server/src/SOR.Chat/ChatMessages.cs index 6e3fed7..2d6931f 100644 --- a/Server/src/SOR.Chat/ChatMessages.cs +++ b/Server/src/SOR.Chat/ChatMessages.cs @@ -63,6 +63,12 @@ public sealed record GetNotificationsRequest(bool UnreadOnly = false); /// public sealed record MarkNotificationsReadRequest(IEnumerable? NotificationIds = null); +/// +/// Delete notifications from mailbox. +/// Null or empty NotificationIds = delete ALL notifications for the caller. +/// +public sealed record DeleteNotificationsRequest(IEnumerable? NotificationIds = null); + /// /// Invite another player to the caller's party. /// Creates a Party channel for the caller if they don't have one yet. @@ -107,6 +113,8 @@ public sealed record GetNotificationsResponse( public sealed record MarkNotificationsReadResponse; +public sealed record DeleteNotificationsResponse; + /// Returned to the inviter after a successful party invite is dispatched. public sealed record PartyInviteResponse(ChatChannelDto Channel); diff --git a/Server/src/SOR.Chat/Handlers/ChatDeleteNotificationsHandler.cs b/Server/src/SOR.Chat/Handlers/ChatDeleteNotificationsHandler.cs new file mode 100644 index 0000000..1792f2f --- /dev/null +++ b/Server/src/SOR.Chat/Handlers/ChatDeleteNotificationsHandler.cs @@ -0,0 +1,50 @@ +namespace SOR.Chat.Handlers; + +using Microsoft.EntityFrameworkCore; +using SOR.Database.Contexts; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// chat.notifications.delete — deletes one or more notifications for the caller. +/// If NotificationIds is null or empty, deletes ALL notifications for the caller. +/// +internal sealed class ChatDeleteNotificationsHandler : ChatHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly ChatDbContext _chatDb; + + public ChatDeleteNotificationsHandler(IMessageSerializer serializer, ChatDbContext chatDb) + { + _serializer = serializer; + _chatDb = chatDb; + } + + public string MessageType => "chat.notifications.delete"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var req = _serializer.DeserializePayload(message.Payload); + var accountId = Guid.Parse(connection.UserId); + + if (req.NotificationIds is null || !req.NotificationIds.Any()) + { + await _chatDb.Notifications + .Where(n => n.RecipientAccountId == accountId) + .ExecuteDeleteAsync(ct); + } + else + { + var ids = req.NotificationIds.ToList(); + await _chatDb.Notifications + .Where(n => n.RecipientAccountId == accountId && ids.Contains(n.Id)) + .ExecuteDeleteAsync(ct); + } + + return ServerMessage.Reply("chat.notifications.delete.ack", message.Seq, new DeleteNotificationsResponse()); + } +} diff --git a/Server/src/SOR.Chat/ServiceRegistration.cs b/Server/src/SOR.Chat/ServiceRegistration.cs index 7eba2ff..9fe0274 100644 --- a/Server/src/SOR.Chat/ServiceRegistration.cs +++ b/Server/src/SOR.Chat/ServiceRegistration.cs @@ -35,6 +35,7 @@ public static class ServiceRegistration services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); diff --git a/Server/src/SOR.Support/Handlers/GetBugReportThreadHandler.cs b/Server/src/SOR.Support/Handlers/GetBugReportThreadHandler.cs new file mode 100644 index 0000000..02a76a0 --- /dev/null +++ b/Server/src/SOR.Support/Handlers/GetBugReportThreadHandler.cs @@ -0,0 +1,66 @@ +namespace SOR.Support.Handlers; + +using Microsoft.EntityFrameworkCore; +using SOR.Database.Contexts; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// support.get_bug_report_thread — fetches a specific bug report thread for the caller. +/// +internal sealed class GetBugReportThreadHandler : IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly SupportDbContext _supportDb; + + public GetBugReportThreadHandler(IMessageSerializer serializer, SupportDbContext supportDb) + { + _serializer = serializer; + _supportDb = supportDb; + } + + public string MessageType => "support.get_bug_report_thread"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken cancellationToken) + { + var req = _serializer.DeserializePayload(message.Payload); + var accountId = Guid.Parse(connection.UserId); + + var report = await _supportDb.BugReports + .Include(r => r.Responses) + .FirstOrDefaultAsync(r => r.Id == req.BugReportId, cancellationToken); + + if (report is null) + return ServerMessage.Error(message.Seq, "NOT_FOUND", "Bug report not found."); + + if (report.SubmitterAccountId != accountId) + return ServerMessage.Error(message.Seq, "FORBIDDEN", "You do not have access to this bug report."); + + var responseDtos = report.Responses + .OrderBy(r => r.CreatedAt) + .Select(r => new BugReportResponseDto( + r.Id, + r.AdminAccountId, + r.AdminDisplayName, + r.Content, + r.CreatedAt)); + + var dto = new BugReportThreadDto( + report.Id, + report.Category, + report.Title, + report.Description, + report.StepsToReproduce, + report.Status, + report.CreatedAt, + report.UpdatedAt, + responseDtos); + + return ServerMessage.Reply("support.get_bug_report_thread.ack", message.Seq, + new GetBugReportThreadResponse(dto)); + } +} diff --git a/Server/src/SOR.Support/Handlers/ReplyBugReportHandler.cs b/Server/src/SOR.Support/Handlers/ReplyBugReportHandler.cs new file mode 100644 index 0000000..c12b81d --- /dev/null +++ b/Server/src/SOR.Support/Handlers/ReplyBugReportHandler.cs @@ -0,0 +1,71 @@ +namespace SOR.Support.Handlers; + +using Microsoft.EntityFrameworkCore; +using SOR.Database.Contexts; +using SOR.Database.Entities.Support; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// support.reply_bug_report — lets the submitter reply to their own support thread. +/// +internal sealed class ReplyBugReportHandler : IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly SupportDbContext _supportDb; + + public ReplyBugReportHandler(IMessageSerializer serializer, SupportDbContext supportDb) + { + _serializer = serializer; + _supportDb = supportDb; + } + + public string MessageType => "support.reply_bug_report"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken cancellationToken) + { + var req = _serializer.DeserializePayload(message.Payload); + var accountId = Guid.Parse(connection.UserId); + + var content = req.Content?.Trim() ?? string.Empty; + if (string.IsNullOrWhiteSpace(content)) + return ServerMessage.Error(message.Seq, "INVALID_PAYLOAD", "Reply content is required."); + + var report = await _supportDb.BugReports + .FirstOrDefaultAsync(r => r.Id == req.BugReportId, cancellationToken); + + if (report is null) + return ServerMessage.Error(message.Seq, "NOT_FOUND", "Bug report not found."); + + if (report.SubmitterAccountId != accountId) + return ServerMessage.Error(message.Seq, "FORBIDDEN", "You can only reply to your own bug report."); + + var response = new BugReportResponse + { + BugReportId = report.Id, + AdminAccountId = accountId, + AdminDisplayName = connection.DisplayName, + Content = content[..Math.Min(content.Length, 4000)], + CreatedAt = DateTimeOffset.UtcNow, + }; + + report.UpdatedAt = DateTimeOffset.UtcNow; + if (report.Status is "Resolved" or "Closed") + report.Status = "InProgress"; + + _supportDb.BugReportResponses.Add(response); + await _supportDb.SaveChangesAsync(cancellationToken); + + return ServerMessage.Reply("support.reply_bug_report.ack", message.Seq, + new ReplyBugReportResponse(new BugReportResponseDto( + response.Id, + response.AdminAccountId, + response.AdminDisplayName, + response.Content, + response.CreatedAt))); + } +} diff --git a/Server/src/SOR.Support/ServiceRegistration.cs b/Server/src/SOR.Support/ServiceRegistration.cs index fb46047..c361d8b 100644 --- a/Server/src/SOR.Support/ServiceRegistration.cs +++ b/Server/src/SOR.Support/ServiceRegistration.cs @@ -24,6 +24,8 @@ public static class ServiceRegistration services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); return services; } diff --git a/Server/src/SOR.Support/SupportMessages.cs b/Server/src/SOR.Support/SupportMessages.cs index ebf14a0..e38732d 100644 --- a/Server/src/SOR.Support/SupportMessages.cs +++ b/Server/src/SOR.Support/SupportMessages.cs @@ -17,6 +17,12 @@ public sealed record GetLeaderboardRequest( /// Fetch the caller's own account profile. public sealed record GetAccountProfileRequest; // identity from connection +/// Fetch full thread details for one bug report in the caller's mailbox. +public sealed record GetBugReportThreadRequest(Guid BugReportId); + +/// Reply to an existing bug report thread as the submitting player. +public sealed record ReplyBugReportRequest(Guid BugReportId, string Content); + // ── Response types (server → client) ───────────────────────────────────────── public sealed record SubmitBugReportResponse(Guid ReportId); @@ -33,6 +39,10 @@ public sealed record GetAccountProfileResponse( int OriginPoints, int RankScore); +public sealed record GetBugReportThreadResponse(BugReportThreadDto Thread); + +public sealed record ReplyBugReportResponse(BugReportResponseDto Response); + // ── DTOs ───────────────────────────────────────────────────────────────────── public sealed record LeaderboardEntryDto( @@ -40,3 +50,21 @@ public sealed record LeaderboardEntryDto( Guid AccountId, string DisplayName, int RankScore); + +public sealed record BugReportThreadDto( + Guid Id, + string Category, + string Title, + string Description, + string? StepsToReproduce, + string Status, + DateTimeOffset CreatedAt, + DateTimeOffset? UpdatedAt, + IEnumerable Responses); + +public sealed record BugReportResponseDto( + Guid Id, + Guid AuthorAccountId, + string AuthorDisplayName, + string Content, + DateTimeOffset CreatedAt);