ReservationManagementPanel.xaml.cs 31 KB

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