public virtual ActionResult ResetShippings(string orderId)
        {
            LogI("ResetShippings begin, orderid=" + orderId);
            var result = MessageResult.Error("Undefined");

            if (!string.IsNullOrEmpty(orderId))
            {
                var syncInfo      = new EmptySyncInformer(LogService, SyncType.Orders);
                var rateProviders = ServiceFactory.GetShipmentProviders(LogService,
                                                                        Time,
                                                                        DbFactory,
                                                                        WeightService,
                                                                        AccessManager.Company.ShipmentProviderInfoList,
                                                                        null,
                                                                        null,
                                                                        null,
                                                                        null);

                DTOOrder dtoOrder = Db.ItemOrderMappings.GetOrderWithItems(WeightService, orderId, unmaskReferenceStyle: false, includeSourceItems: true);
                if (dtoOrder != null)
                {
                    dtoOrder.OrderStatus = OrderStatusEnumEx.Unshipped;

                    var synchronizer = new AmazonOrdersSynchronizer(LogService,
                                                                    AccessManager.Company,
                                                                    syncInfo,
                                                                    rateProviders,
                                                                    CompanyAddress,
                                                                    Time,
                                                                    WeightService,
                                                                    MessageService);

                    if (synchronizer.UIUpdate(Db, dtoOrder, true, false, keepCustomShipping: false, switchToMethodId: null))
                    {
                        var dbOrder = Db.Orders.Get(dtoOrder.Id);
                        dbOrder.OrderStatus  = OrderStatusEnum.Unshipped.ToString();
                        dbOrder.UpgradeLevel = null;
                        Db.Commit();

                        result = MessageResult.Success("Success updates");
                    }
                }
                else
                {
                    result = MessageResult.Error("Not found OrderId: " + orderId);
                }
            }
            else
            {
                result = MessageResult.Error("OrderId is empty");
            }

            return(new JsonResult {
                Data = result, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
        public void RefreshAmazonRates()
        {
            var syncInfo = new EmptySyncInformer(_log, SyncType.Orders);

            using (var db = _dbFactory.GetRWDb())
            {
                var toRefreshOrderIds = (from o in db.Orders.GetAll()
                                         join sh in db.OrderShippingInfos.GetAll() on o.Id equals sh.OrderId
                                         where o.OrderStatus == OrderStatusEnumEx.Unshipped &&
                                         sh.IsActive &&
                                         (o.Market == (int)MarketType.Amazon ||
                                          o.Market == (int)MarketType.AmazonAU ||
                                          o.Market == (int)MarketType.AmazonEU) &&
                                         (sh.ShippingMethodId == (int)ShippingUtils.AmazonFedExExpressSaverShippingMethodId || //TEMP: old
                                          sh.ShippingMethodId == (int)ShippingUtils.AmazonFedExHomeDeliveryShippingMethodId || //TEMP: old
                                          o.SourceShippingService == ShippingUtils.SecondDayServiceName ||
                                          o.SourceShippingService == ShippingUtils.NextDayServiceName ||
                                          o.OrderType == (int)OrderTypeEnum.Prime)
                                         select o.Id).ToList();

                _log.Info("Orders to update: " + String.Join(", ", toRefreshOrderIds.Select(o => o).ToList()));

                var orderIdList = toRefreshOrderIds.ToArray();
                if (!orderIdList.Any())
                {
                    return;
                }

                IList <DTOOrder> dtoOrders = db.ItemOrderMappings.GetSelectedOrdersWithItems(_weightService, orderIdList, includeSourceItems: true).ToList();
                foreach (var dtoOrder in dtoOrders)
                {
                    //Ignore shipped orders
                    if (ShippingUtils.IsOrderShipped(dtoOrder.OrderStatus) ||
                        dtoOrder.ShippingInfos.Any(s => !String.IsNullOrEmpty(s.LabelPath)) ||
                        dtoOrder.ShippingInfos.Any(s => !String.IsNullOrEmpty(s.TrackingNumber)))
                    {
                        _log.Info("OrderId: " + dtoOrder.Id + " (" + dtoOrder.OrderId + ") - Skipped (has shipped status or has tr#)");
                    }
                    else
                    {
                        _log.Info("Add recalc action for OrderId=" + dtoOrder.OrderId);

                        _actionService.AddAction(db,
                                                 SystemActionType.UpdateRates,
                                                 dtoOrder.OrderId,
                                                 new UpdateRatesInput()
                        {
                            OrderId = dtoOrder.Id
                        },
                                                 null,
                                                 null);
                    }
                }
            }
        }
Beispiel #3
0
        public void UpgradeOrderList(IList <long> orderIds)
        {
            var syncInfo       = new EmptySyncInformer(_log, SyncType.Orders);
            var serviceFactory = new ServiceFactory();
            var weightService  = new WeightService();
            var messageService = new SystemMessageService(_log, _time, _dbFactory);

            var rateProviders = serviceFactory.GetShipmentProviders(_log,
                                                                    _time,
                                                                    _dbFactory,
                                                                    weightService,
                                                                    _company.ShipmentProviderInfoList,
                                                                    null,
                                                                    null,
                                                                    null,
                                                                    null);

            var companyAddress = new CompanyAddressService(_company);

            var synchronizer = new AmazonOrdersSynchronizer(_log,
                                                            _company,
                                                            syncInfo,
                                                            rateProviders,
                                                            companyAddress,
                                                            _time,
                                                            weightService,
                                                            messageService);

            using (var db = _dbFactory.GetRWDb())
            {
                IList <DTOOrder> dtoOrders = db.ItemOrderMappings.GetSelectedOrdersWithItems(weightService, orderIds.ToArray(), includeSourceItems: true).ToList();
                foreach (var dtoOrder in dtoOrders)
                {
                    _log.Info("Upgrade order: " + dtoOrder.OrderId);
                    //Update into DB, after success update
                    var order = db.Orders.GetById(dtoOrder.Id);
                    order.UpgradeLevel = 1;
                    db.Commit();
                    dtoOrder.UpgradeLevel = 1;

                    if (synchronizer.UIUpdate(db, dtoOrder, false, false, false, null))
                    {
                        _log.Info("Success");
                    }
                    else
                    {
                        _log.Info("Failed");
                    }
                }
            }
        }
        public void RefreshSuspiciousFedexRates()
        {
            var syncInfo = new EmptySyncInformer(_log, SyncType.Orders);

            using (var db = _dbFactory.GetRWDb())
            {
                var toRefreshOrderIds = (from o in db.Orders.GetAll()
                                         join sh in db.OrderShippingInfos.GetAll() on o.Id equals sh.OrderId
                                         where o.OrderStatus == OrderStatusEnumEx.Unshipped &&
                                         sh.IsActive &&
                                         (sh.ShippingMethodId == ShippingUtils.FedexOneRate2DayEnvelope ||
                                          sh.ShippingMethodId == ShippingUtils.FedexOneRate2DayPak) &&
                                         sh.StampsShippingCost > 12
                                         select o.Id).ToList();

                _log.Info("Orders to update: " + String.Join(", ", toRefreshOrderIds.Select(o => o).ToList()));

                var orderIdList = toRefreshOrderIds.ToArray();
                if (!orderIdList.Any())
                {
                    return;
                }

                IList <DTOOrder> dtoOrders = db.ItemOrderMappings.GetSelectedOrdersWithItems(_weightService, orderIdList, includeSourceItems: true).ToList();
                foreach (var dtoOrder in dtoOrders)
                {
                    //Ignore shipped orders
                    if (ShippingUtils.IsOrderShipped(dtoOrder.OrderStatus) ||
                        dtoOrder.ShippingInfos.Any(s => !String.IsNullOrEmpty(s.LabelPath)) ||
                        dtoOrder.ShippingInfos.Any(s => !String.IsNullOrEmpty(s.TrackingNumber)))
                    {
                        _log.Info("OrderId: " + dtoOrder.Id + " (" + dtoOrder.OrderId + ") - Skipped (has shipped status or has tr#)");
                    }
                    else
                    {
                        _log.Info("Add recalc action for OrderId=" + dtoOrder.OrderId);

                        _actionService.AddAction(db,
                                                 SystemActionType.UpdateRates,
                                                 dtoOrder.OrderId,
                                                 new UpdateRatesInput()
                        {
                            OrderId = dtoOrder.Id
                        },
                                                 null,
                                                 null);
                    }
                }
            }
        }
Beispiel #5
0
        public void Create(ILogService log,
                           ITime time,
                           IQuantityManager quantityManager,
                           IDbFactory dbFactory,
                           IWeightService weightService,
                           IShippingService shippingService,
                           IAutoCreateListingService createListingService,
                           ISettingsService settingService,
                           IEmailService emailService,
                           ISystemActionService actionService,
                           IHtmlScraperService htmlScraper,
                           IOrderHistoryService orderHistory,
                           IPriceService priceService,
                           CompanyDTO company,
                           DateTime when,
                           long?by)
        {
            var syncInfo      = new EmptySyncInformer(log, SyncType.Orders);
            var market        = (int)MarketType.OfflineOrders;
            var marketplaceId = MarketplaceKeeper.ManuallyCreated;

            var orderItems = new List <ListingOrderDTO>();

            using (var db = dbFactory.GetRWDb())
            {
                var index = 1;
                foreach (var item in Items)
                {
                    var dbItem = db.Items.GetAll().FirstOrDefault(i => i.Market == market &&
                                                                  i.MarketplaceId == marketplaceId &&
                                                                  i.StyleItemId == item.StyleItemId);

                    if (dbItem == null)
                    {
                        var itemPrice = item.ItemPrice; // db.Items.GetAllViewActual()
                                                        //.FirstOrDefault(i => i.Market == (int)MarketType.Amazon
                                                        //    && i.MarketplaceId == MarketplaceKeeper.AmazonComMarketplaceId)?.CurrentPrice;

                        log.Info("Request create listing, market=" + market
                                 + ", marketplaceId=" + marketplaceId);

                        IList <MessageString> messages = new List <MessageString>();
                        //Create New
                        var model = createListingService.CreateFromStyle(db,
                                                                         item.StyleId.Value,
                                                                         (MarketType)market,
                                                                         marketplaceId,
                                                                         out messages);

                        model.Variations.ForEach(v => v.CurrentPrice = itemPrice);

                        createListingService.Save(model,
                                                  "",
                                                  db,
                                                  when,
                                                  by);

                        dbItem = db.Items.GetAll().FirstOrDefault(i => i.Market == market &&
                                                                  i.MarketplaceId == marketplaceId &&
                                                                  i.StyleItemId == item.StyleItemId);
                    }

                    var dbListing = db.Listings.GetAll().FirstOrDefault(l => l.Market == market &&
                                                                        l.MarketplaceId == marketplaceId &&
                                                                        l.ItemId == dbItem.Id);

                    orderItems.Add(new ListingOrderDTO()
                    {
                        ASIN            = dbItem.ASIN,
                        SKU             = dbListing.SKU,
                        ItemPaid        = item.ItemPrice,
                        ItemPrice       = item.ItemPrice,
                        ItemGrandPrice  = item.ItemPrice,
                        StyleId         = dbItem.StyleId,
                        StyleID         = dbItem.StyleString,
                        StyleItemId     = dbItem.StyleItemId,
                        Market          = dbItem.Market,
                        MarketplaceId   = dbItem.MarketplaceId,
                        QuantityOrdered = item.Quantity,
                        ItemOrderId     = index.ToString(),
                        SourceListingId = dbListing.Id,
                    });

                    index++;
                }

                OrderNumber = db.Orders.GetAll()
                              .Where(o => o.Market == (int)market &&
                                     o.MarketplaceId == marketplaceId)
                              .OrderByDescending(o => o.Id).FirstOrDefault()?.AmazonIdentifier;

                if (String.IsNullOrEmpty(OrderNumber))
                {
                    OrderNumber = "1000";
                }
                else
                {
                    OrderNumber = ((StringHelper.TryGetInt(OrderNumber) ?? 1000) + 1).ToString();
                }
            }

            var dtoOrder = new DTOOrder()
            {
                Market            = market,
                MarketplaceId     = marketplaceId,
                OrderDate         = OrderDate,
                OrderStatus       = "Unshipped",
                SourceOrderStatus = "Unshipped",
                OrderId           = OrderNumber,
                CustomerOrderId   = OrderNumber,
                MarketOrderId     = OrderNumber,

                AmazonEmail      = ToAddress.Email,
                BuyerEmail       = ToAddress.Email,
                PersonName       = ToAddress.FullName,
                BuyerName        = ToAddress.FullName,
                ShippingAddress1 = ToAddress.Address1,
                ShippingAddress2 = ToAddress.Address2,
                ShippingCity     = ToAddress.City,
                ShippingCountry  = ToAddress.Country,
                ShippingZip      = ToAddress.Zip,
                ShippingZipAddon = ToAddress.ZipAddon,
                ShippingPhone    = ToAddress.Phone,
                ShippingState    = StringHelper.GetFirstNotEmpty(ToAddress.USAState, ToAddress.NonUSAState),

                ShippingPaid  = 0,
                ShippingPrice = 0,
                TotalPaid     = Items.Sum(i => i.ItemPrice),
                TotalPrice    = Items.Sum(i => i.ItemPrice),

                Quantity = Items.Sum(i => i.Quantity),

                InitialServiceType    = ShippingService,
                ShippingService       = ShippingService,
                SourceShippingService = ShippingService,

                Items = orderItems,
            };

            var userOrderApi = new UserOrderApi(new List <DTOOrder>()
            {
                dtoOrder
            });

            var serviceFactory       = new ServiceFactory();
            var addressCheckServices = serviceFactory.GetAddressCheckServices(log,
                                                                              time,
                                                                              dbFactory,
                                                                              company.AddressProviderInfoList);
            var companyAddress = new CompanyAddressService(company);
            var addressService = new AddressService(addressCheckServices, companyAddress.GetReturnAddress(MarketIdentifier.Empty()), companyAddress.GetPickupAddress(MarketIdentifier.Empty()));

            var rateProviders = serviceFactory.GetShipmentProviders(log,
                                                                    time,
                                                                    dbFactory,
                                                                    weightService,
                                                                    company.ShipmentProviderInfoList,
                                                                    null,
                                                                    null,
                                                                    null,
                                                                    null);

            var stampsRateProvider = rateProviders.FirstOrDefault(r => r.Type == ShipmentProviderType.Stamps);

            var validatorService = new OrderValidatorService(log, dbFactory, emailService, settingService, orderHistory, actionService,
                                                             priceService, htmlScraper, addressService, companyAddress.GetReturnAddress(MarketIdentifier.Empty()), stampsRateProvider, time, company);
            var orderHistoryService = new OrderHistoryService(log, time, dbFactory);
            var cacheService        = new CacheService(log, time, actionService, quantityManager);

            using (var db = dbFactory.GetRWDb())
            {
                try
                {
                    var orderSyncFactory = new OrderSyncFactory();
                    var synchronizer     = orderSyncFactory.GetForMarket(userOrderApi,
                                                                         log,
                                                                         company,
                                                                         settingService,
                                                                         syncInfo,
                                                                         rateProviders,
                                                                         quantityManager,
                                                                         emailService,
                                                                         validatorService,
                                                                         orderHistoryService,
                                                                         cacheService,
                                                                         actionService,
                                                                         companyAddress,
                                                                         time,
                                                                         weightService,
                                                                         null);

                    if (!String.IsNullOrEmpty(OrderNumber))
                    {
                        synchronizer.ProcessSpecifiedOrder(db, OrderNumber);
                        Messages.Add(MessageString.Success("The order has been successfully created, order #: " + OrderNumber));
                    }
                }
                catch (Exception ex)
                {
                    Messages.Add(MessageString.Error(ex.Message));
                }
            }
        }
        public void ProcessSystemAction(CancellationToken cancelToken)
        {
            var syncInfo = new EmptySyncInformer(_log, SyncType.Orders);

            using (var db = _dbFactory.GetRWDb())
            {
                var updateRateActions = _actionService.GetUnprocessedByType(db, SystemActionType.UpdateRates, null, null);

                foreach (var action in updateRateActions)
                {
                    if (cancelToken.IsCancellationRequested)
                    {
                        return;
                    }

                    var actionStatus = SystemActionStatus.None;
                    try
                    {
                        var inputData = SystemActionHelper.FromStr <UpdateRatesInput>(action.InputData);
                        var orderId   = inputData.OrderId;
                        if (!orderId.HasValue && !String.IsNullOrEmpty(inputData.OrderNumber))
                        {
                            var order = db.Orders.GetByOrderNumber(inputData.OrderNumber);
                            orderId = order.Id;
                        }

                        if (orderId.HasValue)
                        {
                            var orderIdList            = new long[] { orderId.Value };
                            IList <DTOOrder> dtoOrders = db.ItemOrderMappings.GetSelectedOrdersWithItems(_weightService, orderIdList, includeSourceItems: true).ToList();

                            foreach (var dtoOrder in dtoOrders)
                            {
                                //Ignore shipped orders
                                if ((dtoOrder.Market != (int)MarketType.eBay &&
                                     ShippingUtils.IsOrderShipped(dtoOrder.OrderStatus)) ||
                                    dtoOrder.ShippingInfos.Any(s => !String.IsNullOrEmpty(s.LabelPath))

                                    || dtoOrder.BatchId.HasValue) //NOTE: SKip orders in batch
                                {
                                    actionStatus = SystemActionStatus.Skipped;
                                }
                                else
                                {
                                    var markets = new MarketplaceKeeper(_dbFactory, false);
                                    markets.Init();
                                    var companyAddress = new CompanyAddressService(_company, markets.GetAll());
                                    var synchronizer   = new AmazonOrdersSynchronizer(_log,
                                                                                      _company,
                                                                                      syncInfo,
                                                                                      _rateProviders,
                                                                                      companyAddress,
                                                                                      _time,
                                                                                      _weightService,
                                                                                      _messageService);
                                    if (!synchronizer.UIUpdate(db, dtoOrder, false, false, keepCustomShipping: false, switchToMethodId: null))
                                    {
                                        actionStatus = SystemActionStatus.Fail;
                                    }
                                    else
                                    {
                                        actionStatus = SystemActionStatus.Done;
                                    }
                                }
                            }

                            _log.Info("Order rates was recalculated, actionId=" + action.Id + ", status=" + actionStatus);
                        }
                        else
                        {
                            actionStatus = SystemActionStatus.NotFoundEntity;
                            _log.Info("Can't find order, actionId=" + action.Id + ", orderId=" + inputData.OrderId + ", orderNumber=" + inputData.OrderNumber);
                        }
                    }
                    catch (Exception ex)
                    {
                        _log.Error("Fail recalculate order rates action, actionId=" + action.Id, ex);
                        actionStatus = SystemActionStatus.Fail;
                    }

                    _actionService.SetResult(db,
                                             action.Id,
                                             actionStatus,
                                             null,
                                             null);
                }

                db.Commit();
            }
        }
        public virtual ActionResult ReCalcShippingService(long batchId,
                                                          string orderIds,
                                                          int?switchToProviderId,
                                                          int?switchToMethodId)
        {
            LogI("ReCalcShippingService begin, orderIds=" + orderIds);

            IList <string> failedUpdate  = new List <string>();
            IList <string> successUpdate = new List <string>();

            if (!string.IsNullOrEmpty(orderIds))
            {
                var stringOrderIdList = orderIds.Split(", ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                var orderIdList       = stringOrderIdList.Select(long.Parse).ToArray();
                var rateProviders     = ServiceFactory.GetShipmentProviders(LogService,
                                                                            Time,
                                                                            DbFactory,
                                                                            WeightService,
                                                                            AccessManager.Company.ShipmentProviderInfoList,
                                                                            null,
                                                                            null,
                                                                            null,
                                                                            null);

                var syncInfo = new EmptySyncInformer(LogService, SyncType.Orders);

                IList <DTOOrder> dtoOrders = Db.ItemOrderMappings.GetSelectedOrdersWithItems(WeightService, orderIdList, includeSourceItems: true).ToList();
                foreach (var dtoOrder in dtoOrders)
                {
                    //Ignore shipped orders
                    if ((dtoOrder.Market != (int)MarketType.eBay && ShippingUtils.IsOrderShipped(dtoOrder.OrderStatus)) ||
                        dtoOrder.ShippingInfos.Any(s => !String.IsNullOrEmpty(s.LabelPath)))
                    {
                        failedUpdate.Add(dtoOrder.OrderId);
                        continue;
                    }

                    if (switchToProviderId.HasValue &&
                        dtoOrder.ShipmentProviderType != switchToProviderId.Value)
                    {
                        var skipChanges = false;
                        if (switchToProviderId == (int)ShipmentProviderType.FedexOneRate)
                        {
                            if (ShippingUtils.IsInternational(dtoOrder.FinalShippingCountry))
                            {
                                skipChanges = true;
                            }
                        }

                        if (!skipChanges)
                        {
                            var dbOrder = Db.Orders.Get(dtoOrder.Id);
                            dbOrder.ShipmentProviderType = switchToProviderId.Value;
                            Db.Commit();
                            dtoOrder.ShipmentProviderType = switchToProviderId.Value;
                        }
                    }

                    var synchronizer = new AmazonOrdersSynchronizer(LogService,
                                                                    AccessManager.Company,
                                                                    syncInfo,
                                                                    rateProviders,
                                                                    CompanyAddress,
                                                                    Time,
                                                                    WeightService,
                                                                    MessageService);

                    if (synchronizer.UIUpdate(Db, dtoOrder, false, false, keepCustomShipping: false, switchToMethodId: switchToMethodId))
                    {
                        successUpdate.Add(dtoOrder.OrderId);
                    }
                    else
                    {
                        failedUpdate.Add(dtoOrder.OrderId);
                    }
                }
            }
            LogI("ReCalcShippingService result, failedUpdate=" + String.Join(", ", failedUpdate)
                 + ", successUpdate=" + String.Join(", ", successUpdate));

            return(new JsonResult
            {
                Data = ValueResult <IList <string> > .Success("", new List <string>() { String.Join(", ", failedUpdate), String.Join(", ", successUpdate) }),
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
        public void SwitchToECommerce()
        {
            var syncInfo       = new EmptySyncInformer(_log, SyncType.Orders);
            var serviceFactory = new ServiceFactory();
            var rateProviders  = serviceFactory.GetShipmentProviders(_log,
                                                                     _time,
                                                                     _dbFactory,
                                                                     _weightService,
                                                                     _company.ShipmentProviderInfoList,
                                                                     null,
                                                                     null,
                                                                     null,
                                                                     null);
            var companyAddress = new CompanyAddressService(_company);

            var synchronizer = new AmazonOrdersSynchronizer(_log,
                                                            _company,
                                                            syncInfo,
                                                            rateProviders,
                                                            companyAddress,
                                                            _time,
                                                            _weightService,
                                                            _messageService);

            var toSwitchNumber = 100;

            using (var db = _dbFactory.GetRWDb())
            {
                //Caclulate correction number
                var correctionNumber = 0;
                var fromDate         = DateHelper.GetStartOfWeek(_time.GetAppNowTime());
                var toDate           = _time.GetAppNowTime().Date;
                var shippingQuery    = from o in db.Orders.GetAll()
                                       join sh in db.OrderShippingInfos.GetAllAsDto() on o.Id equals sh.OrderId
                                       where sh.ShipmentProviderType == (int)ShipmentProviderType.DhlECom &&
                                       o.OrderStatus == OrderStatusEnumEx.Shipped &&
                                       sh.LabelPurchaseDate >= fromDate &&
                                       sh.LabelPurchaseDate <= toDate &&
                                       sh.IsActive
                                       select sh.Id;

                var shippedCount = shippingQuery.Count();
                var workDayCount = _time.GetBizDaysCount(fromDate, _time.GetAppNowTime());
                correctionNumber = workDayCount * 100 - shippedCount;
                if (correctionNumber > 100)
                {
                    correctionNumber = 0;
                }

                toSwitchNumber += correctionNumber;
                _log.Info("To switch number=" + correctionNumber);

                IList <DTOOrder> dtoOrders = db.ItemOrderMappings.GetFilteredOrdersWithItems(_weightService,
                                                                                             new OrderSearchFilter()
                {
                    OrderStatus = OrderStatusEnumEx.AllUnshipped
                }).ToList();    // orderIds.ToArray(), includeSourceItems: true).ToList();

                //STEP 1. Switch all stamps firstclass orders
                var switchedCount = (from o in db.Orders.GetAll()
                                     join sh in db.OrderShippingInfos.GetAllAsDto() on o.Id equals sh.OrderId
                                     where sh.ShipmentProviderType == (int)ShipmentProviderType.DhlECom &&
                                     o.OrderStatus == OrderStatusEnumEx.Unshipped &&
                                     sh.IsActive
                                     select sh.Id).Count();

                foreach (var dtoOrder in dtoOrders)
                {
                    if (dtoOrder.ShipmentProviderType == (int)ShipmentProviderType.Stamps &&
                        dtoOrder.ShippingInfos.Where(sh => sh.IsActive)
                        .All(sh => sh.ShippingMethodId == ShippingUtils.FirstClassShippingMethodId))
                    {
                        _log.Info("Change provider for order: " + dtoOrder.OrderId + ", from=" + dtoOrder.ShipmentProviderType);
                        var order = db.Orders.GetById(dtoOrder.Id);
                        order.ShipmentProviderType = (int)ShipmentProviderType.DhlECom;
                        db.Commit();
                        dtoOrder.ShipmentProviderType = (int)ShipmentProviderType.DhlECom;

                        if (synchronizer.UIUpdate(db, dtoOrder, false, false, false, switchToMethodId: null))
                        {
                            switchedCount++;
                            _log.Info("Success");
                        }
                        else
                        {
                            _log.Info("Failed");
                        }
                    }
                }

                var amazonOrderToSwitch = toSwitchNumber - switchedCount;
                foreach (var dtoOrder in dtoOrders)
                {
                    _log.Info("Change provider for order: " + dtoOrder.OrderId + ", from=" + dtoOrder.ShipmentProviderType);

                    if (amazonOrderToSwitch > 0)
                    {
                        if (dtoOrder.ShipmentProviderType == (int)ShipmentProviderType.Amazon &&
                            dtoOrder.ShippingInfos.Where(sh => sh.IsActive)
                            .All(sh => sh.ShippingMethodId == ShippingUtils.AmazonFirstClassShippingMethodId))
                        {
                            var order = db.Orders.GetById(dtoOrder.Id);
                            order.ShipmentProviderType = (int)ShipmentProviderType.DhlECom;
                            db.Commit();
                            dtoOrder.ShipmentProviderType = (int)ShipmentProviderType.DhlECom;

                            if (synchronizer.UIUpdate(db, dtoOrder, false, false, false, null))
                            {
                                switchedCount++;
                                amazonOrderToSwitch--;
                                _log.Info("Success");
                            }
                            else
                            {
                                _log.Info("Failed");
                            }
                        }
                    }
                }

                _emailService.SendSystemEmailToAdmin("Dhl eCommerce, switched count: " + switchedCount,
                                                     "Correction count: " + correctionNumber + ", should switched: " + toSwitchNumber);
            }
        }
        public virtual ActionResult Submit(OrderEditViewModel model)
        {
            LogI("Submit, model=" + model);

            //Save
            if (ModelState.IsValid)
            {
                var company          = AccessManager.Company;
                var serviceFactory   = new ServiceFactory();
                var addressProviders = AccessManager.Company.AddressProviderInfoList
                                       .Where(a => a.Type != (int)AddressProviderType.SelfCorrection)
                                       .ToList(); //NOTE: exclude self correction
                var addressCheckService = serviceFactory.GetAddressCheckServices(LogService,
                                                                                 Time,
                                                                                 DbFactory,
                                                                                 addressProviders);

                var companyAddress = new CompanyAddressService(company);
                var addressService = new AddressService(addressCheckService, companyAddress.GetReturnAddress(MarketIdentifier.Empty()), companyAddress.GetPickupAddress(MarketIdentifier.Empty()));
                var addressChecker = new AddressChecker(LogService, DbFactory, addressService, OrderHistoryService, Time);

                //var validatorService = new OrderValidatorService(LogService,
                //    DbFactory,
                //    EmailService,
                //    OrderHistoryService,
                //    ActionService,
                //    HtmlScraper,
                //    addressService,
                //    null,
                //    null,
                //    Time,
                //    AccessManager.Company);
                var rateProviders = ServiceFactory.GetShipmentProviders(LogService,
                                                                        Time,
                                                                        DbFactory,
                                                                        WeightService,
                                                                        AccessManager.Company.ShipmentProviderInfoList,
                                                                        null,
                                                                        null,
                                                                        null,
                                                                        null);
                var syncInfo     = new EmptySyncInformer(LogService, SyncType.Orders);
                var synchronizer = new AmazonOrdersSynchronizer(LogService,
                                                                AccessManager.Company,
                                                                syncInfo,
                                                                rateProviders,
                                                                CompanyAddress,
                                                                Time,
                                                                WeightService,
                                                                MessageService);

                var applyResult = model.Apply(LogService, Db, OrderHistoryService, QuantityManager, Time.GetAppNowTime(), AccessManager.UserId);

                var resultErrors = model.ProcessApplyResult(applyResult,
                                                            Db,
                                                            LogService,
                                                            Time,
                                                            synchronizer,
                                                            addressChecker,
                                                            OrderHistoryService,
                                                            WeightService,
                                                            AccessManager.UserId);

                if (resultErrors.Any())
                {
                    resultErrors.ForEach(r => ModelState.AddModelError(r.Key, r.Message));
                    return(PartialView("OrderEdit", model));
                }

                var rowOrderDto = Db.ItemOrderMappings.GetOrderWithItems(WeightService, model.EntityId, false, true, unmaskReferenceStyles: true); //NOTE: Unmask for display
                var rowModel    = new OrderViewModel(rowOrderDto, AccessManager.IsFulfilment);
                rowModel.Items = rowOrderDto.Items.Select(i =>
                                                          new OrderItemViewModel(i,
                                                                                 rowOrderDto.OnHold,
                                                                                 ShippingUtils.IsOrderPartial(rowOrderDto.OrderStatus))).ToList();

                return(Json(new UpdateRowViewModel(rowModel,
                                                   model.BatchId.HasValue ? "grid_" + model.BatchId.Value : "grid",
                                                   null,
                                                   false)));
            }
            return(PartialView("OrderEdit", model));
        }