Exemplo n.º 1
0
 public WooCommerceOrdersSynchronizer(ILogService log,
                                      IMarketApi api,
                                      CompanyDTO company,
                                      ISettingsService settings,
                                      ISyncInformer syncInfo,
                                      IList <IShipmentApi> rateProviders,
                                      IQuantityManager quantityManager,
                                      IEmailService emailService,
                                      IOrderValidatorService validatorService,
                                      IOrderHistoryService orderHistoryService,
                                      ICacheService cacheService,
                                      ISystemActionService systemAction,
                                      ICompanyAddressService companyAddress,
                                      ITime time,
                                      IWeightService weightService,
                                      ISystemMessageService messageService) : base(log,
                                                                                   api,
                                                                                   company,
                                                                                   settings,
                                                                                   syncInfo,
                                                                                   rateProviders,
                                                                                   quantityManager,
                                                                                   emailService,
                                                                                   validatorService,
                                                                                   orderHistoryService,
                                                                                   cacheService,
                                                                                   systemAction,
                                                                                   companyAddress,
                                                                                   time,
                                                                                   weightService,
                                                                                   messageService)
 {
 }
Exemplo n.º 2
0
 public WooCommerceOrdersSynchronizer(ILogService log,
                                      CompanyDTO company,
                                      ISyncInformer syncInfo,
                                      IList <IShipmentApi> rateProviders,
                                      ICompanyAddressService companyAddress,
                                      ITime time,
                                      IWeightService weightService,
                                      ISystemMessageService messageService) : base(log,
                                                                                   null,
                                                                                   company,
                                                                                   null,
                                                                                   syncInfo,
                                                                                   rateProviders,
                                                                                   null,
                                                                                   null,
                                                                                   null,
                                                                                   null,
                                                                                   null,
                                                                                   null,
                                                                                   companyAddress,
                                                                                   time,
                                                                                   weightService,
                                                                                   messageService)
 {
 }
Exemplo n.º 3
0
        public AmazonReportService(AmazonReportType reportType,
                                   long companyId,
                                   AmazonApi api,
                                   ILogService log,
                                   ITime time,
                                   IDbFactory dbFactory,
                                   ISyncInformer syncInfo,
                                   IStyleManager styleManager,
                                   INotificationService notificationService,
                                   IStyleHistoryService styleHistoryService,
                                   IItemHistoryService itemHistoryService,
                                   ISystemActionService actionService,
                                   IReportParser parser,
                                   string path = "")
        {
            _log       = log;
            _time      = time;
            _dbFactory = dbFactory;

            _api = api;

            _reportInfo = new AmazonReportInfo();
            _reportInfo.ReportRequestId = String.Empty;

            _path          = path;
            _companyId     = companyId;
            _syncInfo      = syncInfo;
            _reportType    = reportType;
            _parser        = parser;
            _actionService = actionService;

            var parseContext = new ParseContext()
            {
                Log                 = log,
                Time                = time,
                DbFactory           = dbFactory,
                ActionService       = actionService,
                StyleManager        = styleManager,
                NotificationService = notificationService,
                StyleHistoryService = styleHistoryService,
                ItemHistoryService  = itemHistoryService,
                SyncInformer        = syncInfo,
                CompanyId           = companyId
            };

            _parser.Init(parseContext);

            _log.Info(string.Format("Path: {0}", path));
        }
 public ListingLineProcessing(ParseContext parseContext,
                              ITime time,
                              bool canCreateStyleInfo)
 {
     _log                 = parseContext.Log;
     _companyId           = parseContext.CompanyId;
     _styleManager        = parseContext.StyleManager;
     _syncInfo            = parseContext.SyncInformer;
     _notificationService = parseContext.NotificationService;
     _styleHistoryService = parseContext.StyleHistoryService;
     _itemHistoryService  = parseContext.ItemHistoryService;
     _actionService       = parseContext.ActionService;
     _time                = time;
     _canCreateStyleInfo  = canCreateStyleInfo;
 }
        public void ProcessExistingParents(IUnitOfWork db,
                                           IMarketApi api,
                                           ISyncInformer syncInfo,
                                           IList <string> parentASINs,
                                           IList <ItemDTO> items)
        {
            var parentASINsWithError = new List <string>();

            _log.Debug("Begin process existing parents, count=" + parentASINs.Count);
            var parentsDto = api.GetItems(_log,
                                          _time,
                                          MarketItemFilters.Build(parentASINs),
                                          ItemFillMode.NoAdv,
                                          out parentASINsWithError).ToList();

            _log.Debug("Error when GetItems, parentASINS: " + String.Join(", ", parentASINsWithError));

            //Only update fields
            foreach (var parent in parentsDto)
            {
                //NOTE: in case when parent item has "no-img" using child image
                if (String.IsNullOrEmpty(parent.ImageSource))
                {
                    var childImage = items.FirstOrDefault(i => i.ParentASIN == parent.ASIN && !String.IsNullOrEmpty(i.ImageUrl));
                    if (childImage != null)
                    {
                        parent.ImageSource = childImage.ImageUrl;
                    }
                }

                var dbParent = db.ParentItems.CreateOrUpdateParent(parent,
                                                                   api.Market,
                                                                   api.MarketplaceId,
                                                                   _time.GetAppNowTime());

                _log.Warn("Parent item was updated, ParentASIN=" + parent.ASIN);
                syncInfo.AddSuccess(parent.ASIN, "Parent item was updated");
            }
            _log.Debug("End process existing parents");
        }
Exemplo n.º 6
0
 protected IList <ListingOrderDTO> GetOrderItemsFromMarket(ILogService log, IMarketApi api, ISyncInformer syncInfo, string orderId)
 {
     return(new List <ListingOrderDTO>());
 }
Exemplo n.º 7
0
        protected SyncResult SyncAllNewOrders(CancellationToken?token,
                                              ILogService log,
                                              IMarketApi api,
                                              MarketType market,

                                              Func <ILogService, IMarketApi, ISyncInformer, string, IList <ListingOrderDTO> > getOrderItemsFromMarketFunc,

                                              ISyncInformer syncInfo,
                                              IList <IShipmentApi> rateProviders,
                                              IQuantityManager quantityManager,
                                              ISettingsService settings,
                                              IEmailService emailService,
                                              IOrderValidatorService validatorService,
                                              ICacheService cacheService,

                                              ICompanyAddressService companyAddress,
                                              DateTime syncMissedFrom,
                                              ITime time)
        {
            try
            {
                log.Info("Get missed orders");
                var statusList = new List <string> {
                    OrderStatusEnumEx.Canceled,
                    OrderStatusEnumEx.Shipped,
                    OrderStatusEnumEx.Unshipped,
                    OrderStatusEnumEx.Pending
                };                               //NOTE: On API level there status will be converted on eBay status

                var allOrders = api.GetOrders(log, syncMissedFrom, statusList).ToList();

                if (allOrders.Any())
                {
                    var result = ProcessNewOrdersPack(token,
                                                      log,
                                                      api,

                                                      getOrderItemsFromMarketFunc,

                                                      rateProviders,
                                                      validatorService,
                                                      syncInfo,
                                                      settings,
                                                      quantityManager,
                                                      emailService,
                                                      cacheService,

                                                      companyAddress,
                                                      allOrders,
                                                      time);

                    if (!result.IsSuccess)
                    {
                        syncInfo.AddWarning("", "The orders pack processing has failed");
                        return(new SyncResult()
                        {
                            IsSuccess = false
                        });
                    }

                    return(result);
                }

                return(new SyncResult()
                {
                    IsSuccess = true,
                    ProcessedOrders = new List <SyncResultOrderInfo>()
                });
            }
            catch (Exception ex)
            {
                syncInfo.AddError(null, "Error when storing new unshipped orders", ex);
                log.Error("Error when storing new unshipped orders", ex);
                return(new SyncResult()
                {
                    IsSuccess = false
                });
            }
        }
Exemplo n.º 8
0
        protected SyncResult UpdateExistingUnshippedOrders(CancellationToken?token,
                                                           ILogService log,
                                                           IMarketApi api,

                                                           Func <ILogService, IMarketApi, ISyncInformer, string, IList <ListingOrderDTO> > getOrderItemsFromMarketFunc,

                                                           ISyncInformer syncInfo,
                                                           IList <IShipmentApi> rateProviders,
                                                           IQuantityManager quantityManager,
                                                           IEmailService emailService,
                                                           IOrderValidatorService validatorService,

                                                           IList <string> excludeOrderIdList,

                                                           ICompanyAddressService companyAddress,
                                                           ITime time)
        {
            IList <Order> ordersToUpdate = new List <Order>();

            try
            {
                using (var db = new UnitOfWork(log))
                {
                    var existOrders = db.Orders.GetOrdersByStatus(api.Market,
                                                                  api.MarketplaceId,
                                                                  new[] {
                        OrderStatusEnumEx.Pending,
                        OrderStatusEnumEx.Unshipped,
                        OrderStatusEnumEx.PartiallyShipped
                    }
                                                                  ).ToList();

                    if (excludeOrderIdList != null)
                    {
                        ordersToUpdate = existOrders.Where(o => !excludeOrderIdList.Contains(o.AmazonIdentifier)).ToList();
                    }
                    else
                    {
                        ordersToUpdate = existOrders;
                    }

                    log.Info("Orders to update count:" + ordersToUpdate.Count
                             + " (existing in DB=" + existOrders.Count
                             + ", exclude list=" + (excludeOrderIdList != null ? excludeOrderIdList.Count.ToString() : "[null]") + ")");

                    var index = 0;
                    var step  = 50;
                    while (index < ordersToUpdate.Count)
                    {
                        var ordersToProcess = ordersToUpdate.Skip(index).Take(step).ToList();
                        log.Info("Start process orders from api, from=" + index + ", count=" + ordersToProcess.Count);

                        if (!ProcessExistOrdersPack(token,
                                                    log,
                                                    api,

                                                    getOrderItemsFromMarketFunc,

                                                    syncInfo,
                                                    db,

                                                    rateProviders,
                                                    quantityManager,
                                                    emailService,
                                                    validatorService,

                                                    companyAddress,
                                                    ordersToProcess,
                                                    time))
                        {
                            syncInfo.AddWarning("", "The pending orders pack processing has failed");
                            //Break cycle if pack processing is fail, something wrong (m.b. unavailable Db, m.b. parallel sync)
                            return(new SyncResult()
                            {
                                IsSuccess = false
                            });
                        }
                        index += step;
                        syncInfo.PingSync();
                    }
                }
                return(new SyncResult()
                {
                    IsSuccess = true,
                    ProcessedOrders = ordersToUpdate.Select(o => new SyncResultOrderInfo()
                    {
                        OrderId = o.AmazonIdentifier,
                        OrderStatus = o.OrderStatus
                    }).ToList()
                });
            }
            catch (Exception ex)
            {
                LogError(log, syncInfo, ex, "", "Error when updating existing orders");
                return(new SyncResult()
                {
                    IsSuccess = false
                });
            }
        }
Exemplo n.º 9
0
        public IOrderSynchronizer GetForMarket(IMarketApi api,
                                               ILogService log,
                                               CompanyDTO company,
                                               ISettingsService settings,
                                               ISyncInformer syncInfo,
                                               IList <IShipmentApi> rateProviders,
                                               IQuantityManager quantityManager,
                                               IEmailService emailService,
                                               IOrderValidatorService validatorService,
                                               IOrderHistoryService orderHistoryService,
                                               ICacheService cacheService,
                                               ISystemActionService systemAction,
                                               ICompanyAddressService companyAddress,
                                               ITime time,
                                               IWeightService weightService,
                                               ISystemMessageService messageService)
        {
            IOrderSynchronizer synchronizer = null;

            switch (api.Market)
            {
            case MarketType.Amazon:
            case MarketType.AmazonEU:
            case MarketType.AmazonAU:
                synchronizer = new AmazonOrdersSynchronizer(log,
                                                            api,
                                                            company,
                                                            settings,
                                                            syncInfo,
                                                            rateProviders,
                                                            quantityManager,
                                                            emailService,
                                                            validatorService,
                                                            orderHistoryService,
                                                            cacheService,
                                                            systemAction,
                                                            companyAddress,
                                                            time,
                                                            weightService,
                                                            messageService);
                break;

            case MarketType.eBay:
                synchronizer = new EBayOrdersSynchronizer(log,
                                                          api,
                                                          company,
                                                          settings,
                                                          syncInfo,
                                                          rateProviders,
                                                          quantityManager,
                                                          emailService,
                                                          validatorService,
                                                          orderHistoryService,
                                                          cacheService,
                                                          systemAction,
                                                          companyAddress,
                                                          time,
                                                          weightService,
                                                          messageService);
                break;

            case MarketType.Magento:
                synchronizer = new MagentoOrdersSynchronizer(log,
                                                             api,
                                                             company,
                                                             settings,
                                                             syncInfo,
                                                             rateProviders,
                                                             quantityManager,
                                                             emailService,
                                                             validatorService,
                                                             orderHistoryService,
                                                             cacheService,
                                                             systemAction,
                                                             companyAddress,
                                                             time,
                                                             weightService,
                                                             messageService);
                break;

            case MarketType.Groupon:
                synchronizer = new GrouponOrdersSynchronizer(log,
                                                             api,
                                                             company,
                                                             settings,
                                                             syncInfo,
                                                             rateProviders,
                                                             quantityManager,
                                                             emailService,
                                                             validatorService,
                                                             orderHistoryService,
                                                             cacheService,
                                                             systemAction,
                                                             companyAddress,
                                                             time,
                                                             weightService,
                                                             messageService);
                break;

            case MarketType.Shopify:
                synchronizer = new ShopifyOrdersSynchronizer(log,
                                                             api,
                                                             company,
                                                             settings,
                                                             syncInfo,
                                                             rateProviders,
                                                             quantityManager,
                                                             emailService,
                                                             validatorService,
                                                             orderHistoryService,
                                                             cacheService,
                                                             systemAction,
                                                             companyAddress,
                                                             time,
                                                             weightService,
                                                             messageService);
                break;

            case MarketType.WooCommerce:
                synchronizer = new WooCommerceOrdersSynchronizer(log,
                                                                 api,
                                                                 company,
                                                                 settings,
                                                                 syncInfo,
                                                                 rateProviders,
                                                                 quantityManager,
                                                                 emailService,
                                                                 validatorService,
                                                                 orderHistoryService,
                                                                 cacheService,
                                                                 systemAction,
                                                                 companyAddress,
                                                                 time,
                                                                 weightService,
                                                                 messageService);
                break;

            case MarketType.Walmart:
            case MarketType.WalmartCA:
                synchronizer = new WalmartOrdersSynchronizer(log,
                                                             api,
                                                             company,
                                                             settings,
                                                             syncInfo,
                                                             rateProviders,
                                                             quantityManager,
                                                             emailService,
                                                             validatorService,
                                                             orderHistoryService,
                                                             cacheService,
                                                             systemAction,
                                                             companyAddress,
                                                             time,
                                                             weightService,
                                                             messageService);
                break;

            case MarketType.Jet:
                synchronizer = new JetOrdersSynchronizer(log,
                                                         api,
                                                         company,
                                                         settings,
                                                         syncInfo,
                                                         rateProviders,
                                                         quantityManager,
                                                         emailService,
                                                         validatorService,
                                                         orderHistoryService,
                                                         cacheService,
                                                         systemAction,
                                                         companyAddress,
                                                         time,
                                                         weightService,
                                                         messageService);
                break;

            case MarketType.DropShipper:
                synchronizer = new DSOrdersSynchronizer(log,
                                                        api,
                                                        company,
                                                        settings,
                                                        syncInfo,
                                                        rateProviders,
                                                        quantityManager,
                                                        emailService,
                                                        validatorService,
                                                        orderHistoryService,
                                                        cacheService,
                                                        systemAction,
                                                        companyAddress,
                                                        time,
                                                        weightService,
                                                        messageService);
                break;

            case MarketType.OverStock:
                synchronizer = new SupplierOasisOrdersSynchronizer(log,
                                                                   api,
                                                                   company,
                                                                   settings,
                                                                   syncInfo,
                                                                   rateProviders,
                                                                   quantityManager,
                                                                   emailService,
                                                                   validatorService,
                                                                   orderHistoryService,
                                                                   cacheService,
                                                                   systemAction,
                                                                   companyAddress,
                                                                   time,
                                                                   weightService,
                                                                   messageService);
                break;

            case MarketType.OfflineOrders:
                synchronizer = new UserOrdersSynchronizer(log,
                                                          api,
                                                          company,
                                                          settings,
                                                          syncInfo,
                                                          rateProviders,
                                                          quantityManager,
                                                          emailService,
                                                          validatorService,
                                                          orderHistoryService,
                                                          cacheService,
                                                          systemAction,
                                                          companyAddress,
                                                          time,
                                                          weightService,
                                                          messageService);
                break;

            default:
                throw new NotImplementedException("MarketType not supported=" + api.Market.ToString());
                break;
            }

            return(synchronizer);
        }
        public void UpdateParentsForExistantItems(IUnitOfWork db,
                                                  IMarketApi api,
                                                  ISyncInformer syncInfo)
        {
            var parentASINsWithError = new List <string>();

            var allExistingItems = (from i in db.Items.GetAll()
                                    join l in db.Listings.GetAll() on i.Id equals l.ItemId
                                    where i.Market == (int)api.Market &&
                                    (i.MarketplaceId == api.MarketplaceId || String.IsNullOrEmpty(api.MarketplaceId)) &&
                                    !l.IsRemoved
                                    select new
            {
                Id = i.Id,
                ParentASIN = i.ParentASIN,
                MarketParentASIN = i.MarketParentASIN,
                StyleString = i.StyleString,
                IsDefault = l.IsDefault,
            })
                                   .ToList();

            var parentASINs = allExistingItems
                              .Where(i => !String.IsNullOrEmpty(i.ParentASIN))
                              .Select(i => i.ParentASIN)
                              .Distinct()
                              .ToList();

            var marketParentASINs = allExistingItems
                                    .Where(i => !String.IsNullOrEmpty(i.MarketParentASIN))
                                    .Select(i => i.MarketParentASIN)
                                    .Distinct()
                                    .ToList();

            _log.Debug("Begin process existing parents, count=" + marketParentASINs.Count);
            var marketParentsDto = api.GetItems(_log,
                                                _time,
                                                MarketItemFilters.Build(marketParentASINs),
                                                ItemFillMode.NoAdv,
                                                out parentASINsWithError).ToList();

            _log.Debug("Error when GetItems, parentASINS: " + String.Join(", ", parentASINsWithError));

            foreach (var parentASIN in parentASINs)
            {
                var existingItems = allExistingItems.Where(i => i.ParentASIN == parentASIN).ToList();
                //Select actual ParentASIN info
                var parentASINCandidates = existingItems.GroupBy(i => i.MarketParentASIN)
                                           .Select(i => new
                {
                    MarketParentASIN = i.Key,
                    Count            = i.Count()
                })
                                           .OrderByDescending(i => i.Count)
                                           .ToList();

                var parentASINwinner = parentASINCandidates.FirstOrDefault(i => !String.IsNullOrEmpty(i.MarketParentASIN));
                if (parentASINwinner != null)
                {
                    var parentItemDto = marketParentsDto.FirstOrDefault(pi => pi.ASIN == parentASINwinner.MarketParentASIN);

                    //NOTE: TEMP prepare ParentSKU, For first updating Parent SKUs, afterward keep logic only for new
                    if (String.IsNullOrEmpty(parentItemDto.SKU))
                    {
                        var mainStyleString = existingItems.OrderByDescending(i => i.IsDefault).ThenBy(i => i.Id).FirstOrDefault()?.StyleString;
                        parentItemDto.SKU = StringHelper.JoinTwo("-", mainStyleString, parentItemDto.ASIN);
                    }

                    if (parentItemDto != null &&
                        parentItemDto.IsAmazonUpdated == true)
                    {
                        if (parentASIN != parentItemDto.ASIN)
                        {
                            var existNewParent = db.ParentItems.GetByASIN(parentItemDto.ASIN, api.Market, api.MarketplaceId);

                            if (existNewParent == null)
                            {
                                db.ParentItems.UpdateParent(parentASIN, parentItemDto, api.Market, api.MarketplaceId, _time.GetAppNowTime());
                            }
                            else
                            {
                                var dbParentItem = db.ParentItems.GetByASIN(parentASIN, api.Market, api.MarketplaceId);
                                if (dbParentItem != null)
                                {
                                    db.ParentItems.Remove(dbParentItem);
                                    db.Commit();
                                }
                            }

                            //Update child items references
                            var childItemsToUpdate = db.Items.GetAll()
                                                     .Where(i => i.ParentASIN == parentASIN &&
                                                            i.Market == (int)api.Market &&
                                                            (i.MarketplaceId == api.MarketplaceId || String.IsNullOrEmpty(api.MarketplaceId)))
                                                     .ToList();
                            childItemsToUpdate.ForEach(i => i.ParentASIN = parentItemDto.ASIN);
                            db.Commit();

                            _log.Warn("Parent item was updated, ParentASIN=" + parentASIN + "=>" + parentItemDto.ASIN);
                        }
                        else
                        {
                            //NOTE: just update info or create missing parent item
                            db.ParentItems.CreateOrUpdateParent(parentItemDto, api.Market, api.MarketplaceId, _time.GetAppNowTime());
                        }
                    }
                    else
                    {
                        //NOTE: fill FAKE parentItem
                        if (parentItemDto.IsAmazonUpdated != true &&
                            (String.IsNullOrEmpty(parentItemDto.AmazonName) ||
                             String.IsNullOrEmpty(parentItemDto.ImageSource)))
                        {
                            var mainItemId = existingItems.OrderByDescending(i => i.IsDefault).FirstOrDefault()?.Id;
                            if (mainItemId.HasValue)
                            {
                                var mainItem = db.Items.Get(mainItemId.Value);
                                parentItemDto.AmazonName  = mainItem?.Title;
                                parentItemDto.ImageSource = mainItem?.PrimaryImage;
                            }
                        }

                        if (parentItemDto != null)
                        {
                            db.ParentItems.CreateOrUpdateParent(parentItemDto, api.Market, api.MarketplaceId, _time.GetAppNowTime());
                        }
                    }
                }
            }

            _log.Debug("End process existing parents");
        }
Exemplo n.º 11
0
 protected IList <ListingOrderDTO> GetOrderItemsFromMarket(ILogService log, IMarketApi api, ISyncInformer syncInfo, string orderId)
 {
     try
     {
         return(api.GetOrderItems(orderId).ToList());
     }
     catch (Exception ex)
     {
         log.Error("Error when getting order items", ex);
         syncInfo.AddError(orderId, "Failed getting order items", ex);
         return(new List <ListingOrderDTO>());
     }
 }
Exemplo n.º 12
0
        protected SyncResult SyncAllUnshippedOrders(CancellationToken?cancel,
                                                    ILogService log,
                                                    IMarketApi api,

                                                    Func <ILogService, IMarketApi, ISyncInformer, string, IList <ListingOrderDTO> > getOrderItemsFromMarketFunc,

                                                    ISyncInformer syncInfo,
                                                    IList <IShipmentApi> rateProviders,
                                                    IQuantityManager quantityManager,
                                                    ISettingsService settings,
                                                    IEmailService emailService,
                                                    IOrderValidatorService validatorService,
                                                    ICacheService cacheService,

                                                    ICompanyAddressService companyAddress,
                                                    DateTime syncMissedFrom,
                                                    ITime time)
        {
            try
            {
                log.Info("Get missed orders");

                SyncResult result     = new SyncResult();
                var        statusList = new List <string> {
                    OrderStatusEnumEx.Unshipped, OrderStatusEnumEx.PartiallyShipped, OrderStatusEnumEx.Canceled
                };
                var unshippedOrders = api.GetOrders(log, syncMissedFrom, statusList).ToList();

                if (unshippedOrders.Any())
                {
                    result = ProcessNewOrdersPack(cancel,
                                                  log,
                                                  api,

                                                  getOrderItemsFromMarketFunc,

                                                  rateProviders,
                                                  validatorService,
                                                  syncInfo,
                                                  settings,
                                                  quantityManager,
                                                  emailService,
                                                  cacheService,

                                                  companyAddress,
                                                  unshippedOrders,
                                                  time);

                    if (!result.IsSuccess)
                    {
                        syncInfo.AddWarning("", "The orders pack processing has failed");
                        return(new SyncResult()
                        {
                            IsSuccess = false
                        });
                    }
                }

                return(new SyncResult()
                {
                    IsSuccess = true,
                    //NOTE: Return all unshipped orders for correct calculation total orders on Amazon
                    //unprocessed orders actual didn't updated (we can safely skip processing of it)
                    ProcessedOrders = result.ProcessedOrders,
                    SkippedOrders = result.SkippedOrders,

                    /*unshippedOrders.Select(o => new SyncResultOrderInfo()
                     * {
                     *  OrderId = o.OrderId,
                     *  OrderStatus = o.OrderStatus
                     * }).ToList()*/
                });
            }
            catch (Exception ex)
            {
                syncInfo.AddError(null, "Error when storing new unshipped orders", ex);
                log.Error("Error when storing new unshipped orders", ex);
                return(new SyncResult()
                {
                    IsSuccess = false
                });
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Requested new pending orders (from last exist pending order date)
        /// </summary>
        /// <returns></returns>
        protected SyncResult StoreNewPendingOrders(CancellationToken?token,
                                                   ILogService log,
                                                   IMarketApi api,

                                                   Func <ILogService, IMarketApi, ISyncInformer, string, IList <ListingOrderDTO> > getOrderItemsFromMarketFunc,

                                                   IList <IShipmentApi> rateProviders,
                                                   IOrderValidatorService validatorService,
                                                   IEmailService emailService,
                                                   ISyncInformer syncInfo,
                                                   ISettingsService settings,
                                                   IQuantityManager quantityManager,
                                                   ICacheService cacheService,

                                                   ICompanyAddressService companyAddress,
                                                   ITime time)
        {
            try
            {
                using (var db = new UnitOfWork(_log))
                {
                    var lastPending = db.Orders
                                      .GetFiltered(o => o.OrderStatus == OrderStatusEnumEx.Pending &&
                                                   o.Market == (int)api.Market &&
                                                   o.MarketplaceId == api.MarketplaceId)
                                      .OrderBy(o => o.Id).FirstOrDefault();

                    var date = lastPending != null && lastPending.OrderDate.HasValue ? lastPending.OrderDate : null;
                    log.Info(date != null ? "Last pending order date: " + date.Value : "No pending orders!");

                    var updatedAfter = date ?? DateHelper.GetAmazonNowTime().AddDays(-1);
                    log.Info(string.Format("Process Orders created since {0}", updatedAfter));

                    var statusList = new List <string> {
                        OrderStatusEnum.Pending.Str()
                    };

                    var pendingOrders = api.GetOrders(log, updatedAfter, statusList).ToList();
                    log.Info("Total pending orders:" + pendingOrders.Count());

                    syncInfo.PingSync();

                    var result = ProcessNewOrdersPack(token,
                                                      log,
                                                      api,
                                                      getOrderItemsFromMarketFunc,

                                                      rateProviders,
                                                      validatorService,
                                                      syncInfo,
                                                      settings,
                                                      quantityManager,
                                                      emailService,
                                                      cacheService,

                                                      companyAddress,
                                                      pendingOrders,
                                                      time);

                    if (!result.IsSuccess)
                    {
                        syncInfo.AddWarning("", "The orders pack processing has failed");
                        return(new SyncResult()
                        {
                            IsSuccess = false
                        });
                    }

                    return(result);
                }
            }
            catch (Exception ex)
            {
                syncInfo.AddError(null, "Error when storing new orders", ex);
                log.Error("Error when storing new orders", ex);
                return(new SyncResult()
                {
                    IsSuccess = false
                });
            }
        }
        protected override void RunCallback()
        {
            var dbFactory = new DbFactory();
            var time      = new TimeService(dbFactory);
            var log       = GetLogger();

            var settings = new SettingsService(dbFactory);

            var styleHistoryService = new StyleHistoryService(log, time, dbFactory);
            var itemHistoryService  = new ItemHistoryService(log, time, dbFactory);
            var styleManager        = new StyleManager(log, time, styleHistoryService);
            var notificationService = new NotificationService(log, time, dbFactory);
            var actionService       = new SystemActionService(log, time);

            var lastSyncDate          = _reportSettings.GetLastSyncDate(settings, _api.Market, _api.MarketplaceId);
            var isManualSyncRequested = _reportSettings.IsManualSyncRequested(settings, _api.Market, _api.MarketplaceId);

            LogWrite("Market=" + _api.Market + ", marketplaceId=" + _api.MarketplaceId);
            LogWrite("Last sync date=" + lastSyncDate.ToString() + ", isManualSyncRequested=" + isManualSyncRequested);

            if (!lastSyncDate.HasValue ||
                (DateTime.UtcNow - lastSyncDate) > _reportSettings.RequestInterval ||
                isManualSyncRequested == true)
            {
                if (_reportSettings.RequestMode == ReportRequestMode.Sheduled)
                {
                    //TODO: add
                    //http://docs.developer.amazonservices.com/en_US/reports/Reports_Overview.html
                    //NOTE: Trying to get last existing report from Amazon

                    LogWrite("Check Sheduled");
                    _reportService = new AmazonReportService(_reportSettings.ReportType,
                                                             CompanyId,
                                                             _api,
                                                             log,
                                                             time,
                                                             dbFactory,
                                                             _syncInfo,
                                                             styleManager,
                                                             notificationService,
                                                             styleHistoryService,
                                                             itemHistoryService,
                                                             actionService,
                                                             _reportSettings.GetParser(),
                                                             _reportSettings.ReportDirectory);

                    var lastReports = _reportService.GetReportList();
                    if (lastReports.Any())
                    {
                        var reportId = lastReports[0].ReportId;

                        LogWrite("Getting last exist report, ReportId=" + reportId);
                        if (_reportService.SaveScheduledReport(reportId))
                        {
                            using (var db = dbFactory.GetRWDb())
                            {
                                LogWrite("Add sheduled report");
                                db.InventoryReports.AddSheduledReport(reportId, (int)_reportSettings.ReportType, _api.MarketplaceId, _reportService.ReportFileName);

                                ProcessReport(settings);

                                _reportSettings.SetLastSyncDate(settings, _api.Market, _api.MarketplaceId, DateTime.UtcNow);
                                db.InventoryReports.MarkProcessedByReportId(_reportService.ReportId, ReportProcessingResultType.Success);
                                _reportService = null;
                            }
                        }
                    }
                    else
                    {
                        LogWrite("Do not have any reports of type=" + _reportService.ReportType.ToString());
                        _reportSettings.SetLastSyncDate(settings, _api.Market, _api.MarketplaceId, DateTime.UtcNow);
                        _reportService = null;
                    }
                }

                if (_reportSettings.RequestMode == ReportRequestMode.Requested)
                {
                    if (_reportService == null)
                    {
                        LogWrite("Create reportService");
                        _syncInfo = new DbSyncInformer(dbFactory,
                                                       log,
                                                       time,
                                                       SyncType.Listings,
                                                       _api.MarketplaceId,
                                                       _api.Market,
                                                       String.Empty);

                        _reportService = new AmazonReportService(_reportSettings.ReportType,
                                                                 CompanyId,
                                                                 _api,
                                                                 log,
                                                                 time,
                                                                 dbFactory,
                                                                 _syncInfo,
                                                                 styleManager,
                                                                 notificationService,
                                                                 styleHistoryService,
                                                                 itemHistoryService,
                                                                 actionService,
                                                                 _reportSettings.GetParser(),
                                                                 _reportSettings.ReportDirectory);

                        using (var db = dbFactory.GetRWDb())
                        {
                            var lastUnsavedReport = db.InventoryReports.GetLastUnsaved((int)_reportService.ReportType, _api.MarketplaceId);
                            if (lastUnsavedReport == null ||
                                (time.GetUtcTime() - lastUnsavedReport.RequestDate) > _reportSettings.AwaitInterval)
                            {
                                LogWrite("Request report");
                                _syncInfo.SyncBegin(null);
                                _syncInfo.AddInfo("", "Request report from Amazon");

                                _reportService.RequestReport();
                                db.InventoryReports.AddRequestedReport(_reportService.ReportRequestId, (int)_reportService.ReportType, _api.MarketplaceId);
                            }
                            else
                            {
                                LogWrite("Use last report request, id=" + lastUnsavedReport.Id + ", marketplaceId=" + lastUnsavedReport.MarketplaceId);
                                _syncInfo.OpenLastSync();
                                _syncInfo.AddInfo("", "Use last Amazon report request");

                                _reportService.UseReportRequestId(lastUnsavedReport.RequestIdentifier);
                            }
                        }
                    }
                    else
                    {
                        using (var db = dbFactory.GetRWDb())
                        {
                            LogWrite("Save report");
                            if (_reportService.SaveRequestedReport())
                            {
                                LogWrite("Save success, reportId=" + _reportService.ReportId + ", reportName=" + _reportService.ReportFileName);
                                db.InventoryReports.Update(_reportService.ReportRequestId, _reportService.ReportFileName, _reportService.ReportId);

                                ProcessReport(settings);

                                db.InventoryReports.MarkProcessedByReportId(_reportService.ReportId, ReportProcessingResultType.Success);
                                _reportSettings.SetLastSyncDate(settings, _api.Market, _api.MarketplaceId, time.GetUtcTime());
                                _reportService = null;
                            }
                            else
                            {
                                LogWrite("Could not save report");

                                var requestStatus = _reportService.GetRequestStatus();
                                if (requestStatus == null)
                                {
                                    LogWrite("Request status empty, reportId=" + _reportService);

                                    db.InventoryReports.MarkProcessedByRequestId(_reportService.ReportRequestId, ReportProcessingResultType.Cancelled);
                                    _reportSettings.SetLastSyncDate(settings, _api.Market, _api.MarketplaceId, time.GetUtcTime());
                                    _reportService = null;
                                }
                                else
                                {
                                    if (requestStatus.Status == "_CANCELLED_")
                                    {
                                        LogWrite("Mark as cancelled (requestStatus = _CANCELLED_");

                                        db.InventoryReports.MarkProcessedByRequestId(_reportService.ReportRequestId, ReportProcessingResultType.Cancelled);
                                        _reportSettings.SetLastSyncDate(settings, _api.Market, _api.MarketplaceId, DateTime.UtcNow);
                                        _reportService = null;
                                    }
                                    else
                                    {
                                        if (_reportService.SaveReportAttempts > _reportSettings.MaxRequestAttempt)
                                        {
                                            LogWrite("Mark as failed (MaxAttampts), saveReportAttempts > maxRequestAttempt");

                                            db.InventoryReports.MarkProcessedByRequestId(_reportService.ReportRequestId, ReportProcessingResultType.MaxAttampts);
                                            _reportSettings.SetLastSyncDate(settings, _api.Market, _api.MarketplaceId, DateTime.UtcNow);
                                            _reportService = null;
                                        }
                                        else
                                        {
                                            Thread.Sleep(TimeSpan.FromMinutes(Int32.Parse(AppSettings.ReportRequestAttemptIntervalMinutes)));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }