示例#1
0
        public async Task ExportAsync(Stream outStream, ExportImportOptions options, Action <ExportImportProgressInfo> progressCallback, ICancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var progressInfo = new ExportImportProgressInfo {
                Description = "The store are loading"
            };

            progressCallback(progressInfo);

            using (var sw = new StreamWriter(outStream, Encoding.UTF8))
                using (var writer = new JsonTextWriter(sw))
                {
                    writer.WriteStartObject();

                    progressInfo.Description = "Evaluation the number of store records";
                    progressCallback(progressInfo);

                    var searchResult = await _storeSearchService.SearchStoresAsync(new StoreSearchCriteria { Take = BatchSize });

                    var totalCount = searchResult.TotalCount;
                    writer.WritePropertyName("StoreTotalCount");
                    writer.WriteValue(totalCount);

                    writer.WritePropertyName("Stores");
                    writer.WriteStartArray();

                    for (int i = BatchSize; i < totalCount; i += BatchSize)
                    {
                        progressInfo.Description = $"{i} of {totalCount} stores have been loaded";
                        progressCallback(progressInfo);

                        searchResult = await _storeSearchService.SearchStoresAsync(new StoreSearchCriteria { Skip = i, Take = BatchSize });

                        foreach (var store in searchResult.Results)
                        {
                            _serializer.Serialize(writer, store);
                        }
                        writer.Flush();
                        progressInfo.Description = $"{ Math.Min(totalCount, i + BatchSize) } of { totalCount } stores exported";
                        progressCallback(progressInfo);
                    }

                    writer.WriteEndArray();

                    writer.WriteEndObject();
                    writer.Flush();
                }
        }
        public async Task <GenericSearchResult <Store> > SearchStores([FromBody] StoreSearchCriteria criteria)
        {
            //Filter resulting stores correspond to current user permissions
            //first check global permission
            //TODO
            //if (!_securityService.UserHasAnyPermission(User.Identity.Name, null, StorePredefinedPermissions.Read))
            //{
            //    //Get user 'read' permission scopes
            //    criteria.StoreIds = _securityService.GetUserPermissions(User.Identity.Name)
            //                                          .Where(x => x.Id.StartsWith(StorePredefinedPermissions.Read))
            //                                          .SelectMany(x => x.AssignedScopes)
            //                                          .OfType<StoreSelectedScope>()
            //                                          .Select(x => x.Scope)
            //                                          .ToArray();
            //    //Do not return all stores if user don't have corresponding permission
            //    if (criteria.StoreIds.IsNullOrEmpty())
            //    {
            //        throw new HttpResponseException(HttpStatusCode.Unauthorized);
            //    }
            //}

            var result = await _storeSearchService.SearchStoresAsync(criteria);

            return(result);
        }
示例#3
0
        public async Task DoImport(List <CsvProduct> csvProducts, CsvImportInfo importInfo, ExportImportProgressInfo progressInfo, Action <ExportImportProgressInfo> progressCallback)
        {
            var catalog = (await _catalogService.GetByIdsAsync(new[] { importInfo.CatalogId })).FirstOrDefault();

            if (catalog == null)
            {
                throw new InvalidOperationException($"Catalog with id \"{importInfo.CatalogId}\" does not exist.");
            }

            _stores.AddRange((await _storeSearchService.SearchStoresAsync(new StoreSearchCriteria {
                Take = int.MaxValue
            })).Stores);

            var contunie = ImportAllowed(csvProducts, progressInfo, progressCallback);

            if (!contunie)
            {
                return;
            }

            csvProducts = MergeCsvProducts(csvProducts, catalog);

            await MergeFromAlreadyExistProducts(csvProducts, catalog);

            await SaveCategoryTree(catalog, csvProducts, progressInfo, progressCallback);

            await LoadProductDependencies(csvProducts, catalog, importInfo);
            await ResolvePropertyDictionaryItems(csvProducts, progressInfo, progressCallback);

            //take parentless prodcuts and save them first
            progressInfo.TotalCount = csvProducts.Count;

            var mainProcuts = csvProducts.Where(x => x.MainProduct == null).ToList();

            await SaveProducts(mainProcuts, progressInfo, progressCallback);

            //prepare and save variations (needed to be able to save variation with SKU as MainProductId)
            var variations = csvProducts.Except(mainProcuts).ToList();

            foreach (var variation in variations.Where(x => x.MainProductId == null))
            {
                variation.MainProductId = variation.MainProduct.Id;
            }

            await SaveProducts(variations, progressInfo, progressCallback);
        }
        public async Task DoExportAsync(Stream outStream, Action <ExportImportProgressInfo> progressCallback, ICancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var progressInfo = new ExportImportProgressInfo {
                Description = "The store are loading"
            };

            progressCallback(progressInfo);

            using (var sw = new StreamWriter(outStream))
                using (var writer = new JsonTextWriter(sw))
                {
                    await writer.WriteStartObjectAsync();

                    progressInfo.Description = "Stores are started to export";
                    progressCallback(progressInfo);

                    await writer.WritePropertyNameAsync("Stores");

                    await writer.SerializeJsonArrayWithPagingAsync(_jsonSerializer, _batchSize, async (skip, take) =>
                    {
                        var searchCriteria  = AbstractTypeFactory <StoreSearchCriteria> .TryCreateInstance();
                        searchCriteria.Take = take;
                        searchCriteria.Skip = skip;

                        var searchResult = await _storeSearchService.SearchStoresAsync(searchCriteria);
                        return((GenericSearchResult <Store>)searchResult);
                    }, (processedCount, totalCount) =>
                    {
                        progressInfo.Description = $"{processedCount} of {totalCount} stores have been exported";
                        progressCallback(progressInfo);
                    }, cancellationToken);

                    await writer.WriteEndObjectAsync();

                    await writer.FlushAsync();
                }
        }
        private void AttachValidators()
        {
            When(x => new[]
            {
                x.Record.AccountType, x.Record.AccountStatus, x.Record.AccountLogin, x.Record.AccountEmail, x.Record.StoreId, x.Record.StoreName,
                x.Record.EmailVerified.ToString()
            }.Any(field => !string.IsNullOrEmpty(field))
                 , () =>
            {
                RuleFor(x => x.Record.AccountLogin)
                .NotEmpty()
                .WithMissingRequiredValueCodeAndMessage("Account Login")
                .WithImportState()
                .DependentRules(() =>
                {
                    RuleFor(x => x.Record.AccountLogin)
                    .MustAsync(async(thisRecord, userName, __) =>
                    {
                        var lastRecordWithAccountLogin = _allRecords.LastOrDefault(otherRecord => userName.EqualsInvariant(otherRecord.Record.AccountLogin));
                        return(await _userManager.FindByNameAsync(userName) == null &&
                               (_allRecords.All(otherRecord => !userName.EqualsInvariant(otherRecord.Record.AccountLogin)) || lastRecordWithAccountLogin == thisRecord));
                    })
                    .WithNotUniqueValueCodeAndMessage("Account Login")
                    .WithImportState();
                });

                RuleFor(x => x.Record.AccountEmail)
                .NotEmpty()
                .WithMissingRequiredValueCodeAndMessage("Account Email")
                .WithImportState()
                .DependentRules(() =>
                {
                    RuleFor(x => x.Record.AccountEmail)
                    .EmailAddress()
                    .WithInvalidValueCodeAndMessage("Account Email")
                    .WithImportState().DependentRules(() =>
                    {
                        RuleFor(x => x.Record.AccountEmail)
                        .MustAsync(async(thisRecord, email, __) =>
                        {
                            var lastRecordWithAccountEmail = _allRecords.LastOrDefault(otherRecord => email.EqualsInvariant(otherRecord.Record.AccountEmail));
                            return(await _userManager.FindByEmailAsync(email) == null &&
                                   (_allRecords.All(otherRecord => !email.EqualsInvariant(otherRecord.Record.AccountEmail)) || lastRecordWithAccountEmail == thisRecord));
                        })
                        .WithNotUniqueValueCodeAndMessage("Account Email")
                        .WithImportState();
                    });
                });

                RuleFor(x => x.Record.StoreId)
                .NotEmpty()
                .WithMissingRequiredValueCodeAndMessage("Store Id")
                .WithImportState()
                .DependentRules(() =>
                {
                    RuleFor(x => x.Record.StoreId)
                    .MustAsync(async(storeId, _) =>
                    {
                        var storeSearchResult = await _storeSearchService.SearchStoresAsync(new StoreSearchCriteria {
                            StoreIds = new[] { storeId }, Take = 0
                        });
                        return(storeSearchResult.TotalCount == 1);
                    })
                    .WithInvalidValueCodeAndMessage("Store Id")
                    .WithImportState();
                });

                RuleFor(x => x.Record.Password)
                .MustAsync(async(thisRecord, password, _) =>
                {
                    var contact = new Contact();
                    thisRecord.Record.PatchModel(contact);
                    return(await _passwordValidator.ValidateAsync(_userManager, contact.SecurityAccounts.FirstOrDefault(), password) == IdentityResult.Success);
                })
                .When(x => !string.IsNullOrEmpty(x.Record.Password))
                .WithErrorCode(ModuleConstants.ValidationErrors.PasswordDoesntMeetSecurityPolicy)
                .WithMessage(string.Format(ModuleConstants.ValidationMessages[ModuleConstants.ValidationErrors.PasswordDoesntMeetSecurityPolicy], "Password"))
                .WithImportState();

                RuleFor(x => x.Record.AccountType)
                .MustAsync(async(accountType, _) =>
                {
                    var accountTypes = await _settingsManager.GetObjectSettingAsync(PlatformConstants.Settings.Security.SecurityAccountTypes.Name);
                    return(accountTypes.AllowedValues.Contains(accountType));
                })
                .When(x => !string.IsNullOrEmpty(x.Record.AccountType))
                .WithInvalidValueCodeAndMessage("Account Type")
                .WithImportState();

                RuleFor(x => x.Record.AccountStatus)
                .MustAsync(async(accountStatus, _) =>
                {
                    var accountStatuses = await _settingsManager.GetObjectSettingAsync(PlatformConstants.Settings.Other.AccountStatuses.Name);
                    return(accountStatuses.AllowedValues.Contains(accountStatus));
                })
                .When(x => !string.IsNullOrEmpty(x.Record.AccountStatus))
                .WithInvalidValueCodeAndMessage("Account Status")
                .WithImportState();
            });
        }