示例#1
0
        /// <summary>
        /// Adiciona os eventos de 'KeyDown' a todos os controls com a function KeyDowns
        /// </summary>
        private void KeyDowns(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
            case Keys.Up:
                GridListaProdutos.Focus();
                Support.UpDownDataGrid(false, GridListaProdutos);
                e.Handled = true;
                break;

            case Keys.Down:
                GridListaProdutos.Focus();
                Support.UpDownDataGrid(true, GridListaProdutos);
                e.Handled = true;
                break;

            case Keys.Escape:
                Close();
                break;

            case Keys.F1:
                AlterarModo();
                break;

            case Keys.F2:
                BuscarProduto.Focus();
                break;

            case Keys.F3:
                if (GridListaProdutos.SelectedRows.Count > 0)
                {
                    if (Validation.ConvertToInt32(GridListaProdutos.SelectedRows[0].Cells["ID"].Value) > 0)
                    {
                        var itemName = GridListaProdutos.SelectedRows[0].Cells["Descrição"].Value;

                        var result = AlertOptions.Message("Atenção!", $"Cancelar o item ('{itemName}') no pedido?", AlertBig.AlertType.warning, AlertBig.AlertBtn.YesNo);
                        if (result)
                        {
                            var idPedidoItem = Validation.ConvertToInt32(GridListaProdutos.SelectedRows[0].Cells["ID"].Value);

                            GridListaProdutos.Rows.RemoveAt(GridListaProdutos.SelectedRows[0].Index);

                            if (Home.pedidoPage != "Compras")
                            {
                                new Controller.Estoque(idPedidoItem, Home.pedidoPage, "Atalho F3 Cancelar").Add().Item();
                            }
                            else
                            {
                                new Controller.Estoque(idPedidoItem, Home.pedidoPage, "Atalho F3 Cancelar").Remove().Item();
                            }

                            _mPedidoItens.Remove(idPedidoItem);

                            LoadTotais();
                        }
                    }
                }
                break;
            }
        }
示例#2
0
        private void ClearEstoque()
        {
            if (dataGridVariacao.Rows.Count <= 0)
            {
                return;
            }

            var generateAlert = AlertOptions.Message("Atenção",
                                                     "Você está prestes a deletar todo o estoque de combinações, continuar?", AlertBig.AlertType.info,
                                                     AlertBig.AlertBtn.YesNo);

            if (!generateAlert)
            {
                return;
            }

            var checkEstoque = new ItemEstoque().FindAll().WhereFalse("excluir").Where("item", idProduto)
                               .Get <ItemEstoque>();

            if (checkEstoque.Any())
            {
                foreach (var data in checkEstoque)
                {
                    new ItemEstoque().Remove(data.Id);
                }
            }

            dataGridVariacao.Rows.Clear();
        }
示例#3
0
        public async Task AddAlert(AlertOptions alertOptions, string organizationID)
        {
            var users = RemotelyContext.Users
                        .Include(x => x.Alerts)
                        .Where(x => x.OrganizationID == organizationID);

            if (!string.IsNullOrWhiteSpace(alertOptions.AlertDeviceID))
            {
                var filteredUserIDs = FilterUsersByDevicePermission(users.Select(x => x.Id), alertOptions.AlertDeviceID);
                users = users.Where(x => filteredUserIDs.Contains(x.Id));
            }

            await users.ForEachAsync(x =>
            {
                var alert = new Alert()
                {
                    CreatedOn      = DateTimeOffset.Now,
                    DeviceID       = alertOptions.AlertDeviceID,
                    Message        = alertOptions.AlertMessage,
                    OrganizationID = organizationID
                };
                x.Alerts.Add(alert);
            });

            await RemotelyContext.SaveChangesAsync();
        }
示例#4
0
        public static void CreateAlertMessage(TcpClient client, Data data, AlertOptions alertOptions, string message)
        {
            Alert          alert = new Alert(alertOptions, message);
            MessageRequest messageRequestAlert = new MessageRequest(MessageKey.ALERT, alert);

            data.ClientsAlerts.AddNewAlert(client, messageRequestAlert);
        }
示例#5
0
        public async Task <IActionResult> Create(AlertOptions alertOptions)
        {
            Request.Headers.TryGetValue("OrganizationID", out var orgID);

            DataService.WriteEvent("Alert created.  Alert Options: " + JsonSerializer.Serialize(alertOptions), orgID);

            if (alertOptions.ShouldAlert)
            {
                try
                {
                    await DataService.AddAlert(alertOptions, orgID);
                }
                catch (Exception ex)
                {
                    DataService.WriteEvent(ex, orgID);
                }
            }

            if (alertOptions.ShouldEmail)
            {
                try
                {
                    await EmailSender.SendEmailAsync(alertOptions.EmailTo,
                                                     alertOptions.EmailSubject,
                                                     alertOptions.EmailBody,
                                                     orgID);
                }
                catch (Exception ex)
                {
                    DataService.WriteEvent(ex, orgID);
                }
            }

            if (alertOptions.ShouldSendApiRequest)
            {
                try
                {
                    var httpRequest = WebRequest.CreateHttp(alertOptions.ApiRequestUrl);
                    httpRequest.Method      = alertOptions.ApiRequestMethod;
                    httpRequest.ContentType = "application/json";
                    foreach (var header in alertOptions.ApiRequestHeaders)
                    {
                        httpRequest.Headers.Add(header.Key, header.Value);
                    }
                    using (var rs = httpRequest.GetRequestStream())
                        using (var sw = new StreamWriter(rs))
                        {
                            sw.Write(alertOptions.ApiRequestBody);
                        }
                    var response = (HttpWebResponse)httpRequest.GetResponse();
                    DataService.WriteEvent($"Alert API Response Status: {response.StatusCode}.", orgID);
                }
                catch (Exception ex)
                {
                    DataService.WriteEvent(ex, orgID);
                }
            }

            return(Ok());
        }
示例#6
0
        public void alert(string options)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                string[] args          = JSON.JsonHelper.Deserialize <string[]>(options);
                AlertOptions alertOpts = new AlertOptions();
                alertOpts.message      = args[0];
                alertOpts.title        = args[1];
                alertOpts.buttonLabel  = args[2];

                PhoneApplicationPage page = Page;
                if (page != null)
                {
                    Grid grid = page.FindName("LayoutRoot") as Grid;
                    if (grid != null)
                    {
                        notifBox = new NotificationBox();
                        notifBox.PageTitle.Text = alertOpts.title;
                        notifBox.SubTitle.Text  = alertOpts.message;
                        Button btnOK            = new Button();
                        btnOK.Content           = alertOpts.buttonLabel;
                        btnOK.Click            += new RoutedEventHandler(btnOK_Click);
                        btnOK.Tag = 1;
                        notifBox.ButtonPanel.Children.Add(btnOK);
                        grid.Children.Add(notifBox);
                        page.BackKeyPress += page_BackKeyPress;
                    }
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.INSTANTIATION_EXCEPTION));
                }
            });
        }
示例#7
0
        public void confirm(string options)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                AlertOptions alertOpts = JSON.JsonHelper.Deserialize <AlertOptions>(options);

                MessageBoxResult res = MessageBox.Show(alertOpts.message, alertOpts.title, MessageBoxButton.OKCancel);
                DispatchCommandResult(new PluginResult(PluginResult.Status.OK, (int)res));
            });
        }
示例#8
0
        public void confirm(string options)
        {
            string[]     args      = JSON.JsonHelper.Deserialize <string[]>(options);
            AlertOptions alertOpts = new AlertOptions();

            alertOpts.message     = args[0];
            alertOpts.title       = args[1];
            alertOpts.buttonLabel = args[2];
            string aliasCurrentCommandCallbackId = args[3];

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                PhoneApplicationPage page = Page;
                if (page != null)
                {
                    Grid grid = page.FindName("LayoutRoot") as Grid;
                    if (grid != null)
                    {
                        var previous  = notifyBox;
                        notifyBox     = new NotificationBox();
                        notifyBox.Tag = new NotifBoxData {
                            previous = previous, callbackId = aliasCurrentCommandCallbackId
                        };
                        notifyBox.PageTitle.Text = alertOpts.title;
                        notifyBox.SubTitle.Text  = alertOpts.message;

                        string[] labels = JSON.JsonHelper.Deserialize <string[]>(alertOpts.buttonLabel);

                        if (labels == null)
                        {
                            labels = alertOpts.buttonLabel.Split(',');
                        }

                        for (int n = 0; n < labels.Length; n++)
                        {
                            Button btn  = new Button();
                            btn.Content = labels[n];
                            btn.Tag     = n;
                            btn.Click  += new RoutedEventHandler(btnOK_Click);
                            notifyBox.ButtonPanel.Children.Add(btn);
                        }

                        grid.Children.Add(notifyBox);
                        if (previous == null)
                        {
                            page.BackKeyPress += page_BackKeyPress;
                        }
                    }
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.INSTANTIATION_EXCEPTION));
                }
            });
        }
示例#9
0
        public void AddDeviceAlert(string alertMessage)
        {
            var options = new AlertOptions()
            {
                AlertDeviceID = Device.ID,
                AlertMessage  = alertMessage,
                ShouldAlert   = true
            };

            DataService.AddAlert(options, Device.OrganizationID);
        }
示例#10
0
        private void Eventos()
        {
            Shown += (s, e) =>
            {
                if (File.Exists(Program.PATH_BASE + "\\logs\\EXCEPTIONS.txt"))
                {
                    erros.Text = File.ReadAllText(Program.PATH_BASE + "\\logs\\EXCEPTIONS.txt");
                }

                if (!string.IsNullOrEmpty(IniFile.Read("Remoto", "LOCAL")))
                {
                    ip.Text = IniFile.Read("Remoto", "LOCAL");
                }

                if (!string.IsNullOrEmpty(IniFile.Read("syncAuto", "APP")))
                {
                    syncAuto.Toggled = IniFile.Read("syncAuto", "APP") == "True";
                }
            };

            syncAuto.Click += (s, e) =>
            {
                IniFile.Write("syncAuto", syncAuto.Toggled ? "False" : "True", "APP");
            };

            AtualizaDb.Click += (s, e) =>
            {
                new CreateTables().CheckTables();

                Alert.Message("Pronto!", "Banco de dados atualizado com sucesso!", Alert.AlertType.success);
            };

            btnClearErroLog.Click += (s, e) =>
            {
                var result = AlertOptions.Message("Atenção!",
                                                  $"Você está prestes a limpar o log de erros.{Environment.NewLine}Deseja continuar?",
                                                  AlertBig.AlertType.info, AlertBig.AlertBtn.YesNo);
                if (result)
                {
                    File.Delete(Program.PATH_BASE + "\\logs\\EXCEPTIONS.txt");
                    erros.Text = "";
                }
            };

            ip.Leave += (s, e) => IniFile.Write("Remoto", ip.Text, "LOCAL");

            margemSincronizar.Click += (s, e) =>
            {
                margem();
            };

            btnExit.Click += (s, e) => Close();
        }
示例#11
0
        private void Eventos()
        {
            Masks.SetToUpper(this);

            Shown += (s, e) =>
            {
                if (Home.financeiroPage == "Pagar")
                {
                    label6.Text = @"Pagamentos";
                    label2.Text = @"Pagamentoss a serem editados:";
                    label3.Text = @"As alterações abaixo, será aplicado a todos os pagamentos listado acima.";

                    label23.Text         = @"Pagar para";
                    label8.Text          = @"Despesa";
                    visualGroupBox2.Text = @"Pagamento";
                    label9.Text          = @"Data Pagamento";
                    label10.Text         = @"Valor Pagamento";
                }

                Refresh();

                formaPgto.ValueMember   = "Id";
                formaPgto.DisplayMember = "Nome";
                formaPgto.DataSource    = new FormaPagamento().GetAll();

                LoadFornecedores();
                LoadCategorias();

                SetHeadersTable(GridLista);
                SetContentTable(GridLista);
            };

            btnSalvar.Click += (s, e) =>
            {
                var result = AlertOptions.Message("Atenção!", "Confirmar alterações?", AlertBig.AlertType.warning,
                                                  AlertBig.AlertBtn.YesNo);
                if (result)
                {
                    Save();
                }
            };

            dataRecebido.KeyPress += Masks.MaskBirthday;
            recebido.TextChanged  += (s, e) =>
            {
                var txt = (TextBox)s;
                Masks.MaskPrice(ref txt);
            };

            label6.Click  += (s, e) => Close();
            btnExit.Click += (s, e) => Close();
        }
示例#12
0
        /// <summary>
        ///     True para imprimir, false para não imprimir
        /// </summary>
        public void Concluir(bool imprimir = true)
        {
            if (Home.pedidoPage == "Vendas" && aPagartxt.Text != @"R$ 0,00")
            {
                Alert.Message("Ação não permitida", "É necessário informar recebimentos para finalizar",
                              Alert.AlertType.warning);

                return;
            }

            var pedido = _mPedido.FindById(idPedido).FirstOrDefault <Model.Pedido>();

            if (pedido != null)
            {
                pedido.Id     = idPedido;
                pedido.status = _controllerTitulo.GetLancados(idPedido) < pedido.Total ? 2 : 1;
                if (pedido.Save(pedido))
                {
                    AddPedidos.BtnFinalizado = true;
                }
            }

            if (Home.pedidoPage == "Compras")
            {
                imprimir = false;
                Application.OpenForms["AddPedidos"]?.Close();
                Close();
            }

            if (imprimir)
            {
                if (AlertOptions.Message("Impressão!", "Deseja imprimir?", AlertBig.AlertType.info,
                                         AlertBig.AlertBtn.YesNo, true))
                {
                    new Controller.Pedido().Imprimir(idPedido);
                }

                Application.OpenForms["AddPedidos"]?.Close();

                if (IniFile.Read("RetomarVenda", "Comercial") == "True")
                {
                    AddPedidos.Id = 0;
                    var reopen = new AddPedidos {
                        TopMost = true
                    };
                    reopen.Show();
                }

                DialogResult = DialogResult.OK;
                Application.OpenForms["PedidoPagamentos"]?.Close();
            }
        }
示例#13
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);
                };
            }
        }
示例#14
0
        public async Task AddAlert()
        {
            var options = new AlertOptions()
            {
                AlertDeviceID = TestData.Device1.ID,
                AlertMessage  = "Test Message",
                ShouldAlert   = true
            };
            await DataService.AddAlert(options, TestData.OrganizationID);

            var alerts = DataService.GetAlerts(TestData.Admin1.Id);

            Assert.AreEqual("Test Message", alerts.First().Message);
        }
示例#15
0
        public void CheckCaixaDate()
        {
            CheckCaixa();

            var caixa = new Model.Caixa().Query().Where("tipo", "Aberto").Where("usuario", Settings.Default.user_id)
                        .Where("criado", "<", Validation.ConvertDateToSql(DateTime.Now)).WhereFalse("excluir").FirstOrDefault();

            if (caixa != null)
            {
                Home.idCaixa = caixa.ID;

                var msg =
                    $"Antes de começar, há um caixa aberto do dia: {Validation.ConvertDateToForm(caixa.CRIADO)}. {Environment.NewLine}Deseja realizar o FECHAMENTO agora?";
                var Title = "Atenção!";

                var result = AlertOptions.Message(Title, msg, AlertBig.AlertType.warning, AlertBig.AlertBtn.YesNo);
                if (result)
                {
                    DetailsCaixa.idCaixa = Home.idCaixa;
                    using (var f = new DetailsCaixa())
                    {
                        f.ShowDialog();
                    }
                }
                else
                {
                    AlertOptions.Message("Atenção!",
                                         "Os recebimentos gerados a partir de vendas serão lançados no caixa aberto!",
                                         AlertBig.AlertType.info, AlertBig.AlertBtn.OK);
                }
            }

            var caixaAberto = new Model.Caixa().Query().Where("tipo", "Aberto")
                              .Where("usuario", Settings.Default.user_id).WhereFalse("excluir").FirstOrDefault();

            if (caixaAberto == null)
            {
                var result = AlertOptions.Message("Atenção!",
                                                  $"Você não possui um Caixa aberto.{Environment.NewLine} Deseja abrir agora?",
                                                  AlertBig.AlertType.info, AlertBig.AlertBtn.YesNo);
                if (result)
                {
                    using (var f = new AbrirCaixa())
                    {
                        f.ShowDialog();
                    }
                }
            }
        }
示例#16
0
        public static void AcceptAlert(IWebDriver driver, AlertOptions option)
        {
            bool alertPresent = IsAlertPresent(driver);

            if (alertPresent == true && option == AlertOptions.Accept)
            {
                IAlert alert = SeleniumExtras.WaitHelpers.ExpectedConditions.AlertIsPresent().Invoke(driver);
                alert.Accept();
            }

            if (alertPresent == true && option == AlertOptions.Dismiss)
            {
                IAlert alert = SeleniumExtras.WaitHelpers.ExpectedConditions.AlertIsPresent().Invoke(driver);
                alert.Dismiss();
            }
        }
示例#17
0
        //private void btnOK_Click(object sender, RoutedEventArgs e)
        //{
        //    Button btn = sender as Button;
        //    int retVal = 0;
        //    if (btn != null)
        //    {
        //        retVal = (int)btn.Tag + 1;
        //    }
        //    if (notifBox != null)
        //    {
        //        Page page = Page;
        //        if (page != null)
        //        {
        //            Grid grid = page.FindName("LayoutRoot") as Grid;
        //            if (grid != null)
        //            {
        //                grid.Children.Remove(notifBox);
        //            }
        //        }
        //        notifBox = null;
        //        var UserSetting = Windows.Storage.ApplicationData.Current.LocalSettings;
        //        UserSetting.Values["IsAlertVisible"] = "false";

        //    }
        //    DispatchCommandResult(new PluginResult(PluginResult.Status.OK, retVal));
        //}

        public async void confirm(string options)
        {
            string[]     args      = JSON.JsonHelper.Deserialize <string[]>(options);
            AlertOptions alertOpts = new AlertOptions();

            alertOpts.message     = args[0];
            alertOpts.title       = args[1];
            alertOpts.buttonLabel = args[2];
            string[] labels = alertOpts.buttonLabel.Split(',');

            MessageDialog md = new MessageDialog(alertOpts.message, alertOpts.title);

            md.Commands.Add(new UICommand(labels[0], OkHandler));
            md.Commands.Add(new UICommand(labels[1], CancelHandler));
            await md.ShowAsync();

            //Page page = Page;
            //if (page != null)
            //{
            //    Grid grid = page.FindName("LayoutRoot") as Grid;
            //    if (grid != null)
            //    {
            //        notifBox = new NotificationBox();
            //        notifBox.PageTitle.Text = alertOpts.title;
            //        notifBox.SubTitle.Text = alertOpts.message;

            //        string[] labels = alertOpts.buttonLabel.Split(',');
            //        for (int n = 0; n < labels.Length; n++)
            //        {
            //            Button btn = new Button();
            //            btn.Content = labels[n];
            //            btn.Tag = n;
            //            btn.Click += new RoutedEventHandler(btnOK_Click);
            //            notifBox.ButtonPanel.Children.Add(btn);
            //        }

            //        grid.Children.Add(notifBox);
            //        var UserSetting = Windows.Storage.ApplicationData.Current.LocalSettings;
            //        UserSetting.Values["IsAlertVisible"] = "true";

            //    }
            //}
            //else
            //{
            //    DispatchCommandResult(new PluginResult(PluginResult.Status.INSTANTIATION_EXCEPTION));
            //}
        }
示例#18
0
        /// <summary>
        ///     Eventos do form
        /// </summary>
        public void Eventos()
        {
            logs.Click += (s, e) =>
            {
                var f = new Cfesat_logs();
                Cfesat_logs.tipo = 0;
                f.ShowDialog();
            };

            consultarsat.Click += (s, e) =>
            {
                if (!File.Exists("Sat.Dll"))
                {
                    Alert.Message("Opps", "Não encontramos a DLL do SAT", Alert.AlertType.warning);
                    return;
                }

                AlertOptions.Message("Retorno", new Controller.Fiscal().Consulta(), AlertBig.AlertType.info,
                                     AlertBig.AlertBtn.OK);
            };

            consultarstatus.Click += (s, e) =>
            {
                var f = new Cfesat_logs();
                Cfesat_logs.tipo = 1;
                f.ShowDialog();
            };

            base64.Click += (s, e) =>
            {
                var f = new Cfesat_base64();
                f.ShowDialog();
            };

            xml.Click += (s, e) =>
            {
                checkXml();
            };

            servidor.Leave += (s, e) => IniFile.Write("Servidor", servidor.Text, "SAT");
            impressora.SelectedIndexChanged +=
                (s, e) => IniFile.Write("Printer", impressora.SelectedItem.ToString(), "SAT");
            serie.Leave += (s, e) => IniFile.Write("N_Serie", serie.Text, "SAT");

            btnExit.Click += (s, e) => Close();
        }
示例#19
0
        private void SaveItens()
        {
            if (Modelos.SelectedItem.ToString() == "Produtos")
            {
                List <Model.Item> values = File.ReadAllLines(PathCSV).Skip(1).Select(v => new Model.Item().FromCsv(v)).ToList();
                Count = values.Count();
            }
            else if (Modelos.SelectedItem.ToString() == "Clientes")
            {
                List <Model.Pessoa> values = File.ReadAllLines(PathCSV).Skip(1).Select(v => new Model.Pessoa().FromCsv(v)).ToList();
                Count = values.Count();
            }

            if (AlertOptions.Message("Pronto!", $"Importação feita com sucesso.\n{Count} itens importados!  ", AlertBig.AlertType.success, AlertBig.AlertBtn.OK))
            {
                Close();
            }
        }
示例#20
0
        void ReleaseDesignerOutlets()
        {
            if (ResultLabel != null)
            {
                ResultLabel.Dispose();
                ResultLabel = null;
            }

            if (AlertOptions != null)
            {
                AlertOptions.Dispose();
                AlertOptions = null;
            }

            if (ModalCounter != null)
            {
                ModalCounter.Dispose();
                ModalCounter = null;
            }
        }
示例#21
0
        private void Eventos()
        {
            Load += (s, e) =>
            {
                SetDataNota();
                SetTableProdutos();
                SetTableTitulos();
            };

            btnImportar.Click += (s, e) =>
            {
                WorkerBackground.RunWorkerAsync();
                Aguarde();
            };

            WorkerBackground.DoWork += (s, e) =>
            {
                AddProdutos();
                AddCompra();
            };

            WorkerBackground.RunWorkerCompleted += (s, e) =>
            {
                pictureBox4.Visible = false;
                btnImportar.Text    = @"Pronto";

                var Msg   = "Importação concluída com sucesso.";
                var Title = "Pronto!";

                var result = AlertOptions.Message(Title, Msg, AlertBig.AlertType.warning, AlertBig.AlertBtn.OK);
                if (!result)
                {
                    return;
                }

                Close();
                Application.OpenForms["ImportarNfe"]?.Close();
            };

            Back.Click += (s, e) => Close();
        }
示例#22
0
        /// <inheritdoc />
        public async Task <bool?> ShowConfirmationAsync(AlertOptions options)
        {
            await Task.Yield();

            var result = MessageBox.Show(options.Message, options.Title, MessageBoxButton.OKCancel, SelectImage(options.Type), MessageBoxResult.None);

            switch (result)
            {
            case MessageBoxResult.None:
                return(null);

            case MessageBoxResult.OK:
            case MessageBoxResult.Yes:
                return(true);

            case MessageBoxResult.No:
            case MessageBoxResult.Cancel:
                return(false);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#23
0
        public void confirm(string options)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                AlertOptions alertOpts = JSON.JsonHelper.Deserialize <AlertOptions>(options);

                PhoneApplicationPage page = Page;
                if (page != null)
                {
                    Grid grid = page.FindName("LayoutRoot") as Grid;
                    if (grid != null)
                    {
                        notifBox = new NotificationBox();
                        notifBox.PageTitle.Text = alertOpts.title;
                        notifBox.SubTitle.Text  = alertOpts.message;

                        string[] labels = alertOpts.buttonLabel.Split(',');
                        for (int n = 0; n < labels.Length; n++)
                        {
                            Button btn  = new Button();
                            btn.Content = labels[n];
                            btn.Tag     = n;
                            btn.Click  += new RoutedEventHandler(btnOK_Click);
                            notifBox.ButtonPanel.Children.Add(btn);
                        }

                        grid.Children.Add(notifBox);
                        page.BackKeyPress += page_BackKeyPress;
                    }
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.INSTANTIATION_EXCEPTION));
                }
            });
        }
示例#24
0
        public void confirm(string options)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
                AlertOptions alertOpts = new AlertOptions();
                alertOpts.message = args[0];
                alertOpts.title = args[1];
                alertOpts.buttonLabel = args[2];

                PhoneApplicationPage page = Page;
                if (page != null)
                {
                    Grid grid = page.FindName("LayoutRoot") as Grid;
                    if (grid != null)
                    {
                        var previous = notifyBox;
                        notifyBox = new NotificationBox();
                        notifyBox.Tag = previous;
                        notifyBox.PageTitle.Text = alertOpts.title;
                        notifyBox.SubTitle.Text = alertOpts.message;

                        string[] labels = alertOpts.buttonLabel.Split(',');
                        for (int n = 0; n < labels.Length; n++)
                        {
                            Button btn = new Button();
                            btn.Content = labels[n];
                            btn.Tag = n;
                            btn.Click += new RoutedEventHandler(btnOK_Click);
                            notifyBox.ButtonPanel.Children.Add(btn);
                        }

                        grid.Children.Add(notifyBox);
                        if (previous == null)
                        {
                            page.BackKeyPress += page_BackKeyPress;
                        }
                    }
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.INSTANTIATION_EXCEPTION));
                }
            });
        }
        public void alert(string options)
        {
            string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
            AlertOptions alertOpts = new AlertOptions();
            alertOpts.message = args[0];
            alertOpts.title = args[1];
            alertOpts.buttonLabel = args[2];
            string aliasCurrentCommandCallbackId = args[3];

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                PhoneApplicationPage page = Page;
                if (page != null)
                {
                    Grid grid = page.FindName("LayoutRoot") as Grid;
                    if (grid != null)
                    {
                        var previous = notifyBox;
                        notifyBox = new NotificationBox();
                        notifyBox.Tag = new { previous = previous, callbackId = aliasCurrentCommandCallbackId };
                        notifyBox.PageTitle.Text = alertOpts.title;
                        notifyBox.SubTitle.Text = alertOpts.message;
                        Button btnOK = new Button();
                        btnOK.Content = alertOpts.buttonLabel;
                        btnOK.Click += new RoutedEventHandler(btnOK_Click);
                        btnOK.Tag = 1;
                        notifyBox.ButtonPanel.Children.Add(btnOK);
                        grid.Children.Add(notifyBox);

                        if (previous == null)
                        {
                            page.BackKeyPress += page_BackKeyPress;
                        }
                    }
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.INSTANTIATION_EXCEPTION));
                }
            });
        }
示例#26
0
        private void Eventos()
        {
            KeyDown   += KeyDowns;
            KeyPreview = true;
            Masks.SetToUpper(this);

            Shown += (s, e) =>
            {
                ToolHelp.Show("Descreva seu serviço... Lembre-se de utilizar as características do serviço.",
                              pictureBox5, ToolHelp.ToolTipIcon.Info, "Ajuda!");

                if (idSelecionado > 0)
                {
                    LoadData();
                }
                else
                {
                    _modelItem = new Model.Item
                    {
                        Tipo = "Serviços",
                        Id   = 0
                    };
                    if (_modelItem.Save(_modelItem, false))
                    {
                        idSelecionado = _modelItem.GetLastId();
                        LoadData();
                    }
                    else
                    {
                        Alert.Message("Opss", "Erro ao criar.", Alert.AlertType.error);
                        Close();
                    }
                }

                Refresh();
            };

            label6.Click  += (s, e) => Close();
            btnExit.Click += (s, e) =>
            {
                var dataProd = _modelItem.Query().Where("id", idSelecionado)
                               .Where("atualizado", "01.01.0001, 00:00:00.000").FirstOrDefault();
                if (dataProd != null)
                {
                    var result = AlertOptions.Message("Atenção!", "Esse serviço não foi editado, deseja deletar?",
                                                      AlertBig.AlertType.info, AlertBig.AlertBtn.YesNo);
                    if (result)
                    {
                        var data = _modelItem.Remove(idSelecionado);
                        if (data)
                        {
                            Close();
                        }
                    }

                    nome.Focus();
                }

                Close();
            };

            btnSalvar.Click  += (s, e) => Save();
            btnRemover.Click += (s, e) =>
            {
                var result = AlertOptions.Message("Atenção!", "Você está prestes a deletar um serviço, continuar?",
                                                  AlertBig.AlertType.warning, AlertBig.AlertBtn.YesNo);
                if (!result)
                {
                    return;
                }

                var data = _modelItem.Remove(idSelecionado);
                if (data)
                {
                    Close();
                }
            };

            valorcompra.TextChanged += (s, e) =>
            {
                var txt = (TextBox)s;
                Masks.MaskPrice(ref txt);
            };

            valorvenda.TextChanged += (s, e) =>
            {
                var txt = (TextBox)s;
                Masks.MaskPrice(ref txt);
            };

            nome.KeyPress += (s, e) => Masks.MaskMaxLength(s, e, 100);

            btnHelp.Click += (s, e) => Support.OpenLinkBrowser(Configs.LinkAjuda);
        }
示例#27
0
 public static MvcHtmlString PopupAlert(this HtmlHelper html, AlertOptions options)
 {
     return(html.Partial("_PopupAlert", options));
 }
示例#28
0
        private void Eventos()
        {
            email.KeyDown    += KeyDowns;
            password.KeyDown += KeyDowns;

            Load += (s, e) =>
            {
                version.Text = @"Versão " + IniFile.Read("Version", "APP");

                if (Support.CheckForInternetConnection())
                {
                    var update = new Update();
                    update.CheckUpdate();
                    update.CheckIni();

                    if (Data.Core.Update.AtualizacaoDisponivel)
                    {
                        btnUpdate.Visible = true;
                        btnUpdate.Text    = $@"Atualizar Versão {update.GetVersionWebTxt()}";
                        label5.Visible    = false;
                        email.Visible     = false;
                        label6.Visible    = false;
                        password.Visible  = false;
                        btnEntrar.Visible = false;
                        label1.Text       = @"Antes de continuar..";
                    }
                    else
                    {
                        btnUpdate.Visible = false;
                        label5.Visible    = true;
                        email.Visible     = true;
                        label6.Visible    = true;
                        password.Visible  = true;
                        btnEntrar.Visible = true;
                        label1.Text       = @"Entre com sua conta";
                    }
                }

                // Valida a resolução do monitor e exibe uma mensagem
                Resolution.ValidateResolution();

                // Verifica se existe uma empresa vinculada a instalação da aplicação
                if (string.IsNullOrEmpty(IniFile.Read("idEmpresa", "APP")))
                {
                    panelEmpresa.Visible = true;
                    panelEmpresa.Dock    = DockStyle.Fill;
                }

                InitData();
            };

            btnEntrar.Click += (s, e) => LoginAsync();

            btnUpdate.Click += (s, e) =>
            {
                if (!Support.CheckForInternetConnection())
                {
                    AlertOptions.Message("Atenção!", "Você precisa estar conectado a internet para atualizar.",
                                         AlertBig.AlertType.info, AlertBig.AlertBtn.OK);
                    return;
                }

                var result = AlertOptions.Message("Atenção!", "Deseja iniciar o processo de atualização?",
                                                  AlertBig.AlertType.info, AlertBig.AlertBtn.YesNo);
                if (result)
                {
                    IniFile.Write("Update", "true", "APP");

                    if (File.Exists($"{Support.BasePath()}\\Update\\InstalarEmiplus.exe"))
                    {
                        File.Delete($"{Support.BasePath()}\\Update\\InstalarEmiplus.exe");
                    }

                    if (!Directory.Exists($"{Support.BasePath()}\\Update"))
                    {
                        Directory.CreateDirectory($"{Support.BasePath()}\\Update");
                    }

                    using (var d = new WebClient())
                    {
                        d.DownloadFile("https://github.com/lmassi25/files/releases/download/Install/InstallEmiplus.exe",
                                       $"{Support.BasePath()}\\Update\\InstalarEmiplus.exe");
                    }

                    if (!File.Exists($"{Support.BasePath()}\\Update\\InstalarEmiplus.exe"))
                    {
                        Alert.Message("Oopss",
                                      "Não foi possível iniciar a atualização. Verifique a conexão com a internet.",
                                      Alert.AlertType.error);
                    }

                    Process.Start($"{Support.BasePath()}\\Update\\InstalarEmiplus.exe");
                    Validation.KillEmiplus();
                }
            };

            btnConfirmar.Click += (s, e) =>
            {
                var id_empresa = idEmpresa.Text;

                if (id_empresa.Length < 36)
                {
                    Alert.Message("Opps", "ID da empresa está incorreto! Por favor insira um ID válido.",
                                  Alert.AlertType.error);
                    return;
                }

                if (Support.CheckForInternetConnection())
                {
                    dynamic objt = new
                    {
                        token = Program.TOKEN, id_empresa
                    };

                    var validar = new RequestApi().URL(Program.URL_BASE + "/api/validarempresa")
                                  .Content(objt, Method.POST).Response();

                    if (validar["error"] == "true")
                    {
                        Alert.Message("Opps", "O ID da empresa informado não existe.", Alert.AlertType.error);
                        return;
                    }

                    IniFile.Write("idEmpresa", id_empresa, "APP");
                    panelEmpresa.Visible = false;
                }
                else
                {
                    Alert.Message("Opps", "Você precisa estar conectado a internet para continuar.",
                                  Alert.AlertType.error);
                }
            };

            FormClosed        += (s, e) => Validation.KillEmiplus();
            btnFechar.Click   += (s, e) => Close();
            linkRecover.Click += (s, e) => Support.OpenLinkBrowser(Program.URL_BASE + "/admin/forgotten");
            linkSupport.Click += (s, e) => Support.OpenLinkBrowser(Configs.LinkAjuda);
        }
示例#29
0
        private void Eventos()
        {
            KeyDown   += KeyDowns;
            KeyPreview = true;
            Masks.SetToUpper(this);

            Shown += (s, e) =>
            {
                SetHeadersTable(GridLista);

                if (Id == 0)
                {
                    txtVariacao.Visible    = false;
                    btnAddVariacao.Visible = false;
                    GridLista.Visible      = false;
                }

                if (Id <= 0)
                {
                    return;
                }

                var grupo = new ItemGrupo().FindAll().WhereFalse("excluir").Where("id", Id).FirstOrDefault <ItemGrupo>();
                if (grupo == null)
                {
                    return;
                }

                txtGrupo.Text = grupo.Title;

                txtVariacao.Visible    = true;
                btnAddVariacao.Visible = true;
                GridLista.Visible      = true;

                // Carrega os atributos
                LoadData(GridLista);
            };

            btnSalvarGrupo.Click += (s, e) =>
            {
                if (string.IsNullOrEmpty(txtGrupo.Text))
                {
                    Alert.Message("Opps", "O título do grupo não pode ficar vazio.", Alert.AlertType.error);
                    return;
                }

                var grupoCheck = new ItemGrupo().FindAll().WhereFalse("excluir").Where("title", txtGrupo.Text)
                                 .FirstOrDefault <ItemGrupo>();
                if (grupoCheck != null)
                {
                    Alert.Message("Opps", "Já existe um grupo com esse título.", Alert.AlertType.error);
                    return;
                }

                var grupo = new ItemGrupo
                {
                    Id    = Id,
                    Title = txtGrupo.Text
                };
                if (!grupo.Save(grupo))
                {
                    return;
                }

                Id = grupo.GetLastId();
                txtVariacao.Visible    = true;
                btnAddVariacao.Visible = true;
                GridLista.Visible      = true;
            };

            btnAddVariacao.Click += (s, e) =>
            {
                if (string.IsNullOrEmpty(txtVariacao.Text))
                {
                    Alert.Message("Opps", "O título da variação não pode ficar vazio.", Alert.AlertType.error);
                    return;
                }

                if (Id == 0)
                {
                    Alert.Message("Opps", "Você deve adicionar um grupo antes.", Alert.AlertType.error);
                    return;
                }

                var attrCheck = new ItemAtributos().FindAll().WhereFalse("excluir").Where("atributo", txtVariacao.Text)
                                .Where("grupo", Id).FirstOrDefault <ItemAtributos>();
                if (attrCheck != null)
                {
                    Alert.Message("Opps", "Já existe um atributo com esse título.", Alert.AlertType.error);
                    return;
                }

                var add = new ItemAtributos
                {
                    Grupo    = Id,
                    Atributo = txtVariacao.Text
                };
                if (!add.Save(add))
                {
                    return;
                }

                txtVariacao.Clear();

                // Carrega os atributos
                LoadData(GridLista);
            };

            btnDelete.Click += (s, e) =>
            {
                ListAtributos.Clear();
                foreach (DataGridViewRow item in GridLista.Rows)
                {
                    if ((bool)item.Cells["Selecione"].Value)
                    {
                        ListAtributos.Add(Validation.ConvertToInt32(item.Cells["ID"].Value));
                    }
                }

                var result = AlertOptions.Message("Atenção!",
                                                  "Você está prestes a deletar os ATRIBUTOS selecionados, continuar?", AlertBig.AlertType.warning,
                                                  AlertBig.AlertBtn.YesNo);
                if (result)
                {
                    foreach (var attr in ListAtributos)
                    {
                        new ItemAtributos().Remove(attr);
                    }

                    LoadData(GridLista);
                }

                btnDelete.Visible = false;
            };

            GridLista.CellClick += (s, e) =>
            {
                if (GridLista.Columns[e.ColumnIndex].Name == "Selecione")
                {
                    if ((bool)GridLista.SelectedRows[0].Cells["Selecione"].Value == false)
                    {
                        GridLista.SelectedRows[0].Cells["Selecione"].Value = true;
                        btnDelete.Visible = true;
                    }
                    else
                    {
                        GridLista.SelectedRows[0].Cells["Selecione"].Value = false;

                        var hideBtns = false;
                        foreach (DataGridViewRow item in GridLista.Rows)
                        {
                            if ((bool)item.Cells["Selecione"].Value)
                            {
                                hideBtns = true;
                            }
                        }

                        btnDelete.Visible = hideBtns;
                    }
                }
            };

            GridLista.CellMouseEnter += (s, e) =>
            {
                if (e.ColumnIndex < 0 || e.RowIndex < 0)
                {
                    return;
                }

                var dataGridView = s as DataGridView;
                if (GridLista.Columns[e.ColumnIndex].Name == "Selecione")
                {
                    dataGridView.Cursor = Cursors.Hand;
                }
            };

            GridLista.CellMouseLeave += (s, e) =>
            {
                if (e.ColumnIndex < 0 || e.RowIndex < 0)
                {
                    return;
                }

                var dataGridView = s as DataGridView;
                if (GridLista.Columns[e.ColumnIndex].Name == "Selecione")
                {
                    dataGridView.Cursor = Cursors.Default;
                }
            };

            btnVoltar.Click += (s, e) =>
            {
                DialogResult = DialogResult.OK;
                Close();
            };
        }
示例#30
0
        private void Eventos()
        {
            KeyDown   += KeyDowns;
            KeyPreview = true;
            Masks.SetToUpper(this);

            Shown += (s, e) =>
            {
                Refresh();

                BeginInvoke((MethodInvoker) delegate
                {
                    IdPdtSelecionado = Produtos.IdPdtSelecionado;
                    backOn.RunWorkerAsync();
                });

                SetHeadersAdicionais(GridAdicionais);
                SetHeadersCombo(GridCombos);
                nome.Focus();
            };

            menuEstoque.Click  += (s, e) => Support.DynamicPanel(flowLayoutPanel, panelEstoque, menuEstoque);
            label27.Click      += (s, e) => Support.DynamicPanel(flowLayoutPanel, panelEstoque, menuEstoque);
            pictureBox12.Click += (s, e) => Support.DynamicPanel(flowLayoutPanel, panelEstoque, menuEstoque);

            menuImpostos.Click += (s, e) => Support.DynamicPanel(flowLayoutPanel, panelImpostos, menuImpostos);
            label35.Click      += (s, e) => Support.DynamicPanel(flowLayoutPanel, panelImpostos, menuImpostos);
            pictureBox16.Click += (s, e) => Support.DynamicPanel(flowLayoutPanel, panelImpostos, menuImpostos);

            menuAdicionais.Click += (s, e) => Support.DynamicPanel(flowLayoutPanel, panelAdicionais, menuAdicionais);
            label30.Click        += (s, e) => Support.DynamicPanel(flowLayoutPanel, panelAdicionais, menuAdicionais);
            pictureBox13.Click   += (s, e) => Support.DynamicPanel(flowLayoutPanel, panelAdicionais, menuAdicionais);

            menuCombo.Click    += (s, e) => Support.DynamicPanel(flowLayoutPanel, panelCombo, menuCombo);
            label33.Click      += (s, e) => Support.DynamicPanel(flowLayoutPanel, panelCombo, menuCombo);
            pictureBox17.Click += (s, e) => Support.DynamicPanel(flowLayoutPanel, panelCombo, menuCombo);

            menuInfoAdicionais.Click += (s, e) => Support.DynamicPanel(flowLayoutPanel, panelInfoAdicionais, menuInfoAdicionais);
            label31.Click            += (s, e) => Support.DynamicPanel(flowLayoutPanel, panelInfoAdicionais, menuInfoAdicionais);
            pictureBox15.Click       += (s, e) => Support.DynamicPanel(flowLayoutPanel, panelInfoAdicionais, menuInfoAdicionais);

            btnExit.Click += (s, e) =>
            {
                var dataProd = _modelItem.Query().Where("id", IdPdtSelecionado)
                               .Where("atualizado", "01.01.0001, 00:00:00.000").WhereNull("codebarras").FirstOrDefault();
                if (dataProd != null)
                {
                    var result = AlertOptions.Message("Atenção!", "Esse produto não foi editado, deseja deletar?",
                                                      AlertBig.AlertType.info, AlertBig.AlertBtn.YesNo);
                    if (result)
                    {
                        var data = _modelItem.Remove(IdPdtSelecionado, false);
                        if (data)
                        {
                            Close();
                        }
                    }

                    nome.Focus();
                    return;
                }

                Close();
            };

            btnSalvar.Click += (s, e) => Save();

            btnRemover.Click += (s, e) =>
            {
                var result = AlertOptions.Message("Atenção!", "Você está prestes a deletar um produto, continuar?",
                                                  AlertBig.AlertType.warning, AlertBig.AlertBtn.YesNo);
                if (result)
                {
                    var data = _modelItem.Remove(IdPdtSelecionado);
                    if (data)
                    {
                        Close();
                    }
                }
            };

            btnEstoque.Click += (s, e) =>
            {
                _modelItem.Nome = nome.Text;
                if (new Model.Item().ValidarDados(_modelItem))
                {
                    return;
                }

                var f = new AddEstoque {
                    TopMost = true
                };
                if (f.ShowDialog() == DialogResult.OK)
                {
                    LoadEstoque();

                    estoqueminimo.Focus();
                    DataTableEstoque();
                }
            };

            valorcompra.TextChanged += (s, e) =>
            {
                var txt = (TextBox)s;
                Masks.MaskPrice(ref txt);
            };

            valorvenda.TextChanged += (s, e) =>
            {
                var txt = (TextBox)s;
                Masks.MaskPrice(ref txt);
            };

            txtLimiteDesconto.TextChanged += (s, e) =>
            {
                var txt = (TextBox)s;
                Masks.MaskPrice(ref txt);
            };

            btnAddCategoria.Click += (s, e) =>
            {
                Home.CategoriaPage = "Produtos";
                var f = new AddCategorias
                {
                    FormBorderStyle = FormBorderStyle.FixedSingle,
                    StartPosition   = FormStartPosition.CenterScreen,
                    TopMost         = true
                };
                if (f.ShowDialog() == DialogResult.OK)
                {
                    Categorias.DataSource = new Categoria().GetAll("Produtos");
                    Categorias.Refresh();
                }
            };

            btnAddFornecedor.Click += (s, e) =>
            {
                Home.pessoaPage = "Fornecedores";
                AddClientes.Id  = 0;
                var f = new AddClientes
                {
                    FormBorderStyle = FormBorderStyle.FixedSingle,
                    StartPosition   = FormStartPosition.CenterScreen,
                    TopMost         = true
                };
                if (f.ShowDialog() == DialogResult.OK)
                {
                    LoadFornecedores();
                }
            };

            btnAddImpostoOne.Click += (s, e) =>
            {
                View.Produtos.Impostos.idImpSelected = 0;
                var f = new AddImpostos
                {
                    FormBorderStyle = FormBorderStyle.FixedSingle,
                    StartPosition   = FormStartPosition.CenterScreen,
                    TopMost         = true
                };
                if (f.ShowDialog() == DialogResult.OK)
                {
                    LoadImpostoOne();
                    LoadImpostoTwo();
                }
            };

            btnAddImpostoTwo.Click += (s, e) =>
            {
                View.Produtos.Impostos.idImpSelected = 0;
                var f = new AddImpostos
                {
                    FormBorderStyle = FormBorderStyle.FixedSingle,
                    StartPosition   = FormStartPosition.CenterScreen,
                    TopMost         = true
                };
                if (f.ShowDialog() == DialogResult.OK)
                {
                    LoadImpostoOne();
                    LoadImpostoTwo();
                }
            };

            valorvenda.TextChanged += (s, e) =>
            {
                if (Validation.ConvertToDouble(valorcompra.Text) == 0)
                {
                    return;
                }

                if (Validation.ConvertToDouble(valorvenda.Text) == 0)
                {
                    return;
                }

                var media =
                    (Validation.ConvertToDouble(valorvenda.Text) - Validation.ConvertToDouble(valorcompra.Text)) * 100 /
                    Validation.ConvertToDouble(valorcompra.Text);
                precoMedio.Text = $"{Validation.ConvertToDouble(Validation.RoundTwo(media))}%";
            };

            valorcompra.TextChanged += (s, e) =>
            {
                if (Validation.ConvertToDouble(valorcompra.Text) == 0)
                {
                    return;
                }

                if (Validation.ConvertToDouble(valorvenda.Text) == 0)
                {
                    return;
                }

                var media =
                    (Validation.ConvertToDouble(valorvenda.Text) - Validation.ConvertToDouble(valorcompra.Text)) * 100 /
                    Validation.ConvertToDouble(valorcompra.Text);
                precoMedio.Text = Validation.Price(media);
            };

            estoqueminimo.KeyPress += (s, e) => Masks.MaskDouble(s, e);
            codebarras.KeyPress    += (s, e) => Masks.MaskOnlyNumbers(s, e, 20);
            referencia.KeyPress    += (s, e) => Masks.MaskOnlyNumberAndChar(s, e, 50);
            ncm.KeyPress           += (s, e) => Masks.MaskOnlyNumbers(s, e, 8);
            cest.KeyPress          += (s, e) => Masks.MaskOnlyNumbers(s, e, 7);

            nome.TextChanged += (s, e) => { btnEstoque.Visible = nome.Text.Length >= 2; };

            nome.KeyPress += (s, e) => { Masks.MaskMaxLength(s, e, 100); };

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

            chkImpostoNFE.Click += (s, e) =>
            {
                if (chkImpostoNFE.Checked)
                {
                    ImpostoNFE.Enabled = true;
                }
                else
                {
                    ImpostoNFE.Enabled       = false;
                    ImpostoNFE.SelectedValue = 0;
                }
            };

            chkImpostoCFE.Click += (s, e) =>
            {
                if (chkImpostoCFE.Checked)
                {
                    ImpostoCFE.Enabled = true;
                }
                else
                {
                    ImpostoCFE.Enabled       = false;
                    ImpostoCFE.SelectedValue = 0;
                }
            };

            btnRemoverImage.Click += (s, e) =>
            {
                _modelItem.Id = IdPdtSelecionado;

                if (File.Exists($@"{Program.PATH_IMAGE}\Imagens\{_modelItem.Image}"))
                {
                    File.Delete($@"{Program.PATH_IMAGE}\Imagens\{_modelItem.Image}");
                }

                _modelItem.Image = "";
                _modelItem.Save(_modelItem, false);

                imageProduct.Image      = Resources.sem_imagem;
                pathImage.Text          = "";
                btnRemoverImage.Visible = false;
                Alert.Message("Pronto!", "Imagem removida com sucesso.", Alert.AlertType.success);
            };

            btnImage.Click += (s, e) =>
            {
                ofd.RestoreDirectory = true;
                ofd.Filter           = @"Image files (*.jpg, *.jpeg, *.png) | *.jpg; *.jpeg; *.png";
                ofd.CheckFileExists  = true;
                ofd.CheckPathExists  = true;
                ofd.Multiselect      = false;
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    if (!ofd.CheckFileExists)
                    {
                        Alert.Message("Opps", "Não encontramos a imagem selecionada. Tente Novamente!",
                                      Alert.AlertType.error);
                        return;
                    }

                    var path = ofd.InitialDirectory + ofd.FileName;
                    var ext  = Path.GetExtension(ofd.FileName);

                    if (File.Exists(path))
                    {
                        if (!Directory.Exists(Program.PATH_IMAGE + @"\Imagens"))
                        {
                            Directory.CreateDirectory(Program.PATH_IMAGE + @"\Imagens");
                        }

                        var nameImage = $"{Validation.CleanString(nome.Text).Replace(" ", "-")}{ext}";

                        if (File.Exists($@"{Program.PATH_IMAGE}\Imagens\{nameImage}"))
                        {
                            File.Delete($@"{Program.PATH_IMAGE}\Imagens\{nameImage}");
                        }

                        File.Copy(path, $@"{Program.PATH_IMAGE}\Imagens\{nameImage}");

                        _modelItem.Id    = IdPdtSelecionado;
                        _modelItem.Image = nameImage;
                        _modelItem.Save(_modelItem, false);

                        var imageAsByteArray = File.ReadAllBytes($@"{Program.PATH_IMAGE}\Imagens\{nameImage}");
                        imageProduct.Image      = Support.ByteArrayToImage(imageAsByteArray);
                        pathImage.Text          = $@"{Program.PATH_IMAGE}\Imagens\{nameImage}";
                        btnRemoverImage.Visible = true;
                        Alert.Message("Pronto!", "Imagem atualizada com sucesso.", Alert.AlertType.success);
                    }
                    else
                    {
                        Alert.Message("Opps", "Não foi possível copiar a imagem. Tente novamente.",
                                      Alert.AlertType.error);
                    }
                }
            };

            filterTodos.Click        += (s, e) => DataTableEstoque();
            filterMaisRecentes.Click += (s, e) => DataTableEstoque();

            selecionarNCM.Click += (s, e) =>
            {
                var f = new ModalNCM {
                    TopMost = true
                };
                if (f.ShowDialog() == DialogResult.OK)
                {
                    ncm.Text = ModalNCM.NCM;
                }
            };

            backOn.DoWork += (s, e) =>
            {
                _modelItem       = _modelItem.FindById(IdPdtSelecionado).FirstOrDefault <Model.Item>();
                ListCategorias   = new Categoria().GetAll("Produtos");
                ListFornecedores = new Pessoa().GetAll("Fornecedores");
                Impostos         = new Model.Imposto().FindAll().WhereFalse("excluir").OrderByDesc("nome").Get();
                Impostos2        = new Model.Imposto().FindAll().WhereFalse("excluir").OrderByDesc("nome").Get();
            };

            backOn.RunWorkerCompleted += (s, e) =>
            {
                Start();

                if (IdPdtSelecionado > 0)
                {
                    LoadData();
                }
                else
                {
                    _modelItem = new Item {
                        Tipo = "Produtos", Id = IdPdtSelecionado
                    };
                    if (_modelItem.Save(_modelItem, false))
                    {
                        IdPdtSelecionado = _modelItem.GetLastId();
                        LoadData();
                    }
                    else
                    {
                        Alert.Message("Opss", "Erro ao criar.", Alert.AlertType.error);
                        Close();
                    }
                }
            };

            workerBackEstoque.DoWork += (s, e) =>
            {
                var query = new ItemEstoqueMovimentacao().Query()
                            .LeftJoin("USUARIOS", "USUARIOS.id_user", "ITEM_MOV_ESTOQUE.id_usuario")
                            .Select("ITEM_MOV_ESTOQUE.*", "USUARIOS.id_user", "USUARIOS.nome as nome_user")
                            .Where("id_item", IdPdtSelecionado)
                            .OrderByDesc("criado");

                if (LimitShowStock > 0)
                {
                    query.Limit(LimitShowStock);
                }

                ListEstoque = query.Get();
            };

            workerBackEstoque.RunWorkerCompleted += (s, e) =>
            {
                GetDataTableEstoque(listaEstoque);
            };

            btnVariacao.Click += (s, e) =>
            {
                ModalVariacao.idProduto = IdPdtSelecionado;
                var form = new ModalVariacao();
                form.ShowDialog();
            };

            GridAdicionais.CellContentClick += (s, e) =>
            {
                if (GridAdicionais.Columns[e.ColumnIndex].Name == "Selecione")
                {
                    GridAdicionais.SelectedRows[0].Cells["Selecione"].Value = (bool)GridAdicionais.SelectedRows[0].Cells["Selecione"].Value == false;
                }
            };

            GridAdicionais.CellMouseEnter += (s, e) =>
            {
                if (e.ColumnIndex < 0 || e.RowIndex < 0)
                {
                    return;
                }

                var dataGridView = s as DataGridView;
                if (GridAdicionais.Columns[e.ColumnIndex].Name == "Selecione")
                {
                    dataGridView.Cursor = Cursors.Hand;
                }
            };

            GridAdicionais.CellMouseLeave += (s, e) =>
            {
                if (e.ColumnIndex < 0 || e.RowIndex < 0)
                {
                    return;
                }

                var dataGridView = s as DataGridView;
                if (GridAdicionais.Columns[e.ColumnIndex].Name == "Selecione")
                {
                    dataGridView.Cursor = Cursors.Default;
                }
            };

            GridCombos.CellContentClick += (s, e) =>
            {
                if (GridCombos.Columns[e.ColumnIndex].Name == "Selecione")
                {
                    GridCombos.SelectedRows[0].Cells["Selecione"].Value = (bool)GridCombos.SelectedRows[0].Cells["Selecione"].Value == false;
                }
            };

            GridCombos.CellMouseEnter += (s, e) =>
            {
                if (e.ColumnIndex < 0 || e.RowIndex < 0)
                {
                    return;
                }

                var dataGridView = s as DataGridView;
                if (GridCombos.Columns[e.ColumnIndex].Name == "Selecione")
                {
                    dataGridView.Cursor = Cursors.Hand;
                }
            };

            GridCombos.CellMouseLeave += (s, e) =>
            {
                if (e.ColumnIndex < 0 || e.RowIndex < 0)
                {
                    return;
                }

                var dataGridView = s as DataGridView;
                if (GridCombos.Columns[e.ColumnIndex].Name == "Selecione")
                {
                    dataGridView.Cursor = Cursors.Default;
                }
            };
        }
示例#31
0
        private void Save()
        {
            if (!string.IsNullOrEmpty(nome.Text))
            {
                if (_modelItem.ExistsName(nome.Text, false, IdPdtSelecionado))
                {
                    Alert.Message("Oppss", "Já existe um produto cadastrado com esse NOME.", Alert.AlertType.error);
                    return;
                }
            }

            codebarras.Text = codebarras.Text.Trim();
            if (!string.IsNullOrEmpty(codebarras.Text))
            {
                if (codebarras.Text.Length <= 3)
                {
                    Alert.Message("Oppss", "Código de barras é muito pequeno.", Alert.AlertType.error);
                    return;
                }

                if (_modelItem.ExistsCodeBarras(codebarras.Text, false, IdPdtSelecionado))
                {
                    Alert.Message("Oppss", "Já existe um produto cadastrado com esse código de barras.",
                                  Alert.AlertType.error);
                    return;
                }
            }
            else
            {
                var result = AlertOptions.Message("Atenção!",
                                                  "É necessário preencher o código de barras, deseja gerar um código automático?",
                                                  AlertBig.AlertType.warning, AlertBig.AlertBtn.YesNo);
                if (result)
                {
                    codebarras.Text = Validation.CodeBarrasRandom();
                }
                else
                {
                    return;
                }
            }

            _modelItem.Id            = IdPdtSelecionado;
            _modelItem.Tipo          = "Produtos";
            _modelItem.Nome          = nome.Text;
            _modelItem.CodeBarras    = codebarras.Text;
            _modelItem.Referencia    = referencia.Text;
            _modelItem.ValorCompra   = Validation.ConvertToDouble(valorcompra.Text);
            _modelItem.ValorVenda    = Validation.ConvertToDouble(valorvenda.Text);
            _modelItem.EstoqueMinimo = Validation.ConvertToDouble(estoqueminimo.Text);
            _modelItem.Medida        = Medidas.Text;
            _modelItem.InfAdicional  = inf_adicional.Text;

            _modelItem.Cest = cest.Text;
            _modelItem.Ncm  = ncm.Text;

            /*if (Support.CheckForInternetConnection())
             * {
             *  if (string.IsNullOrEmpty(_modelItem.Ncm) || _modelItem.Ncm != "0")
             *      if (aliq_federal.Text == "0,00" || aliq_estadual.Text == "0,00")
             *      {
             *          var data = new IBPT()
             *              .SetCodeBarras(_modelItem.CodeBarras)
             *              .SetDescricao(_modelItem.Nome)
             *              .SetMedida(_modelItem.Medida)
             *              .SetValor(_modelItem.ValorVenda)
             *              .SetCodigoNCM(_modelItem.Ncm)
             *              .GetDados();
             *
             *          if (data != null)
             *          {
             *              if (data.Message != null)
             *              {
             *                  aliq_federal.Text = "0";
             *                  aliq_estadual.Text = "0";
             *                  aliq_municipal.Text = "0";
             *              }
             *              else
             *              {
             *                  var s = JsonConvert.DeserializeObject(data.ToString());
             *
             *                  aliq_federal.Text = Validation.Price(s?.Nacional.Value);
             *                  aliq_estadual.Text = Validation.Price(s?.Estadual.Value);
             *                  aliq_municipal.Text = Validation.Price(s?.Municipal.Value);
             *              }
             *          }
             *      }
             * }*/

            if (_modelItem.Ncm == "0")
            {
                aliq_federal.Text   = "";
                aliq_estadual.Text  = "";
                aliq_municipal.Text = "";
            }

            _modelItem.AliqFederal     = Validation.ConvertToDouble(aliq_federal.Text);
            _modelItem.AliqEstadual    = Validation.ConvertToDouble(aliq_estadual.Text);
            _modelItem.AliqMunicipal   = Validation.ConvertToDouble(aliq_municipal.Text);
            _modelItem.Limite_Desconto = Validation.ConvertToDouble(txtLimiteDesconto.Text);

            _modelItem.Categoriaid = Validation.ConvertToInt32(Categorias.SelectedValue);

            _modelItem.Fornecedor = Validation.ConvertToInt32(Fornecedor.SelectedValue);

            if (ImpostoNFE.SelectedValue != null)
            {
                _modelItem.Impostoid = (int)ImpostoNFE.SelectedValue;
            }
            else
            {
                _modelItem.Impostoid = 0;
            }

            if (ImpostoCFE.SelectedValue != null)
            {
                _modelItem.Impostoidcfe = (int)ImpostoCFE.SelectedValue;
            }
            else
            {
                _modelItem.Impostoidcfe = 0;
            }

            if (Origens.SelectedValue != null)
            {
                _modelItem.Origem = Origens.SelectedValue.ToString();
            }

            _modelItem.ativo = Ativo.Toggled ? 0 : 1;

            var addon = new StringBuilder();

            foreach (DataGridViewRow item in GridAdicionais.Rows)
            {
                if ((bool)item.Cells["Selecione"].Value)
                {
                    if (string.IsNullOrEmpty(addon.ToString()))
                    {
                        addon.Append(Validation.ConvertToInt32(item.Cells["ID"].Value).ToString());
                        continue;
                    }

                    addon.Append($",{Validation.ConvertToInt32(item.Cells["ID"].Value)}");
                }
            }

            _modelItem.Adicional = addon.ToString();

            var combos = new StringBuilder();

            foreach (DataGridViewRow item in GridCombos.Rows)
            {
                if ((bool)item.Cells["Selecione"].Value)
                {
                    if (string.IsNullOrEmpty(combos.ToString()))
                    {
                        combos.Append(Validation.ConvertToInt32(item.Cells["ID"].Value).ToString());
                        continue;
                    }

                    combos.Append($",{Validation.ConvertToInt32(item.Cells["ID"].Value)}");
                }
            }

            _modelItem.Combos = combos.ToString();

            if (_modelItem.Save(_modelItem))
            {
                Close();
            }
        }
示例#32
0
        private void Eventos()
        {
            KeyDown   += KeyDowns;
            KeyPreview = true;
            Masks.SetToUpper(this);

            Load += (s, e) => search.Focus();

            Shown += async(s, e) =>
            {
                Refresh();

                SetHeadersTable(GridLista);
                await SetContentTableAsync(GridLista);
            };

            btnAdicionar.Click += (s, e) => EditProduct(true);
            btnEditar.Click    += (s, e) => EditProduct();

            btnRemover.Click += (s, e) =>
            {
                ListAdicionais.Clear();
                foreach (DataGridViewRow item in GridLista.Rows)
                {
                    if ((bool)item.Cells["Selecione"].Value)
                    {
                        ListAdicionais.Add(Validation.ConvertToInt32(item.Cells["ID"].Value));
                    }
                }

                var result = AlertOptions.Message("Atenção!",
                                                  "Você está prestes a deletar os ADICIONAIS selecionados, continuar?", AlertBig.AlertType.warning,
                                                  AlertBig.AlertBtn.YesNo);
                if (result)
                {
                    foreach (var item in ListAdicionais)
                    {
                        new ItemAdicional().Remove(item);
                    }

                    SetContentTableAsync(GridLista);
                }

                btnRemover.Visible   = false;
                btnEditar.Visible    = true;
                btnAdicionar.Visible = true;
            };

            search.TextChanged += (s, e) => SetContentTableAsync(GridLista);

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

            GridLista.CellClick += (s, e) =>
            {
                if (GridLista.Columns[e.ColumnIndex].Name == "Selecione")
                {
                    if ((bool)GridLista.SelectedRows[0].Cells["Selecione"].Value == false)
                    {
                        GridLista.SelectedRows[0].Cells["Selecione"].Value = true;
                        btnRemover.Visible   = true;
                        btnEditar.Visible    = false;
                        btnAdicionar.Visible = false;
                    }
                    else
                    {
                        GridLista.SelectedRows[0].Cells["Selecione"].Value = false;

                        var hideBtns    = false;
                        var hideBtnsTop = true;
                        foreach (DataGridViewRow item in GridLista.Rows)
                        {
                            if ((bool)item.Cells["Selecione"].Value)
                            {
                                hideBtns    = true;
                                hideBtnsTop = false;
                            }
                        }

                        btnRemover.Visible   = hideBtns;
                        btnEditar.Visible    = hideBtnsTop;
                        btnAdicionar.Visible = hideBtnsTop;
                    }
                }
            };

            GridLista.CellMouseEnter += (s, e) =>
            {
                if (e.ColumnIndex < 0 || e.RowIndex < 0)
                {
                    return;
                }

                var dataGridView = s as DataGridView;
                if (GridLista.Columns[e.ColumnIndex].Name == "Selecione")
                {
                    dataGridView.Cursor = Cursors.Hand;
                }
            };

            GridLista.CellMouseLeave += (s, e) =>
            {
                if (e.ColumnIndex < 0 || e.RowIndex < 0)
                {
                    return;
                }

                var dataGridView = s as DataGridView;
                if (GridLista.Columns[e.ColumnIndex].Name == "Selecione")
                {
                    dataGridView.Cursor = Cursors.Default;
                }
            };
        }