public IHttpActionResult ProcessOrderPayments(string orderId, string paymentId,
                                                      [SwaggerOptional] BankCardInfo bankCardInfo)
        {
            var order = _customerOrderService.GetByIds(new[] { orderId }, CustomerOrderResponseGroup.Full.ToString())
                        .FirstOrDefault();

            if (order == null)
            {
                var searchCriteria = AbstractTypeFactory <CustomerOrderSearchCriteria> .TryCreateInstance();

                searchCriteria.Number        = orderId;
                searchCriteria.ResponseGroup = CustomerOrderResponseGroup.Full.ToString();

                order = _searchService.SearchCustomerOrders(searchCriteria).Results.FirstOrDefault();
            }

            if (order == null)
            {
                throw new InvalidOperationException($"Cannot find order with ID {orderId}");
            }

            var payment = order.InPayments.FirstOrDefault(x => x.Id == paymentId);

            if (payment == null)
            {
                throw new InvalidOperationException($"Cannot find payment with ID {paymentId}");
            }

            var store         = _storeService.GetById(order.StoreId);
            var paymentMethod = store.PaymentMethods.FirstOrDefault(x => x.Code == payment.GatewayCode);

            if (paymentMethod == null)
            {
                throw new InvalidOperationException($"Cannot find payment method with code {payment.GatewayCode}");
            }

            var context = new ProcessPaymentEvaluationContext
            {
                Order        = order,
                Payment      = payment,
                Store        = store,
                BankCardInfo = bankCardInfo
            };

            var result = paymentMethod.ProcessPayment(context);

            if (result.OuterId != null)
            {
                payment.OuterId = result.OuterId;
            }

            _customerOrderService.SaveChanges(new[] { order });

            return(Ok(result));
        }
        public IHttpActionResult ProcessOrderPayments(string orderId, string paymentId, [SwaggerOptional] BankCardInfo bankCardInfo)
        {
            var order = _customerOrderService.GetByIds(new[] { orderId }, CustomerOrderResponseGroup.Full.ToString()).FirstOrDefault();

            if (order == null)
            {
                order = _searchService.SearchCustomerOrders(new CustomerOrderSearchCriteria {
                    Number = orderId, ResponseGroup = CustomerOrderResponseGroup.Full.ToString()
                }).Results.FirstOrDefault();
            }

            if (order == null)
            {
                throw new NullReferenceException("order");
            }
            var payment = order.InPayments.FirstOrDefault(x => x.Id == paymentId);

            if (payment == null)
            {
                throw new NullReferenceException("payment");
            }
            var store         = _storeService.GetById(order.StoreId);
            var paymentMethod = store.PaymentMethods.FirstOrDefault(x => x.Code == payment.GatewayCode);

            if (paymentMethod == null)
            {
                throw new NullReferenceException("appropriate paymentMethod not found");
            }

            var context = new ProcessPaymentEvaluationContext
            {
                Order        = order,
                Payment      = payment,
                Store        = store,
                BankCardInfo = bankCardInfo
            };

            var result = paymentMethod.ProcessPayment(context);

            if (result.OuterId != null)
            {
                payment.OuterId = result.OuterId;
            }

            _customerOrderService.SaveChanges(new[] { order });

            return(Ok(result));
        }
Esempio n. 3
0
        public virtual orderModel.CustomerOrder PlaceCustomerOrderFromCart(cartModel.ShoppingCart cart)
        {
            var customerOrder = ConvertCartToOrder(cart);

            _customerOrderService.SaveChanges(new[] { customerOrder });
            return(customerOrder);
        }
Esempio n. 4
0
        protected virtual void TryToCancelOrder(GenericChangedEntry <CustomerOrder> changedEntry)
        {
            var store = _storeService.GetById(changedEntry.NewEntry.StoreId);

            //Try to load payment methods for payments
            foreach (var payment in changedEntry.NewEntry.InPayments)
            {
                payment.PaymentMethod = store.PaymentMethods.FirstOrDefault(p => p.Code.EqualsInvariant(payment.GatewayCode));
            }

            var toCancelPayments = new List <PaymentIn>();
            var isOrderCancelled = !changedEntry.OldEntry.IsCancelled && changedEntry.NewEntry.IsCancelled;

            if (isOrderCancelled)
            {
                toCancelPayments = changedEntry.NewEntry.InPayments?.ToList();
            }
            else
            {
                foreach (var canceledPayment in changedEntry.NewEntry?.InPayments.Where(x => x.IsCancelled) ?? Enumerable.Empty <PaymentIn>())
                {
                    var oldSamePayment = changedEntry.OldEntry?.InPayments.FirstOrDefault(x => x == canceledPayment);
                    if (oldSamePayment != null && !oldSamePayment.IsCancelled)
                    {
                        toCancelPayments.Add(canceledPayment);
                    }
                }
            }
            TryToCancelOrderPayments(toCancelPayments);
            if (!toCancelPayments.IsNullOrEmpty())
            {
                _orderService.SaveChanges(new[] { changedEntry.NewEntry });
            }
        }
Esempio n. 5
0
        protected virtual Task HandleOrderChangesAsync(GenericChangedEntry <CustomerOrder> changedEntry)
        {
            var customerOrder = changedEntry.NewEntry;

            //Prevent creating subscription for customer orders with other operation type (it is need for preventing to handling  subscription prototype and recurring order creations)
            if (!customerOrder.IsPrototype && string.IsNullOrEmpty(customerOrder.SubscriptionId))
            {
                try
                {
                    var subscription = _subscriptionBuilder.TryCreateSubscriptionFromOrder(customerOrder);
                    if (subscription != null)
                    {
                        _subscriptionBuilder.TakeSubscription(subscription).Actualize();
                        _subscriptionService.SaveSubscriptions(new[] { subscription });
                        //Link subscription with customer order
                        customerOrder.SubscriptionId     = subscription.Id;
                        customerOrder.SubscriptionNumber = subscription.Number;
                        //Save order changes
                        _customerOrderService.SaveChanges(new[] { customerOrder });
                    }
                }
                catch (Exception ex)
                {
                    throw new CreateSubscriptionException(ex);
                }
            }

            return(Task.CompletedTask);
        }
        public IHttpActionResult UpdateOrders(string action, string order_number, string carrier, string service, string tracking_number, ShipNotice shipnotice)
        {
            var searchCriteria = new CustomerOrderSearchCriteria {
                Number        = shipnotice.OrderNumber,
                ResponseGroup = "Full"
            };

            var order = _orderSearchService.SearchCustomerOrders(searchCriteria);

            if (order == null)
            {
                return(BadRequest("Order not found"));
            }

            var updatedOrder = _orderService.GetByIds(new[] { order.Results.FirstOrDefault().Id }).FirstOrDefault();

            if (updatedOrder != null)
            {
                updatedOrder.Patch(shipnotice);

                _orderService.SaveChanges(new[] { updatedOrder });
            }

            return(Ok(shipnotice));
        }
Esempio n. 7
0
        public void Process()
        {
            var criteria = new SubscriptionSearchCriteria
            {
                Statuses = new[] { SubscriptionStatus.Active, SubscriptionStatus.PastDue, SubscriptionStatus.Trialing, SubscriptionStatus.Unpaid }.Select(x => x.ToString()).ToArray(),
                Take     = 0,
            };
            var result    = _subscriptionSearchService.SearchSubscriptions(criteria);
            var batchSize = 20;

            for (var i = 0; i < result.TotalCount; i += batchSize)
            {
                criteria.Skip = i;
                criteria.Take = batchSize;
                result        = _subscriptionSearchService.SearchSubscriptions(criteria);
                var subscriptions = _subscriptionService.GetByIds(result.Results.Select(x => x.Id).ToArray());
                foreach (var subscription in subscriptions)
                {
                    var newOrder = _subscriptionBuilder.TakeSubscription(subscription).Actualize().TryToCreateRecurrentOrder();
                    if (newOrder != null)
                    {
                        _customerOrderService.SaveChanges(new[] { newOrder });
                    }
                }
            }
        }
Esempio n. 8
0
        public IHttpActionResult CreateReccurentOrderForSubscription(Subscription subscription)
        {
            var order = _subscriptionBuilder.TakeSubscription(subscription).Actualize()
                        .TryToCreateRecurrentOrder(forceCreation: true);

            _customerOrderService.SaveChanges(new[] { order });
            return(Ok(order));
        }
Esempio n. 9
0
        public virtual orderModel.CustomerOrder PlaceCustomerOrderFromCart(cartModel.ShoppingCart cart)
        {
            var customerOrder = ConvertCartToOrder(cart);

            _customerOrderService.SaveChanges(new[] { customerOrder });

            customerOrder = _customerOrderService.GetByIds(new[] { customerOrder.Id }).FirstOrDefault();

            return(customerOrder);
        }
Esempio n. 10
0
        public void SaveSubscriptions(Subscription[] subscriptions)
        {
            var pkMap          = new PrimaryKeyResolvingMap();
            var changedEntries = new List <GenericChangedEntry <Subscription> >();

            using (var repository = _subscriptionRepositoryFactory())
                using (var changeTracker = GetChangeTracker(repository))
                {
                    var existEntities = repository.GetSubscriptionsByIds(subscriptions.Where(x => !x.IsTransient()).Select(x => x.Id).ToArray());
                    foreach (var subscription in subscriptions)
                    {
                        //Generate numbers for new subscriptions
                        if (string.IsNullOrEmpty(subscription.Number))
                        {
                            var store          = _storeService.GetById(subscription.StoreId);
                            var numberTemplate = store.Settings.GetSettingValue("Subscription.SubscriptionNewNumberTemplate", "SU{0:yyMMdd}-{1:D5}");
                            subscription.Number = _uniqueNumberGenerator.GenerateNumber(numberTemplate);
                        }
                        //Save subscription order prototype with same as subscription Number
                        if (subscription.CustomerOrderPrototype != null)
                        {
                            subscription.CustomerOrderPrototype.Number      = subscription.Number;
                            subscription.CustomerOrderPrototype.IsPrototype = true;
                            _customerOrderService.SaveChanges(new[] { subscription.CustomerOrderPrototype });
                        }
                        var originalEntity       = existEntities.FirstOrDefault(x => x.Id == subscription.Id);
                        var originalSubscription = originalEntity != null?originalEntity.ToModel(AbstractTypeFactory <Subscription> .TryCreateInstance()) : subscription;

                        var modifiedEntity = AbstractTypeFactory <SubscriptionEntity> .TryCreateInstance()
                                             .FromModel(subscription, pkMap) as SubscriptionEntity;

                        if (originalEntity != null)
                        {
                            changeTracker.Attach(originalEntity);
                            changedEntries.Add(new GenericChangedEntry <Subscription>(subscription, originalEntity.ToModel(AbstractTypeFactory <Subscription> .TryCreateInstance()), EntryState.Modified));
                            modifiedEntity.Patch(originalEntity);
                            //force the subscription.ModifiedDate update, because the subscription object may not have any changes in its properties
                            originalEntity.ModifiedDate = DateTime.UtcNow;
                        }
                        else
                        {
                            repository.Add(modifiedEntity);
                            changedEntries.Add(new GenericChangedEntry <Subscription>(subscription, EntryState.Added));
                        }
                    }

                    //Raise domain events
                    _eventPublisher.Publish(new SubscriptionChangingEvent(changedEntries));
                    CommitChanges(repository);
                    pkMap.ResolvePrimaryKeys();
                    _eventPublisher.Publish(new SubscriptionChangedEvent(changedEntries));
                }
        }
Esempio n. 11
0
        public void DoImport(Stream backupStream, Action <ExportImportProgressInfo> progressCallback)
        {
            var backupObject = backupStream.DeserializeJson <BackupObject>();

            var progressInfo = new ExportImportProgressInfo();
            var totalCount   = backupObject.CustomerOrders.Count();
            var take         = 20;

            for (int skip = 0; skip < totalCount; skip += take)
            {
                _customerOrderService.SaveChanges(backupObject.CustomerOrders.Skip(skip).Take(take).ToArray());

                progressInfo.Description = String.Format("{0} of {1} orders imported", Math.Min(skip + take, totalCount), totalCount);
                progressCallback(progressInfo);
            }
        }
        public IHttpActionResult RegisterPayment(string orderId)
        {
            var order = _customerOrderService.GetByIds(new[] { orderId }).FirstOrDefault();

            if (order == null)
            {
                throw new NullReferenceException("order");
            }

            var store      = _storeService.GetById(order.StoreId);
            var parameters = new NameValueCollection();

            foreach (var key in HttpContext.Current.Request.QueryString.AllKeys)
            {
                parameters.Add(key, HttpContext.Current.Request.Form[key]);
            }

            foreach (var key in HttpContext.Current.Request.Form.AllKeys)
            {
                parameters.Add(key, HttpContext.Current.Request.Form[key]);
            }

            var paymentMethod = store.PaymentMethods.FirstOrDefault(x => x.Code == "AuthorizeNet");

            if (paymentMethod != null)
            {
                var validateResult = paymentMethod.ValidatePostProcessRequest(parameters);
                var paymentOuterId = validateResult.OuterId;

                var payment = order.InPayments.FirstOrDefault(x => x.GatewayCode == "AuthorizeNet" && x.Sum == Convert.ToDecimal(parameters["x_amount"], CultureInfo.InvariantCulture));
                if (payment == null)
                {
                    throw new NullReferenceException("payment");
                }

                if (payment == null)
                {
                    throw new NullReferenceException("appropriate paymentMethod not found");
                }

                var context = new PostProcessPaymentEvaluationContext
                {
                    Order      = order,
                    Payment    = payment,
                    Store      = store,
                    OuterId    = paymentOuterId,
                    Parameters = parameters
                };

                var retVal = paymentMethod.PostProcessPayment(context);

                if (retVal != null && retVal.IsSuccess)
                {
                    _customerOrderService.SaveChanges(new CustomerOrder[] { order });

                    var returnHtml = string.Format("<html><head><script type='text/javascript' charset='utf-8'>window.location='{0}';</script><noscript><meta http-equiv='refresh' content='1;url={0}'></noscript></head><body></body></html>", retVal.ReturnUrl);

                    return(Ok(returnHtml));
                }
            }

            return(StatusCode(System.Net.HttpStatusCode.NoContent));
        }
Esempio n. 13
0
        public IHttpActionResult SyncOrders(SyncOrdersRequest request)
        {
            if (request == null)
            {
                return(Ok(true));
            }
            var syncSettings = _syncSettingsService.GetSettingsByAccountName(request.UserLogin);

            if (syncSettings == null || string.IsNullOrEmpty(syncSettings.ProductsCategoryId))
            {
                return(Ok());
            }
            var customerOrders = new List <CustomerOrder>();
            var store          = _storeService.GetById(syncSettings.ProductsCategoryId);

            foreach (var item in request.Orders)
            {
                var address = new Address
                {
                    AddressType  = AddressType.Shipping,
                    City         = item.Customer.City,
                    CountryName  = item.Customer.Coutry,
                    CountryCode  = item.Customer.Coutry.Substring(0, 3),
                    Email        = item.Customer.Email,
                    FirstName    = item.Customer.FirstName,
                    Name         = item.Customer.FirstName,
                    LastName     = item.Customer.LastName,
                    Phone        = item.Customer.Phone,
                    Line1        = item.Customer.Address,
                    Organization = item.Customer.CompanyName,
                    PostalCode   = item.Customer.PostalCode
                };
                var customer = new Domain.Customer.Model.Employee
                {
                    Id        = item.Customer.Id,
                    Addresses = new[] { address },
                    Emails    = new[] { item.Customer.Email },
                    IsActive  = true,
                    Phones    = new[] { item.Customer.Phone },
                    FirstName = item.Customer.FirstName,
                    LastName  = item.Customer.LastName,
                    FullName  = $"{item.Customer.FirstName} {item.Customer.LastName}"
                };
                _memberService.SaveChanges(new[] { customer });
                //convert items
                var products = _itemService.GetByIds(item.Items.Select(x => x.ProductId).ToArray(), ItemResponseGroup.ItemInfo);
                var order    = new CustomerOrder
                {
                    Id           = item.Id,
                    StoreId      = store.Id,
                    StoreName    = store.Name,
                    Addresses    = new[] { address },
                    Currency     = item.Items.First().Currency,
                    Items        = new List <LineItem>(),
                    EmployeeId   = customer.Id,
                    EmployeeName = customer.FullName,
                    CustomerId   = customer.Id,
                };
                foreach (var lineItem in item.Items)
                {
                    var prod = products.First(x => x.Id == lineItem.ProductId);
                    order.Items.Add(new LineItem
                    {
                        CatalogId      = prod.CatalogId,
                        Currency       = lineItem.Currency,
                        Sku            = prod.Code,
                        CategoryId     = prod.CategoryId,
                        ImageUrl       = _blobUrlResolver.GetAbsoluteUrl(prod.Images.FirstOrDefault()?.Url),
                        DiscountAmount = lineItem.Discount / lineItem.Quantity,
                        Id             = lineItem.Id,
                        Name           = prod.Name,
                        Price          = lineItem.SubTotal / lineItem.Quantity + lineItem.Discount / lineItem.Quantity,
                        Quantity       = lineItem.Quantity,
                        ProductType    = prod.ProductType,
                        ProductId      = prod.Id,
                        Product        = prod
                    });
                }
                //
                customerOrders.Add(order);
            }
            _customerOrderService.SaveChanges(customerOrders.ToArray());
            return(Ok(true));
        }