Feat: chat archiving + ranked OP rewards + admin award OP

- ChatChannel: add ArchivedAt (nullable DateTimeOffset)
- ChatChannelMembership.EndMatchMembershipsAsync: set channel.ArchivedAt
  so match channels are archived when games end
- GameHandlerBase.FinalizeGameAsync: add IEventBus param; compute
  OriginPoints rewards scaled by rank diff; publish GameEndedEvent so
  ChatLifecycleHostedService triggers archival
- GameRuleSet: add WinnerOpReward (50), LoserOpReward (10),
  RankDiffOpMultiplierPct (0) with NOT NULL + defaults
- GameMessages.GameOverPush: add WinnerOpDelta / LoserOpDelta fields
- GameConcedeHandler + GameAttackHandler: inject IEventBus, pass to
  FinalizeGameAsync
- Migrations: 20260309200000_AddArchivedAtToChatChannel (ChatDbContext),
  20260309210000_AddOpRewardFields (GameDbContext)
- Admin GameSessionsPage: inject ChatDbContext; purge Match channels
  before deleting sessions in PurgeAllAsync
- Admin RankedRulesPage: new "Origin Points Rewards" card with three
  number inputs (WinnerOpReward, LoserOpReward, RankDiffOpMultiplierPct)
- Admin AccountDetail: display RankScore + OriginPoints in Profile card;
  new "Award OP" card that credits OP directly to the account balance

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-03-09 16:16:22 -04:00
co-authored by Claude Happy
parent c9f7c22bf0
commit 0600326db7
16 changed files with 848 additions and 9 deletions
@@ -51,6 +51,10 @@ else
<dd class="col-sm-8">@(_account.EmailConfirmed ? "Yes" : "No")</dd> <dd class="col-sm-8">@(_account.EmailConfirmed ? "Yes" : "No")</dd>
<dt class="col-sm-4">2FA</dt> <dt class="col-sm-4">2FA</dt>
<dd class="col-sm-8">@(_account.TwoFactorEnabled ? "Enabled" : "Disabled")</dd> <dd class="col-sm-8">@(_account.TwoFactorEnabled ? "Enabled" : "Disabled")</dd>
<dt class="col-sm-4">Rank Score</dt>
<dd class="col-sm-8">@_account.RankScore</dd>
<dt class="col-sm-4">Origin Points</dt>
<dd class="col-sm-8">@_account.OriginPoints</dd>
</dl> </dl>
</div> </div>
</div> </div>
@@ -268,6 +272,29 @@ else
</div> </div>
</div> </div>
<!-- Award Origin Points -->
<div class="col-md-6">
<div class="card shadow-sm">
<div class="card-header fw-medium">Award Origin Points</div>
<div class="card-body">
<div class="d-flex gap-2 align-items-end">
<div>
<label class="form-label small">Amount</label>
<input @bind="_awardOpAmount" type="number" min="1" max="999999"
class="form-control form-control-sm" style="width:120px" />
</div>
<button class="btn btn-sm btn-success" @onclick="AwardOpAsync"
disabled="@(_awardOpAmount <= 0)">
<i class="bi bi-coin me-1"></i>Award OP
</button>
</div>
<div class="form-text mt-2">
Immediately credits the specified OriginPoints to this account's balance.
</div>
</div>
</div>
</div>
<!-- Grant Cards --> <!-- Grant Cards -->
<div class="col-12"> <div class="col-12">
<div class="card shadow-sm"> <div class="card shadow-sm">
@@ -486,6 +513,9 @@ else
private bool _grantFoil; private bool _grantFoil;
private bool _granting; private bool _granting;
// Award OP
private int _awardOpAmount = 100;
// Account properties // Account properties
private List<AccountProperty> _props = new(); private List<AccountProperty> _props = new();
private Guid _editingPropId = Guid.Empty; private Guid _editingPropId = Guid.Empty;
@@ -674,6 +704,27 @@ else
} }
} }
// ── Award OP ──────────────────────────────────────────────────────────────
private async Task AwardOpAsync()
{
if (_account == null || _awardOpAmount <= 0) return;
_account.OriginPoints += _awardOpAmount;
var result = await UserManager.UpdateAsync(_account);
if (result.Succeeded)
{
_message = $"Awarded {_awardOpAmount} OP. New balance: {_account.OriginPoints}.";
_isError = false;
_awardOpAmount = 100;
}
else
{
_message = string.Join(" ", result.Errors.Select(e => e.Description));
_isError = true;
}
}
// ── Grant Cards ─────────────────────────────────────────────────────────── // ── Grant Cards ───────────────────────────────────────────────────────────
private async Task ResetStarterDeckSelectionAsync() private async Task ResetStarterDeckSelectionAsync()
@@ -4,6 +4,7 @@
@using SOR.Database.Contexts @using SOR.Database.Contexts
@using SOR.Database.Enums @using SOR.Database.Enums
@inject GameDbContext Db @inject GameDbContext Db
@inject ChatDbContext ChatDb
@inject IJSRuntime JS @inject IJSRuntime JS
<PageTitle>Game Sessions – SOR Admin</PageTitle> <PageTitle>Game Sessions – SOR Admin</PageTitle>
@@ -249,8 +250,12 @@ else
private async Task PurgeAllAsync() private async Task PurgeAllAsync()
{ {
if (!await JS.InvokeAsync<bool>("confirm", "Permanently delete ALL sessions and action logs?")) if (!await JS.InvokeAsync<bool>("confirm", "Permanently delete ALL sessions, action logs, and match chat channels?"))
return; return;
// Delete match chat channels (cascade removes members + messages).
await ChatDb.Channels
.Where(c => c.ChannelType == ChatChannelType.Match)
.ExecuteDeleteAsync();
// Cascade delete on action_logs means deleting sessions removes logs too. // Cascade delete on action_logs means deleting sessions removes logs too.
await Db.GameSessions.ExecuteDeleteAsync(); await Db.GameSessions.ExecuteDeleteAsync();
_page = 1; _page = 1;
@@ -123,6 +123,36 @@ else
</div> </div>
</div> </div>
</div> </div>
<div class="col-md-6">
<div class="card">
<div class="card-header">Origin Points Rewards</div>
<div class="card-body">
<div class="mb-3">
<label class="form-label fw-semibold">Winner OP Reward</label>
<input type="number" class="form-control" min="0" max="9999"
@bind="_rules.WinnerOpReward" />
<div class="form-text">Base OP awarded to the winner after a ranked game.</div>
</div>
<div class="mb-3">
<label class="form-label fw-semibold">Loser OP Reward</label>
<input type="number" class="form-control" min="0" max="9999"
@bind="_rules.LoserOpReward" />
<div class="form-text">Consolation OP awarded to the loser.</div>
</div>
<div class="mb-3">
<label class="form-label fw-semibold">Rank Diff OP Multiplier (‰)</label>
<input type="number" class="form-control" min="-1000" max="1000"
@bind="_rules.RankDiffOpMultiplierPct" />
<div class="form-text">
Per-rank-point scaling in thousandths. 0 = flat rewards.
Positive = upset wins pay more. Formula:
adjustment = (loserRank − winnerRank) × multiplier ÷ 1000.
</div>
</div>
</div>
</div>
</div>
</div> </div>
} }
@@ -62,6 +62,8 @@ internal static class ChatChannelMembership
foreach (var member in members) foreach (var member in members)
member.LeftAt = now; member.LeftAt = now;
channel.ArchivedAt = now;
await chatDb.SaveChangesAsync(ct); await chatDb.SaveChangesAsync(ct);
} }
@@ -13,6 +13,9 @@ public sealed class ChatChannel
public DateTimeOffset CreatedAt { get; set; } public DateTimeOffset CreatedAt { get; set; }
/// <summary>Set when the match ends and the channel is archived (members marked Left).</summary>
public DateTimeOffset? ArchivedAt { get; set; }
public ICollection<ChatMember> Members { get; set; } = new List<ChatMember>(); public ICollection<ChatMember> Members { get; set; } = new List<ChatMember>();
public ICollection<ChatMessage> Messages { get; set; } = new List<ChatMessage>(); public ICollection<ChatMessage> Messages { get; set; } = new List<ChatMessage>();
} }
@@ -49,6 +49,21 @@ public sealed class GameRuleSet
/// <summary>Battlefield height (rows). Default: 8.</summary> /// <summary>Battlefield height (rows). Default: 8.</summary>
public int BoardHeight { get; set; } = 8; public int BoardHeight { get; set; } = 8;
// ── Origin Points Rewards ─────────────────────────────────────────────────
/// <summary>OP awarded to the winner of a ranked game.</summary>
public int WinnerOpReward { get; set; } = 50;
/// <summary>OP awarded to the loser of a ranked game (consolation).</summary>
public int LoserOpReward { get; set; } = 10;
/// <summary>
/// Per-rank-point scaling for the OP award (in thousandths, i.e. 0 = flat).
/// adjustment = (loserRank − winnerRank) × RankDiffOpMultiplierPct / 1000.
/// Positive diff = winner was underdog → pays more. Negative = expected win → pays less.
/// </summary>
public int RankDiffOpMultiplierPct { get; set; } = 0;
// ── Timestamps ─────────────────────────────────────────────────────────── // ── Timestamps ───────────────────────────────────────────────────────────
public DateTimeOffset CreatedAt { get; set; } public DateTimeOffset CreatedAt { get; set; }
@@ -0,0 +1,275 @@
// <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.Chat
{
[DbContext(typeof(ChatDbContext))]
[Migration("20260309200000_AddArchivedAtToChatChannel")]
partial class AddArchivedAtToChatChannel
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasDefaultSchema("chat")
.HasAnnotation("ProductVersion", "8.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SOR.Database.Entities.Chat.AccountPresence", b =>
{
b.Property<Guid>("AccountId")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid?>("CurrentMatchId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("LastSeenAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("AccountId");
b.ToTable("account_presence", "chat");
});
modelBuilder.Entity("SOR.Database.Entities.Chat.BlockedUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("BlockedAccountId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("BlockedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("BlockerAccountId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("BlockerAccountId");
b.HasIndex("BlockerAccountId", "BlockedAccountId")
.IsUnique();
b.ToTable("blocked_users", "chat");
});
modelBuilder.Entity("SOR.Database.Entities.Chat.ChatChannel", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset?>("ArchivedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("ChannelType")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("MatchId")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ChannelType");
b.HasIndex("MatchId");
b.ToTable("channels", "chat");
});
modelBuilder.Entity("SOR.Database.Entities.Chat.ChatMember", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<Guid>("ChannelId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("JoinedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("LeftAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("AccountId");
b.HasIndex("ChannelId", "AccountId")
.IsUnique();
b.ToTable("members", "chat");
});
modelBuilder.Entity("SOR.Database.Entities.Chat.ChatMessage", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("ChannelId")
.HasColumnType("uuid");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset?>("EditedAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<Guid>("SenderAccountId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("SentAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("SenderAccountId");
b.HasIndex("ChannelId", "SentAt");
b.ToTable("messages", "chat");
});
modelBuilder.Entity("SOR.Database.Entities.Chat.FriendRequest", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("RecipientAccountId")
.HasColumnType("uuid");
b.Property<Guid>("RequesterAccountId")
.HasColumnType("uuid");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("RecipientAccountId");
b.HasIndex("Status");
b.HasIndex("RequesterAccountId", "RecipientAccountId")
.IsUnique();
b.ToTable("friend_requests", "chat");
});
modelBuilder.Entity("SOR.Database.Entities.Chat.Notification", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("NotificationType")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PayloadJson")
.HasColumnType("jsonb")
.HasColumnName("payload");
b.Property<DateTimeOffset?>("ReadAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("RecipientAccountId")
.HasColumnType("uuid");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RecipientAccountId", "ReadAt", "CreatedAt");
b.ToTable("notifications", "chat");
});
modelBuilder.Entity("SOR.Database.Entities.Chat.ChatMember", b =>
{
b.HasOne("SOR.Database.Entities.Chat.ChatChannel", "Channel")
.WithMany("Members")
.HasForeignKey("ChannelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Channel");
});
modelBuilder.Entity("SOR.Database.Entities.Chat.ChatMessage", b =>
{
b.HasOne("SOR.Database.Entities.Chat.ChatChannel", "Channel")
.WithMany("Messages")
.HasForeignKey("ChannelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Channel");
});
modelBuilder.Entity("SOR.Database.Entities.Chat.ChatChannel", b =>
{
b.Navigation("Members");
b.Navigation("Messages");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,31 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SOR.Database.Migrations.Chat
{
/// <inheritdoc />
public partial class AddArchivedAtToChatChannel : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTimeOffset>(
name: "ArchivedAt",
schema: "chat",
table: "channels",
type: "timestamp with time zone",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ArchivedAt",
schema: "chat",
table: "channels");
}
}
}
@@ -78,6 +78,9 @@ namespace SOR.Database.Migrations.Chat
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
.HasColumnType("uuid"); .HasColumnType("uuid");
b.Property<DateTimeOffset?>("ArchivedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("ChannelType") b.Property<string>("ChannelType")
.IsRequired() .IsRequired()
.HasColumnType("text"); .HasColumnType("text");
@@ -0,0 +1,309 @@
// <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.Game
{
[DbContext(typeof(GameDbContext))]
[Migration("20260309210000_AddOpRewardFields")]
partial class AddOpRewardFields
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasDefaultSchema("game")
.HasAnnotation("ProductVersion", "8.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SOR.Database.Entities.Game.CustomLobby", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<int?>("DrawPerTurnOverride")
.HasColumnType("integer");
b.Property<bool?>("FirstPlayerSkipsDrawOverride")
.HasColumnType("boolean");
b.Property<Guid?>("GameSessionId")
.HasColumnType("uuid");
b.Property<Guid?>("GuestAccountId")
.HasColumnType("uuid");
b.Property<Guid?>("GuestDeckId")
.HasColumnType("uuid");
b.Property<Guid>("HostAccountId")
.HasColumnType("uuid");
b.Property<Guid>("HostDeckId")
.HasColumnType("uuid");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("OpeningHandSizeOverride")
.HasColumnType("integer");
b.Property<int?>("SpAccumulationPerTurnOverride")
.HasColumnType("integer");
b.Property<int?>("SpCapOverride")
.HasColumnType("integer");
b.Property<bool?>("SpHasCapOverride")
.HasColumnType("boolean");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("HostAccountId");
b.HasIndex("Status", "CreatedAt");
b.ToTable("custom_lobbies", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.GameActionLog", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ActionType")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("ActorAccountId")
.HasColumnType("uuid");
b.Property<Guid>("GameSessionId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("OccurredAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("PayloadJson")
.HasColumnType("jsonb")
.HasColumnName("payload");
b.Property<string>("ResultJson")
.HasColumnType("jsonb")
.HasColumnName("result");
b.Property<int>("SequenceNumber")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ActorAccountId");
b.HasIndex("GameSessionId", "SequenceNumber")
.IsUnique();
b.ToTable("action_logs", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.GameRuleSet", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<int>("BoardHeight")
.HasColumnType("integer");
b.Property<int>("BoardWidth")
.HasColumnType("integer");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("DrawPerTurn")
.HasColumnType("integer");
b.Property<bool>("FirstPlayerSkipsDraw")
.HasColumnType("boolean");
b.Property<bool>("IsCustomDefault")
.HasColumnType("boolean");
b.Property<bool>("IsRankedDefault")
.HasColumnType("boolean");
b.Property<int>("LoserOpReward")
.HasColumnType("integer");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int>("OpeningHandSize")
.HasColumnType("integer");
b.Property<int>("RankDiffOpMultiplierPct")
.HasColumnType("integer");
b.Property<int>("SpAccumulationPerTurn")
.HasColumnType("integer");
b.Property<int>("SpCap")
.HasColumnType("integer");
b.Property<bool>("SpHasCap")
.HasColumnType("boolean");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("WinnerOpReward")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("IsCustomDefault");
b.HasIndex("IsRankedDefault");
b.ToTable("game_rule_sets", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.GameSession", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("EndedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("PlayerOneAccountId")
.HasColumnType("uuid");
b.Property<Guid>("PlayerOneDeckId")
.HasColumnType("uuid");
b.Property<bool>("PlayerOneReady")
.HasColumnType("boolean");
b.Property<Guid>("PlayerTwoAccountId")
.HasColumnType("uuid");
b.Property<Guid>("PlayerTwoDeckId")
.HasColumnType("uuid");
b.Property<bool>("PlayerTwoReady")
.HasColumnType("boolean");
b.Property<string>("RuleSnapshotJson")
.HasColumnType("jsonb")
.HasColumnName("rule_snapshot");
b.Property<DateTimeOffset?>("StartedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("StateJson")
.HasColumnType("jsonb")
.HasColumnName("state");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.Property<string>("WinCondition")
.HasColumnType("text");
b.Property<Guid?>("WinnerAccountId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("PlayerOneAccountId");
b.HasIndex("PlayerTwoAccountId");
b.HasIndex("Status", "CreatedAt");
b.ToTable("game_sessions", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.MatchmakingEntry", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<Guid>("DeckId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("JoinedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("MatchedGameSessionId")
.HasColumnType("uuid");
b.Property<int>("RankScore")
.HasColumnType("integer");
b.Property<DateTimeOffset?>("ResolvedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("AccountId", "Status");
b.HasIndex("Status", "RankScore");
b.ToTable("matchmaking_entries", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.GameActionLog", b =>
{
b.HasOne("SOR.Database.Entities.Game.GameSession", "Session")
.WithMany("ActionLog")
.HasForeignKey("GameSessionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Session");
});
modelBuilder.Entity("SOR.Database.Entities.Game.GameSession", b =>
{
b.Navigation("ActionLog");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,57 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SOR.Database.Migrations.Game
{
/// <inheritdoc />
public partial class AddOpRewardFields : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "WinnerOpReward",
schema: "game",
table: "game_rule_sets",
type: "integer",
nullable: false,
defaultValue: 50);
migrationBuilder.AddColumn<int>(
name: "LoserOpReward",
schema: "game",
table: "game_rule_sets",
type: "integer",
nullable: false,
defaultValue: 10);
migrationBuilder.AddColumn<int>(
name: "RankDiffOpMultiplierPct",
schema: "game",
table: "game_rule_sets",
type: "integer",
nullable: false,
defaultValue: 0);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "WinnerOpReward",
schema: "game",
table: "game_rule_sets");
migrationBuilder.DropColumn(
name: "LoserOpReward",
schema: "game",
table: "game_rule_sets");
migrationBuilder.DropColumn(
name: "RankDiffOpMultiplierPct",
schema: "game",
table: "game_rule_sets");
}
}
}
@@ -149,6 +149,9 @@ namespace SOR.Database.Migrations.Game
b.Property<bool>("IsRankedDefault") b.Property<bool>("IsRankedDefault")
.HasColumnType("boolean"); .HasColumnType("boolean");
b.Property<int>("LoserOpReward")
.HasColumnType("integer");
b.Property<string>("Name") b.Property<string>("Name")
.IsRequired() .IsRequired()
.HasColumnType("text"); .HasColumnType("text");
@@ -156,6 +159,9 @@ namespace SOR.Database.Migrations.Game
b.Property<int>("OpeningHandSize") b.Property<int>("OpeningHandSize")
.HasColumnType("integer"); .HasColumnType("integer");
b.Property<int>("RankDiffOpMultiplierPct")
.HasColumnType("integer");
b.Property<int>("SpAccumulationPerTurn") b.Property<int>("SpAccumulationPerTurn")
.HasColumnType("integer"); .HasColumnType("integer");
@@ -168,6 +174,9 @@ namespace SOR.Database.Migrations.Game
b.Property<DateTimeOffset>("UpdatedAt") b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone"); .HasColumnType("timestamp with time zone");
b.Property<int>("WinnerOpReward")
.HasColumnType("integer");
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("IsCustomDefault"); b.HasIndex("IsCustomDefault");
+3 -1
View File
@@ -176,7 +176,9 @@ public sealed record GameOverPush(
Guid LoserAccountId, Guid LoserAccountId,
string WinCondition, // "health" | "concede" | "disconnect" string WinCondition, // "health" | "concede" | "disconnect"
int WinnerRankDelta, int WinnerRankDelta,
int LoserRankDelta); int LoserRankDelta,
int WinnerOpDelta,
int LoserOpDelta);
/// <summary> /// <summary>
/// Pushed to both players when a custom lobby is full and a GameSession has been created. /// Pushed to both players when a custom lobby is full and a GameSession has been created.
@@ -2,6 +2,7 @@ namespace SOR.Game.Handlers;
using System.Text.Json; using System.Text.Json;
using SOR.Database.Contexts; using SOR.Database.Contexts;
using SOR.Networking.Abstractions.EventBus;
using SOR.Networking.Abstractions.Messaging; using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Push; using SOR.Networking.Abstractions.Push;
using SOR.Networking.Abstractions.Transport; using SOR.Networking.Abstractions.Transport;
@@ -16,17 +17,20 @@ internal sealed class GameAttackHandler : GameHandlerBase, IMessageHandler
private readonly GameDbContext _gameDb; private readonly GameDbContext _gameDb;
private readonly SorIdentityDbContext _identityDb; private readonly SorIdentityDbContext _identityDb;
private readonly IClientPush _clientPush; private readonly IClientPush _clientPush;
private readonly IEventBus _eventBus;
public GameAttackHandler( public GameAttackHandler(
IMessageSerializer serializer, IMessageSerializer serializer,
GameDbContext gameDb, GameDbContext gameDb,
SorIdentityDbContext identityDb, SorIdentityDbContext identityDb,
IClientPush clientPush) IClientPush clientPush,
IEventBus eventBus)
{ {
_serializer = serializer; _serializer = serializer;
_gameDb = gameDb; _gameDb = gameDb;
_identityDb = identityDb; _identityDb = identityDb;
_clientPush = clientPush; _clientPush = clientPush;
_eventBus = eventBus;
} }
public string MessageType => "game.attack"; public string MessageType => "game.attack";
@@ -57,7 +61,7 @@ internal sealed class GameAttackHandler : GameHandlerBase, IMessageHandler
: session.PlayerOneAccountId; : session.PlayerOneAccountId;
await FinalizeGameAsync( await FinalizeGameAsync(
_gameDb, _identityDb, _clientPush, _gameDb, _identityDb, _clientPush, _eventBus,
session, session,
winnerAccountId: Guid.Parse(actorId), winnerAccountId: Guid.Parse(actorId),
loserAccountId: loserId, loserAccountId: loserId,
@@ -2,6 +2,7 @@ namespace SOR.Game.Handlers;
using System.Text.Json; using System.Text.Json;
using SOR.Database.Contexts; using SOR.Database.Contexts;
using SOR.Networking.Abstractions.EventBus;
using SOR.Networking.Abstractions.Messaging; using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Push; using SOR.Networking.Abstractions.Push;
using SOR.Networking.Abstractions.Transport; using SOR.Networking.Abstractions.Transport;
@@ -16,17 +17,20 @@ internal sealed class GameConcedeHandler : GameHandlerBase, IMessageHandler
private readonly GameDbContext _gameDb; private readonly GameDbContext _gameDb;
private readonly SorIdentityDbContext _identityDb; private readonly SorIdentityDbContext _identityDb;
private readonly IClientPush _clientPush; private readonly IClientPush _clientPush;
private readonly IEventBus _eventBus;
public GameConcedeHandler( public GameConcedeHandler(
IMessageSerializer serializer, IMessageSerializer serializer,
GameDbContext gameDb, GameDbContext gameDb,
SorIdentityDbContext identityDb, SorIdentityDbContext identityDb,
IClientPush clientPush) IClientPush clientPush,
IEventBus eventBus)
{ {
_serializer = serializer; _serializer = serializer;
_gameDb = gameDb; _gameDb = gameDb;
_identityDb = identityDb; _identityDb = identityDb;
_clientPush = clientPush; _clientPush = clientPush;
_eventBus = eventBus;
} }
public string MessageType => "game.concede"; public string MessageType => "game.concede";
@@ -52,7 +56,7 @@ internal sealed class GameConcedeHandler : GameHandlerBase, IMessageHandler
: session.PlayerOneAccountId; : session.PlayerOneAccountId;
await FinalizeGameAsync( await FinalizeGameAsync(
_gameDb, _identityDb, _clientPush, _gameDb, _identityDb, _clientPush, _eventBus,
session, session,
winnerAccountId: winnerId, winnerAccountId: winnerId,
loserAccountId: Guid.Parse(actorId), loserAccountId: Guid.Parse(actorId),
@@ -1,11 +1,14 @@
namespace SOR.Game.Handlers; namespace SOR.Game.Handlers;
using System.Text.Json;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts; using SOR.Database.Contexts;
using SOR.Database.Entities.Game; using SOR.Database.Entities.Game;
using SOR.Database.Enums; using SOR.Database.Enums;
using SOR.Networking.Abstractions.EventBus;
using SOR.Networking.Abstractions.Push; using SOR.Networking.Abstractions.Push;
using SOR.Networking.Abstractions.Transport; using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Nats;
using SOR.Shared.Networking; using SOR.Shared.Networking;
/// <summary> /// <summary>
@@ -106,14 +109,21 @@ internal abstract class GameHandlerBase
new GameStateUpdatePush(GameEngine.ToDto(state, p2Id))), ct)); new GameStateUpdatePush(GameEngine.ToDto(state, p2Id))), ct));
} }
// OP config snapshot — read from RuleSnapshotJson at finalization time.
private sealed record OpSnapshot(
int WinnerOpReward = 50,
int LoserOpReward = 10,
int RankDiffOpMultiplierPct = 0);
/// <summary> /// <summary>
/// Finalize a completed game: update session status, adjust ELO ranks, /// Finalize a completed game: update session status, adjust ELO ranks,
/// push game-over to both players. /// award OriginPoints, push game-over to both players, publish GameEndedEvent.
/// </summary> /// </summary>
protected static async Task FinalizeGameAsync( protected static async Task FinalizeGameAsync(
GameDbContext gameDb, GameDbContext gameDb,
SorIdentityDbContext identityDb, SorIdentityDbContext identityDb,
IClientPush clientPush, IClientPush clientPush,
IEventBus eventBus,
GameSession session, GameSession session,
Guid winnerAccountId, Guid winnerAccountId,
Guid loserAccountId, Guid loserAccountId,
@@ -125,7 +135,7 @@ internal abstract class GameHandlerBase
session.WinCondition = winCondition; session.WinCondition = winCondition;
session.EndedAt = DateTimeOffset.UtcNow; session.EndedAt = DateTimeOffset.UtcNow;
// Load both accounts for ELO adjustment. // Load both accounts for ELO + OP adjustment.
var accounts = await identityDb.Users var accounts = await identityDb.Users
.Where(a => a.Id == winnerAccountId || a.Id == loserAccountId) .Where(a => a.Id == winnerAccountId || a.Id == loserAccountId)
.ToListAsync(ct); .ToListAsync(ct);
@@ -133,11 +143,28 @@ internal abstract class GameHandlerBase
var winner = accounts.First(a => a.Id == winnerAccountId); var winner = accounts.First(a => a.Id == winnerAccountId);
var loser = accounts.First(a => a.Id == loserAccountId); var loser = accounts.First(a => a.Id == loserAccountId);
// Capture pre-ELO ranks for OP scaling.
var winnerPreRank = winner.RankScore;
var loserPreRank = loser.RankScore;
var (winnerDelta, loserDelta) = GameEngine.ComputeEloDelta(winner.RankScore, loser.RankScore); var (winnerDelta, loserDelta) = GameEngine.ComputeEloDelta(winner.RankScore, loser.RankScore);
winner.RankScore += winnerDelta; winner.RankScore += winnerDelta;
loser.RankScore = Math.Max(0, loser.RankScore - loserDelta); loser.RankScore = Math.Max(0, loser.RankScore - loserDelta);
// Compute OriginPoints rewards from the rule snapshot.
var snap = JsonSerializer.Deserialize<OpSnapshot>(
session.RuleSnapshotJson ?? "{}",
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new OpSnapshot();
var rankDiff = loserPreRank - winnerPreRank; // positive = winner was underdog
var adjustment = rankDiff * snap.RankDiffOpMultiplierPct / 1000;
var winnerOp = Math.Max(1, snap.WinnerOpReward + adjustment);
var loserOp = Math.Max(0, snap.LoserOpReward - adjustment);
winner.OriginPoints += winnerOp;
loser.OriginPoints += loserOp;
await identityDb.SaveChangesAsync(ct); await identityDb.SaveChangesAsync(ct);
await gameDb.SaveChangesAsync(ct); await gameDb.SaveChangesAsync(ct);
@@ -147,12 +174,24 @@ internal abstract class GameHandlerBase
LoserAccountId : loserAccountId, LoserAccountId : loserAccountId,
WinCondition : winCondition, WinCondition : winCondition,
WinnerRankDelta : winnerDelta, WinnerRankDelta : winnerDelta,
LoserRankDelta : loserDelta); LoserRankDelta : loserDelta,
WinnerOpDelta : winnerOp,
LoserOpDelta : loserOp);
await Task.WhenAll( await Task.WhenAll(
clientPush.PushAsync(winnerAccountId.ToString(), clientPush.PushAsync(winnerAccountId.ToString(),
ServerMessage.Push("game.over", push), ct), ServerMessage.Push("game.over", push), ct),
clientPush.PushAsync(loserAccountId.ToString(), clientPush.PushAsync(loserAccountId.ToString(),
ServerMessage.Push("game.over", push), ct)); ServerMessage.Push("game.over", push), ct));
// Publish inter-service event so ChatLifecycleHostedService archives the match channel.
await eventBus.PublishAsync(NatsSubjects.GameEnded,
new GameEndedEvent(
GameId : session.Id,
WinnerId : winnerAccountId,
LoserId : loserAccountId,
DurationSeconds : (int)(session.EndedAt!.Value - session.CreatedAt).TotalSeconds,
EndedAt : session.EndedAt.Value),
ct);
} }
} }