using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Net.Http; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using System.Windows.Media.Imaging; using Comal.Classes; using InABox.Clients; using InABox.Configuration; using InABox.Core; using InABox.Integration; using InABox.Integration.Awg; using InABox.WPF; using Inflector; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Xaml.Behaviors.Core; using PRSDimensionUtils; using sun.text.resources.ro; namespace PRSDesktop.Integrations.Common; public class AWGMappingWindowViewModel : DependencyObject { private readonly LogikalSettings _settings; public LogikalSettings Settings => _settings; public AWGMappingWindowViewModel() : base() { _settings = new GlobalConfiguration().Load(); StylesChecked = _settings.UpdateStyles != LogikalUpdateType.None; GroupsChecked = _settings.UpdateGroups != LogikalUpdateType.None; SuppliersChecked = _settings.UpdateSuppliers != LogikalUpdateType.None; DiscountsChecked = _settings.UpdateDiscounts != LogikalUpdateType.None; ProfilesChecked = _settings.UpdateProfiles != LogikalUpdateType.None; GasketsChecked = _settings.UpdateGaskets != LogikalUpdateType.None; ComponentsChecked = _settings.UpdateComponents != LogikalUpdateType.None; GlassChecked = _settings.UpdateGlass != LogikalUpdateType.None; LabourChecked = _settings.UpdateLabour != LogikalUpdateType.None; } private static readonly DependencyProperty SourceTypeProperty = DependencyProperty.Register( nameof(SourceType), typeof(IntegrationSourceType), typeof(AWGMappingWindowViewModel) ); public IntegrationSourceType SourceType { get => (IntegrationSourceType)GetValue(SourceTypeProperty); set => SetValue(SourceTypeProperty, value); } private static readonly DependencyProperty StylesProperty = DependencyProperty.Register( nameof(Styles), typeof(IEnumerable), typeof(AWGMappingWindowViewModel), new FrameworkPropertyMetadata(StylesChanged) ); private static void StylesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is not AWGMappingWindowViewModel model || e.NewValue is not IEnumerable styles) return; var mappings = model.ExtractMappings( styles, (logikal, mapping) => { mapping.Cost = logikal.Cost; mapping.StyleType = logikal.StyleType; }, x => x.Code ); mappings.Wait(); model.StyleMappings = mappings.Result; model.CheckChanged(); } public IEnumerable? Styles { get => GetValue(StylesProperty) as IEnumerable; set => SetValue(StylesProperty, value); } private static readonly DependencyProperty GroupsProperty = DependencyProperty.Register( nameof(Groups), typeof(IEnumerable), typeof(AWGMappingWindowViewModel), new FrameworkPropertyMetadata(GroupsChanged) ); private static void GroupsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is not AWGMappingWindowViewModel model || e.NewValue is not IEnumerable groups) return; var mappings = model.ExtractMappings( groups, (logikal, mapping) => { mapping.Parent = logikal.Parent; }, x => x.Code ); mappings.Wait(); model.GroupMappings = mappings.Result; model.CheckChanged(); } public IEnumerable? Groups { get => GetValue(GroupsProperty) as IEnumerable; set => SetValue(GroupsProperty, value); } private static readonly DependencyProperty SuppliersProperty = DependencyProperty.Register( nameof(Suppliers), typeof(IEnumerable), typeof(AWGMappingWindowViewModel), new FrameworkPropertyMetadata(SuppliersChanged) ); private static void SuppliersChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is not AWGMappingWindowViewModel model || e.NewValue is not IEnumerable suppliers) return; var mappings = model.ExtractMappings( suppliers, null, x => x.Code ); mappings.Wait(); model.SupplierMappings = mappings.Result; model.CheckChanged(); } public IEnumerable? Suppliers { get => GetValue(SuppliersProperty) as IEnumerable; set => SetValue(SuppliersProperty, value); } private static readonly DependencyProperty DiscountsProperty = DependencyProperty.Register( nameof(Discounts), typeof(IEnumerable), typeof(AWGMappingWindowViewModel), new FrameworkPropertyMetadata(DiscountsChanged) ); private static void DiscountsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is not AWGMappingWindowViewModel model || e.NewValue is not IEnumerable discounts) return; var mappings = model.ExtractMappings( discounts, (logikal, mapping) => { mapping.Supplier = logikal.SupplierCode; mapping.Discount = logikal.Discount; }, x => x.Code ); mappings.Wait(); model.DiscountMappings = mappings.Result; model.CheckChanged(); } public IEnumerable? Discounts { get => GetValue(DiscountsProperty) as IEnumerable; set => SetValue(DiscountsProperty, value); } private static readonly DependencyProperty ProfilesProperty = DependencyProperty.Register( nameof(Profiles), typeof(IEnumerable), typeof(AWGMappingWindowViewModel), new FrameworkPropertyMetadata(ProfilesChanged) ); private static void ProfilesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is not AWGMappingWindowViewModel model || e.NewValue is not IEnumerable profiles) return; var mappings = model.ExtractMappings( profiles, (logikal, mapping) => { mapping.Style = logikal.Finish; mapping.Dimensions.Unit.CopyFrom(model.Settings.ProfileUom); mapping.Dimensions.Length = logikal.Length; mapping.Group = logikal.Group; mapping.Supplier = logikal.Supplier; mapping.Cost = logikal.Cost; mapping.MillCost = logikal.MillCost; mapping.Quantity = logikal.Quantity; mapping.TreatmentParameters[AwgStyleType.Powdercoated] = logikal.PaintPerimeter; mapping.TreatmentParameters[AwgStyleType.Anodised] = logikal.AnodizePerimeter; }, x => x.Code ); mappings.Wait(); model.ProfileMappings = mappings.Result; model.CheckChanged(); } public IEnumerable? Profiles { get => GetValue(ProfilesProperty) as IEnumerable; set => SetValue(ProfilesProperty, value); } private static readonly DependencyProperty GasketsProperty = DependencyProperty.Register( nameof(Gaskets), typeof(IEnumerable), typeof(AWGMappingWindowViewModel), new FrameworkPropertyMetadata(GasketsChanged) ); private static void GasketsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is not AWGMappingWindowViewModel model || e.NewValue is not IEnumerable gaskets) return; var mappings = model.ExtractMappings( gaskets, (logikal, mapping) => { mapping.Group = logikal.Group; mapping.Supplier = logikal.Supplier; mapping.Style = logikal.Finish; mapping.Dimensions.Unit.CopyFrom(model.Settings.GasketUom); mapping.Dimensions.Length = logikal.Length; mapping.Cost = logikal.Cost; mapping.Quantity = logikal.Quantity; }, x => x.Code ); mappings.Wait(); model.GasketMappings = mappings.Result; model.CheckChanged(); } public IEnumerable? Gaskets { get => GetValue(GasketsProperty) as IEnumerable; set => SetValue(GasketsProperty, value); } private static readonly DependencyProperty ComponentsProperty = DependencyProperty.Register( nameof(Components), typeof(IEnumerable), typeof(AWGMappingWindowViewModel), new FrameworkPropertyMetadata(ComponentsChanged) ); private static void ComponentsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is not AWGMappingWindowViewModel model || e.NewValue is not IEnumerable components) return; var mappings = model.ExtractMappings( components, (logikal, mapping) => { mapping.Dimensions.Unit.CopyFrom(model.Settings.ComponentUom); mapping.Dimensions.Quantity = logikal.PackSize; mapping.Quantity = logikal.Quantity; mapping.Cost = logikal.Cost; mapping.Group = logikal.Group; mapping.Supplier = logikal.Supplier; mapping.Style = logikal.Finish; }, x => x.Code ); mappings.Wait(); model.ComponentMappings = mappings.Result; model.CheckChanged(); } public IEnumerable? Components { get => GetValue(ComponentsProperty) as IEnumerable; set => SetValue(ComponentsProperty, value); } private static readonly DependencyProperty GlassProperty = DependencyProperty.Register( nameof(Glass), typeof(IEnumerable), typeof(AWGMappingWindowViewModel), new FrameworkPropertyMetadata(GlassChanged) ); private static void GlassChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is not AWGMappingWindowViewModel model || e.NewValue is not IEnumerable glass) return; var mappings = model.ExtractMappings( glass, (logikal, mapping) => { mapping.Group = logikal.Group; mapping.Supplier = logikal.Supplier; mapping.Dimensions.Unit.CopyFrom(model.Settings.GlassUom); mapping.Dimensions.Height = logikal.Height; mapping.Dimensions.Width = logikal.Width; mapping.Style = logikal.Treatment; mapping.Quantity = logikal.Quantity; mapping.Cost = logikal.Cost; }, x => x.Code ); mappings.Wait(); model.GlassMappings = mappings.Result; model.CheckChanged(); } public IEnumerable? Glass { get => GetValue(GlassProperty) as IEnumerable; set => SetValue(GlassProperty, value); } private static readonly DependencyProperty LabourProperty = DependencyProperty.Register( nameof(Labour), typeof(IEnumerable), typeof(AWGMappingWindowViewModel), new FrameworkPropertyMetadata(LabourChanged) ); private static void LabourChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is not AWGMappingWindowViewModel model || e.NewValue is not IEnumerable labour) return; var mappings = model.ExtractMappings( labour, (logikal, mapping) => { mapping.Quantity = logikal.Quantity; }, x => x.Code ); mappings.Wait(); model.LabourMappings = mappings.Result; model.CheckChanged(); } public IEnumerable? Labour { get => GetValue(LabourProperty) as IEnumerable; set => SetValue(LabourProperty, value); } private static void SectionCheckedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is AWGMappingWindowViewModel model) model.CheckChanged(); } private static readonly DependencyProperty StyleMappingsProperty = DependencyProperty.Register( nameof(StyleMappings), typeof(List), typeof(AWGMappingWindowViewModel) ); public List? StyleMappings { get => GetValue(StyleMappingsProperty) as List; set => SetValue(StyleMappingsProperty, value); } private static readonly DependencyProperty StylesCheckedProperty = DependencyProperty.Register( nameof(StylesChecked), typeof(bool), typeof(AWGMappingWindowViewModel), new FrameworkPropertyMetadata(defaultValue: true, propertyChangedCallback: SectionCheckedChanged) ); public bool StylesChecked { get => (bool)GetValue(StylesCheckedProperty); set => SetValue(StylesCheckedProperty, value); } private static readonly DependencyProperty GroupMappingsProperty = DependencyProperty.Register( nameof(GroupMappings), typeof(List), typeof(AWGMappingWindowViewModel) ); public List? GroupMappings { get => GetValue(GroupMappingsProperty) as List; set => SetValue(GroupMappingsProperty, value); } private static readonly DependencyProperty GroupsCheckedProperty = DependencyProperty.Register( nameof(GroupsChecked), typeof(bool), typeof(AWGMappingWindowViewModel), new FrameworkPropertyMetadata(defaultValue: true, propertyChangedCallback: SectionCheckedChanged) ); public bool GroupsChecked { get => (bool)GetValue(GroupsCheckedProperty); set => SetValue(GroupsCheckedProperty, value); } private static readonly DependencyProperty SupplierMappingsProperty = DependencyProperty.Register( nameof(SupplierMappings), typeof(List), typeof(AWGMappingWindowViewModel) ); public List? SupplierMappings { get => GetValue(SupplierMappingsProperty) as List; set => SetValue(SupplierMappingsProperty, value); } private static readonly DependencyProperty DiscountMappingsProperty = DependencyProperty.Register( nameof(DiscountMappings), typeof(List), typeof(AWGMappingWindowViewModel) ); public List? DiscountMappings { get => GetValue(DiscountMappingsProperty) as List; set => SetValue(DiscountMappingsProperty, value); } private static readonly DependencyProperty SuppliersCheckedProperty = DependencyProperty.Register( nameof(SuppliersChecked), typeof(bool), typeof(AWGMappingWindowViewModel), new FrameworkPropertyMetadata(defaultValue: true, propertyChangedCallback: SectionCheckedChanged) ); public bool SuppliersChecked { get => (bool)GetValue(SuppliersCheckedProperty); set => SetValue(SuppliersCheckedProperty, value); } private static readonly DependencyProperty DiscountsCheckedProperty = DependencyProperty.Register( nameof(DiscountsChecked), typeof(bool), typeof(AWGMappingWindowViewModel), new FrameworkPropertyMetadata(defaultValue: true, propertyChangedCallback: SectionCheckedChanged) ); public bool DiscountsChecked { get => (bool)GetValue(DiscountsCheckedProperty); set => SetValue(DiscountsCheckedProperty, value); } private static readonly DependencyProperty ProfileMappingsProperty = DependencyProperty.Register( nameof(ProfileMappings), typeof(List), typeof(AWGMappingWindowViewModel) ); public List? ProfileMappings { get => GetValue(ProfileMappingsProperty) as List; set => SetValue(ProfileMappingsProperty, value); } private static readonly DependencyProperty ProfilesCheckedProperty = DependencyProperty.Register( nameof(ProfilesChecked), typeof(bool), typeof(AWGMappingWindowViewModel), new FrameworkPropertyMetadata(defaultValue: true, propertyChangedCallback: SectionCheckedChanged) ); public bool ProfilesChecked { get => (bool)GetValue(ProfilesCheckedProperty); set => SetValue(ProfilesCheckedProperty, value); } private static readonly DependencyProperty GasketMappingsProperty = DependencyProperty.Register( nameof(GasketMappings), typeof(List), typeof(AWGMappingWindowViewModel) ); public List? GasketMappings { get => GetValue(GasketMappingsProperty) as List; set => SetValue(GasketMappingsProperty, value); } private static readonly DependencyProperty GasketsCheckedProperty = DependencyProperty.Register( nameof(GasketsChecked), typeof(bool), typeof(AWGMappingWindowViewModel), new FrameworkPropertyMetadata(defaultValue: true, propertyChangedCallback: SectionCheckedChanged) ); public bool GasketsChecked { get => (bool)GetValue(GasketsCheckedProperty); set => SetValue(GasketsCheckedProperty, value); } private static readonly DependencyProperty ComponentMappingsProperty = DependencyProperty.Register( nameof(ComponentMappings), typeof(List), typeof(AWGMappingWindowViewModel) ); public List? ComponentMappings { get => GetValue(ComponentMappingsProperty) as List; set => SetValue(ComponentMappingsProperty, value); } private static readonly DependencyProperty ComponentsCheckedProperty = DependencyProperty.Register( nameof(ComponentsChecked), typeof(bool), typeof(AWGMappingWindowViewModel), new FrameworkPropertyMetadata(defaultValue: true, propertyChangedCallback: SectionCheckedChanged) ); public bool ComponentsChecked { get => (bool)GetValue(ComponentsCheckedProperty); set => SetValue(ComponentsCheckedProperty, value); } private static readonly DependencyProperty GlassMappingsProperty = DependencyProperty.Register( nameof(GlassMappings), typeof(List), typeof(AWGMappingWindowViewModel) ); public List? GlassMappings { get => GetValue(GlassMappingsProperty) as List; set => SetValue(GlassMappingsProperty, value); } private static readonly DependencyProperty GlassCheckedProperty = DependencyProperty.Register( nameof(GlassChecked), typeof(bool), typeof(AWGMappingWindowViewModel), new FrameworkPropertyMetadata(defaultValue: true, propertyChangedCallback: SectionCheckedChanged) ); public bool GlassChecked { get => (bool)GetValue(GlassCheckedProperty); set => SetValue(GlassCheckedProperty, value); } private static readonly DependencyProperty LabourMappingsProperty = DependencyProperty.Register( nameof(LabourMappings), typeof(List), typeof(AWGMappingWindowViewModel) ); public List? LabourMappings { get => GetValue(LabourMappingsProperty) as List; set => SetValue(LabourMappingsProperty, value); } private static readonly DependencyProperty LabourCheckedProperty = DependencyProperty.Register( nameof(LabourChecked), typeof(bool), typeof(AWGMappingWindowViewModel), new FrameworkPropertyMetadata(defaultValue: true, propertyChangedCallback: SectionCheckedChanged) ); public bool LabourChecked { get => (bool)GetValue(LabourCheckedProperty); set => SetValue(LabourCheckedProperty, value); } private static readonly DependencyProperty SectionsProperty = DependencyProperty.Register( nameof(Sections), typeof(CoreObservableCollection>), typeof(AWGMappingWindowViewModel), new PropertyMetadata(new CoreObservableCollection>()) ); public CoreObservableCollection> Sections { get => (CoreObservableCollection>)GetValue(SectionsProperty); set => SetValue(SectionsProperty, value); } private static readonly DependencyProperty SelectedSectionProperty = DependencyProperty.Register( nameof(SelectedSection), typeof(KeyValuePair?), typeof(AWGMappingWindowViewModel) ); public KeyValuePair? SelectedSection { get => (KeyValuePair?)GetValue(SelectedSectionProperty); set => SetValue(SelectedSectionProperty, value); } private static readonly DependencyProperty MappingsCompleteProperty = DependencyProperty.Register( nameof(MappingsComplete), typeof(bool), typeof(AWGMappingWindowViewModel) ); public bool MappingsComplete { get => (bool)GetValue(MappingsCompleteProperty); set => SetValue(MappingsCompleteProperty, value); } private Task> ExtractMappings( IEnumerable? items, Action? populate, Expression> entitycode ) where TType : IAwgItem where TCode : BaseIntegrationSource, IRemotable, IPersistent, new() where TEntity : Entity, IRemotable, IPersistent, new() where TLink : EntityLink { return Task.Run(() => { var results = new List(); if (items == null) return results; //var sourceitems = new Dictionary(); //foreach (var item in items) // sourceitems[item.Code] = item.Description; var keys = items.Select(x => x.Code).Distinct().ToArray(); MultiQuery query = new(); query.Add( new Filter(entitycode).InList(keys), Columns.Required().Add(x => x.ID).Add(entitycode) ); var entitycodecol = $"Entity.{CoreUtils.GetFullPropertyName(entitycode, ".")}"; query.Add( new Filter(x => x.Code).InList(keys), Columns.Required() .Add(x => x.ID) .Add(x => x.Code) .Add(x => x.Entity.ID) .Add(entitycodecol) ); query.Query(); var mappings = query.Get().ToObjects().ToArray(); var entities = query.Get(); foreach (var item in items) { var result = new TCode() { Code = item.Code, Description = item.Description }; populate?.Invoke(item, result); var mapping = mappings.FirstOrDefault(x => string.Equals(x.Code, item.Code)); if (mapping != null) result.Entity.CopyFrom(mapping.Entity); else { var entity = entities.Rows.FirstOrDefault(r => Equals(item.Code, r.Get(entitycode))); if (entity != null) { result.Entity.CopyFrom(entity.ToObject()); result.DirectMatch = true; } } results.Add(result); // result.PropertyChanged += (_, _) => // { // // TMapping mapping = mappingtable.Rows.FirstOrDefault(r => // // string.Equals(r.Get(c => c.Code), result.Code))?.ToObject(); // // if (mapping == null) // // mapping = new TMapping() { Code = result.Code }; // // mapping.Entity.ID = result.Entity.ID; // // new Client().Save(mapping, "Created from BOM Integration Window"); // // CheckChanged(); // }; } return results; }); } public void CheckChanged() { Dispatcher.BeginInvoke(() => { var curSel = SelectedSection?.Key ?? ""; SelectedSection = null; Sections.Clear(); if (StylesChecked && StyleMappings?.Any() == true) Sections.Add(new KeyValuePair("Styles", Resources.palette.AsBitmapImage(64, 64))); if (GroupsChecked && GroupMappings?.Any() == true) Sections.Add( new KeyValuePair("Groups", Resources.productgroup.AsBitmapImage(64, 64))); if (SuppliersChecked && SupplierMappings?.Any() == true) Sections.Add( new KeyValuePair("Suppliers", Resources.supplier.AsBitmapImage(64, 64))); if (DiscountsChecked && DiscountMappings?.Any() == true) Sections.Add( new KeyValuePair("Discounts", Resources.receipt.AsBitmapImage(64, 64))); if (ProfilesChecked && ProfileMappings?.Any() == true) Sections.Add( new KeyValuePair("Profiles", Resources.profile.AsBitmapImage(64, 64))); if (GasketsChecked && GasketMappings?.Any() == true) Sections.Add(new KeyValuePair("Gaskets", Resources.gasket.AsBitmapImage(64, 64))); if (ComponentsChecked && ComponentMappings?.Any() == true) Sections.Add( new KeyValuePair("Components", Resources.fixings.AsBitmapImage(64, 64))); if (GlassChecked && GlassMappings?.Any() == true) Sections.Add(new KeyValuePair("Glass", Resources.glass.AsBitmapImage(64, 64))); if (LabourChecked && LabourMappings?.Any() == true) Sections.Add(new KeyValuePair("Labour", Resources.quality.AsBitmapImage(64, 64))); SelectedSection = Sections.Any(x => string.Equals(x.Key, curSel)) ? Sections.First(x => string.Equals(x.Key, curSel)) : Sections.FirstOrDefault(); var styles = !StylesChecked || (StyleMappings?.Any() != true) || (StyleMappings?.All(x => x.Entity.ID != Guid.Empty) ?? false); var groups = !GroupsChecked || (GroupMappings?.Any() != true) || (GroupMappings?.All(x => x.Entity.ID != Guid.Empty) ?? false); var suppliers = !SuppliersChecked || (SupplierMappings?.Any() != true) || (SupplierMappings?.All(x => x.Entity.ID != Guid.Empty) ?? false); var discounts = !DiscountsChecked || (DiscountMappings?.Any() != true) || (DiscountMappings?.All(x => x.Entity.ID != Guid.Empty) ?? false); var profiles = !ProfilesChecked || (ProfileMappings?.Any() != true) || (ProfileMappings?.All(x => x.Entity.ID != Guid.Empty) ?? false); var gaskets = !GasketsChecked || (GasketMappings?.Any() != true) || (GasketMappings?.All(x => x.Entity.ID != Guid.Empty) ?? false); var components = !ComponentsChecked || (ComponentMappings?.Any() != true) || (ComponentMappings?.All(x => x.Entity.ID != Guid.Empty) ?? false); var glass = !GlassChecked || (GlassMappings?.Any() != true) || (GlassMappings?.All(x => x.Entity.ID != Guid.Empty) ?? false); var labour = !LabourChecked || (LabourMappings?.Any() != true) || (LabourMappings?.All(x => x.Entity.ID != Guid.Empty) ?? false); MappingsComplete = styles && groups && suppliers && discounts && profiles && gaskets && components && glass && labour; }); } public ICommand CreateStyle => new ActionCommand( o => { if (o is IntegrationGridCreateEntityArgs args) { PopulateStyle(args.Entity, args.Mapping); args.Entity.Problem.Notes = ["Created from BOM Integration Window"]; } } ); private void PopulateStyle(ProductStyle entity, ProductStyleIntegrationSource mapping) { entity.Code = mapping.Code ?? ""; entity.Description = mapping.Description ?? ""; TreatmentTypeLink? type = mapping.StyleType == AwgStyleType.Powdercoated ? _settings.PowdercoatedType : mapping.StyleType == AwgStyleType.Anodised ? _settings.AnodisedType : mapping.StyleType == AwgStyleType.Varnished ? _settings.VarnishedType : mapping.StyleType == AwgStyleType.Taped ? _settings.TapedType : new TreatmentTypeLink(); entity.TreatmentType.ID = type.ID; if (entity.TreatmentType.ID != Guid.Empty) { var product = new Client().Query( new Filter(x => x.Code).IsEqualTo(entity.Code), Columns.Local() ).ToArray().FirstOrDefault(); if (product == null) { product = new Product(); product.Problem.Notes = ["Created from BOM Integration Window"]; } product.Code = entity.Code; product.Name = entity.Description; product.TreatmentType.ID = entity.TreatmentType.ID; if (product.IsChanged()) Client.Save(product, "Created from AWG Mapping Window"); entity.StockTreatmentProduct.ID = product.ID; entity.ManufacturingTreatmentProduct.ID = product.ID; } } public ICommand CreateGroup => new ActionCommand( o => { if (o is IntegrationGridCreateEntityArgs args) { PopulateGroup(args.Entity, args.Mapping); args.Entity.Problem.Notes = ["Created from BOM Integration Window"]; } } ); public void PopulateGroup(ProductGroup entity, ProductGroupIntegrationSource mapping) { Guid parentid = Guid.Empty; var parentcodes = mapping.Parent .Split('/') .Select(x => x.Trim().ToUpper()) .Where(x=>!string.IsNullOrWhiteSpace(x)) .ToArray(); var parents = Client.Query( new Filter(x => x.Code).InList(parentcodes), Columns.None().Add(x => x.ID).Add(x => x.Code) ).ToArray(); foreach (var parentcode in parentcodes) { var parent = parents.FirstOrDefault(x => Equals(x.Code,parentcode)); if (parent == null) { parent = new ProductGroup(); parent.Code = parentcode; parent.Description = !string.IsNullOrWhiteSpace(parentcode) ? parentcode.Titleize() : ""; parent.Parent.ID = parentid; parent.Problem.Notes = ["Created from BOM Integration Window"]; Client.Save(parent, "Created from AWG Mapping Window"); } parentid = parent.ID; } entity.Parent.ID = parentid; entity.Code = mapping.Code ?? ""; entity.Description = mapping.Description ?? ""; } public ICommand CreateSupplier => new ActionCommand( o => { if (o is IntegrationGridCreateEntityArgs args) { PopulateSupplier(args.Entity, args.Mapping); args.Entity.Problem.Notes = ["Created from BOM Integration Window"]; } } ); private void PopulateSupplier(Supplier entity, SupplierIntegrationSource mapping) { entity.Code = mapping.Code ?? ""; entity.Name = mapping.Description ?? ""; } public ICommand CreateDiscount => new ActionCommand( o => { if (o is IntegrationGridCreateEntityArgs args) { PopulateDiscountGroup(args.Entity, args.Mapping); args.Entity.Problem.Notes = ["Created from BOM Integration Window"]; } } ); private void PopulateDiscountGroup(SupplierDiscountGroup entity, SupplierDiscountGroupIntegrationSource mapping) { entity.Code = mapping.Code ?? ""; entity.Description = mapping.Description ?? ""; entity.Type = SupplierDiscountGroupType.Discount; var _supplier = SupplierMappings?.FirstOrDefault(x => string.Equals(x.Code, mapping.Supplier))?.Entity.ID; if (_supplier == null) _supplier = new Client() .Query(new Filter(x => x.Code).IsEqualTo(entity.Code), Columns.None().Add(x => x.ID)) .ToArray() .FirstOrDefault()?.ID ?? Guid.Empty; entity.Supplier.ID = _supplier.Value; } public ICommand AfterCreateDiscountGroup => new ActionCommand( o => { if (o is IntegrationGridCreateEntityArgs args) { PopulateDiscount(args.Entity,args.Mapping); } } ); private void PopulateDiscount(SupplierDiscountGroup entity, SupplierDiscountGroupIntegrationSource mapping) { var _discount = new Client().Query( new Filter(x => x.Group.ID).IsEqualTo(entity.ID), Columns.Local() ).ToObjects().FirstOrDefault(); if (_discount == null) { _discount = new(); _discount.Group.ID = entity.ID; } _discount.Value = mapping.Discount; if (_discount.IsChanged()) Client.Save(_discount, "Updated from AWG Mapping Window"); } public ICommand CreateProfile => new ActionCommand( o => { if (o is IntegrationGridCreateEntityArgs args) { PopulateProfile(args.Entity,args.Mapping); args.Entity.Problem.Notes = ["Created from BOM Integration Window"]; //CreateImage(args); } } ); private void PopulateProfile(Product entity, ProductIntegrationSource mapping) { entity.Code = mapping.Code ?? ""; entity.Name = mapping.Description ?? ""; entity.UnitOfMeasure.ID = _settings.ProfileUom.ID; var _group = GroupMappings?.FirstOrDefault(x => Equals(x.Code, mapping.Group)); if (_group != null) entity.Group.ID = _group.Entity.ID; } public ICommand AfterCreateProduct => new ActionCommand( o => { if (o is IntegrationGridCreateEntityArgs args) { PopulateProduct(args.Entity,args.Mapping); } } ); private void PopulateProduct(Product entity, ProductIntegrationSource mapping) { CreateTreatmentParams(entity, mapping, AwgStyleType.Powdercoated, Settings.PowdercoatedType); CreateTreatmentParams(entity, mapping, AwgStyleType.Anodised, Settings.AnodisedType); CreateTreatmentParams(entity, mapping, AwgStyleType.Taped, Settings.TapedType); CreateTreatmentParams(entity, mapping, AwgStyleType.Varnished, Settings.VarnishedType); CreateSupplierProducts(entity, mapping); } // private void CreateImage(IntegrationGridCreateEntityArgs args) // { // if (!string.IsNullOrWhiteSpace(_settings.ImageUrl)) // { // var model = new LogikalCodeModel() { Code = args.Mapping.Code }; // var _expression = new CoreExpression(_settings.ImageUrl); // if (_expression.Evaluate(model).Get(out var eval, out var e)) // { // var tcs = new TaskCompletionSource(); // new HttpClient().GetByteArrayAsync(eval) // .ContinueWith( // t => // { // if (t.IsFaulted) // tcs.SetException(t.Exception); // else // tcs.SetResult(t.Result); // }); // try // { // var data = tcs.Task.Result; // var document = new Document() // { // Data = tcs.Task.Result, // CRC = CoreUtils.CalculateCRC(data), // FileName = args.Mapping.Code // }; // Client.Save(document,"Created from AWG Mapping Window"); // args.Entity.Image.ID = document.ID; // } // catch (Exception exception) // { // Logger.Send(LogType.Error,"",$"Exception in CreateImage(): {exception.Message}"); // } // } // } // } private void CreateTreatmentParams(Product entity, ProductIntegrationSource mapping, AwgStyleType type, TreatmentTypeLink link) { if (mapping.TreatmentParameters.ContainsKey(type) && !Equals(link.ID,Guid.Empty)) { var _treatment = new Client().Query( new Filter(x=>x.Product.ID).IsEqualTo(entity.ID) .And(x=>x.TreatmentType.ID).IsEqualTo(link.ID), Columns.Local() ).ToObjects().FirstOrDefault(); if (_treatment == null) { _treatment = new(); _treatment.Product.ID = entity.ID; _treatment.TreatmentType.ID = link.ID; } _treatment.Parameter = mapping.TreatmentParameters[type]; if (_treatment.IsChanged()) Client.Save(_treatment,"Updated from AWG Mapping Window"); } } private void CreateSupplierProducts(Product entity, ProductIntegrationSource mapping) { var supplier = SupplierMappings?.FirstOrDefault(x => Equals(x.Code, mapping.Supplier)); if (supplier != null) { List products = new(); if (!mapping.MillCost.IsEffectivelyEqual(mapping.Cost)) { var _mill = CreateSupplierProduct(entity, mapping, supplier, "", mapping.MillCost, false); products.Add(_mill); } var _treated = CreateSupplierProduct(entity, mapping, supplier, mapping.Style, mapping.Cost, false); products.Add(_treated); var _updates = products.Where(x => x.IsChanged()).ToArray(); if (_updates.Any()) Client.Save(_updates,"Updated from AWG Mapping Window"); } } private SupplierProduct CreateSupplierProduct(Product entity, ProductIntegrationSource mapping, SupplierIntegrationSource supplier, string stylecode, double cost, bool save) { var _sp = new Client().Query( new Filter(x => x.Product.ID).IsEqualTo(entity.ID).And(x=>x.SupplierLink.ID).IsEqualTo(supplier.Entity.ID), Columns.Local() ).ToObjects().FirstOrDefault(); if (_sp == null) { _sp = new(); _sp.Product.ID = entity.ID; _sp.SupplierLink.ID = supplier.Entity.ID; } _sp.SupplierCode = mapping.Code ?? ""; _sp.SupplierDescription = mapping.Description ?? ""; _sp.Dimensions.Unit.ID = mapping.Dimensions.Unit.ID; _sp.Dimensions.Height = mapping.Dimensions.Height; _sp.Dimensions.Width = mapping.Dimensions.Width; _sp.Dimensions.Length = mapping.Dimensions.Length; _sp.Dimensions.Quantity = mapping.Dimensions.Quantity; _sp.Dimensions.Weight = mapping.Dimensions.Weight; _sp.Dimensions.Value = mapping.Dimensions.Value; _sp.Dimensions.UnitSize = mapping.Dimensions.UnitSize; var _style = StyleMappings?.FirstOrDefault(x => Equals(x.Code, stylecode)); _sp.Style.ID = _style?.Entity.ID ?? Guid.Empty; _sp.TradePrice = cost; if (save && _sp.IsChanged()) new Client().Save(_sp, "Updated by Awg Mapping Window"); return _sp; } public ICommand CreateGasket => new ActionCommand( o => { if (o is IntegrationGridCreateEntityArgs args) { PopulateGasket(args.Entity, args.Mapping); args.Entity.Problem.Notes = ["Created from BOM Integration Window"]; } } ); private void PopulateGasket(Product argsEntity, ProductIntegrationSource argsMapping) { argsEntity.Code = argsMapping.Entity.Code ?? ""; argsEntity.Name = argsMapping.Description ?? ""; argsEntity.UnitOfMeasure.ID = _settings.GasketUom.ID; var _group = GroupMappings?.FirstOrDefault(x => Equals(x.Code, argsMapping.Group)); if (_group != null) argsEntity.Group.ID = _group.Entity.ID; } public ICommand CreateComponent => new ActionCommand( o => { if (o is IntegrationGridCreateEntityArgs args) { PopulateComponent(args.Entity, args.Mapping); args.Entity.Problem.Notes = ["Created from BOM Integration Window"]; } } ); private void PopulateComponent(Product entity, ProductIntegrationSource mapping) { entity.Code = mapping.Entity.Code ?? ""; entity.Name = mapping.Description ?? ""; entity.UnitOfMeasure.ID = _settings.ComponentUom.ID; var _group = GroupMappings?.FirstOrDefault(x => Equals(x.Code, mapping.Group)); if (_group != null) entity.Group.ID = _group.Entity.ID; } public ICommand CreateGlass => new ActionCommand( o => { if (o is IntegrationGridCreateEntityArgs args) { PopulateGlass(args.Entity, args.Mapping); args.Entity.Problem.Notes = ["Created from BOM Integration Window"]; } } ); private void PopulateGlass(Product entity, ProductIntegrationSource mapping) { entity.Code = mapping.Entity.Code ?? ""; entity.Name = mapping.Description ?? ""; entity.UnitOfMeasure.ID = _settings.GlassUom.ID; var _group = GroupMappings?.FirstOrDefault(x => Equals(x.Code, mapping.Group)); if (_group != null) entity.Group.ID = _group.Entity.ID; } public ICommand CreateActivity => new ActionCommand( o => { if (o is IntegrationGridCreateEntityArgs args) { PopulateActivity(args.Entity, args.Mapping); args.Entity.Problem.Notes = ["Created from BOM Integration Window"]; } } ); private void PopulateActivity(Activity entity, ActivityIntegrationSource mapping) { entity.Code = mapping.Entity.Code ?? ""; entity.Description = mapping.Description ?? ""; } private class RawDimensions : IBaseDimensions { public double Quantity { get; set; } public double Length { get; set; } public double Width { get; set; } public double Height { get; set; } public double Weight { get; set; } } public void GetDiscounts(Action? discountCallback) { if (DiscountsChecked && Discounts != null) { foreach (var discount in Discounts) { var discountmapping = DiscountMappings?.FirstOrDefault(x => x.Code == discount.Code); if (discountmapping != null && discountCallback != null) discountCallback?.Invoke(discountmapping.Entity,discountmapping.Discount); } } } public void GetParts( Action? productCallback, Action? labourCallback) { GetParts(Profiles,Gaskets,Components,Glass,Labour,productCallback,labourCallback); } public void GetParts( IEnumerable? profiles, IEnumerable? gaskets, IEnumerable? components, IEnumerable? glasses, IEnumerable? labour, Action? productCallback, Action? labourCallback) where TProfile : IAwgProfile where TGasket : IAwgGasket where TComponent : IAwgComponent where TGlass : IAwgGlass where TLabour : IAwgLabour { if (ProfilesChecked && profiles != null) { foreach (var profile in profiles) { var profilemapping = ProfileMappings?.FirstOrDefault(x => x.Code == profile.Code); var stylemapping = StyleMappings?.FirstOrDefault(x => string.Equals(x.Code, profile.Finish)); if (profilemapping != null && productCallback is not null) { productCallback( profilemapping.Entity, stylemapping?.Entity, new RawDimensions() { Length = profile.Length }, profile.Quantity, profile.Cost * profile.Quantity); } } } if (GasketsChecked && gaskets != null) { foreach (var gasket in gaskets) { var _mapping = GasketMappings?.FirstOrDefault(x => x.Code == gasket.Code); var stylemapping = StyleMappings?.FirstOrDefault(x => string.Equals(x.Code, gasket.Finish)); if (_mapping != null && productCallback is not null) { _mapping.ConvertDimensions( x => x.Dimensions, x => x.Quantity, x => x.Cost, Client.Provider ); productCallback( _mapping.Entity, stylemapping?.Entity, new RawDimensions() { Length = _mapping.Dimensions.Length }, _mapping.Quantity, _mapping.Quantity * _mapping.Cost); } } } if (ComponentsChecked && components != null) { foreach (var component in components) { var _mapping = ComponentMappings?.FirstOrDefault(x => string.Equals(x.Code, component.Code)); var stylemapping = StyleMappings?.FirstOrDefault(x => string.Equals(x.Code, component.Finish)); if (_mapping != null && productCallback is not null) { _mapping.ConvertDimensions( x => x.Dimensions, x => x.Quantity, x => x.Cost, Client.Provider ); productCallback( _mapping.Entity, stylemapping?.Entity, new RawDimensions() { Quantity = _mapping.Dimensions.Quantity }, _mapping.Quantity, _mapping.Quantity * _mapping.Cost); } } } if (GlassChecked && glasses != null) { foreach (var glass in glasses) { var _mapping = GlassMappings?.FirstOrDefault(x => string.Equals(x.Code, glass.Code)); if (_mapping != null && productCallback is not null) { productCallback( _mapping.Entity, null, new RawDimensions() { Height = glass.Height, Width = glass.Width }, glass.Quantity, glass.Quantity * glass.Cost); } } } if (LabourChecked && labour != null) { foreach (var activity in labour) { var _mapping = LabourMappings?.FirstOrDefault(x => string.Equals(x.Code, activity.Code)); if (_mapping != null && labourCallback is not null) { labourCallback( _mapping.Entity, TimeSpan.FromHours(activity.Quantity), activity.Quantity * activity.Cost); } } } } private void CheckUpdate(bool isChecked, LogikalUpdateType updateType, IEnumerable? items, IEnumerable? mappings, Action callback) where TEntity : Entity, IRemotable, IPersistent, new() where TItem : IIntegrationItem where TMapping : class, IBaseIntegrationSource { var _items = items as TItem[] ?? items?.ToArray(); var _mappings = mappings as TMapping[] ?? mappings?.ToArray(); if (isChecked && updateType.Equals(LogikalUpdateType.AlwaysUpdate) && _items?.Any()==true && _mappings?.Any() == true) { var _ids = _mappings?.Select(x => x.Entity.ID).Distinct().ToArray() ?? []; var _entities = new Client().Query( new Filter(x=>x.ID).InList(_ids), Columns.Local().Add(Columns.Required()) ).ToArray(); foreach (var _item in _items) { var _mapping = _mappings?.FirstOrDefault(x => string.Equals(x.Code, _item.Code)); if (_mapping != null) { var _entity = _entities.FirstOrDefault(x => x.ID == _mapping.Entity.ID); if (_entity != null) callback(_entity, _mapping); } } var _updates = _entities.Where(x => x.IsChanged()).ToArray(); if (_updates.Any()) new Client().Save(_updates,"Updated by AWG Mapping Window"); } } public void CheckUpdates() { CheckUpdate(StylesChecked, Settings.UpdateStyles, Styles, StyleMappings, PopulateStyle); CheckUpdate(GroupsChecked, Settings.UpdateGroups, Groups, GroupMappings, PopulateGroup); CheckUpdate(SuppliersChecked, Settings.UpdateSuppliers, Suppliers, SupplierMappings, PopulateSupplier); CheckUpdate(DiscountsChecked, Settings.UpdateDiscounts, Discounts, DiscountMappings, (entity,mapping) => { PopulateDiscountGroup(entity,mapping); PopulateDiscount(entity,mapping); }); CheckUpdate(ProfilesChecked, Settings.UpdateProfiles, Profiles, ProfileMappings, (entity, mapping) => { PopulateProfile(entity,mapping); PopulateProduct(entity,mapping); }); CheckUpdate(GasketsChecked, Settings.UpdateGaskets, Gaskets, GasketMappings, (entity, mapping) => { PopulateGasket(entity,mapping); PopulateProduct(entity,mapping); }); CheckUpdate(ComponentsChecked, Settings.UpdateComponents, Components, ComponentMappings, (entity, mapping) => { PopulateComponent(entity,mapping); PopulateProduct(entity,mapping); }); CheckUpdate(GlassChecked, Settings.UpdateGlass, Glass, GlassMappings, (entity, mapping) => { PopulateGlass(entity,mapping); PopulateProduct(entity,mapping); }); CheckUpdate(LabourChecked, Settings.UpdateLabour, Labour, LabourMappings, PopulateActivity); } }