public PrintLabelResult PrintBatch(long batchId, long companyId, long?by) { var printLabelResult = new PrintLabelResult() { IsPrintStarted = false }; var syncInfo = new DbSyncInformer(_dbFactory, _log, _time, SyncType.PostagePurchase, "", MarketType.None, JsonConvert.SerializeObject(new { batchId = batchId })); using (var db = _dbFactory.GetRWDb()) { var when = _time.GetAppNowTime(); var company = db.Companies.GetByIdWithSettingsAsDto(companyId); var companyAddress = new CompanyAddressService(company); var labelProviders = _serviceFactory.GetShipmentProviders(_log, _time, _dbFactory, _weightService, company.ShipmentProviderInfoList, _defaultCustomType, _labelDirectory, _reserveDirectory, _templateDirectory); var labelService = new LabelService(labelProviders, _log, _time, _dbFactory, _emailService, _pdfMaker, _addressService); CompanyHelper.UpdateBalance(db, company, labelProviders, true, when); var orderIds = db.OrderBatches.GetOrderIdsForBatch( batchId, OrderStatusEnumEx.AllUnshippedWithShipped //for composing pdf file with all ); var batchDto = db.OrderBatches.GetAsDto(batchId); //Close batch db.OrderBatches.CloseBatch(batchId); SendBeforePrintNotificationMessage(batchDto.Name); var shippingList = db.OrderShippingInfos.GetOrderInfoWithItems(_weightService, orderIds.ToList(), SortMode.ByLocation, unmaskReferenceStyle: false, includeSourceItems: false).ToList(); //NOTE: Update from address var dropShipperList = db.DropShippers.GetAllAsDto().ToList(); foreach (var shipping in shippingList) { shipping.ReturnAddress = dropShipperList.FirstOrDefault(ds => ds.Id == shipping.DropShipperId)?.GetAddressDto(); } //NOTE: update phone if missing foreach (var shipping in shippingList) { if (shipping.ShippingMethod.CarrierName == ShippingServiceUtils.FedexCarrier && String.IsNullOrEmpty(shipping.ToAddress.FinalPhone)) { shipping.ToAddress.Phone = company.Phone; shipping.ToAddress.ManuallyPhone = company.Phone; } } //NOTE: Sort for setting # shippingList = SortHelper.Sort(shippingList, SortMode.ByShippingMethodThenLocation).ToList(); IList <long> removedOrderIds = new List <long>(); if (!syncInfo.IsSyncInProgress()) { UpdateLabelPrintStatus(db, orderIds, shippingList); removedOrderIds = RemoveOrdersWithIssue(db, orderIds, shippingList, printLabelResult); if (removedOrderIds.Any()) { var batchName = string.Format("Issues of {0} {1} orders", batchDto.Name, removedOrderIds.Count); db.OrderBatches.CreateBatch(batchName, BatchType.PrintLabel, removedOrderIds, when, by); //NOTE: keep to final email notification //shippingList = shippingList.Where(sh => !removedOrderIds.Contains(sh.OrderId)).ToList(); } //Removed list var removedList = shippingList.Where(sh => removedOrderIds.Contains(sh.OrderId)).ToList(); if (batchDto.LockDate.HasValue) { var historyRemovedOrderIds = db.OrderChangeHistories.GetAll().Where(ch => ch.FromValue == batchDto.Id.ToString() && ch.FieldName == OrderHistoryHelper.AddToBatchKey && ch.ChangeDate >= batchDto.LockDate) .Select(ch => ch.OrderId) .Distinct() .ToList(); historyRemovedOrderIds = historyRemovedOrderIds.Where(id => !orderIds.Contains(id)).ToList(); var historyShippingList = db.OrderShippingInfos.GetOrderInfoWithItems(_weightService, historyRemovedOrderIds.ToList(), SortMode.ByLocation, unmaskReferenceStyle: false, includeSourceItems: false).ToList(); removedList.AddRange(historyShippingList); } //Changed list var styleChangedList = new List <StyleChangeInfo>(); if (batchDto.LockDate.HasValue) { var historyChangeStyles = db.OrderChangeHistories.GetAll().Where(ch => orderIds.Contains(ch.OrderId) && ch.FieldName == OrderHistoryHelper.ReplaceItemKey && ch.ChangeDate >= batchDto.LockDate) .ToList(); foreach (var change in historyChangeStyles) { if (!String.IsNullOrEmpty(change.FromValue) && !String.IsNullOrEmpty(change.ToValue)) { var fromStyleItemId = StringHelper.ToInt(change.FromValue); var fromStyleItem = db.StyleItems.GetAll().FirstOrDefault(si => si.Id == fromStyleItemId); var toStyleItemId = StringHelper.ToInt(change.ToValue); var toStyleItem = db.StyleItems.GetAll().FirstOrDefault(si => si.Id == toStyleItemId); if (fromStyleItem != null && toStyleItem != null) { var fromStyle = db.Styles.Get(fromStyleItem.StyleId); var toStyle = db.Styles.Get(toStyleItem.StyleId); styleChangedList.Add(new StyleChangeInfo() { SourceStyleString = fromStyle.StyleID, SourceStyleSize = fromStyleItem.Size, DestStyleString = toStyle.StyleID, DestStyleSize = toStyleItem.Size, }); } } } } //Printing printLabelResult = labelService.PrintLabels(db, company, companyAddress, syncInfo, batchId, shippingList, false, removedList, styleChangedList, batchDto.ScanFormPath, _labelDirectory, _isSampleMode, when, by); printLabelResult.RemovedIds = removedOrderIds; long?failedBatchId = null; //Move orders with errors to a new batch if (printLabelResult.FailedIds.Count > 0) { var batchName = string.Format("Failed of {0} {1} orders", batchDto.Name, printLabelResult.FailedIds.Count); var failedOrderIds = printLabelResult.FailedIds.Select(s => s.OrderId).Distinct().ToList(); failedBatchId = db.OrderBatches.CreateBatch(batchName, BatchType.PrintLabel, failedOrderIds, when, by); printLabelResult.Messages.Add( new Message( String.Format("{0} unprinted orders was moved to new batch \"{1}\"", failedOrderIds.Count, batchName), MessageTypes.Error)); } if (printLabelResult.IsPrintStarted) { //Send notification to seller SendAfterPrintNotificationMessage(db, printLabelResult.Messages, batchDto.Id, batchDto.Name, company, shippingList.Where(sh => printLabelResult.RemovedIds.Any(f => f == sh.OrderId)).ToList(), shippingList.Where(sh => printLabelResult.FailedIds.Any(f => f.ShipmentId == sh.Id)).ToList()); //Apply new balance to Session CompanyHelper.UpdateBalance(db, company, labelProviders, false, _time.GetAppNowTime()); SaveBatchPrintResultToDb(db, _log, batchDto.Id, printLabelResult, shippingList, _time.GetAppNowTime(), by); if (printLabelResult.FailedIds.Any()) { printLabelResult.Messages.Add(new Message(printLabelResult.GetConcatFailedOrdersString(), MessageTypes.Error)); } } else { _emailService.SendSystemEmailToAdmin(String.Format("Batch \"{0}\" print wasn't started", batchDto.Name), String.Format("Ended at {0}", _time.GetAppNowTime())); } } else { printLabelResult.Messages.Add(new Message("Request rejected. The system is already buys postage", MessageTypes.Warning)); } return(printLabelResult); } }
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"); } } } }