Esempio n. 1
0
        private string CadastraCliFor(string psDoc)
        {
            string scdClifor = string.Empty;

            try
            {
                scdClifor = BuscaValorChavePrimaria("CLIFOR", 7, "cd_clifor", "Clifor", "");

                string sPEssoaj = (PessoaJuridica() == true ? "S" : "N");
                StringBuilder sInsert = new StringBuilder();
                sInsert.Append("Insert into ");
                sInsert.Append("Clifor (");
                sInsert.Append("cd_clifor, ");
                sInsert.Append("cd_alter, ");
                sInsert.Append("nm_clifor, ");
                sInsert.Append("nm_guerra, ");
                sInsert.Append("ds_endnor, ");
                sInsert.Append("nr_endnor, ");
                sInsert.Append("nm_bairronor, ");
                sInsert.Append("nm_cidnor, ");
                sInsert.Append("cd_ufnor, ");
                sInsert.Append("cd_cepnor, ");
                sInsert.Append("cd_fonenor, ");
                sInsert.Append("cd_catego, ");
                sInsert.Append("st_pessoaj, ");

                if (sPEssoaj == "S")
                {
                    sInsert.Append("cd_cgc, ");
                }
                else
                {
                    sInsert.Append("cd_cpf, ");
                }

                sInsert.Append("cd_insest, ");
                sInsert.Append("st_zfmalc ");
                sInsert.Append(") ");
                sInsert.Append("Values ('");
                sInsert.Append(scdClifor);
                sInsert.Append("', '");
                GeraXMLExp objGerarXMLExp = new GeraXMLExp(1);
                sInsert.Append(belUtil.TiraSimbolo(psDoc, ""));
                sInsert.Append("', '");
                sInsert.Append(objInfNFe.BelDest.Xnome.ToString());
                sInsert.Append("', '");
                sInsert.Append(objInfNFe.BelDest.Xnome.ToString().Substring(0, 15));
                sInsert.Append("', '");
                sInsert.Append(objInfNFe.BelDest.Xlgr.ToString());
                sInsert.Append("', '");
                sInsert.Append(objInfNFe.BelDest.Nro.ToString());
                sInsert.Append("', '");
                if (objInfNFe.BelDest.Xbairro.ToString().Length > 20)
                {
                    objInfNFe.BelDest.Xbairro = objInfNFe.BelDest.Xbairro.ToString().Substring(0, 20);
                }
                sInsert.Append(objInfNFe.BelDest.Xbairro.ToString());
                sInsert.Append("', '");
                sInsert.Append(objInfNFe.BelDest.Xmun.ToString());
                sInsert.Append("', '");
                sInsert.Append(objInfNFe.BelDest.Uf.ToString());
                sInsert.Append("', '");
                sInsert.Append(objInfNFe.BelDest.Cep != null ? objInfNFe.BelDest.Cep.ToString() : "");
                sInsert.Append("', '");
                sInsert.Append((objInfNFe.BelDest.Fone != null ? objInfNFe.BelDest.Fone.ToString() : ""));
                sInsert.Append("', '");
                sInsert.Append(BuscaCategoria());
                sInsert.Append("', '");
                sInsert.Append(sPEssoaj);
                sInsert.Append("', '");
                sInsert.Append(psDoc);
                sInsert.Append("', '");
                sInsert.Append(objInfNFe.BelDest.Ie.ToString() != null ? objInfNFe.BelDest.Ie.ToString() : "Null");
                sInsert.Append("', '");
                sInsert.Append(objInfNFe.BelDest.Isuf != null ? "S" : "N");
                sInsert.Append("') ");

                using (FbCommand cmd = new FbCommand(sInsert.ToString(), Conexao))
                {
                    if (Conexao.State != ConnectionState.Open)
                    {
                        Conexao.Open();
                    }

                    cmd.ExecuteNonQuery();

                }

            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Não foi Possível incluir o Cliente/Fornecedor, CNPJ {0}, Erro.:{1}",
                                                  psDoc,
                                                  ex.Message));
            }
            finally
            {
                if (Conexao.State == ConnectionState.Open)
                {
                    Conexao.Close();
                }
            }
            return scdClifor;
        }
Esempio n. 2
0
        public string TipoLancamento()
        {
            try
            {
                string sTipoLancamento = string.Empty;
                string sCNPJempresa = "";
                using (FbCommand cmd = new FbCommand("select cd_cgc from empresa where cd_empresa ='" + objInfNFe.Empresa + "'", Conexao))
                {
                    if (Conexao.State != ConnectionState.Open)
                    {
                        Conexao.Open();
                    }
                    GeraXMLExp objGerarXMLExp = new GeraXMLExp();
                    sCNPJempresa = belUtil.TiraSimbolo(cmd.ExecuteScalar().ToString(), "");
                    Conexao.Close();
                }

                //--->  0-Entrada / 1-Saída


                if (objInfNFe.BelIde.Tpnf == "0")
                {
                    sTipoLancamento = "E";
                    if (objInfNFe.BelEmit.Cnpj != null)
                    {
                        if (objInfNFe.BelEmit.Cnpj.ToString() == sCNPJempresa)
                        {
                            bProdutorRural = true;
                        }
                    }
                    else
                    {
                        string sInstrucao = string.Empty;
                        sInstrucao = "select cd_cpf from empresa where cd_empresa ='" + objInfNFe.Empresa + "'";
                        using (FbCommand cmd = new FbCommand(sInstrucao, Conexao))
                        {
                            if (Conexao.State != ConnectionState.Open)
                            {
                                Conexao.Open();
                            }
                            GeraXMLExp objGerarXMLExp = new GeraXMLExp();

                            string sCPF = belUtil.TiraSimbolo(cmd.ExecuteScalar().ToString(), "");

                            if (sCPF == objInfNFe.BelEmit.Cpf.ToString())
                            {
                                sCPF = objInfNFe.BelEmit.Cpf;
                                bProdutorRural = true;
                            }
                        }
                    }
                }
                else
                {

                    if (objInfNFe.BelEmit.Cnpj != null)
                    {
                        if (objInfNFe.BelEmit.Cnpj.ToString() == sCNPJempresa)
                        {
                            sTipoLancamento = "S";
                        }
                    }
                    if (objInfNFe.BelDest.Cnpj != null)
                    {
                        if (objInfNFe.BelDest.Cnpj.ToString() == sCNPJempresa)
                        {
                            sTipoLancamento = "E";
                        }
                    }
                }
                return sTipoLancamento;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Não foi possivel definir o Tipo de Lançamento, Erro.: {0}",
                                                   ex.Message));
            }

            #region Codigo Comentado
            // string sTipoLancamento = string.Empty;

            // if (objInfNFe.BelIde.Tpnf == "0")
            // {
            //     sTipoLancamento = "S";
            // }
            // else
            // {
            //     sTipoLancamento = "E";
            // }



            //try
            //{
            //    if (sTipoLancamento == "E")
            //    {
            //        if (objInfNFe.BelEmit.Cnpj != null)
            //        {
            //            using (FbCommand cmd = new FbCommand("select cd_cgc from empresa where cd_empresa ='" + objInfNFe.Empresa + "'", Conexao))
            //            {
            //                if (Conexao.State != ConnectionState.Open)
            //                {
            //                    Conexao.Open();
            //                }
            //                GeraXMLExp objGerarXMLExp = new GeraXMLExp();

            //                string sCNPJ = objGerarXMLExp.TiraSimbolo(cmd.ExecuteScalar().ToString(), "");

            //                if (objInfNFe.BelEmit.Cnpj.ToString() == sCNPJ)
            //                {
            //                    bProdutorRural = true;
            //                }
            //            }
            //        }
            //        else
            //        {
            //            string sInstrucao = string.Empty;
            //            sInstrucao = "select cd_cpf from empresa where cd_empresa ='" + objInfNFe.Empresa + "'";
            //            using (FbCommand cmd = new FbCommand(sInstrucao, Conexao))
            //            {
            //                if (Conexao.State != ConnectionState.Open)
            //                {
            //                    Conexao.Open();
            //                }
            //                GeraXMLExp objGerarXMLExp = new GeraXMLExp();

            //                string sCPF = objGerarXMLExp.TiraSimbolo(cmd.ExecuteScalar().ToString(), "");

            //                if (sCPF == objInfNFe.BelEmit.Cpf.ToString())
            //                {
            //                    sCPF = objInfNFe.BelEmit.Cpf;
            //                    bProdutorRural = true;
            //                }
            //            }
            //        }                    
            //    }


            //    return sTipoLancamento;

            //}
            //catch (Exception ex)
            //{
            //    throw new Exception(string.Format("Não foi possivel definir o Tipo de Lançamento, Erro.: {0}",
            //                                       ex.Message));
            //}            
            #endregion
        }
Esempio n. 3
0
        private bool NotaSaida()
        {
            bool bSaida = false;
            try
            {
                StringBuilder sSql = new StringBuilder();
                string sDoc = string.Empty;

                sSql.Append("Select ");
                if (objInfNFe.BelDest.Cnpj != null)
                {
                    sSql.Append("cd_cgc ");
                }
                else
                {
                    sSql.Append("cd_CPF ");
                }
                sSql.Append("from Empresa ");
                sSql.Append("where cd_empresa = '");
                sSql.Append(objInfNFe.Empresa);
                sSql.Append("'");

                using (FbCommand cmd = new FbCommand(sSql.ToString(), Conexao))
                {
                    if (Conexao.State != ConnectionState.Open)
                    {
                        Conexao.Open();
                    }
                    GeraXMLExp objGerarXMLExp = new GeraXMLExp(1);

                    sDoc = belUtil.TiraSimbolo(cmd.ExecuteScalar().ToString(), "");
                }

                if (objInfNFe.BelDest.Cnpj != null)
                {
                    if (sDoc == objInfNFe.BelDest.Cnpj)
                    {
                        bSaida = false;
                    }
                    else
                    {
                        bSaida = true;
                    }
                }
                else
                {
                    if (sDoc == objInfNFe.BelDest.Cpf)
                    {
                        bSaida = false;
                    }
                    else
                    {
                        bSaida = true;
                    }
                }

            }
            catch (Exception ex)
            {

                throw new Exception(string.Format("Não foi possivel definir se à Nota é de entrada ou saída. Erro {0}",
                                                   ex.Message));
            }
            finally
            {
                if (Conexao.State == ConnectionState.Open)
                {
                    Conexao.Close();
                }
            }
            return bSaida;
        }
        public string TipoLancamento(belInfNFe objInfNFe)
        {
            try
            {
                string sTipoLancamento = string.Empty;
                string sCNPJempresa = "";
                bool bProdutorRural = false;
                using (FbCommand cmd = new FbCommand("select cd_cgc from empresa where cd_empresa ='" + cbxEmpresas.SelectedValue.ToString() + "'", fbConexao))
                {
                    if (fbConexao.State != ConnectionState.Open)
                    {
                        fbConexao.Open();
                    }
                    GeraXMLExp objGerarXMLExp = new GeraXMLExp();
                    sCNPJempresa = belUtil.TiraSimbolo(cmd.ExecuteScalar().ToString(), "");
                    fbConexao.Close();
                }

                //--->  0-Entrada / 1-Saída


                if (objInfNFe.BelIde.Tpnf == "0")
                {
                    sTipoLancamento = "E";
                    if (objInfNFe.BelEmit.Cnpj != null)
                    {
                        if (objInfNFe.BelEmit.Cnpj.ToString() == sCNPJempresa)
                        {
                            bProdutorRural = true;
                        }
                    }
                    else
                    {
                        string sInstrucao = string.Empty;
                        sInstrucao = "select cd_cpf from empresa where cd_empresa ='" + objInfNFe.Empresa + "'";
                        using (FbCommand cmd = new FbCommand(sInstrucao, fbConexao))
                        {
                            if (fbConexao.State != ConnectionState.Open)
                            {
                                fbConexao.Open();
                            }
                            GeraXMLExp objGerarXMLExp = new GeraXMLExp();

                            string sCPF = belUtil.TiraSimbolo(cmd.ExecuteScalar().ToString(), "");

                            if (sCPF == objInfNFe.BelEmit.Cpf.ToString())
                            {
                                sCPF = objInfNFe.BelEmit.Cpf;
                                bProdutorRural = true;
                            }
                        }
                    }
                }
                else
                {

                    if (objInfNFe.BelEmit.Cnpj != null)
                    {
                        if (objInfNFe.BelEmit.Cnpj.ToString() == sCNPJempresa)
                        {
                            sTipoLancamento = "S";
                        }
                    }
                    if (objInfNFe.BelDest.Cnpj != null)
                    {
                        if (objInfNFe.BelDest.Cnpj.ToString() == sCNPJempresa)
                        {
                            sTipoLancamento = "E";
                        }
                    }
                }
                return sTipoLancamento;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Não foi possivel definir o Tipo de Lançamento, Erro.: {0}",
                                                   ex.Message));
            }
        }
Esempio n. 5
0
        private string geraChaveCanc(string sEmp, string sSeq)
        {
            belConnection cx = new belConnection();
            try
            {
                StringBuilder sSql = new StringBuilder();
                sSql.Append("Select ");
                sSql.Append("uf.nr_ufnfe, ");
                sSql.Append("coalesce(nf.cd_serie, 1) serie, ");
                sSql.Append("nf.cd_notafis nNF, ");
                sSql.Append("nf.dt_emi dEmi, ");
                sSql.Append("empresa.cd_cgc CNPJ, ");
                sSql.Append("nf.cd_nfseq cNF ");
                sSql.Append(" From ");
                sSql.Append("NF ");
                sSql.Append("inner join empresa on (empresa.cd_empresa = nf.cd_empresa) ");
                sSql.Append("left join uf on (uf.cd_uf = empresa.cd_ufnor) ");
                sSql.Append("where ");
                sSql.Append("(nf.cd_empresa ='");
                sSql.Append(sEmp);
                sSql.Append("')");
                sSql.Append(" and ");
                sSql.Append("(nf.cd_nfseq = '");
                sSql.Append(sSeq);
                sSql.Append("')");

                FbCommand sqlConsulta = new FbCommand(sSql.ToString(), cx.get_Conexao());
                cx.Open_Conexao();
                sqlConsulta.ExecuteNonQuery();
                FbDataReader drChave = sqlConsulta.ExecuteReader();
                drChave.Read();

                GeraXMLExp objgeraxmlexp = new GeraXMLExp();

                string scUF, sAAmM, sCNPJ, sMod, sSerie, snNF, scNF;
                scUF = drChave["nr_ufnfe"].ToString().PadLeft(2, '0');
                sAAmM = drChave["demi"].ToString().Replace("/", "").Substring(6, 2).ToString() +
                        drChave["demi"].ToString().Replace("/", "").Substring(2, 2).ToString();
                sCNPJ = belUtil.TiraSimbolo(drChave["cnpj"].ToString(), "");
                sCNPJ = sCNPJ.PadLeft(14, '0');
                sMod = "55";

                if (IsNumeric(drChave["serie"].ToString()))
                {
                    sSerie = drChave["serie"].ToString().PadLeft(3, '0');
                }
                else
                {
                    sSerie = "001";
                }
                snNF = drChave["nNF"].ToString().PadLeft(9, '0');
                scNF = drChave["cNF"].ToString().PadLeft(9, '0');

                string sChaveantDig = "";
                string sChave = "";
                string sDig = "";

                sChaveantDig = scUF.Trim() + sAAmM.Trim() + sCNPJ.Trim() + sMod.Trim() + sSerie.Trim() + snNF.Trim() + scNF.Trim();
                sDig = objgeraxmlexp.CalculaDig11(sChaveantDig).ToString();

                sChave = sChaveantDig + sDig;
                return sChave;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                cx.Close_Conexao();
            }
        }
Esempio n. 6
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();
            }
        }
Esempio n. 7
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();
            }
        }