Exemplo n.º 1
0
 public Task <bool> DeleteCustomer(CustomerRole entity)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 2
0
        public async Task Can_get_final_product_price_with_tier_prices_by_customerRole()
        {
            /*
             * this test shows how property "Price" of class "Product" can change in relation to:
             *  > TierPrice (the more you buy, the less you pay)
             *  > CustomerRole (some of our customers are more "valuable" than others e.g. wholesale customer
             */

            var product = new Product
            {
                Id    = "1",
                Name  = "product name 01",
                Price = 49.99M,
                CustomerEntersPrice = false,
                Published           = true,
            };

            //this is normal user - normal prices
            var customerRoleNormal = new CustomerRole {
                Id = "101", Name = "same role 01", Active = true
            };
            //very important person - extra off
            var customerRoleVip = new CustomerRole {
                Id = "201", Name = "vip role 02", Active = true
            };
            //king of the world - he will have everything for free
            var customerRoleKingOfWorld = new CustomerRole {
                Id = "301", Name = "king role 02", Active = true
            };

            //101 stands for normal user
            //201 vip
            //301 king
            product.TierPrices.Add(new TierPrice {
                Price = 40M, Quantity = 5, ProductId = "1", CustomerRoleId = "101"
            });
            product.TierPrices.Add(new TierPrice {
                Price = 2M, Quantity = 1000, ProductId = "1", CustomerRoleId = "101"
            });
            product.TierPrices.Add(new TierPrice {
                Price = 20M, Quantity = 5, ProductId = "1", CustomerRoleId = "201"
            });
            product.TierPrices.Add(new TierPrice {
                Price = 2M, Quantity = 1000, ProductId = "1", CustomerRoleId = "201"
            });
            product.TierPrices.Add(new TierPrice {
                Price = 10M, Quantity = 5, ProductId = "1", CustomerRoleId = "301"
            });
            product.TierPrices.Add(new TierPrice {
                Price = 2M, Quantity = 1000, ProductId = "1", CustomerRoleId = "301"
            });

            //all of these Customers will pay 49.99 for one product, if they buy less than 5 products
            //but when they buy exactly 5 or more..
            //then they will pay:
            //      normal 5x40     = 200
            //      vip 5x20        = 100
            //      king 5x10       = 50

            //but
            //all of them will pay only 2 per unit if they buy at least quantity of 1000
            //2x1000                = 2000

            //lets try normal customer
            var normalCustomer = new Customer();

            normalCustomer.CustomerRoles.Add(customerRoleNormal);
            //49.99 - 40 - 2
            Assert.AreEqual(49.99M, (await _priceCalcService.GetFinalPrice(product, normalCustomer, _currency, 0, false, 1)).finalPrice);
            Assert.AreEqual(40, (await _priceCalcService.GetFinalPrice(product, normalCustomer, _currency, 0, false, 5)).finalPrice);
            Assert.AreEqual(2, (await _priceCalcService.GetFinalPrice(product, normalCustomer, _currency, 0, false, 1000)).finalPrice);

            //lets try vip customer
            var vipCustomer = new Customer();

            vipCustomer.CustomerRoles.Add(customerRoleVip);
            //49.99 - 20 - 2
            Assert.AreEqual(49.99M, (await _priceCalcService.GetFinalPrice(product, vipCustomer, _currency, 0, false, 1)).finalPrice);
            Assert.AreEqual(20, (await _priceCalcService.GetFinalPrice(product, vipCustomer, _currency, 0, false, 5)).finalPrice);
            Assert.AreEqual(2, (await _priceCalcService.GetFinalPrice(product, vipCustomer, _currency, 0, false, 1000)).finalPrice);

            //lets try king customer
            var kingCustomer = new Customer();

            kingCustomer.CustomerRoles.Add(customerRoleKingOfWorld);
            //49.99 - 10 - 2
            Assert.AreEqual(49.99M, (await _priceCalcService.GetFinalPrice(product, kingCustomer, _currency, 0, false, 1)).finalPrice);
            Assert.AreEqual(10, (await _priceCalcService.GetFinalPrice(product, kingCustomer, _currency, 0, false, 5)).finalPrice);
            Assert.AreEqual(2, (await _priceCalcService.GetFinalPrice(product, kingCustomer, _currency, 0, false, 1000)).finalPrice);
            //I know it is intricate, but all works fine
        }
Exemplo n.º 3
0
        public void Can_get_final_product_price_with_tier_prices_by_customerRole()
        {
            var product = new Product
            {
                Id    = 1,
                Name  = "Product name 1",
                Price = 12.34M,
                CustomerEntersPrice = false,
                Published           = true,
            };

            //customer roles
            var customerRole1 = new CustomerRole
            {
                Id     = 1,
                Name   = "Some role 1",
                Active = true,
            };
            var customerRole2 = new CustomerRole
            {
                Id     = 2,
                Name   = "Some role 2",
                Active = true,
            };

            //add tier prices
            product.TierPrices.Add(new TierPrice
            {
                Price        = 10,
                Quantity     = 2,
                Product      = product,
                CustomerRole = customerRole1
            });
            product.TierPrices.Add(new TierPrice
            {
                Price        = 9,
                Quantity     = 2,
                Product      = product,
                CustomerRole = customerRole2
            });
            product.TierPrices.Add(new TierPrice
            {
                Price        = 8,
                Quantity     = 5,
                Product      = product,
                CustomerRole = customerRole1
            });
            product.TierPrices.Add(new TierPrice
            {
                Price        = 5,
                Quantity     = 10,
                Product      = product,
                CustomerRole = customerRole2
            });
            //set HasTierPrices property
            product.HasTierPrices = true;

            //customer
            var customer = new Customer();

            customer.CustomerRoles.Add(customerRole1);

            _priceCalcService.GetFinalPrice(product, customer, 0, false, 1).ShouldEqual(12.34M);
            _priceCalcService.GetFinalPrice(product, customer, 0, false, 2).ShouldEqual(10);
            _priceCalcService.GetFinalPrice(product, customer, 0, false, 3).ShouldEqual(10);
            _priceCalcService.GetFinalPrice(product, customer, 0, false, 5).ShouldEqual(8);
            _priceCalcService.GetFinalPrice(product, customer, 0, false, 10).ShouldEqual(8);
        }
Exemplo n.º 4
0
        public virtual void InstallPermissions(IPermissionProvider[] permissionProviders, bool removeUnusedPermissions = false)
        {
            if (!(permissionProviders?.Any() ?? false))
            {
                return;
            }

            Dictionary <string, CustomerRole> existingRoles = null;
            var allPermissionNames = _permissionRepository.TableUntracked.Select(x => x.SystemName).ToList();
            var existing           = new HashSet <string>(allPermissionNames, StringComparer.InvariantCultureIgnoreCase);
            var added = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase);
            var providerPermissions = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase);
            var log        = existing.Any();
            var clearCache = false;

            if (existing.Any())
            {
                var permissionsMigrated = existing.Contains(Permissions.System.AccessShop) && !existing.Contains("PublicStoreAllowNavigation");
                if (!permissionsMigrated)
                {
                    // Migrations must have been completed before permissions can be added or deleted.
                    return;
                }
            }

            try
            {
                using (var scope = new DbContextScope(_permissionRepository.Context, validateOnSave: false, hooksEnabled: false, autoCommit: false))
                {
                    // Add new permissions.
                    foreach (var provider in permissionProviders)
                    {
                        try
                        {
                            var systemNames        = provider.GetPermissions().Select(x => x.SystemName);
                            var missingSystemNames = systemNames.Except(existing);

                            if (removeUnusedPermissions)
                            {
                                providerPermissions.AddRange(systemNames);
                            }

                            if (missingSystemNames.Any())
                            {
                                var defaultPermissions = provider.GetDefaultPermissions();
                                foreach (var systemName in missingSystemNames)
                                {
                                    var roleNames = defaultPermissions
                                                    .Where(x => x.PermissionRecords.Any(y => y.SystemName == systemName))
                                                    .Select(x => x.CustomerRoleSystemName);

                                    var newPermission = new PermissionRecord {
                                        SystemName = systemName
                                    };

                                    foreach (var roleName in new HashSet <string>(roleNames, StringComparer.InvariantCultureIgnoreCase))
                                    {
                                        if (existingRoles == null)
                                        {
                                            existingRoles = new Dictionary <string, CustomerRole>();

                                            var rolesQuery = _customerService.Value.GetAllCustomerRoles(true).SourceQuery;
                                            rolesQuery = rolesQuery.Where(x => !string.IsNullOrEmpty(x.SystemName));

                                            var rolesPager = new FastPager <CustomerRole>(rolesQuery, 500);

                                            while (rolesPager.ReadNextPage(out var roles))
                                            {
                                                roles.Each(x => existingRoles[x.SystemName] = x);
                                            }
                                        }

                                        if (!existingRoles.TryGetValue(roleName, out var role))
                                        {
                                            role = new CustomerRole
                                            {
                                                Active     = true,
                                                Name       = roleName,
                                                SystemName = roleName
                                            };

                                            _customerService.Value.InsertCustomerRole(role);
                                            scope.Commit();
                                            existingRoles[roleName] = role;
                                        }

                                        newPermission.PermissionRoleMappings.Add(new PermissionRoleMapping
                                        {
                                            Allow          = true,
                                            CustomerRoleId = role.Id
                                        });
                                    }

                                    _permissionRepository.Insert(newPermission);

                                    clearCache = true;
                                    added.Add(newPermission.SystemName);
                                    existing.Add(newPermission.SystemName);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex);
                        }
                    }

                    scope.Commit();

                    if (log && added.Any())
                    {
                        Logger.Info(T("Admin.Permissions.AddedPermissions", string.Join(", ", added)));
                    }

                    // Remove permissions no longer supported by providers.
                    if (removeUnusedPermissions)
                    {
                        var toDelete = existing.Except(providerPermissions).ToList();
                        if (toDelete.Any())
                        {
                            clearCache = true;

                            foreach (var chunk in toDelete.Slice(500))
                            {
                                var entities = _permissionRepository.Table.Where(x => chunk.Contains(x.SystemName)).ToList();
                                entities.Each(x => _permissionRepository.Delete(x));
                                scope.Commit();
                            }

                            if (log)
                            {
                                Logger.Info(T("Admin.Permissions.RemovedPermissions", string.Join(", ", toDelete)));
                            }
                        }
                    }
                }
            }
            finally
            {
                if (clearCache)
                {
                    _cacheManager.RemoveByPattern(PERMISSION_TREE_PATTERN_KEY);
                }
            }
        }
Exemplo n.º 5
0
        public ActionResult Register(RegisterCustomerModel model)
        {
            bool   statusRegistration  = false;
            string messageRegistration = string.Empty;

            if (ModelState.IsValid)
            {
                // Email Verification
                string userName = Membership.GetUserNameByEmail(model.Email);
                if (!string.IsNullOrEmpty(userName))
                {
                    ModelState.AddModelError("Warning Email", "Sorry: Email already Exists");
                    return(View(model));
                }

                //Save User Data
                var customer = new Customer()
                {
                    FirstName            = model.FirstName,
                    LastName             = model.LastName,
                    Email                = model.Email,
                    Contactno            = model.Contactno,
                    Username             = model.Email,
                    Password             = model.Password,
                    CompanyName          = model.CompanyName,
                    Date_of_Registration = DateTime.Now,
                    IsActive             = false,
                    createddate          = DateTime.Now,
                    updateddate          = DateTime.Now,
                    ActivationCode       = Guid.NewGuid()
                };
                var          role         = RoleService.GetRoleByName("User");
                CustomerRole customerrole = new CustomerRole();
                if (role != null)
                {
                    customerrole.RoleId     = role.RoleId;
                    customerrole.CustomerId = customer.CustomerId;
                }
                customer.CustomerRoles.Add(customerrole);

                CustomerService.InsertCustomer(customer);

                //Verification Email
                VerificationEmail(model.FirstName, model.LastName, model.Email, customer.ActivationCode.ToString());

                messageRegistration = "Congratulations! You have successfully created your account.Please check your email for instruction to activate your account.";
                statusRegistration  = true;
                Transaction transaction = new Transaction();
                transaction.CustomerId      = customer.CustomerId;
                transaction.Amount          = 100;
                transaction.TransactionDate = DateTime.Now;
                transaction.Status          = "completed";
                transaction.TransactionType = "credit";
                transaction.CreatedDate     = DateTime.Now;
                transaction.UpdatedDate     = DateTime.Now;
                transaction.PaymentMethod   = "offline";
                TransactionService.InsertTransaction(transaction);
                ViewBag.Message = messageRegistration;
                ViewBag.Status  = statusRegistration;
            }
            return(View(model));
        }
Exemplo n.º 6
0
 public static CustomerRole ToEntity(this CustomerRoleModel model, CustomerRole destination)
 {
     return(model.MapTo(destination));
 }
Exemplo n.º 7
0
 public Customer(CustomerRole role)
 {
     Role = role;
 }
Exemplo n.º 8
0
        protected virtual int ProcessCustomerRoles(
            ImportExecuteContext context,
            IEnumerable <ImportRow <Customer> > batch,
            Dictionary <string, CustomerRole> allCustomerRoles)
        {
            CustomerRole role = null;
            var          hasCustomerRoleSystemNames = context.DataSegmenter.HasColumn("CustomerRoleSystemNames");

            // Deprecated fields. Still processed for backward compatibility. Use "CustomerRoleSystemNames" instead.
            var hasIsGuest          = context.DataSegmenter.HasColumn("IsGuest");
            var hasIsRegistered     = context.DataSegmenter.HasColumn("IsRegistered");
            var hasIsForumModerator = context.DataSegmenter.HasColumn("IsForumModerator");

            foreach (var row in batch)
            {
                var customer = row.Entity;

                // Deprecated customer role fields.
                if (hasIsGuest)
                {
                    UpsertRole(customer, row.GetDataValue <bool>("IsGuest"), allCustomerRoles, SystemCustomerRoleNames.Guests);
                }
                if (hasIsRegistered)
                {
                    UpsertRole(customer, row.GetDataValue <bool>("IsRegistered"), allCustomerRoles, SystemCustomerRoleNames.Registered);
                }
                if (hasIsForumModerator)
                {
                    UpsertRole(customer, row.GetDataValue <bool>("IsForumModerator"), allCustomerRoles, SystemCustomerRoleNames.ForumModerators);
                }

                // New customer role field.
                if (hasCustomerRoleSystemNames)
                {
                    var importRoleSystemNames = row.GetDataValue <List <string> >("CustomerRoleSystemNames");
                    var assignedRoles         = customer.CustomerRoles.ToDictionarySafe(x => x.SystemName, StringComparer.OrdinalIgnoreCase);

                    // Roles to remove.
                    foreach (var customerRole in assignedRoles)
                    {
                        var systemName = customerRole.Key;
                        if (!systemName.IsCaseInsensitiveEqual(SystemCustomerRoleNames.Administrators) &&
                            !systemName.IsCaseInsensitiveEqual(SystemCustomerRoleNames.SuperAdministrators) &&
                            !importRoleSystemNames.Contains(systemName))
                        {
                            customer.CustomerRoles.Remove(customerRole.Value);
                        }
                    }

                    // Roles to add.
                    foreach (var systemName in importRoleSystemNames)
                    {
                        if (systemName.IsCaseInsensitiveEqual(SystemCustomerRoleNames.Administrators) ||
                            systemName.IsCaseInsensitiveEqual(SystemCustomerRoleNames.SuperAdministrators))
                        {
                            context.Result.AddInfo("Security. Ignored administrator role.", row.GetRowInfo(), "CustomerRoleSystemNames");
                        }
                        else if (!assignedRoles.ContainsKey(systemName) && allCustomerRoles.TryGetValue(systemName, out role))
                        {
                            // Never insert roles!
                            context.Services.DbContext.SetToUnchanged(role);

                            customer.CustomerRoles.Add(role);
                        }
                    }
                }
            }

            return(context.Services.DbContext.SaveChanges());
        }
Exemplo n.º 9
0
        protected virtual void InstallCustomersAndUsers(string defaultUserEmail, string defaultUserPassword)
        {
            var crAdministrators = new CustomerRole
            {
                Name         = "Administrators",
                Active       = true,
                IsSystemRole = true,
                SystemName   = SystemCustomerRoleNames.Administrators,
            };
            var crForumModerators = new CustomerRole
            {
                Name         = "Forum Moderators",
                Active       = true,
                IsSystemRole = true,
                SystemName   = SystemCustomerRoleNames.ForumModerators,
            };
            var crRegistered = new CustomerRole
            {
                Name         = "Registered",
                Active       = true,
                IsSystemRole = true,
                SystemName   = SystemCustomerRoleNames.Registered,
            };
            var crGuests = new CustomerRole
            {
                Name         = "Guests",
                Active       = true,
                IsSystemRole = true,
                SystemName   = SystemCustomerRoleNames.Guests,
            };
            var crVendors = new CustomerRole
            {
                Name         = "Vendors",
                Active       = true,
                IsSystemRole = true,
                SystemName   = SystemCustomerRoleNames.Vendors,
            };
            var customerRoles = new List <CustomerRole>
            {
                crAdministrators,
                crForumModerators,
                crRegistered,
                crGuests,
                crVendors
            };

            _customerRoleRepository.Insert(customerRoles);

            //admin user
            var adminUser = new Customer
            {
                CustomerGuid        = Guid.NewGuid(),
                Email               = defaultUserEmail,
                Username            = defaultUserEmail,
                Active              = true,
                CreatedOnUtc        = DateTime.UtcNow,
                LastActivityDateUtc = DateTime.UtcNow
            };

            adminUser.CustomerCustomerRoleMapping.Add(new CustomerCustomerRoleMapping(adminUser.Id, crAdministrators.Id));
            adminUser.CustomerCustomerRoleMapping.Add(new CustomerCustomerRoleMapping(adminUser.Id, crForumModerators.Id));
            adminUser.CustomerCustomerRoleMapping.Add(new CustomerCustomerRoleMapping(adminUser.Id, crRegistered.Id));
            _customerRepository.Insert(adminUser);
        }
        public ActionResult TaoTaiKhoan(XuLyHopDongModel.KhachHangModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.CVLeTanHopDong))
            {
                return(AccessDeniedView());
            }
            var khachhangrole = new CustomerRole();
            var customer      = new Customer
            {
                CustomerGuid        = Guid.NewGuid(),
                Email               = model.Email,
                Active              = true,
                CreatedOnUtc        = DateTime.UtcNow,
                LastActivityDateUtc = DateTime.UtcNow,
            };
            var item = _customerService.GetCustomerByEmail(model.Email);

            if (item == null)
            {
                _customerService.InsertCustomer(customer);


                //firstname,lastname
                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.FirstName, model.FirstName);
                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastName, model.LastName);
                //mã hóa password
                if (!String.IsNullOrWhiteSpace(model.Password))
                {
                    var changePassRequest = new ChangePasswordRequest(model.Email, false, _customerSettings.DefaultPasswordFormat, model.Password);
                    var changePassResult  = _customerRegistrationService.ChangePassword(changePassRequest);
                    if (!changePassResult.Success)
                    {
                        foreach (var changePassError in changePassResult.Errors)
                        {
                            ErrorNotification(changePassError);
                        }
                    }
                }
                //update khách hàng cho hop dong
                var _hopdong = _chonveService.GetHopDongById(model.HopDongId);

                if (_hopdong != null)
                {
                    if (_hopdong.KhachHangID > 0 && _hopdong.KhachHangID != customer.Id)
                    {
                        var khachhang   = _customerService.GetCustomerById(_hopdong.KhachHangID);
                        var newitemrole = new CustomerRole();
                        foreach (var _item in khachhang.CustomerRoles)
                        {
                            if (_item.SystemName == SystemCustomerRoleNames.HTNhaXeManager)
                            {
                                newitemrole = _item;
                            }
                        }
                        khachhang.CustomerRoles.Remove(newitemrole);
                        _customerService.UpdateCustomer(khachhang);
                    }
                    _hopdong.KhachHangID = customer.Id;
                    _chonveService.UpdateHopDong(_hopdong);
                }
                //customerrole

                var allCustomerRoles = _customerService.GetAllCustomerRoles(true);
                var newCustomerRoles = new List <CustomerRole>();
                foreach (var customerRole in allCustomerRoles)
                {
                    if (customerRole.SystemName == SystemCustomerRoleNames.Registered)
                    {
                        newCustomerRoles.Add(customerRole);
                    }
                    if (customerRole.SystemName == SystemCustomerRoleNames.HTNhaXeManager)
                    {
                        newCustomerRoles.Add(customerRole);
                    }
                }
                foreach (var _customerRole in newCustomerRoles)
                {
                    customer.CustomerRoles.Add(_customerRole);
                }
                _customerService.UpdateCustomer(customer);
                //tạo văn phong với địa chỉ của nhà xe là trụ sở chính
                var truso = new VanPhong();
                truso.NhaXeId = _hopdong.NhaXeID;
                var nhaxe = _nhaxeService.GetNhaXeById(_hopdong.NhaXeID);
                truso.TenVanPhong    = nhaxe.TenNhaXe;
                truso.KieuVanPhongID = (int)ENKieuVanPhong.TruSo;
                truso.DiaChiID       = nhaxe.DiaChiID;
                _nhaxeService.InsertVanPhong(truso);
                // tao nhan vien thuoc van phong
                var nhanvien = new NhanVien();
                nhanvien.HoVaTen           = nhaxe.TenNhaXe;
                nhanvien.Email             = nhaxe.Email;
                nhanvien.CustomerID        = customer.Id;
                nhanvien.KieuNhanVienID    = (int)ENKieuNhanVien.QuanLy;
                nhanvien.GioiTinhID        = (int)ENGioiTinh.Nam;
                nhanvien.TrangThaiID       = (int)ENTrangThaiNhanVien.DangLamViec;
                nhanvien.NgayBatDauLamViec = DateTime.Now;

                nhanvien.VanPhongID = truso.Id;
                nhanvien.NhaXeID    = _hopdong.NhaXeID;
                nhanvien.DiaChiID   = nhaxe.DiaChiID;
                _nhanvienService.Insert(nhanvien);
                return(RedirectToAction("ChiTietHopDong", new { id = model.HopDongId }));
            }
            return(View());
        }
Exemplo n.º 11
0
        public void BindGrid(int paramPageIndex, int paramPageSize)
        {
            string ContractNumber  = this.txtContractNumber.Text.Trim();
            string ClientCompany   = this.txtClientCompany.Text.Trim();
            string BelongingPeople = this.txtBelongingPeople.Text.Trim();
            string FinancialStatus = this.ddlFinancialStatus.SelectedValue;

            var list = base.XMBusinessDataService.GetXMBusinessDataListByData(ContractNumber, ClientCompany, BelongingPeople, 297);

            if (FinancialStatus != "-1")
            {
                if (FinancialStatus == "1")
                {
                    list = list.Where(p => p.FinancialStatus == true).ToList <XMBusinessData>();
                }
                else
                {
                    list = list.Where(p => p.FinancialStatus == false).ToList <XMBusinessData>();
                }
            }

            List <XMBusinessData> List           = new List <XMBusinessData>();
            List <int>            CustomerIDList = new List <int>();
            int CustomerID = HozestERPContext.Current.User.CustomerID;
            var RoleList   = base.CustomerService.GetRolesByCustomerId(CustomerID);

            int[] IntList = { 10000072, 10000073, 10000074, 10000063, 10000062 };//B2B业务员,B2B客服,B2B经理,出纳,财务
            List <CustomerRole> RoleIDList = new List <CustomerRole>();

            foreach (int one in IntList)
            {
                if (RoleList != null && RoleList.Count > 0)
                {
                    foreach (CustomerRole two in RoleList)
                    {
                        if (one == two.CustomerRoleID)
                        {
                            CustomerRole role = new CustomerRole();
                            role.CustomerRoleID = one;
                            RoleIDList.Add(role);
                        }
                    }
                }
            }

            if (RoleIDList != null && RoleIDList.Count > 0)
            {
                List <string> DepId = new List <string>();
                foreach (CustomerRole one in RoleIDList)
                {
                    List <string> RoleId = new List <string>();
                    RoleId = CustomerRoleIdList(one.CustomerRoleID, RoleId);
                    foreach (string two in RoleId)
                    {
                        var DepList = base.EnterpriseService.GetDepartmentListByRoleID(int.Parse(two));
                        if (DepList != null && DepList.Count > 0)
                        {
                            foreach (Department three in DepList)
                            {
                                List <string> dep = new List <string>();
                                dep = DepartmentIdList(three.DepartmentID, dep);
                                if (dep != null && dep.Count > 0)
                                {
                                    foreach (string four in dep)
                                    {
                                        DepId.Add(four);
                                    }
                                }
                            }
                        }

                        var customerlist = base.CustomerService.GetCustomerInfosByRoleID(int.Parse(two));
                        if (customerlist != null && customerlist.Count > 0)
                        {
                            foreach (CustomerInfo customerId in customerlist)
                            {
                                CustomerIDList.Add(customerId.CustomerID);
                            }
                        }
                    }
                }
                DepId = DepId.Distinct().ToList();
                foreach (string one in DepId)
                {
                    var CustomerIDAll = base.CustomerInfoService.GetCustomerInfoListByDepId(int.Parse(one));
                    if (CustomerIDAll != null && CustomerIDAll.Count > 0)
                    {
                        foreach (CustomerInfo two in CustomerIDAll)
                        {
                            CustomerIDList.Add(two.CustomerID);
                        }
                    }
                }
            }

            CustomerIDList.Add(CustomerID);//添加自己ID
            CustomerIDList = CustomerIDList.Distinct().ToList();

            if (list != null && list.Count > 0)
            {
                foreach (XMBusinessData info in list)
                {
                    bool state      = false;
                    var  DetailList = base.XMBusinessDataDetailService.GetXMBusinessDataDetailListByBusinessDataID(info.ID);
                    if (DetailList != null && DetailList.Count > 0)
                    {
                        foreach (XMBusinessDataDetail detail in DetailList)
                        {
                            foreach (int CustomerInfoID in CustomerIDList)
                            {
                                var CustomerInfo = base.CustomerInfoService.GetCustomerInfoByID(CustomerInfoID);
                                if (detail.BelongingName.Contains(CustomerInfo.FullName.Trim()))
                                {
                                    List.Add(info);
                                    state = true;
                                    break;
                                }
                            }
                            if (state)
                            {
                                break;
                            }
                        }
                    }
                }
            }

            var pageList = new PagedList <XMBusinessData>(List, paramPageIndex, paramPageSize, this.Master.GridViewSortField, this.Master.GridViewSortDir.ToString());

            this.Master.BindData(this.grdvClients, pageList);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Prepare customer role model
        /// </summary>
        /// <param name="model">Customer role model</param>
        /// <param name="customerRole">Customer role</param>
        /// <param name="excludeProperties">Whether to exclude populating of some properties of model</param>
        /// <returns>Customer role model</returns>
        public virtual async Task <CustomerRoleModel> PrepareCustomerRoleModelAsync(CustomerRoleModel model, CustomerRole customerRole, bool excludeProperties = false)
        {
            if (customerRole != null)
            {
                //fill in model values from the entity
                model ??= customerRole.ToModel <CustomerRoleModel>();
                model.PurchasedWithProductName = (await _productService.GetProductByIdAsync(customerRole.PurchasedWithProductId))?.Name;
            }

            //set default values for the new model
            if (customerRole == null)
            {
                model.Active = true;
            }

            //prepare available tax display types
            await _baseAdminModelFactory.PrepareTaxDisplayTypesAsync(model.TaxDisplayTypeValues, false);

            return(model);
        }
Exemplo n.º 13
0
        protected virtual void InstallCustomersAndUsers(string defaultUserEmail, string defaultUserPassword)
        {
            var crAdministrators = new CustomerRole
            {
                Name         = "Administrators",
                Active       = true,
                IsSystemRole = true,
                SystemName   = SystemCustomerRoleNames.Administrators,
            };
            var crRegistered = new CustomerRole
            {
                Name         = "Registered",
                Active       = true,
                IsSystemRole = true,
                SystemName   = SystemCustomerRoleNames.Registered,
            };
            var crGuests = new CustomerRole
            {
                Name         = "Guests",
                Active       = true,
                IsSystemRole = true,
                SystemName   = SystemCustomerRoleNames.Guests,
            };
            var customerRoles = new List <CustomerRole>
            {
                crAdministrators,
                crRegistered,
                crGuests
            };

            _customerRoleRepository.Insert(customerRoles);

            var adminUser = new Customer
            {
                Email               = defaultUserEmail,
                Username            = "******",
                Active              = true,
                LastActivityDateUtc = DateTime.UtcNow
            };

            adminUser.CustomerRoles.Add(crRegistered);
            adminUser.CustomerRoles.Add(crAdministrators);

            _customerRepository.Insert(adminUser);

            var customerRegistrationService = EngineContext.Current.Resolve <ICustomerRegistrationService>();

            customerRegistrationService.ChangePassword(new ChangePasswordRequest(defaultUserEmail, false,
                                                                                 PasswordFormat.Hashed, defaultUserPassword));

            //搜索引擎(内置)用户
            var searchEngineUser = new Customer
            {
                Username            = "******",
                Email               = "builtin@search_engine_record.com",
                Guid                = Guid.NewGuid(),
                AdminComment        = "内置用户,用于处理搜索引擎的请求.",
                Active              = true,
                IsSystemAccount     = true,
                SystemName          = SystemCustomerNames.SearchEngine,
                LastActivityDateUtc = DateTime.UtcNow
            };

            searchEngineUser.CustomerRoles.Add(crGuests);
            _customerRepository.Insert(searchEngineUser);

            //后台任务(内置)用户
            var backgroundTaskUser = new Customer
            {
                Username            = "******",
                Email               = "*****@*****.**",
                AdminComment        = "内置用户,用于处理后台任务.",
                Active              = true,
                IsSystemAccount     = true,
                SystemName          = SystemCustomerNames.BackgroundTask,
                LastActivityDateUtc = DateTime.UtcNow
            };

            backgroundTaskUser.CustomerRoles.Add(crGuests);
            _customerRepository.Insert(backgroundTaskUser);
        }
        public void Can_get_final_product_price_with_tier_prices_by_customerRole()
        {
            var product = new Product
            {
                Id    = 1,
                Name  = "Product name 1",
                Price = 12.34M,
                CustomerEntersPrice = false,
                Published           = true,
            };

            var customerRole1 = new CustomerRole
            {
                Id     = 1,
                Name   = "Some role 1",
                Active = true,
            };
            var customerRole2 = new CustomerRole
            {
                Id     = 2,
                Name   = "Some role 2",
                Active = true,
            };

            product.TierPrices.Add(new TierPrice
            {
                Price             = 10,
                Quantity          = 2,
                Product           = product,
                CustomerRole      = customerRole1,
                CalculationMethod = TierPriceCalculationMethod.Fixed
            });
            product.TierPrices.Add(new TierPrice
            {
                Price             = 9,
                Quantity          = 2,
                Product           = product,
                CustomerRole      = customerRole2,
                CalculationMethod = TierPriceCalculationMethod.Fixed
            });
            product.TierPrices.Add(new TierPrice
            {
                Price             = 8,
                Quantity          = 5,
                Product           = product,
                CustomerRole      = customerRole1,
                CalculationMethod = TierPriceCalculationMethod.Fixed
            });
            product.TierPrices.Add(new TierPrice
            {
                Price             = 5,
                Quantity          = 10,
                Product           = product,
                CustomerRole      = customerRole2,
                CalculationMethod = TierPriceCalculationMethod.Fixed
            });
            product.HasTierPrices = true;


            var customer = new Customer();

            customer.CustomerRoleMappings.Add(new CustomerRoleMapping
            {
                CustomerId     = customer.Id,
                CustomerRoleId = customerRole1.Id,
                CustomerRole   = customerRole1
            });

            _priceCalcService.GetFinalPrice(product, customer, 0, false, 1, isTierPrice: true).ShouldEqual(12.34M);
            _priceCalcService.GetFinalPrice(product, customer, 0, false, 2, isTierPrice: true).ShouldEqual(10);
            _priceCalcService.GetFinalPrice(product, customer, 0, false, 3, isTierPrice: true).ShouldEqual(10);
            _priceCalcService.GetFinalPrice(product, customer, 0, false, 5, isTierPrice: true).ShouldEqual(8);
            _priceCalcService.GetFinalPrice(product, customer, 0, false, 10, isTierPrice: true).ShouldEqual(8);
        }
Exemplo n.º 15
0
        public virtual void InsertCustomerRole(CustomerRole role)
        {
            Guard.NotNull(role, nameof(role));

            _customerRoleRepository.Insert(role);
        }
Exemplo n.º 16
0
        protected CustomerRoleModel PrepareCustomerRoleModel(CustomerRole customerRole)
        {
            var model = customerRole.ToModel();

            return(model);
        }
Exemplo n.º 17
0
 public static CustomerRoleModel ToModel(this CustomerRole entity)
 {
     return(entity.MapTo <CustomerRole, CustomerRoleModel>());
 }
Exemplo n.º 18
0
        /// <summary>
        /// Authorize permission
        /// </summary>
        /// <param name="permissionRecordSystemName">Permission record system name</param>
        /// <param name="customerRole">Customer role</param>
        /// <returns>true - authorized; otherwise, false</returns>
        protected virtual async Task <bool> Authorize(string permissionRecordSystemName, CustomerRole customerRole)
        {
            if (String.IsNullOrEmpty(permissionRecordSystemName))
            {
                return(false);
            }

            string key = string.Format(PERMISSIONS_ALLOWED_KEY, customerRole.Id, permissionRecordSystemName);

            return(await _cacheManager.GetAsync(key, async() =>
            {
                var permissionRecord = await _permissionRecordRepository.Table.Where(x => x.CustomerRoles.Contains(customerRole.Id) && x.SystemName == permissionRecordSystemName).ToListAsync();
                if (permissionRecord.Any())
                {
                    return true;
                }

                return false;
            }));
        }
Exemplo n.º 19
0
        /// <summary>
        /// Authorize permission
        /// </summary>
        /// <param name="permissionRecordSystemName">Permission record system name</param>
        /// <param name="customerRole">Customer role</param>
        /// <returns>true - authorized; otherwise, false</returns>
        protected virtual async Task <bool> Authorize(string permissionRecordSystemName, CustomerRole customerRole)
        {
            if (string.IsNullOrEmpty(permissionRecordSystemName))
            {
                return(false);
            }

            string key = string.Format(PERMISSIONS_ALLOWED_KEY, customerRole.Id, permissionRecordSystemName);

            return(await _cacheManager.GetAsync(key, async() =>
            {
                var permissionRecord = await _permissionRecordRepository.Table.FirstOrDefaultAsync(x => x.SystemName == permissionRecordSystemName);
                return permissionRecord?.CustomerRoles.Contains(customerRole.Id) ?? false;
            }));
        }
Exemplo n.º 20
0
        public virtual void UpdateCustomerRole(CustomerRole role)
        {
            Guard.NotNull(role, nameof(role));

            _customerRoleRepository.Update(role);
        }
Exemplo n.º 21
0
 public static CustomerRole ToEntity(this CustomerRoleModel model, CustomerRole entity)
 {
     MapperFactory.Map(model, entity);
     return(entity);
 }
Exemplo n.º 22
0
 public static CustomerRoleDto ToDto(this CustomerRole customerRole)
 {
     return(customerRole.MapTo <CustomerRole, CustomerRoleDto>());
 }
Exemplo n.º 23
0
        public virtual CustomerRoleModel PrepareCustomerRoleModel(CustomerRole customerRole)
        {
            var model = customerRole.ToModel();

            return(model);
        }
Exemplo n.º 24
0
        protected virtual int ProcessCustomerRoles(
            ImportExecuteContext context,
            IEnumerable <ImportRow <Customer> > batch)
        {
            var          num  = 0;
            CustomerRole role = null;
            Dictionary <string, CustomerRole> allCustomerRoles = null;
            var hasCustomerRoleSystemNames = context.DataSegmenter.HasColumn("CustomerRoleSystemNames");

            foreach (var row in batch)
            {
                var customer = row.Entity;

                // New customer role field.
                if (hasCustomerRoleSystemNames)
                {
                    var updateCustomer        = false;
                    var importRoleSystemNames = row.GetDataValue <List <string> >("CustomerRoleSystemNames");
                    var assignedRoles         = customer.CustomerRoles.ToDictionarySafe(x => x.SystemName, StringComparer.OrdinalIgnoreCase);

                    // Roles to remove.
                    foreach (var customerRole in assignedRoles)
                    {
                        var systemName = customerRole.Key;
                        if (!systemName.IsCaseInsensitiveEqual(SystemCustomerRoleNames.Administrators) &&
                            !systemName.IsCaseInsensitiveEqual(SystemCustomerRoleNames.SuperAdministrators) &&
                            !importRoleSystemNames.Contains(systemName))
                        {
                            customer.CustomerRoles.Remove(customerRole.Value);
                            updateCustomer = true;
                        }
                    }

                    // Roles to add.
                    foreach (var systemName in importRoleSystemNames)
                    {
                        if (systemName.IsCaseInsensitiveEqual(SystemCustomerRoleNames.Administrators) ||
                            systemName.IsCaseInsensitiveEqual(SystemCustomerRoleNames.SuperAdministrators))
                        {
                            context.Result.AddInfo("Security. Ignored administrator role.", row.GetRowInfo(), "CustomerRoleSystemNames");
                        }
                        else if (!assignedRoles.ContainsKey(systemName))
                        {
                            // Add role mapping, never insert roles.
                            // Be careful not to insert the roles several times!
                            if (allCustomerRoles == null)
                            {
                                allCustomerRoles = _customerRoleRepository.Table
                                                   .Where(x => !string.IsNullOrEmpty(x.SystemName))
                                                   .ToDictionarySafe(x => x.SystemName, StringComparer.OrdinalIgnoreCase);
                            }

                            if (allCustomerRoles?.TryGetValue(systemName, out role) ?? false)
                            {
                                customer.CustomerRoles.Add(role);
                                updateCustomer = true;
                            }
                        }
                    }

                    if (updateCustomer)
                    {
                        _customerRepository.Update(customer);
                        ++num;
                    }
                }
            }

            return(num);
        }
Exemplo n.º 25
0
        private async Task From440To450()
        {
            #region Install String resources
            await InstallStringResources("EN_440_450.nopres.xml");

            #endregion

            #region Update task
            var tasks = _serviceProvider.GetRequiredService <IRepository <ScheduleTask> >();
            foreach (var task in tasks.Table)
            {
                if (task.TimeInterval == 0)
                {
                    task.TimeInterval = 1440;
                    await tasks.UpdateAsync(task);
                }
                if (task.Type == "Grand.Services.Tasks.ClearLogScheduleTask")
                {
                    task.Type = "Grand.Services.Tasks.ClearLogScheduleTask, Grand.Services";
                    await tasks.UpdateAsync(task);
                }
            }
            #endregion

            #region Update shipments - storeId

            var shipments = _serviceProvider.GetRequiredService <IRepository <Shipment> >();
            var orders    = _serviceProvider.GetRequiredService <IRepository <Order> >();
            foreach (var shipment in shipments.Table)
            {
                var order = orders.Table.Where(x => x.Id == shipment.OrderId).FirstOrDefault();
                if (order != null)
                {
                    shipment.StoreId = order.StoreId;
                    await shipments.UpdateAsync(shipment);
                }
            }
            #endregion

            #region Update topics - rename fields

            var renameFields = Builders <object> .Update
                               .Rename("IncludeInFooterColumn1", "IncludeInFooterRow1")
                               .Rename("IncludeInFooterColumn2", "IncludeInFooterRow2")
                               .Rename("IncludeInFooterColumn3", "IncludeInFooterRow3");

            var dbContext = _serviceProvider.GetRequiredService <IMongoDatabase>();
            await dbContext.GetCollection <object>(typeof(Topic).Name).UpdateManyAsync(new BsonDocument(), renameFields);

            #endregion

            #region Update order - primary currency code

            var pc = await _serviceProvider.GetRequiredService <ICurrencyService>().GetPrimaryStoreCurrency();

            var updateOrder = Builders <Order> .Update
                              .Set(x => x.PrimaryCurrencyCode, pc.CurrencyCode);

            var orderRepository = _serviceProvider.GetRequiredService <IRepository <Order> >();

            await orderRepository.Collection.UpdateManyAsync(new BsonDocument(), updateOrder);

            #endregion

            #region Insert new system customer role - staff

            var crStaff = new CustomerRole {
                Name         = "Staff",
                Active       = true,
                IsSystemRole = true,
                SystemName   = SystemCustomerRoleNames.Staff,
            };
            await _serviceProvider.GetRequiredService <IRepository <CustomerRole> >().InsertAsync(crStaff);

            #endregion

            #region Permisions

            IPermissionProvider provider = new StandardPermissionProvider();
            await _mediator.Send(new InstallNewPermissionsCommand()
            {
                PermissionProvider = provider
            });

            #endregion
        }
Exemplo n.º 26
0
 public static CustomerRole ToEntity(this CustomerRoleModel model, CustomerRole destination)
 {
     return(Mapper.Map(model, destination));
 }
Exemplo n.º 27
0
        public void WriteCustomer(dynamic customer, string node)
        {
            if (customer == null)
            {
                return;
            }

            Customer entity = customer.Entity;

            if (node.HasValue())
            {
                _writer.WriteStartElement(node);
            }

            _writer.Write("Id", entity.Id.ToString());
            _writer.Write("CustomerGuid", entity.CustomerGuid.ToString());
            _writer.Write("Username", entity.Username);
            _writer.Write("Email", entity.Email);
            _writer.Write("Password", entity.Password);
            _writer.Write("PasswordFormatId", entity.PasswordFormatId.ToString());
            _writer.Write("PasswordSalt", entity.PasswordSalt);
            _writer.Write("AdminComment", entity.AdminComment);
            _writer.Write("IsTaxExempt", entity.IsTaxExempt.ToString());
            _writer.Write("AffiliateId", entity.AffiliateId.ToString());
            _writer.Write("Active", entity.Active.ToString());
            _writer.Write("Deleted", entity.Deleted.ToString());
            _writer.Write("IsSystemAccount", entity.IsSystemAccount.ToString());
            _writer.Write("SystemName", entity.SystemName);
            _writer.Write("LastIpAddress", entity.LastIpAddress);
            _writer.Write("CreatedOnUtc", entity.CreatedOnUtc.ToString(_culture));
            _writer.Write("LastLoginDateUtc", entity.LastLoginDateUtc.HasValue ? entity.LastLoginDateUtc.Value.ToString(_culture) : "");
            _writer.Write("LastActivityDateUtc", entity.LastActivityDateUtc.ToString(_culture));
            _writer.Write("RewardPointsBalance", ((int)customer._RewardPointsBalance).ToString());

            if (customer.CustomerRoles != null)
            {
                _writer.WriteStartElement("CustomerRoles");
                foreach (dynamic role in customer.CustomerRoles)
                {
                    CustomerRole entityRole = role.Entity;

                    _writer.WriteStartElement("CustomerRole");
                    _writer.Write("Id", entityRole.Id.ToString());
                    _writer.Write("Name", (string)role.Name);
                    _writer.Write("FreeShipping", entityRole.FreeShipping.ToString());
                    _writer.Write("TaxExempt", entityRole.TaxExempt.ToString());
                    _writer.Write("TaxDisplayType", entityRole.TaxDisplayType.HasValue ? entityRole.TaxDisplayType.Value.ToString() : "");
                    _writer.Write("Active", entityRole.Active.ToString());
                    _writer.Write("IsSystemRole", entityRole.IsSystemRole.ToString());
                    _writer.Write("SystemName", entityRole.SystemName);
                    _writer.WriteEndElement();                  // CustomerRole
                }
                _writer.WriteEndElement();                      // CustomerRoles
            }

            WriteRewardPointsHistory(customer.RewardPointsHistory, "RewardPointsHistories");
            WriteAddress(customer.BillingAddress, "BillingAddress");
            WriteAddress(customer.ShippingAddress, "ShippingAddress");

            if (customer.Addresses != null)
            {
                _writer.WriteStartElement("Addresses");
                foreach (dynamic address in customer.Addresses)
                {
                    WriteAddress(address, "Address");
                }
                _writer.WriteEndElement();                      // Addresses
            }

            WriteGenericAttributes(customer);

            if (node.HasValue())
            {
                _writer.WriteEndElement();
            }
        }
        public ActionResult Create(CustomerModel model)
        {
            if (Session["CustomerId"] == null)
            {
                return(RedirectToAction("Login", "Home"));
            }

            if (ModelState.IsValid)
            {
                var matchuser = db.Customers.Where(a => a.Username.Equals(model.Username)).FirstOrDefault();
                if (matchuser == null)
                {
                    Customer customer = new Customer();
                    customer.CustomerId           = model.CustomerId;
                    customer.FirstName            = model.FirstName;
                    customer.LastName             = model.LastName;
                    customer.Email                = model.Email;
                    customer.Contactno            = model.Contactno;
                    customer.Username             = model.Username;
                    customer.Password             = model.Password;
                    customer.CompanyName          = model.CompanyName;
                    customer.Date_of_Registration = DateTime.Now;
                    customer.IsActive             = true;
                    customer.createddate          = DateTime.Now;
                    customer.updateddate          = DateTime.Now;

                    ViewBag.CustomerId    = customer.CustomerId;
                    ViewBag.StatusMessage = "SuccessAdd";


                    var          role         = RoleService.GetRoleByName("User");
                    CustomerRole customerrole = new CustomerRole();
                    if (role != null)
                    {
                        customerrole.RoleId     = role.RoleId;
                        customerrole.CustomerId = customer.CustomerId;
                    }
                    customer.CustomerRoles.Add(customerrole);
                    ManageCustomerService.InsertCustomer(customer);


                    //Transaction
                    Transaction transaction = new Transaction();
                    transaction.CustomerId      = customer.CustomerId;
                    transaction.Amount          = 100;
                    transaction.TransactionDate = DateTime.Now;
                    transaction.Status          = "completed";
                    transaction.TransactionType = "credit";
                    transaction.CreatedDate     = DateTime.Now;
                    transaction.UpdatedDate     = DateTime.Now;
                    transaction.PaymentMethod   = "offline";
                    TransactionService.InsertTransaction(transaction);
                }
                else
                {
                    ViewBag.Message = "  This user is already exists";
                    return(View());
                }
            }
            return(View(model));
        }
Exemplo n.º 29
0
 //customer roles
 public static CustomerRoleModel ToModel(this CustomerRole entity)
 {
     return(Mapper.Map <CustomerRole, CustomerRoleModel>(entity));
 }
Exemplo n.º 30
0
        public IHttpActionResult ImportCustomers()
        {
            //  return BadRequest("导入关闭");
            var crAdministrators = new CustomerRole
            {
                Name         = SystemCustomerRoleNames.Administrators,
                Active       = true,
                IsSystemRole = true,
                SystemName   = "Administrators"
            };

            var crRegistered = new CustomerRole
            {
                Name         = SystemCustomerRoleNames.Registered,
                Active       = true,
                IsSystemRole = true,
                SystemName   = "Registered",
            };
            var crGuests = new CustomerRole
            {
                Name         = SystemCustomerRoleNames.Guests,
                Active       = true,
                IsSystemRole = true,
                SystemName   = "Guests",
            };

            _customerService.InsertCustomerRole(crAdministrators);
            _customerService.InsertCustomerRole(crRegistered);
            _customerService.InsertCustomerRole(crGuests);

            var adminUser = new Customer
            {
                CustomerGuid     = Guid.NewGuid(),
                Email            = "",
                UserName         = "******",
                Password         = "******",
                PasswordFormat   = PasswordFormat.Clear,
                PasswordSalt     = "",
                Active           = true,
                CreatedOn        = DateTime.Now,
                LastActivityDate = DateTime.Now,
            };

            adminUser.CustomerRoles.Add(crAdministrators);
            _customerService.InsertCustomer(adminUser);

            var user1 = new Customer
            {
                CustomerGuid     = Guid.NewGuid(),
                Email            = "",
                MobilePhone      = "18057081250",
                UserName         = "",
                Password         = "******",
                PasswordFormat   = PasswordFormat.Clear,
                PasswordSalt     = "",
                Active           = true,
                CreatedOn        = DateTime.Now,
                LastActivityDate = DateTime.Now,
            };

            user1.CustomerRoles.Add(crRegistered);
            _customerService.InsertCustomer(user1);

            var user2 = new Customer
            {
                CustomerGuid     = Guid.NewGuid(),
                Email            = "*****@*****.**",
                UserName         = "******",
                Password         = "******",
                PasswordFormat   = PasswordFormat.Clear,
                PasswordSalt     = "",
                Active           = true,
                CreatedOn        = DateTime.Now,
                LastActivityDate = DateTime.Now,
            };

            user2.CustomerRoles.Add(crRegistered);
            _customerService.InsertCustomer(user2);

            return(Ok("导入成功"));
        }