ReservationManagementPanel.xaml.cs 33 KB

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