Fix loading sheet creation flow

This commit is contained in:
2026-09-23 12:46:23 +05:30
parent 35fa3b19e3
commit ae302d0c9c
7 changed files with 540 additions and 83 deletions
@@ -64,26 +64,47 @@ public class LoadingSheetService(
if (sheet.Status != LoadingSheetStatus.Planned)
throw new InvalidOperationException("Items can only be changed while the sheet is Planned");
var shopPOItemIds = request.Items
.Where(i => i.FK_ShopPOItemId.HasValue)
.Select(i => i.FK_ShopPOItemId!.Value)
.ToList();
var shopPOIds = shopPOItemIds.Count > 0
? await repo.GetShopPOIdsByItemIdsAsync(shopPOItemIds)
: new List<Guid>();
// Upsert by (item, warehouse, shop PO item): a matching row gets its quantity
// updated in place, a new combination is added. Rows for combinations not present
// in this request are left untouched, so a later save can top up the same PO
// item's remaining quantity from a different warehouse without losing what was
// already planned from the first one.
await uow.BeginAsync(ct);
try
{
repo.RemoveItems(sheet.Items);
await repo.AddItemsAsync(request.Items.Select(i => new LoadingSheetItem
var newItems = new List<LoadingSheetItem>();
foreach (var input in request.Items)
{
FK_LoadingSheetId = sheet.Id,
FK_ItemId = i.FK_ItemId,
FK_WarehouseId = i.FK_WarehouseId,
FK_ShopPOItemId = i.FK_ShopPOItemId,
QuantityDispatched = i.Quantity
}));
var existing = sheet.Items.FirstOrDefault(i =>
i.FK_ItemId == input.FK_ItemId &&
i.FK_WarehouseId == input.FK_WarehouseId &&
i.FK_ShopPOItemId == input.FK_ShopPOItemId);
if (existing is not null)
existing.QuantityDispatched = input.Quantity;
else
newItems.Add(new LoadingSheetItem
{
FK_LoadingSheetId = sheet.Id,
FK_ItemId = input.FK_ItemId,
FK_WarehouseId = input.FK_WarehouseId,
FK_ShopPOItemId = input.FK_ShopPOItemId,
QuantityDispatched = input.Quantity
});
}
if (newItems.Count > 0)
await repo.AddItemsAsync(newItems);
var shopPOItemIds = sheet.Items.Select(i => i.FK_ShopPOItemId)
.Concat(newItems.Select(i => i.FK_ShopPOItemId))
.Where(x => x.HasValue)
.Select(x => x!.Value)
.Distinct()
.ToList();
var shopPOIds = shopPOItemIds.Count > 0
? await repo.GetShopPOIdsByItemIdsAsync(shopPOItemIds)
: new List<Guid>();
await repo.ReplaceOrdersAsync(sheet.Id, shopPOIds);
await uow.CommitAsync(ct);
}