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

217 lines
8.2 KiB
C#

namespace KArtSell.Modules.ModelOperations.ApprovalWorkflow;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Dapper;
using KArtSell.BuildingBlocks.Time;
using Npgsql;
public class ApprovalSql
{
private readonly string _connectionString;
private readonly IClock _clock;
public ApprovalSql(string connectionString, IClock clock)
{
_connectionString = connectionString;
_clock = clock;
}
public async Task<ApprovalProposal?> GetProposalByIdAsync(Guid id, DateTimeOffset cutoff)
{
using var conn = new NpgsqlConnection(_connectionString);
const string sql = """
SELECT
id, model_id, status, created_by, created_at, justification, effective_at,
proposed_at, approved_by, approved_at, approval_notes, activated_by, activated_at,
published_at, revision, correlation_id
FROM model_operations.approval_proposals
WHERE id = @id
AND published_at <= @cutoff
ORDER BY published_at DESC
LIMIT 1
""";
var proposal = await conn.QueryFirstOrDefaultAsync<ApprovalProposalRaw>(sql, new { id, cutoff });
if (proposal == null) return null;
return MapFromRaw(proposal);
}
public async Task<List<ApprovalProposal>> GetProposalsByStatusAsync(string status, DateTimeOffset cutoff, int pageSize = 100)
{
using var conn = new NpgsqlConnection(_connectionString);
const string sql = """
SELECT
id, model_id, status, created_by, created_at, justification, effective_at,
proposed_at, approved_by, approved_at, approval_notes, activated_by, activated_at,
published_at, revision, correlation_id
FROM model_operations.approval_proposals
WHERE status = @status
AND published_at <= @cutoff
ORDER BY created_at DESC
LIMIT @pageSize
""";
var proposals = await conn.QueryAsync<ApprovalProposalRaw>(sql, new { status, cutoff, pageSize });
return proposals.Select(MapFromRaw).ToList();
}
public async Task InsertProposalAsync(
Guid id, Guid modelId, string status, string createdBy, string justification,
DateOnly effectiveAt, DateTimeOffset publishedAt, Guid correlationId)
{
using var conn = new NpgsqlConnection(_connectionString);
const string sql = """
INSERT INTO model_operations.approval_proposals
(id, model_id, status, created_by, created_at, justification, effective_at, published_at, revision, correlation_id)
VALUES (@id, @modelId, @status, @createdBy, @createdAt, @justification, @effectiveAt, @publishedAt, 1, @correlationId)
""";
await conn.ExecuteAsync(sql, new
{
id,
modelId,
status,
createdBy,
createdAt = _clock.UtcNow,
justification,
effectiveAt,
publishedAt,
correlationId
});
}
public async Task UpdateProposalStatusAsync(Guid id, string newStatus, string approvedBy, string? approvalNotes, DateTimeOffset publishedAt)
{
using var conn = new NpgsqlConnection(_connectionString);
const string sql = """
INSERT INTO model_operations.approval_proposals
(id, model_id, status, created_by, created_at, justification, effective_at,
approved_by, approved_at, approval_notes, published_at, revision, correlation_id)
SELECT id, model_id, @newStatus, created_by, created_at, justification, effective_at,
@approvedBy, @approvedAt, @approvalNotes, @publishedAt, revision + 1, correlation_id
FROM model_operations.approval_proposals
WHERE id = @id
ORDER BY published_at DESC LIMIT 1
""";
await conn.ExecuteAsync(sql, new
{
id,
newStatus,
approvedBy,
approvedAt = _clock.UtcNow,
approvalNotes,
publishedAt
});
}
public async Task InsertEvidenceAsync(Guid id, Guid proposalId, string evidenceType, string evidenceUrl, string? comment, Guid correlationId)
{
using var conn = new NpgsqlConnection(_connectionString);
const string sql = """
INSERT INTO model_operations.approval_evidence
(id, approval_proposal_id, evidence_type, evidence_url, reviewer_comment, published_at, correlation_id)
VALUES (@id, @proposalId, @evidenceType, @evidenceUrl, @comment, @publishedAt, @correlationId)
""";
await conn.ExecuteAsync(sql, new
{
id,
proposalId,
evidenceType,
evidenceUrl,
comment,
publishedAt = _clock.UtcNow,
correlationId
});
}
public async Task InsertEventAsync(Guid id, Guid proposalId, string eventType, string actorEmail, Dictionary<string, object>? details, Guid correlationId)
{
using var conn = new NpgsqlConnection(_connectionString);
const string sql = """
INSERT INTO model_operations.approval_events
(id, approval_proposal_id, event_type, actor_email, event_at, details, published_at, correlation_id)
VALUES (@id, @proposalId, @eventType, @actorEmail, @eventAt, @details::jsonb, @publishedAt, @correlationId)
""";
var detailsJson = details != null ? JsonSerializer.Serialize(details) : null;
await conn.ExecuteAsync(sql, new
{
id,
proposalId,
eventType,
actorEmail,
eventAt = _clock.UtcNow,
details = detailsJson,
publishedAt = _clock.UtcNow,
correlationId
});
}
public async Task<List<ApprovalEvidence>> GetEvidenceByProposalAsync(Guid proposalId, DateTimeOffset cutoff)
{
using var conn = new NpgsqlConnection(_connectionString);
const string sql = """
SELECT id, approval_proposal_id, evidence_type, evidence_url, reviewer_comment, published_at, correlation_id
FROM model_operations.approval_evidence
WHERE approval_proposal_id = @proposalId
AND published_at <= @cutoff
ORDER BY published_at DESC
""";
var results = await conn.QueryAsync<ApprovalEvidence>(sql, new { proposalId, cutoff });
return results.ToList();
}
private ApprovalProposal MapFromRaw(ApprovalProposalRaw raw)
{
return new ApprovalProposal
{
Id = raw.Id,
ModelId = raw.ModelId,
Status = Enum.Parse<ApprovalStatus>(raw.Status),
CreatedBy = raw.CreatedBy,
CreatedAt = raw.CreatedAt,
Justification = raw.Justification,
EffectiveAt = raw.EffectiveAt,
ProposedAt = raw.ProposedAt,
ApprovedBy = raw.ApprovedBy,
ApprovedAt = raw.ApprovedAt,
ApprovalNotes = raw.ApprovalNotes,
ActivatedBy = raw.ActivatedBy,
ActivatedAt = raw.ActivatedAt,
PublishedAt = raw.PublishedAt,
Revision = raw.Revision,
CorrelationId = raw.CorrelationId
};
}
private sealed class ApprovalProposalRaw
{
public Guid Id { get; set; }
public Guid ModelId { get; set; }
public string Status { get; set; } = null!;
public string CreatedBy { get; set; } = null!;
public DateTimeOffset CreatedAt { get; set; }
public string Justification { get; set; } = null!;
public DateOnly EffectiveAt { get; set; }
public DateTimeOffset? ProposedAt { get; set; }
public string? ApprovedBy { get; set; }
public DateTimeOffset? ApprovedAt { get; set; }
public string? ApprovalNotes { get; set; }
public string? ActivatedBy { get; set; }
public DateTimeOffset? ActivatedAt { get; set; }
public DateTimeOffset PublishedAt { get; set; }
public int Revision { get; set; }
public Guid CorrelationId { get; set; }
}
}