Files
KArtSell.Aegis/src/KArtSell.Modules.ModelOperations/PortfolioReconciliation/ReconcileTradeHandler.cs
T
kjh2064 b1e38ac374 feat: Phase 3 J/K/L (Sell Decision, Trade Execution, Portfolio Reconciliation) + fix pre-existing build/boot breakage
Completes VS-10/VS-12/VS-14 and makes the solution and Host actually
build and boot for the first time on this branch (main did not build
before this commit).

Root-cause fixes required to reach a green build/boot (not scoped to
J/K/L but blocking any verification of it):
- Restore Polly PackageVersion accidentally deleted from
  Directory.Packages.props (broke KArtSell.Host).
- Remove MediatR dependency from Compliance/VS-04 (package was never
  installed; ICommand/ICommandHandler/IMediator never existed) and
  wire Endpoint -> Handler directly per this repo's convention.
- Migrate FastEndpoints v5 API calls (SendOkAsync/SendAsync/
  SendCreatedAtAsync/SendNotFoundAsync, Description().WithName()) to
  the v7 Send.* fluent API across ~10 endpoint files.
- Fix migrations 0036/0038/0039/0040: rewritten from invalid T-SQL
  (`IF NOT EXISTS ... BEGIN ... END`) to idiomatic Postgres
  (`CREATE TABLE/INDEX IF NOT EXISTS`) — these could not apply to any
  fresh database before this fix.
- Collapse 3 duplicate cross-cutting abstractions that shadowed the
  BuildingBlocks versions and caused type-mismatch compile errors:
  IKrxDataService, IOutboxWriter (ReconcileTradeHandler), IClock
  (ApprovalWorkflow/ApprovalPolicy).
- Inject IClock (BuildingBlocks.Time) in place of direct
  DateTime.Now/UtcNow across 19 files to satisfy the architecture
  test AGENTS.md#DateTime-abstraction rule (13/13 architecture tests
  now pass, was 12/13).
- Register all new and previously-unregistered slices in
  Program.cs DI (SellDecision, TradeExecution, PortfolioReconciliation,
  Compliance, Features/ApprovalWorkflow) — the Host had never
  successfully completed a boot with this code present.
- Disable ("[DontRegister]") the older, route-colliding
  ApprovalWorkflow/ (Workstream H) endpoint set in favor of
  Features/ApprovalWorkflow/ (Workstream G, matches the documented
  Features/<Slice>/ convention); kept for its existing test coverage.
  See TECH_DEBT-017 for the follow-up decision needed.

Verified: dotnet build 0 errors/0 warnings; architecture tests 13/13;
unit tests 54/54 + 18/18; integration tests 34/36 (2 failures are a
local test-DB migration-journal/schema mismatch, not a code defect);
Host boots cleanly and registers all 34 endpoints.

New tech debt recorded: DEBT-017 (duplicate VS-03 implementation),
DEBT-018 (outbox write not co-transactional with entity write in
TradeExecution/PortfolioReconciliation), DEBT-019 (duplicate
BuildingBlocks-shadowing abstractions, partially resolved).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 19:53:38 +09:00

181 lines
6.6 KiB
C#

namespace KArtSell.Modules.ModelOperations.PortfolioReconciliation;
using System;
using System.Text.Json;
using System.Threading.Tasks;
using KArtSell.BuildingBlocks.Data;
using KArtSell.BuildingBlocks.Hashing;
using KArtSell.BuildingBlocks.Reliability;
using KArtSell.BuildingBlocks.Time;
/// <summary>
/// Handles trade reconciliation command.
/// Updates holdings, calculates cost basis, detects mismatches.
/// Publishes reconciliation event to Outbox.
/// </summary>
public class ReconcileTradeCommand
{
public Guid TradeId { get; set; }
public Guid SecurityId { get; set; }
public int ExecutedQuantity { get; set; }
public decimal ExecutedPrice { get; set; }
public int ApprovedQuantity { get; set; }
public decimal ApprovedPrice { get; set; }
public DateTime TradeDate { get; set; }
public DateTime ExpectedSettlementDate { get; set; }
public DateTime? ActualSettlementDate { get; set; }
public Guid CorrelationId { get; set; }
public string? IdempotencyKey { get; set; }
}
public class ReconcileTradeHandler
{
private readonly ReconciliationEngine _engine;
private readonly IDbConnectionFactory _connectionFactory;
private readonly IOutboxWriter _outboxWriter;
private readonly IClock _clock;
public ReconcileTradeHandler(
ReconciliationEngine engine,
IDbConnectionFactory connectionFactory,
IOutboxWriter outboxWriter,
IClock clock)
{
_engine = engine ?? throw new ArgumentNullException(nameof(engine));
_connectionFactory = connectionFactory ?? throw new ArgumentNullException(nameof(connectionFactory));
_outboxWriter = outboxWriter ?? throw new ArgumentNullException(nameof(outboxWriter));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
}
public async Task HandleAsync(ReconcileTradeCommand command)
{
ArgumentNullException.ThrowIfNull(command);
var result = await _engine.ReconcileTradeAsync(
command.TradeId,
command.SecurityId,
command.ExecutedQuantity,
command.ExecutedPrice,
command.ApprovedQuantity,
command.ApprovedPrice,
command.TradeDate,
command.ExpectedSettlementDate,
command.ActualSettlementDate,
command.CorrelationId);
if (!result.Success)
{
throw new InvalidOperationException($"Reconciliation failed: {result.Error}");
}
// Publish event to Outbox for async processing
var @event = new TradeReconciledEvent
{
EventId = Guid.NewGuid(),
TradeId = command.TradeId,
HoldingId = result.Holding!.Id,
SecurityId = command.SecurityId,
QuantityAfter = result.Holding.Quantity,
CostBasisAfter = result.Holding.TotalCostBasis,
MismatchDetected = result.MismatchDetected,
MismatchSummary = result.MismatchDetected
? FormatMismatchSummary(result.Mismatches)
: null,
ReconciliationTimestamp = _clock.UtcNow.UtcDateTime,
CorrelationId = command.CorrelationId,
IdempotencyKey = command.IdempotencyKey ?? Guid.NewGuid().ToString()
};
await PublishAsync("TradeReconciled", @event, command.CorrelationId, CancellationToken.None);
// If mismatches detected, publish alert event
if (result.MismatchDetected)
{
var alertEvent = new ReconciliationMismatchAlertEvent
{
EventId = Guid.NewGuid(),
TradeId = command.TradeId,
HoldingId = result.Holding.Id,
MismatchCount = result.Mismatches.Count,
HighSeverityCount = CountBysSeverity(result.Mismatches, MismatchSeverity.High),
MismatchDetails = FormatMismatchDetails(result.Mismatches),
AlertedAt = _clock.UtcNow.UtcDateTime,
CorrelationId = command.CorrelationId
};
await PublishAsync("ReconciliationMismatchAlert", alertEvent, command.CorrelationId, CancellationToken.None);
}
}
/// <summary>
/// DEBT-TRADE-001: outbox write happens in its own transaction, separate from the
/// preceding holding/log writes owned by ReconciliationSql. Not yet atomic with the
/// entity write. See TECH_DEBT_REGISTER.md.
/// </summary>
private async Task PublishAsync<T>(string eventType, T @event, Guid correlationId, CancellationToken ct) where T : class
{
var payload = JsonSerializer.Serialize(@event);
var message = new OutboxMessage(
Guid.NewGuid(),
eventType,
1,
payload,
correlationId.ToString(),
_clock.UtcNow,
ContentHasher.Sha256(payload));
await using var connection = await _connectionFactory.OpenAsync(ct);
await using var transaction = await connection.BeginTransactionAsync(ct);
await _outboxWriter.AddAsync(connection, transaction, message, ct);
await transaction.CommitAsync(ct);
}
private int CountBysSeverity(List<Mismatch> mismatches, MismatchSeverity severity)
{
return mismatches.Count(m => m.Severity == severity);
}
private string FormatMismatchSummary(List<Mismatch> mismatches)
{
return string.Join("; ", mismatches.ConvertAll(m => m.Type.ToString()));
}
private string FormatMismatchDetails(List<Mismatch> mismatches)
{
return string.Join("\n", mismatches.ConvertAll(m => $"{m.Type}: {m.Description}"));
}
}
/// <summary>
/// Event published when trade is reconciled.
/// </summary>
public class TradeReconciledEvent
{
public Guid EventId { get; set; }
public Guid TradeId { get; set; }
public Guid HoldingId { get; set; }
public Guid SecurityId { get; set; }
public int QuantityAfter { get; set; }
public decimal CostBasisAfter { get; set; }
public bool MismatchDetected { get; set; }
public string? MismatchSummary { get; set; }
public DateTime ReconciliationTimestamp { get; set; }
public Guid CorrelationId { get; set; }
public string IdempotencyKey { get; set; } = string.Empty;
}
/// <summary>
/// Event published when reconciliation mismatches are detected.
/// </summary>
public class ReconciliationMismatchAlertEvent
{
public Guid EventId { get; set; }
public Guid TradeId { get; set; }
public Guid HoldingId { get; set; }
public int MismatchCount { get; set; }
public int HighSeverityCount { get; set; }
public string MismatchDetails { get; set; } = string.Empty;
public DateTime AlertedAt { get; set; }
public Guid CorrelationId { get; set; }
}