diff --git a/OpenNest.Core/PlateOption.cs b/OpenNest.Core/PlateOption.cs
index e48f06cf..58ea8de7 100644
--- a/OpenNest.Core/PlateOption.cs
+++ b/OpenNest.Core/PlateOption.cs
@@ -6,6 +6,12 @@ namespace OpenNest
public double Length { get; set; }
public double Cost { get; set; }
+ /// Sheets on hand for this request; null offers the size without limit. Not saved with the nest.
+ public int? Quantity { get; set; }
+
+ /// The engine stock id for this request; null uses the option's position. Not saved with the nest.
+ public string Id { get; set; }
+
public double Area => Width * Length;
}
}
diff --git a/OpenNest.Data/MaterialLedger/LedgerStock.cs b/OpenNest.Data/MaterialLedger/LedgerStock.cs
new file mode 100644
index 00000000..406c67dc
--- /dev/null
+++ b/OpenNest.Data/MaterialLedger/LedgerStock.cs
@@ -0,0 +1,67 @@
+namespace OpenNest.Data.MaterialLedger;
+
+///
+/// The body of MaterialLedger's GET /api/stock/opennest: the /api/stock shape plus
+/// , false when ML has no approved mapping for the OpenNest material.
+///
+public sealed record LedgerStockResponse(
+ bool Mapped,
+ IReadOnlyList? Specs,
+ IReadOnlyList? Items);
+
+public sealed record LedgerStockSpec(long MaterialSpecId, string DisplayName, decimal ThicknessIn, string? GaugeLabel);
+
+///
+/// Mirrors ML StockApi.StockItemDto. Sizes are inches with the short
+/// side; is free after active holds. and
+/// stay strings so a new ML enum value still deserializes.
+///
+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);
+
+/// ML InventoryItemKind names.
+public static class LedgerItemKinds
+{
+ public const string FullSheetBundle = "FullSheetBundle";
+ public const string FullSheet = "FullSheet";
+ public const string Drop = "Drop";
+}
+
+/// ML ShapeClassification names.
+public static class LedgerItemShapes
+{
+ public const string Rectangular = "Rectangular";
+ public const string IrregularConservativeRectangle = "IrregularConservativeRectangle";
+ public const string Unknown = "Unknown";
+}
+
+/// What a ledger stock request came to. Expected failures are results, never exceptions.
+public abstract record LedgerStockResult
+{
+ private LedgerStockResult() { }
+
+ /// No ledger URL is set on this PC.
+ public sealed record NotConfigured : LedgerStockResult;
+
+ /// The ledger did not answer usefully: network error, timeout, bad status or body.
+ public sealed record Unreachable(string Reason) : LedgerStockResult;
+
+ /// The ledger rejected the API key (401/403).
+ public sealed record Unauthorized : LedgerStockResult;
+
+ /// The ledger has no approved mapping for this material, grade and thickness.
+ public sealed record Unmapped : LedgerStockResult;
+
+ public sealed record Ok(IReadOnlyList Specs, IReadOnlyList Items) : LedgerStockResult;
+}
diff --git a/OpenNest.Data/MaterialLedger/LedgerStockMapper.cs b/OpenNest.Data/MaterialLedger/LedgerStockMapper.cs
new file mode 100644
index 00000000..69e79e7d
--- /dev/null
+++ b/OpenNest.Data/MaterialLedger/LedgerStockMapper.cs
@@ -0,0 +1,168 @@
+using OpenNest.Geometry;
+using OpenNest.Math;
+
+namespace OpenNest.Data.MaterialLedger;
+
+///
+/// One Auto Nest stock row built from ledger items. is in nest units with
+/// Width the short side. lists one code per unit of
+/// (a bundle repeats its code), in the order later steps assign them.
+///
+public sealed record LedgerStockRow(
+ string Id,
+ Size Size,
+ int Quantity,
+ bool IsDrop,
+ bool IsIrregular,
+ IReadOnlyList ItemCodes,
+ IReadOnlyList Locations);
+
+/// The rows offered to Auto Nest and the counts of ledger items left out.
+public sealed record LedgerStockMapping(
+ IReadOnlyList 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);
+
+ /// E.g. "Ledger: 3 sheet sizes, 7 drops (2 skipped: unknown shape)".
+ public string Summary
+ {
+ get
+ {
+ var skipped = new List();
+ 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";
+}
+
+///
+/// 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 ledger:{n} ids.
+///
+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);
+
+ /// The nest thickness in inches for the ledger query, rounded to 4 places.
+ public static double ThicknessInches(double thickness, Units units) =>
+ System.Math.Round(units == Units.Millimeters ? thickness / MillimetersPerInch : thickness, 4);
+
+ /// Ledger items in ledger order.
+ /// The nest's units; ledger sizes are always inches.
+ ///
+ /// 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.
+ ///
+ public static LedgerStockMapping Map(IEnumerable items, Units units,
+ IReadOnlyCollection? partEnvelopes = null)
+ {
+ ArgumentNullException.ThrowIfNull(items);
+ var scale = units == Units.Millimeters ? MillimetersPerInch : 1.0;
+ var unknown = 0;
+ var tooSmall = 0;
+ var entries = new List();
+ 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(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? 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 Items { get; } = new();
+ }
+}
diff --git a/OpenNest.Data/MaterialLedger/MaterialLedgerClient.cs b/OpenNest.Data/MaterialLedger/MaterialLedgerClient.cs
new file mode 100644
index 00000000..641a9fbc
--- /dev/null
+++ b/OpenNest.Data/MaterialLedger/MaterialLedgerClient.cs
@@ -0,0 +1,95 @@
+using System.Globalization;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+
+namespace OpenNest.Data.MaterialLedger;
+
+///
+/// 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
+/// cases; only the caller's own cancellation throws.
+///
+public sealed class MaterialLedgerClient
+{
+ /// Stock lists are larger than the nest-name lookup, so this waits longer than its 3 s.
+ 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;
+
+ /// Per-request limit; when null.
+ 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;
+ }
+
+ ///
+ /// The free sheets and drops for an OpenNest material. ML resolves the
+ /// material/grade/thickness mapping itself; is inches.
+ ///
+ public async Task 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(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(),
+ stock.Items ?? Array.Empty());
+ }
+ 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);
+ }
+ }
+}
diff --git a/OpenNest.Data/MaterialLedger/MaterialLedgerSettings.cs b/OpenNest.Data/MaterialLedger/MaterialLedgerSettings.cs
new file mode 100644
index 00000000..7397047f
--- /dev/null
+++ b/OpenNest.Data/MaterialLedger/MaterialLedgerSettings.cs
@@ -0,0 +1,105 @@
+using System.Text.Json;
+
+namespace OpenNest.Data.MaterialLedger;
+
+///
+/// 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.
+///
+public sealed class MaterialLedgerSettings
+{
+ private static readonly JsonSerializerOptions JsonOptions = new()
+ {
+ WriteIndented = true,
+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
+ PropertyNameCaseInsensitive = true,
+ };
+
+ /// Base URL of MaterialLedger, e.g. http://ledger:5000. Empty means not configured.
+ public string BaseUrl { get; set; } = "";
+
+ /// The plain API key in memory (ML key name Api:Keys:OpenNest).
+ public string ApiKey { get; set; } = "";
+
+ public bool IsConfigured => !string.IsNullOrWhiteSpace(BaseUrl);
+
+ /// %APPDATA%\OpenNest\material-ledger.json.
+ public static string DefaultPath => Path.Combine(
+ Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
+ "OpenNest", "material-ledger.json");
+
+ ///
+ /// Reads the settings, unprotecting the stored key with . A key
+ /// that cannot be unprotected (another user or PC) loads as empty so the ledger reports
+ /// unauthorized instead of failing to start.
+ ///
+ public static MaterialLedgerSettings Load(string path, Func unprotect)
+ {
+ ArgumentNullException.ThrowIfNull(unprotect);
+ if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
+ return new();
+
+ try
+ {
+ var file = JsonSerializer.Deserialize(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();
+ }
+ }
+
+ /// Writes camelCase JSON with the key protected by .
+ public void Save(string path, Func 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);
+ }
+
+ /// Validate and normalize a ledger base URL; blank is valid and means not configured.
+ 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; }
+ }
+}
diff --git a/OpenNest.Engine.Tests/Jobs/NestStockBuilderTests.cs b/OpenNest.Engine.Tests/Jobs/NestStockBuilderTests.cs
index c2335c37..7bcd0ced 100644
--- a/OpenNest.Engine.Tests/Jobs/NestStockBuilderTests.cs
+++ b/OpenNest.Engine.Tests/Jobs/NestStockBuilderTests.cs
@@ -65,4 +65,19 @@ public class NestStockBuilderTests
Assert.Throws(() => NestStockBuilder.FromTemplate(null, null));
Assert.Throws(() => 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);
+ }
}
diff --git a/OpenNest.Engine/Jobs/NestStockBuilder.cs b/OpenNest.Engine/Jobs/NestStockBuilder.cs
index fc169923..400614d8 100644
--- a/OpenNest.Engine/Jobs/NestStockBuilder.cs
+++ b/OpenNest.Engine/Jobs/NestStockBuilder.cs
@@ -5,7 +5,10 @@ using OpenNest.Geometry;
namespace OpenNest.Engine.Jobs;
-/// Shared stock snapshots for whole-job front ends. Plate repeat count is not inventory.
+///
+/// Shared stock snapshots for whole-job front ends. Plate repeat count is not inventory; an
+/// option's own quantity and id win over quantityPerOption and its position.
+///
public static class NestStockBuilder
{
public static IReadOnlyList 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,
diff --git a/OpenNest.Tests/Data/LedgerStockMapperTests.cs b/OpenNest.Tests/Data/LedgerStockMapperTests.cs
new file mode 100644
index 00000000..7e93bc12
--- /dev/null
+++ b/OpenNest.Tests/Data/LedgerStockMapperTests.cs
@@ -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);
+}
diff --git a/OpenNest.Tests/Data/MaterialLedgerClientTests.cs b/OpenNest.Tests/Data/MaterialLedgerClientTests.cs
new file mode 100644
index 00000000..3427db21
--- /dev/null
+++ b/OpenNest.Tests/Data/MaterialLedgerClientTests.cs
@@ -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(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(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(await unmapped.GetStockAsync("Unobtainium", "", 1, default));
+
+ var empty = Client(_ => Json("""{ "mapped": true, "specs": [], "items": [] }"""));
+ var ok = Assert.IsType(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(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(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(
+ await down.GetStockAsync("Steel", "A36", 0.25, default)).Reason);
+
+ var garbage = Client(_ => Json("login"));
+ Assert.IsType(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(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(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(() => 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(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 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 reply) : HttpMessageHandler
+ {
+ protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ return Task.FromResult(reply(request));
+ }
+ }
+
+ private sealed class HangingHandler : HttpMessageHandler
+ {
+ protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+ {
+ await Task.Delay(Timeout.Infinite, cancellationToken);
+ throw new InvalidOperationException("unreachable");
+ }
+ }
+}
diff --git a/OpenNest.Tests/Data/MaterialLedgerSettingsTests.cs b/OpenNest.Tests/Data/MaterialLedgerSettingsTests.cs
new file mode 100644
index 00000000..7739c5b8
--- /dev/null
+++ b/OpenNest.Tests/Data/MaterialLedgerSettingsTests.cs
@@ -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);
+ }
+}
diff --git a/OpenNest.WinForms.Tests/Forms/AutoNestFormLedgerStockTests.cs b/OpenNest.WinForms.Tests/Forms/AutoNestFormLedgerStockTests.cs
new file mode 100644
index 00000000..67022fed
--- /dev/null
+++ b/OpenNest.WinForms.Tests/Forms/AutoNestFormLedgerStockTests.cs
@@ -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(), 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(),
+ 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(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 { 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(grid.DataSource).Clear();
+ form.ApplyLedgerStock(Stock);
+ SetValue(Assert.IsAssignableFrom(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(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() };
+ 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? 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 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 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(form.Controls.Find("plateGrid", true).Single());
+ grid.CreateControl();
+ return grid;
+ }
+
+ private static int QuantityColumn(DataGridView grid) =>
+ grid.Columns.Cast().Single(c => c.DataPropertyName == "Quantity").Index;
+
+ private static Label Label(AutoNestForm form) =>
+ Assert.IsType