public ActionResult PreviewHoadonHuy(string Idhoadon, string chinhanh)
        {
            var hd = _huyhdvatRepository.GetByTwoKey(Idhoadon, chinhanh);// HttpContext.Session.GetString("chinhanh"));

            ViewBag.sohd = hd.hdvat;
            List <Huycthdvat>        cthd = _huycthdvatRepository.Listhuycthdvat(Idhoadon, HttpContext.Session.GetString("chinhanh")).Where(x => x.ngayhuy is null).ToList();
            List <ProductsViewModel> products = new List <ProductsViewModel>();
            double tcvat = 0, tcsotien = 0, tcppv = 0;
            int    stt = 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);
                var p = new ProductsViewModel();
                tcvat    += tienthuevat;
                tcsotien += doanhthu;
                tcppv    += tienppv;
                stt      += 1;
                products.Add(new ProductsViewModel()
                {
                    ProdId       = stt,
                    ProdName     = i.diengiai,
                    ProdUnit     = (i.sk == 0 ? 1 : i.sk),
                    ProdQuantity = (i.slve == 0 ? 1 : i.slve),
                    Total        = Math.Abs(doanhthu),
                    Extra1       = Math.Abs(tienppv),
                    VATRate      = i.vat,
                    VATAmount    = Math.Abs(tienthuevat),
                    Amount       = Math.Abs(doanhthu)
                });;;
            }
            ViewBag.count       = products.Count();
            ViewBag.listProduct = products;
            ViewBag.tong        = Math.Abs((tcsotien + tcvat + tcppv));
            ViewBag.tcsotien    = Math.Abs(tcsotien);
            ViewBag.tcvat       = Math.Abs(tcvat);
            ViewBag.tcppv       = Math.Abs(tcppv);
            double t = Math.Abs(tcsotien + tcvat + tcppv);
            //string a = SoSangChu.DoiSoSangChu((tcsotien + tcvat + tcppv).ToString());
            string a = SoSangChu.DoiSoSangChu((t).ToString());

            a = char.ToUpper(a[0]) + a.Substring(1);
            // ViewBag.sotienbangchu = SoSangChu.DoiSoSangChu(tcsotien + tcvat + tcppv).ToString()) + " đồng.";
            ViewBag.sotienbangchu = a + " đồng.";
            return(PartialView("PreviewHoadonHuy", hd));
        }
Beispiel #2
0
        public ActionResult Xemhoadon(string idhoadon)
        {
            var hd       = _hoadonRepository.GetByTwoKey(idhoadon, HttpContext.Session.GetString("chinhanh"));
            var chinhanh = _dsdangkyhdRepository.getthongtinhd(HttpContext.Session.GetString("chinhanh"), HttpContext.Session.GetString("kyhieuhd"));
            var cthd     = _cthdvatRepository.ListChitietHoadon(idhoadon, HttpContext.Session.GetString("chinhanh"));
            //DocX doc = null;
            string webRootPath = _hostingEnvironment.WebRootPath;
            string fileName    = webRootPath + @"\Wordtemp\hddt.docx";
            var    doc         = DocX.Load(fileName);

            doc.AddCustomProperty(new CustomProperty("mausohd", hd.mausohd));
            doc.AddCustomProperty(new CustomProperty("kyhieu", hd.kyhieu));
            doc.AddCustomProperty(new CustomProperty("sohd", hd.hdvat));
            doc.AddCustomProperty(new CustomProperty("ngayhd", hd.ngayin.HasValue? "(Date)Ngày " + hd.ngayin.Value.ToString("dd") + " tháng " + hd.ngayin.Value.ToString("MM") + " năm " + hd.ngayin.Value.ToString("yyyy"):" Ngày.....tháng.....năm..... "));
            doc.AddCustomProperty(new CustomProperty("tencongty", chinhanh.tencn));
            doc.AddCustomProperty(new CustomProperty("mstcty", chinhanh.masothue));
            doc.AddCustomProperty(new CustomProperty("diachicty", chinhanh.diachi));
            doc.AddCustomProperty(new CustomProperty("taikhoancty", ""));
            doc.AddCustomProperty(new CustomProperty("dienthoaicty", chinhanh.dienthoai));
            doc.AddCustomProperty(new CustomProperty("donvikhach", hd.tenkh));
            doc.AddCustomProperty(new CustomProperty("tenkhach", string.IsNullOrEmpty(hd.tenkhach)?"":hd.tenkhach));
            doc.AddCustomProperty(new CustomProperty("mstkhach", string.IsNullOrEmpty(hd.msthue)?"":hd.msthue));
            doc.AddCustomProperty(new CustomProperty("diachikhach", string.IsNullOrEmpty(hd.diachi)?"":hd.diachi.Trim()));

            double totalsotiennt = 0;
            double totaltienthue = 0;
            double totaltienppv  = 0;
            double total         = 0;
            var    tbChitiet     = doc.AddTable(1, 6);

            tbChitiet.SetWidths(new float[] { 50, 320, 100, 120, 80, 100 });

            tbChitiet.Rows[0].Cells[0].Paragraphs[0].Append("STT" + System.Environment.NewLine + " Order").Color(Color.Black).Font("Times New Roman").FontSize(10).Alignment = Alignment.center;
            tbChitiet.Rows[0].Cells[1].Paragraphs[0].Append("Tên hàng hoá, dịch vụ" + System.Environment.NewLine + " Description").Color(Color.Black).Font("Times New Roman").FontSize(10).Alignment = Alignment.center;
            tbChitiet.Rows[0].Cells[2].Paragraphs[0].Append("Số tiền" + System.Environment.NewLine + " Amount").Color(Color.Black).Font("Times New Roman").FontSize(10).Alignment = Alignment.center;
            tbChitiet.Rows[0].Cells[3].Paragraphs[0].Append("Tiền phí dịch vụ" + System.Environment.NewLine + " Service Chargers").Color(Color.Black).Font("Times New Roman").FontSize(10).Alignment = Alignment.center;
            tbChitiet.Rows[0].Cells[4].Paragraphs[0].Append("Thuế suất" + System.Environment.NewLine + " VAT Rate%").Color(Color.Black).Font("Times New Roman").FontSize(10).Alignment  = Alignment.center;
            tbChitiet.Rows[0].Cells[5].Paragraphs[0].Append("Tiền thuế" + System.Environment.NewLine + " VAT Amount").Color(Color.Black).Font("Times New Roman").FontSize(10).Alignment = Alignment.center;
            foreach (var i in cthd)
            {
                var    row      = tbChitiet.InsertRow();
                double ptvat    = Math.Round((i.vat / 100.0), 2);
                double tienthue = Math.Round((double)i.sotien * ptvat, 0);
                double tienppv  = Math.Round((double)i.sotien * ((double)i.ppv / 100.0), 0);
                row.Cells[0].Paragraphs[0].Append(i.sttdong == 0?"": i.sttdong.ToString()).Color(Color.Black).Font("Times New Roman").FontSize(10).Alignment = Alignment.center;
                row.Cells[1].Paragraphs[0].Append(i.diengiai).Color(Color.Black).Font("Times New Roman").FontSize(10).Alignment = Alignment.left;
                row.Cells[2].Paragraphs[0].Append(string.Format("{0:#,##0}", i.sotiennt)).Color(Color.Black).Font("Times New Roman").FontSize(10).Alignment = Alignment.right;
                row.Cells[3].Paragraphs[0].Append(string.Format("{0:#,##0}", tienppv)).Color(Color.Black).Font("Times New Roman").FontSize(10).Alignment    = Alignment.right;
                row.Cells[4].Paragraphs[0].Append(i.vat.ToString()).Color(Color.Black).Font("Times New Roman").FontSize(10).Alignment = Alignment.right;
                row.Cells[5].Paragraphs[0].Append(string.Format("{0:#,##0}", tienthue)).Color(Color.Black).Font("Times New Roman").FontSize(10).Alignment = Alignment.right;

                totalsotiennt += (double)i.sotiennt;
                totaltienthue += tienthue;
                totaltienppv  += tienppv;
                total         += (double)i.sotiennt + tienthue + tienppv;
                //row.Cells[0].SetBorder(TableCellBorderType.Bottom, new Novacode.Border(BorderStyle.Tcbs_double, BorderSize.one, 1, Color.Transparent));
                //row.Cells[1].SetBorder(TableCellBorderType.Bottom, new Novacode.Border(BorderStyle.Tcbs_double, BorderSize.one, 1, Color.Transparent));
                //row.Cells[2].SetBorder(TableCellBorderType.Bottom, new Novacode.Border(BorderStyle.Tcbs_double, BorderSize.one, 1, Color.Transparent));
                //row.Cells[3].SetBorder(TableCellBorderType.Bottom, new Novacode.Border(BorderStyle.Tcbs_double, BorderSize.one, 1, Color.Transparent));
                //row.Cells[4].SetBorder(TableCellBorderType.Bottom, new Novacode.Border(BorderStyle.Tcbs_double, BorderSize.one, 1, Color.Transparent));
                //row.Cells[5].SetBorder(TableCellBorderType.Bottom, new Novacode.Border(BorderStyle.Tcbs_double, BorderSize.one, 1, Color.Transparent));
            }
            // set no border cho table
            Novacode.Border b = new Novacode.Border(Novacode.BorderStyle.Tcbs_none, BorderSize.seven, 0, Color.Transparent);
            tbChitiet.SetBorder(TableBorderType.InsideH, b);
            tbChitiet.SetBorder(TableBorderType.InsideV, b);
            tbChitiet.SetBorder(TableBorderType.Bottom, b);
            tbChitiet.SetBorder(TableBorderType.Top, b);
            tbChitiet.SetBorder(TableBorderType.Left, b);
            tbChitiet.SetBorder(TableBorderType.Right, b);

            // insert dong subtotal
            var rowsub = tbChitiet.InsertRow();

            rowsub.Cells[1].Paragraphs[0].Append("Cộng (Subtotal)").Color(Color.Black).Font("Times New Roman").FontSize(10).Alignment = Alignment.right;
            rowsub.Cells[2].Paragraphs[0].Append(string.Format("{0:#,##0}", totalsotiennt)).Color(Color.Black).Font("Times New Roman").FontSize(10).Alignment = Alignment.right;
            rowsub.Cells[3].Paragraphs[0].Append(string.Format("{0:#,##0}", totaltienppv)).Color(Color.Black).Font("Times New Roman").FontSize(10).Alignment  = Alignment.right;
            rowsub.Cells[5].Paragraphs[0].Append(string.Format("{0:#,##0}", totaltienthue)).Color(Color.Black).Font("Times New Roman").FontSize(10).Alignment = Alignment.right;
            // insert dong Total
            var rowstotal = tbChitiet.InsertRow();

            rowstotal.Cells[1].Paragraphs[0].Append("Tổng cộng(Total)").Color(Color.Black).Font("Times New Roman").FontSize(10).Alignment = Alignment.right;
            rowstotal.Cells[2].Paragraphs[0].Append(string.Format("{0:#,##0}", total)).Color(Color.Black).Font("Times New Roman").FontSize(10).Alignment = Alignment.right;

            doc.InsertTable(tbChitiet);
            doc.InsertParagraph("Số tiền bằng chữ-Inwords: " + SoSangChu.DoiSoSangChu(Math.Round(total, 0).ToString())).Color(Color.Black).Font("Times New Roman").FontSize(11).Alignment = Alignment.left;

            MemoryStream stream = new MemoryStream();

            doc.SaveAs(stream);
            stream.Position = 0;
            //Download Word document in the browser

            return(File(stream, "application/msword", "hoadon_" + DateTime.Now + ".docx"));
        }
        public async Task <ActionResult> TaoHoadonVetour(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;
            //string account = user.accounthddt;// HttpContext.Session.GetString("accounthddt");
            //string pass = user.passwordhddt;// HttpContext.Session.GetString("passhddt");

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

            List <cthdvat> cthd        = _cthdvatRepository.ListChitietHoadon(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>" + i.sotien + "</ProdPrice>";
                InvData_xml += "<Total>" + doanhthu + "</Total>";  // Thành tiền chưa thuế vat
                InvData_xml += "<Extra1>" + 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>" + tienthuevat + "</VATAmount>"; // Tiền thuế
                InvData_xml += "<Amount>" + 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>" + 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>" + tcvat + "</VatAmount10>";            //Tổng tiền thuế của mức thuế 10% NUMBER(18,4)
            InvData_xml += "<TotalQuantity>" + tcppv + "</TotalQuantity>";        //Tổng tiền phí phục vụ NUMBER(38,4)
            InvData_xml += "<Total>" + tcsotien + "</Total>";                     //Cộng tiền hàng (Sub -total)* NUMBER(38,4)
            InvData_xml += "<VATRate>" + 10 + "</VATRate>";                       // Thuế GTGT* FLOAT
            InvData_xml += "<VATAmount>" + tcvat + "</VATAmount>";                //Tổng Tiền thuế GTGT* NUMBER(38,4)
            InvData_xml += "<Amount>" + (tcsotien + tcvat + tcppv) + "</Amount>"; // Tổng cộng tiền thanh toán(Grand total)* NUMBER(38,4)
            string a = SoSangChu.DoiSoSangChu((tcsotien + tcvat + tcppv).ToString());

            a = char.ToUpper(a[0]) + a.Substring(1);
            // InvData_xml += "<AmountInWords>" + SoSangChu.DoiSoSangChu((tcsotien + tcvat + tcppv).ToString()) + " đồng </AmountInWords>";//	<!--Số tiền viết bằng chữ* VARCHAR2(255 CHAR)-->";
            InvData_xml += "<AmountInWords>" + a + " đồ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.ngayct   = System.DateTime.Now;
                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: " + hd.user + " vào lúc: " + System.DateTime.Now;
                _hoadonRepository.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 Json(result);
            return(Redirect(HttpContext.Session.GetString("urlEditHoadon")));
        }