shoc-backend/Data.SeaHavenIndustries/Migrations/20260925001752_SH393_BackfillBoardCreatedDispatchWorkOrder.cs
Alexandre Brandizzi 89376e99e4 fix(uplifts): resolve work-order uplifts through owned dispatches (SH-393)
Board create left the new primary dispatch with no WorkOrderId, so uplifts
created on those work orders were written to a dispatch the work order's
uplift reads never resolve: not listed, allowance never consumed, queue WO
number blank. The same orphan made ApptDate/vendor patches fail with
"A primary dispatch is required".

- Board create backfills Dispatch.WorkOrderId after the first save.
- Uplift create resolves its dispatch through the read-side scope
  (non-deleted, owned or linked); otherwise the stable
  "no primary dispatch" error.
- Data-only migration assigns existing orphaned primaries to the single
  work order naming them primary; idempotent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 21:22:13 -03:00

43 lines
1.7 KiB
C#

using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Data.SeaHavenIndustries.Migrations
{
/// <summary>
/// SH-393: board-created work orders with a vendor stored their primary dispatch with
/// no WorkOrderId and no DispatchWorkOrders link, so every owned-or-linked read (uplift
/// list, allowance, approval queue WO number, dispatch patches) missed it. Data-only
/// heal: assign the dispatch to the single work order that names it as primary. Rows
/// already owned or linked, and dispatches named primary by more than one work order,
/// are left untouched, so re-running is a no-op.
/// </summary>
public partial class SH393_BackfillBoardCreatedDispatchWorkOrder : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(
"""
UPDATE d
SET d.[WorkOrderId] = w.[Id]
FROM [Dispatches] AS d
INNER JOIN [workOrders] AS w ON w.[PrimaryDispatchId] = d.[Id]
WHERE d.[WorkOrderId] IS NULL
AND NOT EXISTS (
SELECT 1 FROM [DispatchWorkOrders] AS l
WHERE l.[DispatchId] = d.[Id])
AND (
SELECT COUNT(*) FROM [workOrders] AS owner
WHERE owner.[PrimaryDispatchId] = d.[Id]) = 1;
""");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
// The heal is not reversible: healed rows are indistinguishable from dispatches
// that were created with their work order set.
}
}
}