public void CallRedistributeQuantity(IList <string> styleIdList)
        {
            var settings               = new SettingsService(_dbFactory);
            var quantityManager        = new QuantityManager(_log, _time);
            var qtyDistributionService = new QuantityDistributionService(_dbFactory,
                                                                         quantityManager,
                                                                         _log,
                                                                         _time,
                                                                         QuantityDistributionHelper.GetDistributionMarkets(),
                                                                         DistributeMode.None);

            using (var db = _dbFactory.GetRWDb())
            {
                db.DisableValidation();
                if (!styleIdList.Any())
                {
                    qtyDistributionService.Redistribute(db);
                }
                else
                {
                    var style    = db.Styles.GetAllActiveAsDto().Where(st => styleIdList.Contains(st.StyleID)).ToList();
                    var styleIds = style.Select(st => st.Id).ToList();
                    qtyDistributionService.RedistributeForStyle(db, styleIds);
                }
            }
        }
        public virtual JsonResult GenerateOpenBox(long styleId)
        {
            LogI("GenerateOpenBox, styleId=" + styleId);

            var messages = new List <MessageString>();

            StyleQuantityViewModel.ValidateGenerateOpenBox(Db, styleId, out messages);
            if (!messages.Any())
            {
                var quantityManager = new QuantityManager(LogService, Time);
                StyleQuantityViewModel.GenerateOpenBox(Db,
                                                       Cache,
                                                       quantityManager,
                                                       styleId,
                                                       Time.GetAppNowTime(),
                                                       AccessManager.UserId);

                return(JsonGet(new MessagesResult(true)));
            }
            else
            {
                return(JsonGet(new MessagesResult(false)
                {
                    Messages = messages
                }));
            }
        }
Esempio n. 3
0
        protected override void RunCallback()
        {
            var dbFactory       = new DbFactory();
            var time            = new TimeService(dbFactory);
            var settings        = new SettingsService(dbFactory);
            var actionService   = new SystemActionService(GetLogger(), time);
            var quantityManager = new QuantityManager(GetLogger(), time);
            var cache           = new CacheService(GetLogger(), time, actionService, quantityManager);

            using (var db = dbFactory.GetRWDb())
            {
                db.DisableValidation();

                var lastUpdate    = settings.GetCacheUpdateDate();
                var updateInteval = settings.CacheUpdateInteval;

                if (lastUpdate + updateInteval < time.GetUtcTime())
                {
                    //Full update
                    if (cache.UpdateDbCacheUsingSettings(db, settings))
                    {
                        settings.SetCacheUpdateDate(time.GetUtcTime());
                    }
                    else
                    {
                        GetLogger().Fatal("Cache updating fails");
                    }
                }
                else
                {
                    //Process cache update actions
                    cache.ProcessUpdateCacheActions(db);
                }
            }
        }
        protected override void RunCallback()
        {
            CompanyDTO company   = null;
            var        dbFactory = new DbFactory();
            var        time      = new TimeService(dbFactory);
            var        log       = GetLogger();

            var now = time.GetAppNowTime();

            if (!time.IsBusinessDay(now))
            {
                return;
            }

            using (var db = dbFactory.GetRDb())
            {
                company = db.Companies.GetByIdWithSettingsAsDto(CompanyId);
            }

            var companyAddress     = new CompanyAddressService(company);
            var quantityManager    = new QuantityManager(log, time);
            var actionService      = new SystemActionService(log, time);
            var addressService     = new AddressService(null, companyAddress.GetReturnAddress(MarketIdentifier.Empty()), companyAddress.GetPickupAddress(MarketIdentifier.Empty()));
            var emailSmtpSettings  = SettingsBuilder.GetSmtpSettingsFromCompany(company, AppSettings.IsDebug, AppSettings.IsSampleLabels);
            var emailService       = new EmailService(GetLogger(), emailSmtpSettings, addressService);
            var cacheService       = new CacheService(log, time, actionService, quantityManager);
            var barcodeService     = new BarcodeService(log, time, dbFactory);
            var itemHistoryService = new ItemHistoryService(log, time, dbFactory);

            var autoCreateWMListingService = new AutoCreateWalmartListingService(log,
                                                                                 time,
                                                                                 dbFactory,
                                                                                 cacheService,
                                                                                 barcodeService,
                                                                                 emailService,
                                                                                 null,
                                                                                 itemHistoryService,
                                                                                 AppSettings.IsDebug);
            var autoCreateEBayListingService = new AutoCreateEBayListingService(log,
                                                                                time,
                                                                                dbFactory,
                                                                                cacheService,
                                                                                barcodeService,
                                                                                emailService,
                                                                                itemHistoryService,
                                                                                AppSettings.IsDebug);
            var autoCreateAmazonUSPrimeService = new AutoCreateAmazonUSPrimeListingService(log,
                                                                                           time,
                                                                                           dbFactory,
                                                                                           itemHistoryService);

            //autoCreateWMListingService.CreateListings();
            //log.Info("Walmart listings were created");

            //autoCreateEBayListingService.CreateListings();
            //log.Info("eBay listings were created");

            autoCreateAmazonUSPrimeService.CreateListings();
            log.Info("Amazon US Prime listings were created");
        }
Esempio n. 5
0
        public virtual ActionResult QuickPrintReturnLabel(string orderNumber,
                                                          int shippingMethodId)
        {
            var companyAddress = new CompanyAddressService(AccessManager.Company);

            var model = MailViewModel.GetByOrderId(Db, WeightService, orderNumber);

            model.IsAddressSwitched      = true;
            model.FromAddress            = model.ToAddress;
            model.ToAddress              = MailViewModel.GetFromAddress(companyAddress.GetReturnAddress(MarketIdentifier.Empty()), MarketplaceType.Amazon);
            model.ShipmentProviderId     = (int)ShipmentProviderType.Stamps;
            model.ReasonCode             = (int)MailLabelReasonCodes.ReturnLabelReasonCode;
            model.OrderComment           = "Return label was generated by " + AccessManager.User.Name;
            model.ShippingMethodSelected = shippingMethodId;

            var shipmentProviders = ServiceFactory.GetShipmentProviders(LogService,
                                                                        Time,
                                                                        DbFactory,
                                                                        WeightService,
                                                                        AccessManager.ShipmentProviderInfoList,
                                                                        AppSettings.DefaultCustomType,
                                                                        AppSettings.LabelDirectory,
                                                                        AppSettings.ReserveDirectory,
                                                                        AppSettings.TemplateDirectory);

            var labelService    = new LabelService(shipmentProviders, LogService, Time, DbFactory, EmailService, PdfMaker, AddressService);
            var quantityManager = new QuantityManager(LogService, Time);

            var results = model.Generate(LogService,
                                         Time,
                                         labelService,
                                         quantityManager,
                                         Db,
                                         WeightService,
                                         ShippingService,
                                         AppSettings.IsSampleLabels,
                                         Time.GetAppNowTime(),
                                         AccessManager.UserId);

            if (!String.IsNullOrEmpty(model.PrintedLabelUrl))
            {
                results.Insert(0, new MessageString()
                {
                    Message = "Label has been successfully printed, tracking number: " + model.PrintedTrackingNumber
                              + " <a href='" + model.PrintedLabelUrl + "' target='_blank'>download</a>",
                    Status = MessageStatus.Success
                });
            }

            return(JsonGet(new ValueMessageResult <EmailAttachmentViewModel>()
            {
                IsSuccess = !String.IsNullOrEmpty(model.PrintedLabelUrl),
                Data = new EmailAttachmentViewModel()
                {
                    ServerFileName = model.PrintedLabelPath,
                    ViewUrl = model.PrintedLabelUrl,
                },
                Messages = results
            }));
        }
        public virtual JsonResult Redistribute(long styleId)
        {
            LogI("Redistribute, styleId=" + styleId);
            try
            {
                var quantityManager = new QuantityManager(LogService, Time);
                var service         = new QuantityDistributionService(DbFactory,
                                                                      quantityManager,
                                                                      LogService,
                                                                      Time,
                                                                      QuantityDistributionHelper.GetDistributionMarkets(),
                                                                      DistributeMode.None);
                var listings = service.RedistributeForStyle(Db, styleId);

                return(new JsonResult()
                {
                    Data = ValueResult <IList <ListingQuantityDTO> > .Success("Quantity was redistributed", listings),
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                });
            }
            catch (Exception ex)
            {
                LogE("Redistribute, styleId=" + styleId, ex);
                return(new JsonResult()
                {
                    Data = MessageResult.Error(ex.Message),
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                });
            }
        }
Esempio n. 7
0
        protected override void RunCallback()
        {
            var        dbFactory = new DbFactory();
            var        time      = new TimeService(dbFactory);
            var        log       = GetLogger();
            CompanyDTO company;

            using (var db = dbFactory.GetRDb())
            {
                company = db.Companies.GetByIdWithSettingsAsDto(CompanyId);
            }

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

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

            var actionService = new SystemActionService(log, time);

            var commentService = new OrderCommentService(dbFactory,
                                                         log,
                                                         time,
                                                         actionService);

            commentService.ProcessSystemAction();

            var rateService = new RateService(dbFactory,
                                              log,
                                              time,
                                              weightService,
                                              messageService,
                                              company,
                                              actionService,
                                              rateProviders);

            rateService.ProcessSystemAction(CancellationToken);


            var quantityDistribution = new QuantityDistributionService(dbFactory,
                                                                       quantityManager,
                                                                       log,
                                                                       time,
                                                                       QuantityDistributionHelper.GetDistributionMarkets(),
                                                                       DistributeMode.None);

            quantityDistribution.ProcessSystemAction(actionService);
        }
Esempio n. 8
0
        public virtual ActionResult Generate(MailViewModel model)
        {
            LogI("Index, model=" + model);

            if (ModelState.IsValid)
            {
                model.OrderID = model.OrderID.RemoveWhitespaces();
                if (model.IsAddressSwitched)
                {
                    model.ToAddress.IsVerified = true;
                }
                else
                {
                    model.FromAddress.IsVerified = true;
                }


                var shipmentProviders = ServiceFactory.GetShipmentProviders(LogService,
                                                                            Time,
                                                                            DbFactory,
                                                                            WeightService,
                                                                            AccessManager.ShipmentProviderInfoList,
                                                                            AppSettings.DefaultCustomType,
                                                                            AppSettings.LabelDirectory,
                                                                            AppSettings.ReserveDirectory,
                                                                            AppSettings.TemplateDirectory);

                var labelService    = new LabelService(shipmentProviders, LogService, Time, DbFactory, EmailService, PdfMaker, AddressService);
                var quantityManager = new QuantityManager(LogService, Time);

                var results = model.Generate(LogService,
                                             Time,
                                             labelService,
                                             quantityManager,
                                             Db,
                                             WeightService,
                                             ShippingService,
                                             AppSettings.IsSampleLabels,
                                             Time.GetAppNowTime(),
                                             AccessManager.UserId);

                model.Messages.AddRange(results);
            }
            else
            {
                model.Messages.AddRange(ModelState.GetErrors().Select(m => MessageString.Error(m)));
            }

            LogI("Index, Generate results=");
            model.Messages.ForEach(m => LogI(m.Status + ": " + m.Message));

            return(new JsonResult {
                Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
        public void CallCheckQty()
        {
            var settings   = new SettingsService(_dbFactory);
            var qtyManager = new QuantityManager(_log, _time);

            using (var db = _dbFactory.GetRWDb())
            {
                db.DisableValidation();

                qtyManager.FixupListingQuantity(db, settings);
            }
        }
        public virtual ActionResult Submit(StyleQuantityViewModel model)
        {
            LogI("Submit, model=" + model);

            //Save
            if (ModelState.IsValid)
            {
                var quantityManager = new QuantityManager(LogService, Time);

                model.Apply(Db,
                            Cache,
                            quantityManager,
                            StyleHistoryService,
                            SystemActions,
                            Time.GetAppNowTime(),
                            AccessManager.UserId);

                var outputModel = StyleViewModel.GetAll(Db, new StyleSearchFilterViewModel()
                {
                    StyleId = model.StyleId
                }).Items?.FirstOrDefault();

                return(Json(new UpdateRowViewModel(outputModel,
                                                   "Styles",
                                                   new[]
                {
                    "UsedBoxQuantity",
                    "HasManuallyQuantity",
                    "ManuallyQuantity",
                    "RemainingQuantity",
                    "TotalQuantity",
                    "BoxQuantity",
                    "InventoryQuantity",
                    "MarketsSoldQuantity",
                    "ScannedSoldQuantity",
                    "SentToFBAQuantity",
                    "SpecialCaseQuantity",
                    "TotalMarketsSoldQuantity",
                    "TotalScannedSoldQuantity",
                    "TotalSentToFBAQuantity",
                    "TotalSpecialCaseQuantity",
                    "QuantityModeName",
                    "StyleItemCaches",
                },
                                                   false)));
            }
            return(View(PopupContentView, model));
        }
Esempio n. 11
0
        protected override void RunCallback()
        {
            var dbFactory       = new DbFactory();
            var time            = new TimeService(dbFactory);
            var settings        = new SettingsService(dbFactory);
            var quantityManager = new QuantityManager(GetLogger(), time);

            using (var db = dbFactory.GetRWDb())
            {
                var service = new QuantityDistributionService(dbFactory,
                                                              quantityManager,
                                                              GetLogger(),
                                                              time,
                                                              QuantityDistributionHelper.GetDistributionMarkets(),
                                                              DistributeMode.None);
                service.Redistribute(db);

                settings.SetQuantityDistributeDate(time.GetAppNowTime());
            }
        }
Esempio n. 12
0
        protected override void RunCallback()
        {
            var dbFactory = new DbFactory();
            var time      = new TimeService(dbFactory);

            var log             = GetLogger();
            var settings        = new SettingsService(dbFactory);
            var actionService   = new SystemActionService(GetLogger(), time);
            var quantityManager = new QuantityManager(GetLogger(), time);
            var cache           = new CacheService(GetLogger(), time, actionService, quantityManager);

            var manageService = new ManageService(log, dbFactory, actionService);

            using (var db = dbFactory.GetRWDb())
            {
                db.DisableValidation();

                //Process cache update actions
                manageService.ProcessRestartActions();
            }
        }
        public virtual ActionResult MergeStyleItems(long toStyleItemId,
                                                    long fromStyleItemId)
        {
            LogI("MergeStyleItems, toStyleItemId=" + toStyleItemId + ", fromStyleItemId=" + fromStyleItemId);

            var quantityManager = new QuantityManager(LogService, Time);

            var result = StyleViewModel.MergeStyleItems(Db,
                                                        LogService,
                                                        Cache,
                                                        quantityManager,
                                                        toStyleItemId,
                                                        fromStyleItemId,
                                                        Time.GetAppNowTime(),
                                                        AccessManager.UserId);

            return(JsonGet(new MessagesResult()
            {
                IsSuccess = result.Status == CallStatus.Success,
                Messages = result.Messages
            }));
        }
Esempio n. 14
0
        public virtual ActionResult Submit(QuantityOperationViewModel model)
        {
            LogI("Submit, model=" + model);

            //Save
            if (ModelState.IsValid)
            {
                var errors = model.Validate(Db);
                if (!errors.Any())
                {
                    var quantityManager = new QuantityManager(LogService, Time);

                    var id = model.Add(Db,
                                       quantityManager,
                                       Cache,
                                       Time.GetAppNowTime(),
                                       AccessManager.UserId);
                }
                else
                {
                    foreach (var error in errors)
                    {
                        ModelState.AddModelError("", error.ErrorMessage);
                    }

                    return(PartialView(PopupContentView, model));
                }

                return(Json(new UpdateRowViewModel(model,
                                                   "quantityOperationGrid",
                                                   new[]
                {
                    "Type"
                },
                                                   false)));
            }

            return(View(PopupContentView, model));
        }
Esempio n. 15
0
        protected override void RunCallback()
        {
            var dbFactory       = new DbFactory();
            var time            = new TimeService(dbFactory);
            var log             = GetLogger();
            var settings        = new SettingsService(dbFactory);
            var quantityManager = new QuantityManager(GetLogger(), time);
            var actionService   = new SystemActionService(GetLogger(), time);
            var priceManager    = new PriceManager(GetLogger(), time, dbFactory, actionService, settings);

            using (var db = dbFactory.GetRWDb())
            {
                db.DisableValidation();

                RetryHelper.ActionWithRetries(() => quantityManager.FixupListingQuantity(db, settings), log, retryCount: 1, throwException: false);

                RetryHelper.ActionWithRetries(() => priceManager.FixupListingPrices(db), log, retryCount: 1, throwException: false);

                //RetryHelper.ActionWithRetries(() => priceManager.FixupBusinessPrices(db), log, retryCount: 1, throwException: false);
                //RetryHelper.ActionWithRetries(() => priceManager.FixupFBAPrices(db), log, retryCount: 1, throwException: false);

                RetryHelper.ActionWithRetries(() => priceManager.FixupWalmartPrices(db), log, retryCount: 1, throwException: false);
            }
        }
Esempio n. 16
0
        public virtual ActionResult Generate(ReturnOrderViewModel model)
        {
            LogI("Index, model=" + model);

            if (ModelState.IsValid)
            {
                model.OrderID = model.OrderID.RemoveWhitespaces();

                var shipmentProviders = ServiceFactory.GetShipmentProviders(LogService,
                                                                            Time,
                                                                            DbFactory,
                                                                            WeightService,
                                                                            AccessManager.ShipmentProviderInfoList,
                                                                            AppSettings.DefaultCustomType,
                                                                            AppSettings.LabelDirectory,
                                                                            AppSettings.ReserveDirectory,
                                                                            AppSettings.TemplateDirectory);

                var labelService   = new LabelService(shipmentProviders, LogService, Time, DbFactory, EmailService, PdfMaker, AddressService);
                var quntityManager = new QuantityManager(LogService, Time);
                var actionService  = new SystemActionService(LogService, Time);

                if (model.ReasonCode == (int)MailLabelReasonCodes.ReturnLabelReasonCode)
                {
                    var returnResults = model.ReturnAction(Db,
                                                           quntityManager,
                                                           actionService,
                                                           LogService,
                                                           Time,
                                                           Time.GetAppNowTime(),
                                                           AccessManager.UserId);

                    model.Messages.AddRange(returnResults);
                }

                if (model.ReasonCode == (int)MailLabelReasonCodes.ExchangeCode)
                {
                    var exchangeResults = model.ExchangeAction(Db,
                                                               LogService,
                                                               Time,
                                                               quntityManager,
                                                               labelService,
                                                               WeightService,
                                                               ShippingService,
                                                               AccessManager.Company,
                                                               Time.GetAppNowTime(),
                                                               AccessManager.UserId);

                    model.Messages.AddRange(exchangeResults);
                }

                if (model.ReasonCode == (int)MailLabelReasonCodes.RefundCode)
                {
                    var refundResults = model.RefundAction(Db,
                                                           quntityManager,
                                                           actionService,
                                                           LogService,
                                                           Time,
                                                           Time.GetAppNowTime(),
                                                           AccessManager.UserId);

                    model.Messages.AddRange(refundResults);
                }

                var affectedStyleIdList = model.Items.Where(i => i.ExchangeStyleId.HasValue).Select(i => (long)i.ExchangeStyleId.Value).Distinct().ToList();
                affectedStyleIdList.AddRange(model.Items.Where(i => i.StyleId.HasValue).Select(i => i.StyleId.Value).Distinct().ToList());
                Cache.RequestStyleIdUpdates(Db,
                                            affectedStyleIdList,
                                            UpdateCacheMode.IncludeChild,
                                            AccessManager.UserId);
            }
            else
            {
                model.Messages.AddRange(ModelState.GetErrors().Select(m => MessageString.Error(m)));
            }

            LogI("Index, Generate results=");
            model.Messages.ForEach(m => LogI(m.Status + ": " + m.Message));

            return(new JsonResult {
                Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
Esempio n. 17
0
        public void CallProcessEBayOrders(string orderNumber)
        {
            var syncInfo             = new DbSyncInformer(_dbFactory, _log, _time, SyncType.Orders, "", MarketType.eBay, String.Empty);
            var settings             = new SettingsService(_dbFactory);
            var dbFactory            = new DbFactory();
            var quantityManager      = new QuantityManager(_log, _time);
            var priceService         = new PriceService(dbFactory);
            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 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 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,
                                                                companyAddress.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 synchronizer = new EBayOrdersSynchronizer(_log,
                                                                      _eBayApi,
                                                                      _company,
                                                                      settings,
                                                                      syncInfo,
                                                                      rateProviders,
                                                                      quantityManager,
                                                                      _emailService,
                                                                      validatorService,
                                                                      orderHistoryService,
                                                                      cacheService,
                                                                      _actionService,
                                                                      companyAddress,
                                                                      _time,
                                                                      weightService,
                                                                      messageService);

                        if (String.IsNullOrEmpty(orderNumber))
                        {
                            synchronizer.Sync(OrderSyncModes.Full, null);
                        }
                        else
                        {
                            synchronizer.ProcessSpecifiedOrder(db, orderNumber);
                        }
                    }
                    finally
                    {
                        syncInfo.SyncEnd();
                    }
                }
            }
        }
Esempio n. 18
0
        public void StoreOrderInfo(OrderInfo order)
        {
            var dbFactory = new DbFactory();
            var log       = LogFactory.Default;
            var time      = new TimeService(dbFactory);

            var quantityManager = new QuantityManager(log, time);

            using (var invDb = new Amazon.DAL.Inventory.InventoryUnitOfWork())
            {
                if (order.Type == InventoryOrderType.InventoryOrder)
                {
                    var orderDto = new InventoryDTO()
                    {
                        Description   = order.Name,
                        FileName      = order.FileName,
                        InventoryDate = DateHelper.ConvertUtcToApp(order.OrderDate)
                    };

                    var itemsDto = order.Barcodes.Select(b => new ScanItemDTO()
                    {
                        Barcode  = b.Barcode,
                        Quantity = b.Quantity
                    }).ToList();

                    invDb.ItemInventoryMappings.AddNewInventory(orderDto, itemsDto);
                }

                if (order.Type == InventoryOrderType.ShopOrder ||
                    order.Type == InventoryOrderType.FBAOrder)
                {
                    var orderDto = new ScanOrderDTO()
                    {
                        Description = order.Name,
                        FileName    = order.FileName,
                        OrderDate   = DateHelper.ConvertUtcToApp(order.OrderDate),
                        IsFBA       = order.Type == InventoryOrderType.FBAOrder
                    };

                    var itemsDto = order.Barcodes.Select(b => new ScanItemDTO()
                    {
                        Barcode  = b.Barcode,
                        Quantity = b.Quantity
                    }).ToList();

                    invDb.ItemOrderMappings.AddNewOrder(orderDto, itemsDto);

                    try
                    {
                        using (var db = dbFactory.GetRWDb())
                        {
                            foreach (var item in itemsDto)
                            {
                                var barcodeDto =
                                    db.StyleItemBarcodes.GetAllAsDto().FirstOrDefault(b => b.Barcode == item.Barcode);
                                if (barcodeDto != null)
                                {
                                    quantityManager.LogStyleItemQuantity(db,
                                                                         barcodeDto.StyleItemId,
                                                                         item.Quantity,
                                                                         null,
                                                                         order.Type == InventoryOrderType.ShopOrder
                                            ? QuantityChangeSourceType.SentToStore
                                            : QuantityChangeSourceType.SentToFBA,
                                                                         orderDto.Id.ToString(),
                                                                         item.Id,
                                                                         StringHelper.Substring(orderDto.Description, 50),
                                                                         time.GetAppNowTime(),
                                                                         null);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("When write style item log", ex);
                    }
                }
            }
        }
Esempio n. 19
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");
                    }
                }
            }
        }
Esempio n. 20
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();
                    }
                }
            }
        }