예제 #1
0
        public ProcessShipmentReply Create(Packages package)
        {
            ProcessShipmentRequest request = _shipmentInit();

            request.TransactionDetail = new QDLogistics.FedExShipService.TransactionDetail();
            request.TransactionDetail.CustomerTransactionId = "*** Process Shipment Request ***";

            request.RequestedShipment = new RequestedShipment()
            {
                ShipTimestamp          = DateTime.Today,
                DropoffType            = DropoffType.REGULAR_PICKUP,
                ServiceType            = (QDLogistics.FedExShipService.ServiceType)package.Method.MethodType,
                PackagingType          = (QDLogistics.FedExShipService.PackagingType)package.Method.BoxType,
                Shipper                = _shipperInit(),
                ShippingChargesPayment = new Payment()
                {
                    PaymentType = PaymentType.SENDER, Payor = new Payor()
                    {
                        ResponsibleParty = _shipperInit()
                    }
                },
                PackageCount = "1"
            };

            Addresses address = package.Orders.Addresses;

            request.RequestedShipment.Recipient = new Party()
            {
                Contact = new QDLogistics.FedExShipService.Contact()
                {
                    PersonName  = string.Join(" ", new string[] { address.FirstName, address.MiddleInitial, address.LastName }),
                    CompanyName = address.CompanyName,
                    PhoneNumber = address.PhoneNumber
                },
                Address = new QDLogistics.FedExShipService.Address()
                {
                    StreetLines         = new string[] { address.StreetLine1, address.StreetLine2 },
                    City                = address.City,
                    StateOrProvinceCode = address.StateName,
                    PostalCode          = address.PostalCode,
                    CountryName         = address.CountryName,
                    CountryCode         = address.CountryCode
                }
            };

            Dictionary <string, StockKeepingUnit.SkuData> SkuData;

            using (StockKeepingUnit stock = new StockKeepingUnit())
            {
                var IDs = package.Items.Where(i => i.IsEnable.Value).Select(i => i.ProductID).Distinct().ToArray();
                SkuData = stock.GetSkuData(IDs);
            }

            string currency = Enum.GetName(typeof(QDLogistics.OrderService.CurrencyCodeType2), package.Orders.OrderCurrencyCode.Value);

            QDLogistics.FedExShipService.Money customsValue = new QDLogistics.FedExShipService.Money()
            {
                Currency = currency, Amount = package.DeclaredTotal
            };
            QDLogistics.FedExShipService.Commodity commodity = new QDLogistics.FedExShipService.Commodity
            {
                NumberOfPieces       = "1",
                Description          = string.Join(", ", package.Items.Select(i => i.Skus.ProductType.ProductTypeName).Distinct().ToArray()),
                CountryOfManufacture = "CN",
                Weight = new QDLogistics.FedExShipService.Weight()
                {
                    Units = address.CountryCode.Equals("US") ? QDLogistics.FedExShipService.WeightUnits.LB : QDLogistics.FedExShipService.WeightUnits.KG,
                    Value = package.Items.Where(i => i.IsEnable.Equals(true)).Sum(i => i.Qty.Value * ((decimal)(SkuData[i.ProductID]?.Weight ?? i.Skus.ShippingWeight) / (request.RequestedShipment.Shipper.Address.CountryCode.Equals("US") ? 453 : 1000)))
                },
                Quantity          = 1,
                QuantityUnits     = "EA",
                UnitPrice         = customsValue,
                CustomsValue      = customsValue,
                QuantitySpecified = true
            };

            request.RequestedShipment.CustomsClearanceDetail = new CustomsClearanceDetail()
            {
                DutiesPayment = new Payment()
                {
                    PaymentType = address.CountryCode.Equals("US") && package.ShippingMethod.Equals(35) ? PaymentType.SENDER : PaymentType.RECIPIENT,
                    Payor       = address.CountryCode.Equals("US") && package.ShippingMethod.Equals(35) ? new Payor()
                    {
                        ResponsibleParty = _shipperInit()
                    } : null
                },
                DocumentContent          = InternationalDocumentContentType.DOCUMENTS_ONLY,
                CustomsValue             = customsValue,
                Commodities              = new QDLogistics.FedExShipService.Commodity[] { commodity },
                DocumentContentSpecified = true
            };

            request.RequestedShipment.RequestedPackageLineItems = new RequestedPackageLineItem[] {
                new RequestedPackageLineItem()
                {
                    SequenceNumber = "1",
                    InsuredValue   = new QDLogistics.FedExShipService.Money()
                    {
                        Amount = package.NeedInsurance ? package.DeclaredTotal : 0, Currency = currency
                    },
                    Weight             = commodity.Weight,
                    CustomerReferences = new CustomerReference[]
                    {
                        new CustomerReference()
                        {
                            CustomerReferenceType = CustomerReferenceType.CUSTOMER_REFERENCE,
                            Value = package.OrderID.ToString()
                        }
                    }
                }
            };

            request.RequestedShipment.LabelSpecification = new LabelSpecification()
            {
                LabelFormatType                   = LabelFormatType.COMMON2D,
                ImageType                         = ShippingDocumentImageType.ZPLII,
                LabelStockType                    = LabelStockType.STOCK_4X6,
                LabelPrintingOrientation          = LabelPrintingOrientationType.BOTTOM_EDGE_OF_TEXT_FIRST,
                ImageTypeSpecified                = true,
                LabelStockTypeSpecified           = true,
                LabelPrintingOrientationSpecified = true
            };

            ProcessShipmentReply reply;

            using (ShipPortTypeClient client = new ShipPortTypeClient())
            {
                var endpoint = client.Endpoint;
                ConsoleOutputBehavior consoleOutputBehavior = new ConsoleOutputBehavior();
                client.Endpoint.Behaviors.Add(consoleOutputBehavior);

                try
                {
                    reply = client.processShipment(request);
                }
                catch (Exception e)
                {
                    QDLogistics.FedExShipService.Notification notification = new QDLogistics.FedExShipService.Notification();

                    if (!string.IsNullOrEmpty(consoleOutputBehavior.ConsoleOutputInspector.ResponseXML))
                    {
                        XElement element = XElement.Parse(consoleOutputBehavior.ConsoleOutputInspector.ResponseXML);
                        notification.Message = element.Attributes("Message").Any() ? element.Attributes("Message").First().Value : element.Attributes("Desc").First().Value;
                    }
                    else
                    {
                        notification.Message = e.Message;
                    }

                    reply = new ProcessShipmentReply()
                    {
                        Notifications = new QDLogistics.FedExShipService.Notification[] { notification }
                    };
                }
            }

            return(reply);
        }
예제 #2
0
        public ProcessShipmentReply CreateBox(List <Box> boxList, ShippingMethod method, DirectLine directLine)
        {
            ProcessShipmentRequest request = _shipmentInit();

            request.TransactionDetail = new QDLogistics.FedExShipService.TransactionDetail();
            request.TransactionDetail.CustomerTransactionId = "*** Process Shipment Request ***";

            request.RequestedShipment = new RequestedShipment()
            {
                ShipTimestamp          = DateTime.Today,
                DropoffType            = DropoffType.REGULAR_PICKUP,
                ServiceType            = (QDLogistics.FedExShipService.ServiceType)method.MethodType,
                PackagingType          = (QDLogistics.FedExShipService.PackagingType)method.BoxType,
                Shipper                = _shipperInit(),
                ShippingChargesPayment = new Payment()
                {
                    PaymentType = PaymentType.SENDER, Payor = new Payor()
                    {
                        ResponsibleParty = _shipperInit()
                    }
                },
                PackageCount = boxList.Count().ToString()
            };

            request.RequestedShipment.Recipient = new Party()
            {
                Contact = new QDLogistics.FedExShipService.Contact()
                {
                    PersonName  = directLine.ContactName,
                    CompanyName = directLine.CompanyName,
                    PhoneNumber = directLine.PhoneNumber
                },
                Address = new QDLogistics.FedExShipService.Address()
                {
                    StreetLines         = new string[] { directLine.StreetLine1, directLine.StreetLine2 },
                    City                = directLine.City,
                    StateOrProvinceCode = directLine.StateName,
                    PostalCode          = directLine.PostalCode,
                    CountryName         = directLine.CountryName,
                    CountryCode         = directLine.CountryCode
                }
            };

            int NumberOfPieces = 1;

            string[] IDS      = new string[] { "IDS", "IDS (US)" };
            string   currency = IDS.Contains(directLine.Abbreviation) ? "USD" : Enum.GetName(typeof(QDLogistics.OrderService.CurrencyCodeType2), boxList[0].Packages.First(p => p.IsEnable.Value).Orders.OrderCurrencyCode.Value);
            //string currency = Enum.GetName(typeof(QDLogistics.OrderService.CurrencyCodeType2), box.Packages.First(p => p.IsEnable.Value).Orders.OrderCurrencyCode.Value);
            var commodityList = new List <QDLogistics.FedExShipService.Commodity>();
            var itemLineList  = new List <RequestedPackageLineItem>();

            QDLogistics.FedExShipService.Money customsValue;

            Dictionary <string, StockKeepingUnit.SkuData> SkuData;

            using (StockKeepingUnit stock = new StockKeepingUnit())
            {
                var allPackages = boxList.SelectMany(b => b.Packages.Where(p => p.IsEnable.Value)).ToList();
                customsValue = new QDLogistics.FedExShipService.Money()
                {
                    Currency = currency, Amount = allPackages.Sum(p => p.DeclaredTotal)
                };
                var IDs = allPackages.SelectMany(p => p.Items.Where(i => i.IsEnable.Value)).Select(i => i.ProductID).Distinct().ToArray();
                SkuData = stock.GetSkuData(IDs);
            }

            foreach (Box box in boxList)
            {
                List <Items> itemList = box.Packages.Where(p => p.IsEnable.Value).SelectMany(p => p.Items.Where(i => i.IsEnable.Value)).ToList();

                QDLogistics.FedExShipService.Commodity commodity = new QDLogistics.FedExShipService.Commodity
                {
                    NumberOfPieces       = boxList.Count().ToString(),
                    Description          = string.Join(", ", itemList.Select(i => i.Skus.ProductType.ProductTypeName).Distinct().ToArray()),
                    CountryOfManufacture = "CN",
                    Weight = new QDLogistics.FedExShipService.Weight()
                    {
                        Units = request.RequestedShipment.Shipper.Address.CountryCode.Equals("US") ? QDLogistics.FedExShipService.WeightUnits.LB : QDLogistics.FedExShipService.WeightUnits.KG,
                        Value = itemList.Sum(i => i.Qty.Value * ((decimal)(SkuData[i.ProductID]?.Weight ?? i.Skus.ShippingWeight) / (request.RequestedShipment.Shipper.Address.CountryCode.Equals("US") ? 453 : 1000)))
                    },
                    Quantity      = 1,
                    QuantityUnits = "EA",
                    UnitPrice     = new QDLogistics.FedExShipService.Money()
                    {
                        Currency = currency, Amount = box.Packages.Where(p => p.IsEnable.Value).Sum(p => p.DeclaredTotal)
                    },
                    CustomsValue      = customsValue,
                    QuantitySpecified = true
                };

                commodityList.Add(commodity);
                itemLineList.Add(new RequestedPackageLineItem()
                {
                    SequenceNumber = NumberOfPieces++.ToString(),
                    InsuredValue   = new QDLogistics.FedExShipService.Money()
                    {
                        Amount = 0, Currency = currency
                    },
                    Weight             = commodity.Weight,
                    CustomerReferences = new CustomerReference[]
                    {
                        new CustomerReference()
                        {
                            CustomerReferenceType = CustomerReferenceType.CUSTOMER_REFERENCE,
                            Value = box.BoxID
                        }
                    }
                });
            }

            request.RequestedShipment.TotalWeight = new QDLogistics.FedExShipService.Weight()
            {
                Units = request.RequestedShipment.Shipper.Address.CountryCode.Equals("US") ? QDLogistics.FedExShipService.WeightUnits.LB : QDLogistics.FedExShipService.WeightUnits.KG,
                Value = commodityList.Select(c => c.Weight).Sum(w => w.Value)
            };

            request.RequestedShipment.CustomsClearanceDetail = new CustomsClearanceDetail()
            {
                DutiesPayment = new Payment()
                {
                    PaymentType = PaymentType.SENDER, Payor = new Payor()
                    {
                        ResponsibleParty = _shipperInit()
                    }
                },
                DocumentContent          = InternationalDocumentContentType.DOCUMENTS_ONLY,
                Commodities              = new QDLogistics.FedExShipService.Commodity[1],
                DocumentContentSpecified = true
            };

            request.RequestedShipment.RequestedPackageLineItems = new RequestedPackageLineItem[1];

            request.RequestedShipment.LabelSpecification = new LabelSpecification()
            {
                LabelOrder                        = LabelOrderType.SHIPPING_LABEL_FIRST,
                LabelFormatType                   = LabelFormatType.COMMON2D,
                ImageType                         = ShippingDocumentImageType.ZPLII,
                LabelStockType                    = LabelStockType.STOCK_4X6,
                LabelPrintingOrientation          = LabelPrintingOrientationType.BOTTOM_EDGE_OF_TEXT_FIRST,
                LabelOrderSpecified               = true,
                ImageTypeSpecified                = true,
                LabelStockTypeSpecified           = true,
                LabelPrintingOrientationSpecified = true
            };

            ProcessShipmentReply reply = new ProcessShipmentReply();

            using (ShipPortTypeClient client = new ShipPortTypeClient())
            {
                var endpoint = client.Endpoint;
                ConsoleOutputBehavior consoleOutputBehavior = new ConsoleOutputBehavior();
                client.Endpoint.Behaviors.Add(consoleOutputBehavior);

                try
                {
                    var basePath = HostingEnvironment.MapPath("~/FileUploads");
                    var filePath = Path.Combine(basePath, "export", "box", boxList[0].Create_at.ToString("yyyy/MM/dd"), boxList[0].MainBox);
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }

                    for (int i = 0; i < itemLineList.Count(); i++)
                    {
                        if (!i.Equals(0))
                        {
                            request.RequestedShipment.TotalWeight      = null;
                            request.RequestedShipment.MasterTrackingId = reply.CompletedShipmentDetail.MasterTrackingId;
                        }
                        request.RequestedShipment.CustomsClearanceDetail.CustomsValue   = commodityList[i].CustomsValue;
                        request.RequestedShipment.CustomsClearanceDetail.Commodities[0] = commodityList[i];
                        request.RequestedShipment.RequestedPackageLineItems[0]          = itemLineList[i];

                        reply = client.processShipment(request);
                        if (reply.HighestSeverity.Equals(QDLogistics.FedExShipService.NotificationSeverityType.ERROR) || reply.HighestSeverity.Equals(QDLogistics.FedExShipService.NotificationSeverityType.FAILURE))
                        {
                            throw new Exception(string.Join("\n", reply.Notifications.Select(n => n.Message).ToArray()));
                        }

                        boxList[i].TrackingNumber = reply.CompletedShipmentDetail.CompletedPackageDetails.First().TrackingIds.Select(t => t.TrackingNumber).First();

                        var content = reply.CompletedShipmentDetail.CompletedPackageDetails.First().Label.Parts.First().Image;
                        System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://api.labelary.com/v1/printers/8dpmm/labels/4x6/");
                        webRequest.Method        = "POST";
                        webRequest.Accept        = "application/pdf";
                        webRequest.ContentType   = "application/x-www-form-urlencoded";
                        webRequest.ContentLength = content.Length;

                        using (Stream requestStream = webRequest.GetRequestStream())
                        {
                            requestStream.Write(content, 0, content.Length);

                            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)webRequest.GetResponse();
                            using (Stream responseStream = response.GetResponseStream())
                            {
                                using (FileStream fileStream = File.Create(Path.Combine(filePath, boxList[i].BoxID + ".pdf")))
                                {
                                    responseStream.CopyTo(fileStream);
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    QDLogistics.FedExShipService.Notification notification = new QDLogistics.FedExShipService.Notification();

                    if (!string.IsNullOrEmpty(consoleOutputBehavior.ConsoleOutputInspector.ResponseXML))
                    {
                        XElement element = XElement.Parse(consoleOutputBehavior.ConsoleOutputInspector.ResponseXML);
                        notification.Message = element.Attributes("Message").Any() ? element.Attributes("Message").First().Value : element.Attributes("Desc").First().Value;
                    }
                    else
                    {
                        notification.Message = e.Message;
                    }

                    reply = new ProcessShipmentReply()
                    {
                        Notifications = new QDLogistics.FedExShipService.Notification[] { notification }
                    };
                }
            }

            return(reply);
        }