Exemplo n.º 1
0
        private void Eventos()
        {
            KeyDown   += KeyDowns;
            KeyPreview = true;

            Load += (s, e) =>
            {
                DataTableStart();
            };

            btnHelp.Click += (s, e) => Support.OpenLinkBrowser(Program.URL_BASE + "/ajuda");

            btnAdicionar.Click += (s, e) =>
            {
                DocumentosReferenciadosAdd f = new DocumentosReferenciadosAdd();
                f.TopMost = true;
                if (f.ShowDialog() == DialogResult.OK)
                {
                    DataTableStart();
                }
            };

            btnRemover.Click += (s, e) =>
            {
                var result = AlertOptions.Message("Atenção!", "Você está prestes a deletar uma chave de acesso, continuar?", AlertBig.AlertType.warning, AlertBig.AlertBtn.YesNo);
                if (result)
                {
                    if (GridLista.SelectedRows.Count > 0)
                    {
                        _mNota         = _mNota.FindById(Validation.ConvertToInt32(GridLista.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault <Model.Nota>();
                        _mNota.Excluir = 1;
                        _mNota.Save(_mNota, false);

                        DataTableStart();
                    }
                }
            };

            using (var b = WorkerBackground)
            {
                b.DoWork += async(s, e) =>
                {
                    dataTable = await _cNota.GetDataTableDoc(idPedido);
                };

                b.RunWorkerCompleted += async(s, e) =>
                {
                    await _cNota.SetTableDoc(GridLista, idPedido);
                };
            }
        }
Exemplo n.º 2
0
        public void Eventos()
        {
            Load += (s, e) =>
            {
                if (idNota > 0)
                {
                    _nota = new Model.Nota().FindById(idNota).FirstOrDefault <Model.Nota>();

                    inicio.Text        = _nota.nr_Nota.ToString();
                    final.Text         = _nota.assinatura_qrcode.ToString();
                    serie.Text         = _nota.Serie.ToString();
                    justificativa.Text = _nota.correcao.ToString();
                }

                inicio.Select();
            };

            btnSalvar.Click += (s, e) =>
            {
                if (justificativa.Text.Length < 15)
                {
                    Alert.Message("Ação não permitida", "Justificativa deve conter 15 caracteres", Alert.AlertType.warning);
                    return;
                }

                _nota.Id                = idNota;
                _nota.Tipo              = "Inutiliza";
                _nota.Status            = "Transmitindo...";
                _nota.nr_Nota           = inicio.Text;
                _nota.assinatura_qrcode = final.Text;
                _nota.Serie             = serie.Text;
                _nota.correcao          = justificativa.Text;
                _nota.correcao          = Validation.CleanStringForFiscal(Validation.OneSpaceString(_nota.correcao));
                _nota.Save(_nota, true);

                DialogResult = DialogResult.OK;
                Close();
            };

            btnCancelar.Click += (s, e) =>
            {
                DialogResult = DialogResult.Cancel;
                Close();
            };

            justificativa.TextChanged += (s, e) =>
            {
                caracteres.Text = justificativa.Text.Length.ToString();
            };
        }
Exemplo n.º 3
0
        public void Eventos()
        {
            btnSalvar.Click += (s, e) =>
            {
                _modelNota.Id            = 0;
                _modelNota.Tipo          = "Documento";
                _modelNota.id_pedido     = Nota.Id;
                _modelNota.ChaveDeAcesso = correcao.Text;

                _modelNota.Save(_modelNota, false);

                DialogResult = DialogResult.OK;
                Close();
            };

            btnCancelar.Click += (s, e) =>
            {
                DialogResult = DialogResult.OK;
                Close();
            };
        }
Exemplo n.º 4
0
        public void Eventos()
        {
            Load += (s, e) =>
            {
                if (idNota == 0)
                {
                    return;
                }

                var nota = new Model.Nota().FindById(idNota).FirstOrDefault <Model.Nota>();

                if (nota == null)
                {
                    return;
                }

                var pedido = new Model.Pedido().FindById(nota.id_pedido).FirstOrDefault <Model.Pedido>();

                if (pedido == null)
                {
                    return;
                }

                var pessoaContato = new Model.PessoaContato().FindByIdUser(pedido.Cliente).Get();

                if (pessoaContato == null)
                {
                    return;
                }

                foreach (var item in pessoaContato)
                {
                    if (String.IsNullOrEmpty(correcao.Text))
                    {
                        correcao.Text = item.EMAIL + ";";
                    }
                    else
                    {
                        correcao.Text = correcao.Text + item.EMAIL + ";";
                    }
                }

                correcao.Text = correcao.Text.ToLower();
            };

            btnSalvar.Click += (s, e) =>
            {
                if (CartaCorrecaoAdd.tela == "Cancelar")
                {
                    if (correcao.Text.Length < 15)
                    {
                        Alert.Message("Ação não permitida", "Justificativa deve conter 15 caracteres", Alert.AlertType.warning);
                        return;
                    }

                    CartaCorrecaoAdd.justificativa = correcao.Text;

                    DialogResult = DialogResult.OK;
                    Close();

                    return;
                }

                if (CartaCorrecaoAdd.tela == "Email")
                {
                    CartaCorrecaoAdd.justificativa = correcao.Text;

                    DialogResult = DialogResult.OK;
                    Close();

                    return;
                }

                if (correcao.Text.Length < 15)
                {
                    Alert.Message("Ação não permitida", "Correção deve conter 15 caracteres", Alert.AlertType.warning);
                    return;
                }

                _modelNota.Id        = 0;
                _modelNota.Tipo      = "CCe";
                _modelNota.Status    = "Transmitindo...";
                _modelNota.id_pedido = CartaCorrecao.idPedido;
                _modelNota.correcao  = correcao.Text;

                _modelNota.correcao = Validation.CleanStringForFiscal(Validation.OneSpaceString(_modelNota.correcao));

                _modelNota.Save(_modelNota, false);

                DialogResult = DialogResult.OK;
                Close();
            };

            btnCancelar.Click += (s, e) =>
            {
                DialogResult = DialogResult.Cancel;
                Close();
            };

            correcao.TextChanged += (s, e) =>
            {
                caracteres.Text = correcao.Text.Length.ToString();
            };
        }
Exemplo n.º 5
0
        private void Eventos()
        {
            KeyDown   += KeyDowns;
            KeyPreview = true;

            Load += (s, e) =>
            {
                if (_mPedido.Cliente == 0)
                {
                    TelaDados.telaDados = false;
                }

                Resolution.SetScreenMaximized(this);

                if (Id > 0)
                {
                    _mNota   = _mNota.FindById(Id).FirstOrDefault <Model.Nota>();
                    _mPedido = _mPedido.FindById(_mNota.id_pedido).FirstOrDefault <Model.Pedido>();
                }
                else
                {
                    if (OpcoesNfeRapida.idPedido > 0)
                    {
                        _mNota.Id        = 0;
                        _mNota.id_pedido = OpcoesNfeRapida.idPedido;
                        _mNota.Tipo      = "NFe";
                        _mNota.Status    = "Pendente";
                        _mNota.Save(_mNota, false);
                        Id = _mNota.GetLastId();
                    }
                    else
                    {
                        _mPedido.Id   = 0;
                        _mPedido.Tipo = "NFe";
                        _mPedido.Save(_mPedido);

                        _mNota.Id        = 0;
                        _mNota.id_pedido = _mPedido.GetLastId();
                        _mNota.Tipo      = "NFe";
                        _mNota.Status    = "Pendente";
                        _mNota.Save(_mNota, false);
                        Id = _mNota.GetLastId();
                    }
                }

                OpenForm.ShowInPanel <TelasNota.TelaDados>(panelTelas);
            };

            FormClosing += (s, e) =>
            {
                OpcoesNfeRapida.idPedido = 0;

                _mNota = new Model.Nota().FindById(Id).FirstOrDefault <Model.Nota>();

                if (_mNota == null)
                {
                    Close();
                }

                if (_mPedido != null)
                {
                    if (_mNota.id_pedido > 0)
                    {
                        _mPedido = _mPedido.FindById(_mNota.id_pedido).FirstOrDefault <Model.Pedido>();
                    }
                }

                if (_mNota.Status == "Pendente")
                {
                    if (!TelaDados.telaDados)
                    {
                        var result = AlertOptions.Message("Atenção!", "Você está prestes a excluir! Deseja continuar?", AlertBig.AlertType.warning, AlertBig.AlertBtn.YesNo);
                        if (result)
                        {
                            //if (Id > 0)
                            //{
                            //    _mPedido.Excluir = 1;
                            //    if (_mPedido.Save(_mPedido))
                            //    {
                            //        _mNota.Excluir = 1;
                            //        _mNota.Save(_mNota, false);
                            //    }

                            //    TelaDados.telaDados = true;
                            //    Close();
                            //}

                            if (_mPedido != null)
                            {
                                if (_mPedido.Tipo == "NFe")
                                {
                                    _mPedido.Excluir = 1;
                                    _mPedido.Save(_mPedido);
                                }
                            }

                            if (_mNota != null)
                            {
                                _mNota.Excluir   = 1;
                                _mNota.id_pedido = 0;
                                _mNota.Save(_mNota, false);
                            }
                        }
                    }
                }
            };
        }
Exemplo n.º 6
0
        private void Eventos()
        {
            KeyDown   += KeyDowns;
            KeyPreview = true;

            Load += (s, e) =>
            {
                Filter();

                dataInicial.Text = Validation.DateNowToSql();
                dataFinal.Text   = Validation.DateNowToSql();
            };

            btnAdicionar.Click    += (s, e) => Edit(true);
            btnEditar.Click       += (s, e) => Edit();
            GridLista.DoubleClick += (s, e) => Edit();
            btnExit.Click         += (s, e) => Close();

            dataInicial.ValueChanged    += (s, e) => Filter();
            dataFinal.ValueChanged      += (s, e) => Filter();
            status.SelectedValueChanged += (s, e) => Filter();

            btnHelp.Click += (s, e) => Support.OpenLinkBrowser(Configs.LinkAjuda);

            btnRetransmitir.Click += (s, e) =>
            {
                if (p1 == 0)
                {
                    p1 = 1;
                    WorkerBackground.RunWorkerAsync();
                }
            };

            btnRemover.Click += (s, e) =>
            {
                Model.Nota _nota = new Model.Nota();
                _nota = _nota.Query().Where("status", "Transmitindo...").Where("excluir", 0).First <Model.Nota>();

                if (_nota != null)
                {
                    Alert.Message("Ação não permitida", "Exclusão não realizada", Alert.AlertType.warning);
                    return;
                }

                var result = AlertOptions.Message("Atenção!", "Você está prestes a deletar, deseja continuar?", AlertBig.AlertType.warning, AlertBig.AlertBtn.YesNo);
                if (result)
                {
                    _nota.Excluir = 1;
                    _nota.Save(_nota);

                    Filter();
                }
            };

            WorkerBackground.RunWorkerAsync();

            //imprimir.Click += async (s, e) => await RenderizarAsync();

            using (var b = WorkerBackground)
            {
                b.DoWork += async(s, e) =>
                {
                    _msg = new Controller.Fiscal().EmitirInutiliza();
                };

                b.RunWorkerCompleted += async(s, e) =>
                {
                    p1 = 0;

                    if (String.IsNullOrEmpty(_msg))
                    {
                        return;
                    }
                    else if (_msg.Contains("Inutilização de número homologado"))
                    {
                        Alert.Message("Tudo certo!", "Inutilização de número homologado", Alert.AlertType.success);//AlertOptions.Message("Tudo certo!", "Carta de correção autorizada", AlertBig.AlertType.success, AlertBig.AlertBtn.OK);
                    }
                    else
                    {
                        Alert.Message("Opss", _msg, Alert.AlertType.error);//AlertOptions.Message("Opss", _msg, AlertBig.AlertType.error, AlertBig.AlertBtn.OK);
                    }
                    Filter();
                };
            }
        }
Exemplo n.º 7
0
        private void Eventos()
        {
            KeyDown   += KeyDowns;
            KeyPreview = true;

            Load += (s, e) =>
            {
                DataTableStart();
            };

            //GridLista.DoubleClick += (s, e) => MessageBox.Show("");

            btnHelp.Click += (s, e) => Support.OpenLinkBrowser(Configs.LinkAjuda);

            btnAdicionar.Click += (s, e) =>
            {
                Model.Nota _notaCCe = new Model.Nota();
                //_notaCCe = _notaCCe.Query().Where("status", "Transmitindo...").Where("id", idNota).Where("excluir", 0).FirstOrDefault<Model.Nota>();
                _notaCCe = _notaCCe.Query().Where("status", "Transmitindo...").Where("id_pedido", idPedido).Where("excluir", 0).FirstOrDefault <Model.Nota>();

                if (_notaCCe != null)
                {
                    Alert.Message("Ação não permitida", "Existe outra CCe transmitindo", Alert.AlertType.warning);
                    return;
                }

                CartaCorrecaoAdd f = new CartaCorrecaoAdd();
                f.TopMost = true;
                if (f.ShowDialog() == DialogResult.OK)
                {
                    p1 = 1;
                    WorkerBackground2.RunWorkerAsync();
                }
            };

            btnRetransmitir.Click += (s, e) =>
            {
                //validação de registro com status Transmitindo...
                p1 = 1;
                WorkerBackground2.RunWorkerAsync();
            };

            imprimir.Click += (s, e) =>
            {
                imprimir.Text = "Imprimindo...";
                p1            = 2;
                WorkerBackground2.RunWorkerAsync();
            };

            btnRemover.Click += (s, e) =>
            {
                Model.Nota _notaCCe = new Model.Nota();
                _notaCCe = _notaCCe.Query().Where("id", Convert.ToInt32(GridLista.SelectedRows[0].Cells["ID"].Value)).Where("excluir", 0).First <Model.Nota>();

                if (_notaCCe.Status != "Transmitindo...")
                {
                    Alert.Message("Ação não permitida", "Exclusão não realizada", Alert.AlertType.warning);
                    return;
                }

                var result = AlertOptions.Message("Atenção!", "Você está prestes a deletar uma carta de correção, continuar?", AlertBig.AlertType.warning, AlertBig.AlertBtn.YesNo);
                if (result)
                {
                    _notaCCe.Excluir = 1;
                    _notaCCe.Save(_notaCCe);

                    DataTableStart();
                }
            };

            GridLista.CellFormatting += (s, e) =>
            {
            };

            using (var b = WorkerBackground)
            {
                b.DoWork += async(s, e) =>
                {
                    dataTable = await _cNota.GetDataTable(idPedido, idNota);
                };

                b.RunWorkerCompleted += async(s, e) =>
                {
                    await _cNota.SetTable(GridLista, idPedido, idNota);
                };
            }

            using (var b = WorkerBackground2)
            {
                b.DoWork += async(s, e) =>
                {
                    switch (p1)
                    {
                    case 1:
                        _msg = new Controller.Fiscal().EmitirCCe(idPedido, idNota);
                        break;

                    case 2:
                        var msg = new Controller.Fiscal().ImprimirCCe(idPedido, idNota);
                        if (!msg.Contains(".pdf"))
                        {
                            _msg = msg;
                        }
                        break;
                    }
                };

                b.RunWorkerCompleted += async(s, e) =>
                {
                    switch (p1)
                    {
                    case 1:

                        if (_msg.Contains("AUTORIZADA"))
                        {
                            //Alert.Message("Tudo certo!", "Carta de correção autorizada", Alert.AlertType.success);//AlertOptions.Message("Tudo certo!", "Carta de correção autorizada", AlertBig.AlertType.success, AlertBig.AlertBtn.OK);
                            //MessageBox.Show("Carta de correção autorizada");
                            retorno.Text = "Carta de correção autorizada";
                        }
                        else
                        {
                            //Alert.Message("Opss", _msg, Alert.AlertType.error);
                            //AlertOptions.Message("Opss", _msg, AlertBig.AlertType.error, AlertBig.AlertBtn.OK);
                            //MessageBox.Show(_msg);
                            retorno.Text = _msg;
                        }

                        break;

                    case 2:
                        imprimir.Text = "Imprimir";
                        break;
                    }

                    DataTableStart();

                    p1 = 0;
                };
            }
        }
Exemplo n.º 8
0
        private void Eventos()
        {
            Masks.SetToUpper(this);

            Load += (s, e) =>
            {
                if (Id > 0)
                {
                    LoadData();
                }

                if (_mNota.Status != "Pendente")
                {
                    Nota.disableCampos = true;
                    DisableCampos();

                    progress5.Visible = false;
                    step5.Visible     = false;
                    label16.Visible   = false;
                    Apagar.Visible    = false;
                }
            };

            addNatureza.Click += (s, e) =>
            {
                AddNatureza f = new AddNatureza();
                f.btnSalvarText     = "Salvar e Inserir";
                f.btnSalvarWidth    = 150;
                f.btnSalvarLocation = 590;
                f.FormBorderStyle   = FormBorderStyle.FixedSingle;
                f.StartPosition     = FormStartPosition.CenterParent;
                f.TopMost           = true;
                if (f.ShowDialog() == DialogResult.OK)
                {
                    DialogResult = DialogResult.OK;
                    IdNatureza   = AddNatureza.idSelected;
                    LoadNatureza();
                }
            };

            Next.Click += (s, e) =>
            {
                if (Validate())
                {
                    return;
                }

                telaDados = true;

                #region CONFERE DADOS

                var dataAddrFirst = _mClienteAddr.Query().Where("id_pessoa", IdCliente).FirstOrDefault <Model.PessoaEndereco>();

                if (_mPedido.id_useraddress > 0)
                {
                    dataAddrFirst = new Model.PessoaEndereco().Query().Where("id", _mPedido.id_useraddress).FirstOrDefault <Model.PessoaEndereco>();
                }

                if (DetailsClient.IdAddress > 0)
                {
                    dataAddrFirst = new Model.PessoaEndereco().Query().Where("id", DetailsClient.IdAddress).FirstOrDefault <Model.PessoaEndereco>();
                }

                if (dataAddrFirst != null)
                {
                    if (String.IsNullOrEmpty(dataAddrFirst.Rua))
                    {
                        Alert.Message("Atenção!", "O endereço do destinatário não pode ser vazio. Acesse o cadastro do cliente para corrigir!", Alert.AlertType.warning);
                        return;
                    }

                    if (String.IsNullOrEmpty(dataAddrFirst.Cep))
                    {
                        Alert.Message("Atenção!", "O cep do destinatário não pode ser vazio. Acesse o cadastro do cliente para corrigir!", Alert.AlertType.warning);
                        return;
                    }

                    if (String.IsNullOrEmpty(dataAddrFirst.Bairro))
                    {
                        Alert.Message("Atenção!", "O bairro do destinatário não pode ser vazio. Acesse o cadastro do cliente para corrigir!", Alert.AlertType.warning);
                        return;
                    }

                    if (String.IsNullOrEmpty(dataAddrFirst.Cidade))
                    {
                        Alert.Message("Atenção!", "A cidade do destinatário não pode ser vazio. Acesse o cadastro do cliente para corrigir!", Alert.AlertType.warning);
                        return;
                    }

                    if (String.IsNullOrEmpty(dataAddrFirst.IBGE))
                    {
                        Alert.Message("Atenção!", "O código do municipio (IBGE) do destinatário não pode ser vazio. Acesse o cadastro do cliente para corrigir!", Alert.AlertType.warning);
                        return;
                    }
                }

                #endregion

                GetData();

                if (!Nota.disableCampos)
                {
                    _mPedido.Save(_mPedido);
                }

                OpenForm.Show <TelaProdutos>(this);
            };

            SelecionarCliente.Click += (s, e) =>
            {
                PedidoModalClientes form = new PedidoModalClientes();
                form.TopMost = true;
                if (form.ShowDialog() == DialogResult.OK)
                {
                    GetData();
                    _mPedido.Save(_mPedido);
                    LoadCliente();
                }
            };

            btnAddAddr.Click += (s, e) =>
            {
                if (_mPedido.Cliente > 0)
                {
                    DetailsClient.IdClient = _mPedido.Cliente;
                    DetailsClient form = new DetailsClient();
                    form.TopMost = true;
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        GetData();
                        _mPedido.Save(_mPedido);
                        LoadCliente();

                        var dataAddr = _mClienteAddr.FindById(_mPedido.id_useraddress).FirstOrDefault <Model.PessoaEndereco>();
                        if (dataAddr != null)
                        {
                            AddrInfo.Text = $"Rua: {dataAddr.Rua}, {dataAddr.Cep} - {dataAddr.Bairro} - {dataAddr.Cidade}/{dataAddr.Estado} - {dataAddr.Pais}";
                            IdAddr        = dataAddr.Id;
                        }

                        btnAddAddr.Text = "Selecionar outro Endereço.";
                    }
                }
                else
                {
                    Alert.Message("Opps", "Selecione um destinatário..", Alert.AlertType.info);
                }
            };

            Documentos.Click += (s, e) =>
            {
                DocumentosReferenciados form = new DocumentosReferenciados();
                form.TopMost = true;
                form.Show();
            };

            emissao.KeyPress += (s, e) => Masks.MaskBirthday(s, e);
            saida.KeyPress   += (s, e) => Masks.MaskBirthday(s, e);
            hora.KeyPress    += (s, e) => Masks.MaskHour(s, e);

            Apagar.Click += (s, e) =>
            {
                var result = AlertOptions.Message("Atenção!", "Você está prestes a excluir! Deseja continuar?", AlertBig.AlertType.warning, AlertBig.AlertBtn.YesNo);
                if (result)
                {
                    if (_mPedido != null)
                    {
                        if (_mPedido.Tipo == "NFe")
                        {
                            _mPedido.Excluir = 1;
                            _mPedido.Save(_mPedido);
                        }
                    }

                    if (_mNota != null)
                    {
                        _mNota.Excluir   = 1;
                        _mNota.id_pedido = 0;
                        _mNota.Save(_mNota, false);
                    }

                    telaDados = true;
                    Alert.Message("Pronto!", "Removido com sucesso!", Alert.AlertType.info);
                    Application.OpenForms["Nota"].Close();
                    Close();
                }
            };
        }
Exemplo n.º 9
0
        public void Eventos()
        {
            Load += (s, e) =>
            {
                var nota = new Model.Nota().FindById(idNota).FirstOrDefault <Model.Nota>();

                if (nota == null)
                {
                    return;
                }

                nsefaz.Text        = (!String.IsNullOrEmpty(nota.nr_Nota)) ? nota.nr_Nota : "";
                serie.Text         = (!String.IsNullOrEmpty(nota.Serie)) ? nota.Serie : "";
                status.Text        = (!String.IsNullOrEmpty(nota.Status)) ? nota.Status : "";
                chavedeacesso.Text = (!String.IsNullOrEmpty(nota.ChaveDeAcesso)) ? nota.ChaveDeAcesso : "";

                Emitir.Visible = false;
            };

            btnDetalhes.Click += (s, e) =>
            {
                //Nota.disableCampos = true;
                Nota.Id = idNota;
                Nota nota = new Nota();
                nota.TopMost = true;
                nota.ShowDialog();
            };

            Emitir.Click += (s, e) =>
            {
                //var checkNota = _modelNota.FindByIdPedido(idPedido).WhereNotNull("status").Where("nota.tipo", "NFe").FirstOrDefault();
                //var checkNota = _modelNota.FindByIdPedidoUltReg(idPedido, "", "NFe").FirstOrDefault<Model.Nota>();
                var checkNota = new Model.Nota().FindById(idNota).FirstOrDefault <Model.Nota>();
                if (checkNota == null)
                {
                    Model.Nota _modelNotaNova = new Model.Nota();

                    _modelNotaNova.Id        = 0;
                    _modelNotaNova.Tipo      = "NFe";
                    _modelNotaNova.Status    = "Pendente";
                    _modelNotaNova.id_pedido = idPedido;
                    _modelNotaNova.Save(_modelNotaNova, false);

                    checkNota = new Model.Nota().FindByIdPedidoUltReg(idPedido, "", "NFe").FirstOrDefault <Model.Nota>();
                }

                if (checkNota.Status == "Cancelada")
                {
                    if (Home.pedidoPage == "Notas")
                    {
                        Alert.Message("Atenção!", "Não é possível emitir uma nota Autorizada/Cancelada.", Alert.AlertType.warning);
                        return;
                    }

                    var result = AlertOptions.Message("Atenção!", "Existem registro(s) de nota(s) cancelada(s) a partir desta venda. Deseja gerar um nova nota?", AlertBig.AlertType.warning, AlertBig.AlertBtn.YesNo);
                    if (result)
                    {
                        Model.Nota _modelNotaNova = new Model.Nota();

                        _modelNotaNova.Id        = 0;
                        _modelNotaNova.Tipo      = "NFe";
                        _modelNotaNova.Status    = "Pendente";
                        _modelNotaNova.id_pedido = idPedido;
                        _modelNotaNova.Save(_modelNotaNova, false);

                        checkNota = new Model.Nota().FindByIdPedidoUltReg(idPedido, "", "NFe").FirstOrDefault <Model.Nota>();
                    }
                }

                if (checkNota.Status != "Pendente")
                {
                    Alert.Message("Atenção!", "Não é possível emitir uma nota Autorizada/Cancelada.", Alert.AlertType.warning);
                    return;
                }

                _modelNota = checkNota;

                retorno.Text = "Emitindo NF-e .......................................... (1/2)";

                if (p1 == 0)
                {
                    p1 = 1;
                    WorkerBackground.RunWorkerAsync();
                }
                else
                {
                    Alert.Message("Ação não permitida", "Aguarde processo finalizar", Alert.AlertType.warning);
                }
            };

            CartaCorrecao.Click += (s, e) =>
            {
                //var checkNota = new Model.Nota().FindByIdPedidoUltReg(idPedido, "", "NFe").FirstOrDefault<Model.Nota>();
                var checkNota = new Model.Nota().FindById(idNota).FirstOrDefault <Model.Nota>();
                if (checkNota == null || checkNota?.Status != "Autorizada")
                {
                    Alert.Message("Ação não permitida!", "Não é possível emitir uma Carta de Correção.", Alert.AlertType.warning);
                    return;
                }

                _modelNota = checkNota;

                CartaCorrecao cce = new CartaCorrecao();
                cce.TopMost = true;
                cce.Show();

                Application.OpenForms["OpcoesNfeRapida"].Close();
            };

            Cancelar.Click += (s, e) =>
            {
                //var checkNota = new Model.Nota().FindByIdPedidoUltReg(idPedido, "", "NFe").FirstOrDefault<Model.Nota>();
                var checkNota = new Model.Nota().FindById(idNota).FirstOrDefault <Model.Nota>();
                if (checkNota == null || checkNota?.Status != "Autorizada")
                {
                    Alert.Message("Ação não permitida!", "Não é possível cancelar uma nota Pendente/Cancelada.", Alert.AlertType.warning);
                    return;
                }

                _modelNota = checkNota;

                CartaCorrecaoAdd.tela = "Cancelar";
                CartaCorrecaoAdd f = new CartaCorrecaoAdd();
                f.TopMost = true;
                if (f.ShowDialog() == DialogResult.OK)
                {
                    CartaCorrecaoAdd.tela = "";
                    justificativa         = CartaCorrecaoAdd.justificativa;

                    retorno.Text = "Cancelando NF-e .......................................... (1/2)";

                    p1 = 4;
                    WorkerBackground.RunWorkerAsync();
                }
            };

            EnviarEmail.Click += (s, e) =>
            {
                //var checkNota = new Model.Nota().FindByIdPedidoUltReg(idPedido, "", "NFe").FirstOrDefault<Model.Nota>();
                var checkNota = new Model.Nota().FindById(idNota).FirstOrDefault <Model.Nota>();
                if (checkNota == null || checkNota?.Status == "Pendente")
                {
                    Alert.Message("Ação não permitida!", "Não é possível enviar uma nota Pendente.", Alert.AlertType.warning);
                    return;
                }

                _modelNota = checkNota;

                CartaCorrecaoAdd.tela   = "Email";
                CartaCorrecaoAdd.idNota = idNota;
                CartaCorrecaoAdd f = new CartaCorrecaoAdd();
                f.TopMost = true;
                if (f.ShowDialog() == DialogResult.OK)
                {
                    CartaCorrecaoAdd.tela = "";
                    justificativa         = CartaCorrecaoAdd.justificativa;

                    retorno.Text = "Enviando NF-e .......................................... (1/2)";

                    p1 = 5;
                    WorkerBackground.RunWorkerAsync();
                }
            };

            Imprimir.Click += (s, e) =>
            {
                var checkNota = new Model.Nota().FindByIdPedidoUltReg(idPedido, "", "NFe").FirstOrDefault <Model.Nota>();
                if (checkNota == null || checkNota?.Status == "Pendente")
                {
                    Alert.Message("Opps!", "Emita a nota para imprimir.", Alert.AlertType.warning);
                    return;
                }

                _modelNota = checkNota;

                retorno.Text = "Imprimindo NF-e .......................................... (1/2)";

                if (p1 == 0)
                {
                    p1 = 2;
                    WorkerBackground.RunWorkerAsync();
                }
                else
                {
                    Alert.Message("Ação não permitida", "Aguarde processo finalizar", Alert.AlertType.warning);
                }
            };

            using (var b = WorkerBackground)
            {
                b.DoWork += async(s, e) =>
                {
                    switch (p1)
                    {
                    case 1:

                        //_modelNota = _modelNota.FindByIdPedido(idPedido).FirstOrDefault<Model.Nota>();
                        //if (_modelNota == null)
                        //{
                        //    _modelNota.Id = 0;
                        //    _modelNota.id_pedido = idPedido;
                        //    _modelNota.Save(_modelNota);
                        //}

                        _msg = new Controller.Fiscal().Emitir(idPedido, "NFe", _modelNota.Id);
                        break;

                    case 2:

                        if (IniFile.Read("NFe", "APP") != "Uninfe")
                        {
                            var msg = new Controller.Fiscal().Imprimir(idPedido, "NFe", _modelNota.Id);
                            if (!msg.Contains(".pdf"))
                            {
                                _msg = msg;
                            }
                        }
                        else
                        {
                            EmissorImprimirDanfe();
                        }

                        break;

                    case 3:
                        //_msg = new Controller.Fiscal().EmitirCCe(idPedido, "Nota gerada com informacoes incorretas, por gentileza verificar as corretas");
                        break;

                    case 4:
                        if (justificativa.Length <= 15)
                        {
                            break;
                        }

                        _msg = new Controller.Fiscal().Cancelar(idPedido, "NFe", justificativa, _modelNota.Id);
                        break;

                    case 5:
                        _msg = new Controller.Fiscal().EnviarEmail(idPedido, justificativa, "NFe", _modelNota.Id);
                        break;
                    }
                };

                b.RunWorkerCompleted += async(s, e) =>
                {
                    p1 = 0;

                    if (!String.IsNullOrEmpty(_msg))
                    {
                        retorno.Text = _msg;
                    }
                };
            }

            FormClosing += (s, e) =>
            {
                OpcoesNfeRapida.idPedido = 0;
                OpcoesNfeRapida.idNota   = 0;
            };
        }