StagingPanel.xaml.cs 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  1. using Comal.Classes;
  2. using Comal.Classes;
  3. using InABox.Core;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Windows;
  8. using System.Windows.Controls;
  9. using InABox.Clients;
  10. using InABox.Configuration;
  11. using InABox.DynamicGrid;
  12. using System.Diagnostics;
  13. using System.IO;
  14. using InABox.WPF;
  15. using System.ComponentModel;
  16. using InABox.Scripting;
  17. using System.Reflection;
  18. using System.Collections.Immutable;
  19. using FastReport.Data;
  20. using Microsoft.Xaml.Behaviors.Core;
  21. using StagingManufacturingPacketComponent = Comal.Classes.StagingManufacturingPacketComponent;
  22. using System.Threading.Tasks;
  23. namespace PRSDesktop
  24. {
  25. [Caption("Staging Panel Settings")]
  26. public class StagingPanellSettings : BaseObject, IGlobalConfigurationSettings
  27. {
  28. [Caption("PDF Markup Program Pathway", IncludePath = false)]
  29. [FileNameEditor]
  30. public string MarkupPathway { get; set; }
  31. [FolderEditor(Environment.SpecialFolder.CommonDocuments)]
  32. public string SetoutsFolder { get; set; }
  33. [ScriptEditor]
  34. public string? Script { get; set; }
  35. public StagingPanellSettings()
  36. {
  37. MarkupPathway = "";
  38. SetoutsFolder = "";
  39. Script = null;
  40. }
  41. public string DefaultScript()
  42. {
  43. return @"
  44. using PRSDesktop;
  45. using InABox.Core;
  46. using System.Collections.Generic;
  47. public class Module
  48. {
  49. /*public void CustomiseSetouts(CustomiseSetoutsArgs args)
  50. {
  51. // Perform customisation on the setouts when they are added to the 'Staged Documents' grid.
  52. }*/
  53. }";
  54. }
  55. }
  56. public class CustomiseSetoutsArgs
  57. {
  58. public IReadOnlyList<Tuple<StagingSetout, Document>> Setouts;
  59. public CustomiseSetoutsArgs(IReadOnlyList<Tuple<StagingSetout, Document>> setouts)
  60. {
  61. Setouts = setouts;
  62. }
  63. }
  64. /// <summary>
  65. /// Interaction logic for StagingPanel.xaml
  66. /// </summary>
  67. public partial class StagingPanel : UserControl, IPanel<StagingSetout>
  68. {
  69. private StagingPanellSettings _settings = new StagingPanellSettings();
  70. /// <summary>
  71. /// The currently selected setout.
  72. /// </summary>
  73. private StagingSetout? selectedSetout;
  74. /// <summary>
  75. /// All currently selected setouts; <see cref="selectedSetout"/> will be a member of this list.
  76. /// </summary>
  77. private List<StagingSetout> selectedSetouts = new();
  78. private CoreTable _templateGroups = null!;
  79. #region Script Stuff
  80. private MethodInfo? _customiseSetoutsMethod;
  81. private MethodInfo? CustomiseSetoutsMethod
  82. {
  83. get
  84. {
  85. EnsureScript();
  86. return _customiseSetoutsMethod;
  87. }
  88. }
  89. private object? _scriptObject;
  90. private object? ScriptObject
  91. {
  92. get
  93. {
  94. EnsureScript();
  95. return _scriptObject;
  96. }
  97. }
  98. private ScriptDocument? _script;
  99. private ScriptDocument? Script
  100. {
  101. get
  102. {
  103. EnsureScript();
  104. return _script;
  105. }
  106. }
  107. private void EnsureScript()
  108. {
  109. if (_script is null && !_settings.Script.IsNullOrWhiteSpace())
  110. {
  111. _script = new ScriptDocument(_settings.Script);
  112. if (!_script.Compile())
  113. {
  114. throw new Exception("Script in Staging Panel Settings failed to compile!");
  115. }
  116. _scriptObject = _script?.GetObject();
  117. _customiseSetoutsMethod = _script?.GetMethod(methodName: "CustomiseSetouts");
  118. }
  119. }
  120. #endregion
  121. public StagingPanel()
  122. {
  123. InitializeComponent();
  124. SectionName = nameof(StagingPanel);
  125. }
  126. public void Setup()
  127. {
  128. _settings = new GlobalConfiguration<StagingPanellSettings>().Load();
  129. _templateGroups = new Client<ManufacturingTemplateGroup>().Query();
  130. MarkUpButton.Visibility = Security.IsAllowed<CanMarkUpSetouts>() ? Visibility.Visible : Visibility.Hidden;
  131. RejectButton.Visibility = Security.IsAllowed<CanApproveSetouts>() ? Visibility.Visible : Visibility.Hidden;
  132. ApproveButton.Visibility = Security.IsAllowed<CanApproveSetouts>() ? Visibility.Visible : Visibility.Hidden;
  133. ProcessButton.Visibility = Security.IsAllowed<CanApproveSetouts>() ? Visibility.Visible : Visibility.Hidden;
  134. //stagingSetoutGrid.ScanFiles(_settings.SetoutsFolder);
  135. stagingSetoutGrid.Refresh(true, false);
  136. SetoutComponentGrid.Refresh(true, false);
  137. }
  138. private bool CanViewPackets() => MainPanel.View != DynamicSplitPanelView.Master && NestedPanel.View != DynamicSplitPanelView.Master;
  139. private void NestedPanel_OnChanged(object sender, DynamicSplitPanelSettings e)
  140. {
  141. if(CanViewPackets())
  142. {
  143. ManufacturingPacketList.Setout = selectedSetout;
  144. SetoutComponentGrid.StagingSetout = selectedSetout;
  145. }
  146. }
  147. #region Document Viewer
  148. public enum DocumentMode
  149. {
  150. Markup,
  151. Complete,
  152. Locked
  153. }
  154. private DocumentMode _mode;
  155. private DocumentMode Mode
  156. {
  157. get => _mode;
  158. set => SetMode(value);
  159. }
  160. private void SetMode(DocumentMode mode)
  161. {
  162. _mode = mode;
  163. if (_mode == DocumentMode.Markup)
  164. {
  165. MarkUpButton.Content = "Mark Up";
  166. MarkUpButton.IsEnabled = Document != null && !Document.Approved;
  167. UpdateOriginalButton.Visibility =
  168. Document != null && !String.Equals(Document.DocumentLink.CRC, selectedSetout?.OriginalCRC)
  169. ? Visibility.Visible
  170. : Visibility.Collapsed;
  171. ProcessButton.IsEnabled = Document != null && Document.Approved;
  172. RejectButton.IsEnabled = Document != null && !Document.Approved;
  173. ApproveButton.IsEnabled = Document != null;
  174. }
  175. else if (_mode == DocumentMode.Complete)
  176. {
  177. MarkUpButton.Content = "Complete";
  178. MarkUpButton.IsEnabled = Document != null;
  179. UpdateOriginalButton.Visibility = Visibility.Collapsed;
  180. ProcessButton.IsEnabled = false;
  181. RejectButton.IsEnabled = false;
  182. ApproveButton.IsEnabled = false;
  183. }
  184. else if (_mode == DocumentMode.Locked)
  185. {
  186. MarkUpButton.Content = "Locked";
  187. MarkUpButton.IsEnabled = false;
  188. UpdateOriginalButton.Visibility = Visibility.Collapsed;
  189. ProcessButton.IsEnabled = false;
  190. RejectButton.IsEnabled = false;
  191. ApproveButton.IsEnabled = false;
  192. }
  193. }
  194. private StagingSetoutDocument? _document;
  195. private StagingSetoutDocument? Document
  196. {
  197. get => _document;
  198. set
  199. {
  200. _document = value;
  201. if(_document is not null)
  202. {
  203. ApproveButton.Content = _document.Approved ? "Unapprove" : "Approve";
  204. }
  205. }
  206. }
  207. private byte[]? _documentdata = null;
  208. private void ClearDocuments()
  209. {
  210. Document = null;
  211. RenderDocuments(null);
  212. }
  213. private List<byte[]>? GetDocuments(StagingSetoutDocument? document)
  214. {
  215. if(document is null)
  216. {
  217. return null;
  218. }
  219. var table = new Client<Document>().Query(
  220. new Filter<Document>(x => x.ID).IsEqualTo(document.DocumentLink.ID),
  221. new Columns<Document>(x => x.Data));
  222. var first = table.Rows.FirstOrDefault();
  223. if (first is null)
  224. return null;
  225. _documentdata = first.Get<Document, byte[]>(x => x.Data);
  226. return ImageUtils.RenderPDFToImages(_documentdata);
  227. }
  228. private void RenderDocuments(List<byte[]>? documents)
  229. {
  230. DocumentViewer.Children.Clear();
  231. if(documents is not null)
  232. {
  233. foreach (var image in documents)
  234. {
  235. DocumentViewer.Children.Add(new Image
  236. {
  237. Source = ImageUtils.LoadImage(image),
  238. Margin = new Thickness(0, 0, 0, 20)
  239. });
  240. }
  241. }
  242. }
  243. private void ProcessButton_Click(object sender, RoutedEventArgs e)
  244. {
  245. bool bulkApprove = false;
  246. if (selectedSetouts.Count > 1)
  247. {
  248. if (MessageBox.Show("Bulk approve? (Skip individual setout approval)", "Continue?", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
  249. {
  250. bulkApprove = true;
  251. Progress.Show("Approving Setouts..");
  252. }
  253. }
  254. if(selectedSetouts.Any(x => x.UnapprovedDocuments > 0))
  255. {
  256. MessageBox.Show("Cannot process setouts with unapproved documents.");
  257. Progress.Close();
  258. return;
  259. }
  260. if (selectedSetouts.Any(x => x.JobLink.ID == Guid.Empty))
  261. {
  262. MessageBox.Show("Cannot process setout without a linked job.");
  263. Progress.Close();
  264. return;
  265. }
  266. if (ManufacturingPacketList.Packets.Any(x => x.Template.ID == Guid.Empty))
  267. {
  268. MessageBox.Show("Cannot process manufacturing packets without templates.");
  269. Progress.Close();
  270. return;
  271. }
  272. if(selectedSetouts.Any(x => x.Packets == 0))
  273. {
  274. if(MessageBox.Show("Warning: some setouts do not have any manufacturing packets: are you sure you wish to proceed?", "Warning", MessageBoxButton.YesNoCancel) != MessageBoxResult.Yes)
  275. {
  276. Progress.Close();
  277. return;
  278. }
  279. }
  280. string message = "Result: " + Environment.NewLine;
  281. foreach (var item in selectedSetouts)
  282. {
  283. if (bulkApprove)
  284. Progress.Show("Working on " + item.Number);
  285. var returnstring = ApproveSetout(item, bulkApprove);
  286. if (!string.IsNullOrWhiteSpace(returnstring))
  287. message = message + returnstring + Environment.NewLine;
  288. }
  289. if (bulkApprove)
  290. Progress.Close();
  291. new Client<StagingSetout>().Save(selectedSetouts, "Updated from staging screen");
  292. selectedSetout = null;
  293. Refresh();
  294. MessageBox.Show(message);
  295. MainPanel.View = DynamicSplitPanelView.Combined;
  296. NestedPanel.View = DynamicSplitPanelView.Master;
  297. }
  298. private string ApproveSetout(StagingSetout item, bool bulkapprove)
  299. {
  300. if (item.Group.ID == Guid.Empty)
  301. {
  302. var message = "Setout has no group assigned";
  303. if (Security.IsAllowed<CanApproveSetoutsWithoutGroup>())
  304. {
  305. if (MessageBox.Show(message + ", continue?", "Continue?", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
  306. return "";
  307. }
  308. else
  309. {
  310. MessageBox.Show(message + ", please assign a group!");
  311. return "";
  312. }
  313. }
  314. var setoutDocument = new Client<StagingSetoutDocument>()
  315. .Query(
  316. new Filter<StagingSetoutDocument>(x => x.EntityLink.ID).IsEqualTo(item.ID),
  317. new Columns<StagingSetoutDocument>(x => x.ID, x => x.DocumentLink.ID, x => x.DocumentLink.FileName))
  318. .ToObjects<StagingSetoutDocument>().FirstOrDefault();
  319. if (setoutDocument is null)
  320. return "";
  321. var setout = new Client<Setout>()
  322. .Query(
  323. new Filter<Setout>(x => x.Number).IsEqualTo(item.Number),
  324. new Columns<Setout>(x => x.ID))
  325. .ToObjects<Setout>().FirstOrDefault();
  326. string result;
  327. //setout already exists - create new setoutdoc and supercede old ones
  328. if (setout is not null)
  329. {
  330. if (!bulkapprove)
  331. if (MessageBox.Show("Supercede existing documents?", "Proceed?", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
  332. return "";
  333. setout.Group.ID = item.Group.ID;
  334. item.Setout.ID = setout.ID;
  335. var setoutdoc = new SetoutDocument();
  336. setoutdoc.EntityLink.ID = setout.ID;
  337. setoutdoc.DocumentLink.ID = setoutDocument.DocumentLink.ID;
  338. var setoutdocs = new List<SetoutDocument>
  339. {
  340. setoutdoc
  341. };
  342. CoreTable oldDocsTable = new Client<SetoutDocument>().Query(
  343. new Filter<SetoutDocument>(x => x.EntityLink.ID).IsEqualTo((Guid)setout.ID)
  344. .And(x => x.DocumentLink.ID).IsNotEqualTo(item.Group.OptimizationDocument.ID)
  345. );
  346. foreach (var row in oldDocsTable.Rows)
  347. {
  348. var oldDoc = row.ToObject<SetoutDocument>();
  349. if (oldDoc.Superceded == DateTime.MinValue)
  350. {
  351. oldDoc.Superceded = DateTime.Now;
  352. setoutdocs.Add(oldDoc);
  353. }
  354. }
  355. new Client<SetoutDocument>().Save(setoutdocs, "Updated from Staging Screen");
  356. new Client<Setout>().Save((Setout)setout, "Updated from Staging Screen");
  357. result = item.Number + " Superceded";
  358. }
  359. //no setout for this pdf - create new
  360. else
  361. {
  362. setout = new Setout
  363. {
  364. Number = item.Number
  365. };
  366. setout.JobLink.ID = item.JobLink.ID;
  367. setout.Group.ID = item.Group.ID;
  368. var editor = new DynamicDataGrid<Setout>();
  369. editor.OnAfterSave += (editor, items) =>
  370. {
  371. CreateSetoutDocument(setout, item, setoutDocument);
  372. };
  373. if (!bulkapprove)
  374. {
  375. if (!editor.EditItems(new[] { setout }))
  376. {
  377. MessageBox.Show("Setout Creation Cancelled");
  378. return "";
  379. }
  380. else
  381. result = item.Number + " Created";
  382. }
  383. else
  384. {
  385. new Client<Setout>().Save(setout, "Added from staging screen");
  386. CreateSetoutDocument(setout, item, setoutDocument);
  387. result = item.Number + " Created";
  388. }
  389. }
  390. var tuples = new List<Tuple<ManufacturingPacket, StagingManufacturingPacket>>();
  391. var stagingPackets = new Client<StagingManufacturingPacket>()
  392. .Query(
  393. new Filter<StagingManufacturingPacket>(x => x.StagingSetout.ID).IsEqualTo(item.ID),
  394. new Columns<StagingManufacturingPacket>(x => x.ID)
  395. .Add(x => x.Serial)
  396. .Add(x => x.Title)
  397. .Add(x => x.Quantity)
  398. .Add(x => x.BarcodeQuantity)
  399. .Add(x => x.Watermark)
  400. .Add(x => x.Group.Watermark)
  401. .Add(x => x.Location)
  402. .Add(x => x.ITP.ID)
  403. .Add(x => x.Job.ID)
  404. .Add(x => x.Template.ID));
  405. foreach(var stagingPacket in stagingPackets.ToObjects<StagingManufacturingPacket>())
  406. {
  407. if(stagingPacket.ManufacturingPacket.ID != Guid.Empty)
  408. {
  409. MessageBox.Show($"A manufacturing packet already exists for {stagingPacket.Serial}; skipping packet.");
  410. continue;
  411. }
  412. var packet = new ManufacturingPacket
  413. {
  414. Serial = stagingPacket.Serial,
  415. Title = stagingPacket.Title,
  416. Quantity = stagingPacket.Quantity,
  417. BarcodeQty = string.IsNullOrWhiteSpace(stagingPacket.BarcodeQuantity)
  418. ? stagingPacket.Quantity
  419. : int.Parse(stagingPacket.BarcodeQuantity),
  420. WaterMark = string.IsNullOrWhiteSpace(stagingPacket.Watermark)
  421. ? stagingPacket.Group.Watermark
  422. : stagingPacket.Watermark,
  423. Location = stagingPacket.Location
  424. };
  425. packet.SetoutLink.ID = setout.ID;
  426. packet.ITP.ID = stagingPacket.ITP.ID;
  427. packet.JobLink.ID = stagingPacket.Job.ID;
  428. packet.ManufacturingTemplateLink.ID = stagingPacket.Template.ID;
  429. tuples.Add(new(packet, stagingPacket));
  430. }
  431. new Client<ManufacturingPacket>().Save(tuples.Select(x => x.Item1), "Created from Design Management Panel");
  432. var newStages = new List<ManufacturingPacketStage>();
  433. var newComponents = new List<ManufacturingPacketComponent>();
  434. var newTreatments = new List<ManufacturingTreatment>();
  435. foreach(var (packet, stagingPacket) in tuples)
  436. {
  437. stagingPacket.ManufacturingPacket.ID = packet.ID;
  438. var stages = new Client<StagingManufacturingPacketStage>()
  439. .Query(
  440. new Filter<StagingManufacturingPacketStage>(x => x.Packet.ID).IsEqualTo(stagingPacket.ID),
  441. IManufacturingPacketGeneratorExtensions.GetPacketGeneratorRequiredColumns<StagingManufacturingPacketStage>());
  442. newStages.AddRange(stages.ToObjects<StagingManufacturingPacketStage>()
  443. .Select(x =>
  444. {
  445. var stage = x.CreateManufacturingPacketStage();
  446. stage.Parent.ID = packet.ID;
  447. return stage;
  448. }));
  449. var components = new Client<StagingManufacturingPacketComponent>()
  450. .Query(
  451. new Filter<StagingManufacturingPacketComponent>(x => x.Packet.ID).IsEqualTo(stagingPacket.ID),
  452. new Columns<StagingManufacturingPacketComponent>(x=>x.Packet.ID)
  453. .Add(x => x.Product.ID)
  454. .Add(x => x.Quantity)
  455. .Add(x => x.Dimensions.Unit.ID)
  456. .Add(x => x.Dimensions.Quantity)
  457. .Add(x => x.Dimensions.Length)
  458. .Add(x => x.Dimensions.Width)
  459. .Add(x => x.Dimensions.Height)
  460. .Add(x => x.Dimensions.Weight)
  461. .Add(x => x.Dimensions.Value)
  462. .Add(x => x.Dimensions.UnitSize)
  463. );
  464. newComponents.AddRange(components.ToObjects<StagingManufacturingPacketComponent>()
  465. .Select(x => x.CreateComponent(packet.ID)));
  466. var treatments = new Client<StagingManufacturingPacketTreatment>()
  467. .Query(
  468. new Filter<StagingManufacturingPacketTreatment>(x => x.Packet.ID).IsEqualTo(stagingPacket.ID),
  469. new Columns<StagingManufacturingPacketTreatment>(x=>x.Packet.ID)
  470. .Add(x=>x.Product.ID)
  471. .Add(x=>x.Parameter)
  472. );
  473. newTreatments.AddRange(treatments.ToObjects<StagingManufacturingPacketTreatment>()
  474. .Select(x => x.CreateTreatment(packet.ID)));
  475. }
  476. new Client<ManufacturingPacketStage>().Save(newStages, "Created from Design Management");
  477. new Client<ManufacturingPacketComponent>().Save(newComponents, "Created from Design Management");
  478. new Client<ManufacturingTreatment>().Save(newTreatments, "Created from Design Management");
  479. new Client<StagingManufacturingPacket>().Save(tuples.Select(x => x.Item2), "Created from Design Management");
  480. //currently not creating packets due to temporary change in requirements - to uncomment and check for validity when required
  481. //CreatePackets(setout);
  482. return result;
  483. }
  484. private static void CreateSetoutDocument(Setout setout, StagingSetout item, StagingSetoutDocument stagingsetoutdocument)
  485. {
  486. item.Setout.ID = setout.ID;
  487. var setoutdoc = new SetoutDocument();
  488. setoutdoc.EntityLink.ID = setout.ID;
  489. setoutdoc.DocumentLink.ID = stagingsetoutdocument.DocumentLink.ID;
  490. new Client<SetoutDocument>().Save(setoutdoc, "Added from staging screen");
  491. }
  492. private void RejectButton_Click(object sender, RoutedEventArgs e)
  493. {
  494. if (selectedSetout is null || Document is null)
  495. {
  496. MessageBox.Show("Please select a setout");
  497. return;
  498. }
  499. //dont create setout - setout.id remains blank
  500. //create kanban and populate task.id - this prevents it from appearing on the stagingsetout grid, and allows a new staging setout to be created when the file is saved to the folder again
  501. //attach the document to the task for reference
  502. var task = new Kanban
  503. {
  504. Title = "Setout Review Task (setout rejected)",
  505. Description = "Please review the attached document for setout " + selectedSetout.Number
  506. };
  507. task.ManagerLink.ID = App.EmployeeID;
  508. var page = new TaskGrid();
  509. page.MyID = App.EmployeeID;
  510. if (page.EditItems(new[] { task }))
  511. {
  512. var doc = new KanbanDocument();
  513. doc.EntityLink.ID = task.ID;
  514. doc.DocumentLink.ID = Document.DocumentLink.ID;
  515. new Client<KanbanDocument>().Save(doc, "Created from staging screen");
  516. selectedSetout.Task.ID = task.ID;
  517. new Client<StagingSetout>().Save(selectedSetout, "Updated from staging screen");
  518. MessageBox.Show("Success - Task Created for Document " + selectedSetout.Number + " (Task no. " + task.Number + " assigned to " + task.EmployeeLink.Name + ")");
  519. selectedSetout = null;
  520. ClearDocuments();
  521. refreshing = true;
  522. stagingSetoutGrid.Refresh(false, true);
  523. }
  524. else
  525. {
  526. MessageBox.Show("Task creation cancelled - setout not rejected");
  527. }
  528. }
  529. private void MarkUpButton_Click(object sender, RoutedEventArgs e)
  530. {
  531. if (Mode == DocumentMode.Markup)
  532. {
  533. Mode = DocumentMode.Complete;
  534. MessageBox.Show("IMPORTANT - press save in your document editor, then press the Complete Button in PRS");
  535. OnMarkupSelected();
  536. }
  537. else
  538. {
  539. OnMarkupComplete();
  540. Mode = DocumentMode.Markup;
  541. }
  542. }
  543. private void UpdateOriginalButton_Click(object sender, RoutedEventArgs e)
  544. {
  545. if ((_documentdata?.Any() == true) && !String.IsNullOrWhiteSpace(selectedSetout?.OriginalPath))
  546. {
  547. try
  548. {
  549. File.WriteAllBytes(selectedSetout.OriginalPath, _documentdata);
  550. selectedSetout.OriginalCRC = CoreUtils.CalculateCRC(_documentdata);
  551. new Client<StagingSetout>().Save(selectedSetout,"Updated Source File with markups");
  552. UpdateOriginalButton.Visibility = Visibility.Collapsed;
  553. }
  554. catch (Exception _exception)
  555. {
  556. MessageBox.Show($"Unable to update {selectedSetout?.OriginalPath}!\n\n{_exception.Message}");
  557. }
  558. return;
  559. }
  560. MessageBox.Show("Please select a design first!");
  561. }
  562. private void ApproveButton_Click(object sender, RoutedEventArgs e)
  563. {
  564. if (Document is null || selectedSetout is null)
  565. {
  566. MessageBox.Show("Please select a setout first.");
  567. return;
  568. }
  569. Document.Approved = !Document.Approved;
  570. new Client<StagingSetoutDocument>().Save(Document, "");
  571. refreshing = true;
  572. stagingSetoutGrid.Refresh(false, true);
  573. }
  574. private void OnMarkupSelected()
  575. {
  576. if (Document is null || selectedSetout is null)
  577. {
  578. MessageBox.Show("Please select a setout first.");
  579. return;
  580. }
  581. var doc = new Client<Document>()
  582. .Query(
  583. new Filter<Document>(x => x.ID).IsEqualTo(Document.DocumentLink.ID))
  584. .ToObjects<Document>().FirstOrDefault();
  585. if (doc is null)
  586. {
  587. Logger.Send(LogType.Error, "", $"Document with ID {Document.DocumentLink.ID} could not be found.");
  588. MessageBox.Show("Error: the selected document could not be found in the database.");
  589. return;
  590. }
  591. var tempdocpath = Path.Combine(Path.GetTempPath(), doc.FileName);
  592. selectedSetout.SavePath = tempdocpath;
  593. selectedSetout.LockedBy.ID = App.EmployeeID;
  594. selectedSetout.LockedBy.Name = App.EmployeeName;
  595. new Client<StagingSetout>().Save(selectedSetout, "Locked from Staging Screen");
  596. File.WriteAllBytes(tempdocpath, doc.Data);
  597. using (var p = new Process())
  598. {
  599. p.StartInfo = new ProcessStartInfo()
  600. {
  601. UseShellExecute = true,
  602. FileName = tempdocpath
  603. };
  604. p.Start();
  605. }
  606. refreshing = true;
  607. stagingSetoutGrid.Refresh(false, true);
  608. }
  609. private void OnMarkupComplete()
  610. {
  611. if (selectedSetout is null)
  612. {
  613. MessageBox.Show("Please select a setout first.");
  614. return;
  615. }
  616. StagingSetoutGrid.ReloadFile(selectedSetout);
  617. refreshing = true;
  618. stagingSetoutGrid.Refresh(false, true);
  619. }
  620. #endregion
  621. private bool refreshing = false;
  622. private void stagingSetoutGrid_AfterRefresh(object sender, AfterRefreshEventArgs args)
  623. {
  624. refreshing = false;
  625. }
  626. private void StagingSetoutGrid_OnSelectItem(object sender, InABox.DynamicGrid.DynamicGridSelectionEventArgs e)
  627. {
  628. var newSetouts = new List<StagingSetout>();
  629. foreach (var row in e.Rows ?? Enumerable.Empty<CoreRow>())
  630. newSetouts.Add(row.ToObject<StagingSetout>());
  631. if(!refreshing && (selectedSetouts.Count == newSetouts.Count
  632. && !selectedSetouts.Any(x => !newSetouts.Any(y => x.ID == y.ID))))
  633. {
  634. return;
  635. }
  636. selectedSetouts = newSetouts;
  637. selectedSetout = selectedSetouts.FirstOrDefault();
  638. AddPacketButton.IsEnabled = selectedSetout is not null;
  639. if(selectedSetout is null)
  640. {
  641. ClearDocuments();
  642. ManufacturingPacketList.Setout = null;
  643. CollapsePacketsButton.IsEnabled = false;
  644. SetoutComponentGrid.StagingSetout = null;
  645. SetMode(DocumentMode.Markup);
  646. return;
  647. }
  648. var doc = new Client<StagingSetoutDocument>()
  649. .Query(
  650. new Filter<StagingSetoutDocument>(x => x.EntityLink.ID).IsEqualTo(selectedSetout.ID),
  651. new Columns<StagingSetoutDocument>(x => x.ID)
  652. .Add(x => x.DocumentLink.ID)
  653. .Add(x => x.DocumentLink.FileName)
  654. .Add(x => x.Approved)
  655. .Add(x=>x.DocumentLink.CRC)
  656. ).ToObjects<StagingSetoutDocument>().FirstOrDefault();
  657. if(doc is null)
  658. {
  659. MessageBox.Show("No document found for this setout.");
  660. ClearDocuments();
  661. ManufacturingPacketList.Setout = null;
  662. CollapsePacketsButton.IsEnabled = false;
  663. SetoutComponentGrid.StagingSetout = null;
  664. return;
  665. }
  666. Document = doc;
  667. var docTask = Task.Run(() => GetDocuments(doc));
  668. if(CanViewPackets())
  669. {
  670. ManufacturingPacketList.Setout = selectedSetout;
  671. SetoutComponentGrid.StagingSetout = selectedSetout;
  672. }
  673. CollapsePacketsButton.IsEnabled = true;
  674. var mode =
  675. selectedSetout.LockedBy.ID == Guid.Empty ?
  676. DocumentMode.Markup :
  677. selectedSetout.LockedBy.ID == App.EmployeeID ?
  678. DocumentMode.Complete :
  679. DocumentMode.Locked;
  680. docTask.Wait();
  681. RenderDocuments(docTask.Result);
  682. SetMode(mode);
  683. }
  684. public bool IsReady { get; set; }
  685. public string SectionName { get; }
  686. public event DataModelUpdateEvent? OnUpdateDataModel;
  687. #region Settings
  688. public void CreateToolbarButtons(IPanelHost host)
  689. {
  690. host.CreateSetupAction(
  691. new PanelAction()
  692. {
  693. Caption = "Setouts Configuration",
  694. Image = PRSDesktop.Resources.specifications,
  695. OnExecute = ConfigSettingsClick
  696. }
  697. );
  698. host.CreateSetupAction(
  699. new PanelAction()
  700. {
  701. Caption = "Component Import Profiles",
  702. Image = PRSDesktop.Resources.doc_xls,
  703. OnExecute = ConfigComponentProfiles
  704. });
  705. host.CreateSetupAction(
  706. new PanelAction()
  707. {
  708. Caption = "Template Products",
  709. Image = PRSDesktop.Resources.specifications,
  710. OnExecute =
  711. action =>
  712. {
  713. var list = new MasterList(typeof(ManufacturingTemplateGroupProducts));
  714. list.ShowDialog();
  715. }
  716. }
  717. );
  718. }
  719. private void ConfigComponentProfiles(PanelAction obj)
  720. {
  721. var list = new DynamicImportList(
  722. typeof(StagingSetoutComponent),
  723. Guid.Empty,
  724. canImport: false
  725. );
  726. list.ShowDialog();
  727. }
  728. private void ConfigSettingsClick(PanelAction obj)
  729. {
  730. var pages = new DynamicEditorPages();
  731. var propertyEditor = new DynamicEditorForm(typeof(StagingPanellSettings), pages);
  732. propertyEditor.OnDefineLookups += sender =>
  733. {
  734. var editor = sender.EditorDefinition as ILookupEditor;
  735. var colname = sender.ColumnName;
  736. var values = editor.Values(colname, new[] { _settings });
  737. sender.LoadLookups(values);
  738. };
  739. propertyEditor.OnEditorValueChanged += (sender, name, value) =>
  740. {
  741. CoreUtils.SetPropertyValue(_settings, name, value);
  742. return new Dictionary<string, object?>();
  743. };
  744. propertyEditor.OnFormCustomiseEditor += Settings_OnFormCustomiseEditor;
  745. propertyEditor.Items = new BaseObject[] { _settings };
  746. if (propertyEditor.ShowDialog() == true)
  747. {
  748. new GlobalConfiguration<StagingPanellSettings>().Save(_settings);
  749. _script = null;
  750. }
  751. }
  752. private void Settings_OnFormCustomiseEditor(IDynamicEditorForm sender, object[] items, DynamicGridColumn column, BaseEditor editor)
  753. {
  754. if (items?.FirstOrDefault() is not StagingPanellSettings settings) return;
  755. if (column.ColumnName == nameof(StagingPanellSettings.Script) && editor is ScriptEditor scriptEditor)
  756. {
  757. scriptEditor.Type = ScriptEditorType.TemplateEditor;
  758. scriptEditor.OnEditorClicked += () =>
  759. {
  760. var script = settings.Script.NotWhiteSpaceOr()
  761. ?? settings.DefaultScript();
  762. var editor = new ScriptEditorWindow(script, SyntaxLanguage.CSharp);
  763. if (editor.ShowDialog() == true)
  764. {
  765. sender.SetEditorValue(column.ColumnName, editor.Script);
  766. settings.Script = editor.Script;
  767. }
  768. };
  769. }
  770. }
  771. #endregion
  772. public void Heartbeat(TimeSpan time)
  773. {
  774. }
  775. public void Refresh()
  776. {
  777. //stagingSetoutGrid.ScanFiles(_settings.SetoutsFolder);
  778. refreshing = true;
  779. stagingSetoutGrid.Refresh(false, true);
  780. /*Document = null;
  781. selectedSetout = null;
  782. ManufacturingPacketList.Setout = null;
  783. SetoutComponentGrid.StagingSetout = null;*/
  784. CalculateTime();
  785. }
  786. public Dictionary<string, object[]> Selected()
  787. {
  788. return new();
  789. }
  790. public void Shutdown(CancelEventArgs? cancel)
  791. {
  792. }
  793. public DataModel DataModel(Selection selection)
  794. {
  795. return new AutoDataModel<StagingSetout>(new Filter<StagingSetout>().All());
  796. }
  797. private void AddPacketButton_Click(object sender, RoutedEventArgs e)
  798. {
  799. if (_templateGroups.Rows.Any() == true)
  800. {
  801. ContextMenu menu = new ContextMenu();
  802. foreach (var row in _templateGroups.Rows)
  803. {
  804. MenuItem item = new MenuItem()
  805. {
  806. Header =
  807. $"{row.Get<ManufacturingTemplateGroup, String>(x => x.Code)}: {row.Get<ManufacturingTemplateGroup, String>(x => x.Description)}",
  808. Command = new ActionCommand((obj) =>
  809. {
  810. ManufacturingPacketList.Add(
  811. selectedSetout?.JobLink.ID ?? Guid.Empty,
  812. row.ToObject<ManufacturingTemplateGroup>()
  813. );
  814. UpdateStagingSetoutGrid();
  815. })
  816. };
  817. menu.Items.Add(item);
  818. }
  819. menu.Items.Add(new Separator());
  820. MenuItem misc = new MenuItem()
  821. {
  822. Header = "Miscellaneous Item",
  823. Command = new ActionCommand((obj) =>
  824. {
  825. ManufacturingPacketList.Add(
  826. selectedSetout?.JobLink.ID ?? Guid.Empty,
  827. null
  828. );
  829. UpdateStagingSetoutGrid();
  830. })
  831. };
  832. menu.Items.Add(misc);
  833. menu.IsOpen = true;
  834. }
  835. else
  836. {
  837. ManufacturingPacketList.Add(
  838. selectedSetout?.JobLink.ID ?? Guid.Empty,
  839. null
  840. );
  841. UpdateStagingSetoutGrid();
  842. }
  843. }
  844. private void UpdateStagingSetoutGrid()
  845. {
  846. var selected = stagingSetoutGrid.SelectedRows.FirstOrDefault();
  847. if (selected != null)
  848. {
  849. var packets = ManufacturingPacketList.Packets;
  850. selected.Set<StagingSetout, int>(x => x.Packets, packets.Length);
  851. selected.Set<StagingSetout, int>(x => x.UnprocessedPackets, packets.Count(x => x.ManufacturingPacket.ID == Guid.Empty));
  852. stagingSetoutGrid.InvalidateRow(selected);
  853. }
  854. }
  855. private void CollapsePacketsButton_Click(object sender, RoutedEventArgs e)
  856. {
  857. if (ManufacturingPacketList.Collapsed())
  858. {
  859. ManufacturingPacketList.Uncollapse();
  860. }
  861. else
  862. {
  863. ManufacturingPacketList.Collapse();
  864. }
  865. }
  866. private void ManufacturingPacketList_OnCollapsed(bool collapsed)
  867. {
  868. if (collapsed)
  869. {
  870. CollapsePacketsButton.Content = "Expand";
  871. }
  872. else
  873. {
  874. CollapsePacketsButton.Content = "Collapse";
  875. }
  876. }
  877. private void stagingSetoutGrid_OnCustomiseSetouts(IReadOnlyList<StagingSetoutGrid.SetoutDocument> setouts)
  878. {
  879. if(CustomiseSetoutsMethod != null && ScriptObject != null)
  880. {
  881. CustomiseSetoutsMethod?.Invoke(ScriptObject, new object?[]
  882. {
  883. new CustomiseSetoutsArgs(setouts.Select(x => new Tuple<StagingSetout, Document>(x.Setout, x.Document)).ToImmutableList())
  884. });
  885. }
  886. }
  887. private void StagingSetoutGrid_OnOnDoubleClick(object sender, HandledEventArgs args)
  888. {
  889. ManufacturingPacketList.Setout = selectedSetout;
  890. SetoutComponentGrid.StagingSetout = selectedSetout;
  891. MainPanel.View = DynamicSplitPanelView.Detail;
  892. NestedPanel.View = DynamicSplitPanelView.Combined;
  893. args.Handled = true;
  894. }
  895. private void CalculateTime()
  896. {
  897. if (selectedSetout != null)
  898. {
  899. var time = ManufacturingPacketList.TimeRequired();
  900. TimeRequired.Content = $"{time.TotalHours:F2} hours";
  901. }
  902. else
  903. TimeRequired.Content = "N/A";
  904. }
  905. private void ManufacturingPacketList_OnChanged(object? sender, EventArgs e)
  906. {
  907. CalculateTime();
  908. UpdateStagingSetoutGrid();
  909. }
  910. private void DoImport(Importer importer, string? componentFileName, Guid setoutID)
  911. {
  912. var success = DynamicImportGrid.CreateImporter(importer, ref componentFileName, out var iimporter);
  913. if (!success)
  914. {
  915. return;
  916. }
  917. var errors = new List<string>();
  918. var stagingSetoutComponents = new List<StagingSetoutComponent>();
  919. iimporter.OnLoad += Iimporter_OnLoad;
  920. iimporter.OnSave += (_, entity) => stagingSetoutComponents.Add((entity as StagingSetoutComponent)!);
  921. iimporter.OnError += (_, error) => errors.Add(error);
  922. using var stream = new FileStream(componentFileName!, FileMode.Open, FileAccess.Read);
  923. if (iimporter.Open(stream))
  924. {
  925. if (iimporter.ReadHeader())
  926. {
  927. var mismatches = iimporter.Mappings.Where(x =>
  928. !string.IsNullOrWhiteSpace(x.Field) &&
  929. !iimporter.Fields.Contains(x.Field)
  930. ).Select(x => x.Field).ToArray();
  931. if (!mismatches.Any())
  932. {
  933. var imported = iimporter.Import();
  934. if (errors.Any())
  935. {
  936. MessageBox.Show($"Import for component file {componentFileName} failed:\nSome errors occurred: {string.Join('\n', errors)}", "Import failed");
  937. }
  938. else
  939. {
  940. var valid = true;
  941. var conflicts = false;
  942. if (setoutID != Guid.Empty)
  943. {
  944. var newComponents = new List<StagingSetoutComponent>();
  945. foreach (var component in stagingSetoutComponents)
  946. {
  947. if (component.StagingSetout.ID == Guid.Empty)
  948. {
  949. component.StagingSetout.ID = setoutID;
  950. newComponents.Add(component);
  951. }
  952. else if (component.StagingSetout.ID != setoutID)
  953. {
  954. conflicts = true;
  955. // Ignoring this item.
  956. }
  957. else
  958. {
  959. newComponents.Add(component);
  960. }
  961. }
  962. stagingSetoutComponents = newComponents;
  963. if (conflicts)
  964. {
  965. MessageBox.Show($"Warning: the lines in this file have conflicting setout numbers.", "Warning");
  966. }
  967. }
  968. if (valid)
  969. {
  970. foreach (var component in stagingSetoutComponents)
  971. {
  972. if (component.StagingSetout.ID == Guid.Empty)
  973. {
  974. MessageBox.Show($"Component with no related setout cannot be imported.");
  975. valid = false;
  976. break;
  977. }
  978. else if (component.Description.IsNullOrWhiteSpace())
  979. {
  980. MessageBox.Show($"Component with no description cannot be imported.");
  981. valid = false;
  982. break;
  983. }
  984. else if (component.Dimensions.Unit.ID == Guid.Empty)
  985. {
  986. MessageBox.Show($"Component with no dimensions unit cannot be imported.");
  987. valid = false;
  988. break;
  989. }
  990. }
  991. }
  992. if (valid)
  993. {
  994. new Client<StagingSetoutComponent>().Save(stagingSetoutComponents, $"Imported from {componentFileName}");
  995. SetoutComponentGrid.Refresh(false, true);
  996. }
  997. else
  998. {
  999. MessageBox.Show($"Import for component file {componentFileName} failed.", "Import failed");
  1000. }
  1001. }
  1002. }
  1003. else
  1004. {
  1005. MessageBox.Show("Import Mappings do not match file headers!\n\n- " + string.Join("\n- ", mismatches),
  1006. "Import Failed");
  1007. }
  1008. }
  1009. else
  1010. {
  1011. MessageBox.Show("Unable to Read Headers from {0}", Path.GetFileName(componentFileName));
  1012. }
  1013. }
  1014. else
  1015. {
  1016. MessageBox.Show("Unable to Open {0}", Path.GetFileName(componentFileName));
  1017. }
  1018. iimporter.Close();
  1019. }
  1020. private CoreTable Iimporter_OnLoad(object sender, Type type, string[] fields, string ID)
  1021. {
  1022. var result = new CoreTable();
  1023. result.LoadColumns(new Columns<StagingSetoutComponent>(fields));
  1024. return result;
  1025. }
  1026. private void stagingSetoutGrid_OnParseComponentFile(string componentFileName, Guid setoutID)
  1027. {
  1028. try
  1029. {
  1030. var entityName = typeof(StagingSetoutComponent).EntityName();
  1031. var importers = new Client<Importer>()
  1032. .Query(
  1033. new Filter<Importer>(x => x.EntityName).IsEqualTo(entityName),
  1034. new Columns<Importer>(x => x.ID));
  1035. if (importers.Rows.Count == 0)
  1036. {
  1037. var importer = new Importer
  1038. {
  1039. EntityName = entityName,
  1040. FileName = componentFileName
  1041. };
  1042. var form = new DynamicImportForm(importer);
  1043. if (form.ShowDialog() == true)
  1044. {
  1045. new Client<Importer>().Save(importer, "");
  1046. DoImport(importer, componentFileName, setoutID);
  1047. return;
  1048. }
  1049. }
  1050. else if (importers.Rows.Count == 1)
  1051. {
  1052. var importer = new Client<Importer>().Load(new Filter<Importer>(x => x.ID).IsEqualTo(importers.Rows[0].Get<Importer, Guid>(x => x.ID))).First();
  1053. DoImport(importer, componentFileName, setoutID);
  1054. }
  1055. else
  1056. {
  1057. var list = new PopupList(
  1058. typeof(Importer),
  1059. Guid.Empty,
  1060. Array.Empty<string>());
  1061. list.OnDefineFilter += t => new Filter<Importer>(x => x.EntityName).IsEqualTo(entityName);
  1062. if (list.ShowDialog() == true)
  1063. {
  1064. var importer = new Client<Importer>().Load(new Filter<Importer>(x => x.ID).IsEqualTo(list.ID)).First();
  1065. DoImport(importer, componentFileName, setoutID);
  1066. }
  1067. }
  1068. }
  1069. catch(Exception e)
  1070. {
  1071. Logger.Send(LogType.Error, "", $"Error in file {componentFileName}: {CoreUtils.FormatException(e)}");
  1072. MessageBox.Show($"Error opening {componentFileName}: {e.Message}");
  1073. }
  1074. }
  1075. }
  1076. }