protected void grdNotas_PageIndexChanging(object sender, GridViewPageEventArgs e) { grdNotas.PageIndex = e.NewPageIndex; grdNotas.DataSource = Session["dwNotas"] as DataView; grdNotas.DataBind(); ScriptManager.RegisterStartupScript(this, GetType(), "SweetAlert", _navegarAteDivGrid, true); } protected void grdNotas_RowCommand(object sender, GridViewCommandEventArgs e) { List list = new List(); NotaBLL notaBLL = new NotaBLL(); Nota nota = new Nota(); int tipoNf = 0; string especieNf; DeParaEspecieNfBLL dpEspNfBLL = new DeParaEspecieNfBLL(); Int64 codNota; Int64 codCliente; string fileName; string caminho; try { if (rdbEntrada.Checked)//Entrada { tipoNf = 0; } else if (rdbSaida.Checked)//Saída { tipoNf = 1; } else if (rdbCTE.Checked)//CTE { tipoNf = 8; } else if (rdbCFe.Checked) { tipoNf = 10; } switch (e.CommandName) { case "Selecione": if (chkNotasEmitidasMyGeraArq.Checked) { //Se o uso já estiver autorizado ou denegado ou a nota for cancelada if (grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[11].Text.ToUpper().Contains("AUTORIZADO O USO") || grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[11].Text.ToUpper().Contains("USO DENEGADO") || grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[12].Text.ToUpper().Contains("S")) { nota.CodNota = Convert.ToInt64(grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[1].Text); nota.ProtocoloNFe.ChaveNFe = (grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[10].Text); string url = "DetalheNota.aspx?codNota=" + nota.CodNota + "&chave=" + nota.ProtocoloNFe.ChaveNFe; Server.Transfer(url); } else//Se for rejeição, tem que corrigir a nota e enviar { nota.CodNota = Convert.ToInt64(grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[1].Text); nota.ProtocoloNFe.ChaveNFe = (grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[10].Text); string url = "EmissorNFe.aspx?codNota=" + nota.CodNota + "&chave=" + nota.ProtocoloNFe.ChaveNFe + "&estorno=0"; //Response.Redirect(url); Server.Transfer(url); } } else { nota.CodNota = Convert.ToInt64(grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[1].Text); nota.ProtocoloNFe.ChaveNFe = (grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[10].Text); string url = "DetalheNota.aspx?codNota=" + nota.CodNota + "&chave=" + nota.ProtocoloNFe.ChaveNFe; Response.Redirect(url); Server.Transfer(url); } break; case "CartaCorrecao": if (ddlModeloNF.SelectedValue == "65") { ScriptManager.RegisterStartupScript(this, GetType(), "js", _navegarAteDivBotoes + "swal('Alerta','Carta de correção é exclusivo da NF-e (Modelo 55)', 'warning');", true); return; } Session["Grid"] = e; txtCartaCorrecao.Text = string.Empty; const string modalCartaCorrecao = @"$(document).ready(function() {$('#divModalCartaCorrecao').modal('show');});"; ScriptManager.RegisterStartupScript(this, GetType(), "divModalCartaCorrecao", _navegarAteDivBotoes + modalCartaCorrecao, true); break; case "EstornarNFE": if (chkNotasEmitidasMyGeraArq.Checked) { codNota = Convert.ToInt64(grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[1].Text); string chaveNFe = (grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[10].Text); string url = "EmissorNFe.aspx?codNota=" + codNota + "&chave=" + chaveNFe + "&estorno=1"; Server.Transfer(url); } break; case "Download": codNota = Convert.ToInt64(grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[1].Text); codCliente = Convert.ToInt64(((Usuario)Session["Usuario"]).CodCliente.ToString()); fileName = notaBLL.ConsultaFileName(codCliente, codNota); if (chkNotasEmitidasMyGeraArq.Checked) { if (grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[10].Text.Substring(20, 2) == "57") { caminho = Server.MapPath("Arquivos\\ARMAZENA_XML_EMISSORNFE\\" + ((Usuario)Session["Usuario"]).CodCliente + "\\" + ddlEmpresas.SelectedValue + "\\CTETRANSMITIDO\\") + fileName; } else { caminho = Server.MapPath("Arquivos\\ARMAZENA_XML_EMISSORNFE\\" + ((Usuario)Session["Usuario"]).CodCliente + "\\" + ddlEmpresas.SelectedValue + "\\NFETRANSMITIDA\\") + fileName; } } else { if (grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[10].Text.Substring(20, 2) == "57") { caminho = Server.MapPath("Arquivos\\ARMAZENA XML\\" + ((Usuario)Session["Usuario"]).CodCliente + "\\" + ddlEmpresas.SelectedValue + "\\CTE\\") + fileName; } else { caminho = Server.MapPath("Arquivos\\ARMAZENA XML\\" + ((Usuario)Session["Usuario"]).CodCliente + "\\" + ddlEmpresas.SelectedValue + "\\SAIDAENTRADA\\") + fileName; } } EventoNFEDAO eventoNFEDAO = new EventoNFEDAO(); List listaEventoNFE = eventoNFEDAO.Listar(codNota); string caminhoEventoNFE; if (chkNotasEmitidasMyGeraArq.Checked) { if (grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[10].Text.Substring(20, 2) == "57")//CTE { caminhoEventoNFE = Server.MapPath("Arquivos\\ARMAZENA_XML_EMISSORNFE\\" + ((Usuario)Session["Usuario"]).CodCliente + "\\" + ddlEmpresas.SelectedValue + "\\CTETRANSMITIDO\\"); } else { caminhoEventoNFE = Server.MapPath("Arquivos\\ARMAZENA_XML_EMISSORNFE\\" + ((Usuario)Session["Usuario"]).CodCliente + "\\" + ddlEmpresas.SelectedValue + "\\NFETRANSMITIDA\\"); } } else { if (grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[10].Text.Substring(20, 2) == "57")//CTE { caminhoEventoNFE = Server.MapPath("Arquivos\\ARMAZENA XML\\" + ((Usuario)Session["Usuario"]).CodCliente + "\\" + ddlEmpresas.SelectedValue + "\\CTE\\"); } else { caminhoEventoNFE = Server.MapPath("Arquivos\\ARMAZENA XML\\" + ((Usuario)Session["Usuario"]).CodCliente + "\\" + ddlEmpresas.SelectedValue + "\\SAIDAENTRADA\\"); } } if (listaEventoNFE.Count > 0) { foreach (EventoNFE eventoNfe in listaEventoNFE) { if (File.Exists(caminhoEventoNFE + eventoNfe.NomeArquivo)) { if (!list.Contains(new MyFile { FileName = eventoNfe.NomeArquivo, FilePath = caminhoEventoNFE })) { list.Add(new MyFile { FileName = eventoNfe.NomeArquivo, FilePath = caminhoEventoNFE + eventoNfe.NomeArquivo }); } } } if (File.Exists(caminho)) { list.Add(new MyFile { FileName = fileName, FilePath = caminho }); } else { ScriptManager.RegisterStartupScript(this, GetType(), "SweetAlert", _navegarAteDivBotoes + "swal('Alerta','Não há xml desta nota!', 'warning');", true); } if (list.Count > 0) { string nomeArquivo = "Notas-" + DateTime.Now.ToString("ddMMyyyy") + ".zip"; Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename= " + nomeArquivo); Response.CacheControl = "Private"; byte[] buffer = new byte[4096]; ZipOutputStream zipOutputStream = new ZipOutputStream(Response.OutputStream); zipOutputStream.SetLevel(3); //0-9, 9 being the highest level of compression foreach (MyFile fileNam in list) { Stream fs = File.OpenRead(fileNam.FilePath); // or any suitable inputstream ZipEntry entry = new ZipEntry(ZipEntry.CleanName(fileNam.FileName)); entry.Size = fs.Length; zipOutputStream.PutNextEntry(entry); int count = fs.Read(buffer, 0, buffer.Length); while (count > 0) { zipOutputStream.Write(buffer, 0, count); count = fs.Read(buffer, 0, buffer.Length); if (!Response.IsClientConnected) { break; } Response.Flush(); } fs.Close(); } zipOutputStream.Close(); Response.Flush(); Response.Clear(); Response.ClearContent(); Response.End(); } } else { if (File.Exists(caminho)) { DownloadFile(fileName, caminho, Convert.ToInt64(ddlEmpresas.SelectedValue)); } else { ScriptManager.RegisterStartupScript(this, GetType(), "SweetAlert", _navegarAteDivBotoes + "swal('Alerta','Não há xml desta nota!', 'warning');", true); } } break; case "Gerar DANFE": if (!grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[11].Text.ToUpper().Contains("AUTORIZADO O USO") && grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[11].Text != " " && grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[11].Text != string.Empty) { throw new Exception("Não é possível gerar o DANFE de nota cancelada,com rejeição ou que não foi transmitida ainda!"); } if (grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[12].Text.ToUpper().Contains("S") || grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[11].Text.ToUpper().Contains("USO DENEGADO")) { throw new Exception("Não é possível gerar o DANFE de nota cancelada,com rejeição ou que não foi transmitida ainda!"); } codNota = Convert.ToInt64(grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[1].Text); codCliente = Convert.ToInt64(((Usuario)Session["Usuario"]).CodCliente.ToString()); string fileNameXML = notaBLL.ConsultaFileName(codCliente, codNota); string fileNamePDF = grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[10].Text + ".pdf"; if (chkNotasEmitidasMyGeraArq.Checked) { if (grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[10].Text.Substring(20, 2) == "57")//CTE { caminho = Server.MapPath("Arquivos\\ARMAZENA_XML_EMISSORNFE\\" + ((Usuario)Session["Usuario"]).CodCliente + "\\" + ddlEmpresas.SelectedValue + "\\CTETRANSMITIDO\\") + fileNameXML; } else { caminho = Server.MapPath("Arquivos\\ARMAZENA_XML_EMISSORNFE\\" + ((Usuario)Session["Usuario"]).CodCliente + "\\" + ddlEmpresas.SelectedValue + "\\NFETRANSMITIDA\\") + fileNameXML; } } else { if (grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[10].Text.Substring(20, 2) == "57")//CTE { caminho = Server.MapPath("Arquivos\\ARMAZENA XML\\" + ((Usuario)Session["Usuario"]).CodCliente + "\\" + ddlEmpresas.SelectedValue + "\\CTE\\") + fileNameXML; } else { caminho = Server.MapPath("Arquivos\\ARMAZENA XML\\" + ((Usuario)Session["Usuario"]).CodCliente + "\\" + ddlEmpresas.SelectedValue + "\\SAIDAENTRADA\\") + fileNameXML; } } if (File.Exists(caminho)) { if (!Directory.Exists(Server.MapPath("Arquivos\\PDF\\" + ((Usuario)Session["Usuario"]).CodCliente + "\\" + ((Usuario)Session["Usuario"]).CodUsuario))) { Directory.CreateDirectory(Server.MapPath("Arquivos\\PDF\\" + ((Usuario)Session["Usuario"]).CodCliente + "\\" + ((Usuario)Session["Usuario"]).CodUsuario)); } Geral.DeleteFiles("Arquivos\\PDF\\" + ((Usuario)Session["Usuario"]).CodCliente + "\\" + ((Usuario)Session["Usuario"]).CodUsuario); StreamReader srXML = File.OpenText(caminho); string XML = srXML.ReadToEnd(); srXML.Close(); string msgResultado = string.Empty; Util NFeUtil = new Util(); CTe_Util.Util CTeUtil = new CTe_Util.Util(); string modelonf = grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[10].Text.Substring(20, 2); switch (modelonf) { case "57": CTeUtil.geraPdfDACTE(XML, string.Empty, "S", "S", "[ARQUIVO=" + fileNamePDF + "][PASTA=" + Server.MapPath("Arquivos\\PDF\\" + ((Usuario)Session["Usuario"]).CodCliente + "\\" + ((Usuario)Session["Usuario"]).CodUsuario + "\\") + "][RODAPE=Powered by NFe_Util © 2008-2016 www.flexdocs.com.br][OBSFISCO][MOSTRADADOSTOMADOR]", out msgResultado); if (!msgResultado.Contains("7904 -"))//: A DLL não oferece suporte para geração do modal Aéreo Desejado { DownloadFilePDF(fileNamePDF); } else { ScriptManager.RegisterStartupScript(this, GetType(), "SweetAlert", _navegarAteDivBotoes + "swal('Alerta','Não é possível a geração do DACTE Modal Aéreo Atualmente!', 'warning');", true); } break; case "55": NFeUtil.geraPdfDANFE(XML, string.Empty, "S", "S", "S", string.Empty, "L", "[ARQUIVO=" + fileNamePDF + "][PASTA=" + Server.MapPath("Arquivos\\PDF\\" + ((Usuario)Session["Usuario"]).CodCliente + "\\" + ((Usuario)Session["Usuario"]).CodUsuario + "\\") + "][RODAPE=Powered by NFe_Util © 2008-2016 www.flexdocs.com.br]", out msgResultado); if (!msgResultado.Contains("7904 -"))//: A DLL não oferece suporte para geração do modal Aéreo Desejado { DownloadFilePDF(fileNamePDF); } else { ScriptManager.RegisterStartupScript(this, GetType(), "SweetAlert", _navegarAteDivBotoes + "swal('Alerta','Não é possível a geração do DACTE Modal Aéreo Atualmente!', 'warning');", true); } break; case "65": //Se for NFC-e eu envio para a página que visualiza a danfe NFC-e ScriptManager.RegisterStartupScript(this, GetType(), "js", _navegarAteDivBotoes + "window.open('ImpressaoDanfeNFce.aspx?cod=" + codNota + "', '_blank');", true); break; } } else { ScriptManager.RegisterStartupScript(this, GetType(), "SweetAlert", _navegarAteDivBotoes + "swal('Alerta','Não há xml desta nota!', 'warning');", true); } break; case "Duplicar": const bool notaDuplicada = true; codNota = Convert.ToInt64(grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[1].Text); codCliente = Convert.ToInt64(((Usuario)Session["Usuario"]).CodCliente.ToString()); long codEmpresa = Convert.ToInt64(ddlEmpresas.SelectedValue); string fileDirectory; string[] fileNameDup = { string.Empty }; fileNameDup[0] = notaBLL.ConsultaFileName(codCliente, codNota); if (fileNameDup[0].Contains("NFDUPLICADA"))//HSM: Se o nome do arquivo no banco estiver como nota Duplicada, não duplicamos novamente { ScriptManager.RegisterStartupScript(this, GetType(), "SweetAlert", _navegarAteDivBotoes + "swal('Alerta','Essa nota já foi duplicada!', 'warning');", true); } else { //HSM: Se a nota não estiver como o Nome de NF duplicada no banco, verificamos se não tem outra como o mesmo nome,que seja a nota duplicada, se não tiver uma duplicada no banco, então podemos duplica-la if (notaBLL.ConsultaNomeArquivo(codCliente, fileNameDup[0].Replace(".xml", "").Replace(".XML", "").ToUpper() + "NFDUPLICADA.XML")) { ScriptManager.RegisterStartupScript(this, GetType(), "SweetAlert", _navegarAteDivBotoes + "swal('Alerta','Essa nota já foi duplicada!', 'warning');", true); } else { if (grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[10].Text.Substring(20, 2) == "57")//CTE { fileDirectory = Server.MapPath("Arquivos\\ARMAZENA XML\\" + ((Usuario)Session["Usuario"]).CodCliente + "\\" + codEmpresa + "\\CTE\\"); } else { fileDirectory = Server.MapPath("Arquivos\\ARMAZENA XML\\" + ((Usuario)Session["Usuario"]).CodCliente + "\\" + codEmpresa + "\\SAIDAENTRADA\\"); } if (File.Exists(fileDirectory + fileNameDup[0]))//HSM: Se o xml existe, duplicamos ele { File.Copy(fileDirectory + fileNameDup[0], fileDirectory + fileNameDup[0].Replace(".xml", "").Replace(".XML", "") + "NFDUPLICADA.xml", true); especieNf = dpEspNfBLL.GetEspecie(codCliente, tipoNf, false); fileNameDup[0] = fileNameDup[0].Replace(".xml", "").Replace(".XML", "") + "NFDUPLICADA.xml"; NotaDAOLeitura.ReadXML(fileDirectory, fileNameDup, codCliente, codEmpresa, Convert.ToInt64(((Usuario)Session["Usuario"]).CodUsuario), tipoNf, _notasNEntrada, _notasNSaida, _notasNEmpresa, _notasSemItens, false, _notasComItensSemCfop, _emitenteSemCnpj, _notasSemNomeEmit, _notasConvertidas, _produtosConvertidos, especieNf, notaDuplicada, true, _todosErros, _chaves, false); ScriptManager.RegisterStartupScript(this, GetType(), "SweetAlert", _navegarAteDivBotoes + "swal('Sucesso','Nota Duplicada com sucesso!', 'success');", true); CarregaGrdNotas(string.Empty, string.Empty); } else { ScriptManager.RegisterStartupScript(this, GetType(), "SweetAlert", _navegarAteDivBotoes + "swal('Alerta','Não há xml desta nota!', 'warning');", true); } } } break; case "Cancelar": if (grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[12].Text.ToUpper().Contains("S")) { ScriptManager.RegisterStartupScript(this, GetType(), "SweetAlert", _navegarAteDivBotoes + "swal('OK','A nota já está cancelada!', 'warning');", true); return; } if (!grdNotas.Rows[Convert.ToInt16(e.CommandArgument)].Cells[11].Text.ToUpper().Contains("AUTORIZADO O USO"))//Se não contiver autorização de uso,não pode se cancelada { ScriptManager.RegisterStartupScript(this, GetType(), "SweetAlert", _navegarAteDivBotoes + "swal('OK','A nota Não foi autorizada ainda, por isso não pode ser cancelada!', 'warning');", true); return; } Session["Grid"] = e; txtJustificativa.Text = string.Empty; const string modalJustificativa = @"$(document).ready(function() {$('#divModalJustificativa').modal('show');});"; ScriptManager.RegisterStartupScript(this, GetType(), "divModalJustificativa", _navegarAteDivBotoes + modalJustificativa, true); break; } } catch (Exception ex) { ScriptManager.RegisterStartupScript(this, GetType(), "SweetAlert", _navegarAteDivBotoes + "swal('Erro','" + Geral.RemoveCaracteresExcessao(ex.Message) + "', 'error');", true); } } protected void grdNotas_RowDataBound(object sender, GridViewRowEventArgs e) { try { if (e.Row.RowType == DataControlRowType.Header) { CheckBox chk = e.Row.FindControl("chkNotasHeader") as CheckBox; if (chk != null) { chk.Attributes.Add("onclick", "$(this).closest('table').find('td input:checkbox').prop('checked', this.checked);"); } } if (e.Row.RowType == DataControlRowType.DataRow) { switch (e.Row.Cells[12].Text) //12-Nota cancelada? { case "1": e.Row.Cells[12].Text = "S"; for (int i = 0; i < e.Row.Cells.Count; i++) { if (i != 13 && i != 14 && i != 15 && i != 16) { e.Row.Cells[i].ForeColor = Color.Red; } } break; default: e.Row.Cells[12].Text = "N"; //Nota cancelada break; } } } catch (Exception ex) { ScriptManager.RegisterStartupScript(this, GetType(), "SweetAlert", _navegarAteDivBotoes + "swal('Erro','" + Geral.RemoveCaracteresExcessao(ex.Message) + "', 'error');", true); } } protected void grdNotas_Sorting(object sender, GridViewSortEventArgs e) { string sortingDirection; if (direcaoOrdenacao == SortDirection.Ascending) { direcaoOrdenacao = SortDirection.Descending; sortingDirection = "Desc"; } else { direcaoOrdenacao = SortDirection.Ascending; sortingDirection = "Asc"; } DataView sortedView = Session["dwNotas"] as DataView; if (sortedView != null) { sortedView.Sort = e.SortExpression + " " + sortingDirection; Session["dwNotas"] = sortedView; grdNotas.DataSource = sortedView; grdNotas.PageSize = 50; grdNotas.DataBind(); } ScriptManager.RegisterStartupScript(this, GetType(), "SweetAlert", _navegarAteDivGrid, true); }