1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246 |
- using Comal.Classes;
- using InABox.Core;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Windows;
- using System.Windows.Controls;
- using InABox.Clients;
- using InABox.Configuration;
- using InABox.DynamicGrid;
- using System.Diagnostics;
- using System.IO;
- using InABox.WPF;
- using InABox.Wpf;
- using System.ComponentModel;
- using InABox.Scripting;
- using System.Reflection;
- using System.Collections.Immutable;
- using StagingManufacturingPacketComponent = Comal.Classes.StagingManufacturingPacketComponent;
- using System.Threading.Tasks;
- using NPOI.SS.Formula.Functions;
- namespace PRSDesktop
- {
- [Caption("Staging Panel Settings")]
- public class StagingPanellSettings : BaseObject, IGlobalConfigurationSettings
- {
- [Caption("PDF Markup Program Pathway", IncludePath = false)]
- [FileNameEditor]
- public string MarkupPathway { get; set; }
- [FolderEditor(Environment.SpecialFolder.CommonDocuments)]
- public string SetoutsFolder { get; set; }
- [ScriptEditor]
- public string? Script { get; set; }
- [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.")]
- public int MaximumDocumentSize { get; set; }
- public StagingPanellSettings()
- {
- MarkupPathway = "";
- SetoutsFolder = "";
- Script = null;
- MaximumDocumentSize = 0;
- }
- public string DefaultScript()
- {
- return @"
- using PRSDesktop;
- using InABox.Core;
- using System.Collections.Generic;
- public class Module
- {
- /*public void CustomiseSetouts(CustomiseSetoutsArgs args)
- {
- // Perform customisation on the setouts when they are added to the 'Staged Documents' grid.
- }*/
- }";
- }
- }
- public class CustomiseSetoutsArgs
- {
- public IReadOnlyList<Tuple<StagingSetout, Document>> Setouts;
- public CustomiseSetoutsArgs(IReadOnlyList<Tuple<StagingSetout, Document>> setouts)
- {
- Setouts = setouts;
- }
- }
- /// <summary>
- /// Interaction logic for StagingPanel.xaml
- /// </summary>
- public partial class StagingPanel : UserControl, IPanel<StagingSetout>
- {
- private StagingPanellSettings _settings = new StagingPanellSettings();
-
- /// <summary>
- /// The currently selected setout.
- /// </summary>
- private StagingSetout? selectedSetout;
- /// <summary>
- /// All currently selected setouts; <see cref="selectedSetout"/> will be a member of this list.
- /// </summary>
- private List<StagingSetout> selectedSetouts = new();
- private CoreTable _templateGroups = null!;
- #region Script Stuff
- private MethodInfo? _customiseSetoutsMethod;
- private MethodInfo? CustomiseSetoutsMethod
- {
- get
- {
- EnsureScript();
- return _customiseSetoutsMethod;
- }
- }
- private object? _scriptObject;
- private object? ScriptObject
- {
- get
- {
- EnsureScript();
- return _scriptObject;
- }
- }
- private ScriptDocument? _script;
- private ScriptDocument? Script
- {
- get
- {
- EnsureScript();
- return _script;
- }
- }
- private void EnsureScript()
- {
- if (_script is null && !_settings.Script.IsNullOrWhiteSpace())
- {
- _script = new ScriptDocument(_settings.Script);
- if (!_script.Compile())
- {
- throw new Exception("Script in Staging Panel Settings failed to compile!");
- }
- _scriptObject = _script?.GetObject();
- _customiseSetoutsMethod = _script?.GetMethod(methodName: "CustomiseSetouts");
- }
- }
- #endregion
- public StagingPanel()
- {
- InitializeComponent();
- SectionName = nameof(StagingPanel);
- }
- public void Setup()
- {
- _settings = new GlobalConfiguration<StagingPanellSettings>().Load();
-
- _templateGroups = new Client<ManufacturingTemplateGroup>().Query();
-
- MarkUpButton.Visibility = Security.IsAllowed<CanMarkUpSetouts>() ? Visibility.Visible : Visibility.Hidden;
- RejectButton.Visibility = Security.IsAllowed<CanApproveSetouts>() ? Visibility.Visible : Visibility.Hidden;
- ApproveButton.Visibility = Security.IsAllowed<CanApproveSetouts>() ? Visibility.Visible : Visibility.Hidden;
- ProcessButton.Visibility = Security.IsAllowed<CanApproveSetouts>() ? Visibility.Visible : Visibility.Hidden;
- //stagingSetoutGrid.ScanFiles(_settings.SetoutsFolder);
- stagingSetoutGrid.PanelSettings = _settings;
- stagingSetoutGrid.Refresh(true, false);
- SetoutComponentGrid.Refresh(true, false);
-
- }
- private bool CanViewPackets() => MainPanel.View != DynamicSplitPanelView.Master && NestedPanel.View != DynamicSplitPanelView.Master;
- private void NestedPanel_OnChanged(object sender, DynamicSplitPanelSettings e)
- {
- if(CanViewPackets())
- {
- ManufacturingPacketList.Setout = selectedSetout;
- SetoutComponentGrid.StagingSetout = selectedSetout;
- }
- }
- #region Document Viewer
- public enum DocumentMode
- {
- Markup,
- Complete,
- Locked
- }
- private DocumentMode _mode;
- private DocumentMode Mode
- {
- get => _mode;
- set => SetMode(value);
- }
- private void SetMode(DocumentMode mode)
- {
- _mode = mode;
- if (_mode == DocumentMode.Markup)
- {
- MarkUpButton.Content = "Mark Up";
- MarkUpButton.IsEnabled = Document != null && !Document.Approved;
- UpdateOriginalButton.Visibility =
- Document != null && !String.Equals(Document.DocumentLink.CRC, selectedSetout?.OriginalCRC)
- ? Visibility.Visible
- : Visibility.Collapsed;
- ProcessButton.IsEnabled = Document != null && Document.Approved;
- RejectButton.IsEnabled = Document != null && !Document.Approved;
- ApproveButton.IsEnabled = Document != null;
- }
- else if (_mode == DocumentMode.Complete)
- {
- MarkUpButton.Content = "Complete";
- MarkUpButton.IsEnabled = Document != null;
- UpdateOriginalButton.Visibility = Visibility.Collapsed;
- ProcessButton.IsEnabled = false;
- RejectButton.IsEnabled = false;
- ApproveButton.IsEnabled = false;
- }
- else if (_mode == DocumentMode.Locked)
- {
- MarkUpButton.Content = "Locked";
- MarkUpButton.IsEnabled = false;
- UpdateOriginalButton.Visibility = Visibility.Collapsed;
- ProcessButton.IsEnabled = false;
- RejectButton.IsEnabled = false;
- ApproveButton.IsEnabled = false;
- }
- }
- private StagingSetoutDocument? _document;
- private StagingSetoutDocument? Document
- {
- get => _document;
- set
- {
- _document = value;
- if(_document is not null)
- {
- ApproveButton.Content = _document.Approved ? "Unapprove" : "Approve";
- }
- }
- }
- private byte[]? _documentdata = null;
- private void ClearDocuments()
- {
- Document = null;
- RenderDocuments(null);
- }
- private List<byte[]>? GetDocuments(StagingSetoutDocument? document)
- {
- if(document is null)
- {
- return null;
- }
- var table = new Client<Document>().Query(
- new Filter<Document>(x => x.ID).IsEqualTo(document.DocumentLink.ID),
- new Columns<Document>(x => x.Data));
- var first = table.Rows.FirstOrDefault();
- if (first is null)
- return null;
- _documentdata = first.Get<Document, byte[]>(x => x.Data);
- return ImageUtils.RenderPDFToImageBytes(_documentdata);
- }
-
- private void RenderDocuments(List<byte[]>? documents)
- {
- DocumentViewer.Children.Clear();
- if(documents is not null)
- {
- foreach (var image in documents)
- {
- DocumentViewer.Children.Add(new Image
- {
- Source = ImageUtils.LoadImage(image),
- Margin = new Thickness(0, 0, 0, 20)
- });
- }
- }
- }
- private void ProcessButton_Click(object sender, RoutedEventArgs e)
- {
- bool bulkApprove = false;
- if (selectedSetouts.Count > 1)
- {
- if (MessageBox.Show("Bulk approve? (Skip individual setout approval)", "Continue?", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
- {
- bulkApprove = true;
- Progress.Show("Approving Setouts..");
- }
- }
- if (selectedSetouts.Any(x => x.UnapprovedDocuments > 0))
- {
- MessageBox.Show("Cannot process setouts with unapproved documents.");
- Progress.Close();
- return;
- }
- if (selectedSetouts.Any(x => x.JobLink.ID == Guid.Empty))
- {
- MessageBox.Show("Cannot process setout without a linked job.");
- Progress.Close();
- return;
- }
- if (ManufacturingPacketList.Packets.Any(x => x.Template.ID == Guid.Empty))
- {
- MessageBox.Show("Cannot process manufacturing packets without templates.");
- Progress.Close();
- return;
- }
- if (selectedSetouts.Any(x => x.Packets == 0))
- {
- if (MessageBox.Show("Warning: some setouts do not have any manufacturing packets: are you sure you wish to proceed?", "Warning", MessageBoxButton.YesNoCancel) != MessageBoxResult.Yes)
- {
- Progress.Close();
- return;
- }
- }
- string message = "";
- foreach (var item in selectedSetouts)
- {
- if (bulkApprove)
- Progress.Show("Working on " + item.Number);
- var returnstring = ApproveSetout(item, bulkApprove);
- if (!string.IsNullOrWhiteSpace(returnstring))
- message = message + returnstring + Environment.NewLine;
- }
- if (bulkApprove)
- Progress.Close();
- new Client<StagingSetout>().Save(selectedSetouts, "Updated from staging screen");
- selectedSetout = null;
- Refresh();
- if (!message.IsNullOrWhiteSpace())
- {
- MessageBox.Show($"Result:\n{message}");
- }
- MainPanel.View = DynamicSplitPanelView.Combined;
- NestedPanel.View = DynamicSplitPanelView.Master;
- }
- private string ApproveSetout(StagingSetout item, bool bulkapprove)
- {
- if (item.Group.ID == Guid.Empty)
- {
- var message = "Setout has no group assigned";
- if (Security.IsAllowed<CanApproveSetoutsWithoutGroup>())
- {
- if (MessageBox.Show(message + ", continue?", "Continue?", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
- return "";
- }
- else
- {
- MessageBox.Show(message + ", please assign a group!");
- return "";
- }
- }
- var setoutDocument = new Client<StagingSetoutDocument>()
- .Query(
- new Filter<StagingSetoutDocument>(x => x.EntityLink.ID).IsEqualTo(item.ID),
- new Columns<StagingSetoutDocument>(x => x.ID, x => x.DocumentLink.ID, x => x.DocumentLink.FileName))
- .ToObjects<StagingSetoutDocument>().FirstOrDefault();
- if (setoutDocument is null)
- return "";
- var setout = new Client<Setout>()
- .Query(
- new Filter<Setout>(x => x.Number).IsEqualTo(item.Number),
- new Columns<Setout>(x => x.ID))
- .ToObjects<Setout>().FirstOrDefault();
- string result;
- //setout already exists - create new setoutdoc and supercede old ones
- if (setout is not null)
- {
- if (!bulkapprove)
- if (MessageBox.Show("Supercede existing documents?", "Proceed?", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
- return "";
- setout.Group.ID = item.Group.ID;
- item.Setout.ID = setout.ID;
- var setoutdoc = new SetoutDocument();
- setoutdoc.EntityLink.ID = setout.ID;
- setoutdoc.DocumentLink.ID = setoutDocument.DocumentLink.ID;
- var setoutdocs = new List<SetoutDocument>
- {
- setoutdoc
- };
- CoreTable oldDocsTable = new Client<SetoutDocument>().Query(
- new Filter<SetoutDocument>(x => x.EntityLink.ID).IsEqualTo((Guid)setout.ID)
- .And(x => x.DocumentLink.ID).IsNotEqualTo(item.Group.OptimizationDocument.ID)
- );
- foreach (var row in oldDocsTable.Rows)
- {
- var oldDoc = row.ToObject<SetoutDocument>();
- if (oldDoc.Superceded == DateTime.MinValue)
- {
- oldDoc.Superceded = DateTime.Now;
- setoutdocs.Add(oldDoc);
- }
- }
- new Client<SetoutDocument>().Save(setoutdocs, "Updated from Staging Screen");
- new Client<Setout>().Save((Setout)setout, "Updated from Staging Screen");
- result = item.Number + " Superceded";
- }
- //no setout for this pdf - create new
- else
- {
- setout = new Setout
- {
- Number = item.Number
- };
- setout.JobLink.ID = item.JobLink.ID;
- setout.Group.ID = item.Group.ID;
- var editor = new DynamicDataGrid<Setout>();
- editor.OnAfterSave += (editor, items) =>
- {
- CreateSetoutDocument(setout, item, setoutDocument);
- };
- if (!bulkapprove)
- {
- if (!editor.EditItems(new[] { setout }))
- {
- MessageBox.Show("Setout Creation Cancelled");
- return "";
- }
- else
- result = item.Number + " Created";
- }
- else
- {
- new Client<Setout>().Save(setout, "Added from staging screen");
- CreateSetoutDocument(setout, item, setoutDocument);
- result = item.Number + " Created";
- }
- }
- var tuples = new List<Tuple<ManufacturingPacket, StagingManufacturingPacket>>();
- var stagingPackets = new Client<StagingManufacturingPacket>()
- .Query(
- new Filter<StagingManufacturingPacket>(x => x.StagingSetout.ID).IsEqualTo(item.ID),
- new Columns<StagingManufacturingPacket>(x => x.ID)
- .Add(x => x.Serial)
- .Add(x => x.Title)
- .Add(x => x.Quantity)
- .Add(x => x.BarcodeQuantity)
- .Add(x => x.Watermark)
- .Add(x => x.Group.Watermark)
- .Add(x => x.Location)
- .Add(x => x.ITP.ID)
- .Add(x => x.Job.ID)
- .Add(x => x.Template.ID));
- foreach(var stagingPacket in stagingPackets.ToObjects<StagingManufacturingPacket>())
- {
- if(stagingPacket.ManufacturingPacket.ID != Guid.Empty)
- {
- MessageBox.Show($"A manufacturing packet already exists for {stagingPacket.Serial}; skipping packet.");
- continue;
- }
- var packet = new ManufacturingPacket
- {
- Serial = stagingPacket.Serial,
- Title = stagingPacket.Title,
- Quantity = stagingPacket.Quantity,
- BarcodeQty = string.IsNullOrWhiteSpace(stagingPacket.BarcodeQuantity)
- ? stagingPacket.Quantity
- : int.Parse(stagingPacket.BarcodeQuantity),
- WaterMark = string.IsNullOrWhiteSpace(stagingPacket.Watermark)
- ? stagingPacket.Group.Watermark
- : stagingPacket.Watermark,
- Location = stagingPacket.Location
- };
- packet.SetoutLink.ID = setout.ID;
- packet.ITP.ID = stagingPacket.ITP.ID;
- packet.JobLink.ID = stagingPacket.Job.ID;
- packet.ManufacturingTemplateLink.ID = stagingPacket.Template.ID;
- tuples.Add(new(packet, stagingPacket));
- }
- new Client<ManufacturingPacket>().Save(tuples.Select(x => x.Item1), "Created from Design Management Panel");
- var newStages = new List<ManufacturingPacketStage>();
- var newComponents = new List<ManufacturingPacketComponent>();
- var newTreatments = new List<ManufacturingTreatment>();
- foreach(var (packet, stagingPacket) in tuples)
- {
- stagingPacket.ManufacturingPacket.ID = packet.ID;
-
- var stages = new Client<StagingManufacturingPacketStage>()
- .Query(
- new Filter<StagingManufacturingPacketStage>(x => x.Packet.ID).IsEqualTo(stagingPacket.ID),
- IManufacturingPacketGeneratorExtensions.GetPacketGeneratorRequiredColumns<StagingManufacturingPacketStage>());
- newStages.AddRange(stages.ToObjects<StagingManufacturingPacketStage>()
- .Select(x =>
- {
- var stage = x.CreateManufacturingPacketStage();
- stage.Parent.ID = packet.ID;
- return stage;
- }));
-
- var components = new Client<StagingManufacturingPacketComponent>()
- .Query(
- new Filter<StagingManufacturingPacketComponent>(x => x.Packet.ID).IsEqualTo(stagingPacket.ID),
- new Columns<StagingManufacturingPacketComponent>(x=>x.Packet.ID)
- .Add(x => x.Product.ID)
- .Add(x => x.Quantity)
- .Add(x => x.Dimensions.Unit.ID)
- .Add(x => x.Dimensions.Quantity)
- .Add(x => x.Dimensions.Length)
- .Add(x => x.Dimensions.Width)
- .Add(x => x.Dimensions.Height)
- .Add(x => x.Dimensions.Weight)
- .Add(x => x.Dimensions.Value)
- .Add(x => x.Dimensions.UnitSize)
- );
-
- newComponents.AddRange(components.ToObjects<StagingManufacturingPacketComponent>()
- .Select(x => x.CreateComponent(packet.ID)));
-
- var treatments = new Client<StagingManufacturingPacketTreatment>()
- .Query(
- new Filter<StagingManufacturingPacketTreatment>(x => x.Packet.ID).IsEqualTo(stagingPacket.ID),
- new Columns<StagingManufacturingPacketTreatment>(x=>x.Packet.ID)
- .Add(x=>x.Product.ID)
- .Add(x=>x.Parameter)
- );
-
- newTreatments.AddRange(treatments.ToObjects<StagingManufacturingPacketTreatment>()
- .Select(x => x.CreateTreatment(packet.ID)));
-
- }
- new Client<ManufacturingPacketStage>().Save(newStages, "Created from Design Management");
- new Client<ManufacturingPacketComponent>().Save(newComponents, "Created from Design Management");
- new Client<ManufacturingTreatment>().Save(newTreatments, "Created from Design Management");
- new Client<StagingManufacturingPacket>().Save(tuples.Select(x => x.Item2), "Created from Design Management");
- //currently not creating packets due to temporary change in requirements - to uncomment and check for validity when required
- //CreatePackets(setout);
- return result;
- }
- private static void CreateSetoutDocument(Setout setout, StagingSetout item, StagingSetoutDocument stagingsetoutdocument)
- {
- item.Setout.ID = setout.ID;
- var setoutdoc = new SetoutDocument();
- setoutdoc.EntityLink.ID = setout.ID;
- setoutdoc.DocumentLink.ID = stagingsetoutdocument.DocumentLink.ID;
- new Client<SetoutDocument>().Save(setoutdoc, "Added from staging screen");
- }
- private void RejectButton_Click(object sender, RoutedEventArgs e)
- {
- if (selectedSetout is null || Document is null)
- {
- MessageBox.Show("Please select a setout");
- return;
- }
- //dont create setout - setout.id remains blank
- //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
- //attach the document to the task for reference
- var task = new Kanban
- {
- Title = "Setout Review Task (setout rejected)",
- Description = "Please review the attached document for setout " + selectedSetout.Number
- };
- task.ManagerLink.ID = App.EmployeeID;
- var page = new TaskGrid();
- if (page.EditItems(new[] { task }))
- {
- var doc = new KanbanDocument();
- doc.EntityLink.ID = task.ID;
- doc.DocumentLink.ID = Document.DocumentLink.ID;
- new Client<KanbanDocument>().Save(doc, "Created from staging screen");
- selectedSetout.Task.ID = task.ID;
- new Client<StagingSetout>().Save(selectedSetout, "Updated from staging screen");
- MessageBox.Show("Success - Task Created for Document " + selectedSetout.Number + " (Task no. " + task.Number + " assigned to " + task.EmployeeLink.Name + ")");
- selectedSetout = null;
- ClearDocuments();
- refreshing = true;
- stagingSetoutGrid.Refresh(false, true);
- }
- else
- {
- MessageBox.Show("Task creation cancelled - setout not rejected");
- }
- }
- private void MarkUpButton_Click(object sender, RoutedEventArgs e)
- {
- if (Mode == DocumentMode.Markup)
- {
- Mode = DocumentMode.Complete;
- MessageBox.Show("IMPORTANT - press save in your document editor, then press the Complete Button in PRS");
- OnMarkupSelected();
- }
- else
- {
- OnMarkupComplete();
- Mode = DocumentMode.Markup;
- }
- }
- private void UpdateOriginalButton_Click(object sender, RoutedEventArgs e)
- {
- if ((_documentdata?.Any() == true) && !String.IsNullOrWhiteSpace(selectedSetout?.OriginalPath))
- {
- try
- {
- File.WriteAllBytes(selectedSetout.OriginalPath, _documentdata);
- selectedSetout.OriginalCRC = CoreUtils.CalculateCRC(_documentdata);
- new Client<StagingSetout>().Save(selectedSetout,"Updated Source File with markups");
- UpdateOriginalButton.Visibility = Visibility.Collapsed;
- }
- catch (Exception _exception)
- {
- MessageBox.Show($"Unable to update {selectedSetout?.OriginalPath}!\n\n{_exception.Message}");
- }
- return;
- }
- MessageBox.Show("Please select a design first!");
- }
- private void ApproveButton_Click(object sender, RoutedEventArgs e)
- {
- if (Document is null || selectedSetout is null)
- {
- MessageBox.Show("Please select a setout first.");
- return;
- }
- if (selectedSetouts.Count > 1)
- {
- var msg = Document.Approved
- ? "Bulk unapprove?"
- : "Bulk approve? (Skip individual setout approval)";
- if (MessageBox.Show(msg, "Continue?", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
- {
- Progress.Show("Approving Setouts..");
- var documents = Client.Query(
- new Filter<StagingSetoutDocument>(x => x.EntityLink.ID).InList(selectedSetouts.Select(x => x.ID).ToArray()),
- new Columns<StagingSetoutDocument>(x => x.ID, x => x.Approved)
- ).ToObjects<StagingSetoutDocument>().ToList();
- foreach(var document in documents)
- {
- document.Approved = !Document.Approved;
- }
- Client.Save(documents, "Approved by user.");
- Progress.Close();
- refreshing = true;
- stagingSetoutGrid.Refresh(false, true);
- }
- }
- else
- {
- Document.Approved = !Document.Approved;
- new Client<StagingSetoutDocument>().Save(Document, "");
- refreshing = true;
- stagingSetoutGrid.Refresh(false, true);
- }
- }
- private void OnMarkupSelected()
- {
- if (Document is null || selectedSetout is null)
- {
- MessageBox.Show("Please select a setout first.");
- return;
- }
- var doc = new Client<Document>()
- .Query(
- new Filter<Document>(x => x.ID).IsEqualTo(Document.DocumentLink.ID))
- .ToObjects<Document>().FirstOrDefault();
- if (doc is null)
- {
- Logger.Send(LogType.Error, "", $"Document with ID {Document.DocumentLink.ID} could not be found.");
- MessageBox.Show("Error: the selected document could not be found in the database.");
- return;
- }
- var tempdocpath = Path.Combine(Path.GetTempPath(), doc.FileName);
- selectedSetout.SavePath = tempdocpath;
- selectedSetout.LockedBy.ID = App.EmployeeID;
- selectedSetout.LockedBy.Name = App.EmployeeName;
- new Client<StagingSetout>().Save(selectedSetout, "Locked from Staging Screen");
- File.WriteAllBytes(tempdocpath, doc.Data);
- using (var p = new Process())
- {
- p.StartInfo = new ProcessStartInfo()
- {
- UseShellExecute = true,
- FileName = tempdocpath
- };
- p.Start();
- }
- refreshing = true;
- stagingSetoutGrid.Refresh(false, true);
- }
- private void OnMarkupComplete()
- {
- if (selectedSetout is null)
- {
- MessageBox.Show("Please select a setout first.");
- return;
- }
- StagingSetoutGrid.ReloadFile(selectedSetout);
- refreshing = true;
- stagingSetoutGrid.Refresh(false, true);
- }
- #endregion
- private bool refreshing = false;
- private void stagingSetoutGrid_AfterRefresh(object sender, AfterRefreshEventArgs args)
- {
- refreshing = false;
- }
- private void StagingSetoutGrid_OnSelectItem(object sender, InABox.DynamicGrid.DynamicGridSelectionEventArgs e)
- {
- var newSetouts = new List<StagingSetout>();
- foreach (var row in e.Rows ?? Enumerable.Empty<CoreRow>())
- newSetouts.Add(row.ToObject<StagingSetout>());
- if(!refreshing && (selectedSetouts.Count == newSetouts.Count
- && !selectedSetouts.Any(x => !newSetouts.Any(y => x.ID == y.ID))))
- {
- selectedSetouts = newSetouts;
- selectedSetout = selectedSetouts.FirstOrDefault();
- return;
- }
- selectedSetouts = newSetouts;
- selectedSetout = selectedSetouts.FirstOrDefault();
- AddPacketButton.IsEnabled = selectedSetout is not null;
- if(selectedSetout is null)
- {
- ClearDocuments();
- ManufacturingPacketList.Setout = null;
- CollapsePacketsButton.IsEnabled = false;
- SetoutComponentGrid.StagingSetout = null;
- SetMode(DocumentMode.Markup);
- return;
- }
- var doc = new Client<StagingSetoutDocument>()
- .Query(
- new Filter<StagingSetoutDocument>(x => x.EntityLink.ID).IsEqualTo(selectedSetout.ID),
- new Columns<StagingSetoutDocument>(x => x.ID)
- .Add(x => x.DocumentLink.ID)
- .Add(x => x.DocumentLink.FileName)
- .Add(x => x.Approved)
- .Add(x=>x.DocumentLink.CRC)
- ).ToObjects<StagingSetoutDocument>().FirstOrDefault();
- if(doc is null)
- {
- MessageBox.Show("No document found for this setout.");
- ClearDocuments();
- ManufacturingPacketList.Setout = null;
- CollapsePacketsButton.IsEnabled = false;
- SetoutComponentGrid.StagingSetout = null;
- return;
- }
- Document = doc;
- var docTask = Task.Run(() => GetDocuments(doc));
- if(CanViewPackets())
- {
- ManufacturingPacketList.Setout = selectedSetout;
- SetoutComponentGrid.StagingSetout = selectedSetout;
- }
- CollapsePacketsButton.IsEnabled = true;
- var mode =
- selectedSetout.LockedBy.ID == Guid.Empty ?
- DocumentMode.Markup :
- selectedSetout.LockedBy.ID == App.EmployeeID ?
- DocumentMode.Complete :
- DocumentMode.Locked;
- docTask.Wait();
- RenderDocuments(docTask.Result);
- SetMode(mode);
- }
- public bool IsReady { get; set; }
- public string SectionName { get; }
- public event DataModelUpdateEvent? OnUpdateDataModel;
- #region Settings
- public void CreateToolbarButtons(IPanelHost host)
- {
- ProjectSetupActions.JobStatuses(host);
- ProjectSetupActions.DrawingTemplates(host);
- host.CreateSetupSeparator();
- ProjectSetupActions.JobSpreadsheetTemplates(host);
- host.CreateSetupSeparator();
- ProjectSetupActions.SetoutGroups(host);
- host.CreateSetupSeparator();
- host.CreateSetupAction(
- new PanelAction()
- {
- Caption = "Setouts Configuration",
- Image = PRSDesktop.Resources.specifications,
- OnExecute = ConfigSettingsClick
- }
- );
- host.CreateSetupAction(
- new PanelAction()
- {
- Caption = "Component Import Profiles",
- Image = PRSDesktop.Resources.doc_xls,
- OnExecute = ConfigComponentProfiles
- });
-
- host.CreateSetupAction(
- new PanelAction()
- {
- Caption = "Template Products",
- Image = PRSDesktop.Resources.specifications,
- OnExecute =
- action =>
- {
- var list = new MasterList(typeof(ManufacturingTemplateGroupProducts));
- list.ShowDialog();
- }
- }
- );
- }
- private void ConfigComponentProfiles(PanelAction obj)
- {
- var list = new DynamicImportList(
- typeof(StagingSetoutComponent),
- Guid.Empty,
- canImport: false
- );
- list.ShowDialog();
- }
- private void ConfigSettingsClick(PanelAction obj)
- {
- var grid = new DynamicItemsListGrid<StagingPanellSettings>();
- grid.OnCustomiseEditor += Grid_OnCustomiseEditor;
- if(grid.EditItems(new[] { _settings }))
- {
- new GlobalConfiguration<StagingPanellSettings>().Save(_settings);
- _script = null;
- }
- }
- private void Grid_OnCustomiseEditor(IDynamicEditorForm sender, StagingPanellSettings[]? items, DynamicGridColumn column, BaseEditor editor)
- {
- if (items?.FirstOrDefault() is not StagingPanellSettings settings) return;
- if (column.ColumnName == nameof(StagingPanellSettings.Script) && editor is ScriptEditor scriptEditor)
- {
- scriptEditor.Type = ScriptEditorType.TemplateEditor;
- scriptEditor.OnEditorClicked += () =>
- {
- var script = settings.Script.NotWhiteSpaceOr()
- ?? settings.DefaultScript();
- var editor = new ScriptEditorWindow(script, SyntaxLanguage.CSharp);
- if (editor.ShowDialog() == true)
- {
- sender.SetEditorValue(column.ColumnName, editor.Script);
- settings.Script = editor.Script;
- }
- };
- }
- }
- #endregion
- public void Heartbeat(TimeSpan time)
- {
- }
- public void Refresh()
- {
- //stagingSetoutGrid.ScanFiles(_settings.SetoutsFolder);
- refreshing = true;
- stagingSetoutGrid.Refresh(false, true);
- /*Document = null;
- selectedSetout = null;
- ManufacturingPacketList.Setout = null;
- SetoutComponentGrid.StagingSetout = null;*/
- CalculateTime();
- }
- private void stagingSetoutGrid_OnRefreshPackets()
- {
- if (CanViewPackets())
- {
- ManufacturingPacketList.Refresh();
- }
- }
- public Dictionary<string, object[]> Selected()
- {
- return new();
- }
- public void Shutdown(CancelEventArgs? cancel)
- {
- }
- public DataModel DataModel(Selection selection)
- {
- return new AutoDataModel<StagingSetout>(new Filter<StagingSetout>().All());
- }
- private void AddPacketButton_Click(object sender, RoutedEventArgs e)
- {
- if (_templateGroups.Rows.Any() == true)
- {
- ContextMenu menu = new ContextMenu();
- foreach (var row in _templateGroups.Rows)
- {
- menu.AddItem(
- $"{row.Get<ManufacturingTemplateGroup, String>(x => x.Code)}: {row.Get<ManufacturingTemplateGroup, String>(x => x.Description)}",
- null,
- () =>
- {
- ManufacturingPacketList.Add(
- selectedSetout?.JobLink.ID ?? Guid.Empty,
- row.ToObject<ManufacturingTemplateGroup>()
- );
- UpdateStagingSetoutGrid();
- });
- }
- menu.AddSeparator();
- menu.AddItem("Miscellaneous Item", null, () =>
- {
- ManufacturingPacketList.Add(
- selectedSetout?.JobLink.ID ?? Guid.Empty,
- null
- );
- UpdateStagingSetoutGrid();
- });
- menu.IsOpen = true;
- }
- else
- {
- ManufacturingPacketList.Add(
- selectedSetout?.JobLink.ID ?? Guid.Empty,
- null
- );
- UpdateStagingSetoutGrid();
- }
- }
- private void UpdateStagingSetoutGrid()
- {
- var selected = stagingSetoutGrid.SelectedRows.FirstOrDefault();
- if (selected != null)
- {
- var packets = ManufacturingPacketList.Packets;
- selected.Set<StagingSetout, int>(x => x.Packets, packets.Length);
- selected.Set<StagingSetout, int>(x => x.UnprocessedPackets, packets.Count(x => x.ManufacturingPacket.ID == Guid.Empty));
- stagingSetoutGrid.InvalidateRow(selected);
- }
- }
- private void CollapsePacketsButton_Click(object sender, RoutedEventArgs e)
- {
- if (ManufacturingPacketList.Collapsed())
- {
- ManufacturingPacketList.Uncollapse();
- }
- else
- {
- ManufacturingPacketList.Collapse();
- }
- }
- private void ManufacturingPacketList_OnCollapsed(bool collapsed)
- {
- if (collapsed)
- {
- CollapsePacketsButton.Content = "Expand";
- }
- else
- {
- CollapsePacketsButton.Content = "Collapse";
- }
- }
- private void stagingSetoutGrid_OnCustomiseSetouts(IReadOnlyList<StagingSetoutGrid.SetoutDocument> setouts)
- {
- if(CustomiseSetoutsMethod != null && ScriptObject != null)
- {
- CustomiseSetoutsMethod?.Invoke(ScriptObject, new object?[]
- {
- new CustomiseSetoutsArgs(setouts.Select(x => new Tuple<StagingSetout, Document>(x.Setout, x.Document)).ToImmutableList())
- });
- }
- }
- private void StagingSetoutGrid_OnOnDoubleClick(object sender, HandledEventArgs args)
- {
- ManufacturingPacketList.Setout = selectedSetout;
- SetoutComponentGrid.StagingSetout = selectedSetout;
- MainPanel.View = DynamicSplitPanelView.Detail;
- NestedPanel.View = DynamicSplitPanelView.Combined;
- args.Handled = true;
- }
- private void CalculateTime()
- {
- if (selectedSetout != null)
- {
- var time = ManufacturingPacketList.TimeRequired();
- TimeRequired.Content = $"{time.TotalHours:F2} hours";
- }
- else
- TimeRequired.Content = "N/A";
- }
- private void ManufacturingPacketList_OnChanged(object? sender, EventArgs e)
- {
- CalculateTime();
- UpdateStagingSetoutGrid();
- }
- private void DoImport(Importer importer, string? componentFileName, Guid setoutID)
- {
- var success = DynamicImportGrid.CreateImporter(importer, ref componentFileName, out var iimporter);
- if (!success)
- {
- return;
- }
- var errors = new List<string>();
- var stagingSetoutComponents = new List<StagingSetoutComponent>();
- iimporter.OnLoad += Iimporter_OnLoad;
- iimporter.OnSave += (_, entity) => stagingSetoutComponents.Add((entity as StagingSetoutComponent)!);
- iimporter.OnError += (_, error) => errors.Add(error);
- using var stream = new FileStream(componentFileName!, FileMode.Open, FileAccess.Read);
- if (iimporter.Open(stream))
- {
- if (iimporter.ReadHeader())
- {
- var mismatches = iimporter.Mappings.Where(x =>
- !string.IsNullOrWhiteSpace(x.Field) &&
- !iimporter.Fields.Contains(x.Field)
- ).Select(x => x.Field).ToArray();
- if (!mismatches.Any())
- {
- var imported = iimporter.Import();
- if (errors.Any())
- {
- MessageBox.Show($"Import for component file {componentFileName} failed:\nSome errors occurred: {string.Join('\n', errors)}", "Import failed");
- }
- else
- {
- var valid = true;
- var conflicts = false;
- if (setoutID != Guid.Empty)
- {
- var newComponents = new List<StagingSetoutComponent>();
- foreach (var component in stagingSetoutComponents)
- {
- if (component.StagingSetout.ID == Guid.Empty)
- {
- component.StagingSetout.ID = setoutID;
- newComponents.Add(component);
- }
- else if (component.StagingSetout.ID != setoutID)
- {
- conflicts = true;
- // Ignoring this item.
- }
- else
- {
- newComponents.Add(component);
- }
- }
- stagingSetoutComponents = newComponents;
- if (conflicts)
- {
- MessageBox.Show($"Warning: the lines in this file have conflicting setout numbers.", "Warning");
- }
- }
- if (valid)
- {
- foreach (var component in stagingSetoutComponents)
- {
- if (component.StagingSetout.ID == Guid.Empty)
- {
- MessageBox.Show($"Component with no related setout cannot be imported.");
- valid = false;
- break;
- }
- else if (component.Description.IsNullOrWhiteSpace())
- {
- MessageBox.Show($"Component with no description cannot be imported.");
- valid = false;
- break;
- }
- else if (component.Dimensions.Unit.ID == Guid.Empty)
- {
- MessageBox.Show($"Component with no dimensions unit cannot be imported.");
- valid = false;
- break;
- }
- }
- }
- if (valid)
- {
- new Client<StagingSetoutComponent>().Save(stagingSetoutComponents, $"Imported from {componentFileName}");
- SetoutComponentGrid.Refresh(false, true);
- }
- else
- {
- MessageBox.Show($"Import for component file {componentFileName} failed.", "Import failed");
- }
- }
- }
- else
- {
- MessageBox.Show("Import Mappings do not match file headers!\n\n- " + string.Join("\n- ", mismatches),
- "Import Failed");
- }
- }
- else
- {
- MessageBox.Show("Unable to Read Headers from {0}", Path.GetFileName(componentFileName));
- }
- }
- else
- {
- MessageBox.Show("Unable to Open {0}", Path.GetFileName(componentFileName));
- }
- iimporter.Close();
- }
- private CoreTable Iimporter_OnLoad(object sender, Type type, string[] fields, string ID)
- {
- var result = new CoreTable();
- result.LoadColumns(new Columns<StagingSetoutComponent>(fields));
- return result;
- }
- private void stagingSetoutGrid_OnParseComponentFile(string componentFileName, Guid setoutID)
- {
- try
- {
- var entityName = typeof(StagingSetoutComponent).EntityName();
- var importers = new Client<Importer>()
- .Query(
- new Filter<Importer>(x => x.EntityName).IsEqualTo(entityName),
- new Columns<Importer>(x => x.ID));
- if (importers.Rows.Count == 0)
- {
- var importer = new Importer
- {
- EntityName = entityName,
- FileName = componentFileName
- };
- var form = new DynamicImportForm(importer);
- if (form.ShowDialog() == true)
- {
- new Client<Importer>().Save(importer, "");
- DoImport(importer, componentFileName, setoutID);
- return;
- }
- }
- else if (importers.Rows.Count == 1)
- {
- var importer = new Client<Importer>().Load(new Filter<Importer>(x => x.ID).IsEqualTo(importers.Rows[0].Get<Importer, Guid>(x => x.ID))).First();
- DoImport(importer, componentFileName, setoutID);
- }
- else
- {
- var list = new PopupList(
- typeof(Importer),
- Guid.Empty,
- Array.Empty<string>());
- list.OnDefineFilter += t => new Filter<Importer>(x => x.EntityName).IsEqualTo(entityName);
- if (list.ShowDialog() == true)
- {
- var importer = new Client<Importer>().Load(new Filter<Importer>(x => x.ID).IsEqualTo(list.ID)).First();
- DoImport(importer, componentFileName, setoutID);
- }
- }
- }
- catch(Exception e)
- {
- Logger.Send(LogType.Error, "", $"Error in file {componentFileName}: {CoreUtils.FormatException(e)}");
- MessageBox.Show($"Error opening {componentFileName}: {e.Message}");
- }
- }
- }
- }
|