Extend booster pack slot system — 4 slot kinds + handler support
BoosterPackEditor.razor: - New SlotKind enum: Rarity, Specific, RandomFromSet, Random - Pack-level default CardSet picker (maps to BoosterPack.CardSetId) - Per-slot UI: Rarity (rarity + set override), Specific (card GUID + name resolve), RandomFromSet (set dropdown), Random (any published card) - Backwards-compatible SlotsJson parse (detects legacy lowercase format) - Slot legend card explaining all 4 types BazaarBuyBoosterPackHandler.cs: - Replace old SlotEntry record with JsonElement-based parsing - Rarity slots: slot-level SetId → pack.CardSetId → all sets - Specific slots: guarantee exact CardDefinitionId (Count ≥ 1 for duplicates) - RandomFromSet slots: random from a given set, no rarity filter - Random slots: random from all published cards - Refund OriginPoints on bad SlotsJson before returning error - Extract CreateAndTrackCard helper to deduplicate PlayerCard creation 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:
@@ -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) { <div class="alert alert-success">Saved successfully.</div> }
|
||||
|
||||
<div class="row g-4">
|
||||
<!-- Left column: identity + pricing -->
|
||||
<!-- Left column: identity + pricing + slots -->
|
||||
<div class="col-lg-7">
|
||||
<div class="card shadow-sm mb-4">
|
||||
<div class="card-header fw-medium">Details</div>
|
||||
@@ -73,6 +74,20 @@ else
|
||||
<label class="form-check-label fw-medium" for="chkActive">Active</label>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Default set for rarity slots -->
|
||||
<div class="col-12">
|
||||
<label class="form-label">
|
||||
Default Card Set
|
||||
<small class="text-muted ms-1">— used by Rarity slots that don't specify their own set</small>
|
||||
</label>
|
||||
<select @bind="_defaultSetId" class="form-select">
|
||||
<option value="">— All Sets (no restriction) —</option>
|
||||
@foreach (var s in _cardSets)
|
||||
{
|
||||
<option value="@s.Id">@s.Name (@s.Code)</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -100,53 +115,163 @@ else
|
||||
<div class="card shadow-sm">
|
||||
<div class="card-header fw-medium d-flex justify-content-between align-items-center">
|
||||
<span>Card Slots</span>
|
||||
<button class="btn btn-sm btn-outline-secondary" @onclick="AddSlot">
|
||||
<i class="bi bi-plus-lg me-1"></i>Add Slot
|
||||
</button>
|
||||
<div class="d-flex gap-1">
|
||||
<button class="btn btn-sm btn-outline-secondary" @onclick='() => AddSlot(SlotKind.Rarity)'
|
||||
title="Rarity slot — draw N cards of a given rarity">
|
||||
<i class="bi bi-plus-lg me-1"></i>Rarity
|
||||
</button>
|
||||
<button class="btn btn-sm btn-outline-secondary" @onclick='() => AddSlot(SlotKind.Specific)'
|
||||
title="Specific card — guarantees a specific card definition">
|
||||
<i class="bi bi-plus-lg me-1"></i>Specific
|
||||
</button>
|
||||
<button class="btn btn-sm btn-outline-secondary" @onclick='() => AddSlot(SlotKind.RandomFromSet)'
|
||||
title="Random from set — draw N cards from a set (any rarity)">
|
||||
<i class="bi bi-plus-lg me-1"></i>Set
|
||||
</button>
|
||||
<button class="btn btn-sm btn-outline-secondary" @onclick='() => AddSlot(SlotKind.Random)'
|
||||
title="Pure random — draw N cards from anywhere">
|
||||
<i class="bi bi-plus-lg me-1"></i>Random
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="form-text mb-3">
|
||||
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.
|
||||
</div>
|
||||
|
||||
@if (_slots.Count == 0)
|
||||
{
|
||||
<p class="text-muted small">No slots defined yet.</p>
|
||||
<p class="text-muted small">No slots defined yet. Use the buttons above to add slots.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<table class="table table-sm">
|
||||
<thead>
|
||||
<tr><th>Rarity</th><th style="width:100px">Count</th><th style="width:50px"></th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var slot in _slots)
|
||||
{
|
||||
var s = slot;
|
||||
<tr>
|
||||
<td>
|
||||
<select @bind="s.Rarity" class="form-select form-select-sm">
|
||||
@foreach (var r in Enum.GetValues<CardRarity>())
|
||||
<div class="d-flex flex-column gap-2">
|
||||
@for (int si = 0; si < _slots.Count; si++)
|
||||
{
|
||||
var sidx = si;
|
||||
var slot = _slots[sidx];
|
||||
|
||||
<div class="border rounded p-2">
|
||||
<div class="d-flex gap-2 align-items-start">
|
||||
<!-- Kind badge + count -->
|
||||
<div class="d-flex flex-column gap-1" style="min-width:110px">
|
||||
<span class="badge @KindBadge(slot.Kind) text-uppercase small">@slot.Kind</span>
|
||||
@if (slot.Kind != SlotKind.Specific)
|
||||
{
|
||||
<div class="d-flex align-items-center gap-1">
|
||||
<label class="form-label small mb-0 text-nowrap">×</label>
|
||||
<input type="number" min="1" max="99"
|
||||
class="form-control form-control-sm"
|
||||
style="width:65px"
|
||||
@bind="slot.Count" />
|
||||
<span class="text-muted small">cards</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<!-- Kind-specific fields -->
|
||||
<div class="flex-grow-1">
|
||||
@if (slot.Kind == SlotKind.Rarity)
|
||||
{
|
||||
<div class="row g-2">
|
||||
<div class="col-auto">
|
||||
<label class="form-label small mb-0">Rarity</label>
|
||||
<select @bind="slot.Rarity" class="form-select form-select-sm">
|
||||
@foreach (var r in Enum.GetValues<CardRarity>())
|
||||
{
|
||||
<option value="@r">@r</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col">
|
||||
<label class="form-label small mb-0">
|
||||
Set Override
|
||||
<span class="text-muted">(blank = use pack default)</span>
|
||||
</label>
|
||||
<select @bind="slot.SetIdStr" class="form-select form-select-sm">
|
||||
<option value="">— Pack default —</option>
|
||||
@foreach (var s in _cardSets)
|
||||
{
|
||||
<option value="@s.Id">@s.Name (@s.Code)</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
else if (slot.Kind == SlotKind.Specific)
|
||||
{
|
||||
<div class="row g-2 align-items-end">
|
||||
<div class="col">
|
||||
<label class="form-label small mb-0">Card Definition ID</label>
|
||||
<div class="input-group input-group-sm">
|
||||
<input class="form-control font-monospace"
|
||||
placeholder="paste card definition GUID"
|
||||
value="@slot.CardDefinitionIdStr"
|
||||
@onchange="e => OnSpecificCardIdChanged(slot, e.Value?.ToString())" />
|
||||
<button class="btn btn-outline-secondary"
|
||||
type="button"
|
||||
@onclick="() => ResolveCardNameAsync(slot)"
|
||||
title="Look up card name">
|
||||
<i class="bi bi-search"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-auto">
|
||||
<label class="form-label small mb-0">Count</label>
|
||||
<input type="number" min="1" max="10"
|
||||
class="form-control form-control-sm"
|
||||
style="width:70px"
|
||||
@bind="slot.Count" />
|
||||
</div>
|
||||
</div>
|
||||
@if (!string.IsNullOrEmpty(slot.CardDisplayName))
|
||||
{
|
||||
<option value="@r">@r</option>
|
||||
<div class="mt-1">
|
||||
<span class="badge bg-success">
|
||||
<i class="bi bi-check me-1"></i>@slot.CardDisplayName
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
</select>
|
||||
</td>
|
||||
<td>
|
||||
<input @bind="s.Count" type="number" min="1"
|
||||
class="form-control form-control-sm" />
|
||||
</td>
|
||||
<td>
|
||||
<button class="btn btn-sm btn-outline-danger"
|
||||
@onclick="() => _slots.Remove(s)">
|
||||
<i class="bi bi-trash"></i>
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="text-muted small">
|
||||
else if (slot.CardResolveFailed)
|
||||
{
|
||||
<div class="text-danger small mt-1">
|
||||
<i class="bi bi-exclamation-circle me-1"></i>Card not found.
|
||||
</div>
|
||||
}
|
||||
}
|
||||
else if (slot.Kind == SlotKind.RandomFromSet)
|
||||
{
|
||||
<div>
|
||||
<label class="form-label small mb-0">Set <span class="text-danger">*</span></label>
|
||||
<select @bind="slot.SetIdStr" class="form-select form-select-sm">
|
||||
<option value="">— select a set —</option>
|
||||
@foreach (var s in _cardSets)
|
||||
{
|
||||
<option value="@s.Id">@s.Name (@s.Code)</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
}
|
||||
else if (slot.Kind == SlotKind.Random)
|
||||
{
|
||||
<p class="text-muted small mb-0 mt-1">
|
||||
Draws from all published cards across every set, any rarity.
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
|
||||
<!-- Remove -->
|
||||
<button class="btn btn-sm btn-outline-danger"
|
||||
@onclick="() => _slots.RemoveAt(sidx)">
|
||||
<i class="bi bi-trash"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="text-muted small mt-3">
|
||||
Total cards per pack: <strong>@_slots.Sum(s => s.Count)</strong>
|
||||
</div>
|
||||
}
|
||||
@@ -167,7 +292,7 @@ else
|
||||
else
|
||||
{
|
||||
<div class="border rounded d-flex align-items-center justify-content-center mb-3"
|
||||
style="height:180px;background:#f8f9fa">
|
||||
style="height:180px;background:var(--bs-body-bg)">
|
||||
<span class="text-muted"><i class="bi bi-image fs-1"></i></span>
|
||||
</div>
|
||||
}
|
||||
@@ -193,6 +318,23 @@ else
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Slot legend -->
|
||||
<div class="card shadow-sm mt-4">
|
||||
<div class="card-header fw-medium">Slot Types</div>
|
||||
<div class="card-body small">
|
||||
<dl class="row mb-0">
|
||||
<dt class="col-4"><span class="badge bg-primary">Rarity</span></dt>
|
||||
<dd class="col-8 text-muted">Draw N cards of a specific rarity. Optionally scoped to one set; falls back to the pack's default set.</dd>
|
||||
<dt class="col-4"><span class="badge bg-success">Specific</span></dt>
|
||||
<dd class="col-8 text-muted">Guarantees a specific card (by definition ID) appears in the pack. Count > 1 gives duplicates.</dd>
|
||||
<dt class="col-4"><span class="badge bg-info text-dark">Set</span></dt>
|
||||
<dd class="col-8 text-muted">Draw N random cards from a chosen set, ignoring rarity. Good for set-completion packs.</dd>
|
||||
<dt class="col-4"><span class="badge bg-secondary">Random</span></dt>
|
||||
<dd class="col-8 text-muted">Draw N fully random cards from all published cards across every set.</dd>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@@ -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<PackSlot> _slots = new();
|
||||
private string _defaultSetId = ""; // tracks _pack.CardSetId via string
|
||||
|
||||
private readonly List<PackSlot> _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<List<SlotDto>>(json);
|
||||
if (raw != null)
|
||||
_slots.AddRange(raw.Select(s =>
|
||||
new PackSlot { Rarity = s.Rarity, Count = s.Count }));
|
||||
var arr = System.Text.Json.JsonSerializer.Deserialize<List<System.Text.Json.JsonElement>>(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<SlotKind>(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<CardRarity>(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<CardRarity>(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",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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<SlotEntry> slots;
|
||||
// ── Parse SlotsJson ───────────────────────────────────────────────────
|
||||
List<JsonElement> rawSlots;
|
||||
try
|
||||
{
|
||||
slots = System.Text.Json.JsonSerializer.Deserialize<List<SlotEntry>>(pack.SlotsJson)
|
||||
?? new List<SlotEntry>();
|
||||
rawSlots = JsonSerializer.Deserialize<List<JsonElement>>(pack.SlotsJson)
|
||||
?? new List<JsonElement>();
|
||||
}
|
||||
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<CardRarity>(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<CardRarity>(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":"<guid>"}
|
||||
// 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":"<guid>"}
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user