StagingPanel.xaml.cs 47 KB

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