Ejemplo n.º 1
0
        private void btnGerarXml_Click(object sender, EventArgs e)
        {
            try
            {
                for (int i = 0; i < dgvNF.RowCount; i++)
                {
                    if (dgvNF["ASSINANF", i].Value != null)
                    {
                        if (dgvNF["ASSINANF", i].Value.ToString().Equals("True"))
                        {
                            string sRetorno = VerificaCampoReciboPreenchido(belStatic.codEmpresaNFe, dgvNF["CD_NFSEQ", i].Value.ToString());
                            if (sRetorno == "denegada")
                            {
                                throw new Exception("A Nota de Sequencia = " + dgvNF["CD_NFSEQ", i].Value.ToString() + " foi Denegada pelo Sefaz e não podera ser excluída, cancelada e nem alterada.");
                            }
                            else if (sRetorno != "")
                            {
                                throw new Exception("A Nota de Sequencia = " + dgvNF["CD_NFSEQ", i].Value.ToString() + " Já tem um retorno Salvo no Banco de Dados, tente Buscar Retorno");
                            }
                        }
                    }
                }

                #region Verificações
                sslStatusEnvio.Text = "Gerando e Assinando XML...";
                sFormaEmiNFe = "";

                if (belStatic.bModoSCAN && ((belStatic.iStatusAtualSistema == 3)))
                {
                    sFormaEmiNFe = "3";
                }
                else if (belStatic.bModoContingencia && (belStatic.iStatusAtualSistema == 2))
                {
                    sFormaEmiNFe = "2";
                }
                else
                {
                    sFormaEmiNFe = "1";
                }

                sFormDanfe = "";
                if (cbxFormDanfe.SelectedIndex == 0)
                {
                    sFormDanfe = "1";
                }
                else
                {
                    sFormDanfe = "2";
                }
                string sNfCancelada = "";
                #endregion

                #region Seleciona Notas Selecionadas na Grid
                bool bEnviaContingencia = false;
                GeraXMLExp Export = new GeraXMLExp(belStatic.iStatusAtualSistema);
                for (int i = 0; i < dgvNF.RowCount; i++)
                {
                    if (((dgvNF["ASSINANF", i].Value != null) && (dgvNF["ASSINANF", i].Value.ToString().Equals("True")))
                                && ((dgvNF["CANCELADA", i].Value == null) || (dgvNF["CANCELADA", i].Value.ToString() == "0"))
                                && (dgvNF["ST_NFE", i].Value.ToString().Equals("0")))
                    {
                        if ((dgvNF["st_contingencia", i].Value.ToString().Equals("S"))
                            && (dgvNF["ST_NFE", i].Value.ToString().Equals("0"))
                            && (dgvNF["CD_NOTAFIS", i].Value.ToString() != ""))
                        {
                            if (sNotas.Count > 0)
                            {
                                throw new Exception("Obs: As Notas Pendentes de Envio devem ser Enviadas Uma de cada vez." + Environment.NewLine + Environment.NewLine);
                            }
                            else
                            {
                                bEnviaContingencia = true;
                            }
                        }

                        sNotas.Add((string)dgvNF["CD_NFSEQ", i].Value);
                    }
                    if ((dgvNF["CANCELADA", i].Value != null) && (dgvNF["CANCELADA", i].Value.ToString() == "1"))
                    {
                        sNfCancelada += "Nota Fiscal " + dgvNF["CD_NOTAFIS", i].Value.ToString() + " - Esta Cancelada e não é Permitido o Reenvio da mesma Nota!" + Environment.NewLine + Environment.NewLine;
                    }
                }

                Export.sExecao = string.Empty;

                if (sNotas.Count == 0)
                {
                    KryptonMessageBox.Show("Nenhuma nota Valida foi Selecionada!", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    if (sNfCancelada != "")
                    {
                        KryptonMessageBox.Show(sNfCancelada, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    return;
                }

                #endregion
                //verifica no banco se as sequencias são existentes.
                belBusRetFazenda objbusretfazenda = new belBusRetFazenda();
                if (ValidaSeqNoBanco())
                {
                    if (bEnviaContingencia == false)
                    {

                        #region Visualiza Nota
                        Export.NFe(belStatic.codEmpresaNFe, sNotas, Export.NomeArqNFe(belStatic.codEmpresaNFe), sFormaEmiNFe, sFormDanfe, cd_ufnor, cert, belStatic.bModoSCAN, belStatic.iSerieSCAN, sFormaEmiNFe, version);
                        frmVisualizaNotasNfe objFrm = new frmVisualizaNotasNfe(Export.lTotNota, belStatic.codEmpresaNFe);
                        objFrm.ShowDialog();
                        if (objFrm.Cancel == true)
                        {
                            _msgIcon = MessageBoxIcon.Information;
                            throw new Exception("Envio da(s) Nota(s) Cancelado");
                        }

                        Export.lTotNota = objFrm.lObjTotNotasFinal;
                        #endregion

                        #region Envia Nfe Normal
                        // Gera a Estrutura do XML
                        Export.geraArquivoNFE(sNotas, cert, belStatic.codEmpresaNFe, Export.NomeArqNFe(belStatic.codEmpresaNFe));
                        sslStatusEnvio.Text = "Enviando o Lote a Ministério da Fazenda...";
                        belNfeRecepcao y = new belNfeRecepcao(Export.sXmlfull, "2.00", cert, Uf_Empresa, belStatic.bModoSCAN, belStatic.iSerieSCAN);
                        if (y.Recibo.ToUpper().Contains("VERSAO"))
                        {
                            throw new Exception("Ocorreu uma exceção com o webservice de Recepção. Favor verificar se os serviços estão estáveis.");
                        }


                        for (int i = 0; i < sNotas.Count; i++)
                        {
                            //Grava o número do recibo nas notas que foram enviadas a Fazenda
                            gravaRecibo(y.Recibo, belStatic.codEmpresaNFe, sNotas[i]);

                            sslStatusEnvio.Text = "Gravando recibo do Lote";
                        }
                        sslStatusEnvio.Text = "Buscando retorno do Ministério da Fazenda";

                        objbusretfazenda = new belBusRetFazenda(sNotas, Export.nfes, y.Recibo, cert, Uf_Empresa);
                        GeraXml.NFe.frmBuscaRetorno objfrmAvisoRet = new GeraXml.NFe.frmBuscaRetorno(objbusretfazenda, GeraXml.NFe.frmBuscaRetorno.tipoBusca.ENVIO);
                        objfrmAvisoRet.ShowDialog();

                        //Se nenhuma nota foi autorizada entao, ele nem continua para não dar erro nas proximas rotinas.
                        if (objbusretfazenda.Nfeautorizadas.Count == 0)
                        {
                            sslStatusEnvio.Text = "Nenhuma Nota Autorizada ...";
                            throw new Exception("Nenhuma nota do Lote enviado a Fazenda foi Autorizada" + Environment.NewLine + objbusretfazenda.Loteres);
                        }

                        sMesageErro = Export.sExecao;
                        StringBuilder sSql = new StringBuilder();
                        foreach (string sNota in objbusretfazenda.Nfeautorizadas)
                        {
                            if (sSql.ToString().Length > 0)
                            {
                                sSql.Append(string.Format(", '{0}'", sNota));
                            }
                            else
                            {
                                sSql.Append(string.Format("'{0}'", sNota));
                            }
                        }
                        /// Update para mudar o estado da nota dizendo que a nota foi autorizada ou não.
                        sSql.Insert(0, "update nf set st_nfe = 'S' Where cd_nfseq in (");
                        sSql.Append(")");
                        sSql.Append("and ");
                        sSql.Append("cd_empresa = '");
                        sSql.Append(belStatic.codEmpresaNFe);
                        sSql.Append("'");


                        using (FbCommand cmdUpdate = new FbCommand(sSql.ToString(), cx.get_Conexao()))
                        {
                            cx.Open_Conexao();
                            cmdUpdate.ExecuteNonQuery();
                            cx.Close_Conexao();
                        }
                        for (int i = 0; i < dgvNF.RowCount; i++)
                        {
                            if (dgvNF["ASSINANF", i].Value != null)
                            {
                                if (dgvNF["ASSINANF", i].Value.ToString().Equals("True"))
                                {
                                    dgvNF["ST_NFE", i].Value = true;
                                }
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        #region Envio de Notas de Contingencia Pendentes !!

                        XmlDocument xml = new XmlDocument();
                        string sQuery = "SELECT NF.cd_chavenfe from nf " +
                                        "Where nf.cd_empresa = '" + belStatic.codEmpresaNFe +
                                        "' and nf.cd_nfseq = '" + sNotas[0].ToString() + "'";
                        string sID = string.Empty;

                        using (FbCommand cmd = new FbCommand(sQuery, cx.get_Conexao()))
                        {
                            cx.Open_Conexao();
                            sID = cmd.ExecuteScalar().ToString();
                            cx.Close_Conexao();
                        }
                        DirectoryInfo dinfo = new DirectoryInfo(belStaticPastas.CONTINGENCIA); ;
                        FileInfo[] finfo = dinfo.GetFiles();
                        foreach (FileInfo item in finfo)
                        {
                            if (Path.GetExtension(item.FullName).ToUpper().Equals(".XML"))
                            {
                                if (item.Name.ToString().Length == 26)
                                {
                                    xml.Load(@item.FullName);
                                    if (xml.GetElementsByTagName("infNFe")[0].Attributes["Id"].Value.ToString().Replace("NFe", "").Equals(sID))
                                    {
                                        Export.sXmlfull = xml.InnerXml.ToString();
                                        string sPathDest = belStaticPastas.ENVIO + "\\" + item.Name;
                                        string sPathOrigem = belStaticPastas.CONTINGENCIA + "\\" + item.Name;
                                        if (File.Exists(sPathDest))
                                        {
                                            File.Delete(sPathDest);
                                        }
                                        File.Copy(sPathOrigem, sPathDest);
                                    }
                                }
                                else if (item.Name.ToString().Length == 52)
                                {
                                    xml.Load(@item.FullName);
                                    if (xml.GetElementsByTagName("infNFe")[0].Attributes["Id"].Value.ToString().Replace("-nfe", "").Replace("NFe", "").Equals(sID))
                                    {
                                        Export.nfes.Add(xml.InnerXml.ToString());
                                        string sPathDest = belStaticPastas.ENVIO + "\\" + item.Name.Substring(2, 4) + "\\" + item.Name; //OS_25024
                                        string sPathOrigem = belStaticPastas.CONTINGENCIA + "\\" + item.Name;
                                        if (File.Exists(sPathDest))
                                        {
                                            File.Delete(sPathDest);
                                        }
                                        File.Copy(sPathOrigem, sPathDest);
                                    }
                                }
                                if ((Export.nfes.Count > 0) && (Export.sXmlfull != null))
                                {
                                    belNfeRecepcao y = new belNfeRecepcao(Export.sXmlfull, "2.00", cert, Uf_Empresa, belStatic.bModoSCAN, belStatic.iSerieSCAN);
                                    for (int i = 0; i < sNotas.Count; i++)
                                    {
                                        //Grava o número do recibo nas notas que foram enviadas a Fazenda
                                        gravaRecibo(y.Recibo, belStatic.codEmpresaNFe, sNotas[i]);
                                        sslStatusEnvio.Text = "Gravando recibo do Lote";
                                    }

                                    objbusretfazenda = new belBusRetFazenda(sNotas, Export.nfes, y.Recibo, cert, Uf_Empresa);
                                    GeraXml.NFe.frmBuscaRetorno objfrmAvisoRet = new GeraXml.NFe.frmBuscaRetorno(objbusretfazenda, GeraXml.NFe.frmBuscaRetorno.tipoBusca.ENVIO);
                                    objfrmAvisoRet.ShowDialog();

                                    //Se nenhuma nota foi autorizada entao, ele nem continua para não dar erro nas proximas rotinas.
                                    if (objbusretfazenda.Nfeautorizadas.Count == 0)
                                    {
                                        sslStatusEnvio.Text = "Nenhuma Nota Autorizada ...";
                                        throw new Exception("Nenhuma nota do Lote enviado a Fazenda foi Autorizada" + Environment.NewLine + objbusretfazenda.Loteres);
                                    }

                                    sMesageErro = Export.sExecao;
                                    StringBuilder sSql = new StringBuilder();
                                    foreach (string sNota in objbusretfazenda.Nfeautorizadas)
                                    {
                                        if (sSql.ToString().Length > 0)
                                        {
                                            sSql.Append(string.Format(", '{0}'", sNota));
                                        }
                                        else
                                        {
                                            sSql.Append(string.Format("'{0}'", sNota));
                                        }
                                    }
                                    /// Update para mudar o estado da nota dizendo que a nota foi autorizada ou não.
                                    sSql.Insert(0, "update nf set st_nfe = 'S' Where cd_nfseq in (");
                                    sSql.Append(")");
                                    sSql.Append("and ");
                                    sSql.Append("cd_empresa = '");
                                    sSql.Append(belStatic.codEmpresaNFe);
                                    sSql.Append("'");

                                    using (FbCommand cmdUpdate = new FbCommand(sSql.ToString(), cx.get_Conexao()))
                                    {
                                        cx.Open_Conexao();
                                        cmdUpdate.ExecuteNonQuery();
                                        cx.Close_Conexao();
                                    }
                                    for (int i = 0; i < dgvNF.RowCount; i++)
                                    {
                                        if (dgvNF["ASSINANF", i].Value != null)
                                        {
                                            if (dgvNF["ASSINANF", i].Value.ToString().Equals("True"))
                                            {
                                                dgvNF.Rows[i].DefaultCellStyle.BackColor = Color.Aquamarine;
                                                dgvNF["ST_NFE", i].Value = true;
                                            }
                                        }
                                    }
                                    VerificaNotasPendentesEnvio();
                                    break;
                                }
                            }
                        }

                        #endregion
                    }
                    sslStatusEnvio.Text = "Arquivos Gerados...";
                    KryptonMessageBox.Show("Arquivo Gerado" + Environment.NewLine + objbusretfazenda.Loteres);
                    sslStatusEnvio.Text = "";
                    for (int i = 0; i < dgvNF.RowCount; i++)
                    {
                        foreach (var item in objbusretfazenda.Nfeautorizadas) //Danner  - o.s. 23851 - 21/11/2009
                        {
                            if (dgvNF["cd_nfseq", i].Value.ToString() == item) //Danner - o.s. 23851 - 19/11/2009
                            {
                                if (dgvNF["ASSINANF", i].Value != null)
                                {
                                    dgvNF["ST_NFE", i].Value = true;
                                }
                            }
                        }
                    }
                }
                else
                {
                    PopulaDataGridView();
                }
            }

            catch (Exception ex)
            {
                KryptonMessageBox.Show(ex.Message + Environment.NewLine + "XML não Foi gerado com Sucesso!!!", "A V I S O", MessageBoxButtons.OK, MessageBoxIcon.Information);
                _msgIcon = MessageBoxIcon.Error;
                PopulaDataGridView();
            }
            finally
            {
                cx.Close_Conexao();
                sNotas.Clear();
            }
        }
Ejemplo n.º 2
0
        private void btnGerarContingencia_Click(object sender, EventArgs e)
        {
            try
            {
                for (int i = 0; i < dgvNF.RowCount; i++)
                {
                    if (dgvNF["ASSINANF", i].Value != null)
                    {
                        if (dgvNF["ASSINANF", i].Value.ToString().Equals("True"))
                        {
                            string sRetorno = VerificaCampoReciboPreenchido(belStatic.codEmpresaNFe, dgvNF["CD_NFSEQ", i].Value.ToString());
                            if (sRetorno == "denegada")
                            {
                                throw new Exception("A Nota de Sequencia = " + dgvNF["CD_NFSEQ", i].Value.ToString() + " foi Denegada pelo Sefaz e não podera ser excluída, cancelada e nem alterada.");
                            }
                            else
                            {
                                throw new Exception("A Nota de Sequencia = " + dgvNF["CD_NFSEQ", i].Value.ToString() + " Já tem um retorno Salvo no Banco de Dados, tente Buscar Retorno");
                            }
                        }
                    }
                }

                sslStatusEnvio.Text = "Acessando Banco de Dados ...";


                sFormaEmiNFe = "";

                if (belStatic.bModoSCAN && ((belStatic.iStatusAtualSistema == 3)))
                {
                    sFormaEmiNFe = "3";
                }
                else if (belStatic.bModoContingencia && (belStatic.iStatusAtualSistema == 2))
                {
                    sFormaEmiNFe = "2";
                }
                else
                {
                    sFormaEmiNFe = "1";
                }

                sFormDanfe = "";
                if (cbxFormDanfe.SelectedIndex == 0)
                {
                    sFormDanfe = "1";
                }
                else
                {
                    sFormDanfe = "2";
                }
                string sNfCancelada = "";
                GeraXMLExp Export = new GeraXMLExp(belStatic.iStatusAtualSistema);

                for (int i = 0; i < dgvNF.RowCount; i++)
                {
                    if (((dgvNF["ASSINANF", i].Value != null) && (dgvNF["ASSINANF", i].Value.ToString().Equals("True"))) && ((dgvNF["CANCELADA", i].Value == null) || (dgvNF["CANCELADA", i].Value.ToString() == "0"))) //Danner - o.s. SEM - 17/12/2009
                    {
                        //Verifico se a Nota Já foi Enviada em Modo de Contingencia
                        if ((dgvNF["st_contingencia", i].Value.ToString().Equals("S"))
                                   && (dgvNF["ST_NFE", i].Value.ToString().Equals("0"))
                                   && (dgvNF["CD_NOTAFIS", i].Value.ToString() != ""))
                        {
                            KryptonMessageBox.Show(null, "Nfe já Gerada em Modo de Contingência - Seq: " + dgvNF["CD_NOTAFIS", i].Value.ToString(), "A V I S O", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            break;
                        }
                        else
                        {
                            sNotas.Add((string)dgvNF["CD_NFSEQ", i].Value);
                        }
                    }
                    if ((dgvNF["CANCELADA", i].Value != null) && (dgvNF["CANCELADA", i].Value.ToString() == "1"))
                    {
                        sNfCancelada += "Nota Fiscal " + dgvNF["CD_NOTAFIS", i].Value.ToString() + " - Esta Cancelada e não é Permitido o Reenvio da mesma Nota!" + Environment.NewLine + Environment.NewLine;
                    }
                }
                Export.sExecao = string.Empty;

                if (sNotas.Count == 0)
                {
                    KryptonMessageBox.Show("Nenhuma nota Valida foi Selecionada!", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    if (sNfCancelada != "")
                    {
                        KryptonMessageBox.Show(sNfCancelada, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    return;
                }
                else if (sNotas.Count > 1)
                {
                    throw new Exception("Só é Possível Enviar uma Nota de Cada vez em Modo de Contingência");
                }
                //verifica no banco se as sequencias são existentes.
                if (ValidaSeqNoBanco())
                {
                    Export.NFe(belStatic.codEmpresaNFe, sNotas, Export.NomeArqNFe(belStatic.codEmpresaNFe), sFormaEmiNFe, sFormDanfe, cd_ufnor, cert, belStatic.bModoSCAN, belStatic.iSerieSCAN, sFormaEmiNFe, version);

                    frmVisualizaNotasNfe objFrm = new frmVisualizaNotasNfe(Export.lTotNota, belStatic.codEmpresaNFe);
                    objFrm.ShowDialog();
                    if (objFrm.Cancel == true)
                    {
                        sNotas.Clear();
                        _msgIcon = MessageBoxIcon.Information;
                        PopulaDataGridView();
                        throw new Exception("Envio da(s) Nota(s) Cancelado");
                    }
                    sslStatusEnvio.Text = "Gerando XML de Contingência ...";

                    Export.lTotNota = objFrm.lObjTotNotasFinal;

                    // Gera a Estrutura do XML
                    Export.geraArquivoNFE(sNotas, cert, belStatic.codEmpresaNFe, Export.NomeArqNFe(belStatic.codEmpresaNFe));
                    sslStatusEnvio.Text = "Arquivos Gerados...";
                    string sNotasGeradas = "Sequencia(as) de Nota(as) Gerada(as)  ";
                    foreach (string item in sNotas)
                    {
                        sNotasGeradas += "- " + item.ToString();
                    }
                    for (int i = 0; i < objFrm.lObjTotNotasFinal.Count; i++)
                    {
                        belIde objbelIde = objFrm.lObjTotNotasFinal[i][0] as belIde;

                        string sSqlAtualizaNF = "update NF set st_contingencia = '" + "S" +
                                         "' where cd_empresa = '" + belStatic.codEmpresaNFe +
                                         "' and cd_nfseq = '" + objbelIde.Cnf.Substring(2, 6) + "'";

                        using (FbCommand fbc = new FbCommand(sSqlAtualizaNF, cx.get_Conexao()))
                        {
                            cx.Open_Conexao();
                            fbc.ExecuteNonQuery();
                            cx.Close_Conexao();
                        }
                    }
                    KryptonMessageBox.Show(null, Environment.NewLine + sNotasGeradas, "I M P O R T A N T E", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    sslStatusEnvio.Text = "";
                    PopulaDataGridView();
                    sNotas.Clear();
                }
                else
                {
                    PopulaDataGridViewPendenciaContingencia();
                }
            }
            catch (Exception ex)
            {
                sNotas.Clear();
                new HLPexception(ex.Message, ex);
            }
            finally
            {
                cx.Close_Conexao();
            }
        }