示例#1
0
        public Boletos LerArquivoRetorno(Stream arquivo)
        {
            Boletos.Clear();
            try
            {
                if (TipoArquivo == TipoArquivo.CNAB400 && Banco.IdsRetornoCnab400RegistroDetalhe.Count == 0)
                {
                    throw new Exception("Banco " + Banco.Codigo.ToString() + " não implementou os Ids do Registro Retorno do CNAB400.");
                }

                using (StreamReader arquivoRetorno = new StreamReader(arquivo, System.Text.Encoding.UTF8))
                {
                    while (!arquivoRetorno.EndOfStream)
                    {
                        var registro = arquivoRetorno.ReadLine();
                        if (TipoArquivo == TipoArquivo.CNAB240)
                        {
                            LerLinhaDoArquivoRetornoCNAB240(registro);
                        }
                        if (TipoArquivo == TipoArquivo.CNAB400)
                        {
                            LerLinhaDoArquivoRetornoCNAB400(registro);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Erro ao ler arquivo.", ex);
            }
            return(Boletos);
        }
示例#2
0
        private void LerLinhaDoArquivoRetornoCNAB240(string registro)
        {
            var tipoRegistro = registro.Substring(7, 1);
            var tipoSegmento = registro.Substring(13, 1);

            if (tipoRegistro == "0")
            {
                //REGISTRO HEADER DO ARQUIVO RETORNO
                Banco.LerHeaderRetornoCNAB240(this, registro);
                return;
            }

            if (tipoRegistro == "3" & tipoSegmento == "T")
            {
                // Segmento T - Indica um novo boleto
                var boleto = new Boleto(this.Banco);
                Banco.LerDetalheRetornoCNAB240SegmentoT(ref boleto, registro);
                Boletos.Add(boleto);
                return;
            }

            if (tipoRegistro == "3" & tipoSegmento == "U")
            {
                // Segmento U - Continuação do segmento T anterior (localiza o último boleto da lista)
                var boleto = Boletos.LastOrDefault();
                // Se não encontrou um boleto válido, ocorreu algum problema, pois deveria ter criado um novo objeto no registro que foi analisado anteriormente.
                if (boleto == null)
                {
                    throw new Exception("Objeto boleto não identificado");
                }
                Banco.LerDetalheRetornoCNAB240SegmentoU(ref boleto, registro);
                return;
            }
        }
示例#3
0
        public bool LerRetorno(int formatoArquivo, string nomeArquivo, ref string mensagemErro)
        {
            try
            {
                if (boletos.Banco == null)
                {
                    mensagemErro = "Banco não definido.";
                    return(false);
                }
                if (formatoArquivo != 0 & formatoArquivo != 1)
                {
                    // Formato do Arquivo - CNAB240 = 0 / CNAB400 = 1
                    mensagemErro = "Tipo do arquivo inválido: 0-CNAB240, 1-CNAB400";
                    return(false);
                }
                boletos.Clear();

                var arquivoRetorno = new ArquivoRetorno(boletos.Banco, (TipoArquivo)formatoArquivo);
                using (var fileStream = new FileStream(nomeArquivo, FileMode.Open))
                {
                    boletos = arquivoRetorno.LerArquivoRetorno(fileStream);
                }

                return(true);
            }
            catch (Exception ex)
            {
                while (ex != null)
                {
                    mensagemErro += ex.Message + Environment.NewLine;
                    ex            = ex.InnerException;
                }
                return(false);
            }
        }
示例#4
0
        private void LerArquivoRetorno2(Stream arquivo)
        {
            Boletos.Clear();
            try
            {
                using (StreamReader arquivoRetorno = new StreamReader(arquivo, System.Text.Encoding.UTF8))
                {
                    if (arquivoRetorno.EndOfStream)
                    {
                        return;
                    }

                    //busca o primeiro registro do arquivo
                    var registro = arquivoRetorno.ReadLine();

                    //atribui o tipo de acordo com o conteúdo do arquivo
                    TipoArquivo = registro.Length == 240 ? TipoArquivo.CNAB240 : TipoArquivo.CNAB400;

                    if (TipoArquivo == TipoArquivo.CNAB400 && Banco.IdsRetornoCnab400RegistroDetalhe.Count == 0)
                    {
                        throw new Exception("Banco " + Banco.Codigo.ToString() + " não implementou os Ids do Registro Retorno do CNAB400.");
                    }

                    //instacia o banco de acordo com o codigo/id do banco presente no arquivo de retorno
                    Banco = Boleto2Net.Banco.Instancia(Utils.ToInt32(registro.Substring(TipoArquivo == TipoArquivo.CNAB240 ? 0 : 76, 3)));

                    //define a posicao do reader para o início
                    arquivoRetorno.DiscardBufferedData();
                    arquivoRetorno.BaseStream.Seek(0, SeekOrigin.Begin);

                    while (!arquivoRetorno.EndOfStream)
                    {
                        registro = arquivoRetorno.ReadLine();
                        if (TipoArquivo == TipoArquivo.CNAB240)
                        {
                            LerLinhaDoArquivoRetornoCNAB240(registro);
                        }
                        else
                        if (TipoArquivo == TipoArquivo.CNAB400)
                        {
                            LerLinhaDoArquivoRetornoCNAB400(registro);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Erro ao ler arquivo.", ex);
            }
        }
示例#5
0
        private void LerLinhaDoArquivoRetornoCNAB400(string registro)
        {
            // Identifica o tipo do registro (primeira posição da linha)
            var tipoRegistro = registro.Substring(0, 1);

            // Registro HEADER
            if (tipoRegistro == "0")
            {
                Banco.LerHeaderRetornoCNAB400(registro);
                return;
            }

            // Registro TRAILER
            if (tipoRegistro == "9")
            {
                Banco.LerTrailerRetornoCNAB400(registro);
                return;
            }

            // Se o registro não estiver na lista a ser processada pelo banco selecionado, ignora o registro
            if (!Banco.IdsRetornoCnab400RegistroDetalhe.Contains(tipoRegistro))
            {
                return;
            }

            // O primeiro ID da lista, identifica um novo boleto.
            bool novoBoleto = false;

            if (tipoRegistro == Banco.IdsRetornoCnab400RegistroDetalhe.First())
            {
                novoBoleto = true;
            }


            // Se for um novo boleto, cria um novo objeto, caso contrário, seleciona o último boleto
            // Estamos considerando que, quando houver mais de um registro para o mesmo boleto, no arquivo retorno, os registros serão apresentados na sequencia.
            Boleto boleto;

            if (novoBoleto)
            {
                boleto = new Boleto(this.Banco);
            }
            else
            {
                boleto = Boletos.Last();
                // Se não encontrou um boleto válido, ocorreu algum problema, pois deveria ter criado um novo objeto no registro que foi analisado anteriormente.
                if (boleto == null)
                {
                    throw new Exception("Objeto boleto não identificado");
                }
            }


            // Identifica o tipo de registro que deve ser analisado pelo Banco.
            switch (tipoRegistro)
            {
            case "1":
                Banco.LerDetalheRetornoCNAB400Segmento1(ref boleto, registro);
                break;

            case "7":
                Banco.LerDetalheRetornoCNAB400Segmento7(ref boleto, registro);
                break;

            default:
                break;
            }

            // Se for um novo boleto, adiciona na lista de boletos.
            if (novoBoleto)
            {
                Boletos.Add(boleto);
            }
        }
示例#6
0
        public void GerarArquivoRemessa(Boletos boletos, Stream arquivo)
        {
            try
            {
                int numeroRegistroGeral              = 0,
                    numeroRegistroCobrancaSimples    = 0,
                    numeroRegistroCobrancaVinculada  = 0,
                    numeroRegistroCobrancaCaucionada = 0,
                    numeroRegistroCobrancaDescontada = 0;
                decimal valorBoletoGeral             = 0,
                        valorCobrancaSimples         = 0,
                        valorCobrancaVinculada       = 0,
                        valorCobrancaCaucionada      = 0,
                        valorCobrancaDescontada      = 0;

                int tamanhoRegistro;
                if (this.TipoArquivo == TipoArquivo.CNAB240)
                {
                    tamanhoRegistro = 240;
                }
                else
                {
                    tamanhoRegistro = 400;
                }

                StreamWriter arquivoRemessa = new StreamWriter(arquivo, Encoding.GetEncoding("ISO-8859-1"));
                string       strline        = String.Empty;

                // Header do Arquivo
                strline = Banco.GerarHeaderRemessa(this.TipoArquivo, this.NumeroArquivoRemessa, ref numeroRegistroGeral);
                if (String.IsNullOrWhiteSpace(strline))
                {
                    throw new Exception("Registro HEADER obrigatório.");
                }
                strline = FormataLinhaArquivoCNAB(strline, tamanhoRegistro);
                arquivoRemessa.WriteLine(strline);

                foreach (Boleto boleto in boletos)
                {
                    // Todos os boletos da coleção devem ser do mesmo banco da geração do arquivo remessa
                    // A solução aqui é forçar essa relação, mas talvez seja melhor subir uma exceção detalhando o erro.
                    boleto.Banco = this.Banco;

                    // Detalhe do arquivo
                    strline = boleto.Banco.GerarDetalheRemessa(this.TipoArquivo, boleto, ref numeroRegistroGeral);
                    if (String.IsNullOrWhiteSpace(strline))
                    {
                        throw new Exception("Registro DETALHE obrigatório.");
                    }
                    strline = FormataLinhaArquivoCNAB(strline, tamanhoRegistro);
                    arquivoRemessa.WriteLine(strline);

                    // Ajusta Totalizadores
                    valorBoletoGeral += boleto.ValorTitulo;
                    switch (boleto.TipoCarteira)
                    {
                    case TipoCarteira.CarteiraCobrancaSimples:
                        numeroRegistroCobrancaSimples++;
                        valorCobrancaSimples += boleto.ValorTitulo;
                        break;

                    case TipoCarteira.CarteiraCobrancaVinculada:
                        numeroRegistroCobrancaVinculada++;
                        valorCobrancaVinculada += boleto.ValorTitulo;
                        break;

                    case TipoCarteira.CarteiraCobrancaCaucionada:
                        numeroRegistroCobrancaCaucionada++;
                        valorCobrancaCaucionada += boleto.ValorTitulo;
                        break;

                    case TipoCarteira.CarteiraCobrancaDescontada:
                        numeroRegistroCobrancaDescontada++;
                        valorCobrancaDescontada += boleto.ValorTitulo;
                        break;

                    default:
                        break;
                    }
                }

                // Trailler do Arquivo
                strline = Banco.GerarTrailerRemessa(this.TipoArquivo, this.NumeroArquivoRemessa,
                                                    ref numeroRegistroGeral, valorBoletoGeral,
                                                    numeroRegistroCobrancaSimples, valorCobrancaSimples,
                                                    numeroRegistroCobrancaVinculada, valorCobrancaVinculada,
                                                    numeroRegistroCobrancaCaucionada, valorCobrancaCaucionada,
                                                    numeroRegistroCobrancaDescontada, valorCobrancaDescontada);
                if (!String.IsNullOrWhiteSpace(strline))
                {
                    strline = FormataLinhaArquivoCNAB(strline, tamanhoRegistro);
                    arquivoRemessa.WriteLine(strline);
                }

                arquivoRemessa.Close();
                arquivoRemessa.Dispose();
                arquivoRemessa = null;
            }
            catch (Exception ex)
            {
                throw new Exception("Erro ao gerar arquivo remessa.", ex);
            }
        }