Add SOR.Bazaar service — store, P2P marketplace, auction house, cosmetics

New project: SOR.Bazaar (12 message handlers)
  Store:       get_store, buy_booster_pack, buy_prebuilt_deck, buy_cosmetic, get_my_balance
  Marketplace: get_listings, get_my_listings, list_card, cancel_listing,
               buy_listing (shared-tx atomicity), place_bid (shared-tx + refund),
               get_transactions

New DB entities:
  BazaarDb:    Cosmetic, PurchaseRecord, BoosterPackCardGrant, AuctionBid
  CollectionDb: PlayerCosmetic
  IdentityDb:  Account.OriginPoints

BoosterPack gets CardSetId for set-scoped card pool draws.
BazaarEnums: PurchaseProductType, CosmeticType.

3 EF migrations applied to pg-forge-01:
  AddOriginPoints, AddBazaarCosmetics, AddPlayerCosmetics

Admin pages: CosmeticsPage, CosmeticEditor, PurchaseRecordsPage (with
  expandable booster pack card grant rows), NavMenu Bazaar submenu updates.

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 19:02:59 -05:00
co-authored by Claude Happy
parent 2cac55cbd9
commit 348c37b9b5
42 changed files with 4127 additions and 10 deletions
+1
View File
@@ -2,6 +2,7 @@
<Folder Name="/src/">
<Project Path="src/SOR.Admin/SOR.Admin.csproj" />
<Project Path="src/SOR.Auth/SOR.Auth.csproj" />
<Project Path="src/SOR.Bazaar/SOR.Bazaar.csproj" />
<Project Path="src/SOR.Cdn/SOR.Cdn.csproj" />
<Project Path="src/SOR.Chat/SOR.Chat.csproj" />
<Project Path="src/SOR.Collection/SOR.Collection.csproj" />
@@ -39,6 +39,16 @@
<i class="bi bi-stack me-2"></i>Prebuilt Decks
</NavLink>
</li>
<li class="nav-item">
<NavLink class="nav-link text-white-50 py-1" href="/bazaar/cosmetics">
<i class="bi bi-stars me-2"></i>Cosmetics
</NavLink>
</li>
<li class="nav-item">
<NavLink class="nav-link text-white-50 py-1" href="/bazaar/purchases">
<i class="bi bi-receipt me-2"></i>Purchases
</NavLink>
</li>
</ul>
</li>
<li class="nav-item">
@@ -0,0 +1,238 @@
@page "/bazaar/cosmetics/new"
@page "/bazaar/cosmetics/{Id:guid}"
@attribute [Authorize(Roles = "Admin,SuperAdmin")]
@using Microsoft.EntityFrameworkCore
@using SOR.Database.Contexts
@using SOR.Database.Entities.Bazaar
@using SOR.Database.Enums
@inject BazaarDbContext Db
@inject CatalogDbContext CatalogDb
@inject SOR.Cdn.ICdnClient Cdn
@inject NavigationManager Nav
<PageTitle>@(IsNew ? "New Cosmetic" : "Edit Cosmetic") – SOR Admin</PageTitle>
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="mb-0">@(IsNew ? "New Cosmetic" : "Edit Cosmetic")</h1>
<a href="/bazaar/cosmetics" class="btn btn-outline-secondary btn-sm">
<i class="bi bi-arrow-left me-1"></i>Back
</a>
</div>
@if (_cosmetic is null)
{
<p class="text-muted">Loading…</p>
}
else
{
<div class="row g-4">
<div class="col-md-7">
<div class="card shadow-sm">
<div class="card-header fw-medium">Details</div>
<div class="card-body">
<div class="mb-3">
<label class="form-label fw-medium">Name</label>
<input @bind="_cosmetic.Name" class="form-control" placeholder="e.g. Ember Card Back" />
</div>
<div class="mb-3">
<label class="form-label fw-medium">Description</label>
<textarea @bind="_cosmetic.Description" class="form-control" rows="2"
placeholder="Optional description shown in the store." />
</div>
<div class="row g-3 mb-3">
<div class="col-md-6">
<label class="form-label fw-medium">Type</label>
<select @bind="_cosmeticTypeStr" class="form-select">
@foreach (var t in Enum.GetNames<CosmeticType>())
{
<option value="@t">@t</option>
}
</select>
</div>
@if (_cosmetic.CosmeticType != CosmeticType.CardBack)
{
<div class="col-md-6">
<label class="form-label fw-medium">Card (optional)</label>
<input @bind="_cardDefinitionIdStr"
class="form-control font-monospace"
placeholder="Card Definition GUID" />
</div>
}
</div>
<div class="row g-3 mb-3">
<div class="col-md-6">
<label class="form-label fw-medium">Origin Point Price</label>
<input @bind="_cosmetic.OriginPointPrice" type="number"
class="form-control" min="0" />
</div>
<div class="col-md-6">
<label class="form-label fw-medium">USD Price (optional)</label>
<input @bind="_cosmetic.UsdPrice" type="number"
class="form-control" step="0.01" min="0"
placeholder="Leave blank for OP-only" />
</div>
</div>
<div class="form-check mb-3">
<input @bind="_cosmetic.IsActive" type="checkbox"
class="form-check-input" id="chkActive" />
<label class="form-check-label fw-medium" for="chkActive">Active</label>
</div>
</div>
</div>
</div>
<div class="col-md-5">
<!-- Preview Image -->
<div class="card shadow-sm mb-3">
<div class="card-header fw-medium">Preview Image (thumbnail)</div>
<div class="card-body">
@if (!string.IsNullOrEmpty(_cosmetic.PreviewImageCdnUrl))
{
<img src="@_cosmetic.PreviewImageCdnUrl"
class="img-fluid rounded mb-2"
alt="Preview" style="max-height:120px" />
}
<input @bind="_cosmetic.PreviewImageCdnUrl"
class="form-control form-control-sm mb-2"
placeholder="https://cdn.sor.gg/…" />
<label class="btn btn-sm btn-outline-primary @(_uploadingPreview ? "disabled" : "")">
@if (_uploadingPreview) { <span class="spinner-border spinner-border-sm"></span> }
else { <i class="bi bi-upload"></i> }
<span class="ms-1">Upload</span>
<InputFile style="display:none" accept="image/*"
OnChange="UploadPreviewAsync" />
</label>
</div>
</div>
<!-- Asset -->
<div class="card shadow-sm">
<div class="card-header fw-medium">Asset URL (art / model)</div>
<div class="card-body">
<input @bind="_cosmetic.AssetCdnUrl"
class="form-control form-control-sm mb-2"
placeholder="https://cdn.sor.gg/…" />
<label class="btn btn-sm btn-outline-primary @(_uploadingAsset ? "disabled" : "")">
@if (_uploadingAsset) { <span class="spinner-border spinner-border-sm"></span> }
else { <i class="bi bi-upload"></i> }
<span class="ms-1">Upload</span>
<InputFile style="display:none"
accept="image/*,.glb,.gltf,.fbx"
OnChange="UploadAssetAsync" />
</label>
</div>
</div>
</div>
</div>
@if (!string.IsNullOrEmpty(_error))
{
<div class="alert alert-danger mt-3">@_error</div>
}
<div class="mt-4 d-flex gap-2">
<button class="btn btn-primary" @onclick="SaveAsync" disabled="@_saving">
@if (_saving) { <span class="spinner-border spinner-border-sm me-1"></span> }
Save
</button>
@if (!IsNew)
{
<button class="btn btn-outline-danger" @onclick="DeleteAsync">
<i class="bi bi-trash me-1"></i>Delete
</button>
}
</div>
}
@code {
[Parameter] public Guid? Id { get; set; }
private bool IsNew => !Id.HasValue;
private Cosmetic? _cosmetic;
private string _cosmeticTypeStr = nameof(CosmeticType.CardBack);
private string _cardDefinitionIdStr = string.Empty;
private bool _saving, _uploadingPreview, _uploadingAsset;
private string? _error;
protected override async Task OnInitializedAsync()
{
if (IsNew)
{
_cosmetic = new Cosmetic { CreatedAt = DateTimeOffset.UtcNow, UpdatedAt = DateTimeOffset.UtcNow };
}
else
{
_cosmetic = await Db.Cosmetics.FirstOrDefaultAsync(c => c.Id == Id!.Value);
if (_cosmetic is null) { Nav.NavigateTo("/bazaar/cosmetics"); return; }
_cosmeticTypeStr = _cosmetic.CosmeticType.ToString();
_cardDefinitionIdStr = _cosmetic.CardDefinitionId?.ToString() ?? string.Empty;
}
}
private async Task UploadPreviewAsync(InputFileChangeEventArgs e)
{
_uploadingPreview = true;
_error = null;
try
{
await using var stream = e.File.OpenReadStream(maxAllowedSize: 10 * 1024 * 1024);
var result = await Cdn.UploadAsync("cosmetics/previews", e.File.Name, e.File.ContentType, stream);
_cosmetic!.PreviewImageCdnUrl = result.PublicUrl ?? string.Empty;
}
catch (Exception ex) { _error = $"Upload failed: {ex.Message}"; }
finally { _uploadingPreview = false; }
}
private async Task UploadAssetAsync(InputFileChangeEventArgs e)
{
_uploadingAsset = true;
_error = null;
try
{
await using var stream = e.File.OpenReadStream(maxAllowedSize: 50 * 1024 * 1024);
var result = await Cdn.UploadAsync("cosmetics/assets", e.File.Name, e.File.ContentType, stream);
_cosmetic!.AssetCdnUrl = result.PublicUrl ?? string.Empty;
}
catch (Exception ex) { _error = $"Upload failed: {ex.Message}"; }
finally { _uploadingAsset = false; }
}
private async Task SaveAsync()
{
_error = null;
if (string.IsNullOrWhiteSpace(_cosmetic!.Name))
{ _error = "Name is required."; return; }
if (string.IsNullOrWhiteSpace(_cosmetic.AssetCdnUrl))
{ _error = "Asset URL is required."; return; }
if (!Enum.TryParse<CosmeticType>(_cosmeticTypeStr, out var t))
{ _error = "Invalid cosmetic type."; return; }
_cosmetic.CosmeticType = t;
_cosmetic.CardDefinitionId = string.IsNullOrWhiteSpace(_cardDefinitionIdStr) ? null
: Guid.TryParse(_cardDefinitionIdStr, out var g) ? g : null;
_saving = true;
try
{
_cosmetic.UpdatedAt = DateTimeOffset.UtcNow;
if (IsNew) Db.Cosmetics.Add(_cosmetic);
await Db.SaveChangesAsync();
Nav.NavigateTo("/bazaar/cosmetics");
}
catch (Exception ex) { _error = $"Save failed: {ex.Message}"; }
finally { _saving = false; }
}
private async Task DeleteAsync()
{
Db.Cosmetics.Remove(_cosmetic!);
await Db.SaveChangesAsync();
Nav.NavigateTo("/bazaar/cosmetics");
}
}
@@ -0,0 +1,121 @@
@page "/bazaar/cosmetics"
@attribute [Authorize(Roles = "Admin,SuperAdmin")]
@using Microsoft.EntityFrameworkCore
@using SOR.Database.Contexts
@using SOR.Database.Enums
@inject BazaarDbContext Db
@inject NavigationManager Nav
<PageTitle>Cosmetics – SOR Admin</PageTitle>
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="mb-0">Cosmetics</h1>
<a href="/bazaar/cosmetics/new" class="btn btn-primary">
<i class="bi bi-plus-lg me-1"></i>New Cosmetic
</a>
</div>
@if (_loading)
{
<p class="text-muted">Loading…</p>
}
else
{
<div class="card shadow-sm">
<div class="card-body p-0">
<table class="table table-sm table-hover mb-0">
<thead class="table-light">
<tr>
<th>Name</th>
<th>Type</th>
<th>Card</th>
<th class="text-end">OP Price</th>
<th class="text-end">USD</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var c in _cosmetics)
{
<tr>
<td class="fw-medium">@c.Name</td>
<td>
<span class="badge @TypeBadge(c.Type)">@c.Type</span>
</td>
<td class="text-muted small">@(c.CardName ?? "—")</td>
<td class="text-end">@c.OriginPointPrice.ToString("N0")</td>
<td class="text-end text-muted small">
@(c.UsdPrice.HasValue ? $"${c.UsdPrice:F2}" : "—")
</td>
<td>
@if (c.IsActive)
{
<span class="badge bg-success">Active</span>
}
else
{
<span class="badge bg-secondary">Inactive</span>
}
</td>
<td>
<a href="/bazaar/cosmetics/@c.Id"
class="btn btn-sm btn-outline-secondary">
<i class="bi bi-pencil"></i>
</a>
</td>
</tr>
}
@if (!_cosmetics.Any())
{
<tr>
<td colspan="7" class="text-muted text-center py-3">
No cosmetics yet. <a href="/bazaar/cosmetics/new">Create one.</a>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
}
@code {
private bool _loading = true;
private record CosmeticRow(
Guid Id,
string Name,
string Type,
string? CardName,
int OriginPointPrice,
decimal? UsdPrice,
bool IsActive);
private List<CosmeticRow> _cosmetics = new();
protected override async Task OnInitializedAsync()
{
_cosmetics = await Db.Cosmetics
.OrderBy(c => c.CosmeticType)
.ThenBy(c => c.Name)
.Select(c => new CosmeticRow(
c.Id,
c.Name,
c.CosmeticType.ToString(),
null,
c.OriginPointPrice,
c.UsdPrice,
c.IsActive))
.ToListAsync();
_loading = false;
}
private static string TypeBadge(string type) => type switch
{
nameof(CosmeticType.CardBack) => "bg-info text-dark",
nameof(CosmeticType.AlternateCardArt) => "bg-primary",
nameof(CosmeticType.AlternateCardModel) => "bg-warning text-dark",
_ => "bg-secondary",
};
}
@@ -0,0 +1,277 @@
@page "/bazaar/purchases"
@attribute [Authorize(Roles = "Admin,SuperAdmin")]
@using Microsoft.EntityFrameworkCore
@using SOR.Database.Contexts
@using SOR.Database.Enums
@inject BazaarDbContext Db
<PageTitle>Purchase Records – SOR Admin</PageTitle>
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="mb-0">Purchase Records</h1>
<button class="btn btn-outline-secondary btn-sm" @onclick="LoadAsync">
<i class="bi bi-arrow-clockwise me-1"></i>Refresh
</button>
</div>
<!-- Filters -->
<div class="card shadow-sm mb-4">
<div class="card-body">
<div class="row g-3">
<div class="col-md-3">
<label class="form-label small fw-medium">Account ID</label>
<input @bind="_filterAccountId" class="form-control form-control-sm font-monospace"
placeholder="GUID" />
</div>
<div class="col-md-3">
<label class="form-label small fw-medium">Product Type</label>
<select @bind="_filterProductType" class="form-select form-select-sm">
<option value="">All</option>
@foreach (var t in Enum.GetNames<PurchaseProductType>())
{
<option value="@t">@t</option>
}
</select>
</div>
<div class="col-md-2">
<label class="form-label small fw-medium">From</label>
<input @bind="_filterFrom" type="date" class="form-control form-control-sm" />
</div>
<div class="col-md-2">
<label class="form-label small fw-medium">To</label>
<input @bind="_filterTo" type="date" class="form-control form-control-sm" />
</div>
<div class="col-md-2 d-flex align-items-end">
<button class="btn btn-primary btn-sm w-100" @onclick="LoadAsync">
<i class="bi bi-search me-1"></i>Search
</button>
</div>
</div>
</div>
</div>
@if (_loading)
{
<p class="text-muted">Loading…</p>
}
else
{
<div class="card shadow-sm">
<div class="card-header fw-medium d-flex justify-content-between">
<span>Results</span>
<span class="badge bg-secondary">@_total records</span>
</div>
<div class="card-body p-0">
<table class="table table-sm table-hover mb-0">
<thead class="table-light">
<tr>
<th>Date</th>
<th>Account</th>
<th>Type</th>
<th>Product ID</th>
<th class="text-end">OP Spent</th>
<th class="text-end">USD</th>
<th class="text-end">Qty</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var r in _records)
{
<tr>
<td class="text-muted small">@r.PurchasedAt.ToString("yyyy-MM-dd HH:mm")</td>
<td class="font-monospace small">@r.AccountId.ToString()[..8]…</td>
<td><span class="badge @TypeBadge(r.ProductType)">@r.ProductType</span></td>
<td class="font-monospace small text-muted">
@(r.ProductId.HasValue ? r.ProductId.Value.ToString()[..8] + "…" : "—")
</td>
<td class="text-end">@r.OriginPointsSpent.ToString("N0")</td>
<td class="text-end text-muted small">
@(r.UsdSpent.HasValue ? $"${r.UsdSpent:F2}" : "—")
</td>
<td class="text-end">@r.QuantityGranted</td>
<td>
@if (r.ProductType == PurchaseProductType.BoosterPack.ToString() && r.HasGrants)
{
<button class="btn btn-sm btn-outline-secondary"
@onclick="() => ToggleGrants(r.Id)">
<i class="bi bi-card-list"></i>
</button>
}
</td>
</tr>
@if (_expandedGrants.Contains(r.Id))
{
<tr>
<td colspan="8" class="bg-light p-2">
<div class="small fw-medium mb-1">Cards Opened:</div>
@if (_grantsCache.TryGetValue(r.Id, out var grants))
{
<div class="d-flex flex-wrap gap-2">
@foreach (var g in grants)
{
<span class="badge @RarityBadge(g.Rarity)">
@g.CardName
@if (g.IsFoil) { <span class="ms-1">✨</span> }
</span>
}
</div>
}
else
{
<span class="text-muted">Loading…</span>
}
</td>
</tr>
}
}
@if (!_records.Any())
{
<tr>
<td colspan="8" class="text-muted text-center py-3">No records found.</td>
</tr>
}
</tbody>
</table>
</div>
</div>
<!-- Pagination -->
@if (_totalPages > 1)
{
<div class="d-flex justify-content-center gap-2 mt-3">
<button class="btn btn-sm btn-outline-secondary"
disabled="@(_page <= 1)"
@onclick="() => ChangePage(_page - 1)">
<i class="bi bi-chevron-left"></i>
</button>
<span class="btn btn-sm disabled">@_page / @_totalPages</span>
<button class="btn btn-sm btn-outline-secondary"
disabled="@(_page >= _totalPages)"
@onclick="() => ChangePage(_page + 1)">
<i class="bi bi-chevron-right"></i>
</button>
</div>
}
}
@code {
private bool _loading = true;
private int _page = 1, _totalPages = 1, _total;
private const int PageSize = 50;
private string _filterAccountId = string.Empty;
private string _filterProductType = string.Empty;
private DateOnly? _filterFrom, _filterTo;
private record PurchaseRow(
Guid Id,
DateTimeOffset PurchasedAt,
Guid AccountId,
string ProductType,
Guid? ProductId,
int OriginPointsSpent,
decimal? UsdSpent,
int QuantityGranted,
bool HasGrants);
private record GrantRow(string CardName, string Rarity, bool IsFoil);
private List<PurchaseRow> _records = new();
private HashSet<Guid> _expandedGrants = new();
private Dictionary<Guid, List<GrantRow>> _grantsCache = new();
protected override async Task OnInitializedAsync() => await LoadAsync();
private async Task LoadAsync()
{
_loading = true;
_expandedGrants.Clear();
var q = Db.PurchaseRecords.AsQueryable();
if (Guid.TryParse(_filterAccountId, out var accId))
q = q.Where(r => r.AccountId == accId);
if (!string.IsNullOrEmpty(_filterProductType) &&
Enum.TryParse<PurchaseProductType>(_filterProductType, out var pt))
q = q.Where(r => r.ProductType == pt);
if (_filterFrom.HasValue)
{
var from = new DateTimeOffset(_filterFrom.Value.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
q = q.Where(r => r.PurchasedAt >= from);
}
if (_filterTo.HasValue)
{
var to = new DateTimeOffset(_filterTo.Value.ToDateTime(TimeOnly.MaxValue), TimeSpan.Zero);
q = q.Where(r => r.PurchasedAt <= to);
}
_total = await q.CountAsync();
_totalPages = Math.Max(1, (int)Math.Ceiling(_total / (double)PageSize));
_page = Math.Clamp(_page, 1, _totalPages);
_records = await q
.OrderByDescending(r => r.PurchasedAt)
.Skip((_page - 1) * PageSize)
.Take(PageSize)
.Select(r => new PurchaseRow(
r.Id,
r.PurchasedAt,
r.AccountId,
r.ProductType.ToString(),
r.ProductId,
r.OriginPointsSpent,
r.UsdSpent,
r.QuantityGranted,
r.CardGrants.Any()))
.ToListAsync();
_loading = false;
}
private async Task ToggleGrants(Guid id)
{
if (_expandedGrants.Contains(id))
{
_expandedGrants.Remove(id);
return;
}
_expandedGrants.Add(id);
if (!_grantsCache.ContainsKey(id))
{
var grants = await Db.BoosterPackCardGrants
.Where(g => g.PurchaseRecordId == id)
.OrderBy(g => g.Rarity)
.ThenBy(g => g.CardName)
.Select(g => new GrantRow(g.CardName, g.Rarity, g.IsFoil))
.ToListAsync();
_grantsCache[id] = grants;
}
}
private async Task ChangePage(int p)
{
_page = p;
await LoadAsync();
}
private static string TypeBadge(string type) => type switch
{
nameof(PurchaseProductType.BoosterPack) => "bg-primary",
nameof(PurchaseProductType.PrebuiltDeck) => "bg-success",
nameof(PurchaseProductType.Cosmetic) => "bg-warning text-dark",
nameof(PurchaseProductType.OriginPointTopUp) => "bg-info text-dark",
_ => "bg-secondary",
};
private static string RarityBadge(string rarity) => rarity switch
{
"Legendary" => "bg-warning text-dark",
"Epic" => "bg-purple",
"Rare" => "bg-primary",
"Uncommon" => "bg-success",
_ => "bg-secondary",
};
}
+201
View File
@@ -0,0 +1,201 @@
namespace SOR.Bazaar;
// ── Requests ─────────────────────────────────────────────────────────────────
/// <summary>Returns all active store products (packs, decks, cosmetics).</summary>
public sealed record GetStoreRequest;
/// <summary>Open a booster pack. Deducts OriginPoints and draws cards.</summary>
public sealed record BuyBoosterPackRequest(Guid PackId);
/// <summary>Purchase a prebuilt deck. Deducts OriginPoints, grants cards, creates a deck.</summary>
public sealed record BuyPrebuiltDeckRequest(Guid DeckId);
/// <summary>Purchase a cosmetic. Deducts OriginPoints, grants PlayerCosmetic.</summary>
public sealed record BuyCosmeticRequest(Guid CosmeticId);
/// <summary>Browse active P2P listings with optional filters.</summary>
public sealed record GetListingsRequest(
int Page,
int PageSize,
Guid? CardDefinitionId,
decimal? MinPrice,
decimal? MaxPrice,
string? Rarity,
string? ListingType);
/// <summary>Returns the caller's own listings, optionally filtered by status.</summary>
public sealed record GetMyListingsRequest(string? StatusFilter);
/// <summary>
/// List a card for sale on the P2P marketplace.
/// Card must be IsTradeable = true and not already in an active listing.
/// </summary>
public sealed record ListCardRequest(
Guid PlayerCardId,
decimal Price,
string ListingType,
bool IsMasked,
DateTimeOffset? ExpiresAt);
/// <summary>Cancel an active listing owned by the caller.</summary>
public sealed record CancelListingRequest(Guid ListingId);
/// <summary>Buy a Fixed-price listing. Transfers card ownership and OriginPoints atomically.</summary>
public sealed record BuyListingRequest(Guid ListingId);
/// <summary>Place a bid on an Auction listing. Amount must exceed the current highest bid.</summary>
public sealed record PlaceBidRequest(Guid ListingId, decimal Amount);
/// <summary>Returns the caller's buy and sell transaction history.</summary>
public sealed record GetTransactionsRequest(int Page, int PageSize);
/// <summary>Returns the caller's current OriginPoints balance.</summary>
public sealed record GetMyBalanceRequest;
// ── Responses ────────────────────────────────────────────────────────────────
public sealed record GetStoreResponse(
IEnumerable<StorePackDto> Packs,
IEnumerable<StoreDeckDto> Decks,
IEnumerable<CosmeticDto> Cosmetics);
public sealed record BuyBoosterPackResponse(
Guid PurchaseId,
IEnumerable<OpenedCardDto> CardsOpened,
int NewOriginPointBalance);
public sealed record BuyPrebuiltDeckResponse(
Guid PurchaseId,
Guid DeckId,
string DeckName,
int TotalCards,
int NewOriginPointBalance);
public sealed record BuyCosmeticResponse(
Guid PurchaseId,
CosmeticDto Cosmetic,
int NewOriginPointBalance);
public sealed record GetListingsResponse(
IEnumerable<ListingDto> Listings,
int TotalCount,
int Page,
int PageSize);
public sealed record GetMyListingsResponse(IEnumerable<ListingDto> Listings);
public sealed record ListCardResponse(ListingDto Listing);
public sealed record CancelListingResponse(Guid ListingId);
public sealed record BuyListingResponse(
TransactionDto Transaction,
int NewOriginPointBalance);
public sealed record PlaceBidResponse(
BidDto Bid,
bool WasPreviousBidRefunded,
int NewOriginPointBalance);
public sealed record GetTransactionsResponse(
IEnumerable<TransactionDto> Transactions,
int TotalCount,
int Page,
int PageSize);
public sealed record GetMyBalanceResponse(int OriginPoints);
// ── DTOs ─────────────────────────────────────────────────────────────────────
public sealed record StorePackDto(
Guid Id,
string Name,
string? Description,
string? ImageCdnUrl,
int OriginPointPrice,
decimal? UsdPrice,
Guid? CardSetId,
int TotalSlots,
DateTimeOffset? AvailableFrom,
DateTimeOffset? AvailableUntil);
public sealed record StoreDeckDto(
Guid Id,
string Name,
string? Description,
string? ImageCdnUrl,
int OriginPointPrice,
decimal? UsdPrice,
int TotalCards,
string? ArchSpiritName,
bool IsStarterDeck,
DateTimeOffset? AvailableFrom,
DateTimeOffset? AvailableUntil);
public sealed record CosmeticDto(
Guid Id,
string Name,
string? Description,
string CosmeticType,
Guid? CardDefinitionId,
string? PreviewImageCdnUrl,
string AssetCdnUrl,
int OriginPointPrice,
decimal? UsdPrice);
public sealed record OpenedCardDto(
Guid PlayerCardId,
Guid CardDefinitionId,
string Name,
string CardType,
string Affinity,
string Rarity,
bool IsFoil,
int? SerialNumber,
string? ArtUrl);
public sealed record ListingDto(
Guid Id,
Guid SellerAccountId,
Guid PlayerCardId,
Guid? CardDefinitionId,
string? CardName,
string? CardType,
string? Rarity,
string ListingType,
decimal Price,
string Currency,
DateTimeOffset ListedAt,
DateTimeOffset? ExpiresAt,
bool IsMasked,
decimal? CurrentBid,
int BidCount);
public sealed record TransactionDto(
Guid Id,
Guid ListingId,
Guid BuyerAccountId,
Guid SellerAccountId,
Guid PlayerCardId,
decimal Amount,
string Currency,
DateTimeOffset TransactedAt);
public sealed record BidDto(
Guid Id,
Guid ListingId,
Guid BidderAccountId,
decimal Amount,
string Currency,
DateTimeOffset PlacedAt,
bool IsWinning);
public sealed record PlayerCosmeticDto(
Guid Id,
Guid CosmeticId,
string CosmeticType,
Guid? CardDefinitionId,
string? PreviewImageCdnUrl,
string AssetCdnUrl,
DateTimeOffset AcquiredAt);
@@ -0,0 +1,178 @@
namespace SOR.Bazaar.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Database.Entities.Bazaar;
using SOR.Database.Entities.Collection;
using SOR.Database.Enums;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
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 SorIdentityDbContext _identityDb;
public string MessageType => "bazaar.buy_booster_pack";
public BazaarBuyBoosterPackHandler(
IMessageSerializer serializer,
BazaarDbContext bazaarDb,
CollectionDbContext collectionDb,
CatalogDbContext catalogDb,
SorIdentityDbContext identityDb)
{
_serializer = serializer;
_bazaarDb = bazaarDb;
_collectionDb = collectionDb;
_catalogDb = catalogDb;
_identityDb = identityDb;
}
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<BuyBoosterPackRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
var now = DateTimeOffset.UtcNow;
// ── Load pack ──────────────────────────────────────────────────────────
var pack = await _bazaarDb.BoosterPacks
.FirstOrDefaultAsync(p => p.Id == req.PackId && p.IsActive
&& (p.AvailableFrom == null || p.AvailableFrom <= now)
&& (p.AvailableUntil == null || p.AvailableUntil >= now), ct);
if (pack is null)
return ServerMessage.Error(message.Seq, "PACK_NOT_FOUND",
"Booster pack not found or not currently available.");
if (string.IsNullOrEmpty(pack.SlotsJson))
return ServerMessage.Error(message.Seq, "PACK_NOT_CONFIGURED",
"This pack has no card slots configured.");
// ── Debit OriginPoints ────────────────────────────────────────────────
var debited = await TryDebitOriginPointsAsync(_identityDb, accountId, pack.OriginPointPrice, ct);
if (!debited)
return ServerMessage.Error(message.Seq, "INSUFFICIENT_FUNDS",
"You do not have enough Origin Points to purchase this pack.");
// ── Draw cards ────────────────────────────────────────────────────────
List<SlotEntry> slots;
try
{
slots = System.Text.Json.JsonSerializer.Deserialize<List<SlotEntry>>(pack.SlotsJson)
?? new List<SlotEntry>();
}
catch
{
return ServerMessage.Error(message.Seq, "PACK_NOT_CONFIGURED",
"This pack has an invalid slot configuration.");
}
var grantedCards = new List<(PlayerCard card, string rarity, string name)>();
foreach (var slot in slots)
{
if (!Enum.TryParse<CardRarity>(slot.Rarity, true, out var rarity))
continue;
// Build pool query: rarity match + published + optional set scope
var poolQuery = _catalogDb.CardDefinitions
.Where(cd => cd.Rarity == rarity && cd.IsPublished);
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++)
{
var pick = pool[Random.Shared.Next(pool.Count)];
var playerCard = new PlayerCard
{
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));
}
}
await _collectionDb.SaveChangesAsync(ct);
// ── Create PurchaseRecord + BoosterPackCardGrants ─────────────────────
var purchase = new PurchaseRecord
{
AccountId = accountId,
ProductType = PurchaseProductType.BoosterPack,
ProductId = pack.Id,
OriginPointsSpent = pack.OriginPointPrice,
QuantityGranted = grantedCards.Count,
PurchasedAt = now,
};
_bazaarDb.PurchaseRecords.Add(purchase);
await _bazaarDb.SaveChangesAsync(ct);
foreach (var (card, rarity, cardName) in grantedCards)
{
_bazaarDb.BoosterPackCardGrants.Add(new BoosterPackCardGrant
{
PurchaseRecordId = purchase.Id,
PlayerCardId = card.Id,
CardDefinitionId = card.CardDefinitionId,
CardName = cardName,
Rarity = rarity,
IsFoil = card.IsFoil,
});
}
await _bazaarDb.SaveChangesAsync(ct);
var newBalance = await GetOriginPointsAsync(_identityDb, accountId, ct);
// ── Build response ────────────────────────────────────────────────────
var defIds = grantedCards.Select(g => g.card.CardDefinitionId).Distinct().ToList();
var defs = await _catalogDb.CardDefinitions
.Include(cd => cd.Assets)
.Where(cd => defIds.Contains(cd.Id))
.ToDictionaryAsync(cd => cd.Id, ct);
var opened = grantedCards.Select(g =>
{
defs.TryGetValue(g.card.CardDefinitionId, out var def);
return new OpenedCardDto(
g.card.Id,
g.card.CardDefinitionId,
def?.Name ?? string.Empty,
def?.CardType.ToString() ?? string.Empty,
def?.Affinity.ToString() ?? string.Empty,
g.rarity,
g.card.IsFoil,
g.card.SerialNumber,
GetArtUrl(def));
}).ToList();
return ServerMessage.Reply(
"bazaar.buy_booster_pack.ack",
message.Seq,
new BuyBoosterPackResponse(purchase.Id, opened, newBalance));
}
private sealed record SlotEntry(string Rarity, int Count);
}
@@ -0,0 +1,104 @@
namespace SOR.Bazaar.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Database.Entities.Bazaar;
using SOR.Database.Entities.Collection;
using SOR.Database.Enums;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
internal sealed class BazaarBuyCosmeticHandler : BazaarHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly BazaarDbContext _bazaarDb;
private readonly CollectionDbContext _collectionDb;
private readonly SorIdentityDbContext _identityDb;
public string MessageType => "bazaar.buy_cosmetic";
public BazaarBuyCosmeticHandler(
IMessageSerializer serializer,
BazaarDbContext bazaarDb,
CollectionDbContext collectionDb,
SorIdentityDbContext identityDb)
{
_serializer = serializer;
_bazaarDb = bazaarDb;
_collectionDb = collectionDb;
_identityDb = identityDb;
}
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<BuyCosmeticRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
var now = DateTimeOffset.UtcNow;
var cosmetic = await _bazaarDb.Cosmetics
.FirstOrDefaultAsync(c => c.Id == req.CosmeticId && c.IsActive, ct);
if (cosmetic is null)
return ServerMessage.Error(message.Seq, "COSMETIC_NOT_FOUND",
"Cosmetic not found or not currently available.");
// Guard: already owned
var alreadyOwned = await _collectionDb.PlayerCosmetics
.AnyAsync(pc => pc.AccountId == accountId && pc.CosmeticId == req.CosmeticId, ct);
if (alreadyOwned)
return ServerMessage.Error(message.Seq, "ALREADY_OWNED",
"You already own this cosmetic.");
// ── Debit ─────────────────────────────────────────────────────────────
var debited = await TryDebitOriginPointsAsync(_identityDb, accountId, cosmetic.OriginPointPrice, ct);
if (!debited)
return ServerMessage.Error(message.Seq, "INSUFFICIENT_FUNDS",
"You do not have enough Origin Points to purchase this cosmetic.");
// ── Grant cosmetic ────────────────────────────────────────────────────
var playerCosmetic = new PlayerCosmetic
{
AccountId = accountId,
CosmeticId = cosmetic.Id,
AcquiredAt = now,
};
_collectionDb.PlayerCosmetics.Add(playerCosmetic);
await _collectionDb.SaveChangesAsync(ct);
// ── PurchaseRecord ────────────────────────────────────────────────────
var purchase = new PurchaseRecord
{
AccountId = accountId,
ProductType = PurchaseProductType.Cosmetic,
ProductId = cosmetic.Id,
OriginPointsSpent = cosmetic.OriginPointPrice,
QuantityGranted = 1,
PurchasedAt = now,
};
_bazaarDb.PurchaseRecords.Add(purchase);
await _bazaarDb.SaveChangesAsync(ct);
var newBalance = await GetOriginPointsAsync(_identityDb, accountId, ct);
var cosmeticDto = new CosmeticDto(
cosmetic.Id,
cosmetic.Name,
cosmetic.Description,
cosmetic.CosmeticType.ToString(),
cosmetic.CardDefinitionId,
cosmetic.PreviewImageCdnUrl,
cosmetic.AssetCdnUrl,
cosmetic.OriginPointPrice,
cosmetic.UsdPrice);
return ServerMessage.Reply(
"bazaar.buy_cosmetic.ack",
message.Seq,
new BuyCosmeticResponse(purchase.Id, cosmeticDto, newBalance));
}
}
@@ -0,0 +1,148 @@
namespace SOR.Bazaar.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Database.Entities.Bazaar;
using SOR.Database.Enums;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// Purchases a Fixed-price listing.
///
/// Atomicity: a single NpgsqlConnection transaction is shared across BazaarDbContext,
/// CollectionDbContext, and SorIdentityDbContext so that the listing claim, card transfer,
/// and OriginPoint debit/credit are all committed or rolled back together. This is safe
/// on multiple application servers because step 2 uses a conditional SQL UPDATE that acts
/// as a row-level optimistic lock — only one buyer can claim the listing.
/// </summary>
internal sealed class BazaarBuyListingHandler : BazaarHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly BazaarDbContext _bazaarDb;
private readonly CollectionDbContext _collectionDb;
private readonly SorIdentityDbContext _identityDb;
public string MessageType => "bazaar.buy_listing";
public BazaarBuyListingHandler(
IMessageSerializer serializer,
BazaarDbContext bazaarDb,
CollectionDbContext collectionDb,
SorIdentityDbContext identityDb)
{
_serializer = serializer;
_bazaarDb = bazaarDb;
_collectionDb = collectionDb;
_identityDb = identityDb;
}
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<BuyListingRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
await using var tx = await OpenSharedTransactionAsync(_bazaarDb, _collectionDb, _identityDb, ct);
try
{
// ── Step 1: Atomic claim — flip Active → Sold (optimistic lock) ──
var claimed = await _bazaarDb.Database.ExecuteSqlRawAsync(
"""
UPDATE bazaar.listings
SET status = 'Sold'
WHERE id = {0}
AND status = 'Active'
AND listing_type = 'Fixed'
AND seller_account_id <> {1}
""",
req.ListingId, accountId);
if (claimed == 0)
return ServerMessage.Error(message.Seq, "LISTING_ALREADY_SOLD",
"This listing is no longer available.");
// ── Step 2: Load listing details ──────────────────────────────────
var listing = await _bazaarDb.Listings
.FirstAsync(l => l.Id == req.ListingId, ct);
var price = (int)listing.Price; // OriginPoints are integer
var sellerAccId = listing.SellerAccountId;
// ── Step 3: Debit buyer ───────────────────────────────────────────
var debited = await TryDebitOriginPointsAsync(_identityDb, accountId, price, ct);
if (!debited)
{
await tx.RollbackAsync(ct);
return ServerMessage.Error(message.Seq, "INSUFFICIENT_FUNDS",
"You do not have enough Origin Points for this purchase.");
}
// ── Step 4: Credit seller ─────────────────────────────────────────
await CreditOriginPointsAsync(_identityDb, sellerAccId, price, ct);
// ── Step 5: Transfer card ownership ──────────────────────────────
var card = await _collectionDb.PlayerCards
.FirstAsync(pc => pc.Id == listing.PlayerCardId, ct);
card.AccountId = accountId;
await _collectionDb.SaveChangesAsync(ct);
// ── Step 6: Record transaction + purchase record ──────────────────
var now = DateTimeOffset.UtcNow;
var txnRecord = new BazaarTransaction
{
ListingId = listing.Id,
BuyerAccountId = accountId,
SellerAccountId = sellerAccId,
PlayerCardId = listing.PlayerCardId,
Amount = listing.Price,
Currency = listing.Currency,
TransactedAt = now,
};
_bazaarDb.Transactions.Add(txnRecord);
var purchase = new PurchaseRecord
{
AccountId = accountId,
ProductType = PurchaseProductType.BoosterPack, // reuse enum? no — use a distinct concept
ProductId = listing.Id,
OriginPointsSpent = price,
QuantityGranted = 1,
PurchasedAt = now,
};
// Note: P2P buys are tracked via BazaarTransaction; PurchaseRecord is for store purchases.
// We do NOT create a PurchaseRecord here — BazaarTransaction already serves as the audit trail.
_bazaarDb.Transactions.Add(txnRecord);
await _bazaarDb.SaveChangesAsync(ct);
// ── Step 7: Commit ────────────────────────────────────────────────
await tx.CommitAsync(ct);
var newBalance = await GetOriginPointsAsync(_identityDb, accountId, ct);
var txnDto = new TransactionDto(
txnRecord.Id,
txnRecord.ListingId,
txnRecord.BuyerAccountId,
txnRecord.SellerAccountId,
txnRecord.PlayerCardId,
txnRecord.Amount,
txnRecord.Currency.ToString(),
txnRecord.TransactedAt);
return ServerMessage.Reply(
"bazaar.buy_listing.ack",
message.Seq,
new BuyListingResponse(txnDto, newBalance));
}
catch
{
await tx.RollbackAsync(ct);
throw;
}
}
}
@@ -0,0 +1,146 @@
namespace SOR.Bazaar.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Database.Entities.Bazaar;
using SOR.Database.Entities.Collection;
using SOR.Database.Enums;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
internal sealed class BazaarBuyPrebuiltDeckHandler : BazaarHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly BazaarDbContext _bazaarDb;
private readonly CollectionDbContext _collectionDb;
private readonly SorIdentityDbContext _identityDb;
public string MessageType => "bazaar.buy_prebuilt_deck";
public BazaarBuyPrebuiltDeckHandler(
IMessageSerializer serializer,
BazaarDbContext bazaarDb,
CollectionDbContext collectionDb,
SorIdentityDbContext identityDb)
{
_serializer = serializer;
_bazaarDb = bazaarDb;
_collectionDb = collectionDb;
_identityDb = identityDb;
}
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<BuyPrebuiltDeckRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
var now = DateTimeOffset.UtcNow;
var deck = await _bazaarDb.PrebuiltDecks
.Include(d => d.Cards)
.FirstOrDefaultAsync(d => d.Id == req.DeckId && d.IsActive
&& (d.AvailableFrom == null || d.AvailableFrom <= now)
&& (d.AvailableUntil == null || d.AvailableUntil >= now), ct);
if (deck is null)
return ServerMessage.Error(message.Seq, "DECK_NOT_FOUND",
"Prebuilt deck not found or not currently available.");
// Starter decks are handled by collection.select_starter_deck; not purchasable here.
if (deck.IsStarterDeck)
return ServerMessage.Error(message.Seq, "STARTER_DECK",
"Starter decks must be selected during onboarding, not purchased.");
// ── Debit ─────────────────────────────────────────────────────────────
var debited = await TryDebitOriginPointsAsync(_identityDb, accountId, deck.OriginPointPrice, ct);
if (!debited)
return ServerMessage.Error(message.Seq, "INSUFFICIENT_FUNDS",
"You do not have enough Origin Points to purchase this deck.");
// ── Grant cards ───────────────────────────────────────────────────────
var grantedCards = new List<PlayerCard>();
foreach (var deckCard in deck.Cards)
{
for (int i = 0; i < deckCard.Quantity; i++)
{
var pc = new PlayerCard
{
AccountId = accountId,
CardDefinitionId = deckCard.CardDefinitionId,
AcquiredAt = now,
IsTradeable = true, // purchased deck cards are tradeable
};
_collectionDb.PlayerCards.Add(pc);
grantedCards.Add(pc);
}
}
// Grant ArchSpirit card if specified
if (deck.ArchSpiritCardDefinitionId.HasValue)
{
var archCard = new PlayerCard
{
AccountId = accountId,
CardDefinitionId = deck.ArchSpiritCardDefinitionId.Value,
AcquiredAt = now,
IsTradeable = true,
};
_collectionDb.PlayerCards.Add(archCard);
grantedCards.Add(archCard);
}
await _collectionDb.SaveChangesAsync(ct);
// ── Create Deck ───────────────────────────────────────────────────────
var newDeck = new Deck
{
AccountId = accountId,
Name = deck.Name,
Description = deck.Description,
ArchSpiritCardDefinitionId = deck.ArchSpiritCardDefinitionId ?? Guid.Empty,
CreatedAt = now,
UpdatedAt = now,
IsValid = false, // will be validated on next use
};
_collectionDb.Decks.Add(newDeck);
await _collectionDb.SaveChangesAsync(ct);
foreach (var deckCard in deck.Cards)
{
_collectionDb.DeckCards.Add(new DeckCard
{
DeckId = newDeck.Id,
CardDefinitionId = deckCard.CardDefinitionId,
Quantity = deckCard.Quantity,
});
}
await _collectionDb.SaveChangesAsync(ct);
// ── PurchaseRecord ────────────────────────────────────────────────────
var purchase = new PurchaseRecord
{
AccountId = accountId,
ProductType = PurchaseProductType.PrebuiltDeck,
ProductId = deck.Id,
OriginPointsSpent = deck.OriginPointPrice,
QuantityGranted = 1,
PurchasedAt = now,
};
_bazaarDb.PurchaseRecords.Add(purchase);
await _bazaarDb.SaveChangesAsync(ct);
var newBalance = await GetOriginPointsAsync(_identityDb, accountId, ct);
return ServerMessage.Reply(
"bazaar.buy_prebuilt_deck.ack",
message.Seq,
new BuyPrebuiltDeckResponse(
purchase.Id,
newDeck.Id,
newDeck.Name,
grantedCards.Count,
newBalance));
}
}
@@ -0,0 +1,73 @@
namespace SOR.Bazaar.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;
internal sealed class BazaarCancelListingHandler : BazaarHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly BazaarDbContext _bazaarDb;
private readonly SorIdentityDbContext _identityDb;
public string MessageType => "bazaar.cancel_listing";
public BazaarCancelListingHandler(
IMessageSerializer serializer,
BazaarDbContext bazaarDb,
SorIdentityDbContext identityDb)
{
_serializer = serializer;
_bazaarDb = bazaarDb;
_identityDb = identityDb;
}
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<CancelListingRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
var listing = await _bazaarDb.Listings
.FirstOrDefaultAsync(l => l.Id == req.ListingId, ct);
if (listing is null)
return ServerMessage.Error(message.Seq, "LISTING_NOT_FOUND", "Listing not found.");
if (listing.SellerAccountId != accountId)
return ServerMessage.Error(message.Seq, "FORBIDDEN",
"You can only cancel your own listings.");
if (listing.Status != BazaarListingStatus.Active)
return ServerMessage.Error(message.Seq, "LISTING_NOT_ACTIVE",
"Only active listings can be cancelled.");
// For auction listings with an active winning bid, refund the winning bidder.
if (listing.ListingType == BazaarListingType.Auction)
{
var winningBid = await _bazaarDb.AuctionBids
.FirstOrDefaultAsync(b => b.ListingId == listing.Id && b.IsWinning, ct);
if (winningBid is not null)
{
await CreditOriginPointsAsync(_identityDb, winningBid.BidderAccountId,
(int)winningBid.Amount, ct);
winningBid.IsWinning = false;
await _bazaarDb.SaveChangesAsync(ct);
}
}
listing.Status = BazaarListingStatus.Cancelled;
await _bazaarDb.SaveChangesAsync(ct);
return ServerMessage.Reply(
"bazaar.cancel_listing.ack",
message.Seq,
new CancelListingResponse(listing.Id));
}
}
@@ -0,0 +1,101 @@
namespace SOR.Bazaar.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;
internal sealed class BazaarGetListingsHandler : BazaarHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly BazaarDbContext _bazaarDb;
public string MessageType => "bazaar.get_listings";
public BazaarGetListingsHandler(IMessageSerializer serializer, BazaarDbContext bazaarDb)
{
_serializer = serializer;
_bazaarDb = bazaarDb;
}
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<GetListingsRequest>(message.Payload);
var query = _bazaarDb.Listings
.Where(l => l.Status == BazaarListingStatus.Active);
if (req.CardDefinitionId.HasValue)
query = query.Where(l => l.CardDefinitionId == req.CardDefinitionId.Value);
if (req.MinPrice.HasValue)
query = query.Where(l => l.Price >= req.MinPrice.Value);
if (req.MaxPrice.HasValue)
query = query.Where(l => l.Price <= req.MaxPrice.Value);
if (!string.IsNullOrEmpty(req.ListingType) &&
Enum.TryParse<BazaarListingType>(req.ListingType, true, out var lt))
query = query.Where(l => l.ListingType == lt);
var total = await query.CountAsync(ct);
var page = Math.Max(1, req.Page);
var pageSize = Math.Clamp(req.PageSize, 1, 100);
var listings = await query
.OrderBy(l => l.ListedAt)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.Select(l => new
{
l.Id,
l.SellerAccountId,
l.PlayerCardId,
l.CardDefinitionId,
l.ListingType,
l.Price,
l.Currency,
l.ListedAt,
l.ExpiresAt,
l.IsMasked,
CurrentBid = l.ListingType == BazaarListingType.Auction
? _bazaarDb.AuctionBids
.Where(b => b.ListingId == l.Id && b.IsWinning)
.Select(b => (decimal?)b.Amount)
.FirstOrDefault()
: (decimal?)null,
BidCount = l.ListingType == BazaarListingType.Auction
? _bazaarDb.AuctionBids.Count(b => b.ListingId == l.Id)
: 0,
})
.ToListAsync(ct);
var dtos = listings.Select(l => new ListingDto(
l.Id,
l.SellerAccountId,
l.PlayerCardId,
l.IsMasked ? null : l.CardDefinitionId,
null, // CardName — not denormalized on BazaarListing; clients resolve via catalog
null, // CardType
null, // Rarity
l.ListingType.ToString(),
l.Price,
l.Currency.ToString(),
l.ListedAt,
l.ExpiresAt,
l.IsMasked,
l.CurrentBid,
l.BidCount)).ToList();
return ServerMessage.Reply(
"bazaar.get_listings.ack",
message.Seq,
new GetListingsResponse(dtos, total, page, pageSize));
}
}
@@ -0,0 +1,40 @@
namespace SOR.Bazaar.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Database.Entities.Identity;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
internal sealed class BazaarGetMyBalanceHandler : BazaarHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly SorIdentityDbContext _identityDb;
public string MessageType => "bazaar.get_my_balance";
public BazaarGetMyBalanceHandler(IMessageSerializer serializer, SorIdentityDbContext identityDb)
{
_serializer = serializer;
_identityDb = identityDb;
}
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var accountId = Guid.Parse(connection.UserId);
var balance = await _identityDb.Set<Account>()
.Where(a => a.Id == accountId)
.Select(a => a.OriginPoints)
.FirstOrDefaultAsync(ct);
return ServerMessage.Reply(
"bazaar.get_my_balance.ack",
message.Seq,
new GetMyBalanceResponse(balance));
}
}
@@ -0,0 +1,84 @@
namespace SOR.Bazaar.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;
internal sealed class BazaarGetMyListingsHandler : BazaarHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly BazaarDbContext _bazaarDb;
public string MessageType => "bazaar.get_my_listings";
public BazaarGetMyListingsHandler(IMessageSerializer serializer, BazaarDbContext bazaarDb)
{
_serializer = serializer;
_bazaarDb = bazaarDb;
}
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<GetMyListingsRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
var query = _bazaarDb.Listings
.Where(l => l.SellerAccountId == accountId);
if (!string.IsNullOrEmpty(req.StatusFilter) &&
Enum.TryParse<BazaarListingStatus>(req.StatusFilter, true, out var status))
query = query.Where(l => l.Status == status);
var listings = await query
.OrderByDescending(l => l.ListedAt)
.Select(l => new
{
l.Id,
l.SellerAccountId,
l.PlayerCardId,
l.CardDefinitionId,
l.ListingType,
l.Price,
l.Currency,
l.ListedAt,
l.ExpiresAt,
l.IsMasked,
CurrentBid = l.ListingType == BazaarListingType.Auction
? _bazaarDb.AuctionBids
.Where(b => b.ListingId == l.Id && b.IsWinning)
.Select(b => (decimal?)b.Amount)
.FirstOrDefault()
: (decimal?)null,
BidCount = l.ListingType == BazaarListingType.Auction
? _bazaarDb.AuctionBids.Count(b => b.ListingId == l.Id)
: 0,
})
.ToListAsync(ct);
var dtos = listings.Select(l => new ListingDto(
l.Id,
l.SellerAccountId,
l.PlayerCardId,
l.CardDefinitionId,
null, null, null,
l.ListingType.ToString(),
l.Price,
l.Currency.ToString(),
l.ListedAt,
l.ExpiresAt,
l.IsMasked,
l.CurrentBid,
l.BidCount)).ToList();
return ServerMessage.Reply(
"bazaar.get_my_listings.ack",
message.Seq,
new GetMyListingsResponse(dtos));
}
}
@@ -0,0 +1,102 @@
namespace SOR.Bazaar.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
internal sealed class BazaarGetStoreHandler : BazaarHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly BazaarDbContext _bazaarDb;
public string MessageType => "bazaar.get_store";
public BazaarGetStoreHandler(IMessageSerializer serializer, BazaarDbContext bazaarDb)
{
_serializer = serializer;
_bazaarDb = bazaarDb;
}
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var now = DateTimeOffset.UtcNow;
var packs = await _bazaarDb.BoosterPacks
.Where(p => p.IsActive
&& (p.AvailableFrom == null || p.AvailableFrom <= now)
&& (p.AvailableUntil == null || p.AvailableUntil >= now))
.OrderBy(p => p.Name)
.Select(p => new StorePackDto(
p.Id,
p.Name,
p.Description,
p.ImageCdnUrl,
p.OriginPointPrice,
p.UsdPrice,
p.CardSetId,
p.SlotsJson == null ? 0 : CountSlots(p.SlotsJson),
p.AvailableFrom,
p.AvailableUntil))
.ToListAsync(ct);
var decks = await _bazaarDb.PrebuiltDecks
.Where(d => d.IsActive
&& (d.AvailableFrom == null || d.AvailableFrom <= now)
&& (d.AvailableUntil == null || d.AvailableUntil >= now))
.OrderBy(d => d.Name)
.Select(d => new StoreDeckDto(
d.Id,
d.Name,
d.Description,
d.ImageCdnUrl,
d.OriginPointPrice,
d.UsdPrice,
d.Cards.Sum(c => c.Quantity),
d.ArchSpiritName,
d.IsStarterDeck,
d.AvailableFrom,
d.AvailableUntil))
.ToListAsync(ct);
var cosmetics = await _bazaarDb.Cosmetics
.Where(c => c.IsActive)
.OrderBy(c => c.CosmeticType)
.ThenBy(c => c.Name)
.Select(c => new CosmeticDto(
c.Id,
c.Name,
c.Description,
c.CosmeticType.ToString(),
c.CardDefinitionId,
c.PreviewImageCdnUrl,
c.AssetCdnUrl,
c.OriginPointPrice,
c.UsdPrice))
.ToListAsync(ct);
return ServerMessage.Reply(
"bazaar.get_store.ack",
message.Seq,
new GetStoreResponse(packs, decks, cosmetics));
}
// SlotsJson is a JSONB string — count total cards across all slots without
// full deserialisation (just count "count" values via a quick parse).
private static int CountSlots(string slotsJson)
{
try
{
var slots = System.Text.Json.JsonSerializer
.Deserialize<SlotEntry[]>(slotsJson);
return slots?.Sum(s => s.Count) ?? 0;
}
catch { return 0; }
}
private sealed record SlotEntry(string Rarity, int Count);
}
@@ -0,0 +1,58 @@
namespace SOR.Bazaar.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
internal sealed class BazaarGetTransactionsHandler : BazaarHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly BazaarDbContext _bazaarDb;
public string MessageType => "bazaar.get_transactions";
public BazaarGetTransactionsHandler(IMessageSerializer serializer, BazaarDbContext bazaarDb)
{
_serializer = serializer;
_bazaarDb = bazaarDb;
}
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<GetTransactionsRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
var page = Math.Max(1, req.Page);
var pageSize = Math.Clamp(req.PageSize, 1, 100);
var query = _bazaarDb.Transactions
.Where(t => t.BuyerAccountId == accountId || t.SellerAccountId == accountId);
var total = await query.CountAsync(ct);
var txns = await query
.OrderByDescending(t => t.TransactedAt)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.Select(t => new TransactionDto(
t.Id,
t.ListingId,
t.BuyerAccountId,
t.SellerAccountId,
t.PlayerCardId,
t.Amount,
t.Currency.ToString(),
t.TransactedAt))
.ToListAsync(ct);
return ServerMessage.Reply(
"bazaar.get_transactions.ack",
message.Seq,
new GetTransactionsResponse(txns, total, page, pageSize));
}
}
@@ -0,0 +1,118 @@
namespace SOR.Bazaar.Handlers;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Npgsql;
using SOR.Database.Contexts;
using SOR.Database.Entities.Catalog;
using SOR.Database.Enums;
/// <summary>
/// Shared helpers for all bazaar message handlers.
/// </summary>
internal abstract class BazaarHandlerBase
{
// ── Origin Points ─────────────────────────────────────────────────────────
/// <summary>
/// Atomically deducts <paramref name="amount"/> from the account's OriginPoints
/// using a conditional UPDATE (origin_points >= amount).
/// Returns true when the deduction succeeded; false when the balance was insufficient.
/// Must be called within an open transaction when cross-context atomicity is required.
/// </summary>
protected static async Task<bool> TryDebitOriginPointsAsync(
SorIdentityDbContext identityDb,
Guid accountId,
int amount,
CancellationToken ct)
{
var rows = await identityDb.Database.ExecuteSqlRawAsync(
"""
UPDATE identity.accounts
SET origin_points = origin_points - {0}
WHERE "Id" = {1}
AND origin_points >= {0}
""",
amount, accountId, ct);
return rows == 1;
}
/// <summary>
/// Credits <paramref name="amount"/> OriginPoints to the account.
/// Does not require a minimum balance check.
/// </summary>
protected static async Task CreditOriginPointsAsync(
SorIdentityDbContext identityDb,
Guid accountId,
int amount,
CancellationToken ct)
{
await identityDb.Database.ExecuteSqlRawAsync(
"""
UPDATE identity.accounts
SET origin_points = origin_points + {0}
WHERE "Id" = {1}
""",
amount, accountId, ct);
}
/// <summary>
/// Reads the account's current OriginPoints balance after a debit/credit.
/// </summary>
protected static async Task<int> GetOriginPointsAsync(
SorIdentityDbContext identityDb,
Guid accountId,
CancellationToken ct)
{
return await identityDb.Database
.SqlQuery<int>($"""
SELECT origin_points AS "Value"
FROM identity.accounts
WHERE "Id" = {accountId}
""")
.FirstOrDefaultAsync(ct);
}
// ── Shared Npgsql transaction ─────────────────────────────────────────────
/// <summary>
/// Opens a single <see cref="NpgsqlConnection"/> and begins a transaction on it,
/// then shares that same underlying transaction across all supplied DbContexts.
///
/// All three contexts must point to the same Postgres instance (which they do —
/// they all share the same connection string). This approach is safe across
/// multiple application servers because Postgres row-level locking serialises
/// concurrent claims; no distributed coordination is needed.
///
/// Caller is responsible for CommitAsync / RollbackAsync and disposing the returned
/// transaction.
/// </summary>
protected static async Task<IDbContextTransaction> OpenSharedTransactionAsync(
BazaarDbContext bazaarDb,
CollectionDbContext collectionDb,
SorIdentityDbContext identityDb,
CancellationToken ct)
{
var conn = (NpgsqlConnection)bazaarDb.Database.GetDbConnection();
if (conn.State != System.Data.ConnectionState.Open)
await conn.OpenAsync(ct);
var tx = await conn.BeginTransactionAsync(
System.Data.IsolationLevel.ReadCommitted, ct);
await bazaarDb.Database.UseTransactionAsync(tx, ct);
await collectionDb.Database.UseTransactionAsync(tx, ct);
await identityDb.Database.UseTransactionAsync(tx, ct);
// Wrap so callers use EF's IDbContextTransaction interface for Commit/Rollback.
return bazaarDb.Database.CurrentTransaction!;
}
// ── Card art helper ───────────────────────────────────────────────────────
protected static string? GetArtUrl(CardDefinition? def)
=> def?.Assets
.FirstOrDefault(a => a.AssetType == CardAssetType.Art2D)
?.CdnUrl;
}
@@ -0,0 +1,111 @@
namespace SOR.Bazaar.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Database.Entities.Bazaar;
using SOR.Database.Enums;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
internal sealed class BazaarListCardHandler : BazaarHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly BazaarDbContext _bazaarDb;
private readonly CollectionDbContext _collectionDb;
public string MessageType => "bazaar.list_card";
public BazaarListCardHandler(
IMessageSerializer serializer,
BazaarDbContext bazaarDb,
CollectionDbContext collectionDb)
{
_serializer = serializer;
_bazaarDb = bazaarDb;
_collectionDb = collectionDb;
}
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<ListCardRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
// Validate listing type
if (!Enum.TryParse<BazaarListingType>(req.ListingType, true, out var listingType))
return ServerMessage.Error(message.Seq, "INVALID_LISTING_TYPE",
$"ListingType must be Fixed or Auction.");
// Validate expiry for Auction
if (listingType == BazaarListingType.Auction && req.ExpiresAt == null)
return ServerMessage.Error(message.Seq, "EXPIRY_REQUIRED",
"Auction listings require an ExpiresAt date.");
if (req.ExpiresAt.HasValue && req.ExpiresAt.Value <= DateTimeOffset.UtcNow)
return ServerMessage.Error(message.Seq, "INVALID_EXPIRY",
"ExpiresAt must be in the future.");
// Validate price
if (req.Price <= 0)
return ServerMessage.Error(message.Seq, "INVALID_PRICE", "Price must be greater than zero.");
// Load the card — must be owned by this account
var card = await _collectionDb.PlayerCards
.FirstOrDefaultAsync(pc => pc.Id == req.PlayerCardId && pc.AccountId == accountId, ct);
if (card is null)
return ServerMessage.Error(message.Seq, "CARD_NOT_FOUND",
"Card not found in your collection.");
if (!card.IsTradeable)
return ServerMessage.Error(message.Seq, "CARD_NOT_TRADEABLE",
"This card cannot be listed on the bazaar (starter deck card).");
// Check not already in an active listing
var alreadyListed = await _bazaarDb.Listings
.AnyAsync(l => l.PlayerCardId == req.PlayerCardId
&& l.Status == BazaarListingStatus.Active, ct);
if (alreadyListed)
return ServerMessage.Error(message.Seq, "ALREADY_LISTED",
"This card already has an active listing.");
var now = DateTimeOffset.UtcNow;
var listing = new BazaarListing
{
SellerAccountId = accountId,
PlayerCardId = req.PlayerCardId,
CardDefinitionId = card.CardDefinitionId,
ListingType = listingType,
Price = req.Price,
Currency = BazaarCurrency.Gold,
ListedAt = now,
ExpiresAt = req.ExpiresAt,
Status = BazaarListingStatus.Active,
IsMasked = req.IsMasked,
};
_bazaarDb.Listings.Add(listing);
await _bazaarDb.SaveChangesAsync(ct);
var dto = new ListingDto(
listing.Id,
listing.SellerAccountId,
listing.PlayerCardId,
listing.CardDefinitionId,
null, null, null,
listing.ListingType.ToString(),
listing.Price,
listing.Currency.ToString(),
listing.ListedAt,
listing.ExpiresAt,
listing.IsMasked,
null,
0);
return ServerMessage.Reply("bazaar.list_card.ack", message.Seq, new ListCardResponse(dto));
}
}
@@ -0,0 +1,141 @@
namespace SOR.Bazaar.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Database.Entities.Bazaar;
using SOR.Database.Enums;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// Places a bid on an Auction listing.
///
/// Atomicity: shared NpgsqlConnection transaction across Bazaar and Identity contexts.
/// The previous winning bidder's OriginPoints are refunded and their IsWinning flag cleared
/// in the same transaction as the new bid being recorded, so no bid is ever "lost".
/// </summary>
internal sealed class BazaarPlaceBidHandler : BazaarHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly BazaarDbContext _bazaarDb;
private readonly CollectionDbContext _collectionDb;
private readonly SorIdentityDbContext _identityDb;
public string MessageType => "bazaar.place_bid";
public BazaarPlaceBidHandler(
IMessageSerializer serializer,
BazaarDbContext bazaarDb,
CollectionDbContext collectionDb,
SorIdentityDbContext identityDb)
{
_serializer = serializer;
_bazaarDb = bazaarDb;
_collectionDb = collectionDb;
_identityDb = identityDb;
}
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<PlaceBidRequest>(message.Payload);
var accountId = Guid.Parse(connection.UserId);
if (req.Amount <= 0)
return ServerMessage.Error(message.Seq, "INVALID_BID", "Bid must be greater than zero.");
await using var tx = await OpenSharedTransactionAsync(_bazaarDb, _collectionDb, _identityDb, ct);
try
{
// ── Load and validate listing ──────────────────────────────────────
var listing = await _bazaarDb.Listings
.FirstOrDefaultAsync(l => l.Id == req.ListingId, ct);
if (listing is null)
return ServerMessage.Error(message.Seq, "LISTING_NOT_FOUND", "Listing not found.");
if (listing.ListingType != BazaarListingType.Auction)
return ServerMessage.Error(message.Seq, "NOT_AUCTION",
"This listing is not an auction.");
if (listing.Status != BazaarListingStatus.Active)
return ServerMessage.Error(message.Seq, "LISTING_NOT_ACTIVE",
"This auction is no longer active.");
if (listing.ExpiresAt.HasValue && listing.ExpiresAt.Value <= DateTimeOffset.UtcNow)
return ServerMessage.Error(message.Seq, "AUCTION_EXPIRED",
"This auction has already expired.");
if (listing.SellerAccountId == accountId)
return ServerMessage.Error(message.Seq, "CANNOT_BID_OWN",
"You cannot bid on your own listing.");
// ── Check bid beats current highest ───────────────────────────────
var prevWinner = await _bazaarDb.AuctionBids
.FirstOrDefaultAsync(b => b.ListingId == req.ListingId && b.IsWinning, ct);
decimal minBid = prevWinner?.Amount ?? listing.Price;
if (req.Amount <= minBid)
return ServerMessage.Error(message.Seq, "BID_TOO_LOW",
$"Bid must exceed the current highest bid of {minBid}.");
// ── Debit new bidder ───────────────────────────────────────────────
var debited = await TryDebitOriginPointsAsync(_identityDb, accountId, (int)req.Amount, ct);
if (!debited)
{
await tx.RollbackAsync(ct);
return ServerMessage.Error(message.Seq, "INSUFFICIENT_FUNDS",
"You do not have enough Origin Points to place this bid.");
}
// ── Refund previous winner ────────────────────────────────────────
bool refunded = false;
if (prevWinner is not null)
{
await CreditOriginPointsAsync(_identityDb, prevWinner.BidderAccountId,
(int)prevWinner.Amount, ct);
prevWinner.IsWinning = false;
refunded = true;
}
// ── Record new winning bid ────────────────────────────────────────
var bid = new AuctionBid
{
ListingId = req.ListingId,
BidderAccountId = accountId,
Amount = req.Amount,
Currency = BazaarCurrency.Gold,
PlacedAt = DateTimeOffset.UtcNow,
IsWinning = true,
};
_bazaarDb.AuctionBids.Add(bid);
await _bazaarDb.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
var newBalance = await GetOriginPointsAsync(_identityDb, accountId, ct);
var bidDto = new BidDto(
bid.Id,
bid.ListingId,
bid.BidderAccountId,
bid.Amount,
bid.Currency.ToString(),
bid.PlacedAt,
bid.IsWinning);
return ServerMessage.Reply(
"bazaar.place_bid.ack",
message.Seq,
new PlaceBidResponse(bidDto, refunded, newBalance));
}
catch
{
await tx.RollbackAsync(ct);
throw;
}
}
}
+15
View File
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>SOR.Bazaar</AssemblyName>
</PropertyGroup>
<ItemGroup>
<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,47 @@
namespace SOR.Bazaar;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SOR.Bazaar.Handlers;
using SOR.Database;
using SOR.Networking.Abstractions.Messaging;
/// <summary>
/// Registers all bazaar service components into the DI container.
/// Called from SOR.Host/Program.cs when ENABLED_SERVICES includes "bazaar".
/// </summary>
public static class ServiceRegistration
{
public static IServiceCollection AddBazaarService(
this IServiceCollection services,
IConfiguration configuration)
{
// All four DbContexts needed across the bazaar handlers.
services.AddBazaarDatabase(configuration);
services.AddCollectionDatabase(configuration);
services.AddCatalogDatabase(configuration);
services.AddIdentityDatabase(configuration);
// Store — read-only browsing
services.AddTransient<IMessageHandler, BazaarGetStoreHandler>();
services.AddTransient<IMessageHandler, BazaarGetMyBalanceHandler>();
// Store — purchases
services.AddTransient<IMessageHandler, BazaarBuyBoosterPackHandler>();
services.AddTransient<IMessageHandler, BazaarBuyPrebuiltDeckHandler>();
services.AddTransient<IMessageHandler, BazaarBuyCosmeticHandler>();
// P2P marketplace — browsing
services.AddTransient<IMessageHandler, BazaarGetListingsHandler>();
services.AddTransient<IMessageHandler, BazaarGetMyListingsHandler>();
services.AddTransient<IMessageHandler, BazaarGetTransactionsHandler>();
// P2P marketplace — mutations
services.AddTransient<IMessageHandler, BazaarListCardHandler>();
services.AddTransient<IMessageHandler, BazaarCancelListingHandler>();
services.AddTransient<IMessageHandler, BazaarBuyListingHandler>();
services.AddTransient<IMessageHandler, BazaarPlaceBidHandler>();
return services;
}
}
@@ -8,18 +8,23 @@ using SOR.Database.Enums;
/// EF Core DbContext for the bazaar schema.
///
/// Schema: "bazaar"
/// Entities: BazaarListing, BazaarTransaction, BoosterPack, PrebuiltDeck, PrebuiltDeckCard
/// Entities: BazaarListing, BazaarTransaction, BoosterPack, PrebuiltDeck, PrebuiltDeckCard,
/// Cosmetic, PurchaseRecord, BoosterPackCardGrant, AuctionBid
/// </summary>
public sealed class BazaarDbContext : DbContext
{
public BazaarDbContext(DbContextOptions<BazaarDbContext> options)
: base(options) { }
public DbSet<BazaarListing> Listings => Set<BazaarListing>();
public DbSet<BazaarTransaction> Transactions => Set<BazaarTransaction>();
public DbSet<BoosterPack> BoosterPacks => Set<BoosterPack>();
public DbSet<PrebuiltDeck> PrebuiltDecks => Set<PrebuiltDeck>();
public DbSet<PrebuiltDeckCard> PrebuiltDeckCards => Set<PrebuiltDeckCard>();
public DbSet<BazaarListing> Listings => Set<BazaarListing>();
public DbSet<BazaarTransaction> Transactions => Set<BazaarTransaction>();
public DbSet<BoosterPack> BoosterPacks => Set<BoosterPack>();
public DbSet<PrebuiltDeck> PrebuiltDecks => Set<PrebuiltDeck>();
public DbSet<PrebuiltDeckCard> PrebuiltDeckCards => Set<PrebuiltDeckCard>();
public DbSet<Cosmetic> Cosmetics => Set<Cosmetic>();
public DbSet<PurchaseRecord> PurchaseRecords => Set<PurchaseRecord>();
public DbSet<BoosterPackCardGrant> BoosterPackCardGrants => Set<BoosterPackCardGrant>();
public DbSet<AuctionBid> AuctionBids => Set<AuctionBid>();
protected override void OnModelCreating(ModelBuilder builder)
{
@@ -94,5 +99,59 @@ public sealed class BazaarDbContext : DbContext
// One entry per card per deck.
e.HasIndex(c => new { c.PrebuiltDeckId, c.CardDefinitionId }).IsUnique();
});
// ── Cosmetics ─────────────────────────────────────────────────────────
builder.Entity<Cosmetic>(e =>
{
e.ToTable("cosmetics");
e.HasKey(c => c.Id);
e.Property(c => c.Name).HasMaxLength(200);
e.Property(c => c.CosmeticType).HasConversion<string>();
e.Property(c => c.UsdPrice).HasColumnType("numeric(10,2)");
e.HasIndex(c => new { c.CosmeticType, c.IsActive });
e.HasIndex(c => c.CardDefinitionId);
});
// ── Purchase Records ──────────────────────────────────────────────────
builder.Entity<PurchaseRecord>(e =>
{
e.ToTable("purchase_records");
e.HasKey(r => r.Id);
e.Property(r => r.ProductType).HasConversion<string>();
e.Property(r => r.UsdSpent).HasColumnType("numeric(10,2)");
e.HasIndex(r => new { r.AccountId, r.PurchasedAt });
e.HasIndex(r => new { r.ProductType, r.PurchasedAt });
e.HasMany(r => r.CardGrants)
.WithOne(g => g.PurchaseRecord)
.HasForeignKey(g => g.PurchaseRecordId)
.OnDelete(DeleteBehavior.Cascade);
});
builder.Entity<BoosterPackCardGrant>(e =>
{
e.ToTable("booster_pack_card_grants");
e.HasKey(g => g.Id);
e.HasIndex(g => g.PurchaseRecordId);
e.HasIndex(g => g.PlayerCardId);
});
// ── Auction Bids ──────────────────────────────────────────────────────
builder.Entity<AuctionBid>(e =>
{
e.ToTable("auction_bids");
e.HasKey(b => b.Id);
e.Property(b => b.Amount).HasColumnType("numeric(18,4)");
e.Property(b => b.Currency).HasConversion<string>();
e.HasOne(b => b.Listing)
.WithMany()
.HasForeignKey(b => b.ListingId)
.OnDelete(DeleteBehavior.Restrict);
e.HasIndex(b => new { b.ListingId, b.IsWinning });
e.HasIndex(b => new { b.ListingId, b.Amount });
e.HasIndex(b => b.BidderAccountId);
});
}
}
@@ -19,9 +19,10 @@ public sealed class CollectionDbContext : DbContext
public CollectionDbContext(DbContextOptions<CollectionDbContext> options)
: base(options) { }
public DbSet<PlayerCard> PlayerCards => Set<PlayerCard>();
public DbSet<Deck> Decks => Set<Deck>();
public DbSet<DeckCard> DeckCards => Set<DeckCard>();
public DbSet<PlayerCard> PlayerCards => Set<PlayerCard>();
public DbSet<Deck> Decks => Set<Deck>();
public DbSet<DeckCard> DeckCards => Set<DeckCard>();
public DbSet<PlayerCosmetic> PlayerCosmetics => Set<PlayerCosmetic>();
protected override void OnModelCreating(ModelBuilder builder)
{
@@ -55,5 +56,14 @@ public sealed class CollectionDbContext : DbContext
// Same card definition can only appear once per deck row (use Quantity for copies).
e.HasIndex(dc => new { dc.DeckId, dc.CardDefinitionId }).IsUnique();
});
builder.Entity<PlayerCosmetic>(e =>
{
e.ToTable("player_cosmetics");
e.HasKey(pc => pc.Id);
e.HasIndex(pc => pc.AccountId);
// A player can only own a given cosmetic once.
e.HasIndex(pc => new { pc.AccountId, pc.CosmeticId }).IsUnique();
});
}
}
@@ -0,0 +1,36 @@
namespace SOR.Database.Entities.Bazaar;
using SOR.Database.Enums;
/// <summary>
/// A bid placed on an Auction-type BazaarListing.
///
/// At most one bid per listing has IsWinning = true (the current highest bid).
/// When a new higher bid arrives, the previous winning bid is set to IsWinning = false
/// and the bidder's Origin Points are refunded, atomically within the same transaction.
///
/// When the listing's ExpiresAt passes, the winning bidder receives the card and the
/// seller receives the winning bid amount (handled by the auction-resolution job).
/// </summary>
public sealed class AuctionBid
{
public Guid Id { get; set; } = Guid.NewGuid();
public Guid ListingId { get; set; }
/// <summary>Cross-schema: the account that placed this bid.</summary>
public Guid BidderAccountId { get; set; }
public decimal Amount { get; set; }
public BazaarCurrency Currency { get; set; }
public DateTimeOffset PlacedAt { get; set; }
/// <summary>
/// True only for the current highest bid on this listing.
/// Previous winning bids are set to false when outbid.
/// </summary>
public bool IsWinning { get; set; }
public BazaarListing Listing { get; set; } = null!;
}
@@ -42,6 +42,12 @@ public sealed class BoosterPack
/// </summary>
public string? SlotsJson { get; set; }
/// <summary>
/// Cross-schema: restricts the card draw pool to cards belonging to this CardSet.
/// Null = draw from all published cards of matching rarity across the entire catalog.
/// </summary>
public Guid? CardSetId { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
}
@@ -0,0 +1,32 @@
namespace SOR.Database.Entities.Bazaar;
/// <summary>
/// Records a single card received when a player opens a booster pack.
/// One row per card drawn; linked to the parent PurchaseRecord.
///
/// CardDefinitionId, CardName, and Rarity are denormalized from the
/// catalog schema to make historical reporting self-contained — we never
/// want a report query to break because a card was renamed.
/// </summary>
public sealed class BoosterPackCardGrant
{
public Guid Id { get; set; } = Guid.NewGuid();
public Guid PurchaseRecordId { get; set; }
/// <summary>Cross-schema: the PlayerCard instance created in the collection schema.</summary>
public Guid PlayerCardId { get; set; }
/// <summary>Denormalized from CardDefinition for self-contained reporting.</summary>
public Guid CardDefinitionId { get; set; }
/// <summary>Denormalized card name at time of grant.</summary>
public string CardName { get; set; } = string.Empty;
/// <summary>Denormalized rarity string at time of grant.</summary>
public string Rarity { get; set; } = string.Empty;
public bool IsFoil { get; set; }
public PurchaseRecord PurchaseRecord { get; set; } = null!;
}
@@ -0,0 +1,49 @@
namespace SOR.Database.Entities.Bazaar;
using SOR.Database.Enums;
/// <summary>
/// A purchasable cosmetic item available in the bazaar store.
///
/// CardBack — global cosmetic; applies to all of the player's cards.
/// CardDefinitionId is null.
/// AlternateCardArt — replaces the 2D art asset for a specific card definition.
/// CardDefinitionId is set.
/// AlternateCardModel — replaces the 3D model asset for a specific card definition.
/// CardDefinitionId is set.
///
/// AssetCdnUrl points to the actual art file / model file.
/// PreviewImageCdnUrl is a smaller thumbnail used in store listings.
/// </summary>
public sealed class Cosmetic
{
public Guid Id { get; set; } = Guid.NewGuid();
public string Name { get; set; } = string.Empty;
public string? Description { get; set; }
public CosmeticType CosmeticType { get; set; }
/// <summary>
/// Cross-schema: links to a specific card definition for AlternateCardArt /
/// AlternateCardModel cosmetics. Null for CardBack (global cosmetics).
/// </summary>
public Guid? CardDefinitionId { get; set; }
/// <summary>Thumbnail shown in store listings.</summary>
public string? PreviewImageCdnUrl { get; set; }
/// <summary>The actual cosmetic asset (art file, model file, card back texture).</summary>
public string AssetCdnUrl { get; set; } = string.Empty;
/// <summary>Cost in origin points.</summary>
public int OriginPointPrice { get; set; }
/// <summary>Cost in USD. Null if not available for real-money purchase.</summary>
public decimal? UsdPrice { get; set; }
public bool IsActive { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
}
@@ -0,0 +1,49 @@
namespace SOR.Database.Entities.Bazaar;
using SOR.Database.Enums;
/// <summary>
/// Immutable record of every purchase made through the bazaar store.
/// Created for every BoosterPack open, PrebuiltDeck purchase, Cosmetic purchase,
/// and Origin Point top-up. Never updated or deleted.
///
/// For BoosterPack purchases, CardGrants lists the exact cards received.
/// </summary>
public sealed class PurchaseRecord
{
public Guid Id { get; set; } = Guid.NewGuid();
/// <summary>Cross-schema: the account that made the purchase.</summary>
public Guid AccountId { get; set; }
public PurchaseProductType ProductType { get; set; }
/// <summary>
/// The product that was purchased (pack/deck/cosmetic ID).
/// Null for OriginPointTopUp purchases.
/// </summary>
public Guid? ProductId { get; set; }
/// <summary>
/// Origin points deducted from the account for this purchase.
/// Zero for USD-only purchases.
/// </summary>
public int OriginPointsSpent { get; set; }
/// <summary>
/// USD charged for this purchase.
/// Null for Origin Point purchases.
/// </summary>
public decimal? UsdSpent { get; set; }
/// <summary>
/// Number of cards opened (for BoosterPack) or Origin Points granted (for TopUp).
/// 1 for Deck and Cosmetic purchases.
/// </summary>
public int QuantityGranted { get; set; } = 1;
public DateTimeOffset PurchasedAt { get; set; }
/// <summary>Cards received from a booster pack opening. Empty for other product types.</summary>
public ICollection<BoosterPackCardGrant> CardGrants { get; set; } = new List<BoosterPackCardGrant>();
}
@@ -0,0 +1,21 @@
namespace SOR.Database.Entities.Collection;
/// <summary>
/// A cosmetic item owned by a player.
/// Created when a player purchases a cosmetic from the bazaar store.
///
/// CosmeticId is a cross-schema bare Guid referencing bazaar.cosmetics.
/// No EF FK — the collection schema is independent of the bazaar schema.
/// </summary>
public sealed class PlayerCosmetic
{
public Guid Id { get; set; } = Guid.NewGuid();
/// <summary>Cross-schema: the account that owns this cosmetic.</summary>
public Guid AccountId { get; set; }
/// <summary>Cross-schema: references bazaar.cosmetics.id.</summary>
public Guid CosmeticId { get; set; }
public DateTimeOffset AcquiredAt { get; set; }
}
@@ -31,4 +31,11 @@ public sealed class Account : IdentityUser<Guid>
/// Null means they have not yet chosen their starter deck.
/// </summary>
public DateTimeOffset? StarterDeckSelectedAt { get; set; }
/// <summary>
/// In-game earned currency balance (Origin Points / Gold).
/// Earned through gameplay; can also be purchased from the bazaar store.
/// Spent on booster packs, prebuilt decks, cosmetics, and P2P listings.
/// </summary>
public int OriginPoints { get; set; }
}
@@ -26,3 +26,27 @@ public enum BazaarCurrency
Gold,
Premium,
}
/// <summary>
/// Classifies what was purchased in a PurchaseRecord.
/// </summary>
public enum PurchaseProductType
{
BoosterPack,
PrebuiltDeck,
Cosmetic,
OriginPointTopUp,
}
/// <summary>
/// Type of cosmetic item purchasable from the bazaar.
/// CardBack — replaces the card back artwork globally (not card-specific).
/// AlternateCardArt — replaces the 2D art for a specific card definition.
/// AlternateCardModel — replaces the 3D model for a specific card definition.
/// </summary>
public enum CosmeticType
{
CardBack,
AlternateCardArt,
AlternateCardModel,
}
@@ -0,0 +1,478 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SOR.Database.Contexts;
#nullable disable
namespace SOR.Database.Migrations.Bazaar
{
[DbContext(typeof(BazaarDbContext))]
[Migration("20260225231658_AddBazaarCosmetics")]
partial class AddBazaarCosmetics
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasDefaultSchema("bazaar")
.HasAnnotation("ProductVersion", "8.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SOR.Database.Entities.Bazaar.AuctionBid", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<decimal>("Amount")
.HasColumnType("numeric(18,4)");
b.Property<Guid>("BidderAccountId")
.HasColumnType("uuid");
b.Property<string>("Currency")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsWinning")
.HasColumnType("boolean");
b.Property<Guid>("ListingId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("PlacedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("BidderAccountId");
b.HasIndex("ListingId", "Amount");
b.HasIndex("ListingId", "IsWinning");
b.ToTable("auction_bids", "bazaar");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.BazaarListing", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("CardDefinitionId")
.HasColumnType("uuid");
b.Property<string>("Currency")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset?>("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsMasked")
.HasColumnType("boolean");
b.Property<DateTimeOffset>("ListedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("ListingType")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("PlayerCardId")
.HasColumnType("uuid");
b.Property<decimal>("Price")
.HasColumnType("numeric(18,4)");
b.Property<Guid>("SellerAccountId")
.HasColumnType("uuid");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("SellerAccountId");
b.HasIndex("Status", "CardDefinitionId");
b.HasIndex("Status", "ExpiresAt");
b.ToTable("listings", "bazaar");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.BazaarTransaction", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<decimal>("Amount")
.HasColumnType("numeric(18,4)");
b.Property<Guid>("BuyerAccountId")
.HasColumnType("uuid");
b.Property<string>("Currency")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("ListingId")
.HasColumnType("uuid");
b.Property<Guid>("PlayerCardId")
.HasColumnType("uuid");
b.Property<Guid>("SellerAccountId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("TransactedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("BuyerAccountId");
b.HasIndex("ListingId");
b.HasIndex("SellerAccountId");
b.HasIndex("TransactedAt");
b.ToTable("transactions", "bazaar");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.BoosterPack", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset?>("AvailableFrom")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("AvailableUntil")
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("CardSetId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("ImageCdnUrl")
.HasColumnType("text");
b.Property<bool>("IsActive")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<int>("OriginPointPrice")
.HasColumnType("integer");
b.Property<string>("SlotsJson")
.HasColumnType("jsonb");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<decimal?>("UsdPrice")
.HasColumnType("numeric(10,2)");
b.HasKey("Id");
b.HasIndex("IsActive");
b.HasIndex("AvailableFrom", "AvailableUntil");
b.ToTable("booster_packs", "bazaar");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.BoosterPackCardGrant", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("CardDefinitionId")
.HasColumnType("uuid");
b.Property<string>("CardName")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsFoil")
.HasColumnType("boolean");
b.Property<Guid>("PlayerCardId")
.HasColumnType("uuid");
b.Property<Guid>("PurchaseRecordId")
.HasColumnType("uuid");
b.Property<string>("Rarity")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("PlayerCardId");
b.HasIndex("PurchaseRecordId");
b.ToTable("booster_pack_card_grants", "bazaar");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.Cosmetic", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AssetCdnUrl")
.IsRequired()
.HasColumnType("text");
b.Property<Guid?>("CardDefinitionId")
.HasColumnType("uuid");
b.Property<string>("CosmeticType")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<bool>("IsActive")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<int>("OriginPointPrice")
.HasColumnType("integer");
b.Property<string>("PreviewImageCdnUrl")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<decimal?>("UsdPrice")
.HasColumnType("numeric(10,2)");
b.HasKey("Id");
b.HasIndex("CardDefinitionId");
b.HasIndex("CosmeticType", "IsActive");
b.ToTable("cosmetics", "bazaar");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.PrebuiltDeck", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid?>("ArchSpiritCardDefinitionId")
.HasColumnType("uuid");
b.Property<string>("ArchSpiritName")
.HasColumnType("text");
b.Property<DateTimeOffset?>("AvailableFrom")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("AvailableUntil")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("ImageCdnUrl")
.HasColumnType("text");
b.Property<bool>("IsActive")
.HasColumnType("boolean");
b.Property<bool>("IsStarterDeck")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<int>("OriginPointPrice")
.HasColumnType("integer");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<decimal?>("UsdPrice")
.HasColumnType("numeric(10,2)");
b.HasKey("Id");
b.HasIndex("IsActive");
b.HasIndex("IsStarterDeck");
b.ToTable("prebuilt_decks", "bazaar");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.PrebuiltDeckCard", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("CardDefinitionId")
.HasColumnType("uuid");
b.Property<string>("CardName")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<Guid>("PrebuiltDeckId")
.HasColumnType("uuid");
b.Property<int>("Quantity")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("PrebuiltDeckId", "CardDefinitionId")
.IsUnique();
b.ToTable("prebuilt_deck_cards", "bazaar");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.PurchaseRecord", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<int>("OriginPointsSpent")
.HasColumnType("integer");
b.Property<Guid?>("ProductId")
.HasColumnType("uuid");
b.Property<string>("ProductType")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("PurchasedAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("QuantityGranted")
.HasColumnType("integer");
b.Property<decimal?>("UsdSpent")
.HasColumnType("numeric(10,2)");
b.HasKey("Id");
b.HasIndex("AccountId", "PurchasedAt");
b.HasIndex("ProductType", "PurchasedAt");
b.ToTable("purchase_records", "bazaar");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.AuctionBid", b =>
{
b.HasOne("SOR.Database.Entities.Bazaar.BazaarListing", "Listing")
.WithMany()
.HasForeignKey("ListingId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Listing");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.BazaarTransaction", b =>
{
b.HasOne("SOR.Database.Entities.Bazaar.BazaarListing", "Listing")
.WithMany("Transactions")
.HasForeignKey("ListingId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Listing");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.BoosterPackCardGrant", b =>
{
b.HasOne("SOR.Database.Entities.Bazaar.PurchaseRecord", "PurchaseRecord")
.WithMany("CardGrants")
.HasForeignKey("PurchaseRecordId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("PurchaseRecord");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.PrebuiltDeckCard", b =>
{
b.HasOne("SOR.Database.Entities.Bazaar.PrebuiltDeck", "PrebuiltDeck")
.WithMany("Cards")
.HasForeignKey("PrebuiltDeckId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("PrebuiltDeck");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.BazaarListing", b =>
{
b.Navigation("Transactions");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.PrebuiltDeck", b =>
{
b.Navigation("Cards");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.PurchaseRecord", b =>
{
b.Navigation("CardGrants");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,193 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SOR.Database.Migrations.Bazaar
{
/// <inheritdoc />
public partial class AddBazaarCosmetics : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "CardSetId",
schema: "bazaar",
table: "booster_packs",
type: "uuid",
nullable: true);
migrationBuilder.CreateTable(
name: "auction_bids",
schema: "bazaar",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
ListingId = table.Column<Guid>(type: "uuid", nullable: false),
BidderAccountId = table.Column<Guid>(type: "uuid", nullable: false),
Amount = table.Column<decimal>(type: "numeric(18,4)", nullable: false),
Currency = table.Column<string>(type: "text", nullable: false),
PlacedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
IsWinning = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_auction_bids", x => x.Id);
table.ForeignKey(
name: "FK_auction_bids_listings_ListingId",
column: x => x.ListingId,
principalSchema: "bazaar",
principalTable: "listings",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "cosmetics",
schema: "bazaar",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
Name = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
Description = table.Column<string>(type: "text", nullable: true),
CosmeticType = table.Column<string>(type: "text", nullable: false),
CardDefinitionId = table.Column<Guid>(type: "uuid", nullable: true),
PreviewImageCdnUrl = table.Column<string>(type: "text", nullable: true),
AssetCdnUrl = table.Column<string>(type: "text", nullable: false),
OriginPointPrice = table.Column<int>(type: "integer", nullable: false),
UsdPrice = table.Column<decimal>(type: "numeric(10,2)", nullable: true),
IsActive = table.Column<bool>(type: "boolean", nullable: false),
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
UpdatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_cosmetics", x => x.Id);
});
migrationBuilder.CreateTable(
name: "purchase_records",
schema: "bazaar",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
AccountId = table.Column<Guid>(type: "uuid", nullable: false),
ProductType = table.Column<string>(type: "text", nullable: false),
ProductId = table.Column<Guid>(type: "uuid", nullable: true),
OriginPointsSpent = table.Column<int>(type: "integer", nullable: false),
UsdSpent = table.Column<decimal>(type: "numeric(10,2)", nullable: true),
QuantityGranted = table.Column<int>(type: "integer", nullable: false),
PurchasedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_purchase_records", x => x.Id);
});
migrationBuilder.CreateTable(
name: "booster_pack_card_grants",
schema: "bazaar",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
PurchaseRecordId = table.Column<Guid>(type: "uuid", nullable: false),
PlayerCardId = table.Column<Guid>(type: "uuid", nullable: false),
CardDefinitionId = table.Column<Guid>(type: "uuid", nullable: false),
CardName = table.Column<string>(type: "text", nullable: false),
Rarity = table.Column<string>(type: "text", nullable: false),
IsFoil = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_booster_pack_card_grants", x => x.Id);
table.ForeignKey(
name: "FK_booster_pack_card_grants_purchase_records_PurchaseRecordId",
column: x => x.PurchaseRecordId,
principalSchema: "bazaar",
principalTable: "purchase_records",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_auction_bids_BidderAccountId",
schema: "bazaar",
table: "auction_bids",
column: "BidderAccountId");
migrationBuilder.CreateIndex(
name: "IX_auction_bids_ListingId_Amount",
schema: "bazaar",
table: "auction_bids",
columns: new[] { "ListingId", "Amount" });
migrationBuilder.CreateIndex(
name: "IX_auction_bids_ListingId_IsWinning",
schema: "bazaar",
table: "auction_bids",
columns: new[] { "ListingId", "IsWinning" });
migrationBuilder.CreateIndex(
name: "IX_booster_pack_card_grants_PlayerCardId",
schema: "bazaar",
table: "booster_pack_card_grants",
column: "PlayerCardId");
migrationBuilder.CreateIndex(
name: "IX_booster_pack_card_grants_PurchaseRecordId",
schema: "bazaar",
table: "booster_pack_card_grants",
column: "PurchaseRecordId");
migrationBuilder.CreateIndex(
name: "IX_cosmetics_CardDefinitionId",
schema: "bazaar",
table: "cosmetics",
column: "CardDefinitionId");
migrationBuilder.CreateIndex(
name: "IX_cosmetics_CosmeticType_IsActive",
schema: "bazaar",
table: "cosmetics",
columns: new[] { "CosmeticType", "IsActive" });
migrationBuilder.CreateIndex(
name: "IX_purchase_records_AccountId_PurchasedAt",
schema: "bazaar",
table: "purchase_records",
columns: new[] { "AccountId", "PurchasedAt" });
migrationBuilder.CreateIndex(
name: "IX_purchase_records_ProductType_PurchasedAt",
schema: "bazaar",
table: "purchase_records",
columns: new[] { "ProductType", "PurchasedAt" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "auction_bids",
schema: "bazaar");
migrationBuilder.DropTable(
name: "booster_pack_card_grants",
schema: "bazaar");
migrationBuilder.DropTable(
name: "cosmetics",
schema: "bazaar");
migrationBuilder.DropTable(
name: "purchase_records",
schema: "bazaar");
migrationBuilder.DropColumn(
name: "CardSetId",
schema: "bazaar",
table: "booster_packs");
}
}
}
@@ -23,6 +23,42 @@ namespace SOR.Database.Migrations.Bazaar
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SOR.Database.Entities.Bazaar.AuctionBid", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<decimal>("Amount")
.HasColumnType("numeric(18,4)");
b.Property<Guid>("BidderAccountId")
.HasColumnType("uuid");
b.Property<string>("Currency")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsWinning")
.HasColumnType("boolean");
b.Property<Guid>("ListingId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("PlacedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("BidderAccountId");
b.HasIndex("ListingId", "Amount");
b.HasIndex("ListingId", "IsWinning");
b.ToTable("auction_bids", "bazaar");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.BazaarListing", b =>
{
b.Property<Guid>("Id")
@@ -126,6 +162,9 @@ namespace SOR.Database.Migrations.Bazaar
b.Property<DateTimeOffset?>("AvailableUntil")
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("CardSetId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
@@ -164,6 +203,93 @@ namespace SOR.Database.Migrations.Bazaar
b.ToTable("booster_packs", "bazaar");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.BoosterPackCardGrant", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("CardDefinitionId")
.HasColumnType("uuid");
b.Property<string>("CardName")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsFoil")
.HasColumnType("boolean");
b.Property<Guid>("PlayerCardId")
.HasColumnType("uuid");
b.Property<Guid>("PurchaseRecordId")
.HasColumnType("uuid");
b.Property<string>("Rarity")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("PlayerCardId");
b.HasIndex("PurchaseRecordId");
b.ToTable("booster_pack_card_grants", "bazaar");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.Cosmetic", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AssetCdnUrl")
.IsRequired()
.HasColumnType("text");
b.Property<Guid?>("CardDefinitionId")
.HasColumnType("uuid");
b.Property<string>("CosmeticType")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<bool>("IsActive")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<int>("OriginPointPrice")
.HasColumnType("integer");
b.Property<string>("PreviewImageCdnUrl")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<decimal?>("UsdPrice")
.HasColumnType("numeric(10,2)");
b.HasKey("Id");
b.HasIndex("CardDefinitionId");
b.HasIndex("CosmeticType", "IsActive");
b.ToTable("cosmetics", "bazaar");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.PrebuiltDeck", b =>
{
b.Property<Guid>("Id")
@@ -248,6 +374,54 @@ namespace SOR.Database.Migrations.Bazaar
b.ToTable("prebuilt_deck_cards", "bazaar");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.PurchaseRecord", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<int>("OriginPointsSpent")
.HasColumnType("integer");
b.Property<Guid?>("ProductId")
.HasColumnType("uuid");
b.Property<string>("ProductType")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("PurchasedAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("QuantityGranted")
.HasColumnType("integer");
b.Property<decimal?>("UsdSpent")
.HasColumnType("numeric(10,2)");
b.HasKey("Id");
b.HasIndex("AccountId", "PurchasedAt");
b.HasIndex("ProductType", "PurchasedAt");
b.ToTable("purchase_records", "bazaar");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.AuctionBid", b =>
{
b.HasOne("SOR.Database.Entities.Bazaar.BazaarListing", "Listing")
.WithMany()
.HasForeignKey("ListingId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Listing");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.BazaarTransaction", b =>
{
b.HasOne("SOR.Database.Entities.Bazaar.BazaarListing", "Listing")
@@ -259,6 +433,17 @@ namespace SOR.Database.Migrations.Bazaar
b.Navigation("Listing");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.BoosterPackCardGrant", b =>
{
b.HasOne("SOR.Database.Entities.Bazaar.PurchaseRecord", "PurchaseRecord")
.WithMany("CardGrants")
.HasForeignKey("PurchaseRecordId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("PurchaseRecord");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.PrebuiltDeckCard", b =>
{
b.HasOne("SOR.Database.Entities.Bazaar.PrebuiltDeck", "PrebuiltDeck")
@@ -279,6 +464,11 @@ namespace SOR.Database.Migrations.Bazaar
{
b.Navigation("Cards");
});
modelBuilder.Entity("SOR.Database.Entities.Bazaar.PurchaseRecord", b =>
{
b.Navigation("CardGrants");
});
#pragma warning restore 612, 618
}
}
@@ -0,0 +1,165 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SOR.Database.Contexts;
#nullable disable
namespace SOR.Database.Migrations.Collection
{
[DbContext(typeof(CollectionDbContext))]
[Migration("20260225231700_AddPlayerCosmetics")]
partial class AddPlayerCosmetics
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasDefaultSchema("collection")
.HasAnnotation("ProductVersion", "8.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SOR.Database.Entities.Collection.Deck", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<Guid>("ArchSpiritCardDefinitionId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<bool>("IsValid")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("AccountId");
b.ToTable("decks", "collection");
});
modelBuilder.Entity("SOR.Database.Entities.Collection.DeckCard", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("CardDefinitionId")
.HasColumnType("uuid");
b.Property<Guid>("DeckId")
.HasColumnType("uuid");
b.Property<int>("Quantity")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("DeckId", "CardDefinitionId")
.IsUnique();
b.ToTable("deck_cards", "collection");
});
modelBuilder.Entity("SOR.Database.Entities.Collection.PlayerCard", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("AcquiredAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("CardDefinitionId")
.HasColumnType("uuid");
b.Property<bool>("IsFoil")
.HasColumnType("boolean");
b.Property<bool>("IsTradeable")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(true);
b.Property<int?>("SerialNumber")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("AccountId");
b.HasIndex("AccountId", "CardDefinitionId");
b.ToTable("player_cards", "collection");
});
modelBuilder.Entity("SOR.Database.Entities.Collection.PlayerCosmetic", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("AcquiredAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("CosmeticId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("AccountId");
b.HasIndex("AccountId", "CosmeticId")
.IsUnique();
b.ToTable("player_cosmetics", "collection");
});
modelBuilder.Entity("SOR.Database.Entities.Collection.DeckCard", b =>
{
b.HasOne("SOR.Database.Entities.Collection.Deck", "Deck")
.WithMany("Cards")
.HasForeignKey("DeckId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Deck");
});
modelBuilder.Entity("SOR.Database.Entities.Collection.Deck", b =>
{
b.Navigation("Cards");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,51 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SOR.Database.Migrations.Collection
{
/// <inheritdoc />
public partial class AddPlayerCosmetics : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "player_cosmetics",
schema: "collection",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
AccountId = table.Column<Guid>(type: "uuid", nullable: false),
CosmeticId = table.Column<Guid>(type: "uuid", nullable: false),
AcquiredAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_player_cosmetics", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_player_cosmetics_AccountId",
schema: "collection",
table: "player_cosmetics",
column: "AccountId");
migrationBuilder.CreateIndex(
name: "IX_player_cosmetics_AccountId_CosmeticId",
schema: "collection",
table: "player_cosmetics",
columns: new[] { "AccountId", "CosmeticId" },
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "player_cosmetics",
schema: "collection");
}
}
}
@@ -116,6 +116,31 @@ namespace SOR.Database.Migrations.Collection
b.ToTable("player_cards", "collection");
});
modelBuilder.Entity("SOR.Database.Entities.Collection.PlayerCosmetic", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("AcquiredAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("CosmeticId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("AccountId");
b.HasIndex("AccountId", "CosmeticId")
.IsUnique();
b.ToTable("player_cosmetics", "collection");
});
modelBuilder.Entity("SOR.Database.Entities.Collection.DeckCard", b =>
{
b.HasOne("SOR.Database.Entities.Collection.Deck", "Deck")
@@ -0,0 +1,371 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SOR.Database.Contexts;
#nullable disable
namespace SOR.Database.Migrations.Identity
{
[DbContext(typeof(SorIdentityDbContext))]
[Migration("20260225231657_AddOriginPoints")]
partial class AddOriginPoints
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasDefaultSchema("identity")
.HasAnnotation("ProductVersion", "8.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("roles", "identity");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<Guid>("RoleId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("role_claims", "identity");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("account_claims", "identity");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("ProviderKey")
.HasColumnType("text");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("external_logins", "identity");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.Property<Guid>("RoleId")
.HasColumnType("uuid");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("account_roles", "identity");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("account_tokens", "identity");
});
modelBuilder.Entity("SOR.Database.Entities.Identity.Account", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("AvatarCdnUrl")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("DisplayName")
.HasColumnType("text");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LastLoginAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<int>("OriginPoints")
.HasColumnType("integer");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<DateTimeOffset?>("StarterDeckSelectedAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("DisplayName");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("accounts", "identity");
});
modelBuilder.Entity("SOR.Database.Entities.Identity.AccountProperty", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Key")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("AccountId");
b.HasIndex("AccountId", "Key")
.IsUnique();
b.ToTable("account_properties", "identity");
});
modelBuilder.Entity("SOR.Database.Entities.Identity.AccountSession", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("DeviceId")
.HasColumnType("text");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("IpAddress")
.HasColumnType("text");
b.Property<DateTimeOffset?>("RevokedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("text");
b.Property<string>("UserAgent")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.HasIndex("AccountId", "ExpiresAt");
b.ToTable("account_sessions", "identity");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.HasOne("SOR.Database.Entities.Identity.Account", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.HasOne("SOR.Database.Entities.Identity.Account", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SOR.Database.Entities.Identity.Account", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.HasOne("SOR.Database.Entities.Identity.Account", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,31 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SOR.Database.Migrations.Identity
{
/// <inheritdoc />
public partial class AddOriginPoints : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "OriginPoints",
schema: "identity",
table: "accounts",
type: "integer",
nullable: false,
defaultValue: 0);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "OriginPoints",
schema: "identity",
table: "accounts");
}
}
}
@@ -199,6 +199,9 @@ namespace SOR.Database.Migrations.Identity
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<int>("OriginPoints")
.HasColumnType("integer");
b.Property<string>("PasswordHash")
.HasColumnType("text");
+3 -1
View File
@@ -13,6 +13,7 @@
// ENABLED_SERVICES=gateway → run only Gateway (dedicated gateway pod)
using SOR.Auth;
using SOR.Bazaar;
using SOR.Chat;
using SOR.Collection;
using SOR.Gateway;
@@ -134,8 +135,9 @@ if (IsEnabled("chat")) builder.Services.AddChatService(builder.Configurati
if (IsEnabled("collection")) builder.Services.AddCollectionService(builder.Configuration);
if (IsEnabled("gateway")) builder.Services.AddGatewayService(builder.Configuration);
if (IsEnabled("bazaar")) builder.Services.AddBazaarService(builder.Configuration);
// TODO: Uncomment as each service is implemented:
// if (IsEnabled("bazaar")) builder.Services.AddBazaarService(builder.Configuration);
// if (IsEnabled("leaderboard")) builder.Services.AddLeaderboardService(builder.Configuration);
// if (IsEnabled("content")) builder.Services.AddContentService(builder.Configuration);
// if (IsEnabled("admin")) builder.Services.AddAdminService(builder.Configuration);
+1
View File
@@ -31,5 +31,6 @@
<ProjectReference Include="..\SOR.Auth\SOR.Auth.csproj" />
<ProjectReference Include="..\SOR.Chat\SOR.Chat.csproj" />
<ProjectReference Include="..\SOR.Collection\SOR.Collection.csproj" />
<ProjectReference Include="..\SOR.Bazaar\SOR.Bazaar.csproj" />
</ItemGroup>
</Project>