StagingPanel.xaml.cs 47 KB

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