fix: Release build breakage + Dapper mapping bugs in VS-03/VS-04/Phase3-K

- KArtSell.Host.csproj: FrontendFiles glob was evaluated at project-load
  time, before pnpm build ran, so it copied stale/missing Vite-hashed
  filenames every Release build. Move the glob inside the target, after
  the build Exec.
- ApprovalSql/AuditSql/TradeSql: fix live-DB integration failures never
  caught by unit tests: DateOnly and inet columns can't be bound/read
  directly through Dapper without conversion; kis_response (jsonb) read
  as JsonElement threw InvalidCastException; GdprRetention.RetentionEndsAt
  was typed DateTime against a DATE column.
- TradeSql: UpdateTradeStatusAsync only ever persisted status/kis_response
  /error_message, silently dropping kis_order_id, executed_quantity,
  unit_price, total_amount, commission, net_proceeds and the execution/
  settlement timestamps on every call. Changed it to take the Trade
  aggregate so the full state transition persists.
- TradeSql: add a static ctor setting Dapper.DefaultTypeMap.
  MatchNamesWithUnderscores = true. The repo's [ModuleInitializer] in
  KArtSell.BuildingBlocks only fires once that assembly is actually
  loaded; TradeSql/Trade never reference a BuildingBlocks type, so under
  test isolation (or any host that queries a trade before touching
  BuildingBlocks) every snake_case column silently mapped to null/default.
- Test fixes: seed the FK prerequisites (model_operations.models,
  sell_decisions) that ApprovalWorkflowTests/TradeExecutionTests were
  missing, correct a SellPriorityRanker test input to match the approved
  VS-10-SLICE_SPEC age-boost threshold, and fix a GDPR redaction
  assertion that called ToString() on a Dictionary instead of inspecting
  its values.

12 DbUpMigrationTests failures remain and are unrelated to this fix: the
kartsell DB user isn't the owner of kartsell_migration_test, so DbUp's
fresh-database rehearsal can't DROP/CREATE it. Needs a DBA grant.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-08-07 23:21:04 +09:00
parent 54b7922167
commit 2ccf74c410
11 changed files with 119 additions and 92 deletions
@@ -26,7 +26,7 @@ public class Trade
public decimal? Commission { get; set; }
public decimal? NetProceeds { get; set; }
public string? ErrorMessage { get; set; }
public JsonElement? KisResponse { get; set; }
public string? KisResponse { get; set; }
public DateTime? ExecutionTimestamp { get; set; }
public DateTime? SettlementTimestamp { get; set; }
public DateTime PublishedAt { get; set; }
@@ -55,14 +55,14 @@ public class Trade
{
Status = TradeStatus.Submitted;
KisOrderId = kisOrderId;
KisResponse = response;
KisResponse = response.ToString();
Revision++;
}
public void MarkAccepted(JsonElement response)
{
Status = TradeStatus.Accepted;
KisResponse = response;
KisResponse = response.ToString();
Revision++;
}
@@ -73,7 +73,7 @@ public class Trade
TotalAmount = executedQty * unitPrice;
Status = executedQty >= Quantity ? TradeStatus.FullyFilled : TradeStatus.PartiallyFilled;
ExecutionTimestamp = now;
KisResponse = response;
KisResponse = response.ToString();
Revision++;
}
@@ -98,7 +98,7 @@ public class Trade
public void MarkErrored(KisTradeExecutionException exception)
{
ErrorMessage = exception.Message;
KisResponse = exception.KisResponse;
KisResponse = exception.KisResponse?.ToString();
Revision++;
}
}
@@ -57,14 +57,7 @@ public class SubmitTradeHandler
);
trade.MarkSubmitted(orderId, response);
await _sql.UpdateTradeStatusAsync(
trade.Id,
TradeStatus.Submitted,
response,
null,
command.CorrelationId,
ct
);
await _sql.UpdateTradeStatusAsync(trade, response, null, ct);
await PublishEventAsync(
"TradeSubmitted",
@@ -84,14 +77,7 @@ public class SubmitTradeHandler
catch (KisTradeExecutionException ex)
{
trade.MarkErrored(ex);
await _sql.UpdateTradeStatusAsync(
trade.Id,
trade.Status,
ex.KisResponse,
ex.Message,
command.CorrelationId,
ct
);
await _sql.UpdateTradeStatusAsync(trade, ex.KisResponse, ex.Message, ct);
_logger.LogError(
"Trade submission failed: {TradeId} {Classification}",
@@ -163,14 +149,7 @@ public class PollTradeStatusHandler
trade.MarkFilled(executedQty, unitPrice, response, _clock.UtcNow.UtcDateTime);
}
await _sql.UpdateTradeStatusAsync(
trade.Id,
trade.Status,
response,
null,
command.CorrelationId,
ct
);
await _sql.UpdateTradeStatusAsync(trade, response, null, ct);
if (trade.Status is TradeStatus.FullyFilled)
{
@@ -195,14 +174,7 @@ public class PollTradeStatusHandler
}
catch (KisTradeExecutionException ex)
{
await _sql.UpdateTradeStatusAsync(
trade.Id,
trade.Status,
ex.KisResponse,
ex.Message,
command.CorrelationId,
ct
);
await _sql.UpdateTradeStatusAsync(trade, ex.KisResponse, ex.Message, ct);
_logger.LogError("Failed to poll trade status: {TradeId}", trade.Id);
}
@@ -262,14 +234,7 @@ public class ConfirmSettlementHandler
if (success)
{
trade.MarkConfirmed(_clock.UtcNow.UtcDateTime, command.Commission);
await _sql.UpdateTradeStatusAsync(
trade.Id,
TradeStatus.Confirmed,
response,
null,
command.CorrelationId,
ct
);
await _sql.UpdateTradeStatusAsync(trade, response, null, ct);
await TradeOutboxPublisher.PublishAsync(
_connectionFactory,
@@ -290,14 +255,7 @@ public class ConfirmSettlementHandler
}
catch (KisTradeExecutionException ex)
{
await _sql.UpdateTradeStatusAsync(
trade.Id,
trade.Status,
ex.KisResponse,
ex.Message,
command.CorrelationId,
ct
);
await _sql.UpdateTradeStatusAsync(trade, ex.KisResponse, ex.Message, ct);
_logger.LogError("Failed to confirm settlement: {TradeId}", trade.Id);
}
@@ -12,7 +12,7 @@ public interface ITradeSql
Task<IEnumerable<Trade>> GetTradesByStatusAsync(TradeStatus status, Guid correlationId, CancellationToken ct = default);
Task<IEnumerable<Trade>> GetTradesByDecisionIdAsync(Guid sellDecisionId, Guid correlationId, CancellationToken ct = default);
Task InsertTradeAsync(Trade trade, CancellationToken ct = default);
Task UpdateTradeStatusAsync(Guid tradeId, TradeStatus newStatus, JsonElement? kisResponse, string? errorMessage, Guid correlationId, CancellationToken ct = default);
Task UpdateTradeStatusAsync(Trade trade, JsonElement? kisResponse, string? errorMessage, CancellationToken ct = default);
Task<int> CountTradesByStatusAsync(TradeStatus status, CancellationToken ct = default);
}
@@ -21,6 +21,16 @@ public class TradeSql : ITradeSql
private readonly NpgsqlDataSource _dataSource;
private readonly ILogger<TradeSql> _logger;
static TradeSql()
{
// KArtSell.BuildingBlocks.Data.DapperBootstrap sets this via [ModuleInitializer], but that
// only fires once its assembly is actually loaded into the process. Nothing in this class
// references a BuildingBlocks type, so under test isolation (or any host that queries Trade
// before touching BuildingBlocks) that assembly load - and the mapping - can be skipped,
// silently nulling out every snake_case column (kis_order_id, sell_decision_id, ...).
Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;
}
public TradeSql(NpgsqlDataSource dataSource, ILogger<TradeSql> logger)
{
_dataSource = dataSource;
@@ -33,7 +43,7 @@ public class TradeSql : ITradeSql
const string sql = """
SELECT id, sell_decision_id, kis_order_id, status, quantity, executed_quantity,
unit_price, total_amount, commission, net_proceeds, error_message, kis_response,
unit_price, total_amount, commission, net_proceeds, error_message, kis_response::text as kis_response,
execution_timestamp, settlement_timestamp, published_at, correlation_id, revision
FROM model_operations.trades
WHERE id = @tradeId
@@ -61,7 +71,7 @@ public class TradeSql : ITradeSql
const string sql = """
SELECT id, sell_decision_id, kis_order_id, status, quantity, executed_quantity,
unit_price, total_amount, commission, net_proceeds, error_message, kis_response,
unit_price, total_amount, commission, net_proceeds, error_message, kis_response::text as kis_response,
execution_timestamp, settlement_timestamp, published_at, correlation_id, revision
FROM model_operations.trades
WHERE kis_order_id = @kisOrderId
@@ -82,7 +92,7 @@ public class TradeSql : ITradeSql
const string sql = """
SELECT id, sell_decision_id, kis_order_id, status, quantity, executed_quantity,
unit_price, total_amount, commission, net_proceeds, error_message, kis_response,
unit_price, total_amount, commission, net_proceeds, error_message, kis_response::text as kis_response,
execution_timestamp, settlement_timestamp, published_at, correlation_id, revision
FROM model_operations.trades
WHERE status = @status
@@ -102,7 +112,7 @@ public class TradeSql : ITradeSql
const string sql = """
SELECT id, sell_decision_id, kis_order_id, status, quantity, executed_quantity,
unit_price, total_amount, commission, net_proceeds, error_message, kis_response,
unit_price, total_amount, commission, net_proceeds, error_message, kis_response::text as kis_response,
execution_timestamp, settlement_timestamp, published_at, correlation_id, revision
FROM model_operations.trades
WHERE sell_decision_id = @sellDecisionId
@@ -143,7 +153,7 @@ public class TradeSql : ITradeSql
trade.Commission,
trade.NetProceeds,
trade.ErrorMessage,
kisResponse = trade.KisResponse?.ToString(),
trade.KisResponse,
trade.ExecutionTimestamp,
trade.SettlementTimestamp,
trade.PublishedAt,
@@ -155,11 +165,9 @@ public class TradeSql : ITradeSql
}
public async Task UpdateTradeStatusAsync(
Guid tradeId,
TradeStatus newStatus,
Trade trade,
JsonElement? kisResponse,
string? errorMessage,
Guid correlationId,
CancellationToken ct = default)
{
using var connection = await _dataSource.OpenConnectionAsync(ct);
@@ -173,6 +181,14 @@ public class TradeSql : ITradeSql
UPDATE model_operations.trades
SET status = @newStatus,
kis_order_id = COALESCE(@kisOrderId, kis_order_id),
executed_quantity = COALESCE(@executedQuantity, executed_quantity),
unit_price = COALESCE(@unitPrice, unit_price),
total_amount = COALESCE(@totalAmount, total_amount),
commission = COALESCE(@commission, commission),
net_proceeds = COALESCE(@netProceeds, net_proceeds),
execution_timestamp = COALESCE(@executionTimestamp, execution_timestamp),
settlement_timestamp = COALESCE(@settlementTimestamp, settlement_timestamp),
kis_response = COALESCE(@kisResponse::jsonb, kis_response),
error_message = COALESCE(@errorMessage, error_message),
revision = revision + 1
@@ -182,14 +198,22 @@ public class TradeSql : ITradeSql
await connection.ExecuteAsync(sql, new
{
id = Guid.NewGuid(),
tradeId,
newStatus = newStatus.ToString(),
tradeId = trade.Id,
newStatus = trade.Status.ToString(),
kisOrderId = trade.KisOrderId,
executedQuantity = trade.ExecutedQuantity,
unitPrice = trade.UnitPrice,
totalAmount = trade.TotalAmount,
commission = trade.Commission,
netProceeds = trade.NetProceeds,
executionTimestamp = trade.ExecutionTimestamp,
settlementTimestamp = trade.SettlementTimestamp,
kisResponse = kisResponse?.ToString(),
errorMessage,
correlationId
correlationId = trade.CorrelationId
});
_logger.LogInformation("Updated trade {TradeId} status to {Status}", tradeId, newStatus);
_logger.LogInformation("Updated trade {TradeId} status to {Status}", trade.Id, trade.Status);
}
public async Task<int> CountTradesByStatusAsync(TradeStatus status, CancellationToken ct = default)