Files
KArtSell.Aegis/db/migrations/0040_reconciliation.sql
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

76 lines
3.6 KiB
SQL

-- Migration 0040: Portfolio Reconciliation Schema (VS-14)
-- Creates tables for holdings tracking, cost basis, and reconciliation logs
CREATE SCHEMA IF NOT EXISTS portfolio_management;
CREATE TABLE IF NOT EXISTS portfolio_management.holdings (
id UUID PRIMARY KEY,
security_id UUID NOT NULL,
quantity INT NOT NULL DEFAULT 0,
weighted_avg_cost DECIMAL(15,2) NOT NULL DEFAULT 0,
total_cost_basis DECIMAL(18,2) NOT NULL DEFAULT 0,
market_value DECIMAL(18,2),
unrealized_gain_loss DECIMAL(18,2),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
published_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
correlation_id UUID NOT NULL,
revision INT NOT NULL DEFAULT 1,
CONSTRAINT chk_quantity_non_negative CHECK (quantity >= 0),
CONSTRAINT chk_cost_basis_non_negative CHECK (total_cost_basis >= 0)
);
CREATE INDEX IF NOT EXISTS idx_holdings_security_id ON portfolio_management.holdings(security_id);
CREATE INDEX IF NOT EXISTS idx_holdings_correlation_id ON portfolio_management.holdings(correlation_id);
CREATE INDEX IF NOT EXISTS idx_holdings_updated_at ON portfolio_management.holdings(updated_at DESC);
CREATE TABLE IF NOT EXISTS portfolio_management.reconciliation_logs (
id UUID PRIMARY KEY,
trade_id UUID NOT NULL,
holding_id UUID NOT NULL REFERENCES portfolio_management.holdings(id),
quantity_before INT,
quantity_after INT,
cost_basis_delta DECIMAL(18,2),
unrealized_gain_loss_delta DECIMAL(18,2),
mismatch_detected BOOLEAN DEFAULT FALSE,
mismatch_reason VARCHAR(255),
reconciled_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
published_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
correlation_id UUID NOT NULL,
CONSTRAINT chk_mismatch_reason_when_detected
CHECK (NOT mismatch_detected OR mismatch_reason IS NOT NULL)
);
CREATE INDEX IF NOT EXISTS idx_reconciliation_logs_trade_id ON portfolio_management.reconciliation_logs(trade_id);
CREATE INDEX IF NOT EXISTS idx_reconciliation_logs_holding_id ON portfolio_management.reconciliation_logs(holding_id);
CREATE INDEX IF NOT EXISTS idx_reconciliation_logs_mismatch ON portfolio_management.reconciliation_logs(mismatch_detected);
CREATE INDEX IF NOT EXISTS idx_reconciliation_logs_correlation_id ON portfolio_management.reconciliation_logs(correlation_id);
CREATE INDEX IF NOT EXISTS idx_reconciliation_logs_reconciled_at ON portfolio_management.reconciliation_logs(reconciled_at DESC);
CREATE TABLE IF NOT EXISTS portfolio_management.lots (
id UUID PRIMARY KEY,
holding_id UUID NOT NULL REFERENCES portfolio_management.holdings(id),
purchase_date DATE NOT NULL,
quantity INT NOT NULL,
unit_cost DECIMAL(15,2) NOT NULL,
total_cost DECIMAL(18,2) NOT NULL,
status VARCHAR(50) NOT NULL DEFAULT 'OPEN',
fifo_order INT NOT NULL,
published_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
correlation_id UUID NOT NULL,
CONSTRAINT chk_lot_quantity_positive CHECK (quantity > 0),
CONSTRAINT chk_lot_status CHECK (status IN ('OPEN', 'PARTIAL_SOLD', 'CLOSED'))
);
CREATE INDEX IF NOT EXISTS idx_lots_holding_id ON portfolio_management.lots(holding_id);
CREATE INDEX IF NOT EXISTS idx_lots_status ON portfolio_management.lots(status);
CREATE INDEX IF NOT EXISTS idx_lots_fifo_order ON portfolio_management.lots(holding_id, fifo_order);
CREATE INDEX IF NOT EXISTS idx_lots_correlation_id ON portfolio_management.lots(correlation_id);
-- Grant permissions (adjust to match your security model)
GRANT SELECT, INSERT ON portfolio_management.holdings TO kartsell;
GRANT SELECT, INSERT ON portfolio_management.reconciliation_logs TO kartsell;
GRANT SELECT, INSERT ON portfolio_management.lots TO kartsell;