StagingPanel.xaml.cs 48 KB

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