Beispiel #1
0
        public async Task <IActionResult> Edit(int id)
        {
            var(profile, provider) = await LoadProfileAndProvider(id);

            if (profile == null)
            {
                return(RedirectToAction("List"));
            }

            var model             = new ExportProfileModel();
            var lastExecutionInfo = await _taskStore.GetLastExecutionInfoByTaskIdAsync(profile.TaskId);

            await PrepareProfileModel(model, profile, provider, lastExecutionInfo, true);

            return(View(model));
        }
Beispiel #2
0
        public async Task <IActionResult> Create(ExportProfileModel model)
        {
            if (model.ProviderSystemName.HasValue())
            {
                var provider = _providerManager.GetProvider <IExportProvider>(model.ProviderSystemName);
                if (provider != null)
                {
                    var profile = await _exportProfileService.InsertExportProfileAsync(provider, false, null, model.CloneProfileId ?? 0);

                    return(RedirectToAction("Edit", new { id = profile.Id }));
                }
            }

            NotifyError(T("Admin.Common.ProviderNotLoaded", model.ProviderSystemName.NaIfEmpty()));

            return(RedirectToAction("List"));
        }
Beispiel #3
0
        public async Task <IActionResult> List()
        {
            var model = new List <ExportProfileModel>();

            var providers = _exportProfileService.LoadAllExportProviders(0, false)
                            .ToDictionarySafe(x => x.Metadata.SystemName);

            var profiles = await _db.ExportProfiles
                           .AsNoTracking()
                           .Include(x => x.Task)
                           .Include(x => x.Deployments)
                           .OrderBy(x => x.IsSystemProfile).ThenBy(x => x.Name)
                           .ToListAsync();

            var lastExecutionInfos = (await _taskStore.GetExecutionInfoQuery(false)
                                      .ApplyCurrentMachineNameFilter()
                                      .ApplyTaskFilter(0, true)
                                      .ToListAsync())
                                     .ToDictionarySafe(x => x.TaskDescriptorId);

            foreach (var profile in profiles)
            {
                if (providers.TryGetValue(profile.ProviderSystemName, out var provider))
                {
                    var profileModel = new ExportProfileModel();

                    lastExecutionInfos.TryGetValue(profile.TaskId, out var lastExecutionInfo);
                    await PrepareProfileModel(profileModel, profile, provider, lastExecutionInfo, false);

                    var fileDetailsModel = await CreateFileDetailsModel(profile, null);

                    profileModel.FileCount = fileDetailsModel.FileCount;

                    // TODO: (mg) (core) add Task model.

                    model.Add(profileModel);
                }
            }

            return(View(model));
        }
Beispiel #4
0
        public async Task <IActionResult> Create()
        {
            var num       = 0;
            var providers = _exportProfileService.LoadAllExportProviders(0, false)
                            .ToDictionarySafe(x => x.Metadata.SystemName);

            var profiles = await _db.ExportProfiles
                           .AsNoTracking()
                           .ApplyStandardFilter()
                           .ToListAsync();

            var model = new ExportProfileModel();

            ViewBag.Providers = providers.Values
                                .Select(x => new ExportProfileModel.ProviderSelectItem
            {
                Id         = ++num,
                SystemName = x.Metadata.SystemName,
                ImageUrl   = GetThumbnailUrl(x),
                // TODO: (mg) (core) PluginMediator required in ExportController.
                //FriendlyName = _pluginMediator.GetLocalizedFriendlyName(x.Metadata),
                FriendlyName = x.Metadata.SystemName,
                //Description = _pluginMediator.GetLocalizedDescription(x.Metadata)
                Description = x.Metadata.SystemName
            })
                                .ToList();

            ViewBag.Profiles = profiles
                               .Select(x => new ExportProfileModel.ProviderSelectItem
            {
                Id           = x.Id,
                SystemName   = x.ProviderSystemName,
                FriendlyName = x.Name,
                ImageUrl     = GetThumbnailUrl(providers.Get(x.ProviderSystemName))
            })
                               .ToList();

            return(PartialView(model));
        }
Beispiel #5
0
        // TODO: (mg) (core) add ViewComponent for former child-action "InfoProfile".
        // TODO: (mg) (core) implement action methods for Deployment.

        #region Utilities

        private async Task PrepareProfileModel(
            ExportProfileModel model,
            ExportProfile profile,
            Provider <IExportProvider> provider,
            TaskExecutionInfo lastExecutionInfo,
            bool createForEdit)
        {
            MiniMapper.Map(profile, model);

            var dir = await _exportProfileService.GetExportDirectoryAsync(profile);

            var logFile = await dir.GetFileAsync("log.txt");

            //var moduleDescriptor = provider.Metadata.ModuleDescriptor;

            model.TaskName                    = profile.Task.Name.NaIfEmpty();
            model.IsTaskRunning               = lastExecutionInfo?.IsRunning ?? false;
            model.IsTaskEnabled               = profile.Task.Enabled;
            model.LogFileExists               = logFile.Exists;
            model.HasActiveProvider           = provider != null;
            model.FileNamePatternDescriptions = T("Admin.DataExchange.Export.FileNamePatternDescriptions").Value.SplitSafe(";").ToArray();

            model.Provider = new ExportProfileModel.ProviderModel
            {
                EntityType     = provider.Value.EntityType,
                EntityTypeName = await Services.Localization.GetLocalizedEnumAsync(provider.Value.EntityType),
                FileExtension  = provider.Value.FileExtension,
                ThumbnailUrl   = GetThumbnailUrl(provider),
                // TODO: (mg) (core) PluginMediator required in ExportController.
                //FriendlyName = _pluginMediator.GetLocalizedFriendlyName(provider.Metadata),
                FriendlyName = provider.Metadata.SystemName,
                //Description = _pluginMediator.GetLocalizedDescription(provider.Metadata),
                Description = provider.Metadata.SystemName,
                //Url = descriptor?.Url,
                //Author = descriptor?.Author,
                //Version = descriptor?.Version?.ToString()
            };

            if (!createForEdit)
            {
                return;
            }

            var projection = XmlHelper.Deserialize <ExportProjection>(profile.Projection);
            var filter     = XmlHelper.Deserialize <ExportFilter>(profile.Filtering);

            var language      = Services.WorkContext.WorkingLanguage;
            var store         = Services.StoreContext.CurrentStore;
            var stores        = Services.StoreContext.GetAllStores();
            var emailAccounts = await _db.EmailAccounts.AsNoTracking().ToListAsync();

            var languages = await _db.Languages
                            .AsNoTracking()
                            .OrderBy(x => x.DisplayOrder)
                            .ToListAsync();

            var currencies = await _db.Currencies
                             .AsNoTracking()
                             .OrderBy(x => x.DisplayOrder)
                             .ToListAsync();

            model.Offset                   = profile.Offset;
            model.Limit                    = profile.Limit == 0 ? null : profile.Limit;
            model.BatchSize                = profile.BatchSize == 0 ? null : profile.BatchSize;
            model.PerStore                 = profile.PerStore;
            model.EmailAccountId           = profile.EmailAccountId;
            model.CompletedEmailAddresses  = profile.CompletedEmailAddresses.SplitSafe(",").ToArray();
            model.CreateZipArchive         = profile.CreateZipArchive;
            model.Cleanup                  = profile.Cleanup;
            model.PrimaryStoreCurrencyCode = Services.StoreContext.CurrentStore.PrimaryStoreCurrency.CurrencyCode;
            model.FileNamePatternExample   = profile.ResolveFileNamePattern(store, 1, _dataExchangeSettings.MaxFileNameLength);

            ViewBag.EmailAccounts = emailAccounts
                                    .Select(x => new SelectListItem {
                Text = x.FriendlyName, Value = x.Id.ToString()
            })
                                    .ToList();

            ViewBag.CompletedEmailAddresses = new MultiSelectList(profile.CompletedEmailAddresses.SplitSafe(","));

            // TODO: (mg) (core) check\test whether such ViewBag objects can really be used multiple times for different view controls.
            ViewBag.Stores = stores.ToSelectListItems();

            ViewBag.Languages = languages
                                .Select(y => new SelectListItem {
                Text = y.Name, Value = y.Id.ToString()
            })
                                .ToList();

            ViewBag.Currencies = currencies
                                 .Select(y => new SelectListItem {
                Text = y.Name, Value = y.Id.ToString()
            })
                                 .ToList();

            ViewBag.DeploymentTypeIconClasses = DeploymentTypeIconClasses;

            // Projection.
            model.Projection = MiniMapper.Map <ExportProjection, ExportProjectionModel>(projection);
            model.Projection.NumberOfPictures      = projection.NumberOfMediaFiles;
            model.Projection.AppendDescriptionText = projection.AppendDescriptionText.SplitSafe(",").ToArray();
            model.Projection.CriticalCharacters    = projection.CriticalCharacters.SplitSafe(",").ToArray();

            if (profile.Projection.IsEmpty())
            {
                model.Projection.DescriptionMergingId = (int)ExportDescriptionMerging.Description;
            }

            // Filtering.
            model.Filter = MiniMapper.Map <ExportFilter, ExportFilterModel>(filter);

            // Deployment.
            model.Deployments = await profile.Deployments.SelectAsync(async x =>
            {
                var deploymentModel = await CreateDeploymentModel(profile, x, null, false);

                if (x.ResultInfo.HasValue())
                {
                    var resultInfo    = XmlHelper.Deserialize <DataDeploymentResult>(x.ResultInfo);
                    var lastExecution = Services.DateTimeHelper.ConvertToUserTime(resultInfo.LastExecutionUtc, DateTimeKind.Utc);

                    deploymentModel.LastResult = new ExportDeploymentModel.LastResultInfo
                    {
                        Execution       = lastExecution,
                        ExecutionPretty = lastExecution.Humanize(false),
                        Error           = resultInfo.LastError
                    };
                }

                return(deploymentModel);
            })
                                .AsyncToList();

            // Provider.
            if (provider != null)
            {
                model.Provider.Feature = provider.Metadata.ExportFeatures;

                if (model.Provider.EntityType == ExportEntityType.Product)
                {
                    var manufacturers = await _db.Manufacturers
                                        .AsNoTracking()
                                        .ApplyStandardFilter(true)
                                        .ToListAsync();

                    var productTags = await _db.ProductTags
                                      .AsNoTracking()
                                      .ToListAsync();

                    ViewBag.Manufacturers = manufacturers
                                            .Select(x => new SelectListItem {
                        Text = x.Name, Value = x.Id.ToString()
                    })
                                            .ToList();

                    ViewBag.ProductTags = productTags
                                          .Select(x => new SelectListItem {
                        Text = x.Name, Value = x.Id.ToString()
                    })
                                          .ToList();

                    ViewBag.PriceTypes = PriceDisplayType.LowestPrice
                                         .ToSelectList(false)
                                         .Where(x => x.Value != ((int)PriceDisplayType.Hide).ToString())
                                         .ToList();

                    ViewBag.AppendDescriptionTexts = new MultiSelectList(projection.AppendDescriptionText.SplitSafe(","));
                    ViewBag.CriticalCharacters     = new MultiSelectList(projection.CriticalCharacters.SplitSafe(","));

                    if (model.Filter.CategoryIds?.Any() ?? false)
                    {
                        var tree = await _categoryService.GetCategoryTreeAsync(0, true);

                        ViewBag.SelectedCategories = model.Filter.CategoryIds
                                                     .Where(x => x != 0)
                                                     .Select(x =>
                        {
                            var node = tree.SelectNodeById(x);
                            var item = new SelectListItem {
                                Selected = true, Value = x.ToString(), Text = node == null ? x.ToString() : _categoryService.GetCategoryPath(node)
                            };
                            return(item);
                        })
                                                     .ToList();
                    }
                    else
                    {
                        ViewBag.SelectedCategories = new List <SelectListItem>();
                    }
                }
                else if (model.Provider.EntityType == ExportEntityType.Customer)
                {
                    var countries = await _db.Countries
                                    .AsNoTracking()
                                    .ApplyStandardFilter(true)
                                    .ToListAsync();

                    ViewBag.Countries = countries
                                        .Select(x => new SelectListItem {
                        Text = x.GetLocalized(y => y.Name, language, true, false), Value = x.Id.ToString()
                    })
                                        .ToList();
                }

                try
                {
                    var configInfo = provider.Value.ConfigurationInfo;
                    if (configInfo != null)
                    {
                        model.Provider.ConfigurationWidget = configInfo.ConfigurationWidget;
                        model.Provider.ConfigDataType      = configInfo.ModelType;
                        model.Provider.ConfigData          = XmlHelper.Deserialize(profile.ProviderConfigData, configInfo.ModelType);

                        if (configInfo.Initialize != null)
                        {
                            try
                            {
                                configInfo.Initialize(model.Provider.ConfigData);
                            }
                            catch (Exception ex)
                            {
                                NotifyWarning(ex.ToAllMessages());
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    NotifyError(ex);
                }
            }
        }
Beispiel #6
0
        public async Task <IActionResult> Edit(ExportProfileModel model, bool continueEditing)
        {
            var(profile, provider) = await LoadProfileAndProvider(model.Id);

            if (profile == null)
            {
                return(RedirectToAction("List"));
            }

            if (!ModelState.IsValid)
            {
                var lastExecutionInfo = await _taskStore.GetLastExecutionInfoByTaskIdAsync(profile.TaskId);
                await PrepareProfileModel(model, profile, provider, lastExecutionInfo, true);

                return(View(model));
            }

            profile.Name                    = model.Name.NullEmpty() ?? provider.Metadata.FriendlyName.NullEmpty() ?? provider.Metadata.SystemName;
            profile.FileNamePattern         = model.FileNamePattern;
            profile.FolderName              = model.FolderName;
            profile.Enabled                 = model.Enabled;
            profile.ExportRelatedData       = model.ExportRelatedData;
            profile.Offset                  = model.Offset;
            profile.Limit                   = model.Limit ?? 0;
            profile.BatchSize               = model.BatchSize ?? 0;
            profile.PerStore                = model.PerStore;
            profile.CompletedEmailAddresses = string.Join(",", model.CompletedEmailAddresses ?? Array.Empty <string>());
            profile.EmailAccountId          = model.EmailAccountId ?? 0;
            profile.CreateZipArchive        = model.CreateZipArchive;
            profile.Cleanup                 = model.Cleanup;

            // Projection.
            if (model.Projection != null)
            {
                var projection = MiniMapper.Map <ExportProjectionModel, ExportProjection>(model.Projection);
                projection.NumberOfMediaFiles       = model.Projection.NumberOfPictures;
                projection.AppendDescriptionText    = string.Join(",", model.Projection.AppendDescriptionText ?? Array.Empty <string>());
                projection.RemoveCriticalCharacters = model.Projection.RemoveCriticalCharacters;
                projection.CriticalCharacters       = string.Join(",", model.Projection.CriticalCharacters ?? Array.Empty <string>());

                profile.Projection = XmlHelper.Serialize(projection);
            }

            // Filtering.
            if (model.Filter != null)
            {
                var filter = MiniMapper.Map <ExportFilterModel, ExportFilter>(model.Filter);
                filter.StoreId     = model.Filter.StoreId ?? 0;
                filter.CategoryIds = model.Filter.CategoryIds?.Where(x => x != 0)?.ToArray() ?? Array.Empty <int>();

                profile.Filtering = XmlHelper.Serialize(filter);
            }

            // Provider configuration.
            profile.ProviderConfigData = null;
            try
            {
                var configInfo = provider.Value.ConfigurationInfo;
                if (configInfo != null && model.CustomProperties.ContainsKey("ProviderConfigData"))
                {
                    profile.ProviderConfigData = XmlHelper.Serialize(model.CustomProperties["ProviderConfigData"], configInfo.ModelType);
                }
            }
            catch (Exception ex)
            {
                NotifyError(ex);
            }

            await _db.SaveChangesAsync();

            NotifySuccess(T("Admin.Common.DataSuccessfullySaved"));

            return(continueEditing
                ? RedirectToAction("Edit", new { id = profile.Id })
                : RedirectToAction("List"));
        }