//---------------------------------------------------------------------------

#include <vcl.h>
#include <DateUtils.hpp>
#include "tsplash.h"
#pragma hdrstop

#include "clientes.h"
#include "agentes.h"
#include "imprimirClientes.h"
#include "cuentaPolizas.h"
#include "imprimirFichaCliente.h"
#include "login_dlg.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "ZAbstractDataset"
#pragma link "ZAbstractRODataset"
#pragma link "ZConnection"
#pragma link "ZDataset"
#pragma link "ZSqlUpdate"
#pragma resource "*.dfm"
TgestionClientes *gestionClientes;
//---------------------------------------------------------------------------
__fastcall TgestionClientes::TgestionClientes(TComponent* Owner)
        : TForm(Owner)
{
  gettingAutoIncrement = false;

  #define IDM_ABOUTBOX 1
  HMENU pSysMenu = GetSystemMenu(this->Handle, FALSE);
  if (pSysMenu != NULL)
  {
        AppendMenu(pSysMenu, MF_SEPARATOR,0,0);
        AppendMenu(pSysMenu, MF_STRING, IDM_ABOUTBOX, "Acerca de...");
  }
  WindowProc=MyWndProc;


  // Cargamos el listado de agentes disponibles
  TZQuery *zquery;
  zquery = new TZQuery(this);
  zquery->Connection = ZConnection1;
  zquery->SQL->Clear();
  zquery->SQL->Add("SELECT id,nombre FROM agentes ORDER BY nombre");
  zquery->Active=zquery->Connection->Connected;

   srch_agentes->Items->Clear();
   srch_agentes->Items->AddObject("",(TObject *)(-1) );
   srch_agentes->Items->AddObject("-[ Sin Agente Asignado ]-",(TObject *)(0) );
   while(!zquery->Eof)
   {
      srch_agentes->Items->AddObject(zquery->FieldByName("nombre")->AsString,(TObject *)(zquery->FieldByName("id")->AsInteger));
      zquery->Next();
   }


  // Orden del listado
  dsListado_sort = "c.id";


  zuClientes->ModifySQL->Clear();
  zuClientes->ModifySQL->Add("UPDATE clientes SET agente=:agente, nombre=:nombre, dni=:dni, calle=:calle, poblacion=:poblacion, provincia=:provincia, cp=:cp, telefono=:telefono, movil=:movil, fax=:fax, correo=:correo, cobroCalle=:cobroCalle, estado=:estado, gradoFidelidad=:gradoFidelidad, pCargo=:pCargo, fechaNacimiento=:fechaNacimiento, fechaCarnet=:fechaCarnet, fecha=:fecha, hora=:hora, notas=:notas WHERE id=:OLD_id");
  zuClientes->DeleteSQL->Clear();
  zuClientes->DeleteSQL->Add("DELETE FROM clientes WHERE id=:OLD_id");
  zuClientes->InsertSQL->Clear();
  zuClientes->InsertSQL->Add("INSERT INTO clientes (agente, nombre, dni, calle, poblacion, provincia, cp, telefono, movil, fax, correo, cobroCalle, estado, gradoFidelidad, pCargo, fechaNacimiento, fechaCarnet, fecha, hora, notas) VALUES (:agente, :nombre, :dni, :calle, :poblacion, :provincia, :cp, :telefono, :movil, :fax, :correo, :cobroCalle, :estado, :gradoFidelidad, :pCargo, :fechaNacimiento, :fechaCarnet, :fecha, :hora, :notas)");

  zuServicios->ModifySQL->Clear();
  zuServicios->ModifySQL->Add("UPDATE servicios SET tipoServicio=:tipoServicio, nPoliza=:nPoliza, fechaEfecto=:fechaEfecto, fechaVencimiento=:fechaVencimiento, primaNeta=:primaNeta WHERE id=:OLD_id");
  zuServicios->DeleteSQL->Clear();
  zuServicios->DeleteSQL->Add("DELETE FROM servicios WHERE id=:OLD_id");
  zuServicios->InsertSQL->Clear();
  zuServicios->InsertSQL->Add("INSERT INTO servicios (cliente, tipoServicio, nPoliza, fechaEfecto, fechaVencimiento, primaNeta) VALUES (:cliente, :tipoServicio, :nPoliza, :fechaEfecto, :fechaVencimiento, :primaNeta)");

  
  zuServiciosExternos->ModifySQL->Clear();
  zuServiciosExternos->ModifySQL->Add("UPDATE serviciosExternos SET tipoServicio=:tipoServicio, nPoliza=:nPoliza, fechaEfecto=:fechaEfecto, fechaVencimiento=:fechaVencimiento, primaNeta=:primaNeta WHERE id=:OLD_id");
  zuServiciosExternos->DeleteSQL->Clear();
  zuServiciosExternos->DeleteSQL->Add("DELETE FROM serviciosExternos WHERE id=:OLD_id");
  zuServiciosExternos->InsertSQL->Clear();
  zuServiciosExternos->InsertSQL->Add("INSERT INTO serviciosExternos (cliente, tipoServicio, nPoliza, fechaEfecto, fechaVencimiento, primaNeta) VALUES (:cliente, :tipoServicio, :nPoliza, :fechaEfecto, :fechaVencimiento, :primaNeta)");


  PageControl1->ActivePage = TabSheet1;
  PageControl2->ActivePage = TabSheet3;

  zqClientes->Active = zqClientes->Connection->Connected;
  zqServicios->Active = zqServicios->Connection->Connected;
  zqServiciosExternos->Active = zqServicios->Connection->Connected;
  zqTipoServicios->Active = zqTipoServicios->Connection->Connected;
  zqFamiliares->Active = zqFamiliares->Connection->Connected;
  zqAgentes->Active = zqAgentes->Connection->Connected;

}
//---------------------------------------------------------------------------
void __fastcall TgestionClientes::MyWndProc(Messages::TMessage &Message)
{
  HMENU hMenu;
  hMenu = GetSystemMenu (this->Handle, FALSE);
  if (Message.Msg == WM_SYSCOMMAND)
  {
     switch(Message.WParamLo)
     {
        case IDM_ABOUTBOX:
                 if ( Splash==NULL ) Splash = new TSplash(NULL);
                 Splash->pressKeyToClose = true;
                 Splash->Show();
                 Splash->Repaint();
            break;
        default:
           WndProc(Message);
   }
}

else
    WndProc(Message);
}
//---------------------------------------------------------------------------
void __fastcall TgestionClientes::FormShow(TObject *Sender)
{
  if(Splash){
        delete Splash;
        Splash = NULL;

        Tlogin *login;
        login = new Tlogin(this);

        do {
                login->ShowModal();
                if ( login->ModalResult!=mrOk ) {
                        Close();
                        break;
                }
                if ( login->auth ) break;

                MessageDlg("Error iniciando sesión.\nEl usuario/contraseña no es correcto.",mtError, TMsgDlgButtons() << mbOK, 0);
                login->pass->Text = "";
        } while(1);
  }
}
//---------------------------------------------------------------------------
void __fastcall TgestionClientes::DBGrid1DblClick(TObject *Sender)
{
  PageControl1->ActivePage = TabSheet2;
}
//---------------------------------------------------------------------------

void __fastcall TgestionClientes::DBGrid1TitleClick(TColumn *Column)
{
  if ( dsListado_sort.Pos(Column->FieldName)==1 && dsListado_sort.Pos(" ASC")==0 )
        dsListado_sort = Column->FieldName + " ASC";
  else
        dsListado_sort = Column->FieldName + " DESC";

  dsListado_Indice = Column->Index;

  doFilterClick(NULL);
}
//---------------------------------------------------------------------------

void __fastcall TgestionClientes::doFilterClick(TObject *Sender)
{
  AnsiString where,orderBy,query, leftJOIN;

  where = "";
  leftJOIN = "";
  if ( !srch_vFilter->Text.IsEmpty() )
  switch( srch_kFilter->ItemIndex ) {
        case 0:
                if ( where.IsEmpty() ) where = " WHERE "; else where+=" AND ";
                where+=" c.id='"+srch_vFilter->Text+"'";
                break;
        case 1:
                if ( where.IsEmpty() ) where = " WHERE "; else where+=" AND ";
                where+=" c.nombre LIKE '%"+srch_vFilter->Text+"%'";
                break;
        case 2:
                if ( where.IsEmpty() ) where = " WHERE "; else where+=" AND ";
                where+=" (c.telefono LIKE '%"+srch_vFilter->Text+"%'";
                where+=" OR c.movil LIKE '%"+srch_vFilter->Text+"%'";
                where+=" OR c.fax LIKE '%"+srch_vFilter->Text+"%')";
                break;
        case 3:
                if ( where.IsEmpty() ) where = " WHERE "; else where+=" AND ";
                where+=" c.calle LIKE '%"+srch_vFilter->Text+"%'";
                break;
        case 4:
                if ( where.IsEmpty() ) where = " WHERE "; else where+=" AND ";
                where+=" c.poblacion LIKE '%"+srch_vFilter->Text+"%'";
                break;
        case 5:
                if ( where.IsEmpty() ) where = " WHERE "; else where+=" AND ";
                where+=" c.provincia LIKE '%"+srch_vFilter->Text+"%'";
                break;
        case 6:
                if ( where.IsEmpty() ) where = " WHERE "; else where+=" AND ";
                where+=" c.cp LIKE '%"+srch_vFilter->Text+"%'";
                break;
        case 7:
                if ( where.IsEmpty() ) where = " WHERE "; else where+=" AND ";
                where+=" c.dni LIKE '%"+srch_vFilter->Text+"%'";
                break;
        case 8:
                System::TDateTime fecha;
                if ( TryStrToDate(srch_vFilter->Text, fecha) ) {
                        DateSeparator = '-';
                        ShortDateFormat = "yyyy-mm-dd";
                        
                        if ( where.IsEmpty() ) where = " WHERE "; else where+=" AND ";
                        where+=" p.fechaVencimiento<='"+DateToStr(fecha)+"'";
                        leftJOIN = " LEFT JOIN serviciosExternos p ON (p.cliente=c.id) ";

                        DateSeparator = '/';
                        ShortDateFormat = "dd/mm/yyyy";
                }
                break;

  }

  int agente;
  if ( srch_agentes->ItemIndex>0 ) {
          agente = (int)srch_agentes->Items->Objects[srch_agentes->ItemIndex];
          if ( agente>=0 ) {
                if ( where.IsEmpty() ) where = " WHERE "; else where+=" AND ";
                where+=" a.id="+AnsiString(agente);
          }
  }


  orderBy = " ORDER BY ";
  if ( dsListado_sort.Pos("agenteNombre")>0 ) orderBy += "a.nombre"; else orderBy += "c."+dsListado_sort;


  query = "SELECT c.id, c.agente, a.nombre agenteNombre, c.nombre, c.dni, c.calle, c.poblacion, c.provincia, c.cp, c.telefono, c.movil, c.fax, c.correo, c.cobroCalle, c.estado, c.gradoFidelidad, c.pCargo, c.fechaNacimiento,c.fechaCarnet,c.fecha, c.hora, c.notas";
  query+= " FROM clientes c LEFT JOIN agentes a ON (a.id=c.agente)";
  query+= leftJOIN;
  query+= where;
  query+= orderBy;


  // Volver a filtrar el listado...
  zqClientes->SQL->Clear();
  zqClientes->SQL->Add(query);
  zqClientes->Active = zqClientes->Connection->Connected;

}
//---------------------------------------------------------------------------

void __fastcall TgestionClientes::DBGrid1DrawColumnCell(TObject *Sender,
      const TRect &Rect, int DataCol, TColumn *Column,
      TGridDrawState State)
{
//- ---------------------------------------------------------
  if ( !State.Contains(gdSelected) )
  {
          Graphics::TBitmap *Bmp;
          TDBGrid *dbG;
          dbG = (TDBGrid *)Sender;

          // Determina la columna clicada...
          if ( Column->Index == dsListado_Indice )
          {
            Bmp = new Graphics::TBitmap();
            Bmp->TransparentColor = clWhite;
            Bmp->Transparent = true;
            Bmp->TransparentMode = tmAuto;

            try {
                    // Determina la imagen mostrada de acuerdo con el orden de los registros
                    if ( dsListado_sort.Pos(Column->FieldName) == 1 && dsListado_sort.Pos(" ASC")== 0 )
                        gridIcons->GetBitmap(0, Bmp);  // Set abajo
                    else
                        gridIcons->GetBitmap(1, Bmp); // Set arriba

                    dbG->Canvas->Draw( Rect.right - Bmp->Width,2, Bmp);
            } __finally {
          	 delete Bmp;  // Liberamos la variable Bmp de la memoria
            }
          }
          dbG->DefaultDrawColumnCell(Rect,DataCol,Column,State);
  }
  //- ---------------------------------------------------------
}
//---------------------------------------------------------------------------

void __fastcall TgestionClientes::zqClientesBeforePost(TDataSet *DataSet)
{
  // Comprobar que no exista el DNI introducido
  AnsiString dni;
  dni = zqClientes->FieldByName("dni")->AsString;


  if ( DataSet->State == dsInsert && !dni.IsEmpty() ) {
          TZQuery *q;
          q = new TZQuery(this);
          q->SQL->Clear();
          q->SQL->Add( AnsiString("select id FROM clientes WHERE dni='")+dni+AnsiString("'") );
          q->Connection = ZConnection1;
          q->Active = true;

          if ( q->RecordCount>0 ) {
                int res;
                res = MessageDlg("El dni introducido ya existe, ficha " + IntToStr(q->FieldByName("id")->AsInteger) + ". ¿Duplicar ficha?", mtInformation,  mbYesNoCancel, 0);
                switch( res ) {
                        case mrCancel:
                                Abort();
                                return;
                                break;
                        case mrNo:
                                zqClientes->CancelUpdates();
                                zqClientes->Locate("id",q->FieldByName("id")->AsInteger, TLocateOptions() );
                                return;
                                break;
                        default:
                                break;
                }
          }
  }

  // Guardamos el contenido de los combos
  zqClientes->FieldByName("fechaNacimiento")->AsDateTime = DateTimePicker1->DateTime;
  zqClientes->FieldByName("fechaCarnet")->AsDateTime = DateTimePicker2->DateTime;
  switch( dbEstadoCivil->ItemIndex ) {
        case 0: zqClientes->FieldByName("estado")->AsString = "S"; break;
        case 1: zqClientes->FieldByName("estado")->AsString = "C"; break;
        case 2: zqClientes->FieldByName("estado")->AsString = "D"; break;
        case 3: zqClientes->FieldByName("estado")->AsString = "V"; break;
  }
  zqClientes->FieldByName("gradoFidelidad")->AsInteger = cbGradoFidelidad->ItemIndex;
  zqClientes->FieldByName("pCargo")->AsString = (dbPCargo->Checked?"Y":"N");
}
//---------------------------------------------------------------------------


void __fastcall TgestionClientes::DateTimePicker1CloseUp(TObject *Sender)
{
  lbEdad->Caption =  AnsiString( YearsBetween(TDateTime::CurrentDate(), DateTimePicker1->DateTime) ) + " Años";

  if ( dbUpdating ) return;
  if (zqClientes->State != dsEdit || zqClientes->State != dsInsert ) zqClientes->Edit();
}
//---------------------------------------------------------------------------


void __fastcall TgestionClientes::zqClientesAfterScroll(TDataSet *DataSet)
{
  dbUpdating = true;

  // Guardamos el contenido de los combos
  DateTimePicker1->DateTime = zqClientes->FieldByName("fechaNacimiento")->AsDateTime;
  DateTimePicker2->DateTime = zqClientes->FieldByName("fechaCarnet")->AsDateTime;
  if ( zqClientes->FieldByName("estado")->AsString=="S" ) dbEstadoCivil->ItemIndex = 0; else
  if ( zqClientes->FieldByName("estado")->AsString=="C" ) dbEstadoCivil->ItemIndex = 1; else
  if ( zqClientes->FieldByName("estado")->AsString=="D" ) dbEstadoCivil->ItemIndex = 2; else
  if ( zqClientes->FieldByName("estado")->AsString=="V" ) dbEstadoCivil->ItemIndex = 3;

  if ( zqClientes->FieldByName("gradoFidelidad")->AsInteger == 0 ) cbGradoFidelidad->ItemIndex = 0;
  else if ( zqClientes->FieldByName("gradoFidelidad")->AsInteger == 1 ) cbGradoFidelidad->ItemIndex = 1;
  else if ( zqClientes->FieldByName("gradoFidelidad")->AsInteger == 2 ) cbGradoFidelidad->ItemIndex = 2;
  else cbGradoFidelidad->ItemIndex = 2;

  dbPCargo->Checked = (zqClientes->FieldByName("pCargo")->AsString=="Y");

  lbEdad->Caption =  AnsiString( YearsBetween(TDateTime::CurrentDate(), DateTimePicker1->DateTime) ) + " Años";

  dbUpdating = false;
}
//---------------------------------------------------------------------------

void __fastcall TgestionClientes::dbEstadoCivilChange(TObject *Sender)
{
  if ( dbUpdating ) return;
  if (zqClientes->State != dsEdit || zqClientes->State != dsInsert ) zqClientes->Edit();
}
//---------------------------------------------------------------------------

void __fastcall TgestionClientes::dbPCargoClick(TObject *Sender)
{
  if ( dbUpdating ) return;
  if (zqClientes->State != dsEdit || zqClientes->State != dsInsert ) zqClientes->Edit();
}
//---------------------------------------------------------------------------


void __fastcall TgestionClientes::Salir1Click(TObject *Sender)
{
  Close();
}
//---------------------------------------------------------------------------


void __fastcall TgestionClientes::GestindeAgentes1Click(TObject *Sender)
{
  TgestionAgentes *f;
  f = new TgestionAgentes(this);
  f->DBGrid2->DataSource = dsAgentes;
  f->ShowModal();
  delete f;
}
//---------------------------------------------------------------------------

void __fastcall TgestionClientes::zqFamiliaresNewRecord(TDataSet *DataSet)
{
  zqFamiliares->FieldByName("cliente")->AsInteger = zqClientes->FieldByName("id")->AsInteger;
  zqFamiliares->FieldByName("sexo")->AsString = "H";
  zqFamiliares->FieldByName("estado")->AsString = "C";
  zqFamiliares->FieldByName("relacion")->AsString = "C";
}
//---------------------------------------------------------------------------

void __fastcall TgestionClientes::zqFamiliaresBeforePost(TDataSet *DataSet)
{
  // Convertir los desplegables
  zqFamiliares->FieldByName("sexo")->AsString = (zqFamiliares->FieldByName("sexo")->AsString=="Hombre"?"H":"M");
  if ( zqFamiliares->FieldByName("estado")->AsString=="Soltero" )       zqFamiliares->FieldByName("estado")->AsString = "S"; else
  if ( zqFamiliares->FieldByName("estado")->AsString=="Casado" )        zqFamiliares->FieldByName("estado")->AsString = "C"; else
  if ( zqFamiliares->FieldByName("estado")->AsString=="Divorciado" )    zqFamiliares->FieldByName("estado")->AsString = "D"; else
  if ( zqFamiliares->FieldByName("estado")->AsString=="Viudo" )         zqFamiliares->FieldByName("estado")->AsString = "V";

  if ( zqFamiliares->FieldByName("relacion")->AsString == "Padre/Madre" )   zqFamiliares->FieldByName("relacion")->AsString = "P"; else
  if ( zqFamiliares->FieldByName("relacion")->AsString == "Marido/Mujer" )  zqFamiliares->FieldByName("relacion")->AsString = "C"; else
  if ( zqFamiliares->FieldByName("relacion")->AsString == "Hermano/a" )     zqFamiliares->FieldByName("relacion")->AsString = "H"; else
  if ( zqFamiliares->FieldByName("relacion")->AsString == "Hijo/a" )        zqFamiliares->FieldByName("relacion")->AsString = "N"; else
  if ( zqFamiliares->FieldByName("relacion")->AsString == "otros" )         zqFamiliares->FieldByName("relacion")->AsString = "o";

}
//---------------------------------------------------------------------------

void __fastcall TgestionClientes::zqFamiliaresestadoGetText(TField *Sender,
      AnsiString &Text, bool DisplayText)
{
  if ( Sender->AsString == "S" ) Text = "Soltero"; else
  if ( Sender->AsString == "C" ) Text = "Casado"; else
  if ( Sender->AsString == "D" ) Text = "Divorciado"; else
  if ( Sender->AsString == "V" ) Text = "Viudo";
}
//---------------------------------------------------------------------------

void __fastcall TgestionClientes::zqFamiliaresrelacionGetText(
      TField *Sender, AnsiString &Text, bool DisplayText)
{
  if ( Sender->AsString == "P" ) Text = "Padre/Madre"; else
  if ( Sender->AsString == "C" ) Text = "Marido/Mujer"; else
  if ( Sender->AsString == "H" ) Text = "Hermano/a"; else
  if ( Sender->AsString == "N" ) Text = "Hijo/a"; else
  if ( Sender->AsString == "o" ) Text = "otros";
}
//---------------------------------------------------------------------------

void __fastcall TgestionClientes::zqFamiliaressexoGetText(TField *Sender,
      AnsiString &Text, bool DisplayText)
{
  if ( Sender->AsString == "H" ) Text = "Hombre"; else
  if ( Sender->AsString == "M" ) Text = "Mujer";
}
//---------------------------------------------------------------------------

void __fastcall TgestionClientes::zqServiciosNewRecord(TDataSet *DataSet)
{
  zqServicios->FieldByName("cliente")->AsInteger = zqClientes->FieldByName("id")->AsInteger;
  zqServicios->FieldByName("primaNeta")->AsCurrency = 0;
}
//---------------------------------------------------------------------------

void __fastcall TgestionClientes::TiposdeServicio1Click(TObject *Sender)
{
  TgestionAgentes *f;
  f = new TgestionAgentes(this);
  f->Caption = "Tipos de Servicios";
  f->DBGrid2->Columns->Items[0]->Title->Caption = "Nombre del Servicio Contratado";
  f->DBGrid2->DataSource = dsTipoServicios;
  f->ShowModal();
  delete f;
}
//---------------------------------------------------------------------------

void __fastcall TgestionClientes::ImprimirListado1Click(TObject *Sender)
{
  TimprimirCarteraClientes *i;
  i = new TimprimirCarteraClientes(this);
  i->QuickRep1->DataSet = zqClientes;
  i->QuickRep1->Preview();
  delete i;
}
//---------------------------------------------------------------------------

void __fastcall TgestionClientes::ImprimirFicha1Click(TObject *Sender)
{
  TimprFichaCliente *i;
  i = new TimprFichaCliente(this);

  i->rID->Caption = zqClientes->FieldByName("id")->AsString;
  i->rNombre->Caption = zqClientes->FieldByName("nombre")->AsString;
  i->rDNI->Caption = zqClientes->FieldByName("dni")->AsString;
  i->rFechaNacimiento->Caption = zqClientes->FieldByName("fechaNacimiento")->AsString;
  i->rEstadoCivil->Caption = zqClientes->FieldByName("estado")->AsString;
  i->rPCargo->Caption = zqClientes->FieldByName("pCargo")->AsString=="Y"?"SI":"NO";
  i->rCalle->Caption = zqClientes->FieldByName("calle")->AsString;
  i->rPoblacion->Caption = zqClientes->FieldByName("poblacion")->AsString;
  i->rProvincia->Caption = zqClientes->FieldByName("provincia")->AsString;
  i->rCP->Caption = zqClientes->FieldByName("cp")->AsString;
  i->rDirCobro->Caption = zqClientes->FieldByName("cobroCalle")->AsString;
  i->rTelefono->Caption = zqClientes->FieldByName("telefono")->AsString;
  i->rMovil->Caption = zqClientes->FieldByName("movil")->AsString;
  i->rFax->Caption = zqClientes->FieldByName("fax")->AsString;
  i->rEMail->Caption = zqClientes->FieldByName("correo")->AsString;
  i->rAgente->Caption = DBLookupComboBox1->Text;
  i->rGradoFidelidad->Caption = zqClientes->FieldByName("gradoFidelidad")->AsString;
  i->rNotas->Lines->Text = zqClientes->FieldByName("notas")->AsString;

  i->QuickRep1->DataSet = zqFamiliares;
  i->QuickRep1->Preview();
  delete i;
}
//---------------------------------------------------------------------------


void __fastcall TgestionClientes::CuentaPolizas1Click(TObject *Sender)
{
  TgestionCuentaPolizas *f;
  f = new TgestionCuentaPolizas(this);
  f->ShowModal();
  delete f;
}
//---------------------------------------------------------------------------

void __fastcall TgestionClientes::dsClientesStateChange(TObject *Sender)
{
  if ( dsClientes->State==dsInsert ) {
          PageControl2->ActivePage = TabSheet5;
  }

  TabSheet3->Enabled = (dsClientes->State!=dsInsert);
  TabSheet6->Enabled = (dsClientes->State!=dsInsert);
  TabSheet4->Enabled = (dsClientes->State!=dsInsert);
}
//---------------------------------------------------------------------------



void __fastcall TgestionClientes::zqClientesAfterPost(TDataSet *DataSet)
{
  if ( gettingAutoIncrement ) return;
  // Read auto-increment
  if ( zqClientes->FieldByName("id")->AsInteger==0 ) {
        gettingAutoIncrement = true;

        zqClientes->Edit();

          TZQuery *q;
          q = new TZQuery(this);
          q->SQL->Clear();
          q->SQL->Add("select last_insert_rowid() id");
          q->Connection = ZConnection1;
          q->Active = true;

          zqClientes->FieldByName("id")->AsInteger = q->FieldByName("id")->AsInteger;
          delete q;

        zqClientes->Post();
        gettingAutoIncrement = false;
  }

}
//---------------------------------------------------------------------------

void __fastcall TgestionClientes::cbGradoFidelidadChange(TObject *Sender)
{
  if ( dbUpdating ) return;
  if (zqClientes->State != dsEdit || zqClientes->State != dsInsert ) zqClientes->Edit();
}
//---------------------------------------------------------------------------

void __fastcall TgestionClientes::FormClose(TObject *Sender,
      TCloseAction &Action)
{
  if( zqClientes->State == dsEdit || zqClientes->State == dsInsert ) zqClientes->Post();
  if( zqServicios->State == dsEdit || zqServicios->State == dsInsert ) zqServicios->Post();
  if( zqFamiliares->State == dsEdit || zqFamiliares->State == dsInsert ) zqFamiliares->Post();
  if( zqAgentes->State == dsEdit || zqAgentes->State == dsInsert ) zqAgentes->Post();
}
//---------------------------------------------------------------------------

void __fastcall TgestionClientes::zqServiciosExternosNewRecord(
      TDataSet *DataSet)
{
  zqServiciosExternos->FieldByName("cliente")->AsInteger = zqClientes->FieldByName("id")->AsInteger;
  zqServiciosExternos->FieldByName("primaNeta")->AsCurrency = 0;
}
//---------------------------------------------------------------------------



void __fastcall TgestionClientes::PageControl2Changing(TObject *Sender,
      bool &AllowChange)
{
  AllowChange = ( dsClientes->State!=dsInsert );
}
//---------------------------------------------------------------------------

