public async Task <IHttpActionResult> Search(CustomerOrderSearchCriteria criteria)
        {
            //Scope bound ACL filtration
            criteria = await FilterOrderSearchCriteria(HttpContext.Current.User.Identity.Name, criteria);

            var result = _searchService.SearchCustomerOrders(criteria);
            var retVal = new CustomerOrderSearchResult
            {
                CustomerOrders = result.Results.ToList(),
                TotalCount     = result.TotalCount
            };

            return(Ok(retVal));
        }
Exemplo n.º 2
0
        public IHttpActionResult Search(CustomerOrderSearchCriteria criteria)
        {
            //Scope bound ACL filtration
            //criteria = FilterOrderSearchCriteria(HttpContext.Current.User.Identity.Name, criteria);

            // var result = _searchService.SearchCustomerOrders(criteria);
            //var retVal = new webModel.CustomerOrderSearchResult
            //{
            //    CustomerOrders = result.Results.ToList(),
            //    TotalCount = result.TotalCount
            //};
            var retVal = _orderShipmenyService.SearchCustomerOrdersExt(criteria);

            return(Ok(retVal));
        }
        protected virtual IList <SortInfo> BuildSortExpression(CustomerOrderSearchCriteria criteria)
        {
            var sortInfos = criteria.SortInfos;

            if (sortInfos.IsNullOrEmpty())
            {
                sortInfos = new[]
                {
                    new SortInfo
                    {
                        SortColumn    = nameof(CustomerOrderEntity.CreatedDate),
                        SortDirection = SortDirection.Descending
                    }
                };
            }
            return(sortInfos);
        }
        private async Task <IReadOnlyCollection <IndexDocumentChange> > PerformGettingOrders(int skip, int take)
        {
            if (_startDate == null && _endDate == null)
            {
                var searchCriteria = new CustomerOrderSearchCriteria {
                    Skip = skip, Take = take
                };
                var searchResult = await _orderSearchService.SearchCustomerOrdersAsync(searchCriteria);

                return(searchResult.Results
                       .Select(x => new IndexDocumentChange
                {
                    ChangeDate = x.ModifiedDate ?? DateTime.MinValue,
                    DocumentId = x.Id,
                    ChangeType = IndexDocumentChangeType.Modified
                })
                       .ToArray());
            }
            else
            {
                var customerOrderType = GetCustomerOrderType();

                var searchResult = await _changeLogSearchService.SearchAsync(new ChangeLogSearchCriteria
                {
                    ObjectType = customerOrderType,
                    StartDate  = _startDate,
                    EndDate    = _endDate
                });

                return(searchResult.Results.Select(x => x.ObjectId)
                       .Distinct()
                       .Skip(skip)
                       .Take(take)
                       .Select(x => new IndexDocumentChange
                {
                    ChangeDate = DateTime.MinValue,
                    DocumentId = x,
                    ChangeType = IndexDocumentChangeType.Modified
                })
                       .ToArray());
            }
        }
        protected override void EnsureThatAllOperationsHaveNumber(CustomerOrder order)
        {
            var store = StoreService.GetById(order.StoreId);

            foreach (var operation in order.GetFlatObjectsListWithInterface <Domain.Commerce.Model.IOperation>())
            {
                if (operation.Number == null)
                {
                    if (operation.OperationType == "CustomerOrder")
                    {
                        CustomerOrderSearchCriteria criteria = new CustomerOrderSearchCriteria()
                        {
                            Sort = "createdDate:desc", Take = 1, ResponseGroup = "default"
                        };
                        var lastOrder = _orderSearchService.SearchCustomerOrders(criteria).Results.First();
                        if (lastOrder != null)
                        {
                            operation.Number = (Convert.ToInt32(lastOrder.Number) + 1).ToString();
                        }
                    }
                    else
                    {
                        var objectTypeName = operation.OperationType;
                        // take uppercase chars to form operation type, or just take 2 first chars. (CustomerOrder => CO, PaymentIn => PI, Shipment => SH)
                        var opType = string.Concat(objectTypeName.Select(c => char.IsUpper(c) ? c.ToString() : ""));
                        if (opType.Length < 2)
                        {
                            opType = objectTypeName.Substring(0, 2).ToUpper();
                        }
                        var numberTemplate = opType + "{0:yyMMdd}-{1:D5}";
                        if (store != null)
                        {
                            numberTemplate = store.Settings.GetSettingValue("Order." + objectTypeName + "NewNumberTemplate", numberTemplate);
                        }
                        operation.Number = UniqueNumberGenerator.GenerateNumber(numberTemplate);
                    }
                }
            }
        }
Exemplo n.º 6
0
        public void Map_TermFilter()
        {
            // Arrange
            var mapperCfg = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new OrderMappingProfile());
            });

            var mapper = mapperCfg.CreateMapper();
            var terms  = new List <IFilter>
            {
                new TermFilter {
                    FieldName = "CustomerId", Values = new[] { Guid.NewGuid().ToString() }
                },
                new TermFilter {
                    FieldName = "CustomerIds", Values = new[] { Guid.NewGuid().ToString() }
                },
                new TermFilter {
                    FieldName = "SubscriptionIds", Values = new string [] { }
                },
                new TermFilter {
                    FieldName = "SubscriptionIds", Values = null
                }
            };

            // Action
            var criteria = new CustomerOrderSearchCriteria();

            mapper.Map(terms, criteria);

            // Assert
            Assert.NotNull(criteria);
            Assert.NotNull(criteria.CustomerId);
            Assert.NotNull(criteria.CustomerIds);
            Assert.NotNull(criteria.CustomerId);
            Assert.Null(criteria.SubscriptionIds);
        }
Exemplo n.º 7
0
 protected virtual Expression <Func <CustomerOrderEntity, bool> > GetKeywordPredicate(CustomerOrderSearchCriteria criteria)
 {
     return(order => order.Number.Contains(criteria.Keyword) || order.CustomerName.Contains(criteria.Keyword));
 }
        private CustomerOrderSearchCriteria FilterOrderSearchCriteria(string userName, CustomerOrderSearchCriteria criteria)
        {
            if (!_securityService.UserHasAnyPermission(userName, null, OrderPredefinedPermissions.Read))
            {
                //Get defined user 'read' permission scopes
                var readPermissionScopes = _securityService.GetUserPermissions(userName)
                                           .Where(x => x.Id.StartsWith(OrderPredefinedPermissions.Read))
                                           .SelectMany(x => x.AssignedScopes)
                                           .ToList();

                //Check user has a scopes
                //Stores
                criteria.StoreIds = readPermissionScopes.OfType <OrderStoreScope>()
                                    .Select(x => x.Scope)
                                    .Where(x => !String.IsNullOrEmpty(x))
                                    .ToArray();

                var responsibleScope = readPermissionScopes.OfType <OrderResponsibleScope>().FirstOrDefault();
                //employee id
                if (responsibleScope != null)
                {
                    criteria.EmployeeId = userName;
                }
            }
            return(criteria);
        }
        public GenericSearchResult <CustomerOrder> SearchCustomerOrdersExt(CustomerOrderSearchCriteria criteria)
        {
            var retVal = new GenericSearchResult <CustomerOrder>();

            using (var repository = _orderRepositoryFactoryEx())
            {
                var query = repository.CustomerOrders;

                var queryShipment = repository.ShipmentExtended.Where(s => s.IsApproved == true);
                var orderIds      = queryShipment.Select(x => x.CustomerOrderId).ToArray();
                query = query.Where(x => orderIds.Contains(x.Id));

                //by default does not return prototypes
                if (!criteria.WithPrototypes)
                {
                    query = query.Where(x => !x.IsPrototype);
                }
                if (!criteria.Numbers.IsNullOrEmpty())
                {
                    query = query.Where(x => criteria.Numbers.Contains(x.Number));
                }
                else if (!string.IsNullOrEmpty(criteria.Keyword))
                {
                    query = query.Where(x => x.Number.Contains(criteria.Keyword) || x.CustomerName.Contains(criteria.Keyword));
                }
                if (criteria.OnlyRecurring)
                {
                    query = query.Where(x => x.SubscriptionId != null);
                }
                if (!criteria.SubscriptionIds.IsNullOrEmpty())
                {
                    query = query.Where(x => criteria.SubscriptionIds.Contains(x.SubscriptionId));
                }
                if (criteria.CustomerId != null)
                {
                    query = query.Where(x => x.CustomerId == criteria.CustomerId);
                }
                if (criteria.Statuses != null && criteria.Statuses.Any())
                {
                    query = query.Where(x => criteria.Statuses.Contains(x.Status));
                }
                if (criteria.StoreIds != null && criteria.StoreIds.Any())
                {
                    query = query.Where(x => criteria.StoreIds.Contains(x.StoreId));
                }
                if (criteria.EmployeeId != null)
                {
                    query = query.Where(x => x.EmployeeId == criteria.EmployeeId);
                }
                if (criteria.StartDate != null)
                {
                    query = query.Where(x => x.CreatedDate >= criteria.StartDate);
                }

                if (criteria.EndDate != null)
                {
                    query = query.Where(x => x.CreatedDate <= criteria.EndDate);
                }

                var sortInfos = criteria.SortInfos;
                if (sortInfos.IsNullOrEmpty())
                {
                    sortInfos = new[] { new SortInfo {
                                            SortColumn = ReflectionUtility.GetPropertyName <CustomerOrderEntity>(x => x.CreatedDate), SortDirection = SortDirection.Descending
                                        } };
                }
                query = query.OrderBySortInfos(sortInfos);

                retVal.TotalCount = query.Count();

                var orderCustomerIds = query.Select(x => x.Id).Skip(criteria.Skip).Take(criteria.Take).ToArray();
                var orders           = GetByIds(orderCustomerIds, criteria.ResponseGroup);
                retVal.Results = orders.AsQueryable <CustomerOrder>().OrderBySortInfos(sortInfos).ToList();

                return(retVal);
            }
        }
Exemplo n.º 10
0
        public virtual async Task <Subscription[]> GetByIdsAsync(string[] subscriptionIds, string responseGroup = null)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(GetByIdsAsync), string.Join("-", subscriptionIds), responseGroup);

            return(await PlatformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async cacheEntry =>
            {
                var retVal = new List <Subscription>();
                var subscriptionResponseGroup = EnumUtility.SafeParse(responseGroup, SubscriptionResponseGroup.Full);
                using (var repository = SubscriptionRepositoryFactory())
                {
                    repository.DisableChangesTracking();

                    var subscriptionEntities = await repository.GetSubscriptionsByIdsAsync(subscriptionIds, responseGroup);
                    foreach (var subscriptionEntity in subscriptionEntities)
                    {
                        var subscription = AbstractTypeFactory <Subscription> .TryCreateInstance();
                        if (subscription != null)
                        {
                            subscription = subscriptionEntity.ToModel(subscription) as Subscription;
                            if (subscriptionResponseGroup.HasFlag(SubscriptionResponseGroup.WithChangeLog))
                            {
                                //Load change log by separate request
                                ChangeLogService.LoadChangeLogs(subscription);
                            }
                            retVal.Add(subscription);
                        }
                    }
                }

                CustomerOrder[] orderPrototypes = null;
                CustomerOrder[] subscriptionOrders = null;

                if (subscriptionResponseGroup.HasFlag(SubscriptionResponseGroup.WithOrderPrototype))
                {
                    orderPrototypes = await CustomerOrderService.GetByIdsAsync(retVal.Select(x => x.CustomerOrderPrototypeId).ToArray());
                }
                if (subscriptionResponseGroup.HasFlag(SubscriptionResponseGroup.WithRelatedOrders))
                {
                    //Loads customer order prototypes and related orders for each subscription via order service
                    var criteria = new CustomerOrderSearchCriteria
                    {
                        SubscriptionIds = subscriptionIds
                    };
                    subscriptionOrders = (await CustomerOrderSearchService.SearchCustomerOrdersAsync(criteria)).Results.ToArray();
                }

                foreach (var subscription in retVal)
                {
                    if (!orderPrototypes.IsNullOrEmpty())
                    {
                        subscription.CustomerOrderPrototype = orderPrototypes.FirstOrDefault(x => x.Id == subscription.CustomerOrderPrototypeId);
                    }
                    if (!subscriptionOrders.IsNullOrEmpty())
                    {
                        subscription.CustomerOrders = subscriptionOrders.Where(x => x.SubscriptionId == subscription.Id).ToList();
                        subscription.CustomerOrdersIds = subscription.CustomerOrders.Select(x => x.Id).ToArray();
                    }

                    cacheEntry.AddExpirationToken(SubscriptionCacheRegion.CreateChangeToken(subscription));
                }

                return retVal.ToArray();
            }));
        }
Exemplo n.º 11
0
 public CustomerOrderSearchCriteriaBuilder()
 {
     _searchCriteria = AbstractTypeFactory <CustomerOrderSearchCriteria> .TryCreateInstance();
 }
Exemplo n.º 12
0
        public async Task <ActionResult <GenericSearchResult <CustomerOrder> > > Search([FromBody] CustomerOrderSearchCriteria criteria)
        {
            //Scope bound ACL filtration
            criteria = FilterOrderSearchCriteria(User.Identity.Name, criteria);

            var result = await _searchService.SearchCustomerOrdersAsync(criteria);

            return(Ok(result));
        }
        public virtual async Task <CustomerOrderSearchResult> SearchCustomerOrdersAsync(CustomerOrderSearchCriteria criteria)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(SearchCustomerOrdersAsync), criteria.GetCacheKey());

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(OrderSearchCacheRegion.CreateChangeToken());
                using (var repository = _repositoryFactory())
                {
                    repository.DisableChangesTracking();

                    var result = AbstractTypeFactory <CustomerOrderSearchResult> .TryCreateInstance();

                    var query = BuildQuery(repository, criteria);
                    var sortInfos = BuildSortExpression(criteria);

                    result.TotalCount = await query.CountAsync();
                    if (criteria.Take > 0)
                    {
                        var orderIds = await query.OrderBySortInfos(sortInfos).ThenBy(x => x.Id)
                                       .Select(x => x.Id)
                                       .Skip(criteria.Skip).Take(criteria.Take)
                                       .ToArrayAsync();
                        var unorderedResults = await _customerOrderService.GetByIdsAsync(orderIds, criteria.ResponseGroup);
                        result.Results = unorderedResults.OrderBy(x => Array.IndexOf(orderIds, x.Id)).ToList();
                    }
                    return result;
                }
            }));
        }
        public async Task <ActionResult <CustomerOrderSearchResult> > SearchCustomerOrder([FromBody] CustomerOrderSearchCriteria criteria)
        {
            var authorizationResult = await _authorizationService.AuthorizeAsync(User, criteria, new OrderAuthorizationRequirement(ModuleConstants.Security.Permissions.Read));

            if (!authorizationResult.Succeeded)
            {
                return(Unauthorized());
            }

            var result = await _searchService.SearchCustomerOrdersAsync(criteria);

            return(Ok(result));
        }
Exemplo n.º 15
0
        public virtual async Task <CustomerOrderSearchResult> SearchCustomerOrdersAsync(CustomerOrderSearchCriteria criteria)
        {
            var cacheKey = CacheKey.With(GetType(), "SearchCustomerOrdersAsync", criteria.GetCacheKey());

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(OrderSearchCacheRegion.CreateChangeToken());
                using (var repository = _repositoryFactory())
                {
                    repository.DisableChangesTracking();
                    var result = AbstractTypeFactory <CustomerOrderSearchResult> .TryCreateInstance();
                    var orderResponseGroup = EnumUtility.SafeParseFlags(criteria.ResponseGroup, CustomerOrderResponseGroup.Full);

                    var query = GetOrdersQuery(repository, criteria);

                    var sortInfos = criteria.SortInfos;
                    if (sortInfos.IsNullOrEmpty())
                    {
                        sortInfos = new[]
                        {
                            new SortInfo
                            {
                                SortColumn = ReflectionUtility.GetPropertyName <CustomerOrderEntity>(x => x.CreatedDate),
                                SortDirection = SortDirection.Descending
                            }
                        };
                    }
                    query = query.OrderBySortInfos(sortInfos);

                    result.TotalCount = await query.CountAsync();
                    var orderIds = await query.Select(x => x.Id).Skip(criteria.Skip).Take(criteria.Take).ToArrayAsync();

                    result.Results = (await _customerOrderService.GetByIdsAsync(orderIds, criteria.ResponseGroup)).AsQueryable()
                                     .OrderBySortInfos(sortInfos)
                                     .ToList();
                    return result;
                }
            }));
        }
        private async Task <CustomerOrderSearchCriteria> FilterOrderSearchCriteria(string userName, CustomerOrderSearchCriteria criteria)
        {
            var user = await _securityService.FindByNameAsync(userName, UserDetails.Reduced);

            criteria.ResponseGroup = OrderReadPricesPermission.ApplyResponseGroupFiltering(user, _securityService.GetUserPermissions(userName), criteria.ResponseGroup);

            if (!_securityService.UserHasAnyPermission(userName, null, OrderPredefinedPermissions.Read))
            {
                //Get defined user 'read' permission scopes
                var readPermissionScopes = _securityService.GetUserPermissions(userName)
                                           .Where(x => x.Id.StartsWith(OrderPredefinedPermissions.Read))
                                           .SelectMany(x => x.AssignedScopes)
                                           .ToList();

                //Check user has a scopes
                //Stores
                criteria.StoreIds = readPermissionScopes.OfType <OrderStoreScope>()
                                    .Select(x => x.Scope)
                                    .Where(x => !string.IsNullOrEmpty(x))
                                    .ToArray();

                //employee id
                var responsibleScope = readPermissionScopes.OfType <OrderResponsibleScope>().FirstOrDefault();
                if (responsibleScope != null)
                {
                    criteria.EmployeeId = userName;
                }
            }

            return(criteria);
        }
Exemplo n.º 17
0
        protected virtual IQueryable <CustomerOrderEntity> GetOrdersQuery(IOrderRepository repository, CustomerOrderSearchCriteria criteria)
        {
            var query = repository.CustomerOrders;

            // Don't return prototypes by default
            if (!criteria.WithPrototypes)
            {
                query = query.Where(x => !x.IsPrototype);
            }

            if (criteria.OnlyRecurring)
            {
                query = query.Where(x => x.SubscriptionId != null);
            }

            if (criteria.CustomerId != null)
            {
                query = query.Where(x => x.CustomerId == criteria.CustomerId);
            }

            if (criteria.EmployeeId != null)
            {
                query = query.Where(x => x.EmployeeId == criteria.EmployeeId);
            }

            if (criteria.StartDate != null)
            {
                query = query.Where(x => x.CreatedDate >= criteria.StartDate);
            }

            if (criteria.EndDate != null)
            {
                query = query.Where(x => x.CreatedDate <= criteria.EndDate);
            }

            if (!criteria.SubscriptionIds.IsNullOrEmpty())
            {
                query = query.Where(x => criteria.SubscriptionIds.Contains(x.SubscriptionId));
            }

            if (criteria.Statuses != null && criteria.Statuses.Any())
            {
                query = query.Where(x => criteria.Statuses.Contains(x.Status));
            }

            if (criteria.StoreIds != null && criteria.StoreIds.Any())
            {
                query = query.Where(x => criteria.StoreIds.Contains(x.StoreId));
            }

            if (!criteria.Numbers.IsNullOrEmpty())
            {
                query = query.Where(x => criteria.Numbers.Contains(x.Number));
            }
            else if (!string.IsNullOrEmpty(criteria.Keyword))
            {
                query = query.Where(GetKeywordPredicate(criteria));
            }

            return(query);
        }
        public async Task <ActionResult <CustomerOrderSearchResult> > SearchCustomerOrder([FromBody] CustomerOrderSearchCriteria criteria)
        {
            var authorizationResult = await _authorizationService.AuthorizeAsync(User, criteria, new OrderAuthorizationRequirement(ModuleConstants.Security.Permissions.Read));

            if (!authorizationResult.Succeeded)
            {
                return(Unauthorized());
            }

            var result = await _searchService.SearchCustomerOrdersAsync(criteria);

            //It is a important to return serialized data by such way. Instead you have a slow response time for large outputs
            //https://github.com/dotnet/aspnetcore/issues/19646
            return(Content(JsonConvert.SerializeObject(result, _jsonOptions.SerializerSettings), "application/json"));
        }