Levelcode-IBRCAD/IBRCAD/frm_movimentacaocompra.cs

705 lines
28 KiB
C#

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_movimentacaocompra : Form
{
public string operacao;
private double totalcompra;
public frm_movimentacaocompra()
{
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;
}
}
private void displayclear()
{
this.txt_comp_cod.Text = "";
this.txt_notafiscal.Text = "";
this.txt_forcod.Text = "";
this.txt_nomeFor.Text = "";
this.txt_procod.Text = "";
this.txt_proname.Text = "";
this.txtqtde.Text = "";
this.txtValorUnitario.Text = "";
this.txtTotal.Text = "";
this.dgCompra.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.totalcompra = 0;
this.alterabotoes(2);
}//btn inserir
private void btn_localizar_Click(object sender, EventArgs e)
{
frm_consultacompra fc = new frm_consultacompra();
fc.ShowDialog();
if (fc.codigo != 0)
{
DALLconexao cx = new DALLconexao(DadosDaConexao.StringDeConexao);
BLLCompra bcompra = new BLLCompra(cx);
ModeloCompra mcompra = bcompra.CarregaModeloCompra(fc.codigo);
txt_comp_cod.Text = mcompra.ComCod.ToString();
txt_notafiscal.Text = mcompra.ComNFiscal.ToString();
dtpDatacompra.Value = mcompra.ComData;
cbTipoPag.SelectedValue = mcompra.TpaCod;
cbParcelas.SelectedValue = mcompra.ComNParcelas;
cbParcelas.Text = mcompra.ComNParcelas.ToString();
txt_forcod.Text = mcompra.ForCod.ToString();
txt_forcod_Leave(sender, e);
txtTotal.Text = mcompra.ComTotal.ToString();
this.totalcompra = mcompra.ComTotal;
//itens da compra
BLLitensCompra bitens = new BLLitensCompra(cx);
DataTable tabela = bitens.localizar(mcompra.ComCod);
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]["itc_qtde"].ToString();
string ivalorU = tabela.Rows[i]["itc_valor"].ToString();
double valorTotal = Convert.ToDouble(tabela.Rows[i]["itc_qtde"]) * Convert.ToDouble(tabela.Rows[i]["itc_valor"]);
string[] it = new string[] { icod, inome, iqtde, ivalorU, valorTotal.ToString() };
this.dgCompra.Rows.Add(it);
}
this.alterabotoes(3);
}
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_comp_cod.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)
{
try
{
DialogResult d = MessageBox.Show("Deseja excluir o registro?", "Aviso", MessageBoxButtons.YesNo);
if (d.ToString() == "Yes")
{
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_comp_cod.Text);
int qtde = Convert.ToInt32(cbParcelas.Text);
qtde -= bLLCompra.verificarParcelasEmAberto(comcod);
if (qtde == 0)
{
cx.Conectar();
cx.IniciarTransacao();
try
{
bparcelas.ExcluirTodasAsParcelas(comcod);
bitens.ExcluirTodosOsItens(comcod);
bLLCompra.Excluir(comcod);
MessageBox.Show("A compra foi excluida!");
this.displayclear();
this.alterabotoes(1);
cx.TerminarTransacao();
cx.Desconectar();
}
catch (Exception erro)
{
MessageBox.Show(erro.Message);
cx.cancelarTransacao();
cx.Desconectar();
}
}
else
{
MessageBox.Show("Não foi possivel excluir o registro! pois existe parcelas pagas ", "Parcelas!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
catch
{
MessageBox.Show("Impossível excluir o registro. \n O registro esta sendo utilizado em outro local.");
this.alterabotoes(3);
}
}//end delete
private void btn_save_Click(object sender, EventArgs e)
{
try
{
Convert.ToInt32(txtTotal.Text);
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();
lblTotalCompra.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.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;
}
catch (Exception)
{
MessageBox.Show("Existe campos faltando a serem preenchidos");
}
}//end save 1
private void btn_cancel_Click(object sender, EventArgs e)
{
this.alterabotoes(1);
this.displayclear();
this.totalcompra = 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
ModeloCompra modelo = new ModeloCompra();
ModeloitensCompra mitens = new ModeloitensCompra();
ModeloParcelasCompra mparcelas = new ModeloParcelasCompra();
modelo.ComData = dtpDatacompra.Value;
modelo.ComNFiscal = Convert.ToInt32(txt_notafiscal.Text);
modelo.ComNParcelas = Convert.ToInt32(cbParcelas.SelectedItem);
modelo.ComStatus = "ativo";
//modelo.ComTotal = this.totalCompra;
modelo.ComTotal = Convert.ToInt32(lblTotalCompra.Text);
modelo.ForCod = Convert.ToInt32(txt_forcod.Text);
modelo.TpaCod = Convert.ToInt32(cbTipoPag.SelectedValue);
//inicializando blls
BLLCompra bll = new BLLCompra(cx);
BLLparcelascompra bparcelas = new BLLparcelascompra(cx);
BLLitensCompra bLLitensCompra = new BLLitensCompra(cx);
if (this.operacao == "inserir")
{
bll.Incluir(modelo);
int procod;
for (int i = 0; i < dgCompra.RowCount; i++)
{
mitens.ItcCod = i + 1;
mitens.ComCod = modelo.ComCod;
procod = Convert.ToInt32(dgCompra.Rows[i].Cells[0].Value);
mitens.ProCod = procod;
mitens.ItcQtd = Convert.ToInt32(dgCompra.Rows[i].Cells[2].Value);
mitens.Valor = Convert.ToDouble(dgCompra.Rows[i].Cells[3].Value);
bLLitensCompra.Incluir(mitens);
}
for (int i = 0; i < dgvParcelas.RowCount; i++)
{
mparcelas.Com_cod = modelo.ComCod;
mparcelas.Pco_cod = Convert.ToInt32(dgvParcelas.Rows[i].Cells[0].Value);
mparcelas.Pco_valor = Convert.ToDouble(dgvParcelas.Rows[i].Cells[1].Value);
mparcelas.Datavenci = Convert.ToDateTime(dgvParcelas.Rows[i].Cells[2].Value);
bparcelas.Incluir(mparcelas);
}
MessageBox.Show("Cadastro efetuado: Código : " + modelo.ComCod.ToString());
}
else
{
//alterar
modelo.ComCod = Convert.ToInt32(txt_comp_cod.Text);
bLLitensCompra.ExcluirTodosOsItens(modelo.ComCod);
bll.Alterar(modelo);
for (int i = 0; i < dgCompra.RowCount; i++)
{
mitens.ItcCod = i + 1;
mitens.ComCod = modelo.ComCod;
mitens.ProCod = Convert.ToInt32(dgCompra.Rows[i].Cells[0].Value);
mitens.ItcQtd = Convert.ToInt32(dgCompra.Rows[i].Cells[2].Value);
mitens.Valor = Convert.ToDouble(dgCompra.Rows[i].Cells[3].Value);
bLLitensCompra.Incluir(mitens);
}//itens compra
bparcelas.ExcluirTodasAsParcelas(modelo.ComCod);
for (int i = 0; i < dgvParcelas.RowCount; i++)
{
mparcelas.Com_cod = modelo.ComCod;
mparcelas.Pco_cod = Convert.ToInt32(dgvParcelas.Rows[i].Cells[0].Value);
mparcelas.Pco_valor = Convert.ToDouble(dgvParcelas.Rows[i].Cells[1].Value);
mparcelas.Datavenci = Convert.ToDateTime(dgvParcelas.Rows[i].Cells[2].Value);
bparcelas.Incluir(mparcelas);
}
MessageBox.Show("Cadastro Alterado com sucesso!", "Atualização de Cadastro");
}
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.totalcompra = 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_consultafornecedor f = new frm_consultafornecedor();
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_forcod.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_forcod_Leave(sender, e);
}
f.Dispose();
}
private void txt_forcod_Leave(object sender, EventArgs e)
{
try
{
DALLconexao cx = new DALLconexao(DadosDaConexao.StringDeConexao);
BLLFornecedor bll = new BLLFornecedor(cx);
ModeloFornecedor modelo = bll.CarregaModeloFornecedor(Convert.ToInt32(txt_forcod.Text));
this.txt_nomeFor.Text = modelo.ForNome;
}
catch
{
this.txt_forcod.Text = "";
MessageBox.Show("Informe o nome do fornecedor" + "\n clicando em 'LOCALIZAR'");
}
}//end leave
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)
{
if ((txt_procod.Text != "") && (txtqtde.Text != "") && (txtValorUnitario.Text != ""))
{
double valorTotal = Convert.ToDouble(txtqtde.Text) * Convert.ToDouble(txtValorUnitario.Text);
totalcompra = totalcompra + valorTotal;
string[] i = new string[] { txt_procod.Text, txt_proname.Text, txtqtde.Text, txtValorUnitario.Text, valorTotal.ToString() };
this.dgCompra.Rows.Add(i);
//limpar os campos
//this.txt_procod.Text = "";
//this.txt_proname.Text = "";
//this.txtqtde.Text = "";
//this.txtValorUnitario.Text = "";
txtTotal.Text = totalcompra.ToString();
}
}//end add produto
private void dgCompra_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
txt_procod.Text = dgCompra.Rows[e.RowIndex].Cells[0].Value.ToString();
txt_proname.Text = dgCompra.Rows[e.RowIndex].Cells[1].Value.ToString();
txtqtde.Text = dgCompra.Rows[e.RowIndex].Cells[2].Value.ToString();
txtValorUnitario.Text = dgCompra.Rows[e.RowIndex].Cells[3].Value.ToString();
double valor = Convert.ToDouble(dgCompra.Rows[e.RowIndex].Cells[4].Value);
this.totalcompra = this.totalcompra - valor;
dgCompra.Rows.RemoveAt(e.RowIndex);
txtTotal.Text = this.totalcompra.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(dgCompra);
}//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
}
}