示例#1
0
        public void SyncOrders(SupplieroasisApi api)
        {
            var coreApi         = new Mock <ISupplieroasisCoreApi>(MockBehavior.Strict);
            var asinsWithErrors = new List <string>();

            coreApi.Setup(p => p.GetOrders(It.IsAny <DateTime>(), It.IsAny <DateTime>())).Returns((DateTime d1, DateTime d2) =>
            {
                using (var sr = new StringReader(File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Files/OverstockSampleResponses/overstock_get_orders_response.xml"))))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(GetOrdersResponse));
                    return(CallResult <GetOrdersResponse> .Success((GetOrdersResponse)serializer.Deserialize(sr)));
                }
            });
            api.OverrideCoreApi(coreApi.Object);

            var syncInfo = new DbSyncInformer(_dbFactory,
                                              _log,
                                              _time,
                                              SyncType.Orders,
                                              api.MarketplaceId,
                                              api.Market,
                                              String.Empty);
            var settings             = new SettingsService(_dbFactory);
            var dbFactory            = new DbFactory();
            var quantityManager      = new QuantityManager(_log, _time);
            var priceService         = new PriceService(dbFactory);
            var companyAddressList   = new CompanyAddressService(_company, null);
            var serviceFactory       = new ServiceFactory();
            var addressCheckServices = serviceFactory.GetAddressCheckServices(_log,
                                                                              _time,
                                                                              dbFactory,
                                                                              _company.AddressProviderInfoList);
            var addressService = new AddressService(addressCheckServices,
                                                    companyAddressList.GetReturnAddress(MarketIdentifier.Empty()),
                                                    companyAddressList.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 orderHistoryService = new OrderHistoryService(_log, _time, _dbFactory);
            var validatorService    = new OrderValidatorService(_log,
                                                                _dbFactory,
                                                                _emailService,
                                                                settings,
                                                                orderHistoryService,
                                                                _actionService,
                                                                priceService,
                                                                _htmlScraper,
                                                                addressService,
                                                                companyAddressList.GetReturnAddress(MarketIdentifier.Empty()),
                                                                stampsRateProvider,
                                                                _time,
                                                                _company);

            var actionService = new SystemActionService(_log, _time);
            var cacheService  = new CacheService(_log, _time, actionService, quantityManager);

            using (var db = _dbFactory.GetRWDb())
            {
                //if (!syncInfo.IsSyncInProgress())
                {
                    try
                    {
                        syncInfo.SyncBegin(null);

                        var orderSyncFactory = new OrderSyncFactory();
                        var synchronizer     = orderSyncFactory.GetForMarket(api,
                                                                             _log,
                                                                             _company,
                                                                             settings,
                                                                             syncInfo,
                                                                             rateProviders,
                                                                             quantityManager,
                                                                             _emailService,
                                                                             validatorService,
                                                                             orderHistoryService,
                                                                             cacheService,
                                                                             _actionService,
                                                                             companyAddressList,
                                                                             _time,
                                                                             _weightService,
                                                                             _messageService);

                        //if (!String.IsNullOrEmpty(orderNumber))
                        //    synchronizer.ProcessSpecifiedOrder(db, orderNumber);
                        //else
                        synchronizer.Sync(Core.Models.Orders.OrderSyncModes.Full, null);
                    }
                    finally
                    {
                        syncInfo.SyncEnd();
                    }
                }
            }
        }
示例#2
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));
                }
            }
        }
示例#3
0
        protected override void RunCallback()
        {
            _api.Connect();

            var dbFactory = new DbFactory();
            var time      = new TimeService(dbFactory);
            var log       = GetLogger();

            var syncInfo = new DbSyncInformer(dbFactory,
                                              log,
                                              time,
                                              SyncType.Orders,
                                              _api.MarketplaceId,
                                              _market,
                                              String.Empty);

            using (var db = dbFactory.GetRWDb())
            {
                var serviceFactory = new ServiceFactory();

                var settings       = new SettingsService(dbFactory);
                var company        = db.Companies.GetByIdWithSettingsAsDto(CompanyId);
                var companyAddress = new CompanyAddressService(company);

                var shipmentProviders = company.ShipmentProviderInfoList;
                var addressProviders  = company.AddressProviderInfoList;

                var addressCheckServiceList = serviceFactory.GetAddressCheckServices(log,
                                                                                     time,
                                                                                     dbFactory,
                                                                                     addressProviders);
                var addressService = new AddressService(addressCheckServiceList, companyAddress.GetReturnAddress(MarketIdentifier.Empty()), companyAddress.GetPickupAddress(MarketIdentifier.Empty()));

                var actionService   = new SystemActionService(log, time);
                var priceService    = new PriceService(dbFactory);
                var quantityManager = new QuantityManager(log, time);
                var emailService    = new EmailService(log,
                                                       SettingsBuilder.GetSmtpSettingsFromCompany(company, AppSettings.IsDebug, AppSettings.IsSampleLabels),
                                                       addressService);

                var weightService  = new WeightService();
                var messageService = new SystemMessageService(log, time, dbFactory);

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

                var htmlScraper         = new HtmlScraperService(log, time, dbFactory);
                var orderHistoryService = new OrderHistoryService(log, time, dbFactory);
                var validatorService    = new OrderValidatorService(log,
                                                                    dbFactory,
                                                                    emailService,
                                                                    settings,
                                                                    orderHistoryService,
                                                                    actionService,
                                                                    priceService,
                                                                    htmlScraper,
                                                                    addressService,
                                                                    companyAddress.GetReturnAddress(MarketIdentifier.Empty()),
                                                                    rateProviders.FirstOrDefault(r => r.Type == ShipmentProviderType.Stamps),
                                                                    time,
                                                                    company);

                var cacheService = new CacheService(log, time, actionService, quantityManager);

                var orderSyncFactory = new OrderSyncFactory();

                if (settings.GetOrdersSyncEnabled() != false)
                {
                    if (!syncInfo.IsSyncInProgress()) //NOTE: for now it a few minutes ~10
                    {
                        if (!IsPrintLabelsInProgress(db, actionService, time))
                        {
                            try
                            {
                                var marketplaceId = _api.MarketplaceId;

                                LogWrite("Set OrderSyncInProgress");
                                syncInfo.SyncBegin(null);

                                var synchronizer = orderSyncFactory.GetForMarket(_api,
                                                                                 GetLogger(),
                                                                                 company,
                                                                                 settings,
                                                                                 syncInfo,
                                                                                 rateProviders,
                                                                                 quantityManager,
                                                                                 emailService,
                                                                                 validatorService,
                                                                                 orderHistoryService,
                                                                                 cacheService,
                                                                                 actionService,
                                                                                 companyAddress,
                                                                                 time,
                                                                                 weightService,
                                                                                 messageService);

                                var isFullSync = !_lastFullSync.HasValue || (time.GetUtcTime() - _lastFullSync) > _fullSyncInterval;

                                var syncResult = synchronizer.Sync(isFullSync ? OrderSyncModes.Full : OrderSyncModes.Fast, CancellationToken);

                                if (isFullSync)
                                {
                                    _lastFullSync = time.GetUtcTime();
                                }

                                var statusList = new List <string>()
                                {
                                    OrderStatusEnum.Unshipped.Str()
                                };
                                if (_market == MarketType.Walmart ||
                                    _market == MarketType.WalmartCA)
                                {
                                    statusList.Add(OrderStatusEnum.Pending.Str());
                                }

                                var dbOrderIdList = (from o in db.Orders.GetAll()
                                                     join sh in db.OrderShippingInfos.GetAll() on o.Id equals sh.OrderId
                                                     where (sh.IsActive || sh.IsVisible) &&
                                                     statusList.Contains(o.OrderStatus) &&
                                                     o.Market == (int)_market &&
                                                     (o.MarketplaceId == marketplaceId || String.IsNullOrEmpty(marketplaceId))
                                                     select o.AmazonIdentifier).Distinct().ToList();
                                //var dbOrders = db.ItemOrderMappings.GetOrdersWithItemsByStatus(weightService, statusList.ToArray(), _market, marketplaceId).ToList();
                                //dbOrders = dbOrders.Where(o => o.ShippingInfos != null && o.ShippingInfos.Any(sh => sh.IsActive || sh.IsVisible)).ToList();


                                var unshippedMarketOrderIdList = syncResult.ProcessedOrders
                                                                 .Where(o => statusList.Contains(o.OrderStatus))
                                                                 .Select(o => o.OrderId)
                                                                 .ToList();

                                if (syncResult.SkippedOrders != null)
                                {
                                    unshippedMarketOrderIdList.AddRange(syncResult.SkippedOrders
                                                                        .Where(o => statusList.Contains(o.OrderStatus))
                                                                        .Select(o => o.OrderId)
                                                                        .ToList());
                                }

                                unshippedMarketOrderIdList = unshippedMarketOrderIdList.Distinct().ToList();

                                //var dbOrderIdList = dbOrders.Select(o => o.OrderId).Distinct().ToList();
                                LogDiffrents(unshippedMarketOrderIdList, dbOrderIdList, "Missing order: ");

                                if (unshippedMarketOrderIdList.Count != dbOrderIdList.Count ||
                                    !syncResult.IsSuccess)
                                {
                                    emailService.SendSystemEmailToAdmin("PA Orders Sync has issue",
                                                                        "Market: " + _api.Market + " - " + _api.MarketplaceId + "<br/>" +
                                                                        "Sync message: " + syncResult.Message + "<br/>" +
                                                                        "Missing orders: " + (unshippedMarketOrderIdList.Count - dbOrderIdList.Count));
                                }

                                //NOTE: otherwise if we have missed order (older than 2 hours that was hidden in next lite iteration)
                                if (isFullSync)
                                {
                                    settings.SetOrderCountOnMarket(unshippedMarketOrderIdList.Count, _market, marketplaceId);
                                    settings.SetOrderCountInDB(dbOrderIdList.Count, _market, marketplaceId);
                                }

                                if (syncResult.IsSuccess)
                                {
                                    settings.SetOrderSyncDate(time.GetUtcTime(), _market, marketplaceId);
                                }
                            }
                            catch (Exception ex)
                            {
                                emailService.SendSystemEmailToAdmin("PA Orders Sync has error",
                                                                    "Market: " + _api.Market + " - " + _api.MarketplaceId + "<br/>" +
                                                                    "Sync message: " + ExceptionHelper.GetAllMessages(ex));
                                LogError("RunCallback", ex);
                            }
                            finally
                            {
                                syncInfo.SyncEnd();
                            }
                        }
                        else
                        {
                            LogWrite("Labels printing in-progress");
                        }
                    }
                    else
                    {
                        LogWrite("Order Sync already runned");
                    }
                }
            }
        }