public AddressDTO GetReturnAddress(MarketIdentifier market)
        {
            var returnAddress = _addressList.FirstOrDefault(p => p.Type == (int)CompanyAddressTypes.Default);

            if (returnAddress == null)
            {
                returnAddress = _addressList.FirstOrDefault();
            }

            return(new AddressDTO()
            {
                Type = returnAddress.Type,
                FullName = _fullName,

                Address1 = returnAddress.Address1,
                Address2 = returnAddress.Address2,
                City = returnAddress.City,
                State = returnAddress.State,
                Zip = returnAddress.Zip,
                ZipAddon = returnAddress.ZipAddon,
                Country = returnAddress.Country,
                Phone = returnAddress.Phone,

                BuyerEmail = _contactEmail,
                CompanyName = _companyName,
                ContactName = _fullName,
            });
        }
Пример #2
0
        //public virtual ActionResult GetPackingSlipWithCoupon(long orderId)
        //{
        //    LogI("GetSamplePackingSlip, orderId=" + orderId);

        //    try
        //    {
        //        var orders = PackingSlipViewModel.GetList(Db, new[] { orderId }, SortMode.None, true).ToList();
        //        var model = new PackingSlipCollectionModel
        //        {
        //            ReturnAddress = AccessManager.Company.GetReturnAddressDto(),
        //            PackingSlips = orders,
        //        };

        //        var marketplaces = new MarketplaceKeeper(DbFactory);
        //        marketplaces.Init();
        //        model.Marketplaces = marketplaces.GetAll().Select(m => new PackingSlipMarketplaceInfo(m)).ToList();


        //        return View("PackingSlipWithCoupon", model);
        //    }
        //    catch (Exception ex)
        //    {
        //        LogE("GetPackingSlip", ex);
        //        throw;
        //    }
        //}

        public virtual ActionResult GetPackingSlipsForBatch(long batchId)
        {
            LogI("GetPackingSlipsForBatch, batchId=" + batchId);

            var orderIds       = Db.OrderBatches.GetOrderIdsForBatch(batchId, OrderStatusEnumEx.AllUnshippedWithShipped);
            var orders         = PackingSlipViewModel.GetList(Db, orderIds, SortMode.ByShippingMethodThenLocation, false).ToList();
            var companyAddress = new CompanyAddressService(AccessManager.Company);
            var batch          = Db.OrderBatches.Get(batchId);

            var model = new PackingSlipCollectionModel
            {
                BatchId   = batch.Id,
                BatchName = batch.Name,
                Date      = Time.GetAppNowTime(),

                ReturnAddress = companyAddress.GetReturnAddress(MarketIdentifier.Empty()),
                PackingSlips  = orders,
            };

            var marketplaces = new MarketplaceKeeper(DbFactory, false);

            marketplaces.Init();
            model.Marketplaces = marketplaces.GetAll().Select(m => new PackingSlipMarketplaceInfo(m)).ToList();


            return(View("PackingSlip", model));
        }
Пример #3
0
        public virtual ActionResult GetPackingSlip(long orderId)
        {
            LogI("GetPackingSlip, orderId=" + orderId);

            try
            {
                var companyAddress = new CompanyAddressService(AccessManager.Company);
                var orders         = PackingSlipViewModel.GetList(Db, new[] { orderId }, SortMode.None, true).ToList();
                var model          = new PackingSlipCollectionModel
                {
                    ReturnAddress = companyAddress.GetReturnAddress(MarketIdentifier.Empty()),
                    PackingSlips  = orders,
                };

                var marketplaces = new MarketplaceKeeper(DbFactory, false);
                marketplaces.Init();
                model.Marketplaces = marketplaces.GetAll().Select(m => new PackingSlipMarketplaceInfo(m)).ToList();


                return(View("PackingSlip", model));
            }
            catch (Exception ex)
            {
                LogE("GetPackingSlip", ex);
                throw;
            }
        }
Пример #4
0
        protected override void RunCallback()
        {
            var dbFactory = new DbFactory();
            var time      = new TimeService(dbFactory);
            var log       = GetLogger();
            var settings  = new SettingsService(dbFactory);

            var now = time.GetAppNowTime();

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

            log.Info("Checking Same Day");

            CompanyDTO company = null;

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

            var companyAddress    = new CompanyAddressService(company);
            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 checker = new AlertChecker(log, time, dbFactory, emailService, company);

            using (var db = dbFactory.GetRWDb())
            {
                checker.CheckSameDay(db);
                settings.SetSameDayLastCheck(time.GetUtcTime());
            }
        }
Пример #5
0
        public virtual ActionResult Index(string orderId)
        {
            LogI("Index, orderId=" + orderId);

            var company = AccessManager.Company;


            var model = new MailPageViewModel()
            {
                OrderId       = orderId,
                ReturnAddress = MailViewModel.GetFromAddress(CompanyAddress.GetReturnAddress(MarketIdentifier.Empty()), MarketplaceType.Amazon),
                PickupAddress = MailViewModel.GetFromAddress(CompanyAddress.GetPickupAddress(MarketIdentifier.Empty()), MarketplaceType.Amazon)
            };

            return(View(model));
        }
Пример #6
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();
                    }
                }
            }
        }
        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 fromAddressList = new CompanyAddressService(company);

            var serviceFactory = new ServiceFactory();
            var pdfMaker       = new PdfMakerByIText(GetLogger());
            var actionService  = new SystemActionService(log, time);
            var addressService = new AddressService(null,
                                                    fromAddressList.GetReturnAddress(MarketIdentifier.Empty()),
                                                    fromAddressList.GetPickupAddress(MarketIdentifier.Empty()));
            var emailSmtpSettings = SettingsBuilder.GetSmtpSettingsFromCompany(company, AppSettings.IsDebug, AppSettings.IsSampleLabels);
            var emailService      = new EmailService(GetLogger(), emailSmtpSettings, addressService);

            var weightService = new WeightService();

            var orderHistoryService = new OrderHistoryService(log, time, dbFactory);
            var batchManager        = new BatchManager(log, time, orderHistoryService, weightService);
            var labelBatchService   = new LabelBatchService(dbFactory,
                                                            actionService,
                                                            log,
                                                            time,
                                                            weightService,
                                                            serviceFactory,
                                                            emailService,
                                                            batchManager,
                                                            pdfMaker,
                                                            AddressService.Default,
                                                            orderHistoryService,
                                                            AppSettings.DefaultCustomType,
                                                            AppSettings.LabelDirectory,
                                                            AppSettings.ReserveDirectory,
                                                            AppSettings.TemplateDirectory,
                                                            new LabelBatchService.Config()
            {
                PrintErrorsToEmails = new[] { company.SellerEmail, company.SellerWarehouseEmailAddress },
                PrintErrorsCCEmails = new[] { EmailHelper.RaananEmail, EmailHelper.SupportDgtexEmail },
            },
                                                            AppSettings.IsSampleLabels);

            var autoPurchaseService = new LabelAutoBuyService(dbFactory,
                                                              log,
                                                              time,
                                                              batchManager,
                                                              labelBatchService,
                                                              actionService,
                                                              emailService,
                                                              weightService,
                                                              company.Id);

            autoPurchaseService.PurchaseAmazonNextDay();
        }
        protected override void RunCallback()
        {
            CompanyDTO company   = null;
            var        dbFactory = new DbFactory();
            var        time      = new TimeService(dbFactory);
            var        log       = GetLogger();

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

            var companyAddress = new CompanyAddressService(company);
            var addressService = new AddressService(null, companyAddress.GetReturnAddress(MarketIdentifier.Empty()), companyAddress.GetPickupAddress(MarketIdentifier.Empty()));
            var settings       = new SettingsService(dbFactory);

            //Checking email service, sent test message
            var emailSmtpSettings = SettingsBuilder.GetSmtpSettingsFromCompany(company, AppSettings.IsDebug, AppSettings.IsSampleLabels);
            var emailService      = new EmailService(GetLogger(), emailSmtpSettings, addressService);

            var lastSendDate = settings.GetSendDhlInvoiceNotification();

            var sizeMappingService = new SizeMappingService(log, time, dbFactory);
            var newIssues          = sizeMappingService.CheckItemsSizeMappingIssue();

            if (newIssues.Any())
            {
                var body = String.Join("<br/>",
                                       newIssues.Select(i => i.ASIN + ", marketSize: " + i.Size + ", styleSize: " + i.StyleSize));
                emailService.SendSystemEmailToAdmin("New size mapping issues, count: " + newIssues.Count,
                                                    body);

                log.Info("New issues: " + body);
            }
            else
            {
                log.Info("No new issues");
            }

            if (time.GetAppNowTime().DayOfWeek == DayOfWeek.Saturday)
            {
                var issueSummary = sizeMappingService.GetItemsSummaryWithSizeMappingIssue();
                var body         = String.Join("<br/>",
                                               issueSummary.Select(i => i.ASIN + ", marketSize: " + i.Size + ", styleSize: " + i.StyleSize));
                emailService.SendSystemEmailToAdmin("Size mapping issue summary, count: " + issueSummary.Count,
                                                    body);

                log.Info("Summary issues: " + body);
            }
        }
        public void ReProcessTrackInfoFull(IDbFactory dbFactory, string trackingNumber)
        {
            using (var db = dbFactory.GetRWDb())
            {
                var shippings = db.Orders.GetUnDeliveredShippingInfoes(_time.GetUtcTime(), false, null)
                                .Where(o => o.TrackingNumber == trackingNumber)
                                .OrderByDescending(o => o.OrderDate)
                                .ToList();

                shippings.AddRange(db.Orders.GetUnDeliveredMailInfoes(_time.GetUtcTime(), false, null)
                                   .Where(o => o.TrackingNumber == trackingNumber)
                                   .OrderByDescending(o => o.OrderDate)
                                   .ToList());

                var actionService       = new SystemActionService(_log, _time);
                var companyAddress      = new CompanyAddressService(_company);
                var addressService      = new AddressService(null, companyAddress.GetReturnAddress(MarketIdentifier.Empty()), companyAddress.GetPickupAddress(MarketIdentifier.Empty()));
                var notificationService = new NotificationService(_log, _time, dbFactory);

                var ruleList = new List <ITrackingRule>()
                {
                    new NeverShippedTrackingRule(_log, notificationService, _time),
                    new GetStuckTrackingRule(_log, notificationService, _time),
                    new NoticeLeftTrackingRule(_log, actionService, addressService, _time),
                    //new UndeliverableAsAddressedTrackingRule(_log, actionService, addressService, _emailService, _time)
                };

                var trackingService = new TrackingManager(_log,
                                                          actionService,
                                                          addressService,
                                                          _emailService,
                                                          _time,
                                                          ruleList);

                var trackingProvider = new ComposedUspsAndCanadaPostTrackingProvider(_log, _time, _company.USPSUserId, _company.CanadaPostKeys);

                var fedexInfo             = _company.ShipmentProviderInfoList.FirstOrDefault(sh => sh.Type == (int)ShipmentProviderType.FedexGeneral);
                var fedexTrackingProvider = new FedexTrackingApi(_log,
                                                                 _time,
                                                                 fedexInfo.EndPointUrl,
                                                                 fedexInfo.UserName,
                                                                 fedexInfo.Password,
                                                                 fedexInfo.Key1,
                                                                 fedexInfo.Key2,
                                                                 fedexInfo.Key3,
                                                                 _company.ShortName);

                //var dhlInfo = _company.ShipmentProviderInfoList.FirstOrDefault(sh => sh.Type == (int)ShipmentProviderType.Dhl);
                //var trackingProvider = new DhlTrackingProvider(_log,
                //    _time,
                //    dhlInfo.EndPointUrl,
                //    dhlInfo.UserName,
                //    dhlInfo.Password,
                //    dhlInfo.Key1);

                trackingService.UpdateOrderTracking(db, _company, shippings, fedexTrackingProvider);
            }
        }
        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");
        }
Пример #11
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
            }));
        }
Пример #12
0
        protected override void RunCallback()
        {
            CompanyDTO company   = null;
            var        dbFactory = new DbFactory();
            var        time      = new TimeService(dbFactory);
            var        log       = GetLogger();

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

            var companyAddress = new CompanyAddressService(company);
            var addressService = new AddressService(null, companyAddress.GetReturnAddress(MarketIdentifier.Empty()), companyAddress.GetPickupAddress(MarketIdentifier.Empty()));
            //Checking email service, sent test message
            var emailSmtpSettings = SettingsBuilder.GetSmtpSettingsFromCompany(company, AppSettings.IsDebug, AppSettings.IsSampleLabels);
            var emailService      = new EmailService(GetLogger(), emailSmtpSettings, addressService);

            var supportNotificatons = new List <ISupportNotification>()
            {
                new ListingCreationIssuesNotification(dbFactory, emailService, log, time),
                new QtyDistributionSupportNotification(dbFactory, emailService, log, time),
                new SubstractQtySupportNotification(dbFactory, emailService, log, time),
                new UnprocessedRefundSupportNotification(dbFactory, emailService, log, time)
            };

            log.Info("Notification count: " + supportNotificatons.Count());

            var currentDate          = time.GetAppNowTime();
            var nowTime              = new TimeSpan(currentDate.Hour, currentDate.Minute, currentDate.Second);
            var notificationToLaunch = supportNotificatons.Where(n => n.When.Any(w => Math.Abs((w - nowTime).TotalSeconds) < 30)).ToList();

            if (notificationToLaunch.Count > 0)
            {
                log.Info("Notification count: " + notificationToLaunch.Count());

                foreach (var notification in notificationToLaunch)
                {
                    try
                    {
                        log.Info("Begin check " + notification.Name);
                        notification.Check();
                        log.Info("End check " + notification.Name);
                    }
                    catch (Exception ex)
                    {
                        log.Error("Notification error: " + notification.Name, ex);
                    }
                }
            }
        }
Пример #13
0
        public virtual ActionResult Submit(OrderEditViewModel model)
        {
            LogI("Submit, model=" + model);

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

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

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

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

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

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

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

                return(Json(new UpdateRowViewModel(rowModel,
                                                   model.BatchId.HasValue ? "grid_" + model.BatchId.Value : "grid",
                                                   null,
                                                   false)));
            }
            return(PartialView("OrderEdit", model));
        }
Пример #14
0
        public virtual ActionResult SetCustomShipping(long orderId,
                                                      IList <CustomShippingItemViewModel> items)
        {
            LogI("SetCustomShipping, orderId=" + orderId + ", items=" + String.Join(", ", items.Select(i => i.ToString()).ToList()));

            var rateProviders = ServiceFactory.GetShipmentProviders(LogService,
                                                                    Time,
                                                                    DbFactory,
                                                                    WeightService,
                                                                    AccessManager.Company.ShipmentProviderInfoList,
                                                                    null,
                                                                    null,
                                                                    null,
                                                                    null);

            var result = CustomShippingItemViewModel.Apply(Db,
                                                           LogService,
                                                           Time,
                                                           WeightService,
                                                           orderId,
                                                           rateProviders,
                                                           CompanyAddress.GetReturnAddress(MarketIdentifier.Empty()),
                                                           CompanyAddress.GetPickupAddress(MarketIdentifier.Empty()),
                                                           items,
                                                           AccessManager.IsFulfilment);

            if (result.IsSuccess)
            {
                return(JsonGet(ValueResult <IList <SelectListShippingOption> > .Success("", result.Data)));
            }
            return(JsonGet(ValueResult <IList <SelectListShippingOption> > .Error(result.Message)));
        }
Пример #15
0
        protected override void RunCallback()
        {
            var        dbFactory = new DbFactory();
            var        time      = new TimeService(dbFactory);
            var        log       = GetLogger();
            CompanyDTO company   = null;

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

            var companyAddress    = new CompanyAddressService(company);
            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 kioskBarcodeService = new KioskBarcodeService(dbFactory,
                                                              emailService,
                                                              time,
                                                              log);

            kioskBarcodeService.CheckOrders();

            log.Info("After check orders");
        }
        public void UpdateDHLTrackOrders()
        {
            while (true)
            {
                using (var db = new UnitOfWork(_log))
                {
                    var service             = new UpdateOrderTrackingStatus(_company.Id, null, TimeSpan.FromSeconds(10));
                    var actionService       = new SystemActionService(_log, _time);
                    var dbFactory           = new DbFactory();
                    var notificationService = new NotificationService(_log, _time, dbFactory);
                    var companyAddress      = new CompanyAddressService(_company);
                    var addressService      = new AddressService(null, companyAddress.GetReturnAddress(MarketIdentifier.Empty()), companyAddress.GetPickupAddress(MarketIdentifier.Empty()));
                    var ruleList            = new List <ITrackingRule>()
                    {
                    };

                    var dhlInfo = _company.ShipmentProviderInfoList.FirstOrDefault(sh => sh.Type == (int)ShipmentProviderType.Dhl);

                    var trackingService = new TrackingManager(_log, actionService, addressService, _emailService, _time, ruleList);

                    var dhlTrackingProvider = new DhlTrackingProvider(_log,
                                                                      _time,
                                                                      dhlInfo.EndPointUrl,
                                                                      dhlInfo.UserName,
                                                                      dhlInfo.Password,
                                                                      dhlInfo.Key1);

                    service.UpdateAllShippedOrderStatus(trackingService,
                                                        _time,
                                                        db,
                                                        dhlTrackingProvider,
                                                        _company);
                }
                Thread.Sleep(TimeSpan.FromMinutes(0));
            }
        }
        public void ReProcessTrackNotifications(IDbFactory dbFactory)
        {
            var from      = _time.GetAppNowTime().AddDays(-42); //NOTE: Possible/not sure: After 42 days USPS not update/keep info
            var orderFrom = _time.GetAppNowTime().AddDays(-90);

            using (var db = dbFactory.GetRWDb())
            {
                var shippings = db.Orders.GetUnDeliveredShippingInfoes(_time.GetUtcTime(), false, null)
                                .Where(o => (!o.TrackingStateDate.HasValue || o.TrackingStateDate.Value > from) &&
                                       o.OrderDate > orderFrom)
                                .OrderBy(o => o.OrderDate)
                                .ToList();

                shippings.AddRange(db.Orders.GetUnDeliveredMailInfoes(_time.GetUtcTime(), false, null)
                                   .Where(o => (!o.TrackingStateDate.HasValue || o.TrackingStateDate.Value > from) &&
                                          o.OrderDate > orderFrom)
                                   .OrderBy(o => o.OrderDate)
                                   .ToList());

                var actionService       = new SystemActionService(_log, _time);
                var companyAddress      = new CompanyAddressService(_company);
                var addressService      = new AddressService(null, companyAddress.GetReturnAddress(MarketIdentifier.Empty()), companyAddress.GetPickupAddress(MarketIdentifier.Empty()));
                var notificationService = new NotificationService(_log, _time, dbFactory);

                var ruleList = new List <ITrackingRule>()
                {
                    //new NeverShippedTrackingRule(_log, notificationService, _time),
                    //new GetStuckTrackingRule(_log, notificationService, _time),
                    //new NoticeLeftTrackingRule(actionService, _log)
                };

                var trackingService = new TrackingManager(_log,
                                                          actionService,
                                                          addressService,
                                                          _emailService,
                                                          _time,
                                                          ruleList);


                foreach (var shipping in shippings)
                {
                    trackingService.CheckRules(db,
                                               shipping,
                                               shipping.TrackingStateEvent,
                                               shipping.TrackingStateDate,
                                               new List <TrackingRecord>()
                    {
                        new TrackingRecord()
                        {
                            Date    = shipping.TrackingStateDate,
                            Message = shipping.TrackingStateEvent,
                        }
                    },
                                               ruleList);
                }
            }
        }
Пример #18
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");
                    }
                }
            }
        }
Пример #19
0
        protected override void RunCallback()
        {
            CompanyDTO company   = null;
            var        dbFactory = new DbFactory();
            var        time      = new TimeService(dbFactory);

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

            var companyAddress = new CompanyAddressService(company);
            var addressService = new AddressService(null, companyAddress.GetReturnAddress(MarketIdentifier.Empty()), companyAddress.GetPickupAddress(MarketIdentifier.Empty()));
            //Checking email service, sent test message
            var emailSmtpSettings = SettingsBuilder.GetSmtpSettingsFromCompany(company, AppSettings.IsDebug, AppSettings.IsSampleLabels);
            var emailService      = new EmailService(GetLogger(), emailSmtpSettings, addressService);

            var fromDate = time.GetAppNowTime().AddDays(-5);
            var emails   = new List <EmailOrderDTO>();

            using (var db = dbFactory.GetRDb())
            {
                emails = db.Emails.GetAllWithOrder(new EmailSearchFilter()
                {
                    ResponseStatus = (int)EmailResponseStatusFilterEnum.ResponseNeeded
                })
                         .Where(e => e.ReceiveDate > fromDate)
                         .ToList();
            }

            emailService.SendEmailStatusNotification(emails);
        }
Пример #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();
                    }
                }
            }
        }
        public void RePrintLastPack(long packId)
        {
            IList <long> orderIds;
            var          labelService   = new LabelService(GetShipmentProviders(_company), _log, _time, _dbFactory, _emailService, _pdfMaker, AddressService.Default);
            var          companyAddress = new CompanyAddressService(_company);
            var          addressService = new AddressService(new List <IAddressCheckService>(), companyAddress.GetReturnAddress(MarketIdentifier.Empty()), companyAddress.GetPickupAddress(MarketIdentifier.Empty()));

            using (var db = new UnitOfWork(_log))
            {
                //packId = 329;// db.GetSet<LabelPrintPack>().OrderByDescending(l => l.CreateDate).FirstOrDefault().Id;
//                var shippings = db.OrderShippingInfos.GetByLabelPackId(packId);
//                orderIds = shippings.Select(o => o.OrderId).ToList();
//#if DEBUG
//                //orderIds = orderIds.Take(3).ToList();
//#endif
//                labelService.PrintLabels(_log,
//                    db,
//                    addressService,
//                    _user,
//                    new EmptySyncInformer(SyncType.PostagePurchase),
//                    shippings.AsQueryable(),
//                    false,
//                    null,
//                    SortMode.ByLocation,
//                    AppSettings.LabelDirectory,
//                   AppSettings.IsSampleLabels);

//                string orderListAsString = String.Join(",", orderIds);
//                _log.Debug(orderListAsString);
            }
        }
Пример #22
0
        public IList <CheckResult <AddressDTO> > CallCheckAddress(IUnitOfWork db, string orderId)
        {
            var order                = db.Orders.GetFiltered(o => o.AmazonIdentifier == orderId).First();
            var orderInfo            = db.ItemOrderMappings.GetSelectedOrdersWithItems(null, new[] { order.Id }, includeSourceItems: false).First();
            var addressTo            = db.Orders.GetAddressInfo(orderInfo.OrderId);
            var dbFactory            = new DbFactory();
            var time                 = new TimeService(dbFactory);
            var serviceFactory       = new ServiceFactory();
            var addressCheckServices = serviceFactory.GetAddressCheckServices(_log,
                                                                              _time,
                                                                              dbFactory,
                                                                              _company.AddressProviderInfoList);
            var priceService = new PriceService(dbFactory);

            var        companyAddress   = new CompanyAddressService(_company);
            var        addressService   = new AddressService(addressCheckServices, companyAddress.GetReturnAddress(MarketIdentifier.Empty()), companyAddress.GetPickupAddress(MarketIdentifier.Empty()));
            AddressDTO outAddress       = null;
            var        validatorService = new OrderValidatorService(_log, _dbFactory, null, null, null, null, priceService, _htmlScraper, addressService, null, null, time, _company);

            var result = validatorService.CheckAddress(CallSource.Service,
                                                       db,
                                                       addressTo,
                                                       order.Id,
                                                       out outAddress);


            Console.WriteLine("Validation result: " + result);

            return(result);
        }
Пример #23
0
        protected override void RunCallback()
        {
            CompanyDTO company   = null;
            var        dbFactory = new DbFactory();
            var        time      = new TimeService(dbFactory);
            var        settings  = new SettingsService(dbFactory);
            var        log       = GetLogger();

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

            var companyAddress    = new CompanyAddressService(company);
            var addressService    = new AddressService(null, companyAddress.GetReturnAddress(MarketIdentifier.Empty()), companyAddress.GetPickupAddress(MarketIdentifier.Empty()));
            var emailSmtpSettings = SettingsBuilder.GetSmtpSettingsFromCompany(company, AppSettings.IsDebug, AppSettings.IsSampleLabels);

            var actionService = new SystemActionService(log, time);
            var emailService  = new EmailService(log, emailSmtpSettings, addressService);

            var lastSyncDate = settings.GetOrdersAdjustmentDate(_api.Market, _api.MarketplaceId);

            using (var db = dbFactory.GetRWDb())
            {
                LogWrite("Last sync date=" + lastSyncDate);

                if (!lastSyncDate.HasValue ||
                    (time.GetUtcTime() - lastSyncDate) > _betweenProcessingInverval)
                {
                    var updater = new BaseOrderRefundService(_api, actionService, emailService, log, time);
                    updater.ProcessRefunds(db, null);
                    settings.SetOrdersAdjustmentDate(time.GetUtcTime(), _api.Market, _api.MarketplaceId);
                }
            }
        }
Пример #24
0
        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 autoPurchaseTime = AppSettings.OverdueAutoPurchaseTime;

            var companyAddress = new CompanyAddressService(company);
            var addressService = new AddressService(null, companyAddress.GetReturnAddress(MarketIdentifier.Empty()), companyAddress.GetPickupAddress(MarketIdentifier.Empty()));
            //Checking email service, sent test message
            var emailSmtpSettings = SettingsBuilder.GetSmtpSettingsFromCompany(company, AppSettings.IsDebug, AppSettings.IsSampleLabels);
            var emailService      = new EmailService(GetLogger(), emailSmtpSettings, addressService);

            var checker = new AlertChecker(log, time, dbFactory, emailService, company);

            using (var db = dbFactory.GetRWDb())
            {
                checker.CheckOverdue(db, now, autoPurchaseTime);
            }
        }
Пример #25
0
        public void Create(ILogService log,
                           ITime time,
                           IQuantityManager quantityManager,
                           IDbFactory dbFactory,
                           IWeightService weightService,
                           IShippingService shippingService,
                           IAutoCreateListingService createListingService,
                           ISettingsService settingService,
                           IEmailService emailService,
                           ISystemActionService actionService,
                           IHtmlScraperService htmlScraper,
                           IOrderHistoryService orderHistory,
                           IPriceService priceService,
                           CompanyDTO company,
                           DateTime when,
                           long?by)
        {
            var syncInfo      = new EmptySyncInformer(log, SyncType.Orders);
            var market        = (int)MarketType.OfflineOrders;
            var marketplaceId = MarketplaceKeeper.ManuallyCreated;

            var orderItems = new List <ListingOrderDTO>();

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

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

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

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

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

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

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

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

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

                    index++;
                }

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

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

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

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

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

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

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

                Items = orderItems,
            };

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

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

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

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

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

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

                    if (!String.IsNullOrEmpty(OrderNumber))
                    {
                        synchronizer.ProcessSpecifiedOrder(db, OrderNumber);
                        Messages.Add(MessageString.Success("The order has been successfully created, order #: " + OrderNumber));
                    }
                }
                catch (Exception ex)
                {
                    Messages.Add(MessageString.Error(ex.Message));
                }
            }
        }
Пример #26
0
        public void FillIBCRateTable()
        {
            using (var db = _dbFactory.GetRWDb())
            {
                var newRateTable = new List <RateByCountryDTO>();
                var addressList  = new List <AddressDTO>()
                {
                    //RateHelper.GetSampleUSAddress(),
                    RateHelper.GetSampleCAAddress(),
                    RateHelper.GetSampleUKAddress()
                };

                var serviceFactory = new ServiceFactory();

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

                var stampsRateProvider = rateProviders.FirstOrDefault(r => r.Type == ShipmentProviderType.IBC);
                var companyAddress     = new CompanyAddressService(_company);

                var shippingSizes = new string[] { //"S",
                    "XL"
                };
                var internationalPackages = new string[] { "", "" };

                for (var oz = 1; oz < 50; oz++)
                {
                    //International Package Type: Regular, Flat
                    //Shipping Size: S, XL

                    foreach (var address in addressList)
                    {
                        foreach (var shippingSize in shippingSizes)
                        {
                            var packageType = shippingSize == "XL" ?
                                              PackageTypeCode.Regular :
                                              (ShippingUtils.IsInternational(address.Country) ? PackageTypeCode.LargeEnvelopeOrFlat : PackageTypeCode.Flat);

                            var shippintType = ShippingUtils.IsInternational(address.Country)
                                ? ShippingTypeCode.IStandard
                                : ShippingTypeCode.Standard;

                            var rate = RateHelper.GetRougeChipestRate(_log,
                                                                      stampsRateProvider,
                                                                      companyAddress.GetReturnAddress(MarketIdentifier.Empty()),
                                                                      address,
                                                                      oz,
                                                                      DateTime.Today,
                                                                      shippintType,
                                                                      packageType);

                            if (rate != null && rate.Amount.HasValue)
                            {
                                _log.Info("Add rate: " + address.Country + ", " + oz + "oz, " + shippingSize + ", " + rate.Amount.Value + ", package=" + ((PackageTypeCode)rate.PackageTypeUniversal).ToString() + ", shippingType=" + ((ShippingTypeCode)rate.ServiceTypeUniversal).ToString());
                                newRateTable.Add(new RateByCountryDTO()
                                {
                                    Cost             = rate.Amount.Value,
                                    Country          = address.Country,
                                    Weight           = oz,
                                    PackageType      = packageType.ToString(), //NOTE: need to use source package type, no matter what actual package is ((PackageTypeCode) rate.PackageTypeUniversal).ToString(),
                                    ShipmentProvider = stampsRateProvider.Type.ToString(),
                                    UpdateDate       = _time.GetAppNowTime()
                                });
                            }
                            else
                            {
                                _log.Info("No rates: " + oz + "oz, " + shippingSize);
                            }
                        }
                    }
                }

                var existRates = db.RateByCountries.GetAll();
                foreach (var rate in newRateTable)
                {
                    var exist = existRates.FirstOrDefault(r => r.Country == rate.Country &&
                                                          r.PackageType == rate.PackageType &&
                                                          r.Weight == rate.Weight);
                    if (exist == null)
                    {
                        db.RateByCountries.Add(new RateByCountry()
                        {
                            Country          = rate.Country,
                            PackageType      = rate.PackageType,
                            Cost             = rate.Cost,
                            Weight           = rate.Weight,
                            ShipmentProvider = rate.ShipmentProvider,
                            UpdateDate       = rate.UpdateDate,
                        });
                    }
                    else
                    {
                        exist.Cost             = rate.Cost;
                        exist.ShipmentProvider = rate.ShipmentProvider;
                    }
                }
                db.Commit();
            }
        }
        protected override void RunCallback()
        {
            var dbFactory           = new DbFactory();
            var time                = new TimeService(dbFactory);
            var log                 = GetLogger();
            var orderHistoryService = new OrderHistoryService(log, time, dbFactory);
            var serviceFactory      = new ServiceFactory();

            CompanyDTO company = null;

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

            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 addressChecker = new AddressChecker(log, dbFactory, addressService, orderHistoryService, time);

            using (var db = dbFactory.GetRWDb())
            {
                addressChecker.RecheckAddressesWithException();
            }
        }
        public void UpdateUSPSTrackOrders()
        {
            while (true)
            {
                using (var db = new UnitOfWork(_log))
                {
                    var service             = new UpdateOrderTrackingStatus(_company.Id, null, TimeSpan.FromSeconds(10));
                    var actionService       = new SystemActionService(_log, _time);
                    var dbFactory           = new DbFactory();
                    var notificationService = new NotificationService(_log, _time, dbFactory);
                    var companyAddress      = new CompanyAddressService(_company);
                    var addressService      = new AddressService(null, companyAddress.GetReturnAddress(MarketIdentifier.Empty()), companyAddress.GetPickupAddress(MarketIdentifier.Empty()));
                    var ruleList            = new List <ITrackingRule>()
                    {
                    };

                    var trackingService = new TrackingManager(_log, actionService, addressService, _emailService, _time, ruleList);

                    var uspsTrackingProvider = new ComposedUspsAndCanadaPostTrackingProvider(_log, _time, _company.USPSUserId, _company.CanadaPostKeys);

                    service.UpdateAllShippedOrderStatus(trackingService,
                                                        _time,
                                                        db,
                                                        uspsTrackingProvider,
                                                        _company);
                }
                Thread.Sleep(TimeSpan.FromMinutes(0));
            }
        }
        public static ShippingMethodViewModel GetQuickPrintLabelRate(IUnitOfWork db,
                                                                     IDbFactory dbFactory,
                                                                     IServiceFactory serviceFactory,
                                                                     IShippingService shippingService,
                                                                     CompanyDTO company,
                                                                     ICompanyAddressService companyAddress,
                                                                     ILogService log,
                                                                     ITime time,
                                                                     IWeightService weightService,
                                                                     string orderNumber)
        {
            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;

            var rateProvider = serviceFactory.GetShipmentProviderByType((ShipmentProviderType)model.ShipmentProviderId,
                                                                        log,
                                                                        time,
                                                                        dbFactory,
                                                                        weightService,
                                                                        company.ShipmentProviderInfoList,
                                                                        null,
                                                                        null,
                                                                        null,
                                                                        null);

            var shippingOptionsResult           = model.GetShippingOptionsModel(db, time, log, rateProvider, shippingService, weightService);
            ShippingMethodViewModel chipestRate = null;

            if (shippingOptionsResult.IsSuccess)
            {
                chipestRate = shippingOptionsResult.Data.OrderBy(o => o.Rate).FirstOrDefault();
            }
            return(chipestRate);
        }
Пример #30
0
        protected override void RunCallback()
        {
            var        dbFactory = new DbFactory();
            CompanyDTO company;

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

            var time                = new TimeService(dbFactory);
            var log                 = GetLogger();
            var serviceFactory      = new ServiceFactory();
            var actionService       = new SystemActionService(GetLogger(), time);
            var notificationService = new NotificationService(GetLogger(), time, dbFactory);
            var companyAddress      = new CompanyAddressService(company);
            var addressService      = new AddressService(null, companyAddress.GetReturnAddress(MarketIdentifier.Empty()), companyAddress.GetPickupAddress(MarketIdentifier.Empty()));

            var emailService = new EmailService(GetLogger(),
                                                SettingsBuilder.GetSmtpSettingsFromCompany(company, AppSettings.IsDebug, AppSettings.IsSampleLabels),
                                                addressService);


            var ruleList = new List <ITrackingRule>()
            {
                new NeverShippedTrackingRule(GetLogger(), notificationService, time),
                new GetStuckTrackingRule(GetLogger(), notificationService, time),
                new NoticeLeftTrackingRule(GetLogger(), actionService, addressService, time),
                new UndeliverableAsAddressedTrackingRule(GetLogger(), actionService, addressService, emailService, time)
            };

            var trackingService = new TrackingManager(GetLogger(),
                                                      actionService,
                                                      addressService,
                                                      emailService,
                                                      time,
                                                      ruleList);

            var trackingProviderTypes = new List <ShipmentProviderType>()
            {
                ShipmentProviderType.Stamps,
                ShipmentProviderType.Dhl,
                //ShipmentProviderType.DhlECom,
                ShipmentProviderType.FedexOneRate,
            };

            using (var db = dbFactory.GetRWDb())
            {
                foreach (var trackingProviderType in trackingProviderTypes)
                {
                    try
                    {
                        var trackingProvider = serviceFactory.GetTrackingProviderByType(trackingProviderType,
                                                                                        company,
                                                                                        company.ShipmentProviderInfoList,
                                                                                        dbFactory,
                                                                                        log,
                                                                                        time);

                        if (trackingProvider == null)
                        {
                            continue;
                        }

                        LogWrite("UpdateAllShippedOrderStatus " + trackingProviderType);
                        UpdateAllShippedOrderStatus(trackingService,
                                                    time,
                                                    db,
                                                    trackingProvider,
                                                    company);
                    }
                    catch (Exception ex)
                    {
                        LogError("TrackingProviderType: " + trackingProviderType, ex);
                    }
                }
            }
        }