using BLL; using DAL; using Modelo; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using iTextSharp.text; using iTextSharp.text.pdf; using System.Xml; namespace IBRCAD { public partial class frm_movimentacaovenda : Form { public string operacao; private double totalvenda; public frm_movimentacaovenda() { InitializeComponent(); } public void alterabotoes(int op) { pn_dados.Enabled = false; pnfinalizar.Visible = false; pn_dados.Visible = true; pn_controls.Visible = true; //gpparcelas.Enabled = false; btn_inserir.Enabled = false; btn_localizar.Enabled = false; btn_alterar.Enabled = false; btn_excluir.Enabled = false; btn_cancel.Enabled = false; btn_save.Enabled = false; btn_print.Enabled = false; if (op == 1) { btn_inserir.Enabled = true; btn_localizar.Enabled = true; } if (op == 2) { pn_dados.Enabled = true; btn_save.Enabled = true; btn_cancel.Enabled = true; btn_print.Enabled = true; } if (op == 3) { btn_alterar.Enabled = true; btn_excluir.Enabled = true; btn_cancel.Enabled = true; } }//end altera botões private double verificaqtdeprodutos(int procod) { double qtde_estoque = 0; try { DALLconexao cx = new DALLconexao(DadosDaConexao.StringDeConexao); BLLProduto bll = new BLLProduto(cx); ModeloProduto modelo = bll.CarregaModeloProduto(procod); qtde_estoque = modelo.ProQtde; for (int i = 0; i < dgVendas.RowCount; i++) { if (Convert.ToDouble(dgVendas.Rows[i].Cells[0].Value) == procod) { qtde_estoque -= Convert.ToDouble(dgVendas.Rows[i].Cells[2].Value); } } } catch (Exception) { throw; } return qtde_estoque; }//verificar estoque private void displayclear() { this.txt_vendCod.Text = ""; this.txt_notafiscal.Text = ""; this.txt_clicod.Text = ""; this.txt_nomeCli.Text = ""; this.txt_procod.Text = ""; this.txt_proname.Text = ""; this.txtqtde.Text = ""; this.txtValorUnitario.Text = ""; this.txtTotal.Text = ""; this.dgVendas.Rows.Clear(); this.dgvParcelas.Rows.Clear(); this.cbParcelas.Text = "1"; } private void buttonGerarPDF_Click(DataGridView dataGridView1, object sender, EventArgs e) { // Criar o documento PDF Document doc = new Document(); try { // Escolher o local para salvar o PDF SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "PDF (*.pdf)|*.pdf"; saveFileDialog1.Title = "Salvar PDF"; saveFileDialog1.ShowDialog(); if (saveFileDialog1.FileName != "") { // Criar o arquivo PDF FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create, FileAccess.Write, FileShare.None); PdfWriter writer = PdfWriter.GetInstance(doc, fs); doc.Open(); // Adicionar cabeçalho "Relatório de compras" Paragraph cabecalho = new Paragraph("Relatório de compras\n\n"); cabecalho.Alignment = Element.ALIGN_CENTER; doc.Add(cabecalho); // Adicionar data atual ao PDF Paragraph dataAtual = new Paragraph("Data: " + DateTime.Now.ToShortDateString() + "\n\n"); doc.Add(dataAtual); // Adicionar conteúdo ao PDF a partir do DataGridView PdfPTable table = new PdfPTable(dataGridView1.ColumnCount); for (int i = 0; i < dataGridView1.ColumnCount; i++) { table.AddCell(new Phrase(dataGridView1.Columns[i].HeaderText)); } table.HeaderRows = 1; double valorTotalCompras = 0; for (int i = 0; i < dataGridView1.Rows.Count; i++) { for (int j = 0; j < dataGridView1.Columns.Count; j++) { if (dataGridView1[j, i].Value != null) { table.AddCell(new Phrase(dataGridView1[j, i].Value.ToString())); // Somar os valores da quinta coluna if (j == 4) { double valor; if (double.TryParse(dataGridView1[j, i].Value.ToString(), out valor)) { valorTotalCompras += valor; } } } } } doc.Add(table); // Adicionar o valor total de compras ao PDF Paragraph totalCompras = new Paragraph("\n\nValor total de compras: R$ " + valorTotalCompras.ToString("0.00")); doc.Add(totalCompras); // Fechar o documento e liberar recursos doc.Close(); writer.Close(); fs.Close(); MessageBox.Show("PDF gerado com sucesso!"); } } catch (Exception ex) { MessageBox.Show("Erro ao gerar PDF: " + ex.Message); } finally { // Certificar-se de que o documento é fechado, mesmo em caso de exceção if (doc.IsOpen()) { doc.Close(); } } } private void pb_exit_Click(object sender, EventArgs e) { this.Close(); }//end close private void btn_inserir_Click(object sender, EventArgs e) { this.operacao = "inserir"; this.totalvenda = 0; this.alterabotoes(2); }//btn inserir private void btn_localizar_Click(object sender, EventArgs e) { frm_consultavendas fc = new frm_consultavendas(); fc.ShowDialog(); if (fc.codigo != 0) { DALLconexao cx = new DALLconexao(DadosDaConexao.StringDeConexao); BLLvenda bvenda = new BLLvenda(cx); ModeloVenda mvenda = bvenda.CarregaModeloVenda(fc.codigo); txt_vendCod.Text = mvenda.Ven_cod.ToString(); txt_notafiscal.Text = mvenda.Ven_nfiscal.ToString(); dtpDataVenda.Value =Convert.ToDateTime(mvenda.Ven_data); cbTipoPag.SelectedValue = mvenda.Tpa_cod; cbParcelas.SelectedValue = mvenda.Ven_nparcelas; if (mvenda.Ven_avista == 1) { chb_avista.Checked = true; } else { chb_avista.Checked = false; } cbParcelas.Text = mvenda.Ven_nparcelas.ToString(); txt_clicod.Text = mvenda.Cli_cod.ToString(); txt_clicod_Leave(sender, e); txtTotal.Text = mvenda.Ven_total.ToString(); this.totalvenda = mvenda.Ven_total; //itens da venda BLLitensVenda bitens = new BLLitensVenda(cx); DataTable tabela = bitens.localizar(mvenda.Ven_cod); for (int i = 0; i < tabela.Rows.Count; i++) { string icod = tabela.Rows[i]["pro_cod"].ToString(); string inome = tabela.Rows[i]["pro_nome"].ToString(); string iqtde = tabela.Rows[i]["itv_qtde"].ToString(); string ivalorU = tabela.Rows[i]["itv_valor"].ToString(); double valorTotal = Convert.ToDouble(tabela.Rows[i]["itv_qtde"]) * Convert.ToDouble(tabela.Rows[i]["itv_valor"]); string[] it = new string[] { icod, inome, iqtde, ivalorU, valorTotal.ToString() }; this.dgVendas.Rows.Add(it); } this.alterabotoes(3); if (mvenda.Ven_status == "ativo") { lbl_statusvenda.Text = "Ativa"; lbl_statusvenda.ForeColor = Color.Green; pn_dados.Enabled = true; } else { lbl_statusvenda.Text = "Cancelada"; lbl_statusvenda.ForeColor = Color.Red; pn_dados.Enabled = true; } } else { this.alterabotoes(1); this.displayclear(); } fc.Dispose(); }//end localizar private void btn_alterar_Click(object sender, EventArgs e) { DALLconexao cx = new DALLconexao(DadosDaConexao.StringDeConexao); BLLparcelascompra bparcelas = new BLLparcelascompra(cx); BLLCompra bLLCompra = new BLLCompra(cx); BLLitensCompra bitens = new BLLitensCompra(cx); int comcod = Convert.ToInt32(txt_vendCod.Text); int qtde = Convert.ToInt32(cbParcelas.Text); qtde -= bLLCompra.verificarParcelasEmAberto(comcod); if (qtde == 0) { this.alterabotoes(2); this.operacao = "alterar"; } else { MessageBox.Show("Impossivel alterar registro,pois existe parcelas pagas na compra", "Aviso!", MessageBoxButtons.OK, MessageBoxIcon.Information); } }//end update private void btn_excluir_Click(object sender, EventArgs e) { DialogResult r = MessageBox.Show("Deseja realizar o cancelamento dessa venda?", "Cancelamento", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (r == DialogResult.Yes) { DALLconexao conexao = new DALLconexao(DadosDaConexao.StringDeConexao); BLLvenda bvenda = new BLLvenda(conexao); if (bvenda.CancelarVenda(Convert.ToInt32(txt_vendCod.Text))) { MessageBox.Show("Venda Cancelada com sucesso!", "Cancelamento da venda efetuado com sucesso."); this.displayclear(); this.alterabotoes(1); } else { MessageBox.Show("Não foi possivel efetuar o cancelamento da venda,por favor contacte o administrador do sistema", "Erro ao tentar cancelar"); } } else { this.alterabotoes(1); this.displayclear(); }//cancelando a venda }//end delete private void btn_save_Click(object sender, EventArgs e) { if (totalvenda > 0) { dgvParcelas.Rows.Clear(); int parcelas = Convert.ToInt32(cbParcelas.Text); double totalLocal = Convert.ToDouble(txtTotal.Text); double valorLocal = totalLocal / parcelas; DateTime dt = new DateTime(); dt = dtpInicial.Value; //lblTotalCompra.Text = totalCompra.ToString(); lblTotalVenda.Text = txtTotal.Text; for (int i = 1; i <= parcelas; i++) { string[] k = new string[] { i.ToString(), valorLocal.ToString(), dt.Date.ToString() }; dgvParcelas.Rows.Add(k); if (dt.Month != 12) { dt = new DateTime(dt.Year, dt.Month + 1, dt.Day); } else { dt = new DateTime(dt.Year + 1, 1, dt.Day); } this.pnfinalizar.Visible = true; } this.btn_save.Enabled = false; this.btn_cancel.Enabled = false; this.btn_print.Enabled = false; this.pnfinalizar.Visible = true; this.pnfinalizar.Location = new Point(4, 27); this.pnfinalizar.Enabled = true; this.pn_dados.Visible = false; this.pn_controls.Visible = false; } else { MessageBox.Show("Porfavor preencha todos os campos para prosseguir com a venda!", "Campos faltando"); } }//end save 1 private void btn_cancel_Click(object sender, EventArgs e) { this.alterabotoes(1); this.displayclear(); this.totalvenda = 0x00; }//end cancell private void btn_save2_Click(object sender, EventArgs e) { DALLconexao cx = new DALLconexao(DadosDaConexao.StringDeConexao); //string conexão cx.Conectar(); cx.IniciarTransacao(); //Inicializando Transação com o banco de dados try { //leitura dos dados nos modelos ModeloVenda modeloVenda = new ModeloVenda(); ModeloItensVenda itensVenda = new ModeloItensVenda(); ModeloParcelasVenda mparcelas = new ModeloParcelasVenda(); modeloVenda.Ven_data =Convert.ToDateTime(dtpDataVenda.Value); modeloVenda.Ven_nfiscal = Convert.ToInt32(txt_notafiscal.Text); modeloVenda.Ven_nparcelas = Convert.ToInt32(cbParcelas.Text); modeloVenda.Ven_status = "ativo"; //modelo.ComTotal = this.totalCompra; modeloVenda.Ven_total = Convert.ToInt32(lblTotalVenda.Text); modeloVenda.Cli_cod = Convert.ToInt32(txt_clicod.Text); modeloVenda.Tpa_cod = Convert.ToInt32(cbTipoPag.SelectedValue); if (chb_avista.Checked) { modeloVenda.Ven_avista = 1; } else { modeloVenda.Ven_avista = 0; } //inicializando blls BLLvenda bllVenda = new BLLvenda(cx); BLLparcelasvenda bparcelas = new BLLparcelasvenda(cx); BLLitensVenda bllitensVenda = new BLLitensVenda(cx); if (this.operacao == "inserir") { bllVenda.Incluir(modeloVenda); for (int i = 0; i < dgVendas.RowCount; i++) { itensVenda.Itv_cod = i + 1; itensVenda.Ven_cod = modeloVenda.Ven_cod; itensVenda.Pro_cod = Convert.ToInt32(dgVendas.Rows[i].Cells[0].Value); itensVenda.Itv_qtde = Convert.ToDouble(dgVendas.Rows[i].Cells[2].Value); itensVenda.Itv_valor = Convert.ToDouble(dgVendas.Rows[i].Cells[3].Value); bllitensVenda.Incluir(itensVenda); } for (int i = 0; i < dgvParcelas.RowCount; i++) { mparcelas.Ven_cod = modeloVenda.Ven_cod; mparcelas.Pve_cod = Convert.ToInt32(dgvParcelas.Rows[i].Cells[0].Value); mparcelas.Pve_valor = Convert.ToDouble(dgvParcelas.Rows[i].Cells[1].Value); mparcelas.Datavenci = Convert.ToDateTime(dgvParcelas.Rows[i].Cells[2].Value); bparcelas.Incluir(mparcelas); } //dgVendas.DataSource = ""; MessageBox.Show("Venda efetuada: Código : " + modeloVenda.Ven_cod.ToString()); } this.pnfinalizar.Visible = false; this.dgvParcelas.DataSource = null; this.displayclear(); this.alterabotoes(1); cx.TerminarTransacao(); //termina transação cx.Desconectar(); //desconecta do banco } catch (Exception erro) { MessageBox.Show(erro.Message, "Erro 01: Sql"); cx.cancelarTransacao(); //desfaz tudo cx.Desconectar(); //desconectando mesmo se tiver erro } }//end save 2 private void btn_cancel2_Click(object sender, EventArgs e) { this.pnfinalizar.Visible = false; this.displayclear(); this.alterabotoes(1); }//end cancell 2 private void frm_movimentacaocompra_Load(object sender, EventArgs e) { this.totalvenda = 0; this.alterabotoes(1); DALLconexao cx = new DALLconexao(DadosDaConexao.StringDeConexao); BLLTipoPagamento pagamento = new BLLTipoPagamento(cx); cbTipoPag.DataSource = pagamento.Localizar(""); cbTipoPag.DisplayMember = "tpa_nome"; cbTipoPag.ValueMember = "tpa_cod"; cbParcelas.Text = "1"; } private void btn_loc_for_Click(object sender, EventArgs e) { frm_consultacliente f = new frm_consultacliente(); f.ShowDialog(); if (f.codigo != 0) { txt_clicod.Text = f.codigo.ToString(); this.txt_clicod_Leave(sender, e); } }//end loc cliente private void btn_loc_produto_Click(object sender, EventArgs e) { frm_consultaprodutos f = new frm_consultaprodutos(); f.ShowDialog(); if (f.codigo != 0) { #pragma warning disable CS1690 // Acessar um membro em um campo de uma classe de empacotamento por referência pode gerar uma exceção de tempo de execução txt_procod.Text = f.codigo.ToString(); #pragma warning restore CS1690 // Acessar um membro em um campo de uma classe de empacotamento por referência pode gerar uma exceção de tempo de execução txt_procod_Leave(sender, e); } f.Dispose(); } private void txt_proname_Leave(object sender, EventArgs e) { } private void txt_procod_Leave(object sender, EventArgs e) { try { DALLconexao cx = new DALLconexao(DadosDaConexao.StringDeConexao); BLLProduto bll = new BLLProduto(cx); ModeloProduto modelo = bll.CarregaModeloProduto(Convert.ToInt32(txt_procod.Text)); txt_proname.Text = modelo.ProNome; txtqtde.Text = "1"; txtValorUnitario.Text = modelo.ProValorPago.ToString(); } catch { this.txt_procod.Text = ""; this.txt_proname.Text = ""; } }//end leave procod private void btnAddProd_Click(object sender, EventArgs e) { double qtde = 0; try { if ((txt_procod.Text != "") && (txtqtde.Text != "") && (txtValorUnitario.Text != "")) { if (chb_verificar_estoque.Checked) { qtde = verificaqtdeprodutos(Convert.ToInt32(txt_procod.Text)); if (Convert.ToDouble(txtqtde.Text) > qtde) { MessageBox.Show("Quantidade de produtos é indisponivel, você possui " + qtde + " em seu estoque", "Não é possivel efetuar essa venda"); return; } } double valorTotal = Convert.ToDouble(txtqtde.Text) * Convert.ToDouble(txtValorUnitario.Text); this.totalvenda += valorTotal; string[] i = new string[] { txt_procod.Text, txtqtde.Text, txtValorUnitario.Text, valorTotal.ToString() }; this.dgVendas.Rows.Add(i); //limpar os campos this.txt_procod.Text = ""; this.txt_proname.Text = ""; this.txtqtde.Text = ""; this.txtValorUnitario.Text = ""; txtTotal.Text = totalvenda.ToString(); }//end if else { MessageBox.Show("Existe dados faltando na sua venda", "Dados faltando"); } } catch (Exception) { MessageBox.Show("Não foi possivel realizar a conversão de valores para o preenchimento da tabela", "Erro de conversão"); } }//end add produto private void dgCompra_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { txt_procod.Text = dgVendas.Rows[e.RowIndex].Cells[0].Value.ToString(); txt_proname.Text = dgVendas.Rows[e.RowIndex].Cells[1].Value.ToString(); txtqtde.Text = dgVendas.Rows[e.RowIndex].Cells[2].Value.ToString(); txtValorUnitario.Text = dgVendas.Rows[e.RowIndex].Cells[3].Value.ToString(); double valor = Convert.ToDouble(dgVendas.Rows[e.RowIndex].Cells[4].Value); this.totalvenda = this.totalvenda - valor; dgVendas.Rows.RemoveAt(e.RowIndex); txtTotal.Text = this.totalvenda.ToString(); } } private void buttonGerarXML_Click(DataGridView dataGridView1, object sender, EventArgs e) { try { // Escolher o local para salvar o arquivo XML SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "XML (*.xml)|*.xml"; saveFileDialog1.Title = "Salvar XML"; saveFileDialog1.ShowDialog(); if (saveFileDialog1.FileName != "") { // Criar o arquivo XML XmlTextWriter xmlWriter = new XmlTextWriter(saveFileDialog1.FileName, null); xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("RelatorioCompras"); // Adicionar data atual ao XML xmlWriter.WriteStartElement("DataAtual"); xmlWriter.WriteString(DateTime.Now.ToShortDateString()); xmlWriter.WriteEndElement(); // Adicionar conteúdo ao XML a partir do DataGridView xmlWriter.WriteStartElement("Compras"); for (int i = 0; i < dataGridView1.Rows.Count; i++) { xmlWriter.WriteStartElement("Compra"); for (int j = 0; j < dataGridView1.Columns.Count; j++) { if (dataGridView1[j, i].Value != null) { xmlWriter.WriteStartElement(dataGridView1.Columns[j].Name); xmlWriter.WriteString(dataGridView1[j, i].Value.ToString()); xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); xmlWriter.Close(); MessageBox.Show("Arquivo XML gerado com sucesso!"); } } catch (Exception ex) { MessageBox.Show("Erro ao gerar XML: " + ex.Message); } } private void btn_print_Click(object sender, EventArgs e) { // this.buttonGerarPDF_Click(dgCompra,sender, e); // this.buttonGerarXML_Click(dgCompra, sender, e); //PrintScreenHelper.SaveCapture(); PdfPrinter.PrintDocument(dgVendas); }//gerar relatorio private void buttonGerarPdfPag(DataGridView dataGridView1, object sender, EventArgs e) { // Criar o documento PDF Document doc = new Document(); try { // Escolher o local para salvar o PDF SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "PDF (*.pdf)|*.pdf"; saveFileDialog1.Title = "Salvar PDF"; saveFileDialog1.ShowDialog(); if (saveFileDialog1.FileName != "") { // Criar o arquivo PDF FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create, FileAccess.Write, FileShare.None); PdfWriter writer = PdfWriter.GetInstance(doc, fs); doc.Open(); // Adicionar cabeçalho "Dados de Pagamento" Paragraph cabecalho = new Paragraph("Dados de Pagamento\n\n"); cabecalho.Alignment = Element.ALIGN_CENTER; doc.Add(cabecalho); // Adicionar conteúdo ao PDF a partir do DataGridView PdfPTable table = new PdfPTable(dataGridView1.ColumnCount); for (int i = 0; i < dataGridView1.ColumnCount; i++) { table.AddCell(new Phrase(dataGridView1.Columns[i].HeaderText)); } table.HeaderRows = 1; for (int i = 0; i < dataGridView1.Rows.Count; i++) { for (int j = 0; j < dataGridView1.Columns.Count; j++) { if (dataGridView1[j, i].Value != null) { table.AddCell(new Phrase(dataGridView1[j, i].Value.ToString())); } } } doc.Add(table); // Fechar o documento e liberar recursos doc.Close(); writer.Close(); fs.Close(); MessageBox.Show("PDF gerado com sucesso!"); } } catch (Exception ex) { MessageBox.Show("Erro ao gerar PDF: " + ex.Message); } finally { // Certificar-se de que o documento é fechado, mesmo em caso de exceção if (doc.IsOpen()) { doc.Close(); } } }//end buttonImprimirPDFPag private void btn_imprimirPag_Click(object sender, EventArgs e) { this.buttonGerarPDF_Click(dgvParcelas, sender, e); }//end btn_imprimirPag_Click private void txt_clicod_Leave(object sender, EventArgs e) { try { DALLconexao cx = new DALLconexao(DadosDaConexao.StringDeConexao); BLLCliente bll = new BLLCliente(cx); ModeloCliente modelo = bll.CarregaModeloCliente(Convert.ToInt32(txt_clicod.Text)); this.txt_nomeCli.Text = modelo.CliNome; } catch { this.txt_clicod.Text = ""; } }//end cli cod private void chb_avista_CheckedChanged(object sender, EventArgs e) { if (chb_avista.Checked == true) { cbParcelas.SelectedIndex = 0; cbParcelas.Enabled = false; cbTipoPag.Enabled = false; } else { cbParcelas.Enabled = true; cbTipoPag.Enabled = true; } }//end a vista } }