feat(autonest): load sheet and drop stock from MaterialLedger

Auto Nest's Stock Options gets a Load from ledger button that reads the nest
material's free sheets and drops from MaterialLedger's API-key-protected
GET /api/stock/opennest. Ledger rows are request-local: the engine sees them as
ordinary NestPlateStock rows with ledger:{n} ids and finite quantities, and they
are never written to Nest.PlateOptions.

- OpenNest.Data/MaterialLedger: settings file, read-only client (X-Api-Key,
  5 s timeout, closed LedgerStockResult set) and LedgerStockMapper (bundles and
  sheets one row each, same-size drops grouped with ordered item codes, unknown
  shapes and too-small items skipped, inch/mm conversion).
- Options: MaterialLedger URL and API key (DPAPI, CurrentUser) with Test.
- Auto Nest grid: Use, Qty and Source columns for every row; PlateOption gains
  request-local Quantity and Id, which NestStockBuilder passes to the engine.
  Ledger rows score by area; hand-typed costs stay saved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-10-25 17:40:44 -04:00
1 parent 42f1762c56
commit ea1decc097
21 files changed
+1793 -23

No files matched your search

+6
View File
@@ -6,6 +6,12 @@ namespace OpenNest
public double Length { get; set; }
public double Cost { get; set; }
/// <summary>Sheets on hand for this request; null offers the size without limit. Not saved with the nest.</summary>
public int? Quantity { get; set; }
/// <summary>The engine stock id for this request; null uses the option's position. Not saved with the nest.</summary>
public string Id { get; set; }
public double Area => Width * Length;
}
}
@@ -0,0 +1,67 @@
namespace OpenNest.Data.MaterialLedger;
/// <summary>
/// The body of MaterialLedger's <c>GET /api/stock/opennest</c>: the <c>/api/stock</c> shape plus
/// <see cref="Mapped"/>, false when ML has no approved mapping for the OpenNest material.
/// </summary>
public sealed record LedgerStockResponse(
bool Mapped,
IReadOnlyList<LedgerStockSpec>? Specs,
IReadOnlyList<LedgerStockItem>? Items);
public sealed record LedgerStockSpec(long MaterialSpecId, string DisplayName, decimal ThicknessIn, string? GaugeLabel);
/// <summary>
/// Mirrors ML <c>StockApi.StockItemDto</c>. Sizes are inches with <see cref="WidthIn"/> the short
/// side; <see cref="Quantity"/> is free after active holds. <see cref="Kind"/> and
/// <see cref="Shape"/> stay strings so a new ML enum value still deserializes.
/// </summary>
public sealed record LedgerStockItem(
string ItemCode,
long MaterialSpecId,
string Kind,
decimal WidthIn,
decimal LengthIn,
int Quantity,
string Shape,
string LocationCode,
string LocationName,
string? ParentLocationCode,
decimal? CostPerUnit,
DateTime LastObservedAtUtc);
/// <summary>ML <c>InventoryItemKind</c> names.</summary>
public static class LedgerItemKinds
{
public const string FullSheetBundle = "FullSheetBundle";
public const string FullSheet = "FullSheet";
public const string Drop = "Drop";
}
/// <summary>ML <c>ShapeClassification</c> names.</summary>
public static class LedgerItemShapes
{
public const string Rectangular = "Rectangular";
public const string IrregularConservativeRectangle = "IrregularConservativeRectangle";
public const string Unknown = "Unknown";
}
/// <summary>What a ledger stock request came to. Expected failures are results, never exceptions.</summary>
public abstract record LedgerStockResult
{
private LedgerStockResult() { }
/// <summary>No ledger URL is set on this PC.</summary>
public sealed record NotConfigured : LedgerStockResult;
/// <summary>The ledger did not answer usefully: network error, timeout, bad status or body.</summary>
public sealed record Unreachable(string Reason) : LedgerStockResult;
/// <summary>The ledger rejected the API key (401/403).</summary>
public sealed record Unauthorized : LedgerStockResult;
/// <summary>The ledger has no approved mapping for this material, grade and thickness.</summary>
public sealed record Unmapped : LedgerStockResult;
public sealed record Ok(IReadOnlyList<LedgerStockSpec> Specs, IReadOnlyList<LedgerStockItem> Items) : LedgerStockResult;
}
@@ -0,0 +1,168 @@
using OpenNest.Geometry;
using OpenNest.Math;
namespace OpenNest.Data.MaterialLedger;
/// <summary>
/// One Auto Nest stock row built from ledger items. <see cref="Size"/> is in nest units with
/// Width the short side. <see cref="ItemCodes"/> lists one code per unit of
/// <see cref="Quantity"/> (a bundle repeats its code), in the order later steps assign them.
/// </summary>
public sealed record LedgerStockRow(
string Id,
Size Size,
int Quantity,
bool IsDrop,
bool IsIrregular,
IReadOnlyList<string> ItemCodes,
IReadOnlyList<string> Locations);
/// <summary>The rows offered to Auto Nest and the counts of ledger items left out.</summary>
public sealed record LedgerStockMapping(
IReadOnlyList<LedgerStockRow> Rows,
int SkippedUnknownShape,
int SkippedTooSmall)
{
public int SheetRows => Rows.Count(r => !r.IsDrop);
public int Drops => Rows.Where(r => r.IsDrop).Sum(r => r.Quantity);
/// <summary>E.g. "Ledger: 3 sheet sizes, 7 drops (2 skipped: unknown shape)".</summary>
public string Summary
{
get
{
var skipped = new List<string>();
if (SkippedUnknownShape > 0)
skipped.Add($"{SkippedUnknownShape} unknown shape");
if (SkippedTooSmall > 0)
skipped.Add($"{SkippedTooSmall} too small for any part");
var text = $"Ledger: {Plural(SheetRows, "sheet size")}, {Plural(Drops, "drop")}";
return skipped.Count == 0
? text
: $"{text} ({SkippedUnknownShape + SkippedTooSmall} skipped: {string.Join(", ", skipped)})";
}
}
private static string Plural(int count, string noun) => count == 1 ? $"1 {noun}" : $"{count} {noun}s";
}
/// <summary>
/// Turns ledger items into Auto Nest stock rows: each bundle or full sheet becomes a row, and
/// drops of the same usable size share a row. The engine sees only the <c>ledger:{n}</c> ids.
/// </summary>
public static class LedgerStockMapper
{
public const string IdPrefix = "ledger:";
private const double MillimetersPerInch = 25.4;
public static bool IsLedgerId(string? id) =>
id != null && id.StartsWith(IdPrefix, StringComparison.Ordinal);
/// <summary>The nest thickness in inches for the ledger query, rounded to 4 places.</summary>
public static double ThicknessInches(double thickness, Units units) =>
System.Math.Round(units == Units.Millimeters ? thickness / MillimetersPerInch : thickness, 4);
/// <param name="items">Ledger items in ledger order.</param>
/// <param name="units">The nest's units; ledger sizes are always inches.</param>
/// <param name="partEnvelopes">
/// Bounding sizes of the parts to nest, in nest units. An item no part fits in either
/// orientation is skipped; null or empty keeps every size.
/// </param>
public static LedgerStockMapping Map(IEnumerable<LedgerStockItem> items, Units units,
IReadOnlyCollection<Size>? partEnvelopes = null)
{
ArgumentNullException.ThrowIfNull(items);
var scale = units == Units.Millimeters ? MillimetersPerInch : 1.0;
var unknown = 0;
var tooSmall = 0;
var entries = new List<Entry>();
var drops = new Dictionary<(decimal Width, decimal Length, bool Irregular), Entry>();
foreach (var item in items)
{
if (item == null || item.Quantity <= 0)
continue;
if (!IsShape(item, LedgerItemShapes.Rectangular) && !IsShape(item, LedgerItemShapes.IrregularConservativeRectangle))
{
// Unknown, and any shape this build does not know, has no trustworthy usable size.
unknown++;
continue;
}
if (!IsKind(item, LedgerItemKinds.Drop) && !IsKind(item, LedgerItemKinds.FullSheet)
&& !IsKind(item, LedgerItemKinds.FullSheetBundle))
continue;
var shortIn = System.Math.Min(item.WidthIn, item.LengthIn);
var longIn = System.Math.Max(item.WidthIn, item.LengthIn);
if (shortIn <= 0)
continue;
var size = new Size((double)shortIn * scale, (double)longIn * scale);
if (!AnyPartFits(size, partEnvelopes))
{
tooSmall += item.Quantity;
continue;
}
var irregular = IsShape(item, LedgerItemShapes.IrregularConservativeRectangle);
if (IsKind(item, LedgerItemKinds.Drop))
{
// ML stores sizes as decimal(10,3), so identical drops match after rounding.
var key = (System.Math.Round(shortIn, 3), System.Math.Round(longIn, 3), irregular);
if (!drops.TryGetValue(key, out var group))
{
group = new Entry(size, IsDrop: true, irregular);
drops.Add(key, group);
entries.Add(group);
}
group.Items.Add(item);
}
else
{
var sheet = new Entry(size, IsDrop: false, irregular);
sheet.Items.Add(item);
entries.Add(sheet);
}
}
var rows = new List<LedgerStockRow>(entries.Count);
foreach (var entry in entries)
{
var ordered = entry.IsDrop
? entry.Items.OrderBy(i => i.LocationCode, StringComparer.Ordinal)
.ThenBy(i => i.ItemCode, StringComparer.Ordinal).ToList()
: entry.Items;
var codes = ordered.SelectMany(i => Enumerable.Repeat(i.ItemCode, i.Quantity)).ToList();
var locations = ordered.Select(i => i.LocationCode).Where(code => !string.IsNullOrEmpty(code))
.Distinct(StringComparer.Ordinal).ToList();
rows.Add(new LedgerStockRow($"{IdPrefix}{rows.Count + 1}", entry.Size, codes.Count,
entry.IsDrop, entry.IsIrregular, codes, locations));
}
return new LedgerStockMapping(rows, unknown, tooSmall);
}
private static bool AnyPartFits(Size size, IReadOnlyCollection<Size>? partEnvelopes)
{
if (partEnvelopes == null || partEnvelopes.Count == 0)
return true;
foreach (var part in partEnvelopes)
{
var partShort = System.Math.Min(part.Width, part.Length);
var partLong = System.Math.Max(part.Width, part.Length);
if (partShort <= size.Width + Tolerance.Epsilon && partLong <= size.Length + Tolerance.Epsilon)
return true;
}
return false;
}
private static bool IsKind(LedgerStockItem item, string kind) =>
string.Equals(item.Kind, kind, StringComparison.OrdinalIgnoreCase);
private static bool IsShape(LedgerStockItem item, string shape) =>
string.Equals(item.Shape, shape, StringComparison.OrdinalIgnoreCase);
private sealed record Entry(Size Size, bool IsDrop, bool IsIrregular)
{
public List<LedgerStockItem> Items { get; } = new();
}
}
@@ -0,0 +1,95 @@
using System.Globalization;
using System.Net;
using System.Net.Http;
using System.Text.Json;
namespace OpenNest.Data.MaterialLedger;
/// <summary>
/// Read-only client for MaterialLedger's stock API. It never writes to the ledger, and what it
/// reads is a snapshot, not a reservation. Expected failures come back as
/// <see cref="LedgerStockResult"/> cases; only the caller's own cancellation throws.
/// </summary>
public sealed class MaterialLedgerClient
{
/// <summary>Stock lists are larger than the nest-name lookup, so this waits longer than its 3 s.</summary>
public static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(5);
public const string ApiKeyHeader = "X-Api-Key";
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
private readonly HttpClient http;
private readonly MaterialLedgerSettings settings;
private readonly TimeSpan timeout;
/// <param name="timeout">Per-request limit; <see cref="RequestTimeout"/> when null.</param>
public MaterialLedgerClient(HttpClient http, MaterialLedgerSettings settings, TimeSpan? timeout = null)
{
this.http = http ?? throw new ArgumentNullException(nameof(http));
this.settings = settings ?? throw new ArgumentNullException(nameof(settings));
this.timeout = timeout ?? RequestTimeout;
}
/// <summary>
/// The free sheets and drops for an OpenNest material. ML resolves the
/// material/grade/thickness mapping itself; <paramref name="thicknessIn"/> is inches.
/// </summary>
public async Task<LedgerStockResult> GetStockAsync(string material, string? grade, double thicknessIn,
CancellationToken cancellationToken)
{
if (!settings.IsConfigured)
return new LedgerStockResult.NotConfigured();
if (!Uri.TryCreate(settings.BaseUrl.TrimEnd('/') + "/", UriKind.Absolute, out var baseUri)
|| baseUri.Scheme != Uri.UriSchemeHttp && baseUri.Scheme != Uri.UriSchemeHttps)
return new LedgerStockResult.Unreachable($"'{settings.BaseUrl}' is not an http or https address.");
var query = "api/stock/opennest"
+ "?material=" + Uri.EscapeDataString(material ?? "")
+ "&grade=" + Uri.EscapeDataString(grade ?? "")
+ "&thicknessIn=" + System.Math.Round(thicknessIn, 4).ToString("0.####", CultureInfo.InvariantCulture);
using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeoutSource.CancelAfter(timeout);
try
{
using var request = new HttpRequestMessage(HttpMethod.Get, new Uri(baseUri, query));
if (!string.IsNullOrEmpty(settings.ApiKey))
request.Headers.TryAddWithoutValidation(ApiKeyHeader, settings.ApiKey);
using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeoutSource.Token);
if (response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
return new LedgerStockResult.Unauthorized();
if (response.StatusCode == HttpStatusCode.NotFound)
return new LedgerStockResult.Unreachable("This MaterialLedger has no OpenNest stock route; update MaterialLedger.");
if (!response.IsSuccessStatusCode)
return new LedgerStockResult.Unreachable($"HTTP {(int)response.StatusCode} {response.ReasonPhrase}".TrimEnd());
await using var body = await response.Content.ReadAsStreamAsync(timeoutSource.Token);
var stock = await JsonSerializer.DeserializeAsync<LedgerStockResponse>(body, JsonOptions, timeoutSource.Token);
if (stock == null)
return new LedgerStockResult.Unreachable("The ledger returned an empty response.");
if (!stock.Mapped)
return new LedgerStockResult.Unmapped();
return new LedgerStockResult.Ok(stock.Specs ?? Array.Empty<LedgerStockSpec>(),
stock.Items ?? Array.Empty<LedgerStockItem>());
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
return new LedgerStockResult.Unreachable(
$"No answer within {timeout.TotalSeconds.ToString("0.#", CultureInfo.InvariantCulture)} s.");
}
catch (HttpRequestException ex)
{
return new LedgerStockResult.Unreachable(ex.Message);
}
catch (JsonException)
{
return new LedgerStockResult.Unreachable("The ledger's response could not be read.");
}
catch (IOException ex)
{
return new LedgerStockResult.Unreachable(ex.Message);
}
}
}
@@ -0,0 +1,105 @@
using System.Text.Json;
namespace OpenNest.Data.MaterialLedger;
/// <summary>
/// The MaterialLedger address and API key for this PC, stored at
/// %APPDATA%\OpenNest\material-ledger.json. The key is written only in the protected form the
/// caller's protector produces (DPAPI on the desktop), never in plain text. Loading never
/// throws; a missing, corrupt or unreadable file means not configured.
/// </summary>
public sealed class MaterialLedgerSettings
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
};
/// <summary>Base URL of MaterialLedger, e.g. http://ledger:5000. Empty means not configured.</summary>
public string BaseUrl { get; set; } = "";
/// <summary>The plain API key in memory (ML key name <c>Api:Keys:OpenNest</c>).</summary>
public string ApiKey { get; set; } = "";
public bool IsConfigured => !string.IsNullOrWhiteSpace(BaseUrl);
/// <summary>%APPDATA%\OpenNest\material-ledger.json.</summary>
public static string DefaultPath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"OpenNest", "material-ledger.json");
/// <summary>
/// Reads the settings, unprotecting the stored key with <paramref name="unprotect"/>. A key
/// that cannot be unprotected (another user or PC) loads as empty so the ledger reports
/// unauthorized instead of failing to start.
/// </summary>
public static MaterialLedgerSettings Load(string path, Func<string, string> unprotect)
{
ArgumentNullException.ThrowIfNull(unprotect);
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
return new();
try
{
var file = JsonSerializer.Deserialize<SettingsFile>(File.ReadAllText(path), JsonOptions);
if (file == null)
return new();
var settings = new MaterialLedgerSettings { BaseUrl = NormalizeUrl(file.BaseUrl) };
if (!string.IsNullOrEmpty(file.ProtectedApiKey))
{
try
{
settings.ApiKey = unprotect(file.ProtectedApiKey);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
settings.ApiKey = "";
}
}
return settings;
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
{
return new();
}
}
/// <summary>Writes camelCase JSON with the key protected by <paramref name="protect"/>.</summary>
public void Save(string path, Func<string, string> protect)
{
ArgumentNullException.ThrowIfNull(protect);
var json = JsonSerializer.Serialize(new SettingsFile
{
BaseUrl = NormalizeUrl(BaseUrl),
ProtectedApiKey = string.IsNullOrEmpty(ApiKey) ? "" : protect(ApiKey),
}, JsonOptions);
var directory = Path.GetDirectoryName(Path.GetFullPath(path));
if (!string.IsNullOrEmpty(directory))
Directory.CreateDirectory(directory);
File.WriteAllText(path, json);
}
/// <summary>Validate and normalize a ledger base URL; blank is valid and means not configured.</summary>
public static bool TryNormalizeUrl(string? url, out string normalized)
{
normalized = NormalizeUrl(url);
if (normalized.Length == 0)
return true;
if (Uri.TryCreate(normalized, UriKind.Absolute, out var uri)
&& (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps))
return true;
normalized = "";
return false;
}
private static string NormalizeUrl(string? url) => (url ?? "").Trim().TrimEnd('/');
private sealed class SettingsFile
{
public string? BaseUrl { get; set; }
public string? ProtectedApiKey { get; set; }
}
}
@@ -65,4 +65,19 @@ public class NestStockBuilderTests
Assert.Throws<ArgumentNullException>(() => NestStockBuilder.FromTemplate(null, null));
Assert.Throws<ArgumentNullException>(() => NestStockBuilder.SinglePlate(null));
}
[Fact]
public void OptionQuantityAndIdWinOverTheDefaults()
{
var options = new[]
{
new PlateOption { Width = 48, Length = 96, Quantity = 2, Id = "ledger:1" },
new PlateOption { Width = 60, Length = 120 },
};
var stock = NestStockBuilder.FromTemplate(Template(), options, quantityPerOption: 5);
Assert.Equal("ledger:1", stock[0].Id);
Assert.Equal(2, stock[0].Quantity);
Assert.Equal("option-1", stock[1].Id);
Assert.Equal(5, stock[1].Quantity);
}
}
+6 -3
View File
@@ -5,7 +5,10 @@ using OpenNest.Geometry;
namespace OpenNest.Engine.Jobs;
/// <summary>Shared stock snapshots for whole-job front ends. Plate repeat count is not inventory.</summary>
/// <summary>
/// Shared stock snapshots for whole-job front ends. Plate repeat count is not inventory; an
/// option's own quantity and id win over <c>quantityPerOption</c> and its position.
/// </summary>
public static class NestStockBuilder
{
public static IReadOnlyList<NestPlateStock> FromTemplate(
@@ -25,9 +28,9 @@ public static class NestStockBuilder
ArgumentNullException.ThrowIfNull(option);
var size = new Size(option.Width, option.Length);
stock.Add(new NestPlateStock(
$"option-{i}",
option.Id ?? $"option-{i}",
size,
quantityPerOption,
option.Quantity ?? quantityPerOption,
template.PartSpacing,
template.EdgeSpacing,
template.Quadrant,
@@ -0,0 +1,128 @@
using OpenNest.Data.MaterialLedger;
using OpenNest.Geometry;
namespace OpenNest.Tests.Data;
public class LedgerStockMapperTests
{
[Fact]
public void BundlesAndSheetsAreOneRowEachAndDropsOfOneSizeShareARow()
{
var mapping = LedgerStockMapper.Map(new[]
{
Item("B-1", LedgerItemKinds.FullSheetBundle, 48, 96, quantity: 3),
Item("S-1", LedgerItemKinds.FullSheet, 48, 96, quantity: 1),
Item("D-2", LedgerItemKinds.Drop, 24, 36, location: "R2"),
Item("D-9", LedgerItemKinds.Drop, 30, 40, location: "R1"),
Item("D-1", LedgerItemKinds.Drop, 36.0004m, 24, location: "R1"),
Item("D-3", LedgerItemKinds.Drop, 24, 36, location: "R1"),
}, Units.Inches);
Assert.Equal(4, mapping.Rows.Count);
var bundle = mapping.Rows[0];
Assert.Equal("ledger:1", bundle.Id);
Assert.False(bundle.IsDrop);
Assert.Equal(3, bundle.Quantity);
Assert.Equal(new[] { "B-1", "B-1", "B-1" }, bundle.ItemCodes);
Assert.Equal(new Size(48, 96), bundle.Size);
Assert.Equal(1, mapping.Rows[1].Quantity);
// Width is the short side; drops matching after ML's 3-place rounding group, ordered by location then code.
var drops = mapping.Rows[2];
Assert.True(drops.IsDrop);
Assert.Equal(new Size(24, 36), drops.Size);
Assert.Equal(3, drops.Quantity);
Assert.Equal(new[] { "D-1", "D-3", "D-2" }, drops.ItemCodes);
Assert.Equal(new[] { "R1", "R2" }, drops.Locations);
Assert.Equal(new[] { "D-9" }, mapping.Rows[3].ItemCodes);
Assert.Equal(2, mapping.SheetRows);
Assert.Equal(4, mapping.Drops);
Assert.Equal("Ledger: 2 sheet sizes, 4 drops", mapping.Summary);
}
[Fact]
public void UnknownShapesAreSkippedAndCounted()
{
var mapping = LedgerStockMapper.Map(new[]
{
Item("U-1", LedgerItemKinds.Drop, 20, 30, shape: LedgerItemShapes.Unknown),
Item("U-2", LedgerItemKinds.Drop, 20, 30, shape: "SomeFutureShape"),
Item("S-1", LedgerItemKinds.FullSheet, 60, 120),
}, Units.Inches);
Assert.Equal("S-1", Assert.Single(Assert.Single(mapping.Rows).ItemCodes));
Assert.Equal(2, mapping.SkippedUnknownShape);
Assert.Equal("Ledger: 1 sheet size, 0 drops (2 skipped: 2 unknown shape)", mapping.Summary);
}
[Fact]
public void IrregularDropsAreMarkedAndKeptApartFromRectangularOnes()
{
var mapping = LedgerStockMapper.Map(new[]
{
Item("D-1", LedgerItemKinds.Drop, 20, 30),
Item("D-2", LedgerItemKinds.Drop, 20, 30, shape: LedgerItemShapes.IrregularConservativeRectangle),
}, Units.Inches);
Assert.Equal(2, mapping.Rows.Count);
Assert.False(mapping.Rows[0].IsIrregular);
Assert.True(mapping.Rows[1].IsIrregular);
}
[Fact]
public void ItemsNoPartFitsAreSkipped()
{
var mapping = LedgerStockMapper.Map(new[]
{
Item("D-1", LedgerItemKinds.Drop, 10, 50),
Item("D-2", LedgerItemKinds.Drop, 20, 25),
Item("D-3", LedgerItemKinds.Drop, 5, 5),
}, Units.Inches, new[] { new Size(22, 12), new Size(40, 30) });
Assert.Equal("D-2", Assert.Single(Assert.Single(mapping.Rows).ItemCodes));
Assert.Equal(2, mapping.SkippedTooSmall);
Assert.Contains("2 too small for any part", mapping.Summary);
}
[Fact]
public void HeldOutItemsAndUnknownKindsAreIgnored()
{
var mapping = LedgerStockMapper.Map(new[]
{
Item("S-1", LedgerItemKinds.FullSheet, 48, 96, quantity: 0),
Item("C-1", "Coil", 48, 96),
}, Units.Inches);
Assert.Empty(mapping.Rows);
}
[Fact]
public void MillimeterNestsGetMillimeterSizes()
{
var row = Assert.Single(LedgerStockMapper.Map(new[] { Item("S-1", LedgerItemKinds.FullSheet, 48, 96.5m) },
Units.Millimeters).Rows);
Assert.Equal(48 * 25.4, row.Size.Width, 9);
Assert.Equal(96.5 * 25.4, row.Size.Length, 9);
}
[Theory]
[InlineData(0.25, Units.Inches, 0.25)]
[InlineData(0.18751, Units.Inches, 0.1875)]
[InlineData(6.35, Units.Millimeters, 0.25)]
[InlineData(3, Units.Millimeters, 0.1181)]
public void ThicknessQueryIsInchesToFourPlaces(double thickness, Units units, double expected) =>
Assert.Equal(expected, LedgerStockMapper.ThicknessInches(thickness, units));
[Fact]
public void LedgerIdsAreRecognized()
{
Assert.True(LedgerStockMapper.IsLedgerId("ledger:3"));
Assert.False(LedgerStockMapper.IsLedgerId("option-0"));
Assert.False(LedgerStockMapper.IsLedgerId(null));
}
private static LedgerStockItem Item(string code, string kind, decimal width, decimal length, int quantity = 1,
string shape = LedgerItemShapes.Rectangular, string location = "R1") =>
new(code, 7, kind, width, length, quantity, shape, location, location, null, null, DateTime.UtcNow);
}
@@ -0,0 +1,166 @@
using System.Net;
using System.Net.Http;
using System.Text;
using OpenNest.Data.MaterialLedger;
namespace OpenNest.Tests.Data;
public class MaterialLedgerClientTests
{
private const string MappedBody = """
{
"mapped": true,
"specs": [{ "materialSpecId": 7, "displayName": "A36 1/4", "thicknessIn": 0.25, "gaugeLabel": null }],
"items": [{
"itemCode": "D-101", "materialSpecId": 7, "kind": "Drop", "widthIn": 24.5, "lengthIn": 36,
"quantity": 1, "shape": "Rectangular", "locationCode": "R1-A", "locationName": "Rack 1 A",
"parentLocationCode": "R1", "costPerUnit": null, "lastObservedAtUtc": "2026-10-20T14:00:00Z"
}]
}
""";
private static readonly MaterialLedgerSettings Configured = new() { BaseUrl = "http://ledger:5000/", ApiKey = "secret-key" };
[Fact]
public async Task NotConfiguredNeverSendsARequest()
{
var sent = 0;
var client = Client(_ => { sent++; return Json(MappedBody); }, new MaterialLedgerSettings());
Assert.IsType<LedgerStockResult.NotConfigured>(await client.GetStockAsync("Steel", "A36", 0.25, default));
Assert.Equal(0, sent);
}
[Fact]
public async Task MappedStockIsOkAndSendsTheKeyAndQuery()
{
HttpRequestMessage? seen = null;
var client = Client(request => { seen = request; return Json(MappedBody); });
var ok = Assert.IsType<LedgerStockResult.Ok>(await client.GetStockAsync("Stainless Steel", "304 #4", 0.18750, default));
Assert.Equal("secret-key", Assert.Single(seen!.Headers.GetValues(MaterialLedgerClient.ApiKeyHeader)));
Assert.Equal("/api/stock/opennest?material=Stainless%20Steel&grade=304%20%234&thicknessIn=0.1875",
seen.RequestUri!.PathAndQuery);
Assert.Equal("ledger", seen.RequestUri.Host);
var spec = Assert.Single(ok.Specs);
Assert.Equal(0.25m, spec.ThicknessIn);
var item = Assert.Single(ok.Items);
Assert.Equal("D-101", item.ItemCode);
Assert.Equal(LedgerItemKinds.Drop, item.Kind);
Assert.Equal(24.5m, item.WidthIn);
Assert.Null(item.CostPerUnit);
}
[Fact]
public async Task UnmappedMaterialIsDistinctFromEmptyStock()
{
var unmapped = Client(_ => Json("""{ "mapped": false, "specs": [], "items": [] }"""));
Assert.IsType<LedgerStockResult.Unmapped>(await unmapped.GetStockAsync("Unobtainium", "", 1, default));
var empty = Client(_ => Json("""{ "mapped": true, "specs": [], "items": [] }"""));
var ok = Assert.IsType<LedgerStockResult.Ok>(await empty.GetStockAsync("Steel", "A36", 0.25, default));
Assert.Empty(ok.Items);
}
[Theory]
[InlineData(HttpStatusCode.Unauthorized)]
[InlineData(HttpStatusCode.Forbidden)]
public async Task RejectedKeyIsUnauthorized(HttpStatusCode status)
{
var client = Client(_ => new HttpResponseMessage(status));
Assert.IsType<LedgerStockResult.Unauthorized>(await client.GetStockAsync("Steel", "A36", 0.25, default));
}
[Theory]
[InlineData(HttpStatusCode.NotFound, "no OpenNest stock route")]
[InlineData(HttpStatusCode.InternalServerError, "HTTP 500")]
public async Task OtherStatusesAreUnreachable(HttpStatusCode status, string reason)
{
var client = Client(_ => new HttpResponseMessage(status));
var result = Assert.IsType<LedgerStockResult.Unreachable>(await client.GetStockAsync("Steel", "A36", 0.25, default));
Assert.Contains(reason, result.Reason);
}
[Fact]
public async Task NetworkFailureAndGarbageAreUnreachable()
{
var down = Client(_ => throw new HttpRequestException("No such host is known."));
Assert.Contains("No such host", Assert.IsType<LedgerStockResult.Unreachable>(
await down.GetStockAsync("Steel", "A36", 0.25, default)).Reason);
var garbage = Client(_ => Json("<html>login</html>"));
Assert.IsType<LedgerStockResult.Unreachable>(await garbage.GetStockAsync("Steel", "A36", 0.25, default));
}
[Fact]
public async Task InvalidUrlIsUnreachableWithoutARequest()
{
var client = Client(_ => throw new InvalidOperationException("sent"),
new MaterialLedgerSettings { BaseUrl = "ftp://ledger" });
Assert.IsType<LedgerStockResult.Unreachable>(await client.GetStockAsync("Steel", "A36", 0.25, default));
}
[Fact]
public async Task SlowLedgerTimesOutAsUnreachable()
{
using var http = new HttpClient(new HangingHandler());
var client = new MaterialLedgerClient(http, Configured, TimeSpan.FromMilliseconds(50));
var result = Assert.IsType<LedgerStockResult.Unreachable>(await client.GetStockAsync("Steel", "A36", 0.25, default));
Assert.Contains("No answer", result.Reason);
Assert.Equal(TimeSpan.FromSeconds(5), MaterialLedgerClient.RequestTimeout);
}
[Fact]
public async Task CallerCancellationThrows()
{
using var http = new HttpClient(new HangingHandler());
var client = new MaterialLedgerClient(http, Configured);
using var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(50));
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => client.GetStockAsync("Steel", "A36", 0.25, cancel.Token));
}
[Fact]
public async Task UnknownKindAndShapeStillDeserialize()
{
var client = Client(_ => Json("""
{
"mapped": true, "specs": [],
"items": [{
"itemCode": "X-1", "materialSpecId": 7, "kind": "Coil", "widthIn": 48, "lengthIn": 96,
"quantity": 2, "shape": "Circular", "locationCode": "", "locationName": "",
"parentLocationCode": null, "costPerUnit": 12.5, "lastObservedAtUtc": "2026-10-20T14:00:00Z",
"someNewField": 1
}]
}
"""));
var ok = Assert.IsType<LedgerStockResult.Ok>(await client.GetStockAsync("Steel", "A36", 0.25, default));
var item = Assert.Single(ok.Items);
Assert.Equal("Coil", item.Kind);
Assert.Equal("Circular", item.Shape);
}
private static MaterialLedgerClient Client(Func<HttpRequestMessage, HttpResponseMessage> reply,
MaterialLedgerSettings? settings = null) =>
new(new HttpClient(new Handler(reply)), settings ?? Configured);
private static HttpResponseMessage Json(string body) =>
new(HttpStatusCode.OK) { Content = new StringContent(body, Encoding.UTF8, "application/json") };
private sealed class Handler(Func<HttpRequestMessage, HttpResponseMessage> reply) : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(reply(request));
}
}
private sealed class HangingHandler : HttpMessageHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
await Task.Delay(Timeout.Infinite, cancellationToken);
throw new InvalidOperationException("unreachable");
}
}
}
@@ -0,0 +1,65 @@
using OpenNest.Data.MaterialLedger;
namespace OpenNest.Tests.Data;
public class MaterialLedgerSettingsTests : IDisposable
{
private readonly string directory = Path.Combine(Path.GetTempPath(), "opennest-ledger-" + Guid.NewGuid().ToString("N"));
private string SettingsPath => Path.Combine(directory, "material-ledger.json");
private static string Protect(string plain) => "P:" + new string(plain.Reverse().ToArray());
private static string Unprotect(string text) =>
text.StartsWith("P:") ? new string(text[2..].Reverse().ToArray()) : throw new FormatException("not ours");
[Fact]
public void RoundTripStoresOnlyTheProtectedKey()
{
new MaterialLedgerSettings { BaseUrl = " http://ledger:5000/ ", ApiKey = "secret-key" }.Save(SettingsPath, Protect);
var json = File.ReadAllText(SettingsPath);
Assert.DoesNotContain("secret-key", json);
Assert.Contains("yek-terces", json);
var loaded = MaterialLedgerSettings.Load(SettingsPath, Unprotect);
Assert.Equal("http://ledger:5000", loaded.BaseUrl);
Assert.Equal("secret-key", loaded.ApiKey);
Assert.True(loaded.IsConfigured);
}
[Fact]
public void KeyThatCannotBeUnprotectedLoadsEmpty()
{
new MaterialLedgerSettings { BaseUrl = "http://ledger", ApiKey = "secret-key" }.Save(SettingsPath, _ => "foreign blob");
var loaded = MaterialLedgerSettings.Load(SettingsPath, Unprotect);
Assert.Equal("http://ledger", loaded.BaseUrl);
Assert.Equal("", loaded.ApiKey);
}
[Fact]
public void MissingOrCorruptFileIsNotConfigured()
{
Assert.False(MaterialLedgerSettings.Load(SettingsPath, Unprotect).IsConfigured);
Directory.CreateDirectory(directory);
File.WriteAllText(SettingsPath, "{ not json");
Assert.False(MaterialLedgerSettings.Load(SettingsPath, Unprotect).IsConfigured);
}
[Theory]
[InlineData("", true, "")]
[InlineData(" https://ledger/ ", true, "https://ledger")]
[InlineData("ledger", false, "")]
[InlineData("ftp://ledger", false, "")]
public void UrlsAreValidatedAndNormalized(string input, bool valid, string expected)
{
Assert.Equal(valid, MaterialLedgerSettings.TryNormalizeUrl(input, out var normalized));
Assert.Equal(expected, normalized);
}
public void Dispose()
{
if (Directory.Exists(directory))
Directory.Delete(directory, recursive: true);
}
}
@@ -0,0 +1,267 @@
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using OpenNest.Data.MaterialLedger;
using OpenNest.Engine.Jobs;
using OpenNest.Forms;
using OpenNest.Geometry;
namespace OpenNest.WinForms.Tests.Forms;
public class AutoNestFormLedgerStockTests
{
private static readonly LedgerStockResult Stock = new LedgerStockResult.Ok(Array.Empty<LedgerStockSpec>(), new[]
{
Item("B-1", LedgerItemKinds.FullSheetBundle, 48, 96, 3),
Item("D-1", LedgerItemKinds.Drop, 24, 36, 1),
Item("D-2", LedgerItemKinds.Drop, 24, 36, 1),
});
[Fact]
public void LedgerRowsJoinManualRowsAndAreNeverSaved() => RunSta(() =>
{
using var form = new LedgerTestForm();
form.LoadPlateOptions(Manual(0, 0), 0.5);
GetGrid(form);
form.ApplyLedgerStock(Stock);
Assert.True(form.TryGetPlateOptions(out var options, out var saved, out var error), error);
Assert.Equal(4, options.Count);
Assert.Equal(new string?[] { null, null, "ledger:1", "ledger:2" }, options.Select(o => o.Id));
Assert.Equal(new int?[] { null, null, 3, 2 }, options.Select(o => o.Quantity));
Assert.Equal(24, options[3].Width);
Assert.Equal(36, options[3].Length);
Assert.Equal(new[] { 60.0, 72.0 }, saved.Select(o => o.Width));
Assert.All(saved, o => Assert.Null(o.Quantity));
Assert.All(saved, o => Assert.Null(o.Id));
// A second load replaces the ledger rows and keeps the typed ones.
form.ApplyLedgerStock(new LedgerStockResult.Ok(Array.Empty<LedgerStockSpec>(),
new[] { Item("S-9", LedgerItemKinds.FullSheet, 60, 144, 1) }));
Assert.True(form.TryGetPlateOptions(out options, out saved, out error), error);
Assert.Equal(3, options.Count);
Assert.Equal("ledger:1", options[2].Id);
Assert.Equal(144, options[2].Length);
Assert.Equal(2, saved.Count);
Assert.Equal("Ledger: 1 sheet size, 0 drops", Label(form).Text);
});
[Fact]
public void QuantitiesReachEngineStock() => RunSta(() =>
{
using var form = new LedgerTestForm();
form.LoadPlateOptions(Manual(0, 0), 0.5);
var grid = GetGrid(form);
form.ApplyLedgerStock(Stock);
var rows = Assert.IsAssignableFrom<IList>(grid.DataSource);
SetValue(rows[0]!, "Quantity", 4);
SetValue(rows[3]!, "Quantity", 1);
SetValue(rows[1]!, "Use", false);
Assert.True(form.TryGetPlateOptions(out var options, out var saved, out var error), error);
var stock = NestStockBuilder.FromTemplate(new Plate(new Size(48, 96)), options);
Assert.Equal(new int?[] { 4, 3, 1 }, stock.Select(s => s.Quantity));
Assert.Equal(new[] { "option-0", "ledger:1", "ledger:2" }, stock.Select(s => s.Id));
Assert.Equal(2, saved.Count);
});
[Fact]
public void BlankQuantityCellMeansUnlimited() => RunSta(() =>
{
using var form = new LedgerTestForm();
form.LoadPlateOptions(new List<PlateOption> { new() { Width = 48, Length = 96, Quantity = 2 } }, 0.5);
var grid = GetGrid(form);
((TabControl)form.Controls.Find("tabControl", true).Single()).SelectedIndex = 1;
form.Show();
grid.Focus();
grid.CurrentCell = grid.Rows[0].Cells[QuantityColumn(grid)];
Assert.True(grid.BeginEdit(false));
grid.EditingControl.Text = "";
Assert.True(form.TryGetPlateOptions(out var options, out var error), error);
Assert.Null(Assert.Single(options).Quantity);
});
[Theory]
[InlineData(0, false)]
[InlineData(4, false)]
[InlineData(2, true)]
public void LedgerQuantityCannotExceedTheFreeCount(int quantity, bool valid) => RunSta(() =>
{
using var form = new LedgerTestForm();
var grid = GetGrid(form);
Assert.IsAssignableFrom<IList>(grid.DataSource).Clear();
form.ApplyLedgerStock(Stock);
SetValue(Assert.IsAssignableFrom<IList>(grid.DataSource)[0]!, "Quantity", quantity);
Assert.Equal(valid, form.TryGetPlateOptions(out var options, out var error));
if (valid)
Assert.Equal(2, options[0].Quantity);
else
Assert.Contains("3 free", error);
});
[Fact]
public void CostsAreIgnoredWhileLedgerStockIsOffered() => RunSta(() =>
{
using var form = new LedgerTestForm();
form.LoadPlateOptions(Manual(25, 40), 0.5);
var grid = GetGrid(form);
form.ApplyLedgerStock(Stock);
Assert.True(form.TryGetPlateOptions(out var options, out var saved, out var error), error);
Assert.All(options, o => Assert.Equal(0, o.Cost));
Assert.Equal(new[] { 25.0, 40.0 }, saved.Select(o => o.Cost));
Assert.NotNull(NestStockBuilder.FromTemplate(new Plate(new Size(48, 96)), options));
Assert.Contains("costs ignored", Label(form).Text);
// Unticking every ledger row restores the typed costs for the run.
var rows = Assert.IsAssignableFrom<IList>(grid.DataSource);
SetValue(rows[2]!, "Use", false);
SetValue(rows[3]!, "Use", false);
Assert.True(form.TryGetPlateOptions(out options, out error), error);
Assert.Equal(new[] { 25.0, 40.0 }, options.Select(o => o.Cost));
});
[Fact]
public void FailuresAreReportedAndUnmappedClearsLedgerRows() => RunSta(() =>
{
using var form = new LedgerTestForm();
form.LoadPlateOptions(Manual(0, 0), 0.5);
GetGrid(form);
form.ApplyLedgerStock(Stock);
form.ApplyLedgerStock(new LedgerStockResult.Unreachable("No answer within 5 s."));
Assert.Contains("unreachable", Label(form).Text);
Assert.Equal(4, form.GetPlateOptions().Count);
form.ApplyLedgerStock(new LedgerStockResult.Unauthorized());
Assert.Contains("API key", Label(form).Text);
form.ApplyLedgerStock(new LedgerStockResult.Unmapped());
Assert.Equal("MaterialLedger has no mapping for Steel A36 0.25 in.", Label(form).Text);
Assert.Equal(2, form.GetPlateOptions().Count);
});
[Fact]
public void LoadAsksForTheNestMaterialInInches() => RunSta(() =>
{
var nest = LedgerNest();
nest.Units = Units.Millimeters;
nest.Thickness = 6.35;
using var form = new LedgerTestForm(nest) { Reply = Stock };
GetGrid(form);
Assert.True(form.LoadLedgerStockAsync().IsCompleted);
Assert.Equal(("Steel", "A36", 0.25), form.Requests.Single());
Assert.Equal(25.4 * 48, form.GetPlateOptions().First(o => o.Id == "ledger:1").Width, 9);
});
[Fact]
public void ClosingTheFormCancelsAPendingLoad() => RunSta(() =>
{
using var form = new LedgerTestForm { Pending = new TaskCompletionSource<LedgerStockResult>() };
GetGrid(form);
var load = form.LoadLedgerStockAsync();
Assert.False(load.IsCompleted);
Assert.False(Button(form).Enabled);
form.Show();
form.Close();
Assert.True(form.LastToken.IsCancellationRequested);
});
[Fact]
public void LoadButtonNeedsALedgerAndAMaterialAndThickness() => RunSta(() =>
{
using var form = new LedgerTestForm();
Assert.True(Button(form).Enabled);
form.Configured = false;
form.UpdateLedgerButton();
Assert.False(Button(form).Enabled);
using var noMaterial = new LedgerTestForm(new Nest { Thickness = 0.25 });
Assert.False(Button(noMaterial).Enabled);
using var noThickness = new LedgerTestForm(new Nest { Material = new Material("Steel", "A36") });
Assert.False(Button(noThickness).Enabled);
});
[Fact]
public void TooltipNamesItemsAndLocations()
{
var row = LedgerStockMapper.Map(new[]
{
Item("D-1", LedgerItemKinds.Drop, 24, 36, 1, "R1"),
Item("D-2", LedgerItemKinds.Drop, 24, 36, 1, "R2"),
}, Units.Inches).Rows.Single();
var tooltip = AutoNestForm.LedgerTooltip(row);
Assert.Contains("D-1, D-2", tooltip);
Assert.Contains("R1, R2", tooltip);
}
private sealed class LedgerTestForm : AutoNestForm
{
public LedgerTestForm() : this(LedgerNest()) { }
public LedgerTestForm(Nest nest) : base(nest) { }
public bool Configured { get; set; } = true;
public LedgerStockResult Reply { get; set; } = Stock;
public TaskCompletionSource<LedgerStockResult>? Pending { get; set; }
public List<(string, string, double)> Requests { get; } = new();
public CancellationToken LastToken { get; private set; }
internal override bool LedgerConfigured => Configured;
internal override Task<LedgerStockResult> FetchLedgerStockAsync(string material, string grade,
double thicknessIn, CancellationToken cancellationToken)
{
Requests.Add((material, grade, thicknessIn));
LastToken = cancellationToken;
return Pending?.Task ?? Task.FromResult(Reply);
}
}
private static Nest LedgerNest() => new() { Material = new Material("Steel", "A36"), Thickness = 0.25 };
private static List<PlateOption> Manual(double firstCost, double secondCost) => new()
{
new() { Width = 60, Length = 120, Cost = firstCost },
new() { Width = 72, Length = 144, Cost = secondCost },
};
private static LedgerStockItem Item(string code, string kind, decimal width, decimal length, int quantity,
string location = "R1") =>
new(code, 7, kind, width, length, quantity, LedgerItemShapes.Rectangular, location, location, null, null,
DateTime.UtcNow);
private static DataGridView GetGrid(AutoNestForm form)
{
form.BindingContext = new BindingContext();
var grid = Assert.IsType<DataGridView>(form.Controls.Find("plateGrid", true).Single());
grid.CreateControl();
return grid;
}
private static int QuantityColumn(DataGridView grid) =>
grid.Columns.Cast<DataGridViewColumn>().Single(c => c.DataPropertyName == "Quantity").Index;
private static Label Label(AutoNestForm form) =>
Assert.IsType<Label>(form.Controls.Find("ledgerSummaryLabel", true).Single());
private static Button Button(AutoNestForm form) =>
Assert.IsType<Button>(form.Controls.Find("ledgerButton", true).Single());
private static void SetValue(object row, string property, object value) =>
TypeDescriptor.GetProperties(row)[property]!.SetValue(row, value);
private static void RunSta(Action action) =>
StaTestThread.Run(action, TimeSpan.FromSeconds(15), "The STA test did not complete.");
}
@@ -25,7 +25,7 @@ public class AutoNestFormStockOptionsTests
((TabControl)form.Controls.Find("tabControl", true).Single()).SelectedIndex = 1;
form.Show();
grid.Focus();
grid.CurrentCell = grid.Rows[0].Cells[1];
grid.CurrentCell = grid.Rows[0].Cells[Column(grid, "Cost")];
Assert.True(grid.BeginEdit(false));
grid.EditingControl.Text = text;
Assert.Equal(valid, form.TryGetPlateOptions(out var options, out var error));
@@ -239,7 +239,7 @@ public class AutoNestFormStockOptionsTests
form.LoadPlateOptions(new List<PlateOption> { new() { Width = 48, Length = 96 } }, 0.5);
var grid = GetGrid(form);
form.Show();
grid.CurrentCell = grid.Rows[0].Cells[0];
grid.CurrentCell = grid.Rows[0].Cells[Column(grid, "Size")];
Assert.True(grid.BeginEdit(false));
grid.EditingControl.Text = "48 x";
@@ -309,6 +309,9 @@ public class AutoNestFormStockOptionsTests
return grid;
}
private static int Column(DataGridView grid, string property) =>
grid.Columns.Cast<DataGridViewColumn>().Single(c => c.DataPropertyName == property).Index;
private static void AssertNewRow(DataGridView grid)
{
Assert.True(grid.AllowUserToAddRows);
@@ -0,0 +1,27 @@
using System.Windows.Forms;
using OpenNest.Data.MaterialLedger;
using OpenNest.Forms;
namespace OpenNest.WinForms.Tests.Forms;
public class MaterialLedgerStoreTests
{
[Fact]
public void ApiKeyRoundTripsThroughDpapiWithoutPlainText()
{
var protectedKey = MaterialLedgerStore.Protect("secret-key");
Assert.DoesNotContain("secret-key", protectedKey);
Assert.Equal("secret-key", MaterialLedgerStore.Unprotect(protectedKey));
}
[Fact]
public void TestButtonTreatsMappedFalseAsConnected()
{
Assert.Equal(MessageBoxIcon.Information,
OptionsForm.DescribeLedgerTest(new LedgerStockResult.Unmapped()).Icon);
Assert.Contains("rejected the API key",
OptionsForm.DescribeLedgerTest(new LedgerStockResult.Unauthorized()).Text);
Assert.Contains("timed out",
OptionsForm.DescribeLedgerTest(new LedgerStockResult.Unreachable("timed out")).Text);
}
}
+37 -8
View File
@@ -29,6 +29,10 @@ namespace OpenNest.Forms
this.plateOptimizerGroup = new System.Windows.Forms.GroupBox();
this.optimizePlateSizeBox = new System.Windows.Forms.CheckBox();
this.plateGrid = new System.Windows.Forms.DataGridView();
this.ledgerButton = new System.Windows.Forms.Button();
this.ledgerSummaryLabel = new System.Windows.Forms.Label();
this.components = new System.ComponentModel.Container();
this.ledgerToolTip = new System.Windows.Forms.ToolTip(this.components);
this.salvageRateLabel = new System.Windows.Forms.Label();
this.salvageRateBox = new System.Windows.Forms.TextBox();
this.salvageRatePercentLabel = new System.Windows.Forms.Label();
@@ -121,7 +125,7 @@ namespace OpenNest.Forms
// minRemnantLabel
//
this.minRemnantLabel.AutoSize = true;
this.minRemnantLabel.Location = new System.Drawing.Point(10, 193);
this.minRemnantLabel.Location = new System.Drawing.Point(10, 303);
this.minRemnantLabel.Name = "minRemnantLabel";
this.minRemnantLabel.Size = new System.Drawing.Size(117, 16);
this.minRemnantLabel.TabIndex = 3;
@@ -129,7 +133,7 @@ namespace OpenNest.Forms
//
// minRemnantBox
//
this.minRemnantBox.Location = new System.Drawing.Point(155, 190);
this.minRemnantBox.Location = new System.Drawing.Point(155, 300);
this.minRemnantBox.Name = "minRemnantBox";
this.minRemnantBox.Size = new System.Drawing.Size(60, 22);
this.minRemnantBox.TabIndex = 4;
@@ -141,13 +145,15 @@ namespace OpenNest.Forms
this.plateOptimizerGroup.Controls.Add(this.minRemnantLabel);
this.plateOptimizerGroup.Controls.Add(this.minRemnantBox);
this.plateOptimizerGroup.Controls.Add(this.optimizePlateSizeBox);
this.plateOptimizerGroup.Controls.Add(this.ledgerButton);
this.plateOptimizerGroup.Controls.Add(this.plateGrid);
this.plateOptimizerGroup.Controls.Add(this.ledgerSummaryLabel);
this.plateOptimizerGroup.Controls.Add(this.salvageRateLabel);
this.plateOptimizerGroup.Controls.Add(this.salvageRateBox);
this.plateOptimizerGroup.Controls.Add(this.salvageRatePercentLabel);
this.plateOptimizerGroup.Location = new System.Drawing.Point(10, 52);
this.plateOptimizerGroup.Name = "plateOptimizerGroup";
this.plateOptimizerGroup.Size = new System.Drawing.Size(528, 224);
this.plateOptimizerGroup.Size = new System.Drawing.Size(528, 334);
this.plateOptimizerGroup.TabIndex = 4;
this.plateOptimizerGroup.TabStop = false;
this.plateOptimizerGroup.Text = " Stock Options";
@@ -165,17 +171,37 @@ namespace OpenNest.Forms
// plateGrid
//
this.plateGrid.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)));
this.plateGrid.Location = new System.Drawing.Point(10, 22);
this.plateGrid.Location = new System.Drawing.Point(10, 54);
this.plateGrid.Name = "plateGrid";
this.plateGrid.RowHeadersVisible = true;
this.plateGrid.AutoGenerateColumns = false;
this.plateGrid.Size = new System.Drawing.Size(508, 130);
this.plateGrid.Size = new System.Drawing.Size(508, 190);
this.plateGrid.TabIndex = 1;
//
// ledgerButton
//
this.ledgerButton.Location = new System.Drawing.Point(10, 22);
this.ledgerButton.Name = "ledgerButton";
this.ledgerButton.Size = new System.Drawing.Size(150, 26);
this.ledgerButton.TabIndex = 5;
this.ledgerButton.Text = "Load from ledger";
this.ledgerButton.UseVisualStyleBackColor = true;
this.ledgerButton.Click += new System.EventHandler(this.ledgerButton_Click);
//
// ledgerSummaryLabel
//
this.ledgerSummaryLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)));
this.ledgerSummaryLabel.AutoEllipsis = true;
this.ledgerSummaryLabel.ForeColor = System.Drawing.SystemColors.GrayText;
this.ledgerSummaryLabel.Location = new System.Drawing.Point(10, 248);
this.ledgerSummaryLabel.Name = "ledgerSummaryLabel";
this.ledgerSummaryLabel.Size = new System.Drawing.Size(508, 18);
this.ledgerSummaryLabel.TabIndex = 6;
//
// salvageRateLabel
//
this.salvageRateLabel.AutoSize = true;
this.salvageRateLabel.Location = new System.Drawing.Point(10, 162);
this.salvageRateLabel.Location = new System.Drawing.Point(10, 272);
this.salvageRateLabel.Name = "salvageRateLabel";
this.salvageRateLabel.Size = new System.Drawing.Size(96, 16);
this.salvageRateLabel.TabIndex = 2;
@@ -183,7 +209,7 @@ namespace OpenNest.Forms
//
// salvageRateBox
//
this.salvageRateBox.Location = new System.Drawing.Point(108, 159);
this.salvageRateBox.Location = new System.Drawing.Point(108, 269);
this.salvageRateBox.Name = "salvageRateBox";
this.salvageRateBox.Size = new System.Drawing.Size(50, 22);
this.salvageRateBox.TabIndex = 3;
@@ -192,7 +218,7 @@ namespace OpenNest.Forms
// salvageRatePercentLabel
//
this.salvageRatePercentLabel.AutoSize = true;
this.salvageRatePercentLabel.Location = new System.Drawing.Point(160, 162);
this.salvageRatePercentLabel.Location = new System.Drawing.Point(160, 272);
this.salvageRatePercentLabel.Name = "salvageRatePercentLabel";
this.salvageRatePercentLabel.Size = new System.Drawing.Size(21, 16);
this.salvageRatePercentLabel.TabIndex = 4;
@@ -274,6 +300,9 @@ namespace OpenNest.Forms
private System.Windows.Forms.GroupBox plateOptimizerGroup;
private System.Windows.Forms.CheckBox optimizePlateSizeBox;
private System.Windows.Forms.DataGridView plateGrid;
private System.Windows.Forms.Button ledgerButton;
private System.Windows.Forms.Label ledgerSummaryLabel;
private System.Windows.Forms.ToolTip ledgerToolTip;
private System.Windows.Forms.Label salvageRateLabel;
private System.Windows.Forms.TextBox salvageRateBox;
private System.Windows.Forms.Label salvageRatePercentLabel;
+352 -3
View File
@@ -3,9 +3,13 @@ using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenNest.Controls;
using OpenNest.Data.MaterialLedger;
using OpenNest.Engine;
using OpenNest.Geometry;
using OpenNest.Help;
namespace OpenNest.Forms
@@ -18,8 +22,14 @@ namespace OpenNest.Forms
TimeSpan.FromMilliseconds(250)
);
private readonly Nest nest;
private CancellationTokenSource ledgerCancellation;
private bool loadingLedger;
private string ledgerSummary = "";
public AutoNestForm(Nest nest)
{
this.nest = nest;
InitializeComponent();
GridStyle.Apply(partsGrid);
GridStyle.Apply(plateGrid);
@@ -30,6 +40,7 @@ namespace OpenNest.Forms
LoadDrawings(nest);
LoadDefaultPlateOptions();
SetPlateOptimizerVisible(false);
UpdateLedgerButton();
HelpTopics.Attach(this, HelpTopics.AutoNest);
partsGrid.DataError += PartsGrid_DataError;
@@ -146,6 +157,16 @@ namespace OpenNest.Forms
private void SetupPlateGrid()
{
plateGrid.Columns.Add(
new DataGridViewCheckBoxColumn
{
DataPropertyName = "Use",
HeaderText = "Use",
ToolTipText = "Untick to leave the row out of this Auto Nest.",
Width = 40,
AutoSizeMode = DataGridViewAutoSizeColumnMode.None,
}
);
plateGrid.Columns.Add(
new DataGridViewTextBoxColumn
{
@@ -155,6 +176,18 @@ namespace OpenNest.Forms
AutoSizeMode = DataGridViewAutoSizeColumnMode.None,
}
);
var quantityColumn = new DataGridViewTextBoxColumn
{
DataPropertyName = "Quantity",
HeaderText = "Qty",
ToolTipText = "Sheets on hand. Blank offers the size without limit.",
Width = 55,
AutoSizeMode = DataGridViewAutoSizeColumnMode.None,
};
// A blank cell binds as null (unlimited), not DBNull.
quantityColumn.DefaultCellStyle.DataSourceNullValue = null;
quantityColumn.DefaultCellStyle.NullValue = "";
plateGrid.Columns.Add(quantityColumn);
plateGrid.Columns.Add(
new DataGridViewTextBoxColumn
{
@@ -166,8 +199,29 @@ namespace OpenNest.Forms
}
);
plateGrid.Columns.Add(
new DataGridViewTextBoxColumn
{
DataPropertyName = "Source",
HeaderText = "Source",
ReadOnly = true,
Width = 90,
AutoSizeMode = DataGridViewAutoSizeColumnMode.None,
}
);
plateGrid.CellValidating += PlateGrid_CellValidating;
plateGrid.DataError += PlateGrid_DataError;
plateGrid.CellBeginEdit += PlateGrid_CellBeginEdit;
plateGrid.CellFormatting += PlateGrid_CellFormatting;
plateGrid.CellToolTipTextNeeded += PlateGrid_CellToolTipTextNeeded;
plateGrid.CellValueChanged += (s, e) => UpdateLedgerSummary();
// Commit a Use tick at once so the summary line follows it.
plateGrid.CurrentCellDirtyStateChanged += (s, e) =>
{
if (plateGrid.IsCurrentCellDirty && plateGrid.CurrentCell is DataGridViewCheckBoxCell)
plateGrid.CommitEdit(DataGridViewDataErrorContexts.Commit);
};
}
private void LoadDrawings(Nest nest)
@@ -220,9 +274,20 @@ namespace OpenNest.Forms
return options;
}
public bool TryGetPlateOptions(out List<PlateOption> options, out string error)
public bool TryGetPlateOptions(out List<PlateOption> options, out string error) =>
TryGetPlateOptions(out options, out _, out error);
/// <summary>
/// <paramref name="options"/> is the stock for this run: ticked rows with their
/// quantities, ledger rows under their <c>ledger:{n}</c> ids, and no costs while ledger
/// stock is offered. <paramref name="savedOptions"/> is what the nest keeps: every
/// hand-typed row with its typed cost, never ledger rows or quantities.
/// </summary>
public bool TryGetPlateOptions(out List<PlateOption> options, out List<PlateOption> savedOptions,
out string error)
{
options = new List<PlateOption>();
savedOptions = new List<PlateOption>();
error = null;
// CellValidating cancels an unparsable size and leaves the cell in edit mode;
@@ -253,6 +318,15 @@ namespace OpenNest.Forms
return false;
}
if (plateGrid.IsCurrentCellInEditMode && plateGrid.CurrentCell != null
&& plateGrid.Columns[plateGrid.CurrentCell.ColumnIndex].DataPropertyName == "Quantity"
&& plateGrid.EditingControl != null
&& !ValidQuantity(plateGrid.EditingControl.Text, ItemAt(plateGrid.CurrentCell.RowIndex)))
{
error = QuantityError(plateGrid.CurrentCell.RowIndex);
return false;
}
bool committed;
try
{
@@ -273,10 +347,35 @@ namespace OpenNest.Forms
if (gridItems == null)
return true;
// Ledger costs are per lot unit (a drop carries its source sheet's), so a run with
// ledger stock scores by area; hand-typed costs stay saved for later runs.
var ledgerOffered = gridItems.Any(i => i.LedgerRow != null && i.Use);
var validated = new List<PlateOption>();
var saved = new List<PlateOption>();
for (var index = 0; index < gridItems.Count; index++)
{
var item = gridItems[index];
if (item.LedgerRow != null)
{
if (!ValidQuantity(item.Quantity, item))
{
error = QuantityError(index);
if (index < plateGrid.Rows.Count)
plateGrid.Rows[index].ErrorText = error;
return false;
}
if (index < plateGrid.Rows.Count)
plateGrid.Rows[index].ErrorText = "";
if (item.Use)
validated.Add(new PlateOption
{
Width = item.LedgerRow.Size.Width,
Length = item.LedgerRow.Size.Length,
Quantity = item.Quantity ?? item.LedgerRow.Quantity,
Id = item.LedgerRow.Id,
});
continue;
}
if (string.IsNullOrWhiteSpace(item.Size))
continue;
if (!TryParseSize(item.Size, out var width, out var length))
@@ -288,23 +387,46 @@ namespace OpenNest.Forms
}
if (!double.IsFinite(item.Cost) || item.Cost < 0
|| validated.Count > 0 && (validated[0].Cost == 0) != (item.Cost == 0))
|| saved.Count > 0 && (saved[0].Cost == 0) != (item.Cost == 0))
{
error = $"Invalid stock cost in row {index + 1}. Use finite positive costs on every active row, or zero on every row.";
if (index < plateGrid.Rows.Count)
plateGrid.Rows[index].ErrorText = error;
return false;
}
if (!ValidQuantity(item.Quantity, item))
{
error = QuantityError(index);
if (index < plateGrid.Rows.Count)
plateGrid.Rows[index].ErrorText = error;
return false;
}
if (index < plateGrid.Rows.Count)
plateGrid.Rows[index].ErrorText = "";
validated.Add(new PlateOption { Width = width, Length = length, Cost = item.Cost });
saved.Add(new PlateOption { Width = width, Length = length, Cost = item.Cost });
if (item.Use)
validated.Add(new PlateOption
{
Width = width,
Length = length,
Cost = ledgerOffered ? 0 : item.Cost,
Quantity = item.Quantity,
});
}
// Publish only a completely validated collection, never a valid prefix.
options = validated;
savedOptions = saved;
return true;
}
protected override void OnFormClosed(FormClosedEventArgs e)
{
// Closing the dialog abandons a ledger request still in flight.
ledgerCancellation?.Cancel();
base.OnFormClosed(e);
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (DialogResult == DialogResult.OK && OptimizePlateSize
@@ -341,6 +463,7 @@ namespace OpenNest.Forms
{
Size = FormatSize(o.Width, o.Length),
Cost = o.Cost,
Quantity = o.Quantity,
})
.ToList();
plateGrid.DataSource = new BindingList<PlateOptionItem>(items);
@@ -375,6 +498,8 @@ namespace OpenNest.Forms
private void SetPlateOptimizerVisible(bool visible)
{
plateGrid.Visible = visible;
ledgerButton.Visible = visible;
ledgerSummaryLabel.Visible = visible;
salvageRateLabel.Visible = visible;
salvageRateBox.Visible = visible;
salvageRatePercentLabel.Visible = visible;
@@ -404,11 +529,223 @@ namespace OpenNest.Forms
UpdateSummary();
}
/// <summary>True when the ledger is set up on this PC; the form's tests replace it.</summary>
internal virtual bool LedgerConfigured => MaterialLedgerStore.Settings.IsConfigured;
/// <summary>Reads the nest material's free stock; the form's tests replace it.</summary>
internal virtual Task<LedgerStockResult> FetchLedgerStockAsync(string material, string grade,
double thicknessIn, CancellationToken cancellationToken) =>
MaterialLedgerStore.CreateClient().GetStockAsync(material, grade, thicknessIn, cancellationToken);
private string MaterialName => nest?.Material?.Name?.Trim() ?? "";
internal void UpdateLedgerButton()
{
string reason = null;
if (!LedgerConfigured)
reason = "Set the MaterialLedger URL and API key under Tools > Options first.";
else if (MaterialName.Length == 0 || !(nest.Thickness > 0))
reason = "Give the nest a material and a thickness first.";
ledgerButton.Enabled = reason == null && !loadingLedger;
ledgerToolTip.SetToolTip(ledgerButton, reason
?? "Replace the ledger rows with the free sheets and drops of this nest's material. "
+ "Stock is a snapshot, not a reservation.");
}
private async void ledgerButton_Click(object sender, EventArgs e) => await LoadLedgerStockAsync();
/// <summary>Requests the nest material's stock and applies the answer, unless the form closed first.</summary>
internal async Task LoadLedgerStockAsync()
{
ledgerCancellation?.Cancel();
ledgerCancellation = new CancellationTokenSource();
var token = ledgerCancellation.Token;
loadingLedger = true;
UpdateLedgerButton();
ledgerSummaryLabel.Text = "Loading stock from MaterialLedger...";
try
{
var result = await FetchLedgerStockAsync(MaterialName, nest.Material?.Grade?.Trim() ?? "",
LedgerStockMapper.ThicknessInches(nest.Thickness, nest.Units), token);
if (token.IsCancellationRequested || IsDisposed)
return;
ApplyLedgerStock(result);
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
// The form closed or a newer load started.
}
finally
{
if (!IsDisposed && !token.IsCancellationRequested)
{
loadingLedger = false;
UpdateLedgerButton();
}
}
}
/// <summary>
/// Replaces the ledger rows with <paramref name="result"/>'s stock (an unmapped material
/// clears them; a failed request keeps them) and reports the outcome under the grid.
/// </summary>
internal void ApplyLedgerStock(LedgerStockResult result)
{
switch (result)
{
case LedgerStockResult.Ok ok:
var mapping = LedgerStockMapper.Map(ok.Items, nest.Units, PartEnvelopes());
ReplaceLedgerRows(mapping.Rows);
ledgerSummary = mapping.Rows.Count == 0 && mapping.SkippedUnknownShape + mapping.SkippedTooSmall == 0
? $"Ledger: no free stock of {DescribeMaterial()}."
: mapping.Summary;
break;
case LedgerStockResult.Unmapped:
ReplaceLedgerRows(Array.Empty<LedgerStockRow>());
ledgerSummary = $"MaterialLedger has no mapping for {DescribeMaterial()}.";
break;
case LedgerStockResult.Unauthorized:
ledgerSummary = "MaterialLedger rejected the API key (Tools > Options).";
break;
case LedgerStockResult.Unreachable unreachable:
ledgerSummary = $"MaterialLedger unreachable: {unreachable.Reason}";
break;
default:
ledgerSummary = "Set the MaterialLedger URL under Tools > Options.";
break;
}
UpdateLedgerSummary();
}
private string DescribeMaterial()
{
var grade = nest.Material?.Grade?.Trim();
var unit = nest.Units == Units.Millimeters ? "mm" : "in";
return FormattableString.Invariant(
$"{MaterialName}{(string.IsNullOrEmpty(grade) ? "" : " " + grade)} {nest.Thickness:G} {unit}");
}
private List<Size> PartEnvelopes()
{
var envelopes = new List<Size>();
if (partsGrid.DataSource is not List<DataGridViewItem> gridItems)
return envelopes;
foreach (var item in gridItems.Where(i => i.Quantity > 0 && i.RefDrawing?.Program != null))
{
var box = item.RefDrawing.Program.BoundingBox();
if (double.IsFinite(box.Width) && double.IsFinite(box.Length) && box.Width > 0 && box.Length > 0)
envelopes.Add(new Size(box.Width, box.Length));
}
return envelopes;
}
private void ReplaceLedgerRows(IReadOnlyList<LedgerStockRow> rows)
{
plateGrid.EndEdit();
if (plateGrid.DataSource is not BindingList<PlateOptionItem> items)
{
items = new BindingList<PlateOptionItem>();
plateGrid.DataSource = items;
}
for (var i = items.Count - 1; i >= 0; i--)
{
if (items[i].LedgerRow != null)
items.RemoveAt(i);
}
foreach (var row in rows)
{
items.Add(new PlateOptionItem
{
Size = FormatSize(System.Math.Round(row.Size.Width, 3), System.Math.Round(row.Size.Length, 3)),
Quantity = row.Quantity,
LedgerRow = row,
});
}
}
private void UpdateLedgerSummary()
{
var text = ledgerSummary;
if (plateGrid.DataSource is BindingList<PlateOptionItem> items
&& items.Any(i => i.LedgerRow != null && i.Use)
&& items.Any(i => i.LedgerRow == null && i.Use && i.Cost > 0))
text = (text.Length > 0 ? text + "; " : "") + "costs ignored while ledger stock is loaded";
ledgerSummaryLabel.Text = text;
}
private PlateOptionItem ItemAt(int rowIndex) =>
plateGrid.DataSource is BindingList<PlateOptionItem> items && rowIndex >= 0 && rowIndex < items.Count
? items[rowIndex]
: null;
private string QuantityError(int rowIndex)
{
var ledger = ItemAt(rowIndex)?.LedgerRow;
return ledger == null
? $"Invalid stock quantity in row {rowIndex + 1}. Enter a whole number of sheets, or leave it blank for no limit."
: $"Invalid stock quantity in row {rowIndex + 1}. The ledger has {ledger.Quantity} free; enter 1 to {ledger.Quantity}, or untick the row.";
}
private static bool ValidQuantity(int? quantity, PlateOptionItem item) =>
quantity == null || quantity >= 1 && (item?.LedgerRow == null || quantity <= item.LedgerRow.Quantity);
private static bool ValidQuantity(string text, PlateOptionItem item)
{
if (string.IsNullOrWhiteSpace(text))
return true;
return int.TryParse(text.Trim(), System.Globalization.NumberStyles.None,
System.Globalization.CultureInfo.CurrentCulture, out var quantity)
&& ValidQuantity(quantity, item);
}
// Ledger rows keep the ledger's size and carry no cost; only Use and Qty are editable.
private void PlateGrid_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
var property = plateGrid.Columns[e.ColumnIndex].DataPropertyName;
if (ItemAt(e.RowIndex)?.LedgerRow != null && property is "Size" or "Cost")
e.Cancel = true;
}
private void PlateGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
var property = plateGrid.Columns[e.ColumnIndex].DataPropertyName;
if (ItemAt(e.RowIndex)?.LedgerRow != null && property is "Size" or "Cost" or "Source")
e.CellStyle.ForeColor = System.Drawing.SystemColors.GrayText;
}
private void PlateGrid_CellToolTipTextNeeded(object sender, DataGridViewCellToolTipTextNeededEventArgs e)
{
var ledger = ItemAt(e.RowIndex)?.LedgerRow;
if (ledger != null)
e.ToolTipText = LedgerTooltip(ledger);
}
internal static string LedgerTooltip(LedgerStockRow row)
{
const int Shown = 12;
var codes = row.ItemCodes.Distinct(StringComparer.Ordinal).ToList();
var codeText = string.Join(", ", codes.Take(Shown)) + (codes.Count > Shown ? $", +{codes.Count - Shown} more" : "");
var text = $"Items: {codeText}";
if (row.Locations.Count > 0)
text += $"\nLocations: {string.Join(", ", row.Locations.Take(Shown))}"
+ (row.Locations.Count > Shown ? $", +{row.Locations.Count - Shown} more" : "");
if (row.IsIrregular)
text += "\nIrregular: offered at its conservative usable rectangle.";
return text;
}
private static bool ValidCost(string text) =>
double.TryParse(text, out var cost) && double.IsFinite(cost) && cost >= 0;
private void PlateGrid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (plateGrid.Columns[e.ColumnIndex].DataPropertyName == "Quantity")
{
e.Cancel = !plateGrid.Rows[e.RowIndex].IsNewRow
&& !ValidQuantity(e.FormattedValue?.ToString(), ItemAt(e.RowIndex));
plateGrid.Rows[e.RowIndex].ErrorText = e.Cancel ? QuantityError(e.RowIndex) : "";
return;
}
if (plateGrid.Columns[e.ColumnIndex].DataPropertyName == "Cost")
{
e.Cancel = !plateGrid.Rows[e.RowIndex].IsNewRow && !ValidCost(e.FormattedValue?.ToString());
@@ -540,8 +877,20 @@ namespace OpenNest.Forms
{
public PlateOptionItem() { }
public bool Use { get; set; } = true;
public string Size { get; set; }
/// <summary>Null offers the size without limit; a ledger row starts at its free count.</summary>
public int? Quantity { get; set; }
public double Cost { get; set; }
public string Source => LedgerRow == null ? ""
: LedgerRow.IsIrregular ? "Ledger (irr.)"
: "Ledger";
/// <summary>Set for rows loaded from MaterialLedger; these are never saved with the nest.</summary>
internal LedgerStockRow LedgerRow { get; set; }
}
}
}
+12 -3
View File
@@ -28,6 +28,7 @@ namespace OpenNest.Forms.Commands
private readonly List<PlateOption> plateOptions;
private readonly double salvageRate;
private readonly double minRemnantSize;
private List<PlateOption> savedOptions;
private AutoNestCommand(IWin32Window owner, EditNestForm target, List<NestItem> items,
List<PlateOption> plateOptions, string engineName, double salvageRate, double minRemnantSize)
@@ -60,14 +61,19 @@ namespace OpenNest.Forms.Commands
if (!items.Any(it => it.Quantity > 0))
return null;
var plateOptions = default(List<PlateOption>);
if (form.OptimizePlateSize && !form.TryGetPlateOptions(out plateOptions, out var stockError))
var savedOptions = default(List<PlateOption>);
if (form.OptimizePlateSize
&& !form.TryGetPlateOptions(out plateOptions, out savedOptions, out var stockError))
{
MessageBox.Show(owner, stockError, Caption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return null;
}
return new AutoNestCommand(owner, target, items, plateOptions,
form.EngineName ?? EngineSelection.EngineName, form.SalvageRate, form.MinRemnantSize);
form.EngineName ?? EngineSelection.EngineName, form.SalvageRate, form.MinRemnantSize)
{
savedOptions = savedOptions,
};
}
/// <summary>
@@ -111,7 +117,10 @@ namespace OpenNest.Forms.Commands
target.PlateManager.LoadAt(target.Nest.Plates.IndexOf(applied[0]));
if (plateOptions?.Count > 0)
{
target.Nest.PlateOptions = plateOptions;
// Ledger rows and quantities are request-local inventory; the nest keeps
// only the hand-typed offers.
if (savedOptions?.Count > 0)
target.Nest.PlateOptions = savedOptions;
target.Nest.SalvageRate = salvageRate;
}
target.PlateView.Invalidate();
+47
View File
@@ -0,0 +1,47 @@
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using OpenNest.Data.MaterialLedger;
namespace OpenNest.Forms
{
/// <summary>
/// This PC's MaterialLedger connection, persisted to %APPDATA%\OpenNest\material-ledger.json
/// with the API key protected by DPAPI for the current Windows user. The ledger is optional:
/// nothing else in the app waits on it.
/// </summary>
public static class MaterialLedgerStore
{
// Distinguishes OpenNest's ledger key from other DPAPI blobs of the same user.
private static readonly byte[] Entropy = Encoding.UTF8.GetBytes("OpenNest.MaterialLedger.ApiKey");
private static readonly HttpClient Http = new();
private static MaterialLedgerSettings settings =
MaterialLedgerSettings.Load(MaterialLedgerSettings.DefaultPath, Unprotect);
/// <summary>Current settings, loaded once at process start.</summary>
public static MaterialLedgerSettings Settings => settings;
/// <summary>Persists the URL and key; the current settings stay unchanged if writing fails.</summary>
public static void Save(string baseUrl, string apiKey)
{
var next = new MaterialLedgerSettings { BaseUrl = baseUrl ?? "", ApiKey = apiKey ?? "" };
next.Save(MaterialLedgerSettings.DefaultPath, Protect);
settings = next;
}
/// <summary>A client for <paramref name="connection"/>, or for the saved settings when null.</summary>
public static MaterialLedgerClient CreateClient(MaterialLedgerSettings connection = null) =>
new(Http, connection ?? settings);
internal static string Protect(string plain) =>
Convert.ToBase64String(ProtectedData.Protect(Encoding.UTF8.GetBytes(plain), Entropy,
DataProtectionScope.CurrentUser));
internal static string Unprotect(string protectedText) =>
Encoding.UTF8.GetString(ProtectedData.Unprotect(Convert.FromBase64String(protectedText), Entropy,
DataProtectionScope.CurrentUser));
}
}
+92 -4
View File
@@ -49,12 +49,20 @@
this.updateGroupBox = new System.Windows.Forms.GroupBox();
this.updateFeedUrlBox = new System.Windows.Forms.TextBox();
this.setUpdateFeedButton = new System.Windows.Forms.Button();
this.ledgerGroupBox = new System.Windows.Forms.GroupBox();
this.ledgerUrlLabel = new System.Windows.Forms.Label();
this.ledgerUrlBox = new System.Windows.Forms.TextBox();
this.ledgerKeyLabel = new System.Windows.Forms.Label();
this.ledgerKeyBox = new System.Windows.Forms.TextBox();
this.testLedgerButton = new System.Windows.Forms.Button();
this.saveLedgerButton = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.planningEffortBox)).BeginInit();
this.tableLayoutPanel1.SuspendLayout();
this.bottomPanel1.SuspendLayout();
this.serverGroupBox.SuspendLayout();
this.updateGroupBox.SuspendLayout();
this.ledgerGroupBox.SuspendLayout();
this.SuspendLayout();
//
// checkBox1
@@ -176,7 +184,7 @@
this.bottomPanel1.Controls.Add(this.cancelButton);
this.bottomPanel1.Controls.Add(this.saveButton);
this.bottomPanel1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.bottomPanel1.Location = new System.Drawing.Point(0, 549);
this.bottomPanel1.Location = new System.Drawing.Point(0, 647);
this.bottomPanel1.Name = "bottomPanel1";
this.bottomPanel1.Size = new System.Drawing.Size(708, 50);
this.bottomPanel1.TabIndex = 1;
@@ -195,7 +203,7 @@
// strategyGroupBox
//
this.strategyGroupBox.Controls.Add(this.strategyGrid);
this.strategyGroupBox.Location = new System.Drawing.Point(12, 359);
this.strategyGroupBox.Location = new System.Drawing.Point(12, 457);
this.strategyGroupBox.Name = "strategyGroupBox";
this.strategyGroupBox.Size = new System.Drawing.Size(684, 180);
this.strategyGroupBox.TabIndex = 2;
@@ -254,7 +262,7 @@
//
this.updateGroupBox.Controls.Add(this.updateFeedUrlBox);
this.updateGroupBox.Controls.Add(this.setUpdateFeedButton);
this.updateGroupBox.Location = new System.Drawing.Point(12, 293);
this.updateGroupBox.Location = new System.Drawing.Point(12, 391);
this.updateGroupBox.Name = "updateGroupBox";
this.updateGroupBox.Size = new System.Drawing.Size(684, 60);
this.updateGroupBox.TabIndex = 3;
@@ -279,14 +287,85 @@
this.setUpdateFeedButton.UseVisualStyleBackColor = true;
this.setUpdateFeedButton.Click += new System.EventHandler(this.SetUpdateFeed_Click);
//
// ledgerGroupBox
//
this.ledgerGroupBox.Controls.Add(this.ledgerUrlLabel);
this.ledgerGroupBox.Controls.Add(this.ledgerUrlBox);
this.ledgerGroupBox.Controls.Add(this.ledgerKeyLabel);
this.ledgerGroupBox.Controls.Add(this.ledgerKeyBox);
this.ledgerGroupBox.Controls.Add(this.testLedgerButton);
this.ledgerGroupBox.Controls.Add(this.saveLedgerButton);
this.ledgerGroupBox.Location = new System.Drawing.Point(12, 293);
this.ledgerGroupBox.Name = "ledgerGroupBox";
this.ledgerGroupBox.Size = new System.Drawing.Size(684, 92);
this.ledgerGroupBox.TabIndex = 4;
this.ledgerGroupBox.TabStop = false;
this.ledgerGroupBox.Text = "MaterialLedger (optional; Auto Nest loads stock from it; set per machine)";
//
// ledgerUrlLabel
//
this.ledgerUrlLabel.AutoSize = true;
this.ledgerUrlLabel.Location = new System.Drawing.Point(12, 27);
this.ledgerUrlLabel.Name = "ledgerUrlLabel";
this.ledgerUrlLabel.Size = new System.Drawing.Size(37, 16);
this.ledgerUrlLabel.TabIndex = 0;
this.ledgerUrlLabel.Text = "URL:";
//
// ledgerUrlBox
//
this.ledgerUrlBox.Location = new System.Drawing.Point(80, 24);
this.ledgerUrlBox.Name = "ledgerUrlBox";
this.ledgerUrlBox.PlaceholderText = "http://ledger:5000";
this.ledgerUrlBox.Size = new System.Drawing.Size(417, 22);
this.ledgerUrlBox.TabIndex = 1;
//
// ledgerKeyLabel
//
this.ledgerKeyLabel.AutoSize = true;
this.ledgerKeyLabel.Location = new System.Drawing.Point(12, 59);
this.ledgerKeyLabel.Name = "ledgerKeyLabel";
this.ledgerKeyLabel.Size = new System.Drawing.Size(56, 16);
this.ledgerKeyLabel.TabIndex = 2;
this.ledgerKeyLabel.Text = "API key:";
//
// ledgerKeyBox
//
this.ledgerKeyBox.Location = new System.Drawing.Point(80, 56);
this.ledgerKeyBox.Name = "ledgerKeyBox";
this.ledgerKeyBox.Size = new System.Drawing.Size(417, 22);
this.ledgerKeyBox.TabIndex = 3;
this.ledgerKeyBox.UseSystemPasswordChar = true;
this.toolTip1.SetToolTip(this.ledgerKeyBox, "MaterialLedger's Api:Keys:OpenNest key. Stored encrypted for this Windows user.");
//
// testLedgerButton
//
this.testLedgerButton.Location = new System.Drawing.Point(504, 21);
this.testLedgerButton.Name = "testLedgerButton";
this.testLedgerButton.Size = new System.Drawing.Size(168, 28);
this.testLedgerButton.TabIndex = 4;
this.testLedgerButton.Text = "Test";
this.testLedgerButton.UseVisualStyleBackColor = true;
this.testLedgerButton.Click += new System.EventHandler(this.TestLedger_Click);
//
// saveLedgerButton
//
this.saveLedgerButton.Location = new System.Drawing.Point(504, 53);
this.saveLedgerButton.Name = "saveLedgerButton";
this.saveLedgerButton.Size = new System.Drawing.Size(168, 28);
this.saveLedgerButton.TabIndex = 5;
this.saveLedgerButton.Text = "Save Ledger";
this.saveLedgerButton.UseVisualStyleBackColor = true;
this.saveLedgerButton.Click += new System.EventHandler(this.SaveLedger_Click);
//
// OptionsForm
//
this.AcceptButton = this.saveButton;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
this.CancelButton = this.cancelButton;
this.ClientSize = new System.Drawing.Size(708, 599);
this.ClientSize = new System.Drawing.Size(708, 697);
this.Controls.Add(this.strategyGroupBox);
this.Controls.Add(this.updateGroupBox);
this.Controls.Add(this.ledgerGroupBox);
this.Controls.Add(this.serverGroupBox);
this.Controls.Add(this.tableLayoutPanel1);
this.Controls.Add(this.bottomPanel1);
@@ -308,6 +387,8 @@
this.serverGroupBox.PerformLayout();
this.updateGroupBox.ResumeLayout(false);
this.updateGroupBox.PerformLayout();
this.ledgerGroupBox.ResumeLayout(false);
this.ledgerGroupBox.PerformLayout();
this.ResumeLayout(false);
}
@@ -334,5 +415,12 @@
private System.Windows.Forms.GroupBox updateGroupBox;
private System.Windows.Forms.TextBox updateFeedUrlBox;
private System.Windows.Forms.Button setUpdateFeedButton;
private System.Windows.Forms.GroupBox ledgerGroupBox;
private System.Windows.Forms.Label ledgerUrlLabel;
private System.Windows.Forms.TextBox ledgerUrlBox;
private System.Windows.Forms.Label ledgerKeyLabel;
private System.Windows.Forms.TextBox ledgerKeyBox;
private System.Windows.Forms.Button testLedgerButton;
private System.Windows.Forms.Button saveLedgerButton;
}
}
+68
View File
@@ -1,9 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using OpenNest.Controls;
using OpenNest.Data;
using OpenNest.Data.MaterialLedger;
using OpenNest.Engine.CuttingPlanning;
using OpenNest.Engine.Strategies;
using OpenNest.Properties;
@@ -80,6 +82,8 @@ namespace OpenNest.Forms
{
serverUrlBox.Text = NestStorage.Settings.ServerUrl;
updateFeedUrlBox.Text = Settings.Default.UpdateFeedUrl;
ledgerUrlBox.Text = MaterialLedgerStore.Settings.BaseUrl;
ledgerKeyBox.Text = MaterialLedgerStore.Settings.ApiKey;
checkBox1.Checked = Settings.Default.CreateNewNestOnOpen;
numericUpDown1.Value = (decimal)Settings.Default.AutoSizePlateFactor;
planningEffortBox.Value = (decimal)CuttingPlanBatch.ClampBudgetMultiplier(Settings.Default.CuttingPlanEffort);
@@ -176,6 +180,70 @@ namespace OpenNest.Forms
}
}
private void SaveLedger_Click(object sender, EventArgs e)
{
if (!MaterialLedgerSettings.TryNormalizeUrl(ledgerUrlBox.Text, out var url))
{
MessageBox.Show(this, "Enter a valid http or https MaterialLedger URL, or clear it to turn the ledger off.",
"MaterialLedger", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
try
{
MaterialLedgerStore.Save(url, ledgerKeyBox.Text.Trim());
ledgerUrlBox.Text = MaterialLedgerStore.Settings.BaseUrl;
MessageBox.Show(this, url.Length == 0
? "MaterialLedger cleared. Auto Nest will not offer ledger stock."
: "MaterialLedger settings saved.",
"MaterialLedger", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(this, $"Could not save the MaterialLedger settings: {ex.Message}",
"MaterialLedger", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private async void TestLedger_Click(object sender, EventArgs e)
{
if (!MaterialLedgerSettings.TryNormalizeUrl(ledgerUrlBox.Text, out var url) || url.Length == 0)
{
MessageBox.Show(this, "Enter a valid http or https MaterialLedger URL.",
"MaterialLedger", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
testLedgerButton.Enabled = false;
try
{
var client = MaterialLedgerStore.CreateClient(
new MaterialLedgerSettings { BaseUrl = url, ApiKey = ledgerKeyBox.Text.Trim() });
// No mapping names this material, so a working ledger answers mapped:false.
var result = await client.GetStockAsync("OpenNest connection test", "", 0.25, CancellationToken.None);
if (IsDisposed)
return;
var (text, icon) = DescribeLedgerTest(result);
MessageBox.Show(this, text, "MaterialLedger", MessageBoxButtons.OK, icon);
}
finally
{
if (!IsDisposed)
testLedgerButton.Enabled = true;
}
}
internal static (string Text, MessageBoxIcon Icon) DescribeLedgerTest(LedgerStockResult result) => result switch
{
LedgerStockResult.Ok or LedgerStockResult.Unmapped =>
("Connected to MaterialLedger. The API key was accepted.", MessageBoxIcon.Information),
LedgerStockResult.Unauthorized =>
("MaterialLedger answered but rejected the API key. Check Api:Keys:OpenNest.", MessageBoxIcon.Warning),
LedgerStockResult.Unreachable unreachable =>
($"Could not reach MaterialLedger: {unreachable.Reason}", MessageBoxIcon.Warning),
_ => ("Enter a MaterialLedger URL.", MessageBoxIcon.Warning),
};
private void SetUpdateFeed_Click(object sender, EventArgs e)
{
var text = updateFeedUrlBox.Text?.Trim() ?? "";
+1
View File
@@ -33,6 +33,7 @@
<PackageReference Include="System.Drawing.Common" Version="8.0.10" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2903.40" />
<PackageReference Include="Velopack" Version="1.2.0" />
<PackageReference Include="System.Security.Cryptography.ProtectedData" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
+64
View File
@@ -255,3 +255,67 @@ save/reopen preserves them and existing nest metadata. Rejected/cancelled propos
change neither requirements nor options. Inventory remains request-local; saved
options are offers, not a per-sheet purchase ledger. These are cost-aware heuristics,
not global cost optimizers; validation and fulfillment remain required.
## Stock from MaterialLedger
Auto Nest can offer the sheets and drops that MaterialLedger reports as free for the
nest's material. The ledger is optional: with no URL set, or the ledger unreachable,
Auto Nest, save and post work exactly as before. OpenNest only reads from the ledger.
The stock it loads is a snapshot taken at nesting time and reserves nothing. ML's hold
batch stays the only authority, and another programmer can hold the same drop first.
**Setup (per PC).** Tools > Options > MaterialLedger takes the ledger URL and the API
key for ML's `Api:Keys:OpenNest`. They are stored in `%APPDATA%\OpenNest\material-ledger.json`,
with the key encrypted by DPAPI for the current Windows user. The key never goes in
`defaults.json` or a nest file. **Test** makes the same request with a material no
mapping names, so it reports the connection as working when ML answers `mapped: false`.
**Request.** **Load from ledger** above the Stock Options grid calls
`GET {url}/api/stock/opennest?material=&grade=&thicknessIn=` with the `X-Api-Key`
header and a 5 s timeout. The request sends the nest's `Material.Name`, its `Material.Grade`
and the thickness converted to inches (rounded to 4 places). ML resolves its own
OpenNest material mapping, and OpenNest keeps no copy of it. The button is enabled when
the ledger is configured and the nest has a material and a thickness. The request runs
while the dialog stays usable, and closing the dialog cancels it. The client
(`OpenNest.Data/MaterialLedger/`) returns `NotConfigured`, `Unreachable(reason)`,
`Unauthorized` (401/403), `Unmapped` (`mapped: false`) or `Ok` and never throws for these
failures. Unknown `kind`/`shape` strings still deserialize.
**Rows.** `LedgerStockMapper` turns the items into stock rows. Ledger sizes are inches
with the short side first, and become `Size(short, long)` in nest units:
| Ledger item | Stock row |
|---|---|
| `FullSheetBundle` / `FullSheet`, free quantity N | one row, quantity N |
| `Drop` | drops of identical usable size (3-place inches) share one row; quantity is the count |
| `IrregularConservativeRectangle` | its conservative rectangle, kept apart and marked "irregular" |
| `Unknown` or an unrecognized shape | skipped and counted in the summary |
| no part to nest fits in either orientation | skipped and counted in the summary |
Each row keeps its item codes (one per sheet, drops ordered by location then code)
and locations for the row tooltip and for later item assignment. The engine sees only
ordinary `NestPlateStock` rows with ids `ledger:{n}` and finite quantities. It never
sees item codes, and `OpenNest.Engine` has no ledger reference.
**Grid.** A load replaces earlier ledger rows and keeps hand-typed rows. Ledger rows
show Source "Ledger", and their size and cost are read-only. You can lower a ledger
row's quantity (not above the free count) or untick **Use** to leave any row out.
The **Qty** column applies to every row: blank offers the size without limit, as
hand-typed rows always have, and a number is passed as `PlateOption.Quantity` to
`NestPlateStock.Quantity`. A summary line under the grid reports the load, for example
"Ledger: 3 sheet sizes, 7 drops (2 skipped: 2 unknown shape)", or the failure. An
unmapped material clears the ledger rows. A failed request keeps them.
**Persistence.** Ledger rows and quantities are request-local and are never written to
`Nest.PlateOptions`. After a kept result, the nest saves the hand-typed rows with their
typed costs, as before.
**Cost.** Ledger rows load without cost. A ledger `CostPerUnit` is per lot unit, and a
drop's is its source sheet's. While any ledger row is ticked, the run scores by area and
hand-typed costs are ignored. The summary line says so, and the saved options keep
those costs. Pro-rating drop cost by area is a possible later change. Area scoring does
not make drops preferred over full sheets; a stock priority would be a `NestJob` input
with its own benchmark.
MCP, Console and `OpenNest.Api` do not load ledger stock yet. The client and mapper live
in `OpenNest.Data`, so these front ends can use them.