diff --git a/Server/src/SOR.Admin/Components/Pages/Bazaar/BoosterPackEditor.razor b/Server/src/SOR.Admin/Components/Pages/Bazaar/BoosterPackEditor.razor index 724f8b1..2517f2e 100644 --- a/Server/src/SOR.Admin/Components/Pages/Bazaar/BoosterPackEditor.razor +++ b/Server/src/SOR.Admin/Components/Pages/Bazaar/BoosterPackEditor.razor @@ -2,6 +2,7 @@ @page "/bazaar/packs/{Id:guid}" @attribute [Authorize(Roles = "Admin,SuperAdmin")] @inject BazaarDbContext Db +@inject CatalogDbContext CatalogDb @inject SOR.Cdn.ICdnClient Cdn @inject NavigationManager Nav @@ -38,7 +39,7 @@ else @if (_success) {
Saved successfully.
}
- +
Details
@@ -73,6 +74,20 @@ else
+ +
+ + +
@@ -100,53 +115,163 @@ else
Card Slots - +
+ + + + +
- Defines how many cards of each rarity drop per pack. When a player opens a pack, - the server draws randomly from cards matching each slot's rarity. + Each slot draws the specified number of cards when a player opens the pack. + Slots are resolved in order — earlier slots take priority in edge cases.
+ @if (_slots.Count == 0) { -

No slots defined yet.

+

No slots defined yet. Use the buttons above to add slots.

} else { - - - - - - @foreach (var slot in _slots) - { - var s = slot; - - - - - - } - -
RarityCount
- + cards + + } + + + +
+ @if (slot.Kind == SlotKind.Rarity) + { +
+
+ + +
+
+ + +
+
+ } + else if (slot.Kind == SlotKind.Specific) + { +
+
+ +
+ + +
+
+
+ + +
+
+ @if (!string.IsNullOrEmpty(slot.CardDisplayName)) { - +
+ + @slot.CardDisplayName + +
} - -
- - - -
-
+ else if (slot.CardResolveFailed) + { +
+ Card not found. +
+ } + } + else if (slot.Kind == SlotKind.RandomFromSet) + { +
+ + +
+ } + else if (slot.Kind == SlotKind.Random) + { +

+ Draws from all published cards across every set, any rarity. +

+ } +
+ + + +
+
+ } + + +
Total cards per pack: @_slots.Sum(s => s.Count)
} @@ -167,7 +292,7 @@ else else {
+ style="height:180px;background:var(--bs-body-bg)">
} @@ -193,6 +318,23 @@ else } + + +
+
Slot Types
+
+
+
Rarity
+
Draw N cards of a specific rarity. Optionally scoped to one set; falls back to the pack's default set.
+
Specific
+
Guarantees a specific card (by definition ID) appears in the pack. Count > 1 gives duplicates.
+
Set
+
Draw N random cards from a chosen set, ignoring rarity. Good for set-completion packs.
+
Random
+
Draw N fully random cards from all published cards across every set.
+
+
+
} @@ -201,24 +343,47 @@ else [Parameter] public Guid? Id { get; set; } private BoosterPack? _pack; - private bool _isNew; - private bool _saving; - private bool _uploadingImage; + private bool _isNew; + private bool _saving; + private bool _uploadingImage; private string? _error; - private bool _success; + private bool _success; private string? _usdInput; private string? _availableFrom; private string? _availableUntil; - private readonly List _slots = new(); + private string _defaultSetId = ""; // tracks _pack.CardSetId via string + + private readonly List _slots = new(); + private List<(Guid Id, string Name, string Code)> _cardSets = new(); + + // ── Slot model ─────────────────────────────────────────────────────────────── + + private enum SlotKind { Rarity, Specific, RandomFromSet, Random } private sealed class PackSlot { - public CardRarity Rarity { get; set; } = CardRarity.Common; - public int Count { get; set; } = 1; + public SlotKind Kind { get; set; } = SlotKind.Rarity; + public CardRarity Rarity { get; set; } = CardRarity.Common; + public int Count { get; set; } = 1; + // SetId stored as string for binding to select + public string SetIdStr { get; set; } = ""; + // Specific card + public string CardDefinitionIdStr { get; set; } = ""; + public string CardDisplayName { get; set; } = ""; + public bool CardResolveFailed { get; set; } } + // ── Lifecycle ──────────────────────────────────────────────────────────────── + protected override async Task OnInitializedAsync() { + _cardSets = await CatalogDb.CardSets + .Where(s => s.IsActive) + .OrderBy(s => s.Name) + .Select(s => new { s.Id, s.Name, s.Code }) + .ToListAsync() + .ContinueWith(t => t.Result.Select(s => (s.Id, s.Name, s.Code)).ToList()); + _isNew = Id == null; if (_isNew) { @@ -232,28 +397,88 @@ else _usdInput = _pack.UsdPrice?.ToString("F2"); _availableFrom = _pack.AvailableFrom?.LocalDateTime.ToString("yyyy-MM-ddTHH:mm"); _availableUntil = _pack.AvailableUntil?.LocalDateTime.ToString("yyyy-MM-ddTHH:mm"); + _defaultSetId = _pack.CardSetId?.ToString() ?? ""; ParseSlots(_pack.SlotsJson); } } } + // ── Slot helpers ───────────────────────────────────────────────────────────── + + private void AddSlot(SlotKind kind) => _slots.Add(new PackSlot { Kind = kind }); + + private void OnSpecificCardIdChanged(PackSlot slot, string? value) + { + slot.CardDefinitionIdStr = value ?? ""; + slot.CardDisplayName = ""; + slot.CardResolveFailed = false; + } + + private async Task ResolveCardNameAsync(PackSlot slot) + { + slot.CardDisplayName = ""; + slot.CardResolveFailed = false; + + if (!Guid.TryParse(slot.CardDefinitionIdStr, out var id)) { slot.CardResolveFailed = true; return; } + + var card = await CatalogDb.CardDefinitions + .Where(c => c.Id == id) + .Select(c => c.Name) + .FirstOrDefaultAsync(); + + if (card == null) slot.CardResolveFailed = true; + else slot.CardDisplayName = card; + } + + // ── Parse ──────────────────────────────────────────────────────────────────── + private void ParseSlots(string? json) { _slots.Clear(); if (string.IsNullOrWhiteSpace(json)) return; try { - var raw = System.Text.Json.JsonSerializer.Deserialize>(json); - if (raw != null) - _slots.AddRange(raw.Select(s => - new PackSlot { Rarity = s.Rarity, Count = s.Count })); + var arr = System.Text.Json.JsonSerializer.Deserialize>(json); + if (arr == null) return; + foreach (var el in arr) + { + // Detect new format (has "Kind") vs old format (just "Rarity"/"Count") + if (el.TryGetProperty("Kind", out var kindProp)) + { + var kindStr = kindProp.GetString() ?? "Rarity"; + var kind = Enum.TryParse(kindStr, out var k) ? k : SlotKind.Rarity; + var count = el.TryGetProperty("Count", out var cp) ? cp.GetInt32() : 1; + var slot = new PackSlot { Kind = kind, Count = count }; + + if (el.TryGetProperty("Rarity", out var rp) && + Enum.TryParse(rp.GetString(), out var rarity)) + slot.Rarity = rarity; + + if (el.TryGetProperty("SetId", out var sp) && sp.ValueKind != System.Text.Json.JsonValueKind.Null) + slot.SetIdStr = sp.GetString() ?? ""; + + if (el.TryGetProperty("CardDefinitionId", out var cp2) && + cp2.ValueKind != System.Text.Json.JsonValueKind.Null) + slot.CardDefinitionIdStr = cp2.GetString() ?? ""; + + _slots.Add(slot); + } + else + { + // Legacy format: {"rarity":"Common","count":5} + var slot = new PackSlot { Kind = SlotKind.Rarity }; + if (el.TryGetProperty("rarity", out var rp) && + Enum.TryParse(rp.GetString(), out var rarity)) + slot.Rarity = rarity; + slot.Count = el.TryGetProperty("count", out var cp) ? cp.GetInt32() : 1; + _slots.Add(slot); + } + } } - catch { /* malformed JSON — start fresh */ } + catch { /* malformed — start fresh */ } } - private record SlotDto(CardRarity Rarity, int Count); - - private void AddSlot() => _slots.Add(new PackSlot()); + // ── Save ───────────────────────────────────────────────────────────────────── private async Task SaveAsync() { @@ -266,13 +491,13 @@ else ? new DateTimeOffset(af, TimeZoneInfo.Local.GetUtcOffset(af)) : null; _pack.AvailableUntil = DateTime.TryParse(_availableUntil, out var au) ? new DateTimeOffset(au, TimeZoneInfo.Local.GetUtcOffset(au)) : null; - _pack.SlotsJson = _slots.Count > 0 - ? System.Text.Json.JsonSerializer.Serialize( - _slots.Select(s => new SlotDto(s.Rarity, s.Count))) - : null; - _pack.UpdatedAt = DateTimeOffset.UtcNow; + _pack.CardSetId = Guid.TryParse(_defaultSetId, out var sid) ? sid : null; + _pack.SlotsJson = SerializeSlots(); + _pack.UpdatedAt = DateTimeOffset.UtcNow; + if (_isNew) Db.BoosterPacks.Add(_pack); await Db.SaveChangesAsync(); + _success = true; if (_isNew) { _isNew = false; Nav.NavigateTo($"/bazaar/packs/{_pack.Id}", replace: true); } } @@ -280,6 +505,41 @@ else finally { _saving = false; } } + private string? SerializeSlots() + { + if (_slots.Count == 0) return null; + + var list = _slots.Select(s => + { + var obj = new System.Text.Json.Nodes.JsonObject + { + ["Kind"] = s.Kind.ToString(), + ["Count"] = s.Count, + }; + if (s.Kind == SlotKind.Rarity) + { + obj["Rarity"] = s.Rarity.ToString(); + if (!string.IsNullOrEmpty(s.SetIdStr)) + obj["SetId"] = s.SetIdStr; + } + else if (s.Kind == SlotKind.Specific) + { + if (!string.IsNullOrEmpty(s.CardDefinitionIdStr)) + obj["CardDefinitionId"] = s.CardDefinitionIdStr; + } + else if (s.Kind == SlotKind.RandomFromSet) + { + if (!string.IsNullOrEmpty(s.SetIdStr)) + obj["SetId"] = s.SetIdStr; + } + return (System.Text.Json.Nodes.JsonNode)obj; + }).ToList(); + + return new System.Text.Json.Nodes.JsonArray([.. list]).ToJsonString(); + } + + // ── Delete / Upload ────────────────────────────────────────────────────────── + private async Task DeleteAsync() { if (_pack == null || _isNew) return; @@ -298,12 +558,21 @@ else var folder = $"bazaar/packs/{_pack.Id}"; await using var stream = file.OpenReadStream(maxAllowedSize: 10 * 1024 * 1024); var result = await Cdn.UploadAsync(folder, file.Name, file.ContentType, stream); - if (result.Success) - _pack.ImageCdnUrl = result.PublicUrl; - else - _error = $"Upload failed: {result.Error}"; + if (result.Success) _pack.ImageCdnUrl = result.PublicUrl; + else _error = $"Upload failed: {result.Error}"; } catch (Exception ex) { _error = ex.Message; } finally { _uploadingImage = false; } } + + // ── UI helpers ─────────────────────────────────────────────────────────────── + + private static string KindBadge(SlotKind k) => k switch + { + SlotKind.Rarity => "bg-primary", + SlotKind.Specific => "bg-success", + SlotKind.RandomFromSet => "bg-info text-dark", + SlotKind.Random => "bg-secondary", + _ => "bg-secondary", + }; } diff --git a/Server/src/SOR.Bazaar/Handlers/BazaarBuyBoosterPackHandler.cs b/Server/src/SOR.Bazaar/Handlers/BazaarBuyBoosterPackHandler.cs index 40205d7..3d5cdd9 100644 --- a/Server/src/SOR.Bazaar/Handlers/BazaarBuyBoosterPackHandler.cs +++ b/Server/src/SOR.Bazaar/Handlers/BazaarBuyBoosterPackHandler.cs @@ -1,6 +1,7 @@ namespace SOR.Bazaar.Handlers; using Microsoft.EntityFrameworkCore; +using System.Text.Json; using SOR.Database.Contexts; using SOR.Database.Entities.Bazaar; using SOR.Database.Entities.Collection; @@ -11,10 +12,10 @@ using SOR.Shared.Networking; internal sealed class BazaarBuyBoosterPackHandler : BazaarHandlerBase, IMessageHandler { - private readonly IMessageSerializer _serializer; - private readonly BazaarDbContext _bazaarDb; - private readonly CollectionDbContext _collectionDb; - private readonly CatalogDbContext _catalogDb; + private readonly IMessageSerializer _serializer; + private readonly BazaarDbContext _bazaarDb; + private readonly CollectionDbContext _collectionDb; + private readonly CatalogDbContext _catalogDb; private readonly SorIdentityDbContext _identityDb; public string MessageType => "bazaar.buy_booster_pack"; @@ -62,56 +63,131 @@ internal sealed class BazaarBuyBoosterPackHandler : BazaarHandlerBase, IMessageH return ServerMessage.Error(message.Seq, "INSUFFICIENT_FUNDS", "You do not have enough Origin Points to purchase this pack."); - // ── Draw cards ──────────────────────────────────────────────────────── - List slots; + // ── Parse SlotsJson ─────────────────────────────────────────────────── + List rawSlots; try { - slots = System.Text.Json.JsonSerializer.Deserialize>(pack.SlotsJson) - ?? new List(); + rawSlots = JsonSerializer.Deserialize>(pack.SlotsJson) + ?? new List(); } catch { + // Refund before returning error + await CreditOriginPointsAsync(_identityDb, accountId, pack.OriginPointPrice, ct); return ServerMessage.Error(message.Seq, "PACK_NOT_CONFIGURED", "This pack has an invalid slot configuration."); } + // ── Draw cards per slot ─────────────────────────────────────────────── var grantedCards = new List<(PlayerCard card, string rarity, string name)>(); - foreach (var slot in slots) + foreach (var el in rawSlots) { - if (!Enum.TryParse(slot.Rarity, true, out var rarity)) - continue; + // Detect slot kind — new format has "Kind" key; legacy ("rarity"/"count") defaults to Rarity. + var kindStr = el.TryGetProperty("Kind", out var kp) ? kp.GetString() ?? "Rarity" : "Rarity"; - // Build pool query: rarity match + published + optional set scope - var poolQuery = _catalogDb.CardDefinitions - .Where(cd => cd.Rarity == rarity && cd.IsPublished); + // Count: new format uses "Count" (PascalCase); legacy uses "count" (lowercase). + var count = el.TryGetProperty("Count", out var cp) ? cp.GetInt32() + : el.TryGetProperty("count", out var cpl) ? cpl.GetInt32() + : 1; - if (pack.CardSetId.HasValue) - poolQuery = poolQuery.Where(cd => cd.SetId == pack.CardSetId.Value); - - // Random draw: pull all eligible IDs, then randomly pick server-side. - // For large pools this can be optimised with ORDER BY RANDOM() LIMIT n in raw SQL, - // but this approach is simple and correct for typical pool sizes. - var pool = await poolQuery - .Select(cd => new { cd.Id, cd.Name, cd.Rarity }) - .ToListAsync(ct); - - if (pool.Count == 0) continue; - - for (int i = 0; i < slot.Count; i++) + switch (kindStr) { - var pick = pool[Random.Shared.Next(pool.Count)]; - - var playerCard = new PlayerCard + // ── Rarity slot ────────────────────────────────────────────── + // New: {"Kind":"Rarity","Count":5,"Rarity":"Common","SetId":"..."} + // Legacy: {"rarity":"Common","count":5} + case "Rarity": { - AccountId = accountId, - CardDefinitionId = pick.Id, - AcquiredAt = now, - IsFoil = Random.Shared.NextDouble() < 0.05, // 5% foil chance - IsTradeable = true, - }; - _collectionDb.PlayerCards.Add(playerCard); - grantedCards.Add((playerCard, pick.Rarity.ToString(), pick.Name)); + string rarityStr; + if (el.TryGetProperty("Rarity", out var rp)) rarityStr = rp.GetString() ?? "Common"; + else if (el.TryGetProperty("rarity", out var rpl)) rarityStr = rpl.GetString() ?? "Common"; + else break; + + if (!Enum.TryParse(rarityStr, true, out var rarity)) break; + + // Set scope priority: slot-level SetId → pack default CardSetId → all sets (null) + Guid? setId = null; + if (el.TryGetProperty("SetId", out var sp) + && sp.ValueKind != JsonValueKind.Null + && Guid.TryParse(sp.GetString(), out var slotSetId)) + setId = slotSetId; + else if (pack.CardSetId.HasValue) + setId = pack.CardSetId; + + var q = _catalogDb.CardDefinitions.Where(cd => cd.Rarity == rarity && cd.IsPublished); + if (setId.HasValue) q = q.Where(cd => cd.SetId == setId.Value); + + var pool = await q.Select(cd => new { cd.Id, cd.Name, cd.Rarity }).ToListAsync(ct); + if (pool.Count == 0) break; + + for (int i = 0; i < count; i++) + { + var pick = pool[Random.Shared.Next(pool.Count)]; + grantedCards.Add(CreateAndTrackCard(accountId, now, pick.Id, pick.Rarity.ToString(), pick.Name)); + } + break; + } + + // ── Specific card slot ──────────────────────────────────────── + // {"Kind":"Specific","Count":1,"CardDefinitionId":""} + // Guarantees a specific card definition; Count > 1 gives duplicates. + case "Specific": + { + if (!el.TryGetProperty("CardDefinitionId", out var cdp)) break; + if (!Guid.TryParse(cdp.GetString(), out var defId)) break; + + var def = await _catalogDb.CardDefinitions + .Where(cd => cd.Id == defId && cd.IsPublished) + .Select(cd => new { cd.Id, cd.Name, cd.Rarity }) + .FirstOrDefaultAsync(ct); + if (def == null) break; + + for (int i = 0; i < count; i++) + grantedCards.Add(CreateAndTrackCard(accountId, now, def.Id, def.Rarity.ToString(), def.Name)); + + break; + } + + // ── Random-from-set slot ────────────────────────────────────── + // {"Kind":"RandomFromSet","Count":3,"SetId":""} + // Draws N cards from a given set, ignoring rarity. + case "RandomFromSet": + { + if (!el.TryGetProperty("SetId", out var sp)) break; + if (!Guid.TryParse(sp.GetString(), out var setId)) break; + + var pool = await _catalogDb.CardDefinitions + .Where(cd => cd.SetId == setId && cd.IsPublished) + .Select(cd => new { cd.Id, cd.Name, cd.Rarity }) + .ToListAsync(ct); + if (pool.Count == 0) break; + + for (int i = 0; i < count; i++) + { + var pick = pool[Random.Shared.Next(pool.Count)]; + grantedCards.Add(CreateAndTrackCard(accountId, now, pick.Id, pick.Rarity.ToString(), pick.Name)); + } + break; + } + + // ── Pure random slot ────────────────────────────────────────── + // {"Kind":"Random","Count":2} + // Draws N cards from all published cards across every set. + case "Random": + { + var pool = await _catalogDb.CardDefinitions + .Where(cd => cd.IsPublished) + .Select(cd => new { cd.Id, cd.Name, cd.Rarity }) + .ToListAsync(ct); + if (pool.Count == 0) break; + + for (int i = 0; i < count; i++) + { + var pick = pool[Random.Shared.Next(pool.Count)]; + grantedCards.Add(CreateAndTrackCard(accountId, now, pick.Id, pick.Rarity.ToString(), pick.Name)); + } + break; + } } } @@ -174,5 +250,20 @@ internal sealed class BazaarBuyBoosterPackHandler : BazaarHandlerBase, IMessageH new BuyBoosterPackResponse(purchase.Id, opened, newBalance)); } - private sealed record SlotEntry(string Rarity, int Count); + // ── Helpers ─────────────────────────────────────────────────────────────── + + private (PlayerCard card, string rarity, string name) CreateAndTrackCard( + Guid accountId, DateTimeOffset now, Guid defId, string rarity, string name) + { + var card = new PlayerCard + { + AccountId = accountId, + CardDefinitionId = defId, + AcquiredAt = now, + IsFoil = Random.Shared.NextDouble() < 0.05, // 5% foil chance + IsTradeable = true, + }; + _collectionDb.PlayerCards.Add(card); + return (card, rarity, name); + } }