JobSummaryGrid.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. using com.sun.corba.se.spi.orbutil.threadpool;
  2. using Comal.Classes;
  3. using InABox.Clients;
  4. using InABox.Core;
  5. using InABox.DynamicGrid;
  6. using InABox.WPF;
  7. using InABox.Wpf;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Diagnostics.CodeAnalysis;
  11. using System.Linq;
  12. using System.Linq.Expressions;
  13. using System.Windows;
  14. using System.Windows.Controls;
  15. using System.Windows.Media;
  16. using PRSDesktop.Panels.Jobs.Summary;
  17. namespace PRSDesktop;
  18. internal class JobSummaryGrid : DynamicDataGrid<JobMaterial>, IMasterDetailControl<Job,JobMaterial>, IDataModelSource
  19. {
  20. Guid empID = Guid.Empty;
  21. string empName = "";
  22. private List<DetailsColumn> DetailsColumns;
  23. private Job? _master;
  24. private Button _cancelRequisitions;
  25. private Button _releaseStock;
  26. public Job? Master
  27. {
  28. get => _master;
  29. set
  30. {
  31. _master = value;
  32. _cancelRequisitions.IsEnabled = Master?.JobStatus.Active == false;
  33. }
  34. }
  35. public Filter<JobMaterial> MasterDetailFilter => (Master?.ID ?? Guid.Empty) != Guid.Empty
  36. ? new Filter<JobMaterial>(x => x.Job.ID).IsEqualTo(Master.ID)
  37. .And(x => x.Product.ID).IsNotEqualTo(Guid.Empty)
  38. : new Filter<JobMaterial>().None();
  39. public bool IncludeReserves { get; set; }
  40. public bool ShowIssues { get; set; }
  41. public JobSummaryGrid() : base()
  42. {
  43. ColumnsTag = nameof(JobSummaryGrid);
  44. OnCellDoubleClick += JobSummaryGrid_OnCellDoubleClick;
  45. SetupDetailsColumns();
  46. _cancelRequisitions = AddButton("Cancel Requisitions", PRSDesktop.Resources.archive.AsBitmapImage(),
  47. CancelRequisitions);
  48. _releaseStock = AddButton("Release Stock", PRSDesktop.Resources.archive.AsBitmapImage(),
  49. ReleaseStock);
  50. }
  51. public Dictionary<StockHolding,IEnumerable<JobRequisitionItem>> GetHoldings(CoreRow[] rows)
  52. {
  53. var result = new Dictionary<StockHolding,IEnumerable<JobRequisitionItem>>();
  54. foreach (var row in rows)
  55. {
  56. var material = row.ToObject<JobMaterial>();
  57. var filter = new Filter<StockHolding>(x => x.Product.ID).IsEqualTo(material.Product.ID);
  58. if (StyleColumnVisible())
  59. filter = filter.And(x => x.Style.ID).IsEqualTo(material.Style.ID);
  60. if(DimensionsColumnVisible())
  61. filter = filter.And(x => x.Dimensions).DimensionEquals(material.Dimensions);
  62. var columns = Columns.None<StockHolding>().Add(x => x.Location.ID)
  63. .Add(x => x.Product.ID)
  64. .Add(x => x.Style.ID)
  65. .AddDimensionsColumns(x=>x.Dimensions);
  66. foreach (var holding in new Client<StockHolding>().Query(filter, columns).ToObjects<StockHolding>())
  67. result[holding] = holding.LoadRequisitionItems(true);
  68. }
  69. return result;
  70. }
  71. private bool ReleaseStock(System.Windows.Controls.Button btn, CoreRow[] rows)
  72. {
  73. if (rows?.Any() != true)
  74. return false;
  75. if(MessageWindow.ShowYesNoCancel("This will release any stock holdings for the selected items!\n\nAre you sure you wish to do this? ", "Confirm") != MessageWindowResult.Yes)
  76. return false;
  77. var updates = new List<StockMovement>();
  78. Progress.ShowModal("Loading Holdings", progress =>
  79. {
  80. var holdings = GetHoldings(rows);
  81. foreach (var (holding, items) in holdings)
  82. {
  83. foreach (var item in items)
  84. {
  85. var from = holding.CreateMovement();
  86. //from.OrderItem.ID = group.Key.OrderItem;
  87. from.JobRequisitionItem.ID = item.ID;
  88. from.Cost = StockRelease == StockReleaseWriteDownMethod.AverageCost
  89. ? holding.AverageValue
  90. : 0.0;
  91. from.Type = StockMovementType.TransferOut;
  92. from.Job.ID = Master.ID;
  93. from.Issued = item.Qty;
  94. var to = holding.CreateMovement();
  95. to.Cost = StockRelease == StockReleaseWriteDownMethod.AverageCost
  96. ? holding.AverageValue
  97. : 0.0;
  98. //to.OrderItem.ID = group.Key.OrderItem;
  99. //to.JobRequisitionItem.ID = item.ID;
  100. to.Job.ID = Guid.Empty;
  101. to.Type = StockMovementType.TransferIn;
  102. to.Transaction = from.Transaction;
  103. to.Received = item.Qty;
  104. to.Notes = $"Released from job {Master.JobNumber}";
  105. updates.Add(from);
  106. updates.Add(to);
  107. }
  108. }
  109. progress.Report("Saving Movements");
  110. if (updates.Any())
  111. Client.Save(updates, $"Stock Released from {Master.JobNumber} on Job Summary Screen");
  112. });
  113. MessageWindow.ShowMessage("The selected stock holdings have been cancelled.","Done");
  114. return updates.Any();
  115. }
  116. private bool CancelRequisitions(System.Windows.Controls.Button btn, CoreRow[] rows)
  117. {
  118. if (rows?.Any() != true)
  119. return false;
  120. if(MessageWindow.ShowYesNoCancel("This will cancel all outstanding requisitions for the selected items!\n\nAre you sure you wish to do this? ", "Confirm") != MessageWindowResult.Yes)
  121. return false;
  122. var updates = new List<JobRequisitionItem>();
  123. Progress.ShowModal("Loading Holdings", progress =>
  124. {
  125. var holdings = GetHoldings(rows);
  126. foreach (var holding in holdings)
  127. {
  128. var items = holding.Value.Where(
  129. x => x.ID != Guid.Empty
  130. && x.Status != JobRequisitionItemStatus.Cancelled
  131. && x.Status != JobRequisitionItemStatus.Issued
  132. && x.Status != JobRequisitionItemStatus.Archived
  133. );
  134. foreach (var item in items)
  135. {
  136. item.Cancelled = DateTime.Now;
  137. updates.Add(item);
  138. }
  139. progress.Report("Cancelling Requisitions");
  140. Client.Save(updates, $"Requsition cancelled for {Master.JobNumber} from Job Summary Screen");
  141. }
  142. });
  143. MessageWindow.ShowMessage("The selected requisitions have been cancelled.","Done");
  144. return updates.Any();
  145. }
  146. private class UIComponent : DynamicGridGridUIComponent<JobMaterial>
  147. {
  148. private Column<JobMaterial> _jobshortage = new Column<JobMaterial>(x => x.JobShortage);
  149. private Column<JobMaterial> _stockshortage = new Column<JobMaterial>(x => x.FreeStockShortage);
  150. protected override Brush? GetCellBackground(CoreRow row, DynamicColumnBase column)
  151. {
  152. if (column is DynamicGridColumn col)
  153. {
  154. if (_jobshortage.IsEqualTo(col.ColumnName))
  155. return row.Get<JobMaterial, double>(x => x.JobShortage) > 0.0F
  156. ? new SolidColorBrush(Colors.LightSalmon) { Opacity = 0.5 }
  157. : null;
  158. if (_stockshortage.IsEqualTo(col.ColumnName))
  159. return row.Get<JobMaterial, double>(x => x.FreeStockShortage) > 0.0F
  160. ? new SolidColorBrush(Colors.LightSalmon) { Opacity = 0.5 }
  161. : null;
  162. }
  163. return null;
  164. }
  165. }
  166. protected override IDynamicGridUIComponent<JobMaterial> CreateUIComponent()
  167. {
  168. return new UIComponent()
  169. {
  170. Parent = this
  171. };
  172. }
  173. protected override void Init()
  174. {
  175. base.Init();
  176. HiddenColumns.Add(x => x.Product.ID);
  177. HiddenColumns.Add(x => x.Style.ID);
  178. HiddenColumns.Add(x => x.Dimensions.UnitSize);
  179. HiddenColumns.Add(x => x.BillOfMaterials);
  180. HiddenColumns.Add(x => x.Requisitions);
  181. HiddenColumns.Add(x => x.PickingLists);
  182. HiddenColumns.Add(x => x.Issued);
  183. HiddenColumns.Add(x => x.ReservedStock);
  184. HiddenColumns.Add(x => x.OnOrder);
  185. HiddenColumns.Add(x => x.JobShortage);
  186. HiddenColumns.Add(x => x.FreeOnHand);
  187. HiddenColumns.Add(x => x.FreeOnOrder);
  188. HiddenColumns.Add(x => x.FreeStockTotal);
  189. HiddenColumns.Add(x => x.FreeStockShortage);
  190. HiddenColumns.Add(x => x.Product.Image.ID);
  191. HiddenColumns.Add(x => x.Product.Image.FileName);
  192. ActionColumns.Add(new DynamicImageManagerColumn<JobMaterial>(this, x => x.Product.Image, false)
  193. { Position = DynamicActionColumnPosition.Start });
  194. ActionColumns.Add(new DynamicMenuColumn(BuildMenu));
  195. AddButton("Create PO", null, CreatePO);
  196. }
  197. protected override void DoReconfigure(DynamicGridOptions options)
  198. {
  199. base.DoReconfigure(options);
  200. options.RecordCount = true;
  201. options.SelectColumns = true;
  202. options.FilterRows = true;
  203. options.ExportData = true;
  204. options.MultiSelect = true;
  205. }
  206. private bool StyleColumnVisible()
  207. {
  208. var styleColumn = CoreUtils.GetFullPropertyName<JobMaterial, ProductStyleLink>(x => x.Style, ".");
  209. return VisibleColumns.Any(x => x.ColumnName.StartsWith(styleColumn));
  210. }
  211. private bool DimensionsColumnVisible()
  212. {
  213. var dimColumn = CoreUtils.GetFullPropertyName<JobMaterial, StockDimensions>(x => x.Dimensions, ".");
  214. return VisibleColumns.Any(x => x.ColumnName.StartsWith(dimColumn));
  215. }
  216. public override DynamicGridColumns GenerateColumns()
  217. {
  218. var columns = new DynamicGridColumns();
  219. columns.Add<JobMaterial, string>(x => x.Product.Group.Code, 120, "Group Code", "", Alignment.MiddleCenter);
  220. columns.Add<JobMaterial, string>(x => x.Product.Code, 200, "Product Code", "", Alignment.MiddleCenter);
  221. columns.Add<JobMaterial, string>(x => x.Product.Name, 0, "Product Name", "", Alignment.MiddleCenter);
  222. columns.Add<JobMaterial, string>(x => x.Dimensions.UnitSize, 120, "UOM", "", Alignment.MiddleCenter);
  223. columns.Add<JobMaterial, double>(x => x.BillOfMaterials, 80, "BOM", "", Alignment.MiddleCenter);
  224. columns.Add<JobMaterial, double>(x => x.Requisitions, 80, "Req.", "", Alignment.MiddleCenter);
  225. columns.Add<JobMaterial, double>(x => x.PickingLists, 80, "P/L", "", Alignment.MiddleCenter);
  226. columns.Add<JobMaterial, double>(x => x.Issued, 80, "Issued", "", Alignment.MiddleCenter);
  227. columns.Add<JobMaterial, double>(x => x.ReservedStock, 80, "Reserved", "", Alignment.MiddleCenter);
  228. columns.Add<JobMaterial, double>(x => x.OnOrder, 80, "Ordered", "", Alignment.MiddleCenter);
  229. columns.Add<JobMaterial, double>(x => x.JobShortage, 80, "Job Short", "", Alignment.MiddleCenter);
  230. columns.Add<JobMaterial, double>(x => x.FreeStockTotal, 80, "Free Stock", "", Alignment.MiddleCenter);
  231. columns.Add<JobMaterial, double>(x => x.FreeStockShortage, 80, "Stk Short", "", Alignment.MiddleCenter);
  232. return columns;
  233. }
  234. private void BuildMenu(DynamicMenuColumn column, CoreRow? row)
  235. {
  236. if (row is null) return;
  237. var menu = column.GetMenu();
  238. menu.AddItem("View Stock Movements", PRSDesktop.Resources.forklift, row, ViewStockMovements_Click);
  239. foreach(var col in DetailsColumns)
  240. {
  241. menu.AddItem(col.MenuText, null, row, col.Action);
  242. }
  243. }
  244. private void ViewStockMovements_Click(CoreRow row)
  245. {
  246. var item = row.ToObject<JobMaterial>();
  247. var productID = item.Product.ID;
  248. Guid? styleID = StyleColumnVisible() ? item.Style.ID : null;
  249. var dimensions = DimensionsColumnVisible() ? item.Dimensions : null;
  250. /*ShowDetailGrid<StockMovement>(
  251. args.Column.ColumnName,
  252. x => x.Product.ID,
  253. productid,
  254. x => x.Style.ID,
  255. styleid,
  256. x => x.Dimensions.UnitSize,
  257. unitsize,
  258. x => x.Job.ID,
  259. new Filter<StockMovement>(x => x.IsTransfer).IsEqualTo(false).And(x => x.Issued).IsNotEqualTo(0.0F),
  260. null
  261. );
  262. var movements = Client.Query<StockMovement>(
  263. );*/
  264. var grid = (Activator.CreateInstance(typeof(DynamicDataGrid<>).MakeGenericType(typeof(StockMovement))) as DynamicDataGrid<StockMovement>);
  265. if (grid == null)
  266. {
  267. MessageBox.Show($"Cannot create Grid for [{typeof(StockMovement).Name}]");
  268. return;
  269. }
  270. grid.ColumnsTag = $"{ColumnsTag}.Transactions";
  271. grid.Reconfigure(options =>
  272. {
  273. options.Clear();
  274. options.FilterRows = true;
  275. options.SelectColumns = true;
  276. });
  277. grid.OnReload += (object sender, Filters<StockMovement> criteria, Columns<StockMovement> columns, ref SortOrder<StockMovement>? sortby) =>
  278. {
  279. var filter = criteria.Combine();
  280. criteria.Clear();
  281. criteria.Add(new Filter<StockMovement>(x => x.Transaction).InQuery(filter, x => x.Transaction));
  282. };
  283. grid.OnDefineFilter += t =>
  284. {
  285. var filter = new Filter<StockMovement>(x => x.Product.ID).IsEqualTo(productID);
  286. if(dimensions is not null)
  287. filter = filter.And(x => x.Dimensions).DimensionEquals(dimensions);
  288. if (styleID.HasValue)
  289. filter = filter.And(x => x.Style.ID).IsEqualTo(styleID);
  290. filter = filter.And(x => x.Job.ID).IsEqualTo(Master?.ID ?? Guid.Empty);
  291. return filter;
  292. };
  293. var window = DynamicGridUtils.CreateGridWindow($"Stock Movements", grid);
  294. window.ShowDialog();
  295. }
  296. private void ShowDetailGrid<TEntity>(
  297. String columnname,
  298. Expression<Func<TEntity, object?>> productcol,
  299. Guid productid,
  300. Expression<Func<TEntity, object?>> stylecol,
  301. Guid? styleid,
  302. Expression<Func<TEntity, IDimensions>> dimcol,
  303. IDimensions? dimensions,
  304. Expression<Func<TEntity, object?>>? jobcol,
  305. Filter<TEntity>? extrafilter,
  306. Func<CoreRow, bool>? rowfilter
  307. )
  308. {
  309. var grid = (Activator.CreateInstance(typeof(DynamicDataGrid<>).MakeGenericType(typeof(TEntity))) as IDynamicDataGrid);
  310. if (grid == null)
  311. {
  312. MessageBox.Show($"Cannot create Grid for [{typeof(TEntity).Name}]");
  313. return;
  314. }
  315. grid.ColumnsTag = $"{ColumnsTag}.{columnname}";
  316. grid.Reconfigure(options =>
  317. {
  318. options.Clear();
  319. options.FilterRows = true;
  320. options.SelectColumns = true;
  321. });
  322. grid.OnDefineFilter += t =>
  323. {
  324. var filter = new Filter<TEntity>(productcol).IsEqualTo(productid);
  325. if(dimensions is not null)
  326. filter = filter.And(CoreUtils.GetFullPropertyName(dimcol, ".")).DimensionEquals(dimensions);
  327. if (styleid.HasValue)
  328. filter = filter.And(stylecol).IsEqualTo(styleid);
  329. if (jobcol != null)
  330. filter = filter.And(jobcol).IsEqualTo(Master?.ID ?? Guid.Empty);
  331. if (extrafilter != null)
  332. filter = filter.And(extrafilter);
  333. return filter;
  334. };
  335. grid.OnFilterRecord += row => rowfilter?.Invoke(row) ?? true;
  336. var window = DynamicGridUtils.CreateGridWindow($"Viewing {CoreUtils.Neatify(columnname)} Calculation", grid);
  337. window.ShowDialog();
  338. }
  339. private static readonly Column<JobMaterial> BOMColumn = new Column<JobMaterial>(x => x.BillOfMaterials);
  340. private static readonly Column<JobMaterial> RequisitionsColumn = new Column<JobMaterial>(x => x.Requisitions);
  341. private static readonly Column<JobMaterial> PickingListsColumn = new Column<JobMaterial>(x => x.PickingLists);
  342. private static readonly Column<JobMaterial> IssuedColumn = new Column<JobMaterial>(x => x.Issued);
  343. private static readonly Column<JobMaterial> ReservedStockColumn = new Column<JobMaterial>(x => x.ReservedStock);
  344. private static readonly Column<JobMaterial> OnOrderColumn = new Column<JobMaterial>(x => x.OnOrder);
  345. private static readonly Column<JobMaterial> FreeOnHandColumn = new Column<JobMaterial>(x => x.FreeOnHand);
  346. private static readonly Column<JobMaterial> FreeOnOrderColumn = new Column<JobMaterial>(x => x.FreeOnOrder);
  347. private void ViewBillOfMaterials(CoreRow row)
  348. {
  349. var item = row.ToObject<JobMaterial>();
  350. ShowDetailGrid<JobBillOfMaterialsItem>(
  351. BOMColumn.Property,
  352. x => x.Product.ID,
  353. item.Product.ID,
  354. x => x.Style.ID,
  355. StyleColumnVisible() ? item.Style.ID : null,
  356. x => x.Dimensions,
  357. DimensionsColumnVisible() ? item.Dimensions : null,
  358. x => x.Job.ID,
  359. new Filter<JobBillOfMaterialsItem>(x => x.BillOfMaterials.Approved).IsNotEqualTo(DateTime.MinValue),
  360. null
  361. );
  362. }
  363. private void ViewRequisitions(CoreRow row)
  364. {
  365. var item = row.ToObject<JobMaterial>();
  366. Guid? styleID = StyleColumnVisible() ? item.Style.ID : null;
  367. var dimensions = DimensionsColumnVisible() ? item.Dimensions : null;
  368. var grid = new JobRequisitionItemSummaryGrid();
  369. grid.OnDefineFilter += t =>
  370. {
  371. var filter = new Filter<JobRequisitionItem>(x => x.Product.ID).IsEqualTo(item.Product.ID)
  372. .And(x => x.Requisition.Approved).IsNotEqualTo(DateTime.MinValue)
  373. .And(x => x.Cancelled).IsEqualTo(DateTime.MinValue);
  374. if(dimensions is not null)
  375. {
  376. filter = filter.And(x => x.Dimensions).DimensionEquals(item.Dimensions);
  377. }
  378. if (styleID.HasValue)
  379. {
  380. filter = filter.And(x => x.Style.ID).IsEqualTo(styleID.Value);
  381. }
  382. filter = filter.And(x => x.Requisition.Job.ID).IsEqualTo(Master?.ID ?? Guid.Empty);
  383. return filter;
  384. };
  385. var window = DynamicGridUtils.CreateGridWindow($"Viewing Requisition Calculation", grid);
  386. window.ShowDialog();
  387. }
  388. private void ViewPickingLists(CoreRow row)
  389. {
  390. var item = row.ToObject<JobMaterial>();
  391. ShowDetailGrid<RequisitionItem>(
  392. PickingListsColumn.Property,
  393. x => x.Product.ID,
  394. item.Product.ID,
  395. x => x.Style.ID,
  396. StyleColumnVisible() ? item.Style.ID : null,
  397. x => x.Dimensions,
  398. DimensionsColumnVisible() ? item.Dimensions : null,
  399. x => x.JobLink.ID,
  400. new Filter<RequisitionItem>(x => x.RequisitionLink.Filled).IsEqualTo(DateTime.MinValue),
  401. null
  402. );
  403. }
  404. private void ViewIssued(CoreRow row)
  405. {
  406. var item = row.ToObject<JobMaterial>();
  407. ShowDetailGrid<StockMovement>(
  408. IssuedColumn.Property,
  409. x => x.Product.ID,
  410. item.Product.ID,
  411. x => x.Style.ID,
  412. StyleColumnVisible() ? item.Style.ID : null,
  413. x => x.Dimensions,
  414. DimensionsColumnVisible() ? item.Dimensions : null,
  415. x => x.Job.ID,
  416. new Filter<StockMovement>(x => x.Type).IsEqualTo(StockMovementType.Issue),
  417. null
  418. );
  419. }
  420. private void ViewReservedStock(CoreRow row)
  421. {
  422. var item = row.ToObject<JobMaterial>();
  423. ShowDetailGrid<StockHolding>(
  424. ReservedStockColumn.Property,
  425. x => x.Product.ID,
  426. item.Product.ID,
  427. x => x.Style.ID,
  428. StyleColumnVisible() ? item.Style.ID : null,
  429. x => x.Dimensions,
  430. DimensionsColumnVisible() ? item.Dimensions : null,
  431. x => x.Job.ID,
  432. new Filter<StockHolding>(x => x.Units).IsGreaterThan(0.1),
  433. null
  434. );
  435. }
  436. private void ViewOnOrder(CoreRow row)
  437. {
  438. var item = row.ToObject<JobMaterial>();
  439. ShowDetailGrid<PurchaseOrderItem>(
  440. OnOrderColumn.Property,
  441. x => x.Product.ID,
  442. item.Product.ID,
  443. x => x.Style.ID,
  444. StyleColumnVisible() ? item.Style.ID : null,
  445. x => x.Dimensions,
  446. DimensionsColumnVisible() ? item.Dimensions : null,
  447. x => x.Job.ID,
  448. null,
  449. null
  450. );
  451. }
  452. private void ViewFreeOnHand(CoreRow row)
  453. {
  454. var item = row.ToObject<JobMaterial>();
  455. ShowDetailGrid<StockHolding>(
  456. FreeOnHandColumn.Property,
  457. x => x.Product.ID,
  458. item.Product.ID,
  459. x => x.Style.ID,
  460. StyleColumnVisible() ? item.Style.ID : null,
  461. x => x.Dimensions,
  462. DimensionsColumnVisible() ? item.Dimensions : null,
  463. null,
  464. new Filter<StockHolding>(x => x.Units).IsNotEqualTo(0.0F)
  465. .And(
  466. IncludeReserves
  467. ? new Filter<StockHolding>(x => x.Job.ID).IsNotEqualTo(Master?.ID ?? Guid.Empty)
  468. : new Filter<StockHolding>(x => x.Job.JobStatus.Active).IsEqualTo(false)
  469. ),
  470. null
  471. );
  472. }
  473. private void ViewFreeOnOrder(CoreRow row)
  474. {
  475. var item = row.ToObject<JobMaterial>();
  476. ShowDetailGrid<PurchaseOrderItem>(
  477. FreeOnOrderColumn.Property,
  478. x => x.Product.ID,
  479. item.Product.ID,
  480. x => x.Style.ID,
  481. StyleColumnVisible() ? item.Style.ID : null,
  482. x => x.Dimensions,
  483. DimensionsColumnVisible() ? item.Dimensions : null,
  484. null,
  485. IncludeReserves
  486. ? new Filter<PurchaseOrderItem>(x => x.Job.ID).IsNotEqualTo(Master?.ID ?? Guid.Empty)
  487. : new Filter<PurchaseOrderItem>(x => x.Job.JobStatus.Active).IsEqualTo(false),
  488. null
  489. );
  490. }
  491. [MemberNotNull(nameof(DetailsColumns))]
  492. private void SetupDetailsColumns()
  493. {
  494. DetailsColumns = new List<DetailsColumn>
  495. {
  496. new(BOMColumn, ViewBillOfMaterials, "View bill of materials"),
  497. new(RequisitionsColumn, ViewRequisitions, "View requisitions"),
  498. new(PickingListsColumn, ViewPickingLists, "View picking lists"),
  499. new(IssuedColumn, ViewIssued, "View issued"),
  500. new(ReservedStockColumn, ViewReservedStock, "View reserved stock"),
  501. new(OnOrderColumn, ViewOnOrder, "View on order"),
  502. new(FreeOnHandColumn, ViewFreeOnHand, "View free on hand"),
  503. new(FreeOnOrderColumn, ViewFreeOnOrder, "View free on order"),
  504. };
  505. }
  506. private class DetailsColumn
  507. {
  508. public Column<JobMaterial> Column { get; set; }
  509. public Action<CoreRow> Action { get; set; }
  510. public string MenuText { get; set; }
  511. public DetailsColumn(Column<JobMaterial> column, Action<CoreRow> action, string menuText)
  512. {
  513. Column = column;
  514. Action = action;
  515. MenuText = menuText;
  516. }
  517. }
  518. private void JobSummaryGrid_OnCellDoubleClick(object sender, DynamicGridCellClickEventArgs args)
  519. {
  520. if (args?.Column is DynamicGridColumn col)
  521. {
  522. foreach (var column in DetailsColumns)
  523. {
  524. if (column.Column.IsEqualTo(col.ColumnName))
  525. {
  526. column.Action(args.Row);
  527. break;
  528. }
  529. }
  530. }
  531. }
  532. public event DataModelUpdateEvent? OnUpdateDataModel;
  533. public string SectionName => "Job Summary";
  534. public StockReleaseWriteDownMethod StockRelease { get; set; }
  535. public DataModel DataModel(Selection selection)
  536. {
  537. return new AutoDataModel<JobMaterial>(MasterDetailFilter);
  538. }
  539. public override JobMaterial CreateItem()
  540. {
  541. var result = base.CreateItem();
  542. result.Job.ID = Master?.ID ?? Guid.Empty;
  543. result.Job.Synchronise(Master ?? new Job());
  544. return result;
  545. }
  546. private class Key(Guid jobID, Guid productID, Guid? styleID, IDimensions? dimensions)
  547. {
  548. public Guid JobID { get; set; } = jobID;
  549. public Guid ProductID { get; set; } = productID;
  550. public Guid? StyleID { get; set; } = styleID;
  551. public IDimensions? Dimensions { get; set; } = dimensions;
  552. public override bool Equals(object? obj)
  553. {
  554. return obj is Key key
  555. && JobID == key.JobID
  556. && ProductID == key.ProductID
  557. && StyleID == key.StyleID
  558. && Equals(Dimensions, key.Dimensions);
  559. }
  560. public override int GetHashCode()
  561. {
  562. return HashCode.Combine(
  563. JobID, ProductID, StyleID, Dimensions);
  564. }
  565. }
  566. private Key[] GetKeys(IEnumerable<CoreRow> rows, Columns<JobMaterial> columns, bool hasstyle, bool hasDimensions)
  567. {
  568. int jobcol = columns.IndexOf(x => x.Job.ID);
  569. int productcol = columns.IndexOf(x => x.Product.ID);
  570. int stylecol = hasstyle ? columns.IndexOf(x => x.Style.ID) : -1;
  571. var dimCols = hasDimensions ? Dimensions.GetFilterColumnIndices<JobMaterial>(columns, x => x.Dimensions) : null;
  572. var result = rows.Select(r => new Key(
  573. (Guid)(r.Values[jobcol] ?? Guid.Empty),
  574. (Guid)(r.Values[productcol] ?? Guid.Empty),
  575. (stylecol != -1) ? (Guid)(r.Values[stylecol] ?? Guid.Empty) : null,
  576. dimCols is not null ? r.ToDimensions<StockDimensions>(dimCols) : null)
  577. ).Distinct().ToArray();
  578. return result;
  579. }
  580. private CoreRow[] GetRows<TSource>(IEnumerable<CoreRow> rows, Columns<TSource> columns, Guid? jobID, Key key, Func<CoreRow, bool>? extrafilter = null) where TSource : IJobMaterial
  581. {
  582. int jobcol = columns.IndexOf(x => x.Job.ID);
  583. int productcol = columns.IndexOf(x => x.Product.ID);
  584. int stylecol = key.StyleID.HasValue ? columns.IndexOf(x => x.Style.ID) : -1;
  585. int unitcol = columns.IndexOf(x => x.Dimensions.UnitSize);
  586. var dimCols = Dimensions.GetFilterColumnIndices<TSource>(columns, x => x.Dimensions);
  587. var subset = rows
  588. .Where(r =>
  589. (!jobID.HasValue || Guid.Equals(jobID, r.Values[jobcol]))
  590. && Guid.Equals(key.ProductID, r.Values[productcol])
  591. && (!key.StyleID.HasValue || Guid.Equals(key.StyleID, r.Values[stylecol]))
  592. && (key.Dimensions is null || key.Dimensions.Equals(r.ToDimensions<StockDimensions>(dimCols)))
  593. && ((extrafilter == null) || extrafilter(r))
  594. );
  595. return subset.ToArray();
  596. }
  597. private double Aggregate<TSource>(IEnumerable<CoreRow> rows, Columns<TSource> columns, bool hasstyle, bool hasjob, Expression<Func<TSource, object>> source, CoreRow target, Expression<Func<JobMaterial, object>> aggregate)
  598. {
  599. int srcol = columns.IndexOf(source);
  600. if (srcol == -1)
  601. return 0.00;
  602. var total = rows.Aggregate(0d, (value, row) => value + (double)(row.Values[srcol] ?? 0.0d));
  603. target.Set(aggregate, total);
  604. return total;
  605. }
  606. protected override void Reload(Filters<JobMaterial> criteria, Columns<JobMaterial> columns, ref SortOrder<JobMaterial>? sort,
  607. Action<CoreTable?, Exception?> action)
  608. {
  609. criteria.Add(MasterDetailFilter);
  610. criteria.Add(FilterComponent.GetFilter());
  611. var orderby = sort;
  612. Progress.ShowModal("Loading Data",
  613. (progress) =>
  614. {
  615. var table = new CoreTable();
  616. table.LoadColumns(columns);
  617. var data = new Client<JobMaterial>().Query(criteria.Combine(), columns, orderby);
  618. var pids = data.ExtractValues<JobMaterial, Guid>(x => x.Product.ID).ToArray();
  619. if (pids.Any())
  620. {
  621. var results = Client.QueryMultiple(
  622. new KeyedQueryDef<StockHolding>(
  623. new Filter<StockHolding>(x => x.Product.ID).InList(pids)
  624. .And(x => x.Units).IsNotEqualTo(0.0F)
  625. .And(new Filter<StockHolding>(x => x.Job.ID).IsEqualTo(Guid.Empty).Or(x => x.Job.ID).IsNotEqualTo(Master?.ID ?? Guid.Empty)),
  626. Columns.None<StockHolding>().Add(x => x.Product.ID)
  627. .Add(x => x.Style.ID)
  628. .AddDimensionsColumns(x => x.Dimensions, Dimensions.ColumnsType.Local)
  629. .Add(x => x.Units)
  630. .Add(x => x.Job.ID)
  631. .Add(x => x.Job.JobStatus.Active)),
  632. new KeyedQueryDef<PurchaseOrderItem>(
  633. new Filter<PurchaseOrderItem>(x => x.ReceivedDate).IsEqualTo(DateTime.MinValue)
  634. .And(x => x.Product.ID).InList(pids)
  635. .And(new Filter<PurchaseOrderItem>(x => x.Job.ID).IsEqualTo(Guid.Empty).Or(x => x.Job.ID).IsNotEqualTo(Master?.ID ?? Guid.Empty)),
  636. Columns.None<PurchaseOrderItem>().Add(x => x.Product.ID)
  637. .Add(x => x.Style.ID)
  638. .AddDimensionsColumns(x => x.Dimensions, Dimensions.ColumnsType.Local)
  639. .Add(x => x.Qty)
  640. .Add(x => x.Job.ID)
  641. .Add(x => x.Job.JobStatus.Active)));
  642. var freestock = results.Get<StockHolding>();
  643. var freestockcolumns = Columns.None<StockHolding>().Add(freestock.Columns.Select(x => x.ColumnName));
  644. var freeorders = results.Get<PurchaseOrderItem>();
  645. var freeordercolumns = Columns.None<PurchaseOrderItem>().Add(freeorders.Columns.Select(x => x.ColumnName));
  646. var hasStyle = StyleColumnVisible();
  647. var hasDimensions = DimensionsColumnVisible();
  648. var keys = GetKeys(data.Rows, columns, hasStyle, hasDimensions);
  649. foreach (var key in keys)
  650. {
  651. var rows = GetRows(data.Rows, columns, key.JobID, key);
  652. if (rows.Any())
  653. {
  654. CoreRow newrow = table.NewRow();
  655. newrow.LoadValues(rows.First().Values);
  656. var bom = Aggregate(rows, columns, hasStyle, true, x => x.BillOfMaterials, newrow,
  657. x => x.BillOfMaterials);
  658. var requi = Aggregate(rows, columns, hasStyle, true, x => x.Requisitions, newrow, x => x.Requisitions);
  659. var picklist = Aggregate(rows, columns, hasStyle, true, x => x.PickingLists, newrow,
  660. x => x.PickingLists);
  661. var issued = Aggregate(rows, columns, hasStyle, true, x => x.Issued, newrow, x => x.Issued);
  662. var reserved = Aggregate(rows, columns, hasStyle, true, x => x.ReservedStock, newrow,
  663. x => x.ReservedStock);
  664. var ordered = Aggregate(rows, columns, hasStyle, true, x => x.OnOrder, newrow, x => x.OnOrder);
  665. var shortage = Math.Max(0, Math.Max(0, (requi - issued)) - (reserved + ordered));
  666. newrow.Set<JobMaterial, double>(x => x.JobShortage, shortage);
  667. var freestockrows = GetRows(freestock.Rows, freestockcolumns, null, key,
  668. IncludeReserves ? null : (r) => !r.Get<StockHolding, bool>(x => x.Job.JobStatus.Active));
  669. var freeonhand = Aggregate(freestockrows, freestockcolumns, hasStyle, false, x => x.Units, newrow,
  670. x => x.FreeOnHand);
  671. newrow.Set<JobMaterial, double>(x => x.FreeOnHand, freeonhand);
  672. var freeorderrows = GetRows(freeorders.Rows, freeordercolumns, null, key,
  673. IncludeReserves ? null : (r) => !r.Get<PurchaseOrderItem, bool>(x => x.Job.JobStatus.Active));
  674. var freeonorder = Aggregate(freeorderrows, freeordercolumns, hasStyle, false, x => x.Qty, newrow,
  675. x => x.FreeOnOrder);
  676. newrow.Set<JobMaterial, double>(x => x.FreeOnOrder, freeonorder);
  677. newrow.Set<JobMaterial, double>(x => x.FreeStockTotal, freeonhand + freeonorder);
  678. newrow.Set<JobMaterial, double>(x => x.FreeStockShortage, Math.Max(0, shortage - (freeonhand + freeonorder)));
  679. table.Rows.Add(newrow);
  680. }
  681. }
  682. }
  683. action?.Invoke(table, null);
  684. }
  685. );
  686. }
  687. protected override bool FilterRecord(CoreRow row)
  688. {
  689. var result = base.FilterRecord(row)
  690. && (
  691. row.Get<JobMaterial, double>(x => x.BillOfMaterials) != 0.0F ||
  692. row.Get<JobMaterial, double>(x => x.Requisitions) != 0.0F ||
  693. row.Get<JobMaterial, double>(x => x.PickingLists) != 0.0F ||
  694. row.Get<JobMaterial, double>(x => x.Issued) != 0.0F ||
  695. row.Get<JobMaterial, double>(x => x.ReservedStock) != 0.0F ||
  696. row.Get<JobMaterial, double>(x => x.OnOrder) != 0.0F
  697. );
  698. if (ShowIssues)
  699. {
  700. result = result && (
  701. row.Get<JobMaterial, double>(x => x.JobShortage) > 0.0F ||
  702. row.Get<JobMaterial, double>(x => x.FreeStockShortage) > 0.0F);
  703. }
  704. return result;
  705. }
  706. #region Create PO
  707. private bool CreatePO(System.Windows.Controls.Button btn, CoreRow[] rows)
  708. {
  709. if (!rows.Any())
  710. {
  711. MessageBox.Show("Please select at least one row to add to PO");
  712. return false;
  713. }
  714. PurchaseOrder purchaseOrder = new PurchaseOrder();
  715. purchaseOrder.Description = "Created from Job Summary Screen" + System.Environment.NewLine;
  716. purchaseOrder.RaisedBy.ID = empID;
  717. var page = new SupplierPurchaseOrders();
  718. page.OnAfterSave += (form, items) =>
  719. {
  720. MessageBox.Show("Success - New Purchase Order Created (" + purchaseOrder.PONumber + ")");
  721. };
  722. return page.EditItems(new[] { purchaseOrder }, LoadPurchaseOrderItems, true);
  723. }
  724. private CoreTable LoadPurchaseOrderItems(Type arg)
  725. {
  726. Progress.Show("Working");
  727. var result = new CoreTable();
  728. result.LoadColumns(typeof(PurchaseOrderItem));
  729. List<PurchaseOrderItem> items = new List<PurchaseOrderItem>();
  730. foreach (CoreRow row in SelectedRows)
  731. {
  732. JobMaterial material = row.ToObject<JobMaterial>();
  733. PurchaseOrderItem POItem = new PurchaseOrderItem();
  734. POItem.Product.ID = material.Product.ID;
  735. POItem.Product.Code = material.Product.Code;
  736. POItem.Product.Name = material.Product.Name;
  737. POItem.Description = material.Product.Name;
  738. POItem.Qty = 0;
  739. POItem.Dimensions.CopyFrom(material.Dimensions);
  740. POItem.Style.ID = material.Style.ID;
  741. POItem.Style.Code = material.Style.Code;
  742. POItem.Style.Description = material.Style.Description;
  743. POItem.Job.ID = material.Job.ID;
  744. POItem.Dimensions.UnitSize = material.Dimensions.UnitSize;
  745. items.Add(POItem);
  746. }
  747. result.LoadRows(items);
  748. Progress.Close();
  749. return result;
  750. }
  751. #endregion
  752. }