unit Factu;

interface

uses
  SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
  StdCtrls, Forms, DBCtrls, DB, DBTables, Mask, ExtCtrls, Grids, DBGrids,
  Buttons,Dialogos, Menus, Printers, ComCtrls, Tabnotbk,conver,checa,describe,tablas,
  Tabs,Apertura,RepoSQL;

type
  TFormaFactura = class(TForm)
    FuenteTablaFacturae: TDataSource;
    TablaFacturae: TTable;
    TablaDeta: TTable;
    FuenteTablaDeta: TDataSource;
    TablaCliente: TTable;
    TablaInventario: TTable;
    TablaFacturaD: TTable;
    TablaVendedores: TTable;
    TablamovimientosInventario: TTable;
    TablaCuentasxCobrar: TTable;
    MainMenu1: TMainMenu;
    Archivo1: TMenuItem;
    Salir1: TMenuItem;
    Registro1: TMenuItem;
    Nuevo1: TMenuItem;
    Modificar1: TMenuItem;
    Guardar1: TMenuItem;
    Buscar1: TMenuItem;
    Imprimir1: TMenuItem;
    Reportes1: TMenuItem;
    Ayuda1: TMenuItem;
    Consultas1: TMenuItem;
    TablaDetaCANTIDAD: TFloatField;
    TablaDetaPRECIO: TCurrencyField;
    TablaDetaDESCUENTO: TFloatField;
    TablaDetaIMPORTE: TCurrencyField;
    Label13: TLabel;
    Concentrar1: TMenuItem;
    Panel1: TPanel;
    BotonTotales: TSpeedButton;
    BotonSalir: TSpeedButton;
    BotonPago: TSpeedButton;
    BotonBuscar: TSpeedButton;
    BotonCambios: TSpeedButton;
    Label14: TLabel;
    Navegador: TDBNavigator;
    Base: TComboBox;
    Panel2: TPanel;
    caja: TScrollBox;
    Label3: TLabel;
    Label4: TLabel;
    Label5: TLabel;
    Label7: TLabel;
    Label9: TLabel;
    Label16: TLabel;
    Label17: TLabel;
    IvaEtiqueta: TLabel;
    usuario: TLabel;
    EditCLDOC_F: TDBEdit;
    EditCLCLI_F: TDBEdit;
    EditBCLIM_F: TDBEdit;
    EditCLVEN_F: TDBEdit;
    EditDESFI_F: TDBEdit;
    EditCTOVE_F: TDBEdit;
    EditIMIM1_F: TDBEdit;
    EditFEDOC_F: TMaskEdit;
    Estado: TLabel;
    Comisiones1: TMenuItem;
    BotonNuevo: TSpeedButton;
    BotonGuardar: TSpeedButton;
    BotonImprimir: TSpeedButton;
    ConsecutivodeFacturas1: TMenuItem;
    Eliminar1: TMenuItem;
    TablaObservacion: TTable;
    ComisionesDetallado1: TMenuItem;
    Generar1: TMenuItem;
    Pedido1: TMenuItem;
    Remisin1: TMenuItem;
    Factura1: TMenuItem;
    TablaDetaCOSTO: TCurrencyField;
    VentasyUtilidad1: TMenuItem;
    BotonPreliminar: TSpeedButton;
    Calculadora1: TMenuItem;
    Opciones1: TMenuItem;
    Divisas1: TMenuItem;
    TotalesporDivisa1: TMenuItem;
    ImprimirDocumento1: TMenuItem;
    ImprimirRangodeDocumentos1: TMenuItem;
    Detalle: TDBGrid;
    Cancelar1: TMenuItem;
    Bevel1: TBevel;
    Bevel3: TBevel;
    Bevel8: TBevel;
    Bevel12: TBevel;
    Bevel15: TBevel;
    Bevel16: TBevel;
    Formatos: TMenuItem;
    Elegirformato1: TMenuItem;
    DisearFormato1: TMenuItem;
    FacturasFechaeImportes1: TMenuItem;
    BotonObservacion: TSpeedButton;
    Devolucin1: TMenuItem;
    NotadeCrdito1: TMenuItem;
    VentasporDa1: TMenuItem;
    VentasporMes1: TMenuItem;
    Ventasporao1: TMenuItem;
    VentasporArtculo1: TMenuItem;
    ImprimePlantilla1: TMenuItem;
    DocumentosCancelados1: TMenuItem;
    Temas1: TMenuItem;
    CancelaMovimiento1: TMenuItem;
    DesgloceporMoneda1: TMenuItem;
    TablaAuxiliar: TTable;
    TablaDetaCLAVE: TStringField;
    TablaDetaPRODUCTO: TStringField;
    Panel3: TPanel;
    Label12: TLabel;
    SumarTotal: TLabel;
    Label22: TLabel;
    ImpuestoValor: TLabel;
    Label24: TLabel;
    TotalFact: TLabel;
    Panel4: TPanel;
    uno: TLabel;
    dos: TLabel;
    Label2: TLabel;
    SuCambio: TLabel;
    CAMBIO_F: TDBEdit;
    VerFunciones1: TMenuItem;
    UtilidadporProducto1: TMenuItem;
    TabSet1: TTabSet;
    FacturadeCierre1: TMenuItem;
    CortedeCaja1: TMenuItem;
    Nombre: TLabel;
    TablaDetaIMPUESTO: TFloatField;
    TipoPago: TComboBox;
    Direccion: TLabel;
    Label8: TLabel;
    Direc2: TLabel;
    Poblacion: TLabel;
    RFC: TLabel;
    CodigoPostal: TLabel;
    RangodeDocumentos1: TMenuItem;
    Label1: TLabel;
    ConfigurarCaja1: TMenuItem;
    Label6: TLabel;
    Funciones: TLabel;
    Hora: TLabel;
    UtilidadporProductoConcentrado1: TMenuItem;
    CuentaporCobrar1: TMenuItem;
    VentadeTiendaporProducto1: TMenuItem;
    TablaDetaFACTOR: TFloatField;
    TablaDetaTARA: TStringField;
    Artculosmsvendidos1: TMenuItem;
    TablaDetaFPGC: TFloatField;
    TablaDetaUNIDAD: TStringField;
    procedure FormCreate(Sender: TObject);
    procedure EditCLCLI_FExit(Sender: TObject);
    procedure BotonNuevoClick(Sender: TObject);
    procedure BotonGuardarClick(Sender: TObject);
    procedure NavegadorClick(Sender: TObject; Button: TNavigateBtn);
    procedure DetalleColEnter(Sender: TObject);
    procedure EditCLCLI_FKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure EditCLVEN_FKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure EditCLVEN_FExit(Sender: TObject);
    procedure EditFEDOC_FEnter(Sender: TObject);
    procedure DetalleKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure FormActivate(Sender: TObject);
    procedure EditNALMA_FKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure EditFEDOC_FKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure EditIMIM1_FEnter(Sender: TObject);
    procedure EditDESFI_FEnter(Sender: TObject);
    procedure BotonSalirClick(Sender: TObject);
    procedure Consultas1Click(Sender: TObject);
    procedure EditCLDOC_FKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure BotonBuscarClick(Sender: TObject);
    procedure BotonCambiosClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure BotonImprimirClick(Sender: TObject);
    procedure DetalleEditButtonClick(Sender: TObject);
    procedure FolderChange(Sender: TObject; NewTab: Integer;
      var AllowChange: Boolean);
    procedure BaseChange(Sender: TObject);
    procedure EditCLDOC_FEnter(Sender: TObject);
    procedure EditCLCLI_FEnter(Sender: TObject);
    procedure EditBCLIM_FEnter(Sender: TObject);
    procedure EditCLVEN_FEnter(Sender: TObject);
    procedure EditCTOVE_FEnter(Sender: TObject);
    procedure EditCLPED_FEnter(Sender: TObject);
    procedure EditDECOT_FEnter(Sender: TObject);
    procedure Concentrar1Click(Sender: TObject);
    procedure Comisiones1Click(Sender: TObject);
    procedure EditFEDOC_FExit(Sender: TObject);
    procedure EditCLDOC_FMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure EditCLCLI_FMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure EditCLVEN_FMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure EditCTOVE_FMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure EditBCLIM_FMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure EditCLPED_FMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure EditFEDOC_FMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure EditIMIM1_FMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure EditDESFI_FMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure EditDECOT_FMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure EditNALMA_FMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure EditREMIS_FKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure EditCONDI_FKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure EditDESTI_FKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure ConsecutivodeFacturas1Click(Sender: TObject);
    procedure Eliminar1Click(Sender: TObject);
    procedure ComisionesDetallado1Click(Sender: TObject);
    procedure Factura1Click(Sender: TObject);
    procedure Remisin1Click(Sender: TObject);
    procedure Pedido1Click(Sender: TObject);
    procedure VentasyUtilidad1Click(Sender: TObject);
    procedure BotonPreliminarClick(Sender: TObject);
    procedure Calculadora1Click(Sender: TObject);
    procedure Divisas1Click(Sender: TObject);
    procedure ImprimirRangodeDocumentos1Click(Sender: TObject);
    procedure Cancelar1Click(Sender: TObject);
    procedure BotonTotalesClick(Sender: TObject);
    procedure EditDECOT_FKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure Elegirformato1Click(Sender: TObject);
    procedure DisearFormato1Click(Sender: TObject);
    procedure TablaFacturaeEditError(DataSet: TDataSet; E: EDatabaseError;
      var Action: TDataAction);
    procedure TablaFacturaePostError(DataSet: TDataSet; E: EDatabaseError;
      var Action: TDataAction);
    procedure EditCLDOC_FExit(Sender: TObject);
    procedure EditCTOVE_FExit(Sender: TObject);
    procedure EditBCLIM_FExit(Sender: TObject);
    procedure EditIMIM1_FExit(Sender: TObject);
    procedure EditDESFI_FExit(Sender: TObject);
    procedure TablaFacturaeDeleteError(DataSet: TDataSet;
      E: EDatabaseError; var Action: TDataAction);
    procedure TablaFacturaeUpdateError(DataSet: TDataSet;
      E: EDatabaseError; UpdateKind: TUpdateKind;
      var UpdateAction: TUpdateAction);
    procedure TablaFacturaDDeleteError(DataSet: TDataSet;
      E: EDatabaseError; var Action: TDataAction);
    procedure TablaFacturaDEditError(DataSet: TDataSet; E: EDatabaseError;
      var Action: TDataAction);
    procedure TablaFacturaDPostError(DataSet: TDataSet; E: EDatabaseError;
      var Action: TDataAction);
    procedure TablaFacturaDUpdateError(DataSet: TDataSet;
      E: EDatabaseError; UpdateKind: TUpdateKind;
      var UpdateAction: TUpdateAction);
    procedure TablaClienteEditError(DataSet: TDataSet; E: EDatabaseError;
      var Action: TDataAction);
    procedure TablaClienteDeleteError(DataSet: TDataSet; E: EDatabaseError;
      var Action: TDataAction);
    procedure TablaClientePostError(DataSet: TDataSet; E: EDatabaseError;
      var Action: TDataAction);
    procedure TablaClienteUpdateError(DataSet: TDataSet; E: EDatabaseError;
      UpdateKind: TUpdateKind; var UpdateAction: TUpdateAction);
    procedure TablaInventarioDeleteError(DataSet: TDataSet;
      E: EDatabaseError; var Action: TDataAction);
    procedure TablaInventarioEditError(DataSet: TDataSet;
      E: EDatabaseError; var Action: TDataAction);
    procedure TablaInventarioPostError(DataSet: TDataSet;
      E: EDatabaseError; var Action: TDataAction);
    procedure TablaInventarioUpdateError(DataSet: TDataSet;
      E: EDatabaseError; UpdateKind: TUpdateKind;
      var UpdateAction: TUpdateAction);
    procedure TablaVendedoresDeleteError(DataSet: TDataSet;
      E: EDatabaseError; var Action: TDataAction);
    procedure TablaVendedoresEditError(DataSet: TDataSet;
      E: EDatabaseError; var Action: TDataAction);
    procedure TablaVendedoresPostError(DataSet: TDataSet;
      E: EDatabaseError; var Action: TDataAction);
    procedure TablaVendedoresUpdateError(DataSet: TDataSet;
      E: EDatabaseError; UpdateKind: TUpdateKind;
      var UpdateAction: TUpdateAction);
    procedure TablamovimientosInventarioDeleteError(DataSet: TDataSet;
      E: EDatabaseError; var Action: TDataAction);
    procedure TablamovimientosInventarioEditError(DataSet: TDataSet;
      E: EDatabaseError; var Action: TDataAction);
    procedure TablamovimientosInventarioPostError(DataSet: TDataSet;
      E: EDatabaseError; var Action: TDataAction);
    procedure TablamovimientosInventarioUpdateError(DataSet: TDataSet;
      E: EDatabaseError; UpdateKind: TUpdateKind;
      var UpdateAction: TUpdateAction);
    procedure FacturasFechaeImportes1Click(Sender: TObject);
    procedure BotonObservacionClick(Sender: TObject);
    procedure BotonCambiosMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure BotonNuevoMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure BotonGuardarMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure BotonTotalesMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure BotonPreliminarMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure BotonObservacionMouseDown(Sender: TObject;
      Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
    procedure BotonBuscarMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure BotonImprimirMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure BotonPagoMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure Devolucin1Click(Sender: TObject);
    procedure VentasporDa1Click(Sender: TObject);
    procedure VentasporMes1Click(Sender: TObject);
    procedure Ventasporao1Click(Sender: TObject);
    procedure VentasporArtculo1Click(Sender: TObject);
    procedure ImprimePlantilla1Click(Sender: TObject);
    procedure DocumentosCancelados1Click(Sender: TObject);
    procedure EditDIVIS_FKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure EditDIVIS_FEnter(Sender: TObject);
    procedure EditDIVIS_FExit(Sender: TObject);
    procedure Temas1Click(Sender: TObject);
    procedure CancelaMovimiento1Click(Sender: TObject);
    procedure DesgloceporMoneda1Click(Sender: TObject);
    procedure EditDESFI_FKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure DetalleKeyPress(Sender: TObject; var Key: Char);
    procedure DetalleEnter(Sender: TObject);
    procedure Edit1Exit(Sender: TObject);
    procedure CAMBIO_FExit(Sender: TObject);
    procedure CAMBIO_FKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure VerFunciones1Click(Sender: TObject);
    procedure FormKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure DetalleColExit(Sender: TObject);
    procedure UtilidadporProducto1Click(Sender: TObject);
    procedure FacturadeCierre1Click(Sender: TObject);
    procedure CortedeCaja1Click(Sender: TObject);
    procedure CAMBIO_FEnter(Sender: TObject);
    procedure RangodeDocumentos1Click(Sender: TObject);
    procedure ConfigurarCaja1Click(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure DetalleDrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure TipoPagoDblClick(Sender: TObject);
    procedure UtilidadporProductoConcentrado1Click(Sender: TObject);
    procedure CuentaporCobrar1Click(Sender: TObject);
    procedure VentadeTiendaporProducto1Click(Sender: TObject);
    procedure FormResize(Sender: TObject);
    procedure TablaDetaAfterDelete(DataSet: TDataSet);
    procedure Artculosmsvendidos1Click(Sender: TObject);
  private
procedure MyOnGetText(Sender: TField; var Text: string; DisplayText: Boolean);
    { private declarations }
  public
procedure AppMessage(var Msg: TMsg; var Handled: Boolean);
    { public declarations }
  end;



type
registroencab=record
Numero:string[10];
claveCli:string[15];
NombreCli:string[60];
direccionCli:String[60];
direccionCli2:string[60];
Poblacion:string[40];
Vendedor:string[15];
Comision:string[4];
Mostrador:string[10];
Condiciones:string[10];
Destino:string[10];
FechaDoc:string[15];
FechaEnt:string[15];
FechaVen:string[15];
Iva:String[10];
DescFina:string[10];
DescComer:string[10];
Almacen:string[10];
Pago:string[25];
end;

type
registrodeta=record
cantidad:real;
clave:string[15];
descripcion:string[40];
precio:real;
descuento:real;
costo:real;
unidad:string[3];
divisa:string[6];
impuesto:real;
factor:real;

end;



var
  FormaFactura: TFormaFactura;
   numeromovimiento,tipomovimiento,indice:longint;
   cantidad,suma,iva1,total1,costo,saldoanterior:Currency;
   iva,desfin,desfin1:Real;
   indices,ant,sig:integer;
   meses:array[1..12] of Real;
   cliente:String;
   decimales,formatonum:Word;
   local:Boolean;
   Color1:TColor;
   nombreformato:string;
   ultimovendedor:string[10];
   CambiaPrecios:string[1];
   PrecioNumero:Word;
   Orig:String[8];
   ivatotal:Real;
   RangoDocumentos:Boolean;
   ExistenciasNegativos:string[1];
   desglosado:boolean;
   CajaLocal,VendedorDefault:String[10];
   Digitos,DigitosTotal:Word;
   Digi:string[20];
   ListaClaves,ListaCantidad:TStringList;
   IntegrarMI:char;
   PreciosPolitica:Boolean;
   MovimientoBorrado:integer;
   AsignaControlVariable:integer;
   UltimoDocumento:longInt;
   FactorV:real;
   Orig2:String[8];
   DatoRango:string;
   UltimoGuardado:String[10];

procedure posicionafactura(clave:string);
implementation


uses ConVen, ConInve, Acerca, consulta, buscar, ConPro, formatos,
  cerrar,formato, conclie, barras, advierte, edicion, moneda, totales,
  imprime, desgloce, Concobra, cxcd, observa, progreso, Cucobra,
  AyudaMod, Rango, Caja, Glyps, adminis{, Rango};

{$R *.DFM}

function CalculaSecuencia(ant,sig:string):string;
var
i:integer;
aux:string;
begin
aux:='';

for i:=StrToInt(ant) to StrToInt(sig) do
aux:=aux+IntToStr(i)+',';
    CalculaSecuencia:=aux;
end;

function NuevoRango(rang:string):string;
var
i:integer;
aux:string;
anterior,siguiente:string;
begin
aux:='';
anterior:='';

//MuestraMensaje(rang);
i:=1;
rang:=rang+',';
while i<=length(rang) do
begin
if (rang[i]=',')or(rang[i]='-') then
begin
if rang[i]=',' then
aux:=aux+anterior+','
else
begin
//MuestraMensaje(anterior);
siguiente:='';
while i<= length(rang) do
begin

if rang[i]=',' then
begin
//MuestraMensaje(siguiente);

aux:=aux+CalculaSecuencia(anterior,siguiente);
break;
end
else
begin
if rang[i]<>'-' then
siguiente:=siguiente+rang[i];
end;
i:=i+1;
end;

end;
anterior:='';
end
else
anterior:=anterior+rang[i];

i:=i+1;

end;


NuevoRango:=aux;

end;

procedure ActualizaOrigen(Orige,Doc_Final,Base:string);
var
 Tabla,TablaD:TTable;
 nombre:string;
 begin
//muestraMensaje(orige+'  '+Doc_Final+'   '+Base);
Tabla:=TTable.Create(Application);
if Orige[1]='F' then
nombre:='FacturaE.dbf';

if Orige[1]='R' then
nombre:='Remision.dbf';

if Orige[1]='P' then
nombre:='Pedido.dbf';

if Orige[1]='C' then
nombre:='Cotizaci.dbf';

//if Orige[1]='F' then
//nombre:='Devoluc.dbf';
//muestraMensaje(nombre);
with Tabla do
begin
   DatabaseName :=ruta(8);
   TableName := nombre;
   Tabla.IndexName:='INUMENC';
   Tabla.Open;
   if Tabla.Findkey([CortaCadena(2,length(Orige),Orige)]) then
   begin
   if Base[1]+Doc_Final<>FieldByName('REMIS_F').AsString then
   begin
   Edit;
   FieldByName('REMIS_F').AsString:=Base[1]+Doc_Final;
   Post;
   end;
    end;//if
   Close;

end;//width
Tabla.Close;
Tabla.Free;

//********el detalle*****
Tabla:=TTable.Create(Application);
if Orige[1]='F' then
nombre:='FacturaD.dbf';

if Orige[1]='R' then
nombre:='RemisioD.dbf';

if Orige[1]='P' then
nombre:='PedidoD.dbf';

if Orige[1]='C' then
nombre:='CotizacD.dbf';

//if Orige[1]='F' then
//nombre:='Devoluc.dbf';
//muestraMensaje(nombre);
try
with Tabla do
begin
   DatabaseName :=ruta(8);
   TableName := nombre;
   Tabla.IndexName:='CLDOC_FD';
   Tabla.Open;
   Tabla.SetRange([CortaCadena(2,length(Orige),Orige)],[CortaCadena(2,length(Orige),Orige)]);
//   muestraMensaje(CortaCadena(2,length(Orige),Orige));
   While not Tabla.EOF do
   begin
   if FieldByName('TDOCU_FD').AsString<>Base[1]+Doc_Final then
   begin
   Edit;
   FieldByName('TDOCU_FD').AsString:=Base[1]+Doc_Final;
   Post;
   end
   else
   exit;
   Tabla.Next;
    end;//if
   Close;

end;//width
Tabla.Close;
Tabla.Free;
except
end;


end;


procedure ActualizaOrigenRango(rango,anterior,base1,nume:string);
var
 i,j,inicio,fin:integer;
 aux,ante:string;
 ran:Boolean;
begin
with FormaFactura do
begin


inicio:=0;
fin:=0;
aux:='';

ran:=False;
ante:=anterior;
//MuestraMensaje(NuevoRango(rango));
rango:=NuevoRango(rango);
//********************



aux:='';
for i:=1 to length(rango) do
begin

if rango[i]=',' then
begin
//MuestraMensaje(siguiente);
ActualizaOrigen(ante[1]+Aux,nume,base1);
//aux:=aux+CalculaSecuencia(anterior,siguiente);
aux:='';
end
else
begin
aux:=aux+rango[i];
end;




end;//for



//*********************


{ran:=False;
ante:=anterior;
MuestraMensaje(rango);
for i:=1 to length(rango) do
if rango[i]='-' then
begin
ran:=True;
end;
if ran then
rango:=rango+'-'
else
rango:=rango+',';

for j:=1 to length(rango) do
begin

if rango[j]='-' then
begin

if inicio=0 then inicio:=StrToInt(aux)
else
fin:=StrToInt(aux);
aux:='';

end//if rango
else
aux:=rango[j];

end;//for j

if ran then
if inicio<=fin then
for i:=fin downto inicio do
begin
ActualizaOrigen(ante[1]+IntToStr(i),nume,base1);
end;//for i

//**************segundo caso
aux:='';
i:=1;
if not ran then
while i<=length(rango) do
begin
if rango[i]=',' then
begin

ActualizaOrigen(ante[1]+Aux,nume,base1);
Aux:='';
end
else
begin
Aux:=Aux+rango[i];
end;
i:=i+1;
end;//for i
//*************************************

//Tabla.Free;
           }
end;//width


end;

function  Cantidad_Factor(canti,facto:real;tipo:char):real;
begin
case tipo of
'/':begin
if facto<=0 then
 Cantidad_Factor:=canti
 else
 Cantidad_Factor:=canti/facto;
 end;
'*':begin
if facto<=0 then
 Cantidad_Factor:=canti
 else
 Cantidad_Factor:=canti*facto;
end;

end;
end;

procedure CargaGlyps;
begin
with FormaFactura do
begin
BotonCambios.Glyph:=FormaGlyp.BotonCambios1.Glyph;
BotonNuevo.Glyph:=FormaGlyp.BotonNuevo1.Glyph;
BotonGuardar.Glyph:=FormaGlyp.BotonGuardar1.Glyph;
BotonObservacion.Glyph:=FormaGlyp.BotonObservacion1.Glyph;
BotonPago.Glyph:=FormaGlyp.BotonPago1.Glyph;
BotonBuscar.Glyph:=FormaGlyp.BotonBuscar1.Glyph;
BotonTotales.Glyph:=FormaGlyp.BotonTotales1.Glyph;
BotonPreliminar.Glyph:=FormaGlyp.BotonPreliminar1.Glyph;
BotonImprimir.Glyph:=FormaGlyp.BotonImprimir1.Glyph;
BotonSalir.Glyph:=FormaGlyp.BotonSalir1.Glyph;

end;
end;

function AsignaControl:integer;
begin
AsignaControl:=Trunc(Frac(Now)*100000);

end;

function RedondeaTotal(su:real;Di:integer):real;
var
T:real;
decimal:integer;
ajustar:real;
modu:integer;
begin
Di:=Di*10;

decimal:=Trunc(Frac(su)*100);
T:=su;
modu:=decimal mod Di;
//MuestraMensaje(FloatToStr(modu));
if decimal<>0 then
begin
decimal:=decimal div Di;
if modu>0 then
T:=Trunc(su)+(((decimal*Di)+Di)/100)
else
T:=Trunc(su)+((decimal*Di)/100)

end;
//MuestraMensaje(FloatToStr(su)+'   '+FloatToStr(T)+'   '+FloatToStr(di)+'   '+FloatToStr(decimal));

{if Decimal mod Di=0 then
RedondeaTotal:=su
else
begin
Decimal:=(Trunc(decimal/Di)+1)*Di;
if Decimal=100 then
RedondeaTotal:=su+1
else
RedondeaTotal:=su+(Decimal/100);
end;}


//Str(su:12:Di, T);

RedondeaTotal:=T;
//StrToFloat(T);

end;

function LeePrecioPreferencial(pre:integer):real;
begin
with FormaFactura do
begin
if pre<1 then pre:=1;
    case Pre of

  1:begin
  TablaDeta.FieldByName('PRECIO').AsFloat:= TablaInventario.FieldByName('PPUBL_I').AsFloat;
  LeePrecioPreferencial:=TablaInventario.FieldByName('PPUBL_I').AsFloat;
  end;

  2:begin
  TablaDeta.FieldByName('PRECIO').AsString:=  TablaInventario.FieldByName('PLIS2_I').AsString;
    LeePrecioPreferencial:=TablaInventario.FieldByName('PLIS2_I').AsFloat;
  end;

  3:begin
  TablaDeta.FieldByName('PRECIO').AsString:=  TablaInventario.FieldByName('PLIS3_I').AsString;
    LeePrecioPreferencial:=TablaInventario.FieldByName('PLIS3_I').AsFloat;
  end;

  4:begin
  TablaDeta.FieldByName('PRECIO').AsString:=  TablaInventario.FieldByName('PLIS4_I').AsString;
    LeePrecioPreferencial:=TablaInventario.FieldByName('PLIS4_I').AsFloat;
  end;

  5:begin
  TablaDeta.FieldByName('PRECIO').AsString:=  TablaInventario.FieldByName('PMINI_I').AsString;
    LeePrecioPreferencial:=TablaInventario.FieldByName('PMINI_I').AsFloat;
  end;

  6:begin
  TablaDeta.FieldByName('PRECIO').AsString:=  TablaInventario.FieldByName('PLIS6_I').AsString;
    LeePrecioPreferencial:=TablaInventario.FieldByName('PLIS6_I').AsFloat;
  end;

  7:begin
  TablaDeta.FieldByName('PRECIO').AsString:=  TablaInventario.FieldByName('PLIS7_I').AsString;
    LeePrecioPreferencial:=TablaInventario.FieldByName('PLIS7_I').AsFloat;
  end;


  end;


end;
end;

function LeePrecioPolitica(p1,p2,p3,p4,p5,p6,p7,i1,i2,i3,i4,i5,i6,i7,canti:real):Real;
var
maximo:real;
pre:integer;
begin
maximo:=i1;
pre:=1;
if i2>maximo then
begin
maximo:=i2;
pre:=2;
end;
if i3>maximo then
begin
 maximo:=i3;
pre:=3;
end;

if i4>maximo then
begin
 maximo:=i4;
pre:=4;
end;

if i5>maximo then
begin
 maximo:=i5;
pre:=5;
end;

if i6>maximo then
begin
 maximo:=i6;
pre:=6;
end;

if i7>maximo then
begin
 maximo:=i7;
pre:=7;
end;

LeePrecioPolitica:=p1;
if canti<maximo then
begin
if (canti>=0)and(canti<=i1) then
begin
LeePrecioPolitica:=p1;
exit;
end;
if (canti>i1)and(canti<=i2) then
begin
LeePrecioPolitica:=p2;
exit;
end;

if (canti>i2)and(canti<=i3) then
begin
 LeePrecioPolitica:=p3;
exit;
end;

if (canti>i3)and(canti<=i4) then
begin
 LeePrecioPolitica:=p4;
exit;
end;

if (canti>i4)and(canti<=i5) then
begin
LeePrecioPolitica:=p5;
exit;
end;

if (canti>i5)and(canti<=i6) then
begin
LeePrecioPolitica:=p6;
exit;
end;

if (canti>i6) then
begin
LeePrecioPolitica:=p7;
exit;
end;

end
else
LeePrecioPolitica:=LeePrecioPreferencial(pre);

end;


function PrefijoMovimiento(cadena:string):char;
var
pre:char;
begin
if cadena<>'' then
pre:=cadena[1]
else
pre:= ' ';
PrefijoMovimiento:=pre;


end;

function CantidadApartada(clave:string;regi:integer):real;
var
i,acumulado:real;
indi:integer;
aux:string;
begin
{   acumulado:=0;
   for i:=1 to 100 do
   begin
    if  (Apartados[i,1]=clave)and(regi<>i) then
    acumulado:=acumulado+StrToInt(Apartados[i,2])



   end;
   CantidadApartada:=acumulado;}
   acumulado:=0;
   if ListaClaves.Find(clave,indi) then
   begin
   aux:=ListaCantidad.Strings[indi];
    CantidadApartada:=StrToFloat(aux);
    //Insert(indi,FloatToStr(StrToFloat(ListaCantidad.Strings[indi])+TablaDeta.FieldByName('CANTIDAD').AsFloat));

   end
   else
   CantidadApartada:=0;

end;


procedure TFormaFactura.MyOnGetText(Sender: TField; var Text: string; DisplayText: Boolean);
var
aux:string;
i:integer;
begin
aux:=Sender.AsString;
text:=aux;
//Sender.

if aux<>'' then
Case Sender.DataType of
ftInteger:begin
//ShowMessage('entra entero'+aux);
text:=FormatFloat(Digi,StrTofloat(aux));
end;
ftFloat	:begin
//ShowMessage('entra flotante'+AUX);
text:=FormatFloat(Digi,StrTofloat(aux));
end;
ftCurrency:begin
//ShowMessage('entra flotante'+AUX);
text:=FormatFloat(Digi,StrTofloat(aux));
end;


ftString:begin
//ShowMessage('entra cademnae'+text);
text:=aux;
end;

end;//case




end;


procedure LeeDocumentoRango(docu:string;Tabla:TTable);
begin
with FormaFactura do
begin

TablaAuxiliar.SetRange([docu],[docu]);

{TablaFacturaD.First;}
TablaAuxiliar.First;
while not TablaAuxiliar.Eof do
begin
//MuestraMensaje(docu +'   '+TablaAuxiliar.FieldByName('TREGI_FD').AsString) ;
if (TablaAuxiliar.FieldByName('TREGI_FD').AsString<>'C') and
(TablaAuxiliar.FieldByName('TDOCU_FD').AsString='') then
begin
//MuestraMensaje(docu +'   '+TablaAuxiliar.FieldByName('TREGI_FD').AsString) ;

TablaDeta.Append;
TablaDeta.FieldByName('CANTIDAD').AsFloat:=TablaAuxiliar.FieldByName('CANTI_FD').AsFloat;
TablaDeta.FieldByName('CLAVE').AsString:=TablaAuxiliar.FieldByName('CLPRO_FD').AsString;
TablaDeta.FieldByName('FACTOR').AsString:=TablaAuxiliar.FieldByName('PIVA2_FD').AsString;

TablaDeta.FieldByName('PRODUCTO').AsString:=TablaAuxiliar.FieldByName('DEPRO_FD').AsString;
TablaDeta.FieldByName('UNIDAD').AsString:=TablaAuxiliar.FieldByName('UNIDA_FD').AsString;
TablaDeta.FieldByName('PRECIO').AsFloat:=TablaAuxiliar.FieldByName('PUNPR_FD').AsFloat;
TablaDeta.FieldByName('COSTO').AsFloat:=TablaAuxiliar.FieldByName('COPRO_FD').AsFloat;
//*TablaDeta.FieldByName('CANTIDAD').AsFloat;
TablaDeta.FieldByName('DESCUENTO').AsFloat:=TablaAuxiliar.FieldByName('PDES1_FD').AsFloat;
TablaDeta.FieldByName('IMPORTE').AsFloat:=TablaDeta.FieldByName('CANTIDAD').AsFloat*TablaDeta.FieldByName('PRECIO').AsFloat-
(TablaDeta.FieldByName('CANTIDAD').AsFloat*TablaDeta.FieldByName('PRECIO').AsFloat*TablaDeta.FieldByName('DESCUENTO').AsFloat/100);
TablaDeta.FieldByName('IMPUESTO').AsFloat:=TablaAuxiliar.FieldByName('PIVA1_FD').AsFloat;
TablaDeta.Post;
end;//if
TablaAuxiliar.Next;


end;//while


end;
end;



procedure CalculaRangoDocumentos(TablaAnterior:string;rango:string);
var
 Tabla: TTable;
 i,j,inicio,fin:integer;
 aux:string;
 ran:Boolean;
begin
with FormaFactura do
begin
inicio:=0;
fin:=0;
aux:='';
ran:=False;
//MuestraMensaje(NuevoRango(rango));
rango:=NuevoRango(rango);
//********************

if TablaAuxiliar.State=dsBrowse then
TablaAuxiliar.Close;

   TablaAuxiliar.DatabaseName := ruta(8);
   TablaAuxiliar.TableName :=TablaAnterior;
   TablaAuxiliar.IndexName:='CLDOC_FD';
   TablaAuxiliar.Open;


aux:='';
for i:=1 to length(rango) do
begin

if rango[i]=',' then
begin
//MuestraMensaje(siguiente);
LeeDocumentoRango(aux,TablaAuxiliar);
//aux:=aux+CalculaSecuencia(anterior,siguiente);
aux:='';
end
else
begin
aux:=aux+rango[i];
end;




end;//for


TablaAuxiliar.Close;
//Tabla.Free;

//*********************


{for i:=1 to length(rango) do
if rango[i]='-' then
begin
ran:=True;
end;
if ran then
rango:=rango+'-'
else
rango:=rango+',';

for j:=1 to length(rango) do
begin

if rango[j]='-' then
begin

if inicio=0 then inicio:=StrToInt(aux)
else
fin:=StrToInt(aux);
aux:='';

end//if rango
else
aux:=rango[j];

end;//for j

if TablaAuxiliar.State=dsBrowse then
TablaAuxiliar.Close;

   TablaAuxiliar.DatabaseName := ruta(8);
   TablaAuxiliar.TableName :=TablaAnterior;
   TablaAuxiliar.IndexName:='CLDOC_FD';
   TablaAuxiliar.Open;


//MuestraMensaje(IntToStr(inicio)+'   '+IntToStr(fin));
if ran then
if inicio<=fin then
for i:=fin downto inicio do
begin
TablaAuxiliar.SetRange([IntToStr(i)],[IntToStr(i)]);

TablaAuxiliar.Last;

while not TablaAuxiliar.Bof do
begin
if (TablaAuxiliar.FieldByName('TREGI_FD').AsString<>'C') then
begin
TablaDeta.Insert;
TablaDeta.FieldByName('CANTIDAD').AsFloat:=TablaAuxiliar.FieldByName('CANTI_FD').AsFloat;
TablaDeta.FieldByName('CLAVE').AsString:=TablaAuxiliar.FieldByName('CLPRO_FD').AsString;
TablaDeta.FieldByName('FACTOR').AsString:=TablaAuxiliar.FieldByName('PIVA2_FD').AsString;

TablaDeta.FieldByName('PRODUCTO').AsString:=TablaAuxiliar.FieldByName('DEPRO_FD').AsString;
TablaDeta.FieldByName('UNIDAD').AsString:=TablaAuxiliar.FieldByName('UNIDA_FD').AsString;
TablaDeta.FieldByName('PRECIO').AsFloat:=TablaAuxiliar.FieldByName('PUNPR_FD').AsFloat;
TablaDeta.FieldByName('COSTO').AsFloat:=TablaAuxiliar.FieldByName('COPRO_FD').AsFloat;
//*TablaDeta.FieldByName('CANTIDAD').AsFloat;
TablaDeta.FieldByName('DESCUENTO').AsFloat:=TablaAuxiliar.FieldByName('PDES1_FD').AsFloat;
TablaDeta.FieldByName('IMPORTE').AsFloat:=TablaDeta.FieldByName('CANTIDAD').AsFloat*TablaDeta.FieldByName('PRECIO').AsFloat-
(TablaDeta.FieldByName('CANTIDAD').AsFloat*TablaDeta.FieldByName('PRECIO').AsFloat*TablaDeta.FieldByName('DESCUENTO').AsFloat/100);
TablaDeta.FieldByName('IMPUESTO').AsFloat:=TablaAuxiliar.FieldByName('PIVA1_FD').AsFloat;

TablaDeta.Post;
end;//if
TablaAuxiliar.Prior;


end;//while


end;//for i

//**************segundo caso
aux:='';
i:=1;
if not ran then
while i<=length(rango) do
begin
if rango[i]=',' then
begin

TablaAuxiliar.SetRange([Aux],[Aux]);

TablaAuxiliar.Last;

while not TablaAuxiliar.Bof do
begin
if TablaAuxiliar.FieldByName('TREGI_FD').AsString<>'C' then
begin
TablaDeta.Insert;
TablaDeta.FieldByName('CANTIDAD').AsFloat:=TablaAuxiliar.FieldByName('CANTI_FD').AsFloat;
TablaDeta.FieldByName('CLAVE').AsString:=TablaAuxiliar.FieldByName('CLPRO_FD').AsString;
TablaDeta.FieldByName('FACTOR').AsString:=TablaAuxiliar.FieldByName('PIVA2_FD').AsString;

TablaDeta.FieldByName('PRODUCTO').AsString:=TablaAuxiliar.FieldByName('DEPRO_FD').AsString;
TablaDeta.FieldByName('UNIDAD').AsString:=TablaAuxiliar.FieldByName('UNIDA_FD').AsString;
TablaDeta.FieldByName('PRECIO').AsFloat:=TablaAuxiliar.FieldByName('PUNPR_FD').AsFloat;
TablaDeta.FieldByName('COSTO').AsFloat:=TablaAuxiliar.FieldByName('COPRO_FD').AsFloat;
//*TablaDeta.FieldByName('CANTIDAD').AsFloat;
TablaDeta.FieldByName('DESCUENTO').AsFloat:=TablaAuxiliar.FieldByName('PDES1_FD').AsFloat;
TablaDeta.FieldByName('IMPORTE').AsFloat:=TablaDeta.FieldByName('CANTIDAD').AsFloat*TablaDeta.FieldByName('PRECIO').AsFloat-
(TablaDeta.FieldByName('CANTIDAD').AsFloat*TablaDeta.FieldByName('PRECIO').AsFloat*TablaDeta.FieldByName('DESCUENTO').AsFloat/100);
TablaDeta.FieldByName('IMPUESTO').AsFloat:=TablaAuxiliar.FieldByName('PIVA1_FD').AsFloat;

TablaDeta.Post;
end;//if
TablaAuxiliar.Prior;


end;//while
Aux:='';
end
else
begin
Aux:=Aux+rango[i];
end;
i:=i+1;
end;//for i
//*************************************

}
TablaAuxiliar.Close;
//Tabla.Free;

end;//width
end;


procedure ActualizaFacturaImporte(tot,iv,su:real);
begin
with FormaFactura do
begin
if (TablaFacturaE.FieldByName('IMTOD_F').AsFloat<>Total1)or (TablaFacturaE.FieldByName('SUBTO_F').AsFloat<>suma) then
begin
TablaFacturaE.Edit;
AsignaControlVariable:=AsignaControl;
TablaFacturaE.FieldByName('SUBTO_F').AsFloat:=suma;
TablaFacturaE.FieldByName('DECOT_F').AsFloat:=desfin1;
TablaFacturaE.FieldByName('IMIM2_F').AsFloat:=iva1;
TablaFacturaE.FieldByName('IMTOD_F').AsFloat:=Total1;
TablaFacturaE.FieldByName('COSTO_F').AsFloat:=costo;
TablaFacturaE.Post;
end;//if

end;//width
end;


procedure CancelaDetalle(doc:string);
begin
with FormaFactura do
begin

TablaFacturaD.SetRange([doc],[doc]);

{TablaFacturaD.First;}
TablaFacturaD.First;

while not TablaFacturaD.Eof do
begin
TablaFacturaD.Edit;

TablaFacturaD.FieldByName('TREGI_FD').AsString:='C';

TablaFacturaD.Post;
TablaFacturaD.Next;


end;//while
end;
end;



procedure CopiaRegistro(Tabla1,Tabla2:TTable);
var
i:integer;
begin

for i:=0 to Tabla1.FieldCount-1 do
begin
Tabla2.FieldByName(Tabla1.Fields[i].FieldName).AsString:=Tabla1.FieldByName(Tabla1.Fields[i].FieldName).AsString;
end;


end;


procedure GeneraCorteDeCaja(fecha,fecha2:TDate;nombre1,nombre2,nombre3,indice,con_dev:string);
var
Tabla:TTable;
campofecha,nomtab:string;
Fe1,fe2:String;
Indices1: TIndexOptions;

begin
with FormaFactura do
begin
Refresh;
if LowerCase(nombre3)='factauxi.dbf' then
begin
 campofecha:='FEDOC_F';
 nomtab:='enc';
 //************************************
Tabla:=TTable.Create(Application);
 with Tabla do
 begin
      Indices1 := [];
   Active := False;
   DatabaseName :=ruta_8;
   TableName :='FactAuxi.dbf';
   DeleteFile(PChar(DatabaseName+'\FactAuxi.dbf'));
   TableType := ttDefault;
   FieldDefs.Clear;
   FieldDefs:=TablaFacturaE.FieldDefs;
   IndexDefs.Clear;
   IndexDefs.Add('INUMENC','CLDOC_F',Indices1);
   if State=dsBrowse then
   Close;
   try
   CreateTable; { crea la tabla}
   except
   Close;
   end;
//   Muestramensaje('lo creo');
 end;



end
else
begin
campofecha:='FEDOC_FD';
nomtab:='det';
//************************************
Tabla:=TTable.Create(Application);
 with Tabla do
 begin
   Indices1 := [];
   Active := False;
   DatabaseName :=ruta_8;
   TableName :='FactAuxiD.dbf';
   DeleteFile(Pchar(DatabaseName+'\FactAuxiD.dbf'));
   TableType := ttDefault;
   FieldDefs.Clear;
   FieldDefs:=TablaFacturaD.FieldDefs;
   IndexDefs.Clear;
   IndexDefs.Add('CLDOC_FD','CLDOC_FD',Indices1);
   if State=dsBrowse then
   Close;
   try
   CreateTable;
   except
   Close;
   end;
   { crea la tabla}
//   Muestramensaje('lo creo');
 end;

end;
//MuestraMensaje(DateToStr(fecha)+'  '+DateToStr(fecha2));

//Tabla.Free;


//TablaAuxiliar.DatabaseName:=lee_ruta+'\tempo';
//TablaAuxiliar.TableName:='FactAuxi.dbf';
//TablaAuxiliar.Open;

While not TablaAuxiliar.Eof do
begin
TablaAuxiliar.Delete;
end;

//***********************************
if TablaAuxiliar.State=dsBrowse then
TablaAuxiliar.Close;

try

TablaAuxiliar.DatabaseName:=ruta_8;
TablaAuxiliar.TableName:=nombre3;
TablaAuxiliar.IndexName:=indice;
//'FactAuxi.dbf';
TablaAuxiliar.Open;
While not TablaAuxiliar.Eof do
begin
TablaAuxiliar.Delete;
end;

Tabla:=TTable.Create(Tabla);
Tabla.DatabaseName:=ruta(8);
//Tabla.TableName:='Remision.dbf';
Tabla.TableName:=nombre1;
Tabla.Open;
fe1:=DateToStr(fecha);
fe2:=DateToStr(fecha2);

While not Tabla.Eof do
begin
if (StrToDate(fe1)<=Tabla.FieldByName(campofecha).AsDateTime)and(StrToDate(fe2)>=Tabla.FieldByName(campofecha).AsDateTime) then
begin
//MuestraMensaje(Tabla.FieldByName('CLDOC_F').AsString);
TablaAuxiliar.Insert;
CopiaRegistro(Tabla,TablaAuxiliar);
TablaAuxiliar.Post;
end;//if

Tabla.Next;
end;//while


if con_dev='S' then
begin
//*******************devoluciones*****

if Tabla.State=dsBrowse then
Tabla.Close;
Tabla.DatabaseName:=ruta(8);
Tabla.TableName:=nombre2;
//'Devoluc.dbf';
//MuestraMensaje(Tabla.DatabaseName+'\'+ Tabla.TableName);
Tabla.Open;
Tabla.Filtered:=False;
While not Tabla.Eof do
begin
//MuestraMensaje(fe1+'  '+Tabla.FieldByName(campofecha).AsString+'  '+fe2+'  '+Tabla.FieldByName(campofecha).AsString);
if (StrToDate(fe1)<=Tabla.FieldByName(campofecha).AsDateTime)and(StrToDate(fe2)>=Tabla.FieldByName(campofecha).AsDateTime) then
begin
TablaAuxiliar.Insert;
CopiaRegistro(Tabla,TablaAuxiliar);
if  nomtab='enc'then
begin
TablaAuxiliar.FieldByName('IMTOD_F').AsFloat:=TablaAuxiliar.FieldByName('IMTOD_F').AsFloat*(-1);
TablaAuxiliar.FieldByName('SUBTO_F').AsFloat:=TablaAuxiliar.FieldByName('SUBTO_F').AsFloat*(-1);
end
else
begin
TablaAuxiliar.FieldByName('CANTI_FD').AsFloat:=TablaAuxiliar.FieldByName('CANTI_FD').AsFloat*(-1);
//TablaAuxiliar.FieldByName('SUBTO_F').AsFloat:=TablaAuxiliar.FieldByName('SUBTO_F').AsFloat*(-1);
end;
//MuestraMensaje( Tabla.TableName+' inserto   '+Tabla.FieldByName('CLPRO_FD').AsString);

TablaAuxiliar.Post;
end;//if
//MuestraMensaje( Tabla.TableName+'   '+Tabla.FieldByName('CLPRO_FD').AsString);
Tabla.Next;
end;//while

//****terminan devoluciones****
end;

//MuestraMensaje( Tabla.TableName+'   '+intToStr(Tabla.recordcount));

TablaAuxiliar.First;
While not TablaAuxiliar.Eof do
begin
if TablaInventario.FindKey([TablaAuxiliar.FieldByName('CLPRO_FD').AsString]) then
begin
TablaAuxiliar.Edit;
TablaAuxiliar.FieldByName('DEPRO_FD').AsString:=TablaInventario.FieldByName('CODIG_I').AsString;
TablaAuxiliar.FieldByName('NOMDI_FD').AsString:=TablaInventario.FieldByName('LIPRO_I').AsString;
TablaAuxiliar.Post;
end;//if

TablaAuxiliar.Next;
end;//while



Tabla.Close;
Tabla.Free;

except
//if TablaAuxiliar.State=dsBrowse then
//TablaAuxiliar.Close;

end;//try
//



//TablaAuxiliar.Close;

end;
end;



procedure TFormaFactura.AppMessage(var Msg: TMsg; var Handled: Boolean);
begin
{with Form2 do
begin}
 if Msg.wParam = VK_RETURN then
 begin
 if ((Screen.ActiveControl) is TEdit)or((Screen.ActiveControl) is TDBEdit)
  or((Screen.ActiveControl) is TMaskEdit)and ((Screen.ActiveForm) is TFormaFactura) then
 Msg.wParam := VK_TAB;
 end;

{end;}
end;



{***termina procedimiento  de enter******}



{***posiciona desde catalogo****}


{****************************}




{*****activar botones}

procedure activabotones(cambios,nuevo,guardar,buscar,imprimir,navegar,cancela:boolean);
begin
with FormaFactura do
begin
BotonCambios.Enabled:=cambios;
Modificar1.Enabled:=cambios;

BotonNuevo.Enabled:=nuevo;
Nuevo1.Enabled:=nuevo;

BotonGuardar.Enabled:=guardar;
Guardar1.Enabled:=guardar;

BotonBuscar.Enabled:=buscar;

BotonImprimir.Enabled:=imprimir;

Navegador.Enabled:=navegar;

CancelaMovimiento1.Enabled:=cancela;

{*****extras******}
 Eliminar1.Enabled:=nuevo;
 Cancelar1.Enabled:=nuevo;
 CancelaMovimiento1.Enabled:=guardar;

{****************}

//***********nuevos bloqueos*****
Reportes1.Enabled:=not guardar;
Generar1.Enabled:=not guardar;
Buscar1.Enabled:=not guardar;
Base.Enabled:=not guardar;



end;
end;

{*******************}


procedure buscaobservacion(numero:string;tipo:integer);
begin
with FormaFactura do
begin
  FormaObservaciones:=TFormaObservaciones.Create(Application);
{case tipo of
0:begin}

  FormaObservaciones.Tag:=0;
  FormaObservaciones.Observacion.Clear;
  TablaObservacion.First;

  if (TablaObservacion.FindKey([numero])) then
  begin
  FormaObservaciones.Observacion.Lines[0]:=TablaObservacion.FieldByName('OBSER_FO').AsString;
  end;
  {MuestraMensaje('No Tiene Observaciones');}
  FormaObservaciones.ShowModal;
  {  end;
  end;
1:begin
  FormaObservaciones.Observacion.Clear;
  FormaObservaciones.ShowModal;}
 {********************************}

  if FormaObservaciones.Tag=1 then
  begin
  TablaObservacion.First;
  if (TablaObservacion.FindKey([numero])) then
  TablaObservacion.Edit
  else
  TablaObservacion.Insert;

  TablaObservacion.FieldByName('CLDOC_FO').AsString:=numero;
  TablaObservacion.FieldByName('OBSER_FO').AsString:=FormaObservaciones.Observacion.Lines[0];
  TablaObservacion.Post;

  end;
{*************************************}
  FormaObservaciones.Tag:=0;
end;
FormaObservaciones.Free;
end;


procedure ponecolor(indi:integer;col1:TColor);
begin
with FormaFactura do
begin
color1:=col1;
TDBEdit(Components[indi]).Color:=ClAqua;
end;
end;

procedure quitacolor(indi:integer);
begin
with FormaFactura do
begin
TDBEdit(Components[indi]).Color:=Color1;

end;
end;






{function guardadivisa:string;
type
mone=record
Nombre:string[15];
valor:string[10];
end;
var
arch:file of mone;
money:mone;
i:integer;
aux:string;
begin
aux:='';
if FileExists(ruta(8)+'\moneda.sif') then
begin
AssignFile(arch,ruta(8)+'\moneda.sif');
reset(arch);
while not Eof(arch) do
begin
Read(arch,money);
aux:=aux+money.nombre+',';
aux:=aux+money.valor+',';
end;
CloseFile(arch);
guardadivisa:=aux;
end;
end;}

function leedivisa:string;
type
mone=record
Nombre:string[15];
valor:string[10];
eti1:String[30];
eti2:String[30];
eti3:String[30];
eti4:String[30];
eti5:String[5];
end;
var
arch:file of mone;
money:mone;
i:integer;
aux:string;
begin
aux:='';
if FileExists(ruta(8)+'\moneda.sif') then
begin
AssignFile(arch,ruta(8)+'\moneda.sif');
reset(arch);
{FormaFactura.EditDIVIS_F.Items.Clear;}
while not Eof(arch) do
begin

Read(arch,money);
{FormaFactura.EditDIVIS_F.Items.Add(money.nombre);}
{aux:=aux+money.valor+',';}
end;
{FormaFactura.EditDIVIS_F.Text:=FormaFactura.EditDIVIS_F.Items[0];}
CloseFile(arch);
{guardadivisa:=aux;}
end;
end;

function valordivisa(caso:integer):Currency;
type
mone=record
Nombre:string[15];
valor:string[10];
eti1:String[30];
eti2:String[30];
eti3:String[30];
eti4:String[30];
eti5:String[5];

end;
var
arch:file of mone;
money:mone;
i:integer;
begin
if FileExists(ruta(8)+'\moneda.sif') then
begin
AssignFile(arch,ruta(8)+'\moneda.sif');
reset(arch);
for i:=0 to caso do
begin
Read(arch,money);
end;
valordivisa:=StrToCurr(money.valor);
CloseFile(arch);
{guardadivisa:=aux;}
end;
end;
{****procedimiento para leer los distintos valores de mobneda******}
function valordivisaetiqueta(moned:string;valor:word):string;
type
mone=record
Nombre:string[15];
valor:string[10];
eti1:String[30];
eti2:String[30];
eti3:String[30];
eti4:String[30];
eti5:String[5];

end;
var
arch:file of mone;
money:mone;
i:integer;
begin
if FileExists(ruta(8)+'\moneda.sif') then
begin
AssignFile(arch,ruta(8)+'\moneda.sif');
reset(arch);
money.Nombre:='';
valordivisaetiqueta:='xx';
for i:=0 to FileSize(arch)-1 do
begin
if moned=money.Nombre then
begin
if valor=1 then valordivisaetiqueta:=money.eti1;
if valor=2 then valordivisaetiqueta:=money.eti2;
if valor=3 then valordivisaetiqueta:=money.eti3;
if valor=4 then valordivisaetiqueta:=money.eti4;
break;
end;

Read(arch,money);
end;
{valordivisa:=StrToCurr(money.valor);}
CloseFile(arch);
{guardadivisa:=aux;}
end;
end;



{******************************}


procedure calculavencimiento;
var
dias,meses:integer;
a,m,d:Word;
begin
end;

Procedure borra;
begin
with FormaFactura do
begin
TablaDeta.First;
while not TablaDeta.Eof do
begin
TablaDeta.Delete;
end;
end;
end;


procedure asignatipo;
type
datos=record
archivo:String[60];
descrip:String[125];
end;
var
dat:datos;
faltan:Boolean;
arch,arch2:file of datos;
i:integer;
begin
with FormaConsulta do
begin
{MuestraMensaje(leeruta+'\report\facturae.for');}
AssignFile(arch,ruta(8)+'\report\facturae.for');
Reset(arch);
Archivo.Items.Clear;
Descripcion.Clear;
faltan:=True;
for i:=0 to FileSize(arch)-1 do
begin
Read(arch,dat);
if FileExists(Dat.archivo) then
Archivo.Items.Append(Dat.archivo)
else
faltan:=False;
end;
CloseFile(arch);


if faltan=False then
begin
AssignFile(arch,ruta(8)+'\report\facturae.for');
Reset(arch);
AssignFile(arch2,ruta(8)+'\report\Cliente2.for');
Rewrite(arch2);

for i:=0 to FileSize(arch)-1 do
begin
Read(arch,dat);
if FileExists(Dat.archivo) then
write(arch2,dat);
end;
CloseFile(arch);
CloseFile(arch2);
{******************}
AssignFile(arch,ruta(8)+'\report\facturae.for');
Rewrite(arch);
AssignFile(arch2,ruta(8)+'\report\Cliente2.for');
Reset(arch2);

for i:=0 to FileSize(arch2)-1 do
begin
Read(arch2,dat);
if FileExists(Dat.archivo) then
write(arch,dat);
end;
CloseFile(arch);
CloseFile(arch2);
end;


Archivo.Text:=Archivo.Items[0];
Descripcion.lines.Add(Dat.Descrip);

ReporteDe.Caption:='Reporte de Clientes';
Archi.Caption:='facturae.for';
end;

end;




procedure ejes(m:integer);
begin
end;




{%%%%%%%%%%%%%%%%%inicia traduce %%%%%%%%%%%%%%%}

{function exponente(num:longint;j:integer):longint;
var
i:integer;
begin
if j>=1 then
for i:=1 to j do
begin
num:=num*10;
end;
exponente:=num;
end;



function busca(cifra:longint;pos,ult:integer):string;
var
cadenas:array[1..200,1..2] of string;
i,num:longint;
begin
cadenas[1,1]:='1';cadenas[1,2]:='un';
cadenas[2,1]:='2';cadenas[2,2]:='dos';
cadenas[3,1]:='3';cadenas[3,2]:='tres';
cadenas[4,1]:='4';cadenas[4,2]:='cuatro';
cadenas[5,1]:='5';cadenas[5,2]:='cinco';
cadenas[6,1]:='6';cadenas[6,2]:='seis';
cadenas[7,1]:='7';cadenas[7,2]:='siete';
cadenas[8,1]:='8';cadenas[8,2]:='ocho';
cadenas[9,1]:='9';cadenas[9,2]:='nueve';
cadenas[10,1]:='10';cadenas[10,2]:='diez';
cadenas[11,1]:='11';cadenas[11,2]:='once';
cadenas[12,1]:='12';cadenas[12,2]:='doce';
cadenas[13,1]:='13';cadenas[13,2]:='trece';
cadenas[14,1]:='14';cadenas[14,2]:='catorce';
cadenas[15,1]:='15';cadenas[15,2]:='quince';
cadenas[16,1]:='16';cadenas[16,2]:='dieciseis';
cadenas[17,1]:='17';cadenas[17,2]:='diecisiete';
cadenas[18,1]:='18';cadenas[18,2]:='dieciocho';
cadenas[19,1]:='19';cadenas[19,2]:='diecinueve';
cadenas[20,1]:='20';cadenas[20,2]:='veinte';
cadenas[21,1]:='21';cadenas[21,2]:='veintiuno';
cadenas[22,1]:='22';cadenas[22,2]:='veintidos';
cadenas[23,1]:='23';cadenas[23,2]:='veintitres';
cadenas[24,1]:='24';cadenas[24,2]:='veinticuatro';
cadenas[25,1]:='25';cadenas[25,2]:='veinticinco';
cadenas[26,1]:='26';cadenas[26,2]:='veintiseis';
cadenas[27,1]:='27';cadenas[27,2]:='veintisiete';
cadenas[28,1]:='28';cadenas[28,2]:='veintiocho';
cadenas[29,1]:='29';cadenas[29,2]:='veintinueve';
cadenas[30,1]:='30';cadenas[30,2]:='treinta';
cadenas[32,1]:='40';cadenas[32,2]:='cuarenta';
cadenas[33,1]:='50';cadenas[33,2]:='cincuenta';
cadenas[34,1]:='60';cadenas[34,2]:='sesenta';
cadenas[35,1]:='70';cadenas[35,2]:='setenta';
cadenas[36,1]:='80';cadenas[36,2]:='ochenta';
cadenas[37,1]:='90';cadenas[37,2]:='noventa';
cadenas[38,1]:='100';cadenas[38,2]:='ciento';
cadenas[39,1]:='200';cadenas[39,2]:='doscientos';
cadenas[40,1]:='300';cadenas[40,2]:='trescientos';
cadenas[41,1]:='400';cadenas[41,2]:='cuatrocientos';
cadenas[42,1]:='500';cadenas[42,2]:='quinientos';
cadenas[43,1]:='600';cadenas[43,2]:='seiscientos';
cadenas[44,1]:='700';cadenas[44,2]:='setecientos';
cadenas[45,1]:='800';cadenas[45,2]:='ochocientos';
cadenas[46,1]:='900';cadenas[46,2]:='novecientos';
cadenas[47,1]:='1000';cadenas[47,2]:='mil';
cadenas[48,1]:='1000000';cadenas[48,2]:='millones';
i:=1;

while not(cadenas[i,1]=IntToStr(cifra))and(i<50) do
begin
i:=i+1;
end;


if cadenas[i,2]<>'' then
begin

if (cifra<=10)and (cifra>=1)and(ult<>1) then
cadenas[i,2]:=' y '+cadenas[i,2];


if (pos=0)then
cadenas[i,2]:=' '+cadenas[i,2];
end;

if cadenas[i,2]<>'0' then
busca:='  '+cadenas[i,2];

case pos+1 of
4:busca:='  '+cadenas[i,2] +' mil ';


end;


end;


function traduce(cantidad:Real):String;
var
aux,letra:String;
valores:array[1..10] of longint;
cifra:longint;
j,i,pos,ult:integer;
begin
aux:=intToStr(Trunc(cantidad));
j:=length(aux);

for i:=1 to length(aux) do
begin
valores[i]:=exponente(StrToInt(aux[i]),j-1);
j:=j-1;
end;

j:=0;

if length(aux)>2 then
begin
for i:=length(aux) downto 2  do
begin
j:=j+1;
if j=1 then
begin
valores[i]:=valores[i]+valores[i-1];
end;
if j=3 then j:=0;
end;

end
else
begin
valores[2]:=StrToInt(aux);
valores[1]:= (valores[2]div 10)*10   ;
end;


letra:='';
pos:=length(aux);
j:=1;



i:=length(aux);

j:=0;
pos:=0;
if i<=2 then
i:=2;
ult:=0;
while i>=1  do
begin
j:=j+1;
if i=2 then ult:=1;

if valores[i]>=1000 then
begin
valores[i]:=valores[i] div exponente(1,pos);
if i-1>0 then
valores[i-1]:=valores[i-1] div exponente(1,pos);
end;


if j=1 then
begin
if valores[i]>30 then
begin

valores[i-1]:=valores[i]-valores[i-1];
letra:=busca(valores[i-1],pos,ult)+letra;
valores[i]:=valores[i]-valores[i-1];
letra:=busca(valores[i],1,ult)+letra;

end
else
begin
letra:=busca(valores[i],pos,ult)+letra;

end;

end;


if j=3 then
begin
letra:=busca(valores[i],pos,ult)+letra;
j:=0;
end;
i:=i-1;
pos:=pos+1;


end;



letra:=letra+'  pesos '+IntToStr(Trunc(Frac(cantidad)*100))+'/100' ;

traduce:=letra;
end; }

{%%%%%%%%%%%%%%%%%termina traduce %%%%%%%%%%%%%%%}

{**** iniciaN procedimientos para formatos***************}
procedure dibujabitmap(nombre:String);
var
  mapa: TBitmap;
  rectangulo:TRect;
begin

  mapa := TBitmap.Create;
  mapa.LoadFromFile(nombre);
  rectangulo.Left:=5;
  rectangulo.Top:=5;
  rectangulo.Right:=100;
  rectangulo.Bottom:=240;
  Printer.Canvas.StretchDraw(rectangulo,mapa);
end;


procedure imprimelinea(li:string;tipo,y:integer;palabra:word);

var
l,j,i,conta,cod:integer;
aux:string;
valor:array[1..3] of string;
palabras:array[1..5]of string;
nume:Real;
begin
conta:=1;
i:=1;
palabras[1]:='';
palabras[2]:='';
palabras[3]:='';
palabras[4]:='';
palabras[5]:='';
while (i<=length(li))and (conta<=5) do
begin

if (li[i]=',')or(li[i]='(')or(li[i]=')') then
conta:=conta+1
else
begin
if (li[i]<>' ')and (li[i]<>'@') then
palabras[conta]:=palabras[conta]+li[i];
end;
i:=i+1;
end;

aux:='';

case palabra of
1:begin
  valor[1]:='';
  valor[2]:='';
  valor[3]:='';
  j:=1;
  for l:=2 to length(li) do
  begin
  if (li[l]=',') then
  begin
  valor[j]:=aux;
  j:=j+1;
  aux:='';
  end
  else
  begin
  aux:=aux+li[l];
  if (l=length(li)) then
  valor[j]:=aux;
  end;

  end;
  {*** *checa tipo de dato****}
  case tipo of
  0:begin
     val(FormaFactura.TablaFacturaE.FieldByName(valor[3]).AsString,nume,cod);
     if cod=0 then
     begin
     if palabras[4]='' then palabras[4]:='0';
     Str(FormaFactura.TablaFacturaE.FieldByName(valor[3]).AsFloat:15:StrToInt(palabras[4]),valor[3]);
     Printer.Canvas.TextOut(StrToInt(valor[1])*25,50*StrToInt(valor[2])+y*50,valor[3]);

     end
     else
     Printer.Canvas.TextOut(StrToInt(valor[1])*25,50*StrToInt(valor[2])+y*50,FormaFactura.TablaFacturaE.FieldByName(valor[3]).AsString);

    end;
  1: begin
      val(FormaFactura.TablaDeta.FieldByName(valor[3]).AsString,nume,cod);
     if cod=0 then
     begin
     if palabras[4]='' then palabras[4]:='0';
     Str(FormaFactura.TablaDeta.FieldByName(valor[3]).AsFloat:15:StrToInt(palabras[4]),valor[3]);
     Printer.Canvas.TextOut(StrToInt(valor[1])*25,50*StrToInt(valor[2])+y*50,valor[3]);
     end
     else
      Printer.Canvas.TextOut(StrToInt(valor[1])*25,50*(StrToInt(valor[2])+y),FormaFactura.TablaDeta.FieldByName(valor[3]).AsString);
     end;
  end;



  {*termina checkeo de dato****}



{  if tipo=0 then
  Printer.Canvas.TextOut(StrToInt(valor[1])*25,50*StrToInt(valor[2])+y*50,FormaFactura.TablaFacturaE.FieldByName(valor[3]).AsString);
  if tipo=1 then
  Printer.Canvas.TextOut(StrToInt(valor[1])*25,50*(StrToInt(valor[2])+y),FormaFactura.TablaDeta.FieldByName(valor[3]).AsString);}

end;

3:begin
  if palabras[2]='rojo' then
  Printer.Canvas.Font.Color:=clRed;

  if palabras[2]='azul' then
  Printer.Canvas.Font.Color:=clBlue;

  if palabras[2]='verde' then
  Printer.Canvas.Font.Color:=clGreen;

  if palabras[2]='amarillo' then
  Printer.Canvas.Font.Color:=clYellow;

  if palabras[2]='negro' then
  Printer.Canvas.Font.Color:=clBlack;
  end;

4:begin

  Printer.Canvas.TextOut(25*StrToInt(palabras[2]),50*StrToInt(palabras[3]),traduce(FormaFactura.TablaFacturaE.FieldByName('IMTOD_F').AsFloat));
  end;

5:begin
  Printer.Canvas.Rectangle(StrToInt(palabras[2]),StrToInt(palabras[3]),StrToInt(palabras[4]),StrToInt(palabras[5]));
  end;

6:begin
  Printer.Canvas.Font.Size:=StrToInt(palabras[2]);
  end;


7:begin
  Printer.Canvas.Font.Name:=Palabras[2];
  end;

8:begin
  if (palabras[1]='logo') then
  dibujabitmap(palabras[2]);

  end;
end;



{if (li[1]='@')or(li[1]='t') then
begin
j:=1;
for l:=2 to length(li) do
begin
if (li[l]=',') then
begin
valor[j]:=aux;
j:=j+1;
aux:='';
end
else
begin
aux:=aux+li[l];
if (l=length(li)) then
valor[j]:=aux;
end;
end;

if li[1]='t' then
begin
Printer.Canvas.Font.Size:=StrToInt(valor[2]);
end;

if li[1]='@' then
if tipo=0 then
Printer.Canvas.TextOut(StrToInt(valor[1])*25,50*StrToInt(valor[2])+y*50,FormaFactura.TablaFacturaE.FieldByName(valor[3]).AsString);
if tipo=1 then
Printer.Canvas.TextOut(StrToInt(valor[1])*25,50*(StrToInt(valor[2])+y*50),FormaFactura.TablaDeta.FieldByName(valor[3]).AsString);
end;
 }



end;

procedure imprimedetalle;
var arch2:TextFile;
lin:string[100];
tipo,y:integer;
begin
FormaFactura.TablaDeta.First;
y:=0;
while not Formafactura.TablaDeta.Eof do
begin

AssignFile(arch2,leeruta+'\consulta\detatmp.tmp');
reset(arch2);

tipo:=1;
while not Eof(arch2) do
begin
readln(arch2,lin);
imprimelinea(lin,1,y,1);
end;

Closefile(arch2);
y:=y+1;
FormaFactura.TablaDeta.Next;

end;
end;

procedure imprimeformato;
var
arch,arch2:TextFile;
lin:string[100];
l:string[4];
tipo,y:integer;
palabra:word;
begin
With FormaFactura do
begin
AssignFile(arch,leeruta+'\consulta\factura.fmt');
reset(arch);
Printer.BeginDoc;


while not Eof(arch) do
begin
readln(arch,lin);
{MuestraMensaje('lineaimprimir     '+lin);}
if lin[1]='&' then
begin
AssignFile(arch2,leeruta+'\consulta\detatmp.tmp');
ReWrite(arch2);
repeat
readln(arch,lin);
if lin[1]<>'&' then
Writeln(arch2,lin);
until lin[1]='&';
CloseFile(arch2);

imprimedetalle;
end
else
begin

l:=lin;

if l[1]='@' then palabra:=1;
{if l[1]='&' then palabra:=2;}
if l='colo' then palabra:=3;
if l='trad' then palabra:=4;
if l='cuad' then palabra:=5;
if l='tama' then palabra:=6;
if l='tipo' then palabra:=7;
if l='logo' then palabra:=8;
imprimelinea(lin,0,0,palabra);

end;

end;
Printer.EndDoc;
closefile(arch);
end;
end;

{****terminan pocedimientos para formatos***************}
function borratodaslascuentas:boolean;
var
borrarcuenta:Boolean;
cuenta:integer;
begin
{
with FormaFactura do
begin
 TablaCuentasxCobrar.SetRange([EditCLDOC_F.Text],[EditCLDOC_F.Text]);
 TablaCuentasxCobrar.First;
 borrarcuenta:=False;
 cuenta:=0;
 while not TablaCuentasxCobrar.Eof do
 begin
 if (TablaCuentasxCobrar.FieldByName('STATU_CC').AsString='F')and (TablaCuentasxCobrar.FieldByName('IMCUE_CC').AsFloat= TablaCuentasxCobrar.FieldByName('SALDO_CC').AsFloat) then
 borrarcuenta:=True;
 TablaCuentasxCobrar.Next;
 cuenta:=cuenta+1;
 end;


 if borrarcuenta then
 begin
  TablaCuentasxCobrar.First;
  while not TablaCuentasxCobrar.Eof do
  begin
  TablaCuentasxCobrar.Delete;
  end;
 borratodaslascuentas:=True;
 end
 else
 begin
  borratodaslascuentas:=False;
 end;
 if cuenta=0 then
 borratodaslascuentas:=True;

 TablaCuentasxCobrar.CancelRange;
end;
}
end;

procedure actualizalacuenta;
var
borrarcuenta:Boolean;
begin
{
with FormaFactura do
begin
 TablaCuentasxCobrar.SetRange([EditCLDOC_F.Text],[EditCLDOC_F.Text]);
 TablaCuentasxCobrar.First;
 borrarcuenta:=False;
 while not TablaCuentasxCobrar.Eof do
 begin

 if (TablaCuentasxCobrar.FieldByName('STATU_CC').AsString='F')and (TablaCuentasxCobrar.FieldByName('IMCUE_CC').AsFloat= TablaCuentasxCobrar.FieldByName('SALDO_CC').AsFloat) then
 borrarcuenta:=True;
 TablaCuentasxCobrar.Next;
 end;


 if borrarcuenta then
 begin
  TablaCuentasxCobrar.First;
  while not TablaCuentasxCobrar.Eof do
  begin
  TablaCuentasxCobrar.Delete;
  end;
 end
 else
 MuestraMensaje('La Cuenta por Cobrar no Puede ser Eliminada Poque tiene Movimientos');


 TablaCuentasxCobrar.CancelRange;
end;
 }
end;


{procedure BorraDatosMovimientos(tipo:Char);
var
borrarcuenta:boolean;
begin
if IntegrarMI='S' then
begin
with FormaFactura do
begin


 TablamovimientosInventario.First;
if (tipo='F')or(tipo='R')then
 while not TablamovimientosInventario.Eof do
 begin
 if (TablamovimientosInventario.FieldByName('BANAF_MI').AsString='F') and (TablamovimientosInventario.FieldByName('REFMO_MI').AsString=EditCLDOC_F.Text) then
 begin
 TablamovimientosInventario.Delete;
 end
 else
 TablamovimientosInventario.Next;

 end;

end;
end;
end;}

procedure BorraDatosMovimientos(tipo:Char);
var
borrarcuenta:boolean;
begin
//MuestraMensaje('Borrara '+tipo);

if IntegrarMI='S' then
begin
with FormaFactura do
begin
try
//if tipo<>'D' then
begin
TablamovimientosInventario.IndexName:='NUDOC_MI';
//if TablaFacturaE.FieldByName('ORIGE_F').AsString<>'' then
//TablamovimientosInventario.SetRange([TablaFacturaE.FieldByName('ORIGE_F').AsString],[TablaFacturaE.FieldByName('ORIGE_F').AsString])
//else
//MovimientoBorrado:=0;
TablamovimientosInventario.SetRange([PrefijoMovimiento(Base.Text)+EditCLDOC_F.Text],[PrefijoMovimiento(Base.Text)+EditCLDOC_F.Text]);
try
MovimientoBorrado:=TablamovimientosInventario.FieldByName('CLDOC_MI').AsInteger;
except
end;

//MuestraMensaje('Borrara '+PrefijoMovimiento(Base.Text)+EditCLDOC_F.Text);
 while not TablamovimientosInventario.Eof do
 begin
 TablamovimientosInventario.Delete;
 end;
TablamovimientosInventario.CancelRange;

TablamovimientosInventario.IndexName:='CLDOC_MI';
end;//if <>D
except

end;//try
end;//with

end;//if
end;


procedure borradatosanteriores(tipo:Char);
var
VariableControl:longInt;
begin
with FormaFactura do
begin
VariableControl:= TablaFacturaE.FieldByName('CONTROL').AsInteger;
//***********************

if BotonCambios.Tag=1 then
begin

end;

 if (tipo='F')or(tipo='R') then
 begin
{ borratodaslascuentas;}

 TablaFacturaD.SetRange([EditCLDOC_F.Text],[EditCLDOC_F.Text]);
 TablaFacturaD.First;
 while not TablaFacturaD.Eof do
 begin
  if VariableControl= TablaFacturaD.FieldByName('CONTROL').AsInteger then
 TablaFacturaD.Delete
 else
 TablaFacturaD.Next;
 end;
end;
{********************************}

if tipo<>'X' then
 begin
  TablaFacturaD.SetRange([EditCLDOC_F.Text],[EditCLDOC_F.Text]);
 TablaFacturaD.First;
 while not TablaFacturaD.Eof do
 begin
 if VariableControl= TablaFacturaD.FieldByName('CONTROL').AsInteger then
  TablaFacturaD.Delete
 else
 TablaFacturaD.Next;

 end;//while

end;//if

end;//with tipo<>X

end;

procedure generadocumento(tipo:char);
var
arch:File of registrodeta;
arch2:File of registroencab;
datos:registrodeta;
encab:registroencab;
k:longint;
TablaAnterior:string[15];
begin
With FormaFactura do
begin
TablaAnterior:=TablaFacturaD.TableName;
{********cambia base****}

if tipo='F' then
begin
Base.Text:='Factura';
TablaFacturaE.Close;
TablaFacturaE.TableName:='Facturae.dbf';
TablaFacturaE.Open;
TablaFacturaD.Close;
TablaFacturaD.TableName:='FacturaD.dbf';
TablaFacturaD.Open;
formatonum:=14;
TablaFacturaE.Last;
UltimoDocumento:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger;

end;

if tipo='R' then
begin
Base.Text:='Remision';
TablaFacturaE.Close;
TablaFacturaE.TableName:='Remision.dbf';
TablaFacturaE.Open;
TablaFacturaD.Close;
TablaFacturaD.TableName:='RemisioD.dbf';
TablaFacturaD.Open;
formatonum:=15;
TablaFacturaE.Last;
UltimoDocumento:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger;

end;

if tipo='P' then
begin
Base.Text:='Pedido';
TablaFacturaE.Close;
TablaFacturaE.TableName:='Pedido.dbf';
TablaFacturaE.Open;
TablaFacturaD.Close;
TablaFacturaD.TableName:='PedidoD.dbf';
TablaFacturaD.Open;
formatonum:=16;
TablaFacturaE.Last;
UltimoDocumento:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger;

end;

{***********************}
if tipo='D' then
begin
Base.Text:='Devolución';
TablaFacturaE.Close;
TablaFacturaE.TableName:='Devoluc.dbf';
TablaFacturaE.Open;
TablaFacturaD.Close;
TablaFacturaD.TableName:='DevolucD.dbf';
TablaFacturaD.Open;
formatonum:=21;
TablaFacturaE.Last;
UltimoDocumento:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger;

end;

{***********************}



{****graba encabezado****}
TablaFacturaE.Last;
k:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger+1;
TablaFacturaE.Insert;
AssignFile(arch2,leeruta+'\buferenc.tmp');
ReSet(arch2);
Read(arch2,encab);

EditCLDOC_F.Text:=IntToStr(k);
EditCLCLI_F.Text:=encab.claveCli;
Nombre.Caption:=encab.NombreCli;
Direccion.Caption:=encab.direccionCli;
Direc2.Caption:=encab.direccionCli2;
Poblacion.Caption:=encab.Poblacion;
EditCLVEN_F.Text:=encab.Vendedor;
EditCTOVE_F.Text:=encab.Comision;
EditBCLIM_F.Text:=encab.Mostrador;
{EditCONDI_F.Text:=encab.Condiciones;}
{EditDESTI_F.Text:=encab.Destino;}
EditFEDOC_F.Text:=encab.FechaDoc;
{EditFEENT_F.Text:=encab.FechaEnt;}
{EditFEVEN_F.Text:=encab.FechaVen;}
EditIMIM1_F.Text:=encab.Iva;
{EditDECOT_F.Text:=encab.DescFina;}
EditDESFI_F.Text:=encab.DescComer;
TipoPago.Text:=encab.Pago;
TablaFacturaE.Post;
//TablaFacturaE.ApplyUpdates;
CloseFile(arch2);

{************************}

{****datos detalle****}
borra;

if not RangoDocumentos then
begin

AssignFile(arch,leeruta+'\bufer.tmp');
ReSet(arch);
While not EoF(arch) do
begin
read(arch,datos);
//if datos.
TablaDeta.Append;
TablaDeta.FieldByName('cantidad').AsFloat:=Datos.cantidad;
TablaDeta.FieldByName('clave').AsString:=Datos.clave;
TablaDeta.FieldByName('FACTOR').AsFloat:=Datos.factor;
TablaDeta.FieldByName('producto').AsString:=Datos.descripcion;
TablaDeta.FieldByName('precio').AsFloat:=Datos.precio;
TablaDeta.FieldByName('descuento').AsFloat:=Datos.descuento;
TablaDeta.FieldByName('costo').AsFloat:=Datos.Costo;
TablaDeta.FieldByName('unidad').AsString:=Datos.Unidad;
TablaDeta.FieldByName('Factor').AsFloat:=Datos.Factor;
//TablaDeta.FieldByName('impuesto').AsFloat:=Datos.impuesto;
TablaDeta.Post;

end; //while

CloseFile(arch);

end
else
begin
CalculaRangoDocumentos(TablaAnterior,FormaRango.Edit1.Text);

end;
//*******************


BotonGuardar.Enabled:=True;
BotonNuevo.Enabled:=False;
BotonNuevo.tag:=1;

end;
end;

procedure regresabufercambios;
{type
registrodeta=record
cantidad:real;
clave:string[15];
descripcion:string[40];
precio:real;
descuento:real;
costo:real;
unidad:string[3];
end;}
var
arch:File of registrodeta;
datos:registrodeta;
k:integer;
CantidadAnterior:Real;
begin
With FormaFactura do
begin
AssignFile(arch,leeruta+'\bufer.tmp');
Reset(arch);
for k:=0 to Filesize(arch) -1 do
begin
seek(arch,k);
read(arch,datos);

 TablaInventario.First;
 if TablaInventario.FindKey([datos.clave]) then
 begin
 TablaInventario.Edit;

  CantidadAnterior:=TablaInventario.FieldByName('EXIST_I').AsFloat;

 TablaInventario.FieldByName('EXIST_I').AsFloat:= TablaInventario.FieldByName('EXIST_I').AsFloat -
 Cantidad_Factor(datos.cantidad,datos.factor,'/');

  TablaInventario.FieldByName('VANCA_I').AsFloat:= TablaInventario.FieldByName('VANCA_I').AsFloat+
 (CantidadAnterior-TablaInventario.FieldByName('EXIST_I').AsFloat);

  TablaInventario.FieldByName('VANMO_I').AsFloat:= TablaInventario.FieldByName('VANMO_I').AsFloat+
 ((CantidadAnterior-TablaInventario.FieldByName('EXIST_I').AsFloat)*datos.precio);


 if (TablaInventario.FieldByName('EXIST_I').AsFloat<0)and(ExistenciasNegativos='N') then
 TablaInventario.FieldByName('EXIST_I').AsFloat:=0;
 TablaInventario.Post;
// TablaInventario.ApplyUpdates;

{***********detalle*********}

 TablaFacturaD.Insert;
 TablaFacturaD.FieldByName('CLDOC_FD').AsString:= EditCLDOC_F.Text;
 TablaFacturaD.FieldByName('CONTROL').AsInteger:=AsignaControlVariable;
 TablaFacturaD.FieldByName('CLPRO_FD').AsString:= Datos.clave;
 TablaFacturaD.FieldByName('CANTI_FD').AsFloat:=Datos.cantidad;
 TablaFacturaD.FieldByName('DEPRO_FD').AsString:= Datos.descripcion;
 TablaFacturaD.FieldByName('PUNPR_FD').AsFloat:= Datos.precio;
 TablaFacturaD.FieldByName('COPRO_FD').AsFloat:= Datos.Costo;
 TablaFacturaD.FieldByName('PDES1_FD').AsFloat:=Datos.descuento;
 TablaFacturaD.FieldByName('UNIDA_FD').AsString:= Datos.Unidad;
  TablaFacturaD.FieldByName('PIVA1_FD').Asfloat:= Datos.impuesto;
 TablaFacturaD.FieldByName('PIVA2_FD').Asfloat:= Datos.factor;
 TablaFacturaD.Post;
// TablaFacturaD.ApplyUpdates;
{***************************}
 end;
{MuestraMensaje(FloatToStr(datos.cantidad)+(datos.clave)+(datos.descripcion)+FloatToStr(datos.precio)+
FloatToStr(datos.descuento));}
end;
CloseFile(arch);
end;
end;


procedure bufercambios(tipo:Char);

{type
registroencab=record
Numero:string[10];
claveCli:string[15];
NombreCli:string[60];
direccionCli:String[60];
direccionCli2:string[60];
Poblacion:string[40];
Vendedor:string[15];
Comision:string[4];
Mostrador:string[10];
Condiciones:string[10];
Destino:string[10];
FechaDoc:string[15];
FechaEnt:string[15];
FechaVen:string[15];
Iva:String[10];
DescFina:string[10];
DescComer:string[10];
Almacen:string[10];
end;

type
registrodeta=record
cantidad:real;
clave:string[15];
descripcion:string[40];
precio:real;
descuento:real;
costo:real;
unidad:string[3];
end; }

var
arch:File of registrodeta;
arch2:File of registroencab;
datos:registrodeta;
encab:registroencab;

k:integer;
CantidadAnterior:Real;
begin
With FormaFactura do
begin
{****graba encabezado****}


AssignFile(arch2,leeruta+'\buferenc.tmp');
ReWrite(arch2);

encab.Numero:=EditCLDOC_F.Text;
encab.claveCli:=EditCLCLI_F.Text;
encab.NombreCli:=Nombre.Caption;
encab.direccionCli:=Direccion.Caption;
encab.direccionCli2:=Direc2.Caption;
encab.Poblacion:=Poblacion.Caption;
encab.Vendedor:=EditCLVEN_F.Text;
encab.Comision:=EditCTOVE_F.Text;
encab.Mostrador:=EditBCLIM_F.Text;
{encab.Condiciones:=EditCONDI_F.Text;
encab.Destino:=EditDESTI_F.Text;}
encab.FechaDoc:=EditFEDOC_F.Text;
{encab.FechaEnt:=EditFEENT_F.Text;}
{encab.FechaVen:=EditFEVEN_F.Text;}
encab.Iva:=EditIMIM1_F.Text;
{encab.DescFina:=EditDECOT_F.Text;}
encab.DescComer:=EditDESFI_F.Text;
encab.Pago:=TipoPago.Text;
write(arch2,encab);
CloseFile(arch2);

{************************}

AssignFile(arch,leeruta+'\bufer.tmp');
ReWrite(arch);

TablaDeta.First;
While not TablaDeta.EoF do
begin
Datos.cantidad:=TablaDeta.FieldByName('cantidad').AsFloat;
Datos.clave:=TablaDeta.FieldByName('clave').AsString;
Datos.factor:=TablaDeta.FieldByName('factor').AsFloat;

Datos.descripcion:=TablaDeta.FieldByName('producto').AsString;
Datos.precio:=TablaDeta.FieldByName('precio').AsFloat;
Datos.descuento:=TablaDeta.FieldByName('descuento').AsFloat;
Datos.Costo:=TablaDeta.FieldByName('costo').AsFloat;
Datos.Unidad:=TablaDeta.FieldByName('unidad').AsString;

Datos.Unidad:=TablaDeta.FieldByName('unidad').AsString;
Datos.impuesto:=TablaDeta.FieldByName('impuesto').AsFloat;//Datos.divisa:=EditDIVIS_F.Text;
Write(arch,datos);
TablaDeta.Next;

end;


if tipo='F' then
begin
for k:=0 to Filesize(arch) -1 do
begin
seek(arch,k);
read(arch,datos);
// TablaInventario.First;
 if TablaInventario.FindKey([datos.clave]) then
 begin
 TablaInventario.Edit;
  CantidadAnterior:=TablaInventario.FieldByName('EXIST_I').AsFloat;

 if  Base.Text='Devolución' then
 TablaInventario.FieldByName('EXIST_I').AsFloat:= TablaInventario.FieldByName('EXIST_I').AsFloat -
 Cantidad_Factor(datos.cantidad,datos.factor,'/')
 else
 TablaInventario.FieldByName('EXIST_I').AsFloat:= TablaInventario.FieldByName('EXIST_I').AsFloat +
 Cantidad_Factor(datos.cantidad,datos.factor,'/');


  TablaInventario.FieldByName('VANCA_I').AsFloat:= TablaInventario.FieldByName('VANCA_I').AsFloat+
 (CantidadAnterior-TablaInventario.FieldByName('EXIST_I').AsFloat);

  TablaInventario.FieldByName('VANMO_I').AsFloat:= TablaInventario.FieldByName('VANMO_I').AsFloat+
 ((CantidadAnterior-TablaInventario.FieldByName('EXIST_I').AsFloat)*datos.precio);

 if (TablaInventario.FieldByName('EXIST_I').AsFloat<0)and(ExistenciasNegativos='N') then
 TablaInventario.FieldByName('EXIST_I').AsFloat:=0;

 TablaInventario.Post;
// Tablainventario.ApplyUpdates;
end;
end;

end;
 CloseFile(arch);
end;

end;

procedure ActualizaInventarioCambios;
var
CantidadAnterior:Real;
begin
with FormaFactura do
begin
//mUESTRAmENSAJE('ACTUALIZAINV');
TablaInventario.First;
 if (TablaInventario.FindKey([TablaDeta.FieldByName('Clave').AsString]))and(TablaInventario.FieldByName('DSCPR_I').AsString<>'') then
 begin
 TablaInventario.Edit;
  CantidadAnterior:=TablaInventario.FieldByName('EXIST_I').AsFloat;

 TablaInventario.FieldByName('EXIST_I').AsFloat:= TablaInventario.FieldByName('EXIST_I').AsFloat-
 Cantidad_Factor(TablaDeta.FieldByName('cantidad').AsFloat,TablaDeta.FieldByName('factor').AsFloat,'/');

  TablaInventario.FieldByName('VANCA_I').AsFloat:= TablaInventario.FieldByName('VANCA_I').AsFloat+
 (CantidadAnterior-TablaInventario.FieldByName('EXIST_I').AsFloat);

  TablaInventario.FieldByName('VANMO_I').AsFloat:= TablaInventario.FieldByName('VANMO_I').AsFloat+
 ((CantidadAnterior-TablaInventario.FieldByName('EXIST_I').AsFloat)*TablaDeta.FieldByName('precio').AsFloat);


 if (TablaInventario.FieldByName('EXIST_I').AsFloat<0)and(ExistenciasNegativos='N') then
 TablaInventario.FieldByName('EXIST_I').AsFloat:=0;

 TablaInventario.Post;
// TablaInventario.ApplyUpdates;
 end;
end;

end;

{function ruta(linea:integer):String;
var
arch:TextFile;
aux:string;
i:integer;

begin

AssignFile(arch,leeempresa());
Reset(arch);
for i:=1 to linea do
Readln(arch,aux);
CloseFile(arch);
ruta:=aux;

end;}


procedure rutas;
var
  j: Integer;
  cerradas:string[2];
begin
cerradas:=ruta(1);
with FormaFactura do
begin
  for j := 0 to ComponentCount -1 do
    begin
     if Components[j] is TTable  then
       begin
       TTable(Components[j]).DatabaseName:=ruta(8);

       //*****caso para inventario separado de las estaciones
//        ShowMessage(LowerCase(TTable(Components[j]).Name));
       if LowerCase(TTable(Components[j]).TableName)='inventar.dbf' then
       begin
       try

       if ruta(59)<>'' then
         TTable(Components[j]).DatabaseName:=ruta(59);
       except
       end;
       end;

       if LowerCase(TTable(Components[j]).TableName)='movinven.dbf' then
       begin
       try
       if ruta(59)<>'' then
         TTable(Components[j]).DatabaseName:=ruta(59);
       except
       end;
       end;

//*****termina inventario separado



       end;
    end;

  TablaDeta.DataBaseName:=leeruta();
  for j := 0 to ComponentCount -1 do
    begin
     if Components[j] is TTable  then
       begin
//       TTable(Components[j]).Open;
AbreTablaTotal(TTable(Components[j]));
    //if UpperCase(Cerradas)='NO' then
//    TTable(Components[j]).CachedUpdates:=True;
       end;
    end;


{if Usuario.Caption='0' then
EditCLDOC_F.ReadOnly:=False
else
EditCLDOC_F.ReadOnly:=True;}

ExistenciasNegativos:=ruta(41);
end;

end;




procedure limpiar;
var
  j: Integer;
begin

with FormaFactura do
begin
  for j:=0 to ComponentCount -1 do
    begin
     if Components[j] is TDBEdit  then
       TDBEdit(Components[j]).Text :='';
     if Components[j] is TEdit  then
       TEdit(Components[j]).Text :='';
     if Components[j] is TMaskEdit then
       TMaskEdit(Components[j]).Text:='';

  end;
Nombre.Caption:='';
Direccion.Caption:='';
Poblacion.Caption:='';
end;
end;


procedure activa;
var
  j: Integer;
begin
with FormaFactura do
begin
Caja.Enabled:=True;
{  for j := 0 to ComponentCount -1 do
    begin
     if Components[j] is TDBEdit  then
       TDBEdit(Components[j]).Enabled :=True;
     if Components[j] is TEdit  then
       TEdit(Components[j]).Enabled :=True;
     if Components[j] is TLabel then
       TLabel(Components[j]).Enabled :=True;
     if Components[j] is TMaskEdit then
       TMaskEdit(Components[j]).Enabled:=True;
end;
Nombre.Enabled:=True;
Direccion.Enabled:=True;
Poblacion.Enabled:=True;}
Detalle.ReadOnly:=False;

end;

end;

procedure desactiva;
var
  j: Integer;
begin
with FormaFactura do
begin
{  for j := 0 to ComponentCount -1 do
    begin
     if Components[j] is TDBEdit then
       TDBEdit(Components[j]).Enabled :=False;
     if Components[j] is TEdit then
       TEdit(Components[j]).Enabled :=False;
     if Components[j] is TLabel then
       TLabel(Components[j]).Enabled :=False;
     if Components[j] is TMaskEdit then
       TMaskEdit(Components[j]).Enabled:=False;
end;
Nombre.Enabled:=False;
Direccion.Enabled:=False;
Poblacion.Enabled:=False;}
Caja.Enabled:=False;
Detalle.ReadOnly:=True;
end;
end;


procedure cursor1;
begin
With FormaFactura do
begin

if indices > 17 then indices:=1;
if indices < 1 then indices:=1;
case indices of
1:EditCLDOC_F.SetFocus;
2:EditCLCLI_F.SetFocus;
3:EditCLVEN_F.SetFocus;
4:EditCTOVE_F.SetFocus;
5:EditBCLIM_F.SetFocus;
6:EditFEDOC_F.SetFocus;
7:EditIMIM1_F.SetFocus;
8:EditDESFI_F.SetFocus;

{3:EditCLPED_F.SetFocus;
4:EditREMIS_F.SetFocus;
5:EditDIVIS_F.SetFocus;


 8:EditDESTI_F.SetFocus;
9:EditCONDI_F.SetFocus;


12:EditFEENT_F.SetFocus;
13:EditFEVEN_F.SetFocus;


16:EditDECOT_F.SetFocus;
17:EditNALMA_F.SetFocus;}
end;
end;
end;

procedure checaexistencias;
var
solicitado,existente:real;
apar:Real;
begin
with FormaFactura do
begin
//cantidad:=TablaInventario.FieldByName('Exist_I').AsFloat-TablaDeta.FieldByName('Cantidad').AsFloat;
//solicitado:=(TablaDeta.FieldByName('Cantidad').AsFloat+CantidadApartada(TablaDeta.FieldByName('Clave').AsString,Detalle.DataSource.DataSet.RecNo));
apar:=CantidadApartada(TablaDeta.FieldByName('Clave').AsString,Detalle.DataSource.DataSet.RecNo);
if apar<>0 then
solicitado:=(apar)
else
solicitado:=Cantidad_Factor(TablaDeta.FieldByName('Cantidad').AsFloat,TablaDeta.FieldByName('fACTOR').AsFloat,'*');

existente:=Cantidad_Factor(TablaInventario.FieldByName('Exist_I').AsFloat,TablaInventario.FieldByName('FACTO_I').AsFloat,'*');
//TablaInventario.FieldByName('Exist_I').AsFloat;
cantidad:=existente-solicitado;

//MuestraMensaje(floattostr(cantidad));
if (cantidad<0) and (UpperCase(TablaInventario.FieldByName('LIPRO_I').AsString)<>'SERVI')and (ruta(21)='N') then
begin
MuestraMensaje('Las Compras son Superiores a las Existencias '+FloatToStr(Cantidad_Factor(TablaInventario.FieldByName('Exist_I').AsFloat,TablaInventario.FieldByName('FACTO_I').AsFloat,'*'))+' Solicitado '+FloatToStr(Solicitado));
if (Base.Text='Factura')or(Base.Text='Remisión') then
Detalle.SelectedIndex:=0;

end;

end;
end;


procedure actualizacliente;
begin
with FormaFactura do
begin
TablaCliente.First;
if TablaCliente.FindKey([cliente]) then
begin
TablaCliente.Edit;
suma:=suma+(suma*StrTofloat(EditIMIM1_F.Text)/100);
TablaCliente.FieldByName('FULCO_C').AsDateTime:=StrToDatetime(EditFEDOC_F.Text);
TablaCliente.FieldByName('SALDO_C').AsFloat:=TablaCliente.FieldByName('SALDO_C').AsFloat+suma-saldoanterior;
TablaCliente.FieldByName('COMPR_C').Asfloat:=TablaCliente.FieldByName('COMPR_C').AsFloat+suma-saldoanterior;
TablaCliente.Post;
//TablaCliente.ApplyUpdates;
end;
end;
end;

procedure configuracion;
var
arch:Textfile;
cadena:string;
begin
with FormaFactura do
begin
AssignFile(arch,leeempresa());
Reset(arch);
readln(arch,cadena);
readln(arch,cadena);
readln(arch,cadena);
readln(arch,cadena);
readln(arch,cadena);
iva:=StrTofloat(cadena);
readln(arch,cadena);
//desfin:=StrTofloat(cadena);
EditIMIM1_F.Text:=FloatToStr(iva);
EditDESFI_F.Text:=FloatToStr(desfin);
closefile(arch);

end;
end;

procedure pegafecha;
begin
with FormaFactura do
begin


end;

end;

{procedure sumatotal;
begin
with FormaFactura do
begin
   TablaDeta.First;
   suma:=0;
   costo:=0;
   desfin1:=0;
   if EditDESFI_F.Text='' then
   EditDESFI_F.Text:='0';
   while not TablaDeta.Eof do
   begin
   TablaDeta.Edit;
   TablaDeta.FieldByName('Importe').AsFloat:=TablaDeta.FieldByName('Cantidad').AsFloat*TablaDeta.FieldByName('Precio').AsFloat;
   TablaDeta.FieldByName('Importe').AsFloat:=TablaDeta.FieldByName('Importe').AsFloat-(TablaDeta.FieldByName('Importe').AsFloat*TablaDeta.FieldByName('Descuento').AsFloat/100);
   TablaDeta.Post;
   suma:=suma+TablaDeta.FieldByName('Importe').AsFloat;
   desfin1:=suma*(StrToFloat(EditDESFI_F.Text)/100);
   costo:=costo+TablaDeta.FieldByName('Costo').AsFloat;
   TablaDeta.Next;
   end;
   desfin1:=StrToFloat(redondear(desfin1));
   suma:=StrToFloat(redondear(suma));
   SumarTotal.Caption:=convierte('###,###,##0.00',redondear(suma),'$');

   if EditIMIM1_F.Text='' then iva1:=0
   else
   iva1:=StrToCurr(redondear(((suma-StrToCurr(redondear(desfin1)))*(StrToCurr(EditIMIM1_F.Text)/100))));
   ImpuestoValor.Caption:=convierte('###,###,##0.00',CurrToStr(iva1),'$');
   total1:=StrToCurr(redondear(suma))-StrToCurr(redondear(desfin1))+StrToCurr(redondear(iva1));
   TotalFact.Caption:=convierte('###,###,##0.00',redondear(total1),'$');
   end;

end;}



{procedure sumatotal;
var
cuenta:integer;
DCom:real;
Tabla:TTable;
begin
with FormaFactura do
begin
//   Tabladeta.Refresh;

   TablaDeta.First;
   suma:=0;
   ivatotal:=0;
   costo:=0;
   desfin1:=0;
   if EditDESFI_F.Text='' then
   EditDESFI_F.Text:='0';
   cuenta:=1;
   while not TablaDeta.Eof do
   begin
   TablaDeta.Edit;
   TablaDeta.FieldByName('IMPORTE').AsFloat:=TablaDeta.FieldByName('CANTIDAD').AsFloat*TablaDeta.FieldByName('PRECIO').AsFloat-
(TablaDeta.FieldByName('CANTIDAD').AsFloat*TablaDeta.FieldByName('PRECIO').AsFloat*TablaDeta.FieldByName('DESCUENTO').AsFloat/100);
TablaDeta.Post;

   suma:=suma+TablaDeta.FieldByName('Importe').AsFloat;

    if desglosado then
   begin
   ivatotal:=ivatotal+TablaDeta.FieldByName('Importe').AsFloat-(TablaDeta.FieldByName('Importe').AsFloat/(1+TablaDeta.FieldByName('Impuesto').AsFloat/100));
   end
   else
   ivatotal:=ivatotal+(TablaDeta.FieldByName('Importe').AsFloat*TablaDeta.FieldByName('Impuesto').AsFloat/100);

   desfin1:=suma*(StrToFloat(EditDESFI_F.Text)/100);
   costo:=costo+TablaDeta.FieldByName('Costo').AsFloat;
   //***guarda para comparar
   //Apartados[cuenta,1]:=TablaDeta.FieldByName('CLAVE').AsString;
  // Apartados[cuenta,2]:=TablaDeta.FieldByName('CANTIDAD').AsString;

   cuenta:=cuenta+1;
   TablaDeta.Next;
   end;

  if desglosado then
   begin
   suma:=suma-ivatotal;
   end;


   //**ojo EditDESFI_F tiene el descuento comercial
//   Dcom:=0;
   //suma:=suma*(StrToFloat(EditDESFI_F.Text)/100);
   suma:=StrToFloat(redondear(suma));
   //calcula desc. com
   if (EditDESFI_F.Text='') then EditDESFI_F.Text:='0';
   DCom:=suma*(StrToFloat(EditDESFI_F.Text)/100);
   DCom:=StrToFloat(redondear(DCom));

   suma:=suma-DCom;
   suma:=StrToFloat(redondear(suma));
   //calcula desc Fin
//   Dfin:=0;
//   if EditDECOT_F.Text='' then EditDECOT_F.Text:='0';
//   DFin:=suma*(StrToFloat(EditDECOT_F.Text)/100);
//   DFin:=StrToFloat(redondear(DFin));

//   suma:=suma-DFin;
  // desfin1:=StrToFloat(redondear(desfin1));
   suma:=StrToFloat(redondear(suma));
//   SumarTotal.Caption:=convierte('###,###,##0.00',redondear(suma),'$');

   if (EditIMIM1_F.Text='')or(EditIMIM1_F.Text='0') then
   begin
    iva1:=StrToCurr(redondear(ivatotal));
   end
   else
   iva1:=StrToCurr(redondear(suma*(StrToCurr(EditIMIM1_F.Text)/100)));

   ImpuestoValor.Caption:=convierte('###,###,##0.00',CurrToStr(iva1),'$');
//   total1:=StrToCurr(redondear(suma))-StrToCurr(redondear(desfin1))+StrToCurr(redondear(iva1));
   total1:=StrToCurr(redondear(suma))+StrToCurr(redondear(iva1));

   TotalFact.Caption:=convierte('###,###,##0.00',redondear(total1),'$');

//   suma:=suma;
   suma:=StrToFloat(redondear(suma));

   SumarTotal.Caption:=convierte('###,###,##0.00',redondear(suma),'$');


  ActualizaFacturaImporte(total1,iva1,suma);


   end;

end;}


procedure sumatotal;
var
cuenta:integer;
DCom:real;
Tabla:TTable;
indi:integer;
begin
with FormaFactura do
begin
try
//   Tabladeta.Refresh;
ListaCantidad.Clear;
ListaClaves.Clear;


Tabla:=TTable.Create(Application);
Tabla.TableName:=TablaDeta.TableName;
Tabla.DatabaseName:=TablaDeta.DatabaseName;
Tabla.Open;

   Tabla.First;
   suma:=0;
   ivatotal:=0;
   costo:=0;
   desfin1:=0;
   if EditDESFI_F.Text='' then
   EditDESFI_F.Text:='0';
   cuenta:=1;
   while not Tabla.Eof do
   begin
   Tabla.Edit;
   Tabla.FieldByName('IMPORTE').AsFloat:=Tabla.FieldByName('CANTIDAD').AsFloat*Tabla.FieldByName('PRECIO').AsFloat-
(Tabla.FieldByName('CANTIDAD').AsFloat*Tabla.FieldByName('PRECIO').AsFloat*Tabla.FieldByName('DESCUENTO').AsFloat/100);
Tabla.Post;

   suma:=suma+Tabla.FieldByName('Importe').AsFloat;


if desglosado then
   begin
   ivatotal:=ivatotal+Tabla.FieldByName('Importe').AsFloat-(Tabla.FieldByName('Importe').AsFloat/(1+Tabla.FieldByName('Impuesto').AsFloat/100));
   costo:=costo+((Tabla.FieldByName('CANTIDAD').AsFloat*Tabla.FieldByName('Costo').AsFloat)/(1+Tabla.FieldByName('Impuesto').AsFloat*0.01));
   end
   else
   begin
   ivatotal:=ivatotal+(Tabla.FieldByName('Importe').AsFloat*Tabla.FieldByName('Impuesto').AsFloat/100);
   costo:=costo+(Tabla.FieldByName('CANTIDAD').AsFloat*Tabla.FieldByName('Costo').AsFloat);
   end;

   desfin1:=suma*(StrToFloat(EditDESFI_F.Text)/100);
   //MuestraMensaje(TablaDeta.FieldByName('Costo').AsString);

   //***guarda para comparar
   //Apartados[cuenta,1]:=TablaDeta.FieldByName('CLAVE').AsString;
  // Apartados[cuenta,2]:=TablaDeta.FieldByName('CANTIDAD').AsString;

   cuenta:=cuenta+1;

   Tabla.Next;
   end;

  if desglosado then
   begin
   suma:=suma-ivatotal;
   end;


   //**ojo EditDESFI_F tiene el descuento comercial
//   Dcom:=0;
   //suma:=suma*(StrToFloat(EditDESFI_F.Text)/100);
   suma:=StrToFloat(redondear(suma));
   //calcula desc. com
   if (EditDESFI_F.Text='') then EditDESFI_F.Text:='0';
   DCom:=suma*(StrToFloat(EditDESFI_F.Text)/100);
   DCom:=StrToFloat(redondear(DCom));

   suma:=suma-DCom;
   suma:=StrToFloat(redondear(suma));
//   suma:=StrToFloat(redondear(suma));
//   SumarTotal.Caption:=convierte('###,###,##0.00',redondear(suma),'$');

   if (EditIMIM1_F.Text='')or(EditIMIM1_F.Text='0') then
   begin
    iva1:=StrToCurr(redondear(ivatotal));
   end
   else
   iva1:=StrToCurr(redondear(suma*(StrToCurr(EditIMIM1_F.Text)/100)));

   ImpuestoValor.Caption:=convierte('###,###,##0.00',CurrToStr(iva1),'$');
//   total1:=StrToCurr(redondear(suma))-StrToCurr(redondear(desfin1))+StrToCurr(redondear(iva1));
   total1:=StrToCurr(redondear(suma))+StrToCurr(redondear(iva1));

//   MuestraMensaje(FloatToStr(digitosTotal));
   if DigitosTotal>0 then
   total1:=RedondeaTotal(total1,DigitosTotal);


   TotalFact.Caption:=convierte('###,###,##0.00',redondear(total1),'$');

//   suma:=suma;
   suma:=StrToFloat(redondear(suma));

   SumarTotal.Caption:=convierte('###,###,##0.00',redondear(suma),'$');


  ActualizaFacturaImporte(total1,iva1,suma);

  Tabla.Close;
  Tabla.Free;

except
end;

   end;//width

end;




procedure SumaTotalCantidad;
var
cuenta:integer;
indi:integer;
TablaD:TTable;
begin
with FormaFactura do
begin

TablaD:=TTable.Create(Application);
TablaD.DatabaseName:=TablaDeta.DataBaseName;
TablaD.TableName:=TablaDeta.TableName;
TablaD.Open;

ListaCantidad.Clear;
ListaClaves.Clear;
//   Tabladeta.Refresh;
   TablaD.First;
   cuenta:=1;
   while not TablaD.Eof do
   begin

   //**pone los valores en las listas
   if ListaClaves.Find(TablaD.FieldByName('CLAVE').AsString,indi) then
   begin
   ListaCantidad.Insert(indi,FloatToStr(StrToFloat(ListaCantidad.Strings[indi])+TablaD.FieldByName('CANTIDAD').AsFloat));
   ListaCantidad.Delete(indi+1);
   end
   else
   begin
   ListaCantidad.Add(TablaD.FieldByName('Cantidad').AsString);
   ListaClaves.Add(TablaD.FieldByName('Clave').AsString);
   end;


   TablaD.Next;


   end;

//   ShowMessage( ListaClaves.Text+ListaCantidad.Text);
   end;

   TablaD.Close;
   TablaD.Free;

end;





procedure generacuentasxcobrar(tipo:char);
var
saldo:Currency;
cambio:Boolean;
begin
{
with FormaFactura do
begin

if tipo='N' then
begin
TablaCuentasxCobrar.Insert;
TablaCuentasxCobrar.FieldByName('CLCLI_CC').AsString:=EditCLCLI_F.Text;
TablaCuentasxCobrar.FieldByName('NOMBR_CC').AsString:=Nombre.Caption;
TablaCuentasxCobrar.FieldByName('STATU_CC').AsString:='F';
TablaCuentasxCobrar.FieldByName('TIMOV_CC').AsInteger:=1;
TablaCuentasxCobrar.FieldByName('CONCE_CC').AsString:='Factura';
TablaCuentasxCobrar.FieldByName('NUFAC_CC').AsString:=EditCLDOC_F.Text;
TablaCuentasxCobrar.FieldByName('OPERA_CC').AsString:='C';
TablaCuentasxCobrar.FieldByName('NUDOC_CC').AsInteger:=StrToInt(EditCLDOC_F.Text);
sumatotal;
TablaCuentasxCobrar.FieldByName('IMCUE_CC').AsFloat:=total1;
TablaCuentasxCobrar.FieldByName('SALDO_CC').AsFloat:=total1;
TablaCuentasxCobrar.FieldByName('CARGO_CC').AsFloat:=total1;
TablaCuentasxCobrar.FieldByName('FEAPL_CC').AsDateTime:=StrToDaTeTime(EditFEDOC_F.Text);
TablaCuentasxCobrar.Post;
//TablaCuentasxCobrar.ApplyUpdates;
end;

if tipo='C' then
begin
TablaCuentasxcobrar.CancelRange;
TablaCuentasxcobrar.SetRange([EditCLDOC_F.Text],[EditCLDOC_F.Text]);
TablaCuentasxcobrar.First;
cambio:=False;

while not TablaCuentasxCobrar.Eof do
begin
if (TablaCuentasxCobrar.FieldByName('STATU_CC').AsString='F') then
begin
TablaCuentasxCobrar.Edit;
TablaCuentasxCobrar.FieldByName('CLCLI_CC').AsString:=EditCLCLI_F.Text;
TablaCuentasxCobrar.FieldByName('NOMBR_CC').AsString:=Nombre.Caption;
TablaCuentasxCobrar.FieldByName('STATU_CC').AsString:='F';
TablaCuentasxCobrar.FieldByName('TIMOV_CC').AsInteger:=1;
TablaCuentasxCobrar.FieldByName('CONCE_CC').AsString:='Factura';
TablaCuentasxCobrar.FieldByName('NUFAC_CC').AsString:=EditCLDOC_F.Text;
TablaCuentasxCobrar.FieldByName('OPERA_CC').AsString:='C';
TablaCuentasxCobrar.FieldByName('NUDOC_CC').AsInteger:=StrToInt(EditCLDOC_F.Text);
sumatotal;
saldo:=TablaCuentasxCobrar.FieldByName('IMCUE_CC').AsFloat-TablaCuentasxCobrar.FieldByName('SALDO_CC').AsFloat;
TablaCuentasxCobrar.FieldByName('IMCUE_CC').AsFloat:=total1;
TablaCuentasxCobrar.FieldByName('CARGO_CC').AsFloat:=total1;
TablaCuentasxCobrar.FieldByName('SALDO_CC').AsFloat:=total1-saldo;
TablaCuentasxCobrar.FieldByName('FEAPL_CC').AsDateTime:=StrToDaTeTime(EditFEDOC_F.Text);
TablaCuentasxCobrar.Post;
//TablaCuentasxCobrar.ApplyUpdates;

cambio:=True;
Break;

end;
 TablaCuentasxCobrar.Next;
end;

if not cambio then
begin
TablaCuentasxCobrar.Insert;
TablaCuentasxCobrar.FieldByName('CLCLI_CC').AsString:=EditCLCLI_F.Text;
TablaCuentasxCobrar.FieldByName('NOMBR_CC').AsString:=Nombre.Caption;
TablaCuentasxCobrar.FieldByName('STATU_CC').AsString:='F';
TablaCuentasxCobrar.FieldByName('TIMOV_CC').AsInteger:=1;
TablaCuentasxCobrar.FieldByName('CONCE_CC').AsString:='Factura';
TablaCuentasxCobrar.FieldByName('NUFAC_CC').AsString:=EditCLDOC_F.Text;
TablaCuentasxCobrar.FieldByName('OPERA_CC').AsString:='C';
TablaCuentasxCobrar.FieldByName('NUDOC_CC').AsInteger:=StrToInt(EditCLDOC_F.Text);
sumatotal;
saldo:=TablaCuentasxCobrar.FieldByName('IMCUE_CC').AsFloat-TablaCuentasxCobrar.FieldByName('SALDO_CC').AsFloat;
TablaCuentasxCobrar.FieldByName('IMCUE_CC').AsFloat:=total1;
TablaCuentasxCobrar.FieldByName('SALDO_CC').AsFloat:=total1-saldo;
TablaCuentasxCobrar.FieldByName('FEAPL_CC').AsDateTime:=StrToDaTeTime(EditFEDOC_F.Text);
TablaCuentasxCobrar.Post;
//TablaCuentasxCobrar.ApplyUpdates;
end;

end;



end;
}
end;


procedure BuscaCxC;
var
cambio:boolean;
begin
{
with FormaFactura do
begin

TablaCuentasxcobrar.CancelRange;
TablaCuentasxcobrar.SetRange([EditCLDOC_F.Text],[EditCLDOC_F.Text]);
TablaCuentasxcobrar.First;
cambio:=True;

while not TablaCuentasxCobrar.Eof do
begin
if (TablaCuentasxCobrar.FieldByName('STATU_CC').AsString='F') then
begin
//sumatotal;
cambio:=False;
Break;
end;
 TablaCuentasxCobrar.Next;
end;

if  cambio then
begin
sumatotal;
generacuentasxcobrar('N');
end;

end;
}

end;


procedure mueveteclas;
var
i,componente:integer;
begin
with FormaFactura do
begin

while indice < ComponentCount-1 do
begin

if Components[indice] is TDBEdit then
if TDBEdit(Components[indice]).TabOrder = sig then
begin
//MuestraMensaje(IntToStr(TDBEdit(Components[indice]).TabOrder));
TDBEdit(Components[indice]).SetFocus;
MuestraMensaje(IntToStr(indice));
indice:=1000;
end;
indice:=indice+1;
end;

indice:=0;
sig:=sig+1;

{while not (Components[indice] is TDBEdit) do
begin

if indice < ComponentCount-1 then
indice:=indice+1;
if indice=ComponentCount-1 then
indice:=0;
end;

if Components[indice] is TDBEdit then
begin
TDBEdit(Components[indice]).SetFocus;
MuestraMensaje(IntToStr(TDBEdit(Components[indice]).TabOrder));
end;
indice:=indice+1;}
end;


end;

{Procedure MovimientosInventario;
begin
if IntegrarMI='S' then
begin
with FormaFactura do
begin


 TablamovimientosInventario.Insert;
 TablamovimientosInventario.FieldByName('CLDOC_MI').AsInteger:= numeromovimiento;
 TablamovimientosInventario.FieldByName('CLPRO_MI').AsString:= TablaDeta.FieldByName('CLAVE').AsString;
 TablamovimientosInventario.FieldByName('DESCR_MI').AsString:= TablaDeta.FieldByName('PRODUCTO').AsString;
 TablamovimientosInventario.FieldByName('TIMOV_MI').AsInteger:= tipomovimiento;
 TablamovimientosInventario.FieldByName('FEDOC_MI').AsString:= EditFEDOC_F.Text;
 TablamovimientosInventario.FieldByName('REFMO_MI').AsString:= EditCLDOC_F.Text;
 TablamovimientosInventario.FieldByName('CLCOP_MI').AsString:= EditCLCLI_F.Text;
 TablamovimientosInventario.FieldByName('CLVEN_MI').AsString:= EditCLVEN_F.Text;
 TablamovimientosInventario.FieldByName('CANTI_MI').AsFloat:= TablaDeta.FieldByName('CANTIDAD').AsFloat;
 TablamovimientosInventario.FieldByName('PUNIT_MI').AsFloat:= TablaDeta.FieldByName('PRECIO').AsFloat;
 TablamovimientosInventario.FieldByName('BANAF_MI').AsString:='F';

 TablamovimientosInventario.Post;
// TablamovimientosInventario.ApplyUpdates;
 end;
end;
end;}


{Procedure MovimientosInventario;
begin
if IntegrarMI='S' then
begin

with FormaFactura do
begin

 TablamovimientosInventario.Insert;
if MovimientoBorrado<>0 then
TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger:=MovimientoBorrado
else
TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger:=numeromovimiento;
//MuestraMensaje(IntToStr(numeromovimiento));
TablamovimientosInventario.FieldByName('CONTROL').AsInteger:=AsignaControlVariable;
 TablamovimientosInventario.FieldByName('CLPRO_MI').AsString:= TablaDeta.FieldByName('CLAVE').AsString;
 TablamovimientosInventario.FieldByName('DESCR_MI').AsString:= TablaDeta.FieldByName('PRODUCTO').AsString;
 TablamovimientosInventario.FieldByName('TIMOV_MI').AsInteger:=tipomovimiento;
 TablamovimientosInventario.FieldByName('FEDOC_MI').AsString:= EditFEDOC_F.Text;
 TablamovimientosInventario.FieldByName('REFMO_MI').AsString:= EditCLDOC_F.Text;
 TablamovimientosInventario.FieldByName('NUDOC_MI').AsString:=PrefijoMovimiento(Base.Text)+ EditCLDOC_F.Text;
 TablamovimientosInventario.FieldByName('CLCOP_MI').AsString:= EditCLCLI_F.Text;
 TablamovimientosInventario.FieldByName('CLVEN_MI').AsString:= EditCLVEN_F.Text;
 TablamovimientosInventario.FieldByName('CANTI_MI').AsFloat:=Cantidad_Factor(TablaDeta.FieldByName('CANTIDAD').AsFloat,TablaDeta.FieldByName('FACTOR').AsFloat,'/');

 TablamovimientosInventario.FieldByName('PUNIT_MI').AsFloat:= TablaDeta.FieldByName('PRECIO').AsFloat;
 TablamovimientosInventario.FieldByName('COSUN_MI').AsFloat:= TablaDeta.FieldByName('COSTO').AsFloat;
// if EditNALMA_F.Text='' then
// TablamovimientosInventario.FieldByName('NALMA_MI').AsString:='1'
// else
// TablamovimientosInventario.FieldByName('NALMA_MI').AsString:=EditNALMA_F.Text;
 TablamovimientosInventario.FieldByName('BANAF_MI').AsString:='F';
 TablamovimientosInventario.FieldByName('CLPRV_MI').AsString:=EditCLCLI_F.Text;
 TablamovimientosInventario.Post;

 end;

end;//if principal

end;}


procedure CreaMI(actu:real);
begin
with FormaFactura do
begin

//ShowMessage(IntToStr(numeromovimiento));
 TablamovimientosInventario.Insert;

if MovimientoBorrado<>0 then
TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger:=MovimientoBorrado
else
TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger:=numeromovimiento;

TablamovimientosInventario.FieldByName('CONTROL').AsInteger:=AsignaControlVariable;

 TablamovimientosInventario.FieldByName('CLPRO_MI').AsString:= TablaDeta.FieldByName('CLAVE').AsString;
 TablamovimientosInventario.FieldByName('DESCR_MI').AsString:= TablaDeta.FieldByName('PRODUCTO').AsString;
 TablamovimientosInventario.FieldByName('TIMOV_MI').AsInteger:=tipomovimiento;
 TablamovimientosInventario.FieldByName('FEDOC_MI').AsString:= EditFEDOC_F.Text;
 TablamovimientosInventario.FieldByName('REFMO_MI').AsString:= EditCLDOC_F.Text;
 TablamovimientosInventario.FieldByName('NUDOC_MI').AsString:=PrefijoMovimiento(Base.Text)+ EditCLDOC_F.Text;
 TablamovimientosInventario.FieldByName('CLCOP_MI').AsString:= EditCLCLI_F.Text;
 TablamovimientosInventario.FieldByName('CLVEN_MI').AsString:= EditCLVEN_F.Text;
 TablamovimientosInventario.FieldByName('CANTI_MI').AsFloat:= TablaDeta.FieldByName('CANTIDAD').AsFloat;
 TablamovimientosInventario.FieldByName('PUNIT_MI').AsFloat:= TablaDeta.FieldByName('PRECIO').AsFloat;
 TablamovimientosInventario.FieldByName('COSUN_MI').AsFloat:= TablaDeta.FieldByName('COSTO').AsFloat;
// if EditNALMA_F.Text='' then
// TablamovimientosInventario.FieldByName('NALMA_MI').AsString:='1'
// else
// TablamovimientosInventario.FieldByName('NALMA_MI').AsString:=EditNALMA_F.Text;
 TablamovimientosInventario.FieldByName('BANAF_MI').AsString:='F';
 TablamovimientosInventario.FieldByName('CLPRV_MI').AsString:=EditCLCLI_F.Text;
 TablamovimientosInventario.FieldByName('EXIST_MI').AsFloat:=actu;

 TablamovimientosInventario.Post;

end;
end;


Procedure MovimientosInventario;
//(actu:Real);
var
aux:string;
begin
//ShowMessage(floatToStr(actu));
if (IntegrarMI='S'){and(actu>=0)} then

begin

with FormaFactura do
begin
try
CreaMI(0);
 except
 //trata de guardar otra vez el movimiento
 i:=0;
 aux:=Caption;
 while i<1000 do
 begin
 try
 CreaMI(0);
 i:=2000;
 except

 Caption:=aux+' Guardando MI, Problema de Tráfico...intento '+IntToStr(i);
 Refresh;
 i:=i+1;
 end;


 end;//except 1

 end;
 end;

end;//if principal

end;



Procedure MovimientosInventarioAjuste;
begin
if IntegrarMI='S' then
begin

with FormaFactura do
begin

 TablamovimientosInventario.Insert;
if MovimientoBorrado<>0 then
TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger:=MovimientoBorrado
else
TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger:=numeromovimiento;

 TablamovimientosInventario.FieldByName('CONTROL').AsInteger:=AsignaControlVariable;
 TablamovimientosInventario.FieldByName('CLPRO_MI').AsString:= TablaDeta.FieldByName('CLAVE').AsString;
 TablamovimientosInventario.FieldByName('DESCR_MI').AsString:= TablaDeta.FieldByName('PRODUCTO').AsString;
 TablamovimientosInventario.FieldByName('TIMOV_MI').AsInteger:=52;
 TablamovimientosInventario.FieldByName('FEDOC_MI').AsString:= EditFEDOC_F.Text;
 TablamovimientosInventario.FieldByName('REFMO_MI').AsString:= EditCLDOC_F.Text;
 TablamovimientosInventario.FieldByName('NUDOC_MI').AsString:=PrefijoMovimiento(Base.Text)+ EditCLDOC_F.Text;
 TablamovimientosInventario.FieldByName('CLCOP_MI').AsString:= EditCLCLI_F.Text;
 TablamovimientosInventario.FieldByName('CLVEN_MI').AsString:= EditCLVEN_F.Text;
 TablamovimientosInventario.FieldByName('CANTI_MI').AsFloat:=Cantidad_Factor(TablaDeta.FieldByName('CANTIDAD').AsFloat,TablaDeta.FieldByName('FACTOR').AsFloat,'/');
 TablamovimientosInventario.FieldByName('PUNIT_MI').AsFloat:= TablaDeta.FieldByName('PRECIO').AsFloat;
 TablamovimientosInventario.FieldByName('COSUN_MI').AsFloat:= TablaDeta.FieldByName('COSTO').AsFloat;
// if EditNALMA_F.Text='' then
// TablamovimientosInventario.FieldByName('NALMA_MI').AsString:='1'
// else
// TablamovimientosInventario.FieldByName('NALMA_MI').AsString:=EditNALMA_F.Text;
 TablamovimientosInventario.FieldByName('BANAF_MI').AsString:='F';
 TablamovimientosInventario.FieldByName('CLPRV_MI').AsString:=EditCLCLI_F.Text;

 TablamovimientosInventario.Post;
 end;

end;//if principal

end;


procedure CreaMovimiento_Cancelar(TM:word);
begin
with FormaFactura do
begin
TablaDeta.First;
MovimientoBorrado:=0;
//TipoMovimiento:=54;
TipoMovimiento:=TM;
//MuestraMensaje(tipo);
//OcurrioFalloExistencias:=True;
while not TablaDeta.eof do
begin
{MuestraMensaje('guardando deta');}

if ((TablaDeta.FieldByName('Cantidad').AsFloat>0)and(TablaDeta.FieldByName('Clave').AsString<>'')and(TablaDeta.FieldByName('Producto').AsString<>''))or(TablaDeta.FieldByName('Clave').AsString='COMENTARIO') then
begin

//TablaInventario.First;
if ((TablaInventario.FindKey([TablaDeta.FieldByName('Clave').AsString])))or(TablaDeta.FieldByName('Clave').AsString='COMENTARIO') then
begin
//if tipo<>'Z' then
//begin

//ActualizaInventario(-1);
try
if (UpperCase(TablaInventario.FieldByName('LIPRO_I').AsString)<>'SERVI') then
begin
if (BotonCambios.Tag<>1)or(MovimientoBorrado<>0) then
MovimientosInventario
else
begin
MovimientosInventarioAjuste;
MovimientosInventario;
end;

end;

except
end;


//end;

end;//if detalle
end;
TablaDeta.Next;
end;//while
MovimientoBorrado:=0;

end;
end;


procedure devolucionproductos;
var
monto,cantidad:Real;
CantidadAnterior:Real;
begin
With FormaFactura do
begin
TablaDeta.First;

while not TablaDeta.Eof do
begin
 TablaInventario.First;
 if TablaInventario.FindKey([TablaDeta.FieldByName('clave').AsString]) then
 begin
 TablaInventario.Edit;

  CantidadAnterior:=TablaInventario.FieldByName('EXIST_I').AsFloat;

 TablaInventario.FieldByName('EXIST_I').AsFloat:= TablaInventario.FieldByName('EXIST_I').AsFloat +
 Cantidad_Factor(TablaDeta.FieldByName('cantidad').AsFloat,TablaDeta.FieldByName('factor').AsFloat,'/');

  TablaInventario.FieldByName('VANCA_I').AsFloat:= TablaInventario.FieldByName('VANCA_I').AsFloat+
 (CantidadAnterior-TablaInventario.FieldByName('EXIST_I').AsFloat);

  TablaInventario.FieldByName('VANMO_I').AsFloat:= TablaInventario.FieldByName('VANMO_I').AsFloat+
 ((CantidadAnterior-TablaInventario.FieldByName('EXIST_I').AsFloat)*TablaDeta.FieldByName('precio').AsFloat);

// TablaDeta.FieldByName('cantidad').AsFloat;
 if (TablaInventario.FieldByName('EXIST_I').AsFloat<0)and(ExistenciasNegativos='N') then
 TablaInventario.FieldByName('EXIST_I').AsFloat:=0;

 TablaInventario.FieldByName('VANMO_I').AsFloat:= TablaInventario.FieldByName('VANMO_I').AsFloat -
 TablaDeta.FieldByName('IMPORTE').AsFloat;

 TablaInventario.FieldByName('VANCA_I').AsFloat:= TablaInventario.FieldByName('VANCA_I').AsFloat -
 TablaDeta.FieldByName('CANTIDAD').AsFloat;

 TablaInventario.Post;
// TablaInventario.ApplyUpdates;

 end;
{MuestraMensaje(FloatToStr(datos.cantidad)+(datos.clave)+(datos.descripcion)+FloatToStr(datos.precio)+
FloatToStr(datos.descuento));}
movimientosinventario;
TablaDeta.Next;
end;

end;
end;


procedure fechas(pos:integer;letra:char);
var cad:string[2];
     fecha:String[12];
    num,code:integer;
begin

end;


function revisafactura(cad:string):boolean;
begin
With FormaFactura do
begin
if EditCLCLI_F.Text='' then
begin
MuestraMensaje('No se puede Guardar la Factura faltan datos del Cliente');
revisafactura:=false;
end
else  revisafactura:=true;
end;
end;

procedure borradatoscliente;
begin

 FormaFactura.Nombre.Caption:='';
 FormaFactura.Direccion.Caption:='';
 FormaFactura.Direc2.Caption:='';
 FormaFactura.Poblacion.Caption:='';
 FormaFactura.CodigoPostal.Caption:='';
 FormaFactura.RFC.Caption:='';

 FormaFactura.EditFEDOC_F.Text:='';
{ FormaFactura.EditFEENT_F.Text:='';}
{ FormaFactura.EditFEVEN_F.Text:='';}

end;


procedure ActualizaInventario;
var
CantidadAnterior:Real;
begin
with FormaFactura do
begin
TablaInventario.First;
 if (TablaInventario.FindKey([TablaDeta.FieldByName('Clave').AsString]))and(TablaInventario.FieldByName('DSCPR_I').AsString<>'') then
 begin
 TablaInventario.Edit;
  CantidadAnterior:=TablaInventario.FieldByName('EXIST_I').AsFloat;

 TablaInventario.FieldByName('EXIST_I').AsFloat:= TablaInventario.FieldByName('EXIST_I').AsFloat-
 Cantidad_Factor(TablaDeta.FieldByName('cantidad').AsFloat,TablaDeta.FieldByName('factor').AsFloat,'/');

  TablaInventario.FieldByName('VANCA_I').AsFloat:= TablaInventario.FieldByName('VANCA_I').AsFloat+
 (CantidadAnterior-TablaInventario.FieldByName('EXIST_I').AsFloat);

  TablaInventario.FieldByName('VANMO_I').AsFloat:= TablaInventario.FieldByName('VANMO_I').AsFloat+
 ((CantidadAnterior-TablaInventario.FieldByName('EXIST_I').AsFloat)*TablaDeta.FieldByName('precio').AsFloat);

// TablaDeta.FieldByName('cantidad').AsFloat;
 if (TablaInventario.FieldByName('EXIST_I').AsFloat<0)and(ExistenciasNegativos='N') then
 TablaInventario.FieldByName('EXIST_I').AsFloat:=0;

 TablaInventario.FieldByName('VANCA_I').AsFloat:= TablaInventario.FieldByName('VANCA_I').AsFloat+TablaDeta.FieldByName('cantidad').AsFloat;
 TablaInventario.FieldByName('VANMO_I').AsFloat:= TablaInventario.FieldByName('VANMO_I').AsFloat+TablaDeta.FieldByName('cantidad').AsFloat*TablaDeta.FieldByName('precio').AsFloat;
  try
 TablaInventario.FieldByName('FEULV_I').AsString:=EditFEDOC_F.Text;
 except
 end;

 TablaInventario.Post;
//  TablaInventario.ApplyUpdates;
 end;
end;

end;


procedure LeeDetalle;
begin

with FormaFactura do

begin

Borra;
TablaFacturaD.SetRange([TablaFacturaE.FieldByName('CLDOC_F').AsString],[TablaFacturaE.FieldByName('CLDOC_F').AsString]);

{TablaFacturaD.First;}
TablaFacturaD.Last;

while not TablaFacturaD.Bof do
begin
TablaDeta.Insert;

TablaDeta.FieldByName('CANTIDAD').AsFloat:=TablaFacturaD.FieldByName('CANTI_FD').AsFloat;
TablaDeta.FieldByName('CLAVE').AsString:=TablaFacturaD.FieldByName('CLPRO_FD').AsString;
TablaDeta.FieldByName('TARA').AsString:=TablaFacturaD.FieldByName('PENDI_FD').AsString;

TablaDeta.FieldByName('PRODUCTO').AsString:=TablaFacturaD.FieldByName('DEPRO_FD').AsString;
TablaDeta.FieldByName('UNIDAD').AsString:=TablaFacturaD.FieldByName('UNIDA_FD').AsString;
TablaDeta.FieldByName('PRECIO').AsFloat:=TablaFacturaD.FieldByName('PUNPR_FD').AsFloat;
TablaDeta.FieldByName('COSTO').AsFloat:=TablaFacturaD.FieldByName('COPRO_FD').AsFloat;
TablaDeta.FieldByName('FACTOR').AsFloat:=TablaFacturaD.FieldByName('PIVA2_FD').AsFloat;
//*TablaDeta.FieldByName('CANTIDAD').AsFloat;
TablaDeta.FieldByName('DESCUENTO').AsFloat:=TablaFacturaD.FieldByName('PDES1_FD').AsFloat;
TablaDeta.FieldByName('IMPORTE').AsFloat:=TablaDeta.FieldByName('CANTIDAD').AsFloat*TablaDeta.FieldByName('PRECIO').AsFloat-
(TablaDeta.FieldByName('CANTIDAD').AsFloat*TablaDeta.FieldByName('PRECIO').AsFloat*TablaDeta.FieldByName('DESCUENTO').AsFloat/100);
TablaDeta.FieldByName('IMPUESTO').AsFloat:=TablaFacturaD.FieldByName('PIVA1_FD').AsFloat;
TablaDeta.FieldByName('FACTOR').AsFloat:=TablaFacturaD.FieldByName('PIVA2_FD').AsFloat;

try
TablaDeta.FieldByName('FPGC').AsFloat:=TablaFacturaD.FieldByName('FPGCX_FD').AsFloat;
except
end;

TablaDeta.Post;
//TablaDeta.ApplyUpdates;
TablaFacturaD.Prior;

begin

end;


end;

end;
end;


function LeeDetalleCierre(inicio,fin,fecha:string):integer;
var
ExistiaFacturaCierre:Boolean;
cuenta:integer;
begin

with FormaFactura do

begin

Borra;
TablaFacturaD.SetRange([inicio],[fin]);
//MuestraMensaje('Ventas del Documento '+inicio+'  al  '+fin);
{TablaFacturaD.First;}
TablaFacturaD.First;
ExistiaFacturaCierre:=False;

cuenta:=0;
while not TablaFacturaD.Eof do
begin
if (TablaFacturaE.FindKey([TablaFacturaD.FieldByName('CLDOC_FD').AsString])) then
begin
if (TablaFacturaE.FieldByName('REMIS_F').AsString='') then
begin
//mUESTRAmENSAJE('ENTRO');
if (TablaFacturaD.FieldByName('TREGI_FD').AsString<>'F') then
begin
if(TablaFacturaD.FieldByName('TREGI_FD').AsString<>'C') then
begin
TablaDeta.Append;
cuenta:=cuenta+1;
TablaDeta.FieldByName('CANTIDAD').AsFloat:=TablaFacturaD.FieldByName('CANTI_FD').AsFloat;
TablaDeta.FieldByName('CLAVE').AsString:=TablaFacturaD.FieldByName('CLPRO_FD').AsString;
TablaDeta.FieldByName('PRODUCTO').AsString:=TablaFacturaD.FieldByName('DEPRO_FD').AsString;
TablaDeta.FieldByName('UNIDAD').AsString:=TablaFacturaD.FieldByName('UNIDA_FD').AsString;
TablaDeta.FieldByName('PRECIO').AsFloat:=TablaFacturaD.FieldByName('PUNPR_FD').AsFloat;
TablaDeta.FieldByName('COSTO').AsFloat:=TablaFacturaD.FieldByName('COPRO_FD').AsFloat;
//*TablaDeta.FieldByName('CANTIDAD').AsFloat;
TablaDeta.FieldByName('DESCUENTO').AsFloat:=TablaFacturaD.FieldByName('PDES1_FD').AsFloat;
TablaDeta.FieldByName('IMPORTE').AsFloat:=TablaDeta.FieldByName('CANTIDAD').AsFloat*TablaDeta.FieldByName('PRECIO').AsFloat-
(TablaDeta.FieldByName('CANTIDAD').AsFloat*TablaDeta.FieldByName('PRECIO').AsFloat*TablaDeta.FieldByName('DESCUENTO').AsFloat/100);

TablaDeta.Post;
end;//if cancelado
//TablaDeta.ApplyUpdates;

end
else
begin
ExistiaFacturaCierre:=True;
end;
end;//if TablaFacturaE.findkey
end;

TablaFacturaD.Next;
end;//while


LeeDetalleCierre:=cuenta;
if ExistiaFacturaCierre then
MuestraMensaje('Existe una Factura de Cierre para esta Fecha...');

end;
end;




{function ChecaRepeticion(ulti:LongInt):LongInt;
var
actual,anterior,siguiente,ultimo:longint;
claves,clavesaux:array[1..15] of LongInt;
j,su,k:integer;
begin
With FormaFactura do
begin
j:=0;
anterior:=ulti;
while (j<15)and (not TablaFacturaE.Bof) do
begin
TablaFacturaE.Prior;
anterior:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger;
j:=j+1;

if (anterior<ulti)then
break;

end;

TablaFacturaE.MoveBy(j);
ChecaRepeticion:=ulti+j-1;
end;
end; }


function ChecaRepeticion(ulti:LongInt):LongInt;
var
actual,anterior,siguiente,ultimo:longint;
claves,clavesaux:array[1..15] of LongInt;
j,su,k:LongInt;
TablaFacturaUltima:TTable;
begin
With FormaFactura do
begin
{*************** checa si no se repite ******}
{TablaFacturaE.MoveBy(-7);}
//MuestraMensaje('nuevo ulti '+IntToStr(UltimoDocumento));

//***************Caso del primer documento
//MuestraMensaje('nuevo ultimos  '+IntToStr(ultimodocumento)+'   '+IntToStr(ulti)+'   registros'+IntToStr(k));
if ulti=1 then
begin
k:=TablaFacturaE.RecordCount;
//MuestraMensaje('nuevo ultimos  '+IntToStr(ultimodocumento)+'   '+IntToStr(ulti)+'   registros'+IntToStr(k));
if k>1 then
begin
try


TablaFacturaUltima:=TTable.Create(Application);
TablaFacturaUltima.DatabaseName:=ruta(8);
//Tabla.TableName:='Remision.dbf';
TablaFacturaUltima.TableName:=TablafacturaE.TableName;
TablaFacturaUltima.IndexName:=TablafacturaE.IndexName;
TablaFacturaUltima.Open;


TablaFacturaUltima.Last;
Ulti:=TablaFacturaUltima.FieldByName('CLDOC_F').AsInteger+1;
//MuestraMensaje('nuevo ulti '+IntToStr(ulti));
TablaFacturaUltima.Close;
TablaFacturaUltima.Free;

except
end;


end;


end;
k:=0;
//*******************************

j:=0;

while  (ulti<UltimoDocumento)and(j<10) do
begin
 //ChecaRepeticion:=UltimoDocumento;

//**********vuelve a buscar el ultimo***********
try

TablaFacturaUltima:=TTable.Create(Application);
TablaFacturaUltima.DatabaseName:=ruta(8);
//Tabla.TableName:='Remision.dbf';
TablaFacturaUltima.TableName:=TablafacturaE.TableName;
TablaFacturaUltima.IndexName:=TablafacturaE.IndexName;
TablaFacturaUltima.Open;


TablaFacturaUltima.Last;
Ulti:=TablaFacturaUltima.FieldByName('CLDOC_F').AsInteger+1;
//MuestraMensaje('nuevo ulti '+IntToStr(ulti));
TablaFacturaUltima.Close;
TablaFacturaUltima.Free;

except
end;

j:=j+1;
end;//while


if ulti>=UltimoDocumento then
begin
TablaFacturaE.Edit;
TablaFacturaE.FieldByName('CLDOC_F').AsInteger:=ulti;
TablaFacturaE.Post;
TablaFacturaE.Refresh;
end;

j:=0;
anterior:=ulti;
{MuestraMensaje(InttoStr(ulti));}
while (j<15)and (not TablaFacturaE.Bof) do
begin
TablaFacturaE.Prior;
anterior:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger;
//MuestraMensaje('fin '+IntToStr(j)+IntToStr(anterior));
j:=j+1;

if (anterior<ulti)then
break;

end;

//MuestraMensaje('Se movera por '+IntToStr(j)+'posicion actual '+IntToStr(TablaFacturaE.RecNo));
TablaFacturaE.MoveBy(j);

ChecaRepeticion:=ulti+j-1;

if ulti+j-1<UltimoDocumento then
begin
 //ChecaRepeticion:=UltimoDocumento;

//**********vuelve a buscar el ultimo***********
try

TablaFacturaUltima:=TTable.Create(Application);
TablaFacturaUltima.DatabaseName:=ruta(8);
//Tabla.TableName:='Remision.dbf';
TablaFacturaUltima.TableName:=TablafacturaE.TableName;
TablaFacturaUltima.IndexName:=TablafacturaE.IndexName;
TablaFacturaUltima.Open;


TablaFacturaUltima.Last;
Ulti:=TablaFacturaUltima.FieldByName('CLDOC_F').AsInteger+1;
//MuestraMensaje(IntToStr(ulti));
TablaFacturaUltima.Close;
TablaFacturaUltima.Free;

except
end;

//MuestraMensaje('nuevo ultimos  '+IntToStr(ultimodocumento)+'   '+IntToStr(ulti));

if ulti<UltimoDocumento then
ChecaRepeticion:=-1
else
ChecaRepeticion:=Ulti;


//if (UltimoDocumento<10)and (UltimoDocumento>1) then  UltimoDocumento:=ulti;
//if UltimoDocumento=0 then UltimoDocumento:=ulti;

end;

end;

//***************************************


//****************************************
end;


procedure actualizafactura(tipo:Char);
var
ultimo:LongInt;
begin
With FormaFactura do
begin
AsignaControlVariable:=AsignaControl;
BotonNuevo.Enabled:=True;
BotonGuardar.Enabled:=False;
BotonImprimir.Enabled:=True;

{******guarda encabezado****************}
sumatotal;
//MuestraMensaje(IntToStr(ultimoDocumento));
ultimo:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger;
if (BotonNuevo.Tag=1) then
begin
if ultimo<UltimoDocumento then
begin
try
ultimo:=StrToInt(EditCLDOC_F.Text);
except
ultimo:=UltimoDocumento;
end;
end;

ultimo:=ChecaRepeticion(ultimo);

if (ultimo=-1) then
begin

MuestraMensaje('Ocurrio un error en la red no se guardaran los datos...');
exit;
end;

end;

TablaFacturaE.Edit;
TablaFacturaE.FieldByName('CLDOC_F').AsInteger:=ultimo;
TablaFacturaE.FieldByName('CONTROL').AsInteger:=AsignaControlVariable;
TablaFacturaE.FieldByName('NOMBR_F').AsString:=Nombre.Caption;
TablaFacturaE.FieldByName('DIREC_F').AsString:=Direccion.Caption;
TablaFacturaE.FieldByName('DIRE2_F').AsString:=Direc2.Caption;
TablaFacturaE.FieldByName('POBLA_F').AsString:=Poblacion.Caption;
TablaFacturaE.FieldByName('RFCXX_F').AsString:=RFC.Caption;
TablaFacturaE.FieldByName('CPXXX_F').AsString:=CodigoPostal.Caption;

TablaFacturaE.FieldByName('FEDOC_F').AsDateTime:=StrToDateTime(EditFEDOC_F.Text);
TablaFacturaE.FieldByName('FEENT_F').AsDateTime:=StrToDateTime(EditFEDOC_F.Text);
TablaFacturaE.FieldByName('FEVEN_F').AsDateTime:=StrToDateTime(EditFEDOC_F.Text);
TablaFacturaE.FieldByName('SUBTO_F').AsFloat:=suma;
TablaFacturaE.FieldByName('DECOT_F').AsFloat:=desfin1;
TablaFacturaE.FieldByName('IMIM2_F').AsFloat:=iva1;
TablaFacturaE.FieldByName('IMTOD_F').AsFloat:=Total1;
TablaFacturaE.FieldByName('COSTO_F').AsFloat:=costo;

TablaFacturaE.FieldByName('HORAX_F').AsString:= TimeToStr(Time);
TablaFacturaE.FieldByName('PAGOX_F').AsString:=TipoPago.Text;
{TablaFacturaE.FieldByName('NOMDI_F').AsString:=EditDIVIS_F.Text;
TablaFacturaE.FieldByName('DIVIS_F').AsString:=EditVALDI_F.Text;
if Tipo='D' then
TablaFacturaE.FieldByName('STATU_F').AsString:='P';}

TablaFacturaE.Post;
//TablaFacturaE.ApplyUpdates;

{*******termina encabezado***********}

TablaDeta.First;
while not TablaDeta.eof do
begin
//MuestraMensaje('guardando deta');

if (TablaDeta.FieldByName('Cantidad').AsFloat>0)and(TablaDeta.FieldByName('Clave').AsString<>'')and(TablaDeta.FieldByName('Producto').AsString<>'') then
begin

if (tipo='F')or(tipo='R') then
begin
ActualizaInventario;
MovimientosInventario;
end;
TablaFacturaD.Insert;
TablaFacturaD.FieldByName('CLDOC_FD').AsString:= EditCLDOC_F.Text;
TablaFacturaD.FieldByName('CONTROL').AsInteger:=AsignaControlVariable;
TablaFacturaD.FieldByName('CLPRO_FD').AsString:= TablaDeta.FieldByName('Clave').AsString;
TablaFacturaD.FieldByName('CANTI_FD').AsFloat:= TablaDeta.FieldByName('Cantidad').AsFloat;
TablaFacturaD.FieldByName('DEPRO_FD').AsString:= TablaDeta.FieldByName('Producto').AsString;
TablaFacturaD.FieldByName('PUNPR_FD').AsFloat:= TablaDeta.FieldByName('Precio').AsFloat;
try
TablaFacturaD.FieldByName('PREDE_FD').AsFloat:= TablaDeta.FieldByName('Precio').AsFloat*
( (1-(TablaDeta.FieldByName('Descuento').AsFloat/100))*(1-(TablaDeta.FieldByName('Descuento2').AsFloat/100))*(1-(TablaDeta.FieldByName('Descuento3').AsFloat/100))*(1-(TablaFacturaE.FieldByName('DECOT_F').AsFloat/100))      );
except
end;

TablaFacturaD.FieldByName('COPRO_FD').AsFloat:= TablaDeta.FieldByName('Costo').AsFloat;
TablaFacturaD.FieldByName('PIVA2_FD').AsFloat:= TablaDeta.FieldByName('Factor').AsFloat;

TablaFacturaD.FieldByName('PDES1_FD').AsFloat:= TablaDeta.FieldByName('Descuento').AsFloat;
TablaFacturaD.FieldByName('UNIDA_FD').AsString:= TablaDeta.FieldByName('Unidad').AsString;
TablaFacturaD.FieldByName('FEDOC_FD').AsString:= EditFEDOC_F.Text;
TablaFacturaD.FieldByName('PIVA1_FD').AsFloat:= TablaDeta.FieldByName('Impuesto').AsFloat;
TablaFacturaD.FieldByName('IMPOR_FD').AsFloat:= TablaDeta.FieldByName('Importe').AsFloat;
TablaFacturaD.FieldByName('PIVA2_FD').AsFloat:=TablaDeta.FieldByName('FACTOR').AsFloat;

TablaFacturaD.Post;
//TablaFacturaD.ApplyUpdates;

end;
TablaDeta.Next;
end;
MovimientoBorrado:=0;
{borra;}
end;


end;


procedure guardatodo(tipo:Char);
begin
With FormaFactura do
begin
cliente:=EditCLCLI_F.Text;
//MuestraMensaje('actualiza devolu 1'+IntToStr(TablaFacturaE.RecNo));

if BotonNuevo.tag=1 then
begin
{MuestraMensaje(IntTostr(numeromovimiento));}
if revisafactura(EditCLCLI_F.Text) then
begin
case tipo of
'Z':begin
generacuentasxcobrar('N');
actualizafactura(tipo);
actualizacliente;
end;

'F':begin
if IntegrarMI='S' then
begin
TablaMovimientosInventario.Last;
numeromovimiento:=TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger+1;
tipomovimiento:=1;

{TablaMovimientosInventario.Insert;
if MovimientoBorrado<>0 then
TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger:=MovimientoBorrado
else
TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger:=numeromovimiento;
TablamovimientosInventario.FieldByName('CONTROL').AsInteger:=AsignaControlVariable;
TablaMovimientosInventario.Post;}

end;
//TablaMovimientosInventario.ApplyUpdates;
actualizafactura(tipo);
generacuentasxcobrar('N');
actualizacliente;
end;

'R':begin
if IntegrarMI='S' then
begin
TablaMovimientosInventario.Last;
numeromovimiento:=TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger+1;
tipomovimiento:=3;

{TablaMovimientosInventario.Insert;
if MovimientoBorrado<>0 then
TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger:=MovimientoBorrado
else
TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger:=numeromovimiento;
TablamovimientosInventario.FieldByName('CONTROL').AsInteger:=AsignaControlVariable;
TablaMovimientosInventario.Post;}

end;
//TablaMovimientosInventario.ApplyUpdates;
actualizafactura(tipo);
{actualizacliente;}
end;

'C':begin
actualizafactura('C');

end;

'P':begin
actualizafactura(tipo);
end;

'X':begin
actualizafactura(tipo);
end;

'N':begin
actualizafactura(tipo);

end;

'D':begin
if IntegrarMI='S' then
begin
TablaMovimientosInventario.Last;
numeromovimiento:=TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger+1;
tipomovimiento:=52;
devolucionproductos;

{TablaMovimientosInventario.Insert;
if MovimientoBorrado<>0 then
TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger:=MovimientoBorrado
else
TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger:=numeromovimiento;

TablamovimientosInventario.FieldByName('CONTROL').AsInteger:=AsignaControlVariable;
TablaMovimientosInventario.Post;}

end;
//TablaMovimientosInventario.ApplyUpdates;
actualizafactura(tipo);


end;



end;{case}


end;
BotonNuevo.Tag:=0;
end;
{*********cambios*******}
if BotonCambios.tag=1 then
begin

case tipo of
'F':begin
borradatosanteriores('F');
if IntegrarMI='S' then
begin
TablaMovimientosInventario.Last;
numeromovimiento:=TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger+1;
end;
generacuentasxcobrar('C');
actualizafactura(tipo);
actualizacliente;
end;

'R':begin
if IntegrarMI='S' then
begin
TablaMovimientosInventario.Last;
numeromovimiento:=TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger+1;
end;
actualizafactura(tipo);
end;

'C':begin
    actualizafactura(tipo);
    end;

'P':begin
    actualizafactura(tipo);
    end;

'D':begin
if IntegrarMI='S' then
begin
TablaMovimientosInventario.Last;
numeromovimiento:=TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger+1;
tipomovimiento:=52;
devolucionproductos;

{TablaMovimientosInventario.Insert;
if MovimientoBorrado<>0 then
TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger:=MovimientoBorrado
else
TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger:=numeromovimiento;

TablamovimientosInventario.FieldByName('CONTROL').AsInteger:=AsignaControlVariable;
TablaMovimientosInventario.Post;}

end;
//TablaMovimientosInventario.ApplyUpdates;
actualizafactura(tipo);


end;


end;
{****case termina cambios*****}



BotonCambios.Tag:=0;
end;



{limpiar;}
desactiva;

end;
end;

procedure ponedatos;
begin

With FormaFactura do
begin
{if TablaFacturaE.FieldByName('NOMBR_F').AsString<>'' then
 begin}
 Nombre.Caption:=TablaFacturaE.FieldByName('NOMBR_F').AsString;
 TipoPago.Text:=TablaFacturaE.FieldByName('PAGOX_F').AsString;


 Direccion.Caption:=TablaFacturaE.FieldByName('DIREC_F').AsString;
 Direc2.Caption:=TablaFacturaE.FieldByName('DIRE2_F').AsString;
 Poblacion.Caption:=TablaFacturaE.FieldByName('POBLA_F').AsString;
 RFC.Caption:=TablaFacturaE.FieldByName('RFCXX_F').AsString;
 CodigoPostal.Caption:=TablaFacturaE.FieldByName('CPXXX_F').AsString;
 FormaFactura.EditFEDOC_F.Text:=TablaFacturaE.FieldByName('FEDOC_F').AsString;

 Hora.Caption:=TablaFacturaE.FieldByName('HORAX_F').AsString;

 if TablaFacturaE.FieldByName('STATU_F').AsString='C' then
 Estado.Caption:='Cancelada'
 else
 begin
 if TablaFacturaE.FieldByName('STATU_F').AsString='D' then
 Estado.Caption:='Dev. Total';
 if TablaFacturaE.FieldByName('STATU_F').AsString='P' then
 Estado.Caption:='Dev. Parcial';
 if TablaFacturaE.FieldByName('STATU_F').AsString='' then
 Estado.Caption:='Activa';
 end;

  if TablaFacturaE.FieldByName('CAMBI_F').AsFloat>0 then
 SuCambio.Caption:=convierte('###,##0.00',redondear(TablaFacturaE.FieldByName('CAMBI_F').AsFloat-TablaFacturaE.FieldByName('IMTOD_F').AsFloat),'$')
 else
 SuCambio.Caption:='0';


{ if TablaFacturaE.FieldByName('STATU_F').AsString='C' then
 Estado.Caption:='Cancelada'
 else
 Estado.Caption:='Activa';}


LeeDetalle;
sumatotal;



end;
end;

{xxx*********}
procedure posicionafactura(clave:string);
begin
with FormaFactura do
begin
if FormaFactura.Tag=0 then
begin
{if FileExists(leetapiz(3)) then
Fondo.Picture.LoadFromFile(leetapiz(3));}
{Fondo.Visible:=True;}
Refresh;

rutas;

desactiva;
Pedido1.Enabled:=False;
Remisin1.Enabled:=False;
//Factura1.Enabled:=False;
BotonCambios.Enabled:=True;
BotonNuevo.Enabled:=true;
BotonGuardar.Enabled:=false;
Guardar1.enabled:=False;
{BotonImprimir.Enabled:=false;}
indices:=1;
decimales:=2;
{ponedatos;}
end;

FormaFactura.Tag:=1;
TablafacturaE.FindKey([clave]);
end;
ponedatos;
end;

{************}


procedure TFormaFactura.FormCreate(Sender: TObject);
var
i:integer;
begin
  MovimientoBorrado:=0;
  tipomovimiento:=1;
  FormatosPais;
 // formatonum:=14;
  formatonum:=15;
  nombreformato:=leeruta+'\consulta\'+ruta(formatonum);
  ultimovendedor:='';
  orig:='';
  if ruta(33)='S' then
  desglosado:=True
  else
  desglosado:=False;

  Digitos:=2;
//  MuestraMensaje(ruta(45));
 Digitos:=StrToInt(ruta(42));
 DigitosTotal:=StrToInt(ruta(45));
//  MuestraMensaje(IntToStr(DigitosTotal));
  if ruta(43)='S' then
    PreciosPolitica:=True
  else
  PreciosPolitica:=False;

if digitos>0 then
begin
  Digi:='';
for i:=1 to Digitos do
Digi:=Digi+'0';
Digi:='##,##0.'+digi;
//MuestraMensaje(Digi);
end;

Funciones.Caption:='F2 -> Buscar Producto'+char(13)+
                   'F3 -> Repite el último Movimiento'+char(13)+
                   'F4 -> Salta a Cantidad'+char(13)+
                   'F5 -> Ingresar Efectivo'+char(13);
  ListaClaves:=TStringList.Create;
  ListaCantidad:=TStringList.Create;


  end;

procedure TFormaFactura.EditCLCLI_FExit(Sender: TObject);
var
trunca:string[60];
begin

quitacolor(EditCLCLI_F.ComponentIndex);
TablaCliente.First;
if Tablacliente.FindKey([EditCLCLI_F.Text]) then
begin
Nombre.Caption:=TablaCliente.FieldByName('NOMBR_C').AsString;
Direccion.Caption:=TablaCliente.FieldByName('DIREC_C').AsString;
Direc2.Caption:=TablaCliente.FieldByName('DIRE2_C').AsString;
Poblacion.Caption:=TablaCliente.FieldByName('POBLA_C').AsString;
RFC.Caption:=TablaCliente.FieldByName('RFCXX_C').AsString;
CodigoPostal.Caption:=TablaCliente.FieldByname('CPXXX_C').AsString;
//EditCONDI_F.Text:=TablaCliente.FieldByname('DCRED_C').AsString;

PrecioNumero:=Tablacliente.FieldByName('PREPR_C').AsInteger;
if PrecioNumero<1 then
Precionumero:=0;

end;
{end;}

end;

procedure TFormaFactura.BotonNuevoClick(Sender: TObject);
var
Ultimo:Integer;
begin

if caso2(StrToInt(usuario.Caption),20) then
begin
MovimientoBorrado:=0;
TipoPago.Text:='Efectivo';
PrecioNumero:=0;
Hora.Caption:=TimeToStr(Time);
{*********}
{TablaFacturaE.LockTable(ltReadLock);
TablaFacturaE.LockTable(ltWriteLock);}
TablaFacturaE.Last;
{TablaUltimo.LockTable(ltReadLock);}

Ultimo:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger;
{TablaFacturaE.UnLockTable(ltWriteLock);}
{TablaUltimo.UnLockTable(ltReadLock);}
TablaFacturae.Insert;
EditBCLIM_F.Text:=CajaLocal;
SuCambio.Caption:='';
{***********************}

if TablaFacturaE.State=dsInsert then
begin

TablaFacturae.FieldByName('CLDOC_F').AsInteger:=Ultimo+1;
TablaFacturae.FieldByName('CLVEN_F').AsString:=ultimovendedor;
TablaFacturae.Post;

//TablaFacturaE.ApplyUpdates;
{TablaFacturaE.UnLockTable(ltReadLock);}
{TablaUltimo.UnLockTable(ltReadLock);}
saldoanterior:=0;
borradatoscliente;
borra;
{BotonImprimir.Enabled:=false;}
BotonNuevo.Tag:=1;
BotonCambios.Tag:=0;
Caja.Enabled:=True;
local:=True;
TablaFacturae.Edit;
EditCLCLI_F.Visible:=True;
activa;
EditFEDOC_F.Text:=DateToStr(Date);
configuracion;
indice:=0;
sig:=1;
{****totales****}
SumarTotal.Caption:=convierte('###,###,##0.00','0','$');
ImpuestoValor.Caption:=convierte('###,###,##0.00','0','$');
TotalFact.Caption:=convierte('###,###,##0.00','0','$');
{**************}
activabotones(False,False,True,False,False,False,True);

{indices:=1;}
EditCLDOC_F.SetFocus;
EditCLCLI_F.Text:='1';

end
else
MuestraMensaje('No Pueden Guardarse los Datos ha Ocurrido un Error');
end;
Navegador.Enabled:=False;
end;


procedure TFormaFactura.BotonGuardarClick(Sender: TObject);
var
ulti:string[20];
begin

Hora.Caption:=TimeToStr(Time);
//MuestraMensaje('actualiza 1 '+IntToStr(TablaFacturaE.RecNo));
if ((BotonNuevo.Tag=1)or(BotonCambios.Tag=1)) and (revisafactura(EditCLCLI_F.Text)) then
begin
// MuestraMensaje(IntToStr(UltimoDocumento));
if BotonCambios.Tag=1 then
BorraDatosMovimientos('F');

if EditCLDOC_F.Text<>'' then
begin
if (Base.Text='Factura')and (Base.Tag=1) then
guardatodo('Z');
if Base.Text='Factura' then
guardatodo('F');
if Base.Text='Remisión' then
guardatodo('R');
if Base.Text='Pedido' then
guardatodo('P');
if Base.Text='Cotización' then
guardatodo('C');
if Base.Text='Devolución' then
begin
//MuestraMensaje('actualiza 1 '+IntToStr(TablaFacturaE.RecNo));
guardatodo('D');
end;
if Base.Text='Nota de Crédito' then
guardatodo('N');
if Base.Text='Caja Chica' then
guardatodo('C');


{configuracion;}

if ruta(1)='NO' then
begin
ulti:=EditCLDOC_F.Text;
//MuestraMensaje('guarda permanete');
GuardaPendientes(TablaMovimientosInventario);
GuardaPendientes(TablaFacturaE);
GuardaPendientes(TablaFacturaD);
GuardaPendientes(TablaInventario);

GuardaPendientes(TablaCuentasxCobrar);
GuardaPendientes(TablaCliente);

if TablaFacturaE.FindKey([ulti]) then
ponedatos;
end;
ultimovendedor:=EditCLVEN_F.Text;
Navegador.Enabled:=True;
Base.Tag:=0;
activabotones(True,True,False,True,True,True,False);
BotonPago.Enabled:=True;
MovimientoBorrado:=0;

if RangoDocumentos then
begin
//FormaRango.Edit1.Text
ActualizaOrigenRango(DatoRango,Orig2,Base.Text,EditCLDOC_F.Text);

end;

RangoDocumentos:=False;

end
else
begin
MuestraMensaje('Falta el Número de Documento');
EditCLDOC_F.SetFocus;
end;
end
else
MuestraMensaje('No Pueden Guardarse los Datos ha Ocurrido un Error');


end;


procedure TFormaFactura.NavegadorClick(Sender: TObject; Button: TNavigateBtn);
begin
ponedatos;
end;

procedure TFormaFactura.DetalleColEnter(Sender: TObject);
var valor:Real;
    code:integer;
    cadena:string;
begin

if (Detalle.Enabled=True)and((BotonCambios.Tag=1)or(BotonNuevo.Tag=1))  then
begin
case Detalle.SelectedIndex of

0:begin

//   Facturable:=False;
   sumatotal;
   Str(suma:12:3,cadena);
   SumarTotal.Caption:=convierte('###,###,##0.00',cadena,'$');

 end;


1:begin
if TablaDeta.FieldByName('Cantidad').AsString='' then
  Detalle.SelectedIndex:=Detalle.SelectedIndex-1
  else
  begin
  Val(TablaDeta.FieldByName('Cantidad').AsString,valor,code);
  if code<>0 then
  TablaDeta.FieldByName('Cantidad').AsString:='0';
  TablaDeta.Edit;
  end;
  end;

2:begin
if TablaDeta.FieldByName('Cantidad').AsString='' then
  Detalle.SelectedIndex:=Detalle.SelectedIndex-1
  else
  if (TablaInventario.FindKey([TablaDeta.FieldByName('Clave').AsString]))and(TablaDeta.FieldByName('CLAVE').AsString<>'COMENTARIO')and(Base.Text<>'Caja Chica') then
  begin
  SumaTotalCantidad;
  checaexistencias;
  TablaDeta.Edit;

  if (cantidad>=0) or ((UpperCase(TablaInventario.FieldByName('LIPRO_I').AsString)='SERVI')or (ruta(21)<>'N')) or
  ((Base.Text='Pedido')or(Base.Text='Cotización')or(Base.Text='Nota de Crédito')or(Base.Text='Devolución'))then
  begin
  TablaDeta.Edit;
  TablaDeta.FieldByName('Producto').AsString:=TablaInventario.FieldByName('DSCPR_I').AsString;
  TablaDeta.FieldByName('Factor').AsString:=TablaInventario.FieldByName('UEMPA_I').AsString;

  if (PrecioNumero>0)or(not PreciosPolitica) then
  LeePrecioPreferencial(PrecioNumero)
  else
  TablaDeta.FieldByName('PRECIO').AsFloat:= LeePrecioPolitica(TablaInventario.FieldByName('PPUBL_I').AsFloat,TablaInventario.FieldByName('PLIS2_I').AsFloat,TablaInventario.FieldByName('PLIS3_I').AsFloat,TablaInventario.FieldByName('PLIS4_I').AsFloat,TablaInventario.FieldByName('PMINI_I').AsFloat,TablaInventario.FieldByName('PLIS6_I').AsFloat,TablaInventario.FieldByName('PLIS7_I').AsFloat,

  TablaInventario.FieldByName('POLI1_I').AsFloat,TablaInventario.FieldByName('POLI2_I').AsFloat,TablaInventario.FieldByName('POLI3_I').AsFloat,TablaInventario.FieldByName('POLI4_I').AsFloat,TablaInventario.FieldByName('POLI5_I').AsFloat,TablaInventario.FieldByName('POLI6_I').AsFloat,TablaInventario.FieldByName('POLI7_I').AsFloat,TablaDeta.FieldByName('Cantidad').AsFloat);

  TablaDeta.FieldByName('Unidad').AsString:=TablaInventario.FieldByName('UMEDI_I').AsString;
//   MuestraMensaje(TablaInventario.FieldByName('CPROM_I').AsString);
  if (TablaInventario.FieldByName('TICOS_I').AsString='PROM')or (TablaInventario.FieldByName('TICOS_I').AsString='') then
  TablaDeta.FieldByName('Costo').AsString:=TablaInventario.FieldByName('CPROM_I').AsString
  else
  TablaDeta.FieldByName('Costo').AsString:=TablaInventario.FieldByName('ULCOS_I').AsString;

  TablaDeta.FieldByName('importe').AsFloat:=  TablaDeta.FieldByName('cantidad').AsFloat*
  TablaDeta.FieldByName('Precio').AsFloat-(TablaDeta.FieldByName('cantidad').AsFloat*TablaDeta.FieldByName('Precio').AsFloat*
  TablaDeta.FieldByName('DESCUENTO').AsFloat/100)+0.000;
  TablaDeta.FieldByName('Impuesto').AsString:=TablaInventario.FieldByName('PIVA1_I').AsString;

  TablaDeta.Post;
  sumatotal;
//  TablaDeta.ApplyUpdates;
TablaDeta.Last;

if (TablaDeta.FieldByName('Clave').AsString<>'')and
(TablaDeta.FieldByName('Producto').AsString<>'') then
begin

  TablaDeta.Append;
  TablaDeta.FieldByName('Cantidad').AsString:='1';
end;
    Detalle.SelectedIndex:=1;
{   TablaDeta.FieldByName('Costo').AsFloat:=}


  Str(TablaDeta.FieldByName('importe').AsFloat:12:4,cadena);
  FormatFloat( CADENA,3);
  TablaDeta.FieldByName('importe').AsString:=cadena;

{******quitamos lo siguiente para EID se agrega parar los demás solo se quita el comentario*****}
{  Detalle.SelectedIndex:=3;}
  end;



  end
  else
  begin

  if (TablaDeta.FieldByName('CLAVE').AsString<>'COMENTARIO')and(Base.Text<>'Caja Chica') then
  begin
  Detalle.SelectedIndex:=Detalle.SelectedIndex-1;
  MuestraMensaje('El Producto No Se encuenta');
  Detalle.SetFocus;
  end;

  end;

  end;

4:begin

if Usuario.Caption<>'0' then
begin
//
//TablaDetaPRECIO.ReadOnly:=False
Detalle.SelectedIndex:=0;
MuestraMensaje('No Tiene Acceso a Precios');
end;

//if CambiaPrecios='s' then
//begin
//MuestraMensaje(CambiaPrecios);
//TablaDetaPRECIO.ReadOnly:=False

//end
//else
//TablaDetaPRECIO.ReadOnly:=True;


  Detalle.Columns[4].PickList.Clear;
  Detalle.Columns[4].PickList.Add(  TablaInventario.FieldByName('PLIS2_I').AsString);
  Detalle.Columns[4].PickList.Add(  TablaInventario.FieldByName('PLIS3_I').AsString);
  Detalle.Columns[4].PickList.Add(  TablaInventario.FieldByName('PLIS4_I').AsString);
  Detalle.Columns[4].PickList.Add(  TablaInventario.FieldByName('PMINI_I').AsString);

  end;


 5:begin
   TablaDeta.Edit;
   TablaDeta.FieldByName('importe').AsFloat:=  TablaDeta.FieldByName('cantidad').AsFloat*
   TablaDeta.FieldByName('Precio').AsFloat-(TablaDeta.FieldByName('cantidad').AsFloat*TablaDeta.FieldByName('Precio').AsFloat*
   TablaDeta.FieldByName('DESCUENTO').AsFloat/100);
//   TablaDeta.FieldByName('Costo').AsFloat:=  TablaDeta.FieldByName('Costo').AsFloat;
   //*TablaDeta.FieldByName('cantidad').AsFloat;

   Str(TablaDeta.FieldByName('importe').AsFloat:12:3,cadena);
   TablaDeta.FieldByName('importe').AsString:=cadena;
  end;
end;
end;//if pricipal
end;

procedure TFormaFactura.EditCLCLI_FKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin


if (key=13) or (key=40) then
begin
indices:=indices+1;
cursor1;
end;
if key=38 then
begin
indices:=indices-1;
cursor1;
end;
if key=113 then
begin
EditCLCLI_F.Text:=BuscaclaveCliente(EditCLCLI_F.Text,Usuario.Caption);
EditCLCLI_F.SetFocus;
end;

end;

procedure TFormaFactura.EditCLVEN_FKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
TablaVendedores.FindNearest([EditCLVEN_F.Text]);
if key=113 then
begin
FormaFactura.Tag:=2;
EditCLVEN_F.Text:=LeeVendedor(EditCLVEN_F.Text);
EditCLVEN_F.SetFocus;
end;
if (key=13) or (key=40) then
begin
indices:=indices+1;
cursor1;
end;
if key=38 then
begin
indices:=indices-1;
cursor1;
end;
end;

procedure TFormaFactura.EditCLVEN_FExit(Sender: TObject);
begin
quitacolor(EditCLVEN_F.ComponentIndex);
if (TablaVendedores.FindKey([EditCLVEN_F.Text]))and(TablaFacturaE.State=dsEdit) then
TablaFacturaE.FieldByName('CTOVE_F').AsFloat:=TablaVendedores.FieldByName('COMIS_V').AsFloat;
end;

procedure TFormaFactura.EditFEDOC_FEnter(Sender: TObject);
begin
ponecolor(EditFEDOC_F.ComponentIndex,EditFEDOC_F.Color);
indices:=6;
EditFEDOC_F.Text:=DateToStr(Date);
Uno.Caption:=comenta(13,'factu.des');
Dos.Caption:=comenta(14,'factu.des');
end;

procedure TFormaFactura.DetalleKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
var
clave,cantidad:string;
begin
if (Detalle.Enabled=True)and((BotonCambios.Tag=1)or(BotonNuevo.Tag=1))  then
begin

Case key of

113:
begin
Detalle.Tag:=3;
TablaDeta.Edit;
TablaDeta.Post;
TablaDeta.Edit;

FormaFactura.TablaDeta.FieldByName('clave').AsString:=BuscaClave(FormaFactura.TablaDeta.FieldByName('clave').AsString,1);

//FormaConProduct.ShowModal;
Detalle.SetFocus;
end;

{118:  //f7
begin
Detalle.SelectedIndex:=0;
BotonImprimir.Enabled:=true;
end;}

13:
begin
Detalle.SelectedIndex:=Detalle.SelectedIndex+1;
if  (Detalle.SelectedIndex =5) then
Detalle.SelectedIndex:=0;

end;

{115:      //f4
begin
if (TablaDeta.State=dsInsert)or(TablaDeta.State=dsEdit) then
begin
TablaDeta.FieldByName('CLAVE').AsString:='COMENTARIO';
TablaDeta.FieldByName('CANTIDAD').AsString:='1';
end;
end;}

//if key=117 then
//begin
//if (TablaDeta.State=dsInsert)or(TablaDeta.State=dsEdit) then
//begin
//TablaDeta.FieldByName('CLAVE').AsString:='DEVOLUCION';
//TablaDeta.FieldByName('CANTIDAD').AsString:='1';
//end;
//end;


116://f5 para dar cambio
begin
CAMBIO_F.SetFocus;

end;

114://f3 para repetir el ulltimo dato
begin
if (TablaDeta.FieldByName('CLAVE').AsString='')and(TablaDeta.FieldByName('CANTIDAD').AsFloat>0) then
TablaDeta.Delete;
clave:=TablaDeta.FieldByName('CLAVE').AsString;
cantidad:=TablaDeta.FieldByName('CANTIDAD').AsString;
TablaDeta.Append;
TablaDeta.FieldByName('CLAVE').AsString:=clave;
TablaDeta.FieldByName('CANTIDAD').AsString:=cantidad;
Detalle.SelectedIndex:=1;
Detalle.SelectedIndex:=2;
end;

115://f4 ir a cantidad
begin
Detalle.SelectedIndex:=0;
end;


118://f7 ir a cantidad
begin
try
TablaDeta.Delete;
sumatotal;
except
end;
end;


123:
begin
TablaDeta.Insert;
if TablaDeta.FieldByName('Cantidad').AsString='' then
TablaDeta.FieldByName('Cantidad').AsInteger:=1;
Detalle.SelectedIndex:=0;
end;

end;//case
end;//if

end;

procedure TFormaFactura.FormActivate(Sender: TObject);
 begin
if FormaFactura.Tag=0 then
begin
{if FileExists(leetapiz(3)) then
Fondo.Picture.LoadFromFile(leetapiz(3));}
{Fondo.Visible:=True;}
rutas;
CargaGlyps;
desactiva;
Pedido1.Enabled:=False;
Remisin1.Enabled:=False;
//Factura1.Enabled:=False;
BotonCambios.Enabled:=True;
BotonNuevo.Enabled:=true;
BotonGuardar.Enabled:=false;
Guardar1.enabled:=False;
{BotonImprimir.Enabled:=false;}
indices:=1;
decimales:=2;
TablafacturaE.Last;
ponedatos;
try
UltimoDocumento:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger;
except
end;

CambiaPrecios:=casoLetra(StrToInt(usuario.Caption),44);

if not Registrado then
begin
//Reportes1.Enabled:=False;
//BotonImprimir.Enabled:=False;
//ImprimirRangodeDocumentos1.Enabled:=False;
//Imprimir1.Enabled:=False;
end;

end;
FormaFactura.Tag:=1;
end;

procedure TFormaFactura.EditNALMA_FKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
if key=13 then
Detalle.SetFocus;
if key=38 then
{EditDECOT_F.SetFocus;}
end;

procedure TFormaFactura.EditFEDOC_FKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin

//if Key=114 then
//EditFEDOC_F.Text:=DateTimeToStr(Date);
if (Key=13) or (Key=40) then
begin
quitacolor(EditFEDOC_F.ComponentIndex);
if not fechavalida(EditFedoc_F.Text) then
EditFedoc_F.Text:=DateTimeToStr(Date);

indices:=indices+1;
cursor1;
end;

if Key=38 then
begin
indices:=indices-1;
cursor1;
end;

end;

procedure TFormaFactura.EditIMIM1_FEnter(Sender: TObject);
begin
ponecolor(EditIMIM1_F.ComponentIndex,EditIMIM1_F.Color);
indices:=7;
EditIMIM1_F.Text:=FloatToStr(iva);
Uno.Caption:=comenta(19,'factu.des');
Dos.Caption:=comenta(20,'factu.des');
end;

procedure TFormaFactura.EditDESFI_FEnter(Sender: TObject);
begin
ponecolor(EditDESFI_F.ComponentIndex,EditDESFI_F.Color);
indices:=8;
//EditDESFI_F.Text:=FloatToStr(desfin);
Uno.Caption:=comenta(21,'factu.des');
Dos.Caption:=comenta(22,'factu.des');
end;




procedure TFormaFactura.BotonSalirClick(Sender: TObject);
begin
Close;
end;

procedure TFormaFactura.Consultas1Click(Sender: TObject);
begin
FormaConsulta.TablaConsulta.DataBaseName:=ruta(8);
FormaConsulta.TablaConsulta.IndexName:='INUMENC';
FormaConsulta.TablaConsulta.TableName:='facturae.dbf';
FormaConsulta.TablaConsulta.Open;
FormaConsulta.TablaConsulta.First;
//FormaConsulta.De.Text:=FormaConsulta.TablaConsulta.Fields[0].AsString;
FormaConsulta.TablaConsulta.Last;
//FormaConsulta.Hasta.Text:=FormaConsulta.TablaConsulta.Fields[0].AsString;
FormaConsulta.TablaConsulta.First;
//FormaConsulta.RutaCampos.Text:=leeruta+'\consulta\facturae.cmp';
//FormaConsulta.TipoVista.Text:=leeruta+'\consulta\facturae.vis';
//FormaConsulta.Destino.Text:=leeruta+'\tempo\repfac.rep';
FormaConsulta.NumCampo.Caption:='0';
asignatipo;
leearchivocampos('facturae.dbf','');
FormaConsulta.ShowModal;

end;

procedure TFormaFactura.EditCLDOC_FKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
if (key=13) or (key=40) then
begin
indices:=indices+1;
cursor1;

end;
if key=38 then
begin
indices:=indices-1;
cursor1;
end;
end;

procedure TFormaFactura.BotonBuscarClick(Sender: TObject);
var siguiente:LongInt;
begin
FormaBusqueda:=TFormaBusqueda.Create(Application);
FormaBusqueda.ShowModal;
TablaFacturae.FindNearest([FormaBusqueda.CajaBuscar.Text]);
ponedatos;
FormaBusqueda.Free;
end;

procedure TFormaFactura.BotonCambiosClick(Sender: TObject);

begin

if caso(StrToInt(usuario.Caption),22) then
begin
local:=False;
TablaFacturae.Edit;
if TablaFacturaE.State=dsEdit then
begin
MovimientoBorrado:=0;
bufercambios('F');
saldoanterior:=TablaFacturaE.FieldByName('IMTOD_F').AsFloat;

TablaDeta.Edit;
EditCLCLI_F.Visible:=True;
activa;
indice:=0;
sig:=1;
indices:=1;
borradatosanteriores('F');

activabotones(False,False,True,False,False,False,True);
BotonCambios.Tag:=1;
BotonNuevo.Tag:=0;

EditCLDOC_F.SetFocus;
end
else
MuestraMensaje('No se Pueden Realizar Cambios');
end;


Navegador.Enabled:=False;

end;




procedure TFormaFactura.FormClose(Sender: TObject;
  var Action: TCloseAction);
begin
if (BotonCambios.Tag=1)or (BotonNuevo.Tag=1) then
begin
FormaCerrar:=TFormaCerrar.Create(Application);
{FormaFactura.Tag:=1;}
FormaCerrar.ShowModal;
{MuestraMensaje(IntToStr(FormaCerrar.Tag));}
if FormaCerrar.Tag=1 then
begin
{MuestraMensaje('voy a guardar');}

if Base.Text='Factura' then
guardatodo('F');
if Base.Text='Remisión' then
guardatodo('R');
if Base.Text='Pedido' then
guardatodo('P');
if Base.Text='Cotización' then
guardatodo('C');


activabotones(True,True,False,True,True,True,False);
desactiva;
BotonCambios.Tag:=0;
BotonNuevo.Tag:=0;
end;

if FormaCerrar.Tag=2 then
begin
if BotonCambios.Tag=1 then
regresabufercambios;

if BotonCambios.Tag<>1 then
TablaFacturae.Delete;
TablaFacturad.Cancel;



{FormaFactura.Close;}


activabotones(True,True,False,True,True,True,False);
desactiva;
BotonCambios.Tag:=0;
BotonNuevo.Tag:=0;

end;

if FormaCerrar.Tag=3 then
Action:=caNone;
FormaCerrar.Tag:=0;
{FormaFactura.Tag:=0;}
FormaCerrar.Free;
end;
Navegador.Enabled:=True;
BotonSalir.Tag:=1000;
end;

procedure TFormaFactura.BotonImprimirClick(Sender: TObject);
begin
if ImpresoraLista then
begin
if FileExists(nombreformato) then
begin
UsuarioActual(Usuario.Caption);
LeeEtiquetasMoneda(valordivisaetiqueta('M.N.',1),valordivisaetiqueta('M.N.',2),valordivisaetiqueta('M.N.',3),valordivisaetiqueta('M.N.',4));
forma(FormaFactura.TablaFacturaE,FormaFactura.TablaDeta,nombreformato,'i');
end
else
MuestraMensaje('El Formato '+nombreformato+' No Existe');
end
else
MuestraMensaje('La Impresora No Se Encuentra Lista...');
end;

procedure TFormaFactura.DetalleEditButtonClick(Sender: TObject);
begin
{MuestraMensaje('Mostrar precios');}
end;

procedure TFormaFactura.FolderChange(Sender: TObject; NewTab: Integer;
  var AllowChange: Boolean);
var
ventas:integer;
begin
{TablaFacturaE.Open;
TablaFacturaE.SetRange([TablaCliente.FieldByName('CLCLI_C').AsString],[TablaCliente.FieldByName('CLCLI_C').AsString]);}
end;

procedure TFormaFactura.BaseChange(Sender: TObject);
begin
RangoDocumentos:=False;

if (Base.Text='') then
Base.Text:='Remisión';
//or(Base.Text<>'Remisión')or(Base.Text<>'Devolución')or(Base.Text<>'Caja Chica') then
//Base.Text:='Remisión';

if Base.Text='Factura' then
begin
TablaFacturaE.Close;
TablaFacturaE.TableName:='Facturae.dbf';
TablaFacturaE.Open;
TablaFacturaD.Close;
TablaFacturaD.TableName:='FacturaD.dbf';
TablaFacturaD.Open;
formatonum:=14;

Pedido1.Enabled:=False;
Remisin1.Enabled:=False;
//Factura1.Enabled:=False;
Devolucin1.Enabled:=True;
NotadeCrdito1.Enabled:=True;
BotonPago.Enabled:=True;
BotonObservacion.Enabled:=True;
TablaFacturaE.Last;
UltimoDocumento:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger;
end;

if Base.Text='Remisión' then
begin
TablaFacturaE.Close;
TablaFacturaE.TableName:='Remision.dbf';
TablaFacturaE.Open;
TablaFacturaD.Close;
TablaFacturaD.TableName:='RemisioD.dbf';
TablaFacturaD.Open;
formatonum:=15;

Pedido1.Enabled:=False;
Remisin1.Enabled:=False;
Factura1.Enabled:=True;
Devolucin1.Enabled:=True;
NotadeCrdito1.Enabled:=False;
BotonPago.Enabled:=False;
BotonObservacion.Enabled:=False;

{if Usuario.Caption='0' then
EditCLDOC_F.ReadOnly:=True
else
EditCLDOC_F.ReadOnly:=False;}
TablaFacturaE.Last;
UltimoDocumento:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger;
end;

if Base.Text='Pedido' then
begin
TablaFacturaE.Close;
TablaFacturaE.TableName:='Pedido.dbf';
TablaFacturaE.Open;
TablaFacturaD.Close;
TablaFacturaD.TableName:='PedidoD.dbf';
TablaFacturaD.Open;
formatonum:=16;

Pedido1.Enabled:=False;
Remisin1.Enabled:=True;
Factura1.Enabled:=True;
Devolucin1.Enabled:=False;
NotadeCrdito1.Enabled:=False;
BotonPago.Enabled:=False;
BotonObservacion.Enabled:=False;
TablaFacturaE.Last;
UltimoDocumento:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger;
end;

if Base.Text='Cotización' then
begin
TablaFacturaE.Close;
TablaFacturaE.TableName:='Cotizaci.dbf';
TablaFacturaE.Open;
TablaFacturaD.Close;
TablaFacturaD.TableName:='CotizacD.dbf';
TablaFacturaD.Open;
formatonum:=17;

Pedido1.Enabled:=True;
Remisin1.Enabled:=True;
Factura1.Enabled:=True;
Devolucin1.Enabled:=False;
NotadeCrdito1.Enabled:=False;
BotonPago.Enabled:=False;
BotonObservacion.Enabled:=False;
TablaFacturaE.Last;
UltimoDocumento:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger;

end;

if Base.Text='Caja Chica' then
begin
TablaFacturaE.Close;
TablaFacturaE.TableName:='CajaChic.dbf';
TablaFacturaE.Open;
TablaFacturaD.Close;
TablaFacturaD.TableName:='CajaChiD.dbf';
TablaFacturaD.Open;
formatonum:=17;

Pedido1.Enabled:=False;
Remisin1.Enabled:=False;
Factura1.Enabled:=False;
Devolucin1.Enabled:=False;
NotadeCrdito1.Enabled:=False;
BotonPago.Enabled:=False;
BotonObservacion.Enabled:=False;
TablaFacturaE.Last;
UltimoDocumento:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger;

end;



if Base.Text='Nota de Crédito' then
begin
TablaFacturaE.Close;
TablaFacturaE.TableName:='Credito.dbf';
TablaFacturaE.Open;
TablaFacturaD.Close;
TablaFacturaD.TableName:='CreditoD.dbf';
TablaFacturaD.Open;
formatonum:=17;

Pedido1.Enabled:=False;
Remisin1.Enabled:=False;
Factura1.Enabled:=False;
Devolucin1.Enabled:=False;
NotadeCrdito1.Enabled:=False;
BotonPago.Enabled:=False;
BotonObservacion.Enabled:=False;
TablaFacturaE.Last;
UltimoDocumento:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger;

end;

if Base.Text='Devolución' then
begin
TablaFacturaE.Close;
TablaFacturaE.TableName:='Devoluc.dbf';
TablaFacturaE.Open;
TablaFacturaD.Close;
TablaFacturaD.TableName:='DevolucD.dbf';
TablaFacturaD.Open;
formatonum:=22;

Pedido1.Enabled:=False;
Remisin1.Enabled:=False;
//Factura1.Enabled:=False;
Devolucin1.Enabled:=False;
NotadeCrdito1.Enabled:=False;
BotonPago.Enabled:=False;
BotonObservacion.Enabled:=False;

TablaFacturaE.Last;
UltimoDocumento:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger;
end;
nombreformato:=leeruta+'\consulta\'+ruta(formatonum);
//MuestraMensaje(ruta(formatonum));
ponedatos;

end;

procedure TFormaFactura.EditCLDOC_FEnter(Sender: TObject);
begin
ponecolor(EditCLDOC_F.ComponentIndex,EditCLDOC_F.Color);
indices:=1;
Uno.Caption:=comenta(1,'factu.des');
Dos.Caption:=comenta(2,'factu.des');
end;

procedure TFormaFactura.EditCLCLI_FEnter(Sender: TObject);
begin

EditCLClI_F.Text:='1';
EditCLClI_F.SelectAll;
ponecolor(EditCLCLI_F.ComponentIndex,EditCLCLI_F.Color);
indices:=2;

Uno.Caption:=comenta(3,'factu.des');
Dos.Caption:=comenta(4,'factu.des');

end;

procedure TFormaFactura.EditBCLIM_FEnter(Sender: TObject);
begin
ponecolor(EditBCLIM_F.ComponentIndex,EditBCLIM_F.Color);
indices:=5;
Uno.Caption:=comenta(9,'factu.des');
Dos.Caption:=comenta(10,'factu.des');
EditBCLIM_F.Text:=CajaLocal;
end;

procedure TFormaFactura.EditCLVEN_FEnter(Sender: TObject);
begin
ponecolor(EditCLVEN_F.ComponentIndex,EditCLVEN_F.Color);
indices:=3;
Uno.Caption:=comenta(5,'factu.des');
Dos.Caption:=comenta(6,'factu.des');
end;

procedure TFormaFactura.EditCTOVE_FEnter(Sender: TObject);
begin
ponecolor(EditCTOVE_F.ComponentIndex,EditCTOVE_F.Color);
indices:=4;
Uno.Caption:=comenta(7,'factu.des');
Dos.Caption:=comenta(8,'factu.des');
end;

procedure TFormaFactura.EditCLPED_FEnter(Sender: TObject);
begin
{ponecolor(EditCLPED_F.ComponentIndex,EditCLPED_F.Color);}
indices:=3;
Uno.Caption:=comenta(11,'factu.des');
Dos.Caption:=comenta(12,'factu.des');
end;

procedure TFormaFactura.EditDECOT_FEnter(Sender: TObject);
begin
{ponecolor(EditDECOT_F.ComponentIndex,EditDECOT_F.Color);}
indices:=16;
Uno.Caption:=comenta(23,'factu.des');
Dos.Caption:=comenta(24,'factu.des');
end;

procedure TFormaFactura.Concentrar1Click(Sender: TObject);
var
desde,hastavalor:string;
begin
FormaFormatos:=TFormaFormatos.Create(Application);
FormaBarras:=TFormaBarras.Create(Application);

FormaFormatos.Rangos.Visible:=True;
FormaFormatos.Formatos.Visible:=False;
activacondiciones(true,true,False,true,False,true,true,true,true,'facturae.dbf');

TablaFacturaE.First;
desde:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
TablaFacturaE.Last;
hastavalor:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
//valoresiniciales('','',desde,hastavalor);
valoresiniciales('','','','');

FormaFormatos.ShowModal;
if FormaFormatos.Tag=1 then
begin
condiciones(FormaFormatos.C1.Caption,tipooperador(FormaFormatos.Operador1.Text),FormaFormatos.Valor1.Text,FormaFormatos.T1.Caption,FormaFormatos.C2.Caption,tipooperador(FormaFormatos.Operador2.Text),FormaFormatos.Valor2.Text,FormaFormatos.T2.Caption,FormaFormatos.C3.Caption,tipooperador(FormaFormatos.Operador3.Text),FormaFormatos.Valor3.Text,FormaFormatos.T3.Caption,'Y');
if FormaFormatos.IncluirDevoluciones.Checked then
begin
GeneraCorteDeCaja(FormaFormatos.Inicial.Date,FormaFormatos.Final.Date,TablaFacturaE.TableName,'devoluc.dbf','FactAuxi.dbf','INUMENC','S');
Concentrar(TablaAuxiliar,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLCLI_F','FEDOC_F','NOMBR_F','IMTOD_F','SUBTO_F','IMIM1_F','IMIM2_F','','','','STATU_F','!','C','D');
if TablaAuxiliar.State=dsBrowse then TablaAuxiliar.Close;
end
else
begin
Concentrar(TablaFacturaE,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLCLI_F','FEDOC_F','NOMBR_F','IMTOD_F','SUBTO_F','IMIM1_F','IMIM2_F','','','','STATU_F','!','C','D');

end;
poneetiquetas('Cliente','Fecha','Nombre','Total del Documento','SubTotal','IVA','% IVA','','','','');
Poneanchos(20,20,20,20,20,20,20,20,20,20,0);
parametrosgrafica('Gráfica de Facturas, Importe e Iva'+Base.Text+' Documentos, Subtotal, I.V.A., Total','Número de Documento','Total por Documento',3);
FormaBarras.Tag:=0;
FormaBarras.Panel2.Tag:=0;
FormaBarras.botonGrafica.Tag:=2;
FormaBarras.Concentrado.Clear;
//******pone el titulo
 with Sender as TMenuItem do
  begin
  desde:=Caption;
  end;
FormaBarras.Caption:=AgregaTitulo2('Reporte de '+desde,FormaFormatos.Titulo.Text);
//******termina pone el titulo

//FormaBarras.Caption:='Reporte de Facturas, Importe e Iva';
FormaBarras.ShowModal;
FormaBarras.Tag:=0;
end;
FormaFormatos.Tag:=0;
FormaFormatos.Free;
FormaBarras.Free;

end;


procedure TFormaFactura.Comisiones1Click(Sender: TObject);
var
desde,hastavalor:string;
begin
FormaFormatos:=TFormaFormatos.Create(Application);
FormaBarras:=TFormaBarras.Create(Application);

FormaFormatos.Rangos.Visible:=True;
FormaFormatos.Formatos.Visible:=False;
activacondiciones(true,true,False,true,False,true,true,true,true,'facturae.dbf');
TablaFacturaE.First;
desde:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
TablaFacturaE.Last;
hastavalor:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
valoresiniciales('','',desde,hastavalor);

FormaFormatos.ShowModal;
if FormaFormatos.Tag=1 then
begin
condiciones(FormaFormatos.C1.Caption,tipooperador(FormaFormatos.Operador1.Text),FormaFormatos.Valor1.Text,FormaFormatos.T1.Caption,FormaFormatos.C2.Caption,tipooperador(FormaFormatos.Operador2.Text),FormaFormatos.Valor2.Text,FormaFormatos.T2.Caption,FormaFormatos.C3.Caption,tipooperador(FormaFormatos.Operador3.Text),FormaFormatos.Valor3.Text,FormaFormatos.T3.Caption,'Y');
if FormaFormatos.IncluirDevoluciones.Checked then
begin
GeneraCorteDeCaja(FormaFormatos.Inicial.Date,FormaFormatos.Final.Date,TablaFacturaE.TableName,'devoluc.dbf','FactAuxi.dbf','INUMENC','N');
//Concentrar(TablaAuxiliar,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLCLI_F','NOMBR_F','IMTOD_F','SUBTO_F','IMIM1_F','IMIM2_F','','','','','STATU_F','!','C','D');
Concentrar(TablaAuxiliar,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLVEN_F','FEDOC_F','SUBTO_F','&%SUBTO_F&*&%CTOVE_F&*&0.01&','IMTOD_F','&%IMTOD_F&*&%CTOVE_F&*&0.01&','','','','','STATU_F','!','C','C');
if TablaAuxiliar.State=dsBrowse then TablaAuxiliar.Close;
end
else
Concentrar(TablaFacturaE,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLVEN_F','FEDOC_F','SUBTO_F','&%SUBTO_F&*&%CTOVE_F&*&0.01&','IMTOD_F','&%IMTOD_F&*&%CTOVE_F&*&0.01&','','','','','STATU_F','!','C','C');
poneetiquetas('Vendedor','Fecha','SubTotal del Documento','Comisión Sobre SubTotal','Total del Documento','Comisión sobre Total','','','','','');
Poneanchos(20,20,20,20,20,20,20,20,20,20,0);
parametrosgrafica('Gráfica de Comisiones de Vendedor'+Base.Text+' , Subtotal, I.V.A., Total','Número de Documento','Total por Documento',1);
FormaBarras.Tag:=0;
FormaBarras.Panel2.Tag:=0;
FormaBarras.botonGrafica.Tag:=2;
FormaBarras.Concentrado.Clear;
//******pone el titulo
 with Sender as TMenuItem do
  begin
  desde:=Caption;
  end;
FormaBarras.Caption:=AgregaTitulo2('Reporte de '+desde,FormaFormatos.Titulo.Text);
//******termina pone el titulo

//FormaBarras.Caption:='Reporte de Comisiones de Vendedor';
FormaBarras.ShowModal;
FormaBarras.Tag:=0;
end;
FormaFormatos.Tag:=0;

FormaFormatos.Free;
FormaBarras.Free;

end;

procedure TFormaFactura.EditFEDOC_FExit(Sender: TObject);
begin
quitacolor(EditFEDOC_F.ComponentIndex);
if not fechavalida(EditFedoc_F.Text) then
EditFedoc_F.Text:=DateTimeToStr(Date);

end;

procedure TFormaFactura.EditCLDOC_FMouseMove(Sender: TObject;
  Shift: TShiftState; X, Y: Integer);
begin
Uno.Caption:=comenta(1,'factu.des');
Dos.Caption:=comenta(2,'factu.des');
end;

procedure TFormaFactura.EditCLCLI_FMouseMove(Sender: TObject;
  Shift: TShiftState; X, Y: Integer);
begin
Uno.Caption:=comenta(3,'factu.des');
Dos.Caption:=comenta(4,'factu.des');
end;

procedure TFormaFactura.EditCLVEN_FMouseMove(Sender: TObject;
  Shift: TShiftState; X, Y: Integer);
begin
Uno.Caption:=comenta(5,'factu.des');
Dos.Caption:=comenta(6,'factu.des');
end;

procedure TFormaFactura.EditCTOVE_FMouseMove(Sender: TObject;
  Shift: TShiftState; X, Y: Integer);
begin
Uno.Caption:=comenta(7,'factu.des');
Dos.Caption:=comenta(8,'factu.des');
end;

procedure TFormaFactura.EditBCLIM_FMouseMove(Sender: TObject;
  Shift: TShiftState; X, Y: Integer);
begin
Uno.Caption:=comenta(9,'factu.des');
Dos.Caption:=comenta(10,'factu.des');
end;

procedure TFormaFactura.EditCLPED_FMouseMove(Sender: TObject;
  Shift: TShiftState; X, Y: Integer);
begin
Uno.Caption:=comenta(11,'factu.des');
Dos.Caption:=comenta(12,'factu.des');
end;

procedure TFormaFactura.EditFEDOC_FMouseMove(Sender: TObject;
  Shift: TShiftState; X, Y: Integer);
begin
Uno.Caption:=comenta(13,'factu.des');
Dos.Caption:=comenta(14,'factu.des');
end;

procedure TFormaFactura.EditIMIM1_FMouseMove(Sender: TObject;
  Shift: TShiftState; X, Y: Integer);
begin
Uno.Caption:=comenta(19,'factu.des');
Dos.Caption:=comenta(20,'factu.des');
end;

procedure TFormaFactura.EditDESFI_FMouseMove(Sender: TObject;
  Shift: TShiftState; X, Y: Integer);
begin
Uno.Caption:=comenta(21,'factu.des');
Dos.Caption:=comenta(22,'factu.des');
end;

procedure TFormaFactura.EditDECOT_FMouseMove(Sender: TObject;
  Shift: TShiftState; X, Y: Integer);
begin
Uno.Caption:=comenta(23,'factu.des');
Dos.Caption:=comenta(24,'factu.des');
end;

procedure TFormaFactura.EditNALMA_FMouseMove(Sender: TObject;
  Shift: TShiftState; X, Y: Integer);
begin
Uno.Caption:=comenta(25,'factu.des');
Dos.Caption:=comenta(26,'factu.des');
end;

procedure TFormaFactura.EditREMIS_FKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
if (key=13) or (key=40) then
begin
indices:=indices+1;
cursor1;
{indice:=0;
mueveteclas;}

end;

if key=38 then
begin
indices:=indices-1;
cursor1;
end;
end;

procedure TFormaFactura.EditCONDI_FKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
if (key=13) or (key=40) then
begin
indices:=indices+1;
cursor1;
{indice:=0;
mueveteclas;}

end;

if key=38 then
begin
indices:=indices-1;
cursor1;
end;
end;

procedure TFormaFactura.EditDESTI_FKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
if (key=13) or (key=40) then
begin
indices:=indices+1;
cursor1;
{indice:=0;
mueveteclas;}

end;

if key=38 then
begin
indices:=indices-1;
cursor1;
end;
end;

procedure TFormaFactura.ConsecutivodeFacturas1Click(Sender: TObject);
var
dia:string[12];
desde,hastavalor:string;
begin
FormaFormatos:=TFormaFormatos.Create(Application);
FormaBarras:=TFormaBarras.Create(Application);

FormaFormatos.Rangos.Visible:=True;
FormaFormatos.Formatos.Visible:=False;
activacondiciones(true,true,False,true,False,true,true,true,true,'facturae.dbf');
TablaFacturaE.First;
desde:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
TablaFacturaE.Last;
hastavalor:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
//valoresiniciales('','',desde,hastavalor);

FormaFormatos.ShowModal;
if FormaFormatos.Tag=1 then
begin
condiciones(FormaFormatos.C1.Caption,tipooperador(FormaFormatos.Operador1.Text),FormaFormatos.Valor1.Text,FormaFormatos.T1.Caption,FormaFormatos.C2.Caption,tipooperador(FormaFormatos.Operador2.Text),FormaFormatos.Valor2.Text,FormaFormatos.T2.Caption,FormaFormatos.C3.Caption,tipooperador(FormaFormatos.Operador3.Text),FormaFormatos.Valor3.Text,FormaFormatos.T3.Caption,'Y');
if FormaFormatos.IncluirDevoluciones.Checked then
begin
GeneraCorteDeCaja(FormaFormatos.Inicial.Date,FormaFormatos.Final.Date,TablaFacturaE.TableName,'devoluc.dbf','FactAuxi.dbf','INUMENC','S');
Concentrar(TablaAuxiliar,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLDOC_F','NOMBR_F','IMTOD_F','SUBTO_F','IMIM2_F','','','','','','STATU_F','!','C','D');
if TablaAuxiliar.State=dsBrowse then TablaAuxiliar.Close;
end
else
Concentrar(TablaFacturaE,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLDOC_F','NOMBR_F','IMTOD_F','SUBTO_F','IMIM2_F','','','','','','STATU_F','!','C','D');

//Concentrar(TablaAuxiliar,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLCLI_F','NOMBR_F','IMTOD_F','SUBTO_F','IMIM1_F','IMIM2_F','','','','','STATU_F','!','C','D');

dia:=DateToStr(FormaFormatos.Inicial.Date);
//

poneetiquetas('Documento','Nombre','Total del Documento','SubTotal','IVA','','','','','','');
Poneanchos(20,20,20,20,20,20,20,20,20,20,0);
parametrosgrafica('Gráfica de Consecutivo de Documentos','Número de Documento','Total por Documento',1);

FormaBarras.Tag:=0;
FormaBarras.Panel2.Tag:=0;
FormaBarras.botonGrafica.Tag:=2;

FormaBarras.Concentrado.Clear;
FormaBarras.Caption:=AgregaTitulo2('Reporte de Consecutivo de Documentos',FormaFormatos.Titulo.Text);
FormaBarras.ShowModal;
FormaBarras.Tag:=0;
end;
FormaFormatos.Tag:=0;
FormaFormatos.Free;
FormaBarras.Free;

end;


procedure TFormaFactura.Eliminar1Click(Sender: TObject);
begin
if caso(StrToInt(usuario.Caption),22) then
begin
FormaAdvertencia:=TFormaAdvertencia.Create(Application);
FormaAdvertencia.ShowModal;
if FormaAdvertencia.Tag=1 then
begin
{***********}
if Base.Text='Factura' then
begin
if borratodaslascuentas then
begin
bufercambios('F');
BorraDatosMovimientos('F');
borradatosanteriores('F');
TablaFacturaE.Delete;
end
else
MuestraMensaje('El documento No Puede Eliminarse Posee Movimientos');
end
else
begin
if Base.Text='Remisión' then
begin

bufercambios('F');
BorraDatosMovimientos('R');
borradatosanteriores('R');
TablaFacturaE.Delete;
end;//if remision
end;
ponedatos;
end;
FormaAdvertencia.Tag:=0;
FormaAdvertencia.Free;
end;
end;

procedure TFormaFactura.ComisionesDetallado1Click(Sender: TObject);
var
desde,hastavalor:string;
begin
FormaFormatos:=TFormaFormatos.Create(Application);
FormaBarras:=TFormaBarras.Create(Application);

FormaFormatos.Rangos.Visible:=True;
FormaFormatos.Formatos.Visible:=False;
activacondiciones(true,true,False,true,False,true,true,true,true,'facturae.dbf');
TablaFacturaE.First;
desde:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
TablaFacturaE.Last;
hastavalor:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
valoresiniciales('','',desde,hastavalor);

FormaFormatos.ShowModal;
if FormaFormatos.Tag=1 then
begin
condiciones(FormaFormatos.C1.Caption,tipooperador(FormaFormatos.Operador1.Text),FormaFormatos.Valor1.Text,FormaFormatos.T1.Caption,FormaFormatos.C2.Caption,tipooperador(FormaFormatos.Operador2.Text),FormaFormatos.Valor2.Text,FormaFormatos.T2.Caption,FormaFormatos.C3.Caption,tipooperador(FormaFormatos.Operador3.Text),FormaFormatos.Valor3.Text,FormaFormatos.T3.Caption,'Y');
if FormaFormatos.IncluirDevoluciones.Checked then
begin
GeneraCorteDeCaja(FormaFormatos.Inicial.Date,FormaFormatos.Final.Date,TablaFacturaE.TableName,'devoluc.dbf','FactAuxi.dbf','INUMENC','S');
//Concentrar(TablaAuxiliar,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLCLI_F','NOMBR_F','IMTOD_F','SUBTO_F','IMIM1_F','IMIM2_F','','','','','STATU_F','!','C','D');
Concentrar(TablaAuxiliar,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLVEN_F','FEDOC_F','IMTOD_F','&%IMTOD_F&*&%CTOVE_F&*&0.01&','','','','','','','STATU_F','!','C','DC');
if TablaAuxiliar.State=dsBrowse then TablaAuxiliar.Close;
end
else
Concentrar(TablaFacturaE,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLVEN_F','FEDOC_F','IMTOD_F','&%IMTOD_F&*&%CTOVE_F&*&0.01&','','','','','','','STATU_F','!','C','DC');
poneetiquetas('Vendedor','Fecha','Total','Comisión','','','','','','','');
Poneanchos(20,20,20,20,20,20,20,20,20,20,0);
parametrosgrafica('Gráfica de Comisiones Detallado','Número de Documento','Total por Documento',1);
FormaBarras.Tag:=0;
FormaBarras.Panel2.Tag:=0;
FormaBarras.botonGrafica.Tag:=2;

FormaBarras.Concentrado.Clear;
//FormaBarras.Caption:='Reporte de Comisiones Detallado';
//******pone el titulo
 with Sender as TMenuItem do
  begin
  desde:=Caption;
  end;
FormaBarras.Caption:=AgregaTitulo2('Reporte de '+desde,FormaFormatos.Titulo.Text);
//******termina pone el titulo

FormaBarras.ShowModal;
FormaBarras.Tag:=0;
end;
FormaFormatos.Tag:=1;
FormaFormatos.Free;
FormaBarras.Free;

end;

procedure TFormaFactura.Factura1Click(Sender: TObject);
var
Aux:string[1];
begin
MovimientoBorrado:=0;
Aux:=Base.Text;
Orig:=Aux+EditCLDOC_F.Text;
RangoDocumentos:=False;

Base.Tag:=1;
while not TablaFacturaD.EOF do
begin
TablaFacturaD.Edit;
TablaFacturaD.FieldByName('TREGI_FD').AsString:='F';
TablaFacturaD.Post;
TablaFacturaD.Next;
end;

bufercambios('C');
generadocumento('F');
TablaFacturaD.First;
activa;
EditCLDOC_F.SetFocus;
local:=True;
TablaFacturaE.Edit;


if (TablaCliente.FindKey([EditCLCLI_F.Text]))and(TablaFacturaE.State=dsEdit) then
begin
Nombre.Caption:=TablaCliente.FieldByName('NOMBR_C').AsString;
Direccion.Caption:=TablaCliente.FieldByName('DIREC_C').AsString;
Direc2.Caption:=TablaCliente.FieldByName('DIRE2_C').AsString;
Poblacion.Caption:=TablaCliente.FieldByName('POBLA_C').AsString;
RFC.Caption:=TablaCliente.FieldByName('RFCXX_C').AsString;
CodigoPostal.Caption:=TablaCliente.FieldByname('CPXXX_C').AsString;
end


end;

procedure TFormaFactura.Remisin1Click(Sender: TObject);
var
Aux:string[1];
begin
Aux:=Base.Text;
Orig:=Aux+EditCLDOC_F.Text;
bufercambios('C');
generadocumento('R');
activa;
EditCLDOC_F.SetFocus;
local:=True;
TablaFacturaE.Edit;
end;

procedure TFormaFactura.Pedido1Click(Sender: TObject);
var
Aux:string[1];
begin
Aux:=Base.Text;
Orig:=Aux+EditCLDOC_F.Text;
bufercambios('C');
generadocumento('P');
activa;
EditCLDOC_F.SetFocus;
local:=True;
TablaFacturaE.Edit;
end;

procedure TFormaFactura.VentasyUtilidad1Click(Sender: TObject);
var
desde,hastavalor:string;
begin
FormaFormatos:=TFormaFormatos.Create(Application);
FormaBarras:=TFormaBarras.Create(Application);

FormaFormatos.Rangos.Visible:=True;
FormaFormatos.Formatos.Visible:=False;
activacondiciones(true,true,False,true,False,true,true,true,true,'facturae.dbf');
TablaFacturaE.First;
desde:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
TablaFacturaE.Last;
hastavalor:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
valoresiniciales('','',desde,hastavalor);

FormaFormatos.ShowModal;
if FormaFormatos.Tag=1 then
begin
if FormaFormatos.IncluirDevoluciones.Checked then
begin
GeneraCorteDeCaja(FormaFormatos.Inicial.Date,FormaFormatos.Final.Date,TablaFacturaE.TableName,'devoluc.dbf','FactAuxi.dbf','INUMENC','S');
condiciones(FormaFormatos.C1.Caption,tipooperador(FormaFormatos.Operador1.Text),FormaFormatos.Valor1.Text,FormaFormatos.T1.Caption,FormaFormatos.C2.Caption,tipooperador(FormaFormatos.Operador2.Text),FormaFormatos.Valor2.Text,FormaFormatos.T2.Caption,FormaFormatos.C3.Caption,tipooperador(FormaFormatos.Operador3.Text),FormaFormatos.Valor3.Text,FormaFormatos.T3.Caption,'Y');
//Concentrar(TablaAuxiliar,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLCLI_F','NOMBR_F','IMTOD_F','SUBTO_F','IMIM1_F','IMIM2_F','','','','','STATU_F','!','C','D');
Concentrar(TablaAuxiliar,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLDOC_F','NOMBR_F','COSTO_F','IMTOD_F','&%IMTOD_F&-&%COSTO_F&*&1.0&','','','','','','STATU_F','!','C','D');
end
else
Concentrar(TablaFacturaE,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLDOC_F','NOMBR_F','COSTO_F','SUBTO_F','&%SUBTO_F&-&%COSTO_F&*&1.0&','','','','','','STATU_F','!','C','D');
poneetiquetas('Documento','Nombre','Costo','Total','Utilidad','','','','','','');
Poneanchos(20,20,20,20,20,20,20,20,20,20,0);
parametrosgrafica('Gráfica de Ventas y Utilidades','Número de Documento','Total por Documento',2);
FormaBarras.Tag:=0;
FormaBarras.Panel2.Tag:=0;
FormaBarras.botonGrafica.Tag:=2;

FormaBarras.Concentrado.Clear;
//FormaBarras.Caption:='Reporte de Ventas y Utilidades';
//******pone el titulo
 with Sender as TMenuItem do
  begin
  desde:=Caption;
  end;
FormaBarras.Caption:=AgregaTitulo2('Reporte de '+desde,FormaFormatos.Titulo.Text);
//******termina pone el titulo

FormaBarras.ShowModal;
FormaBarras.Tag:=0;
end;
FormaFormatos.Tag:=0;
FormaFormatos.Free;
FormaBarras.Free;

end;

procedure TFormaFactura.BotonPreliminarClick(Sender: TObject);
begin
if FileExists(nombreformato) then
begin
FormaEdicion:=TFormaEdicion.Create(Application);
UsuarioActual(Usuario.Caption);
LeeEtiquetasMoneda(valordivisaetiqueta('M.N.',1),valordivisaetiqueta('M.N.',2),valordivisaetiqueta('M.N.',3),valordivisaetiqueta('M.N.',4));
forma(FormaFactura.TablaFacturaE,FormaFactura.TablaDeta,nombreformato,'p');
end
else
MuestraMensaje('El Formato '+nombreformato+' No Existe');
FormaEdicion.Hoja.Tag:=0;
FormaEdicion.ShowModal;
FormaEdicion.Free;
end;


procedure TFormaFactura.Calculadora1Click(Sender: TObject);
begin
{if FileExists('calc.exe') then}
WinExec('calc.exe',SW_SHOWNORMAL);

end;

procedure TFormaFactura.Divisas1Click(Sender: TObject);
begin
FormaDivisa:=TFormaDivisa.Create(Application);
FormaDivisa.ShowModal;
FormaDivisa.Free;
end;

procedure TFormaFactura.ImprimirRangodeDocumentos1Click(Sender: TObject);
var
i:integer;
begin
DialogoImprimir:=TDialogoImprimir.Create(Application);
DialogoImprimir.Tag:=0;
DialogoImprimir.PrimeraPagina.Text:='0';
DialogoImprimir.UltimaPagina.Text:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
DialogoImprimir.ShowModal;

if DialogoImprimir.Tag=1 then
begin
TablaFacturaE.First;
for i:=StrToInt(DialogoImprimir.PrimeraPagina.Text) to StrToInt(DialogoImprimir.UltimaPagina.Text) do
begin
if TablaFacturaE.FindKey([IntToStr(i)]) then
begin
ponedatos;
if FileExists(nombreformato) then
begin
UsuarioActual(Usuario.Caption);
forma(FormaFactura.TablaFacturaE,FormaFactura.TablaDeta,nombreformato,'i');
end
else
MuestraMensaje('El Formato '+nombreformato+' No Existe');
end;
end;
ponedatos;
end;
DialogoImprimir.Free;

end;


procedure TFormaFactura.Cancelar1Click(Sender: TObject);
var
Tipo:Char;
clave:String;
begin
if Usuario.Caption<>'0' then
begin
FormaAdministrador:=TFormaAdministrador.Create(Application);
FormaAdministrador.ShowModal;
if FormaAdministrador.Tag=1 then
clave:='admon'
else
clave:='xxxx';
FormaAdministrador.Free;
end;


if (caso(StrToInt(usuario.Caption),22))or(clave='admon') then

if caso(StrToInt(usuario.Caption),22) then
begin
FormaAdvertencia:=TFormaAdvertencia.Create(Application);
FormaAdvertencia.Label1.Caption:='Esta Seguro que Desea CANCELAR este Documento ?';
FormaAdvertencia.ShowModal;
FormaAdvertencia.Label1.Caption:='Esta Seguro que Desea ELIMINAR este Documento ?';
if FormaAdvertencia.Tag=1 then
begin
Tipo:=Base.Text[1];
if TablaFacturaE.FieldByName('STATU_F').AsString<>'C' then
begin

case Tipo of

'R':begin

   bufercambios('F');
   saldoanterior:=TablaFacturaE.FieldByName('IMTOD_F').AsFloat;

//   BorraDatosMovimientos('F');
   borradatosanteriores('X');
   if IntegrarMI='S' then
   begin
   TablaMovimientosInventario.Last;
   numeromovimiento:=TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger+1;
   end;//if mov inv

if TablaCliente.FindKey([EditCLCLI_F.Text]) then
begin
TablaCliente.Edit;
TablaCliente.FieldByName('SALDO_C').AsFloat:=TablaCliente.FieldByName('SALDO_C').AsFloat-saldoanterior;
TablaCliente.FieldByName('COMPR_C').Asfloat:=TablaCliente.FieldByName('COMPR_C').AsFloat-saldoanterior;
TablaCliente.Post;
end;

{*********};
try
CreaMovimiento_Cancelar(54);
TipoMovimiento:=3;
except
end;



{guardatodo('X');}

local:=False;
TablaFacturaE.Edit;
TablaFacturaE.FieldByName('STATU_F').AsString:='C';
TablaFacturaE.Post;
CancelaDetalle(EditCLDOC_F.Text);
Estado.Caption:='Cancelada';

end;


'D':begin
   bufercambios('F');
   saldoanterior:=TablaFacturaE.FieldByName('IMTOD_F').AsFloat;

//   BorraDatosMovimientos('F');
//   borradatosanteriores('X');
   if IntegrarMI='S' then
   begin
   TablaMovimientosInventario.Last;
   numeromovimiento:=TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger+1;
   end;//if mov inv

if TablaCliente.FindKey([EditCLCLI_F.Text]) then
begin
TablaCliente.Edit;
TablaCliente.FieldByName('SALDO_C').AsFloat:=TablaCliente.FieldByName('SALDO_C').AsFloat-saldoanterior;
TablaCliente.FieldByName('COMPR_C').Asfloat:=TablaCliente.FieldByName('COMPR_C').AsFloat-saldoanterior;
TablaCliente.Post;
end;

{*********};
try
CreaMovimiento_Cancelar(3);
except
end;



{guardatodo('X');}

local:=False;
TablaFacturaE.Edit;
TablaFacturaE.FieldByName('STATU_F').AsString:='C';
TablaFacturaE.Post;
CancelaDetalle(EditCLDOC_F.Text);
Estado.Caption:='Cancelada';

end;


end;//case


{if (borratodaslascuentas) then
   begin

   bufercambios('F');
   saldoanterior:=TablaFacturaE.FieldByName('IMTOD_F').AsFloat;

//   BorraDatosMovimientos('F');
   borradatosanteriores('X');
   if IntegrarMI='S' then
   begin
   TablaMovimientosInventario.Last;
   numeromovimiento:=TablaMovimientosInventario.FieldByName('CLDOC_MI').AsInteger+1;
   end;//if mov inv

if TablaCliente.FindKey([EditCLCLI_F.Text]) then
begin
TablaCliente.Edit;
TablaCliente.FieldByName('SALDO_C').AsFloat:=TablaCliente.FieldByName('SALDO_C').AsFloat-saldoanterior;
TablaCliente.FieldByName('COMPR_C').Asfloat:=TablaCliente.FieldByName('COMPR_C').AsFloat-saldoanterior;
TablaCliente.Post;
end;

try
if (Base.Text='Factura')or(Base.Text='Remisión') then
CreaMovimiento_Cancelar;
except
end;



local:=False;
TablaFacturaE.Edit;
TablaFacturaE.FieldByName('STATU_F').AsString:='C';
TablaFacturaE.Post;
CancelaDetalle(EditCLDOC_F.Text);
Estado.Caption:='Cancelada';
end
else
MuestraMensaje('No Puede Cancelarse un Documento con Abonos');//if borratodaslascuentas}

end
else
MuestraMensaje('La Factura Ya Fue Cancelada');
indice:=0;
sig:=1;
indices:=1;

end;
FormaAdvertencia.Tag:=0;
FormaAdvertencia.Free;
end;

end;

procedure TFormaFactura.BotonTotalesClick(Sender: TObject);
var
cantiletra:string;
begin
sumatotal;
FormaDesglosaTotal:=TFormaDesglosaTotal.Create(Application);
FormaDesglosaTotal.SubTotal.Caption:=SumarTotal.Caption;
FormaDesglosaTotal.Descuento.Caption:=convierte('###,###,##0.00',redondear(desfin1),'$');
FormaDesglosaTotal.Iva.Caption:=ImpuestoValor.Caption;
FormaDesglosaTotal.Total.Caption:=TotalFact.Caption;
{*****************}
cantiletra:=Traduce(Total1);
FormaDesglosaTotal.Letra2.Caption:='';
FormaDesglosaTotal.Letra1.Caption:=cantiletra;
{*****************}
FormaDesglosaTotal.ShowModal;
FormaDesglosaTotal.Free;
end;

procedure TFormaFactura.EditDECOT_FKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
if (key=13) or (key=40) then
begin
indices:=indices+1;
cursor1;
end;
if key=38 then
begin
indices:=indices-1;
cursor1;
end;

end;


procedure TFormaFactura.Elegirformato1Click(Sender: TObject);
begin
FormaFormatos:=TFormaFormatos.Create(Application);
FormaBarras:=TFormaBarras.Create(Application);

FormaFormatos.Tag:=3;
FormaFormatos.Rangos.Visible:=False;
FormaFormatos.Formatos.Visible:=True;
FormaFormatos.ShowModal;
if FormaFormatos.Tag=1 then
begin
if FileExists(Formaformatos.Rutas.Text) then
begin
nombreformato:=Formaformatos.Rutas.Text;
{forma(TablaFacturaE,TablaFacturaE,Formaformatos.Rutas.Text,'i')}

end
else
MuestraMensaje('El Formato '+Formaformatos.Rutas.Text+' No Existe');
end;
FormaFormatos.Tag:=1;
FormaFormatos.Free;
FormaBarras.Free;

end;

procedure TFormaFactura.DisearFormato1Click(Sender: TObject);
begin
FormaFormatos:=TFormaFormatos.Create(Application);
//FormaBarras:=TFormaBarras.Create(Application);

FormaFormatos.Rangos.Visible:=False;
FormaFormatos.Formatos.Visible:=True;
FormaFormatos.BotonEdicionClick(Sender);

//FormaFormatos.ShowModal;

FormaFormatos.Free;
//FormaBarras.Free;

end;

procedure TFormaFactura.TablaFacturaeEditError(DataSet: TDataSet;
  E: EDatabaseError; var Action: TDataAction);
begin
if local then Action:=daRetry
else
DatabaseError('No se Pueden Editar los Datos ha Ocurrido un Error');
end;

procedure TFormaFactura.TablaFacturaePostError(DataSet: TDataSet;
  E: EDatabaseError; var Action: TDataAction);
begin
Action:=daRetry	;
{DatabaseError('No se Pueden Guardar los Datos ha Ocurrido un Error');}
end;

procedure TFormaFactura.EditCLDOC_FExit(Sender: TObject);
begin
quitacolor(EditCLDOC_F.ComponentIndex);
end;

procedure TFormaFactura.EditCTOVE_FExit(Sender: TObject);
begin
quitacolor(EditCTOVE_F.ComponentIndex);

end;

procedure TFormaFactura.EditBCLIM_FExit(Sender: TObject);
begin
quitacolor(EditBCLIM_F.ComponentIndex);
end;

procedure TFormaFactura.EditIMIM1_FExit(Sender: TObject);
begin
quitacolor(EditIMIM1_F.ComponentIndex);
end;

procedure TFormaFactura.EditDESFI_FExit(Sender: TObject);
begin
quitacolor(EditDESFI_F.ComponentIndex);
end;

procedure TFormaFactura.TablaFacturaeDeleteError(DataSet: TDataSet;
  E: EDatabaseError; var Action: TDataAction);
begin
Action:=daRetry	;
end;

procedure TFormaFactura.TablaFacturaeUpdateError(DataSet: TDataSet;
  E: EDatabaseError; UpdateKind: TUpdateKind;
  var UpdateAction: TUpdateAction);
begin
UpdateAction:=uaRetry;
end;

procedure TFormaFactura.TablaFacturaDDeleteError(DataSet: TDataSet;
  E: EDatabaseError; var Action: TDataAction);
begin
Action:=daRetry	;
end;

procedure TFormaFactura.TablaFacturaDEditError(DataSet: TDataSet;
  E: EDatabaseError; var Action: TDataAction);
begin
Action:=daRetry	;
end;

procedure TFormaFactura.TablaFacturaDPostError(DataSet: TDataSet;
  E: EDatabaseError; var Action: TDataAction);
begin
Action:=daRetry	;
end;

procedure TFormaFactura.TablaFacturaDUpdateError(DataSet: TDataSet;
  E: EDatabaseError; UpdateKind: TUpdateKind;
  var UpdateAction: TUpdateAction);
begin
UpdateAction:=uaRetry	;
end;

procedure TFormaFactura.TablaClienteEditError(DataSet: TDataSet;
  E: EDatabaseError; var Action: TDataAction);
begin
Action:=daRetry	;
end;

procedure TFormaFactura.TablaClienteDeleteError(DataSet: TDataSet;
  E: EDatabaseError; var Action: TDataAction);
begin
Action:=daRetry	;
end;

procedure TFormaFactura.TablaClientePostError(DataSet: TDataSet;
  E: EDatabaseError; var Action: TDataAction);
begin
Action:=daRetry	;
end;

procedure TFormaFactura.TablaClienteUpdateError(DataSet: TDataSet;
  E: EDatabaseError; UpdateKind: TUpdateKind;
  var UpdateAction: TUpdateAction);
begin
UpdateAction:=uaRetry	;
end;

procedure TFormaFactura.TablaInventarioDeleteError(DataSet: TDataSet;
  E: EDatabaseError; var Action: TDataAction);
begin
Action:=daRetry	;
end;

procedure TFormaFactura.TablaInventarioEditError(DataSet: TDataSet;
  E: EDatabaseError; var Action: TDataAction);
begin
Action:=daRetry	;
end;

procedure TFormaFactura.TablaInventarioPostError(DataSet: TDataSet;
  E: EDatabaseError; var Action: TDataAction);
begin
Action:=daRetry	;
end;

procedure TFormaFactura.TablaInventarioUpdateError(DataSet: TDataSet;
  E: EDatabaseError; UpdateKind: TUpdateKind;
  var UpdateAction: TUpdateAction);
begin
UpdateAction:=uaRetry	;
end;

procedure TFormaFactura.TablaVendedoresDeleteError(DataSet: TDataSet;
  E: EDatabaseError; var Action: TDataAction);
begin
Action:=daRetry	;
end;

procedure TFormaFactura.TablaVendedoresEditError(DataSet: TDataSet;
  E: EDatabaseError; var Action: TDataAction);
begin
Action:=daRetry	;
end;

procedure TFormaFactura.TablaVendedoresPostError(DataSet: TDataSet;
  E: EDatabaseError; var Action: TDataAction);
begin
Action:=daRetry	;
end;

procedure TFormaFactura.TablaVendedoresUpdateError(DataSet: TDataSet;
  E: EDatabaseError; UpdateKind: TUpdateKind;
  var UpdateAction: TUpdateAction);
begin
UpdateAction:=uaRetry	;
end;

procedure TFormaFactura.TablamovimientosInventarioDeleteError(
  DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction);
begin
Action:=daRetry	;
end;

procedure TFormaFactura.TablamovimientosInventarioEditError(
  DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction);
begin
Action:=daRetry	;
end;

procedure TFormaFactura.TablamovimientosInventarioPostError(
  DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction);
begin
Action:=daRetry	;
end;

procedure TFormaFactura.TablamovimientosInventarioUpdateError(
  DataSet: TDataSet; E: EDatabaseError; UpdateKind: TUpdateKind;
  var UpdateAction: TUpdateAction);
begin
UpdateAction:=uaRetry	;
end;


procedure TFormaFactura.FacturasFechaeImportes1Click(Sender: TObject);
var
desde,hastavalor:string;
begin
FormaFormatos:=TFormaFormatos.Create(Application);
FormaBarras:=TFormaBarras.Create(Application);

FormaFormatos.Rangos.Visible:=True;
FormaFormatos.Formatos.Visible:=False;
activacondiciones(true,true,False,true,False,true,true,true,true,'facturae.dbf');
TablaFacturaE.First;
desde:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
TablaFacturaE.Last;
hastavalor:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
valoresiniciales('','',desde,hastavalor);

TablaFacturaE.First;
desde:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
TablaFacturaE.Last;
hastavalor:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
valoresiniciales('','',desde,hastavalor);

FormaFormatos.ShowModal;
if FormaFormatos.Tag=1 then
begin
condiciones(FormaFormatos.C1.Caption,tipooperador(FormaFormatos.Operador1.Text),FormaFormatos.Valor1.Text,FormaFormatos.T1.Caption,FormaFormatos.C2.Caption,tipooperador(FormaFormatos.Operador2.Text),FormaFormatos.Valor2.Text,FormaFormatos.T2.Caption,FormaFormatos.C3.Caption,tipooperador(FormaFormatos.Operador3.Text),FormaFormatos.Valor3.Text,FormaFormatos.T3.Caption,'Y');
if FormaFormatos.IncluirDevoluciones.Checked then
begin
GeneraCorteDeCaja(FormaFormatos.Inicial.Date,FormaFormatos.Final.Date,TablaFacturaE.TableName,'devoluc.dbf','FactAuxi.dbf','INUMENC','S');
//Concentrar(TablaAuxiliar,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLCLI_F','NOMBR_F','IMTOD_F','SUBTO_F','IMIM1_F','IMIM2_F','','','','','STATU_F','!','C','D');
Concentrar(TablaAuxiliar,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLCLI_F','FEDOC_F','IMTOD_F','SUBTO_F','IMIM2_F','','','','','','STATU_F','!','C','D');
end
else
Concentrar(TablaFacturaE,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLCLI_F','FEDOC_F','IMTOD_F','SUBTO_F','IMIM2_F','','','','','','STATU_F','!','C','D');
poneetiquetas('Cliente','Fecha','Total del Documento','SubTotal','IVA','','','','','','');
Poneanchos(20,20,20,20,20,20,20,20,20,20,0);
parametrosgrafica('Gráfica de Facturas, Fechas e Importes','Número de Documento','Total por Documento',1);
FormaBarras.Tag:=0;
FormaBarras.Panel2.Tag:=0;
FormaBarras.botonGrafica.Tag:=2;

FormaBarras.Concentrado.Clear;
//FormaBarras.Caption:='Reporte de Facturas, Fechas e Importes';
//******pone el titulo
 with Sender as TMenuItem do
  begin
  desde:=Caption;
  end;
FormaBarras.Caption:=AgregaTitulo2('Reporte de '+desde,FormaFormatos.Titulo.Text);
//******termina pone el titulo

FormaBarras.ShowModal;
FormaBarras.Tag:=0;
end;
FormaFormatos.Tag:=0;
FormaFormatos.Free;
FormaBarras.Free;

end;



procedure TFormaFactura.BotonObservacionClick(Sender: TObject);
begin
try
buscaobservacion(EditCLDOC_F.Text,BotonNuevo.Tag);
except
end;
end;

procedure TFormaFactura.BotonCambiosMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
describir(Button,FormaFactura.Left+BotonCambios.Left,FormaFactura.Top+BotonCambios.Top+BotonCambios.Height,15);
end;

procedure TFormaFactura.BotonNuevoMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
describir(Button,FormaFactura.Left+BotonNuevo.Left,FormaFactura.Top+BotonNuevo.Top+BotonNuevo.Height,16);
end;

procedure TFormaFactura.BotonGuardarMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
describir(Button,FormaFactura.Left+BotonGuardar.Left,FormaFactura.Top+BotonGuardar.Top+BotonGuardar.Height,17);
end;

procedure TFormaFactura.BotonTotalesMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
describir(Button,FormaFactura.Left+BotonTotales.Left,FormaFactura.Top+BotonTotales.Top+BotonTotales.Height,18);
end;

procedure TFormaFactura.BotonPreliminarMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
describir(Button,FormaFactura.Left+BotonPreliminar.Left,FormaFactura.Top+BotonPreliminar.Top+BotonPreliminar.Height,19);
end;

procedure TFormaFactura.BotonObservacionMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
describir(Button,FormaFactura.Left+BotonObservacion.Left,FormaFactura.Top+BotonObservacion.Top+BotonObservacion.Height,20);
end;

procedure TFormaFactura.BotonBuscarMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
describir(Button,FormaFactura.Left+BotonBuscar.Left,FormaFactura.Top+BotonBuscar.Top+BotonBuscar.Height,21);
end;

procedure TFormaFactura.BotonImprimirMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
describir(Button,FormaFactura.Left+BotonImprimir.Left,FormaFactura.Top+BotonImprimir.Top+BotonImprimir.Height,22);
end;

procedure TFormaFactura.BotonPagoMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
describir(Button,FormaFactura.Left+BotonPago.Left,FormaFactura.Top+BotonPago.Top+BotonPago.Height,23);
end;

procedure TFormaFactura.Devolucin1Click(Sender: TObject);
var
Aux:string[1];
begin
MovimientoBorrado:=0;
RangoDocumentos:=False;
Aux:=Base.Text;
Orig:=Aux+EditCLDOC_F.Text;

bufercambios('C');
generadocumento('D');
activa;
EditCLDOC_F.SetFocus;
local:=True;
TablaFacturaE.Edit;

end;

procedure TFormaFactura.VentasporDa1Click(Sender: TObject);
var
desde,hastavalor:string;
begin
FormaFormatos:=TFormaFormatos.Create(Application);
FormaBarras:=TFormaBarras.Create(Application);

FormaFormatos.Rangos.Visible:=True;
FormaFormatos.Formatos.Visible:=False;
activacondiciones(true,true,False,true,False,true,true,true,true,'facturae.dbf');
TablaFacturaE.First;
desde:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
TablaFacturaE.Last;
hastavalor:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
valoresiniciales('','',desde,hastavalor);

FormaFormatos.ShowModal;
if FormaFormatos.Tag=1 then
begin
condiciones(FormaFormatos.C1.Caption,tipooperador(FormaFormatos.Operador1.Text),FormaFormatos.Valor1.Text,FormaFormatos.T1.Caption,FormaFormatos.C2.Caption,tipooperador(FormaFormatos.Operador2.Text),FormaFormatos.Valor2.Text,FormaFormatos.T2.Caption,FormaFormatos.C3.Caption,tipooperador(FormaFormatos.Operador3.Text),FormaFormatos.Valor3.Text,FormaFormatos.T3.Caption,'Y');
if FormaFormatos.IncluirDevoluciones.Checked then
begin
GeneraCorteDeCaja(FormaFormatos.Inicial.Date,FormaFormatos.Final.Date,TablaFacturaE.TableName,'devoluc.dbf','FactAuxi.dbf','INUMENC','S');
Concentrar(TablaAuxiliar,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'FEDOC_F','','IMTOD_F','CTOVE_F','&%IMTOD_F&*&%CTOVE_F&*&0.01&','','','','','','STATU_F','!','C','C');
end
else
Concentrar(TablaFacturaE,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'FEDOC_F','','IMTOD_F','CTOVE_F','&%IMTOD_F&*&%CTOVE_F&*&0.01&','','','','','','STATU_F','!','C','C');
poneetiquetas('Fecha','','Importe','- % Comis. Vend.','Comisión','','','','','','');
Poneanchos(20,20,20,20,20,20,20,20,20,20,0);
//FormaBarras.Caption:='Reporte de Ventas por Día';
//******pone el titulo
 with Sender as TMenuItem do
  begin
  desde:=Caption;
  end;
FormaBarras.Caption:=AgregaTitulo2('Reporte de '+desde,FormaFormatos.Titulo.Text);
//******termina pone el titulo

parametrosgrafica('Gráfica de Ventas por Día','Día','Total por Día',1);
FormaBarras.Tag:=0;
FormaBarras.Panel2.Tag:=0;
FormaBarras.botonGrafica.Tag:=2;
FormaBarras.ShowModal;
FormaBarras.Tag:=0;
end;
FormaFormatos.Tag:=0;
FormaFormatos.Free;
FormaBarras.Free;

end;

procedure TFormaFactura.VentasporMes1Click(Sender: TObject);
var
desde,hastavalor:string;
begin
FormaFormatos:=TFormaFormatos.Create(Application);
FormaBarras:=TFormaBarras.Create(Application);

FormaFormatos.Rangos.Visible:=True;
FormaFormatos.Formatos.Visible:=False;
activacondiciones(true,true,False,true,False,true,true,true,true,'facturae.dbf');
TablaFacturaE.First;
desde:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
TablaFacturaE.Last;
hastavalor:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
valoresiniciales('','',desde,hastavalor);

FormaFormatos.ShowModal;
if FormaFormatos.Tag=1 then
begin
condiciones(FormaFormatos.C1.Caption,tipooperador(FormaFormatos.Operador1.Text),FormaFormatos.Valor1.Text,FormaFormatos.T1.Caption,FormaFormatos.C2.Caption,tipooperador(FormaFormatos.Operador2.Text),FormaFormatos.Valor2.Text,FormaFormatos.T2.Caption,FormaFormatos.C3.Caption,tipooperador(FormaFormatos.Operador3.Text),FormaFormatos.Valor3.Text,FormaFormatos.T3.Caption,'Y');
if FormaFormatos.IncluirDevoluciones.Checked then
begin
GeneraCorteDeCaja(FormaFormatos.Inicial.Date,FormaFormatos.Final.Date,TablaFacturaE.TableName,'devoluc.dbf','FactAuxi.dbf','INUMENC','S');
Concentrar(TablaAuxiliar,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'FEDOC_F','','IMTOD_F','CTOVE_F','&%IMTOD_F&*&%CTOVE_F&*&0.01&','','','','','','STATU_F','!','C','C');
end
else
Concentrar(TablaFacturaE,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'FEDOC_F','','IMTOD_F','CTOVE_F','&%IMTOD_F&*&%CTOVE_F&*&0.01&','','','','','','STATU_F','!','C','C');
poneetiquetas('Fecha','','Importe','- % Comis. Vend.','Comisión','','','','','','');
Poneanchos(20,20,20,20,20,20,20,20,20,20,0);
pormes;
//FormaBarras.Caption:='Reporte de Ventas por Mes';
//******pone el titulo
 with Sender as TMenuItem do
  begin
  desde:=Caption;
  end;
FormaBarras.Caption:=AgregaTitulo2('Reporte de '+desde,FormaFormatos.Titulo.Text);
//******termina pone el titulo

parametrosgrafica('Gráfica de Ventas por Mes','Mes','Total por Mes',1);
FormaBarras.Tag:=0;
FormaBarras.Panel2.Tag:=0;
FormaBarras.botonGrafica.Tag:=2;
FormaBarras.ShowModal;
FormaBarras.Tag:=0;
end;
FormaFormatos.Tag:=0;
FormaFormatos.Free;
FormaBarras.Free;

end;

procedure TFormaFactura.Ventasporao1Click(Sender: TObject);
var
desde,hastavalor:string;
begin
FormaFormatos:=TFormaFormatos.Create(Application);
FormaBarras:=TFormaBarras.Create(Application);

FormaFormatos.Rangos.Visible:=True;
FormaFormatos.Formatos.Visible:=False;
activacondiciones(true,true,False,true,False,true,true,true,true,'facturae.dbf');
TablaFacturaE.First;
desde:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
TablaFacturaE.Last;
hastavalor:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
valoresiniciales('','',desde,hastavalor);

FormaFormatos.ShowModal;
if FormaFormatos.Tag=1 then
begin
condiciones(FormaFormatos.C1.Caption,tipooperador(FormaFormatos.Operador1.Text),FormaFormatos.Valor1.Text,FormaFormatos.T1.Caption,FormaFormatos.C2.Caption,tipooperador(FormaFormatos.Operador2.Text),FormaFormatos.Valor2.Text,FormaFormatos.T2.Caption,FormaFormatos.C3.Caption,tipooperador(FormaFormatos.Operador3.Text),FormaFormatos.Valor3.Text,FormaFormatos.T3.Caption,'Y');
if FormaFormatos.IncluirDevoluciones.Checked then
begin
GeneraCorteDeCaja(FormaFormatos.Inicial.Date,FormaFormatos.Final.Date,TablaFacturaE.TableName,'devoluc.dbf','FactAuxi.dbf','INUMENC','S');
Concentrar(TablaAuxiliar,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'FEDOC_F','','IMTOD_F','CTOVE_F','&%IMTOD_F&*&%CTOVE_F&*&0.01&','','','','','','STATU_F','!','C','C');
end
else
Concentrar(TablaFacturaE,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'FEDOC_F','','IMTOD_F','CTOVE_F','&%IMTOD_F&*&%CTOVE_F&*&0.01&','','','','','','STATU_F','!','C','C');
poneetiquetas('Fecha','','Importe','- % Comis. Vend.','Comisión','','','','','','');
Poneanchos(20,20,20,20,20,20,20,20,20,20,0);
//FormaBarras.Caption:='Reporte de Ventas por Año';
//******pone el titulo
 with Sender as TMenuItem do
  begin
  desde:=Caption;
  end;
FormaBarras.Caption:=AgregaTitulo2('Reporte de '+desde,FormaFormatos.Titulo.Text);
//******termina pone el titulo

parametrosgrafica('Gráfica de Ventas por Año','Año','Total por Año',1);
FormaBarras.Tag:=0;
FormaBarras.Panel2.Tag:=0;
FormaBarras.botonGrafica.Tag:=2;
porano;
FormaBarras.ShowModal;
FormaBarras.Tag:=0;
end;
FormaFormatos.Tag:=0;

FormaFormatos.Free;
FormaBarras.Free;

end;

procedure TFormaFactura.VentasporArtculo1Click(Sender: TObject);
var
desde,hastavalor:string;
begin
FormaFormatos:=TFormaFormatos.Create(Application);
FormaBarras:=TFormaBarras.Create(Application);

FormaFormatos.Rangos.Visible:=True;
FormaFormatos.Formatos.Visible:=False;
activacondiciones(true,true,False,true,False,true,true,true,true,'facturad.dbf');
TablaFacturaE.First;
desde:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
TablaFacturaE.Last;
hastavalor:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
valoresiniciales('','',desde,hastavalor);
TablaFacturaD.CancelRange;
FormaFormatos.ShowModal;
if FormaFormatos.Tag=1 then
begin
condiciones(FormaFormatos.C1.Caption,tipooperador(FormaFormatos.Operador1.Text),FormaFormatos.Valor1.Text,FormaFormatos.T1.Caption,FormaFormatos.C2.Caption,tipooperador(FormaFormatos.Operador2.Text),FormaFormatos.Valor2.Text,FormaFormatos.T2.Caption,FormaFormatos.C3.Caption,tipooperador(FormaFormatos.Operador3.Text),FormaFormatos.Valor3.Text,FormaFormatos.T3.Caption,'Y');
if FormaFormatos.IncluirDevoluciones.Checked then
begin
GeneraCorteDeCaja(FormaFormatos.Inicial.Date,FormaFormatos.Final.Date,TablaFacturaD.TableName,'devolucd.dbf','FactAuxiD.dbf',TablaFacturaD.IndexName,'S');
Concentrar(TablaAuxiliar,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_FD',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLPRO_FD','DEPRO_FD','CANTI_FD','IMPOR_FD','','','','','','','TREGI_FD','!','C','C');
end
else
Concentrar(TablaFacturaD,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_FD',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLPRO_FD','DEPRO_FD','CANTI_FD','IMPOR_FD','','','','','','','TREGI_FD','!','C','C');


poneetiquetas('Articulo','Descripción','-Cantidad','Importe','','','','','','','');
Poneanchos(20,20,20,20,20,20,20,20,20,20,0);
//FormaBarras.Caption:='Reporte de Ventas por Artículo';
//******pone el titulo
 with Sender as TMenuItem do
  begin
  desde:=Caption;
  end;
FormaBarras.Caption:=AgregaTitulo2('Reporte de '+desde,FormaFormatos.Titulo.Text);
//******termina pone el titulo

parametrosgrafica('Gráfica de Ventas por Artículo','Artículo','Total por Artículo',1);
FormaBarras.Tag:=0;
FormaBarras.Panel2.Tag:=0;
FormaBarras.botonGrafica.Tag:=2;
FormaBarras.ShowModal;
FormaBarras.Tag:=0;
end;
FormaFormatos.Tag:=0;
FormaFormatos.Free;
FormaBarras.Free;

end;

procedure TFormaFactura.ImprimePlantilla1Click(Sender: TObject);
begin
FormaFactura.Print;
end;

procedure TFormaFactura.DocumentosCancelados1Click(Sender: TObject);
var
desde,hastavalor:string;
begin
FormaFormatos:=TFormaFormatos.Create(Application);
FormaBarras:=TFormaBarras.Create(Application);

FormaFormatos.Rangos.Visible:=True;
FormaFormatos.Formatos.Visible:=False;
activacondiciones(true,true,False,true,False,true,true,true,true,'facturae.dbf');
TablaFacturaE.First;
desde:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
TablaFacturaE.Last;
hastavalor:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
valoresiniciales('','',desde,hastavalor);

FormaFormatos.ShowModal;
if FormaFormatos.Tag=1 then
begin
condiciones(FormaFormatos.C1.Caption,tipooperador(FormaFormatos.Operador1.Text),FormaFormatos.Valor1.Text,FormaFormatos.T1.Caption,FormaFormatos.C2.Caption,tipooperador(FormaFormatos.Operador2.Text),FormaFormatos.Valor2.Text,FormaFormatos.T2.Caption,FormaFormatos.C3.Caption,tipooperador(FormaFormatos.Operador3.Text),FormaFormatos.Valor3.Text,FormaFormatos.T3.Caption,'Y');
{poneetiquetas('Num. Documento','Nombre','Subtotal','Iva','Total','','','','','','');}

{Concentrar(TablaFacturaE,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',FormaFormatos.Inicial.Text,FormaFormatos.Final.Text,'CLDOC_F','NOMBR_F','IMTOD_F','CTOVE_F','&%IMTOD_F&*&%CTOVE_F&*&0.01&','','','','','','','X','','D');}
{dia:=Formaformatos.Inicial.Text;}
Concentrar(TablaFacturaE,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLDOC_F','NOMBR_F','IMTOD_F','SUBTO_F','IMIM2_F','','','','','','STATU_F','=','C','D');
Poneanchos(20,20,20,20,20,20,20,20,20,20,0);
poneetiquetas('Documento','Nombre','Total del Documento','SubTotal','IVA','','','','','','');

parametrosgrafica('Gráfica de Documentos Cancelados','Número de Documento','Total por Documento',1);
FormaBarras.Tag:=0;
FormaBarras.Panel2.Tag:=0;
FormaBarras.botonGrafica.Tag:=2;

FormaBarras.Concentrado.Clear;
//FormaBarras.Caption:='Reporte de Documentos Cancelados';{+dia;}
//******pone el titulo
 with Sender as TMenuItem do
  begin
  desde:=Caption;
  end;
FormaBarras.Caption:=AgregaTitulo2('Reporte de '+desde,FormaFormatos.Titulo.Text);
//******termina pone el titulo

FormaBarras.ShowModal;
FormaBarras.Tag:=0;
end;
FormaFormatos.Tag:=0;

FormaFormatos.Free;
FormaBarras.Free;

end;

procedure TFormaFactura.EditDIVIS_FKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
if (key=13) or (key=40) then
begin
indices:=indices+1;
cursor1;
{indice:=0;
mueveteclas;}

end;

if key=38 then
begin
indices:=indices-1;
cursor1;
end;

end;

procedure TFormaFactura.EditDIVIS_FEnter(Sender: TObject);
begin
leedivisa;
indices:=5;

end;

procedure TFormaFactura.EditDIVIS_FExit(Sender: TObject);
begin
{if Editdivis_F.Text='M.N.' then
EditVALDI_F.Text:='1.00';}
end;

procedure TFormaFactura.Temas1Click(Sender: TObject);
begin
FormaAyudaLinea:=TFormaAyudaLinea.Create(Application);
PoneAyuda(leeruta+'\ayuda\factura.rtf',0);
FormaAyudaLinea.Free;
end;

procedure TFormaFactura.CancelaMovimiento1Click(Sender: TObject);
begin

if (BotonNuevo.Tag=1) then
begin
TablaFacturaE.Delete;
borra;
ponedatos;
desactiva;
end;

if BotonCambios.Tag=1 then
begin
regresabufercambios;
TablaFacturaE.Cancel;
desactiva;
end;

activabotones(True,True,False,True,True,True,False);
BotonNuevo.Tag:=0;
BotonCambios.Tag:=0;
RangoDocumentos:=False;

end;

procedure TFormaFactura.DesgloceporMoneda1Click(Sender: TObject);
var
dia:string[12];
desde,hastavalor:string;
begin
FormaFormatos:=TFormaFormatos.Create(Application);
FormaBarras:=TFormaBarras.Create(Application);

FormaFormatos.Rangos.Visible:=True;
FormaFormatos.Formatos.Visible:=False;
activacondiciones(true,true,False,true,False,true,true,true,true,'facturae.dbf');
TablaFacturaE.First;
desde:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
TablaFacturaE.Last;
hastavalor:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
valoresiniciales('','',desde,hastavalor);

FormaFormatos.ShowModal;
if FormaFormatos.Tag=1 then
begin
condiciones(FormaFormatos.C1.Caption,tipooperador(FormaFormatos.Operador1.Text),FormaFormatos.Valor1.Text,FormaFormatos.T1.Caption,FormaFormatos.C2.Caption,tipooperador(FormaFormatos.Operador2.Text),FormaFormatos.Valor2.Text,FormaFormatos.T2.Caption,FormaFormatos.C3.Caption,tipooperador(FormaFormatos.Operador3.Text),FormaFormatos.Valor3.Text,FormaFormatos.T3.Caption,'Y');
if FormaFormatos.IncluirDevoluciones.Checked then
begin
GeneraCorteDeCaja(FormaFormatos.Inicial.Date,FormaFormatos.Final.Date,TablaFacturaE.TableName,'devoluc.dbf','FactAuxi.dbf','INUMENC','S');
//Concentrar(TablaAuxiliar,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLCLI_F','NOMBR_F','IMTOD_F','SUBTO_F','IMIM1_F','IMIM2_F','','','','','STATU_F','!','C','D');
Concentrar(TablaAuxiliar,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLDOC_F','NOMDI_F','DIVIS_F','SUBTO_F','IMTOD_F','&%SUBTO_F&*&%DIVIS_F&*&1.00&','&%IMTOD_F&*&%DIVIS_F&*&1.00&','','','','STATU_F','!','C','D');
end
else
Concentrar(TablaFacturaE,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLDOC_F','NOMDI_F','DIVIS_F','SUBTO_F','IMTOD_F','&%SUBTO_F&*&%DIVIS_F&*&1.00&','&%IMTOD_F&*&%DIVIS_F&*&1.00&','','','','STATU_F','!','C','D');
dia:=DateToStr(FormaFormatos.Inicial.Date);

poneetiquetas('Documento','Nombre','Valor Div.','SubTotal Divisa','Total Divisa','Subtotal M.N.','Total M.N.','','','','');
Poneanchos(20,20,20,20,20,20,20,20,20,20,0);
parametrosgrafica('Gráfica Desgloce por Moneda','Número de Documento','Total por Moneda',3);
FormaBarras.Tag:=0;
FormaBarras.Panel2.Tag:=0;
FormaBarras.botonGrafica.Tag:=2;

FormaBarras.Concentrado.Clear;
//FormaBarras.Caption:='Reporte Desgloce por monedas';
//******pone el titulo
 with Sender as TMenuItem do
  begin
  desde:=Caption;
  end;
FormaBarras.Caption:=AgregaTitulo2('Reporte de '+desde,FormaFormatos.Titulo.Text);
//******termina pone el titulo

FormaBarras.ShowModal;
FormaBarras.Tag:=0;
end;
FormaFormatos.Tag:=0;
FormaFormatos.Free;
FormaBarras.Free;

end;

procedure TFormaFactura.EditDESFI_FKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
if (key=13) then
Detalle.SetFocus;
end;

procedure TFormaFactura.DetalleKeyPress(Sender: TObject; var Key: Char);
begin
key:=CambiaLetras(key);
end;

procedure TFormaFactura.DetalleEnter(Sender: TObject);
begin
//Facturable:=False;
Detalle.SelectedIndex:=0;
end;



procedure TFormaFactura.Edit1Exit(Sender: TObject);
var
camb:real;
begin
camb:=0;
if CAMBIO_F.Text<>'' then
begin
camb:=StrTofloat(CAMBIO_F.Text)-total1;

SuCambio.Caption:='Cambio '+Convierte('###,##0.00',FloatToStr(camb),'$');

end;
end;


procedure TFormaFactura.CAMBIO_FExit(Sender: TObject);
var
camb:real;
begin
camb:=0;
if CAMBIO_F.Text<>'' then
begin
camb:=StrTofloat(CAMBIO_F.Text)-total1;

SuCambio.Caption:='Camb.'+Convierte('###,##0.00',FloatToStr(camb),'$');

end;
end;


procedure TFormaFactura.CAMBIO_FKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
var
camb:real;
begin
if key=117 then
begin

camb:=0;
if CAMBIO_F.Text<>'' then
begin
camb:=StrTofloat(CAMBIO_F.Text)-total1;

SuCambio.Caption:='Cambio '+Convierte('###,##0.00',FloatToStr(camb),'$');

end;
end;//if f6

if key=13 then
CAMBIO_FExit(Sender);

end;

procedure TFormaFactura.VerFunciones1Click(Sender: TObject);
begin
MuestraMensaje('Ctrl+F1    Ver Funciones'+Char(13)+
               'Ctrl+F4    Inserta Comentario'+Char(13)+
               'Ctrl+N     Nuevo Documento'+Char(13)+
               'Ctrl+G     Guarda Documento'+Char(13)+
               'Ctrl+F5    Introducir Efectivo'+Char(13)+
               'Ctrl+F6    Calcular Cambio'+Char(13)+
               'Ctrl+F7    Inicia Captura de Partidas'+Char(13)+
               'Ctrl+B     Buscar'+Char(13)+
               'Ctrl+I     Imprimir'+Char(13)

               );

end;

procedure TFormaFactura.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin

if Shift=[ssCtrl] then
begin
case key of
65:
begin
TablaFacturaE.Prior;
ponedatos;
end;

83:begin
TablaFacturaE.Next;
ponedatos;
end;
end;

end;


try
if key=118 then
Detalle.SetFocus;


if key=117 then
CAMBIO_FExit(Sender);

if key=119 then
TipoPago.SetFocus;

if key=116 then
begin
try
CAMBIO_F.SetFocus;
except
end;
end;

{if key=120 then
begin
  BotonNuevoClick(Sender);

end;

if key=121 then
begin
BotonGuardarClick(Sender);
Detalle.SetFocus;
end;}

except
end;
end;

procedure TFormaFactura.DetalleColExit(Sender: TObject);
begin
   if Detalle.SelectedIndex=3 then
   begin
   TablaDeta.Edit;
   TablaDeta.FieldByName('Importe').AsFloat:=TablaDeta.FieldByName('Cantidad').AsFloat*TablaDeta.FieldByName('Precio').AsFloat;
   TablaDeta.FieldByName('Importe').AsFloat:=TablaDeta.FieldByName('Importe').AsFloat-(TablaDeta.FieldByName('Importe').AsFloat*TablaDeta.FieldByName('Descuento').AsFloat/100);
   TablaDeta.Post;
   end;

end;

procedure TFormaFactura.UtilidadporProducto1Click(Sender: TObject);
var
desde,hastavalor:string;
ExisteReporte:integer;
EL_IVA:string;
begin

//PRECIO*(1-(DESCUENTO/100))*(1-(DESCUENTO2/100))*(1-(DESCUENTO3/100))
//EL_IVA:=FloatToStr(1/(1+(PIVA1_F/100)));
//EL_IVA:=1/EL_IVA;


with Sender as TMenuItem do
ReporteSIF(Caption,'CLDOC_FD','FEDOC_FD','FEDOC_FD',TablaFacturaE.FieldByName('CLDOC_F').AsString,TablaFacturaD,
           '$'+Caption+char(13)+
//         '& Select CLDOC_FD,CLPRO_FD,CANTI_FD,CANTI_FD*COPRO_FD,CANTI_FD*(PUNPR_FD*(1-(PDES1_FD/100))*(1-(PDES2_FD/100))),(CANTI_FD*(PUNPR_FD*(1-(PDES1_FD/100))*(1-(PDES2_FD/100))*(1-(PDES3_FD/100))))-(CANTI_FD*COPRO_FD),FEDOC_FD from "'+ruta(8)+'\'+TablaFacturad.TableName+'"'+char(13)+
           '& Select I.LIPRO_I,F.CLDOC_FD,F.CLPRO_FD,F.CANTI_FD,F.CANTI_FD*F.COPRO_FD,(F.CANTI_FD*F.PREDE_FD),(F.CANTI_FD*F.PREDE_FD)-(F.CANTI_FD*F.COPRO_FD),F.FEDOC_FD,I.CLPRO_I from "'+ruta(8)+'\'+TablaFacturad.TableName+'" AS F,'+'"'+ruta(8)+'\'+TablaInventario.TableName+'" as I '+char(13)+
           '?(TREGI_FD<>"C" OR TREGI_FD IS NULL) and (F.CLPRO_FD=I.CLPRO_I) '+'¿'+char(13)+
           '!I.LIPRO_I,F.cldoc_fd'+char(13)+
           '>LIPRO_I'+char(13)+
           '%c         e          c            t               t              t                  t             c'+char(13)+
           '#LINEA     DOCUMENTO  PRODUCTO     CANTIDAD        COSTO_X_CANT.  PRECIO_X_CANT.     UTILIDAD      FECHA     '+char(13)+
           '@'+char(13)
           ,0,'');

ponedatos;

{FormaFormatos:=TFormaFormatos.Create(Application);
FormaBarras:=TFormaBarras.Create(Application);

FormaFormatos.Rangos.Visible:=True;
FormaFormatos.Formatos.Visible:=False;
activacondiciones(true,true,False,true,False,true,true,true,true,'facturad.dbf');
TablaFacturaE.First;
desde:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
TablaFacturaE.Last;
hastavalor:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
valoresiniciales('','',desde,hastavalor);
//valoresiniciales('','','','');
 with Sender as TMenuItem do
  begin
  desde:=Caption;
  end;

//ExisteReporte:=CamposReporte(FormaFactura.Name+desde,'CLDOC_FD','CLPRO_FD','CANTI_FD','&%CANTI_FD&*&%COPRO_FD&*1.00&','&%CANTI_FD&*&%PUNPR_FD&*1.00&','&%CANTI_FD&*&%PUNPR_FD&/&1.00&-&%CANTI_FD&*&%COPRO_FD&/&1.00&','','','','TREGI_FD','!','C','DC',
//'Linea','Documento','Clave','-Cantidad','CostoxCantidad','PrecioxCantidad','Utilidad','','','','');

//if ExisteReporte=1 then
//MuestraMensaje('existe '+FormaFactura.Name+desde);

FormaFormatos.ShowModal;

if FormaFormatos.Tag=1 then
begin
condiciones(FormaFormatos.C1.Caption,tipooperador(FormaFormatos.Operador1.Text),FormaFormatos.Valor1.Text,FormaFormatos.T1.Caption,FormaFormatos.C2.Caption,tipooperador(FormaFormatos.Operador2.Text),FormaFormatos.Valor2.Text,FormaFormatos.T2.Caption,FormaFormatos.C3.Caption,tipooperador(FormaFormatos.Operador3.Text),FormaFormatos.Valor3.Text,FormaFormatos.T3.Caption,'Y');
if FormaFormatos.IncluirDevoluciones.Checked then
begin
GeneraCorteDeCaja(FormaFormatos.Inicial.Date,FormaFormatos.Final.Date,TablaFacturaD.TableName,'devolucd.dbf','FactAuxiD.dbf',TablaFacturaD.IndexName,'S');
//lovable
Concentrar(TablaAuxiliar,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_FD',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'%2CLPRO_FD','CLDOC_FD','CLPRO_FD','CANTI_FD','&%CANTI_FD&*&%COPRO_FD&*1.00&','&CANTI_FD&*&%PUNPR_FD&*0.869565&','&%CANTI_FD&*&%PUNPR_FD&*&0.869565&-&%CANTI_FD&*&%COPRO_FD&','&%PUNPR_FD*0.869565&/&%COPRO_FD&-1.0&','&CANTI_FD&*&%PUNPR_FD&*0.869565&*0.15&','','TREGI_FD','!','C','DC');
//Concentrar(TablaAuxiliar,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_FD',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLPRO_FD','CLDOC_FD','CLPRO_FD','CANTI_FD','&%CANTI_FD&*&%COPRO_FD&/(&PIVA1_FD*0.01&+1&)','&CANTI_FD&*&%PUNPR_FD&/(&PIVA1_FD*0.01&+1&)','&CANTI_FD*(PUNPR_FD-COPRO_FD)/(PIVA1_FD*0.01+1)','&%PUNPR_FD*1.0&/&%COPRO_FD&-1.0&','&CANTI_FD&*&%PUNPR_FD&*1.0&*1.0&','','TREGI_FD','!','C','DC');
end
else
begin
//lovable
Concentrar(TablaFacturaD,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_FD',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'%2CLPRO_FD','CLDOC_FD','CLPRO_FD','CANTI_FD','&%CANTI_FD&*&%COPRO_FD&*1.00&','&CANTI_FD&*&%PUNPR_FD&*0.869565&','&%CANTI_FD&*&%PUNPR_FD&*&0.869565&-&%CANTI_FD&*&%COPRO_FD&','&%PUNPR_FD*0.869565&/&%COPRO_FD&-1.0&','&CANTI_FD&*&%PUNPR_FD&*0.869565&*0.15&','','TREGI_FD','!','C','DC');
//Concentrar(TablaFacturaD,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_FD',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLPRO_FD','CLDOC_FD','CLPRO_FD','CANTI_FD','&%CANTI_FD&*&%COPRO_FD&/(&PIVA1_FD*0.01&+1&)','&CANTI_FD&*&%PUNPR_FD&/(&PIVA1_FD*0.01&+1&)','&CANTI_FD*(PUNPR_FD-COPRO_FD)/(PIVA1_FD*0.01+1)','&%PUNPR_FD*1.0&/&%COPRO_FD&-1.0&','&CANTI_FD&*&%PUNPR_FD&*1.0&*1.0&','','TREGI_FD','!','C','DC');
end;

poneetiquetas('Linea','Documento','-Clave','%Cantidad','CostoxCantidad','PrecioxCantidad','Utilidad','%Utilidad','','','');
Poneanchos(10,15,15,15,15,15,15,15,15,15,0);
parametrosgrafica('Gráfica de Ventas y Utilidades','Número de Documento','Total por Documento',2);
FormaBarras.Tag:=0;
FormaBarras.Panel2.Tag:=0;
FormaBarras.botonGrafica.Tag:=2;

FormaBarras.Concentrado.Clear;
//FormaBarras.Caption:='Reporte de Ventas y Utilidades';
//******pone el titulo
FormaBarras.Caption:=AgregaTitulo2('Reporte de '+desde,FormaFormatos.Titulo.Text);
//******termina pone el titulo

FormaBarras.ShowModal;
FormaBarras.Tag:=0;
end;
FormaFormatos.Tag:=0;
FormaFormatos.Free;
FormaBarras.Free;
}
end;

procedure TFormaFactura.FacturadeCierre1Click(Sender: TObject);
var
inicio,fin,ultimo,UltiAux:integer;
Aux:string[1];
Tabla:TTable;
FacturaCreada:string[12];
begin
UltiAux:=UltimoDocumento;
UltimoDocumento:=0;
try
DialogoImprimir:=TDialogoImprimir.Create(Application);
inicio:=0;
fin:=0;
RangoDocumentos:=False;
DialogoImprimir.Tag:=0;
DialogoImprimir.PrimeraPagina.Text:=DatetoStr(date);
DialogoImprimir.UltimaPagina.Text:=DatetoStr(date);
DialogoImprimir.ShowModal;

if DialogoImprimir.Tag=1 then
begin

Aux:=Base.Text;
Orig:=Aux+EditCLDOC_F.Text;


TablaFacturaE.Last;
fin:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger;
while not TablaFacturaE.BOF do
begin
if TablaFacturaE.FieldByName('FEDOC_F').AsDateTime>=StrToDate(DialogoImprimir.PrimeraPagina.Text)then
inicio:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger
else
break;;

TablaFacturaE.Prior;
end;//while
if inicio<>0 then
begin

if LeeDetallecierre(IntToStr(inicio),IntTostr(fin),DialogoImprimir.PrimeraPagina.Text)=0 then
begin
MuestraMensaje('No hay Partidas para estas Fechas, puede ser que ya se Genero la Factura de Cierre');
Base.Text:='Remisión';
BaseChange(Sender);

exit;
end;

//***************************************
PrecioNumero:=0;
Hora.Caption:=TimeToStr(Time);
{*********}
TablaFacturaE.Last;
Ultimo:=TablaFacturaE.FieldByName('CLDOC_F').AsInteger;
TablaFacturae.Insert;

{***********************}

if TablaFacturaE.State=dsInsert then
begin

TablaFacturae.FieldByName('CLDOC_F').AsInteger:=Ultimo+1;
TablaFacturae.FieldByName('CLVEN_F').AsString:=ultimovendedor;
TablaFacturae.Post;
saldoanterior:=0;
borradatoscliente;
//borra;
BotonNuevo.Tag:=1;
BotonCambios.Tag:=0;
Caja.Enabled:=True;
local:=True;
TablaFacturae.Edit;
EditCLCLI_F.Visible:=True;
activa;
EditFEDOC_F.Text:=DateToStr(Date);
configuracion;
indice:=0;
sig:=1;
{****totales****}
SumarTotal.Caption:=convierte('###,###,##0.00','0','$');
ImpuestoValor.Caption:=convierte('###,###,##0.00','0','$');
TotalFact.Caption:=convierte('###,###,##0.00','0','$');
{**************}
activabotones(False,False,True,False,False,False,True);

//EditCLDOC_F.SetFocus;
EditCLCLI_F.SetFocus;
EditCLCLI_F.Text:='1';
TablaFacturaE.FieldByName('CLCLI_F').AsString:='100';
TablaFacturaE.FieldByName('FEDOC_F').AsString:=DialogoImprimir.PrimeraPagina.Text;
TablaFacturaE.FieldByName('IMIM1_F').AsString:=EditIMIM1_F.Text;
TablaFacturaE.FieldByName('DESFI_F').AsString:=EditDESFI_F.Text;


end;//if insert

//******************************



//***********manda los datos a la factura
Base.Tag:=1;
{while not TablaFacturaD.EOF do
begin
TablaFacturaD.Edit;
TablaFacturaD.FieldByName('TREGI_FD').AsString:='F';
TablaFacturaD.Post;
TablaFacturaD.Next;
end;}

bufercambios('C');
TablaFacturaE.Delete;
generadocumento('F');
TablaFacturaD.First;
activa;
//EditCLDOC_F.SetFocus;
EditCLCLI_F.SetFocus;
local:=True;
TablaFacturaE.Edit;
end;//if iicio<>0

end;//if dialogoimprimir

DialogoImprimir.Free;
except
end;
//UltimoDocumento:=UltiAux;

//***********guarda la factura de cierre
//MuestraMensaje('esto lo va a guardar');
BotonGuardarClick(Sender);
//MuestraMensaje('ya guardo');
FacturaCreada:=EditCLDOC_F.Text;

TablaFacturaE.Edit;
//MuestraMensaje('CI('+IntToStr(inicio)+'-'+IntToStr(fin)+')');
TablaFacturaE.FieldByName('CLPED_F').AsString:='CI('+IntToStr(inicio)+'-'+IntToStr(fin)+')';
TablaFacturaE.Post;


Base.Text:='Remisión';
BaseChange(Sender);


//***********marca las remisiones que se utilizaron****
try
Tabla:=TTable.Create(Application);
Tabla.DatabaseName:=ruta(8);
//Tabla.TableName:='Remision.dbf';
Tabla.TableName:='Remision.dbf';
Tabla.IndexName:='INUMENC';
Tabla.Open;
Tabla.SetRange([inicio],[fin]);
While not Tabla.Eof do
begin
Tabla.Edit;

Tabla.FieldByName('REMIS_F').AsString:='F'+FacturaCreada;
Tabla.Post;
Tabla.Next;
end;//while


Tabla.Close;
Tabla.Free;
except
end;

MuestraMensaje('Genero la Factura '+FacturaCreada+' Puede Revisarla en el Módulo de Facturación de SIF');


end;

procedure TFormaFactura.CortedeCaja1Click(Sender: TObject);
var
dia:string[12];
desde,hastavalor:string;

begin
FormaFormatos:=TFormaFormatos.Create(Application);
FormaBarras:=TFormaBarras.Create(Application);

FormaFormatos.Rangos.Visible:=True;
FormaFormatos.Formatos.Visible:=False;
activacondiciones(true,true,False,true,False,true,true,true,true,'facturae.dbf');
TablaFacturaE.First;
desde:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
TablaFacturaE.Last;
hastavalor:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
valoresiniciales('','','','');

FormaFormatos.ShowModal;

if FormaFormatos.Tag=1 then
begin
GeneraCorteDeCaja(FormaFormatos.Inicial.Date,FormaFormatos.Final.Date,TablaFacturaE.TableName,'devoluc.dbf','FactAuxi.dbf',TablaFacturaE.IndexName,'S');

condiciones(FormaFormatos.C1.Caption,tipooperador(FormaFormatos.Operador1.Text),FormaFormatos.Valor1.Text,FormaFormatos.T1.Caption,FormaFormatos.C2.Caption,tipooperador(FormaFormatos.Operador2.Text),FormaFormatos.Valor2.Text,FormaFormatos.T2.Caption,FormaFormatos.C3.Caption,tipooperador(FormaFormatos.Operador3.Text),FormaFormatos.Valor3.Text,FormaFormatos.T3.Caption,'Y');
{poneetiquetas('Num. Documento','Nombre','Subtotal','Iva','Total','','','','','','');}
{Concentrar(TablaFacturaE,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',FormaFormatos.Inicial.Text,FormaFormatos.Final.Text,'CLDOC_F','NOMBR_F','IMTOD_F','CTOVE_F','&%IMTOD_F&*&%CTOVE_F&*&0.01&','','','','','','','X','','D');}
dia:=DateToStr(FormaFormatos.Inicial.Date);
Concentrar(TablaAuxiliar,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_F',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'PAGOX_F','CLDOC_F','NOMBR_F','IMTOD_F','SUBTO_F','PAGOX_F','','','','','STATU_F','!','C','DC');
poneetiquetas('','Documento','-Nombre','Total del Documento','SubTotal','-Tipo de Pago','','','','','');
Poneanchos(0,20,20,20,20,20,20,20,20,20,0);
parametrosgrafica('Gráfica de Corte de Caja','Número de Documento','Total por Documento',1);

FormaBarras.Tag:=0;
FormaBarras.Panel2.Tag:=0;
FormaBarras.botonGrafica.Tag:=2;

FormaBarras.Concentrado.Clear;
//FormaBarras.Caption:='Reporte de Documentos por Periodo ';

//******pone el titulo
 with Sender as TMenuItem do
  begin
  FormaBarras.Caption:=AgregaTitulo2('Reporte de '+Caption,FormaFormatos.Titulo.Text);
  desde:=Caption;
  end;
//FormaBarras.Caption:=AgregaTitulo2('Reporte de '+desde,FormaFormatos.Titulo.Text);
//******termina pone el titulo

FormaBarras.ShowModal;
FormaBarras.Tag:=0;
end;
FormaFormatos.Tag:=0;
FormaFormatos.Free;
FormaBarras.Free;

end;

procedure TFormaFactura.CAMBIO_FEnter(Sender: TObject);
begin
sumatotal;
end;

procedure TFormaFactura.RangodeDocumentos1Click(Sender: TObject);
var
aux:string[1];
op:char;
begin

MovimientoBorrado:=0;
FormaRango:=TFormaRango.Create(Application);
if Base.Text='Cotización' then
begin
FormaRango.Factura.Enabled:=True;
FormaRango.Remision.Enabled:=True;
FormaRango.Pedido.Enabled:=True;
end;

if Base.Text='Pedido' then
begin
FormaRango.Factura.Enabled:=True;
FormaRango.Remision.Enabled:=True;
FormaRango.Pedido.Enabled:=False;
end;

if Base.Text='Remisión' then
begin
FormaRango.Factura.Enabled:=True;
FormaRango.Remision.Enabled:=False;
FormaRango.Pedido.Enabled:=False;
end;

FormaRango.Tag:=0;
FormaRango.ShowModal;


if FormaRango.Factura.Checked=True then
Aux:=FormaRango.Factura.Caption;

if FormaRango.Remision.Checked=True then
Aux:=FormaRango.Remision.Caption;

if FormaRango.Pedido.Checked=True then
Aux:=FormaRango.Pedido.Caption;

if FormaRango.Tag =1 then
begin
//Aux:=Base.Text;
DatoRango:=FormaRango.Edit1.Text;
Orig:=Aux+EditCLDOC_F.Text;
Orig2:=Base.Text;
RangoDocumentos:=True;
Base.Tag:=1;
bufercambios('C');
op:=Aux[1];
generadocumento(op);
activa;
EditCLDOC_F.SetFocus;
local:=True;
TablaFacturaE.Edit;
activabotones(False,False,True,False,False,False,True);
if TablaDeta.RecordCount-1<=0 then
begin
MuestraMensaje('No se puede generar una factura no hay documentos en este rango...');
CancelaMovimiento1Click(Sender);
end;
end;

FormaRango.Free;
end;

procedure TFormaFactura.ConfigurarCaja1Click(Sender: TObject);
var
arch:File of RegistroCaja;
datos:RegistroCaja;

begin
FormaCaja:=TFormaCaja.Create(Application);
FormaCaja.Tag:=0;
FormaCaja.Ruta.Caption:=leeruta;
FormaCaja.NumeroCaja.Text:='';
FormaCaja.ShowModal;
if FormaCaja.Tag=1 then
begin

Assignfile(arch,leeruta+'\caja.cnf');
if FileExists(leeruta+'\caja.cnf') then
Reset(arch)
else
ReWrite(arch);

//MuestraMensaje('seva aGuardar '+FormaCaja.ClaveVendedor.Text);
seek(arch,FormaCaja.NumeroCaja.Value-1);
datos.No_caja:=FormaCaja.NoCaja.Text;
datos.Cl_vendedor:=FormaCaja.ClaveVendedor.Text;
datos.Nom_formato:=FormaCaja.Formato.Text;

write(arch,datos);
CajaLocal:= FormaCaja.NoCaja.Text;
VendedorDefault:=FormaCaja.ClaveVendedor.Text;
if FormaCaja.Formato.Text<>'' then
nombreformato:=leeruta+'\consulta\'+FormaCaja.Formato.Text;
CloseFile(arch);
end;
FormaCaja.Free;

end;

procedure TFormaFactura.FormShow(Sender: TObject);
var
arch2:File of RegistroCaja;
datos:RegistroCaja;
linea:string;
arch:TextFile;
begin
UsuarioActual('-1');
Update;
CajaLocal:='';
if FileExists(leeruta+'\caja.cnf') then
begin
Assignfile(arch2,leeruta+'\caja.cnf');
Reset(arch2);
Read(arch2,datos);
CajaLocal:=datos.No_caja;
VendedorDefault:=datos.Cl_vendedor;

CloseFile(arch2);
end;//if

if ruta(6)='SI' then IntegrarMI:='S' else IntegrarMI:='N';

if FileExists(ruta(8)+'\pagos.cnf') then
begin
Assignfile(arch,ruta(8)+'\pagos.cnf');
Reset(arch);
TipoPago.Clear;
while not eof(arch) do
begin
Readln(arch,LINEA);
TipoPago.Items.Add(linea);
end;
CloseFile(arch);
end;//if

if caso2(StrToInt(usuario.Caption),44) then
 Reportes1.Enabled:=True
 else
 Reportes1.Enabled:=False;


end;

procedure TFormaFactura.DetalleDrawColumnCell(Sender: TObject;
  const Rect: TRect; DataCol: Integer; Column: TColumn;
  State: TGridDrawState);
begin
if Digitos>0 then
Detalle.Fields[DataCol].OnGetText:=MyOnGetText;
end;





procedure TFormaFactura.TipoPagoDblClick(Sender: TObject);
begin
winExec(PChar('notepad.exe '+ruta(8)+'\pagos.cnf'),SW_SHOWNOACTIVATE);

end;

procedure TFormaFactura.UtilidadporProductoConcentrado1Click(
  Sender: TObject);
var
desde,hastavalor:string;
ExisteReporte:integer;
begin

FormaFormatos:=TFormaFormatos.Create(Application);
FormaBarras:=TFormaBarras.Create(Application);

FormaFormatos.Rangos.Visible:=True;
FormaFormatos.Formatos.Visible:=False;
activacondiciones(true,true,False,true,False,true,true,true,true,'facturad.dbf');
TablaFacturaE.First;
desde:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
TablaFacturaE.Last;
hastavalor:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
valoresiniciales('','',desde,hastavalor);
//valoresiniciales('','','','');
 with Sender as TMenuItem do
  begin
  desde:=Caption;
  end;

ExisteReporte:=CamposReporte(FormaFactura.Name+desde,'CLDOC_FD','CLPRO_FD','CANTI_FD','&%CANTI_FD&*&%COPRO_FD&*1.00&','&%CANTI_FD&*&%PUNPR_FD&*1.00&','&%CANTI_FD&*&%PUNPR_FD&/&1.00&-&%CANTI_FD&*&%COPRO_FD&/&1.00&','','','','TREGI_FD','!','C','DC',
'Linea','Documento','Clave','-Cantidad','CostoxCantidad','PrecioxCantidad','Utilidad','','','','');

//if ExisteReporte=1 then
//MuestraMensaje('existe '+FormaFactura.Name+desde);

FormaFormatos.ShowModal;

if FormaFormatos.Tag=1 then
begin
condiciones(FormaFormatos.C1.Caption,tipooperador(FormaFormatos.Operador1.Text),FormaFormatos.Valor1.Text,FormaFormatos.T1.Caption,FormaFormatos.C2.Caption,tipooperador(FormaFormatos.Operador2.Text),FormaFormatos.Valor2.Text,FormaFormatos.T2.Caption,FormaFormatos.C3.Caption,tipooperador(FormaFormatos.Operador3.Text),FormaFormatos.Valor3.Text,FormaFormatos.T3.Caption,'Y');
if FormaFormatos.IncluirDevoluciones.Checked then
begin
GeneraCorteDeCaja(FormaFormatos.Inicial.Date,FormaFormatos.Final.Date,TablaFacturaD.TableName,'devolucd.dbf','FactAuxiD.dbf',TablaFacturaD.IndexName,'S');
//lovable
Concentrar(TablaAuxiliar,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_FD',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'%2CLPRO_FD','','CANTI_FD','&%CANTI_FD&*&%COPRO_FD&*1.00&','&CANTI_FD&*&%PUNPR_FD&*0.869565&','&%CANTI_FD&*&%PUNPR_FD&*&0.869565&-&%CANTI_FD&*&%COPRO_FD&','&CANTI_FD&*&%PUNPR_FD&*0.869565&*0.15&','','','','TREGI_FD','!','C','C');
//Concentrar(TablaAuxiliar,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_FD',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'%2CLPRO_FD','','CANTI_FD','&%CANTI_FD&*&%COPRO_FD&*1.00&','&CANTI_FD&*&%PUNPR_FD&*1.0&','&%CANTI_FD&*&%PUNPR_FD&*&1.0&-&%CANTI_FD&*&%COPRO_FD&','&CANTI_FD&*&%PUNPR_FD&*1.0&*1.0&','','','','TREGI_FD','!','C','C');
end
else
begin
//lovable
Concentrar(TablaFacturaD,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_FD',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'%2CLPRO_FD','','CANTI_FD','&%CANTI_FD&*&%COPRO_FD&*1.00&','&CANTI_FD&*&%PUNPR_FD&*0.869565&','&%CANTI_FD&*&%PUNPR_FD&*&0.869565&-&%CANTI_FD&*&%COPRO_FD&','&CANTI_FD&*&%PUNPR_FD&*0.869565&*0.15&','','','','TREGI_FD','!','C','C');
//Concentrar(TablaFacturaD,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_FD',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'%2CLPRO_FD','','CANTI_FD','&%CANTI_FD&*&%COPRO_FD&*1.00&','&CANTI_FD&*&%PUNPR_FD&*1.0&','&%CANTI_FD&*&%PUNPR_FD&*&1.0&-&%CANTI_FD&*&%COPRO_FD&','&CANTI_FD&*&%PUNPR_FD&*1.0&*1.0&','','','','TREGI_FD','!','C','C');
end;

poneetiquetas('Linea','','%Cantidad','CostoxCantidad','PrecioxCantidad','Utilidad','I.V.A.','','','','');
Poneanchos(10,0,15,15,15,15,15,15,15,15,0);
parametrosgrafica('Gráfica de Ventas y Utilidades','Número de Documento','Total por Documento',2);
FormaBarras.Tag:=0;
FormaBarras.Panel2.Tag:=0;
FormaBarras.botonGrafica.Tag:=2;

FormaBarras.Concentrado.Clear;
//FormaBarras.Caption:='Reporte de Ventas y Utilidades';
//******pone el titulo
FormaBarras.Caption:=AgregaTitulo2('Reporte de '+desde,FormaFormatos.Titulo.Text);
//******termina pone el titulo

FormaBarras.ShowModal;
FormaBarras.Tag:=0;
end;
FormaFormatos.Tag:=0;
FormaFormatos.Free;
FormaBarras.Free;

end;

procedure TFormaFactura.CuentaporCobrar1Click(Sender: TObject);
begin
if Base.Text='Remisión' then
BuscaCxC;
end;

procedure TFormaFactura.VentadeTiendaporProducto1Click(Sender: TObject);
var
desde,hastavalor:string;
ExisteReporte:integer;
begin

FormaFormatos:=TFormaFormatos.Create(Application);
FormaBarras:=TFormaBarras.Create(Application);

FormaFormatos.Rangos.Visible:=True;
FormaFormatos.Formatos.Visible:=False;
activacondiciones(true,true,False,true,False,true,true,true,true,'facturad.dbf');
TablaFacturaE.First;
desde:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
TablaFacturaE.Last;
hastavalor:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
valoresiniciales('','',desde,hastavalor);
//valoresiniciales('','','','');
 with Sender as TMenuItem do
  begin
  desde:=Caption;
  end;

//ExisteReporte:=CamposReporte(FormaFactura.Name+desde,'CLDOC_FD','CLPRO_FD','CANTI_FD','&%CANTI_FD&*&%COPRO_FD&*1.00&','&%CANTI_FD&*&%PUNPR_FD&*1.00&','&%CANTI_FD&*&%PUNPR_FD&/&1.00&-&%CANTI_FD&*&%COPRO_FD&/&1.00&','','','','TREGI_FD','!','C','DC',
//'Linea','Documento','Clave','-Cantidad','CostoxCantidad','PrecioxCantidad','Utilidad','','','','');

//if ExisteReporte=1 then
//MuestraMensaje('existe '+FormaFactura.Name+desde);

FormaFormatos.ShowModal;

if FormaFormatos.Tag=1 then
begin
condiciones(FormaFormatos.C1.Caption,tipooperador(FormaFormatos.Operador1.Text),FormaFormatos.Valor1.Text,FormaFormatos.T1.Caption,FormaFormatos.C2.Caption,tipooperador(FormaFormatos.Operador2.Text),FormaFormatos.Valor2.Text,FormaFormatos.T2.Caption,FormaFormatos.C3.Caption,tipooperador(FormaFormatos.Operador3.Text),FormaFormatos.Valor3.Text,FormaFormatos.T3.Caption,'Y');
if FormaFormatos.IncluirDevoluciones.Checked then
begin
GeneraCorteDeCaja(FormaFormatos.Inicial.Date,FormaFormatos.Final.Date,TablaFacturaD.TableName,'devolucd.dbf','FactAuxiD.dbf',TablaFacturaD.IndexName,'S');
//lovable
Concentrar(TablaAuxiliar,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_FD',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLPRO_FD','CLDOC_FD','DEPRO_FD','NOMDI_FD','CANTI_FD','&%CANTI_FD&*&%COPRO_FD&*1.15&','&CANTI_FD&*&%PUNPR_FD&*1.00&','&%CANTI_FD&*&%PUNPR_FD&*&1.00&-&%CANTI_FD&*&%COPRO_FD&*&1.15&','&(CANTI_FD*PUNPR_FD-CANTI_FD*COPRO_FD*1.15)/(CANTI_FD*PUNPR_FD)','','TREGI_FD','!','C','D');
//Concentrar(TablaAuxiliar,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_FD',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLPRO_FD','CLDOC_FD','CLPRO_FD','CANTI_FD','&%CANTI_FD&*&%COPRO_FD&/(&PIVA1_FD*0.01&+1&)','&CANTI_FD&*&%PUNPR_FD&/(&PIVA1_FD*0.01&+1&)','&CANTI_FD*(PUNPR_FD-COPRO_FD)/(PIVA1_FD*0.01+1)','&%PUNPR_FD*1.0&/&%COPRO_FD&-1.0&','&CANTI_FD&*&%PUNPR_FD&*1.0&*1.0&','','TREGI_FD','!','C','DC');
end
else
begin
//lovable
//Concentrar(TablaFacturaD,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_FD',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLPRO_FD','CLDOC_FD','DEPRO_FD','NOMDI_FD','CANTI_FD','&%CANTI_FD&*&%COPRO_FD&*1.15&','&CANTI_FD&*&%PUNPR_FD&*1.00&','&%CANTI_FD&*&%PUNPR_FD&*&1.00&-&%CANTI_FD&*&%COPRO_FD&*&1.15&','&(CANTI_FD*PUNPR_FD-CANTI_FD*COPRO_FD*1.15)/(CANTI_FD*PUNPR_FD)','','TREGI_FD','!','C','D');
//Concentrar(TablaFacturaD,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_FD',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLPRO_FD','CLDOC_FD','CLPRO_FD','CANTI_FD','&%CANTI_FD&*&%COPRO_FD&/(&PIVA1_FD*0.01&+1&)','&CANTI_FD&*&%PUNPR_FD&/(&PIVA1_FD*0.01&+1&)','&CANTI_FD*(PUNPR_FD-COPRO_FD)/(PIVA1_FD*0.01+1)','&%PUNPR_FD*1.0&/&%COPRO_FD&-1.0&','&CANTI_FD&*&%PUNPR_FD&*1.0&*1.0&','','TREGI_FD','!','C','DC');
GeneraCorteDeCaja(FormaFormatos.Inicial.Date,FormaFormatos.Final.Date,TablaFacturaD.TableName,'devolucd.dbf','FactAuxiD.dbf',TablaFacturaD.IndexName,'N');
//lovable
Concentrar(TablaAuxiliar,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_FD',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLPRO_FD','CLDOC_FD','DEPRO_FD','NOMDI_FD','CANTI_FD','&%CANTI_FD&*&%COPRO_FD&*1.15&','&CANTI_FD&*&%PUNPR_FD&*1.00&','&%CANTI_FD&*&%PUNPR_FD&*&1.00&-&%CANTI_FD&*&%COPRO_FD&*&1.15&','&(CANTI_FD*PUNPR_FD-CANTI_FD*COPRO_FD*1.15)/(CANTI_FD*PUNPR_FD)','','TREGI_FD','!','C','D');
//Concentrar(TablaAuxiliar,FormaFormatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_FD',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CLPRO_FD','CLDOC_FD','CLPRO_FD','CANTI_FD','&%CANTI_FD&*&%COPRO_FD&/(&PIVA1_FD*0.01&+1&)','&CANTI_FD&*&%PUNPR_FD&/(&PIVA1_FD*0.01&+1&)','&CANTI_FD*(PUNPR_FD-COPRO_FD)/(PIVA1_FD*0.01+1)','&%PUNPR_FD*1.0&/&%COPRO_FD&-1.0&','&CANTI_FD&*&%PUNPR_FD&*1.0&*1.0&','','TREGI_FD','!','C','DC');

end;

poneetiquetas('UPC','Documento','-Clave','-Color','%Cantidad','CostoxCantidad','PrecioxCantidad','Utilidad','%Utilidad','','');
Poneanchos(10,10,12,6,15,15,15,15,15,15,0);
parametrosgrafica('Gráfica de Ventas y Utilidades','Número de Documento','Total por Documento',2);
FormaBarras.Tag:=0;
FormaBarras.Panel2.Tag:=0;
FormaBarras.botonGrafica.Tag:=2;

FormaBarras.Concentrado.Clear;
//FormaBarras.Caption:='Reporte de Ventas y Utilidades';
//******pone el titulo
FormaBarras.Caption:=AgregaTitulo2('Reporte de '+desde,FormaFormatos.Titulo.Text);
//******termina pone el titulo

FormaBarras.ShowModal;
FormaBarras.Tag:=0;
end;
FormaFormatos.Tag:=0;
FormaFormatos.Free;
FormaBarras.Free;

end;



procedure TFormaFactura.FormResize(Sender: TObject);
begin
BotonSalir.Left:=Panel1.Width-BotonSalir.Width-4;
end;

procedure TFormaFactura.TablaDetaAfterDelete(DataSet: TDataSet);
begin
if  BotonGuardar.Enabled then
begin
SumaTotal;
end;

end;

procedure TFormaFactura.Artculosmsvendidos1Click(Sender: TObject);
var
desde,hastavalor:string;
begin
FormaFormatos:=TFormaFormatos.Create(Application);
FormaBarras:=TFormaBarras.Create(Application);

FormaFormatos.Rangos.Visible:=True;
FormaFormatos.Formatos.Visible:=False;
activacondiciones(true,true,False,true,False,true,true,true,true,'facturad.dbf');
TablaFacturaE.First;
desde:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
TablaFacturaE.Last;
hastavalor:=TablaFacturaE.FieldByName('CLDOC_F').AsString;
valoresiniciales('','',desde,hastavalor);
TablaFacturaD.CancelRange;
FormaFormatos.ShowModal;
if FormaFormatos.Tag=1 then
begin
condiciones(FormaFormatos.C1.Caption,tipooperador(FormaFormatos.Operador1.Text),FormaFormatos.Valor1.Text,FormaFormatos.T1.Caption,FormaFormatos.C2.Caption,tipooperador(FormaFormatos.Operador2.Text),FormaFormatos.Valor2.Text,FormaFormatos.T2.Caption,FormaFormatos.C3.Caption,tipooperador(FormaFormatos.Operador3.Text),FormaFormatos.Valor3.Text,FormaFormatos.T3.Caption,'Y');
if FormaFormatos.IncluirDevoluciones.Checked then
begin
GeneraCorteDeCaja(FormaFormatos.Inicial.Date,FormaFormatos.Final.Date,TablaFacturaD.TableName,'devolucd.dbf','FactAuxiD.dbf',TablaFacturaD.IndexName,'S');
Concentrar(TablaAuxiliar,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_FD',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CANTI_FD','DEPRO_FD','CLPRO_FD','IMPOR_FD','','','','','','','TREGI_FD','!','C','C');
end
else
Concentrar(TablaFacturaD,Formaformatos.De.Text,FormaFormatos.Hasta.Text,'FEDOC_FD',DateToStr(FormaFormatos.Inicial.Date),DateToStr(FormaFormatos.Final.Date),'CANTI_FD','DEPRO_FD','CLPRO_FD','IMPOR_FD','','','','','','','TREGI_FD','!','C','C');


poneetiquetas('Cantidad','Descripción','Producto','Importe','','','','','','','');
Poneanchos(20,20,20,20,20,20,20,20,20,20,0);
//FormaBarras.Caption:='Reporte de Ventas por Artículo';
//******pone el titulo
 with Sender as TMenuItem do
  begin
  desde:=Caption;
  end;
FormaBarras.Caption:=AgregaTitulo2('Reporte de '+desde,FormaFormatos.Titulo.Text);
//******termina pone el titulo

parametrosgrafica('Gráfica de Ventas por Artículo','Artículo','Total por Artículo',1);
FormaBarras.Tag:=0;
FormaBarras.Panel2.Tag:=0;
FormaBarras.botonGrafica.Tag:=2;
FormaBarras.ShowModal;
FormaBarras.Tag:=0;
end;
FormaFormatos.Tag:=0;
FormaFormatos.Free;
FormaBarras.Free;

end;

end.

