StagingPanel.xaml.cs 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  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. {
  25. [Caption("Staging Panel Settings")]
  26. public class StagingPanellSettings : BaseObject, IGlobalConfigurationSettings
  27. {
  28. [Caption("PDF Markup Program Pathway", IncludePath = false)]
  29. [FileNameEditor]
  30. public string MarkupPathway { get; set; }
  31. [FolderEditor(Environment.SpecialFolder.CommonDocuments)]
  32. public string SetoutsFolder { get; set; }
  33. [ScriptEditor]
  34. public string? Script { get; set; }
  35. [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. var page = new TaskGrid();
  516. if (page.EditItems(new[] { task }))
  517. {
  518. var doc = new KanbanDocument();
  519. doc.EntityLink.ID = task.ID;
  520. doc.DocumentLink.ID = Document.DocumentLink.ID;
  521. new Client<KanbanDocument>().Save(doc, "Created from staging screen");
  522. selectedSetout.Task.ID = task.ID;
  523. new Client<StagingSetout>().Save(selectedSetout, "Updated from staging screen");
  524. MessageBox.Show("Success - Task Created for Document " + selectedSetout.Number + " (Task no. " + task.Number + " assigned to " + task.EmployeeLink.Name + ")");
  525. selectedSetout = null;
  526. ClearDocuments();
  527. refreshing = true;
  528. stagingSetoutGrid.Refresh(false, true);
  529. }
  530. else
  531. {
  532. MessageBox.Show("Task creation cancelled - setout not rejected");
  533. }
  534. }
  535. private void MarkUpButton_Click(object sender, RoutedEventArgs e)
  536. {
  537. if (Mode == DocumentMode.Markup)
  538. {
  539. Mode = DocumentMode.Complete;
  540. MessageBox.Show("IMPORTANT - press save in your document editor, then press the Complete Button in PRS");
  541. OnMarkupSelected();
  542. }
  543. else
  544. {
  545. OnMarkupComplete();
  546. Mode = DocumentMode.Markup;
  547. }
  548. }
  549. private void UpdateOriginalButton_Click(object sender, RoutedEventArgs e)
  550. {
  551. if ((_documentdata?.Any() == true) && !String.IsNullOrWhiteSpace(selectedSetout?.OriginalPath))
  552. {
  553. try
  554. {
  555. File.WriteAllBytes(selectedSetout.OriginalPath, _documentdata);
  556. selectedSetout.OriginalCRC = CoreUtils.CalculateCRC(_documentdata);
  557. new Client<StagingSetout>().Save(selectedSetout,"Updated Source File with markups");
  558. UpdateOriginalButton.Visibility = Visibility.Collapsed;
  559. }
  560. catch (Exception _exception)
  561. {
  562. MessageBox.Show($"Unable to update {selectedSetout?.OriginalPath}!\n\n{_exception.Message}");
  563. }
  564. return;
  565. }
  566. MessageBox.Show("Please select a design first!");
  567. }
  568. private void ApproveButton_Click(object sender, RoutedEventArgs e)
  569. {
  570. if (Document is null || selectedSetout is null)
  571. {
  572. MessageBox.Show("Please select a setout first.");
  573. return;
  574. }
  575. if (selectedSetouts.Count > 1)
  576. {
  577. var msg = Document.Approved
  578. ? "Bulk unapprove?"
  579. : "Bulk approve? (Skip individual setout approval)";
  580. if (MessageBox.Show(msg, "Continue?", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
  581. {
  582. Progress.Show("Approving Setouts..");
  583. var documents = Client.Query(
  584. new Filter<StagingSetoutDocument>(x => x.EntityLink.ID).InList(selectedSetouts.Select(x => x.ID).ToArray()),
  585. Columns.Required<StagingSetoutDocument>().Add(x => x.ID, x => x.Approved)
  586. ).ToObjects<StagingSetoutDocument>().ToList();
  587. foreach(var document in documents)
  588. {
  589. document.Approved = !Document.Approved;
  590. }
  591. Client.Save(documents, "Approved by user.");
  592. Progress.Close();
  593. refreshing = true;
  594. stagingSetoutGrid.Refresh(false, true);
  595. }
  596. }
  597. else
  598. {
  599. Document.Approved = !Document.Approved;
  600. new Client<StagingSetoutDocument>().Save(Document, "");
  601. refreshing = true;
  602. stagingSetoutGrid.Refresh(false, true);
  603. }
  604. }
  605. private void OnMarkupSelected()
  606. {
  607. if (Document is null || selectedSetout is null)
  608. {
  609. MessageBox.Show("Please select a setout first.");
  610. return;
  611. }
  612. var doc = new Client<Document>()
  613. .Query(
  614. new Filter<Document>(x => x.ID).IsEqualTo(Document.DocumentLink.ID))
  615. .ToObjects<Document>().FirstOrDefault();
  616. if (doc is null)
  617. {
  618. Logger.Send(LogType.Error, "", $"Document with ID {Document.DocumentLink.ID} could not be found.");
  619. MessageBox.Show("Error: the selected document could not be found in the database.");
  620. return;
  621. }
  622. var tempdocpath = Path.Combine(Path.GetTempPath(), doc.FileName);
  623. selectedSetout.SavePath = tempdocpath;
  624. selectedSetout.LockedBy.ID = App.EmployeeID;
  625. selectedSetout.LockedBy.Name = App.EmployeeName;
  626. new Client<StagingSetout>().Save(selectedSetout, "Locked from Staging Screen");
  627. File.WriteAllBytes(tempdocpath, doc.Data);
  628. using (var p = new Process())
  629. {
  630. p.StartInfo = new ProcessStartInfo()
  631. {
  632. UseShellExecute = true,
  633. FileName = tempdocpath
  634. };
  635. p.Start();
  636. }
  637. refreshing = true;
  638. stagingSetoutGrid.Refresh(false, true);
  639. }
  640. private void OnMarkupComplete()
  641. {
  642. if (selectedSetout is null)
  643. {
  644. MessageBox.Show("Please select a setout first.");
  645. return;
  646. }
  647. StagingSetoutGrid.ReloadFile(selectedSetout);
  648. refreshing = true;
  649. stagingSetoutGrid.Refresh(false, true);
  650. }
  651. #endregion
  652. private bool refreshing = false;
  653. private void stagingSetoutGrid_AfterRefresh(object sender, AfterRefreshEventArgs args)
  654. {
  655. refreshing = false;
  656. }
  657. private void StagingSetoutGrid_OnSelectItem(object sender, InABox.DynamicGrid.DynamicGridSelectionEventArgs e)
  658. {
  659. var newSetouts = new List<StagingSetout>();
  660. foreach (var row in e.Rows ?? Enumerable.Empty<CoreRow>())
  661. newSetouts.Add(row.ToObject<StagingSetout>());
  662. if(!refreshing && (selectedSetouts.Count == newSetouts.Count
  663. && !selectedSetouts.Any(x => !newSetouts.Any(y => x.ID == y.ID))))
  664. {
  665. selectedSetouts = newSetouts;
  666. selectedSetout = selectedSetouts.FirstOrDefault();
  667. return;
  668. }
  669. selectedSetouts = newSetouts;
  670. selectedSetout = selectedSetouts.FirstOrDefault();
  671. AddPacketButton.IsEnabled = selectedSetout is not null;
  672. if(selectedSetout is null)
  673. {
  674. ClearDocuments();
  675. ManufacturingPacketList.Setout = null;
  676. CollapsePacketsButton.IsEnabled = false;
  677. SetoutComponentGrid.StagingSetout = null;
  678. SetMode(DocumentMode.Markup);
  679. return;
  680. }
  681. var doc = new Client<StagingSetoutDocument>()
  682. .Query(
  683. new Filter<StagingSetoutDocument>(x => x.EntityLink.ID).IsEqualTo(selectedSetout.ID),
  684. Columns.None<StagingSetoutDocument>().Add(x => x.ID)
  685. .Add(x => x.DocumentLink.ID)
  686. .Add(x => x.DocumentLink.FileName)
  687. .Add(x => x.Approved)
  688. .Add(x=>x.DocumentLink.CRC)
  689. ).ToObjects<StagingSetoutDocument>().FirstOrDefault();
  690. if(doc is null)
  691. {
  692. MessageBox.Show("No document found for this setout.");
  693. ClearDocuments();
  694. ManufacturingPacketList.Setout = null;
  695. CollapsePacketsButton.IsEnabled = false;
  696. SetoutComponentGrid.StagingSetout = null;
  697. return;
  698. }
  699. Document = doc;
  700. var docTask = Task.Run(() => GetDocuments(doc));
  701. if(CanViewPackets())
  702. {
  703. ManufacturingPacketList.Setout = selectedSetout;
  704. SetoutComponentGrid.StagingSetout = selectedSetout;
  705. }
  706. CollapsePacketsButton.IsEnabled = true;
  707. var mode =
  708. selectedSetout.LockedBy.ID == Guid.Empty ?
  709. DocumentMode.Markup :
  710. selectedSetout.LockedBy.ID == App.EmployeeID ?
  711. DocumentMode.Complete :
  712. DocumentMode.Locked;
  713. docTask.Wait();
  714. RenderDocuments(docTask.Result);
  715. SetMode(mode);
  716. }
  717. public bool IsReady { get; set; }
  718. public string SectionName { get; }
  719. public event DataModelUpdateEvent? OnUpdateDataModel;
  720. #region Settings
  721. public void CreateToolbarButtons(IPanelHost host)
  722. {
  723. ProjectSetupActions.JobStatuses(host);
  724. ProjectSetupActions.DrawingTemplates(host);
  725. host.CreateSetupSeparator();
  726. ProjectSetupActions.JobSpreadsheetTemplates(host);
  727. host.CreateSetupSeparator();
  728. ProjectSetupActions.SetoutGroups(host);
  729. host.CreateSetupSeparator();
  730. host.CreateSetupAction(
  731. new PanelAction()
  732. {
  733. Caption = "Setouts Configuration",
  734. Image = PRSDesktop.Resources.specifications,
  735. OnExecute = ConfigSettingsClick
  736. }
  737. );
  738. host.CreateSetupAction(
  739. new PanelAction()
  740. {
  741. Caption = "Component Import Profiles",
  742. Image = PRSDesktop.Resources.doc_xls,
  743. OnExecute = ConfigComponentProfiles
  744. });
  745. host.CreateSetupAction(
  746. new PanelAction()
  747. {
  748. Caption = "Template Products",
  749. Image = PRSDesktop.Resources.specifications,
  750. OnExecute =
  751. action =>
  752. {
  753. var list = new MasterList(typeof(ManufacturingTemplateGroupProducts));
  754. list.ShowDialog();
  755. }
  756. }
  757. );
  758. SystemSetupActions.ERPStatuses(host);
  759. }
  760. private void ConfigComponentProfiles(PanelAction obj)
  761. {
  762. var list = new DynamicImportList(
  763. typeof(StagingSetoutComponent),
  764. Guid.Empty,
  765. canImport: false
  766. );
  767. list.ShowDialog();
  768. }
  769. private void ConfigSettingsClick(PanelAction obj)
  770. {
  771. var grid = new DynamicItemsListGrid<StagingPanellSettings>();
  772. grid.OnCustomiseEditor += Grid_OnCustomiseEditor;
  773. if(grid.EditItems(new[] { _settings }))
  774. {
  775. new GlobalConfiguration<StagingPanellSettings>().Save(_settings);
  776. _script = null;
  777. }
  778. }
  779. private void Grid_OnCustomiseEditor(IDynamicEditorForm sender, StagingPanellSettings[]? items, DynamicGridColumn column, BaseEditor editor)
  780. {
  781. if (items?.FirstOrDefault() is not StagingPanellSettings settings) return;
  782. if (column.ColumnName == nameof(StagingPanellSettings.Script) && editor is ScriptEditor scriptEditor)
  783. {
  784. scriptEditor.Type = ScriptEditorType.TemplateEditor;
  785. scriptEditor.OnEditorClicked += () =>
  786. {
  787. var script = settings.Script.NotWhiteSpaceOr()
  788. ?? settings.DefaultScript();
  789. var editor = new ScriptEditorWindow(script, SyntaxLanguage.CSharp);
  790. if (editor.ShowDialog() == true)
  791. {
  792. sender.SetEditorValue(column.ColumnName, editor.Script);
  793. settings.Script = editor.Script;
  794. }
  795. };
  796. }
  797. }
  798. #endregion
  799. public void Heartbeat(TimeSpan time)
  800. {
  801. }
  802. public void Refresh()
  803. {
  804. //stagingSetoutGrid.ScanFiles(_settings.SetoutsFolder);
  805. refreshing = true;
  806. stagingSetoutGrid.Refresh(false, true);
  807. /*Document = null;
  808. selectedSetout = null;
  809. ManufacturingPacketList.Setout = null;
  810. SetoutComponentGrid.StagingSetout = null;*/
  811. CalculateTime();
  812. }
  813. private void stagingSetoutGrid_OnRefreshPackets()
  814. {
  815. if (CanViewPackets())
  816. {
  817. ManufacturingPacketList.Refresh();
  818. }
  819. }
  820. public Dictionary<string, object[]> Selected()
  821. {
  822. return new();
  823. }
  824. public void Shutdown(CancelEventArgs? cancel)
  825. {
  826. }
  827. public DataModel DataModel(Selection selection)
  828. {
  829. return new AutoDataModel<StagingSetout>(new Filter<StagingSetout>().All());
  830. }
  831. private void AddPacketButton_Click(object sender, RoutedEventArgs e)
  832. {
  833. if (_templateGroups.Rows.Any() == true)
  834. {
  835. ContextMenu menu = new ContextMenu();
  836. foreach (var row in _templateGroups.Rows)
  837. {
  838. menu.AddItem(
  839. $"{row.Get<ManufacturingTemplateGroup, String>(x => x.Code)}: {row.Get<ManufacturingTemplateGroup, String>(x => x.Description)}",
  840. null,
  841. () =>
  842. {
  843. ManufacturingPacketList.Add(
  844. selectedSetout?.JobLink.ID ?? Guid.Empty,
  845. row.ToObject<ManufacturingTemplateGroup>()
  846. );
  847. UpdateStagingSetoutGrid();
  848. });
  849. }
  850. menu.AddSeparator();
  851. menu.AddItem("Miscellaneous Item", null, () =>
  852. {
  853. ManufacturingPacketList.Add(
  854. selectedSetout?.JobLink.ID ?? Guid.Empty,
  855. null
  856. );
  857. UpdateStagingSetoutGrid();
  858. });
  859. menu.IsOpen = true;
  860. }
  861. else
  862. {
  863. ManufacturingPacketList.Add(
  864. selectedSetout?.JobLink.ID ?? Guid.Empty,
  865. null
  866. );
  867. UpdateStagingSetoutGrid();
  868. }
  869. }
  870. private void UpdateStagingSetoutGrid()
  871. {
  872. var selected = stagingSetoutGrid.SelectedRows.FirstOrDefault();
  873. if (selected != null)
  874. {
  875. var packets = ManufacturingPacketList.Packets;
  876. selected.Set<StagingSetout, int>(x => x.Packets, packets.Length);
  877. selected.Set<StagingSetout, int>(x => x.UnprocessedPackets, packets.Count(x => x.ManufacturingPacket.ID == Guid.Empty));
  878. stagingSetoutGrid.InvalidateRow(selected);
  879. }
  880. }
  881. private void CollapsePacketsButton_Click(object sender, RoutedEventArgs e)
  882. {
  883. if (ManufacturingPacketList.Collapsed())
  884. {
  885. ManufacturingPacketList.Uncollapse();
  886. }
  887. else
  888. {
  889. ManufacturingPacketList.Collapse();
  890. }
  891. }
  892. private void ManufacturingPacketList_OnCollapsed(bool collapsed)
  893. {
  894. if (collapsed)
  895. {
  896. CollapsePacketsButton.Content = "Expand";
  897. }
  898. else
  899. {
  900. CollapsePacketsButton.Content = "Collapse";
  901. }
  902. }
  903. private void stagingSetoutGrid_OnCustomiseSetouts(IReadOnlyList<StagingSetoutGrid.SetoutDocument> setouts)
  904. {
  905. if(CustomiseSetoutsMethod != null && ScriptObject != null)
  906. {
  907. CustomiseSetoutsMethod?.Invoke(ScriptObject, new object?[]
  908. {
  909. new CustomiseSetoutsArgs(setouts.Select(x => new Tuple<StagingSetout, Document>(x.Setout, x.Document)).ToImmutableList())
  910. });
  911. }
  912. }
  913. private void StagingSetoutGrid_OnOnDoubleClick(object sender, HandledEventArgs args)
  914. {
  915. ManufacturingPacketList.Setout = selectedSetout;
  916. SetoutComponentGrid.StagingSetout = selectedSetout;
  917. MainPanel.View = DynamicSplitPanelView.Detail;
  918. NestedPanel.View = DynamicSplitPanelView.Combined;
  919. args.Handled = true;
  920. }
  921. private void CalculateTime()
  922. {
  923. if (selectedSetout != null)
  924. {
  925. var time = ManufacturingPacketList.TimeRequired();
  926. TimeRequired.Content = $"{time.TotalHours:F2} hours";
  927. }
  928. else
  929. TimeRequired.Content = "N/A";
  930. }
  931. private void ManufacturingPacketList_OnChanged(object? sender, EventArgs e)
  932. {
  933. CalculateTime();
  934. UpdateStagingSetoutGrid();
  935. }
  936. private void DoImport(Importer importer, string? componentFileName, Guid setoutID)
  937. {
  938. var success = DynamicImportGrid.CreateImporter(importer, ref componentFileName, out var iimporter);
  939. if (!success)
  940. {
  941. return;
  942. }
  943. var errors = new List<string>();
  944. var stagingSetoutComponents = new List<StagingSetoutComponent>();
  945. iimporter.OnLoad += Iimporter_OnLoad;
  946. iimporter.OnSave += (_, entity) => stagingSetoutComponents.Add((entity as StagingSetoutComponent)!);
  947. iimporter.OnError += (_, error) => errors.Add(error);
  948. using var stream = new FileStream(componentFileName!, FileMode.Open, FileAccess.Read);
  949. if (iimporter.Open(stream))
  950. {
  951. if (iimporter.ReadHeader())
  952. {
  953. var mismatches = iimporter.Mappings.Where(x =>
  954. !string.IsNullOrWhiteSpace(x.Field) &&
  955. !iimporter.Fields.Contains(x.Field)
  956. ).Select(x => x.Field).ToArray();
  957. if (!mismatches.Any())
  958. {
  959. var imported = iimporter.Import();
  960. if (errors.Any())
  961. {
  962. MessageBox.Show($"Import for component file {componentFileName} failed:\nSome errors occurred: {string.Join('\n', errors)}", "Import failed");
  963. }
  964. else
  965. {
  966. var valid = true;
  967. var conflicts = false;
  968. if (setoutID != Guid.Empty)
  969. {
  970. var newComponents = new List<StagingSetoutComponent>();
  971. foreach (var component in stagingSetoutComponents)
  972. {
  973. if (component.StagingSetout.ID == Guid.Empty)
  974. {
  975. component.StagingSetout.ID = setoutID;
  976. newComponents.Add(component);
  977. }
  978. else if (component.StagingSetout.ID != setoutID)
  979. {
  980. conflicts = true;
  981. // Ignoring this item.
  982. }
  983. else
  984. {
  985. newComponents.Add(component);
  986. }
  987. }
  988. stagingSetoutComponents = newComponents;
  989. if (conflicts)
  990. {
  991. MessageBox.Show($"Warning: the lines in this file have conflicting setout numbers.", "Warning");
  992. }
  993. }
  994. if (valid)
  995. {
  996. foreach (var component in stagingSetoutComponents)
  997. {
  998. if (component.StagingSetout.ID == Guid.Empty)
  999. {
  1000. MessageBox.Show($"Component with no related setout cannot be imported.");
  1001. valid = false;
  1002. break;
  1003. }
  1004. else if (component.Description.IsNullOrWhiteSpace())
  1005. {
  1006. MessageBox.Show($"Component with no description cannot be imported.");
  1007. valid = false;
  1008. break;
  1009. }
  1010. else if (component.Dimensions.Unit.ID == Guid.Empty)
  1011. {
  1012. MessageBox.Show($"Component with no dimensions unit cannot be imported.");
  1013. valid = false;
  1014. break;
  1015. }
  1016. }
  1017. }
  1018. if (valid)
  1019. {
  1020. new Client<StagingSetoutComponent>().Save(stagingSetoutComponents, $"Imported from {componentFileName}");
  1021. SetoutComponentGrid.Refresh(false, true);
  1022. }
  1023. else
  1024. {
  1025. MessageBox.Show($"Import for component file {componentFileName} failed.", "Import failed");
  1026. }
  1027. }
  1028. }
  1029. else
  1030. {
  1031. MessageBox.Show("Import Mappings do not match file headers!\n\n- " + string.Join("\n- ", mismatches),
  1032. "Import Failed");
  1033. }
  1034. }
  1035. else
  1036. {
  1037. MessageBox.Show("Unable to Read Headers from {0}", Path.GetFileName(componentFileName));
  1038. }
  1039. }
  1040. else
  1041. {
  1042. MessageBox.Show("Unable to Open {0}", Path.GetFileName(componentFileName));
  1043. }
  1044. iimporter.Close();
  1045. }
  1046. private CoreTable Iimporter_OnLoad(object sender, Type type, string[] fields, string ID)
  1047. {
  1048. var result = new CoreTable();
  1049. result.LoadColumns(Columns.None<StagingSetoutComponent>().Add(fields));
  1050. return result;
  1051. }
  1052. private void stagingSetoutGrid_OnParseComponentFile(string componentFileName, Guid setoutID)
  1053. {
  1054. try
  1055. {
  1056. var entityName = typeof(StagingSetoutComponent).EntityName();
  1057. var importers = new Client<Importer>()
  1058. .Query(
  1059. new Filter<Importer>(x => x.EntityName).IsEqualTo(entityName),
  1060. Columns.None<Importer>().Add(x => x.ID));
  1061. if (importers.Rows.Count == 0)
  1062. {
  1063. var importer = new Importer
  1064. {
  1065. EntityName = entityName,
  1066. FileName = componentFileName
  1067. };
  1068. var form = new DynamicImportForm(importer);
  1069. if (form.ShowDialog() == true)
  1070. {
  1071. new Client<Importer>().Save(importer, "");
  1072. DoImport(importer, componentFileName, setoutID);
  1073. return;
  1074. }
  1075. }
  1076. else if (importers.Rows.Count == 1)
  1077. {
  1078. var importer = new Client<Importer>().Load(new Filter<Importer>(x => x.ID).IsEqualTo(importers.Rows[0].Get<Importer, Guid>(x => x.ID))).First();
  1079. DoImport(importer, componentFileName, setoutID);
  1080. }
  1081. else
  1082. {
  1083. var list = new PopupList(
  1084. typeof(Importer),
  1085. Guid.Empty,
  1086. Array.Empty<string>());
  1087. list.OnDefineFilter += t => new Filter<Importer>(x => x.EntityName).IsEqualTo(entityName);
  1088. if (list.ShowDialog() == true)
  1089. {
  1090. var importer = new Client<Importer>().Load(new Filter<Importer>(x => x.ID).IsEqualTo(list.ID)).First();
  1091. DoImport(importer, componentFileName, setoutID);
  1092. }
  1093. }
  1094. }
  1095. catch(Exception e)
  1096. {
  1097. Logger.Send(LogType.Error, "", $"Error in file {componentFileName}: {CoreUtils.FormatException(e)}");
  1098. MessageBox.Show($"Error opening {componentFileName}: {e.Message}");
  1099. }
  1100. }
  1101. }
  1102. }