Exemple #1
0
        public ActionResult List(GridCommand command)
        {
            var model = new GridModel <AffiliateModel>();

            if (_permissionService.Authorize(StandardPermissionProvider.ManageAffiliates))
            {
                var affiliates = _affiliateService.GetAllAffiliates(true);

                model.Data = affiliates.PagedForCommand(command).Select(x =>
                {
                    var m = new AffiliateModel();
                    PrepareAffiliateModel(m, x, false);
                    return(m);
                });

                model.Total = affiliates.Count;
            }
            else
            {
                model.Data = Enumerable.Empty <AffiliateModel>();

                NotifyAccessDenied();
            }

            return(new JsonResult
            {
                Data = model
            });
        }
        public virtual IActionResult List(DataSourceRequest command, AffiliateListModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAffiliates))
            {
                return(AccessDeniedKendoGridJson());
            }

            var affiliates = _affiliateService.GetAllAffiliates(model.SearchFriendlyUrlName,
                                                                model.SearchFirstName, model.SearchLastName,
                                                                model.LoadOnlyWithOrders, model.OrdersCreatedFromUtc, model.OrdersCreatedToUtc,
                                                                command.Page - 1, command.PageSize, true);

            var gridModel = new DataSourceResult
            {
                Data = affiliates.Select(x =>
                {
                    var m = new AffiliateModel();
                    PrepareAffiliateModel(m, x, false, false, false);
                    return(m);
                }),
                Total = affiliates.TotalCount,
            };

            return(Json(gridModel));
        }
Exemple #3
0
        /// <summary>
        /// Prepare paged affiliate list model
        /// </summary>
        /// <param name="searchModel">Affiliate search model</param>
        /// <returns>Affiliate list model</returns>
        public virtual AffiliateListModel PrepareAffiliateListModel(AffiliateSearchModel searchModel)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get affiliates
            var affiliates = _affiliateService.GetAllAffiliates(searchModel.SearchFriendlyUrlName,
                                                                searchModel.SearchFirstName,
                                                                searchModel.SearchLastName,
                                                                searchModel.LoadOnlyWithOrders,
                                                                searchModel.OrdersCreatedFromUtc,
                                                                searchModel.OrdersCreatedToUtc,
                                                                searchModel.Page - 1, searchModel.PageSize, true);

            //prepare list model
            var model = new AffiliateListModel
            {
                //fill in model values from the entity
                Data = affiliates.Select(affiliate =>
                {
                    var affiliateModel     = affiliate.ToModel <AffiliateModel>();
                    affiliateModel.Address = affiliate.Address.ToModel <AddressModel>();

                    return(affiliateModel);
                }),
                Total = affiliates.TotalCount
            };

            return(model);
        }
        /// <summary>
        /// Prepare paged affiliate list model
        /// </summary>
        /// <param name="searchModel">Affiliate search model</param>
        /// <returns>Affiliate list model</returns>
        public virtual AffiliateListModel PrepareAffiliateListModel(AffiliateSearchModel searchModel)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get affiliates
            var affiliates = _affiliateService.GetAllAffiliates(searchModel.SearchFriendlyUrlName,
                                                                searchModel.SearchFirstName,
                                                                searchModel.SearchLastName,
                                                                searchModel.LoadOnlyWithOrders,
                                                                searchModel.OrdersCreatedFromUtc,
                                                                searchModel.OrdersCreatedToUtc,
                                                                searchModel.Page - 1, searchModel.PageSize, true);

            //prepare list model
            var model = new AffiliateListModel().PrepareToGrid(searchModel, affiliates, () =>
            {
                //fill in model values from the entity
                return(affiliates.Select(affiliate =>
                {
                    var address = _addressService.GetAddressById(affiliate.AddressId);

                    var affiliateModel = affiliate.ToModel <AffiliateModel>();
                    affiliateModel.Address = address.ToModel <AddressModel>();
                    affiliateModel.Address.CountryName = _countryService.GetCountryByAddress(address)?.Name;
                    affiliateModel.Address.StateProvinceName = _stateProvinceService.GetStateProvinceByAddress(address)?.Name;

                    return affiliateModel;
                }));
            });

            return(model);
        }
 /// <summary>
 /// Gets all affiliates
 /// </summary>
 /// <param name="friendlyUrlName">Friendly URL name; null to load all records</param>
 /// <param name="firstName">First name; null to load all records</param>
 /// <param name="lastName">Last name; null to load all records</param>
 /// <param name="loadOnlyWithOrders">Value indicating whether to load affiliates only with orders placed (by affiliated customers)</param>
 /// <param name="ordersCreatedFromUtc">Orders created date from (UTC); null to load all records. It's used only with "loadOnlyWithOrders" parameter st to "true".</param>
 /// <param name="ordersCreatedToUtc">Orders created date to (UTC); null to load all records. It's used only with "loadOnlyWithOrders" parameter st to "true".</param>
 /// <param name="pageIndex">Page index</param>
 /// <param name="pageSize">Page size</param>
 /// <param name="showHidden">A value indicating whether to show hidden records</param>
 /// <returns>Affiliates</returns>
 public IAPIPagedList <Affiliate> GetAllAffiliates(string friendlyUrlName        = null,
                                                   string firstName              = null, string lastName = null,
                                                   bool loadOnlyWithOrders       = false,
                                                   DateTime?ordersCreatedFromUtc = null, DateTime?ordersCreatedToUtc = null,
                                                   int pageIndex   = 0, int pageSize = int.MaxValue,
                                                   bool showHidden = false)
 {
     return(_affiliateService.GetAllAffiliates(friendlyUrlName, firstName, lastName, loadOnlyWithOrders, ordersCreatedFromUtc, ordersCreatedToUtc, pageIndex, pageSize, showHidden).ConvertPagedListToAPIPagedList());
 }
Exemple #6
0
        public virtual (IEnumerable <AffiliateModel> affiliateModels, int totalCount) PrepareAffiliateModelList(AffiliateListModel model, int pageIndex, int pageSize)
        {
            var affiliates = _affiliateService.GetAllAffiliates(model.SearchFriendlyUrlName,
                                                                model.SearchFirstName, model.SearchLastName,
                                                                model.LoadOnlyWithOrders, model.OrdersCreatedFromUtc, model.OrdersCreatedToUtc,
                                                                pageIndex - 1, pageSize, true);

            return(affiliates.Select(x =>
            {
                var m = new AffiliateModel();
                PrepareAffiliateModel(m, x, false, false);
                return m;
            }), affiliates.TotalCount);
        }
        public async Task Process()
        {
            var affiliates = await _affiliateService.GetAllAffiliates();

            foreach (var affiliate in affiliates)
            {
                try
                {
                    await ProcessOneUser(affiliate);
                }
                catch (Exception ex)
                {
                    await _logger.WriteErrorAsync(nameof(BonusProcessor), nameof(Process), $"Affilaite: {affiliate}", ex);
                }
            }
        }
        public virtual async Task <(IEnumerable <AffiliateModel> affiliateModels, int totalCount)> PrepareAffiliateModelList(AffiliateListModel model, int pageIndex, int pageSize)
        {
            var affiliates = await _affiliateService.GetAllAffiliates(model.SearchFriendlyUrlName,
                                                                      model.SearchFirstName, model.SearchLastName,
                                                                      model.LoadOnlyWithOrders, model.OrdersCreatedFromUtc, model.OrdersCreatedToUtc,
                                                                      pageIndex - 1, pageSize, true);

            var affiliateModels = new List <AffiliateModel>();

            foreach (var x in affiliates)
            {
                var m = new AffiliateModel();
                await PrepareAffiliateModel(m, x, false, false);

                affiliateModels.Add(m);
            }
            return(affiliateModels, affiliates.TotalCount);
        }
Exemple #9
0
        public ActionResult List(GridCommand command)
        {
            var model = new GridModel <AffiliateModel>();

            var affiliates = _affiliateService.GetAllAffiliates(true);

            model.Data = affiliates.PagedForCommand(command).Select(x =>
            {
                var m = new AffiliateModel();
                PrepareAffiliateModel(m, x, false);
                return(m);
            });

            model.Total = affiliates.Count;

            return(new JsonResult
            {
                Data = model
            });
        }
        public ActionResult List(DataSourceRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAffiliates))
            {
                return(AccessDeniedView());
            }

            var affiliates = _affiliateService.GetAllAffiliates(command.Page - 1, command.PageSize, true);
            var gridModel  = new DataSourceResult
            {
                Data = affiliates.Select(x =>
                {
                    var m = new AffiliateModel();
                    PrepareAffiliateModel(m, x, false, false);
                    return(m);
                }),
                Total = affiliates.TotalCount,
            };

            return(Json(gridModel));
        }
        public ActionResult List(GridCommand command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAffiliates))
            {
                return(AccessDeniedView());
            }

            var affiliates = _affiliateService.GetAllAffiliates(true);
            var gridModel  = new GridModel <AffiliateModel>
            {
                Data = affiliates.PagedForCommand(command).Select(x =>
                {
                    var m = new AffiliateModel();
                    PrepareAffiliateModel(m, x, false);
                    return(m);
                }),
                Total = affiliates.Count,
            };

            return(new JsonResult
            {
                Data = gridModel
            });
        }
Exemple #12
0
        protected override void Import(ImportExecuteContext context)
        {
            var customer = _services.WorkContext.CurrentCustomer;
            var allowManagingCustomerRoles = _services.Permissions.Authorize(StandardPermissionProvider.ManageCustomerRoles, customer);

            var allAffiliateIds = _affiliateService.GetAllAffiliates(true)
                                  .Select(x => x.Id)
                                  .ToList();

            var allCountries = new Dictionary <string, int>();

            foreach (var country in _countryService.GetAllCountries(true))
            {
                if (!allCountries.ContainsKey(country.TwoLetterIsoCode))
                {
                    allCountries.Add(country.TwoLetterIsoCode, country.Id);
                }

                if (!allCountries.ContainsKey(country.ThreeLetterIsoCode))
                {
                    allCountries.Add(country.ThreeLetterIsoCode, country.Id);
                }
            }

            var allStateProvinces = _stateProvinceService.GetAllStateProvinces(true)
                                    .ToDictionarySafe(x => new Tuple <int, string>(x.CountryId, x.Abbreviation), x => x.Id);

            var allCustomerNumbers = new HashSet <string>(
                _genericAttributeService.GetAttributes(SystemCustomerAttributeNames.CustomerNumber, _attributeKeyGroup).Select(x => x.Value),
                StringComparer.OrdinalIgnoreCase);

            var allCustomerRoles = _customerRoleRepository.Table.ToDictionarySafe(x => x.SystemName, StringComparer.OrdinalIgnoreCase);

            using (var scope = new DbContextScope(ctx: _services.DbContext, autoDetectChanges: false, proxyCreation: false, validateOnSave: false, autoCommit: false))
            {
                var segmenter = context.DataSegmenter;

                Initialize(context);
                AddInfoForDeprecatedFields(context);

                while (context.Abort == DataExchangeAbortion.None && segmenter.ReadNextBatch())
                {
                    var batch = segmenter.GetCurrentBatch <Customer>();

                    _customerRepository.Context.DetachAll(true);

                    context.SetProgress(segmenter.CurrentSegmentFirstRowIndex - 1, segmenter.TotalRows);

                    // ===========================================================================
                    // Process customers
                    // ===========================================================================
                    try
                    {
                        ProcessCustomers(context, batch, allAffiliateIds);
                    }
                    catch (Exception exception)
                    {
                        context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessCustomers");
                    }

                    // reduce batch to saved (valid) records.
                    // No need to perform import operations on errored records.
                    batch = batch.Where(x => x.Entity != null && !x.IsTransient).ToArray();

                    // update result object
                    context.Result.NewRecords      += batch.Count(x => x.IsNew && !x.IsTransient);
                    context.Result.ModifiedRecords += batch.Count(x => !x.IsNew && !x.IsTransient);

                    // ===========================================================================
                    // Process customer roles
                    // ===========================================================================
                    try
                    {
                        _customerRepository.Context.AutoDetectChangesEnabled = true;
                        ProcessCustomerRoles(context, batch, allCustomerRoles);
                    }
                    catch (Exception exception)
                    {
                        context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessCustomerRoles");
                    }
                    finally
                    {
                        _customerRepository.Context.AutoDetectChangesEnabled = false;
                    }

                    // ===========================================================================
                    // Process generic attributes
                    // ===========================================================================
                    try
                    {
                        ProcessGenericAttributes(context, batch, allCountries, allStateProvinces, allCustomerNumbers);
                    }
                    catch (Exception exception)
                    {
                        context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessGenericAttributes");
                    }

                    // ===========================================================================
                    // Process avatars
                    // ===========================================================================
                    if (_customerSettings.AllowCustomersToUploadAvatars)
                    {
                        try
                        {
                            ProcessAvatars(context, batch);
                        }
                        catch (Exception exception)
                        {
                            context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessAvatars");
                        }
                    }

                    // ===========================================================================
                    // Process addresses
                    // ===========================================================================
                    try
                    {
                        _services.DbContext.AutoDetectChangesEnabled = true;
                        ProcessAddresses(context, batch, allCountries, allStateProvinces);
                    }
                    catch (Exception exception)
                    {
                        context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessAddresses");
                    }
                    finally
                    {
                        _services.DbContext.AutoDetectChangesEnabled = false;
                    }
                }
            }
        }
        protected override void Import(IImportExecuteContext context)
        {
            var customer = _services.WorkContext.CurrentCustomer;
            var allowManagingCustomerRoles = _services.Permissions.Authorize(StandardPermissionProvider.ManageCustomerRoles, customer);

            var allCustomerRoles = _customerService.GetAllCustomerRoles(true);

            var allAffiliateIds = _affiliateService.GetAllAffiliates(true)
                                  .Select(x => x.Id)
                                  .ToList();

            var allCountryIds = _countryService.GetAllCountries(true)
                                .Select(x => x.Id)
                                .ToList();

            var allStateProvinceIds = _stateProvinceService.GetAllStateProvinces(true)
                                      .Select(x => x.Id)
                                      .ToList();

            var allCustomerNumbers = _genericAttributeService.GetAttributes(SystemCustomerAttributeNames.CustomerNumber, _attributeKeyGroup)
                                     .Select(x => x.Value)
                                     .ToList();

            using (var scope = new DbContextScope(ctx: _services.DbContext, autoDetectChanges: false, proxyCreation: false, validateOnSave: false, autoCommit: false))
            {
                var segmenter = context.GetSegmenter <Customer>();

                Init(context, _dataExchangeSettings);

                context.Result.TotalRecords = segmenter.TotalRows;

                while (context.Abort == DataExchangeAbortion.None && segmenter.ReadNextBatch())
                {
                    var batch = segmenter.CurrentBatch;

                    _customerRepository.Context.DetachAll(false);

                    context.SetProgress(segmenter.CurrentSegmentFirstRowIndex - 1, segmenter.TotalRows);

                    try
                    {
                        ProcessCustomers(context, batch, allAffiliateIds, allCustomerRoles);
                    }
                    catch (Exception exception)
                    {
                        context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessCustomers");
                    }

                    // reduce batch to saved (valid) records.
                    // No need to perform import operations on errored records.
                    batch = batch.Where(x => x.Entity != null && !x.IsTransient).ToArray();

                    // update result object
                    context.Result.NewRecords      += batch.Count(x => x.IsNew && !x.IsTransient);
                    context.Result.ModifiedRecords += batch.Count(x => !x.IsNew && !x.IsTransient);

                    try
                    {
                        _services.DbContext.AutoDetectChangesEnabled = true;

                        ProcessGenericAttributes(context, batch, allCountryIds, allStateProvinceIds, allCustomerNumbers);
                    }
                    catch (Exception exception)
                    {
                        context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessGenericAttributes");
                    }
                    finally
                    {
                        _services.DbContext.AutoDetectChangesEnabled = false;
                    }
                }
            }
        }
Exemple #14
0
        protected virtual void PrepareAffiliateModel(AffiliateModel model, Affiliate affiliate, bool excludeProperties,
                                                     bool prepareEntireAddressModel = true)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            if (affiliate != null)
            {
                model.Id  = affiliate.Id;
                model.Url = affiliate.GenerateUrl(_webHelper);
                if (!excludeProperties)
                {
                    model.AdminComment      = affiliate.AdminComment;
                    model.FriendlyUrlName   = affiliate.FriendlyUrlName;
                    model.Active            = affiliate.Active;
                    model.Address           = affiliate.Address.ToModel();
                    model.Level             = affiliate.Level;
                    model.ParentAffiliateId = affiliate.ParentAffiliateId;
                }
            }

            if (prepareEntireAddressModel)
            {
                model.Address.FirstNameEnabled      = true;
                model.Address.FirstNameRequired     = true;
                model.Address.LastNameEnabled       = true;
                model.Address.LastNameRequired      = true;
                model.Address.EmailEnabled          = true;
                model.Address.EmailRequired         = true;
                model.Address.CompanyEnabled        = true;
                model.Address.CountryEnabled        = true;
                model.Address.StateProvinceEnabled  = true;
                model.Address.CityEnabled           = true;
                model.Address.CityRequired          = true;
                model.Address.StreetAddressEnabled  = true;
                model.Address.StreetAddressRequired = true;
                model.Address.StreetAddress2Enabled = true;
                model.Address.ZipPostalCodeEnabled  = true;
                model.Address.ZipPostalCodeRequired = true;
                model.Address.PhoneEnabled          = true;
                model.Address.PhoneRequired         = true;
                model.Address.FaxEnabled            = true;

                //address
                model.Address.AvailableCountries.Add(new SelectListItem {
                    Text = _localizationService.GetResource("Admin.Address.SelectCountry"), Value = "0"
                });
                foreach (var c in _countryService.GetAllCountries(true))
                {
                    model.Address.AvailableCountries.Add(new SelectListItem {
                        Text = c.Name, Value = c.Id.ToString(), Selected = (affiliate != null && c.Id == affiliate.Address.CountryId)
                    });
                }

                var states = model.Address.CountryId.HasValue ? _stateProvinceService.GetStateProvincesByCountryId(model.Address.CountryId.Value, true).ToList() : new List <StateProvince>();
                if (states.Count > 0)
                {
                    foreach (var s in states)
                    {
                        model.Address.AvailableStates.Add(new SelectListItem {
                            Text = s.Name, Value = s.Id.ToString(), Selected = (affiliate != null && s.Id == affiliate.Address.StateProvinceId)
                        });
                    }
                }
                else
                {
                    model.Address.AvailableStates.Add(new SelectListItem {
                        Text = _localizationService.GetResource("Admin.Address.OtherNonUS"), Value = "0"
                    });
                }

                model.AvailableAffiliates.Add(new SelectListItem {
                    Text = "无", Value = "0"
                });

                foreach (var a in _affiliateService.GetAllAffiliates())
                {
                    if (a.Level == 1 || a.Level == 2)
                    {
                        model.AvailableAffiliates.Add(new SelectListItem {
                            Text = a.GetFullName(), Value = a.Id.ToString()
                        });
                    }
                }
            }
        }