| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142 |
- using Comal.Classes;
- using InABox.Clients;
- using InABox.Core;
- using InABox.DynamicGrid;
- using InABox.Wpf;
- using InABox.WPF;
- using NPOI.SS.Formula.Functions;
- using Syncfusion.Data;
- using Syncfusion.Data.Extensions;
- using Syncfusion.UI.Xaml.Grid;
- using Syncfusion.Windows.Shared;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using Columns = InABox.Core.Columns;
- using PRSDesktop.Panels.StockForecast.OrderScreen;
- using PRSDimensionUtils;
- namespace PRSDesktop;
- public class StockForecastBreakupKey(Guid jobID, Guid requiID)
- {
- public Guid JobID { get; set; } = jobID;
- public Guid RequiID { get; set; } = requiID;
- public override bool Equals(object? obj)
- {
- return obj is StockForecastBreakupKey key && key.JobID == JobID && key.RequiID == RequiID;
- }
- public override int GetHashCode()
- {
- return HashCode.Combine(JobID, RequiID);
- }
- }
- public class StockForecastOrderData(ProductLink product, ProductStyleLink style, StockDimensions dimensions)
- {
- public ProductLink Product { get; set; } = product;
- public ProductStyleLink Style { get; set; } = style;
- public StockDimensions Dimensions { get; set; } = dimensions;
- public double RequiredQuantity { get; set; }
- public class QuantityBreakup(Guid jobID, Guid requiID, string description, double qty)
- {
- public Guid JobID { get; set; } = jobID;
- public Guid JobRequiItemID { get; set; } = requiID;
- public string Description { get; set; } = description;
- public double Quantity { get; set; } = qty;
- }
-
- private List<QuantityBreakup> RequiredQuantities { get; set; } = [];
- public List<QuantityBreakup> GetRequiredQuantities() => RequiredQuantities;
-
- public void SetRequiredQuantity(Guid jobID, Guid requiID, string description, double qty)
- {
- RequiredQuantities.Add(new(jobID, requiID, description,qty));
- }
- }
- public enum StockForecastOrderingType
- {
- StockOrder,
- Breakup
- }
- public class StockForecastOrderingItemQuantity
- {
- public event Action? Changed;
- private double orderTotal;
- public double OrderTotal
- {
- get => orderTotal;
- set
- {
- orderTotal = value;
- Changed?.Invoke();
- }
- }
- public Dictionary<StockForecastBreakupKey, double> Breakups { get; init; } = [];
- private SupplierProduct? _supplierProduct;
- /// <summary>
- /// Indicates the Supplier Product that has been selected for this cell. This comes from the combobox column.
- /// </summary>
- public SupplierProduct? SupplierProduct
- {
- get => _supplierProduct;
- set
- {
- _supplierProduct = value;
- Changed?.Invoke();
- }
- }
- public void DoChanged()
- {
- Changed?.Invoke();
- }
- public double JobTotal => Breakups.Values.Sum();
- public double GetTotal(StockForecastOrderingType type) => type == StockForecastOrderingType.StockOrder
- ? OrderTotal
- : JobTotal;
- }
- public class StockOrderingItem : BaseObject
- {
- [EditorSequence(1)]
- public ProductLink Product { get; set; }
- [EditorSequence(2)]
- public ProductStyleLink Style { get; set; }
- [EditorSequence(3)]
- public StockDimensions Dimensions { get; set; }
-
- public List<StockForecastOrderData.QuantityBreakup> Breakups { get; } = [];
-
- [EditorSequence(5)]
- [DoubleEditor]
- public double RequiredQuantity { get; set; }
- [EditorSequence(6)]
- [EnumLookupEditor(typeof(SupplierProductOrderStrategy))]
- public SupplierProductOrderStrategy OrderStrategy { get; set; }
- private Dictionary<StockForecastBreakupKey, double> JobRequiredQuantities { get; set; } = [];
- public Dictionary<StockForecastBreakupKey, double> GetJobRequiredQuantities()
- {
- return JobRequiredQuantities;
- }
-
- public void SetJobRequiredQuantity(Guid jobID, Guid requiID, double requiredQuantity)
- {
- JobRequiredQuantities[new(jobID, requiID)] = requiredQuantity;
- }
- public bool CustomStrategy { get; set; } = false;
- public StockForecastOrderingItemQuantity[] Quantities = [];
- public StockForecastOrderingItemQuantity GetQuantity(int i) => Quantities[i];
- public double GetTotalQuantity(StockForecastOrderingType type) => type == StockForecastOrderingType.StockOrder
- ? Quantities.Sum(x => x.OrderTotal)
- : Quantities.Sum(x => x.JobTotal);
- public void SetQuantities(StockForecastOrderingItemQuantity[] quantities)
- {
- Quantities = quantities;
- }
- }
- public class StockForecastOrderingResult(
- SupplierLink supplier,
- List<StockForecastOrderData.QuantityBreakup> breakups,
- StockOrderingItem item,
- double quantity,
- SupplierProduct supplierProduct)
- {
- public SupplierLink Supplier { get; set; } = supplier;
- public StockOrderingItem Item { get; set; } = item;
- public SupplierProduct SupplierProduct { get; set; } = supplierProduct;
- public double Quantity { get; set; } = quantity;
- public List<StockForecastOrderData.QuantityBreakup> Breakups { get; set; } = breakups;
- }
- public enum StockForecastOrderingStrategy
- {
- PerProduct,
- Exact,
- RoundUp,
- LowestUnitPrice,
- LowestOverallPrice,
- LowestOverstock
- }
- public class StockForecastOrderingGrid : DynamicItemsListGrid<StockOrderingItem>, ISpecificGrid
- {
- private List<SupplierProduct> SupplierProducts = [];
- private SupplierLink[] Suppliers = [];
- public IList<StockForecastOrderData> OrderData { get; set; }
- public double TotalQuantity => Items.Sum(x => x.GetTotalQuantity(OrderType));
- private DynamicActionColumn[] SupplierProductColumns = [];
- private DynamicActionColumn[] QuantityColumns = [];
- private DynamicActionColumn[] CostColumns = [];
- private readonly Dictionary<Guid, Job> JobDetails = [];
- private readonly Dictionary<Guid, JobRequisitionItem> JobRequiDetails = [];
- private static BitmapImage _warning = PRSDesktop.Resources.warning.AsBitmapImage();
- private StockForecastOrderingType _orderType = StockForecastOrderingType.Breakup;
- public StockForecastOrderingType OrderType
- {
- get => _orderType;
- set
- {
- if(_orderType != value)
- {
- _orderType = value;
- if (OrderData != null)
- {
- CalculateQuantities(true);
- UIComponent.UpdateOrderType(OrderType);
- foreach(var control in QuantityControls)
- {
- control.UpdateControl(OrderType);
- }
- Refresh(true, true);
- }
- }
- }
- }
- private StockForecastOrderingStrategy orderStrategy;
- public StockForecastOrderingStrategy OrderStrategy
- {
- get => orderStrategy;
- set
- {
- orderStrategy = value;
- if (OrderData != null)
- {
- foreach (var item in Items)
- {
- item.OrderStrategy = ForecastOrderStrategyToProductOrderStrategy(value, item.Product.OrderStrategy);
- item.CustomStrategy = false;
- }
- CalculateQuantities(false);
- Refresh(false, true);
- }
- }
- }
- private static SupplierProductOrderStrategy ForecastOrderStrategyToProductOrderStrategy(StockForecastOrderingStrategy strategy, SupplierProductOrderStrategy defaultValue)
- {
- return strategy switch
- {
- StockForecastOrderingStrategy.Exact => SupplierProductOrderStrategy.Exact,
- StockForecastOrderingStrategy.LowestOverallPrice => SupplierProductOrderStrategy
- .LowestOverallPrice,
- StockForecastOrderingStrategy.LowestUnitPrice => SupplierProductOrderStrategy.LowestUnitPrice,
- StockForecastOrderingStrategy.LowestOverstock => SupplierProductOrderStrategy.LowestOverstock,
- StockForecastOrderingStrategy.RoundUp => SupplierProductOrderStrategy.RoundUp,
- StockForecastOrderingStrategy.PerProduct or _ => defaultValue
- };
- }
- public IEnumerable<StockForecastOrderingResult> Results
- {
- get
- {
- for(int i = 0; i < Suppliers.Length; ++i)
- {
- var supplier = Suppliers[i];
- foreach(var item in Items)
- {
- var qty = item.GetQuantity(i);
- if (qty.SupplierProduct is null)
- {
- continue;
- }
- if(OrderType == StockForecastOrderingType.StockOrder && qty.OrderTotal > 0)
- {
- yield return new(supplier, new(), item, qty.OrderTotal, qty.SupplierProduct);
- }
- else if(qty.OrderTotal > 0)
- {
- var breakups = new List<StockForecastOrderData.QuantityBreakup>();
- foreach(var (key, q) in qty.Breakups)
- {
- // Check JobID because we are to skip the empty job (this is just the difference between all the allocations and the quantity on the PO).
- if(q > 0 && key.JobID != Guid.Empty)
- {
- breakups.Add(new(key.JobID, key.RequiID, "", q));
- }
- }
- yield return new(supplier, breakups, item, qty.OrderTotal, qty.SupplierProduct);
- }
- }
- }
- }
- }
- public StockForecastOrderingGrid()
- {
- HiddenColumns.Add(x => x.Product.Image.ID);
- }
- #region UI Component
- private Component? _uiComponent;
- private Component UIComponent
- {
- get
- {
- _uiComponent ??= new Component(this);
- return _uiComponent;
- }
- }
- protected override IDynamicGridUIComponent<StockOrderingItem> CreateUIComponent()
- {
- return UIComponent;
- }
- private class Component : DynamicGridGridUIComponent<StockOrderingItem>
- {
- private StockForecastOrderingGrid Grid;
- public Component(StockForecastOrderingGrid grid)
- {
- Parent = grid;
- Grid = grid;
- UpdateOrderType(grid.OrderType);
- }
- public void UpdateOrderType(StockForecastOrderingType type)
- {
- DataGrid.FrozenColumnCount = 8;
- }
- protected override Brush? GetCellSelectionBackgroundBrush()
- {
- return null;
- }
- protected override Brush? GetCellBackground(CoreRow row, DynamicColumnBase column)
- {
- var item = Grid.LoadItem(row);
- if(column is DynamicActionColumn ac)
- {
- var qIdx = Grid.QuantityColumns.IndexOf(ac);
- var idx = Math.Max(qIdx, Grid.CostColumns.IndexOf(ac));
- if(idx != -1)
- {
- var supplierProduct = item.GetQuantity(idx).SupplierProduct;
- return supplierProduct is null
- ? Brushes.Gainsboro
- : Brushes.WhiteSmoke;
- }
- }
- return base.GetCellBackground(row, column);
- }
- }
- #endregion
- private bool _observing = true;
- private void SetObserving(bool observing)
- {
- _observing = observing;
- }
- protected override void Changed()
- {
- if (_observing)
- {
- base.Changed();
- }
- }
- protected override void DoReconfigure(DynamicGridOptions options)
- {
- options.Clear();
- options.FilterRows = true;
- }
- private bool _loadedData = false;
- private void LoadData()
- {
- var supplierColumns = Columns.None<SupplierProduct>().Add(x => x.ID)
- .Add(x => x.SupplierLink.ID)
- .Add(x => x.Product.ID)
- .Add(x => x.Style.ID)
- .Add(x => x.Style.Code)
- .Add(x => x.ForeignCurrencyPrice)
- .Add(x => x.CostPrice)
- .AddDimensionsColumns(x => x.Dimensions)
- .Add(x => x.SupplierLink.Code);
- SupplierProducts = Client.Query(
- new Filter<SupplierProduct>(x => x.Product.ID).InList(OrderData.Select(x => x.Product.ID).ToArray())
- .And(x => x.SupplierLink.ID).IsNotEqualTo(Guid.Empty),
- supplierColumns,
- new SortOrder<SupplierProduct>(x => x.SupplierLink.Code))
- .ToList<SupplierProduct>();
- Suppliers = SupplierProducts.Select(x => x.SupplierLink).DistinctBy(x => x.ID).ToArray();
- CalculateQuantities(true);
- _loadedData = true;
- }
- private StockForecastOrderingItemQuantity CreateQuantity(int itemIdx)
- {
- var qty = new StockForecastOrderingItemQuantity();
- qty.Changed += () =>
- {
- if (!_observing) return;
- var row = Data.Rows[itemIdx];
- InvalidateRow(row);
- DoChanged();
- };
- return qty;
- }
- private SupplierProduct? CalculateSupplierProduct(StockOrderingItem item, int supplierIdx)
- {
- var supplierProduct = SelectSupplierProduct(SupplierProducts.Where(x => x.Product.ID == item.Product.ID && x.Style.ID == item.Style.ID && x.SupplierLink.ID == Suppliers[supplierIdx].ID), item);
- var qty = item.GetQuantity(supplierIdx);
- qty.SupplierProduct = supplierProduct;
- qty.OrderTotal = 0;
- qty.Breakups.Clear();
- foreach(var id in item.GetJobRequiredQuantities().Keys)
- {
- qty.Breakups[id] = 0;
- }
- return supplierProduct;
- }
- private void CalculateSupplierProduct(StockOrderingItem item)
- {
- var selectedSupplierProducts = new List<SupplierProduct>();
- for(int i = 0; i < Suppliers.Length; ++i)
- {
- var supplierProduct = CalculateSupplierProduct(item, i);
- if(supplierProduct is not null)
- {
- selectedSupplierProducts.Add(supplierProduct);
- }
- }
- var selectedSupplierProduct = SelectSupplierProduct(selectedSupplierProducts, item);
- if(selectedSupplierProduct is not null)
- {
- var supplierIdx = Suppliers.WithIndex()
- .FirstOrDefault(x => x.Value.ID == selectedSupplierProduct.SupplierLink.ID, new KeyValuePair<int, SupplierLink>(-1, null)).Key;
- if(supplierIdx != -1)
- {
- var qty = item.GetQuantity(supplierIdx);
- if(OrderType == StockForecastOrderingType.StockOrder)
- {
- qty.OrderTotal = GetRequiredQuantity(item, selectedSupplierProduct, item.RequiredQuantity);
- }
- else
- {
- qty.Breakups.Clear();
- qty.OrderTotal = GetRequiredQuantity(item, selectedSupplierProduct, item.RequiredQuantity);
- foreach(var (id, q) in item.GetJobRequiredQuantities())
- {
- qty.Breakups[id] = q; // / item.RequiredQuantity * qty.OrderTotal;
- }
- }
- }
- }
- }
- private void CalculateQuantities(bool recreateItems)
- {
- SetObserving(false);
- if (recreateItems)
- {
- Items.Clear();
- foreach(var dataItem in OrderData)
- {
- var item = new StockOrderingItem();
- item.Product.CopyFrom(dataItem.Product);
- item.Style.CopyFrom(dataItem.Style);
- item.Dimensions.CopyFrom(dataItem.Dimensions);
- item.OrderStrategy = ForecastOrderStrategyToProductOrderStrategy(OrderStrategy, item.Product.OrderStrategy);
- item.RequiredQuantity = dataItem.RequiredQuantity;
- foreach(var breakup in dataItem.GetRequiredQuantities())
- {
- item.SetJobRequiredQuantity(breakup.JobID, breakup.JobRequiItemID, breakup.Quantity);
- }
- Items.Add(item);
- }
- }
- foreach(var (itemIdx, item) in Items.WithIndex())
- {
- var quantities = new StockForecastOrderingItemQuantity[Suppliers.Length];
- for(int i = 0; i < Suppliers.Length; ++i)
- {
- quantities[i] = CreateQuantity(itemIdx);
- }
- item.SetQuantities(quantities);
- }
- foreach(var item in Items)
- {
- CalculateSupplierProduct(item);
- }
- SetObserving(true);
- DoChanged();
- }
- #region Order Strategy
- private SupplierProduct? SelectSupplierProduct(IEnumerable<SupplierProduct> supplierProducts, StockOrderingItem item)
- {
- switch (item.OrderStrategy)
- {
- case SupplierProductOrderStrategy.Exact:
- case SupplierProductOrderStrategy.RoundUp:
- return supplierProducts.Where(x => x.Dimensions.Equals(item.Dimensions) && x.Style.ID == item.Style.ID)
- .MinBy(x => x.CostPrice)
- ?? supplierProducts.Where(x => x.Dimensions.Equals(item.Dimensions))
- .MinBy(x => x.CostPrice);
-
- case SupplierProductOrderStrategy.LowestOverallPrice:
- return supplierProducts.Where(x => x.Style.ID == item.Style.ID)
- .MinBy(x => x.CostPrice *
- Math.Ceiling(item.RequiredQuantity * item.Dimensions.Value / (x.Dimensions.Value.IsEffectivelyEqual(0.0) ? (item.Dimensions.Value.IsEffectivelyEqual(0.0) ? 1.0 : item.Dimensions.Value) : x.Dimensions.Value)))
- ?? supplierProducts
- .MinBy(x => x.CostPrice * Math.Ceiling(item.RequiredQuantity * item.Dimensions.Value / (x.Dimensions.Value.IsEffectivelyEqual(0.0) ? (item.Dimensions.Value.IsEffectivelyEqual(0.0) ? 1.0 : item.Dimensions.Value) : x.Dimensions.Value)));
-
- case SupplierProductOrderStrategy.LowestUnitPrice:
- return supplierProducts.Where(x => x.Style.ID == item.Style.ID)
- .MinBy(x=>x.CostPrice * item.Dimensions.Value/(x.Dimensions.Value.IsEffectivelyEqual(0.0) ? (item.Dimensions.Value.IsEffectivelyEqual(0.0) ? 1.0 : item.Dimensions.Value) : x.Dimensions.Value))
- ?? supplierProducts
- .MinBy(x=>x.CostPrice * item.Dimensions.Value/(x.Dimensions.Value.IsEffectivelyEqual(0.0) ? (item.Dimensions.Value.IsEffectivelyEqual(0.0) ? 1.0 : item.Dimensions.Value) : x.Dimensions.Value));
-
- case SupplierProductOrderStrategy.LowestOverstock:
- return supplierProducts.Where(x => x.Style.ID == item.Style.ID)
- .MinBy(x=>x.Dimensions.Value * Math.Ceiling(item.RequiredQuantity * item.Dimensions.Value / (x.Dimensions.Value.IsEffectivelyEqual(0.0) ? (item.Dimensions.Value.IsEffectivelyEqual(0.0) ? 1.0 : item.Dimensions.Value) : x.Dimensions.Value)))
- ?? supplierProducts
- .MinBy(x=>x.Dimensions.Value * Math.Ceiling(item.RequiredQuantity * item.Dimensions.Value / (x.Dimensions.Value.IsEffectivelyEqual(0.0) ? (item.Dimensions.Value.IsEffectivelyEqual(0.0) ? 1.0 : item.Dimensions.Value) : x.Dimensions.Value)));
-
- default:
- return null;
- }
- }
- private double GetRequiredQuantity(StockOrderingItem item, SupplierProduct supplierProduct, double requiredQuantity)
- {
- var _strategy = item.CustomStrategy
- ? SupplierProductOrderStrategy.LowestOverstock
- : item.OrderStrategy;
-
- switch (_strategy)
- {
- case SupplierProductOrderStrategy.Exact:
- return requiredQuantity;
- case SupplierProductOrderStrategy.RoundUp:
- return Math.Ceiling(requiredQuantity);
- case SupplierProductOrderStrategy.LowestOverallPrice:
- case SupplierProductOrderStrategy.LowestUnitPrice:
- case SupplierProductOrderStrategy.LowestOverstock:
- return Math.Ceiling(requiredQuantity * item.Dimensions.Value / (supplierProduct.Dimensions.Value.IsEffectivelyEqual(0.0) ? (item.Dimensions.Value.IsEffectivelyEqual(0.0) ? 1.0 : item.Dimensions.Value) : supplierProduct.Dimensions.Value));
- default:
- return 0.0;
- }
- }
- #endregion
- private bool _loadedColumns = false;
- protected override DynamicGridColumns LoadColumns()
- {
- if (!_loadedData)
- {
- LoadData();
- }
- var columns = new DynamicGridColumns();
- columns.Add<StockOrderingItem, string>(x => x.Product.Code, 120, "Product Code", "", Alignment.MiddleCenter);
- columns.Add<StockOrderingItem, string>(x => x.Product.Name, 0, "Product Name", "", Alignment.MiddleLeft);
- columns.Add<StockOrderingItem, string>(x => x.Dimensions.UnitSize, 80, "Size", "", Alignment.MiddleCenter);
- columns.Add<StockOrderingItem, string>(x => x.Style.Code, 80, "Style", "", Alignment.MiddleCenter);
- columns.Add<StockOrderingItem, double>(x => x.RequiredQuantity, 80, "Required", "", Alignment.MiddleCenter);
- if (!_loadedColumns)
- {
- ActionColumns.Clear();
- ActionColumns.Add(new DynamicImageColumn(Warning_Image) { Position = DynamicActionColumnPosition.Start });
- ActionColumns.Add(new DynamicImagePreviewColumn<StockOrderingItem>(x => x.Product.Image) { Position = DynamicActionColumnPosition.Start });
- ActionColumns.Add(new DynamicTemplateColumn(row =>
- {
- var item = LoadItem(row);
- var box = new ComboBox();
- box.ItemsSource = Enum.GetValues<SupplierProductOrderStrategy>()
- .Select(x => new KeyValuePair<SupplierProductOrderStrategy, string>(x, CoreUtils.Neatify(x.ToString())));
- box.DisplayMemberPath = "Value";
- box.SelectedValuePath = "Key";
- box.SelectedValue = item.CustomStrategy ? null : item.OrderStrategy;
- box.SelectionChanged += (o, e) =>
- {
- if (box.SelectedValue is not SupplierProductOrderStrategy strategy) return;
- item.OrderStrategy = strategy;
- item.CustomStrategy = false;
- CalculateSupplierProduct(item);
- InvalidateRow(row);
- };
- box.Margin = new Thickness(2);
- box.VerticalContentAlignment = VerticalAlignment.Center;
- return box;
- })
- {
- HeaderText = "Order Strategy.",
- Width = 140
- });
- SupplierProductColumns = new DynamicActionColumn[Suppliers.Length];
- QuantityColumns = new DynamicActionColumn[Suppliers.Length];
- CostColumns = new DynamicActionColumn[Suppliers.Length];
- QuantityControls.Clear();
- for(int i = 0; i < Suppliers.Length; ++i)
- {
- InitialiseSupplierColumn(i);
- }
- ActionColumns.Add(new DynamicMenuColumn(BuildMenu));
- _loadedColumns = true;
- }
- return columns;
- }
- private void EditSupplierProductGrid(DynamicGrid<SupplierProduct> grid)
- {
- grid.OnCustomiseEditor += (sender, items, column, editor) =>
- {
- if(new Column<SupplierProduct>(x => x.SupplierLink.ID).IsEqualTo(column.ColumnName)
- || new Column<SupplierProduct>(x => x.Product.ID).IsEqualTo(column.ColumnName)
- || new Column<SupplierProduct>(x => x.Style.ID).IsEqualTo(column.ColumnName)
- || new Column<SupplierProduct>(x => x.Job.ID).IsEqualTo(column.ColumnName)
- // || new Column<SupplierProduct>(x => x.Dimensions).IsEqualTo(column.ColumnName)
- )
- {
- editor.Editable = editor.Editable.Combine(Editable.Disabled);
- }
- };
- }
- private void BuildMenu(DynamicMenuColumn column, CoreRow? row)
- {
- if (row is null) return;
- column.AddItem("New Supplier", null, row =>
- {
- if (row is null) return;
- var selection = new MultiSelectDialog<Supplier>(
- new Filter<Supplier>(x => x.ID).NotInList(Suppliers.Select(x => x.ID).ToArray()),
- Columns.None<Supplier>().Add(x => x.ID).Add(x => x.Code), multiselect: false);
- if (selection.ShowDialog() != true)
- {
- return;
- }
- var supplier = selection.Data().Rows.First().ToObject<Supplier>();
- var productInstance = LoadItem(row);
- var supplierProduct = new SupplierProduct();
- supplierProduct.Product.CopyFrom(productInstance.Product);
- supplierProduct.Style.CopyFrom(productInstance.Style);
- supplierProduct.Dimensions.CopyFrom(productInstance.Dimensions);
- supplierProduct.SupplierLink.CopyFrom(supplier);
- if (DynamicGridUtils.EditEntity(supplierProduct, customiseGrid: EditSupplierProductGrid))
- {
- SupplierProducts.Add(supplierProduct);
- var newSuppliers = new SupplierLink[Suppliers.Length + 1];
- var newIdx = Suppliers.Length;
- for (int i = 0; i < Suppliers.Length; i++)
- {
- newSuppliers[i] = Suppliers[i];
- }
- newSuppliers[newIdx] = supplierProduct.SupplierLink;
- foreach (var (itemIdx, item) in Items.WithIndex())
- {
- var quantities = new StockForecastOrderingItemQuantity[newSuppliers.Length];
- for (int i = 0; i < Suppliers.Length; ++i)
- {
- quantities[i] = item.GetQuantity(i);
- }
- var newQty = CreateQuantity(itemIdx);
- quantities[newIdx] = newQty;
- if(OrderType == StockForecastOrderingType.StockOrder)
- {
- newQty.OrderTotal = 0;
- }
- else
- {
- foreach(var id in item.GetJobRequiredQuantities().Keys)
- {
- newQty.Breakups[id] = 0;
- }
- }
- item.SetQuantities(quantities);
- }
- Suppliers = newSuppliers;
- _loadedColumns = false;
- Refresh(true, true);
- }
- });
- }
- private BitmapImage? Warning_Image(CoreRow? row)
- {
- if (row is null) return _warning;
- var item = LoadItem(row);
- if(item.GetTotalQuantity(OrderType) < item.RequiredQuantity)
- {
- return _warning;
- }
- else
- {
- return null;
- }
- }
- protected override void ConfigureColumnGroups()
- {
- for(int idx = 0; idx < Suppliers.Length; ++idx)
- {
- GetColumnGrouping().AddGroup(Suppliers[idx].Code, SupplierProductColumns[idx], CostColumns[idx]);
- }
- }
- private void LoadJobData(IEnumerable<Guid> ids)
- {
- var neededIDs = ids.Where(x => x != Guid.Empty && !JobDetails.ContainsKey(x)).ToArray();
- if(neededIDs.Length > 0)
- {
- var details = Client.Query(
- new Filter<Job>(x => x.ID).InList(neededIDs),
- Columns.None<Job>().Add(x => x.ID)
- .Add(x => x.JobNumber)
- .Add(x => x.Name));
- foreach(var job in details.ToObjects<Job>())
- {
- JobDetails[job.ID] = job;
- }
- }
- }
- private void LoadJobRequiData(IEnumerable<Guid> ids)
- {
- var neededIDs = ids.Where(x => x != Guid.Empty && !JobRequiDetails.ContainsKey(x)).ToArray();
- if(neededIDs.Length > 0)
- {
- var details = Client.Query(
- new Filter<JobRequisitionItem>(x => x.ID).InList(neededIDs),
- Columns.None<JobRequisitionItem>().Add(x => x.ID)
- .Add(x => x.Requisition.Number)
- .Add(x => x.Requisition.Description));
- foreach(var requi in details.ToObjects<JobRequisitionItem>())
- {
- JobRequiDetails[requi.ID] = requi;
- }
- }
- }
- private class QuantityControl : ContentControl
- {
- private readonly StockOrderingItem Item;
- private readonly int SupplierIndex;
- private readonly StockForecastOrderingGrid Parent;
- public QuantityControl(StockForecastOrderingGrid parent, StockOrderingItem item, int supplierIndex, StockForecastOrderingType mode)
- {
- Parent = parent;
- Item = item;
- SupplierIndex = supplierIndex;
- UpdateControl(mode);
- }
- public void UpdateControl(StockForecastOrderingType mode)
- {
- // If no supplier product has been selected for this cell, we can't allow the user to select a quantity.
- if(Item.GetQuantity(SupplierIndex).SupplierProduct is null)
- {
- Content = null;
- return;
- }
- if(mode == StockForecastOrderingType.StockOrder)
- {
- // Otherwise, simple quantity textbox editor.
- var editor = new DoubleTextBox
- {
- VerticalAlignment = VerticalAlignment.Stretch,
- HorizontalAlignment = HorizontalAlignment.Stretch,
- Background = new SolidColorBrush(Colors.LightYellow),
- BorderThickness = new Thickness(0.0),
- MinValue = 0.0,
- Value = Item.GetQuantity(SupplierIndex).OrderTotal
- };
- editor.ValueChanged += (o, e) =>
- {
- Item.GetQuantity(SupplierIndex).OrderTotal = editor.Value ?? default;
- };
- Content = editor;
- }
- else if(mode == StockForecastOrderingType.Breakup)
- {
- var grid = new Grid();
- grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
- grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(30) });
- var _breakups = Item.GetQuantity(SupplierIndex).Breakups.Sum(x => x.Value);
-
- var editor = new DoubleTextBox
- {
- VerticalAlignment = VerticalAlignment.Stretch,
- HorizontalAlignment = HorizontalAlignment.Stretch,
- VerticalContentAlignment = VerticalAlignment.Center,
- HorizontalContentAlignment = HorizontalAlignment.Center,
- Background = new SolidColorBrush(Colors.WhiteSmoke),
- BorderThickness = new Thickness(0.0),
- Value = Item.GetQuantity(SupplierIndex).OrderTotal,
- IsReadOnly = true,
- Focusable = false,
- };
- Grid.SetColumn(editor, 0);
- grid.Children.Add(editor);
- var btn = new Button
- {
- VerticalAlignment = VerticalAlignment.Stretch,
- VerticalContentAlignment = VerticalAlignment.Center,
- HorizontalAlignment = HorizontalAlignment.Stretch,
- Content = "..",
- Margin = new Thickness(1),
- Focusable = false
- };
- btn.SetValue(Grid.ColumnProperty, 1);
- btn.SetValue(Grid.RowProperty, 0);
- btn.Click += (o, e) =>
- {
- var qty = Item.GetQuantity(SupplierIndex);
- var alloc = qty.Breakups
- .Where(x => !Guid.Equals(x.Key.JobID,Guid.Empty) || !Guid.Equals(x.Key.RequiID,Guid.Empty))
- .Sum(x => x.Value);
- var order = qty.OrderTotal;
- var dim = new StockDimensions();
- dim.CopyFrom(qty.SupplierProduct.Dimensions);
- DimensionUtils.ConvertDimensions(dim, ref order, (f,c) => Client.Query(f,c));
- var general = order - alloc;
-
- Parent.LoadJobData(qty.Breakups.Keys.Select(x => x.JobID));
- Parent.LoadJobRequiData(qty.Breakups.Keys.Select(x => x.RequiID));
- var items = qty.Breakups.Select(x =>
- {
- var item = new StockForecastOrderingJobItem
- {
- JobID = x.Key.JobID,
- JobRequiID = x.Key.RequiID,
- RequiredQuantity = Item.GetJobRequiredQuantities().GetValueOrDefault(x.Key),
- Quantity = x.Value
- };
- if(item.JobID == Guid.Empty)
- {
- item.Description = "General Stock";
- }
- else if(Parent.JobDetails.TryGetValue(item.JobID, out var job))
- {
- if(Parent.JobRequiDetails.TryGetValue(item.JobRequiID, out var requi))
- {
- item.Description = $"{job.JobNumber}: Requi #{requi.Requisition.Number} ({requi.Requisition.Description})";
- }
- else
- {
- item.Description = $"{job.JobNumber}: {job.Name}";
- }
- }
- return item;
- }).ToList();
- var genitem = items.FirstOrDefault(x =>
- Guid.Equals(x.JobID, Guid.Empty) && Guid.Equals(x.JobRequiID, Guid.Empty));
- if (genitem == null)
- {
- genitem = new StockForecastOrderingJobItem
- {
- Description = "General Stock",
- JobID = Guid.Empty,
- JobRequiID = Guid.Empty,
- };
- items.Insert(0,genitem);
- }
- genitem.Quantity = general;
- var window = new StockForecastOrderJobScreen();
- window.Items = items;
- if(window.ShowDialog() == true)
- {
- foreach(var item in items)
- {
- qty.Breakups[new(item.JobID, item.JobRequiID)] = item.Quantity;
- }
- qty.DoChanged();
- var req = items.Sum(x => x.Quantity);
- var x = 1.0;
- var d = new StockDimensions();
- d.CopyFrom(qty.SupplierProduct.Dimensions);
- DimensionUtils.ConvertDimensions(d, ref x, (f,c) => Client.Query(f,c));
- req = Math.Ceiling(req / x);
- editor.Value = req;
- qty.OrderTotal = req;
- }
- };
- grid.Children.Add(btn);
- Content = grid;
- }
- }
- }
- private List<QuantityControl> QuantityControls = [];
- private void InitialiseSupplierColumn(int idx)
- {
- var contextMenuFunc = (CoreRow[]? rows) =>
- {
- var row = rows?.FirstOrDefault();
- if (row is null) return null;
- var item = LoadItem(row);
- var menu = new ContextMenu();
- menu.AddItem("Create Supplier Product", null, new Tuple<StockOrderingItem, int>(item, idx), CreateSupplierProduct_Click);
- return menu;
- };
- var qtyColumn = new Tuple<DynamicActionColumn, QuantityControl?>(null!, null);
- SupplierProductColumns[idx] = new DynamicTemplateColumn(row =>
- {
- var instance = LoadItem(row);
- var comboBox = new ComboBox();
- comboBox.Tag = idx;
- var items = SupplierProducts.Where(x => x.SupplierLink.ID == Suppliers[idx].ID && x.Product.ID == instance.Product.ID)
- .Select(x => new KeyValuePair<SupplierProduct?, string>(
- x,
- x.Style.ID != Guid.Empty ? $"{x.Dimensions.UnitSize}/{x.Style.Code}" : $"{x.Dimensions.UnitSize}"));
- if (items.Any())
- items = items.Prepend(new KeyValuePair<SupplierProduct?, string>(null, ""));
- comboBox.SelectedValuePath = "Key";
- comboBox.ItemsSource = items.ToArray();
- comboBox.DisplayMemberPath = "Value";
- var qty = instance.GetQuantity(idx);
- comboBox.Bind(ComboBox.SelectedValueProperty, qty, x => x.SupplierProduct);
- comboBox.SelectionChanged += (o, e) =>
- {
- var box = o as ComboBox;
- instance.CustomStrategy = true;
- var _item = LoadItem(row);
- var _product = ((o as ComboBox)?.SelectedValue as SupplierProduct ?? new SupplierProduct());
- qty.OrderTotal = GetRequiredQuantity(_item, _product, _item.RequiredQuantity);
- qty.Breakups.Clear();
- foreach(var (id, q) in _item.GetJobRequiredQuantities())
- qty.Breakups[id] = q;
-
- InvalidateRow(row);
- };
- comboBox.VerticalContentAlignment = VerticalAlignment.Center;
- comboBox.Margin = new Thickness(2);
- if(!items.Any())
- comboBox.IsEnabled = false;
-
- return comboBox;
- })
- {
- HeaderText = "U.O.M.",
- Width = 80
- };
-
- QuantityColumns[idx] = new DynamicTemplateColumn(row =>
- {
- var instance = LoadItem(row);
- var control = new QuantityControl(this, instance, idx, OrderType);
- QuantityControls.Add(control);
- return control;
- })
- {
- HeaderText = "Qty.",
- Width = 80,
- ContextMenu = contextMenuFunc
- };
-
- CostColumns[idx] = new DynamicTextColumn(row =>
- {
- if(row is null)
- {
- return "Cost";
- }
- var instance = LoadItem(row);
- var qty = instance.GetQuantity(idx);
- if(qty.SupplierProduct is not null)
- {
- return $"{qty.OrderTotal * qty.SupplierProduct.CostPrice:C2}";
- }
- else
- {
- return "";
- }
- })
- {
- HeaderText = "Cost",
- Width = 80,
- ContextMenu = contextMenuFunc,
- GetSummary = () =>
- {
- var summary = new GridSummaryColumn
- {
- Format = "{Sum:C2}",
- SummaryType = Syncfusion.Data.SummaryType.Custom,
- CustomAggregate = new CostAggregate(idx, this)
- };
- return summary;
- }
- };
- ActionColumns.Add(SupplierProductColumns[idx]);
- ActionColumns.Add(QuantityColumns[idx]);
- ActionColumns.Add(CostColumns[idx]);
- }
- private void CreateSupplierProduct_Click(Tuple<StockOrderingItem, int> tuple)
- {
- var (item, supplierIdx) = tuple;
- var supplierProduct = new SupplierProduct();
- supplierProduct.Product.CopyFrom(item.Product);
- supplierProduct.Style.CopyFrom(item.Style);
- supplierProduct.Dimensions.CopyFrom(item.Dimensions);
- supplierProduct.SupplierLink.CopyFrom(Suppliers[supplierIdx]);
- if (DynamicGridUtils.EditEntity(supplierProduct, customiseGrid: EditSupplierProductGrid))
- {
- SupplierProducts.Add(supplierProduct);
- var qty = item.GetQuantity(supplierIdx);
- if(qty.SupplierProduct is null)
- {
- CalculateSupplierProduct(item, supplierIdx);
- }
- InvalidateGrid();
- }
- }
- private class CostAggregate : ISummaryAggregate
- {
- public double Sum { get; private set; }
- private int SupplierIndex;
- private StockForecastOrderingGrid Grid;
- public CostAggregate(int supplierIndex, StockForecastOrderingGrid grid)
- {
- SupplierIndex = supplierIndex;
- Grid = grid;
- }
- public Action<IEnumerable, string, PropertyDescriptor> CalculateAggregateFunc()
- {
- return AggregateFunc;
- }
- private void AggregateFunc(IEnumerable items, string property, PropertyDescriptor args)
- {
- if (items is IEnumerable<DataRowView> rows)
- {
- Sum = 0;
- foreach (var dataRow in rows)
- {
- var rowIdx = dataRow.Row.Table.Rows.IndexOf(dataRow.Row);
- var item = Grid.LoadItem(Grid.Data.Rows[rowIdx]);
- var qty = item.GetQuantity(SupplierIndex);
- if(qty.SupplierProduct is not null)
- {
- Sum += qty.OrderTotal * qty.SupplierProduct.CostPrice;
- }
- }
- }
- else
- {
- Logger.Send(LogType.Error, "", $"Attempting to calculate aggregate on invalid data type '{items.GetType()}'.");
- }
- }
- }
- }
|