feat(guild_chat): deck + replay attachments

Implement all five guild_chat attachment endpoints:
- add_deck: server looks up deck by (viewerId, format, deckNo) and snapshots
  the current state into a DECK-type chat message DeckPayload column.
- delete_deck: author OR leader/sub-leader may clear; returns refreshed
  deck_log. Extended IGuildChatMessageRepository.ClearDeckAsync with
  leaderOverride flag; added GetDeckMessagesAsync + GetByMessageIdAsync.
- add_replay: stores {"battle_id": N} in ReplayPayload; full shape is
  TODO(post-merge) pending replay-subsystem capture.
- replay_detail: returns the stored ReplayPayload as JsonElement passthrough.
- deck_log: returns all active DECK messages grouped by API-side Format string
  key ("1"=Rotation, "2"=Unlimited, "3"=PreRotation always present;
  "4"=Crossover, "5"=MyRotation only when non-empty).

Adds DeckLogDataDto (typed) for deck_log / delete_deck responses.
Replay response uses JsonElement passthrough (TODO(post-merge)).
8 new integration tests — all green. Full suite 1530/1530 pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
gamer147
2026-06-27 15:14:06 -04:00
parent ab1e23b7cb
commit eb65c2081c
11 changed files with 846 additions and 54 deletions

View File

@@ -1,6 +1,9 @@
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using SVSim.Database.Enums;
using SVSim.Database.Repositories.Viewer;
using SVSim.Database.Services.Guild;
using SVSim.EmulatedEntrypoint.Extensions;
using SVSim.EmulatedEntrypoint.Models.Dtos.Common;
using SVSim.EmulatedEntrypoint.Models.Dtos.Common.Guild;
using SVSim.EmulatedEntrypoint.Models.Dtos.GuildChat;
@@ -43,7 +46,9 @@ public sealed class GuildChatController : SVSimController
MessageType = (int)m.MessageType,
CreateTime = new DateTimeOffset(m.CreatedAt, TimeSpan.Zero).ToUnixTimeSeconds(),
Message = m.Body,
// deck / replay / room remain null until Task 17
Deck = m.DeckPayload is not null ? ParseJsonElementOrNull(m.DeckPayload) : null,
Replay = m.ReplayPayload is not null ? ParseJsonElementOrNull(m.ReplayPayload) : null,
Room = m.RoomPayload is not null ? ParseJsonElementOrNull(m.RoomPayload) : null,
}).ToList();
// Build deduplicated users[] catalog from message authors
@@ -87,22 +92,163 @@ public sealed class GuildChatController : SVSimController
}
[HttpPost("add_deck")]
public Task<ActionResult<EmptyResponse>> AddDeck([FromBody] GuildChatAddDeckRequest req, CancellationToken ct)
=> Task.FromResult<ActionResult<EmptyResponse>>(new EmptyResponse());
public async Task<ActionResult<EmptyResponse>> AddDeck([FromBody] GuildChatAddDeckRequest req, CancellationToken ct)
{
if (!TryGetViewerId(out var viewerId)) return Unauthorized();
Format format;
try { format = FormatExtensions.FromApi(req.DeckFormat); }
catch (ArgumentOutOfRangeException) { return Ok(new { result_code = 2 }); }
var result = await _chat.PostDeckAsync(viewerId, format, req.DeckFormat, req.DeckNo, ct);
if (!result.Ok) return Ok(new { result_code = 2 });
return new EmptyResponse();
}
[HttpPost("delete_deck")]
public Task<ActionResult<EmptyResponse>> DeleteDeck([FromBody] GuildChatDeleteDeckRequest req, CancellationToken ct)
=> Task.FromResult<ActionResult<EmptyResponse>>(new EmptyResponse());
public async Task<ActionResult<GuildChatDeleteDeckResponse>> DeleteDeck([FromBody] GuildChatDeleteDeckRequest req, CancellationToken ct)
{
if (!TryGetViewerId(out var viewerId)) return Unauthorized();
var (ok, log) = await _chat.DeleteDeckAsync(viewerId, (int)req.MessageId, ct);
if (!ok || log is null) return Ok(new { result_code = 2 });
return new GuildChatDeleteDeckResponse
{
MaintenanceCardList = new(),
DeckLog = BuildDeckLogDict(log, viewerId),
};
}
[HttpPost("add_replay")]
public Task<ActionResult<EmptyResponse>> AddReplay([FromBody] GuildChatAddReplayRequest req, CancellationToken ct)
=> Task.FromResult<ActionResult<EmptyResponse>>(new EmptyResponse());
public async Task<ActionResult<EmptyResponse>> AddReplay([FromBody] GuildChatAddReplayRequest req, CancellationToken ct)
{
if (!TryGetViewerId(out var viewerId)) return Unauthorized();
var result = await _chat.PostReplayAsync(viewerId, req.BattleId, ct);
if (!result.Ok) return Ok(new { result_code = 2 });
return new EmptyResponse();
}
[HttpPost("replay_detail")]
public Task<ActionResult<GuildChatReplayDetailResponse>> ReplayDetail([FromBody] GuildChatReplayDetailRequest req, CancellationToken ct)
=> Task.FromResult<ActionResult<GuildChatReplayDetailResponse>>(new GuildChatReplayDetailResponse());
public async Task<ActionResult<GuildChatReplayDetailResponse>> ReplayDetail([FromBody] GuildChatReplayDetailRequest req, CancellationToken ct)
{
if (!TryGetViewerId(out var viewerId)) return Unauthorized();
var payloadJson = await _chat.GetReplayDetailAsync(viewerId, (int)req.MessageId, ct);
if (payloadJson is null) return Ok(new { result_code = 2 });
var replayInfo = ParseJsonElementOrNull(payloadJson);
return new GuildChatReplayDetailResponse { ReplayInfo = replayInfo };
}
[HttpPost("deck_log")]
public Task<ActionResult<GuildChatDeckLogResponse>> DeckLog([FromBody] GuildChatDeckLogRequest req, CancellationToken ct)
=> Task.FromResult<ActionResult<GuildChatDeckLogResponse>>(new GuildChatDeckLogResponse());
public async Task<ActionResult<GuildChatDeckLogResponse>> DeckLog([FromBody] GuildChatDeckLogRequest req, CancellationToken ct)
{
if (!TryGetViewerId(out var viewerId)) return Unauthorized();
var log = await _chat.GetDeckLogAsync(viewerId, ct);
if (log is null) return Ok(new { result_code = 2 });
return new GuildChatDeckLogResponse
{
MaintenanceCardList = new(),
DeckLog = BuildDeckLogDict(log, viewerId),
};
}
// ── Private helpers ──────────────────────────────────────────────────────
/// <summary>
/// Converts a DeckLogResult into the wire deck_log dictionary.
/// Keys "1", "2", "3" (Rotation/Unlimited/PreRotation) are always present.
/// Keys "4" (Crossover) and "5" (MyRotation) are only included when non-empty.
/// delete_permission_exists is true when the calling viewer is the author (leader override
/// is handled at the delete endpoint — here it's purely author-based for the display flag).
/// </summary>
private static Dictionary<string, List<DeckLogDataDto>> BuildDeckLogDict(DeckLogResult log, long callerViewerId)
{
// Always-present buckets.
var dict = new Dictionary<string, List<DeckLogDataDto>>
{
["1"] = new(), // Rotation
["2"] = new(), // Unlimited
["3"] = new(), // PreRotation
};
foreach (var entry in log.Entries)
{
DeckLogDataDto? dto = BuildDeckLogDataDto(entry, callerViewerId);
if (dto is null) continue;
string key = dto.DeckFormat.ToApi().ToString();
if (!dict.TryGetValue(key, out var bucket))
{
// Optional bucket (Crossover=4, MyRotation=5) — create on first use.
bucket = new List<DeckLogDataDto>();
dict[key] = bucket;
}
bucket.Add(dto);
}
return dict;
}
/// <summary>
/// Deserializes a stored DeckPayload JSON into a DeckLogDataDto.
/// Returns null if the JSON is malformed or missing required fields.
/// </summary>
private static DeckLogDataDto? BuildDeckLogDataDto(DeckLogEntry entry, long callerViewerId)
{
try
{
using var doc = JsonDocument.Parse(entry.PayloadJson);
var root = doc.RootElement;
if (!root.TryGetProperty("deck_format", out var fmtEl)) return null;
int deckFormatApi = fmtEl.GetInt32();
Format format;
try { format = FormatExtensions.FromApi(deckFormatApi); }
catch (ArgumentOutOfRangeException) { return null; }
var cardIdArray = new List<long>();
if (root.TryGetProperty("card_id_array", out var arrEl))
{
foreach (var el in arrEl.EnumerateArray())
cardIdArray.Add(el.GetInt64());
}
return new DeckLogDataDto
{
DeckFormat = format,
MessageId = entry.MessageId,
DeletePermissionExists = entry.AuthorViewerId == callerViewerId,
DeckNo = root.TryGetProperty("deck_no", out var dno) ? dno.GetInt32() : 0,
DeckName = root.TryGetProperty("deck_name", out var dn) ? dn.GetString() ?? "" : "",
ClassId = root.TryGetProperty("class_id", out var ci) ? ci.GetInt32() : 0,
SleeveId = root.TryGetProperty("sleeve_id", out var si) ? si.GetInt64() : 3_000_011L,
LeaderSkinId = root.TryGetProperty("leader_skin_id", out var ls) ? ls.GetInt32() : 0,
CardIdArray = cardIdArray,
};
}
catch
{
return null;
}
}
private static JsonElement? ParseJsonElementOrNull(string json)
{
try
{
using var doc = JsonDocument.Parse(json);
return doc.RootElement.Clone();
}
catch
{
return null;
}
}
}

View File

@@ -0,0 +1,65 @@
using MessagePack;
using SVSim.Database.Enums;
using SVSim.EmulatedEntrypoint.Extensions;
using System.Text.Json.Serialization;
using SVSim.EmulatedEntrypoint.Models.Dtos.Common;
namespace SVSim.EmulatedEntrypoint.Models.Dtos.Common.Guild;
/// <summary>
/// Wire shape for a single entry in the deck_log bucket array, and for the inline
/// `deck` object on a DECK-type chat message. Matches ChatMessageInfo.DeckLogData
/// shape (Wizard/ChatMessageInfo.cs:DeckLogData).
///
/// Keys are a strict subset of what DeckData.Initialize() consumes:
/// deck_format, message_id, delete_permission_exists, deck_no, deck_name,
/// class_id, card_id_array, sleeve_id, leader_skin_id.
/// </summary>
[MessagePackObject]
public class DeckLogDataDto
{
/// <summary>API-side Format integer (via FormatJsonConverter).</summary>
[JsonPropertyName("deck_format"), Key("deck_format")]
[JsonConverter(typeof(FormatJsonConverter))]
public Format DeckFormat { get; set; }
/// <summary>Per-guild monotonic message_id of the DECK chat message that shared this deck.</summary>
[JsonPropertyName("message_id"), Key("message_id")]
[JsonConverter(typeof(StringifiedIntConverter))]
public int MessageId { get; set; }
/// <summary>Whether the viewing user may call /guild_chat/delete_deck for this entry.</summary>
[JsonPropertyName("delete_permission_exists"), Key("delete_permission_exists")]
public bool DeletePermissionExists { get; set; }
/// <summary>Deck slot number (within the format's personal deck list).</summary>
[JsonPropertyName("deck_no"), Key("deck_no")]
[JsonConverter(typeof(StringifiedIntConverter))]
public int DeckNo { get; set; }
/// <summary>Deck name as it was at share-time.</summary>
[JsonPropertyName("deck_name"), Key("deck_name")]
public string DeckName { get; set; } = string.Empty;
/// <summary>Class/craft id.</summary>
[JsonPropertyName("class_id"), Key("class_id")]
[JsonConverter(typeof(StringifiedIntConverter))]
public int ClassId { get; set; }
/// <summary>
/// Flat card list — card ids repeated by count, as DeckData.ParseCardIdList expects.
/// </summary>
[JsonPropertyName("card_id_array"), Key("card_id_array"),
JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public List<long> CardIdArray { get; set; } = new();
/// <summary>Sleeve id at share-time.</summary>
[JsonPropertyName("sleeve_id"), Key("sleeve_id")]
[JsonConverter(typeof(StringifiedLongConverter))]
public long SleeveId { get; set; }
/// <summary>Leader skin id at share-time.</summary>
[JsonPropertyName("leader_skin_id"), Key("leader_skin_id")]
[JsonConverter(typeof(StringifiedIntConverter))]
public int LeaderSkinId { get; set; }
}

View File

@@ -1,14 +1,15 @@
using MessagePack;
using System.Text.Json;
using System.Text.Json.Serialization;
using SVSim.EmulatedEntrypoint.Models.Dtos.Common;
using SVSim.EmulatedEntrypoint.Models.Dtos.Common.Guild;
namespace SVSim.EmulatedEntrypoint.Models.Dtos.GuildChat;
/// <summary>
/// Response for POST /guild_chat/deck_log.
/// deck_log keys are stringified API-side Format ints (e.g. "1", "2").
/// TODO(task-17): replace deck_log with typed DTOs when DeckLogData shape is fully specified.
/// Crossover/MyRotation keys must be OMITTED (not empty arrays) when those formats are disabled.
/// deck_log keys are stringified API-side Format ints (e.g. "1", "2", "3").
/// Rotation / Unlimited / PreRotation buckets are always present.
/// Crossover / MyRotation keys are included only when non-empty (client uses TryGetValue).
/// </summary>
[MessagePackObject]
public class GuildChatDeckLogResponse
@@ -19,8 +20,9 @@ public class GuildChatDeckLogResponse
/// <summary>
/// Decks shared in chat, bucketed by API-side Format value (stringified int keys).
/// JsonElement pass-through for now — Task 17 will type the inner DeckLogEntry shape.
/// Keys present: "1" (Rotation), "2" (Unlimited), "3" (PreRotation); optionally "4" (Crossover), "5" (MyRotation).
/// </summary>
[JsonPropertyName("deck_log"), Key("deck_log")]
public JsonElement? DeckLog { get; set; }
[JsonPropertyName("deck_log"), Key("deck_log"),
JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public Dictionary<string, List<DeckLogDataDto>> DeckLog { get; set; } = new();
}

View File

@@ -1,13 +1,13 @@
using MessagePack;
using System.Text.Json;
using System.Text.Json.Serialization;
using SVSim.EmulatedEntrypoint.Models.Dtos.Common;
using SVSim.EmulatedEntrypoint.Models.Dtos.Common.Guild;
namespace SVSim.EmulatedEntrypoint.Models.Dtos.GuildChat;
/// <summary>
/// Response for POST /guild_chat/delete_deck.
/// Returns refreshed deck_log after deletion.
/// TODO(task-17): replace deck_log with typed DeckLogData DTOs when deck-log shape is fully documented.
/// Returns the refreshed deck_log after deletion — same shape as /guild_chat/deck_log.
/// </summary>
[MessagePackObject]
public class GuildChatDeleteDeckResponse
@@ -17,9 +17,10 @@ public class GuildChatDeleteDeckResponse
public List<int> MaintenanceCardList { get; set; } = new();
/// <summary>
/// Refreshed deck log keyed by API-side Format int (stringified, e.g. "1", "2").
/// Using JsonElement for now; Task 17 will type this properly.
/// Refreshed deck log keyed by API-side Format int (stringified, e.g. "1", "2", "3").
/// Crossover ("4") / MyRotation ("5") included only when non-empty.
/// </summary>
[JsonPropertyName("deck_log"), Key("deck_log")]
public JsonElement? DeckLog { get; set; }
[JsonPropertyName("deck_log"), Key("deck_log"),
JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public Dictionary<string, List<DeckLogDataDto>> DeckLog { get; set; } = new();
}

View File

@@ -7,13 +7,16 @@ namespace SVSim.EmulatedEntrypoint.Models.Dtos.GuildChat;
/// <summary>
/// Response for POST /guild_chat/replay_detail.
/// Shape is opaque pending replay-subsystem documentation.
/// TODO(task-17): enumerate fields from Wizard/ReplayDetailInfo.cs when replay subsystem is documented.
/// TODO(post-merge): enumerate fields from Wizard/ReplayDetailInfo.cs when replay subsystem is documented.
/// Using JsonElement pass-through so the stored ReplayPayload JSON is forwarded verbatim.
/// </summary>
[MessagePackObject]
public class GuildChatReplayDetailResponse
{
// Placeholder — replay detail shape is undocumented until we capture a live trace.
// Using JsonElement pass-through for now.
[JsonPropertyName("_todo"), Key("_todo")]
public JsonElement? Placeholder { get; set; }
/// <summary>
/// Opaque replay payload forwarded verbatim from the stored ReplayPayload JSON.
/// TODO(post-merge): type this properly once replay subsystem shape is captured.
/// </summary>
[JsonPropertyName("replay_info"), Key("replay_info")]
public JsonElement? ReplayInfo { get; set; }
}