@page "/stock/new" @page "/stock/{Id:int}" @inject StockItemService StockItemService @inject MaterialService MaterialService @inject NavigationManager Navigation @using CutList.Core.Formatting @(IsNew ? "Add Stock Item" : "Edit Stock Item")

@(IsNew ? "Add Stock Item" : $"{stockItem.Material?.DisplayName} - {ArchUnits.FormatFromInches((double)stockItem.LengthInches)}")

@if (loading) {

Loading...

} else {
Stock Item Details
@if (!string.IsNullOrEmpty(errorMessage)) {
@errorMessage
}
@(IsNew ? "Cancel" : "Back to List")
} @code { [Parameter] public int? Id { get; set; } private StockItem stockItem = new(); private List materials = new(); private bool loading = true; private bool saving; private string? errorMessage; private bool IsNew => !Id.HasValue; protected override async Task OnInitializedAsync() { materials = await MaterialService.GetAllAsync(); if (Id.HasValue) { var existing = await StockItemService.GetByIdAsync(Id.Value); if (existing == null) { Navigation.NavigateTo("stock"); return; } stockItem = existing; } loading = false; } private async Task SaveStockItemAsync() { errorMessage = null; saving = true; try { if (stockItem.MaterialId == 0) { errorMessage = "Please select a material"; return; } if (stockItem.LengthInches <= 0) { errorMessage = "Length must be greater than zero"; return; } var exists = await StockItemService.ExistsAsync( stockItem.MaterialId, stockItem.LengthInches, IsNew ? null : stockItem.Id); if (exists) { errorMessage = "A stock item with this material and length already exists"; return; } try { if (IsNew) { var created = await StockItemService.CreateAsync(stockItem); Navigation.NavigateTo($"stock/{created.Id}"); } else { await StockItemService.UpdateAsync(stockItem); } } catch (Microsoft.EntityFrameworkCore.DbUpdateException) { errorMessage = "A stock item with this material and length already exists (it may have been previously deleted)."; } } finally { saving = false; } } }