Não é a linguagem de programação que define o programador, mas sim sua lógica

Geração de parcelas



É super normal em nossos sistemas ter parcelas, principalmente em Vendas/Compras. Para criarmos o exemplo, vamos imaginar uma vendas em que o cliente queira parcelar o valor total em 12 vezes. Neste cenário, informaremos o valor total, a quantidade de parcelas e a quantidade entre os vencimentos.



Vamos precisar de:

2 - TDBGrid { dbgridCDSPai, dbgridCDSFilho };
2 - TClientDataSet { CDSPai, CDSFilho };
2 - TDataSource { dsCDSPai, dsCDSFilho };

Coloque os componente de acordo com a estrutura abaixo;

Na tabela CDSPai crie os campos:
DESCRICAO "string"; 
CODIGO "Integer"; 
NUMERO_PARCELA "Integer"; 
DIAS_ENTRE_PARCELAS "Integer"; 
VALOR "currency"; 


Na tabela CDSFilho crie os campos:
DATA_VENCIMENTO "Date"; 
NUMERO_PARCELA "Integer"; 
VALOR "currency"; 

Vamos começar com os códigos;

No evento OnNewRecord do componente CDSFilho
procedure TFPrincipal.CDSFilhoNewRecord(DataSet: TDataSet);
begin
   CDSFilhoCODIGO.Value := CDSPaiCODIGO.Value;
end;
No Change dos campos VALOR, PARCELA e NUMERO_PARCELA coloque o código abaixo;
procedure TFPrincipal.CDSPaiVALORChange(Sender: TField);
Var
  k: Integer;
  wData : TDate;
  wValorTotal : Double;
begin
  wData := Date;
  wValorTotal := CDSPaiVALOR.Value;
  if (CDSPaiNUMERO_PARCELA.Value > 0) and (CDSPaiVALOR.Value > 0) and (CDSPaiDIAS_ENTRE_PARCELAS.Value > 0) then begin
    for k := 1 to CDSPaiNUMERO_PARCELA.Value do begin
      if not CDSFilho.Locate('NUMERO_PARCELA', k, []) then begin
        CDSFilho.Append;
        CDSFilho.FieldByName('NUMERO_PARCELA').AsInteger := k;
      end else
        CDSFilho.Edit;
      wData := wData + CDSPaiDIAS_ENTRE_PARCELAS.AsInteger;
      CDSFilhoDATA_VENCIMENTO.AsDateTime := wData;
      CDSFilhoVALOR.AsCurrency := CDSPaiVALOR.Value / CDSPaiNUMERO_PARCELA.Value;
      CDSFilho.Post;
      wValorTotal := wValorTotal - CDSFilhoVALOR.AsCurrency;
    end;
    CDSFilho.Last;
    while CDSFilhoNUMERO_PARCELA.AsInteger > CDSPaiNUMERO_PARCELA.Value do
      CDSFilho.Delete;
    if CompareValue(wValorTotal, 0.00, 0.001) <> EqualsValue then begin
      CDSFilho.Edit;
      CDSFilhoVALOR.AsCurrency := CDSFilhoVALOR.AsCurrency + wValorTotal;
      CDSFilho.Post;
    end;
    CDSFilho.First;
  end;
end;
No código acima passamos dividindo o valor total entre a quantidade de parcelas, e a data de vencimento vamos acrescentando o campo dias entre parcelas "Normalmente e 30 dias" mas sempre tem suas exerções.

Resultado


6 comentários: