StagingPanel.xaml.cs 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247
  1. using Comal.Classes;
  2. using InABox.Core;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using InABox.Clients;
  9. using InABox.Configuration;
  10. using InABox.DynamicGrid;
  11. using System.Diagnostics;
  12. using System.IO;
  13. using InABox.WPF;
  14. using InABox.Wpf;
  15. using System.ComponentModel;
  16. using InABox.Scripting;
  17. using System.Reflection;
  18. using System.Collections.Immutable;
  19. using StagingManufacturingPacketComponent = Comal.Classes.StagingManufacturingPacketComponent;
  20. using System.Threading.Tasks;
  21. using NPOI.SS.Formula.Functions;
  22. namespace PRSDesktop
  23. {
  24. [Caption("Staging Panel Settings")]
  25. public class StagingPanellSettings : BaseObject, IGlobalConfigurationSettings
  26. {
  27. [Caption("PDF Markup Program Pathway", IncludePath = false)]
  28. [FileNameEditor]
  29. public string MarkupPathway { get; set; }
  30. [FolderEditor(Environment.SpecialFolder.CommonDocuments)]
  31. public string SetoutsFolder { get; set; }
  32. [ScriptEditor]
  33. public string? Script { get; set; }
  34. [IntegerEditor(Caption = "Maximum Document Size (MB)", ToolTip = "The user will be warned when uploading documents which are larger than this size in megabytes. Set to zero for no maximum.")]
  35. public int MaximumDocumentSize { get; set; }
  36. public StagingPanellSettings()
  37. {
  38. MarkupPathway = "";
  39. SetoutsFolder = "";
  40. Script = null;
  41. MaximumDocumentSize = 0;
  42. }
  43. public string DefaultScript()
  44. {
  45. return @"
  46. using PRSDesktop;
  47. using InABox.Core;
  48. using System.Collections.Generic;
  49. public class Module
  50. {
  51. /*public void CustomiseSetouts(CustomiseSetoutsArgs args)
  52. {
  53. // Perform customisation on the setouts when they are added to the 'Staged Documents' grid.
  54. }*/
  55. }";
  56. }
  57. }
  58. public class CustomiseSetoutsArgs
  59. {
  60. public IReadOnlyList<Tuple<StagingSetout, Document>> Setouts;
  61. public CustomiseSetoutsArgs(IReadOnlyList<Tuple<StagingSetout, Document>> setouts)
  62. {
  63. Setouts = setouts;
  64. }
  65. }
  66. /// <summary>
  67. /// Interaction logic for StagingPanel.xaml
  68. /// </summary>
  69. public partial class StagingPanel : UserControl, IPanel<StagingSetout>
  70. {
  71. private StagingPanellSettings _settings = new StagingPanellSettings();
  72. /// <summary>
  73. /// The currently selected setout.
  74. /// </summary>
  75. private StagingSetout? selectedSetout;
  76. /// <summary>
  77. /// All currently selected setouts; <see cref="selectedSetout"/> will be a member of this list.
  78. /// </summary>
  79. private List<StagingSetout> selectedSetouts = new();
  80. private CoreTable _templateGroups = null!;
  81. #region Script Stuff
  82. private MethodInfo? _customiseSetoutsMethod;
  83. private MethodInfo? CustomiseSetoutsMethod
  84. {
  85. get
  86. {
  87. EnsureScript();
  88. return _customiseSetoutsMethod;
  89. }
  90. }
  91. private object? _scriptObject;
  92. private object? ScriptObject
  93. {
  94. get
  95. {
  96. EnsureScript();
  97. return _scriptObject;
  98. }
  99. }
  100. private ScriptDocument? _script;
  101. private ScriptDocument? Script
  102. {
  103. get
  104. {
  105. EnsureScript();
  106. return _script;
  107. }
  108. }
  109. private void EnsureScript()
  110. {
  111. if (_script is null && !_settings.Script.IsNullOrWhiteSpace())
  112. {
  113. _script = new ScriptDocument(_settings.Script);
  114. if (!_script.Compile())
  115. {
  116. throw new Exception("Script in Staging Panel Settings failed to compile!");
  117. }
  118. _scriptObject = _script?.GetObject();
  119. _customiseSetoutsMethod = _script?.GetMethod(methodName: "CustomiseSetouts");
  120. }
  121. }
  122. #endregion
  123. public StagingPanel()
  124. {
  125. InitializeComponent();
  126. SectionName = nameof(StagingPanel);
  127. }
  128. public void Setup()
  129. {
  130. _settings = new GlobalConfiguration<StagingPanellSettings>().Load();
  131. _templateGroups = new Client<ManufacturingTemplateGroup>().Query();
  132. MarkUpButton.Visibility = Security.IsAllowed<CanMarkUpSetouts>() ? Visibility.Visible : Visibility.Hidden;
  133. RejectButton.Visibility = Security.IsAllowed<CanApproveSetouts>() ? Visibility.Visible : Visibility.Hidden;
  134. ApproveButton.Visibility = Security.IsAllowed<CanApproveSetouts>() ? Visibility.Visible : Visibility.Hidden;
  135. ProcessButton.Visibility = Security.IsAllowed<CanApproveSetouts>() ? Visibility.Visible : Visibility.Hidden;
  136. //stagingSetoutGrid.ScanFiles(_settings.SetoutsFolder);
  137. stagingSetoutGrid.PanelSettings = _settings;
  138. stagingSetoutGrid.Refresh(true, false);
  139. SetoutComponentGrid.Refresh(true, false);
  140. }
  141. private bool CanViewPackets() => MainPanel.View != DynamicSplitPanelView.Master && NestedPanel.View != DynamicSplitPanelView.Master;
  142. private void NestedPanel_OnChanged(object sender, DynamicSplitPanelSettings e)
  143. {
  144. if(CanViewPackets())
  145. {
  146. ManufacturingPacketList.Setout = selectedSetout;
  147. SetoutComponentGrid.StagingSetout = selectedSetout;
  148. }
  149. }
  150. #region Document Viewer
  151. public enum DocumentMode
  152. {
  153. Markup,
  154. Complete,
  155. Locked
  156. }
  157. private DocumentMode _mode;
  158. private DocumentMode Mode
  159. {
  160. get => _mode;
  161. set => SetMode(value);
  162. }
  163. private void SetMode(DocumentMode mode)
  164. {
  165. _mode = mode;
  166. if (_mode == DocumentMode.Markup)
  167. {
  168. MarkUpButton.Content = "Mark Up";
  169. MarkUpButton.IsEnabled = Document != null && !Document.Approved;
  170. UpdateOriginalButton.Visibility =
  171. Document != null && !String.Equals(Document.DocumentLink.CRC, selectedSetout?.OriginalCRC)
  172. ? Visibility.Visible
  173. : Visibility.Collapsed;
  174. ProcessButton.IsEnabled = Document != null && Document.Approved;
  175. RejectButton.IsEnabled = Document != null && !Document.Approved;
  176. ApproveButton.IsEnabled = Document != null;
  177. }
  178. else if (_mode == DocumentMode.Complete)
  179. {
  180. MarkUpButton.Content = "Complete";
  181. MarkUpButton.IsEnabled = Document != null;
  182. UpdateOriginalButton.Visibility = Visibility.Collapsed;
  183. ProcessButton.IsEnabled = false;
  184. RejectButton.IsEnabled = false;
  185. ApproveButton.IsEnabled = false;
  186. }
  187. else if (_mode == DocumentMode.Locked)
  188. {
  189. MarkUpButton.Content = "Locked";
  190. MarkUpButton.IsEnabled = false;
  191. UpdateOriginalButton.Visibility = Visibility.Collapsed;
  192. ProcessButton.IsEnabled = false;
  193. RejectButton.IsEnabled = false;
  194. ApproveButton.IsEnabled = false;
  195. }
  196. }
  197. private StagingSetoutDocument? _document;
  198. private StagingSetoutDocument? Document
  199. {
  200. get => _document;
  201. set
  202. {
  203. _document = value;
  204. if(_document is not null)
  205. {
  206. ApproveButton.Content = _document.Approved ? "Unapprove" : "Approve";
  207. }
  208. }
  209. }
  210. private byte[]? _documentdata = null;
  211. private void ClearDocuments()
  212. {
  213. Document = null;
  214. RenderDocuments(null);
  215. }
  216. private List<byte[]>? GetDocuments(StagingSetoutDocument? document)
  217. {
  218. if(document is null)
  219. {
  220. return null;
  221. }
  222. var table = new Client<Document>().Query(
  223. new Filter<Document>(x => x.ID).IsEqualTo(document.DocumentLink.ID),
  224. new Columns<Document>(x => x.Data));
  225. var first = table.Rows.FirstOrDefault();
  226. if (first is null)
  227. return null;
  228. _documentdata = first.Get<Document, byte[]>(x => x.Data);
  229. return ImageUtils.RenderPDFToImageBytes(_documentdata);
  230. }
  231. private void RenderDocuments(List<byte[]>? documents)
  232. {
  233. DocumentViewer.Children.Clear();
  234. if(documents is not null)
  235. {
  236. foreach (var image in documents)
  237. {
  238. DocumentViewer.Children.Add(new Image
  239. {
  240. Source = ImageUtils.LoadImage(image),
  241. Margin = new Thickness(0, 0, 0, 20)
  242. });
  243. }
  244. }
  245. }
  246. private void ProcessButton_Click(object sender, RoutedEventArgs e)
  247. {
  248. bool bulkApprove = false;
  249. if (selectedSetouts.Count > 1)
  250. {
  251. if (MessageBox.Show("Bulk approve? (Skip individual setout approval)", "Continue?", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
  252. {
  253. bulkApprove = true;
  254. Progress.Show("Approving Setouts..");
  255. }
  256. }
  257. if (selectedSetouts.Any(x => x.UnapprovedDocuments > 0))
  258. {
  259. MessageBox.Show("Cannot process setouts with unapproved documents.");
  260. Progress.Close();
  261. return;
  262. }
  263. if (selectedSetouts.Any(x => x.JobLink.ID == Guid.Empty))
  264. {
  265. MessageBox.Show("Cannot process setout without a linked job.");
  266. Progress.Close();
  267. return;
  268. }
  269. if (ManufacturingPacketList.Packets.Any(x => x.Template.ID == Guid.Empty))
  270. {
  271. MessageBox.Show("Cannot process manufacturing packets without templates.");
  272. Progress.Close();
  273. return;
  274. }
  275. if (selectedSetouts.Any(x => x.Packets == 0))
  276. {
  277. if (MessageBox.Show("Warning: some setouts do not have any manufacturing packets: are you sure you wish to proceed?", "Warning", MessageBoxButton.YesNoCancel) != MessageBoxResult.Yes)
  278. {
  279. Progress.Close();
  280. return;
  281. }
  282. }
  283. string message = "";
  284. foreach (var item in selectedSetouts)
  285. {
  286. if (bulkApprove)
  287. Progress.Show("Working on " + item.Number);
  288. var returnstring = ApproveSetout(item, bulkApprove);
  289. if (!string.IsNullOrWhiteSpace(returnstring))
  290. message = message + returnstring + Environment.NewLine;
  291. }
  292. if (bulkApprove)
  293. Progress.Close();
  294. new Client<StagingSetout>().Save(selectedSetouts, "Updated from staging screen");
  295. selectedSetout = null;
  296. Refresh();
  297. if (!message.IsNullOrWhiteSpace())
  298. {
  299. MessageBox.Show($"Result:\n{message}");
  300. }
  301. MainPanel.View = DynamicSplitPanelView.Combined;
  302. NestedPanel.View = DynamicSplitPanelView.Master;
  303. }
  304. private string ApproveSetout(StagingSetout item, bool bulkapprove)
  305. {
  306. if (item.Group.ID == Guid.Empty)
  307. {
  308. var message = "Setout has no group assigned";
  309. if (Security.IsAllowed<CanApproveSetoutsWithoutGroup>())
  310. {
  311. if (MessageBox.Show(message + ", continue?", "Continue?", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
  312. return "";
  313. }
  314. else
  315. {
  316. MessageBox.Show(message + ", please assign a group!");
  317. return "";
  318. }
  319. }
  320. var setoutDocument = new Client<StagingSetoutDocument>()
  321. .Query(
  322. new Filter<StagingSetoutDocument>(x => x.EntityLink.ID).IsEqualTo(item.ID),
  323. new Columns<StagingSetoutDocument>(x => x.ID, x => x.DocumentLink.ID, x => x.DocumentLink.FileName))
  324. .ToObjects<StagingSetoutDocument>().FirstOrDefault();
  325. if (setoutDocument is null)
  326. return "";
  327. var setout = new Client<Setout>()
  328. .Query(
  329. new Filter<Setout>(x => x.Number).IsEqualTo(item.Number),
  330. new Columns<Setout>(x => x.ID))
  331. .ToObjects<Setout>().FirstOrDefault();
  332. string result;
  333. //setout already exists - create new setoutdoc and supercede old ones
  334. if (setout is not null)
  335. {
  336. if (!bulkapprove)
  337. if (MessageBox.Show("Supercede existing documents?", "Proceed?", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
  338. return "";
  339. setout.Group.ID = item.Group.ID;
  340. item.Setout.ID = setout.ID;
  341. var setoutdoc = new SetoutDocument();
  342. setoutdoc.EntityLink.ID = setout.ID;
  343. setoutdoc.DocumentLink.ID = setoutDocument.DocumentLink.ID;
  344. var setoutdocs = new List<SetoutDocument>
  345. {
  346. setoutdoc
  347. };
  348. CoreTable oldDocsTable = new Client<SetoutDocument>().Query(
  349. new Filter<SetoutDocument>(x => x.EntityLink.ID).IsEqualTo((Guid)setout.ID)
  350. .And(x => x.DocumentLink.ID).IsNotEqualTo(item.Group.OptimizationDocument.ID)
  351. );
  352. foreach (var row in oldDocsTable.Rows)
  353. {
  354. var oldDoc = row.ToObject<SetoutDocument>();
  355. if (oldDoc.Superceded == DateTime.MinValue)
  356. {
  357. oldDoc.Superceded = DateTime.Now;
  358. setoutdocs.Add(oldDoc);
  359. }
  360. }
  361. new Client<SetoutDocument>().Save(setoutdocs, "Updated from Staging Screen");
  362. new Client<Setout>().Save((Setout)setout, "Updated from Staging Screen");
  363. result = item.Number + " Superceded";
  364. }
  365. //no setout for this pdf - create new
  366. else
  367. {
  368. setout = new Setout
  369. {
  370. Number = item.Number
  371. };
  372. setout.JobLink.ID = item.JobLink.ID;
  373. setout.Group.ID = item.Group.ID;
  374. var editor = new DynamicDataGrid<Setout>();
  375. editor.OnAfterSave += (editor, items) =>
  376. {
  377. CreateSetoutDocument(setout, item, setoutDocument);
  378. };
  379. if (!bulkapprove)
  380. {
  381. if (!editor.EditItems(new[] { setout }))
  382. {
  383. MessageBox.Show("Setout Creation Cancelled");
  384. return "";
  385. }
  386. else
  387. result = item.Number + " Created";
  388. }
  389. else
  390. {
  391. new Client<Setout>().Save(setout, "Added from staging screen");
  392. CreateSetoutDocument(setout, item, setoutDocument);
  393. result = item.Number + " Created";
  394. }
  395. }
  396. var tuples = new List<Tuple<ManufacturingPacket, StagingManufacturingPacket>>();
  397. var stagingPackets = new Client<StagingManufacturingPacket>()
  398. .Query(
  399. new Filter<StagingManufacturingPacket>(x => x.StagingSetout.ID).IsEqualTo(item.ID),
  400. new Columns<StagingManufacturingPacket>(x => x.ID)
  401. .Add(x => x.Serial)
  402. .Add(x => x.Title)
  403. .Add(x => x.Quantity)
  404. .Add(x => x.BarcodeQuantity)
  405. .Add(x => x.Watermark)
  406. .Add(x => x.Group.Watermark)
  407. .Add(x => x.Location)
  408. .Add(x => x.ITP.ID)
  409. .Add(x => x.Job.ID)
  410. .Add(x => x.Template.ID));
  411. foreach(var stagingPacket in stagingPackets.ToObjects<StagingManufacturingPacket>())
  412. {
  413. if(stagingPacket.ManufacturingPacket.ID != Guid.Empty)
  414. {
  415. MessageBox.Show($"A manufacturing packet already exists for {stagingPacket.Serial}; skipping packet.");
  416. continue;
  417. }
  418. var packet = new ManufacturingPacket
  419. {
  420. Serial = stagingPacket.Serial,
  421. Title = stagingPacket.Title,
  422. Quantity = stagingPacket.Quantity,
  423. BarcodeQty = string.IsNullOrWhiteSpace(stagingPacket.BarcodeQuantity)
  424. ? stagingPacket.Quantity
  425. : int.Parse(stagingPacket.BarcodeQuantity),
  426. WaterMark = string.IsNullOrWhiteSpace(stagingPacket.Watermark)
  427. ? stagingPacket.Group.Watermark
  428. : stagingPacket.Watermark,
  429. Location = stagingPacket.Location
  430. };
  431. packet.SetoutLink.ID = setout.ID;
  432. packet.ITP.ID = stagingPacket.ITP.ID;
  433. packet.JobLink.ID = stagingPacket.Job.ID;
  434. packet.ManufacturingTemplateLink.ID = stagingPacket.Template.ID;
  435. tuples.Add(new(packet, stagingPacket));
  436. }
  437. new Client<ManufacturingPacket>().Save(tuples.Select(x => x.Item1), "Created from Design Management Panel");
  438. var newStages = new List<ManufacturingPacketStage>();
  439. var newComponents = new List<ManufacturingPacketComponent>();
  440. var newTreatments = new List<ManufacturingTreatment>();
  441. foreach(var (packet, stagingPacket) in tuples)
  442. {
  443. stagingPacket.ManufacturingPacket.ID = packet.ID;
  444. var stages = new Client<StagingManufacturingPacketStage>()
  445. .Query(
  446. new Filter<StagingManufacturingPacketStage>(x => x.Packet.ID).IsEqualTo(stagingPacket.ID),
  447. IManufacturingPacketGeneratorExtensions.GetPacketGeneratorRequiredColumns<StagingManufacturingPacketStage>());
  448. newStages.AddRange(stages.ToObjects<StagingManufacturingPacketStage>()
  449. .Select(x =>
  450. {
  451. var stage = x.CreateManufacturingPacketStage();
  452. stage.Parent.ID = packet.ID;
  453. return stage;
  454. }));
  455. var components = new Client<StagingManufacturingPacketComponent>()
  456. .Query(
  457. new Filter<StagingManufacturingPacketComponent>(x => x.Packet.ID).IsEqualTo(stagingPacket.ID),
  458. new Columns<StagingManufacturingPacketComponent>(x=>x.Packet.ID)
  459. .Add(x => x.Product.ID)
  460. .Add(x => x.Quantity)
  461. .Add(x => x.Dimensions.Unit.ID)
  462. .Add(x => x.Dimensions.Quantity)
  463. .Add(x => x.Dimensions.Length)
  464. .Add(x => x.Dimensions.Width)
  465. .Add(x => x.Dimensions.Height)
  466. .Add(x => x.Dimensions.Weight)
  467. .Add(x => x.Dimensions.Value)
  468. .Add(x => x.Dimensions.UnitSize)
  469. );
  470. newComponents.AddRange(components.ToObjects<StagingManufacturingPacketComponent>()
  471. .Select(x => x.CreateComponent(packet.ID)));
  472. var treatments = new Client<StagingManufacturingPacketTreatment>()
  473. .Query(
  474. new Filter<StagingManufacturingPacketTreatment>(x => x.Packet.ID).IsEqualTo(stagingPacket.ID),
  475. new Columns<StagingManufacturingPacketTreatment>(x=>x.Packet.ID)
  476. .Add(x=>x.Product.ID)
  477. .Add(x=>x.Parameter)
  478. );
  479. newTreatments.AddRange(treatments.ToObjects<StagingManufacturingPacketTreatment>()
  480. .Select(x => x.CreateTreatment(packet.ID)));
  481. }
  482. new Client<ManufacturingPacketStage>().Save(newStages, "Created from Design Management");
  483. new Client<ManufacturingPacketComponent>().Save(newComponents, "Created from Design Management");
  484. new Client<ManufacturingTreatment>().Save(newTreatments, "Created from Design Management");
  485. new Client<StagingManufacturingPacket>().Save(tuples.Select(x => x.Item2), "Created from Design Management");
  486. //currently not creating packets due to temporary change in requirements - to uncomment and check for validity when required
  487. //CreatePackets(setout);
  488. return result;
  489. }
  490. private static void CreateSetoutDocument(Setout setout, StagingSetout item, StagingSetoutDocument stagingsetoutdocument)
  491. {
  492. item.Setout.ID = setout.ID;
  493. var setoutdoc = new SetoutDocument();
  494. setoutdoc.EntityLink.ID = setout.ID;
  495. setoutdoc.DocumentLink.ID = stagingsetoutdocument.DocumentLink.ID;
  496. new Client<SetoutDocument>().Save(setoutdoc, "Added from staging screen");
  497. }
  498. private void RejectButton_Click(object sender, RoutedEventArgs e)
  499. {
  500. if (selectedSetout is null || Document is null)
  501. {
  502. MessageBox.Show("Please select a setout");
  503. return;
  504. }
  505. //dont create setout - setout.id remains blank
  506. //create kanban and populate task.id - this prevents it from appearing on the stagingsetout grid, and allows a new staging setout to be created when the file is saved to the folder again
  507. //attach the document to the task for reference
  508. var task = new Kanban
  509. {
  510. Title = "Setout Review Task (setout rejected)",
  511. Description = "Please review the attached document for setout " + selectedSetout.Number
  512. };
  513. task.ManagerLink.ID = App.EmployeeID;
  514. var page = new TaskGrid();
  515. page.MyID = App.EmployeeID;
  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. new Columns<StagingSetoutDocument>(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. new Columns<StagingSetoutDocument>(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. }
  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(new Columns<StagingSetoutComponent>(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. new Columns<Importer>(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. }
  1101. }