예제 #1
0
        protected virtual IQueryable <SubscriptionEntity> BuildQuery(ISubscriptionRepository repository, SubscriptionSearchCriteria criteria)
        {
            var query = repository.Subscriptions;

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

            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.StoreId != null)
            {
                query = query.Where(x => criteria.StoreId == x.StoreId);
            }

            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.ModifiedSinceDate != null)
            {
                query = query.Where(x => x.ModifiedDate >= criteria.ModifiedSinceDate);
            }

            if (!string.IsNullOrEmpty(criteria.CustomerOrderId))
            {
                var order = _customerOrderService.GetByIdsAsync(new[] { criteria.CustomerOrderId }).GetAwaiter().GetResult().FirstOrDefault();
                if (order != null && !string.IsNullOrEmpty(order.SubscriptionId))
                {
                    query = query.Where(x => x.Id == order.SubscriptionId);
                }
                else
                {
                    query = query.Where(x => false);
                }
            }

            if (criteria.OuterId != null)
            {
                query = query.Where(x => x.OuterId == criteria.OuterId);
            }
            return(query);
        }
        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.SafeParseFlags(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);

                            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();
            }));
        }
        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 <AvaTaxOrderSynchronizationStatus> GetOrderSynchronizationStatusAsync(string orderId)
        {
            var order = (await _orderService.GetByIdsAsync(new[] { orderId })).FirstOrDefault();

            if (order == null)
            {
                throw new ArgumentException("Order with given ID does not exist.", nameof(orderId));
            }

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

            var avaTaxSettings = await GetAvataxSettingsForOrder(order);

            if (avaTaxSettings != null)
            {
                var avaTaxClient = _avaTaxClientFactory(avaTaxSettings);
                try
                {
                    var companyCode      = avaTaxSettings.CompanyCode;
                    var transactionModel = await avaTaxClient.GetTransactionByCodeAsync(companyCode, order.Number, DocumentType.SalesInvoice, string.Empty);

                    result.TransactionId           = transactionModel.id;
                    result.LastSynchronizationDate = transactionModel.modifiedDate;
                    result.LinkToAvaTax            = BuildLinkToAvaTaxTransaction(transactionModel, avaTaxSettings);
                    result.RawContent = JsonConvert.SerializeObject(transactionModel, Formatting.Indented);
                }
                catch (AvaTaxError e) when(e.statusCode == HttpStatusCode.NotFound)
                {
                    // The transaction does not exist in Avalara - the order had probably never been sent there.
                    // This is normal, and we shouldn't treat it as error.
                    result.LastSynchronizationDate = null;
                }
                catch (AvaTaxError e)
                {
                    var errorDetails   = e.error.error;
                    var joinedMessages = string.Join(Environment.NewLine, errorDetails.details.Select(x => $"{x.severity}: {x.message} {x.description}"));

                    var errorMessage = $"{errorDetails.message}{Environment.NewLine}{joinedMessages}";
                    result.Errors    = new[] { errorMessage };
                    result.HasErrors = true;
                }
            }
            result.StoreUsesAvaTax = avaTaxSettings != null;

            return(result);
        }
예제 #5
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;
                }
            }));
        }
예제 #6
0
        protected virtual async Task DoBulkActionsWithOrderAggregate(PaymentIn[] payments, Action <CustomerOrder, PaymentIn> action)
        {
            if (payments.Any(x => string.IsNullOrEmpty(x.OrderId)))
            {
                throw new OperationCanceledException($"{ nameof(PaymentIn.OrderId) } must be set.");
            }
            var oderIds = payments.Select(x => x.OrderId).Distinct().ToArray();

            if (oderIds.Any())
            {
                var ordersAggregates = await _customerOrderService.GetByIdsAsync(oderIds);

                foreach (var payment in payments)
                {
                    var orderAggregateRoot = ordersAggregates.FirstOrDefault(x => x.Id == payment.OrderId);
                    if (orderAggregateRoot != null)
                    {
                        orderAggregateRoot.InPayments.Remove(payment);
                        orderAggregateRoot.InPayments.Add(payment);
                    }
                }
                await _customerOrderService.SaveChangesAsync(ordersAggregates);
            }
        }
        protected virtual async Task <IQueryable <SubscriptionEntity> > GetSubscriptionsQueryForCriteria(
            ISubscriptionRepository repository, SubscriptionSearchCriteria criteria)
        {
            var query = repository.Subscriptions;

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

            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.StoreId != null)
            {
                query = query.Where(x => criteria.StoreId == x.StoreId);
            }

            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.ModifiedSinceDate != null)
            {
                query = query.Where(x => x.ModifiedDate >= criteria.ModifiedSinceDate);
            }

            if (!string.IsNullOrEmpty(criteria.CustomerOrderId))
            {
                var order = (await _customerOrderService.GetByIdsAsync(new[] { criteria.CustomerOrderId })).FirstOrDefault();
                if (order != null && !string.IsNullOrEmpty(order.SubscriptionId))
                {
                    query = query.Where(x => x.Id == order.SubscriptionId);
                }
                else
                {
                    query = query.Where(x => false);
                }
            }

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

            var sortInfos = criteria.SortInfos;

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

            return(query);
        }