diff --git a/PepApi.Core/Controllers/NestsController.cs b/PepApi.Core/Controllers/NestsController.cs index 0173fef..c88f5ba 100644 --- a/PepApi.Core/Controllers/NestsController.cs +++ b/PepApi.Core/Controllers/NestsController.cs @@ -214,7 +214,7 @@ public class NestsController : ControllerBase DateLastModified = info.ModifiedDate!.Value, Material = PepHelper.GetMaterial(nest), Plates = PepHelper.GetPlates(nest), - Parts = PepHelper.GetParts(nest), + Parts = await GetPartsFromDbAsync(info), NumberOfTestSquares = PepHelper.GetTestSquareCount(nest), AreTestSquaresOutOfSequence = !PepHelper.AreTestSquaresInCorrectOrder(nest), Customer = info.CustomerName, @@ -228,4 +228,52 @@ public class NestsController : ControllerBase return details; } + + // Build Parts using database PlateDetail.QtyNstd instead of calculating from files + private async Task> GetPartsFromDbAsync(NestHeader info) + { + // Filter by NestName and CopyID to get the correct set for this program + var nestName = info.NestName; + var copyId = info.CopyID; + + // Avoid method calls on columns in the WHERE clause to keep index usage optimal + var plateDetails = await _db.PlateDetails + .Where(p => p.NestName == nestName && p.CopyID == copyId) + .Select(p => new { p.Drawing, p.QtyNstd, p.QtyReq, p.PlateNumber }) + .ToListAsync(); + + // Group by drawing name, aggregate nested and required quantities + var groups = plateDetails + .Where(p => !string.IsNullOrWhiteSpace(p.Drawing)) + .GroupBy(p => p.Drawing.Trim().ToUpper()); + + var parts = new List(); + + foreach (var g in groups) + { + var qtyNested = g.Sum(x => x.QtyNstd ?? 0); + var qtyReq = g.Select(x => x.QtyReq ?? 0).DefaultIfEmpty(0).Max(); + + // Use PlateNumber from DB; convert to 0-based index to align with previous behavior + var nestedOn = g + .Where(x => (x.QtyNstd ?? 0) > 0 && x.PlateNumber.HasValue) + .Select(x => x.PlateNumber!.Value - 1) + .Distinct() + .OrderBy(i => i) + .ToArray(); + + // Preserve the original case for Name if available + var originalName = g.Select(x => x.Drawing).FirstOrDefault(x => !string.IsNullOrWhiteSpace(x)) ?? g.Key; + + parts.Add(new PepApi.Core.Models.Part + { + Name = originalName, + QtyNested = qtyNested, + QtyRequired = qtyReq, + NestedOn = nestedOn + }); + } + + return parts.OrderBy(p => p.Name).ToList(); + } }