예제 #1
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);
        }
예제 #2
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);
            }
        }
        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");
        }
예제 #4
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);
        }
예제 #5
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;
            }
        }
예제 #6
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
            }));
        }
예제 #7
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");
        }
예제 #8
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));
        }
        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);
            }
        }
예제 #10
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);
                }
            }
        }
        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));
            }
        }
        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 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);
            }
        }
        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);
                }
            }
        }
예제 #15
0
        public void UpgradeOrderList(IList <long> orderIds)
        {
            var syncInfo       = new EmptySyncInformer(_log, SyncType.Orders);
            var serviceFactory = new ServiceFactory();
            var weightService  = new WeightService();
            var messageService = new SystemMessageService(_log, _time, _dbFactory);

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

            var companyAddress = new CompanyAddressService(_company);

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

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

                    if (synchronizer.UIUpdate(db, dtoOrder, false, false, false, null))
                    {
                        _log.Info("Success");
                    }
                    else
                    {
                        _log.Info("Failed");
                    }
                }
            }
        }
        public void TestGetOneRateRates(string orderId)
        {
            var weightService  = new WeightService();
            var companyAddress = new CompanyAddressService(_company);

            using (var db = _dbFactory.GetRWDb())
            {
                var order                 = db.ItemOrderMappings.GetOrderWithItems(weightService, orderId, unmaskReferenceStyle: false, includeSourceItems: true);
                var shippingService       = ShippingUtils.InitialShippingServiceIncludeUpgrade(order.InitialServiceType, order.UpgradeLevel); //order.ShippingService
                var orderItemInfoes       = OrderHelper.BuildAndGroupOrderItems(order.Items);
                var sourceOrderItemInfoes = OrderHelper.BuildAndGroupOrderItems(order.SourceItems);

                var serviceFactory = new ServiceFactory();

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

                var fedexRateProvider = rateProviders.FirstOrDefault(r => r.Type == ShipmentProviderType.FedexOneRate);

                var rates = fedexRateProvider.GetLocalRate(
                    companyAddress.GetReturnAddress(order.GetMarketId()),
                    companyAddress.GetPickupAddress(order.GetMarketId()),
                    order.GetAddressDto(),
                    _time.GetAppNowTime(),
                    order.WeightD,
                    null,
                    order.IsInsured ? order.TotalPrice : 0,
                    order.IsSignConfirmation,
                    new OrderRateInfo()
                {
                    ShippingService    = shippingService,
                    InitialServiceType = order.InitialServiceType,
                    OrderNumber        = order.OrderId,
                    Items       = orderItemInfoes,
                    SourceItems = sourceOrderItemInfoes,
                    TotalPrice  = order.TotalPrice,
                    Currency    = order.TotalPriceCurrency,
                },
                    RetryModeType.Normal);


                _log.Info("Rates: " + rates.Rates.Count);
            }
        }
예제 #17
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);
                    }
                }
            }
        }
        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);
            }
        }
예제 #19
0
 public void PopulateInfo(int CompanyAddressId)
 {
     isCompany = isCompany;
     LoadForm();
     using (var db = new WTCCeresEntities())
     {
         cp = CompanyAddressService.GetById(CompanyAddressId, db);
         rc = cp.RegionCity;
         country1ComboBox1.SelectedValue   = rc.CountryRegion.CountryId;
         cboCity.SelectedValue             = rc.RegionCityId;
         address1TextBox2.Text             = cp.StreetAddress;
         locationDescription1TextBox1.Text = cp.AddressDescription;
         postal1TextBox1.Text = cp.ZipCode;
         phone1TextBox.Text   = cp.Phone;
         fax1TextBox.Text     = cp.Fax;
     }
 }
예제 #20
0
        private void BunifuButton1_Click(object sender, EventArgs e)
        {
            var cpService = new CompanyAddressService();

            cp.StreetAddress      = MdlDataCleasing.TrimAll(address1TextBox2.Text);
            cp.AddressDescription = MdlDataCleasing.TrimAll(locationDescription1TextBox1.Text);
            cp.ZipCode            = MdlDataCleasing.TrimAll(postal1TextBox1.Text);
            cp.Phone        = MdlDataCleasing.TrimAll(phone1TextBox.Text);
            cp.Fax          = MdlDataCleasing.TrimAll(fax1TextBox.Text);
            cp.RegionCityId = (int?)cboCity.SelectedValue;
            using (var db = new WTCCeresEntities())
            {
                if (cpService.AddOrUpdate(cp, db))
                {
                    My.MyProject.Forms.FrmAddOrganization.addrList.Add(cp);
                    My.MyProject.Forms.FrmAddOrganization.CompanyAddressBindingSource.DataSource = null;
                    My.MyProject.Forms.FrmAddOrganization.CompanyAddressBindingSource.DataSource = My.MyProject.Forms.FrmAddOrganization.addrList;
                    Close();
                }
            }
        }
예제 #21
0
        public static ShippingMethodViewModel GetQuickPrintLabelRate(IUnitOfWork db,
                                                                     IDbFactory dbFactory,
                                                                     IServiceFactory serviceFactory,
                                                                     IShippingService shippingService,
                                                                     CompanyDTO company,
                                                                     ILogService log,
                                                                     ITime time,
                                                                     IWeightService weightService,
                                                                     string orderNumber)
        {
            var companyAddress = new CompanyAddressService(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;

            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);
        }
        public void UpdateFedexTrackOrders()
        {
            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 fedexInfo       = _company.ShipmentProviderInfoList.FirstOrDefault(sh => sh.Type == (int)ShipmentProviderType.FedexOneRate);

                    var fedexTrackingProvider = new FedexTrackingApi(_log,
                                                                     _time,
                                                                     fedexInfo.EndPointUrl,
                                                                     fedexInfo.UserName,
                                                                     fedexInfo.Password,
                                                                     fedexInfo.Key1,
                                                                     fedexInfo.Key2,
                                                                     fedexInfo.Key3,
                                                                     _company.ShortName);

                    service.UpdateAllShippedOrderStatus(trackingService,
                                                        _time,
                                                        db,
                                                        fedexTrackingProvider,
                                                        _company);
                }
                Thread.Sleep(TimeSpan.FromMinutes(0));
            }
        }
예제 #23
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());
            }
        }
예제 #24
0
 private void LoadCountryAndCity()
 {
     if (Conversions.ToBoolean(Operators.ConditionalCompareObjectNotEqual(cboCompany.SelectedValue, null, false)))
     {
         if (string.IsNullOrEmpty(cboCompany.SelectedValue.ToString()) == false)
         {
             if (Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(cboCompany.SelectedValue, 0, false)))
             {
                 cboCountry.Text = "";
                 txtCity.Text    = "";
             }
             else
             {
                 using (var db = new WTCCeresEntities())
                 {
                     var L = CompanyAddressService.GetCompanyAddressByCompanyId(Conversions.ToInteger(cboCompany.SelectedValue), db).ToList();
                     foreach (var item in L)
                     {
                         cboCountry.Text = item.RegionCity.CountryRegion.Country.CountryName.ToUpper();
                         txtCity.Text    = item.RegionCity.CityName.ToUpper();
                     }
                 }
             }
         }
         else
         {
             cboCountry.Text = "";
             txtCity.Text    = "";
         }
     }
     else
     {
         cboCountry.Text = "";
         txtCity.Text    = "";
     }
 }
예제 #25
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();
                    }
                }
            }
        }
예제 #26
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));
                }
            }
        }
        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();
        }
예제 #28
0
        public void ProcessSystemAction(CancellationToken cancelToken)
        {
            var syncInfo = new EmptySyncInformer(_log, SyncType.Orders);

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

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

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

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

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

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

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

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

                db.Commit();
            }
        }
        public void GetDhlInvoice()
        {
            using (var db = _dbFactory.GetRWDb())
            {
                var orderIdList = from o in db.Orders.GetAll()
                                  join sh in db.OrderShippingInfos.GetAll() on o.Id equals sh.OrderId
                                  where o.BatchId == 1907 &&
                                  sh.IsActive &&
                                  (sh.ShippingMethodId == ShippingUtils.DhlExpressWorldWideShippingMethodId ||
                                   sh.ShippingMethodId == ShippingUtils.AmazonDhlExpressMXShippingMethodId)
                                  select o.Id;

                var shippingList =
                    db.OrderShippingInfos.GetOrderInfoWithItems(_weightService,
                                                                orderIdList.ToList(),
                                                                SortMode.ByLocation,
                                                                unmaskReferenceStyle: false,
                                                                includeSourceItems: false).ToList();

                var companyAddress = new CompanyAddressService(_company);

                foreach (var shippingInfo in shippingList)
                {
                    var toAddress     = db.Orders.GetAddressInfo(shippingInfo.OrderAmazonId);
                    var pickupAddress = companyAddress.GetPickupAddress(shippingInfo.GetMarketId());

                    _log.Info("Begin generate invoice");
                    try
                    {
                        var trackingNumber = shippingInfo.TrackingNumber;

                        var invoiceFileName = "~\\Labels\\invoice_" + trackingNumber + "_" +
                                              DateTime.UtcNow.Ticks + ".pdf";
                        var invoiceFilePath   = _outputDirectory + invoiceFileName.Trim(new[] { '~' });
                        var commercialInvoice = CommercialInvoiceHelper.BuildCommercialInvoice(_templateDirectory,
                                                                                               shippingInfo.OrderAmazonId,
                                                                                               shippingInfo,
                                                                                               pickupAddress,
                                                                                               toAddress,
                                                                                               shippingInfo.Items,
                                                                                               trackingNumber,
                                                                                               shippingInfo.ShippingDate.Value);
                        try
                        {
                            var dbShippingInfo = db.OrderShippingInfos.Get(shippingInfo.Id);
                            var labels         = (dbShippingInfo.LabelPath ?? "").Split(";".ToCharArray());
                            if (labels.Count() == 1)
                            {
                                FileHelper.WriteToFile(commercialInvoice, invoiceFilePath);

                                dbShippingInfo.LabelPath += ";" + invoiceFileName;
                                db.Commit();
                            }
                        }
                        catch (Exception ex)
                        {
                            //NOTE: continue all processing, label content we can get later using GetShipment
                            _log.Fatal("Can't save label, path=" + invoiceFilePath, ex);

                            var reserveInvoiceFilePath = _reserveDirectory + invoiceFileName.Trim(new[] { '~' });
                            try
                            {
                                FileHelper.WriteToFile(commercialInvoice, reserveInvoiceFilePath);
                            }
                            catch (Exception exInner)
                            {
                                _log.Fatal("Can't save invoice, path=" + reserveInvoiceFilePath, exInner);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _log.Error("Generate Commercial invoice", ex);
                    }
                }
            }
        }
예제 #30
0
        public void PopulateInfo(int companyId)
        {
            firstLoad = true;
            addrList.Clear();
            loadForm();
            using (var db = new WTCCeresEntities())
            {
                c       = CompanyService.GetById(companyId, db);
                cctList = CompanyCompanyTypeService.GetByCompanyId(companyId, db);
                for (int i = 0, loopTo = cblCompanyType.Items.Count - 1; i <= loopTo; i++)
                {
                    CompanyType isInCheckList = (CompanyType)cblCompanyType.Items[i];

                    bool typeExistsInList = cctList.Where(c => Operators.ConditionalCompareObjectEqual(c.CompanyTypeId, isInCheckList.CompanyTypeId, false)).Count() > 0;
                    if (typeExistsInList)
                    {
                        cblCompanyType.SetItemChecked(i, true);
                    }
                }

                cboCompanyCategory.SelectedValue = c.CompanyCategoryId;
                tbCode.Text      = c.CompanyCode;
                tbName.Text      = c.CompanyName;
                tbEmail.Text     = c.Email;
                tbWebsite.Text   = c.Website;
                tbAttention.Text = c.Attention;
                tbNotes.Text     = c.Notes;
                if (!Information.IsNothing(c.Rating))
                {
                    SetStarRate((int)c.Rating);
                }
                else
                {
                    SetStarRate(1);
                }

                addrList = CompanyAddressService.GetCompanyAddressByCompanyId(companyId, db);
                CompanyAddressBindingSource.DataSource = addrList;
                if (c.CompanyCategoryId != (int)MdlEnum.CompanyCategory.VENDOR)
                {
                    ccrt = CompanyCustomerRateTypeService.GetByCompanyId(companyId, db);
                    if (!Information.IsNothing(ccrt))
                    {
                        cboRateTier.SelectedValue = ccrt.CustomerRateTypeId;
                    }
                    else
                    {
                        ccrt                      = new CompanyCustomerRateType();
                        ccrt.CompanyId            = companyId;
                        cboRateTier.SelectedValue = 0;
                    }

                    isCustomer = true;
                    pnlRAteTier.Show();
                }
                else
                {
                    isCustomer = false;
                    pnlRAteTier.Hide();
                }
            }

            firstLoad = false;
        }