ReservationManagementPanel.xaml.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. using Comal.Classes;
  2. using InABox.Configuration;
  3. using InABox.Core;
  4. using InABox.DynamicGrid;
  5. using InABox.WPF;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.ComponentModel;
  9. using System.Diagnostics;
  10. using System.Linq;
  11. using System.Windows;
  12. using System.Windows.Controls;
  13. using System.Windows.Controls.Primitives;
  14. using System.Windows.Input;
  15. using System.Windows.Media;
  16. using InABox.WPF.Themes;
  17. using NPOI.SS.Formula.Functions;
  18. using System.Collections.ObjectModel;
  19. using InABox.Clients;
  20. using InABox.Wpf;
  21. using InABox.Wpf.Reports;
  22. using Columns = InABox.Core.Columns;
  23. using PRSDesktop.Panels.ReservationManagement.TreatmentPO;
  24. namespace PRSDesktop;
  25. /// <summary>
  26. /// Interaction logic for JobRequisitionsPanel.xaml
  27. /// </summary>
  28. public partial class ReservationManagementPanel : UserControl, IPanel<JobRequisitionItem>
  29. {
  30. private ReservationManagementGlobalSettings _globalSettings = null!; // Initialised in Setup()
  31. private DynamicSplitPanelView CurrentView;
  32. private List<PurchaseOrder> PurchaseOrders = new List<PurchaseOrder>();
  33. public ReservationManagementPanel()
  34. {
  35. InitializeComponent();
  36. CurrentView = SplitPanel.View;
  37. JobRequiItems.Reconfigure(options =>
  38. {
  39. var canMultiSelect = Mode != PanelMode.Reserve || SplitPanel.View == DynamicSplitPanelView.Master;
  40. if(canMultiSelect)
  41. {
  42. options.MultiSelect = true;
  43. }
  44. else
  45. {
  46. options.MultiSelect = false;
  47. }
  48. });
  49. }
  50. enum PanelMode
  51. {
  52. Reserve,
  53. Purchase
  54. }
  55. private PanelMode Mode { get; set; }
  56. private void SelectDetailButton(Button button)
  57. {
  58. reserveBtn.Background = new SolidColorBrush(Colors.WhiteSmoke);
  59. reserveBtn.Foreground = new SolidColorBrush(Colors.Black);
  60. foreach(var btn in PurchaseOrderButtons.Children.OfType<Button>())
  61. {
  62. btn.Background = new SolidColorBrush(Colors.WhiteSmoke);
  63. btn.Foreground = new SolidColorBrush(Colors.Black);
  64. }
  65. AddPOButton.Background = new SolidColorBrush(Colors.WhiteSmoke);
  66. AddPOButton.Foreground = new SolidColorBrush(Colors.Black);
  67. button.Background = ThemeManager.SelectedTabItemBackgroundBrush;
  68. button.Foreground = ThemeManager.SelectedTabItemForegroundBrush;
  69. }
  70. private void Reconfigure()
  71. {
  72. JobRequiItems.Reconfigure();
  73. OnUpdateDataModel?.Invoke(SectionName, DataModel(Selection.None));
  74. }
  75. private void SelectReserved()
  76. {
  77. SelectDetailButton(reserveBtn);
  78. reserveCol.Width = new System.Windows.GridLength(1, System.Windows.GridUnitType.Star);
  79. purchaseCol.Width = new System.Windows.GridLength(0);
  80. if(Mode != PanelMode.Reserve)
  81. {
  82. Mode = PanelMode.Reserve;
  83. Reconfigure();
  84. }
  85. }
  86. private void SelectNewPurchaseOrder()
  87. {
  88. SelectDetailButton(AddPOButton);
  89. reserveCol.Width = new System.Windows.GridLength(0);
  90. purchaseCol.Width = new System.Windows.GridLength(1, System.Windows.GridUnitType.Star);
  91. if (Mode != PanelMode.Purchase)
  92. {
  93. Mode = PanelMode.Purchase;
  94. Reconfigure();
  95. }
  96. purchasing.LoadFromRequiLine(Guid.Empty);
  97. }
  98. private void SelectPurchaseOrder(Button button, PurchaseOrder order)
  99. {
  100. SelectDetailButton(button);
  101. reserveCol.Width = new System.Windows.GridLength(0);
  102. purchaseCol.Width = new System.Windows.GridLength(1, System.Windows.GridUnitType.Star);
  103. if (Mode != PanelMode.Purchase)
  104. {
  105. Mode = PanelMode.Purchase;
  106. Reconfigure();
  107. }
  108. purchasing.LoadFromRequiLine(order.ID);
  109. }
  110. public bool IsReady { get; set; }
  111. public string SectionName => "Job Requisitions";
  112. public event DataModelUpdateEvent? OnUpdateDataModel;
  113. public void CreateToolbarButtons(IPanelHost host)
  114. {
  115. ProductSetupActions.Standard(host);
  116. host.CreateSetupAction(new PanelAction() { Caption = "Reservation Management Settings", Image = PRSDesktop.Resources.specifications, OnExecute = ConfigSettingsClick });
  117. // host.CreatePanelAction(new PanelAction("Treatment PO", PRSDesktop.Resources.purchase, TreatmentPO_Click));
  118. if(Mode == PanelMode.Purchase && SplitPanel.IsDetailVisible())
  119. {
  120. var sectionName = SupplierPurchaseOrderPanel.SectionName;
  121. var dataModel = SupplierPurchaseOrderPanel.DataModel(Array.Empty<Guid>());
  122. var reports = ReportUtils.LoadReports(sectionName, dataModel);
  123. foreach(var report in reports)
  124. {
  125. host.CreateReport(PanelHost.CreateReportAction(report, (selection) =>
  126. {
  127. Guid[] ids;
  128. if(selection == Selection.None)
  129. {
  130. ids = Array.Empty<Guid>();
  131. }
  132. else
  133. {
  134. ids = PurchaseOrders.Select(x => x.ID).ToArray();
  135. }
  136. return SupplierPurchaseOrderPanel.DataModel(ids);
  137. }));
  138. }
  139. }
  140. }
  141. private void ConfigSettingsClick(PanelAction obj)
  142. {
  143. var grid = new DynamicItemsListGrid<ReservationManagementGlobalSettings>();
  144. if(grid.EditItems(new ReservationManagementGlobalSettings[] { _globalSettings }))
  145. {
  146. new GlobalConfiguration<ReservationManagementGlobalSettings>().Save(_globalSettings);
  147. holdings.CompanyDefaultStyle = _globalSettings.ProductStyle;
  148. JobRequiItems.DueDateAlert = _globalSettings.DueDateAlert;
  149. JobRequiItems.DueDateWarning = _globalSettings.DueDateWarning;
  150. }
  151. }
  152. public DataModel DataModel(Selection selection)
  153. {
  154. var ids = JobRequiItems.ExtractValues(x => x.ID, selection).ToArray();
  155. return new BaseDataModel<JobRequisitionItem>(new Filter<JobRequisitionItem>(x => x.ID).InList(ids));
  156. }
  157. public void Heartbeat(TimeSpan time)
  158. {
  159. }
  160. public void Refresh()
  161. {
  162. JobRequiItems.Refresh(false, true);
  163. }
  164. public Dictionary<string, object[]> Selected()
  165. {
  166. return new Dictionary<string, object[]>
  167. {
  168. [typeof(JobRequisitionItem).EntityName()] = JobRequiItems.SelectedRows
  169. };
  170. }
  171. public void Setup()
  172. {
  173. SelectReserved();
  174. JobRequiItems.OnSelectItem += OnJobRequiItemSelected;
  175. JobRequiItems.Refresh(true, false);
  176. _globalSettings = new GlobalConfiguration<ReservationManagementGlobalSettings>().Load();
  177. substitutions.FreeStockOnly = JobRequiItems.UserSettings.SubstituteFreeStockOnly;
  178. substitutions.UpdateStyle = JobRequiItems.UserSettings.SubstituteUpdateStyle;
  179. JobRequiItems.DueDateAlert = _globalSettings.DueDateAlert;
  180. JobRequiItems.DueDateWarning = _globalSettings.DueDateWarning;
  181. holdings.CompanyDefaultStyle = _globalSettings.ProductStyle;
  182. holdings.OnHoldingsReviewRefresh += Holdings_OnHoldingsReviewRefresh;
  183. purchasing.OnPurchaseOrderSaved += Refresh;
  184. }
  185. private void OnJobRequiItemSelected(object sender, DynamicGridSelectionEventArgs e)
  186. {
  187. if (SplitPanel.IsDetailVisible())
  188. {
  189. holdings.Item = e.Rows?.FirstOrDefault()?.ToObject<JobRequisitionItem>();
  190. RefreshPurchaseOrderButtons();
  191. }
  192. }
  193. private void RefreshPurchaseOrderButtons()
  194. {
  195. var requiIDs = JobRequiItems.SelectedRows
  196. .Select(x => x.Get<JobRequisitionItem, Guid>(x => x.ID))
  197. .ToArray();
  198. var pos = Client.Query(
  199. new Filter<PurchaseOrder>(x => x.ID).InQuery(
  200. new Filter<JobRequisitionItemPurchaseOrderItem>(x => x.JobRequisitionItem.ID)
  201. .InList(requiIDs),
  202. x => x.PurchaseOrderItem.PurchaseOrderLink.ID),
  203. Columns.None<PurchaseOrder>().Add(x => x.ID)
  204. .Add(x => x.PONumber))
  205. .ToObjects<PurchaseOrder>().ToList();
  206. PurchaseOrders = pos;
  207. PurchaseOrderButtons.Children.Clear();
  208. var buttons = new List<(Button btn, PurchaseOrder po)>();
  209. foreach (var po in pos)
  210. {
  211. var button = new Button
  212. {
  213. Content = po.PONumber,
  214. Height = 30,
  215. FontWeight = FontWeights.DemiBold,
  216. BorderBrush = new SolidColorBrush(Colors.DarkGray),
  217. BorderThickness = new Thickness(1.25),
  218. Margin = new Thickness(2, 0, 0, 2),
  219. Padding = new Thickness(13, 3, 13, 3)
  220. };
  221. button.Click += (o, e) =>
  222. {
  223. SelectPurchaseOrder(button, po);
  224. };
  225. buttons.Add((button, po));
  226. PurchaseOrderButtons.Children.Add(button);
  227. }
  228. if (Mode == PanelMode.Purchase)
  229. {
  230. if (buttons.Count == 0)
  231. {
  232. SelectNewPurchaseOrder();
  233. }
  234. else
  235. {
  236. var btn = buttons[0];
  237. SelectPurchaseOrder(btn.btn, btn.po);
  238. }
  239. }
  240. else if (Mode == PanelMode.Reserve)
  241. {
  242. SelectReserved();
  243. }
  244. }
  245. private void Holdings_OnHoldingsReviewRefresh()
  246. {
  247. Refresh();
  248. }
  249. private void CheckSaved(CancelEventArgs cancel)
  250. {
  251. if (!SplitPanel.IsDetailVisible() || !purchasing.EditorChanged)
  252. {
  253. return;
  254. }
  255. var result = MessageWindow.ShowYesNoCancel("You have changes that have not been saved; do you wish to save these changes?", "Save Changes?");
  256. if (result == MessageWindowResult.Yes)
  257. {
  258. purchasing.Editor.SaveItem(cancel);
  259. if (!cancel.Cancel)
  260. {
  261. MessageWindow.ShowMessage("Purchase Order saved.", "Success");
  262. }
  263. }
  264. else if (result == MessageWindowResult.Cancel)
  265. {
  266. cancel.Cancel = true;
  267. }
  268. }
  269. public void Shutdown(CancelEventArgs? cancel)
  270. {
  271. if(cancel is not null && purchasing.EditorChanged)
  272. {
  273. CheckSaved(cancel);
  274. }
  275. }
  276. private void ReserveStock_Clicked(object sender, System.Windows.RoutedEventArgs e)
  277. {
  278. SelectReserved();
  279. }
  280. private void Purchasing_Drop(object sender, DragEventArgs e)
  281. {
  282. if(DynamicGridUtils.TryGetDropData(e, out var type, out var table))
  283. {
  284. if(type == typeof(JobRequisitionItem))
  285. {
  286. purchasing.DropItems(table.Rows);
  287. }
  288. }
  289. }
  290. private void AddPOButton_Click(object sender, RoutedEventArgs e)
  291. {
  292. SelectNewPurchaseOrder();
  293. }
  294. private void TreatmentPO_Click(PanelAction action)
  295. {
  296. var jris = JobRequiItems.SelectedRows.ToObjects<JobRequisitionItem>().ToDictionary(x => x.ID);
  297. if(jris.Count == 0)
  298. {
  299. MessageWindow.ShowMessage("Please select at least one job requisition item.", "No items selected");
  300. return;
  301. }
  302. if(jris.Values.Any(x => x.TreatmentRequired - x.TreatmentOnOrder <= 0))
  303. {
  304. MessageWindow.ShowMessage("Please select only items requiring treatment.", "Already treated");
  305. return;
  306. }
  307. if(jris.Values.Any(x => x.Style.ID == Guid.Empty))
  308. {
  309. MessageWindow.ShowMessage("Please select only items with a style.", "No style");
  310. return;
  311. }
  312. Client.EnsureColumns(jris.Values, Columns.None<JobRequisitionItem>()
  313. .Add(x => x.Product.Code)
  314. .Add(x => x.Product.Name)
  315. .Add(x => x.Requisition.Number)
  316. .Add(x => x.Job.JobNumber)
  317. .Add(x => x.Dimensions.Value));
  318. // Here, we grab every stock movement for the selected JRIs, and group them per JRI. For each JRI, any stock movements that are in the wrong style
  319. // are grouped according to their holding key. Note that this mimics precisely the TreatmentRequired aggregate on JRI. Hence, these holdings represent
  320. // the TreatmentRequired amounts; the 'Units' field is equivalent to TreatmentRequired.
  321. var holdings = Client.Query(
  322. new Filter<StockMovement>(x => x.JobRequisitionItem.ID).InList(jris.Keys.ToArray()),
  323. Columns.None<StockMovement>()
  324. .Add(x => x.JobRequisitionItem.ID)
  325. .Add(x => x.Job.ID)
  326. .Add(x => x.Job.JobNumber)
  327. .Add(x => x.Job.Name)
  328. .Add(x => x.Product.ID)
  329. .Add(x => x.Product.Code)
  330. .Add(x => x.Product.Name)
  331. .Add(x => x.Location.ID)
  332. .Add(x => x.Location.Code)
  333. .Add(x => x.Location.Description)
  334. .Add(x => x.Style.ID)
  335. .Add(x => x.Style.Code)
  336. .Add(x => x.Style.Description)
  337. .AddDimensionsColumns(x => x.Dimensions, Dimensions.ColumnsType.Local)
  338. .Add(x => x.Units))
  339. .ToObjects<StockMovement>()
  340. .GroupBy(x => x.JobRequisitionItem.ID)
  341. .ToDictionary(x => x.Key, x =>
  342. {
  343. var jri = jris[x.Key];
  344. return x.Where(x => x.Style.ID != jri.Style.ID).GroupBy(x => new
  345. {
  346. Job = x.Job.ID,
  347. Product = x.Product.ID,
  348. Location = x.Location.ID,
  349. Style = x.Style.ID,
  350. x.Dimensions
  351. }).ToDictionary(
  352. x => x.Key,
  353. x =>
  354. {
  355. var items = x.ToArray();
  356. return new
  357. {
  358. Job = items[0].Job,
  359. Product = items[0].Product,
  360. Location = items[0].Location,
  361. Style = items[0].Style,
  362. Dimensions = items[0].Dimensions,
  363. Units = items.Sum(x => x.Units)
  364. };
  365. });
  366. });
  367. var styles = Client.Query(
  368. new Filter<ProductStyle>(x => x.ID).InList(jris.Values.Select(x => x.Style.ID).ToArray()),
  369. Columns.None<ProductStyle>()
  370. .Add(x => x.ID)
  371. .Add(x => x.Code)
  372. .Add(x => x.StockTreatmentProduct.ID))
  373. .ToObjects<ProductStyle>().ToDictionary(x => x.ID);
  374. // We need to load the treatment product for the styles that we need.
  375. var treatmentProducts = Client.Query(
  376. new Filter<Product>(x => x.ID).InList(styles.Select(x => x.Value.StockTreatmentProduct.ID).ToArray()),
  377. Columns.None<Product>()
  378. .Add(x => x.ID)
  379. .Add(x => x.Code)
  380. .Add(x => x.Name)
  381. .Add(x => x.Supplier.ID)
  382. .Add(x => x.TreatmentType.ID)
  383. .Add(x => x.TreatmentType.Description)
  384. .Add(x => x.TreatmentType.Calculation))
  385. .ToObjects<Product>().ToDictionary(x => x.ID);
  386. // Also, the ProductTreatment contains the parameter we need.
  387. var jriProductsParameters = Client.Query(
  388. new Filter<ProductTreatment>(x => x.Product.ID).InList(jris.Values.Select(x => x.Product.ID).ToArray()),
  389. Columns.None<ProductTreatment>()
  390. .Add(x => x.Product.ID)
  391. .Add(x => x.TreatmentType.ID)
  392. .Add(x => x.Parameter))
  393. .ToObjects<ProductTreatment>().ToDictionary<ProductTreatment, (Guid product, Guid treatmentType)>(x => (x.Product.ID, x.TreatmentType.ID));
  394. var items = new List<ReservationManagementTreatmentPOItem>();
  395. foreach(var (id, jri) in jris)
  396. {
  397. if (!styles.TryGetValue(jri.Style.ID, out var style))
  398. {
  399. continue;
  400. }
  401. if(!treatmentProducts.TryGetValue(style.StockTreatmentProduct.ID, out var treatmentProduct))
  402. {
  403. MessageWindow.ShowMessage($"No stock treatment product found for style {style.Code}", "Treatment product not found");
  404. return;
  405. }
  406. else if(treatmentProduct.TreatmentType.ID == Guid.Empty)
  407. {
  408. MessageWindow.ShowMessage($"Treatment product {treatmentProduct.Code} does not have a treatment type", "No treatment type");
  409. return;
  410. }
  411. if(!jriProductsParameters.TryGetValue((jri.Product.ID, treatmentProduct.TreatmentType.ID), out var treatment))
  412. {
  413. MessageWindow.ShowMessage(
  414. $"No treatment parameter found for product {jri.Product.Code} for treatment type {treatmentProduct.TreatmentType.Description}",
  415. "Treatment product not found");
  416. return;
  417. }
  418. var jriHoldings = holdings.GetValueOrDefault(id);
  419. // We know here that the TreatmentRequired > 0, because of the check at the top of the function. Hence, there definitely should be holdings.
  420. // This therefore shouldn't ever happen, but if it does, we've made a logic mistake, and this error will tell us that.
  421. if(jriHoldings is null || jriHoldings.Count == 0)
  422. {
  423. MessageWindow.ShowError($"Internal error for requisition {jri.Requisition.Number} for job {jri.Job.JobNumber}", $"No holdings even though TreatmentRequired is greater than 0.");
  424. continue;
  425. }
  426. double multiplier;
  427. if (treatmentProduct.TreatmentType.Calculation.IsNullOrWhiteSpace())
  428. {
  429. // This is the default calculation.
  430. multiplier = treatment.Parameter * jri.Dimensions.Value;
  431. }
  432. else
  433. {
  434. var model = new TreatmentTypeCalculationModel();
  435. model.Dimensions.CopyFrom(jri.Dimensions);
  436. model.Parameter = treatment.Parameter;
  437. var expression = new CoreExpression<TreatmentTypeCalculationModel, double>(treatmentProduct.TreatmentType.Calculation);
  438. if(!expression.Evaluate(model).Get(out multiplier, out var e))
  439. {
  440. MessageWindow.ShowError("Error calculating expression multiplier; using Parameter * Dimensions.Value instead.", e);
  441. multiplier = treatment.Parameter * jri.Dimensions.Value;
  442. }
  443. }
  444. foreach(var (key, holding) in jriHoldings)
  445. {
  446. if (!holding.Units.IsEffectivelyGreaterThan(0)) continue;
  447. var item = new ReservationManagementTreatmentPOItem();
  448. item.Product.CopyFrom(holding.Product);
  449. item.Style.CopyFrom(holding.Style);
  450. item.Job.CopyFrom(holding.Job);
  451. item.Location.CopyFrom(holding.Location);
  452. item.Dimensions.CopyFrom(holding.Dimensions);
  453. item.TreatmentProduct.CopyFrom(treatmentProduct);
  454. item.Finish.CopyFrom(style);
  455. item.JRI.CopyFrom(jri);
  456. item.Multiplier = multiplier;
  457. // holding.Units should be TreatmentRequired
  458. item.RequiredQuantity = holding.Units;
  459. items.Add(item);
  460. }
  461. }
  462. var window = new ReservationManagementTreatmentOrderScreen(items);
  463. if(window.ShowDialog() == true)
  464. {
  465. var orders = new List<Tuple<PurchaseOrder, List<(PurchaseOrderItem, JobRequisitionItemLink)>>>();
  466. var movements = new List<StockMovement>();
  467. var results = window.Results.GroupBy(x => x.Supplier.ID).Select(x => (x.Key, x.ToArray())).ToArray();
  468. var suppliers = Client.Query(
  469. new Filter<Supplier>(x => x.ID).InList(results.ToArray(x => x.Key)),
  470. Columns.None<Supplier>().Add(x => x.ID).Add(x => x.DefaultLocation.ID))
  471. .ToObjects<Supplier>()
  472. .ToDictionary(x => x.ID);
  473. foreach(var (supplierID, perSupplier) in results)
  474. {
  475. var order = new PurchaseOrder();
  476. order.RaisedBy.ID = App.EmployeeID;
  477. order.DueDate = DateTime.Today.AddDays(7);
  478. order.Notes = [$"Treatment purchase order raised by {App.EmployeeName} from Reservation Management screen"];
  479. LookupFactory.DoLookup<PurchaseOrder, Supplier, SupplierLink>(order, x => x.SupplierLink, supplierID);
  480. var orderItems = new List<(PurchaseOrderItem, JobRequisitionItemLink)>();
  481. foreach(var item in perSupplier)
  482. {
  483. var orderItem = new PurchaseOrderItem();
  484. orderItem.Product.ID = item.Item.TreatmentProduct.ID;
  485. orderItem.Job.ID = item.Item.JRI.Job.ID;
  486. orderItems.Add((orderItem, item.Item.JRI));
  487. }
  488. LookupFactory.DoLookups<PurchaseOrderItem, Product, ProductLink>(
  489. orderItems.Select(x => new Tuple<PurchaseOrderItem, Guid>(x.Item1, x.Item1.Product.ID)),
  490. x => x.Product);
  491. LookupFactory.DoLookups<PurchaseOrderItem, Job, JobLink>(
  492. orderItems.Select(x => new Tuple<PurchaseOrderItem, Guid>(x.Item1, x.Item1.Job.ID)),
  493. x => x.Job);
  494. LookupFactory.DoLookups<PurchaseOrderItem, TaxCode, TaxCodeLink>(
  495. orderItems.WithIndex().Select(x => new Tuple<PurchaseOrderItem, Guid>(x.Value.Item1, perSupplier[x.Key].SupplierProduct.TaxCode.ID)),
  496. x => x.TaxCode);
  497. foreach (var (i, item) in perSupplier.WithIndex())
  498. {
  499. var orderItem = orderItems[i].Item1;
  500. orderItem.Qty = item.Quantity;
  501. orderItem.Cost = item.SupplierProduct.CostPrice * item.Item.Multiplier;
  502. orderItem.Description = $"Treatment for {item.Item.JRI.Product.Name} ({item.Item.Product.Code}/{item.Item.Product.Name})";
  503. }
  504. if(suppliers.TryGetValue(supplierID, out var supplier))
  505. {
  506. foreach(var item in perSupplier)
  507. {
  508. var tOut = new StockMovement();
  509. tOut.Job.CopyFrom(item.Item.Job);
  510. tOut.Style.CopyFrom(item.Item.Style);
  511. tOut.Location.CopyFrom(item.Item.Location);
  512. tOut.Product.CopyFrom(item.Item.Product);
  513. tOut.Dimensions.CopyFrom(item.Item.Dimensions);
  514. tOut.Employee.ID = App.EmployeeID;
  515. tOut.Date = DateTime.Now;
  516. tOut.Issued = item.Quantity;
  517. tOut.Type = StockMovementType.TransferOut;
  518. tOut.JobRequisitionItem.CopyFrom(item.Item.JRI);
  519. tOut.Notes = "Stock movement for treatment purchase order created from Reservation Management";
  520. var tIn = tOut.CreateMovement();
  521. tIn.Transaction = tOut.Transaction;
  522. tIn.Style.CopyFrom(item.Item.JRI.Style);
  523. tIn.Location.CopyFrom(supplier.DefaultLocation);
  524. tIn.Employee.ID = App.EmployeeID;
  525. tIn.Date = tOut.Date;
  526. tIn.Received = item.Quantity;
  527. tIn.Type = StockMovementType.TransferIn;
  528. tIn.JobRequisitionItem.CopyFrom(item.Item.JRI);
  529. tIn.Notes = "Stock movement for treatment purchase order created from Reservation Management";
  530. movements.Add(tOut);
  531. movements.Add(tIn);
  532. }
  533. }
  534. else
  535. {
  536. MessageWindow.ShowMessage(
  537. $"No default location set up for supplier '{perSupplier[0].Supplier.Code}'; skipping creating stock movements",
  538. "No default location");
  539. }
  540. orders.Add(new(order, orderItems));
  541. }
  542. var doIssue = false;
  543. if(Security.IsAllowed<CanIssueTreatmentPurchaseOrders>())
  544. {
  545. if (_globalSettings.AutoIssueTreatmentPOs)
  546. {
  547. doIssue = true;
  548. }
  549. else if(MessageWindow.ShowYesNo($"Do you wish to mark the purchase order{(orders.Count != 1 ? "s" : "")} as issued?", "Mark as issued?"))
  550. {
  551. doIssue = true;
  552. }
  553. }
  554. if (doIssue)
  555. {
  556. foreach(var (order, _) in orders)
  557. {
  558. order.IssuedBy.ID = App.EmployeeID;
  559. order.IssuedDate = DateTime.Now;
  560. }
  561. }
  562. Client.Save(orders.Select(x => x.Item1), "Treatment PO created from Reservation Management screen");
  563. foreach(var (order, orderItems) in orders)
  564. {
  565. foreach(var item in orderItems)
  566. {
  567. item.Item1.PurchaseOrderLink.ID = order.ID;
  568. }
  569. }
  570. Client.Save(orders.SelectMany(x => x.Item2).Select(x => x.Item1), "Treatment PO created from Reservation Management screen");
  571. Client.Save(orders.SelectMany(x => x.Item2).Select(x =>
  572. {
  573. var jriPOI = new JobRequisitionItemPurchaseOrderItem();
  574. jriPOI.JobRequisitionItem.ID = x.Item2.ID;
  575. jriPOI.PurchaseOrderItem.ID = x.Item1.ID;
  576. return jriPOI;
  577. }), "Treatment PO created from Reservation Management screen");
  578. Client.Save(movements, "Treatment PO created from Reservation Management screen");
  579. MessageWindow.ShowMessage(
  580. $"{orders.Count} treatment purchase order{(orders.Count != 1 ? "s" : "")} {(doIssue ? "issued" : "raised")}:\n" +
  581. $"- {string.Join(',', orders.Select(x => x.Item1.PONumber))}",
  582. "Success");
  583. JobRequiItems.SelectedRows = [];
  584. JobRequiItems.Refresh(false, true);
  585. }
  586. }
  587. private void SplitPanel_OnChanged(object sender, DynamicSplitPanelSettings e)
  588. {
  589. JobRequiItems.Reconfigure();
  590. if(CurrentView != e.View)
  591. {
  592. CurrentView = e.View;
  593. if (e.View != DynamicSplitPanelView.Master)
  594. {
  595. Refresh();
  596. }
  597. }
  598. }
  599. private bool _updatingSubstitution = false;
  600. private void JobRequiItems_OnOnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  601. {
  602. _updatingSubstitution = true;
  603. try
  604. {
  605. var row = e.Rows?.SingleOrDefault();
  606. var visible =
  607. row != null
  608. && row.Get<JobRequisitionItem, double>(x => x.InStock).IsEffectivelyEqual(0.0)
  609. && row.Get<JobRequisitionItem, double>(x => x.TotalOrders).IsEffectivelyEqual(0.0)
  610. && row.Get<JobRequisitionItem, double>(x => x.OnOrder).IsEffectivelyEqual(0.0)
  611. && row.Get<JobRequisitionItem, double>(x => x.TreatmentRequired).IsEffectivelyEqual(0.0)
  612. && row.Get<JobRequisitionItem, double>(x => x.TreatmentOnOrder).IsEffectivelyEqual(0.0)
  613. && row.Get<JobRequisitionItem, double>(x => x.Allocated).IsEffectivelyEqual(0.0)
  614. && row.Get<JobRequisitionItem, double>(x => x.PickRequested).IsEffectivelyEqual(0.0)
  615. && row.Get<JobRequisitionItem, double>(x => x.Issued).IsEffectivelyEqual(0.0);
  616. substitutions.SizeChanged -= Substitutions_OnSizeChanged;
  617. SubstitutionSplitterRow.Height = visible ? GridLength.Auto : new GridLength(0.0);
  618. SubstitutionRow.Height = visible ? new GridLength(JobRequiItems.UserSettings.SubstitutionGridHeight) : new GridLength(0.0);
  619. SubstitutionButtonRow.Height = visible ? GridLength.Auto : new GridLength(0.0);
  620. substitutions.SizeChanged += Substitutions_OnSizeChanged;
  621. if (visible)
  622. substitutions.JRI = row?.ToObject<JobRequisitionItem>() ?? new JobRequisitionItem();
  623. SubstitutionFreeStock.IsChecked = JobRequiItems.UserSettings.SubstituteFreeStockOnly;
  624. SubstitutionUpdateStyle.IsChecked = JobRequiItems.UserSettings.SubstituteUpdateStyle;
  625. }
  626. finally
  627. {
  628. _updatingSubstitution = false;
  629. }
  630. }
  631. private void SubstitutionFreeStock_OnChecked(object sender, RoutedEventArgs e)
  632. {
  633. if (_updatingSubstitution)
  634. return;
  635. substitutions.FreeStockOnly = SubstitutionFreeStock.IsChecked == true;
  636. JobRequiItems.UserSettings.SubstituteFreeStockOnly = substitutions.FreeStockOnly;
  637. new UserConfiguration<ReservationManagementUserSettings>().Save(JobRequiItems.UserSettings);
  638. }
  639. private void SubstitutionUpdateStyle_OnChecked(object sender, RoutedEventArgs e)
  640. {
  641. if (_updatingSubstitution)
  642. return;
  643. substitutions.UpdateStyle = SubstitutionUpdateStyle.IsChecked == true;
  644. JobRequiItems.UserSettings.SubstituteUpdateStyle = substitutions.UpdateStyle;
  645. new UserConfiguration<ReservationManagementUserSettings>().Save(JobRequiItems.UserSettings);
  646. }
  647. private bool _sizeChanging = false;
  648. private void Substitutions_OnSizeChanged(object sender, SizeChangedEventArgs e)
  649. {
  650. _sizeChanging = System.Windows.Input.Mouse.LeftButton == MouseButtonState.Pressed;
  651. }
  652. protected override void OnPreviewMouseUp(MouseButtonEventArgs e)
  653. {
  654. base.OnPreviewMouseUp(e);
  655. if (_sizeChanging)
  656. {
  657. _sizeChanging = false;
  658. JobRequiItems.UserSettings.SubstitutionGridHeight = substitutions.ActualHeight;
  659. new UserConfiguration<ReservationManagementUserSettings>().Save(JobRequiItems.UserSettings);
  660. }
  661. }
  662. private void ChangeProduct_OnClick(object sender, RoutedEventArgs e)
  663. {
  664. var _holding = substitutions.SelectedRows?.FirstOrDefault()?.ToObject<StockHolding>();
  665. var _jrirow = JobRequiItems.SelectedRows.FirstOrDefault();
  666. if (_holding == null || _jrirow == null)
  667. return;
  668. var _jri = _jrirow.ToObject<JobRequisitionItem>();
  669. _jri.Dimensions.CopyFrom(_holding.Dimensions, true);
  670. if (substitutions.UpdateStyle)
  671. _jri.Style.CopyFrom(_holding.Style);
  672. Client.Save(_jri,"Substituted by Requisition Management Screen");
  673. var _xferout = _holding.CreateMovement();
  674. _xferout.Issued = Math.Min(_holding.Available, _jri.Qty);
  675. _xferout.Notes = "Substituted by Requisition Management Screen";
  676. _xferout.Transaction = Guid.NewGuid();
  677. _xferout.Type = StockMovementType.TransferOut;
  678. var _xferin = _holding.CreateMovement();
  679. _xferin.JobRequisitionItem.CopyFrom(_jri);
  680. _xferin.Job.CopyFrom(_jri.Job);
  681. _xferin.Received = Math.Min(_holding.Available, _jri.Qty);
  682. _xferin.Notes = "Substituted by Requisition Management Screen";
  683. _xferin.Transaction = _xferout.Transaction;
  684. _xferin.Type = StockMovementType.TransferIn;
  685. Client.Save(new[] { _xferout, _xferin}, "Substituted by Requisition Management Screen");
  686. JobRequiItems.Refresh(false,true);
  687. // Allocate Stock (transfer if required)
  688. }
  689. private void Substitutions_OnOnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  690. {
  691. ChangeProduct.IsEnabled = e.Rows?.SingleOrDefault() != null;
  692. }
  693. }