public ActionResult Capnhathuycthd(decimal id)
        {
            var cthd = _huycthdvatRepository.GetById(id);
            var hd   = _huyhdvatRepository.GetByTwoKey(cthd.Idhoadon, cthd.chinhanh);

            cthd.sotien      = -cthd.sotien;
            cthd.sotiennt    = -cthd.sotiennt;
            ViewBag.idhoadon = cthd.Idhoadon;
            ListNgoaite(cthd.loaitien);
            Listhttc(cthd.httc);
            Tkco(cthd.tkco);
            Tkno(cthd.tkno);
            if (string.IsNullOrEmpty(hd.keyhddt))
            {
                ViewBag.hide = "Cập nhật";
            }
            else
            {
                ViewBag.hide = "hide";
            }
            //var hd = _hoadonRepository.GetById(cthd.Idhoadon);
            //if (!String.IsNullOrEmpty(hd.hdvat))
            //{
            //    SetAlert("Đây là hoá đơn điện tử, không được điều chỉnh thông tin khi đã xuất hoá đơn", "error");
            //    return Redirect(HttpContext.Session.GetString("urlEditHoadon"));
            //}
            return(View("Capnhathuycthd", cthd));
        }
        public IActionResult Edit(string id)
        {
            TempData["idhoadonhuy"] = id;
            HttpContext.Session.SetString("urlEditHoadonhuy", UriHelper.GetDisplayUrl(Request));
            if (id == null)
            {
                return(NotFound());
            }
            var hoadon = _huyhdvatRepository.GetByTwoKey(id, HttpContext.Session.GetString("chinhanh"));

            if (hoadon == null)
            {
                return(NotFound());
            }
            ViewBag.idhoadon = id;
            listHttt(hoadon.httt);
            if (string.IsNullOrEmpty(hoadon.hdvat) && hoadon.nguoitaohd == HttpContext.Session.GetString("username"))
            {
                ViewBag.capnhat = "Cập nhật";
            }
            else
            {
                ViewBag.capnhat = "hide";
            }
            return(View(hoadon));
        }
        public async Task <ActionResult> TaoHoadonHuy(string Idhoadon)
        {
            var     user    = _userRepository.GetById(HttpContext.Session.GetString("username"));
            string  khhd    = HttpContext.Session.GetString("kyhieuhd").Trim();
            string  mausohd = HttpContext.Session.GetString("mausohd").Trim();
            var     dkhd    = _dsdangkyhdRepository.listDangkyhoadon().Where(x => x.kyhieuhd == HttpContext.Session.GetString("kyhieuhd") && x.chinhanh == HttpContext.Session.GetString("maviettat")).SingleOrDefault();
            decimal mainkey = Convert.ToDecimal(dkhd.mainkey) + 1;
            string  key     = mainkey.ToString() + HttpContext.Session.GetString("maviettat") + mausohd.Replace("/", "") + khhd.Replace("/", "");// HttpContext.Session.GetString("mausohd").Replace("/","")+HttpContext.Session.GetString("kyhieuhd").Replace("/","");
            // Lấy thông tin site, user, pass add tự động
            string sitehddt = dkhd.sitehddt + "/PublishService.asmx";
            string usersite = dkhd.usersite;
            string passsite = dkhd.passsite;


            var hd = _huyhdvatRepository.GetByTwoKey(Idhoadon, HttpContext.Session.GetString("chinhanh"));

            List <Huycthdvat> cthd        = _huycthdvatRepository.Listhuycthdvat(Idhoadon, HttpContext.Session.GetString("chinhanh")).Where(x => x.ngayhuy is null).ToList();
            string            InvData_xml = "<Invoices><Inv><key>" + key + "</key><Invoice>";

            // Tạo thông tin người bán (không cần truyền tham số, VNPT sẽ tự lấy trên trang web
            InvData_xml += "<SellerName></SellerName><SellerAddress></SellerAddress><SellerTaxCode></SellerTaxCode><SellerPhone></SellerPhone>";
            // Thông tin khách hàng
            InvData_xml += "<CusCode>" + (string.IsNullOrEmpty(hd.makh) ? "00000" : hd.makh.Trim()) + HttpContext.Session.GetString("maviettat") + "</CusCode><CusName>" + (string.IsNullOrEmpty(hd.tenkh) ? "" : hd.tenkh.Replace("&", "&amp;")) + "</CusName><Buyer>" + (string.IsNullOrEmpty(hd.tenkhach) ? "" : hd.tenkhach.Replace("&", "&amp;")) + " </Buyer><CusAddress>" + hd.diachi + "</CusAddress>";
            InvData_xml += "<CusTaxCode>" + hd.msthue + "</CusTaxCode><PaymentMethod>" + hd.httt + "</PaymentMethod><CusBankNo></CusBankNo><CusPhone>" + hd.dienthoai + "</CusPhone><ContNo></ContNo><VehicleNo></VehicleNo>";
            InvData_xml += "<ContractDate></ContractDate><DocDate>" + (hd.ngayct.HasValue ? hd.ngayct.Value.ToString("dd/MM/yyyy") : "") + "</DocDate><ContractNumber></ContractNumber><ReferenceNo></ReferenceNo>";

            //Tạo list Product
            InvData_xml += "<Products>";
            double tcvat = 0, tcsotien = 0, tcppv = 0;

            foreach (var i in cthd)
            {
                double tienthuevat = 0, doanhthu = 0, tienppv = 0;;
                tienppv     = Math.Round(0.01 * (double)i.sotien * (double)i.ppv / ((1 + 0.01 * (double)i.ppv) * (1 + 0.01 * i.vat)), 0);
                tienthuevat = Math.Round((double)i.sotien * 0.01 * i.vat / (1 + 0.01 * i.vat), 0);
                doanhthu    = Math.Round((double)i.sotien - tienthuevat - tienppv, 0);

                InvData_xml += "<Product>";
                InvData_xml += "<ProdName>" + i.diengiai + "</ProdName>";
                InvData_xml += "<ProdUnit>" + (i.sk == 0 ? 1 : i.sk) + "</ProdUnit>";
                InvData_xml += "<ProdQuantity>" + (i.slve == 0 ? 1 : i.slve) + "</ProdQuantity>";
                InvData_xml += "<ProdPrice>" + Math.Abs(i.sotien) + "</ProdPrice>";
                InvData_xml += "<Total>" + Math.Abs(doanhthu) + "</Total>";  // Thành tiền chưa thuế vat
                InvData_xml += "<Extra1>" + Math.Abs(tienppv) + "</Extra1>"; // Tiền phí phục vụ
                InvData_xml += "<VATRate>" + i.vat + "</VATRate>";           // Thuế vat
                tcvat       += tienthuevat;
                tcsotien    += doanhthu;
                tcppv       += tienppv;
                //tcsotienvathue += tienthuevat;
                InvData_xml += "<VATAmount>" + Math.Abs(tienthuevat) + "</VATAmount>"; // Tiền thuế
                InvData_xml += "<Amount>" + Math.Abs(i.sotien) + "</Amount>";          // Thành tiền có thuế
                InvData_xml += "</Product>";
            }

            //Đóng tag Product
            InvData_xml += "</Products>";
            //Thông tin báo cáo
            InvData_xml += "<GrossValue>" + Math.Abs(tcsotien) + "</GrossValue>";           // *Tổng tiền trước thuế của mức thuế null (không chịu thuế) NUMBER(18,4)
            InvData_xml += "<GrossValue0>0</GrossValue0>";                                  //*Tổng tiền trước thuế của mức thuế 0% NUMBER(18,4)
            InvData_xml += "<GrossValue5>0</GrossValue5>";                                  //*Tổng tiền trước thuế của mức thuế 5 % NUMBER(18, 4)
            InvData_xml += "<GrossValue10>0</GrossValue10>";                                //*Tổng tiền trước thuế của mức thuế 10 % NUMBER(18, 4)
            InvData_xml += "<VatAmount0>0</VatAmount0>";                                    //*Tổng tiền thuế của mức thuế 0% NUMBER(18,4)
            InvData_xml += "<VatAmount5>0</VatAmount5>";                                    //*Tổng tiền thuế của mức thuế 5% NUMBER(18,4)
            InvData_xml += "<VatAmount10>" + Math.Abs(tcvat) + "</VatAmount10>";            //Tổng tiền thuế của mức thuế 10% NUMBER(18,4)
            InvData_xml += "<TotalQuantity>" + Math.Abs(tcppv) + "</TotalQuantity>";        //Tổng tiền phí phục vụ NUMBER(38,4)
            InvData_xml += "<Total>" + Math.Abs(tcsotien) + "</Total>";                     //Cộng tiền hàng (Sub -total)* NUMBER(38,4)
            InvData_xml += "<VATRate>" + 10 + "</VATRate>";                                 // Thuế GTGT* FLOAT
            InvData_xml += "<VATAmount>" + Math.Abs(tcvat) + "</VATAmount>";                //Tổng Tiền thuế GTGT* NUMBER(38,4)
            InvData_xml += "<Amount>" + Math.Abs((tcsotien + tcvat + tcppv)) + "</Amount>"; // Tổng cộng tiền thanh toán(Grand total)* NUMBER(38,4)
            double t = Math.Abs(tcsotien + tcvat + tcppv);
            string a = SoSangChu.DoiSoSangChu(t.ToString());

            a            = char.ToUpper(a[0]) + a.Substring(1);
            InvData_xml += "<AmountInWords>" + a + " đồng </AmountInWords>";                                //	<!--Số tiền viết bằng chữ* VARCHAR2(255 CHAR)-->";
            //InvData_xml += "<AmountInWords>" + SoSangChu.DoiSoSangChu(Math.Abs((tcsotien + tcvat + tcppv)).ToString()) + " đồng </AmountInWords>";//	<!--Số tiền viết bằng chữ* VARCHAR2(255 CHAR)-->";
            InvData_xml += "<ArisingDate>" + System.DateTime.Now.ToString("dd/MM/yyyy") + "</ArisingDate>"; // Ngày hóa đơn (dd/MM/yyyy) VARCHAR2(50 CHAR)

            //Đóng tag Invoice
            InvData_xml += "</Invoice></Inv></Invoices>";
            //XmlDocument doc = new XmlDocument();
            //doc.LoadXml(InvData_xml);
            //string Json= JsonConvert.SerializeXmlNode(doc);

            //string xml = JsonConvert.DeserializeXmlNode(Json).OuterXml;

            var inv = new PublishService.PublishServiceSoapClient(PublishService.PublishServiceSoapClient.EndpointConfiguration.PublishServiceSoap);

            // Hàm add webservice động
            inv.ChannelFactory.Endpoint.Address = new EndpointAddress(sitehddt);


            //Task<PublishService.ImportAndPublishInvResponse> ketqua = inv.ImportAndPublishInvAsync(HttpContext.Session.GetString("accounthddt"), HttpContext.Session.GetString("passhddt"), InvData_xml, usersite, passsite, mausohd, khhd, 0);// HttpContext.Session.GetString("masohd"), HttpContext.Session.GetString("kyhieuhd"), 0);
            Task <PublishService.ImportAndPublishInvResponse> ketqua = inv.ImportAndPublishInvAsync(user.accounthddt, user.passwordhddt, InvData_xml, usersite, passsite, mausohd, khhd, 0);// HttpContext.Session.GetString("masohd"), HttpContext.Session.GetString("kyhieuhd"), 0);
            var result = await ketqua;

            if (result.Body.ImportAndPublishInvResult.Substring(0, 2) == "OK")
            {
                // Cập nhật lại hoá đơn
                //
                string sohoadon = result.Body.ImportAndPublishInvResult.Split("_").Last();
                hd.hdvat = sohoadon.PadLeft(7, '0');
                //hd.hdvat =  mainkey.ToString().PadLeft(7, '0');
                hd.keyhddt  = key;
                hd.ngayin   = System.DateTime.Now;
                hd.datelock = System.DateTime.Now;
                hd.locker   = HttpContext.Session.GetString("username");
                // hd.user = HttpContext.Session.GetString("username");
                hd.logfile += hd.logfile + System.Environment.NewLine + " * User xuất hoá đơn: " + HttpContext.Session.GetString("username") + " vào lúc: " + System.DateTime.Now;
                _huyhdvatRepository.Update(hd);
                SetAlert("Xuất hoá đơn thành công.", "success");
                // Cập nhật mainkey cho table dsdangkyhoadon
                // int id = _dsdangkyhdRepository.listDangkyhoadon().Where(x => x.kyhieuhd == HttpContext.Session.GetString("kyhieuhd") && x.chinhanh == HttpContext.Session.GetString("maviettat")).SingleOrDefault().id;
                _dsdangkyhdRepository.updateMainkey(dkhd.id);
                _dsdangkyhdRepository.updateSohoadon(dkhd.id, decimal.Parse(sohoadon));
            }
            else
            {
                //switch (result.Body.ImportAndPublishInvResult.Substring(0, 5))
                switch (result.Body.ImportAndPublishInvResult.ToString())
                {
                case "ERR:1":
                    SetAlert("User đăng nhập sai, hoặc không có quyền tạo hoá đơn", "error");
                    break;

                case "ERR:3":
                    SetAlert("Dữ liệu đưa vào hoá đơn sai", "error");
                    break;

                case "ERR:5":
                    SetAlert("Không phát hành được hoá đơn", "error");
                    break;

                case "ERR:6":
                    SetAlert("Số hoá đơn vượt mức đăng ký phát hành", "error");
                    break;

                case "ERR:7":
                    SetAlert("User name sai", "error");
                    break;

                case "ERR:10":
                    SetAlert("Số hoá đơn vượt quá mức đăng ký phát hành", "error");
                    break;

                case "ERR:13":
                    // int id = _dsdangkyhdRepository.listDangkyhoadon().Where(x => x.kyhieuhd == HttpContext.Session.GetString("kyhieuhd") && x.chinhanh == HttpContext.Session.GetString("maviettat")).SingleOrDefault().id;
                    SetAlert("Trùng mã tra cứu, vui lòng xuất lại hoá đơn", "error");
                    _dsdangkyhdRepository.updateMainkey(dkhd.id);
                    break;

                default:
                    SetAlert("Không tạo được hoá đơn", "error");
                    break;
                }
            }
            return(Redirect(HttpContext.Session.GetString("urlEditHoadonhuy")));
        }