Add collection service — deck management + card inventory

SOR.Collection project (new):
- 8 message handlers over WebSocket: get_cards, get_decks, get_deck,
  create_deck, rename_deck, delete_deck, add_card, remove_card
- Deck construction rules (DeckRules.cs): min 20 / max 40 cards,
  max 4 copies per definition, max 20 decks per player
- add_card validates ownership (player must own enough physical copies),
  copy limit, deck size limit, and rejects ArchSpirits from the card list
- RefreshValidityAsync recalculates Deck.IsValid after every mutation
- Cross-context lookups (CollectionDbContext + CatalogDbContext) with
  batch queries — never N+1

Admin portal pages (new):
- /collection — overview stats (total cards, total decks, valid decks,
  unique players) + account ID lookup
- /collection/player/{accountId} — full player collection viewer:
  paginated card grid with name/type/affinity/rarity/foil/serial filters,
  deck list with expanded card tables, Grant Card modal (search + foil
  toggle, grants 1–100 copies), revoke individual card instances

Wiring:
- SOR.slnx + SOR.Host.csproj: added SOR.Collection project reference
- Program.cs: uncommented collection service registration
- NavMenu: added Collection item

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
dingo
2026-02-25 12:28:17 -05:00
co-authored by Claude Happy
parent 925b2b1b3b
commit 0198aec9e5
19 changed files with 1594 additions and 3 deletions
+1
View File
@@ -3,6 +3,7 @@
<Project Path="src/SOR.Admin/SOR.Admin.csproj" />
<Project Path="src/SOR.Auth/SOR.Auth.csproj" />
<Project Path="src/SOR.Cdn/SOR.Cdn.csproj" />
<Project Path="src/SOR.Collection/SOR.Collection.csproj" />
<Project Path="src/SOR.Database/SOR.Database.csproj" />
<Project Path="src/SOR.Gateway/SOR.Gateway.csproj" />
<Project Path="src/SOR.Host/SOR.Host.csproj" />
@@ -19,6 +19,11 @@
<i class="bi bi-people me-2"></i>Accounts
</NavLink>
</li>
<li class="nav-item">
<NavLink class="nav-link text-white" href="/collection" Match="NavLinkMatch.All">
<i class="bi bi-bag me-2"></i>Collection
</NavLink>
</li>
<li class="nav-item">
<NavLink class="nav-link text-white" href="/bazaar" Match="NavLinkMatch.All">
<i class="bi bi-shop me-2"></i>Bazaar
@@ -0,0 +1,95 @@
@page "/collection"
@attribute [Authorize(Roles = "Admin,SuperAdmin")]
@inject CollectionDbContext CollectionDb
@inject NavigationManager Nav
<PageTitle>Collection – SOR Admin</PageTitle>
<h1 class="mb-4">Collection</h1>
<div class="row g-4 mb-4">
<div class="col-sm-6 col-lg-3">
<div class="card shadow-sm">
<div class="card-body">
<div class="text-muted small mb-1">Total Player Cards</div>
<div class="fs-3 fw-bold text-primary">@(_totalCards?.ToString("N0") ?? "…")</div>
</div>
</div>
</div>
<div class="col-sm-6 col-lg-3">
<div class="card shadow-sm">
<div class="card-body">
<div class="text-muted small mb-1">Total Decks</div>
<div class="fs-3 fw-bold">@(_totalDecks?.ToString("N0") ?? "…")</div>
</div>
</div>
</div>
<div class="col-sm-6 col-lg-3">
<div class="card shadow-sm">
<div class="card-body">
<div class="text-muted small mb-1">Valid Decks</div>
<div class="fs-3 fw-bold text-success">@(_validDecks?.ToString("N0") ?? "…")</div>
</div>
</div>
</div>
<div class="col-sm-6 col-lg-3">
<div class="card shadow-sm">
<div class="card-body">
<div class="text-muted small mb-1">Unique Players w/ Cards</div>
<div class="fs-3 fw-bold text-info">@(_uniquePlayers?.ToString("N0") ?? "…")</div>
</div>
</div>
</div>
</div>
<div class="card shadow-sm">
<div class="card-header fw-medium">Look Up Player Collection</div>
<div class="card-body">
<div class="row g-2 align-items-end">
<div class="col-md-8">
<label class="form-label">Account ID (GUID)</label>
<input @bind="_accountIdInput" class="form-control" placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" />
</div>
<div class="col-md-4">
<button class="btn btn-primary w-100" @onclick="GoToPlayer">
<i class="bi bi-search me-1"></i>View Collection
</button>
</div>
</div>
@if (_lookupError != null)
{
<div class="alert alert-danger mt-2 mb-0">@_lookupError</div>
}
</div>
</div>
@code {
private int? _totalCards;
private int? _totalDecks;
private int? _validDecks;
private int? _uniquePlayers;
private string _accountIdInput = string.Empty;
private string? _lookupError;
protected override async Task OnInitializedAsync()
{
_totalCards = await CollectionDb.PlayerCards.CountAsync();
_totalDecks = await CollectionDb.Decks.CountAsync();
_validDecks = await CollectionDb.Decks.CountAsync(d => d.IsValid);
_uniquePlayers = await CollectionDb.PlayerCards
.Select(pc => pc.AccountId)
.Distinct()
.CountAsync();
}
private void GoToPlayer()
{
_lookupError = null;
if (!Guid.TryParse(_accountIdInput?.Trim(), out var id))
{
_lookupError = "Please enter a valid GUID.";
return;
}
Nav.NavigateTo($"/collection/player/{id}");
}
}
@@ -0,0 +1,511 @@
@page "/collection/player/{AccountId:guid}"
@attribute [Authorize(Roles = "Admin,SuperAdmin")]
@inject CollectionDbContext CollectionDb
@inject CatalogDbContext CatalogDb
@inject SOR.Database.Contexts.SorIdentityDbContext IdentityDb
<PageTitle>Player Collection – SOR Admin</PageTitle>
@if (_loaded)
{
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<a href="/collection" class="text-muted text-decoration-none small">
<i class="bi bi-arrow-left me-1"></i>Collection
</a>
<h1 class="mb-0 mt-1">
<i class="bi bi-person-circle me-2 text-muted"></i>
@(_displayName ?? AccountId.ToString())
</h1>
<div class="text-muted small">@AccountId</div>
</div>
<button class="btn btn-outline-primary btn-sm" @onclick="() => _showGrant = true">
<i class="bi bi-plus-circle me-1"></i>Grant Card
</button>
</div>
@if (_grantSuccess != null) { <div class="alert alert-success">@_grantSuccess</div> }
@if (_grantError != null) { <div class="alert alert-danger">@_grantError</div> }
<!-- Tab switcher -->
<ul class="nav nav-tabs mb-3">
<li class="nav-item">
<button class="nav-link @(_tab == "cards" ? "active" : "")" @onclick='() => _tab = "cards"'>
<i class="bi bi-collection me-1"></i>Cards
<span class="badge bg-secondary ms-1">@_totalCards</span>
</button>
</li>
<li class="nav-item">
<button class="nav-link @(_tab == "decks" ? "active" : "")" @onclick='() => _tab = "decks"'>
<i class="bi bi-stack me-1"></i>Decks
<span class="badge bg-secondary ms-1">@_decks.Count</span>
</button>
</li>
</ul>
<!-- ── Cards tab ───────────────────────────────────────────────────── -->
@if (_tab == "cards")
{
<div class="row g-2 mb-3">
<div class="col-md-5">
<input @bind="_cardSearch" class="form-control form-control-sm"
placeholder="Search by name…" @bind:event="oninput" @bind:after="OnCardSearchChanged" />
</div>
<div class="col-md-3">
<select @bind="_cardTypeFilter" class="form-select form-select-sm" @bind:after="LoadCardsAsync">
<option value="">All types</option>
@foreach (var t in Enum.GetValues<CardType>())
{
<option value="@t">@t</option>
}
</select>
</div>
<div class="col-md-3">
<select @bind="_rarityFilter" class="form-select form-select-sm" @bind:after="LoadCardsAsync">
<option value="">All rarities</option>
@foreach (var r in Enum.GetValues<CardRarity>())
{
<option value="@r">@r</option>
}
</select>
</div>
</div>
@if (_cards == null)
{
<p class="text-muted">Loading…</p>
}
else if (_cards.Count == 0)
{
<p class="text-muted">No cards found.</p>
}
else
{
<table class="table table-sm table-hover">
<thead class="table-dark">
<tr>
<th>Name</th>
<th>Type</th>
<th>Affinity</th>
<th>Rarity</th>
<th>Foil</th>
<th>#</th>
<th>Acquired</th>
<th style="width:50px"></th>
</tr>
</thead>
<tbody>
@foreach (var row in _cards)
{
var r = row;
<tr>
<td class="fw-medium">@r.Name</td>
<td><span class="badge bg-secondary">@r.CardType</span></td>
<td>@r.Affinity</td>
<td>@r.Rarity</td>
<td>@(r.IsFoil ? "✦" : "")</td>
<td class="text-muted small">@(r.SerialNumber?.ToString() ?? "—")</td>
<td class="text-muted small">@r.AcquiredAt.ToString("yyyy-MM-dd")</td>
<td>
<button class="btn btn-sm btn-outline-danger"
@onclick="() => RevokeCardAsync(r.PlayerCardId)"
title="Revoke this card">
<i class="bi bi-trash"></i>
</button>
</td>
</tr>
}
</tbody>
</table>
<!-- Pagination -->
<div class="d-flex justify-content-between align-items-center">
<span class="text-muted small">
Showing @((_cardPage - 1) * PageSize + 1)–@(Math.Min(_cardPage * PageSize, _totalCards)) of @_totalCards
</span>
<div class="btn-group btn-group-sm">
<button class="btn btn-outline-secondary" disabled="@(_cardPage <= 1)"
@onclick="() => GoToCardPage(_cardPage - 1)">
<i class="bi bi-chevron-left"></i>
</button>
<button class="btn btn-outline-secondary" disabled="@(_cardPage * PageSize >= _totalCards)"
@onclick="() => GoToCardPage(_cardPage + 1)">
<i class="bi bi-chevron-right"></i>
</button>
</div>
</div>
}
}
<!-- ── Decks tab ──────────────────────────────────────────────────── -->
@if (_tab == "decks")
{
@if (_decks.Count == 0)
{
<p class="text-muted">This player has no decks.</p>
}
else
{
@foreach (var deck in _decks)
{
var d = deck;
<div class="card shadow-sm mb-3">
<div class="card-header d-flex justify-content-between align-items-center">
<div>
<span class="fw-medium">@d.Name</span>
@if (d.IsValid)
{
<span class="badge bg-success ms-2">Valid</span>
}
else
{
<span class="badge bg-warning text-dark ms-2">Invalid</span>
}
</div>
<div class="text-muted small">
ArchSpirit: <strong>@(d.ArchSpiritName ?? d.ArchSpiritCardDefinitionId.ToString())</strong>
&nbsp;·&nbsp; @d.TotalCards card@(d.TotalCards == 1 ? "" : "s")
</div>
</div>
@if (d.Cards.Count > 0)
{
<div class="card-body p-0">
<table class="table table-sm mb-0">
<thead><tr><th>Card</th><th>Type</th><th>Affinity</th><th style="width:80px">Qty</th></tr></thead>
<tbody>
@foreach (var card in d.Cards)
{
<tr>
<td>@card.Name</td>
<td><span class="badge bg-secondary">@card.CardType</span></td>
<td>@card.Affinity</td>
<td>×@card.Quantity</td>
</tr>
}
</tbody>
</table>
</div>
}
</div>
}
}
}
<!-- ── Grant Card modal ───────────────────────────────────────────── -->
@if (_showGrant)
{
<div class="modal fade show d-block" tabindex="-1" style="background:rgba(0,0,0,.5)">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Grant Card</h5>
<button class="btn-close" @onclick="CloseGrant"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label class="form-label">Search Card</label>
<div class="input-group">
<input @bind="_grantSearch" class="form-control" placeholder="Card name…" />
<button class="btn btn-outline-secondary" @onclick="SearchGrantCardAsync">
<i class="bi bi-search"></i>
</button>
</div>
</div>
@if (_grantResults.Count > 0)
{
<div class="list-group mb-3">
@foreach (var cd in _grantResults)
{
var c = cd;
<button class="list-group-item list-group-item-action py-1 @(_grantSelected?.Id == c.Id ? "active" : "")"
@onclick="() => _grantSelected = c">
<span class="fw-medium">@c.Name</span>
<span class="badge bg-secondary ms-2">@c.CardType</span>
<span class="text-muted small ms-1">@c.Affinity · @c.Rarity</span>
</button>
}
</div>
}
@if (_grantSelected != null)
{
<div class="mb-3">
<label class="form-label">Copies to Grant</label>
<input @bind="_grantQty" type="number" min="1" max="100" class="form-control" />
</div>
<div class="mb-0">
<div class="form-check">
<input @bind="_grantFoil" type="checkbox" class="form-check-input" id="chkFoil" />
<label class="form-check-label" for="chkFoil">Foil</label>
</div>
</div>
}
</div>
<div class="modal-footer">
<button class="btn btn-secondary" @onclick="CloseGrant">Cancel</button>
<button class="btn btn-primary" @onclick="GrantCardAsync"
disabled="@(_grantSelected == null || _granting)">
@if (_granting) { <span class="spinner-border spinner-border-sm me-1"></span> }
<i class="bi bi-gift me-1"></i>Grant @_grantQty
</button>
</div>
</div>
</div>
</div>
}
}
else
{
<p class="text-muted">Loading…</p>
}
@code {
[Parameter] public Guid AccountId { get; set; }
private const int PageSize = 50;
// State
private bool _loaded;
private string? _displayName;
private string _tab = "cards";
// Cards tab
private List<PlayerCardRow>? _cards;
private int _totalCards;
private int _cardPage = 1;
private string _cardSearch = string.Empty;
private string _cardTypeFilter = string.Empty;
private string _rarityFilter = string.Empty;
// Decks tab
private List<DeckRow> _decks = new();
// Grant modal
private bool _showGrant;
private string _grantSearch = string.Empty;
private List<CardDefinition> _grantResults = new();
private CardDefinition? _grantSelected;
private int _grantQty = 1;
private bool _grantFoil;
private bool _granting;
private string? _grantSuccess;
private string? _grantError;
// View models
private sealed class PlayerCardRow
{
public Guid PlayerCardId { get; init; }
public Guid CardDefinitionId { get; init; }
public string Name { get; init; } = "";
public string CardType { get; init; } = "";
public string Affinity { get; init; } = "";
public string Rarity { get; init; } = "";
public bool IsFoil { get; init; }
public int? SerialNumber { get; init; }
public DateTimeOffset AcquiredAt { get; init; }
}
private sealed class DeckRow
{
public Guid Id { get; init; }
public string Name { get; init; } = "";
public Guid ArchSpiritCardDefinitionId { get; init; }
public string? ArchSpiritName { get; init; }
public bool IsValid { get; init; }
public int TotalCards { get; init; }
public List<DeckCardRow> Cards { get; init; } = new();
}
private sealed class DeckCardRow
{
public Guid CardDefinitionId { get; init; }
public string Name { get; init; } = "";
public string CardType { get; init; } = "";
public string Affinity { get; init; } = "";
public int Quantity { get; init; }
}
protected override async Task OnInitializedAsync()
{
// Fetch player display name from identity schema.
_displayName = await IdentityDb.Users
.Where(u => u.Id == AccountId)
.Select(u => u.DisplayName)
.FirstOrDefaultAsync();
await LoadCardsAsync();
await LoadDecksAsync();
_loaded = true;
}
private async Task LoadCardsAsync()
{
var query = CollectionDb.PlayerCards
.Where(pc => pc.AccountId == AccountId);
// Cross-context filters: resolve matching definition IDs first.
if (!string.IsNullOrWhiteSpace(_cardSearch)
|| !string.IsNullOrEmpty(_cardTypeFilter)
|| !string.IsNullOrEmpty(_rarityFilter))
{
var defQ = CatalogDb.CardDefinitions.AsQueryable();
if (!string.IsNullOrWhiteSpace(_cardSearch))
defQ = defQ.Where(cd => cd.Name.Contains(_cardSearch));
if (!string.IsNullOrEmpty(_cardTypeFilter)
&& Enum.TryParse<CardType>(_cardTypeFilter, out var ctf))
defQ = defQ.Where(cd => cd.CardType == ctf);
if (!string.IsNullOrEmpty(_rarityFilter)
&& Enum.TryParse<CardRarity>(_rarityFilter, out var rf))
defQ = defQ.Where(cd => cd.Rarity == rf);
var matchIds = await defQ.Select(cd => cd.Id).ToListAsync();
query = query.Where(pc => matchIds.Contains(pc.CardDefinitionId));
}
_totalCards = await query.CountAsync();
int skip = (_cardPage - 1) * PageSize;
var playerCards = await query
.OrderBy(pc => pc.AcquiredAt)
.Skip(skip).Take(PageSize)
.ToListAsync();
var defIds = playerCards.Select(pc => pc.CardDefinitionId).Distinct().ToList();
var defLookup = await CatalogDb.CardDefinitions
.Where(cd => defIds.Contains(cd.Id))
.ToDictionaryAsync(cd => cd.Id);
_cards = playerCards.Select(pc =>
{
defLookup.TryGetValue(pc.CardDefinitionId, out var def);
return new PlayerCardRow
{
PlayerCardId = pc.Id,
CardDefinitionId = pc.CardDefinitionId,
Name = def?.Name ?? "Unknown",
CardType = def?.CardType.ToString() ?? "Unknown",
Affinity = def?.Affinity.ToString() ?? "Unknown",
Rarity = def?.Rarity.ToString() ?? "Unknown",
IsFoil = pc.IsFoil,
SerialNumber = pc.SerialNumber,
AcquiredAt = pc.AcquiredAt,
};
}).ToList();
}
private async Task LoadDecksAsync()
{
var decks = await CollectionDb.Decks
.Include(d => d.Cards)
.Where(d => d.AccountId == AccountId)
.OrderBy(d => d.CreatedAt)
.ToListAsync();
// Batch-load definitions for arch spirits + deck cards.
var allDefIds = decks
.SelectMany(d => d.Cards.Select(c => c.CardDefinitionId).Append(d.ArchSpiritCardDefinitionId))
.Distinct()
.ToList();
var defs = await CatalogDb.CardDefinitions
.Where(cd => allDefIds.Contains(cd.Id))
.ToDictionaryAsync(cd => cd.Id);
_decks = decks.Select(d =>
{
defs.TryGetValue(d.ArchSpiritCardDefinitionId, out var archDef);
return new DeckRow
{
Id = d.Id,
Name = d.Name,
ArchSpiritCardDefinitionId = d.ArchSpiritCardDefinitionId,
ArchSpiritName = archDef?.Name,
IsValid = d.IsValid,
TotalCards = d.Cards.Sum(c => c.Quantity),
Cards = d.Cards
.OrderBy(c => defs.TryGetValue(c.CardDefinitionId, out var cd) ? cd.Name : "")
.Select(c =>
{
defs.TryGetValue(c.CardDefinitionId, out var cd);
return new DeckCardRow
{
CardDefinitionId = c.CardDefinitionId,
Name = cd?.Name ?? "Unknown",
CardType = cd?.CardType.ToString() ?? "",
Affinity = cd?.Affinity.ToString() ?? "",
Quantity = c.Quantity,
};
}).ToList(),
};
}).ToList();
}
private async Task GoToCardPage(int page)
{
_cardPage = page;
await LoadCardsAsync();
}
private async Task OnCardSearchChanged()
{
_cardPage = 1;
await LoadCardsAsync();
}
private async Task RevokeCardAsync(Guid playerCardId)
{
_grantSuccess = _grantError = null;
var card = await CollectionDb.PlayerCards.FindAsync(playerCardId);
if (card == null || card.AccountId != AccountId) return;
CollectionDb.PlayerCards.Remove(card);
await CollectionDb.SaveChangesAsync();
await LoadCardsAsync();
}
// ── Grant modal ──────────────────────────────────────────────────────────
private void CloseGrant()
{
_showGrant = false;
_grantSearch = string.Empty;
_grantResults.Clear();
_grantSelected = null;
_grantQty = 1;
_grantFoil = false;
}
private async Task SearchGrantCardAsync()
{
if (string.IsNullOrWhiteSpace(_grantSearch)) return;
_grantResults = await CatalogDb.CardDefinitions
.Where(cd => cd.Name.Contains(_grantSearch))
.OrderBy(cd => cd.Name)
.Take(20)
.ToListAsync();
}
private async Task GrantCardAsync()
{
if (_grantSelected == null) return;
_granting = true; _grantError = null; _grantSuccess = null;
try
{
int qty = Math.Clamp(_grantQty, 1, 100);
var now = DateTimeOffset.UtcNow;
for (int i = 0; i < qty; i++)
{
CollectionDb.PlayerCards.Add(new SOR.Database.Entities.Collection.PlayerCard
{
AccountId = AccountId,
CardDefinitionId = _grantSelected.Id,
AcquiredAt = now,
IsFoil = _grantFoil,
});
}
await CollectionDb.SaveChangesAsync();
_grantSuccess = $"Granted {qty}× {_grantSelected.Name}{(_grantFoil ? " (Foil)" : "")} to player.";
CloseGrant();
await LoadCardsAsync();
}
catch (Exception ex) { _grantError = ex.Message; }
finally { _granting = false; }
}
}
@@ -0,0 +1,102 @@
namespace SOR.Collection;
// ── Request types (client → server) ──────────────────────────────────────────
/// <summary>
/// Paginated list of all cards the authenticated player owns.
/// NameFilter: case-insensitive substring match on card name (optional).
/// CardTypeFilter / AffinityFilter: exact enum name match (optional).
/// </summary>
public sealed record GetCardsRequest(
int Page = 1,
int PageSize = 50,
string? NameFilter = null,
string? CardTypeFilter = null,
string? AffinityFilter = null);
/// <summary>Returns all decks for the authenticated player (summaries only).</summary>
public sealed record GetDecksRequest; // no fields — identity from connection
/// <summary>Returns one deck with its full card list and owned-count per card.</summary>
public sealed record GetDeckRequest(Guid DeckId);
/// <summary>
/// Creates a new deck.
/// ArchSpiritCardDefinitionId must be an ArchSpirit card the player owns.
/// </summary>
public sealed record CreateDeckRequest(string Name, Guid ArchSpiritCardDefinitionId);
/// <summary>Renames an existing deck the player owns.</summary>
public sealed record RenameDeckRequest(Guid DeckId, string Name);
/// <summary>Permanently deletes a deck and all its DeckCard rows.</summary>
public sealed record DeleteDeckRequest(Guid DeckId);
/// <summary>
/// Adds (or increases the quantity of) a card definition to a deck.
/// Quantity is the number of copies to add (default 1).
/// Fails if the player does not own enough copies or deck/copy limits are exceeded.
/// </summary>
public sealed record AddCardRequest(Guid DeckId, Guid CardDefinitionId, int Quantity = 1);
/// <summary>
/// Removes copies of a card definition from a deck.
/// Quantity null → remove all copies of that definition.
/// </summary>
public sealed record RemoveCardRequest(Guid DeckId, Guid CardDefinitionId, int? Quantity = null);
// ── Response / DTO types (server → client) ────────────────────────────────────
public sealed record GetCardsResponse(
IEnumerable<PlayerCardDto> Cards,
int TotalCount,
int Page,
int PageSize);
public sealed record PlayerCardDto(
Guid PlayerCardId,
Guid CardDefinitionId,
string Name,
string CardType,
string Affinity,
string Rarity,
bool IsFoil,
int? SerialNumber,
DateTimeOffset AcquiredAt,
string? ArtUrl);
public sealed record GetDecksResponse(IEnumerable<DeckSummaryDto> Decks);
public sealed record DeckSummaryDto(
Guid Id,
string Name,
Guid ArchSpiritCardDefinitionId,
string? ArchSpiritName,
int CardCount,
bool IsValid,
DateTimeOffset CreatedAt,
DateTimeOffset UpdatedAt);
public sealed record GetDeckResponse(DeckDetailDto? Deck);
public sealed record DeckDetailDto(
Guid Id,
string Name,
Guid ArchSpiritCardDefinitionId,
string? ArchSpiritName,
bool IsValid,
DateTimeOffset CreatedAt,
DateTimeOffset UpdatedAt,
IEnumerable<DeckCardDto> Cards);
public sealed record DeckCardDto(
Guid CardDefinitionId,
string Name,
string CardType,
string Affinity,
string Rarity,
string? ArtUrl,
int Quantity,
int OwnedCount);
public sealed record DeckMutationResponse(DeckSummaryDto Deck);
+20
View File
@@ -0,0 +1,20 @@
namespace SOR.Collection;
/// <summary>
/// Deck construction rules enforced by the collection service.
/// Change values here to adjust rules without hunting handler code.
/// </summary>
public static class DeckRules
{
/// <summary>Minimum number of non-ArchSpirit cards in a deck.</summary>
public const int MinDeckSize = 20;
/// <summary>Maximum number of non-ArchSpirit cards in a deck.</summary>
public const int MaxDeckSize = 40;
/// <summary>Maximum copies of any single card definition in a deck.</summary>
public const int MaxCopiesPerCard = 4;
/// <summary>Maximum number of decks a single player may own.</summary>
public const int MaxDecksPerPlayer = 20;
}
@@ -0,0 +1,133 @@
namespace SOR.Collection.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Database.Entities.Collection;
using SOR.Database.Enums;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// collection.add_card — adds (or increments) a card in a deck.
///
/// Validation:
/// - Deck exists and belongs to the player.
/// - CardDefinitionId must not be an ArchSpirit (those live at the deck level).
/// - Player owns enough physical copies (existing + delta ≤ owned).
/// - Adding would not push the definition over MaxCopiesPerCard.
/// - Adding would not push the deck over MaxDeckSize.
/// </summary>
internal sealed class CollectionAddCardHandler : CollectionHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly CollectionDbContext _collectionDb;
private readonly CatalogDbContext _catalogDb;
public CollectionAddCardHandler(
IMessageSerializer serializer,
CollectionDbContext collectionDb,
CatalogDbContext catalogDb)
{
_serializer = serializer;
_collectionDb = collectionDb;
_catalogDb = catalogDb;
}
public string MessageType => "collection.add_card";
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken cancellationToken)
{
var req = _serializer.DeserializePayload<AddCardRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
if (req.Quantity < 1)
return ServerMessage.Error(message.Seq, "INVALID_QUANTITY", "Quantity must be at least 1.");
// ── Fetch deck ─────────────────────────────────────────────────────────
var deck = await _collectionDb.Decks
.Include(d => d.Cards)
.FirstOrDefaultAsync(
d => d.Id == req.DeckId && d.AccountId == accountId,
cancellationToken);
if (deck == null)
return ServerMessage.Error(message.Seq, "DECK_NOT_FOUND", "Deck not found.");
// ── Validate card type (ArchSpirits cannot be added to the card list) ──
var cardType = await _catalogDb.CardDefinitions
.Where(cd => cd.Id == req.CardDefinitionId)
.Select(cd => (CardType?)cd.CardType)
.FirstOrDefaultAsync(cancellationToken);
if (cardType == null)
return ServerMessage.Error(message.Seq, "CARD_NOT_FOUND", "Card definition not found.");
if (cardType == CardType.ArchSpirit)
return ServerMessage.Error(message.Seq, "ARCH_SPIRIT_NOT_ALLOWED",
"ArchSpirit cards are set at the deck level, not in the card list.");
// ── Copy-count checks ──────────────────────────────────────────────────
var existingEntry = deck.Cards.FirstOrDefault(c => c.CardDefinitionId == req.CardDefinitionId);
int currentInDeck = existingEntry?.Quantity ?? 0;
int afterAdd = currentInDeck + req.Quantity;
if (afterAdd > DeckRules.MaxCopiesPerCard)
return ServerMessage.Error(message.Seq, "COPY_LIMIT_EXCEEDED",
$"You may only include up to {DeckRules.MaxCopiesPerCard} copies of a card.");
// ── Deck size check ────────────────────────────────────────────────────
int currentTotal = deck.Cards.Sum(c => c.Quantity);
if (currentTotal + req.Quantity > DeckRules.MaxDeckSize)
return ServerMessage.Error(message.Seq, "DECK_TOO_LARGE",
$"Deck would exceed the maximum of {DeckRules.MaxDeckSize} cards.");
// ── Ownership check ────────────────────────────────────────────────────
int owned = await _collectionDb.PlayerCards
.CountAsync(
pc => pc.AccountId == accountId
&& pc.CardDefinitionId == req.CardDefinitionId,
cancellationToken);
if (owned < afterAdd)
return ServerMessage.Error(message.Seq, "INSUFFICIENT_COPIES",
$"You own {owned} cop{(owned == 1 ? "y" : "ies")} of that card but the deck would need {afterAdd}.");
// ── Apply the change ───────────────────────────────────────────────────
if (existingEntry != null)
{
existingEntry.Quantity = afterAdd;
}
else
{
var entry = new DeckCard
{
DeckId = deck.Id,
CardDefinitionId = req.CardDefinitionId,
Quantity = req.Quantity,
};
_collectionDb.DeckCards.Add(entry);
deck.Cards.Add(entry);
}
await RefreshValidityAsync(_collectionDb, deck, cancellationToken);
// Return the updated deck summary.
var archName = await _catalogDb.CardDefinitions
.Where(cd => cd.Id == deck.ArchSpiritCardDefinitionId)
.Select(cd => cd.Name)
.FirstOrDefaultAsync(cancellationToken);
var summary = new DeckSummaryDto(
Id: deck.Id,
Name: deck.Name,
ArchSpiritCardDefinitionId: deck.ArchSpiritCardDefinitionId,
ArchSpiritName: archName,
CardCount: deck.Cards.Sum(c => c.Quantity),
IsValid: deck.IsValid,
CreatedAt: deck.CreatedAt,
UpdatedAt: deck.UpdatedAt);
return ServerMessage.Reply("collection.add_card.ack", message.Seq,
new DeckMutationResponse(summary));
}
}
@@ -0,0 +1,104 @@
namespace SOR.Collection.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Database.Entities.Collection;
using SOR.Database.Enums;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// collection.create_deck — creates a new empty deck for the player.
///
/// Validation:
/// - Name must be 1–50 characters.
/// - Player may not exceed MaxDecksPerPlayer.
/// - ArchSpiritCardDefinitionId must exist in the catalog as an ArchSpirit.
/// - Player must own at least one copy of the chosen ArchSpirit.
/// </summary>
internal sealed class CollectionCreateDeckHandler : CollectionHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly CollectionDbContext _collectionDb;
private readonly CatalogDbContext _catalogDb;
public CollectionCreateDeckHandler(
IMessageSerializer serializer,
CollectionDbContext collectionDb,
CatalogDbContext catalogDb)
{
_serializer = serializer;
_collectionDb = collectionDb;
_catalogDb = catalogDb;
}
public string MessageType => "collection.create_deck";
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken cancellationToken)
{
var req = _serializer.DeserializePayload<CreateDeckRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
// ── Validate name ──────────────────────────────────────────────────────
if (string.IsNullOrWhiteSpace(req.Name) || req.Name.Length > 50)
return ServerMessage.Error(message.Seq, "INVALID_NAME",
"Deck name must be 1–50 characters.");
// ── Enforce deck limit ─────────────────────────────────────────────────
var deckCount = await _collectionDb.Decks
.CountAsync(d => d.AccountId == accountId, cancellationToken);
if (deckCount >= DeckRules.MaxDecksPerPlayer)
return ServerMessage.Error(message.Seq, "DECK_LIMIT_REACHED",
$"Maximum of {DeckRules.MaxDecksPerPlayer} decks reached.");
// ── Validate ArchSpirit exists in catalog ──────────────────────────────
var archDef = await _catalogDb.CardDefinitions
.FirstOrDefaultAsync(
cd => cd.Id == req.ArchSpiritCardDefinitionId
&& cd.CardType == CardType.ArchSpirit,
cancellationToken);
if (archDef == null)
return ServerMessage.Error(message.Seq, "INVALID_ARCH_SPIRIT",
"That card is not a valid ArchSpirit.");
// ── Validate player owns the ArchSpirit ────────────────────────────────
var ownsArch = await _collectionDb.PlayerCards
.AnyAsync(
pc => pc.AccountId == accountId
&& pc.CardDefinitionId == req.ArchSpiritCardDefinitionId,
cancellationToken);
if (!ownsArch)
return ServerMessage.Error(message.Seq, "ARCH_SPIRIT_NOT_OWNED",
"You do not own that ArchSpirit card.");
// ── Create the deck ────────────────────────────────────────────────────
var deck = new Deck
{
AccountId = accountId,
Name = req.Name.Trim(),
ArchSpiritCardDefinitionId = req.ArchSpiritCardDefinitionId,
IsValid = false, // empty deck is never valid
CreatedAt = DateTimeOffset.UtcNow,
UpdatedAt = DateTimeOffset.UtcNow,
};
_collectionDb.Decks.Add(deck);
await _collectionDb.SaveChangesAsync(cancellationToken);
var summary = new DeckSummaryDto(
Id: deck.Id,
Name: deck.Name,
ArchSpiritCardDefinitionId: deck.ArchSpiritCardDefinitionId,
ArchSpiritName: archDef.Name,
CardCount: 0,
IsValid: false,
CreatedAt: deck.CreatedAt,
UpdatedAt: deck.UpdatedAt);
return ServerMessage.Reply("collection.create_deck.ack", message.Seq,
new DeckMutationResponse(summary));
}
}
@@ -0,0 +1,48 @@
namespace SOR.Collection.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// collection.delete_deck — permanently removes a deck and all its DeckCard rows.
/// EF cascade delete handles the child rows automatically (configured in BazaarDbContext).
/// </summary>
internal sealed class CollectionDeleteDeckHandler : IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly CollectionDbContext _collectionDb;
public CollectionDeleteDeckHandler(
IMessageSerializer serializer,
CollectionDbContext collectionDb)
{
_serializer = serializer;
_collectionDb = collectionDb;
}
public string MessageType => "collection.delete_deck";
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken cancellationToken)
{
var req = _serializer.DeserializePayload<DeleteDeckRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
var deck = await _collectionDb.Decks
.FirstOrDefaultAsync(
d => d.Id == req.DeckId && d.AccountId == accountId,
cancellationToken);
if (deck == null)
return ServerMessage.Error(message.Seq, "DECK_NOT_FOUND", "Deck not found.");
_collectionDb.Decks.Remove(deck);
await _collectionDb.SaveChangesAsync(cancellationToken);
return ServerMessage.Reply("collection.delete_deck.ack", message.Seq, new { deckId = req.DeckId });
}
}
@@ -0,0 +1,104 @@
namespace SOR.Collection.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Database.Enums;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// collection.get_cards — paginated view of all cards the player owns.
///
/// The player's identity comes from the authenticated connection (no account ID
/// in the payload) so a player can only see their own collection.
/// </summary>
internal sealed class CollectionGetCardsHandler : CollectionHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly CollectionDbContext _collectionDb;
private readonly CatalogDbContext _catalogDb;
public CollectionGetCardsHandler(
IMessageSerializer serializer,
CollectionDbContext collectionDb,
CatalogDbContext catalogDb)
{
_serializer = serializer;
_collectionDb = collectionDb;
_catalogDb = catalogDb;
}
public string MessageType => "collection.get_cards";
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken cancellationToken)
{
var req = _serializer.DeserializePayload<GetCardsRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
int page = Math.Max(1, req.Page);
int pageSize = Math.Clamp(req.PageSize, 1, 100);
int skip = (page - 1) * pageSize;
// Build the query against the collection schema.
var query = _collectionDb.PlayerCards
.Where(pc => pc.AccountId == accountId);
// Cross-context name/type filter: first resolve matching definition IDs from catalog.
if (!string.IsNullOrWhiteSpace(req.NameFilter)
|| !string.IsNullOrWhiteSpace(req.CardTypeFilter)
|| !string.IsNullOrWhiteSpace(req.AffinityFilter))
{
var defQuery = _catalogDb.CardDefinitions.AsQueryable();
if (!string.IsNullOrWhiteSpace(req.NameFilter))
defQuery = defQuery.Where(cd => cd.Name.Contains(req.NameFilter));
if (!string.IsNullOrWhiteSpace(req.CardTypeFilter)
&& Enum.TryParse<CardType>(req.CardTypeFilter, true, out var ct))
defQuery = defQuery.Where(cd => cd.CardType == ct);
if (!string.IsNullOrWhiteSpace(req.AffinityFilter)
&& Enum.TryParse<Affinity>(req.AffinityFilter, true, out var af))
defQuery = defQuery.Where(cd => cd.Affinity == af);
var matchingIds = await defQuery.Select(cd => cd.Id).ToListAsync(cancellationToken);
query = query.Where(pc => matchingIds.Contains(pc.CardDefinitionId));
}
int total = await query.CountAsync(cancellationToken);
var playerCards = await query
.OrderBy(pc => pc.AcquiredAt)
.Skip(skip)
.Take(pageSize)
.ToListAsync(cancellationToken);
// Batch-fetch definitions from catalog schema.
var definitions = await LoadDefinitionsAsync(
_catalogDb,
playerCards.Select(pc => pc.CardDefinitionId),
cancellationToken);
var dtos = playerCards.Select(pc =>
{
definitions.TryGetValue(pc.CardDefinitionId, out var def);
return new PlayerCardDto(
PlayerCardId: pc.Id,
CardDefinitionId: pc.CardDefinitionId,
Name: def?.Name ?? "Unknown",
CardType: def?.CardType.ToString() ?? "Unknown",
Affinity: def?.Affinity.ToString() ?? "Unknown",
Rarity: def?.Rarity.ToString() ?? "Unknown",
IsFoil: pc.IsFoil,
SerialNumber: pc.SerialNumber,
AcquiredAt: pc.AcquiredAt,
ArtUrl: GetArtUrl(def));
});
return ServerMessage.Reply(
"collection.get_cards.ack",
message.Seq,
new GetCardsResponse(dtos, total, page, pageSize));
}
}
@@ -0,0 +1,93 @@
namespace SOR.Collection.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// collection.get_deck — returns a single deck with its full card list.
/// Each card row includes how many copies the player currently owns,
/// so the client can show "you have 3/4" without a separate request.
/// </summary>
internal sealed class CollectionGetDeckHandler : CollectionHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly CollectionDbContext _collectionDb;
private readonly CatalogDbContext _catalogDb;
public CollectionGetDeckHandler(
IMessageSerializer serializer,
CollectionDbContext collectionDb,
CatalogDbContext catalogDb)
{
_serializer = serializer;
_collectionDb = collectionDb;
_catalogDb = catalogDb;
}
public string MessageType => "collection.get_deck";
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken cancellationToken)
{
var req = _serializer.DeserializePayload<GetDeckRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
var deck = await _collectionDb.Decks
.Include(d => d.Cards)
.FirstOrDefaultAsync(
d => d.Id == req.DeckId && d.AccountId == accountId,
cancellationToken);
if (deck == null)
return ServerMessage.Error(message.Seq, "DECK_NOT_FOUND", "Deck not found.");
// Batch-load definitions for all cards + the ArchSpirit.
var allDefIds = deck.Cards
.Select(c => c.CardDefinitionId)
.Append(deck.ArchSpiritCardDefinitionId)
.Distinct();
var definitions = await LoadDefinitionsAsync(_catalogDb, allDefIds, cancellationToken);
var ownedCounts = await GetOwnedCountsAsync(
_collectionDb,
accountId,
deck.Cards.Select(c => c.CardDefinitionId),
cancellationToken);
definitions.TryGetValue(deck.ArchSpiritCardDefinitionId, out var archDef);
var cardDtos = deck.Cards
.OrderBy(c => definitions.TryGetValue(c.CardDefinitionId, out var d) ? d.Name : "")
.Select(c =>
{
definitions.TryGetValue(c.CardDefinitionId, out var def);
return new DeckCardDto(
CardDefinitionId: c.CardDefinitionId,
Name: def?.Name ?? "Unknown",
CardType: def?.CardType.ToString() ?? "Unknown",
Affinity: def?.Affinity.ToString() ?? "Unknown",
Rarity: def?.Rarity.ToString() ?? "Unknown",
ArtUrl: GetArtUrl(def),
Quantity: c.Quantity,
OwnedCount: ownedCounts.GetValueOrDefault(c.CardDefinitionId));
});
var dto = new DeckDetailDto(
Id: deck.Id,
Name: deck.Name,
ArchSpiritCardDefinitionId: deck.ArchSpiritCardDefinitionId,
ArchSpiritName: archDef?.Name,
IsValid: deck.IsValid,
CreatedAt: deck.CreatedAt,
UpdatedAt: deck.UpdatedAt,
Cards: cardDtos);
return ServerMessage.Reply("collection.get_deck.ack", message.Seq,
new GetDeckResponse(dto));
}
}
@@ -0,0 +1,71 @@
namespace SOR.Collection.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// collection.get_decks — returns summary of all decks the player owns.
/// No payload required; identity comes from the authenticated connection.
/// </summary>
internal sealed class CollectionGetDecksHandler : CollectionHandlerBase, IMessageHandler
{
private readonly CollectionDbContext _collectionDb;
private readonly CatalogDbContext _catalogDb;
public CollectionGetDecksHandler(
CollectionDbContext collectionDb,
CatalogDbContext catalogDb)
{
_collectionDb = collectionDb;
_catalogDb = catalogDb;
}
public string MessageType => "collection.get_decks";
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken cancellationToken)
{
var accountId = Guid.Parse(connection.UserId);
var decks = await _collectionDb.Decks
.Where(d => d.AccountId == accountId)
.OrderBy(d => d.CreatedAt)
.Select(d => new
{
d.Id,
d.Name,
d.ArchSpiritCardDefinitionId,
d.IsValid,
d.CreatedAt,
d.UpdatedAt,
CardCount = d.Cards.Sum(c => c.Quantity)
})
.ToListAsync(cancellationToken);
// Batch-fetch ArchSpirit names from catalog.
var archIds = decks.Select(d => d.ArchSpiritCardDefinitionId).Distinct().ToList();
var archNames = await _catalogDb.CardDefinitions
.Where(cd => archIds.Contains(cd.Id))
.ToDictionaryAsync(cd => cd.Id, cd => cd.Name, cancellationToken);
var summaries = decks.Select(d => new DeckSummaryDto(
Id: d.Id,
Name: d.Name,
ArchSpiritCardDefinitionId: d.ArchSpiritCardDefinitionId,
ArchSpiritName: archNames.GetValueOrDefault(d.ArchSpiritCardDefinitionId),
CardCount: d.CardCount,
IsValid: d.IsValid,
CreatedAt: d.CreatedAt,
UpdatedAt: d.UpdatedAt));
return ServerMessage.Reply(
"collection.get_decks.ack",
message.Seq,
new GetDecksResponse(summaries));
}
}
@@ -0,0 +1,91 @@
namespace SOR.Collection.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Database.Entities.Catalog;
using SOR.Database.Enums;
/// <summary>
/// Shared helpers for all collection message handlers.
/// Each handler subclass inherits these utilities for cross-context lookups.
/// </summary>
internal abstract class CollectionHandlerBase
{
/// <summary>
/// Batch-loads CardDefinitions from the catalog context for a set of definition IDs.
/// Used to enrich PlayerCard and DeckCard results with name/type/art data.
/// </summary>
protected static async Task<Dictionary<Guid, CardDefinition>> LoadDefinitionsAsync(
CatalogDbContext catalogDb,
IEnumerable<Guid> ids,
CancellationToken ct)
{
var distinctIds = ids.Distinct().ToList();
if (distinctIds.Count == 0) return new Dictionary<Guid, CardDefinition>();
return await catalogDb.CardDefinitions
.Include(cd => cd.Assets)
.Where(cd => distinctIds.Contains(cd.Id))
.ToDictionaryAsync(cd => cd.Id, ct);
}
/// <summary>
/// Returns the first Art2D CDN URL for a card definition, or null if none.
/// </summary>
protected static string? GetArtUrl(CardDefinition? def)
=> def?.Assets
.FirstOrDefault(a => a.AssetType == CardAssetType.Art2D)
?.CdnUrl;
/// <summary>
/// Counts how many copies of each CardDefinitionId the player currently owns.
/// Returns a dictionary: CardDefinitionId → owned count.
/// </summary>
protected static async Task<Dictionary<Guid, int>> GetOwnedCountsAsync(
CollectionDbContext collectionDb,
Guid accountId,
IEnumerable<Guid> definitionIds,
CancellationToken ct)
{
var ids = definitionIds.Distinct().ToList();
if (ids.Count == 0) return new Dictionary<Guid, int>();
return await collectionDb.PlayerCards
.Where(pc => pc.AccountId == accountId && ids.Contains(pc.CardDefinitionId))
.GroupBy(pc => pc.CardDefinitionId)
.Select(g => new { DefinitionId = g.Key, Count = g.Count() })
.ToDictionaryAsync(x => x.DefinitionId, x => x.Count, ct);
}
/// <summary>
/// Recomputes and saves Deck.IsValid based on current cards and ownership.
/// Should be called after any add/remove card mutation.
/// </summary>
protected static async Task RefreshValidityAsync(
CollectionDbContext collectionDb,
Database.Entities.Collection.Deck deck,
CancellationToken ct)
{
var cards = await collectionDb.DeckCards
.Where(dc => dc.DeckId == deck.Id)
.ToListAsync(ct);
var ownedCounts = await GetOwnedCountsAsync(
collectionDb,
deck.AccountId,
cards.Select(c => c.CardDefinitionId),
ct);
int total = cards.Sum(c => c.Quantity);
bool valid =
total >= DeckRules.MinDeckSize &&
total <= DeckRules.MaxDeckSize &&
cards.All(c =>
c.Quantity <= DeckRules.MaxCopiesPerCard &&
ownedCounts.GetValueOrDefault(c.CardDefinitionId) >= c.Quantity);
deck.IsValid = valid;
deck.UpdatedAt = DateTimeOffset.UtcNow;
await collectionDb.SaveChangesAsync(ct);
}
}
@@ -0,0 +1,87 @@
namespace SOR.Collection.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// collection.remove_card — removes copies of a card from a deck.
///
/// If Quantity is null or ≥ current quantity, the card is removed entirely.
/// If Quantity is a positive int, that many copies are decremented.
/// </summary>
internal sealed class CollectionRemoveCardHandler : CollectionHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly CollectionDbContext _collectionDb;
private readonly CatalogDbContext _catalogDb;
public CollectionRemoveCardHandler(
IMessageSerializer serializer,
CollectionDbContext collectionDb,
CatalogDbContext catalogDb)
{
_serializer = serializer;
_collectionDb = collectionDb;
_catalogDb = catalogDb;
}
public string MessageType => "collection.remove_card";
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken cancellationToken)
{
var req = _serializer.DeserializePayload<RemoveCardRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
var deck = await _collectionDb.Decks
.Include(d => d.Cards)
.FirstOrDefaultAsync(
d => d.Id == req.DeckId && d.AccountId == accountId,
cancellationToken);
if (deck == null)
return ServerMessage.Error(message.Seq, "DECK_NOT_FOUND", "Deck not found.");
var entry = deck.Cards.FirstOrDefault(c => c.CardDefinitionId == req.CardDefinitionId);
if (entry == null)
return ServerMessage.Error(message.Seq, "CARD_NOT_IN_DECK",
"That card is not in this deck.");
int toRemove = req.Quantity is null or <= 0 ? entry.Quantity : req.Quantity.Value;
if (toRemove >= entry.Quantity)
{
// Remove the row entirely.
_collectionDb.DeckCards.Remove(entry);
deck.Cards.Remove(entry);
}
else
{
entry.Quantity -= toRemove;
}
await RefreshValidityAsync(_collectionDb, deck, cancellationToken);
var archName = await _catalogDb.CardDefinitions
.Where(cd => cd.Id == deck.ArchSpiritCardDefinitionId)
.Select(cd => cd.Name)
.FirstOrDefaultAsync(cancellationToken);
var summary = new DeckSummaryDto(
Id: deck.Id,
Name: deck.Name,
ArchSpiritCardDefinitionId: deck.ArchSpiritCardDefinitionId,
ArchSpiritName: archName,
CardCount: deck.Cards.Sum(c => c.Quantity),
IsValid: deck.IsValid,
CreatedAt: deck.CreatedAt,
UpdatedAt: deck.UpdatedAt);
return ServerMessage.Reply("collection.remove_card.ack", message.Seq,
new DeckMutationResponse(summary));
}
}
@@ -0,0 +1,72 @@
namespace SOR.Collection.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// collection.rename_deck — renames a deck the player owns.
/// </summary>
internal sealed class CollectionRenameDeckHandler : CollectionHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly CollectionDbContext _collectionDb;
private readonly CatalogDbContext _catalogDb;
public CollectionRenameDeckHandler(
IMessageSerializer serializer,
CollectionDbContext collectionDb,
CatalogDbContext catalogDb)
{
_serializer = serializer;
_collectionDb = collectionDb;
_catalogDb = catalogDb;
}
public string MessageType => "collection.rename_deck";
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken cancellationToken)
{
var req = _serializer.DeserializePayload<RenameDeckRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
if (string.IsNullOrWhiteSpace(req.Name) || req.Name.Length > 50)
return ServerMessage.Error(message.Seq, "INVALID_NAME",
"Deck name must be 1–50 characters.");
var deck = await _collectionDb.Decks
.Include(d => d.Cards)
.FirstOrDefaultAsync(
d => d.Id == req.DeckId && d.AccountId == accountId,
cancellationToken);
if (deck == null)
return ServerMessage.Error(message.Seq, "DECK_NOT_FOUND", "Deck not found.");
deck.Name = req.Name.Trim();
deck.UpdatedAt = DateTimeOffset.UtcNow;
await _collectionDb.SaveChangesAsync(cancellationToken);
var archName = await _catalogDb.CardDefinitions
.Where(cd => cd.Id == deck.ArchSpiritCardDefinitionId)
.Select(cd => cd.Name)
.FirstOrDefaultAsync(cancellationToken);
var summary = new DeckSummaryDto(
Id: deck.Id,
Name: deck.Name,
ArchSpiritCardDefinitionId: deck.ArchSpiritCardDefinitionId,
ArchSpiritName: archName,
CardCount: deck.Cards.Sum(c => c.Quantity),
IsValid: deck.IsValid,
CreatedAt: deck.CreatedAt,
UpdatedAt: deck.UpdatedAt);
return ServerMessage.Reply("collection.rename_deck.ack", message.Seq,
new DeckMutationResponse(summary));
}
}
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>SOR.Collection</AssemblyName>
</PropertyGroup>
<ItemGroup>
<!-- ASP.NET Core APIs (IServiceCollection etc.) without the web host overhead -->
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SOR.Database\SOR.Database.csproj" />
<ProjectReference Include="..\SOR.Networking.Abstractions\SOR.Networking.Abstractions.csproj" />
<ProjectReference Include="..\SOR.Shared\SOR.Shared.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,36 @@
namespace SOR.Collection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SOR.Collection.Handlers;
using SOR.Database;
using SOR.Networking.Abstractions.Messaging;
/// <summary>
/// Registers all collection service components into the DI container.
/// Called from SOR.Host/Program.cs when ENABLED_SERVICES includes "collection".
/// </summary>
public static class ServiceRegistration
{
public static IServiceCollection AddCollectionService(
this IServiceCollection services,
IConfiguration configuration)
{
// Database contexts the collection service needs.
services.AddCollectionDatabase(configuration);
services.AddCatalogDatabase(configuration);
// Message handlers — one per message type, Transient lifetime.
// MessageDispatcher collects all IMessageHandler registrations at startup.
services.AddTransient<IMessageHandler, CollectionGetCardsHandler>();
services.AddTransient<IMessageHandler, CollectionGetDecksHandler>();
services.AddTransient<IMessageHandler, CollectionGetDeckHandler>();
services.AddTransient<IMessageHandler, CollectionCreateDeckHandler>();
services.AddTransient<IMessageHandler, CollectionRenameDeckHandler>();
services.AddTransient<IMessageHandler, CollectionDeleteDeckHandler>();
services.AddTransient<IMessageHandler, CollectionAddCardHandler>();
services.AddTransient<IMessageHandler, CollectionRemoveCardHandler>();
return services;
}
}
+4 -3
View File
@@ -13,6 +13,7 @@
// ENABLED_SERVICES=gateway → run only Gateway (dedicated gateway pod)
using SOR.Auth;
using SOR.Collection;
using SOR.Gateway;
using SOR.Networking.Nats;
using SOR.Networking.Redis;
@@ -127,12 +128,12 @@ builder.Services.AddRedisClientPush();
// Each service registers its own handlers, options, DbContext, repositories, etc.
// Only services listed in ENABLED_SERVICES are started.
if (IsEnabled("auth")) builder.Services.AddAuthService(builder.Configuration);
if (IsEnabled("gateway")) builder.Services.AddGatewayService(builder.Configuration);
if (IsEnabled("auth")) builder.Services.AddAuthService(builder.Configuration);
if (IsEnabled("collection")) builder.Services.AddCollectionService(builder.Configuration);
if (IsEnabled("gateway")) builder.Services.AddGatewayService(builder.Configuration);
// TODO: Uncomment as each service is implemented:
// if (IsEnabled("chat")) builder.Services.AddChatService(builder.Configuration);
// if (IsEnabled("collection")) builder.Services.AddCollectionService(builder.Configuration);
// if (IsEnabled("bazaar")) builder.Services.AddBazaarService(builder.Configuration);
// if (IsEnabled("leaderboard")) builder.Services.AddLeaderboardService(builder.Configuration);
// if (IsEnabled("content")) builder.Services.AddContentService(builder.Configuration);
+1
View File
@@ -29,5 +29,6 @@
<ProjectReference Include="..\SOR.Networking.Redis\SOR.Networking.Redis.csproj" />
<ProjectReference Include="..\SOR.Gateway\SOR.Gateway.csproj" />
<ProjectReference Include="..\SOR.Auth\SOR.Auth.csproj" />
<ProjectReference Include="..\SOR.Collection\SOR.Collection.csproj" />
</ItemGroup>
</Project>