mirror of
https://github.com/ajisaacs/OpenNest.git
synced 2026-11-25 05:37:40 -05:00
feat(open): list materials for several saved nests
The Database-mode Open dialog now allows multi-row selection and a Get Materials command (button and context menu) that downloads the chosen nests, or every nest the current search matches across all pages, and lists the sheets they use by material, grade, thickness and size with the quantity and the nests using each. Needed to order stock for a whole job's worth of nests at once instead of opening them one by one. Material, grade and thickness come from each nest's server record; sizes and duplicates from its plates, skipping plates with no parts. Copy All and Save CSV export the list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f9abab0c6d
commit
a994bae76f
5 files changed
+679
-8
No files matched your search
@@ -0,0 +1,144 @@
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace OpenNest.Data;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class NestMaterialsReport
|
||||
{
|
||||
private readonly Dictionary<Key, Accumulator> rows = new();
|
||||
private readonly List<string> nestNames = new();
|
||||
|
||||
/// <summary>Nests added, in the order added.</summary>
|
||||
public IReadOnlyList<string> NestNames => nestNames;
|
||||
|
||||
/// <summary>Adds one nest's plates to the report.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One row per material, grade, thickness and sheet size, sorted in that order.</summary>
|
||||
public IReadOnlyList<NestMaterialRow> 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();
|
||||
|
||||
/// <summary>The rows as CSV with a header line, for a spreadsheet.</summary>
|
||||
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<string, int> Nests = new(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
|
||||
/// <param name="Quantity">Sheets of this size, counting each plate's duplicates.</param>
|
||||
/// <param name="Nests">The nests that use this sheet and how many each uses.</param>
|
||||
public sealed record NestMaterialRow(
|
||||
string Material,
|
||||
string Grade,
|
||||
double Thickness,
|
||||
Units Units,
|
||||
double Width,
|
||||
double Length,
|
||||
int Quantity,
|
||||
IReadOnlyList<NestMaterialUse> Nests)
|
||||
{
|
||||
/// <summary>Nest names, with a count after any nest using more than one sheet.</summary>
|
||||
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);
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<DataGridView>(form, "nestGrid");
|
||||
PumpUntil(() => nests.Rows.Count == 2, "the nest page");
|
||||
|
||||
nests.SelectAll();
|
||||
Application.DoEvents();
|
||||
Assert.Equal(2, nests.SelectedRows.Count);
|
||||
Assert.False(Field<Button>(form, "infoButton").Enabled);
|
||||
Assert.Equal("Get Materials for 2 Nests...", Field<ToolStripMenuItem>(form, "materialsMenuItem").Text);
|
||||
|
||||
var records = nests.SelectedRows.Cast<DataGridViewRow>().Select(row => (NestRecord)row.Tag).ToList();
|
||||
using var materials = new NestMaterialsForm(
|
||||
repository, _ => Task.FromResult<IReadOnlyList<NestRecord>>(records), "2 selected nests");
|
||||
materials.Show();
|
||||
var grid = Field<DataGridView>(materials, "grid");
|
||||
PumpUntil(() => grid.Rows.Count == 1, "the materials list");
|
||||
Assert.Equal("Mild Steel", grid.Rows[0].Cells["Material"].Value);
|
||||
Assert.Equal("48 x 96", grid.Rows[0].Cells["Size"].Value);
|
||||
Assert.Equal(5, grid.Rows[0].Cells["Quantity"].Value);
|
||||
Assert.Equal("4734-01 (2), 4734-02 (3)", grid.Rows[0].Cells["Nests"].Value);
|
||||
},
|
||||
TestTimeout,
|
||||
"The materials test did not complete.");
|
||||
}
|
||||
|
||||
private static NestRecord Record(string name) =>
|
||||
new() { Id = Guid.NewGuid(), Name = name, SavedAt = DateTime.Now };
|
||||
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using OpenNest.Controls;
|
||||
using OpenNest.Data;
|
||||
using OpenNest.IO;
|
||||
|
||||
namespace OpenNest.Forms;
|
||||
|
||||
/// <summary>
|
||||
/// Open Nest (Database mode) > Get Materials: downloads the chosen nests and lists the
|
||||
/// sheets they consume by material, grade, thickness and size, with the quantity and the
|
||||
/// nests that use each. Built by <see cref="NestMaterialsReport"/>; nothing is changed on
|
||||
/// the server.
|
||||
/// </summary>
|
||||
public sealed class NestMaterialsForm : Form
|
||||
{
|
||||
// Archives downloaded and read at once; keeps the server and this machine responsive.
|
||||
private const int Parallelism = 4;
|
||||
|
||||
private readonly INestRepository repository;
|
||||
private readonly Func<CancellationToken, Task<IReadOnlyList<NestRecord>>> loadRecords;
|
||||
private readonly CancellationTokenSource cancellation = new();
|
||||
private readonly DataGridView grid;
|
||||
private readonly Label statusLabel;
|
||||
private readonly ProgressBar progress;
|
||||
private readonly Button copyButton;
|
||||
private readonly Button saveButton;
|
||||
private readonly List<string> failures = new();
|
||||
private readonly ToolTip failureTip = new();
|
||||
private NestMaterialsReport report;
|
||||
|
||||
public NestMaterialsForm(
|
||||
INestRepository repository,
|
||||
Func<CancellationToken, Task<IReadOnlyList<NestRecord>>> loadRecords,
|
||||
string description)
|
||||
{
|
||||
this.repository = repository;
|
||||
this.loadRecords = loadRecords;
|
||||
|
||||
Text = $"Materials — {description}";
|
||||
StartPosition = FormStartPosition.Manual;
|
||||
ClientSize = new Size(1100, 600);
|
||||
MinimumSize = new Size(600, 300);
|
||||
MinimizeBox = false;
|
||||
ShowInTaskbar = false;
|
||||
|
||||
grid = GridStyle.Apply(new DataGridView
|
||||
{
|
||||
Dock = DockStyle.Fill,
|
||||
ReadOnly = true,
|
||||
AllowUserToAddRows = false,
|
||||
AllowUserToDeleteRows = false,
|
||||
SelectionMode = DataGridViewSelectionMode.FullRowSelect,
|
||||
MultiSelect = true,
|
||||
RowHeadersVisible = false,
|
||||
AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None,
|
||||
ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText,
|
||||
}, sizeColumns: false);
|
||||
AddColumn("Material", 160, typeof(string));
|
||||
AddColumn("Grade", 90, typeof(string));
|
||||
AddColumn("Thickness", 80, typeof(double), "0.####");
|
||||
AddColumn("Units", 50, typeof(string));
|
||||
AddColumn("Size", 130, typeof(string));
|
||||
AddColumn("Quantity", 70, typeof(int), "N0");
|
||||
var nests = AddColumn("Nests", 500, typeof(string));
|
||||
nests.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
|
||||
nests.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
|
||||
grid.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
|
||||
|
||||
statusLabel = new Label { AutoSize = true, Margin = new Padding(3, 8, 12, 0) };
|
||||
progress = new ProgressBar { Width = 200, Margin = new Padding(3, 6, 3, 3) };
|
||||
copyButton = new Button { Text = "Copy All", AutoSize = true, Enabled = false };
|
||||
copyButton.Click += (_, _) => CopyAll();
|
||||
saveButton = new Button { Text = "Save CSV...", AutoSize = true, Enabled = false };
|
||||
saveButton.Click += (_, _) => SaveCsv();
|
||||
var closeButton = new Button { Text = "Close", AutoSize = true, DialogResult = DialogResult.Cancel };
|
||||
CancelButton = closeButton;
|
||||
|
||||
var bar = new FlowLayoutPanel { Dock = DockStyle.Bottom, AutoSize = true, WrapContents = false, Padding = new Padding(3) };
|
||||
bar.Controls.Add(copyButton);
|
||||
bar.Controls.Add(saveButton);
|
||||
bar.Controls.Add(closeButton);
|
||||
bar.Controls.Add(progress);
|
||||
bar.Controls.Add(statusLabel);
|
||||
|
||||
Controls.Add(grid);
|
||||
Controls.Add(bar);
|
||||
|
||||
Load += (_, _) => DialogBounds.FitToOwnerScreen(this);
|
||||
Shown += async (_, _) => await RunAsync();
|
||||
FormClosed += (_, _) => cancellation.Cancel();
|
||||
}
|
||||
|
||||
private DataGridViewTextBoxColumn AddColumn(string header, int width, Type valueType, string format = null)
|
||||
{
|
||||
var column = new DataGridViewTextBoxColumn
|
||||
{
|
||||
Name = header,
|
||||
HeaderText = header,
|
||||
Width = width,
|
||||
ValueType = valueType,
|
||||
};
|
||||
if (valueType != typeof(string))
|
||||
column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
|
||||
if (format != null)
|
||||
column.DefaultCellStyle.Format = format;
|
||||
grid.Columns.Add(column);
|
||||
return column;
|
||||
}
|
||||
|
||||
private async Task RunAsync()
|
||||
{
|
||||
var token = cancellation.Token;
|
||||
try
|
||||
{
|
||||
statusLabel.Text = "Finding nests...";
|
||||
progress.Style = ProgressBarStyle.Marquee;
|
||||
var records = await loadRecords(token);
|
||||
if (IsDisposed)
|
||||
return;
|
||||
|
||||
progress.Style = ProgressBarStyle.Continuous;
|
||||
progress.Maximum = System.Math.Max(1, records.Count);
|
||||
progress.Value = 0;
|
||||
var built = new NestMaterialsReport();
|
||||
var gate = new object();
|
||||
var done = 0;
|
||||
void Report() => statusLabel.Text = $"Reading nests: {done:N0} of {records.Count:N0}...";
|
||||
Report();
|
||||
|
||||
using var throttle = new SemaphoreSlim(Parallelism);
|
||||
var tasks = records.Select(async record =>
|
||||
{
|
||||
await throttle.WaitAsync(token);
|
||||
try
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var file = await repository.GetFileAsync(record.Id, token);
|
||||
if (file == null)
|
||||
throw new InvalidOperationException("no longer on the server");
|
||||
await Task.Run(() =>
|
||||
{
|
||||
using var stream = new MemoryStream(file);
|
||||
var nest = new NestReader(stream).Read();
|
||||
lock (gate)
|
||||
built.Add(record, nest);
|
||||
}, token);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
lock (gate)
|
||||
failures.Add($"{record.Name}: {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
throttle.Release();
|
||||
if (!IsDisposed)
|
||||
{
|
||||
// Continuations of the UI-thread loop resume on the UI thread.
|
||||
done++;
|
||||
progress.Value = System.Math.Min(progress.Maximum, done);
|
||||
Report();
|
||||
}
|
||||
}
|
||||
}).ToList();
|
||||
await Task.WhenAll(tasks);
|
||||
if (IsDisposed)
|
||||
return;
|
||||
|
||||
report = built;
|
||||
Populate();
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (!IsDisposed)
|
||||
{
|
||||
progress.Visible = false;
|
||||
statusLabel.Text = $"Could not get materials: {ex.Message}";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void Populate()
|
||||
{
|
||||
grid.Rows.Clear();
|
||||
var rows = report.Rows;
|
||||
foreach (var row in rows)
|
||||
{
|
||||
grid.Rows.Add(
|
||||
row.Material,
|
||||
row.Grade,
|
||||
row.Thickness,
|
||||
NestMaterialsReport.UnitName(row.Units),
|
||||
$"{row.Width.ToString("0.###", CultureInfo.CurrentCulture)} x {row.Length.ToString("0.###", CultureInfo.CurrentCulture)}",
|
||||
row.Quantity,
|
||||
row.NestList);
|
||||
}
|
||||
|
||||
progress.Visible = false;
|
||||
var sheets = rows.Sum(row => row.Quantity);
|
||||
var text = $"{report.NestNames.Count:N0} nest(s), {rows.Count:N0} material/size row(s), {sheets:N0} sheet(s)";
|
||||
if (failures.Count > 0)
|
||||
{
|
||||
text += $" — {failures.Count:N0} nest(s) could not be read";
|
||||
failureTip.SetToolTip(statusLabel, string.Join(Environment.NewLine, failures.Take(30)));
|
||||
statusLabel.ForeColor = Color.Firebrick;
|
||||
}
|
||||
|
||||
statusLabel.Text = text;
|
||||
copyButton.Enabled = saveButton.Enabled = rows.Count > 0;
|
||||
}
|
||||
|
||||
private void CopyAll()
|
||||
{
|
||||
// Tab-separated so it pastes into a spreadsheet as columns.
|
||||
var builder = new StringBuilder();
|
||||
builder.AppendLine("Material\tGrade\tThickness\tUnits\tWidth\tLength\tQuantity\tNests");
|
||||
foreach (var row in report.Rows)
|
||||
{
|
||||
builder.Append(row.Material).Append('\t')
|
||||
.Append(row.Grade).Append('\t')
|
||||
.Append(row.Thickness.ToString("0.####", CultureInfo.CurrentCulture)).Append('\t')
|
||||
.Append(NestMaterialsReport.UnitName(row.Units)).Append('\t')
|
||||
.Append(row.Width.ToString("0.###", CultureInfo.CurrentCulture)).Append('\t')
|
||||
.Append(row.Length.ToString("0.###", CultureInfo.CurrentCulture)).Append('\t')
|
||||
.Append(row.Quantity.ToString(CultureInfo.CurrentCulture)).Append('\t')
|
||||
.AppendLine(row.NestList);
|
||||
}
|
||||
|
||||
Clipboard.SetText(builder.ToString());
|
||||
statusLabel.Text = $"Copied {report.Rows.Count:N0} row(s).";
|
||||
}
|
||||
|
||||
private void SaveCsv()
|
||||
{
|
||||
using var dialog = new SaveFileDialog
|
||||
{
|
||||
Filter = "CSV files (*.csv)|*.csv",
|
||||
FileName = "Materials.csv",
|
||||
};
|
||||
if (dialog.ShowDialog(this) != DialogResult.OK)
|
||||
return;
|
||||
try
|
||||
{
|
||||
File.WriteAllText(dialog.FileName, report.ToCsv(), Encoding.UTF8);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(this, $"Could not save: {ex.Message}", "Save CSV", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
failureTip.Dispose();
|
||||
// The cancellation source is left undisposed: downloads still finishing after the
|
||||
// window closes observe its token.
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
@@ -72,6 +73,8 @@ public sealed class SavedNestsForm : Form
|
||||
private bool editingInfo;
|
||||
private readonly Button infoButton;
|
||||
private readonly ToolStripMenuItem infoMenuItem;
|
||||
private readonly ToolStripMenuItem materialsMenuItem;
|
||||
private readonly Button materialsButton;
|
||||
|
||||
internal Func<EditNestInfoForm, DialogResult> ShowNestInfoDialog { get; set; }
|
||||
private IReadOnlyList<Plate> previewPlates = Array.Empty<Plate>();
|
||||
@@ -106,6 +109,8 @@ public sealed class SavedNestsForm : Form
|
||||
|
||||
// Nests: one server page, sorted by the server when a header is clicked.
|
||||
nestGrid = CreateGrid();
|
||||
// Several rows can be chosen for Get Materials; the other commands use the current row.
|
||||
nestGrid.MultiSelect = true;
|
||||
nestGrid.RowHeadersWidth = 64;
|
||||
AddNestColumn("Nest name", NestSortField.Name, 170);
|
||||
AddNestColumn("Status", NestSortField.Status, 100);
|
||||
@@ -136,8 +141,9 @@ public sealed class SavedNestsForm : Form
|
||||
};
|
||||
nestGrid.CellMouseDown += (_, e) =>
|
||||
{
|
||||
// Right-click highlights the row under the pointer before its menu opens.
|
||||
if (e.Button == MouseButtons.Right && e.RowIndex >= 0)
|
||||
// Right-click highlights the row under the pointer before its menu opens, keeping
|
||||
// a multi-row selection that already includes it.
|
||||
if (e.Button == MouseButtons.Right && e.RowIndex >= 0 && !nestGrid.Rows[e.RowIndex].Selected)
|
||||
nestGrid.CurrentCell = nestGrid.Rows[e.RowIndex].Cells[0];
|
||||
};
|
||||
nestGrid.SelectionChanged += (_, _) =>
|
||||
@@ -145,13 +151,26 @@ public sealed class SavedNestsForm : Form
|
||||
UpdateCommands();
|
||||
ScheduleDetails();
|
||||
};
|
||||
// With several rows selected the details follow the current row, which settles
|
||||
// after SelectionChanged.
|
||||
nestGrid.CurrentCellChanged += (_, _) =>
|
||||
{
|
||||
if (nestGrid.SelectedRows.Count > 1)
|
||||
ScheduleDetails();
|
||||
};
|
||||
|
||||
var menu = new ContextMenuStrip();
|
||||
openMenuItem = new ToolStripMenuItem("Open", null, (_, _) => OpenSelected()) { ShortcutKeyDisplayString = "Enter" };
|
||||
deleteMenuItem = new ToolStripMenuItem("Delete...", null, async (_, _) => await DeleteSelectedAsync());
|
||||
var refreshMenuItem = new ToolStripMenuItem("Refresh", null, async (_, _) => await RunAsync(session.RefreshAsync));
|
||||
infoMenuItem = new ToolStripMenuItem("Nest Information...", null, async (_, _) => await EditSelectedInfoAsync());
|
||||
menu.Items.AddRange(new ToolStripItem[] { openMenuItem, infoMenuItem, deleteMenuItem, new ToolStripSeparator(), refreshMenuItem });
|
||||
materialsMenuItem = new ToolStripMenuItem("Get Materials...", null, (_, _) => ShowSelectedMaterials());
|
||||
var allMaterialsMenuItem = new ToolStripMenuItem("Get Materials for All Matching Nests...", null, (_, _) => ShowAllMatchingMaterials());
|
||||
menu.Items.AddRange(new ToolStripItem[]
|
||||
{
|
||||
openMenuItem, infoMenuItem, deleteMenuItem, new ToolStripSeparator(),
|
||||
materialsMenuItem, allMaterialsMenuItem, new ToolStripSeparator(), refreshMenuItem,
|
||||
});
|
||||
nestGrid.ContextMenuStrip = menu;
|
||||
|
||||
// Details of the highlighted nest.
|
||||
@@ -247,8 +266,22 @@ public sealed class SavedNestsForm : Form
|
||||
split.Panel1.Controls.Add(nestGrid);
|
||||
infoButton = new Button { Text = "Nest Information...", AutoSize = true, Dock = DockStyle.Right };
|
||||
infoButton.Click += async (_, _) => await EditSelectedInfoAsync();
|
||||
materialsButton = new Button { Text = "Get Materials \u25BE", AutoSize = true, Dock = DockStyle.Right };
|
||||
materialsButton.Click += (_, _) =>
|
||||
{
|
||||
var selected = SelectedNestRecords().Count;
|
||||
var total = session.Page?.Total ?? 0;
|
||||
var choices = new ContextMenuStrip();
|
||||
choices.Items.Add($"Selected Nests ({selected:N0})...", null, (_, _) => ShowSelectedMaterials())
|
||||
.Enabled = selected > 0;
|
||||
choices.Items.Add($"All Matching Nests ({total:N0})...", null, (_, _) => ShowAllMatchingMaterials())
|
||||
.Enabled = total > 0;
|
||||
choices.Closed += (_, _) => BeginInvoke(new Action(choices.Dispose));
|
||||
choices.Show(materialsButton, new Point(0, materialsButton.Height));
|
||||
};
|
||||
var nestsHeader = new Panel { Dock = DockStyle.Top, Height = 36 };
|
||||
nestsHeader.Controls.Add(infoButton);
|
||||
nestsHeader.Controls.Add(materialsButton);
|
||||
nestsHeader.Controls.Add(SectionLabel("Nests", DockStyle.Left));
|
||||
split.Panel1.Controls.Add(nestsHeader);
|
||||
ShowNestInfoDialog = dialog => dialog.ShowDialog(this);
|
||||
@@ -443,11 +476,16 @@ public sealed class SavedNestsForm : Form
|
||||
|
||||
private void UpdateCommands()
|
||||
{
|
||||
var hasSelection = SelectedNestId() != null && !editingInfo && !deleting;
|
||||
// Open, information and delete act on one nest; Get Materials on every selected nest.
|
||||
var hasSelection = SelectedNestId() != null && nestGrid.SelectedRows.Count == 1 && !editingInfo && !deleting;
|
||||
openMenuItem.Enabled = hasSelection;
|
||||
infoButton.Enabled = hasSelection;
|
||||
infoMenuItem.Enabled = hasSelection;
|
||||
deleteMenuItem.Enabled = hasSelection;
|
||||
materialsMenuItem.Enabled = nestGrid.SelectedRows.Count > 0 && !editingInfo;
|
||||
materialsMenuItem.Text = nestGrid.SelectedRows.Count > 1
|
||||
? $"Get Materials for {nestGrid.SelectedRows.Count:N0} Nests..."
|
||||
: "Get Materials...";
|
||||
}
|
||||
|
||||
private void UpdateTitle(string summary)
|
||||
@@ -513,8 +551,80 @@ public sealed class SavedNestsForm : Form
|
||||
return unitIndex == 0 ? $"{size:0} {FileSizeUnits[unitIndex]}" : $"{size:0.#} {FileSizeUnits[unitIndex]}";
|
||||
}
|
||||
|
||||
private Guid? SelectedNestId() =>
|
||||
nestGrid.SelectedRows.Count > 0 && nestGrid.SelectedRows[0].Cells[IdColumn].Value is Guid id ? id : null;
|
||||
/// <summary>
|
||||
/// The highlighted nest: the current row while it is selected. With several rows
|
||||
/// selected the details follow the row last clicked or arrowed to.
|
||||
/// </summary>
|
||||
private Guid? SelectedNestId()
|
||||
{
|
||||
// While SelectionChanged runs, CurrentRow still names the previously current row,
|
||||
// so a single selection is read from SelectedRows.
|
||||
var row = nestGrid.SelectedRows.Count == 1 ? nestGrid.SelectedRows[0]
|
||||
: nestGrid.CurrentRow is { Selected: true } current ? current : null;
|
||||
return row?.Cells[IdColumn].Value is Guid id ? id : null;
|
||||
}
|
||||
|
||||
/// <summary>Every selected nest, in list order.</summary>
|
||||
private List<NestRecord> SelectedNestRecords() =>
|
||||
nestGrid.SelectedRows.Cast<DataGridViewRow>()
|
||||
.OrderBy(row => row.Index)
|
||||
.Select(row => row.Tag as NestRecord)
|
||||
.Where(record => record != null)
|
||||
.ToList();
|
||||
|
||||
private void ShowSelectedMaterials()
|
||||
{
|
||||
var records = SelectedNestRecords();
|
||||
if (records.Count == 0)
|
||||
return;
|
||||
ShowMaterials(
|
||||
_ => Task.FromResult<IReadOnlyList<NestRecord>>(records),
|
||||
records.Count == 1 ? records[0].Name : $"{records.Count:N0} selected nests");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lists materials for every nest the current search matches, across all pages, read
|
||||
/// from the server in the largest pages it allows.
|
||||
/// </summary>
|
||||
private void ShowAllMatchingMaterials()
|
||||
{
|
||||
var search = session.Search;
|
||||
var sort = session.Sort;
|
||||
var descending = session.Descending;
|
||||
ShowMaterials(
|
||||
async token =>
|
||||
{
|
||||
var records = new List<NestRecord>();
|
||||
var seen = new HashSet<Guid>();
|
||||
var offset = 0;
|
||||
while (true)
|
||||
{
|
||||
var page = await repository.QueryAsync(
|
||||
new NestQuery
|
||||
{
|
||||
Search = search,
|
||||
Sort = sort,
|
||||
Descending = descending,
|
||||
Offset = offset,
|
||||
Limit = NestQuery.MaxLimit,
|
||||
},
|
||||
token);
|
||||
foreach (var record in page.Items)
|
||||
if (seen.Add(record.Id))
|
||||
records.Add(record);
|
||||
offset += page.Items.Count;
|
||||
if (page.Items.Count == 0 || offset >= page.Total)
|
||||
return records;
|
||||
}
|
||||
},
|
||||
search.Length == 0 ? "all nests" : $"nests matching \"{search}\"");
|
||||
}
|
||||
|
||||
private void ShowMaterials(Func<CancellationToken, Task<IReadOnlyList<NestRecord>>> records, string description)
|
||||
{
|
||||
using var dialog = new NestMaterialsForm(repository, records, description);
|
||||
dialog.ShowDialog(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Shows the highlighted nest's details after a short pause, so arrowing through the
|
||||
@@ -706,7 +816,7 @@ public sealed class SavedNestsForm : Form
|
||||
|
||||
private void OpenSelected()
|
||||
{
|
||||
if (editingInfo || SelectedNestId() is not Guid id)
|
||||
if (editingInfo || nestGrid.SelectedRows.Count != 1 || SelectedNestId() is not Guid id)
|
||||
return;
|
||||
SelectedId = id;
|
||||
DialogResult = DialogResult.OK;
|
||||
@@ -908,7 +1018,7 @@ public sealed class SavedNestsForm : Form
|
||||
|
||||
private async Task DeleteSelectedAsync()
|
||||
{
|
||||
if (deleting || SelectedNestId() is not Guid id)
|
||||
if (deleting || nestGrid.SelectedRows.Count != 1 || SelectedNestId() is not Guid id)
|
||||
return;
|
||||
|
||||
var name = nestGrid.SelectedRows[0].Cells[0].Value?.ToString() ?? "";
|
||||
|
||||
Reference in new issue
Block a user