StagingPanel.xaml.cs 46 KB

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