//Função que exclui produto orçado private void budgetedProductDelete() { if (Convert.ToInt32(this.dgv_budgetedProduct.Rows.Count) == 0) { MessageBox.Show("Não há produto selecionado para excluir!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (Convert.ToInt32(this.dgv_budgetedProduct.SelectedRows.Count) > 1) { MessageBox.Show("Selecione apenas uma linha da tabela para excluir!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { Account account = new Account(); account.IdConta = Globals.idConta; BudgetedProduct budgetedProduct = new BudgetedProduct(); budgetedProduct.IdProdutoOrcado = Convert.ToInt32(this.dgv_budgetedProduct.SelectedRows[0].Cells[0].Value); budgetedProduct.NumeroOrcamento = Globals.numeroOrcamento; if (Database.deleteBudgetedProduct(budgetedProduct)) { this.updateBudgetTotalValue(budgetedProduct); } else { MessageBox.Show("[ERRO] Não foi possível excluir produto orçado!", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
//Função que cadastra produto orçado private void budgetedProductRegister() { if (this.cbb_productName.SelectedIndex == -1) { MessageBox.Show("Selecione um produto para adicioná-lo ao orçamento!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { //Definição do número do orçamento e busca do id do produto e do seu valor unitário Account account = new Account(); BudgetedProduct budgetedProduct = new BudgetedProduct(); account.IdConta = Globals.idConta; budgetedProduct.NumeroOrcamento = Globals.numeroOrcamento; DataTable productDataTable = Database.query("SELECT produto.idProduto, produto.valorUnitario FROM produto WHERE produto.nomeProduto = '" + this.cbb_productName.SelectedItem.ToString().Trim() + "';"); //Verifica se o produto já está no orçamento foreach (DataGridViewRow dataGridViewRow in dgv_budgetedProduct.Rows) { if (dataGridViewRow.Cells[3].Value.ToString().Equals(this.cbb_productName.SelectedItem.ToString().Trim())) { MessageBox.Show("O produto já está no orçamento!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning); this.clearFields(); return; } } //Define o número do item no orçamento budgetedProduct.IdProduto = Convert.ToInt32(productDataTable.Rows[0].ItemArray[0]); budgetedProduct.Item = item + 1; item = item + 1; //Calcula o valor total de cada produto de acordo com seu preço e quantidade if (String.IsNullOrEmpty(this.txt_productQuantity.Text.Trim())) { budgetedProduct.QuantidadeProduto = 1; } else { budgetedProduct.QuantidadeProduto = Convert.ToInt32(this.txt_productQuantity.Text.Trim()); } decimal valorUnitario = Convert.ToDecimal(productDataTable.Rows[0].ItemArray[1]); budgetedProduct.ValorTotal = budgetedProduct.QuantidadeProduto * valorUnitario; //Adiciona produto ao orçamento if (Database.newBudgetedProduct(budgetedProduct)) { this.updateBudgetTotalValue(budgetedProduct); } else { MessageBox.Show("[ERRO] Não foi possível cadastrar produto orçado!", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
//FUNÇÕES //Função que atualiza o valor total do orçamento private void updateBudgetTotalValue(Budget budget) { BudgetedProduct budgetedProduct = new BudgetedProduct(); budgetedProduct.NumeroOrcamento = Convert.ToInt32(Globals.numeroOrcamento); Globals.budgetedProductDataTable = Database.query("SELECT produtoOrcado.idProdutoOrcado, produtoOrcado.item AS 'Item:', produtoOrcado.quantidadeProduto AS 'Quantidade:', produto.nomeProduto AS 'Nome do produto:', produto.valorUnitario AS 'Valor unitário:', produtoOrcado.valorTotal AS 'Valor total:' FROM produtoOrcado JOIN produto ON produtoOrcado.idProduto = produto.idProduto WHERE produtoOrcado.numeroOrcamento = " + Globals.numeroOrcamento + " ORDER BY produtoOrcado.item;"); //Soma o valor total de cada produto do orçamento decimal valorTotalProdutos = 0; foreach (DataRow dataRow in Globals.budgetedProductDataTable.Rows) { valorTotalProdutos += Convert.ToDecimal(dataRow.ItemArray[5]); } decimal valorTotalOrcamento = valorTotalProdutos + budget.ValorTrabalho; //Atualiza o valor total do orçamento if (Database.updateBudgetTotalValue(budgetedProduct, valorTotalOrcamento)) { //Seleciona a receita vinculada ao orçamento DataTable incomesDataTable = Database.query("SELECT * FROM receita WHERE numeroOrcamento = " + Globals.numeroOrcamento); if (incomesDataTable.Rows.Count > 0) { if (Convert.ToBoolean(incomesDataTable.Rows[0].ItemArray[9])) { return; } else { //Receita não parcelada if (Database.updateIncomeTotalValue(budgetedProduct, valorTotalOrcamento)) { return; } else { MessageBox.Show("[ERRO] Não foi possível atualizar o valor total do orçamento!", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } else { MessageBox.Show("[ERRO] Não foi possível atualizar o valor total do orçamento!", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
//Função que atualiza orçamento private void budgetUpdate() { if (String.IsNullOrEmpty(mtb_budgetDate.Text.Trim()) || String.IsNullOrEmpty(txt_laborValue.Text.Trim())) { MessageBox.Show("Informe o valor e a data do orçamento!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { if ((this.ckb_parcelValue.Checked) && ((String.IsNullOrEmpty(this.txt_parcels.Text.Trim())) || (this.cbb_period.SelectedIndex == -1))) { MessageBox.Show("Informe o número de parcelas do orçamento e o período em que elas se repetem!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { Account account = new Account(); Budget budget = new Budget(); Income income = new Income(); account.IdConta = Globals.idConta; budget.NumeroOrcamento = Convert.ToInt32(Globals.numeroOrcamento); income.NumeroOrcamento = Convert.ToInt32(Globals.numeroOrcamento); budget.IdCliente = Convert.ToInt32(Globals.budgetStepDataTable.Rows[0].ItemArray[1]); income.IdReceita = Globals.idReceita; budget.DataOrcamento = Convert.ToDateTime(this.mtb_budgetDate.Text.Trim()); income.DataTransacao = Convert.ToDateTime(this.mtb_budgetDate.Text.Trim()); Regex regexValor = new Regex(@"[R$ ]?[R$]?\d{1,3}(\.\d{3})*,\d{2}"); string valorTrabalho = this.txt_laborValue.Text.Trim(); if (regexValor.IsMatch(valorTrabalho)) { if (valorTrabalho.Contains("R$ ")) { budget.ValorTrabalho = Convert.ToDecimal(valorTrabalho.Substring(3).Trim()); } else if (valorTrabalho.Contains("R$")) { budget.ValorTrabalho = Convert.ToDecimal(valorTrabalho.Substring(2).Trim()); } else { budget.ValorTrabalho = Convert.ToDecimal(this.txt_laborValue.Text.Trim()); } budget.ValorTotal = Convert.ToDecimal(Globals.budgetStepDataTable.Rows[0].ItemArray[4]); income.ValorReceita = Convert.ToDecimal(Globals.budgetStepDataTable.Rows[0].ItemArray[4]); } else { MessageBox.Show("Formato monetário incorreto!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning); this.txt_laborValue.Clear(); this.txt_laborValue.PlaceholderText = ""; this.txt_laborValue.Focus(); return; } budget.CondicaoPagamento = this.cbb_paymentCondition.SelectedItem.ToString().Trim(); if (this.ckb_confirmedBudget.Checked) { budget.OrcamentoConfirmado = true; } else { budget.OrcamentoConfirmado = false; } income.DescricaoReceita = this.txt_incomeDescription.Text.Trim(); income.IdConta = Convert.ToInt32(Database.query("SELECT idConta FROM conta WHERE nomeConta = '" + this.cbb_incomeAccount.SelectedItem.ToString().Trim() + "';").Rows[0].ItemArray[0]); income.IdCategoria = Convert.ToInt32(Database.query("SELECT idCategoria FROM categoria WHERE nomeCategoria = 'Orçamentos';").Rows[0].ItemArray[0]); income.ObservacoesReceita = this.txt_incomeObservations.Text.Trim(); if (this.ckb_incomeReceived.Checked) { income.RecebimentoConfirmado = true; } else { income.RecebimentoConfirmado = false; } if (ckb_parcelValue.Checked) { //Orçamento parcelado income.RepetirParcelarReceita = true; //Parcela e atualiza valor do orçamento income.ParcelarValorReceita = true; income.ParcelasReceita = Convert.ToInt32(txt_parcels.Text.Trim()); income.PeriodoRepetirParcelarReceita = cbb_period.SelectedItem.ToString().Trim(); income.ValorReceita = income.ValorReceita / income.ParcelasReceita; if (this.updateParcel(income)) { //Soma o valor total de cada produto do orçamento e atribui a diferença do valor dos produtos pelo valor do trabalho DataTable productStepBudgetedProduct = Database.query("SELECT produtoOrcado.valorTotal FROM produtoOrcado WHERE produtoOrcado.numeroOrcamento = " + budget.NumeroOrcamento + " ORDER BY produtoOrcado.item;"); decimal valorTotalProdutos = 0; foreach (DataRow dataRow in productStepBudgetedProduct.Rows) { valorTotalProdutos += Convert.ToDecimal(dataRow.ItemArray[0]); } budget.ValorTotal = budget.ValorTrabalho + valorTotalProdutos; //Atualiza orçamento if (Database.updateBudget(budget)) { DataTable dataTable = Database.query("SELECT * FROM produtoOrcado WHERE numeroORcamento = " + Globals.numeroOrcamento + " ORDER BY numeroOrcamento DESC LIMIT 1;"); if (dataTable.Rows.Count > 0) { //Já existem produtos no orçamento BudgetedProduct budgetedProduct = new BudgetedProduct(); budgetedProduct.NumeroOrcamento = Globals.numeroOrcamento; decimal incomeValue = budget.ValorTotal / income.ParcelasReceita; //Atualiza valor total da receita, após parcelamento do valor if (Database.updateIncomeTotalValue(budgetedProduct, incomeValue)) { DataTable parcelsDataTable = Database.query("SELECT idParcela FROM parcela WHERE idReceita = " + income.IdReceita); int success = 1; int i = 0; Globals.parcels.Clear(); foreach (DataRow dataRow in parcelsDataTable.Rows) { Globals.parcels.Add(new Parcel()); Globals.parcels[i].IdParcela = Convert.ToInt32(dataRow.ItemArray[0]); Globals.parcels[i].ValorParcela = incomeValue; if (Database.updateParcelValue(Globals.parcels[i])) { i++; continue; } else { success = 0; break; } } MessageBox.Show("Orçamento atualizado com sucesso!", "", MessageBoxButtons.OK, MessageBoxIcon.Information); this.mtb_budgetDate.Focus(); if (success == 0) { MessageBox.Show("[ERRO] Não foi possível atualizar o valor das parcelas!", "", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } else { MessageBox.Show("[ERRO] Não foi possível atualizar o valor total do orçamento!", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { //Não existem produtos no orçamento MessageBox.Show("Orçamento atualizado com sucesso!", "", MessageBoxButtons.OK, MessageBoxIcon.Information); this.mtb_budgetDate.Focus(); } } else { MessageBox.Show("[ERRO] Não foi possível atualizar orçamento!", "", MessageBoxButtons.OK, MessageBoxIcon.Error); this.mtb_budgetDate.Focus(); } } else { MessageBox.Show("[ERRO] Não foi possível atualizar orçamento!", "", MessageBoxButtons.OK, MessageBoxIcon.Error); this.mtb_budgetDate.Focus(); } } else { //Orçamento não parcelado income.ParcelarValorReceita = false; DataTable parcelsDataTable = Database.query("SELECT * FROM parcela WHERE idReceita = " + income.IdReceita); bool success = true; foreach (DataRow dataRow in parcelsDataTable.Rows) { Parcel parcel = new Parcel(); parcel.IdParcela = Convert.ToInt32(dataRow.ItemArray[0]); if (Database.deleteParcel(parcel)) { continue; } else { success = false; MessageBox.Show("[ERRO] Não foi excluir a parcela!", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } } if (!success) { MessageBox.Show("[ERRO] Não foi atualizar todas as parcelas!", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (Database.updateBudget(budget)) { this.updateOneParcel(income); } } this.updateBudgetTotalValue(budget); } } }
//Função que atualiza produto orçado private void budgetedProductUpdate() { if (Convert.ToInt32(this.dgv_budgetedProduct.Rows.Count) == 0) { MessageBox.Show("Não há produto selecionado para atualizar!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (Convert.ToInt32(this.dgv_budgetedProduct.SelectedRows.Count) > 1) { MessageBox.Show("Selecione apenas uma linha da tabela para atualizar!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { if (this.cbb_productName.SelectedIndex == -1) { MessageBox.Show("Selecione um produto para atualizá-lo ao orçamento!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { Account account = new Account(); account.IdConta = Globals.idConta; BudgetedProduct budgetedProduct = new BudgetedProduct(); budgetedProduct.IdProdutoOrcado = Convert.ToInt32(this.dgv_budgetedProduct.SelectedRows[0].Cells[0].Value); budgetedProduct.NumeroOrcamento = Globals.numeroOrcamento; //Verifica se o produto já está no orçamento DataTable productDataTable = Database.query("SELECT produto.idProduto, produto.valorUnitario FROM produto WHERE produto.nomeProduto = '" + this.cbb_productName.SelectedItem.ToString().Trim() + "';"); foreach (DataGridViewRow dataGridViewRow in dgv_budgetedProduct.Rows) { if (dataGridViewRow.Cells[3].Value.ToString().Equals(this.cbb_productName.SelectedItem.ToString())) { if (dgv_budgetedProduct.SelectedRows[0].Cells[3].Value.ToString().Equals(this.cbb_productName.SelectedItem.ToString())) { continue; } else { MessageBox.Show("O produto já está no orçamento!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } } } budgetedProduct.IdProduto = Convert.ToInt32(productDataTable.Rows[0].ItemArray[0]); budgetedProduct.Item = Convert.ToInt32(this.dgv_budgetedProduct.SelectedRows[0].Cells[1].Value); if (String.IsNullOrEmpty(this.txt_productQuantity.Text)) { budgetedProduct.QuantidadeProduto = 1; } else { budgetedProduct.QuantidadeProduto = Convert.ToInt32(this.txt_productQuantity.Text); } //Atribui o valor total pela multiplicação do valor unitário pela quantidade do produto decimal valorUnitario = Convert.ToDecimal(productDataTable.Rows[0].ItemArray[1]); budgetedProduct.ValorTotal = budgetedProduct.QuantidadeProduto * valorUnitario; if (Database.updateBudgetedProduct(budgetedProduct)) { this.updateBudgetTotalValue(budgetedProduct); } else { MessageBox.Show("[ERRO] Não foi possível atualizar produto orçado!", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
//Função que atualiza o valor total do orçamento private void updateBudgetTotalValue(BudgetedProduct budgetedProduct) { //Atualiza o dataGridView com o novo produto adicionado Globals.budgetedProductDataTable = Database.query("SELECT produtoOrcado.idProdutoOrcado, produtoOrcado.item AS 'Item:', produtoOrcado.quantidadeProduto AS 'Quantidade:', produto.nomeProduto AS 'Nome do produto:', produto.valorUnitario AS 'Valor unitário:', produtoOrcado.valorTotal AS 'Valor total:' FROM produtoOrcado JOIN produto ON produtoOrcado.idProduto = produto.idProduto WHERE produtoOrcado.numeroOrcamento = " + Globals.numeroOrcamento + " ORDER BY produtoOrcado.item;"); if (Globals.budgetedProductDataTable.Rows.Count > 0) { this.dgv_budgetedProduct.DataSource = Globals.budgetedProductDataTable; } //Soma o valor total de cada produto do orçamento decimal valorTotalProdutos = 0; foreach (DataRow dataRow in Globals.budgetedProductDataTable.Rows) { valorTotalProdutos += Convert.ToDecimal(dataRow.ItemArray[5]); } decimal valorTotalOrcamento = valorTotalProdutos + Convert.ToDecimal(Globals.productStepDataTable.Rows[0].ItemArray[3]); //Atualiza o valor total do orçamento if (Database.updateBudgetTotalValue(budgetedProduct, valorTotalOrcamento)) { //Seleciona a receita vinculada ao orçamento DataTable incomesDataTable = Database.query("SELECT * FROM receita WHERE numeroOrcamento = " + budgetedProduct.NumeroOrcamento); if (Convert.ToBoolean(incomesDataTable.Rows[0].ItemArray[9]) == true) { //Receita parcelada if (Convert.ToBoolean(incomesDataTable.Rows[0].ItemArray[12]) == true) { valorTotalOrcamento = valorTotalOrcamento / Convert.ToInt32(incomesDataTable.Rows[0].ItemArray[13]); if (Database.updateIncomeTotalValue(budgetedProduct, valorTotalOrcamento)) { DataTable parcelsDataTable = Database.query("SELECT idParcela FROM parcela WHERE idReceita = " + incomesDataTable.Rows[0].ItemArray[0]); int success = 1; int i = 0; Globals.parcels.Clear(); foreach (DataRow dataRow in parcelsDataTable.Rows) { Globals.parcels.Add(new Parcel()); Globals.parcels[i].IdParcela = Convert.ToInt32(dataRow.ItemArray[0]); Globals.parcels[i].ValorParcela = valorTotalOrcamento; if (Database.updateParcelValue(Globals.parcels[i])) { i++; continue; } else { success = 0; break; } } this.clearFields(); this.pcb_btnUpdate.Visible = true; this.pcb_btnDelete.Visible = true; if (success == 0) { MessageBox.Show("[ERRO] Não foi possível atualizar o valor das parcelas!", "", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } else { MessageBox.Show("[ERRO] Não foi possível atualizar o valor total do orçamento!", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } else { //Receita não parcelada if (Database.updateIncomeTotalValue(budgetedProduct, valorTotalOrcamento)) { this.clearFields(); this.lbl_btnUpdateTag.Visible = true; this.pcb_btnUpdate.Visible = true; this.lbl_btnDeleteTag.Visible = true; this.pcb_btnDelete.Visible = true; } else { MessageBox.Show("[ERRO] Não foi possível atualizar o valor total do orçamento!", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } } this.updateItemNumber(); } else { MessageBox.Show("[ERRO] Não foi possível atualizar o valor total do orçamento!", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } }