StagingPanel.xaml.cs 47 KB

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