Files
OpenNest/OpenNest/Forms/OptionsForm.cs
T
ajandClaude Opus 5.5 ea1decc097 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>
2026-10-25 17:40:44 -04:00

275 lines
11 KiB
C#

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;
namespace OpenNest.Forms
{
public partial class OptionsForm : Form
{
public OptionsForm()
{
InitializeComponent();
planningEffortBox.Minimum = (decimal)CuttingPlanBatch.MinimumBudgetMultiplier;
planningEffortBox.Maximum = (decimal)CuttingPlanBatch.MaximumBudgetMultiplier;
GridStyle.Apply(strategyGrid);
BuildStrategyGrid();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
LoadSettings();
}
private void BuildStrategyGrid()
{
strategyGrid.AutoGenerateColumns = false;
strategyGrid.Columns.Add(
new DataGridViewCheckBoxColumn
{
Name = "Enabled",
HeaderText = "",
Width = 30,
}
);
strategyGrid.Columns.Add(
new DataGridViewTextBoxColumn
{
Name = "Name",
HeaderText = "Strategy",
ReadOnly = true,
Width = 220,
}
);
strategyGrid.Columns.Add(
new DataGridViewTextBoxColumn
{
Name = "Phase",
HeaderText = "Phase",
ReadOnly = true,
Width = 100,
}
);
strategyGrid.Columns.Add(
new DataGridViewTextBoxColumn
{
Name = "Order",
HeaderText = "Order",
ReadOnly = true,
Width = 55,
}
);
foreach (var strategy in FillStrategyRegistry.AllStrategies)
{
strategyGrid.Rows.Add(true, strategy.Name, strategy.Phase, strategy.Order);
}
}
private void LoadSettings()
{
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);
colorSchemeCombo.Items.Clear();
foreach (var scheme in ColorSchemeRegistry.AllSchemes)
colorSchemeCombo.Items.Add(scheme.Name);
var active = Settings.Default.ActiveColorScheme;
var idx = colorSchemeCombo.Items.IndexOf(active);
colorSchemeCombo.SelectedIndex = idx >= 0 ? idx : 0;
var disabledNames = ParseDisabledStrategies(Settings.Default.DisabledStrategies);
foreach (DataGridViewRow row in strategyGrid.Rows)
row.Cells["Enabled"].Value = !disabledNames.Contains(
(string)row.Cells["Name"].Value
);
}
private void SaveSettings()
{
Settings.Default.CreateNewNestOnOpen = checkBox1.Checked;
Settings.Default.AutoSizePlateFactor = (double)numericUpDown1.Value;
Settings.Default.CuttingPlanEffort = (double)planningEffortBox.Value;
Settings.Default.ActiveColorScheme =
colorSchemeCombo.SelectedItem as string ?? "Classic";
var disabledNames = new List<string>();
foreach (DataGridViewRow row in strategyGrid.Rows)
{
if (row.Cells["Enabled"].Value is false)
disabledNames.Add((string)row.Cells["Name"].Value);
}
Settings.Default.DisabledStrategies = string.Join(",", disabledNames);
Settings.Default.Save();
ApplyDisabledStrategies();
ColorSchemeRegistry.ApplyActiveFromSettings();
foreach (Form f in Application.OpenForms)
f.Invalidate(invalidateChildren: true);
}
/// <summary>
/// Applies the DisabledStrategies setting to the FillStrategyRegistry.
/// Called on save and at startup from MainForm.
/// </summary>
public static void ApplyDisabledStrategies()
{
// Re-enable all, then disable the persisted set.
var all = FillStrategyRegistry.AllStrategies.Select(s => s.Name).ToArray();
FillStrategyRegistry.Enable(all);
var disabled = ParseDisabledStrategies(Settings.Default.DisabledStrategies);
if (disabled.Count > 0)
FillStrategyRegistry.Disable(disabled.ToArray());
}
private static HashSet<string> ParseDisabledStrategies(string value)
{
if (string.IsNullOrWhiteSpace(value))
return new HashSet<string>(StringComparer.OrdinalIgnoreCase);
return new HashSet<string>(
value.Split(',').Select(s => s.Trim()).Where(s => s.Length > 0),
StringComparer.OrdinalIgnoreCase
);
}
private void SaveSettings_Click(object sender, EventArgs e)
{
SaveSettings();
}
private void SetServer_Click(object sender, EventArgs e)
{
if (!NestStorageSettings.TryNormalizeServerUrl(serverUrlBox.Text, out var url))
{
MessageBox.Show(this, "Enter a valid http or https server URL.",
"Server URL", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
try
{
NestStorage.Save(NestStorage.Settings.Mode, url);
serverUrlBox.Text = NestStorage.Settings.ServerUrl;
MessageBox.Show(this, "Server URL saved. Storage mode has not changed.",
"Server URL", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(this, $"Could not save the server URL: {ex.Message}",
"Server URL", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
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() ?? "";
if (text.Length == 0)
{
Settings.Default.UpdateFeedUrl = "";
Settings.Default.Save();
updateFeedUrlBox.Text = "";
MessageBox.Show(this, "Update feed URL cleared. Update checks are disabled.",
"Update Feed URL", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (!NestStorageSettings.TryNormalizeServerUrl(text, out var url))
{
MessageBox.Show(this, "Enter a valid http or https feed URL, or clear the field to disable updates.",
"Update Feed URL", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
Settings.Default.UpdateFeedUrl = url;
Settings.Default.Save();
updateFeedUrlBox.Text = url;
MessageBox.Show(this, "Update feed URL saved. Restart OpenNest for the new feed to take effect.",
"Update Feed URL", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}