public void PrintPdfFromOrder(string amazonIdentifier)
        {
            var labelService = new LabelService(GetShipmentProviders(_company), _log, _time, _dbFactory, _emailService, new PdfMakerByIText(_log), AddressService.Default);

            using (var db = new UnitOfWork(_log))
            {
                var orderIds = from o in db.Orders.GetAll()
                               where o.AmazonIdentifier == amazonIdentifier
                               select o.Id;

                //var batchDto = db.OrderBatches.Get(734);

                var shippingList = db.OrderShippingInfos.GetOrderInfoWithItems(_weightService, orderIds.ToList(), (SortMode)SortMode.ByLocation, unmaskReferenceStyle: false, includeSourceItems: false)
                                   .ToList();
                shippingList = SortHelper.Sort(shippingList, SortMode.ByShippingMethodThenLocation).ToList();

                var mailList = db.MailLabelInfos.GetAllAsDto().Where(m => orderIds.Contains(m.OrderId)).ToList();
                shippingList.AddRange(mailList);

                var result = new PrintLabelResult();
                labelService.BuildPdfFile(shippingList.Where(sh => !String.IsNullOrEmpty(sh.LabelPath)).ToList(),
                                          new string[] { },
                                          null,
                                          AppSettings.LabelDirectory,
                                          ref result);
            }
        }
        public void PrintScanForm()
        {
            var outputDirectory = AppSettings.LabelDirectory;
            var labelService    = new LabelService(GetShipmentProviders(_company), _log, _time, _dbFactory, _emailService, _pdfMaker, AddressService.Default);

            var scanFormRelativePath = new string[] { "~\\ScanForms\\scanform_9475711201080820619182.jpg" };

            Console.WriteLine(scanFormRelativePath);

            var result = new PrintLabelResult();

            labelService.BuildPdfFile(new List <OrderShippingInfoDTO>(),
                                      scanFormRelativePath,
                                      null,
                                      outputDirectory,
                                      ref result);
        }
        public void PrintPdfFromOrders()
        {
            var labelService = new LabelService(GetShipmentProviders(_company), _log, _time, _dbFactory, _emailService, new PdfMakerByIText(_log), AddressService.Default);

            using (var db = new UnitOfWork(_log))
            {
                var batchId = 1887;

                var orderIds = from o in db.Orders.GetAll()
                               join sh in db.OrderShippingInfos.GetAll() on o.Id equals sh.OrderId
                               where o.BatchId == batchId &&
                               sh.IsActive &&
                               (sh.ShippingMethodId == ShippingUtils.DhlExpressWorldWideShippingMethodId ||
                                sh.ShippingMethodId == ShippingUtils.AmazonDhlExpressMXShippingMethodId)
                               select o.Id;

                var batchDto = db.OrderBatches.Get(batchId);

                var shippingList = db.OrderShippingInfos.GetOrderInfoWithItems(_weightService, orderIds.ToList(), (SortMode)SortMode.ByLocation, unmaskReferenceStyle: false, includeSourceItems: false)
                                   .ToList();
                shippingList = SortHelper.Sort(shippingList, SortMode.ByShippingMethodThenLocation).ToList();

                var mailList = db.MailLabelInfos.GetAllAsDto().Where(m => orderIds.Contains(m.OrderId)).ToList();
                shippingList.AddRange(mailList);

                var result = new PrintLabelResult();
                labelService.BuildPdfFile(shippingList.Where(sh => !String.IsNullOrEmpty(sh.LabelPath)).ToList(),
                                          new string[] { },
                                          new BatchInfoToPrint()
                {
                    BatchId          = batchDto.Id,
                    BatchName        = batchDto.Name,
                    Date             = _time.GetAmazonNowTime(),
                    NumberOfPackages = shippingList.Count
                },
                                          AppSettings.LabelDirectory,
                                          ref result);
            }
        }
        public void PrintPdfFromBatch(long batchId)
        {
            var labelService = new LabelService(GetShipmentProviders(_company), _log, _time, _dbFactory, _emailService, new PdfMakerByIText(_log), AddressService.Default);

            using (var db = new UnitOfWork(_log))
            {
                var orderIds = db.OrderBatches.GetOrderIdsForBatch(
                    batchId,
                    OrderStatusEnumEx.AllUnshippedWithShipped //for composing pdf file with all
                    );

                var batchDto = db.OrderBatches.Get(batchId);

                var shippingList = db.OrderShippingInfos.GetOrderInfoWithItems(_weightService, orderIds.ToList(), (SortMode)SortMode.ByLocation, unmaskReferenceStyle: false, includeSourceItems: false)
                                   .ToList();
                shippingList = SortHelper.Sort(shippingList, SortMode.ByShippingMethodThenLocation).Take(9).ToList().ToList();

                var result = new PrintLabelResult();
                labelService.BuildPdfFile(shippingList,
                                          new string[] { },
                                          new BatchInfoToPrint()
                {
                    BatchId          = batchId,
                    BatchName        = batchDto.Name,
                    NumberOfPackages = shippingList.Count,
                    Date             = _time.GetAmazonNowTime(),
                    Carriers         = shippingList.GroupBy(sh => sh.ShippingMethod.CarrierName)
                                       .Select(c => new {
                        Key   = c.Key,
                        Value = c.Count()
                    })
                                       .ToDictionary(d => d.Key, d => d.Value)
                },
                                          AppSettings.LabelDirectory,
                                          ref result);
            }
        }
Пример #5
0
        public PrintLabelResult PrintLabel(long orderId, long companyId, long?by)
        {
            var printLabelResult = new PrintLabelResult()
            {
                IsPrintStarted = false
            };

            var syncInfo = new DbSyncInformer(_dbFactory,
                                              _log,
                                              _time,
                                              SyncType.PostagePurchase,
                                              "",
                                              MarketType.None,
                                              String.Empty);

            using (var db = _dbFactory.GetRWDb())
            {
                var company        = db.Companies.GetByIdWithSettingsAsDto(companyId);
                var companyAddress = new CompanyAddressService(company);

                var shipmentProviders = _serviceFactory.GetShipmentProviders(_log,
                                                                             _time,
                                                                             _dbFactory,
                                                                             _weightService,
                                                                             company.ShipmentProviderInfoList,
                                                                             _defaultCustomType,
                                                                             _labelDirectory,
                                                                             _reserveDirectory,
                                                                             _templateDirectory);

                var labelService = new LabelService(shipmentProviders, _log, _time, _dbFactory, _emailService, _pdfMaker, _addressService);

                CompanyHelper.UpdateBalance(db, company, shipmentProviders, true, _time.GetAppNowTime());

                var shippingList =
                    db.OrderShippingInfos.GetOrderInfoWithItems(_weightService,
                                                                new[] { orderId }.ToList(),
                                                                SortMode.ByLocation,
                                                                unmaskReferenceStyle: false,
                                                                includeSourceItems: false).ToList();
                shippingList = shippingList.Where(sh => !sh.OnHold).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();
                }


                printLabelResult = labelService.PrintLabels(db,
                                                            company,
                                                            companyAddress,
                                                            syncInfo,
                                                            null,
                                                            shippingList,
                                                            true,
                                                            null,
                                                            null,
                                                            null,
                                                            _labelDirectory,
                                                            _isSampleMode,
                                                            _time.GetAppNowTime(),
                                                            by);

                //Apply new balance to Session
                CompanyHelper.UpdateBalance(db, company, shipmentProviders, false, _time.GetAppNowTime());

                if (printLabelResult.IsPrintStarted)
                {
                    SaveBatchPrintResultToDb(db,
                                             _log,
                                             null,
                                             printLabelResult,
                                             shippingList,
                                             _time.GetAppNowTime(),
                                             by);

                    if (printLabelResult.FailedIds.Any())
                    {
                        printLabelResult.Messages.Add(new Message(printLabelResult.GetConcatFailedOrdersString(), MessageTypes.Error));
                    }
                }
            }

            return(printLabelResult);
        }
Пример #6
0
        private void SaveBatchPrintResultToDb(IUnitOfWork db,
                                              ILogService log,
                                              long?batchId,
                                              PrintLabelResult printResult,
                                              IList <OrderShippingInfoDTO> shippings,
                                              DateTime when,
                                              long?by)
        {
            //Create print pack file
            long?printPackId = null;

            if (!String.IsNullOrEmpty(printResult.Url))
            {
                var printPack = new LabelPrintPack
                {
                    CreateDate     = DateHelper.GetAppNowTime(),
                    FileName       = printResult.Url,
                    NumberOfLabels = shippings.Count,
                    BatchId        = batchId,
                    PersonName     = shippings.Count == 1
                        ? shippings.First().PersonName
                        : null
                };
                db.LabelPrintPacks.Add(printPack);
                db.Commit();

                printPackId = printPack.Id;
            }

            printResult.PrintPackId = printPackId;


            //Update link to print pack file for shippings
            if (printPackId.HasValue)
            {
                foreach (var shipping in shippings)
                {
                    var dbShipping = db.OrderShippingInfos.Get(shipping.Id);
                    if (dbShipping == null)
                    {
                        throw new Exception("dbShipping obj is NULL, dbShippingId=" + shipping.Id + ", orderId=" + shipping.OrderId);
                    }

                    dbShipping.LabelPrintPackId = printPackId;
                }
                db.Commit();
            }

            if (printResult.ResaveNumberInBatchRequested)
            {
                foreach (var shipping in shippings)
                {
                    var dbShipping = db.OrderShippingInfos.Get(shipping.Id);
                    if (dbShipping == null)
                    {
                        throw new Exception("dbShipping obj is NULL, dbShippingId=" + shipping.Id + ", orderId=" + shipping.OrderId);
                    }

                    dbShipping.NumberInBatch = shipping.NumberInList;
                }
                db.Commit();
            }

            if (printResult.PickupInfo != null)
            {
                try
                {
                    db.ScheduledPickups.Store(printResult.PickupInfo,
                                              when,
                                              by);
                }
                catch (Exception ex)
                {
                    log.Error("Store Pickup info", ex);
                }
            }

            //Update Batch Info
            if (batchId.HasValue)
            {
                var batch = db.OrderBatches.Get(batchId.Value);
                batch.LablePrintPackId = printResult.PrintPackId;
                if (printResult.ScanFormList != null)
                {
                    //NOTE: otherwise (if scan form id IS NULL) scan from path not changed
                    if (printResult.ScanFormList.Any(f => !String.IsNullOrEmpty(f.ScanFormId)))
                    {
                        batch.ScanFormPath = String.Join(";", printResult.ScanFormList.Select(s => s.ScanFormPath).ToList());
                        batch.ScanFormId   = String.Join(";", printResult.ScanFormList.Select(s => s.ScanFormId).ToList());
                    }
                }
                if (printResult.PickupInfo != null)
                {
                    batch.PickupConfirmationNumber = printResult.PickupInfo.ConfirmationNumber;
                    batch.PickupTime = printResult.PickupInfo.ReadyByTime;
                    batch.PickupDate = DateHelper.CheckDateRange(printResult.PickupInfo.PickupDate);
                }

                db.Commit();
            }
        }
Пример #7
0
        private IList <long> RemoveOrdersWithIssue(IUnitOfWork db,
                                                   long[] orderIds,
                                                   IList <OrderShippingInfoDTO> shippingList,
                                                   PrintLabelResult printLabelResult)
        {
            var removedOrderIds = new List <long>();

            //Remove orders w/o shippings
            var orderIdsWoShippings = orderIds.Where(oId => shippingList.All(sh => sh.OrderId != oId)).ToList();

            if (orderIdsWoShippings.Any())
            {
                foreach (var orderId in orderIdsWoShippings)
                {
                    var dbOrder = db.Orders.GetById(orderId);
                    _batchManager.CheckRemovedOrder(db,
                                                    _log,
                                                    _actionService,
                                                    dbOrder,
                                                    null,
                                                    null);
                    dbOrder.BatchId = null;
                    _orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.AddToBatchKey, dbOrder.BatchId, null, null, null, null);
                    removedOrderIds.Add(dbOrder.Id);
                    _log.Info("W/o shipping order was removed from batch, orderId=" + dbOrder.AmazonIdentifier);
                }
                printLabelResult.Messages.Add(
                    new Message(String.Format("{0} - orders w/o selected shipping was removed from batch",
                                              orderIdsWoShippings.Distinct().Count()), MessageTypes.Error));
            }

            //Remove OnHold orders from batch
            var onHoldShippingList = shippingList.Where(sh => sh.OnHold).ToList();

            if (onHoldShippingList.Any())
            {
                foreach (var shipping in onHoldShippingList)
                {
                    var dbOrder = db.Orders.GetById(shipping.OrderId);
                    _batchManager.CheckRemovedOrder(db,
                                                    _log,
                                                    _actionService,
                                                    dbOrder,
                                                    null,
                                                    null);
                    dbOrder.BatchId = null;
                    _orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.AddToBatchKey, dbOrder.BatchId, null, null, null, null);
                    removedOrderIds.Add(dbOrder.Id);
                    _log.Info("OnHold order was removed from batch, orderId=" + dbOrder.AmazonIdentifier);
                }
                printLabelResult.Messages.Add(new Message(String.Format("{0} on hold orders was removed from batch",
                                                                        onHoldShippingList.Select(sh => sh.OrderId).Distinct().Count()), MessageTypes.Error));
            }

            //Removed with Mail label
            var alreadyMailedBatchOrderIds = db.MailLabelInfos.GetAllAsDto().Where(m => orderIds.Contains(m.Id) &&
                                                                                   !m.LabelCanceled &&
                                                                                   !m.CancelLabelRequested)
                                             .Select(m => m.OrderId).ToList();
            var alreadyMailedShippingList = shippingList.Where(sh => alreadyMailedBatchOrderIds.Contains(sh.OrderId)).ToList();

            if (alreadyMailedShippingList.Any())
            {
                foreach (var shipping in alreadyMailedShippingList)
                {
                    shipping.LabelPrintStatus = (int)LabelPrintStatus.AlreadyMailed;

                    var dbOrder = db.Orders.GetById(shipping.OrderId);
                    _orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.AddToBatchKey, dbOrder.BatchId, null, null, null, null);
                    dbOrder.BatchId = null;
                    removedOrderIds.Add(dbOrder.Id);
                    _log.Info("Already mailed order was removed from batch, orderId=" + dbOrder.AmazonIdentifier);
                }
                printLabelResult.Messages.Add(new Message(String.Format("{0} previously processed and mailed orders was removed from batch",
                                                                        alreadyMailedShippingList.Select(sh => sh.OrderId).Distinct().Count()), MessageTypes.Error));
            }

            db.Commit();

            return(removedOrderIds);
        }
Пример #8
0
        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);
            }
        }