Beispiel #1
0
        void ConfirmarClassificacao(object sender, RoutedEventArgs e)
        {
            if (Current == TipoClassificacao.Categoria && IdCategoria == Guid.Empty ||
                Current == TipoClassificacao.Fornecedor && IdFornecedor == Guid.Empty)
            {
                Popup.Current.Escrever(TitulosComuns.Atenção, "Primeiro escolha o valor desejado na caixa de seleção ao lado da caixa de busca.");
                return;
            }
            var itens = grdItens.SelectedItems;

            using (var escrita = new BaseGeral.Repositorio.Escrita())
                for (int i = 0; i < itens.Count; i++)
                {
                    var prod = (ProdutoDI)itens[i];
                    if (Current == TipoClassificacao.Categoria)
                    {
                        prod.IdCategoria = IdCategoria;
                    }
                    else
                    {
                        prod.IdFornecedor = IdFornecedor;
                    }
                    escrita.SalvarItemSimples(prod, DefinicoesTemporarias.DateTimeNow);
                }
            AplicarDesignPosClassificacao();
        }
Beispiel #2
0
        void Concluir(RetInutNFe resultado, bool homologacao)
        {
            var info   = resultado.Info;
            var xml    = resultado.ToXElement <RetInutNFe>();
            var itemDB = new Inutilizacao
            {
                CNPJ                 = info.CNPJ,
                FimRange             = info.FinalNumeracao,
                Homologacao          = homologacao,
                Id                   = info.Id,
                InicioRange          = info.InicioNumeracao,
                MomentoProcessamento = DateTime.Parse(info.DataHoraProcessamento),
                NumeroProtocolo      = info.NumeroProtocolo,
                Serie                = info.SerieNFe,
                XMLCompleto          = xml.ToString(SaveOptions.DisableFormatting)
            };

            using (var db = new BaseGeral.Repositorio.Escrita())
            {
                db.SalvarItemSimples(itemDB, DefinicoesTemporarias.DateTimeNow);
            }

            string key   = homologacao ? "Homologação" : "Produção";
            int    index = Lista[0].Key == key ? 0 : 1;
            var    nova  = Lista[index].Concat(new Inutilizacao[1] {
                itemDB
            }).GroupBy(x => key);

            Lista.RemoveAt(index);
            Lista.Insert(0, nova.Single());
        }
Beispiel #3
0
        async void CriarNFeEntrada()
        {
            var caixa = new FileOpenPicker();

            caixa.FileTypeFilter.Add(".xml");
            var arq = await caixa.PickSingleFileAsync();

            if (arq != null)
            {
                try
                {
                    var xml = await ImportacaoDados.ObterXMLNFe(arq);

                    var proc = xml.FromXElement <ProcessoNFe>();
                    var nfe  = proc.NFe;
                    if (nfe.Informacoes.destinatario.CNPJ == DefinicoesTemporarias.EmitenteAtivo.CNPJ)
                    {
                        ClienteDI c;
                        using (var repo = new BaseGeral.Repositorio.Leitura())
                        {
                            c = repo.ObterClienteViaCNPJ(nfe.Informacoes.Emitente.CNPJ);
                        }
                        if (c != null)
                        {
                            nfe.Informacoes.destinatario = c.ToDestinatario();
                            nfe.Informacoes.Emitente     = DefinicoesTemporarias.EmitenteAtivo.ToEmitente();
                            nfe.Informacoes.identificacao.TipoOperacao = 0;
                            var analisador = new AnalisadorNFe(ref nfe);
                            analisador.Desnormalizar();
                            var controle = new ControleNFe(nfe);
                            if (await new Criador(controle).ShowAsync() == ContentDialogResult.Primary)
                            {
                                Popup.Current.Escrever(TitulosComuns.Sucesso, "Nota de entrada criada. Agora verifique se todas as informações estão corretas e se nenhum dado ficou de fora.");
                            }
                        }
                        else
                        {
                            using (var repo = new BaseGeral.Repositorio.Escrita())
                            {
                                repo.SalvarItemSimples(new ClienteDI(nfe.Informacoes.Emitente),
                                                       DefinicoesTemporarias.DateTimeNow);
                            }
                        }
                    }
                    else
                    {
                        Popup.Current.Escrever(TitulosComuns.Atenção, "O cliente dessa nota fiscal não é o emitente ativo, por favor, escolha apenas notas fiscais para o emitente ativo.");
                    }
                }
                catch (Exception erro)
                {
                    erro.ManipularErro();
                }
            }
        }
        private async void Analisar(object sender, RoutedEventArgs e)
        {
            if (UF == null || string.IsNullOrEmpty(Chave))
            {
                return;
            }
            var gerenciador = new GerenciadorGeral <ConsSitNFe, RetConsSitNFe>(UF, Operacoes.Consultar, Homologacao, isNFCe);
            var envio       = new ConsSitNFe(Chave, Homologacao);

            RetConsSitNFe resultado = default(RetConsSitNFe);

            X509Certificate2[] certs;
            using (var loja = new X509Store(StoreName.My, StoreLocation.CurrentUser))
            {
                loja.Open(OpenFlags.ReadOnly);
                certs = loja.Certificates.Cast <X509Certificate2>().ToArray();
            }
            Progresso progresso = null;

            progresso = new Progresso(async x =>
            {
                resultado = await gerenciador.EnviarAsync(envio, false, (X509Certificate2)x);
                await progresso.Update(5);
                return(true, resultado.DescricaoResposta);
            }, certs, "Subject", gerenciador.Etapas.Concat("Analisar resultado no banco de dados"));
            gerenciador.ProgressChanged += async(x, y) => await progresso.Update(y);

            await progresso.ShowAsync();

            if (resultado.StatusResposta == 100)
            {
                NFeDI nota = null;
                using (var leit = new BaseGeral.Repositorio.Leitura())
                {
                    nota = leit.ObterNota($"NFe{resultado.ChaveNFe}");
                }
                if (nota != null && nota.Status < 4)
                {
                    using (var esc = new BaseGeral.Repositorio.Escrita())
                    {
                        nota.Status = (int)StatusNota.Emitida;
                        var original = XElement.Parse(nota.XML).FromXElement <NFe>();
                        var novo     = new ProcessoNFe()
                        {
                            NFe     = original,
                            ProtNFe = resultado.Protocolo
                        };
                        nota.XML = novo.ToXElement().ToString();
                        esc.SalvarItemSimples(nota, DefinicoesTemporarias.DateTimeNow);
                    }
                }
            }
        }
Beispiel #5
0
 void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
 {
     ProdutoDI[] produtos;
     using (var leitor = new BaseGeral.Repositorio.Leitura())
         produtos = leitor.ObterProdutos().ToArray();
     using (var escritor = new BaseGeral.Repositorio.Escrita())
         for (int i = 0; i < produtos.Length; i++)
         {
             bool fornVazio = produtos[i].IdFornecedor == default(Guid);
             if (produtos[i].IdCategoria == Categoria.Id &&
                 (fornVazio || AlterarTodosProdutos))
             {
                 produtos[i].IdFornecedor = Escolhido.Id;
                 escritor.SalvarItemSimples(produtos[i], DefinicoesTemporarias.DateTimeNow);
             }
         }
 }
Beispiel #6
0
 protected void AtualizarDI(object itemCompleto)
 {
     try
     {
         using (var repo = new BaseGeral.Repositorio.Escrita())
         {
             ItemBanco.XML = ItemBanco.Status < (int)StatusNota.Emitida
                 ? itemCompleto.ToXElement().ToString()
                 : itemCompleto.ToXElement().ToString();
             repo.SalvarItemSimples(ItemBanco, DefinicoesTemporarias.DateTimeNow);
         }
     }
     catch (Exception e)
     {
         e.ManipularErro();
     }
 }
        public override async void Editar(ExibicaoGenerica contexto)
        {
            var categoria = contexto.Convert <CategoriaDI>();
            var index     = Itens.IndexOf(contexto);
            var caixa     = new AdicionarCategoria(categoria.Nome);

            if (await caixa.ShowAsync() == ContentDialogResult.Primary)
            {
                categoria.Nome = caixa.Nome;
                using (var repo = new BaseGeral.Repositorio.Escrita())
                {
                    repo.SalvarItemSimples(categoria, DefinicoesTemporarias.DateTimeNow);
                }
                Itens.RemoveAt(index);
                Itens.Insert(index, Convert(categoria));
            }
        }
        public override async void Adicionar()
        {
            var caixa = new AdicionarCategoria();

            if (await caixa.ShowAsync() == ContentDialogResult.Primary)
            {
                var newCategoria = new CategoriaDI()
                {
                    Nome = caixa.Nome
                };
                using (var repo = new BaseGeral.Repositorio.Escrita())
                {
                    repo.SalvarItemSimples(newCategoria, DefinicoesTemporarias.DateTimeNow);
                }
                Itens.Add(Convert(newCategoria));
            }
        }
Beispiel #9
0
        async void ControlarEstoque(object sender, RoutedEventArgs e)
        {
            if (VerificarClassificacaoEmUso())
            {
                return;
            }
            var     contexto = ((FrameworkElement)sender).DataContext;
            var     produto  = (ProdutoDI)contexto;
            Estoque estoque  = null;

            using (var leit = new BaseGeral.Repositorio.Leitura())
            {
                estoque = leit.ObterEstoque(produto.Id);
            }
            if (estoque == null)
            {
                using (var repo = new BaseGeral.Repositorio.Escrita())
                {
                    var caixa = new MessageDialog("Essa é uma operação sem volta, uma vez adicionado ao controle de estoque este produto será permanentemente parte dele. Certeza que você realmente quer isso?", "Atenção");
                    caixa.Commands.Add(new UICommand("Sim", x =>
                    {
                        estoque = new Estoque()
                        {
                            Id = produto.Id
                        };
                        repo.SalvarItemSimples(estoque, DefinicoesTemporarias.DateTimeNow);
                        repo.SalvarComTotalCerteza();
                    }));
                    caixa.Commands.Add(new UICommand("Não"));
                    if ((await caixa.ShowAsync()).Label == "Não")
                    {
                        return;
                    }
                }
                BasicMainPage.Current.Navegar <ControleEstoque>(estoque);
            }
            else
            {
                BasicMainPage.Current.Navegar <ControleEstoque>(estoque);
            }
        }
Beispiel #10
0
 private void Confirmar_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         if (new ValidarDados().ValidarTudo(true,
                                            (Comprador.IdEmpresa == default(Guid), "Selecione uma empresa 'dona' deste comprador"),
                                            (string.IsNullOrEmpty(Comprador.Telefone), "Telefone não pode estar em branco"),
                                            (string.IsNullOrWhiteSpace(Comprador.Nome), "Nome não pode estar em branco"),
                                            (string.IsNullOrWhiteSpace(Comprador.Email), "Email não pode estar em branco")))
         {
             using (var repo = new BaseGeral.Repositorio.Escrita())
             {
                 repo.SalvarItemSimples(Comprador, DefinicoesTemporarias.DateTimeNow);
             }
             MainPage.Current.Retornar();
         }
     }
     catch (Exception erro)
     {
         erro.ManipularErro();
     }
 }
        public async Task <bool> Cancelar(NFeDI nota)
        {
            bool retorno     = true;
            var  processo    = XElement.Parse(nota.XML).FromXElement <ProcessoNFCe>();
            var  informacoes = processo.NFe.Informacoes;
            var  protNFe     = processo.ProtNFe;

            var estado       = informacoes.identificacao.CódigoUF;
            var cnpj         = informacoes.Emitente.CNPJ;
            var chave        = informacoes.ChaveAcesso;
            var tipoAmbiente = protNFe.InfProt.tpAmb;
            var nProtocolo   = protNFe.InfProt.nProt;

            var entrada = new CancelarNFe();

            if (await entrada.ShowAsync() == ContentDialogResult.Primary)
            {
                var infoEvento = new InformacoesEvento(estado, cnpj, chave, nProtocolo, entrada.Motivo, tipoAmbiente);
                var envio      = new EnvEvento(infoEvento);

                AssinaFacil assinador   = new AssinaFacil();
                var         gerenciador = new GerenciadorGeral <EnvEvento, RetEnvEvento>(estado, Operacoes.RecepcaoEvento, tipoAmbiente == 2, true);
                Progresso   progresso   = null;
                progresso = new Progresso(async x =>
                {
                    var cert      = (X509Certificate2)x;
                    var resultado = await envio.PrepararEventos(assinador, cert);
                    if (!resultado.Item1)
                    {
                        retorno = resultado.Item1;
                        return(resultado);
                    }
                    await progresso.Update(1);

                    var resposta = await gerenciador.EnviarAsync(envio);
                    if (resposta.ResultadorEventos[0].InfEvento.CStat == 135)
                    {
                        using (var repo = new BaseGeral.Repositorio.Escrita())
                        {
                            var xml = new ProcEventoCancelamento()
                            {
                                Eventos   = envio.Eventos,
                                RetEvento = resposta.ResultadorEventos,
                                Versao    = resposta.Versao
                            }.ToXElement <ProcEventoCancelamento>();
                            repo.SalvarItemSimples(new RegistroCancelamento()
                            {
                                ChaveNFe       = chave,
                                DataHoraEvento = resposta.ResultadorEventos[0].InfEvento.DhRegEvento,
                                TipoAmbiente   = tipoAmbiente,
                                XML            = xml.ToString()
                            }, DefinicoesTemporarias.DateTimeNow);

                            nota.Status = (int)StatusNota.Cancelada;
                            repo.SalvarItemSimples(nota, DefinicoesTemporarias.DateTimeNow);
                            await progresso.Update(6);

                            using (var opEx = new BaseGeral.Repositorio.OperacoesExtras())
                            {
                                var rvVinculado = opEx.GetRVVinculado(informacoes.Id);
                                if (rvVinculado != null)
                                {
                                    if (rvVinculado.Cancelado)
                                    {
                                        var dialog = new MessageDialog("Um registro de venda já cancelado está vinculado a esta nota fiscal, você ainda deseja aplicar as alterações no estoque?", "Aviso");
                                        dialog.Commands.Add(new UICommand("Sim", y => AtualizarEstoques()));
                                        dialog.Commands.Add(new UICommand("Não"));
                                        await dialog.ShowAsync();
                                    }
                                    else
                                    {
                                        var dialog = new MessageDialog("Um registro de venda válido está vinculado a esta nota fiscal, você ainda deseja aplicar as alterações no estoque?", "Aviso");
                                        dialog.Commands.Add(new UICommand("Sim", y => AtualizarEstoques()));
                                        dialog.Commands.Add(new UICommand("Não"));
                                        await dialog.ShowAsync();

                                        dialog = new MessageDialog("Esta nota foi cancelada com sucesso, você deseja também cancelar o registro de venda?", "Aviso");
                                        dialog.Commands.Add(new UICommand("Sim", y =>
                                        {
                                            using (var escr = new BaseGeral.Repositorio.Escrita())
                                            {
                                                escr.CancelarRV(rvVinculado, new CancelamentoRegistroVenda()
                                                {
                                                    Id = rvVinculado.Id,
                                                    MomentoCancelamento = DefinicoesTemporarias.DateTimeNow,
                                                    Motivo = "Cancelamento decorrente de cancelamento da nota fiscal correspondente."
                                                }, DefinicoesTemporarias.DateTimeNow);
                                            }
                                        }));
                                        dialog.Commands.Add(new UICommand("Não"));
                                        await dialog.ShowAsync();
                                    }
                                }
                                else
                                {
                                    AtualizarEstoques();
                                }
                            }

                            void AtualizarEstoques()
                            {
                                using (var leit = new BaseGeral.Repositorio.Leitura())
                                {
                                    repo.AtualizarEstoques(DefinicoesTemporarias.DateTimeNow,
                                                           (from prod in informacoes.produtos
                                                            let orig = leit.ObterProduto(prod.Produto.CodigoProduto)
                                                                       where orig != null
                                                                       select(orig.Id, prod.Produto.QuantidadeComercializada)).ToArray());
                                }
                            }
                        }
                        retorno = true;
                        return(true, "NFe cancelada com sucesso.");
                    }
                    else
                    {
                        retorno = false;
                        return(false, resposta.ResultadorEventos[0].InfEvento.XMotivo);
                    }
                }, assinador.CertificadosDisponiveis, "Subject",
                                          "Preparar eventos com assinatura do emitente",
                                          "Preparar conexão",
                                          "Obter conteúdo da requisição",
                                          "Enviar requisição",
                                          "Processar resposta",
                                          "Salvar registro de cancelamento no banco de dados");
                gerenciador.ProgressChanged += async(x, y) => await progresso.Update(y + 1);

                await progresso.ShowAsync();
            }
            return(retorno);
        }