| thaita Novato
 
  
 
 Registrado: Sábado, 26 de Novembro de 2022
 Mensagens: 44
 
 
 | 
			
				|  Enviada: Dom Mai 26, 2024 5:56 pm    Assunto: Erro no procedimento Salvar(Inserir Registro) |   |  
				| 
 |  
				| Prezados, Quando tento incluir um  registro em meu Form,
 Aparece a mensagem de erro abaixo:
 
 "ERRO FIREDAC-SQLITE: 335.PARAMETER {CODIGO_COMPRA]
 DATA TYPE IS UNKNOW.HINT: SPECIFY TFDPARAM.DATATYPE
 OR ASSIGN TFDPARAM VALUEBEFORE PREPARE\EXECUTE CALL."
 
 Tenho o procedimento para InserirRegistro que está
 ocasionando um erro quando vou salvar o registro,
 referente ao campo CODIGO_COMPRA da Tabela CompraItens
 que esta ligado{FK} ao Campo Codigo da Tabela Compras.
 
 Estou utilizando o padrão MVC com interfaces.
 Seguem as tabelas e o código completo .
 ALGUÉM PODE ME AJUDAR????AGRADEÇO ANTECIPADAMENTE.
 =x=x=x=x=x=x==x=x=x=x=x==x=x=x=x=x==x=x=x=x=x==x=x=x=x=x==x=x
 CREATE TABLE compra (
 CODIGO      INTEGER         PRIMARY KEY AUTOINCREMENT,
 CPFCNPJ     VARCHAR (1
  REFERENCES Pessoa (CPFCNPJ) ON DELETE CASCADE ON UPDATE CASCADE
 NOT NULL,
 dataemissao DATE            DEFAULT CURRENT_DATE
 NOT NULL,
 valortotal  DECIMAL (17, 2)
 );
 x==x=x=x=x=x=x=x=x==x=x=x=x=x=x=x==x=x=x=x=x=x==x=x=x=x=x=x==x=x
 
 CREATE TABLE compraitens (
 Codigo           INTEGER         PRIMARY KEY AUTOINCREMENT,
 Codigo_Compra    INTEGER         REFERENCES compra (CODIGO) ON DELETE CASCADE
 ON UPDATE CASCADE,
 Codigo_Produto   INTEGER         REFERENCES produto (CODIGO)
 NOT NULL,
 Codigo_Atividade INTEGER         REFERENCES Atividade (CODIGO)
 NOT NULL,
 Codigo_Conta     INTEGER         REFERENCES PlanoContas (CodigoConta)
 NOT NULL,
 quantidade       INTEGER         NOT NULL,
 valorunitario    DECIMAL (17, 2) NOT NULL,
 valortotal       DECIMAL (17, 2)
 );
 
 =x=x=x==x=x=x=x==x=x=x=x=x=x=x=x=x==x=x=x=x=x=x=x==x=x=x=x=x=x==x=x=x=x=x=x=x=x==x=x=x=
 
 unit AdmSitio.view.pages.Compras;
 
 interface
 
 uses
 Winapi.Windows,
 Winapi.Messages,
 System.SysUtils,
 System.Variants,
 System.Classes,
 Vcl.Graphics,
 Vcl.Controls,
 Vcl.Forms,
 Vcl.Dialogs,
 Data.DB,
 AdmSitio.view.pages.CadastroPadrao,
 System.ImageList,
 Vcl.ImgList,
 Vcl.ComCtrls,
 Vcl.StdCtrls,
 Vcl.Buttons,
 Vcl.ExtCtrls, AdmSitio.controller.interfaces,
 AdmSitio.view.utils.interfaces,
 AdmSitio.controller.impl.controller,
 AdmSitio.view.utils.Utilitarios, Vcl.Mask,
 AdmSitio.View.Pages.Relatorios.Compras;
 
 type
 TPageCompras = class(TPagePadrao)
 edtCodigoCompra: TLabeledEdit;
 edtCPFCNPJ: TLabeledEdit;
 edtCodigoProduto: TLabeledEdit;
 edtNomeFornecedor: TLabeledEdit;
 edtNomeProduto: TLabeledEdit;
 edtQuantidade: TLabeledEdit;
 edtValorUnitario: TLabeledEdit;
 edtCodigoAtividade: TLabeledEdit;
 edtNomeAtividade: TLabeledEdit;
 edtDataCompra: TDateTimePicker;
 lblDataEmissao: TLabel;
 edtValorTotal: TLabeledEdit;
 edtCodigo_Conta: TLabeledEdit;
 edtNome_Conta: TLabeledEdit;
 procedure FormCreate(Sender: TObject);
 procedure FormShow(Sender: TObject);
 procedure edtValorUnitarioExit(Sender: TObject);
 procedure ListView1SelectItem(Sender: TObject; Item: TListItem;
 Selected: Boolean);
 procedure btnExcluirClick(Sender: TObject);
 procedure btnIncluirClick(Sender: TObject);
 procedure btnSalvarClick(Sender: TObject);
 procedure btnAlterarClick(Sender: TObject);
 procedure edtQuantidadeExit(Sender: TObject);
 procedure edtCPFCNPJEnter(Sender: TObject);
 procedure edtCPFCNPJExit(Sender: TObject);
 procedure edtCodigoProdutoExit(Sender: TObject);
 procedure edtCodigoProdutoKeyPress(Sender: TObject; var Key: Char);
 procedure edtCodigoAtividadeKeyPress(Sender: TObject; var Key: Char);
 procedure edtCodigoAtividadeExit(Sender: TObject);
 procedure btnImprimirClick(Sender: TObject);
 procedure edtCodigo_ContaKeyPress(Sender: TObject; var Key: Char);
 procedure edtCodigo_ContaExit(Sender: TObject);
 procedure edtCPFCNPJKeyPress(Sender: TObject; var Key: Char);
 procedure edtValorTotalChange(Sender: TObject);
 procedure edtValorUnitarioChange(Sender: TObject);
 procedure edtValorUnitarioEnter(Sender: TObject);
 private
 FController: iController;
 procedure CalcularValorTotal;
 procedure InserirRegistro;
 procedure SearchPessoa;
 function ValidateAndFormatCPFCNPJ: Boolean;
 procedure HandleCPFCNPJExit;
 public
 { Public declarations }
 end;
 
 var
 PageCompras: TPageCompras;
 
 implementation
 
 {$R *.dfm}
 
 procedure TPageCompras.btnAlterarClick(Sender: TObject);
 begin
 inherited;
 if ListView1.Selected <> nil then
 begin
 if ListView1.Selected.SubItems[0] <then> 0 then
 ShowMessage('Erro: Código da compra já existe!')
 else
 ShowMessage('Erro de banco de dados: ' + E.Message);
 on E: Exception do
 ShowMessage('Erro geral: ' + E.Message);
 end;
 end;
 
 procedure TPageCompras.CalcularValorTotal;
 var
 Quantidade: Integer;
 ValorUnitario, ValorTotal: Currency;
 begin
 if TryStrToInt(edtQuantidade.Text, Quantidade) and
 TryStrToCurr(edtValorUnitario.Text, ValorUnitario) then
 begin
 ValorTotal := Quantidade * ValorUnitario;
 edtValorTotal.Text := CurrToStr(ValorTotal);
 end;
 end;
 
 procedure TPageCompras.edtCodigoAtividadeExit(Sender: TObject);
 var
 lId: Integer;
 begin
 inherited;
 if TryStrToInt(edtCodigoAtividade.Text, lId) then
 begin
 var lDataSource := TDataSource.Create(nil);
 try
 FController.Atividade.Build.Datasource(lDataSource).ListarPorId(lId);
 
 if not lDataSource.DataSet.IsEmpty then
 begin
 edtNomeAtividade.Text := lDataSource.DataSet.FieldByName('Nome_Atividade').AsString;
 Exit;
 end
 else
 begin
 ShowMessage('Não foi possível encontrar nenhuma atividade com o código informado!');
 edtNomeAtividade.Clear;
 
 end;
 finally
 lDataSource.Free;
 end;
 end
 else
 begin
 ShowMessage('Código de atividade inválido!');
 edtNomeAtividade.Clear;
 end;
 end;
 
 procedure TPageCompras.edtCodigoAtividadeKeyPress(Sender: TObject;
 var Key: Char);
 begin
 inherited;
 TUtilitarios.SomenteNumeros(key);
 end;
 
 procedure TPageCompras.edtCodigoProdutoExit(Sender: TObject);
 var
 lId: Integer;
 begin
 inherited;
 if TryStrToInt(edtCodigoProduto.Text, lId) then
 begin
 var lDataSource := TDataSource.Create(nil);
 try
 FController.Produto.Build.Datasource(lDataSource).ListarPorId(lId);
 
 if not lDataSource.DataSet.IsEmpty then
 begin
 edtNomeProduto.Text := lDataSource.DataSet.FieldByName('Descricao').AsString;
 //edtValorUnitario.Text := FormatCurr('"R$ ",0.00', lDataSource.DataSet.FieldByName('Preco').AsCurrency);
 edtQuantidade.SetFocus;
 Exit;
 end
 else
 begin
 ShowMessage('Não foi possível encontrar nenhum produto com o código informado!');
 edtNomeProduto.Clear;
 edtValorUnitario.Clear;
 end;
 finally
 lDataSource.Free;
 end;
 end
 else
 begin
 ShowMessage('Código de produto inválido!');
 edtNomeProduto.Clear;
 edtValorUnitario.Clear;
 end;
 
 end;
 
 procedure TPageCompras.edtCodigoProdutoKeyPress(Sender: TObject; var Key: Char);
 begin
 inherited;
 TUtilitarios.SomenteNumeros(key);
 end;
 
 procedure TPageCompras.edtCodigo_ContaExit(Sender: TObject);
 var
 lId: Integer;
 begin
 inherited;
 if TryStrToInt(edtCodigo_Conta.Text, lId) then
 begin
 var lDataSource := TDataSource.Create(nil);
 try
 FController.PlanoContas.Build.Datasource(lDataSource).ListarPorId(lId);
 
 if not lDataSource.DataSet.IsEmpty then
 begin
 edtNome_Conta.Text := lDataSource.DataSet.FieldByName('NomeConta').AsString;
 Exit;
 end
 else
 begin
 ShowMessage('Não foi possível encontrar nenhuma conta com o código informado!');
 edtNome_Conta.Clear;
 
 end;
 finally
 lDataSource.Free;
 end;
 end
 else
 begin
 ShowMessage('Código de Plano de Contas inválido!');
 edtNome_Conta.Clear;
 end;
 
 end;
 
 procedure TPageCompras.edtCodigo_ContaKeyPress(Sender: TObject; var Key: Char);
 begin
 inherited;
 TUtilitarios.SomenteNumeros(key);
 end;
 
 procedure TPageCompras.edtCPFCNPJEnter(Sender: TObject);
 var
 I: Integer;
 S, Texto: string;
 begin
 inherited;
 S := '';
 Texto := edtCPFCNPJ.Text;
 for I := 1 to Length(Texto) do
 begin
 if Texto[I] in ['0' .. '9'] then
 begin
 S := S + Texto[I];
 end;
 end;
 edtCPFCNPJ.Text := S;
 end;
 
 procedure TPageCompras.edtCPFCNPJExit(Sender: TObject);
 begin
 inherited;
 HandleCPFCNPJExit;
 end;
 
 procedure TPageCompras.edtCPFCNPJKeyPress(Sender: TObject; var Key: Char);
 begin
 inherited;
 TUtilitarios.SomenteNumeros(key);
 end;
 
 procedure TPageCompras.edtQuantidadeExit(Sender: TObject);
 begin
 inherited;
 CalcularValorTotal;
 end;
 
 procedure TPageCompras.edtValorTotalChange(Sender: TObject);
 begin
 inherited;
 edtValorTotal.Text := TUtilitarios.FormatarValor(edtValorTotal.Text);
 end;
 
 procedure TPageCompras.edtValorUnitarioChange(Sender: TObject);
 begin
 inherited;
 // CalcularValorTotal;
 end;
 
 procedure TPageCompras.edtValorUnitarioEnter(Sender: TObject);
 begin
 inherited;
 CalcularValorTotal;;
 end;
 
 procedure TPageCompras.edtValorUnitarioExit(Sender: TObject);
 begin
 inherited;
 CalcularValorTotal;
 edtValorUnitario.Text := TUtilitarios.FormatarValor(edtValorUnitario.Text);
 edtValorTotal.Text := TUtilitarios.FormatarValor(edtValorTotal.Text);
 
 end;
 
 procedure TPageCompras.FormCreate(Sender: TObject);
 begin
 inherited;
 FController := TController.New;
 edtValorUnitario.OnKeyPress := TUtilitarios.KeyPressValor;
 edtValorTotal.OnKeyPress := TUtilitarios.KeyPressValor;
 
 end;
 
 procedure TPageCompras.FormShow(Sender: TObject);
 var
 lList: TListItem;
 lDataSource: TDataSource;
 begin
 inherited;
 ListView1.Items.Clear;
 lDataSource := TDataSource.Create(nil);
 try
 FController.Compra.Build.DataSource(lDataSource).ListarTodos;
 if lDataSource.DataSet.IsEmpty then
 begin
 ShowMessage('Não existem dados a serem visualizados');
 Exit;
 end;
 begin
 FController.CompraItens.Build.DataSource(lDataSource).ListarTodos;
 end;
 lDataSource.DataSet.First;
 while not lDataSource.DataSet.Eof do
 begin
 lList := ListView1.Items.Add;
 lList.Caption := lDataSource.Dataset.FieldByName('CPFCNPJ').AsString;
 lList.SubItems.Add(lDataSource.Dataset.FieldByName('CODIGO_COMPRA').AsString);
 lList.SubItems.Add(IntToStr(lDataSource.Dataset.FieldByName('CODIGO_PRODUTO').AsInteger));
 lList.SubItems.Add(IntToStr(lDataSource.Dataset.FieldByName('CODIGO_ATIVIDADE').AsInteger));
 lList.SubItems.Add(IntToStr(lDataSource.Dataset.FieldByName('CODIGO_CONTA').AsInteger));
 lList.SubItems.Add(FloatToStr(lDataSource.Dataset.FieldByName('QUANTIDADE').AsFloat));
 lList.SubItems.Add(CurrToStr(lDataSource.Dataset.FieldByName('VALOR_UNITARIO').AsCurrency));
 lList.SubItems.Add(CurrToStr(lDataSource.Dataset.FieldByName('VALOR_TOTAL').AsCurrency));
 lList.SubItems.Add(FormatDateTime('dd/mm/yyyy', lDataSource.Dataset.FieldByName('DATAEMISSAO').AsDateTime));
 lDataSource.Dataset.Next;
 
 end;
 finally
 lDataSource.DisposeOf;
 end;
 
 end;
 
 procedure TPageCompras.HandleCPFCNPJExit;
 var
 IsValid: Boolean;
 begin
 if edtCPFCNPJ.Text = '' then
 Exit;
 
 IsValid := ValidateAndFormatCPFCNPJ;
 if not IsValid then
 Exit;
 SearchPessoa;
 
 end;
 
 procedure TPageCompras.InserirRegistro;
 var
 NewCompraID: Integer;
 begin
 // Adiciona mensagens de log para verificar o fluxo do método
 ShowMessage('Iniciando inserção de registro.');
 
 TUtilitarios.VerificaCampoVazio(edtCPFCNPJ, 'CPF ou CNPJ');
 TUtilitarios.VerificaCampoVazio(edtCodigoProduto, 'Código do Produto');
 TUtilitarios.VerificaCampoVazio(edtQuantidade, 'Quantidade');
 TUtilitarios.VerificaCampoVazio(edtValorUnitario, 'Valor Unitário');
 TUtilitarios.VerificaCampoVazio(edtCodigoAtividade, 'Código da Atividade');
 TUtilitarios.VerificaCampoVazio(edtCodigo_Conta, 'Código da Conta');
 TUtilitarios.VerificaCampoVazio(edtDataCompra, 'Data da Compra');
 
 try
 ShowMessage('Verificações de campo concluídas. Inserindo compra...');
 
 with FController.Compra do
 begin
 CPFCNPJ(edtCPFCNPJ.Text);
 DATAEMISSAO(edtDataCompra.Date);
 VALORTOTAL(StrToCurrDef(edtValorTotal.Text, 0.00));
 Build.Inserir;
 NewCompraID := CODIGO; // Supondo que `Codigo` retorna o ID da compra recém-inserida
 ShowMessage('Compra inserida com sucesso. ID: ' + IntToStr(NewCompraID));
 end;
 
 ShowMessage('Inserindo itens da compra...');
 
 with FController.CompraItens do
 begin
 // CODIGO(TUtilitarios.GetID);
 CODIGO_COMPRA(NewCompraID); // Atribuir o ID da nova compra aqui
 CODIGO_PRODUTO(StrToInt(edtCodigoProduto.Text));
 CODIGO_ATIVIDADE(StrToInt(edtCodigoAtividade.Text));
 CODIGO_CONTA(StrToInt(edtCodigo_Conta.Text));
 QUANTIDADE(StrToInt(edtQuantidade.Text));
 VALORUNITARIO(StrToCurrDef(edtValorUnitario.Text, 0.00));
 VALORTOTAL(StrToCurrDef(edtValorTotal.Text, 0.00));
 Build.Inserir;
 ShowMessage('Itens da compra inseridos com sucesso.');
 end;
 
 ShowMessage('Compra cadastrada com sucesso!');
 except
 on E: Exception do
 begin
 ShowMessage('Erro ao tentar cadastrar a compra: ' + E.Message);
 raise;
 end;
 end;
 end;
 
 
 
 
 procedure TPageCompras.ListView1SelectItem(Sender: TObject; Item: TListItem;
 Selected: Boolean);
 begin
 inherited;
 if Selected then
 begin
 edtCpfCnpj.Text := Item.Caption;
 edtCodigoCompra.Text := Item.SubItems[0];
 edtCodigoProduto.Text := Item.SubItems[1];
 edtCodigoAtividade.Text := Item.SubItems[2];
 edtCodigo_Conta.Text := Item.SubItems[3];
 edtQuantidade.Text := Item.SubItems[4];
 edtValorUnitario.Text := Item.SubItems[5];
 edtValorTotal.Text := Item.SubItems[6];
 edtDataCompra.Date := StrToDate(Item.SubItems[7]);
 
 end;
 end;
 
 procedure TPageCompras.SearchPessoa;
 var
 DataSourcePessoa: TDataSource;
 begin
 DataSourcePessoa := TDataSource.Create(nil);
 try
 FController.Pessoa.Build.ListarPor('CPFCNPJ', edtCPFCNPJ.Text).DataSource(DataSourcePessoa);
 
 if not DataSourcePessoa.DataSet.IsEmpty then
 begin
 edtNomeFornecedor.Text := DataSourcePessoa.DataSet.FieldByName('Nome').AsString;
 end
 else
 begin
 ShowMessage('Fornecedor não encontrado para o CPF/CNPJ informado.');
 edtNomeFornecedor.Text := '';
 end;
 finally
 DataSourcePessoa.Free;
 end;
 end;
 
 function TPageCompras.ValidateAndFormatCPFCNPJ: Boolean;
 var
 FormatarCNPJ, FormatarCPF: String;
 begin
 Result := False;
 if Length(edtCPFCNPJ.Text) = 14 then
 begin
 if TUtilitarios.cnpj(edtCPFCNPJ.Text) then
 begin
 FormatarCNPJ := Copy(edtCPFCNPJ.Text, 1, 2) + '.' +
 Copy(edtCPFCNPJ.Text, 3, 3) + '.' +
 Copy(edtCPFCNPJ.Text, 6, 3) + '/' +
 Copy(edtCPFCNPJ.Text, 9, 4) + '-' +
 Copy(edtCPFCNPJ.Text, 13, 2);
 edtCPFCNPJ.Text := FormatarCNPJ;
 Label1.Caption := 'CNPJ';
 Result := True;
 end
 else
 begin
 ShowMessage('CNPJ com erro. Favor verificar.');
 edtCPFCNPJ.SetFocus;
 Exit;
 end;
 end
 else if Length(edtCPFCNPJ.Text) = 11 then
 begin
 if TUtilitarios.cpf(edtCPFCNPJ.Text) then
 begin
 FormatarCPF := Copy(edtCPFCNPJ.Text, 1, 3) + '.' +
 Copy(edtCPFCNPJ.Text, 4, 3) + '.' +
 Copy(edtCPFCNPJ.Text, 7, 3) + '-' +
 Copy(edtCPFCNPJ.Text, 10, 2);
 edtCPFCNPJ.Text := FormatarCPF;
 Label1.Caption := 'CPF';
 Result := True;
 end
 else
 begin
 ShowMessage('CPF com erro. Favor verificar.');
 edtCPFCNPJ.SetFocus;
 Exit;
 end;
 end
 else
 begin
 ShowMessage('O CPF tem 11 números e o CNPJ tem 14 números.'#13'Preencha com números.');
 edtCPFCNPJ.SetFocus;
 edtCPFCNPJ.SelectAll;
 Exit;
 end;
 
 end;
 
 end.
 |  |