Exemple #1
0
        /// <summary>
        /// Importa os dados de xml de notas fiscais na pasta padrão
        /// </summary>
        public void LerXmlNotaFiscal(string nomeArquivo)
        {
            try
            {
                NotasFiscais nfLida = new NotasFiscais();

                XmlDocument nf = new XmlDocument();

                nf.Load(nomeArquivo);

                var result = nf.GetElementsByTagName("det");
                nfLida.skuNF     = result.Count;
                nfLida.numeroNF  = nf.GetElementsByTagName("nNF")[0].InnerText;
                nfLida.numeroNF += '-' + nf.GetElementsByTagName("serie")[0].InnerText;

                var fornecedor = nf.GetElementsByTagName("xNome")[0].InnerText;
                if (fornecedor.Length > 49)
                {
                    fornecedor = fornecedor.Remove(49);
                }
                nfLida.fornecedorNF = fornecedor;
                try
                {
                    nfLida.volumesNF = int.Parse(nf.GetElementsByTagName("qVol")[0].InnerText);
                }
                catch
                {
                    var quantidade = nf.GetElementsByTagName("qCom");
                    nfLida.volumesNF = 0;
                    foreach (XmlElement item in quantidade)
                    {
                        nfLida.volumesNF += (int)double.Parse(item.InnerText.Replace('.', ','));
                    }
                }
                if (nfLida.volumesNF <= 1 && !nfLida.fornecedorNF.StartsWith("REGINA") && !nfLida.fornecedorNF.StartsWith("IMPROCROP"))
                {
                    var quantidade = nf.GetElementsByTagName("qCom");
                    nfLida.volumesNF = 0;
                    foreach (XmlElement item in quantidade)
                    {
                        nfLida.volumesNF += (int)double.Parse(item.InnerText.Replace('.', ','));
                    }
                }

                //var cliente = nf.GetElementsByTagName("xNome")[1].InnerText;
                //if (cliente.Length > 49)
                //    cliente = cliente.Remove(49);
                //nfLida.clienteNF = cliente;

                if (nfLida.skuNF > nfLida.volumesNF)
                {
                    nfLida.skuNF = 1;
                }

                InserirNotaFiscal(nfLida);
            }
            catch (System.Exception)
            {
            }
        }
Exemple #2
0
        /// <summary>
        ///
        /// </summary>
        private static void InserirNotaFiscal(NotasFiscais nfLida)
        {
            if (!abd.NfExiste(nfLida.numeroNF, nfLida.fornecedorNF))
            {
                abd.CadastrarNF(nfLida);
            }

            else if (nfLida.skuNF > 0)
            {
                abd.AlterarNF(nfLida);
            }
        }
        private void NotaFiscalVM_NotaCanceladaEventHandler(NotaFiscalEntity nota)
        {
            var notaCancelada = NotasFiscais.FirstOrDefault(n => n.Chave == nota.Chave);
            var index         = NotasFiscais.IndexOf(notaCancelada);

            var notaMemento = new NotaFiscalMemento(nota.Numero,
                                                    nota.Modelo == "NFC-e" ? Modelo.Modelo65 : Modelo.Modelo55, nota.DataEmissao, nota.DataAutorizacao,
                                                    nota.Destinatario, nota.UfDestinatario, nota.ValorTotal.ToString("N2", new CultureInfo("pt-BR")),
                                                    (Status)nota.Status, nota.Chave);

            NotasFiscais[index] = notaMemento;
        }
        private async Task AtualizarNotasPendentes()
        {
            if (_isNotasPendentesVerificadas || NotasFiscais.Count == 0)
            {
                return;
            }

            _isNotasPendentesVerificadas = true;

            var notasFiscaisPendentes = _notaFiscalRepository.GetNotasPendentes(false);

            if (notasFiscaisPendentes.Count == 0)
            {
                return;
            }

            var codigoUf    = UfToCodigoUfConversor.GetCodigoUf(_emissorService.GetEmissor().Endereco.UF);
            var certificado = _certificadoService.GetX509Certificate2();
            var config      = _configuracaoService.GetConfiguracao();

            if (certificado == null)
            {
                throw new ArgumentNullException(nameof(certificado));
            }

            var idsNotasPendentes = notasFiscaisPendentes.Select(n => n.Id);

            foreach (var idNotaPendente in idsNotasPendentes)
            {
                var nota = await ConsultarNotasAsync(idNotaPendente, codigoUf, certificado, config);

                if (nota == null)
                {
                    continue;
                }

                var notaPendente =
                    NotasFiscais.FirstOrDefault(n => n.Status == "Pendente" && n.Chave == nota.Chave);
                var index = NotasFiscais.IndexOf(notaPendente);

                var notaMemento = new NotaFiscalMemento(nota.Numero,
                                                        nota.Modelo == "NFC-e" ? Modelo.Modelo65 : Modelo.Modelo55, nota.DataEmissao,
                                                        nota.DataAutorizacao, nota.Destinatario, nota.UfDestinatario,
                                                        nota.ValorTotal.ToString("N2", new CultureInfo("pt-BR")), (Status)nota.Status, nota.Chave);

                NotasFiscais[index] = notaMemento;
            }
        }
        private static void InserirNotaFiscal(NotasFiscais nfLida)
        {
            AcessoBD abd = new AcessoBD();

            if (!abd.NfExiste(nfLida.numeroNF, nfLida.fornecedorNF))
            {
                if (nfLida.fornecedorNF.StartsWith("REGINA") || nfLida.fornecedorNF.StartsWith("IMPROCROP") || nfLida.fornecedorNF.StartsWith("CONDAT"))
                {
                    nfLida.skuNF = 1;
                }
                abd.CadastrarNF(nfLida);
            }

            else
            {
                abd.AlterarNF(nfLida);
            }
        }
Exemple #6
0
        public void GerarNotaFiscal()
        {
            var vendas = _vendaService.VendasPagas();

            if (vendas != null)
            {
                foreach (var item in vendas)
                {
                    var Nf = new NotasFiscais()
                    {
                        Numero  = "000" + item.VendaId,
                        Valor   = item.Valor,
                        VendaId = item.VendaId
                    };
                    _dbContext.Add(Nf);
                }
                _dbContext.SaveChanges();
            }
        }
        // DELETE: api/NotasFiscais/id
        public HttpResponseMessage Delete(int id)
        {
            HttpResponseMessage response = null;
            SqlConnection       sqlCon   = null;

            try
            {
                sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["MarqDatabaseConnectionString"].ConnectionString);
                sqlCon.Open();
                if (!NotasFiscais.nfValida(id, sqlCon))
                {
                    throw new Exception("Nota fiscal não encontrada!");
                }
                //Exclui registros de Notas Fiscais Produtos associados a Nota Fiscal excluída
                string     script         = $"DELETE FROM dbo.NotasFicaisProdutos WHERE IdNota = {id}";
                SqlCommand sqlCommand     = new SqlCommand(script, sqlCon);
                int        linhasAfetadas = 0;
                try
                {
                    linhasAfetadas = sqlCommand.ExecuteNonQuery();
                    if (linhasAfetadas == 0)
                    {
                        throw new Exception("Nenhuma linha afetada!");
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception($"Falha de comunicação, não foi possível excluir os registros associados a Nota Fiscal: {ex.Message}");
                }
                //Exclui nota fiscal
                script     = $"DELETE FROM dbo.NotasFiscais WHERE Id = {id}";
                sqlCommand = new SqlCommand(script, sqlCon);
                try
                {
                    linhasAfetadas = sqlCommand.ExecuteNonQuery();
                    if (linhasAfetadas == 0)
                    {
                        throw new Exception("Nenhuma linha afetada!");
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception($"Falha de comunicação, não foi possível excluir a Nota Fiscal: {ex.Message}");
                }

                response = Request.CreateResponse(HttpStatusCode.OK, "Nota Fiscal excluída com sucesso!");
            }
            catch (Exception ex)
            {
                response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
            finally
            {
                if (sqlCon != null)
                {
                    sqlCon.Close();
                }
            }

            return(response);
        }
        // PUT: api/NotasFiscais
        public HttpResponseMessage Put([FromBody] NotasFiscais value)
        {
            HttpResponseMessage response = null;
            SqlConnection       sqlCon   = null;

            try
            {
                sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["MarqDatabaseConnectionString"].ConnectionString);
                sqlCon.Open();
                //Checa existência da nota fiscal
                if (!NotasFiscais.nfValida(value.Id, sqlCon))
                {
                    throw new Exception("Nota fiscal não encontrada!");
                }
                //Verifica se chave estrangeira é válida
                if (!checaExistencia(new string[] {
                    $"{NotasFiscais.ALIAS}.Id = {value.Id}",
                    $"{NotasFiscais.ALIAS}.IdEmpresa = {value.IdEmpresa}"
                }, $"dbo.NotasFiscais {NotasFiscais.ALIAS}", sqlCon))
                {
                    throw new Exception("Id Empresa não é válido!");
                }
                //Checa se nota fiscal é a última enviada pela empresa
                SqlCommand sqlCommand = new SqlCommand($"SELECT TOP 1 {NotasFiscais.ALIAS}.Id FROM dbo.NotasFiscais {NotasFiscais.ALIAS} " +
                                                       $"WHERE {NotasFiscais.ALIAS}.IdEmpresa = {value.IdEmpresa} ORDER BY {NotasFiscais.ALIAS}.DataHora DESC", sqlCon);
                int id = 0;
                using (SqlDataReader sqlR = sqlCommand.ExecuteReader())
                {
                    sqlR.Read();
                    id = Convert.ToInt32(sqlR[0]);
                }
                if (id != value.Id)
                {
                    throw new Exception("Somente é permitido atualizar a nota fiscal caso esta seja a última nota enviada pela empresa!");
                }
                //Pega objeto a ser atualizado
                sqlCommand = new SqlCommand($"SELECT {NotasFiscais.ALIAS}.* FROM dbo.NotasFiscais {NotasFiscais.ALIAS}" +
                                            $" WHERE {NotasFiscais.ALIAS}.Id = {value.Id}", sqlCon);
                IDataRecord nf = null;
                using (SqlDataReader sqlR = sqlCommand.ExecuteReader())
                {
                    nf = sqlR.Cast <IDataRecord>().FirstOrDefault();
                }
                //Atualiza
                List <string> updates = new List <string>();
                if (value.DataHora != new DateTime() && !value.DataHora.Equals(Convert.ToDateTime(nf["DataHora"])))
                {
                    updates.Add($"{NotasFiscais.ALIAS}.DataHora = '{value.DataHora.ToString("yyyy-dd-MM HH:mm:ss")}'");
                }
                if (value.Total != Convert.ToDecimal(nf["Total"]))
                {
                    updates.Add($"{NotasFiscais.ALIAS}.Total = {value.Total.ToString(CultureInfo.GetCultureInfo("en-GB"))}");
                }

                sqlCommand = new SqlCommand($"UPDATE {NotasFiscais.ALIAS} SET {string.Join(", ", updates)} " +
                                            $"FROM dbo.NotasFiscais {NotasFiscais.ALIAS} WHERE {NotasFiscais.ALIAS}.Id = {value.Id}", sqlCon);
                int linhasAfetadas = 0;
                try
                {
                    linhasAfetadas = sqlCommand.ExecuteNonQuery();
                    if (linhasAfetadas == 0)
                    {
                        throw new Exception("Nenhuma linha afetada!");
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception($"Não foi possível atualizar a nota fiscal: {ex.Message}");
                }

                response = Request.CreateResponse(HttpStatusCode.OK, "Nota Fiscal atualizada com sucesso!");
            }
            catch (Exception e)
            {
                response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
            }
            finally
            {
                if (sqlCon != null)
                {
                    sqlCon.Close();
                }
            }

            return(response);
        }
        // POST: api/NotasFiscais
        public HttpResponseMessage Post([FromBody] NotasFiscais value)
        {
            HttpResponseMessage response = null;
            SqlConnection       sqlCon   = null;

            try
            {
                sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["MarqDatabaseConnectionString"].ConnectionString);
                sqlCon.Open();
                //Verifica se Id Empresa é válido
                if (!Empresas.empresaValida(value.IdEmpresa, sqlCon))
                {
                    throw new Exception("Id Empresa não é válido!");
                }
                //Verifica se produtos são válidos
                if (value.Produtos == null || value.Produtos.Any(e => !Produtos.produtoValido(e.Id, sqlCon)))
                {
                    throw new Exception("É necessário informar produtos válidos!");
                }
                //Verifica se a nota fiscal já existe
                if (value.DataHora.Equals(new DateTime()))
                {
                    throw new Exception("É necessário informar uma data válida!");
                }
                //Elimina produtos duplicados

                //Verifica se valor da nota fiscal é igual a soma dos produtos associados
                if (value.Total != value.Produtos.Sum(s => s.Preco))
                {
                    throw new Exception("Soma dos preços dos produtos é diferente do valor da Nota Fiscal!");
                }

                //Cadastra Nota Fiscal
                string script = $"INSERT INTO dbo.NotasFiscais (IdEmpresa, DataHora, Total) " +
                                $"OUTPUT INSERTED.Id VALUES ({value.IdEmpresa}, '{value.DataHora}', {value.Total.ToString(CultureInfo.GetCultureInfo("en-GB"))})";
                SqlCommand sqlCommand   = new SqlCommand(script, sqlCon);
                int        IdNotaFiscal = 0;
                try
                {
                    using (SqlDataReader reader = sqlCommand.ExecuteReader())
                    {
                        reader.Read();
                        IdNotaFiscal = Convert.ToInt32(reader[0]);
                    }
                }
                catch (Exception ex) { throw new Exception($"Erro ao cadastrar Nota Fiscal: {ex.Message}"); }
                //Cadastra Nota Fiscal Produto
                string[] inserts = value.Produtos
                                   .Select(e => $"({IdNotaFiscal}, {e.Id}, {e.Quantidade}, {e.Preco.ToString(CultureInfo.GetCultureInfo("en-GB"))})")
                                   .ToArray();
                script     = $"INSERT INTO dbo.NotasFicaisProdutos (IdNota, IdProduto, Quantidade, Preco) VALUES {string.Join(", ", inserts)}";
                sqlCommand = new SqlCommand(script, sqlCon);
                int linhasAfetadas = 0;
                try
                {
                    linhasAfetadas = sqlCommand.ExecuteNonQuery();
                    if (linhasAfetadas != value.Produtos.Count)
                    {
                        throw new Exception("Não foi possível inserir todos as Notas Fiscais Produtos!");
                    }
                }
                catch (Exception ex) { throw new Exception($"Erro ao cadastrar Nota Fiscal Produto: {ex.Message}"); }

                response = Request.CreateResponse(HttpStatusCode.OK, "Nota Fiscal cadastrada com sucesso!");
            }
            catch (Exception e)
            {
                response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
            }
            finally
            {
                if (sqlCon != null)
                {
                    sqlCon.Close();
                }
            }

            return(response);
        }
Exemple #10
0
        /// <summary>
        /// Importa os dados de xml de manifestos na pasta padrão
        /// </summary>
        public bool LerManifesto(string nomeArquivo)
        {
            try
            {
                XmlDocument manifesto = new XmlDocument();
                manifesto.Load(nomeArquivo);

                AcessoBD   abd    = new AcessoBD();
                var        result = manifesto.GetElementsByTagName("Value");
                Manifestos lido   = new Manifestos
                {
                    numeroManifesto    = int.Parse(nomeArquivo.Replace(PastasXml.Default.PastaManifestos + "\\", "").Replace(".xml", "")),
                    VolumesManifesto   = (int)double.Parse(result[result.Count - 2].InnerText.Replace('.', ',')),
                    pesoManifesto      = double.Parse(result[result.Count - 3].InnerText.Replace('.', ',')),
                    quantCtesManifesto = (int)double.Parse(result[result.Count - 4].InnerText.Replace('.', ','))
                };

                abd.CadastrarManifesto(lido);

                int          cte;
                NotasFiscais nfLida = new NotasFiscais();

                for (int i = 0; i < result.Count - 4; i = i + 10)
                {
                    cte = int.Parse(result[i].InnerText);

                    abd.CadastrarCte(new Cte(cte, result[i + 1].InnerText));

                    CriarCteManifesto(cte, lido.numeroManifesto);

                    nfLida.fornecedorNF = result[i + 2].InnerText;
                    nfLida.clienteNF    = result[i + 7].InnerText;
                    nfLida.CteNovoNF    = abd.GetNovoCtePorNum(int.Parse(result[i].InnerText)).Max(x => x.idCte);
                    nfLida.skuNF        = 0;

                    if (!result[i + 1].InnerText.Contains("\\"))
                    {
                        nfLida.numeroNF  = result[i + 1].InnerText;
                        nfLida.volumesNF = (int)double.Parse(result[i + 8].InnerText.Replace('.', ','));
                        InserirNotaFiscal(nfLida);
                    }
                    else
                    {
                        var nfs = result[i + 1].InnerText.Split('\\');
                        nfLida.volumesNF = (int)System.Math.Ceiling(double.Parse(result[i + 8].InnerText.Replace('.', ',')) / nfs.Count()); //volume total pode variar por causa desse truncamento

                        foreach (var item in nfs)
                        {
                            nfLida.numeroNF = item;
                            InserirNotaFiscal(nfLida);
                        }
                    }

                    // AlterarNfs(result[i + 1].InnerText, cte);
                }

                return(true);
            }
            catch (System.Exception)
            {
                return(false);
            }
        }
Exemple #11
0
        /// <summary>
        /// Importa os dados de notfis de notas fiscais na pasta padrão
        /// </summary>
        public void LerNotfisNotaFiscal(string nomeArquivo)
        {
            try
            {
                NotasFiscais nfLida = new NotasFiscais();

                string[] notfis     = File.ReadAllLines(nomeArquivo);
                string   Fornecedor = "";

                if (notfis[0].StartsWith("000"))
                {
                    List <string> conteudoNf;
                    foreach (string nf in notfis)
                    {   //Fornecedor
                        if (nf.StartsWith("311"))
                        {
                            Fornecedor = nf.Remove(0, 133).TrimEnd(' ');
                        }

                        //Cliente e Zerar SKU
                        if (nf.StartsWith("312"))
                        {
                            nfLida.skuNF = 0;
                            //conteudoNf = nf.Split(' ').ToList();
                            //conteudoNf.RemoveAll(l => l == "");

                            //nfLida.clienteNF = conteudoNf[0].Substring(3);

                            //for (int i = 1; i < conteudoNf.Count; i++)
                            //{
                            //    if (conteudoNf[i].Length >= 21)
                            //        break;
                            //    else
                            //        nfLida.clienteNF += " " + conteudoNf[i];
                            //}
                            //if (nfLida.clienteNF.Length > 49)
                            //    nfLida.clienteNF = nfLida.clienteNF.Remove(49);
                        }

                        //Volumes e número da NF
                        if (nf.StartsWith("313"))
                        {
                            conteudoNf = nf.Split(' ').ToList();
                            conteudoNf.RemoveAll(l => l == "");

                            nfLida.volumesNF = int.Parse(conteudoNf[conteudoNf.Count - 3].Remove(5));

                            string aux = conteudoNf[conteudoNf.Count - 1];

                            if (aux[0] == '3')
                            {
                                aux = aux.Substring(22, 12);
                            }
                            else
                            {
                                aux = aux.Substring(29, 12);
                            }

                            nfLida.numeroNF = aux.Remove(0, 3) + "-" + aux.Remove(3).TrimStart('0');
                            nfLida.numeroNF = nfLida.numeroNF.TrimStart('0');
                        }

                        //Contar SKUs
                        if (nf.StartsWith("314"))
                        {
                            conteudoNf = nf.Split(' ').ToList();
                            conteudoNf.RemoveAll(l => l == "");
                            nfLida.skuNF += conteudoNf.Count / 2;
                        }

                        //Salvar NF no banco de dados
                        if (nf.StartsWith("317"))
                        {
                            nfLida.fornecedorNF = Fornecedor;
                            InserirNotaFiscal(nfLida);
                        }
                    }
                }
            }
            catch (System.Exception)
            {
            }
        }
        private async void EnviarNotaNovamenteCmd_ExecuteAsync(NotaFiscalMemento notaPendenteMemento)
        {
            IsBusy      = true;
            BusyContent = "Enviando...";

            var config = _configuracaoService.GetConfiguracao();

            var modelo = notaPendenteMemento.Tipo == "NFC-e" ? Modelo.Modelo65 : Modelo.Modelo55;

            //Preencher objeto da NotaFiscal a partir do XML e enviar para a correspondente ViewModel NFe ou NFCe
            var app        = Application.Current;
            var mainWindow = app.MainWindow;

            if (!_consultaStatusServicoService.ExecutarConsultaStatus(config, modelo))
            {
                MessageBox.Show(mainWindow,
                                "Serviço continua indisponível. Aguarde o reestabelecimento da conexão e tente novamente.",
                                "Erro de conexão ou serviço indisponível", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            var ambiente     = config.IsProducao ? Ambiente.Producao : Ambiente.Homologacao;
            var notaFiscalDb = _notaFiscalRepository.GetNotaFiscalByChave(notaPendenteMemento.Chave);
            var xml          = await notaFiscalDb.LoadXmlAsync();

            var notaFiscalBo = _notaFiscalRepository.GetNotaFiscalFromNfeProcXml(xml);

            notaFiscalBo.Identificacao.DataHoraEmissao = DateTime.Now;

            foreach (var prod in notaFiscalBo.Produtos)
            {
                var produtoDb = _produtoService.GetByCodigo(prod.Codigo);
                prod.Id = produtoDb.Id;
            }

            try
            {
                var cscId = ambiente == Ambiente.Homologacao ? config.CscIdHom : config.CscId;
                var csc   = ambiente == Ambiente.Homologacao ? config.CscHom : config.Csc;

                _notaFiscalRepository.ExcluirNota(notaPendenteMemento.Chave, ambiente);
                _enviaNotaFiscalService.EnviarNotaFiscal(notaFiscalBo, cscId, csc);

                IsBusy = false;

                var mbResult = MessageBox.Show(mainWindow, "Nota enviada com sucesso! Deseja imprimi-la?",
                                               "Emissão NFe", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);

                if (mbResult == MessageBoxResult.Yes)
                {
                    BusyContent = "Gerando impressão...";
                    IsBusy      = true;
                    await GeradorPDF.GerarPdfNotaFiscal(notaFiscalBo);
                }

                IsBusy = false;

                var          notaIndex = NotasFiscais.IndexOf(notaPendenteMemento);
                Destinatario destinatario;
                var          destinatarioUf = notaFiscalBo.Emitente.Endereco.UF;

                if (notaFiscalBo.Destinatario != null)
                {
                    destinatario   = notaFiscalBo.Destinatario;
                    destinatarioUf = destinatario.Endereco != null ? destinatario.Endereco.UF : destinatarioUf;
                }
                else
                {
                    destinatario = new Destinatario("CONSUMIDOR NÃO IDENTIFICADO");
                }

                var valorTotalProdutos = notaFiscalBo.ValorTotalProdutos.ToString("N2", new CultureInfo("pt-BR"));

                var notaMemento = new NotaFiscalMemento(notaFiscalBo.Identificacao.Numero,
                                                        notaFiscalBo.Identificacao.Modelo, notaFiscalBo.Identificacao.DataHoraEmissao,
                                                        notaFiscalBo.DataHoraAutorização, destinatario.NomeRazao, destinatarioUf, valorTotalProdutos,
                                                        notaFiscalBo.Identificacao.Status, notaFiscalBo.Identificacao.Chave);

                NotasFiscais[notaIndex] = notaMemento;
                NotaPendenteReenviadaEvent(notaFiscalBo);
            }
            catch (Exception e)
            {
                log.Error(e);
                MessageBox.Show(mainWindow,
                                "Ocorreram os seguintes erros ao tentar enviar a nota fiscal:\n\n" + e.InnerException.Message,
                                "Erro", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        private void NotaCanceladaVM_NotaInutilizadaEventHandler(NFCeModel notaInutilizada)
        {
            var notaMemento = NotasFiscais.First(n => n.Chave == notaInutilizada.Chave);

            NotasFiscais.Remove(notaMemento);
        }
Exemple #14
0
		protected override void OnInitialize()
		{
            Configuracoes = new NFEConfiguracoes();
            NotasFiscais = new NotasFiscais();
        }
Exemple #15
0
        /// <summary>
        /// Importa os dados de xml de manifestos na pasta padrão
        /// </summary>
        public bool LerPreManifesto(string nomeArquivo)
        {
            try
            {
                XmlDocument manifesto = new XmlDocument();
                manifesto.Load(nomeArquivo);

                var          ValueResult = manifesto.GetElementsByTagName("Value");
                var          TextResult  = manifesto.GetElementsByTagName("TextValue");
                AcessoBD     abd         = new AcessoBD();
                NotasFiscais nfLida      = new NotasFiscais();

                var ctesNoXml = new List <string>();

                //------------------------- CADASTRO PRE MANIFEST0 ------------------

                for (int i = 5; i < ValueResult.Count - 4; i += 6)
                {
                    ctesNoXml.Add(ValueResult[i].InnerText);
                }

                Manifestos lido = new Manifestos()
                {
                    numeroManifesto    = int.Parse(nomeArquivo.Replace(PastasXml.Default.PastaPreManifestos + "\\", "").Replace(".xml", "")),
                    VolumesManifesto   = (int)double.Parse(ValueResult[ValueResult.Count - 4].InnerText.Replace('.', ',')),
                    pesoManifesto      = double.Parse(ValueResult[ValueResult.Count - 2].InnerText.Replace('.', ',')),
                    quantCtesManifesto = ctesNoXml.Distinct().Count()
                };

                abd.CadastrarManifesto(lido);

                //------------------------- CADASTRO CTES ------------------

                int        cte;
                int        indexNF            = 0;
                string     fornecedor         = "";
                List <Cte> ctesNoPreManifesto = new List <Cte>();
                for (int i = 5; i < ValueResult.Count - 4; i += 6)
                {
                    cte = int.Parse(ValueResult[i].InnerText.Replace('/', ' '));

                    Cte cteDaVez = ctesNoPreManifesto.Where(x => x.numeroCte == cte).Select(x => x).FirstOrDefault();
                    if (cteDaVez == null)
                    {
                        ctesNoPreManifesto.Add(new Cte(cte, TextResult[indexNF].InnerText.TrimStart('0')));
                    }

                    else
                    {
                        cteDaVez.notasCte += "\\" + TextResult[indexNF].InnerText.TrimStart('0');
                    }

                    fornecedor = ValueResult[i - 5].InnerText;
                    indexNF++;
                }



                foreach (var item in ctesNoPreManifesto)
                {
                    abd.CadastrarCte(new Cte(item.numeroCte, item.notasCte));
                    CriarCteManifesto(item.numeroCte, lido.numeroManifesto);
                }


                //------------------------- CADASTRO/ALTERAÇÃO DE NF'S E EXPORTAÇÃO CROSS ------------------

                indexNF = 0;
                for (int i = 5; i < ValueResult.Count - 4; i += 6)
                {
                    nfLida.numeroNF     = TextResult[indexNF].InnerText.TrimStart('0');
                    nfLida.fornecedorNF = ValueResult[i - 5].InnerText;
                    nfLida.clienteNF    = ValueResult[i - 4].InnerText;
                    nfLida.CteNovoNF    = abd.GetNovoCtePorNum(int.Parse(ValueResult[i].InnerText.Replace('/', ' '))).Max(x => x.idCte);
                    nfLida.skuNF        = 0;
                    nfLida.volumesNF    = int.Parse(ValueResult[i - 3].InnerText.Replace(".00", "")); //volume corrigido
                    InserirNotaFiscal(nfLida);

                    indexNF++;

                    ExportarXmlCrossDocking(ValueResult[i].InnerText.Replace('/', ' '), nfLida.fornecedorNF);
                }
                return(true);
            }
            catch (System.Exception)
            {
                return(false);
            }
        }