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;
namespace PRSDesktop
{
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; }
public StagingPanellSettings()
{
MarkupPathway = "";
SetoutsFolder = "";
}
}
///
/// Interaction logic for StagingPanel.xaml
///
public partial class StagingPanel : UserControl, IPanel
{
private StagingPanellSettings _settings = new StagingPanellSettings();
StagingSetout _item = new StagingSetout();
List _items = new List();
DynamicDataGrid _materialDocs;
public StagingPanel()
{
InitializeComponent();
SectionName = nameof(StagingPanel);
}
private void DocumentPreviewer_OnApproved(IEntityDocument stagingsetoutdocument)
{
bool bulkApprove = false;
if (_items.Count > 1)
{
if (MessageBox.Show("Bulk approve? (Skip individual setout approval)", "Continue?", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
{
bulkApprove = true;
Progress.Show("Approving Setouts..");
}
}
string message = "Result: " + Environment.NewLine;
foreach (var item in _items)
{
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();
foreach (var item in _items)
DeleteAndRefresh(item);
MessageBox.Show(message);
}
private string ApproveSetout(StagingSetout item, bool bulkapprove)
{
if (item.Group.ID == Guid.Empty)
{
var message = "Setout has no group assigned";
if (Security.IsAllowed())
{
if (MessageBox.Show(message + ", continue?", "Continue?", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
return "";
}
else
{
MessageBox.Show(message + ", please assign a group!");
return "";
}
}
var setoutdoctable = new Client().Query(
new Filter(x => x.EntityLink.ID).IsEqualTo(item.ID),
new Columns(x => x.ID, x => x.DocumentLink.ID, x => x.DocumentLink.FileName));
if (!setoutdoctable.Rows.Any())
return "";
var stagingsetoutdocument = setoutdoctable.Rows.FirstOrDefault().ToObject();
var table = new Client().Query(new Filter(x => x.Number).IsEqualTo(item.Number),
new Columns(x => x.ID));
var setout = new Setout();
//setout already exists - create new setoutdoc and supercede old ones
if (table.Rows.Any())
{
if (!bulkapprove)
if (MessageBox.Show("Supercede existing documents?", "Proceed?", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
return "";
setout = table.Rows.FirstOrDefault().ToObject();
setout.Group.ID = item.Group.ID;
item.Setout.ID = setout.ID;
var setoutdoc = new SetoutDocument();
setoutdoc.EntityLink.ID = setout.ID;
setoutdoc.DocumentLink.ID = stagingsetoutdocument.DocumentLink.ID;
List setoutdocs = new List
{
setoutdoc
};
CoreTable oldDocsTable = new Client().Query(
new Filter(x => x.EntityLink.ID).IsEqualTo(setout.ID)
.And(x => x.DocumentLink.ID).IsNotEqualTo(item.Group.OptimizationDocument.ID)
);
foreach (var row in oldDocsTable.Rows)
{
var oldDoc = row.ToObject();
if (oldDoc.Superceded == DateTime.MinValue)
{
oldDoc.Superceded = DateTime.Now;
setoutdocs.Add(oldDoc);
}
}
new Client().Save(setoutdocs, "Updated from Staging Screen");
new Client().Save(setout, "Updated from Staging Screen");
return item.Number + " Superceded";
}
//no setout for this pdf - create new
else
{
setout.Number = item.Number;
setout.JobLink.ID = item.JobLink.ID;
setout.Group.ID = item.Group.ID;
var editor = new DynamicDataGrid();
editor.OnAfterSave += (editor, items) =>
{
CreateSetoutDocument(setout, item, stagingsetoutdocument);
};
if (!bulkapprove)
{
if (!editor.EditItems(new[] { setout }))
{
MessageBox.Show("Setout Creation Cancelled");
return "";
}
else
return item.Number + " Created";
}
else
{
new Client().Save(setout, "Added from staging screen");
CreateSetoutDocument(setout, item, stagingsetoutdocument);
return item.Number + " Created";
}
}
//currently not creating packets due to temporary change in requirements - to uncomment and check for validity when required
//CreatePackets(setout);
}
private 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().Save(setoutdoc, "Added from staging screen");
}
private void CreatePackets(Setout setout)
{
List packets = new List();
List stagingPackets = new List();
//create new manufacturing packets from the staging packets
foreach (var row in manufacturingControl.Data.Rows)
{
var staging = row.ToObject();
if (staging.ManufacturingPacket.ID != Guid.Empty)
continue;
var packet = new ManufacturingPacket();
packet.SetoutLink.ID = setout.ID;
packet.Serial = staging.Serial;
packet.ITP.ID = staging.ITP.ID;
packet.JobLink.ID = staging.Job.ID;
packet.ManufacturingTemplateLink.ID = staging.Template.ID;
packet.Title = staging.Title;
packet.Quantity = staging.Quantity;
packet.BarcodeQty = staging.BarcodeQuantity != 0 ? staging.BarcodeQuantity : packet.Quantity;
packet.WaterMark = staging.Watermark.ToString();
packet.Location = staging.Location;
packets.Add(packet);
stagingPackets.Add(staging);
}
//save the newly created packets to provide an ID
new Client().Save(packets, "Created from Design Management Panel");
//now work on their stages with the provided packet.ID
List stages = new List();
Dictionary stagingToActualComponents = new Dictionary();
//Handled in this loop:
// - staging packets (update packet.ID)
// - creation of template stages
// - creation of components from staging components
foreach (var stagingPacket in stagingPackets)
{
var packet = packets.FirstOrDefault(x => x.Serial == stagingPacket.Serial);
stagingPacket.ManufacturingPacket.ID = packet.ID;
stages.AddRange(CreateStagesForTemplate(packet.ManufacturingTemplateLink.ID, packet.ID));
CreateComponents(stagingPacket.ID, packet.ID, stagingToActualComponents);
}
//save everything
MultiSave save = new MultiSave();
save.Add(typeof(ManufacturingPacketStage), stages.ToArray());
save.Add(typeof(StagingManufacturingPacket), stagingPackets.ToArray());
save.Add(typeof(ManufacturingPacketComponent), stagingToActualComponents.Values.ToArray());
save.Save(null, "Updated from setout staging screen");
foreach (var pair in stagingToActualComponents)
{
var stagingComponent = pair.Key;
stagingComponent.ComponentID = pair.Value.ID;
}
new Client().Save(stagingToActualComponents.Keys.ToArray(), "Updated from setout staging screen");
}
private void CreateComponents(Guid stagingPacketID, Guid packetID, Dictionary stagingToActualComponents)
{
var components = new List();
CoreTable table = new Client().Query(
new Filter(x => x.StagingPacket.ID).IsEqualTo(stagingPacketID)
.And(x => x.ComponentID).IsEqualTo(Guid.Empty),
new Columns(
x => x.Product.ID,
x => x.Quantity,
x => x.Length,
x => x.Height,
x => x.Width
));
foreach (var row in table.Rows)
{
var stagingComponent = row.ToObject();
var component = stagingComponent.CreateComponent(packetID);
components.Add(component);
stagingToActualComponents.Add(stagingComponent, component);
}
}
private List CreateStagesForTemplate(Guid templateID, Guid packetID)
{
var stages = new List();
CoreTable table = new Client().Query(
new Filter(x => x.Template.ID).IsEqualTo(templateID),
new Columns
(
x => x.Time,
x => x.Sequence,
x => x.SequenceType,
x => x.Section.ID,
x => x.Section.Name
));
foreach (var row in table.Rows)
{
var templateStage = row.ToObject();
var packetStage = templateStage.CreateManufacturingPacketStage();
packetStage.ManufacturingPacketLink.ID = packetID;
stages.Add(packetStage);
}
return stages;
}
private void DeleteAndRefresh(StagingSetout item)
{
new Client().Save(item, "Updated from staging screen");
_item = new StagingSetout();
documentPreviewer.Document = new StagingSetoutDocument();
Refresh();
}
private void DocumentPreviewer_OnRejected(IEntityDocument stagingsetoutdocument)
{
//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
Kanban task = new Kanban();
task.Title = "Setout Review Task (setout rejected)";
task.Description = "Please review the attached document for setout " + _item.Number;
task.ManagerLink.ID = App.EmployeeID;
var page = new KanbanGrid();
page.MyID = App.EmployeeID;
page.OnAfterSave += (editor, items) =>
{
Kanban savedTask = (Kanban)items[0];
KanbanDocument doc = new KanbanDocument();
doc.EntityLink.ID = savedTask.ID;
doc.DocumentLink.ID = stagingsetoutdocument.DocumentLink.ID;
new Client().Save(doc, "Created from staging screen");
_item.Task.ID = savedTask.ID;
new Client().Save(_item, "Updated from staging screen");
MessageBox.Show("Success - Task Created for Document " + _item.Number + " (Task no. " + savedTask.Number + " assigned to " + savedTask.EmployeeLink.Name + ")");
_item = new StagingSetout();
documentPreviewer.Document = new StagingSetoutDocument();
stagingSetoutGrid.Refresh(false, true);
};
if (!page.EditItems(new[] { task }))
MessageBox.Show("Task creation cancelled - setout not rejected");
}
private void StagingSetoutGrid_OnSelectItem(object sender, InABox.DynamicGrid.DynamicGridSelectionEventArgs e)
{
_items.Clear();
foreach (var row in stagingSetoutGrid.SelectedRows)
_items.Add(row.ToObject());
_item = stagingSetoutGrid.SelectedRows.FirstOrDefault().ToObject();
var doc = new Client().Query(
new Filter(x => x.EntityLink.ID)
.IsEqualTo(_item.ID),
new Columns(x => x.ID, x => x.DocumentLink.ID, x => x.DocumentLink.FileName))
.Rows.FirstOrDefault().ToObject();
documentPreviewer.Document = doc;
manufacturingControl.StagingSetout = _item;
documentPreviewer.Mode =
_item.Locked == DateTime.MinValue ? InABox.Wpf.DocumentApprovalControl.ControlMode.Markup :
_item.Locked != DateTime.MinValue && _item.LockedBy.ID == App.EmployeeID ? InABox.Wpf.DocumentApprovalControl.ControlMode.Complete :
_item.Locked != DateTime.MinValue && _item.LockedBy.ID != App.EmployeeID ? InABox.Wpf.DocumentApprovalControl.ControlMode.Locked :
InABox.Wpf.DocumentApprovalControl.ControlMode.Markup;
}
public bool IsReady { get; set; }
public string SectionName { get; }
public event DataModelUpdateEvent? OnUpdateDataModel;
public void CreateToolbarButtons(IPanelHost host)
{
host.CreateSetupAction(new PanelAction() { Caption = "Setouts Configuration", Image = PRSDesktop.Resources.specifications, OnExecute = ConfigSettingsClick });
}
private void ConfigSettingsClick(PanelAction obj)
{
var pages = new DynamicEditorPages();
var propertyEditor = new DynamicEditorForm(typeof(StagingPanellSettings), pages);
propertyEditor.OnDefineLookups += sender =>
{
var editor = sender.EditorDefinition as ILookupEditor;
var colname = sender.ColumnName;
var values = editor.Values(colname, new[] { _settings });
sender.LoadLookups(values);
};
propertyEditor.OnEditorValueChanged += (sender, name, value) =>
{
CoreUtils.SetPropertyValue(_settings, name, value);
return new Dictionary();
};
propertyEditor.OnFormCustomiseEditor += PropertyEditor_OnFormCustomiseEditor;
propertyEditor.Items = new BaseObject[] { _settings };
if (propertyEditor.ShowDialog() == true)
{
new GlobalConfiguration().Save(_settings);
}
}
private void PropertyEditor_OnFormCustomiseEditor(IDynamicEditorForm sender, object[] items, DynamicGridColumn column, BaseEditor editor)
{
}
public void Heartbeat(TimeSpan time)
{
}
public void Refresh()
{
//stagingSetoutGrid.ScanFiles(_settings.SetoutsFolder);
stagingSetoutGrid.Refresh(false, true);
documentPreviewer.Document = new StagingSetoutDocument();
manufacturingControl.StagingSetout = new StagingSetout();
manufacturingControl.Refresh();
}
public Dictionary Selected()
{
return new();
}
public void Setup()
{
_settings = new GlobalConfiguration().Load();
documentPreviewer.SetupButtons(
markupVisible: Security.IsAllowed(),
rejectVisible: Security.IsAllowed(),
approveVisible: Security.IsAllowed()
);
documentPreviewer.OnMarkupSelected += DocumentPreviewer_OnMarkupSelected;
documentPreviewer.OnMarkupComplete += DocumentPreviewer_OnMarkupComplete;
documentPreviewer.OnRejected += DocumentPreviewer_OnRejected;
documentPreviewer.OnApproved += DocumentPreviewer_OnApproved;
//stagingSetoutGrid.ScanFiles(_settings.SetoutsFolder);
stagingSetoutGrid.Refresh(true, true);
stagingSetoutGrid.OnSelectItem += StagingSetoutGrid_OnSelectItem;
}
private void DocumentPreviewer_OnMarkupSelected(IEntityDocument document)
{
var doc = new Client().Query(new Filter(x => x.ID).IsEqualTo(document.DocumentLink.ID)).Rows.FirstOrDefault().ToObject();
var tempdocpath = Path.GetTempPath() + @"\" + doc.FileName;
_item.SavePath = tempdocpath;
_item.LockedBy.ID = App.EmployeeID;
new Client().Save(_item, "Locked from Staging Screen");
File.WriteAllBytes(tempdocpath, doc.Data);
using (Process p = new Process())
{
p.StartInfo = new ProcessStartInfo()
{
UseShellExecute = true,
FileName = tempdocpath
};
p.Start();
}
stagingSetoutGrid.Refresh(false, true);
}
private void DocumentPreviewer_OnMarkupComplete(IEntityDocument document)
{
stagingSetoutGrid.ReloadFile(_item);
stagingSetoutGrid.Refresh(false, true);
}
public void Shutdown()
{
}
public DataModel DataModel(Selection selection)
{
return new AutoDataModel(null);
}
}
}