示例#1
0
        public ActionResult DirectLineEdit(int?id, [Bind(Include = "start,length,search")] RouteValue routeValue)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            if (!MyHelp.CheckAuth("shipping", "directLine", EnumData.AuthType.Edit))
            {
                RedirectToAction("index", "main");
            }

            using (IRepository <DirectLine> DirectLine = new GenericRepository <DirectLine>())
            {
                DirectLine directLine = DirectLine.Get(id.Value);

                if (directLine == null)
                {
                    return(HttpNotFound());
                }

                ViewBag.routeValue = routeValue;
                return(View(directLine));
            }
        }
示例#2
0
        public MainPage()
        {
            InitializeComponent();

            bot = new DirectLine(DirectLineKey);
            bot.OnNewMessage += Bot_OnNewMessage;
        }
示例#3
0
        public ActionResult DirectLineEdit(int id, [Bind(Include = "start,length,search")] RouteValue routeValue)
        {
            if (!MyHelp.CheckAuth("shipping", "directLine", EnumData.AuthType.Edit))
            {
                RedirectToAction("index", "main");
            }

            using (IRepository <DirectLine> DirectLine = new GenericRepository <DirectLine>())
            {
                DirectLine directLine = DirectLine.Get(id);

                if (directLine == null)
                {
                    return(HttpNotFound());
                }

                if (TryUpdateModel(directLine) && ModelState.IsValid)
                {
                    directLine.CountryName = MyHelp.GetCountries().First(c => c.TwoCode.Equals(directLine.CountryCode)).Name;
                    DirectLine.SaveChanges();

                    MyHelp.Log("DirectLine", directLine.ID, "編輯DL運輸廠商");
                    return(RedirectToAction("directLine", "shipping", routeValue));
                }

                ViewBag.routeValue = routeValue;
                return(View(directLine));
            }
        }
示例#4
0
        public Box GetCurrentBox(DirectLine directLine, int warehouseID, int methodID = 0)
        {
            MyHelp.Log("Box", null, string.Format("取得當前未出貨的{0} Box", directLine.Abbreviation), Session);

            boxData = db.Box.Where(b => b.IsEnable && !b.IsReserved && b.DirectLine.Equals(directLine.ID) && b.WarehouseFrom.Equals(warehouseID) && b.FirstMileMethod.Equals(methodID) && b.ShippingStatus.Equals((byte)EnumData.DirectLineStatus.未發貨))
                      .OrderByDescending(b => b.Create_at).FirstOrDefault();
            if (boxData == null)
            {
                MyHelp.Log("Box", null, string.Format("開始建立【{0}】新Box", directLine.Abbreviation), Session);

                string boxID = string.Format("{0}-{1}", directLine.Abbreviation, TimeZoneConvert.Utc.ToString("yyyyMMdd"));
                int    count = db.Box.AsNoTracking().Where(b => b.IsEnable && b.DirectLine.Equals(directLine.ID) && b.BoxID.Contains(boxID)).Select(b => b.MainBox).Distinct().Count() + 1;
                byte[] Byte  = BitConverter.GetBytes(count);
                Byte[0] += 64;
                boxData  = new Box()
                {
                    IsEnable        = true,
                    BoxID           = string.Format("{0}-{1}", boxID, System.Text.Encoding.ASCII.GetString(Byte.Take(1).ToArray())),
                    DirectLine      = directLine.ID,
                    FirstMileMethod = methodID,
                    WarehouseFrom   = warehouseID,
                    BoxType         = (byte)EnumData.DirectLineBoxType.DirectLine,
                    Create_at       = TimeZoneConvert.Utc
                };
                boxData.MainBox         = boxData.BoxID;
                db.Entry(boxData).State = System.Data.Entity.EntityState.Added;
                db.SaveChanges();

                MyHelp.Log("Box", boxData.BoxID, string.Format("Box【{0}】建立完成", boxData.BoxID), Session);
            }

            return(boxData);
        }
示例#5
0
        public ActionResult DirectLineCreate()
        {
            if (!MyHelp.CheckAuth("shipping", "directLine", EnumData.AuthType.Insert))
            {
                return(RedirectToAction("index", "main"));
            }

            using (IRepository <DirectLine> DirectLine = new GenericRepository <DirectLine>())
            {
                DirectLine newDirectLine = new DirectLine()
                {
                    IsEnable = false
                };
                DirectLine.Create(newDirectLine);
                DirectLine.SaveChanges();

                MyHelp.Log("DirectLine", newDirectLine.ID, "新增DL廠商");
                return(RedirectToAction("directLineEdit", new { id = newDirectLine.ID }));
            }
        }
示例#6
0
        public ActionResult DirectLineDelete(int id, [Bind(Include = "start,length,search")] RouteValue routeValue)
        {
            if (!MyHelp.CheckAuth("shipping", "directLine", EnumData.AuthType.Delete))
            {
                RedirectToAction("index", "main");
            }

            using (IRepository <DirectLine> DirectLine = new GenericRepository <DirectLine>())
            {
                DirectLine directLine = DirectLine.Get(id);

                if (directLine == null)
                {
                    return(HttpNotFound());
                }

                directLine.IsEnable = false;
                DirectLine.Update(directLine, directLine.ID);
                DirectLine.SaveChanges();

                MyHelp.Log("DirectLine", directLine.ID, "刪除DL運輸廠商");
                return(RedirectToAction("directLine", "shipping", routeValue));
            }
        }
示例#7
0
        private void FedEx_Test(string BoxID)
        {
            var            boxList    = db.Box.Where(b => b.IsEnable && b.MainBox.Equals(BoxID)).ToList();
            ShippingMethod method     = db.ShippingMethod.Find(boxList.First().FirstMileMethod);
            DirectLine     directLine = db.DirectLine.Find(boxList.First().DirectLine);
            CarrierAPI     api        = method.Carriers.CarrierAPI;
            FedEx_API      FedEx      = new FedEx_API(api);
            var            result     = FedEx.CreateBox(boxList, method, directLine);

            if (result.HighestSeverity.Equals(FedExShipService.NotificationSeverityType.SUCCESS))
            {
                var    Data           = result.CompletedShipmentDetail.CompletedPackageDetails.First();
                string TrackingNumber = Data.TrackingIds.First().TrackingNumber;
                //System.IO.File.WriteAllBytes(@"G:\Downloads\FedEx_Test3.pdf", Crop(Data.Label.Parts.First().Image, 29f, 324f, 319f, 762f));
                //System.IO.File.WriteAllBytes(@"G:\Downloads\FedEx_Test4.pdf", Data.Label.Parts.First().Image);

                var    zpl     = Data.Label.Parts.First().Image;
                string str     = Encoding.ASCII.GetString(zpl);
                var    request = (HttpWebRequest)WebRequest.Create("http://api.labelary.com/v1/printers/8dpmm/labels/4x6.75/");
                request.Method        = "POST";
                request.Accept        = "application/pdf"; // omit this line to get PNG images back
                request.ContentType   = "application/x-www-form-urlencoded";
                request.ContentLength = zpl.Length;

                var requestStream = request.GetRequestStream();
                requestStream.Write(zpl, 0, zpl.Length);
                requestStream.Close();

                try
                {
                    var response       = (HttpWebResponse)request.GetResponse();
                    var responseStream = response.GetResponseStream();
                    var fileStream     = System.IO.File.Create(@"G:\Downloads\FedEx_Test5.pdf"); // change file name for PNG images
                    responseStream.CopyTo(fileStream);
                    responseStream.Close();
                    fileStream.Close();
                }
                catch (WebException e)
                {
                    Console.WriteLine("Error: {0}", e.Status);
                }
            }

            iTextSharp.text.pdf.PdfReader.unethicalreading = true;
            // Reads the PDF document
            using (iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(@"G:\Downloads\FedEx_Test5.pdf"))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    // Create a new document
                    //using (iTextSharp.text.Document doc =
                    //	new iTextSharp.text.Document(new iTextSharp.text.Rectangle(288f,432f)))
                    using (iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4))
                    {
                        // Make a copy of the document
                        iTextSharp.text.pdf.PdfSmartCopy smartCopy = new iTextSharp.text.pdf.PdfSmartCopy(doc, ms)
                        {
                            PdfVersion = iTextSharp.text.pdf.PdfWriter.VERSION_1_7
                        };
                        smartCopy.CloseStream = false;
                        // Open the newly created document
                        doc.Open();
                        // Loop through all pages of the source document
                        for (int i = pdfReader.NumberOfPages; i >= 1; i--)
                        {
                            doc.NewPage();// net necessary line
                            // Get a page
                            var page = pdfReader.GetPageN(i);
                            // Copy the content and insert into the new document
                            var copiedPage = smartCopy.GetImportedPage(pdfReader, i);
                            smartCopy.AddPage(copiedPage);

                            if (i.Equals(1))
                            {
                                doc.NewPage();
                                smartCopy.AddPage(copiedPage);
                            }
                        }
                        smartCopy.FreeReader(pdfReader);
                        smartCopy.Close();
                        ms.Position = 0;
                        System.IO.File.WriteAllBytes(@"G:\Downloads\FedEx_Test6.pdf", ms.GetBuffer());
                        // Close the output document
                        doc.Close();
                    }
                }
            }
        }
 public BotConnector(IDirectLineClient client, IOptions <DirectLine> botClientSettings)
 {
     this.client            = client;
     this.botClientSettings = botClientSettings.Value;
 }
示例#9
0
        public void SendMailToCarrier(Box box, DirectLine directLine)
        {
            List <Items> itemsList = box.Packages.Where(p => p.IsEnable.Value).SelectMany(p => p.Items.Where(i => i.IsEnable.Value)).ToList();

            if (itemsList.Any())
            {
                string basePath = HostingEnvironment.MapPath("~/FileUploads");

                string   sendMail = "*****@*****.**";
                string   mailTitle;
                string   mailBody;
                string[] receiveMails;
                string[] ccMails = new string[] { "*****@*****.**", "*****@*****.**", "*****@*****.**" };

                switch (directLine.Abbreviation)
                {
                case "IDS":
                case "IDS (US)":
                    MyHelp.Log("PickProduct", null, "寄送IDS出貨通知");

                    receiveMails = new string[] { "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**" };
                    mailTitle    = "To IDS Peter and Cherry - 1 parcels-sent out";
                    mailBody     = string.Format("{0}<br /><br />Box 1 will send out", string.Join("<br />", box.DirectLineLabel.Where(l => l.IsEnable).Select(l => l.LabelID)));

                    bool IDS_Status = MyHelp.Mail_Send(sendMail, receiveMails, ccMails, mailTitle, mailBody, true, null, null, false);
                    if (IDS_Status)
                    {
                        MyHelp.Log("PickProduct", null, mailTitle);
                    }
                    else
                    {
                        MyHelp.Log("PickProduct", null, string.Format("{0} 寄送失敗", mailTitle));
                    }
                    break;

                case "ECOF":
                    MyHelp.Log("PickProduct", null, "寄送ECOF出貨通知");

                    receiveMails = new string[] { "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**" };
                    var packageList = box.Packages.Where(p => p.IsEnable.Value).ToList();
                    mailTitle = string.Format("DISPATCHED: {0}, {1}pcs", box.TrackingNumber, packageList.Count());
                    mailBody  = string.Format("Tracking {0}({1}pcs, {2}<br />", box.TrackingNumber, packageList.Count(), box.BoxID);
                    mailBody += string.Join("<br />", box.Packages.Where(p => p.IsEnable.Value).Select(p => string.Format("{0}-{1}-{2}", p.Items.First().ProductID, p.OrderID.Value, p.TrackingNumber)).ToArray());

                    List <Tuple <Stream, string> > ECOF_File = new List <Tuple <Stream, string> >();
                    var memoryStream = new MemoryStream();
                    using (var file = new ZipFile())
                    {
                        foreach (Packages package in box.Packages.Where(p => p.IsEnable.Value).ToList())
                        {
                            string AWB_File = Path.Combine(basePath, package.FilePath, string.Format("{0}-{1}-{2}.pdf", package.Items.First(i => i.IsEnable.Value).ProductID, package.OrderID, package.TrackingNumber));
                            if (!System.IO.File.Exists(AWB_File))
                            {
                                System.IO.File.Copy(Path.Combine(basePath, package.FilePath, "AirWaybill.pdf"), AWB_File);
                            }
                            file.AddFile(AWB_File, "");
                        }
                        file.Save(memoryStream);
                    }
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    ECOF_File.Add(new Tuple <Stream, string>(memoryStream, "Labels.zip"));

                    bool ECOF_Status = MyHelp.Mail_Send(sendMail, receiveMails, ccMails, mailTitle, mailBody, true, null, ECOF_File, false);
                    if (ECOF_Status)
                    {
                        MyHelp.Log("PickProduct", null, mailTitle);
                    }
                    else
                    {
                        MyHelp.Log("PickProduct", null, string.Format("{0} 寄送失敗", mailTitle));
                    }
                    break;
                }
            }
        }
示例#10
0
        public ActionResult Dispatch(int[] packageIDs, int?method, string tracking)
        {
            AjaxResult result = new AjaxResult();

            try
            {
                if (!packageIDs.Any())
                {
                    throw new Exception("沒有給訂單!");
                }

                int warehouseID = 0;
                if (!int.TryParse(Session["warehouseId"].ToString(), out warehouseID))
                {
                    throw new Exception("找不到出貨倉!");
                }

                SC_WebService SCWS = new SC_WebService(Session["ApiUserName"].ToString(), Session["ApiPassword"].ToString());

                if (!SCWS.Is_login)
                {
                    throw new Exception("SC is not login");
                }

                Packages = new GenericRepository <Packages>(db);
                IRepository <Box>             Box   = new GenericRepository <Box>(db);
                IRepository <DirectLineLabel> Label = new GenericRepository <DirectLineLabel>(db);

                TaskFactory factory    = System.Web.HttpContext.Current.Application.Get("TaskFactory") as TaskFactory;
                ThreadTask  threadTask = new ThreadTask("Dropship DL 訂單 Dispatch");

                lock (factory)
                {
                    threadTask.AddWork(factory.StartNew(Session =>
                    {
                        threadTask.Start();

                        string message = "";

                        HttpSessionStateBase session = (HttpSessionStateBase)Session;

                        try
                        {
                            TimeZoneConvert timeZoneConvert = new TimeZoneConvert();

                            List <Packages> dispatchList = new List <Packages>();
                            List <string> errorList      = new List <string>();

                            List <Packages> packageList = db.Packages.AsNoTracking().Where(p => p.IsEnable.Value && packageIDs.Contains(p.ID)).ToList();
                            DirectLine directLine       = db.DirectLine.Find(packageList[0].Method.DirectLine);
                            string boxID = string.Format("{0}-{1}", directLine.Abbreviation, timeZoneConvert.Utc.ToString("yyyyMMdd"));
                            int count    = db.Box.Where(b => b.IsEnable && b.DirectLine.Equals(directLine.ID) && b.BoxID.Contains(boxID)).Select(b => b.MainBox).Distinct().Count() + 1;
                            byte[] Byte  = BitConverter.GetBytes(count);
                            Byte[0]     += 64;
                            boxID        = string.Format("{0}-{1}", boxID, System.Text.Encoding.ASCII.GetString(Byte.Take(1).ToArray()));

                            foreach (Packages package in packageList)
                            {
                                DirectLineLabel label = package.Label;
                                OrderData order       = SCWS.Get_OrderData(package.OrderID.Value);
                                if (CheckOrderStatus(package, order.Order))
                                {
                                    ThreadTask uploadPOTask = new ThreadTask(string.Format("直發商待出貨區 - 更新訂單【{0}】以及PO【{1}】資料至SC", package.OrderID, package.POId), session);

                                    lock (factory)
                                    {
                                        uploadPOTask.AddWork(factory.StartNew(() =>
                                        {
                                            uploadPOTask.Start();

                                            string error = "";

                                            try
                                            {
                                                SyncProcess Sync = new SyncProcess(session, factory);
                                                error            = Sync.Update_PurchaseOrder(package.ID, false);

                                                if (string.IsNullOrEmpty(error))
                                                {
                                                    //if (directLine.Abbreviation.Equals("ECOF"))
                                                    //{
                                                    //    ThreadTask SyncTask = new ThreadTask(string.Format("Direct Line 訂單【{0}】SC更新", package.OrderID));
                                                    //    SyncTask.AddWork(factory.StartNew(() =>
                                                    //    {
                                                    //        SyncTask.Start();
                                                    //        SyncProcess sync = new SyncProcess(session);
                                                    //        return sync.Update_Tracking(package);
                                                    //    }));
                                                    //}
                                                    //else
                                                    //{
                                                    //    foreach (Items item in package.Items.Where(i => i.IsEnable.Value).ToList())
                                                    //    {
                                                    //        if (item.SerialNumbers.Any()) SCWS.Update_ItemSerialNumber(item.ID, item.SerialNumbers.Select(s => s.SerialNumber).ToArray());
                                                    //    }
                                                    //}

                                                    foreach (Items item in package.Items.Where(i => i.IsEnable.Value).ToList())
                                                    {
                                                        if (item.SerialNumbers.Any())
                                                        {
                                                            SCWS.Update_ItemSerialNumber(item.ID, item.SerialNumbers.Select(s => s.SerialNumber).ToArray());
                                                        }
                                                    }
                                                }
                                            }
                                            catch (Exception e)
                                            {
                                                error = e.InnerException != null && !string.IsNullOrEmpty(e.InnerException.Message) ? e.InnerException.Message : e.Message;
                                            }

                                            return(error);
                                        }));
                                    }

                                    package.ProcessStatus = (int)EnumData.ProcessStatus.已出貨;
                                    package.BoxID         = label.BoxID = boxID;
                                    label.Status          = (byte)EnumData.LabelStatus.正常;
                                    dispatchList.Add(package);
                                }
                                else
                                {
                                    MyHelp.Log("DirectLineLabel", label.LabelID, string.Format("標籤【{0}】狀態異常", label.LabelID), session);

                                    package.Orders.StatusCode    = (int)order.Order.StatusCode;
                                    package.Orders.PaymentStatus = (int)order.Order.PaymentStatus;
                                    label.Status = (byte)EnumData.LabelStatus.鎖定中;

                                    if (order.Order.StatusCode.Equals((int)OrderStatusCode.Canceled))
                                    {
                                        label.Status = (byte)EnumData.LabelStatus.作廢;

                                        SerialNumbers = new GenericRepository <SerialNumbers>(db);
                                        foreach (var ss in SerialNumbers.GetAll().Where(s => s.OrderID.Equals(package.OrderID)))
                                        {
                                            SerialNumbers.Delete(ss);
                                        }
                                        ;
                                    }

                                    errorList.Add(string.Format("標籤【{0}】狀態異常,請重新取出!", package.OrderID.Value));
                                }
                                Packages.Update(package, package.ID);
                                Label.Update(label, label.LabelID);
                            }

                            if (dispatchList.Any())
                            {
                                Box box = new Box()
                                {
                                    IsEnable        = true,
                                    BoxID           = boxID,
                                    MainBox         = boxID,
                                    DirectLine      = directLine.ID,
                                    FirstMileMethod = method ?? 0,
                                    WarehouseFrom   = warehouseID,
                                    ShippingStatus  = method.HasValue ? (byte)EnumData.DirectLineStatus.運輸中 : (byte)EnumData.DirectLineStatus.已到貨,
                                    BoxType         = (byte)EnumData.DirectLineBoxType.DirectLine,
                                    TrackingNumber  = tracking,
                                    Create_at       = timeZoneConvert.Utc
                                };
                                db.Entry(box).State = System.Data.Entity.EntityState.Added;

                                db.SaveChanges();
                                MyHelp.Log("Box", boxID, string.Format("Box【{0}】建立成功", boxID), session);

                                MyHelp.Log("Box", box.BoxID, string.Format("寄送 Box【{0}】DL資料", box.BoxID), session);
                                SendMailToCarrier(box, db.DirectLine.AsNoTracking().First(d => d.ID.Equals(box.DirectLine)));

                                MyHelp.Log("Box", box.BoxID, string.Format("Box【{0}】完成出貨", box.BoxID), session);
                            }

                            Packages.SaveChanges();

                            if (errorList.Any())
                            {
                                message = string.Join("\n", errorList.ToArray());
                            }
                        }
                        catch (Exception e)
                        {
                            message = e.InnerException != null && !string.IsNullOrEmpty(e.InnerException.Message) ? e.InnerException.Message : e.Message;
                        }

                        return(message);
                    }, HttpContext.Session));
                }
            }
            catch (Exception e)
            {
                result.status  = false;
                result.message = e.InnerException != null && !string.IsNullOrEmpty(e.InnerException.Message) ? e.InnerException.Message : e.Message;
            }

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
示例#11
0
文件: DHL_API.cs 项目: leeleonis/QD
        public ShipmentValidateResponse CreateBox(Box box, DirectLine directLine)
        {
            ShipmentValidateResponse  result;
            ShipmentValidateRequestEA shipment = new ShipmentValidateRequestEA();

            shipment.Request = requsetInit();
            //shipment.NewShipper = YesNo1.N;
            //shipment.NewShipperSpecified = true;
            shipment.LanguageCode           = "tw";
            shipment.PiecesEnabled          = PiecesEnabled.Y;
            shipment.PiecesEnabledSpecified = true;
            shipment.Reference = new Reference1[] { new Reference1()
                                                    {
                                                        ReferenceID = box.BoxID
                                                    } };
            shipment.LabelImageFormat           = LabelImageFormat.PDF;
            shipment.LabelImageFormatSpecified  = true;
            shipment.RequestArchiveDoc          = YesNo1.Y;
            shipment.RequestArchiveDocSpecified = true;
            shipment.Label = new Label()
            {
                LabelTemplate = "8X4_A4_PDF"
            };

            shipment.Billing = new Billing1()
            {
                ShipperAccountNumber     = api_account,
                ShippingPaymentType      = ShipmentPaymentType.S,
                BillingAccountNumber     = api_account,
                DutyPaymentType          = DutyTaxPaymentType1.S,
                DutyPaymentTypeSpecified = true,
                DutyAccountNumber        = api_account
            };

            Contact2 contact = new Contact2()
            {
                PersonName  = directLine.ContactName,
                PhoneNumber = directLine.PhoneNumber
            };

            shipment.Consignee = new Consignee1()
            {
                CompanyName = !string.IsNullOrEmpty(directLine.CompanyName) ? directLine.CompanyName : contact.PersonName,
                AddressLine = new string[] { directLine.StreetLine1, directLine.StreetLine2 },
                City        = directLine.City,
                Division    = directLine.StateName,
                PostalCode  = directLine.PostalCode,
                CountryCode = directLine.CountryCode,
                CountryName = directLine.CountryName,
                Contact     = contact
            };

            List <Items>  itemList  = box.Packages.Where(p => p.IsEnable.Value).SelectMany(p => p.Items.Where(i => i.IsEnable.Value)).ToList();
            List <Piece2> pieceList = new List <Piece2>();

            pieceList.Add(new Piece2()
            {
                PackageType   = PackageType1.YP,
                Weight        = itemList.Sum(i => i.Qty.Value * ((decimal)i.Skus.Weight / 1000)),
                PieceContents = itemList.First().Skus.ProductType.ProductTypeName
            });

            shipment.ShipmentDetails = new ShipmentDetails2()
            {
                NumberOfPieces    = pieceList.Count().ToString(),
                Pieces            = pieceList.ToArray(),
                Weight            = pieceList.Sum(p => p.Weight),
                WeightUnit        = WeightUnit.K,
                GlobalProductCode = "P",
                LocalProductCode  = "P",
                Date                   = DateTime.Now,
                Contents               = string.Join(", ", itemList.Select(i => i.Skus.ProductType.ProductTypeName).Distinct().ToArray()),
                DoorTo                 = DoorTo.DD,
                DoorToSpecified        = true,
                DimensionUnit          = DimensionUnit.C,
                DimensionUnitSpecified = true,
                //InsuredAmount = "0.00",
                PackageType         = PackageType1.YP,
                IsDutiable          = YesNo1.Y,
                IsDutiableSpecified = true,
                CurrencyCode        = Enum.GetName(typeof(QDLogistics.OrderService.CurrencyCodeType2), box.Packages.First().Orders.OrderCurrencyCode.Value)
            };

            shipment.Dutiable = new Dutiable1()
            {
                DeclaredValue    = box.Packages.Sum(p => p.DeclaredTotal).ToString(),
                DeclaredCurrency = shipment.ShipmentDetails.CurrencyCode,
                TermsOfTrade     = "DDP"
            };

            shipment.Shipper = new Shipper1()
            {
                ShipperID   = api_account,
                CompanyName = "Zhi You Wan LTD",
                AddressLine = new string[] { "No.51, Sec.3 Jianguo N. Rd.,", "South Dist.," },
                City        = "Taichung City",
                PostalCode  = "403",
                CountryCode = "TW",
                CountryName = "Taiwan",
                Contact     = new Contact2()
                {
                    PersonName = "Huai Wei Ho", PhoneNumber = "0423718118"
                }
            };

            shipment.SpecialService = new SpecialService1[] { new SpecialService1()
                                                              {
                                                                  SpecialServiceType = "DD",
                                                                  ChargeValue        = shipment.Dutiable.DeclaredValue,
                                                                  CurrencyCode       = shipment.Dutiable.DeclaredCurrency
                                                              } };

            XmlSerializer serializer = new XmlSerializer(typeof(ShipmentValidateResponse));
            string        request    = SendRequest(shipment);

            using (TextReader reader = new StringReader(request))
            {
                try
                {
                    result = (ShipmentValidateResponse)serializer.Deserialize(reader);
                }
                catch (Exception e)
                {
                    TextReader    errorReader           = new StringReader(request);
                    XmlSerializer errorSerializer       = new XmlSerializer(typeof(ShipmentValidateErrorResponse));
                    ShipmentValidateErrorResponse error = errorSerializer.Deserialize(errorReader) as ShipmentValidateErrorResponse;
                    errorReader.Dispose();
                    throw new Exception(string.Join("; ", error.Response.Status.Condition.Select(c => c.ConditionData)));
                }
            }

            return(result);
        }
示例#12
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);
        }