public static IList <OrderChangeViewModel> BuildChanges(OrderShippingInfoDTO shippingInfo)
        {
            var results = new List <OrderChangeViewModel>();

            if (!String.IsNullOrEmpty(shippingInfo.TrackingNumber))
            {
                var printLabel = new OrderChangeViewModel()
                {
                    ChangeType = OrderChangeTypes.PrintLabel,
                    Value      = shippingInfo.TrackingNumber,
                    ValueUrl   = MarketUrlHelper.GetTrackingUrl(shippingInfo.TrackingNumber, shippingInfo.ShippingMethod.CarrierName, shippingInfo.TrackingStateSource),

                    Message       = shippingInfo.ShippingMethod.CarrierName + " - " + shippingInfo.ShippingMethod.Name.ToString(),
                    ChangeDate    = shippingInfo.LabelPurchaseDate,
                    ChangedBy     = shippingInfo.LabelPurchaseBy,
                    ChangedByName = shippingInfo.LabelPurchaseByName,
                };
                results.Add(printLabel);
            }

            if (shippingInfo.ActualDeliveryDate.HasValue)
            {
                var deliveredEvent = new OrderChangeViewModel()
                {
                    ChangeType = OrderChangeTypes.Delivered,
                    Message    = shippingInfo.TrackingStateEvent,

                    ChangeDate = shippingInfo.ActualDeliveryDate.Value,
                    ChangedBy  = null
                };
                results.Add(deliveredEvent);
            }

            return(results);
        }
        public static string BuildLabelNotes(OrderShippingInfoDTO shipping)
        {
            var notes = OrderHelper.FormatOrderNumber(shipping.OrderAmazonId, (MarketType)shipping.Market) + " > " +
                        (shipping.TotalQuantity > 1 ? shipping.TotalQuantity + " items" : shipping.TotalQuantity + " item") +
                        (ShippingUtils.IsFlat(shipping.ShippingMethod.Id) ? " Flat" : "");

            if (shipping.NumberInList > 0)
            {
                notes = shipping.NumberInList + " > " + notes;
            }

            if (shipping.BatchId.HasValue && shipping.BatchId > 0)
            {
                notes = "B" + shipping.BatchId + " > " + notes;
            }

            return(notes);
        }
        public OrderShippingViewModel(OrderShippingInfoDTO shipping)
        {
            ShippingInfoId     = shipping.Id;
            TrackingNumber     = shipping.TrackingNumber;
            IsActive           = shipping.IsActive;
            ShippingMethodName = shipping.ShippingMethod.ShortName ?? shipping.ShippingMethod.Name;
            RequirePackageSize = shipping.ShippingMethod.RequiredPackageSize;

            if (String.IsNullOrEmpty(shipping.CustomCarrier))
            {
                Carrier = shipping.ShippingMethod.CarrierName;
            }
            else
            {
                Carrier = shipping.CustomCarrier;
            }
            ShippingMethodName = shipping.ShippingMethod.Name;
            GroupId            = shipping.ShippingGroupId;

            PackageLength = shipping.PackageLength;
            PackageWidth  = shipping.PackageWidth;
            PackageHeight = shipping.PackageHeight;
        }
        public List <MessageString> Validate(IUnitOfWork db,
                                             ILogService log,
                                             DateTime when)
        {
            var messages  = new List <MessageString>();
            var emailType = this.EmailType;

            if (ReplyToEmailId.HasValue)
            {
                var replyToEmail = db.Emails.Get(ReplyToEmailId.Value);
                if (replyToEmail.Type == (int)IncomeEmailTypes.CancellationRequest)
                {
                    log.Info("Add message: Cancellation emails usually processed by system automatically. Are you sure you would like to send the response?");
                    messages.Add(new MessageString()
                    {
                        Message = "Cancellation emails usually processed by system automatically. Are you sure you would like to send the response?",
                        Status  = MessageStatus.Info,
                    });
                }
            }

            if (!String.IsNullOrEmpty(OrderNumber) &&
                emailType == EmailTypes.LostPackage)
            {
                var emailNotify = db.OrderEmailNotifies
                                  .GetAll()
                                  .OrderByDescending(o => o.CreateDate)
                                  .FirstOrDefault(o => o.OrderNumber == OrderNumber &&
                                                  o.Type == (int)OrderEmailNotifyType.OutputLostPackageEmail);

                if (emailNotify != null)
                {
                    log.Info("Add message: Lost template was already sent for this order on " + DateHelper.ToDateString(emailNotify.CreateDate) + ", are you sure you want to send it again?");
                    messages.Add(new MessageString()
                    {
                        Message = "Lost template was already sent for this order on " + DateHelper.ToDateString(emailNotify.CreateDate) + ", are you sure you want to send it again?",
                        Status  = MessageStatus.Info,
                    });
                }
            }

            if (!String.IsNullOrEmpty(OrderNumber) &&
                emailType == EmailTypes.LostPackage)
            {
                var order = db.Orders.GetByOrderIdAsDto(OrderNumber);
                if (order != null)
                {
                    var labels = db.Labels.GetByOrderIdAsDto(order.Id).ToList();
                    OrderShippingInfoDTO label = null;
                    if (labels.Any())
                    {
                        label = labels.OrderByDescending(sh => sh.LabelPurchaseDate).FirstOrDefault(i => i.IsActive);
                    }

                    if (label == null || label.DeliveredStatus != (int)DeliveredStatusEnum.Delivered)
                    {
                        log.Info("Add message: The order isn't marked yet as delivered, are you sure you want to send this message?");
                        messages.Add(new MessageString()
                        {
                            Message = "The order isn't marked yet as delivered, are you sure you want to send this message?",
                            Status  = MessageStatus.Info,
                        });
                    }
                }
            }


            if (!String.IsNullOrEmpty(OrderNumber) &&
                emailType == EmailTypes.ReturnInstructions)
            {
                var order = db.Orders.GetByOrderIdAsDto(OrderNumber);
                if (order != null && order.OrderDate.HasValue)
                {
                    var orderShippings = db.OrderShippingInfos
                                         .GetByOrderIdAsDto(order.Id)
                                         .Where(sh => sh.IsActive)
                                         .ToList();

                    var returnRequestToLate = OrderHelper.AcceptReturnRequest(order.OrderDate.Value,
                                                                              order.EarliestDeliveryDate,
                                                                              orderShippings.Max(sh => sh.ActualDeliveryDate),
                                                                              when,
                                                                              when);

                    if (returnRequestToLate)
                    {
                        log.Info("Add message: The order was placed over 30 days ago, are you sure you want to send this message?");
                        messages.Add(new MessageString()
                        {
                            Message = "The order was placed over 30 days ago, are you sure you want to send this message?",
                            Status  = MessageStatus.Info,
                        });
                    }
                }
            }
            return(messages);
        }
Example #5
0
        public void Process(IUnitOfWork db, EmailReadingResult result)
        {
            if (result.Status == EmailMatchingResultStatus.New &&
                result.HasMatches)
            {
                var subject = (result.Email.Subject ?? "");
                var today   = _time.GetAppNowTime().Date;

                //TASK: 1.	Emails which have these in subjects: "Order delivery inquiry" or " Where's My Stuff?”
                //CHANGE: When client sends an email with subject “Package didn’t arrive..” like 113-7086092-7521857, process it same way as emails with subject “Lost Package”…
                var isWhereMyStaff = subject.StartsWith("Order delivery inquiry", StringComparison.OrdinalIgnoreCase) ||
                                     subject.IndexOf("Where's My Stuff?", StringComparison.OrdinalIgnoreCase) >= 0 ||
                                     subject.IndexOf("Where's My Stuff ?", StringComparison.OrdinalIgnoreCase) >= 0 ||
                                     subject.IndexOf("Package didn’t arrive:", StringComparison.OrdinalIgnoreCase) >= 0 ||
                                     subject.IndexOf("Package didn?t arrive", StringComparison.OrdinalIgnoreCase) >= 0 ||
                                     subject.IndexOf("Shipping inquiry", StringComparison.InvariantCultureIgnoreCase) >= 0;    //NOTE: actually came with ? instead of '

                if (isWhereMyStaff)
                {
                    _log.Info("Received 'Where my stuff'");
                    var orderNumber = result.MatchedIdList.FirstOrDefault();
                    if (!String.IsNullOrEmpty(orderNumber))
                    {
                        //TASK: 2.	 Which were successfully delivered to client.
                        var order         = db.Orders.GetByOrderNumber(orderNumber);
                        var shippingInfos = db.OrderShippingInfos.GetByOrderIdAsDto(order.Id).Where(sh => sh.IsActive).ToList();
                        //a.	 delivered to client (not returned to us)
                        var delivered    = shippingInfos.Any() && shippingInfos.All(sh => sh.DeliveredStatus == (int)DeliveredStatusEnum.Delivered);
                        var deliveryDate = shippingInfos.Select(sh => sh.ActualDeliveryDate).FirstOrDefault();
                        //b.	Delivered within last 2 month.
                        if (delivered && deliveryDate.HasValue && deliveryDate > today.AddMonths(-2))
                        {
                            _log.Info("Package was delivered, withing last 2 month");

                            var alreadySendLostTemplate = db.OrderEmailNotifies.IsExist(order.AmazonIdentifier,
                                                                                        OrderEmailNotifyType.OutputLostPackageEmail);

                            //3.	To which we didn’t answer yet with Lost Package template
                            if (!alreadySendLostTemplate)
                            {
                                _log.Info("Not send package lost template");

                                var orderEmails = db.Emails.GetAllByOrderId(order.AmazonIdentifier)
                                                  .Select(m => new
                                {
                                    m.Id,
                                    m.ReceiveDate,
                                    m.Subject
                                }).ToList();
                                var isAnyOtherSimilarEmails = orderEmails.Any(e => e.Id != result.Email.Id &&
                                                                              (e.ReceiveDate <= result.Email.ReceiveDate &&
                                                                               e.Subject.Contains("Where's My Stuff?") ||
                                                                               e.Subject.Contains("Order delivery inquiry")));

                                var isAnyOtherEmailAfterDelivery = deliveryDate.HasValue && orderEmails.Any(e => e.Id != result.Email.Id &&
                                                                                                            e.ReceiveDate >= deliveryDate.Value);

                                //4.	If it’s the first email with that subject ("Order delivery inquiry" or " Where's My Stuff?”)
                                if (!isAnyOtherSimilarEmails && !isAnyOtherEmailAfterDelivery)
                                {
                                    _log.Info("Pass to Order Delivery Inquiry Rule");

                                    OrderShippingInfoDTO shippingInfo   = null;
                                    ShippingMethodDTO    shippingMethod = null;
                                    if (shippingInfos.Any())
                                    {
                                        shippingInfo = shippingInfos.OrderByDescending(sh => sh.ActualDeliveryDate)
                                                       .FirstOrDefault(i => i.IsActive);
                                        if (shippingInfo != null)
                                        {
                                            shippingMethod = db.ShippingMethods.GetByIdAsDto(shippingInfo.ShippingMethodId);
                                        }
                                    }
                                    var emailInfo = new LostPackageEmailInfo(_emailService.AddressService,
                                                                             null,
                                                                             order.AmazonIdentifier,
                                                                             (MarketType)order.Market,
                                                                             shippingInfo != null ? shippingInfo.ActualDeliveryDate : null,
                                                                             shippingInfo != null ? shippingInfo.TrackingStateEvent : null,
                                                                             shippingMethod != null ? shippingMethod.CarrierName : null,
                                                                             shippingInfo != null ? shippingInfo.TrackingNumber : null,
                                                                             order.GetAddressDto(),
                                                                             order.BuyerName,
                                                                             order.BuyerEmail);

                                    _emailService.SendEmail(emailInfo, CallSource.Service);

                                    db.OrderEmailNotifies.Add(new OrderEmailNotify()
                                    {
                                        OrderNumber = order.CustomerOrderId,
                                        Type        = (int)OrderEmailNotifyType.OutputLostPackageEmail,
                                        Reason      = "Email: " + StringHelper.Substring(subject, 40),
                                        CreateDate  = _time.GetUtcTime()
                                    });

                                    db.OrderComments.Add(new OrderComment()
                                    {
                                        OrderId    = order.Id,
                                        Type       = (int)CommentType.OutputEmail,
                                        Message    = "[System] \"Lost Package\" email sent",
                                        CreateDate = _time.GetAppNowTime(),
                                    });

                                    db.Commit();

                                    result.WasEmailProcessed = true;
                                }
                                else
                                {
                                    if (isAnyOtherSimilarEmails)
                                    {
                                        _log.Info("Similar email was found");
                                    }
                                    if (isAnyOtherEmailAfterDelivery)
                                    {
                                        _log.Info("Other email was found after delivery");
                                    }
                                }
                            }
                            else
                            {
                                _log.Info("Already sent Lost Package template");
                            }
                        }
                        else
                        {
                            _log.Info("Package not yet delivered");
                        }
                    }
                }
            }
        }
        public void TestGetLabel(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 fimsProvider = rateProviders.FirstOrDefault(r => r.Type == ShipmentProviderType.FIMS);

                //var rates = fedexRateProvider.GetLocalRate(
                //        companyAddress.GetReturnAddress(order.GetMarketId()),
                //        companyAddress.GetPickupAddress(order.GetMarketId()),
                //        order.GetAddressDto(),
                //        _time.GetAppNowTime(),
                //        order.WeightD,
                //        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);

                var shipmentInfo = new OrderShippingInfoDTO()
                {
                    OrderAmazonId      = order.OrderId,
                    WeightD            = order.WeightD,
                    IsInsured          = order.IsInsured,
                    TotalPrice         = order.TotalPrice,
                    TotalPriceCurrency = order.TotalPriceCurrency,

                    IsSignConfirmation = order.IsSignConfirmation,

                    Items = orderItemInfoes.Select(oi => new DTOOrderItem()
                    {
                        ItemOrderId = oi.ItemOrderId,
                        ItemPrice   = oi.ItemPrice,
                        Weight      = oi.Weight,
                        Quantity    = oi.Quantity,
                    }).ToList(),
                    ShippingMethod = new ShippingMethodDTO()
                    {
                    },
                };

                var shipDate = db.Dates.GetOrderShippingDate(null);

                var boughtInTheCountry = MarketBaseHelper.GetMarketCountry((MarketType)order.Market, order.MarketplaceId);
                //var callResult = labelProvider.CreateShipment(shipmentInfo,
                //    returnAddress,
                //    pickupAddress,
                //    toAddress,
                //    shipDate.Date,
                //    model.Notes,
                //    !model.ShippingMethod.IsSupportReturnToPOBox,
                //    sampleMode,
                //    fromUI: true);


                var labels = fimsProvider.CreateShipment(
                    shipmentInfo,
                    companyAddress.GetReturnAddress(order.GetMarketId()),
                    companyAddress.GetPickupAddress(order.GetMarketId()),
                    order.GetAddressDto(),
                    boughtInTheCountry,
                    shipDate,
                    "",
                    false,
                    false,
                    false);


                _log.Info("Labels: " + labels.Data.LabelFileList.Count);
            }
        }
        public static Byte[] BuildCommercialInvoice(string rootPath,
                                                    string orderNumber,
                                                    OrderShippingInfoDTO shippingInfo,
                                                    AddressDTO fromAddress,
                                                    AddressDTO toAddress,
                                                    IList <DTOOrderItem> items,
                                                    string trackingNumber,
                                                    DateTime shipDate)
        {
            var html = File.ReadAllText(Path.Combine(rootPath, "commercial_invoice.html"));

            var weight = (decimal)shippingInfo.WeightD / (decimal)16;

            var fromString = fromAddress.FullName + "<br/>"
                             + fromAddress.Address1 + "<br/>"
                             + fromAddress.City + ", " + fromAddress.State + " " + fromAddress.Zip + "<br/>"
                             + fromAddress.Country + "<br/>"
                             + fromAddress.Phone + "<br/>"
                             + fromAddress.BuyerEmail;

            var toString = toAddress.FinalFullName + "<br/>"
                           + toAddress.FinalAddress1 + "<br/>"
                           + (!String.IsNullOrEmpty(toAddress.FinalAddress2)
                               ? toAddress.FinalAddress2 + "<br/>"
                               : "")
                           + toAddress.FinalCity + ", " + toAddress.FinalState + " " + toAddress.FinalZip + "<br/>"
                           + toAddress.FinalCountry + "<br/>"
                           + toAddress.FinalPhone + "<br/>"
                           + toAddress.BuyerEmail;

            var currency        = shippingInfo.TotalPriceCurrency;
            var totalPriceInUSD = PriceHelper.RougeConvertToUSD(currency, items.Sum(i => i.ItemPrice));

            var lines = String.Empty;

            foreach (var item in items)
            {
                var itemPriceInUSD       = PriceHelper.RougeConvertToUSD(currency, item.ItemPrice / item.Quantity);
                var totalItemsPriceInUSD = PriceHelper.RougeConvertToUSD(currency, item.ItemPrice);

                lines += String.Format(
                    "<tr><td>Watches</td><td></td><td>US</td><td>{0}</td><td>EA</td><td>{1}</td><td>{2}</td></tr>",
                    item.Quantity,
                    itemPriceInUSD.ToString("0.00") + " USD",        //currency,
                    totalItemsPriceInUSD.ToString("0.00") + " USD"); // + currency);
            }

            html = html.Replace("{Date}", shipDate.ToString("yyyy-MM-dd"));
            html = html.Replace("{ShipperRef}", orderNumber);

            html = html.Replace("{ShipperName}", fromAddress.FullName);
            html = html.Replace("{ShipperAddress}", fromString);
            html = html.Replace("{FromContact}", fromAddress.ContactName);

            html = html.Replace("{ReceiverAddress}", toString);
            html = html.Replace("{DestinationCountry}", toAddress.FinalCountry);
            html = html.Replace("{ToContact}", toAddress.FinalFullName);
            html = html.Replace("{ConsigneeName}", toAddress.FinalFullName);

            html = html.Replace("{Weight}", weight.ToString("0.00"));
            html = html.Replace("{Waybill}", trackingNumber);
            html = html.Replace("{TotalAmount}", totalPriceInUSD.ToString("0.00"));
            html = html.Replace("{Currency}", "USD");//currency
            html = html.Replace("{Lines}", lines);

            var css = File.ReadAllText(Path.Combine(rootPath, "commercial_invoice.css"));; // @".headline{font-size:200%} td { padding:20px }";

            return(PdfHelper.BuildPdfFromHtml(html, css, 2));
        }