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 DAL; using MLL; using BLL; using Modelo; using iTextSharp.text; using iTextSharp.text.pdf; using System.IO; using System.Windows.Forms; using System.Xml; using Font = System.Drawing.Font; namespace IBRCAD { public partial class frm_consultavendas : Form { public int codigo = 0; public frm_consultavendas() { InitializeComponent(); } private void limparCampos() { this.dgvDados.DataSource = null; this.dgv_itens.DataSource = null; this.dgv_parcelas.DataSource = null; this.txt_cli_nome.Text = ""; this.lbl_cod.Text = "Infome o código do cliente"; this.dtp_final.Value = DateTime.Now; this.dtp_inicial.Value = DateTime.Now; }//limpar campos private void orgcampos(DataGridView dg, int op) { try { if (op == 1) { dg.Columns[0].Width = 60; dg.Columns[0].HeaderText = "Código da Venda"; dg.Columns[1].Width = 100; dg.Columns[1].HeaderText = "Data da Venda"; dg.Columns[2].Width = 100; dg.Columns[2].HeaderText = "Nota Fiscal"; dg.Columns[3].Width = 60; dg.Columns[3].HeaderText = "á vista"; dg.Columns[4].Width = 100; dg.Columns[4].HeaderText = "Nº de Parcelas"; dg.Columns[5].Width = 60; dg.Columns[5].HeaderText = "Valor Total (R$)"; dg.Columns[6].Width = 60; dg.Columns[6].HeaderText = "Status da venda"; dg.Columns[7].Visible = false; dg.Columns[8].Visible = false; dg.Columns[9].HeaderText = "Cliente"; }//organizar venda if (op == 2) { dg.Columns[0].Width = 100; dg.Columns[0].HeaderText = "Cód. Itens"; dg.Columns[1].Width = 100; dg.Columns[1].HeaderText = "Quantidade em estoque"; dg.Columns[2].Width = 100; dg.Columns[2].HeaderText = "Valor(R$)"; dg.Columns[3].Width = 100; dg.Columns[3].HeaderText = "ID Venda"; dg.Columns[4].Width = 100; dg.Columns[4].HeaderText = "ID Produto"; dg.Columns[5].Width = 100; dg.Columns[5].HeaderText = "Produto"; }//organiza o data do itens if (op == 3) { dg.Columns[0].Width = 100; dg.Columns[0].HeaderText = "Cód. Venda"; dg.Columns[1].Visible = false; dg.Columns[2].Width = 100; dg.Columns[2].HeaderText = "Valor da Parcela"; dg.Columns[3].Width = 100; dg.Columns[3].HeaderText = "Data de pagamento"; dg.Columns[4].Width = 100; dg.Columns[4].HeaderText = "Data de vencimento"; //dg.Columns[2].Width = 100; //dg.Columns[2].HeaderText = "Data Pagamento"; //dg.Columns[3].Width = 100; //dg.Columns[3].HeaderText = "Data Vencimento"; //dg.Columns[4].Width = 100; //dg.Columns[4].HeaderText = "Cód. Venda"; }//organiza a venda } catch { } }//organiza campos private void frm_consultavendas_Load(object sender, EventArgs e) { this.pn_cliente.Visible = false; this.pn_data.Visible = false; this.pn_parcelas.Visible = false; this.rb_todasCompras_CheckedChanged(sender, e); }//load private void rb_todasCompras_CheckedChanged(object sender, EventArgs e) { this.limparCampos(); if (rb_todasCompras.Checked) { pn_todasCompras.Visible = true; DALLconexao cx = new DALLconexao(DadosDaConexao.StringDeConexao); BLLvenda bvenda = new BLLvenda(cx); dgvDados.DataSource = bvenda.Localizar(); this.orgcampos(dgvDados, 1); } }//rb todas as vendas private void btn_localizarCliente_Click(object sender, EventArgs e) { frm_consultacliente f = new frm_consultacliente(); f.ShowDialog(); if (f.codigo != 0) { lbl_cod.Text = f.codigo.ToString(); DALLconexao cx = new DALLconexao(DadosDaConexao.StringDeConexao); BLLCliente bll = new BLLCliente(cx); BLLvenda bvenda = new BLLvenda(cx); ModeloCliente modelo = bll.CarregaModeloCliente(f.codigo); txt_cli_nome.Text = modelo.CliNome; this.dgvDados.DataSource = bvenda.Localizar(f.codigo); f.Dispose(); this.orgcampos(dgvDados, 1); this.orgcampos(dgv_itens, 2); this.orgcampos(dgv_parcelas, 3); } else { lbl_cod.Text = "Nenhum dado encontrado"; } }//btn localizar por clientes private void btn_localizarPorData_Click(object sender, EventArgs e) { DateTime datainicial, datafinal; DALLconexao cx = new DALLconexao(DadosDaConexao.StringDeConexao); BLLvenda bvenda = new BLLvenda(cx); datainicial = this.dtp_inicial.Value; datafinal = this.dtp_final.Value; dgvDados.DataSource = bvenda.Localizar(datainicial, datafinal); this.orgcampos(dgvDados, 1); }//localizar por dada private void dgvDados_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { int cod = Convert.ToInt32(dgvDados.Rows[e.RowIndex].Cells[0].Value); DALLconexao cx = new DALLconexao(DadosDaConexao.StringDeConexao); //itens da compra BLLitensVenda bitens = new BLLitensVenda(cx); dgv_itens.DataSource = bitens.localizar(cod); this.orgcampos(dgv_itens, 2); //parcelas da compra BLLparcelasvenda bpc = new BLLparcelasvenda(cx); dgv_parcelas.DataSource = bpc.localizar(cod); this.orgcampos(dgv_parcelas, 3); } }//clicando 1 vez no grid private void dgvDados_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { this.codigo = Convert.ToInt32(dgvDados.Rows[e.RowIndex].Cells[0].Value); this.Close(); } }//clicando 2 vezes no grid private void btn_buscarParcelasEmAberto_Click(object sender, EventArgs e) { if (txt_parcelas.Text == "") { DALLconexao conexao = new DALLconexao(DadosDaConexao.StringDeConexao); BLLvenda bvenda = new BLLvenda(conexao); dgvDados.DataSource = bvenda.LocalizarPorParcelasEmAberto(); this.orgcampos(dgvDados, 1); } else { int cod = Convert.ToInt32(txt_parcelas.Text); DALLconexao cx = new DALLconexao(DadosDaConexao.StringDeConexao); BLLvenda bvenda = new BLLvenda(cx); dgvDados.DataSource = bvenda.Localizar(cod); this.orgcampos(dgvDados, 1); } }//btn parcelas em aberto private void rb_cliente_CheckedChanged(object sender, EventArgs e) { this.limparCampos(); if (rb_cliente.Checked) { this.pn_cliente.Visible = true; this.pn_todasCompras.Visible = false; } else { this.pn_cliente.Visible = false; } }//rb clientes private void rb_dataVenda_CheckedChanged(object sender, EventArgs e) { this.limparCampos(); if (rb_dataVenda.Checked) { this.pn_data.Visible = true; } else { this.pn_data.Visible = false; } }//rb data private void rb_parcelas_CheckedChanged(object sender, EventArgs e) { if (rb_parcelas.Checked) { this.pn_parcelas.Visible = true; this.btn_buscarParcelasEmAberto_Click(sender, e); } else { this.pn_parcelas.Visible = false; } }//rb parcelas private void pb_exit_Click(object sender, EventArgs e) { this.Close(); } private string RemoveInvalidChars(string input) { // Substitui todos os caracteres não-alfanuméricos por sublinhados string validChars = new string(input.Select(c => char.IsLetterOrDigit(c) ? c : '_').ToArray()); return validChars; } private void GerarArquivoPDF(DataGridView dgv) { // Verifica se há dados no DataGridView if (dgv.Rows.Count == 0) { MessageBox.Show("Nenhum dado disponível para exportar.", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } try { // Configuração do documento PDF Document doc = new Document(); string nomeArquivoPDF = $"relatorio_de_vendas_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.pdf"; PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream($@"C:\ibrCad\Reports\PDF\{nomeArquivoPDF}", FileMode.Create)); doc.Open(); // Adiciona cabeçalho Paragraph header = new Paragraph("Relatório de vendas\n"); header.Alignment = Element.ALIGN_CENTER; // Centraliza o texto header.Font = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12); // Define a fonte em negrito doc.Add(header); // Adiciona os cabeçalhos da tabela PdfPTable table = new PdfPTable(dgv.Columns.Count); for (int i = 0; i < dgv.Columns.Count; i++) { PdfPCell cell = new PdfPCell(new Phrase(dgv.Columns[i].HeaderText)); table.AddCell(cell); } // Adiciona os dados do DataGridView à tabela for (int i = 0; i < dgv.Rows.Count; i++) { for (int j = 0; j < dgv.Columns.Count; j++) { if (dgv.Rows[i].Cells[j].Value != null) { table.AddCell(new Phrase(dgv.Rows[i].Cells[j].Value.ToString())); } } } // Calcula a soma dos valores da coluna [5] decimal somaValores = 0; for (int i = 0; i < dgv.Rows.Count; i++) { if (dgv.Rows[i].Cells[5].Value != null && decimal.TryParse(dgv.Rows[i].Cells[5].Value.ToString(), out decimal valor)) { somaValores += valor; } } // Adiciona a frase com a soma da coluna 5 ao documento PDF doc.Add(new Phrase($"Valor das vendas R$ {somaValores.ToString("N2")}")); // Adiciona a tabela ao documento PDF doc.Add(table); doc.Close(); writer.Close(); MessageBox.Show("Arquivo PDF gerado com sucesso.", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show("Erro ao gerar arquivo PDF: " + ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void GerarArquivoXML(DataGridView dgv) { // Verifica se há dados no DataGridView if (dgv.Rows.Count == 0) { MessageBox.Show("Nenhum dado disponível para exportar.", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } try { // Configuração do documento XML XmlDocument xmlDoc = new XmlDocument(); string nomeArquivoXML = $"relatorio_de_vendas_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.xml"; XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null); xmlDoc.AppendChild(xmlDeclaration); XmlElement root = xmlDoc.CreateElement("Dados"); xmlDoc.AppendChild(root); // Adiciona os dados do DataGridView ao XML for (int i = 0; i < dgv.Rows.Count; i++) { XmlElement rowElement = xmlDoc.CreateElement("Linha"); for (int j = 0; j < dgv.Columns.Count; j++) { string columnName = RemoveInvalidChars(dgv.Columns[j].HeaderText); XmlElement cellElement = xmlDoc.CreateElement(columnName); cellElement.InnerText = dgv.Rows[i].Cells[j].Value.ToString(); rowElement.AppendChild(cellElement); } root.AppendChild(rowElement); } xmlDoc.Save($@"C:\ibrCad\Reports\XML\{nomeArquivoXML}"); MessageBox.Show("Arquivo XML gerado com sucesso.", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show("Erro ao gerar arquivo XML: " + ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btn_imprimir_Click(object sender, EventArgs e) { try { this.GerarArquivoPDF(dgvDados); } catch { } } } }