Add chat service, collection clone/tier rules, social graph
SOR.Chat (new project):
- 10 WebSocket message handlers: send, get_channels, get_messages,
dm_open, friend_request, friend_respond, friend_remove, block,
unblock, get_social
- Cursor-based pagination for message history
- Block checks on DM send and dm_open
- Social graph: friends / pending requests (in+out) / blocked list
- Batch identity DB lookups for display names
Collection updates:
- clone_deck handler (copy deck + re-validate)
- Tier-chain validation: deck ArchSpirit must be Tier 1 (hard rule);
warn on Tier 2+ card without previous tier present (soft warning)
- Tier 2+ ArchSpirits now allowed in card list as ascension targets
- ValidationWarnings field added to DeckSummaryDto + DeckDetailDto
Database:
- CardDefinition.PreviousTierId self-reference FK for ascension chains
- FriendRequest + BlockedUser entities in chat schema
- ChatChannelType.System + FriendRequestStatus enum values
- Migrations: AddArchSpiritTierChain (catalog), AddSocialGraph (chat)
Admin portal:
- ChatOverview (/chat) — stats + channel list with type filter
- ChatChannelViewer (/chat/channel/{id}) — message history + system
message compose for admins
- SocialModerationPage (/chat/social) — friend/block lookup + actions
- NavMenu: Chat section with Social Graph sub-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:
@@ -45,6 +45,12 @@ public sealed record AddCardRequest(Guid DeckId, Guid CardDefinitionId, int Quan
|
||||
/// </summary>
|
||||
public sealed record RemoveCardRequest(Guid DeckId, Guid CardDefinitionId, int? Quantity = null);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a copy of an existing deck with a new name.
|
||||
/// Name defaults to "Copy of [original name]" if not provided.
|
||||
/// </summary>
|
||||
public sealed record CloneDeckRequest(Guid DeckId, string? Name = null);
|
||||
|
||||
// ── Response / DTO types (server → client) ────────────────────────────────────
|
||||
|
||||
public sealed record GetCardsResponse(
|
||||
@@ -75,7 +81,9 @@ public sealed record DeckSummaryDto(
|
||||
int CardCount,
|
||||
bool IsValid,
|
||||
DateTimeOffset CreatedAt,
|
||||
DateTimeOffset UpdatedAt);
|
||||
DateTimeOffset UpdatedAt,
|
||||
/// <summary>Non-blocking warnings about the deck composition (e.g. missing tier prerequisites).</summary>
|
||||
string[]? ValidationWarnings = null);
|
||||
|
||||
public sealed record GetDeckResponse(DeckDetailDto? Deck);
|
||||
|
||||
@@ -87,7 +95,8 @@ public sealed record DeckDetailDto(
|
||||
bool IsValid,
|
||||
DateTimeOffset CreatedAt,
|
||||
DateTimeOffset UpdatedAt,
|
||||
IEnumerable<DeckCardDto> Cards);
|
||||
IEnumerable<DeckCardDto> Cards,
|
||||
string[]? ValidationWarnings = null);
|
||||
|
||||
public sealed record DeckCardDto(
|
||||
Guid CardDefinitionId,
|
||||
|
||||
@@ -13,7 +13,8 @@ using SOR.Shared.Networking;
|
||||
///
|
||||
/// Validation:
|
||||
/// - Deck exists and belongs to the player.
|
||||
/// - CardDefinitionId must not be an ArchSpirit (those live at the deck level).
|
||||
/// - Tier 1 ArchSpirits are not allowed in the card list (they're the deck commander).
|
||||
/// - Tier 2+ ArchSpirits ARE allowed — they're ascension targets played during the match.
|
||||
/// - Player owns enough physical copies (existing + delta ≤ owned).
|
||||
/// - Adding would not push the definition over MaxCopiesPerCard.
|
||||
/// - Adding would not push the deck over MaxDeckSize.
|
||||
@@ -56,16 +57,21 @@ internal sealed class CollectionAddCardHandler : CollectionHandlerBase, IMessage
|
||||
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
|
||||
// ── Validate card type ─────────────────────────────────────────────────
|
||||
// Tier 1 ArchSpirits: deck commander, not added to card list.
|
||||
// Tier 2+ ArchSpirits: ascension targets, allowed in card list.
|
||||
var cardMeta = await _catalogDb.CardDefinitions
|
||||
.Where(cd => cd.Id == req.CardDefinitionId)
|
||||
.Select(cd => (CardType?)cd.CardType)
|
||||
.Select(cd => new { cd.CardType, cd.Tier })
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
if (cardType == null)
|
||||
|
||||
if (cardMeta == null)
|
||||
return ServerMessage.Error(message.Seq, "CARD_NOT_FOUND", "Card definition not found.");
|
||||
if (cardType == CardType.ArchSpirit)
|
||||
|
||||
if (cardMeta.CardType == CardType.ArchSpirit && (cardMeta.Tier ?? 1) == 1)
|
||||
return ServerMessage.Error(message.Seq, "ARCH_SPIRIT_NOT_ALLOWED",
|
||||
"ArchSpirit cards are set at the deck level, not in the card list.");
|
||||
"Tier 1 ArchSpirits are your deck commander — set them at the deck level. " +
|
||||
"Add a higher-tier version to the card list if you want to ascend during a match.");
|
||||
|
||||
// ── Copy-count checks ──────────────────────────────────────────────────
|
||||
var existingEntry = deck.Cards.FirstOrDefault(c => c.CardDefinitionId == req.CardDefinitionId);
|
||||
@@ -109,9 +115,8 @@ internal sealed class CollectionAddCardHandler : CollectionHandlerBase, IMessage
|
||||
deck.Cards.Add(entry);
|
||||
}
|
||||
|
||||
await RefreshValidityAsync(_collectionDb, deck, cancellationToken);
|
||||
var warnings = await RefreshValidityAsync(_collectionDb, _catalogDb, deck, cancellationToken);
|
||||
|
||||
// Return the updated deck summary.
|
||||
var archName = await _catalogDb.CardDefinitions
|
||||
.Where(cd => cd.Id == deck.ArchSpiritCardDefinitionId)
|
||||
.Select(cd => cd.Name)
|
||||
@@ -125,7 +130,8 @@ internal sealed class CollectionAddCardHandler : CollectionHandlerBase, IMessage
|
||||
CardCount: deck.Cards.Sum(c => c.Quantity),
|
||||
IsValid: deck.IsValid,
|
||||
CreatedAt: deck.CreatedAt,
|
||||
UpdatedAt: deck.UpdatedAt);
|
||||
UpdatedAt: deck.UpdatedAt,
|
||||
ValidationWarnings: warnings.Length > 0 ? warnings : null);
|
||||
|
||||
return ServerMessage.Reply("collection.add_card.ack", message.Seq,
|
||||
new DeckMutationResponse(summary));
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
namespace SOR.Collection.Handlers;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Entities.Collection;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// collection.clone_deck — creates an exact copy of an existing deck.
|
||||
///
|
||||
/// Useful for experimenting with small changes without losing the original.
|
||||
/// The clone's name defaults to "Copy of [original name]" if not specified.
|
||||
/// </summary>
|
||||
internal sealed class CollectionCloneDeckHandler : CollectionHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly CollectionDbContext _collectionDb;
|
||||
private readonly CatalogDbContext _catalogDb;
|
||||
|
||||
public CollectionCloneDeckHandler(
|
||||
IMessageSerializer serializer,
|
||||
CollectionDbContext collectionDb,
|
||||
CatalogDbContext catalogDb)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_collectionDb = collectionDb;
|
||||
_catalogDb = catalogDb;
|
||||
}
|
||||
|
||||
public string MessageType => "collection.clone_deck";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<CloneDeckRequest>(message.Payload);
|
||||
var accountId = Guid.Parse(connection.UserId);
|
||||
|
||||
// ── Load original ──────────────────────────────────────────────────────
|
||||
var original = await _collectionDb.Decks
|
||||
.Include(d => d.Cards)
|
||||
.FirstOrDefaultAsync(
|
||||
d => d.Id == req.DeckId && d.AccountId == accountId,
|
||||
cancellationToken);
|
||||
if (original == null)
|
||||
return ServerMessage.Error(message.Seq, "DECK_NOT_FOUND", "Deck not found.");
|
||||
|
||||
// ── 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.");
|
||||
|
||||
// ── Resolve name ───────────────────────────────────────────────────────
|
||||
string newName = string.IsNullOrWhiteSpace(req.Name)
|
||||
? $"Copy of {original.Name}"
|
||||
: req.Name.Trim();
|
||||
|
||||
if (newName.Length > 50)
|
||||
return ServerMessage.Error(message.Seq, "INVALID_NAME",
|
||||
"Deck name must be 1-50 characters.");
|
||||
|
||||
// ── Create clone ───────────────────────────────────────────────────────
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var clone = new Deck
|
||||
{
|
||||
AccountId = accountId,
|
||||
Name = newName,
|
||||
ArchSpiritCardDefinitionId = original.ArchSpiritCardDefinitionId,
|
||||
IsValid = original.IsValid,
|
||||
CreatedAt = now,
|
||||
UpdatedAt = now,
|
||||
};
|
||||
_collectionDb.Decks.Add(clone);
|
||||
await _collectionDb.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// Copy all DeckCard rows.
|
||||
foreach (var card in original.Cards)
|
||||
{
|
||||
_collectionDb.DeckCards.Add(new DeckCard
|
||||
{
|
||||
DeckId = clone.Id,
|
||||
CardDefinitionId = card.CardDefinitionId,
|
||||
Quantity = card.Quantity,
|
||||
});
|
||||
}
|
||||
await _collectionDb.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// Revalidate the clone (ownership/validity may have changed since original was built).
|
||||
var warnings = await RefreshValidityAsync(_collectionDb, _catalogDb, clone, cancellationToken);
|
||||
|
||||
var archName = await _catalogDb.CardDefinitions
|
||||
.Where(cd => cd.Id == clone.ArchSpiritCardDefinitionId)
|
||||
.Select(cd => cd.Name)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
var summary = new DeckSummaryDto(
|
||||
Id: clone.Id,
|
||||
Name: clone.Name,
|
||||
ArchSpiritCardDefinitionId: clone.ArchSpiritCardDefinitionId,
|
||||
ArchSpiritName: archName,
|
||||
CardCount: original.Cards.Sum(c => c.Quantity),
|
||||
IsValid: clone.IsValid,
|
||||
CreatedAt: clone.CreatedAt,
|
||||
UpdatedAt: clone.UpdatedAt,
|
||||
ValidationWarnings: warnings.Length > 0 ? warnings : null);
|
||||
|
||||
return ServerMessage.Reply("collection.clone_deck.ack", message.Seq,
|
||||
new DeckMutationResponse(summary));
|
||||
}
|
||||
}
|
||||
@@ -7,14 +7,9 @@ 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,
|
||||
@@ -29,18 +24,11 @@ internal abstract class CollectionHandlerBase
|
||||
.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,
|
||||
@@ -58,11 +46,21 @@ internal abstract class CollectionHandlerBase
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recomputes and saves Deck.IsValid based on current cards and ownership.
|
||||
/// Should be called after any add/remove card mutation.
|
||||
/// Recomputes Deck.IsValid and returns any non-blocking validation warnings.
|
||||
///
|
||||
/// Hard rules (affect IsValid = false):
|
||||
/// - Non-ArchSpirit card count must be MinDeckSize..MaxDeckSize
|
||||
/// - No definition may appear more than MaxCopiesPerCard times
|
||||
/// - Player must own enough copies of every card in the list
|
||||
/// - The deck's primary ArchSpirit must be Tier 1
|
||||
///
|
||||
/// Soft warnings (returned but do NOT affect IsValid):
|
||||
/// - A Tier 2+ ArchSpirit in the card list is missing its previous-tier prerequisite.
|
||||
/// Common when players are testing with small changes. Deck is still legal.
|
||||
/// </summary>
|
||||
protected static async Task RefreshValidityAsync(
|
||||
protected static async Task<string[]> RefreshValidityAsync(
|
||||
CollectionDbContext collectionDb,
|
||||
CatalogDbContext catalogDb,
|
||||
Database.Entities.Collection.Deck deck,
|
||||
CancellationToken ct)
|
||||
{
|
||||
@@ -76,16 +74,67 @@ internal abstract class CollectionHandlerBase
|
||||
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);
|
||||
int total = cards.Sum(c => c.Quantity);
|
||||
bool sizeValid = total >= DeckRules.MinDeckSize && total <= DeckRules.MaxDeckSize;
|
||||
bool copiesValid = cards.All(c =>
|
||||
c.Quantity <= DeckRules.MaxCopiesPerCard &&
|
||||
ownedCounts.GetValueOrDefault(c.CardDefinitionId) >= c.Quantity);
|
||||
|
||||
deck.IsValid = valid;
|
||||
deck.UpdatedAt = DateTimeOffset.UtcNow;
|
||||
// Hard rule: primary ArchSpirit must be Tier 1.
|
||||
var primaryTier = await catalogDb.CardDefinitions
|
||||
.Where(cd => cd.Id == deck.ArchSpiritCardDefinitionId)
|
||||
.Select(cd => cd.Tier)
|
||||
.FirstOrDefaultAsync(ct);
|
||||
bool primaryIsT1 = primaryTier == 1;
|
||||
|
||||
// Soft warning: check tier-chain gaps for higher-tier ArchSpirits in the card list.
|
||||
var warnings = new List<string>();
|
||||
if (cards.Count > 0)
|
||||
{
|
||||
var defIds = cards.Select(c => c.CardDefinitionId).Distinct().ToList();
|
||||
|
||||
var archCardsInDeck = await catalogDb.CardDefinitions
|
||||
.Where(cd => defIds.Contains(cd.Id) && cd.CardType == CardType.ArchSpirit)
|
||||
.Select(cd => new { cd.Id, cd.Name, cd.Tier, cd.PreviousTierId })
|
||||
.ToListAsync(ct);
|
||||
|
||||
if (archCardsInDeck.Count > 0)
|
||||
{
|
||||
var presentArchIds = new HashSet<Guid>(archCardsInDeck.Select(a => a.Id))
|
||||
{
|
||||
deck.ArchSpiritCardDefinitionId
|
||||
};
|
||||
|
||||
var gapped = archCardsInDeck
|
||||
.Where(a => a.Tier > 1 && a.PreviousTierId.HasValue
|
||||
&& !presentArchIds.Contains(a.PreviousTierId.Value))
|
||||
.ToList();
|
||||
|
||||
if (gapped.Count > 0)
|
||||
{
|
||||
var prevIds = gapped.Select(g => g.PreviousTierId!.Value).Distinct().ToList();
|
||||
var prevNames = await catalogDb.CardDefinitions
|
||||
.Where(cd => prevIds.Contains(cd.Id))
|
||||
.ToDictionaryAsync(cd => cd.Id, cd => cd.Name, ct);
|
||||
|
||||
foreach (var g in gapped)
|
||||
{
|
||||
var prevName = g.PreviousTierId.HasValue
|
||||
? prevNames.GetValueOrDefault(g.PreviousTierId.Value,
|
||||
$"Tier {g.Tier - 1} prerequisite")
|
||||
: $"Tier {g.Tier - 1} prerequisite";
|
||||
warnings.Add(
|
||||
$"{g.Name} (Tier {g.Tier}) is in the deck but {prevName} is missing. " +
|
||||
"It cannot ascend in-game without its previous tier.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
deck.IsValid = sizeValid && copiesValid && primaryIsT1;
|
||||
deck.UpdatedAt = DateTimeOffset.UtcNow;
|
||||
await collectionDb.SaveChangesAsync(ct);
|
||||
|
||||
return warnings.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ internal sealed class CollectionRemoveCardHandler : CollectionHandlerBase, IMess
|
||||
entry.Quantity -= toRemove;
|
||||
}
|
||||
|
||||
await RefreshValidityAsync(_collectionDb, deck, cancellationToken);
|
||||
var warnings = await RefreshValidityAsync(_collectionDb, _catalogDb, deck, cancellationToken);
|
||||
|
||||
var archName = await _catalogDb.CardDefinitions
|
||||
.Where(cd => cd.Id == deck.ArchSpiritCardDefinitionId)
|
||||
@@ -79,7 +79,8 @@ internal sealed class CollectionRemoveCardHandler : CollectionHandlerBase, IMess
|
||||
CardCount: deck.Cards.Sum(c => c.Quantity),
|
||||
IsValid: deck.IsValid,
|
||||
CreatedAt: deck.CreatedAt,
|
||||
UpdatedAt: deck.UpdatedAt);
|
||||
UpdatedAt: deck.UpdatedAt,
|
||||
ValidationWarnings: warnings.Length > 0 ? warnings : null);
|
||||
|
||||
return ServerMessage.Reply("collection.remove_card.ack", message.Seq,
|
||||
new DeckMutationResponse(summary));
|
||||
|
||||
@@ -30,6 +30,7 @@ public static class ServiceRegistration
|
||||
services.AddTransient<IMessageHandler, CollectionDeleteDeckHandler>();
|
||||
services.AddTransient<IMessageHandler, CollectionAddCardHandler>();
|
||||
services.AddTransient<IMessageHandler, CollectionRemoveCardHandler>();
|
||||
services.AddTransient<IMessageHandler, CollectionCloneDeckHandler>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user