StagingPanel.xaml.cs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  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. using Columns = InABox.Core.Columns;
  23. namespace PRSDesktop;
  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. [Comment("Maximum Document Size (MB)")]
  35. [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.")]
  36. public int MaximumDocumentSize { get; set; }
  37. public StagingPanellSettings()
  38. {
  39. MarkupPathway = "";
  40. SetoutsFolder = "";
  41. Script = null;
  42. MaximumDocumentSize = 0;
  43. }
  44. public string DefaultScript()
  45. {
  46. return @"
  47. using PRSDesktop;
  48. using InABox.Core;
  49. using System.Collections.Generic;
  50. public class Module
  51. {
  52. /*public void CustomiseSetouts(CustomiseSetoutsArgs args)
  53. {
  54. // Perform customisation on the setouts when they are added to the 'Staged Documents' grid.
  55. }*/
  56. }";
  57. }
  58. }
  59. public class CustomiseSetoutsArgs
  60. {
  61. public IReadOnlyList<Tuple<StagingSetout, Document>> Setouts;
  62. public CustomiseSetoutsArgs(IReadOnlyList<Tuple<StagingSetout, Document>> setouts)
  63. {
  64. Setouts = setouts;
  65. }
  66. }
  67. /// <summary>
  68. /// Interaction logic for StagingPanel.xaml
  69. /// </summary>
  70. public partial class StagingPanel : UserControl, IPanel<StagingSetout>
  71. {
  72. private StagingPanellSettings _settings = new StagingPanellSettings();
  73. /// <summary>
  74. /// The currently selected setout.
  75. /// </summary>
  76. private StagingSetout? selectedSetout;
  77. /// <summary>
  78. /// All currently selected setouts; <see cref="selectedSetout"/> will be a member of this list.
  79. /// </summary>
  80. private List<StagingSetout> selectedSetouts = new();
  81. private CoreTable _templateGroups = null!;
  82. #region Script Stuff
  83. private MethodInfo? _customiseSetoutsMethod;
  84. private MethodInfo? CustomiseSetoutsMethod
  85. {
  86. get
  87. {
  88. EnsureScript();
  89. return _customiseSetoutsMethod;
  90. }
  91. }
  92. private object? _scriptObject;
  93. private object? ScriptObject
  94. {
  95. get
  96. {
  97. EnsureScript();
  98. return _scriptObject;
  99. }
  100. }
  101. private ScriptDocument? _script;
  102. private ScriptDocument? Script
  103. {
  104. get
  105. {
  106. EnsureScript();
  107. return _script;
  108. }
  109. }
  110. private void EnsureScript()
  111. {
  112. if (_script is null && !_settings.Script.IsNullOrWhiteSpace())
  113. {
  114. _script = new ScriptDocument(_settings.Script);
  115. if (!_script.Compile())
  116. {
  117. throw new Exception("Script in Staging Panel Settings failed to compile!");
  118. }
  119. _scriptObject = _script?.GetObject();
  120. _customiseSetoutsMethod = _script?.GetMethod(methodName: "CustomiseSetouts");
  121. }
  122. }
  123. #endregion
  124. public StagingPanel()
  125. {
  126. InitializeComponent();
  127. SectionName = nameof(StagingPanel);
  128. }
  129. public void Setup()
  130. {
  131. _settings = new GlobalConfiguration<StagingPanellSettings>().Load();
  132. _templateGroups = new Client<ManufacturingTemplateGroup>().Query();
  133. MarkUpButton.Visibility = Security.IsAllowed<CanMarkUpSetouts>() ? Visibility.Visible : Visibility.Hidden;
  134. RejectButton.Visibility = Security.IsAllowed<CanApproveSetouts>() ? Visibility.Visible : Visibility.Hidden;
  135. ApproveButton.Visibility = Security.IsAllowed<CanApproveSetouts>() ? Visibility.Visible : Visibility.Hidden;
  136. ProcessButton.Visibility = Security.IsAllowed<CanApproveSetouts>() ? Visibility.Visible : Visibility.Hidden;
  137. //stagingSetoutGrid.ScanFiles(_settings.SetoutsFolder);
  138. stagingSetoutGrid.PanelSettings = _settings;
  139. stagingSetoutGrid.Refresh(true, false);
  140. SetoutComponentGrid.Refresh(true, false);
  141. }
  142. private bool CanViewPackets() => MainPanel.View != DynamicSplitPanelView.Master && NestedPanel.View != DynamicSplitPanelView.Master;
  143. private void NestedPanel_OnChanged(object sender, DynamicSplitPanelSettings e)
  144. {
  145. if(CanViewPackets())
  146. {
  147. ManufacturingPacketList.Setout = selectedSetout;
  148. SetoutComponentGrid.StagingSetout = selectedSetout;
  149. }
  150. }
  151. #region Document Viewer
  152. public enum DocumentMode
  153. {
  154. Markup,
  155. Complete,
  156. Locked
  157. }
  158. private DocumentMode _mode;
  159. private DocumentMode Mode
  160. {
  161. get => _mode;
  162. set => SetMode(value);
  163. }
  164. private void SetMode(DocumentMode mode)
  165. {
  166. _mode = mode;
  167. if (_mode == DocumentMode.Markup)
  168. {
  169. MarkUpButton.Content = "Mark Up";
  170. MarkUpButton.IsEnabled = Document != null && !Document.Approved;
  171. UpdateOriginalButton.Visibility =
  172. Document != null && !String.Equals(Document.DocumentLink.CRC, selectedSetout?.OriginalCRC)
  173. ? Visibility.Visible
  174. : Visibility.Collapsed;
  175. ProcessButton.IsEnabled = Document != null && Document.Approved;
  176. RejectButton.IsEnabled = Document != null && !Document.Approved;
  177. ApproveButton.IsEnabled = Document != null;
  178. }
  179. else if (_mode == DocumentMode.Complete)
  180. {
  181. MarkUpButton.Content = "Complete";
  182. MarkUpButton.IsEnabled = Document != null;
  183. UpdateOriginalButton.Visibility = Visibility.Collapsed;
  184. ProcessButton.IsEnabled = false;
  185. RejectButton.IsEnabled = false;
  186. ApproveButton.IsEnabled = false;
  187. }
  188. else if (_mode == DocumentMode.Locked)
  189. {
  190. MarkUpButton.Content = "Locked";
  191. MarkUpButton.IsEnabled = false;
  192. UpdateOriginalButton.Visibility = Visibility.Collapsed;
  193. ProcessButton.IsEnabled = false;
  194. RejectButton.IsEnabled = false;
  195. ApproveButton.IsEnabled = false;
  196. }
  197. }
  198. private StagingSetoutDocument? _document;
  199. private StagingSetoutDocument? Document
  200. {
  201. get => _document;
  202. set
  203. {
  204. _document = value;
  205. if(_document is not null)
  206. {
  207. ApproveButton.Content = _document.Approved ? "Unapprove" : "Approve";
  208. }
  209. }
  210. }
  211. private byte[]? _documentdata = null;
  212. private void ClearDocuments()
  213. {
  214. Document = null;
  215. RenderDocuments(null);
  216. }
  217. private List<byte[]>? GetDocuments(StagingSetoutDocument? document)
  218. {
  219. if(document is null)
  220. {
  221. return null;
  222. }
  223. var table = new Client<Document>().Query(
  224. new Filter<Document>(x => x.ID).IsEqualTo(document.DocumentLink.ID),
  225. Columns.None<Document>().Add(x => x.Data));
  226. var first = table.Rows.FirstOrDefault();
  227. if (first is null)
  228. return null;
  229. _documentdata = first.Get<Document, byte[]>(x => x.Data);
  230. return ImageUtils.RenderPDFToImageBytes(_documentdata);
  231. }
  232. private void RenderDocuments(List<byte[]>? documents)
  233. {
  234. DocumentViewer.Children.Clear();
  235. if(documents is not null)
  236. {
  237. foreach (var image in documents)
  238. {
  239. DocumentViewer.Children.Add(new Image
  240. {
  241. Source = ImageUtils.LoadImage(image),
  242. Margin = new Thickness(0, 0, 0, 20)
  243. });
  244. }
  245. }
  246. }
  247. private void ProcessButton_Click(object sender, RoutedEventArgs e)
  248. {
  249. bool bulkApprove = false;
  250. if (selectedSetouts.Count > 1)
  251. {
  252. if (MessageBox.Show("Bulk approve? (Skip individual setout approval)", "Continue?", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
  253. {
  254. bulkApprove = true;
  255. Progress.Show("Approving Setouts..");
  256. }
  257. }
  258. if (selectedSetouts.Any(x => x.UnapprovedDocuments > 0))
  259. {
  260. MessageBox.Show("Cannot process setouts with unapproved documents.");
  261. Progress.Close();
  262. return;
  263. }
  264. if (selectedSetouts.Any(x => x.JobLink.ID == Guid.Empty))
  265. {
  266. MessageBox.Show("Cannot process setout without a linked job.");
  267. Progress.Close();
  268. return;
  269. }
  270. if (ManufacturingPacketList.Packets.Any(x => x.Template.ID == Guid.Empty))
  271. {
  272. MessageBox.Show("Cannot process manufacturing packets without templates.");
  273. Progress.Close();
  274. return;
  275. }
  276. if (selectedSetouts.Any(x => x.Packets == 0))
  277. {
  278. if (MessageBox.Show("Warning: some setouts do not have any manufacturing packets: are you sure you wish to proceed?", "Warning", MessageBoxButton.YesNoCancel) != MessageBoxResult.Yes)
  279. {
  280. Progress.Close();
  281. return;
  282. }
  283. }
  284. string message = "";
  285. foreach (var item in selectedSetouts)
  286. {
  287. if (bulkApprove)
  288. Progress.Show("Working on " + item.Number);
  289. var returnstring = ApproveSetout(item, bulkApprove);
  290. if (!string.IsNullOrWhiteSpace(returnstring))
  291. message = message + returnstring + Environment.NewLine;
  292. }
  293. if (bulkApprove)
  294. Progress.Close();
  295. new Client<StagingSetout>().Save(selectedSetouts, "Updated from staging screen");
  296. selectedSetout = null;
  297. Refresh();
  298. if (!message.IsNullOrWhiteSpace())
  299. {
  300. MessageBox.Show($"Result:\n{message}");
  301. }
  302. MainPanel.View = DynamicSplitPanelView.Combined;
  303. NestedPanel.View = DynamicSplitPanelView.Master;
  304. }
  305. private string ApproveSetout(StagingSetout item, bool bulkapprove)
  306. {
  307. if (item.Group.ID == Guid.Empty)
  308. {
  309. var message = "Setout has no group assigned";
  310. if (Security.IsAllowed<CanApproveSetoutsWithoutGroup>())
  311. {
  312. if (MessageBox.Show(message + ", continue?", "Continue?", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
  313. return "";
  314. }
  315. else
  316. {
  317. MessageBox.Show(message + ", please assign a group!");
  318. return "";
  319. }
  320. }
  321. var setoutDocument = new Client<StagingSetoutDocument>()
  322. .Query(
  323. new Filter<StagingSetoutDocument>(x => x.EntityLink.ID).IsEqualTo(item.ID),
  324. Columns.None<StagingSetoutDocument>().Add(x => x.ID, x => x.DocumentLink.ID, x => x.DocumentLink.FileName))
  325. .ToObjects<StagingSetoutDocument>().FirstOrDefault();
  326. if (setoutDocument is null)
  327. return "";
  328. var setout = new Client<Setout>()
  329. .Query(
  330. new Filter<Setout>(x => x.Number).IsEqualTo(item.Number),
  331. Columns.Required<Setout>().Add(x => x.ID))
  332. .ToObjects<Setout>().FirstOrDefault();
  333. string result;
  334. //setout already exists - create new setoutdoc and supercede old ones
  335. if (setout is not null)
  336. {
  337. if (!bulkapprove)
  338. if (MessageBox.Show("Supercede existing documents?", "Proceed?", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
  339. return "";
  340. setout.Group.ID = item.Group.ID;
  341. item.Setout.ID = setout.ID;
  342. var setoutdoc = new SetoutDocument();
  343. setoutdoc.EntityLink.ID = setout.ID;
  344. setoutdoc.DocumentLink.ID = setoutDocument.DocumentLink.ID;
  345. var setoutdocs = new List<SetoutDocument>
  346. {
  347. setoutdoc
  348. };
  349. CoreTable oldDocsTable = new Client<SetoutDocument>().Query(
  350. new Filter<SetoutDocument>(x => x.EntityLink.ID).IsEqualTo((Guid)setout.ID)
  351. .And(x => x.DocumentLink.ID).IsNotEqualTo(item.Group.OptimizationDocument.ID)
  352. );
  353. foreach (var row in oldDocsTable.Rows)
  354. {
  355. var oldDoc = row.ToObject<SetoutDocument>();
  356. if (oldDoc.Superceded == DateTime.MinValue)
  357. {
  358. oldDoc.Superceded = DateTime.Now;
  359. setoutdocs.Add(oldDoc);
  360. }
  361. }
  362. new Client<SetoutDocument>().Save(setoutdocs, "Updated from Staging Screen");
  363. new Client<Setout>().Save((Setout)setout, "Updated from Staging Screen");
  364. result = item.Number + " Superceded";
  365. }
  366. //no setout for this pdf - create new
  367. else
  368. {
  369. setout = new Setout
  370. {
  371. Number = item.Number
  372. };
  373. setout.JobLink.ID = item.JobLink.ID;
  374. setout.Group.ID = item.Group.ID;
  375. var editor = new DynamicDataGrid<Setout>();
  376. editor.OnAfterSave += (editor, items) =>
  377. {
  378. CreateSetoutDocument(setout, item, setoutDocument);
  379. };
  380. if (!bulkapprove)
  381. {
  382. if (!editor.EditItems(new[] { setout }))
  383. {
  384. MessageBox.Show("Setout Creation Cancelled");
  385. return "";
  386. }
  387. else
  388. result = item.Number + " Created";
  389. }
  390. else
  391. {
  392. new Client<Setout>().Save(setout, "Added from staging screen");
  393. CreateSetoutDocument(setout, item, setoutDocument);
  394. result = item.Number + " Created";
  395. }
  396. }
  397. var tuples = new List<Tuple<ManufacturingPacket, StagingManufacturingPacket>>();
  398. var stagingPackets = new Client<StagingManufacturingPacket>()
  399. .Query(
  400. new Filter<StagingManufacturingPacket>(x => x.StagingSetout.ID).IsEqualTo(item.ID),
  401. Columns.Required<StagingManufacturingPacket>().Add(x => x.ID)
  402. .Add(x => x.Serial)
  403. .Add(x => x.Title)
  404. .Add(x => x.Quantity)
  405. .Add(x => x.BarcodeQuantity)
  406. .Add(x => x.Watermark)
  407. .Add(x => x.Group.Watermark)
  408. .Add(x => x.Location)
  409. .Add(x => x.ITP.ID)
  410. .Add(x => x.Job.ID)
  411. .Add(x => x.Template.ID));
  412. foreach(var stagingPacket in stagingPackets.ToObjects<StagingManufacturingPacket>())
  413. {
  414. if(stagingPacket.ManufacturingPacket.ID != Guid.Empty)
  415. {
  416. MessageBox.Show($"A manufacturing packet already exists for {stagingPacket.Serial}; skipping packet.");
  417. continue;
  418. }
  419. var packet = new ManufacturingPacket
  420. {
  421. Serial = stagingPacket.Serial,
  422. Title = stagingPacket.Title,
  423. Quantity = stagingPacket.Quantity,
  424. BarcodeQty = string.IsNullOrWhiteSpace(stagingPacket.BarcodeQuantity)
  425. ? stagingPacket.Quantity
  426. : int.Parse(stagingPacket.BarcodeQuantity),
  427. WaterMark = string.IsNullOrWhiteSpace(stagingPacket.Watermark)
  428. ? stagingPacket.Group.Watermark
  429. : stagingPacket.Watermark,
  430. Location = stagingPacket.Location
  431. };
  432. packet.SetoutLink.ID = setout.ID;
  433. packet.ITP.ID = stagingPacket.ITP.ID;
  434. packet.JobLink.ID = stagingPacket.Job.ID;
  435. packet.ManufacturingTemplateLink.ID = stagingPacket.Template.ID;
  436. tuples.Add(new(packet, stagingPacket));
  437. }
  438. new Client<ManufacturingPacket>().Save(tuples.Select(x => x.Item1), "Created from Design Management Panel");
  439. var newStages = new List<ManufacturingPacketStage>();
  440. var newComponents = new List<ManufacturingPacketComponent>();
  441. var newTreatments = new List<ManufacturingTreatment>();
  442. foreach(var (packet, stagingPacket) in tuples)
  443. {
  444. stagingPacket.ManufacturingPacket.ID = packet.ID;
  445. var stages = new Client<StagingManufacturingPacketStage>()
  446. .Query(
  447. new Filter<StagingManufacturingPacketStage>(x => x.Packet.ID).IsEqualTo(stagingPacket.ID),
  448. IManufacturingPacketGeneratorExtensions.GetPacketGeneratorRequiredColumns<StagingManufacturingPacketStage>());
  449. newStages.AddRange(stages.ToObjects<StagingManufacturingPacketStage>()
  450. .Select(x =>
  451. {
  452. var stage = x.CreateManufacturingPacketStage();
  453. stage.Parent.ID = packet.ID;
  454. return stage;
  455. }));
  456. var components = new Client<StagingManufacturingPacketComponent>()
  457. .Query(
  458. new Filter<StagingManufacturingPacketComponent>(x => x.Packet.ID).IsEqualTo(stagingPacket.ID),
  459. Columns.None<StagingManufacturingPacketComponent>().Add(x=>x.Packet.ID)
  460. .Add(x => x.Product.ID)
  461. .Add(x => x.Quantity)
  462. .Add(x => x.Dimensions.Unit.ID)
  463. .Add(x => x.Dimensions.Quantity)
  464. .Add(x => x.Dimensions.Length)
  465. .Add(x => x.Dimensions.Width)
  466. .Add(x => x.Dimensions.Height)
  467. .Add(x => x.Dimensions.Weight)
  468. .Add(x => x.Dimensions.Value)
  469. .Add(x => x.Dimensions.UnitSize)
  470. );
  471. newComponents.AddRange(components.ToObjects<StagingManufacturingPacketComponent>()
  472. .Select(x => x.CreateComponent(packet.ID)));
  473. var treatments = new Client<StagingManufacturingPacketTreatment>()
  474. .Query(
  475. new Filter<StagingManufacturingPacketTreatment>(x => x.Packet.ID).IsEqualTo(stagingPacket.ID),
  476. Columns.None<StagingManufacturingPacketTreatment>().Add(x=>x.Packet.ID)
  477. .Add(x=>x.Product.ID)
  478. .Add(x=>x.Parameter)
  479. );
  480. newTreatments.AddRange(treatments.ToObjects<StagingManufacturingPacketTreatment>()
  481. .Select(x => x.CreateTreatment(packet.ID)));
  482. }
  483. new Client<ManufacturingPacketStage>().Save(newStages, "Created from Design Management");
  484. new Client<ManufacturingPacketComponent>().Save(newComponents, "Created from Design Management");
  485. new Client<ManufacturingTreatment>().Save(newTreatments, "Created from Design Management");
  486. new Client<StagingManufacturingPacket>().Save(tuples.Select(x => x.Item2), "Created from Design Management");
  487. //currently not creating packets due to temporary change in requirements - to uncomment and check for validity when required
  488. //CreatePackets(setout);
  489. return result;
  490. }
  491. private static void CreateSetoutDocument(Setout setout, StagingSetout item, StagingSetoutDocument stagingsetoutdocument)
  492. {
  493. item.Setout.ID = setout.ID;
  494. var setoutdoc = new SetoutDocument();
  495. setoutdoc.EntityLink.ID = setout.ID;
  496. setoutdoc.DocumentLink.ID = stagingsetoutdocument.DocumentLink.ID;
  497. new Client<SetoutDocument>().Save(setoutdoc, "Added from staging screen");
  498. }
  499. private void RejectButton_Click(object sender, RoutedEventArgs e)
  500. {
  501. if (selectedSetout is null || Document is null)
  502. {
  503. MessageBox.Show("Please select a setout");
  504. return;
  505. }
  506. //dont create setout - setout.id remains blank
  507. //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
  508. //attach the document to the task for reference
  509. var task = new Kanban
  510. {
  511. Title = "Setout Review Task (setout rejected)",
  512. Description = "Please review the attached document for setout " + selectedSetout.Number
  513. };
  514. task.ManagerLink.ID = App.EmployeeID;
  515. if (DynamicGridUtils.EditEntity(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. MessageWindow.ShowMessage("Task creation cancelled - setout not rejected", "Action cancelled");
  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. Columns.Required<StagingSetoutDocument>().Add(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. Columns.None<StagingSetoutDocument>().Add(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. SystemSetupActions.ERPStatuses(host);
  758. }
  759. private void ConfigComponentProfiles(PanelAction obj)
  760. {
  761. var list = new DynamicImportList(
  762. typeof(StagingSetoutComponent),
  763. Guid.Empty,
  764. canImport: false
  765. );
  766. list.ShowDialog();
  767. }
  768. private void ConfigSettingsClick(PanelAction obj)
  769. {
  770. var grid = new DynamicItemsListGrid<StagingPanellSettings>();
  771. grid.OnCustomiseEditor += Grid_OnCustomiseEditor;
  772. if(grid.EditItems(new[] { _settings }))
  773. {
  774. new GlobalConfiguration<StagingPanellSettings>().Save(_settings);
  775. _script = null;
  776. }
  777. }
  778. private void Grid_OnCustomiseEditor(IDynamicEditorForm sender, StagingPanellSettings[]? items, DynamicGridColumn column, BaseEditor editor)
  779. {
  780. if (items?.FirstOrDefault() is not StagingPanellSettings settings) return;
  781. if (column.ColumnName == nameof(StagingPanellSettings.Script) && editor is ScriptEditor scriptEditor)
  782. {
  783. scriptEditor.Type = ScriptEditorType.TemplateEditor;
  784. scriptEditor.OnEditorClicked += () =>
  785. {
  786. var script = settings.Script.NotWhiteSpaceOr()
  787. ?? settings.DefaultScript();
  788. var editor = new ScriptEditorWindow(script, SyntaxLanguage.CSharp);
  789. if (editor.ShowDialog() == true)
  790. {
  791. sender.SetEditorValue(column.ColumnName, editor.Script);
  792. settings.Script = editor.Script;
  793. }
  794. };
  795. }
  796. }
  797. #endregion
  798. public void Heartbeat(TimeSpan time)
  799. {
  800. }
  801. public void Refresh()
  802. {
  803. //stagingSetoutGrid.ScanFiles(_settings.SetoutsFolder);
  804. refreshing = true;
  805. stagingSetoutGrid.Refresh(false, true);
  806. /*Document = null;
  807. selectedSetout = null;
  808. ManufacturingPacketList.Setout = null;
  809. SetoutComponentGrid.StagingSetout = null;*/
  810. CalculateTime();
  811. }
  812. private void stagingSetoutGrid_OnRefreshPackets()
  813. {
  814. if (CanViewPackets())
  815. {
  816. ManufacturingPacketList.Refresh();
  817. }
  818. }
  819. public Dictionary<string, object[]> Selected()
  820. {
  821. return new();
  822. }
  823. public void Shutdown(CancelEventArgs? cancel)
  824. {
  825. }
  826. public DataModel DataModel(Selection selection)
  827. {
  828. return new AutoDataModel<StagingSetout>(new Filter<StagingSetout>().All());
  829. }
  830. private void AddPacketButton_Click(object sender, RoutedEventArgs e)
  831. {
  832. if (_templateGroups.Rows.Any() == true)
  833. {
  834. ContextMenu menu = new ContextMenu();
  835. foreach (var row in _templateGroups.Rows)
  836. {
  837. menu.AddItem(
  838. $"{row.Get<ManufacturingTemplateGroup, String>(x => x.Code)}: {row.Get<ManufacturingTemplateGroup, String>(x => x.Description)}",
  839. null,
  840. () =>
  841. {
  842. ManufacturingPacketList.Add(
  843. selectedSetout?.JobLink.ID ?? Guid.Empty,
  844. row.ToObject<ManufacturingTemplateGroup>()
  845. );
  846. UpdateStagingSetoutGrid();
  847. });
  848. }
  849. menu.AddSeparator();
  850. menu.AddItem("Miscellaneous Item", null, () =>
  851. {
  852. ManufacturingPacketList.Add(
  853. selectedSetout?.JobLink.ID ?? Guid.Empty,
  854. null
  855. );
  856. UpdateStagingSetoutGrid();
  857. });
  858. menu.IsOpen = true;
  859. }
  860. else
  861. {
  862. ManufacturingPacketList.Add(
  863. selectedSetout?.JobLink.ID ?? Guid.Empty,
  864. null
  865. );
  866. UpdateStagingSetoutGrid();
  867. }
  868. }
  869. private void UpdateStagingSetoutGrid()
  870. {
  871. var selected = stagingSetoutGrid.SelectedRows.FirstOrDefault();
  872. if (selected != null)
  873. {
  874. var packets = ManufacturingPacketList.Packets;
  875. selected.Set<StagingSetout, int>(x => x.Packets, packets.Length);
  876. selected.Set<StagingSetout, int>(x => x.UnprocessedPackets, packets.Count(x => x.ManufacturingPacket.ID == Guid.Empty));
  877. stagingSetoutGrid.InvalidateRow(selected);
  878. }
  879. }
  880. private void CollapsePacketsButton_Click(object sender, RoutedEventArgs e)
  881. {
  882. if (ManufacturingPacketList.Collapsed())
  883. {
  884. ManufacturingPacketList.Uncollapse();
  885. }
  886. else
  887. {
  888. ManufacturingPacketList.Collapse();
  889. }
  890. }
  891. private void ManufacturingPacketList_OnCollapsed(bool collapsed)
  892. {
  893. if (collapsed)
  894. {
  895. CollapsePacketsButton.Content = "Expand";
  896. }
  897. else
  898. {
  899. CollapsePacketsButton.Content = "Collapse";
  900. }
  901. }
  902. private void stagingSetoutGrid_OnCustomiseSetouts(IReadOnlyList<StagingSetoutGrid.SetoutDocument> setouts)
  903. {
  904. if(CustomiseSetoutsMethod != null && ScriptObject != null)
  905. {
  906. CustomiseSetoutsMethod?.Invoke(ScriptObject, new object?[]
  907. {
  908. new CustomiseSetoutsArgs(setouts.Select(x => new Tuple<StagingSetout, Document>(x.Setout, x.Document)).ToImmutableList())
  909. });
  910. }
  911. }
  912. private void StagingSetoutGrid_OnOnDoubleClick(object sender, HandledEventArgs args)
  913. {
  914. ManufacturingPacketList.Setout = selectedSetout;
  915. SetoutComponentGrid.StagingSetout = selectedSetout;
  916. MainPanel.View = DynamicSplitPanelView.Detail;
  917. NestedPanel.View = DynamicSplitPanelView.Combined;
  918. args.Handled = true;
  919. }
  920. private void CalculateTime()
  921. {
  922. if (selectedSetout != null)
  923. {
  924. var time = ManufacturingPacketList.TimeRequired();
  925. TimeRequired.Content = $"{time.TotalHours:F2} hours";
  926. }
  927. else
  928. TimeRequired.Content = "N/A";
  929. }
  930. private void ManufacturingPacketList_OnChanged(object? sender, EventArgs e)
  931. {
  932. CalculateTime();
  933. UpdateStagingSetoutGrid();
  934. }
  935. private void DoImport(Importer importer, string? componentFileName, Guid setoutID)
  936. {
  937. var success = DynamicImportGrid.CreateImporter(importer, ref componentFileName, out var iimporter);
  938. if (!success)
  939. {
  940. return;
  941. }
  942. var errors = new List<string>();
  943. var stagingSetoutComponents = new List<StagingSetoutComponent>();
  944. iimporter.OnLoad += Iimporter_OnLoad;
  945. iimporter.OnSave += (_, entity) => stagingSetoutComponents.Add((entity as StagingSetoutComponent)!);
  946. iimporter.OnError += (_, error) => errors.Add(error);
  947. using var stream = new FileStream(componentFileName!, FileMode.Open, FileAccess.Read);
  948. if (iimporter.Open(stream))
  949. {
  950. if (iimporter.ReadHeader())
  951. {
  952. var mismatches = iimporter.Mappings.Where(x =>
  953. !string.IsNullOrWhiteSpace(x.Field) &&
  954. !iimporter.Fields.Contains(x.Field)
  955. ).Select(x => x.Field).ToArray();
  956. if (!mismatches.Any())
  957. {
  958. var imported = iimporter.Import();
  959. if (errors.Any())
  960. {
  961. MessageBox.Show($"Import for component file {componentFileName} failed:\nSome errors occurred: {string.Join('\n', errors)}", "Import failed");
  962. }
  963. else
  964. {
  965. var valid = true;
  966. var conflicts = false;
  967. if (setoutID != Guid.Empty)
  968. {
  969. var newComponents = new List<StagingSetoutComponent>();
  970. foreach (var component in stagingSetoutComponents)
  971. {
  972. if (component.StagingSetout.ID == Guid.Empty)
  973. {
  974. component.StagingSetout.ID = setoutID;
  975. newComponents.Add(component);
  976. }
  977. else if (component.StagingSetout.ID != setoutID)
  978. {
  979. conflicts = true;
  980. // Ignoring this item.
  981. }
  982. else
  983. {
  984. newComponents.Add(component);
  985. }
  986. }
  987. stagingSetoutComponents = newComponents;
  988. if (conflicts)
  989. {
  990. MessageBox.Show($"Warning: the lines in this file have conflicting setout numbers.", "Warning");
  991. }
  992. }
  993. if (valid)
  994. {
  995. foreach (var component in stagingSetoutComponents)
  996. {
  997. if (component.StagingSetout.ID == Guid.Empty)
  998. {
  999. MessageBox.Show($"Component with no related setout cannot be imported.");
  1000. valid = false;
  1001. break;
  1002. }
  1003. else if (component.Description.IsNullOrWhiteSpace())
  1004. {
  1005. MessageBox.Show($"Component with no description cannot be imported.");
  1006. valid = false;
  1007. break;
  1008. }
  1009. else if (component.Dimensions.Unit.ID == Guid.Empty)
  1010. {
  1011. MessageBox.Show($"Component with no dimensions unit cannot be imported.");
  1012. valid = false;
  1013. break;
  1014. }
  1015. }
  1016. }
  1017. if (valid)
  1018. {
  1019. new Client<StagingSetoutComponent>().Save(stagingSetoutComponents, $"Imported from {componentFileName}");
  1020. SetoutComponentGrid.Refresh(false, true);
  1021. }
  1022. else
  1023. {
  1024. MessageBox.Show($"Import for component file {componentFileName} failed.", "Import failed");
  1025. }
  1026. }
  1027. }
  1028. else
  1029. {
  1030. MessageBox.Show("Import Mappings do not match file headers!\n\n- " + string.Join("\n- ", mismatches),
  1031. "Import Failed");
  1032. }
  1033. }
  1034. else
  1035. {
  1036. MessageBox.Show("Unable to Read Headers from {0}", Path.GetFileName(componentFileName));
  1037. }
  1038. }
  1039. else
  1040. {
  1041. MessageBox.Show("Unable to Open {0}", Path.GetFileName(componentFileName));
  1042. }
  1043. iimporter.Close();
  1044. }
  1045. private CoreTable Iimporter_OnLoad(object sender, Type type, string[] fields, string ID)
  1046. {
  1047. var result = new CoreTable();
  1048. result.LoadColumns(Columns.None<StagingSetoutComponent>().Add(fields));
  1049. return result;
  1050. }
  1051. private void stagingSetoutGrid_OnParseComponentFile(string componentFileName, Guid setoutID)
  1052. {
  1053. try
  1054. {
  1055. var entityName = typeof(StagingSetoutComponent).EntityName();
  1056. var importers = new Client<Importer>()
  1057. .Query(
  1058. new Filter<Importer>(x => x.EntityName).IsEqualTo(entityName),
  1059. Columns.None<Importer>().Add(x => x.ID));
  1060. if (importers.Rows.Count == 0)
  1061. {
  1062. var importer = new Importer
  1063. {
  1064. EntityName = entityName,
  1065. FileName = componentFileName
  1066. };
  1067. var form = new DynamicImportForm(importer);
  1068. if (form.ShowDialog() == true)
  1069. {
  1070. new Client<Importer>().Save(importer, "");
  1071. DoImport(importer, componentFileName, setoutID);
  1072. return;
  1073. }
  1074. }
  1075. else if (importers.Rows.Count == 1)
  1076. {
  1077. var importer = new Client<Importer>().Load(new Filter<Importer>(x => x.ID).IsEqualTo(importers.Rows[0].Get<Importer, Guid>(x => x.ID))).First();
  1078. DoImport(importer, componentFileName, setoutID);
  1079. }
  1080. else
  1081. {
  1082. var list = new PopupList(
  1083. typeof(Importer),
  1084. Guid.Empty,
  1085. Array.Empty<string>());
  1086. list.OnDefineFilter += t => new Filter<Importer>(x => x.EntityName).IsEqualTo(entityName);
  1087. if (list.ShowDialog() == true)
  1088. {
  1089. var importer = new Client<Importer>().Load(new Filter<Importer>(x => x.ID).IsEqualTo(list.ID)).First();
  1090. DoImport(importer, componentFileName, setoutID);
  1091. }
  1092. }
  1093. }
  1094. catch(Exception e)
  1095. {
  1096. Logger.Send(LogType.Error, "", $"Error in file {componentFileName}: {CoreUtils.FormatException(e)}");
  1097. MessageBox.Show($"Error opening {componentFileName}: {e.Message}");
  1098. }
  1099. }
  1100. }