diff --git a/OpenNest.Data/NestMaterialsReport.cs b/OpenNest.Data/NestMaterialsReport.cs new file mode 100644 index 00000000..c617350e --- /dev/null +++ b/OpenNest.Data/NestMaterialsReport.cs @@ -0,0 +1,144 @@ +using System.Globalization; +using System.Linq; +using System.Text; + +namespace OpenNest.Data; + +/// +/// The sheets a set of saved nests consume, grouped by material, grade, thickness, units +/// and plate size. Material, grade and thickness come from each nest's server record +/// (metadata-only edits can be newer than the archive); plate sizes and duplicates come +/// from the nest's plates. Plates holding no parts other than cutoffs are not counted: +/// they are never cut. +/// +public sealed class NestMaterialsReport +{ + private readonly Dictionary rows = new(); + private readonly List nestNames = new(); + + /// Nests added, in the order added. + public IReadOnlyList NestNames => nestNames; + + /// Adds one nest's plates to the report. + public void Add(NestRecord record, Nest nest) + { + ArgumentNullException.ThrowIfNull(record); + ArgumentNullException.ThrowIfNull(nest); + + var name = string.IsNullOrWhiteSpace(record.Name) ? nest.Name ?? "" : record.Name; + nestNames.Add(name); + foreach (var plate in nest.Plates) + { + if (plate.Quantity < 1 || !plate.Parts.Any(part => !part.BaseDrawing.IsCutOff)) + continue; + var key = new Key( + (record.Material ?? "").Trim(), + (record.MaterialGrade ?? "").Trim(), + System.Math.Round(record.Thickness, 4), + nest.Units, + System.Math.Round(plate.Size.Width, 4), + System.Math.Round(plate.Size.Length, 4)); + if (!rows.TryGetValue(key, out var row)) + rows[key] = row = new Accumulator(); + row.Quantity += plate.Quantity; + row.Nests.TryAdd(name, 0); + row.Nests[name] += plate.Quantity; + } + } + + /// One row per material, grade, thickness and sheet size, sorted in that order. + public IReadOnlyList Rows => + rows + .OrderBy(pair => pair.Key.Material, StringComparer.OrdinalIgnoreCase) + .ThenBy(pair => pair.Key.Grade, StringComparer.OrdinalIgnoreCase) + .ThenBy(pair => pair.Key.Thickness) + .ThenBy(pair => pair.Key.Units) + .ThenBy(pair => pair.Key.Width) + .ThenBy(pair => pair.Key.Length) + .Select(pair => new NestMaterialRow( + pair.Key.Material, + pair.Key.Grade, + pair.Key.Thickness, + pair.Key.Units, + pair.Key.Width, + pair.Key.Length, + pair.Value.Quantity, + pair.Value.Nests + .OrderBy(nest => nest.Key, StringComparer.OrdinalIgnoreCase) + .Select(nest => new NestMaterialUse(nest.Key, nest.Value)) + .ToList())) + .ToList(); + + /// The rows as CSV with a header line, for a spreadsheet. + public string ToCsv(CultureInfo? culture = null) + { + culture ??= CultureInfo.InvariantCulture; + var builder = new StringBuilder(); + builder.AppendLine("Material,Grade,Thickness,Units,Width,Length,Quantity,Nests"); + foreach (var row in Rows) + { + builder.AppendJoin(',', + Csv(row.Material), + Csv(row.Grade), + Csv(row.Thickness.ToString("0.####", culture)), + Csv(UnitName(row.Units)), + Csv(row.Width.ToString("0.###", culture)), + Csv(row.Length.ToString("0.###", culture)), + row.Quantity.ToString(culture), + Csv(row.NestList)); + builder.AppendLine(); + } + + return builder.ToString(); + } + + public static string UnitName(Units units) => units == Units.Millimeters ? "mm" : "in"; + + private static string Csv(string? value) + { + value ??= ""; + return value.IndexOfAny(new[] { ',', '"', '\r', '\n' }) < 0 + ? value + : "\"" + value.Replace("\"", "\"\"") + "\""; + } + + private readonly record struct Key( + string Material, string Grade, double Thickness, Units Units, double Width, double Length) + { + public bool Equals(Key other) => + string.Equals(Material, other.Material, StringComparison.OrdinalIgnoreCase) + && string.Equals(Grade, other.Grade, StringComparison.OrdinalIgnoreCase) + && Thickness == other.Thickness && Units == other.Units + && Width == other.Width && Length == other.Length; + + public override int GetHashCode() => HashCode.Combine( + StringComparer.OrdinalIgnoreCase.GetHashCode(Material), + StringComparer.OrdinalIgnoreCase.GetHashCode(Grade), + Thickness, Units, Width, Length); + } + + private sealed class Accumulator + { + public int Quantity; + public readonly Dictionary Nests = new(StringComparer.OrdinalIgnoreCase); + } +} + +/// Sheets of this size, counting each plate's duplicates. +/// The nests that use this sheet and how many each uses. +public sealed record NestMaterialRow( + string Material, + string Grade, + double Thickness, + Units Units, + double Width, + double Length, + int Quantity, + IReadOnlyList Nests) +{ + /// Nest names, with a count after any nest using more than one sheet. + public string NestList => string.Join(", ", + Nests.Select(nest => nest.Quantity > 1 ? $"{nest.Name} ({nest.Quantity})" : nest.Name)); +} + +public sealed record NestMaterialUse(string Name, int Quantity); diff --git a/OpenNest.Tests/Data/NestMaterialsReportTests.cs b/OpenNest.Tests/Data/NestMaterialsReportTests.cs new file mode 100644 index 00000000..2c76dfea --- /dev/null +++ b/OpenNest.Tests/Data/NestMaterialsReportTests.cs @@ -0,0 +1,105 @@ +using OpenNest.CNC; +using OpenNest.Data; +using OpenNest.Geometry; + +namespace OpenNest.Tests.Data; + +public class NestMaterialsReportTests +{ + [Fact] + public void Add_GroupsSheetsByMaterialThicknessAndSize_AcrossNests() + { + var report = new NestMaterialsReport(); + report.Add(Record("4734-01", "Mild Steel", "A36", 0.25), + NestWithPlates((48, 96, 2), (60, 120, 1))); + report.Add(Record("4734-02", "mild steel", "a36", 0.25), + NestWithPlates((48, 96, 3))); + report.Add(Record("4734-03", "Aluminum", "5052", 0.125), + NestWithPlates((48, 96, 1))); + + Assert.Collection( + report.Rows, + row => + { + Assert.Equal("Aluminum", row.Material); + Assert.Equal(0.125, row.Thickness); + Assert.Equal(1, row.Quantity); + Assert.Equal("4734-03", row.NestList); + }, + row => + { + Assert.Equal("Mild Steel", row.Material); + Assert.Equal((48.0, 96.0), (row.Width, row.Length)); + Assert.Equal(5, row.Quantity); + Assert.Equal("4734-01 (2), 4734-02 (3)", row.NestList); + }, + row => + { + Assert.Equal((60.0, 120.0), (row.Width, row.Length)); + Assert.Equal(1, row.Quantity); + Assert.Equal("4734-01", row.NestList); + }); + Assert.Equal(3, report.NestNames.Count); + } + + [Fact] + public void Add_SkipsPlatesWithoutParts_AndCutoffOnlyPlates() + { + var nest = NestWithPlates((48, 96, 1)); + nest.CreatePlate().Size = new Size(60, 120); + var cutoffOnly = nest.CreatePlate(); + cutoffOnly.Size = new Size(72, 144); + var cutoff = new CutOff(new Vector(30, 0), CutOffAxis.Vertical); + cutoffOnly.CutOffs.Add(cutoff); + cutoffOnly.Parts.Add(new Part(cutoff.Drawing)); + + var report = new NestMaterialsReport(); + report.Add(Record("Job", "Steel", "", 0.5), nest); + + var row = Assert.Single(report.Rows); + Assert.Equal((48.0, 96.0), (row.Width, row.Length)); + } + + [Fact] + public void ToCsv_QuotesFieldsContainingCommas() + { + var report = new NestMaterialsReport(); + report.Add(Record("A", "Steel, HR", "", 0.25), NestWithPlates((48, 96, 1))); + report.Add(Record("B", "Steel, HR", "", 0.25), NestWithPlates((48, 96, 1))); + + var lines = report.ToCsv().Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries); + + Assert.Equal("Material,Grade,Thickness,Units,Width,Length,Quantity,Nests", lines[0]); + Assert.Equal("\"Steel, HR\",,0.25,in,48,96,2,\"A, B\"", lines[1]); + } + + private static NestRecord Record(string name, string material, string grade, double thickness) => + new() { Id = Guid.NewGuid(), Name = name, Material = material, MaterialGrade = grade, Thickness = thickness }; + + private static Nest NestWithPlates(params (double Width, double Length, int Quantity)[] plates) + { + var nest = new Nest("Job") { Units = Units.Inches }; + var drawing = Rectangle("Part", 10, 10); + nest.Drawings.Add(drawing); + foreach (var (width, length, quantity) in plates) + { + var plate = nest.CreatePlate(); + plate.Size = new Size(width, length); + plate.Quantity = quantity; + plate.Parts.Add(new Part(drawing)); + } + + return nest; + } + + private static Drawing Rectangle(string name, double width, double height) + { + var program = new OpenNest.CNC.Program(); + program.Codes.Add(new RapidMove(new Vector(0, 0))); + program.Codes.Add(new LinearMove(new Vector(width, 0))); + program.Codes.Add(new LinearMove(new Vector(width, height))); + program.Codes.Add(new LinearMove(new Vector(0, height))); + program.Codes.Add(new LinearMove(new Vector(0, 0))); + return new Drawing(name, program); + } +} diff --git a/OpenNest.WinForms.Tests/Forms/SavedNestsFormTests.cs b/OpenNest.WinForms.Tests/Forms/SavedNestsFormTests.cs index debbba4c..77d0b4b0 100644 --- a/OpenNest.WinForms.Tests/Forms/SavedNestsFormTests.cs +++ b/OpenNest.WinForms.Tests/Forms/SavedNestsFormTests.cs @@ -338,6 +338,48 @@ public class SavedNestsFormTests }, TestTimeout, "The pending information edit did not complete."); } + [Fact] + public void SelectingSeveralNests_DisablesSingleNestCommands_AndGetMaterialsSumsTheirSheets() + { + StaTestThread.Run( + () => + { + var first = Record("4734-01"); + first.Material = "Mild Steel"; + first.Thickness = 0.25; + var second = Record("4734-02"); + second.Material = "Mild Steel"; + second.Thickness = 0.25; + var repository = new FakeRepository(first, second); + repository.Files[first.Id] = NestFile((Quantity: 2, Parts: 3)); + repository.Files[second.Id] = NestFile((Quantity: 3, Parts: 1)); + + using var form = new SavedNestsForm(repository); + form.Show(); + var nests = Field(form, "nestGrid"); + PumpUntil(() => nests.Rows.Count == 2, "the nest page"); + + nests.SelectAll(); + Application.DoEvents(); + Assert.Equal(2, nests.SelectedRows.Count); + Assert.False(Field