StagingPanel.xaml.cs 47 KB

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