StagingPanel.xaml.cs 48 KB

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