Пример #1
0
        // POST
        protected override DriverResult Editor(CustomerAddressPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var httpContext = Services.WorkContext.HttpContext;

            if (updater.TryUpdateModel(part, Prefix, null, null))
            {
                if (part.CountryId <= 0)
                {
                    updater.AddModelError("CountryId", T("Please select your country."));
                }
                else
                {
                    var states = _locationService.GetStates(part.CountryId);
                    if (states.Any())
                    {
                        if (part.StateId <= 0 || !states.Where(s => s.Id == part.StateId).Any())
                        {
                            updater.AddModelError("StateId", T("Please select your state."));
                        }
                    }
                }

                int customerId;
                if (Int32.TryParse(httpContext.Request.Form[Prefix + ".CustomerId"], out customerId) && Services.Authorizer.Authorize(Permissions.CustomersPermissions.ManageCustomerAccounts))
                {
                    part.Customer = _customersService.GetCustomer(customerId);
                }
                else if (part.Customer == null)
                {
                    part.Customer = _customersService.GetCustomer();
                }
            }

            return(Editor(part, shapeHelper));
        }
        public async Task <IResult <Customer> > GetCustomer(Guid id)
        {
            var customer = await _service.GetCustomer(id);

            if (customer == null)
            {
                return(await Result <Customer> .FailAsync("customer not found"));
            }

            return(await Result <Customer> .SuccessAsync(customer));
        }
Пример #3
0
        public CustomerAddressPartHandler(
            ICustomersService customersService,
            ILocationsService locationService,
            IRepository <CustomerAddressPartRecord> repository
            )
        {
            _customersService = customersService;
            _locationService  = locationService;

            Filters.Add(StorageFilter.For(repository));

            OnActivated <CustomerAddressPart>((context, part) => {
                part._customer.Loader(customer => _customersService.GetCustomer(part.CustomerId));
                part._customer.Setter(customer => {
                    part.CustomerId = customer != null ? customer.Id : 0;
                    return(customer);
                });

                part._country.Loader(country => _locationService.GetCountry(part.CountryId));
                part._country.Setter(country => {
                    part.CountryId = country != null ? country.Id : 0;
                    return(country);
                });

                part._state.Loader(state => _locationService.GetState(part.StateId));
                part._state.Setter(state => {
                    part.StateId = state != null ? state.Id : 0;
                    return(state);
                });
            });
        }
Пример #4
0
        public CustomerAddressPartHandler(
            ICustomersService customersService,
            ILocationsService locationService,
            IRepository<CustomerAddressPartRecord> repository
            )
        {
            _customersService = customersService;
            _locationService = locationService;

            Filters.Add(StorageFilter.For(repository));

            OnActivated<CustomerAddressPart>((context, part) => {
                part._customer.Loader(customer => _customersService.GetCustomer(part.CustomerId));
                part._customer.Setter(customer => {
                    part.CustomerId = customer != null ? customer.Id : 0;
                    return customer;
                });

                part._country.Loader(country => _locationService.GetCountry(part.CountryId));
                part._country.Setter(country => {
                    part.CountryId = country != null ? country.Id : 0;
                    return country;
                });

                part._state.Loader(state => _locationService.GetState(part.StateId));
                part._state.Setter(state => {
                    part.StateId = state != null ? state.Id : 0;
                    return state;
                });
            });
        }
Пример #5
0
        public void BuildCart(IShoppingCartService ShoppingCartService, ShoppingCart Cart)
        {
            var customer = _customersService.GetCustomer();

            if (customer == null)
            {
                return;
            }

            // Get "Checkout" property to know the Checkout provider beeing used
            var checkout = ShoppingCartService.GetProperty <string>("Checkout");

            if (string.IsNullOrWhiteSpace(checkout) && customer.DefaultAddress != null)
            {
                // Override default location
                ShoppingCartService.SetProperty <int>("CountryId", customer.DefaultAddress.CountryId);
                ShoppingCartService.SetProperty <int>("StateId", customer.DefaultAddress.StateId);

                Cart.Properties["BillingCountry"]  = customer.DefaultAddress.Country;
                Cart.Properties["BillingState"]    = customer.DefaultAddress.State;
                Cart.Properties["ShippingCountry"] = customer.DefaultAddress.Country;
                Cart.Properties["ShippingState"]   = customer.DefaultAddress.State;
            }
            else if (checkout == "Checkout")
            {
                var billingAddress  = customer.Addresses.Where(a => a.Id == ShoppingCartService.GetProperty <int>("BillingAddressId")).FirstOrDefault() ?? customer.DefaultAddress ?? customer.Addresses.FirstOrDefault();
                var shippingAddress = customer.Addresses.Where(a => a.Id == ShoppingCartService.GetProperty <int>("ShippingAddressId")).FirstOrDefault() ?? customer.DefaultAddress ?? customer.Addresses.FirstOrDefault();

                if (billingAddress != null)
                {
                    Cart.Properties["BillingAddress"] = billingAddress;
                    Cart.Properties["BillingCountry"] = billingAddress.Country;
                    Cart.Properties["BillingState"]   = billingAddress.State;
                }

                if (shippingAddress != null)
                {
                    Cart.Properties["ShippingAddress"] = shippingAddress;
                    Cart.Properties["ShippingCountry"] = shippingAddress.Country;
                    Cart.Properties["ShippingState"]   = shippingAddress.State;
                }
            }
        }
        /// <summary>
        /// Creates customer user using data of dto for Users API.
        /// </summary>
        /// <param name="customerId">The customer identifier.</param>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public async Task <CreateCustomerUserResultDto> CreateCustomerUser(
            int customerId,
            CreateCustomerUserRequestDto request
            )
        {
            string bearerToken = HttpContext.Current.Request.GetAuthorizationToken();

            var customerUser = Mapper.Map <CreateCustomerUserRequestDto, CustomerUser>(request);

            customerUser.CustomerId = customerId;

            var result = await customerUsersService.CreateCustomerUser(customerUser, bearerToken);

            if (result.IsValid && !request.DoNotSendInvitation)
            {
                var passwordExpirationDays = (await customersService.GetCustomer(customerId, bearerToken)).PasswordExpirationDays;

                await emailManager.SendActivationEmail(customerUser, passwordExpirationDays);
            }

            return(result);
        }
Пример #7
0
        public ActionResult Index()
        {
            if (Services.WorkContext.CurrentUser == null)
            {
                return(RedirectToAction("LogOn", "Account", new { area = "Orchard.Users", ReturnUrl = Url.Action("Index", "Checkout", new { area = "OShop" }) }));
            }

            var customer = _customersService.GetCustomer();

            if (customer == null)
            {
                return(RedirectToAction("Create", "Customer", new { area = "OShop", ReturnUrl = Url.Action("Index", "Checkout", new { area = "OShop" }) }));
            }

            if (!_shoppingCartService.ListItems().Any())
            {
                // Cart is empty => Return to Shopping cart
                return(RedirectToAction("Index", "ShoppingCart", new { area = "OShop" }));
            }

            // Set flag for CustomerResolver
            _shoppingCartService.SetProperty <String>("Checkout", "Checkout");

            ShoppingCart cart = _shoppingCartService.BuildCart();

            var checkoutShape = _shapeFactory.Checkout()
                                .Cart(cart)
                                .Addresses(customer.Addresses);

            if (_shippingService != null && cart.IsShippingRequired())
            {
                // Shipping option selection
                checkoutShape.ShippingOptions = _shapeFactory.ShoppingCart_ShippingOptions()
                                                .Cart(cart)
                                                .ContentItems(_shapeFactory.List()
                                                              .AddRange(_shippingService.GetSuitableProviderOptions(
                                                                            cart.Properties["ShippingZone"] as ShippingZoneRecord,
                                                                            cart.Properties["ShippingInfos"] as IList <Tuple <int, IShippingInfo> > ?? new List <Tuple <int, IShippingInfo> >(),
                                                                            cart.ItemsTotal()
                                                                            ).OrderBy(p => p.Option.Price)
                                                                        .Select(sp => _shapeFactory.ShoppingCart_ShippingOption()
                                                                                .Cart(cart)
                                                                                .ProviderOption(sp)
                                                                                )
                                                                        )
                                                              );
            }

            return(new ShapeResult(this, checkoutShape));
        }
Пример #8
0
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            Customer = await _customersService.GetCustomer(id);

            if (Customer == null)
            {
                return(NotFound());
            }
            return(Page());
        }
        public ActionResult Get(string id)
        {
            var serviceResult = _service.GetCustomer(id);

            if (serviceResult.Status == eOperationStatus.Success)
            {
                return(Ok(serviceResult));
            }

            if (serviceResult.Status == eOperationStatus.NotFound)
            {
                return(NotFound());
            }

            return(BadRequest(serviceResult));
        }
Пример #10
0
        public CustomerOrderPartHandler(
            ICustomersService customersService,
            IRepository <CustomerOrderPartRecord> repository
            )
        {
            _customersService = customersService;

            Filters.Add(StorageFilter.For(repository));

            OnActivated <CustomerOrderPart>((context, part) => {
                part._customer.Loader(customer => _customersService.GetCustomer(part.CustomerId));
                part._customer.Setter(customer => {
                    part.CustomerId = customer.Id;
                    return(customer);
                });
            });
        }
Пример #11
0
        public CustomerOrderPartHandler(
            ICustomersService customersService,
            IRepository<CustomerOrderPartRecord> repository
            )
        {
            _customersService = customersService;

            Filters.Add(StorageFilter.For(repository));

            OnActivated<CustomerOrderPart>((context, part) => {
                part._customer.Loader(customer => _customersService.GetCustomer(part.CustomerId));
                part._customer.Setter(customer => {
                    part.CustomerId = customer.Id;
                    return customer;
                });
            });
        }
Пример #12
0
        public async Task <IActionResult> Get(int id)
        {
            try
            {
                var customer = await _customersService.GetCustomer(id);

                if (customer == null)
                {
                    return(BadRequest("Customer not found!"));
                }
                return(Ok(customer));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
        public TimeSlotAvailability GetTimeSlotInfoWithServProvIdParams([FromBody] TimeSlotParams time_slot_param)
        {
            Authentication_class var_auth = new Authentication_class();
            AuthenticationHeader ah       = var_auth.getAuthHeader(time_slot_param.username_ad, time_slot_param.password_ad);

            AsmRepository.SetServiceLocationUrl(var_auth.var_service_location_url);

            IWorkforceService woService       = AsmRepository.AllServices.GetWorkforceService(ah);
            ICustomersService customerService = AsmRepository.GetServiceProxyCachedOrDefault <ICustomersService>(ah);

            DateTime dt = DateTime.ParseExact(time_slot_param.Date, "yyyy-MM-dd", CultureInfo.InvariantCulture);

            Customer cust = new Customer();

            cust = customerService.GetCustomer(time_slot_param.customer_id);

            var sp = woService.FindSPServiceWithGeoInfo(new FindSPServiceCriteria()
            {
                AddressId         = time_slot_param.serv_addr_id,
                ServiceTypeId     = time_slot_param.serv_type_id,
                ServiceProviderId = time_slot_param.serv_prov_id,
                Active            = true,
                PageSize          = 100
            },
                                                        1);

            TimeSlotAvailability var_timeslotAvailability = new TimeSlotAvailability();
            var var_timeslotAvailabilityItem = new List <TimeSlotAvailabilityItem>();

            foreach (SPServiceWithGeoInfo serviceprovider in sp.Items)
            {
                var sps = woService.GetServiceProviderServiceByServiceTypeGeoDefGroupIdandProviderId(serviceprovider.ServiceTypeId.Value, serviceprovider.GeoDefinitionGroupId.Value, serviceprovider.ServiceProviderId.Value);
                TimeSlotDescription[] timeslot = woService.GetTimeSlotsByServiceProviderServiceId(sps.Id.Value, dt);
                // print the timeslot for this service

                var_timeslotAvailabilityItem.Add(new TimeSlotAvailabilityItem()
                {
                    the_SPServiceWithGeoInfo = serviceprovider,
                    the_timeslot             = timeslot
                });
            }
            var_timeslotAvailability.TimeItemsData = var_timeslotAvailabilityItem;

            return(var_timeslotAvailability);
        }
Пример #14
0
        public ActionResult Index()
        {
            var customer = _customersService.GetCustomer();

            if (customer != null)
            {
                if (Services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.ViewContent, customer, T("You are not allowed to view this account.")))
                {
                    return(new ShapeResult(this, _contentManager.BuildDisplay(customer.ContentItem)));
                }
                else
                {
                    return(new HttpUnauthorizedResult());
                }
            }
            else
            {
                return(RedirectToAction("Create"));
            }
        }
Пример #15
0
        protected override DriverResult Display(CustomerPart part, string displayType, dynamic shapeHelper)
        {
            bool isAdmin = AdminFilter.IsApplied(Services.WorkContext.HttpContext.Request.RequestContext);

            if (isAdmin)
            {
                if (!Services.Authorizer.Authorize(Permissions.OrdersPermissions.ViewOrders))
                {
                    return(null);
                }
            }
            else
            {
                var customer = _customersService.GetCustomer();
                if (customer == null || customer.ContentItem.Id != part.ContentItem.Id || !Services.Authorizer.Authorize(Permissions.OrdersPermissions.ViewOwnOrders))
                {
                    return(null);
                }
            }

            if (part.ContentItem.Id > 0)
            {
                Int32 page = 0;
                if (Services.WorkContext.HttpContext.Request.QueryString.AllKeys.Contains(pageKey))
                {
                    Int32.TryParse(Services.WorkContext.HttpContext.Request.QueryString[pageKey], out page);
                }
                var pager = new Pager(Services.WorkContext.CurrentSite, page, null);

                var orders = _contentManager.Query <CustomerOrderPart, CustomerOrderPartRecord>()
                             .Where(o => o.CustomerId == part.ContentItem.Id)
                             .Join <CommonPartRecord>()
                             .OrderByDescending(c => c.CreatedUtc);

                var pagerShape = shapeHelper.Pager(pager)
                                 .PagerId(pageKey)
                                 .TotalItemCount(orders.Count());

                var list = shapeHelper.List();

                if (isAdmin)
                {
                    list.AddRange(orders.Slice(pager.GetStartIndex(), pager.PageSize)
                                  .Select(o => _contentManager.BuildDisplay(o, "SummaryAdmin")));
                    return(ContentShape("Parts_Customer_Orders_Admin", () => shapeHelper.Parts_Customer_Orders_Admin(
                                            ContentItems: list,
                                            Pager: pagerShape
                                            )));
                }
                else
                {
                    list.AddRange(orders.Slice(pager.GetStartIndex(), pager.PageSize)
                                  .Select(o => _contentManager.BuildDisplay(o, "Summary")));
                    return(ContentShape("Parts_Customer_Orders", () => shapeHelper.Parts_Customer_Orders(
                                            ContentItems: list,
                                            Pager: pagerShape
                                            )));
                }
            }
            else
            {
                return(null);
            }
        }
        /// <summary>
        /// Assign specified user to customer.
        /// </summary>
        /// <param name="customerUser">The customer user.</param>
        /// <param name="bearerToken">The bearer token.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">customerUser</exception>
        /// <exception cref="DataNotFoundException">Role with name {0} not exists.FormatWith(Roles.CustomerDefaultRole)</exception>
        public async Task <CreateCustomerUserResultDto> CreateCustomerUser(CustomerUser customerUser, string bearerToken)
        {
            var result = new CreateCustomerUserResultDto();

            if (customerUser == null)
            {
                throw new ArgumentNullException("customerUser");
            }

            if (string.IsNullOrEmpty(bearerToken))
            {
                throw new ArgumentNullException("bearerToken");
            }

            var roleEntity = await usersService.GetUserRole(Roles.CustomerUser);

            if (roleEntity == null)
            {
                throw new DataNotFoundException("Role with name {0} not exists".FormatWith(Roles.CustomerUser));
            }

            var existingCustomerUser = await GetCustomerUserByEmail(customerUser.Email, true);

            if (existingCustomerUser != null)
            {
                result.Error = CreateUpdateCustomerUserErrorState.EmailAlreadyExists;
            }

            var existingCustomer = await customersService.GetCustomer(customerUser.CustomerId, bearerToken);

            if (existingCustomer == null)
            {
                if (result.Error.HasValue)
                {
                    result.Error |= CreateUpdateCustomerUserErrorState.CustomerDoesNotExist;
                }
                else
                {
                    result.Error = CreateUpdateCustomerUserErrorState.CustomerDoesNotExist;
                }
            }
            else
            {
                var customerSitesIds = existingCustomer.Sites.Select(s => s.Id).ToList();

                if (customerUser.CustomerUserSites != null && !customerSitesIds.Contains(customerUser.CustomerUserSites.Select(s => s.SiteId).ToArray()))
                {
                    if (result.Error.HasValue)
                    {
                        result.Error |= CreateUpdateCustomerUserErrorState.SitesDoNotExistWithinCustomer;
                    }
                    else
                    {
                        result.Error = CreateUpdateCustomerUserErrorState.SitesDoNotExistWithinCustomer;
                    }
                }
            }

            var customerUserRoles = await GetCustomerUserRolesForCustomer(customerUser.CustomerId);

            if (customerUserRoles.All(cr => cr.Id != customerUser.CustomerUserRoleId))
            {
                if (result.Error.HasValue)
                {
                    result.Error |= CreateUpdateCustomerUserErrorState.CustomerUserRoleDoesNotExistWithinCustomer;
                }
                else
                {
                    result.Error = CreateUpdateCustomerUserErrorState.CustomerUserRoleDoesNotExistWithinCustomer;
                }
            }

            if (!string.IsNullOrEmpty(customerUser.CustomerUserId) ||
                !string.IsNullOrEmpty(customerUser.NationalProviderIdentificator))
            {
                var customerUsers = await GetCustomerUsers(customerUser.CustomerId);

                if (!string.IsNullOrEmpty(customerUser.CustomerUserId) &&
                    customerUsers.Any(cu => cu.CustomerUserId == customerUser.CustomerUserId))
                {
                    if (result.Error.HasValue)
                    {
                        result.Error |= CreateUpdateCustomerUserErrorState.CustomerUserIdAlreadyExists;
                    }
                    else
                    {
                        result.Error = CreateUpdateCustomerUserErrorState.CustomerUserIdAlreadyExists;
                    }
                }

                if (!string.IsNullOrEmpty(customerUser.NationalProviderIdentificator) &&
                    customerUsers.Any(
                        cu => cu.NationalProviderIdentificator == customerUser.NationalProviderIdentificator))
                {
                    if (result.Error.HasValue)
                    {
                        result.Error |= CreateUpdateCustomerUserErrorState.NPIAlreadyExists;
                    }
                    else
                    {
                        result.Error = CreateUpdateCustomerUserErrorState.NPIAlreadyExists;
                    }
                }
            }

            if (result.IsValid)
            {
                var principal = await tokenDataProvider.CreateUser(Mapper.Map <CreatePrincipalModel>(customerUser));

                customerUser.RoleId             = roleEntity.Id;
                customerUser.TokenServiceUserId = principal.Id.ToString();
                customerUsersRepository.Insert(customerUser);

                await unitOfWork.SaveAsync();

                var customerUserRole = await GetCustomerUserPermissions(customerUser.Id);

                await usersService.SetUserGroupsByPermissions(customerUserRole.Permissions, customerUser);

                var userSites = customerUser.CustomerUserSites != null?
                                customerUser.CustomerUserSites.Select(s => s.SiteId).ToList() :
                                    new List <Guid>();

                await SetSites(customerUser.Id, userSites);

                result.Id = customerUser.Id;
            }

            return(result);
        }
Пример #17
0
        public async Task <IActionResult> GetCustomer(int id)
        {
            var customer = await _customersService.GetCustomer(id);

            return(Json(customer));
        }