feat: add production templates API and documentation for manufacturing phase 2
- Implemented CRUD operations for production templates, including listing, retrieving, creating, updating, and deactivating templates. - Introduced a new API contract for production runs, detailing the lifecycle from creation to completion, including handling of stock inputs and outputs. - Documented the architecture, requirements, entity model, and API contract for the manufacturing phase 2, ensuring clarity on the production process and its integration with existing systems.
This commit is contained in:
@@ -33,9 +33,9 @@ public sealed class GrnService : IGrnService
|
||||
private readonly IRepository<Bin> _bins;
|
||||
private readonly IRepository<Vendor> _vendors;
|
||||
private readonly IRepository<Batch> _batches;
|
||||
private readonly IRepository<UomConversion> _conversions;
|
||||
private readonly IRepository<StockLayer> _layers;
|
||||
private readonly IRepository<StockLedger> _ledger;
|
||||
private readonly IUomConverter _uomConverter;
|
||||
private readonly IFifoCostingService _fifo;
|
||||
private readonly INumberSequenceService _numbers;
|
||||
private readonly ICurrentUser _currentUser;
|
||||
@@ -45,7 +45,7 @@ public sealed class GrnService : IGrnService
|
||||
IRepository<Grn> grns, IRepository<PurchaseOrder> pos, IRepository<PoLine> poLines,
|
||||
IRepository<Item> items, IRepository<Uom> uoms, IRepository<Warehouse> warehouses,
|
||||
IRepository<Bin> bins, IRepository<Vendor> vendors, IRepository<Batch> batches,
|
||||
IRepository<UomConversion> conversions, IRepository<StockLayer> layers, IRepository<StockLedger> ledger,
|
||||
IRepository<StockLayer> layers, IRepository<StockLedger> ledger, IUomConverter uomConverter,
|
||||
IFifoCostingService fifo, INumberSequenceService numbers, ICurrentUser currentUser, IUnitOfWork uow)
|
||||
{
|
||||
_grns = grns;
|
||||
@@ -57,9 +57,9 @@ public sealed class GrnService : IGrnService
|
||||
_bins = bins;
|
||||
_vendors = vendors;
|
||||
_batches = batches;
|
||||
_conversions = conversions;
|
||||
_layers = layers;
|
||||
_ledger = ledger;
|
||||
_uomConverter = uomConverter;
|
||||
_fifo = fifo;
|
||||
_numbers = numbers;
|
||||
_currentUser = currentUser;
|
||||
@@ -345,19 +345,14 @@ public sealed class GrnService : IGrnService
|
||||
return created; // linked via GrnLine.Batch navigation; FK fixed up on SaveChanges
|
||||
}
|
||||
|
||||
private async Task<(decimal QtyBase, decimal UnitCostBase)> ToBaseAsync(
|
||||
/// <summary>
|
||||
/// Delegates to the shared <see cref="IUomConverter"/>. This was a private method here
|
||||
/// until manufacturing needed the same conversion for stage stock inputs; behaviour is
|
||||
/// identical, so receive costing is unchanged.
|
||||
/// </summary>
|
||||
private Task<(decimal QtyBase, decimal UnitCostBase)> ToBaseAsync(
|
||||
Item item, int uomId, decimal qty, decimal unitCostPerUom, CancellationToken ct)
|
||||
{
|
||||
if (uomId == item.BaseUomId)
|
||||
return (qty, unitCostPerUom);
|
||||
|
||||
var conv = await _conversions.Query().AsNoTracking()
|
||||
.FirstOrDefaultAsync(c => c.ItemId == item.ItemId && c.FromUomId == uomId && c.ToUomId == item.BaseUomId, ct)
|
||||
?? throw new DomainException(ErrorCodes.Validation,
|
||||
$"No UOM conversion from {uomId} to base UOM {item.BaseUomId} for item {item.ItemId}.", 422);
|
||||
|
||||
return (qty * conv.Factor, unitCostPerUom / conv.Factor);
|
||||
}
|
||||
=> _uomConverter.ToBaseAsync(item, uomId, qty, unitCostPerUom, ct);
|
||||
|
||||
private async Task UpdatePoStatusAsync(int? poId, CancellationToken ct)
|
||||
{
|
||||
|
||||
@@ -29,11 +29,22 @@ public interface IFifoCostingService
|
||||
Task<IReadOnlyList<ConsumedSegment>> ConsumeAsync(
|
||||
int itemId, int warehouseId, int? batchId, decimal qtyBase, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Append an immutable ledger entry (value = qtyBase × unitCost).</summary>
|
||||
/// <summary>
|
||||
/// Append an immutable ledger entry. Value defaults to <c>round(qtyBase × unitCost, 4)</c>.
|
||||
/// </summary>
|
||||
/// <param name="valueOverride">
|
||||
/// Posts this exact value instead of deriving it from qty × unit cost. Needed when the
|
||||
/// authoritative figure is a total rather than a rate: a production receipt must carry the
|
||||
/// run's cost pool exactly, but <c>unitCost = pool / goodQty</c> rounds to 6 dp, and at
|
||||
/// 100+ units that rounding error exceeds the ledger's 4 dp tick — so the derived value
|
||||
/// would drift from the pool (FR-MFG-13). Also used by leftover and cancel returns, whose
|
||||
/// value is the exact consumed residual. Omit for every rate-driven movement.
|
||||
/// </param>
|
||||
Task<StockLedger> PostLedgerAsync(
|
||||
int itemId, int warehouseId, int? binId, int? batchId, int? serialId, int userId,
|
||||
Direction direction, decimal qtyBase, decimal unitCost, decimal runningBalance,
|
||||
string sourceDocType, int sourceDocId, DateTime createdAt, CancellationToken ct = default);
|
||||
string sourceDocType, int sourceDocId, DateTime createdAt, CancellationToken ct = default,
|
||||
decimal? valueOverride = null);
|
||||
|
||||
/// <summary>Current on-hand (Σ open-layer qtyRemaining) for an item at a warehouse.</summary>
|
||||
Task<decimal> GetOnHandAsync(int itemId, int warehouseId, CancellationToken ct = default);
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
using ERPCore.Common.Http;
|
||||
using ERPCore.Domain.Enums;
|
||||
using ERPCore.Dtos.Common;
|
||||
using ERPCore.Dtos.Production;
|
||||
|
||||
namespace ERPCore.Services.Interfaces;
|
||||
|
||||
/// <summary>
|
||||
/// Production run lifecycle (docs/30 §D.2–D.3, FR-MFG-08..19). Every stock-affecting
|
||||
/// action runs inside a single <c>ExecuteInTransactionAsync</c> scope and consumes stock
|
||||
/// only through <c>IFifoCostingService</c> (NFR-02/NFR-05).
|
||||
/// </summary>
|
||||
public interface IProductionRunService
|
||||
{
|
||||
Task<PagedResponse<RunSummaryDto>> ListAsync(
|
||||
PageQuery query, ProductionRunStatus? status, int? templateId, int? warehouseId,
|
||||
CancellationToken ct = default);
|
||||
|
||||
Task<ETagged<RunGraphDto>?> GetAsync(int runId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Instantiates a template (FR-MFG-08): copies every stage, input, output and edge,
|
||||
/// scales all quantities by <c>targetQty / terminalOutputQtyPerBatch</c>, issues a
|
||||
/// <c>PRD-…</c> document number, and leaves entry stages Ready with the rest Waiting.
|
||||
/// </summary>
|
||||
Task<ETagged<RunGraphDto>> CreateAsync(CreateRunRequest request, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Per-run quantity override on a stage that has not started
|
||||
/// (<c>409 STAGE_NOT_EDITABLE</c> once it has). Re-evaluates the stage's readiness,
|
||||
/// since raising an upstream input's planned quantity can un-ready it.
|
||||
/// </summary>
|
||||
Task<RunStageDto> UpdateStageQuantitiesAsync(
|
||||
int runId, int runStageId, UpdateStageQuantitiesRequest request, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// <c>Ready → InProgress</c> (FR-MFG-10). FIFO-consumes every Stock input from the run
|
||||
/// warehouse in one transaction and stamps <c>actualStartAt</c>.
|
||||
/// <para>Consumes <c>max(0, plannedBase − consumedQty)</c> per input, so a rework
|
||||
/// restart with an unchanged planned quantity consumes nothing and one with a raised
|
||||
/// planned quantity consumes only the delta (FR-MFG-16).</para>
|
||||
/// </summary>
|
||||
Task<StartStageResultDto> StartStageAsync(int runId, int runStageId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// <c>InProgress → Done</c> (FR-MFG-11). Records produced and scrapped quantities per
|
||||
/// output plus the custom field values. A re-complete after a rework <b>overwrites</b>
|
||||
/// the previous figures rather than adding to them.
|
||||
/// </summary>
|
||||
Task<RunStageDto> CompleteStageAsync(
|
||||
int runId, int runStageId, CompleteStageRequest request, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// <c>Done → Approved</c> (FR-MFG-12/13). Non-terminal: hands WIP to the children,
|
||||
/// defaulting to the full available quantity. Terminal: posts the production receipt —
|
||||
/// a finished-goods layer costed at <c>costPool / goodQty</c> — and completes the run.
|
||||
/// </summary>
|
||||
Task<ApproveStageResultDto> ApproveStageAsync(
|
||||
int runId, int runStageId, ApproveStageRequest request, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Later partial transfer of a remainder held on an already-Approved stage (FR-MFG-12),
|
||||
/// never exceeding produced − scrapped − already transferred.
|
||||
/// </summary>
|
||||
Task<TransferResultDto> TransferAsync(
|
||||
int runId, int runStageId, TransferRemainderRequest request, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Returns unconsumed material to stock before the receipt closes the pool (FR-MFG-14).
|
||||
/// The inbound layer is created at the <b>weighted cost actually consumed</b> for that
|
||||
/// input, so the move is cost-preserving and the pool reduces by exactly what leaves it.
|
||||
/// <c>409 RUN_COST_CLOSED</c> once the run has completed.
|
||||
/// </summary>
|
||||
Task<ReturnLeftoverResultDto> ReturnLeftoverAsync(
|
||||
int runId, int runInputId, ReturnLeftoverRequest request, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Downstream reject (FR-MFG-15): this stage rejects the work it received, its delivering
|
||||
/// parents revert <c>Approved → InProgress</c> with their transferred quantities pulled
|
||||
/// back, and this stage returns to Waiting. Consumed stock stays consumed.
|
||||
/// </summary>
|
||||
Task<RejectIntakeResultDto> RejectIntakeAsync(
|
||||
int runId, int runStageId, RejectRequest request, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Terminal reject (FR-MFG-16): resets the whole run to its starting stages, increments
|
||||
/// <c>reworkCount</c> and snapshots the discarded figures into the event history.
|
||||
/// Already-consumed material remains in the cost pool.
|
||||
/// </summary>
|
||||
Task<TerminalRejectResultDto> RejectTerminalAsync(
|
||||
int runId, int runStageId, RejectRequest request, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Cancels an in-progress run (FR-MFG-17). Net consumed-and-not-returned stock goes back
|
||||
/// at its consumed weighted cost; scrapped output quantities are written off on the event.
|
||||
/// <c>409 RUN_NOT_CANCELLABLE</c> for a completed run.
|
||||
/// </summary>
|
||||
Task<CancelRunResultDto> CancelAsync(int runId, CancelRunRequest request, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using ERPCore.Common.Http;
|
||||
using ERPCore.Domain.Enums;
|
||||
using ERPCore.Dtos.Common;
|
||||
using ERPCore.Dtos.Production;
|
||||
|
||||
namespace ERPCore.Services.Interfaces;
|
||||
|
||||
/// <summary>
|
||||
/// Production template CRUD and graph validation (docs/30 §D.1, FR-MFG-01..07).
|
||||
/// </summary>
|
||||
public interface IProductionTemplateService
|
||||
{
|
||||
Task<PagedResponse<TemplateSummaryDto>> ListAsync(PageQuery query, EntityStatus? status, CancellationToken ct = default);
|
||||
|
||||
Task<ETagged<TemplateGraphDto>?> GetAsync(int templateId, CancellationToken ct = default);
|
||||
|
||||
Task<ETagged<TemplateGraphDto>> CreateAsync(SaveTemplateRequest request, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Replaces the whole graph. Requires the current row version (<c>If-Match</c>) and is
|
||||
/// refused with <c>409 TEMPLATE_IN_USE</c> while any run of this template is
|
||||
/// InProgress — edit-lock stands in for versioning (FR-MFG-06).
|
||||
/// </summary>
|
||||
Task<ETagged<TemplateGraphDto>> UpdateAsync(
|
||||
int templateId, SaveTemplateRequest request, uint expectedRowVersion, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Activate/deactivate (FR-MFG-01). Deliberately <b>not</b> edit-locked: deactivating is
|
||||
/// the "never delete a referenced master" path (FR-MD-08) and only stops <i>new</i> runs
|
||||
/// being started, so it must stay available while runs are in flight.
|
||||
/// </summary>
|
||||
Task SetStatusAsync(int templateId, EntityStatus status, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using ERPCore.Domain.Entities;
|
||||
|
||||
namespace ERPCore.Services.Interfaces;
|
||||
|
||||
/// <summary>
|
||||
/// Converts a quantity and its per-UOM cost into the item's <b>base</b> UOM.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>Everything in the FIFO engine — <c>StockLayer</c>, <c>StockLedger</c>,
|
||||
/// <c>IFifoCostingService.ConsumeAsync</c> — works exclusively in base UOM, while
|
||||
/// documents let a user enter a line in any UOM the item has a conversion for. This is the
|
||||
/// one place that bridges the two.</para>
|
||||
/// <para>Extracted from <c>GrnService</c>'s private <c>ToBaseAsync</c> when manufacturing
|
||||
/// needed the same conversion for stage stock inputs (docs/30 never mentions UOM
|
||||
/// conversion, but <c>STAGE_INPUT.uom_id</c> is a free FK — without this, an input
|
||||
/// specified in "Box of 12" would consume 1 base unit instead of 12 and silently
|
||||
/// mis-cost the run).</para>
|
||||
/// </remarks>
|
||||
public interface IUomConverter
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns the quantity and unit cost restated in <paramref name="item"/>'s base UOM.
|
||||
/// A no-op when <paramref name="uomId"/> already is the base UOM. Throws 422 when no
|
||||
/// conversion is defined for the item from that UOM to its base.
|
||||
/// </summary>
|
||||
Task<(decimal QtyBase, decimal UnitCostBase)> ToBaseAsync(
|
||||
Item item, int uomId, decimal qty, decimal unitCostPerUom, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Quantity-only conversion, for callers that have no per-UOM cost to restate (a
|
||||
/// production stage input declares a quantity; its cost comes from the FIFO layers it
|
||||
/// consumes, not from the document).
|
||||
/// </summary>
|
||||
Task<decimal> ToBaseQtyAsync(Item item, int uomId, decimal qty, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
using ERPCore.Domain.Enums;
|
||||
using ERPCore.System.Errors;
|
||||
|
||||
namespace ERPCore.Services.Production;
|
||||
|
||||
/// <summary>
|
||||
/// Validates a template stage graph (FR-MFG-02, FR-MFG-04, FR-MFG-05) and throws the
|
||||
/// matching <c>422 GRAPH_*</c> domain error on the first violation.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>This is an <b>algorithm, not a service</b> — pure, synchronous, no database and
|
||||
/// no DI, in the spirit of <c>FifoCostingService</c> being the one place FIFO lives. It
|
||||
/// deliberately has no interface: <c>Services/Interfaces/</c> exists for things that get
|
||||
/// injected, and registering this would buy nothing.</para>
|
||||
/// <para>It works entirely in <b>keys</b>, never database ids, so the identical code path
|
||||
/// runs for a POST (where nothing has an id yet) and a PUT (where most things do). All
|
||||
/// database-dependent checks — does this item exist, is it Active, does this UOM exist —
|
||||
/// stay in <c>ProductionTemplateService</c> so this stays free of I/O.</para>
|
||||
/// <para>Checks run cheapest-first and fail fast, and every message names the offending
|
||||
/// stage or edge so the canvas can focus it (docs/21 §2).</para>
|
||||
/// </remarks>
|
||||
public static class ProductionGraphValidator
|
||||
{
|
||||
public sealed record InputDraft(int Index, StageInputSource Source, int? ItemId, string? FromOutputKey);
|
||||
|
||||
public sealed record OutputDraft(string Key, string Name, int? ItemId);
|
||||
|
||||
public sealed record StageDraft(
|
||||
string Key, string Name, IReadOnlyList<InputDraft> Inputs, IReadOnlyList<OutputDraft> Outputs);
|
||||
|
||||
public readonly record struct EdgeDraft(string ParentKey, string ChildKey);
|
||||
|
||||
/// <summary>
|
||||
/// Throws on the first rule violation; returns silently for a valid graph.
|
||||
/// </summary>
|
||||
public static void Validate(IReadOnlyList<StageDraft> stages, IReadOnlyList<EdgeDraft> edges)
|
||||
{
|
||||
// 1 — structural hygiene. These are all blocked in the canvas at draw time
|
||||
// (docs/21 §2); this is the server backstop for a hand-rolled request.
|
||||
if (stages.Count == 0)
|
||||
throw Invalid("A template must have at least one stage.");
|
||||
|
||||
var stageByKey = new Dictionary<string, StageDraft>(StringComparer.Ordinal);
|
||||
foreach (var s in stages)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(s.Key))
|
||||
throw Invalid("Every stage requires a key.");
|
||||
if (!stageByKey.TryAdd(s.Key, s))
|
||||
throw Invalid($"Duplicate stage key '{s.Key}'.");
|
||||
}
|
||||
|
||||
// Output keys are unique across the whole template, not just within a stage —
|
||||
// an Upstream input names one by key alone, so a collision would be ambiguous.
|
||||
var outputOwner = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var s in stages)
|
||||
foreach (var o in s.Outputs)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(o.Key))
|
||||
throw Invalid($"Every output of stage '{s.Name}' requires a key.");
|
||||
if (!outputOwner.TryAdd(o.Key, s.Key))
|
||||
throw Invalid($"Duplicate output key '{o.Key}' (stage '{s.Name}').");
|
||||
}
|
||||
|
||||
var edgeSet = new HashSet<(string, string)>();
|
||||
foreach (var e in edges)
|
||||
{
|
||||
if (!stageByKey.ContainsKey(e.ParentKey) || !stageByKey.ContainsKey(e.ChildKey))
|
||||
throw Invalid($"Edge '{e.ParentKey}' → '{e.ChildKey}' references a stage that is not in the payload.");
|
||||
if (string.Equals(e.ParentKey, e.ChildKey, StringComparison.Ordinal))
|
||||
throw Invalid($"Stage '{stageByKey[e.ParentKey].Name}' cannot connect to itself.");
|
||||
if (!edgeSet.Add((e.ParentKey, e.ChildKey)))
|
||||
throw Invalid($"Duplicate edge '{stageByKey[e.ParentKey].Name}' → '{stageByKey[e.ChildKey].Name}'.");
|
||||
}
|
||||
|
||||
var children = stages.ToDictionary(s => s.Key, _ => new List<string>(), StringComparer.Ordinal);
|
||||
var parents = stages.ToDictionary(s => s.Key, _ => new List<string>(), StringComparer.Ordinal);
|
||||
foreach (var (parent, child) in edgeSet)
|
||||
{
|
||||
children[parent].Add(child);
|
||||
parents[child].Add(parent);
|
||||
}
|
||||
|
||||
// 2 — cycle detection by Kahn's algorithm. If the toposort can't reach every
|
||||
// stage, the unreached set is exactly the stages trapped in (or downstream of)
|
||||
// a cycle, which is what the client highlights.
|
||||
var indegree = stages.ToDictionary(s => s.Key, s => parents[s.Key].Count, StringComparer.Ordinal);
|
||||
var queue = new Queue<string>(indegree.Where(kv => kv.Value == 0).Select(kv => kv.Key));
|
||||
var sorted = 0;
|
||||
while (queue.Count > 0)
|
||||
{
|
||||
var key = queue.Dequeue();
|
||||
sorted++;
|
||||
foreach (var child in children[key])
|
||||
if (--indegree[child] == 0)
|
||||
queue.Enqueue(child);
|
||||
}
|
||||
|
||||
if (sorted != stages.Count)
|
||||
{
|
||||
var trapped = indegree.Where(kv => kv.Value > 0).Select(kv => stageByKey[kv.Key].Name);
|
||||
throw new DomainException(ErrorCodes.GraphCycle,
|
||||
$"The stage graph contains a cycle involving: {string.Join(", ", trapped)}.", 422);
|
||||
}
|
||||
|
||||
// 3 — exactly one terminal stage (multiple starts may converge, but the line must
|
||||
// end in one place, because that single stage is what receives the finished good).
|
||||
var terminals = stages.Where(s => children[s.Key].Count == 0).ToList();
|
||||
if (terminals.Count != 1)
|
||||
throw new DomainException(ErrorCodes.GraphTerminalCount,
|
||||
terminals.Count == 0
|
||||
? "The stage graph has no final stage."
|
||||
: $"The stage graph must converge to exactly one final stage, but {terminals.Count} have no outgoing connection: {string.Join(", ", terminals.Select(t => t.Name))}.",
|
||||
422);
|
||||
|
||||
var terminal = terminals[0];
|
||||
var entries = stages.Where(s => parents[s.Key].Count == 0).ToList();
|
||||
|
||||
// 4 — connectivity. One traversal each way subsumes all three of "no disconnected
|
||||
// stages", "every stage reachable from an entry" and "every stage reaches the
|
||||
// terminal": an isolated stage simply appears in neither set. A lone stage is both
|
||||
// an entry and the terminal, so it falls out correctly with no special case.
|
||||
//
|
||||
// Kept as defence in depth, but note it is unreachable once checks 2 and 3 pass:
|
||||
// in an acyclic graph every stage is reachable from some source, and if exactly one
|
||||
// stage lacks an outbound edge then every stage necessarily reaches it. An isolated
|
||||
// stage therefore surfaces as GRAPH_TERMINAL_COUNT (it is a second terminal), which
|
||||
// is the better message anyway because it names both offenders. Verified by the M2
|
||||
// smoke test, which asserts that behaviour explicitly.
|
||||
var fromEntry = Reach(entries.Select(s => s.Key), children);
|
||||
var toTerminal = Reach([terminal.Key], parents);
|
||||
|
||||
var stranded = stages.Where(s => !fromEntry.Contains(s.Key) || !toTerminal.Contains(s.Key)).ToList();
|
||||
if (stranded.Count > 0)
|
||||
throw new DomainException(ErrorCodes.GraphDisconnected,
|
||||
$"Every stage must sit on a path from a starting stage to '{terminal.Name}', but these do not: {string.Join(", ", stranded.Select(s => s.Name))}.",
|
||||
422);
|
||||
|
||||
// 5 — input sources (FR-MFG-04). An Upstream input may only draw from an output of
|
||||
// a DIRECT parent: allowing a grandparent's output would mean WIP skipping a stage.
|
||||
foreach (var s in stages)
|
||||
{
|
||||
var allowed = parents[s.Key]
|
||||
.SelectMany(p => stageByKey[p].Outputs.Select(o => o.Key))
|
||||
.ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
foreach (var input in s.Inputs)
|
||||
{
|
||||
if (input.Source == StageInputSource.Upstream)
|
||||
{
|
||||
if (input.ItemId is not null)
|
||||
throw new DomainException(ErrorCodes.GraphInputSourceInvalid,
|
||||
$"Input {input.Index + 1} of stage '{s.Name}' is Upstream and cannot also reference an item.", 422);
|
||||
if (string.IsNullOrWhiteSpace(input.FromOutputKey))
|
||||
throw new DomainException(ErrorCodes.GraphInputSourceInvalid,
|
||||
$"Input {input.Index + 1} of stage '{s.Name}' is Upstream but names no source output.", 422);
|
||||
if (!allowed.Contains(input.FromOutputKey))
|
||||
{
|
||||
var owner = outputOwner.TryGetValue(input.FromOutputKey, out var ownerKey)
|
||||
? $"'{stageByKey[ownerKey].Name}' is not a direct parent of '{s.Name}'"
|
||||
: $"output '{input.FromOutputKey}' does not exist";
|
||||
throw new DomainException(ErrorCodes.GraphInputSourceInvalid,
|
||||
$"Input {input.Index + 1} of stage '{s.Name}' must draw from a direct parent's output — {owner}.", 422);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (input.ItemId is null)
|
||||
throw new DomainException(ErrorCodes.GraphInputSourceInvalid,
|
||||
$"Input {input.Index + 1} of stage '{s.Name}' is a Stock input and requires an item.", 422);
|
||||
if (!string.IsNullOrWhiteSpace(input.FromOutputKey))
|
||||
throw new DomainException(ErrorCodes.GraphInputSourceInvalid,
|
||||
$"Input {input.Index + 1} of stage '{s.Name}' is a Stock input and cannot reference an upstream output.", 422);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 6 — outputs (FR-MFG-05). The terminal stage produces exactly one real Item (the
|
||||
// finished good the receipt creates a layer for); every other output is internal
|
||||
// WIP and must stay item-less, or it would imply stock that never exists.
|
||||
if (terminal.Outputs.Count != 1)
|
||||
throw new DomainException(ErrorCodes.TerminalOutputItemRequired,
|
||||
$"The final stage '{terminal.Name}' must have exactly one output, but has {terminal.Outputs.Count}.", 422);
|
||||
|
||||
if (terminal.Outputs[0].ItemId is null)
|
||||
throw new DomainException(ErrorCodes.TerminalOutputItemRequired,
|
||||
$"The output of the final stage '{terminal.Name}' must reference the finished item.", 422);
|
||||
|
||||
foreach (var s in stages.Where(s => !ReferenceEquals(s, terminal)))
|
||||
foreach (var o in s.Outputs.Where(o => o.ItemId is not null))
|
||||
throw Invalid(
|
||||
$"Output '{o.Name}' of stage '{s.Name}' is intermediate work-in-progress and cannot reference an item — only the final stage produces a stocked item.");
|
||||
}
|
||||
|
||||
/// <summary>Set of keys reachable from <paramref name="roots"/> following <paramref name="next"/>.</summary>
|
||||
private static HashSet<string> Reach(IEnumerable<string> roots, Dictionary<string, List<string>> next)
|
||||
{
|
||||
var seen = new HashSet<string>(roots, StringComparer.Ordinal);
|
||||
var queue = new Queue<string>(seen);
|
||||
while (queue.Count > 0)
|
||||
foreach (var n in next[queue.Dequeue()])
|
||||
if (seen.Add(n))
|
||||
queue.Enqueue(n);
|
||||
return seen;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Structural violations the client already prevents and docs/30 §D.4 assigns no
|
||||
/// dedicated code to — still 422, still carrying a message that names the culprit.
|
||||
/// </summary>
|
||||
private static DomainException Invalid(string message) => new(ErrorCodes.Validation, message, 422);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace ERPCore.Services.Production;
|
||||
|
||||
/// <summary>
|
||||
/// The one serializer for every jsonb column in the manufacturing module —
|
||||
/// <c>template_stages.field_defs</c>, <c>run_stages.field_defs</c>/<c>field_values</c>
|
||||
/// and <c>run_stage_events.payload</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>Those columns hold a pre-serialized <c>string</c> rather than a mapped POCO,
|
||||
/// following the <c>AuditLog.ChangeSet</c> precedent. Beyond consistency this keeps
|
||||
/// <c>AuditScribe</c> honest: an owned/typed jsonb mapping would surface the nested
|
||||
/// objects as their own change-tracker entries and scatter spurious audit rows across
|
||||
/// the new tables.</para>
|
||||
/// <para>Everything is written through here so a column can only ever contain canonical
|
||||
/// JSON — the raw client string is never stored, which means a malformed
|
||||
/// <c>fieldDefs</c> can't reach the database and can't later break a run created from
|
||||
/// that template.</para>
|
||||
/// </remarks>
|
||||
public static class ProductionJson
|
||||
{
|
||||
/// <summary>Matches the API's own wire format (docs/11 §1.3): camelCase, enums as strings.</summary>
|
||||
public static readonly JsonSerializerOptions Options = new()
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
Converters = { new JsonStringEnumConverter() }
|
||||
};
|
||||
|
||||
public static string Serialize<T>(T value) => JsonSerializer.Serialize(value, Options);
|
||||
|
||||
/// <summary>
|
||||
/// Reads a stored column back. Returns <paramref name="fallback"/> for null/blank so a
|
||||
/// caller never has to null-check; a parse failure is a genuine data-integrity problem
|
||||
/// and is allowed to throw.
|
||||
/// </summary>
|
||||
public static T Deserialize<T>(string? json, T fallback)
|
||||
=> string.IsNullOrWhiteSpace(json) ? fallback : JsonSerializer.Deserialize<T>(json, Options) ?? fallback;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,496 @@
|
||||
using ERPCore.Common.Http;
|
||||
using ERPCore.Domain.Entities;
|
||||
using ERPCore.Domain.Enums;
|
||||
using ERPCore.Dtos.Common;
|
||||
using ERPCore.Dtos.Production;
|
||||
using ERPCore.Infra.Auth;
|
||||
using ERPCore.Infra.UoW;
|
||||
using ERPCore.Repositories.Interfaces;
|
||||
using ERPCore.Services.Interfaces;
|
||||
using ERPCore.System.Errors;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ERPCore.Services.Production;
|
||||
|
||||
/// <summary>
|
||||
/// Production template CRUD + graph validation (docs/30 §D.1, FR-MFG-01..07).
|
||||
/// Graph rules live in <see cref="ProductionGraphValidator"/>; everything needing the
|
||||
/// database (referential checks, the edit-lock, reconciliation) lives here.
|
||||
/// </summary>
|
||||
public sealed class ProductionTemplateService : IProductionTemplateService
|
||||
{
|
||||
private readonly IRepository<ProductionTemplate> _templates;
|
||||
private readonly IRepository<TemplateStage> _stages;
|
||||
private readonly IRepository<StageInput> _inputs;
|
||||
private readonly IRepository<StageOutput> _outputs;
|
||||
private readonly IRepository<StageEdge> _edges;
|
||||
private readonly IRepository<Item> _items;
|
||||
private readonly IRepository<Uom> _uoms;
|
||||
private readonly IRepository<ProductionRun> _runs;
|
||||
private readonly IUnitOfWork _uow;
|
||||
private readonly ICurrentUser _currentUser;
|
||||
|
||||
public ProductionTemplateService(
|
||||
IRepository<ProductionTemplate> templates, IRepository<TemplateStage> stages,
|
||||
IRepository<StageInput> inputs, IRepository<StageOutput> outputs, IRepository<StageEdge> edges,
|
||||
IRepository<Item> items, IRepository<Uom> uoms, IRepository<ProductionRun> runs,
|
||||
IUnitOfWork uow, ICurrentUser currentUser)
|
||||
{
|
||||
_templates = templates;
|
||||
_stages = stages;
|
||||
_inputs = inputs;
|
||||
_outputs = outputs;
|
||||
_edges = edges;
|
||||
_items = items;
|
||||
_uoms = uoms;
|
||||
_runs = runs;
|
||||
_uow = uow;
|
||||
_currentUser = currentUser;
|
||||
}
|
||||
|
||||
public async Task<PagedResponse<TemplateSummaryDto>> ListAsync(
|
||||
PageQuery query, EntityStatus? status, CancellationToken ct = default)
|
||||
{
|
||||
var q = _templates.Query().AsNoTracking();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(query.Q))
|
||||
{
|
||||
var term = query.Q.Trim();
|
||||
q = q.Where(t => EF.Functions.ILike(t.Code, $"%{term}%") || EF.Functions.ILike(t.Name, $"%{term}%"));
|
||||
}
|
||||
|
||||
if (status is not null) q = q.Where(t => t.Status == status);
|
||||
|
||||
var total = await q.CountAsync(ct);
|
||||
|
||||
// Projected to an anonymous type first, then mapped client-side: EF Core 10 cannot
|
||||
// translate a record constructor sitting alongside aggregates and a collection
|
||||
// projection (same limitation recorded for WarehouseValuationDto, 2026-07-28).
|
||||
var rows = await q
|
||||
.OrderBy(t => t.Code)
|
||||
.Skip(query.Skip).Take(query.PageSize)
|
||||
.Select(t => new
|
||||
{
|
||||
t.TemplateId,
|
||||
t.Code,
|
||||
t.Name,
|
||||
t.Status,
|
||||
StageCount = t.Stages.Count,
|
||||
Stages = t.Stages.Select(s => new { s.StageId, s.Name }).ToList(),
|
||||
Edges = t.Edges.Select(e => new { e.ParentStageId, e.ChildStageId }).ToList(),
|
||||
// Drives the canvas edit-lock banner (docs/21 §2) and mirrors the
|
||||
// condition UpdateAsync enforces server-side.
|
||||
ActiveRunCount = t.Runs.Count(r => r.Status == ProductionRunStatus.InProgress),
|
||||
t.CreatedBy,
|
||||
t.CreatedAt
|
||||
})
|
||||
.ToListAsync(ct);
|
||||
|
||||
var items = rows.Select(t => new TemplateSummaryDto(
|
||||
t.TemplateId, t.Code, t.Name, t.Status, t.StageCount,
|
||||
FlowOrderedNames(
|
||||
t.Stages.Select(s => (s.StageId, s.Name)).ToList(),
|
||||
t.Edges.Select(e => (e.ParentStageId, e.ChildStageId)).ToList()),
|
||||
t.ActiveRunCount, t.CreatedBy, t.CreatedAt)).ToList();
|
||||
|
||||
return PagedResponse<TemplateSummaryDto>.Create(items, query.Page, query.PageSize, total);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stage names in <b>flow order</b> — upstream first — for the overview canvas, which
|
||||
/// draws each template as a line left to right (docs/21 §1).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Ordering by <c>StageId</c> would be insertion order, which routinely puts the terminal
|
||||
/// stage first and renders the line backwards. Kahn's algorithm over the edge set gives the
|
||||
/// real sequence, tie-broken by stage id so parallel branches come out deterministically.
|
||||
/// Falls back to id order if the graph somehow contains a cycle, so a listing can never
|
||||
/// fail because of bad data.
|
||||
/// </remarks>
|
||||
private static List<string> FlowOrderedNames(
|
||||
List<(int StageId, string Name)> stages, List<(int ParentStageId, int ChildStageId)> edges)
|
||||
{
|
||||
var nameById = stages.ToDictionary(s => s.StageId, s => s.Name);
|
||||
var children = stages.ToDictionary(s => s.StageId, _ => new List<int>());
|
||||
var indegree = stages.ToDictionary(s => s.StageId, _ => 0);
|
||||
|
||||
foreach (var (parent, child) in edges)
|
||||
{
|
||||
if (!children.ContainsKey(parent) || !indegree.ContainsKey(child)) continue;
|
||||
children[parent].Add(child);
|
||||
indegree[child]++;
|
||||
}
|
||||
|
||||
// SortedSet keeps the frontier in id order, so the output is stable run to run.
|
||||
var frontier = new SortedSet<int>(indegree.Where(kv => kv.Value == 0).Select(kv => kv.Key));
|
||||
var ordered = new List<string>(stages.Count);
|
||||
|
||||
while (frontier.Count > 0)
|
||||
{
|
||||
var next = frontier.Min;
|
||||
frontier.Remove(next);
|
||||
ordered.Add(nameById[next]);
|
||||
|
||||
foreach (var child in children[next])
|
||||
if (--indegree[child] == 0)
|
||||
frontier.Add(child);
|
||||
}
|
||||
|
||||
return ordered.Count == stages.Count
|
||||
? ordered
|
||||
: stages.OrderBy(s => s.StageId).Select(s => s.Name).ToList();
|
||||
}
|
||||
|
||||
public async Task<ETagged<TemplateGraphDto>?> GetAsync(int templateId, CancellationToken ct = default)
|
||||
{
|
||||
var template = await LoadGraphQuery().AsNoTracking()
|
||||
.FirstOrDefaultAsync(t => t.TemplateId == templateId, ct);
|
||||
|
||||
if (template is null) return null;
|
||||
|
||||
// Counted separately rather than Included: the graph query already fans out over four
|
||||
// collections, and adding Runs would multiply those rows again for a single integer.
|
||||
var activeRuns = await _runs.Query().AsNoTracking()
|
||||
.CountAsync(r => r.TemplateId == templateId && r.Status == ProductionRunStatus.InProgress, ct);
|
||||
|
||||
return new ETagged<TemplateGraphDto>(ToGraphDto(template, activeRuns), template.RowVersion);
|
||||
}
|
||||
|
||||
public async Task<ETagged<TemplateGraphDto>> CreateAsync(SaveTemplateRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var code = request.Code.Trim();
|
||||
if (await _templates.Query().AnyAsync(t => t.Code == code, ct))
|
||||
throw new ConflictException($"A production template with code '{code}' already exists.");
|
||||
|
||||
var template = new ProductionTemplate
|
||||
{
|
||||
Code = code,
|
||||
Name = request.Name.Trim(),
|
||||
Description = request.Description?.Trim(),
|
||||
Status = EntityStatus.Active,
|
||||
CreatedBy = _currentUser.AuditUserId,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
};
|
||||
|
||||
await ValidateAsync(request, ct);
|
||||
|
||||
await _uow.ExecuteInTransactionAsync(async token =>
|
||||
{
|
||||
await _templates.AddAsync(template, token);
|
||||
BuildGraph(template, request);
|
||||
}, ct);
|
||||
|
||||
return await RequireGraphAsync(template.TemplateId, ct);
|
||||
}
|
||||
|
||||
public async Task<ETagged<TemplateGraphDto>> UpdateAsync(
|
||||
int templateId, SaveTemplateRequest request, uint expectedRowVersion, CancellationToken ct = default)
|
||||
{
|
||||
await ValidateAsync(request, ct);
|
||||
|
||||
var code = request.Code.Trim();
|
||||
if (await _templates.Query().AnyAsync(t => t.Code == code && t.TemplateId != templateId, ct))
|
||||
throw new ConflictException($"A production template with code '{code}' already exists.");
|
||||
|
||||
await _uow.ExecuteInTransactionAsync(async token =>
|
||||
{
|
||||
var template = await LoadGraphQuery().FirstOrDefaultAsync(t => t.TemplateId == templateId, token)
|
||||
?? throw new NotFoundException($"Production template {templateId} was not found.");
|
||||
|
||||
if (template.RowVersion != expectedRowVersion)
|
||||
throw new DomainException(ErrorCodes.ConcurrencyConflict,
|
||||
"The template was modified by another request.", 412);
|
||||
|
||||
// FR-MFG-06: edit-lock instead of versioning. Checked inside the transaction to
|
||||
// keep the window small; the residual race is benign because a run copies
|
||||
// everything it needs at creation and never reads the template again.
|
||||
var activeRuns = await _runs.Query().AsNoTracking()
|
||||
.CountAsync(r => r.TemplateId == templateId && r.Status == ProductionRunStatus.InProgress, token);
|
||||
if (activeRuns > 0)
|
||||
throw new DomainException(ErrorCodes.TemplateInUse,
|
||||
$"This template has {activeRuns} run(s) in progress and cannot be edited until they finish.", 409);
|
||||
|
||||
template.Code = code;
|
||||
template.Name = request.Name.Trim();
|
||||
template.Description = request.Description?.Trim();
|
||||
|
||||
// Two passes, deliberately. Tearing the old graph down and flushing before
|
||||
// rebuilding removes any dependence on how EF happens to order a mixed batch of
|
||||
// inserts and deletes — which matters because stage_inputs → stage_outputs is a
|
||||
// Restrict FK and stage_edges carries a unique (parent, child) index.
|
||||
var keptStages = TearDownGraph(template, request);
|
||||
await _uow.SaveChangesAsync(token);
|
||||
|
||||
BuildGraph(template, request, keptStages);
|
||||
}, ct);
|
||||
|
||||
return await RequireGraphAsync(templateId, ct);
|
||||
}
|
||||
|
||||
public async Task SetStatusAsync(int templateId, EntityStatus status, CancellationToken ct = default)
|
||||
{
|
||||
var template = await _templates.Query().FirstOrDefaultAsync(t => t.TemplateId == templateId, ct)
|
||||
?? throw new NotFoundException($"Production template {templateId} was not found.");
|
||||
|
||||
template.Status = status;
|
||||
await _uow.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
// --- graph reconciliation ------------------------------------------------
|
||||
|
||||
private IQueryable<ProductionTemplate> LoadGraphQuery() =>
|
||||
_templates.Query()
|
||||
.Include(t => t.Stages).ThenInclude(s => s.Inputs)
|
||||
.Include(t => t.Stages).ThenInclude(s => s.Outputs)
|
||||
.Include(t => t.Edges);
|
||||
|
||||
/// <summary>
|
||||
/// Runs the pure graph rules then the referential ones. Item/UOM existence needs the
|
||||
/// database, so it can't live in the validator — but it has to run before any write.
|
||||
/// </summary>
|
||||
private async Task ValidateAsync(SaveTemplateRequest request, CancellationToken ct)
|
||||
{
|
||||
ProductionGraphValidator.Validate(
|
||||
request.Stages.Select(s => new ProductionGraphValidator.StageDraft(
|
||||
s.Key, s.Name,
|
||||
s.Inputs.Select((i, idx) => new ProductionGraphValidator.InputDraft(idx, i.Source, i.ItemId, i.FromOutputKey)).ToList(),
|
||||
s.Outputs.Select(o => new ProductionGraphValidator.OutputDraft(o.Key, o.Name, o.ItemId)).ToList())).ToList(),
|
||||
request.Edges.Select(e => new ProductionGraphValidator.EdgeDraft(e.ParentKey, e.ChildKey)).ToList());
|
||||
|
||||
var itemIds = request.Stages
|
||||
.SelectMany(s => s.Inputs.Select(i => i.ItemId).Concat(s.Outputs.Select(o => o.ItemId)))
|
||||
.OfType<int>().Distinct().ToList();
|
||||
|
||||
if (itemIds.Count > 0)
|
||||
{
|
||||
var found = await _items.Query().AsNoTracking()
|
||||
.Where(i => itemIds.Contains(i.ItemId))
|
||||
.Select(i => new { i.ItemId, i.Status })
|
||||
.ToListAsync(ct);
|
||||
|
||||
var missing = itemIds.Except(found.Select(f => f.ItemId)).ToList();
|
||||
if (missing.Count > 0)
|
||||
throw new DomainException(ErrorCodes.Validation,
|
||||
$"Item(s) {string.Join(", ", missing)} do not exist.", 422);
|
||||
|
||||
var inactive = found.Where(f => f.Status != EntityStatus.Active).Select(f => f.ItemId).ToList();
|
||||
if (inactive.Count > 0)
|
||||
throw new DomainException(ErrorCodes.Validation,
|
||||
$"Item(s) {string.Join(", ", inactive)} are inactive and cannot be used in a template.", 422);
|
||||
}
|
||||
|
||||
var uomIds = request.Stages
|
||||
.SelectMany(s => s.Inputs.Select(i => i.UomId).Concat(s.Outputs.Select(o => o.UomId)))
|
||||
.Distinct().ToList();
|
||||
|
||||
var knownUoms = await _uoms.Query().AsNoTracking()
|
||||
.Where(u => uomIds.Contains(u.UomId)).Select(u => u.UomId).ToListAsync(ct);
|
||||
|
||||
var missingUoms = uomIds.Except(knownUoms).ToList();
|
||||
if (missingUoms.Count > 0)
|
||||
throw new DomainException(ErrorCodes.Validation,
|
||||
$"UOM(s) {string.Join(", ", missingUoms)} do not exist.", 422);
|
||||
|
||||
// Annotations go into jsonb unvalidated by anything else, so pin the one field the
|
||||
// client renders off. Unknown kinds would round-trip fine but draw nothing.
|
||||
var badKinds = request.Annotations
|
||||
.Select(a => a.Kind)
|
||||
.Where(k => k is not ("box" or "line"))
|
||||
.Distinct().ToList();
|
||||
if (badKinds.Count > 0)
|
||||
throw new DomainException(ErrorCodes.Validation,
|
||||
$"Unknown canvas annotation kind(s): {string.Join(", ", badKinds)}. Expected 'box' or 'line'.", 422);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes everything the incoming payload replaces and returns the surviving stages
|
||||
/// by key.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Inputs and outputs are always replaced wholesale — nothing outside the template
|
||||
/// references them, because a run copies into its own <c>run_stage_input</c>/
|
||||
/// <c>run_stage_output</c> rows. Stages are <b>diffed</b>, not replaced, because
|
||||
/// <c>run_stages.TemplateStageId</c> points at them; a stage that disappears from the
|
||||
/// payload is deleted and that FK is set null for any historical run (see
|
||||
/// <c>RunStageConfiguration</c>).
|
||||
/// </remarks>
|
||||
private Dictionary<string, TemplateStage> TearDownGraph(ProductionTemplate template, SaveTemplateRequest request)
|
||||
{
|
||||
var payloadKeys = request.Stages.Select(s => s.Key).ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
foreach (var stage in template.Stages)
|
||||
{
|
||||
foreach (var input in stage.Inputs.ToList()) _inputs.Remove(input);
|
||||
foreach (var output in stage.Outputs.ToList()) _outputs.Remove(output);
|
||||
}
|
||||
|
||||
var kept = new Dictionary<string, TemplateStage>(StringComparer.Ordinal);
|
||||
var doomed = new List<TemplateStage>();
|
||||
foreach (var stage in template.Stages.ToList())
|
||||
{
|
||||
var key = stage.StageId.ToString();
|
||||
if (payloadKeys.Contains(key)) kept[key] = stage;
|
||||
else doomed.Add(stage);
|
||||
}
|
||||
|
||||
// Edges are diffed rather than replaced: stage_edges has a unique (parent, child)
|
||||
// index, and dropping then re-adding an unchanged edge in the same round trip can
|
||||
// trip it depending on statement order.
|
||||
var wanted = request.Edges
|
||||
.Select(e => (Parent: ResolveKeptId(kept, e.ParentKey), Child: ResolveKeptId(kept, e.ChildKey)))
|
||||
.Where(e => e.Parent is not null && e.Child is not null)
|
||||
.Select(e => (e.Parent!.Value, e.Child!.Value))
|
||||
.ToHashSet();
|
||||
|
||||
// Edges must go before stages. StageEdge.ParentStage/ChildStage are required
|
||||
// relationships, so deleting a stage that a still-live edge points at makes EF throw
|
||||
// "the association ... has been severed". Any edge touching a doomed stage is
|
||||
// necessarily absent from `wanted` — the payload cannot reference a stage it dropped
|
||||
// — so this ordering never orphans an edge the caller wanted to keep.
|
||||
foreach (var edge in template.Edges.ToList())
|
||||
if (!wanted.Contains((edge.ParentStageId, edge.ChildStageId)))
|
||||
_edges.Remove(edge);
|
||||
|
||||
foreach (var stage in doomed)
|
||||
_stages.Remove(stage);
|
||||
|
||||
return kept;
|
||||
}
|
||||
|
||||
private static int? ResolveKeptId(Dictionary<string, TemplateStage> kept, string key)
|
||||
=> kept.TryGetValue(key, out var stage) ? stage.StageId : null;
|
||||
|
||||
/// <summary>
|
||||
/// Materialises the payload onto the template.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Everything is wired through <b>navigation properties</b> rather than foreign-key
|
||||
/// ints, so EF resolves the ids itself during a single <c>SaveChanges</c>. That is what
|
||||
/// lets a brand-new Upstream input point at a brand-new output without an intermediate
|
||||
/// save to materialise generated keys — outputs are built in the first pass precisely
|
||||
/// so the second pass has the entity instances to hand.
|
||||
/// </remarks>
|
||||
private void BuildGraph(
|
||||
ProductionTemplate template, SaveTemplateRequest request,
|
||||
Dictionary<string, TemplateStage>? keptStages = null)
|
||||
{
|
||||
// Replaced wholesale — annotations are opaque client state, not part of the graph, so
|
||||
// there is nothing to diff and nothing else can reference them.
|
||||
template.Annotations = request.Annotations.Count == 0
|
||||
? null
|
||||
: ProductionJson.Serialize(request.Annotations);
|
||||
|
||||
var stagesByKey = new Dictionary<string, TemplateStage>(StringComparer.Ordinal);
|
||||
var outputsByKey = new Dictionary<string, StageOutput>(StringComparer.Ordinal);
|
||||
|
||||
// Pass 1 — stages and their outputs.
|
||||
foreach (var s in request.Stages)
|
||||
{
|
||||
if (keptStages is null || !keptStages.TryGetValue(s.Key, out var stage))
|
||||
{
|
||||
stage = new TemplateStage { Template = template };
|
||||
template.Stages.Add(stage);
|
||||
}
|
||||
|
||||
stage.Name = s.Name.Trim();
|
||||
stage.RoleLabel = string.IsNullOrWhiteSpace(s.RoleLabel) ? null : s.RoleLabel.Trim();
|
||||
stage.EstimatedMinutes = s.EstimatedMinutes;
|
||||
stage.PosX = s.PosX;
|
||||
stage.PosY = s.PosY;
|
||||
stage.FieldDefs = ProductionJson.Serialize(s.FieldDefs);
|
||||
|
||||
stagesByKey[s.Key] = stage;
|
||||
|
||||
foreach (var o in s.Outputs)
|
||||
{
|
||||
var output = new StageOutput
|
||||
{
|
||||
Stage = stage,
|
||||
ItemId = o.ItemId,
|
||||
Name = o.Name.Trim(),
|
||||
UomId = o.UomId,
|
||||
QtyPerBatch = o.QtyPerBatch
|
||||
};
|
||||
stage.Outputs.Add(output);
|
||||
outputsByKey[o.Key] = output;
|
||||
}
|
||||
}
|
||||
|
||||
// Pass 2 — inputs, which may reference any output built above.
|
||||
foreach (var s in request.Stages)
|
||||
{
|
||||
var stage = stagesByKey[s.Key];
|
||||
foreach (var i in s.Inputs)
|
||||
{
|
||||
stage.Inputs.Add(new StageInput
|
||||
{
|
||||
Stage = stage,
|
||||
Source = i.Source,
|
||||
ItemId = i.Source == StageInputSource.Stock ? i.ItemId : null,
|
||||
FromOutput = i.Source == StageInputSource.Upstream ? outputsByKey[i.FromOutputKey!] : null,
|
||||
UomId = i.UomId,
|
||||
QtyPerBatch = i.QtyPerBatch
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Pass 3 — edges not already present.
|
||||
var existing = template.Edges
|
||||
.Select(e => (e.ParentStageId, e.ChildStageId)).ToHashSet();
|
||||
|
||||
foreach (var e in request.Edges)
|
||||
{
|
||||
var parent = stagesByKey[e.ParentKey];
|
||||
var child = stagesByKey[e.ChildKey];
|
||||
if (parent.StageId != 0 && child.StageId != 0 && existing.Contains((parent.StageId, child.StageId)))
|
||||
continue;
|
||||
|
||||
template.Edges.Add(new StageEdge
|
||||
{
|
||||
Template = template,
|
||||
ParentStage = parent,
|
||||
ChildStage = child
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// --- mapping -------------------------------------------------------------
|
||||
|
||||
private async Task<ETagged<TemplateGraphDto>> RequireGraphAsync(int templateId, CancellationToken ct)
|
||||
=> await GetAsync(templateId, ct)
|
||||
?? throw new NotFoundException($"Production template {templateId} was not found.");
|
||||
|
||||
private static TemplateGraphDto ToGraphDto(ProductionTemplate t, int activeRunCount)
|
||||
{
|
||||
// The key a client sends back is just the id as a string; computing it here keeps
|
||||
// that contract in exactly one place.
|
||||
var outputKeyById = t.Stages
|
||||
.SelectMany(s => s.Outputs)
|
||||
.ToDictionary(o => o.OutputId, o => o.OutputId.ToString());
|
||||
|
||||
var stages = t.Stages
|
||||
.OrderBy(s => s.StageId)
|
||||
.Select(s => new TemplateStageDto(
|
||||
s.StageId, s.StageId.ToString(), s.Name, s.RoleLabel, s.EstimatedMinutes, s.PosX, s.PosY,
|
||||
ProductionJson.Deserialize<List<FieldDefDto>>(s.FieldDefs, []),
|
||||
s.Inputs.OrderBy(i => i.InputId).Select(i => new StageInputDto(
|
||||
i.InputId, i.Source, i.ItemId, i.FromOutputId,
|
||||
i.FromOutputId is null ? null : outputKeyById.GetValueOrDefault(i.FromOutputId.Value),
|
||||
i.UomId, i.QtyPerBatch)).ToList(),
|
||||
s.Outputs.OrderBy(o => o.OutputId).Select(o => new StageOutputDto(
|
||||
o.OutputId, o.OutputId.ToString(), o.ItemId, o.Name, o.UomId, o.QtyPerBatch)).ToList()))
|
||||
.ToList();
|
||||
|
||||
var edges = t.Edges
|
||||
.OrderBy(e => e.EdgeId)
|
||||
.Select(e => new TemplateEdgeDto(
|
||||
e.EdgeId, e.ParentStageId, e.ChildStageId,
|
||||
e.ParentStageId.ToString(), e.ChildStageId.ToString()))
|
||||
.ToList();
|
||||
|
||||
return new TemplateGraphDto(
|
||||
t.TemplateId, t.Code, t.Name, t.Description, t.Status, stages, edges,
|
||||
ProductionJson.Deserialize<List<CanvasAnnotationDto>>(t.Annotations, []),
|
||||
activeRunCount, t.CreatedBy, t.CreatedAt);
|
||||
}
|
||||
}
|
||||
@@ -121,7 +121,8 @@ public sealed class FifoCostingService : IFifoCostingService
|
||||
public async Task<StockLedger> PostLedgerAsync(
|
||||
int itemId, int warehouseId, int? binId, int? batchId, int? serialId, int userId,
|
||||
Direction direction, decimal qtyBase, decimal unitCost, decimal runningBalance,
|
||||
string sourceDocType, int sourceDocId, DateTime createdAt, CancellationToken ct = default)
|
||||
string sourceDocType, int sourceDocId, DateTime createdAt, CancellationToken ct = default,
|
||||
decimal? valueOverride = null)
|
||||
{
|
||||
var entry = new StockLedger
|
||||
{
|
||||
@@ -134,7 +135,9 @@ public sealed class FifoCostingService : IFifoCostingService
|
||||
Direction = direction,
|
||||
QtyBase = qtyBase,
|
||||
UnitCost = unitCost,
|
||||
Value = Math.Round(qtyBase * unitCost, 4, MidpointRounding.AwayFromZero),
|
||||
Value = valueOverride is not null
|
||||
? Math.Round(valueOverride.Value, 4, MidpointRounding.AwayFromZero)
|
||||
: Math.Round(qtyBase * unitCost, 4, MidpointRounding.AwayFromZero),
|
||||
RunningBalance = runningBalance,
|
||||
SourceDocType = sourceDocType,
|
||||
SourceDocId = sourceDocId,
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
using ERPCore.Domain.Entities;
|
||||
using ERPCore.Repositories.Interfaces;
|
||||
using ERPCore.Services.Interfaces;
|
||||
using ERPCore.System.Errors;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ERPCore.Services.Stock;
|
||||
|
||||
/// <summary>
|
||||
/// Shared UOM → base-UOM conversion (see <see cref="IUomConverter"/>). Behaviour is
|
||||
/// unchanged from the <c>GrnService.ToBaseAsync</c> it was extracted from, so the GRN
|
||||
/// receive path keeps costing exactly as before.
|
||||
/// </summary>
|
||||
public sealed class UomConverter : IUomConverter
|
||||
{
|
||||
private readonly IRepository<UomConversion> _conversions;
|
||||
|
||||
public UomConverter(IRepository<UomConversion> conversions) => _conversions = conversions;
|
||||
|
||||
public async Task<(decimal QtyBase, decimal UnitCostBase)> ToBaseAsync(
|
||||
Item item, int uomId, decimal qty, decimal unitCostPerUom, CancellationToken ct = default)
|
||||
{
|
||||
if (uomId == item.BaseUomId)
|
||||
return (qty, unitCostPerUom);
|
||||
|
||||
var conv = await _conversions.Query().AsNoTracking()
|
||||
.FirstOrDefaultAsync(c => c.ItemId == item.ItemId && c.FromUomId == uomId && c.ToUomId == item.BaseUomId, ct)
|
||||
?? throw new DomainException(ErrorCodes.Validation,
|
||||
$"No UOM conversion from {uomId} to base UOM {item.BaseUomId} for item {item.ItemId}.", 422);
|
||||
|
||||
// Quantity scales up by the factor, so the per-unit cost scales down by it —
|
||||
// total value is preserved.
|
||||
return (qty * conv.Factor, unitCostPerUom / conv.Factor);
|
||||
}
|
||||
|
||||
public async Task<decimal> ToBaseQtyAsync(Item item, int uomId, decimal qty, CancellationToken ct = default)
|
||||
=> (await ToBaseAsync(item, uomId, qty, 0m, ct)).QtyBase;
|
||||
}
|
||||
Reference in New Issue
Block a user