StagingPanel.xaml.cs 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  1. using Comal.Classes;
  2. using InABox.Core;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using InABox.Clients;
  9. using InABox.Configuration;
  10. using InABox.DynamicGrid;
  11. using System.Diagnostics;
  12. using System.IO;
  13. using InABox.WPF;
  14. using System.ComponentModel;
  15. using InABox.Scripting;
  16. using System.Reflection;
  17. using System.Collections.Immutable;
  18. using StagingManufacturingPacketComponent = Comal.Classes.StagingManufacturingPacketComponent;
  19. using System.Threading.Tasks;
  20. namespace PRSDesktop
  21. {
  22. [Caption("Staging Panel Settings")]
  23. public class StagingPanellSettings : BaseObject, IGlobalConfigurationSettings
  24. {
  25. [Caption("PDF Markup Program Pathway", IncludePath = false)]
  26. [FileNameEditor]
  27. public string MarkupPathway { get; set; }
  28. [FolderEditor(Environment.SpecialFolder.CommonDocuments)]
  29. public string SetoutsFolder { get; set; }
  30. [ScriptEditor]
  31. public string? Script { get; set; }
  32. public StagingPanellSettings()
  33. {
  34. MarkupPathway = "";
  35. SetoutsFolder = "";
  36. Script = null;
  37. }
  38. public string DefaultScript()
  39. {
  40. return @"
  41. using PRSDesktop;
  42. using InABox.Core;
  43. using System.Collections.Generic;
  44. public class Module
  45. {
  46. /*public void CustomiseSetouts(CustomiseSetoutsArgs args)
  47. {
  48. // Perform customisation on the setouts when they are added to the 'Staged Documents' grid.
  49. }*/
  50. }";
  51. }
  52. }
  53. public class CustomiseSetoutsArgs
  54. {
  55. public IReadOnlyList<Tuple<StagingSetout, Document>> Setouts;
  56. public CustomiseSetoutsArgs(IReadOnlyList<Tuple<StagingSetout, Document>> setouts)
  57. {
  58. Setouts = setouts;
  59. }
  60. }
  61. /// <summary>
  62. /// Interaction logic for StagingPanel.xaml
  63. /// </summary>
  64. public partial class StagingPanel : UserControl, IPanel<StagingSetout>
  65. {
  66. private StagingPanellSettings _settings = new StagingPanellSettings();
  67. /// <summary>
  68. /// The currently selected setout.
  69. /// </summary>
  70. private StagingSetout? selectedSetout;
  71. /// <summary>
  72. /// All currently selected setouts; <see cref="selectedSetout"/> will be a member of this list.
  73. /// </summary>
  74. private List<StagingSetout> selectedSetouts = new();
  75. private CoreTable _templateGroups = null!;
  76. #region Script Stuff
  77. private MethodInfo? _customiseSetoutsMethod;
  78. private MethodInfo? CustomiseSetoutsMethod
  79. {
  80. get
  81. {
  82. EnsureScript();
  83. return _customiseSetoutsMethod;
  84. }
  85. }
  86. private object? _scriptObject;
  87. private object? ScriptObject
  88. {
  89. get
  90. {
  91. EnsureScript();
  92. return _scriptObject;
  93. }
  94. }
  95. private ScriptDocument? _script;
  96. private ScriptDocument? Script
  97. {
  98. get
  99. {
  100. EnsureScript();
  101. return _script;
  102. }
  103. }
  104. private void EnsureScript()
  105. {
  106. if (_script is null && !_settings.Script.IsNullOrWhiteSpace())
  107. {
  108. _script = new ScriptDocument(_settings.Script);
  109. if (!_script.Compile())
  110. {
  111. throw new Exception("Script in Staging Panel Settings failed to compile!");
  112. }
  113. _scriptObject = _script?.GetObject();
  114. _customiseSetoutsMethod = _script?.GetMethod(methodName: "CustomiseSetouts");
  115. }
  116. }
  117. #endregion
  118. public StagingPanel()
  119. {
  120. InitializeComponent();
  121. SectionName = nameof(StagingPanel);
  122. }
  123. public void Setup()
  124. {
  125. _settings = new GlobalConfiguration<StagingPanellSettings>().Load();
  126. _templateGroups = new Client<ManufacturingTemplateGroup>().Query();
  127. MarkUpButton.Visibility = Security.IsAllowed<CanMarkUpSetouts>() ? Visibility.Visible : Visibility.Hidden;
  128. RejectButton.Visibility = Security.IsAllowed<CanApproveSetouts>() ? Visibility.Visible : Visibility.Hidden;
  129. ApproveButton.Visibility = Security.IsAllowed<CanApproveSetouts>() ? Visibility.Visible : Visibility.Hidden;
  130. ProcessButton.Visibility = Security.IsAllowed<CanApproveSetouts>() ? Visibility.Visible : Visibility.Hidden;
  131. //stagingSetoutGrid.ScanFiles(_settings.SetoutsFolder);
  132. stagingSetoutGrid.Refresh(true, false);
  133. SetoutComponentGrid.Refresh(true, false);
  134. }
  135. private bool CanViewPackets() => MainPanel.View != DynamicSplitPanelView.Master && NestedPanel.View != DynamicSplitPanelView.Master;
  136. private void NestedPanel_OnChanged(object sender, DynamicSplitPanelSettings e)
  137. {
  138. if(CanViewPackets())
  139. {
  140. ManufacturingPacketList.Setout = selectedSetout;
  141. SetoutComponentGrid.StagingSetout = selectedSetout;
  142. }
  143. }
  144. #region Document Viewer
  145. public enum DocumentMode
  146. {
  147. Markup,
  148. Complete,
  149. Locked
  150. }
  151. private DocumentMode _mode;
  152. private DocumentMode Mode
  153. {
  154. get => _mode;
  155. set => SetMode(value);
  156. }
  157. private void SetMode(DocumentMode mode)
  158. {
  159. _mode = mode;
  160. if (_mode == DocumentMode.Markup)
  161. {
  162. MarkUpButton.Content = "Mark Up";
  163. MarkUpButton.IsEnabled = Document != null && !Document.Approved;
  164. UpdateOriginalButton.Visibility =
  165. Document != null && !String.Equals(Document.DocumentLink.CRC, selectedSetout?.OriginalCRC)
  166. ? Visibility.Visible
  167. : Visibility.Collapsed;
  168. ProcessButton.IsEnabled = Document != null && Document.Approved;
  169. RejectButton.IsEnabled = Document != null && !Document.Approved;
  170. ApproveButton.IsEnabled = Document != null;
  171. }
  172. else if (_mode == DocumentMode.Complete)
  173. {
  174. MarkUpButton.Content = "Complete";
  175. MarkUpButton.IsEnabled = Document != null;
  176. UpdateOriginalButton.Visibility = Visibility.Collapsed;
  177. ProcessButton.IsEnabled = false;
  178. RejectButton.IsEnabled = false;
  179. ApproveButton.IsEnabled = false;
  180. }
  181. else if (_mode == DocumentMode.Locked)
  182. {
  183. MarkUpButton.Content = "Locked";
  184. MarkUpButton.IsEnabled = false;
  185. UpdateOriginalButton.Visibility = Visibility.Collapsed;
  186. ProcessButton.IsEnabled = false;
  187. RejectButton.IsEnabled = false;
  188. ApproveButton.IsEnabled = false;
  189. }
  190. }
  191. private StagingSetoutDocument? _document;
  192. private StagingSetoutDocument? Document
  193. {
  194. get => _document;
  195. set
  196. {
  197. _document = value;
  198. if(_document is not null)
  199. {
  200. ApproveButton.Content = _document.Approved ? "Unapprove" : "Approve";
  201. }
  202. }
  203. }
  204. private byte[]? _documentdata = null;
  205. private void ClearDocuments()
  206. {
  207. Document = null;
  208. RenderDocuments(null);
  209. }
  210. private List<byte[]>? GetDocuments(StagingSetoutDocument? document)
  211. {
  212. if(document is null)
  213. {
  214. return null;
  215. }
  216. var table = new Client<Document>().Query(
  217. new Filter<Document>(x => x.ID).IsEqualTo(document.DocumentLink.ID),
  218. new Columns<Document>(x => x.Data));
  219. var first = table.Rows.FirstOrDefault();
  220. if (first is null)
  221. return null;
  222. _documentdata = first.Get<Document, byte[]>(x => x.Data);
  223. return ImageUtils.RenderPDFToImages(_documentdata);
  224. }
  225. private void RenderDocuments(List<byte[]>? documents)
  226. {
  227. DocumentViewer.Children.Clear();
  228. if(documents is not null)
  229. {
  230. foreach (var image in documents)
  231. {
  232. DocumentViewer.Children.Add(new Image
  233. {
  234. Source = ImageUtils.LoadImage(image),
  235. Margin = new Thickness(0, 0, 0, 20)
  236. });
  237. }
  238. }
  239. }
  240. private void ProcessButton_Click(object sender, RoutedEventArgs e)
  241. {
  242. bool bulkApprove = false;
  243. if (selectedSetouts.Count > 1)
  244. {
  245. if (MessageBox.Show("Bulk approve? (Skip individual setout approval)", "Continue?", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
  246. {
  247. bulkApprove = true;
  248. Progress.Show("Approving Setouts..");
  249. }
  250. }
  251. if (selectedSetouts.Any(x => x.UnapprovedDocuments > 0))
  252. {
  253. MessageBox.Show("Cannot process setouts with unapproved documents.");
  254. Progress.Close();
  255. return;
  256. }
  257. if (selectedSetouts.Any(x => x.JobLink.ID == Guid.Empty))
  258. {
  259. MessageBox.Show("Cannot process setout without a linked job.");
  260. Progress.Close();
  261. return;
  262. }
  263. if (ManufacturingPacketList.Packets.Any(x => x.Template.ID == Guid.Empty))
  264. {
  265. MessageBox.Show("Cannot process manufacturing packets without templates.");
  266. Progress.Close();
  267. return;
  268. }
  269. if (selectedSetouts.Any(x => x.Packets == 0))
  270. {
  271. if (MessageBox.Show("Warning: some setouts do not have any manufacturing packets: are you sure you wish to proceed?", "Warning", MessageBoxButton.YesNoCancel) != MessageBoxResult.Yes)
  272. {
  273. Progress.Close();
  274. return;
  275. }
  276. }
  277. string message = "";
  278. foreach (var item in selectedSetouts)
  279. {
  280. if (bulkApprove)
  281. Progress.Show("Working on " + item.Number);
  282. var returnstring = ApproveSetout(item, bulkApprove);
  283. if (!string.IsNullOrWhiteSpace(returnstring))
  284. message = message + returnstring + Environment.NewLine;
  285. }
  286. if (bulkApprove)
  287. Progress.Close();
  288. new Client<StagingSetout>().Save(selectedSetouts, "Updated from staging screen");
  289. selectedSetout = null;
  290. Refresh();
  291. if (!message.IsNullOrWhiteSpace())
  292. {
  293. MessageBox.Show($"Result:\n{message}");
  294. }
  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. if (selectedSetouts.Count > 1)
  570. {
  571. var msg = Document.Approved
  572. ? "Bulk unapprove?"
  573. : "Bulk approve? (Skip individual setout approval)";
  574. if (MessageBox.Show(msg, "Continue?", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
  575. {
  576. Progress.Show("Approving Setouts..");
  577. var documents = Client.Query(
  578. new Filter<StagingSetoutDocument>(x => x.EntityLink.ID).InList(selectedSetouts.Select(x => x.ID).ToArray()),
  579. new Columns<StagingSetoutDocument>(x => x.ID, x => x.Approved)
  580. ).ToObjects<StagingSetoutDocument>().ToList();
  581. foreach(var document in documents)
  582. {
  583. document.Approved = !Document.Approved;
  584. }
  585. Client.Save(documents, "Approved by user.");
  586. Progress.Close();
  587. refreshing = true;
  588. stagingSetoutGrid.Refresh(false, true);
  589. }
  590. }
  591. else
  592. {
  593. Document.Approved = !Document.Approved;
  594. new Client<StagingSetoutDocument>().Save(Document, "");
  595. refreshing = true;
  596. stagingSetoutGrid.Refresh(false, true);
  597. }
  598. }
  599. private void OnMarkupSelected()
  600. {
  601. if (Document is null || selectedSetout is null)
  602. {
  603. MessageBox.Show("Please select a setout first.");
  604. return;
  605. }
  606. var doc = new Client<Document>()
  607. .Query(
  608. new Filter<Document>(x => x.ID).IsEqualTo(Document.DocumentLink.ID))
  609. .ToObjects<Document>().FirstOrDefault();
  610. if (doc is null)
  611. {
  612. Logger.Send(LogType.Error, "", $"Document with ID {Document.DocumentLink.ID} could not be found.");
  613. MessageBox.Show("Error: the selected document could not be found in the database.");
  614. return;
  615. }
  616. var tempdocpath = Path.Combine(Path.GetTempPath(), doc.FileName);
  617. selectedSetout.SavePath = tempdocpath;
  618. selectedSetout.LockedBy.ID = App.EmployeeID;
  619. selectedSetout.LockedBy.Name = App.EmployeeName;
  620. new Client<StagingSetout>().Save(selectedSetout, "Locked from Staging Screen");
  621. File.WriteAllBytes(tempdocpath, doc.Data);
  622. using (var p = new Process())
  623. {
  624. p.StartInfo = new ProcessStartInfo()
  625. {
  626. UseShellExecute = true,
  627. FileName = tempdocpath
  628. };
  629. p.Start();
  630. }
  631. refreshing = true;
  632. stagingSetoutGrid.Refresh(false, true);
  633. }
  634. private void OnMarkupComplete()
  635. {
  636. if (selectedSetout is null)
  637. {
  638. MessageBox.Show("Please select a setout first.");
  639. return;
  640. }
  641. StagingSetoutGrid.ReloadFile(selectedSetout);
  642. refreshing = true;
  643. stagingSetoutGrid.Refresh(false, true);
  644. }
  645. #endregion
  646. private bool refreshing = false;
  647. private void stagingSetoutGrid_AfterRefresh(object sender, AfterRefreshEventArgs args)
  648. {
  649. refreshing = false;
  650. }
  651. private void StagingSetoutGrid_OnSelectItem(object sender, InABox.DynamicGrid.DynamicGridSelectionEventArgs e)
  652. {
  653. var newSetouts = new List<StagingSetout>();
  654. foreach (var row in e.Rows ?? Enumerable.Empty<CoreRow>())
  655. newSetouts.Add(row.ToObject<StagingSetout>());
  656. if(!refreshing && (selectedSetouts.Count == newSetouts.Count
  657. && !selectedSetouts.Any(x => !newSetouts.Any(y => x.ID == y.ID))))
  658. {
  659. selectedSetouts = newSetouts;
  660. selectedSetout = selectedSetouts.FirstOrDefault();
  661. return;
  662. }
  663. selectedSetouts = newSetouts;
  664. selectedSetout = selectedSetouts.FirstOrDefault();
  665. AddPacketButton.IsEnabled = selectedSetout is not null;
  666. if(selectedSetout is null)
  667. {
  668. ClearDocuments();
  669. ManufacturingPacketList.Setout = null;
  670. CollapsePacketsButton.IsEnabled = false;
  671. SetoutComponentGrid.StagingSetout = null;
  672. SetMode(DocumentMode.Markup);
  673. return;
  674. }
  675. var doc = new Client<StagingSetoutDocument>()
  676. .Query(
  677. new Filter<StagingSetoutDocument>(x => x.EntityLink.ID).IsEqualTo(selectedSetout.ID),
  678. new Columns<StagingSetoutDocument>(x => x.ID)
  679. .Add(x => x.DocumentLink.ID)
  680. .Add(x => x.DocumentLink.FileName)
  681. .Add(x => x.Approved)
  682. .Add(x=>x.DocumentLink.CRC)
  683. ).ToObjects<StagingSetoutDocument>().FirstOrDefault();
  684. if(doc is null)
  685. {
  686. MessageBox.Show("No document found for this setout.");
  687. ClearDocuments();
  688. ManufacturingPacketList.Setout = null;
  689. CollapsePacketsButton.IsEnabled = false;
  690. SetoutComponentGrid.StagingSetout = null;
  691. return;
  692. }
  693. Document = doc;
  694. var docTask = Task.Run(() => GetDocuments(doc));
  695. if(CanViewPackets())
  696. {
  697. ManufacturingPacketList.Setout = selectedSetout;
  698. SetoutComponentGrid.StagingSetout = selectedSetout;
  699. }
  700. CollapsePacketsButton.IsEnabled = true;
  701. var mode =
  702. selectedSetout.LockedBy.ID == Guid.Empty ?
  703. DocumentMode.Markup :
  704. selectedSetout.LockedBy.ID == App.EmployeeID ?
  705. DocumentMode.Complete :
  706. DocumentMode.Locked;
  707. docTask.Wait();
  708. RenderDocuments(docTask.Result);
  709. SetMode(mode);
  710. }
  711. public bool IsReady { get; set; }
  712. public string SectionName { get; }
  713. public event DataModelUpdateEvent? OnUpdateDataModel;
  714. #region Settings
  715. public void CreateToolbarButtons(IPanelHost host)
  716. {
  717. host.CreateSetupAction(
  718. new PanelAction()
  719. {
  720. Caption = "Setouts Configuration",
  721. Image = PRSDesktop.Resources.specifications,
  722. OnExecute = ConfigSettingsClick
  723. }
  724. );
  725. host.CreateSetupAction(
  726. new PanelAction()
  727. {
  728. Caption = "Component Import Profiles",
  729. Image = PRSDesktop.Resources.doc_xls,
  730. OnExecute = ConfigComponentProfiles
  731. });
  732. host.CreateSetupAction(
  733. new PanelAction()
  734. {
  735. Caption = "Template Products",
  736. Image = PRSDesktop.Resources.specifications,
  737. OnExecute =
  738. action =>
  739. {
  740. var list = new MasterList(typeof(ManufacturingTemplateGroupProducts));
  741. list.ShowDialog();
  742. }
  743. }
  744. );
  745. }
  746. private void ConfigComponentProfiles(PanelAction obj)
  747. {
  748. var list = new DynamicImportList(
  749. typeof(StagingSetoutComponent),
  750. Guid.Empty,
  751. canImport: false
  752. );
  753. list.ShowDialog();
  754. }
  755. private void ConfigSettingsClick(PanelAction obj)
  756. {
  757. var pages = new DynamicEditorPages();
  758. var propertyEditor = new DynamicEditorForm(typeof(StagingPanellSettings), pages);
  759. propertyEditor.OnDefineLookups += sender =>
  760. {
  761. var editor = sender.EditorDefinition as ILookupEditor;
  762. var colname = sender.ColumnName;
  763. var values = editor.Values(colname, new[] { _settings });
  764. sender.LoadLookups(values);
  765. };
  766. propertyEditor.OnEditorValueChanged += (sender, name, value) =>
  767. {
  768. CoreUtils.SetPropertyValue(_settings, name, value);
  769. return new Dictionary<string, object?>();
  770. };
  771. propertyEditor.OnFormCustomiseEditor += Settings_OnFormCustomiseEditor;
  772. propertyEditor.Items = new BaseObject[] { _settings };
  773. if (propertyEditor.ShowDialog() == true)
  774. {
  775. new GlobalConfiguration<StagingPanellSettings>().Save(_settings);
  776. _script = null;
  777. }
  778. }
  779. private void Settings_OnFormCustomiseEditor(IDynamicEditorForm sender, object[] items, DynamicGridColumn column, BaseEditor editor)
  780. {
  781. if (items?.FirstOrDefault() is not StagingPanellSettings settings) return;
  782. if (column.ColumnName == nameof(StagingPanellSettings.Script) && editor is ScriptEditor scriptEditor)
  783. {
  784. scriptEditor.Type = ScriptEditorType.TemplateEditor;
  785. scriptEditor.OnEditorClicked += () =>
  786. {
  787. var script = settings.Script.NotWhiteSpaceOr()
  788. ?? settings.DefaultScript();
  789. var editor = new ScriptEditorWindow(script, SyntaxLanguage.CSharp);
  790. if (editor.ShowDialog() == true)
  791. {
  792. sender.SetEditorValue(column.ColumnName, editor.Script);
  793. settings.Script = editor.Script;
  794. }
  795. };
  796. }
  797. }
  798. #endregion
  799. public void Heartbeat(TimeSpan time)
  800. {
  801. }
  802. public void Refresh()
  803. {
  804. //stagingSetoutGrid.ScanFiles(_settings.SetoutsFolder);
  805. refreshing = true;
  806. stagingSetoutGrid.Refresh(false, true);
  807. /*Document = null;
  808. selectedSetout = null;
  809. ManufacturingPacketList.Setout = null;
  810. SetoutComponentGrid.StagingSetout = null;*/
  811. CalculateTime();
  812. }
  813. public Dictionary<string, object[]> Selected()
  814. {
  815. return new();
  816. }
  817. public void Shutdown(CancelEventArgs? cancel)
  818. {
  819. }
  820. public DataModel DataModel(Selection selection)
  821. {
  822. return new AutoDataModel<StagingSetout>(new Filter<StagingSetout>().All());
  823. }
  824. private void AddPacketButton_Click(object sender, RoutedEventArgs e)
  825. {
  826. if (_templateGroups.Rows.Any() == true)
  827. {
  828. ContextMenu menu = new ContextMenu();
  829. foreach (var row in _templateGroups.Rows)
  830. {
  831. menu.AddItem(
  832. $"{row.Get<ManufacturingTemplateGroup, String>(x => x.Code)}: {row.Get<ManufacturingTemplateGroup, String>(x => x.Description)}",
  833. null,
  834. () =>
  835. {
  836. ManufacturingPacketList.Add(
  837. selectedSetout?.JobLink.ID ?? Guid.Empty,
  838. row.ToObject<ManufacturingTemplateGroup>()
  839. );
  840. UpdateStagingSetoutGrid();
  841. });
  842. }
  843. menu.AddSeparator();
  844. menu.AddItem("Miscellaneous Item", null, () =>
  845. {
  846. ManufacturingPacketList.Add(
  847. selectedSetout?.JobLink.ID ?? Guid.Empty,
  848. null
  849. );
  850. UpdateStagingSetoutGrid();
  851. });
  852. menu.IsOpen = true;
  853. }
  854. else
  855. {
  856. ManufacturingPacketList.Add(
  857. selectedSetout?.JobLink.ID ?? Guid.Empty,
  858. null
  859. );
  860. UpdateStagingSetoutGrid();
  861. }
  862. }
  863. private void UpdateStagingSetoutGrid()
  864. {
  865. var selected = stagingSetoutGrid.SelectedRows.FirstOrDefault();
  866. if (selected != null)
  867. {
  868. var packets = ManufacturingPacketList.Packets;
  869. selected.Set<StagingSetout, int>(x => x.Packets, packets.Length);
  870. selected.Set<StagingSetout, int>(x => x.UnprocessedPackets, packets.Count(x => x.ManufacturingPacket.ID == Guid.Empty));
  871. stagingSetoutGrid.InvalidateRow(selected);
  872. }
  873. }
  874. private void CollapsePacketsButton_Click(object sender, RoutedEventArgs e)
  875. {
  876. if (ManufacturingPacketList.Collapsed())
  877. {
  878. ManufacturingPacketList.Uncollapse();
  879. }
  880. else
  881. {
  882. ManufacturingPacketList.Collapse();
  883. }
  884. }
  885. private void ManufacturingPacketList_OnCollapsed(bool collapsed)
  886. {
  887. if (collapsed)
  888. {
  889. CollapsePacketsButton.Content = "Expand";
  890. }
  891. else
  892. {
  893. CollapsePacketsButton.Content = "Collapse";
  894. }
  895. }
  896. private void stagingSetoutGrid_OnCustomiseSetouts(IReadOnlyList<StagingSetoutGrid.SetoutDocument> setouts)
  897. {
  898. if(CustomiseSetoutsMethod != null && ScriptObject != null)
  899. {
  900. CustomiseSetoutsMethod?.Invoke(ScriptObject, new object?[]
  901. {
  902. new CustomiseSetoutsArgs(setouts.Select(x => new Tuple<StagingSetout, Document>(x.Setout, x.Document)).ToImmutableList())
  903. });
  904. }
  905. }
  906. private void StagingSetoutGrid_OnOnDoubleClick(object sender, HandledEventArgs args)
  907. {
  908. ManufacturingPacketList.Setout = selectedSetout;
  909. SetoutComponentGrid.StagingSetout = selectedSetout;
  910. MainPanel.View = DynamicSplitPanelView.Detail;
  911. NestedPanel.View = DynamicSplitPanelView.Combined;
  912. args.Handled = true;
  913. }
  914. private void CalculateTime()
  915. {
  916. if (selectedSetout != null)
  917. {
  918. var time = ManufacturingPacketList.TimeRequired();
  919. TimeRequired.Content = $"{time.TotalHours:F2} hours";
  920. }
  921. else
  922. TimeRequired.Content = "N/A";
  923. }
  924. private void ManufacturingPacketList_OnChanged(object? sender, EventArgs e)
  925. {
  926. CalculateTime();
  927. UpdateStagingSetoutGrid();
  928. }
  929. private void DoImport(Importer importer, string? componentFileName, Guid setoutID)
  930. {
  931. var success = DynamicImportGrid.CreateImporter(importer, ref componentFileName, out var iimporter);
  932. if (!success)
  933. {
  934. return;
  935. }
  936. var errors = new List<string>();
  937. var stagingSetoutComponents = new List<StagingSetoutComponent>();
  938. iimporter.OnLoad += Iimporter_OnLoad;
  939. iimporter.OnSave += (_, entity) => stagingSetoutComponents.Add((entity as StagingSetoutComponent)!);
  940. iimporter.OnError += (_, error) => errors.Add(error);
  941. using var stream = new FileStream(componentFileName!, FileMode.Open, FileAccess.Read);
  942. if (iimporter.Open(stream))
  943. {
  944. if (iimporter.ReadHeader())
  945. {
  946. var mismatches = iimporter.Mappings.Where(x =>
  947. !string.IsNullOrWhiteSpace(x.Field) &&
  948. !iimporter.Fields.Contains(x.Field)
  949. ).Select(x => x.Field).ToArray();
  950. if (!mismatches.Any())
  951. {
  952. var imported = iimporter.Import();
  953. if (errors.Any())
  954. {
  955. MessageBox.Show($"Import for component file {componentFileName} failed:\nSome errors occurred: {string.Join('\n', errors)}", "Import failed");
  956. }
  957. else
  958. {
  959. var valid = true;
  960. var conflicts = false;
  961. if (setoutID != Guid.Empty)
  962. {
  963. var newComponents = new List<StagingSetoutComponent>();
  964. foreach (var component in stagingSetoutComponents)
  965. {
  966. if (component.StagingSetout.ID == Guid.Empty)
  967. {
  968. component.StagingSetout.ID = setoutID;
  969. newComponents.Add(component);
  970. }
  971. else if (component.StagingSetout.ID != setoutID)
  972. {
  973. conflicts = true;
  974. // Ignoring this item.
  975. }
  976. else
  977. {
  978. newComponents.Add(component);
  979. }
  980. }
  981. stagingSetoutComponents = newComponents;
  982. if (conflicts)
  983. {
  984. MessageBox.Show($"Warning: the lines in this file have conflicting setout numbers.", "Warning");
  985. }
  986. }
  987. if (valid)
  988. {
  989. foreach (var component in stagingSetoutComponents)
  990. {
  991. if (component.StagingSetout.ID == Guid.Empty)
  992. {
  993. MessageBox.Show($"Component with no related setout cannot be imported.");
  994. valid = false;
  995. break;
  996. }
  997. else if (component.Description.IsNullOrWhiteSpace())
  998. {
  999. MessageBox.Show($"Component with no description cannot be imported.");
  1000. valid = false;
  1001. break;
  1002. }
  1003. else if (component.Dimensions.Unit.ID == Guid.Empty)
  1004. {
  1005. MessageBox.Show($"Component with no dimensions unit cannot be imported.");
  1006. valid = false;
  1007. break;
  1008. }
  1009. }
  1010. }
  1011. if (valid)
  1012. {
  1013. new Client<StagingSetoutComponent>().Save(stagingSetoutComponents, $"Imported from {componentFileName}");
  1014. SetoutComponentGrid.Refresh(false, true);
  1015. }
  1016. else
  1017. {
  1018. MessageBox.Show($"Import for component file {componentFileName} failed.", "Import failed");
  1019. }
  1020. }
  1021. }
  1022. else
  1023. {
  1024. MessageBox.Show("Import Mappings do not match file headers!\n\n- " + string.Join("\n- ", mismatches),
  1025. "Import Failed");
  1026. }
  1027. }
  1028. else
  1029. {
  1030. MessageBox.Show("Unable to Read Headers from {0}", Path.GetFileName(componentFileName));
  1031. }
  1032. }
  1033. else
  1034. {
  1035. MessageBox.Show("Unable to Open {0}", Path.GetFileName(componentFileName));
  1036. }
  1037. iimporter.Close();
  1038. }
  1039. private CoreTable Iimporter_OnLoad(object sender, Type type, string[] fields, string ID)
  1040. {
  1041. var result = new CoreTable();
  1042. result.LoadColumns(new Columns<StagingSetoutComponent>(fields));
  1043. return result;
  1044. }
  1045. private void stagingSetoutGrid_OnParseComponentFile(string componentFileName, Guid setoutID)
  1046. {
  1047. try
  1048. {
  1049. var entityName = typeof(StagingSetoutComponent).EntityName();
  1050. var importers = new Client<Importer>()
  1051. .Query(
  1052. new Filter<Importer>(x => x.EntityName).IsEqualTo(entityName),
  1053. new Columns<Importer>(x => x.ID));
  1054. if (importers.Rows.Count == 0)
  1055. {
  1056. var importer = new Importer
  1057. {
  1058. EntityName = entityName,
  1059. FileName = componentFileName
  1060. };
  1061. var form = new DynamicImportForm(importer);
  1062. if (form.ShowDialog() == true)
  1063. {
  1064. new Client<Importer>().Save(importer, "");
  1065. DoImport(importer, componentFileName, setoutID);
  1066. return;
  1067. }
  1068. }
  1069. else if (importers.Rows.Count == 1)
  1070. {
  1071. var importer = new Client<Importer>().Load(new Filter<Importer>(x => x.ID).IsEqualTo(importers.Rows[0].Get<Importer, Guid>(x => x.ID))).First();
  1072. DoImport(importer, componentFileName, setoutID);
  1073. }
  1074. else
  1075. {
  1076. var list = new PopupList(
  1077. typeof(Importer),
  1078. Guid.Empty,
  1079. Array.Empty<string>());
  1080. list.OnDefineFilter += t => new Filter<Importer>(x => x.EntityName).IsEqualTo(entityName);
  1081. if (list.ShowDialog() == true)
  1082. {
  1083. var importer = new Client<Importer>().Load(new Filter<Importer>(x => x.ID).IsEqualTo(list.ID)).First();
  1084. DoImport(importer, componentFileName, setoutID);
  1085. }
  1086. }
  1087. }
  1088. catch(Exception e)
  1089. {
  1090. Logger.Send(LogType.Error, "", $"Error in file {componentFileName}: {CoreUtils.FormatException(e)}");
  1091. MessageBox.Show($"Error opening {componentFileName}: {e.Message}");
  1092. }
  1093. }
  1094. }
  1095. }