Files
KArtSell.Aegis/src/KArtSell.Modules.ModelOperations/PortfolioReconciliation/Endpoints.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

254 lines
8.1 KiB
C#

namespace KArtSell.Modules.ModelOperations.PortfolioReconciliation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FastEndpoints;
using KArtSell.BuildingBlocks.Time;
/// <summary>
/// GET /reconciliation/holdings - Returns current portfolio holdings
/// </summary>
public class GetHoldingsEndpoint : EndpointWithoutRequest<GetHoldingsResponse>
{
private readonly IReconciliationRepository _repository;
public GetHoldingsEndpoint(IReconciliationRepository repository)
{
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
}
public override void Configure()
{
Get("/reconciliation/holdings");
AllowAnonymous();
}
public override async Task HandleAsync(CancellationToken ct)
{
var holdings = await _repository.GetOpenHoldingsAsync();
var response = new GetHoldingsResponse
{
Items = holdings.ConvertAll(h => new HoldingDto
{
Id = h.Id,
SecurityId = h.SecurityId,
Quantity = h.Quantity,
WeightedAvgCost = h.WeightedAvgCost,
TotalCostBasis = h.TotalCostBasis,
MarketValue = h.MarketValue,
UnrealizedGainLoss = h.UnrealizedGainLoss,
UpdatedAt = h.UpdatedAt,
CorrelationId = h.CorrelationId
}),
Total = holdings.Count,
Pages = 1
};
await Send.OkAsync(response, ct);
}
}
public class GetHoldingsResponse
{
public List<HoldingDto> Items { get; set; } = new();
public int Total { get; set; }
public int Pages { get; set; }
}
public class HoldingDto
{
public Guid Id { get; set; }
public Guid SecurityId { get; set; }
public int Quantity { get; set; }
public decimal WeightedAvgCost { get; set; }
public decimal TotalCostBasis { get; set; }
public decimal? MarketValue { get; set; }
public decimal? UnrealizedGainLoss { get; set; }
public DateTime UpdatedAt { get; set; }
public Guid CorrelationId { get; set; }
}
/// <summary>
/// GET /reconciliation/mismatches - Returns flagged discrepancies
/// </summary>
public class GetMismatchesEndpoint : EndpointWithoutRequest<GetMismatchesResponse>
{
private readonly IReconciliationRepository _repository;
private readonly IClock _clock;
public GetMismatchesEndpoint(IReconciliationRepository repository, IClock clock)
{
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
}
public override void Configure()
{
Get("/reconciliation/mismatches");
AllowAnonymous();
}
public override async Task HandleAsync(CancellationToken ct)
{
var now = _clock.UtcNow.UtcDateTime;
var dateFrom = HttpContext.Request.Query.TryGetValue("dateFrom", out var fromVal)
? DateTime.Parse(fromVal.ToString())
: now.AddDays(-30);
var dateTo = HttpContext.Request.Query.TryGetValue("dateTo", out var toVal)
? DateTime.Parse(toVal.ToString())
: now;
var logs = await _repository.GetReconciliationLogsAsync(dateFrom, dateTo);
var mismatches = logs.Where(l => l.MismatchDetected).ToList();
var response = new GetMismatchesResponse
{
Items = mismatches.ConvertAll(m => new MismatchDto
{
Id = m.Id,
TradeId = m.TradeId,
HoldingId = m.HoldingId,
MismatchReason = m.MismatchReason,
QuantityBefore = m.QuantityBefore,
QuantityAfter = m.QuantityAfter,
CostBasisDelta = m.CostBasisDelta,
DetectedAt = m.ReconciledAt
}),
Total = mismatches.Count,
Pages = 1
};
await Send.OkAsync(response, ct);
}
}
public class GetMismatchesResponse
{
public List<MismatchDto> Items { get; set; } = new();
public int Total { get; set; }
public int Pages { get; set; }
}
public class MismatchDto
{
public Guid Id { get; set; }
public Guid TradeId { get; set; }
public Guid HoldingId { get; set; }
public string? MismatchReason { get; set; }
public int QuantityBefore { get; set; }
public int QuantityAfter { get; set; }
public decimal CostBasisDelta { get; set; }
public DateTime DetectedAt { get; set; }
}
/// <summary>
/// POST /reconciliation/reconcile-trade - Trigger trade reconciliation
/// </summary>
public class ReconcileTradeEndpoint : Endpoint<ReconcileTradeRequest>
{
private readonly ReconcileTradeHandler _handler;
public ReconcileTradeEndpoint(ReconcileTradeHandler handler)
{
_handler = handler ?? throw new ArgumentNullException(nameof(handler));
}
public override void Configure()
{
Post("/reconciliation/reconcile-trade");
AllowAnonymous();
}
public override async Task HandleAsync(ReconcileTradeRequest request, CancellationToken ct)
{
var command = new ReconcileTradeCommand
{
TradeId = request.TradeId,
SecurityId = request.SecurityId,
ExecutedQuantity = request.ExecutedQuantity,
ExecutedPrice = request.ExecutedPrice,
ApprovedQuantity = request.ApprovedQuantity,
ApprovedPrice = request.ApprovedPrice,
TradeDate = request.TradeDate,
ExpectedSettlementDate = request.ExpectedSettlementDate,
ActualSettlementDate = request.ActualSettlementDate,
CorrelationId = request.CorrelationId,
IdempotencyKey = request.IdempotencyKey
};
await _handler.HandleAsync(command);
await Send.NoContentAsync(ct);
}
}
public class ReconcileTradeRequest
{
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; }
}
/// <summary>
/// GET /reconciliation/report/daily - Returns daily reconciliation report
/// </summary>
public class GetDailyReportEndpoint : EndpointWithoutRequest<ReconciliationReportDto>
{
private readonly ReconciliationEngine _engine;
private readonly IClock _clock;
public GetDailyReportEndpoint(ReconciliationEngine engine, IClock clock)
{
_engine = engine ?? throw new ArgumentNullException(nameof(engine));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
}
public override void Configure()
{
Get("/reconciliation/report/daily");
AllowAnonymous();
}
public override async Task HandleAsync(CancellationToken ct)
{
var reportDate = _clock.UtcNow.UtcDateTime;
var report = await _engine.GenerateDailyReportAsync(reportDate, Guid.NewGuid());
var response = new ReconciliationReportDto
{
ReportDate = report.ReportDate,
TotalLogsProcessed = report.TotalLogsProcessed,
TotalMismatches = report.TotalMismatches,
MismatchesByHighSeverity = report.MismatchesByHighSeverity,
MismatchesByMediumSeverity = report.MismatchesByMediumSeverity,
MismatchPercentage = report.MismatchPercentage,
GeneratedAt = report.GeneratedAt
};
await Send.OkAsync(response, ct);
}
}
public class ReconciliationReportDto
{
public DateTime ReportDate { get; set; }
public int TotalLogsProcessed { get; set; }
public int TotalMismatches { get; set; }
public int MismatchesByHighSeverity { get; set; }
public int MismatchesByMediumSeverity { get; set; }
public double MismatchPercentage { get; set; }
public DateTime GeneratedAt { get; set; }
}