/********************************* CMoteur_Base.cpp *******************************
 *                                                                                *
 *   #include "CMoteur_Base.h"                                                    *
 *   Project: MedinTux                                                            *
 *   Copyright (C) 2003 2004 2005 by Sevin Roland  and Data Medical Design        *
 *   E-Mail: data.medical.design@club-internet.fr                                 *
 *                                                                                *
 *   This program is free software; you can redistribute it and/or modify         *
 *   it under the terms of the CeCILL Version 1 du 21/06/2004                     *
 *   License (GPL compatible)                                                     *
 *                              http://www.cecill.info/                           *
 *   as published by :                                                            *
 *                                                                                *
 *   Commissariat à l'Energie Atomique                                            *
 *   - CEA,                                                                       *
 *                            31-33 rue de la Fédération, 75752 PARIS cedex 15.   *
 *                            FRANCE                                              *
 *   Centre National de la Recherche Scientifique                                 *
 *   - CNRS,                                                                      *
 *                            3 rue Michel-Ange, 75794 Paris cedex 16.            *
 *                            FRANCE                                              *
 *   Institut National de Recherche en Informatique et en Automatique             *
 *   - INRIA,                                                                     *
 *                            Domaine de Voluceau, Rocquencourt, BP 105, 78153    *
 *                            FRANCE                                              *
 *                                                                                *
 *         This program is distributed in the hope that it will be useful,        *
 *         but WITHOUT ANY WARRANTY; without even the implied warranty of         *
 *         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                   *
 *         CeCILL  License (GPL compatible) for more details.                     *
 *                                                                                *
 **********************************************************************************/

//=============================================== INCLUDES ============================================================
#include <stdlib.h>


#include <qprocess.h>
#include <qwaitcondition.h>
#include <qmessagebox.h>
#include <math.h>
#include <quuid.h>
#include <qeventloop.h>


#include "../../MedinTuxTools/CHtmlTools.h"
#include "CMoteur_Base.h"
#include "Global.h"
#include "../../MedinTuxTools/CPrtQListBoxItem.h"
#include "../../MedinTuxTools/CPrtQListViewItem.h"


#define TR  QObject::tr

//=============================================== GLOBALES ============================================================
char * DEFAULT_CONF_BASE = "DOSS_INDEX_TBL_NAME        'IndexNomPrenom'                    \r\n"
                           "DOSS_INDEX_GUID            'FchGnrl_IDDos'                '0'  \r\n"
                           "DOSS_INDEX_NOM             'FchGnrl_NomDos'               '1'  \r\n"
                           "DOSS_INDEX_PRENOM          'FchGnrl_Prenom'               '2'  \r\n"
                           "DOSS_INDEX_PRIM_KEY        'ID_PrimKey'                   '3'  \r\n"
                           "DOSS_IDENT_TBL_NAME        'fchpat2002'                        \r\n"
                           "DOSS_IDENT_GUID            'FchPat_GUID_Doss'             '0'  \r\n"      // GUID du dossier auquel l'enregistrement     fait reference
                           "DOSS_IDENT_JFNOM           'FchPat_NomFille'              '1'  \r\n"      // nom de jeune fille
                           "DOSS_IDENT_NSS             'FchPat_Nee'                   '2'  \r\n"      // date de naissance
                           "DOSS_IDENT_SEX             'FchPat_Sexe'                  '3'  \r\n"      // sexe
                           "DOSS_IDENT_NB_ENF          'FchPat_NbEnfant'              '4'  \r\n"      // nombre d'enfants
                           "DOSS_IDENT_RUE             'FchPat_Adresse'               '5'  \r\n"      // adresse
                           "DOSS_IDENT_CODE_POST       'FchPat_CP'                    '6'  \r\n"      // Code postal
                           "DOSS_IDENT_VILLE           'FchPat_Ville'                 '7'  \r\n"      // Ville
                           "DOSS_IDENT_CEDEX           'FchPat_Cdx'                   '8'  \r\n"      // cedex
                           "DOSS_IDENT_PAYS            'FchPat_Pays'                  '9'  \r\n"      // pays
                           "DOSS_IDENT_TEL1            'FchPat_Tel1'                  '10' \r\n"     // Telephone 1
                           "DOSS_IDENT_TEL1_TYP        'FchPat_Tel1_Typ'              '11' \r\n"     // Telephone 1  type (parent amis etc...)
                           "DOSS_IDENT_TEL2            'FchPat_Tel2'                  '12' \r\n"     // Telephone 2
                           "DOSS_IDENT_TEL2_TYP        'FchPat_Tel2_Typ'              '13' \r\n"     // Telephone 2
                           "DOSS_IDENT_TEL3            'FchPat_Tel3'                  '14' \r\n"     // Telephone 3
                           "DOSS_IDENT_TEL3_TYP        'FchPat_Tel3_Typ'              '15' \r\n"     // Telephone 3
                           "DOSS_IDENT_EMAIL           'FchPat_Email'                 '16' \r\n"     // Email
                           "DOSS_IDENT_NUMSS           'FchPat_NumSS'                 '17' \r\n"     // Numéro de secu
                           "DOSS_IDENT_IS_ASS          'FchPat_PatientAss'            '18' \r\n"     // le patient est il l'assuré
                           "DOSS_IDENT_NOM_ASS         'FchPat_NomAss'                '19' \r\n"     // nom de l'assuré
                           "DOSS_IDENT_PRENOM_ASS      'FchPat_PrenomAss'             '20' \r\n"     // prénom de l'assuré
                           "DOSS_IDENT_PROF            'FchPat_Profession'            '21' \r\n"     // profession
                           "DOSS_IDENT_TITRE           'FchPat_Titre'                 '22' \r\n"     // Titre( Dr Mr Md Pr ...)
                           "DOSS_IDENT_MEDTT_NOM       'FchPat_NomMedTT'              '23' \r\n"     // nom du medecin traitant
                           "DOSS_IDENT_MEDTT_PRENOM    'FchPat_PrenomMedTT'           '24' \r\n"     // prenom du medecin traitant
                           "DOSS_IDENT_REF_PK          'FchPat_RefPk'                 '25' \r\n"     // reference à la primary key: DOSS_INDEX_PRIM_KEY de la table: DOSS_INDEX
                           "DOSS_NOTE_TBL_NAME         'fchpat_Note'                       \r\n"      // nom de la table de Notes patient
                           "DOSS_NOTE_PK               'fchpat_Note_PK     '          '0'  \r\n"      // clef primaire de cet enregisteement
                           "DOSS_NOTE_PAT_GUID         'fchpat_Note_PatGUID'          '1'  \r\n"      // GUID du dossier auquel l'enregistrement   fait reference
                           "DOSS_NOTE_PAT_PK           'fchpat_Note_PatPK'            '2'  \r\n"      // Clef primaire du dossier auquel fait reference cette note
                           "DOSS_NOTE_HTML             'fchpat_Note_Html'             '3'  \r\n"      // Données HTML de la note
                           "DOSS_INTERVENANTS_TBL_NAME 'fchpat_Intervenants'               \r\n"      // nom de la table des intervenants patient
                           "DOSS_INTERVENANTS_PK       'fchpat_Intervenants_PK'       '0'  \r\n"      // Clef primaire de l'intervenant auquel fait reference cet enregistrement
                           "DOSS_INTERVENANTS_PAT_GUID 'fchpat_Intervenants_PatGUID'  '1'  \r\n"      // GUID du dossier auquel l'enregistrement fait reference
                           "DOSS_INTERVENANTS_PAT_PK   'fchpat_Intervenants_PatPK'    '2'  \r\n"      // Clef primaire du dossier auquel fait reference cet intervenant
                           "DOSS_INTERVENANTS_INTERVPK 'fchpat_Intervenants_IntervPK' '3'  \r\n"      // Clef primaire de l'intervenant auquel fait reference cet enregistrement
                           "INTERVENANTS_TBL_NAME      'Personnes'                         \r\n"      // nom de la table des intervenants
                           "INTERVENANTS_PK            'ID_PrimKey'                   '2'  \r\n"      // primary key
                           "INTERVENANTS_NOM           'Nom'                          '3'  \r\n"      // nom de l'intervenant
                           "INTERVENANTS_PRENOM        'Prenom'                       '4'  \r\n"      // prenom de l'intervenant
                           "INTERVENANTS_SPEC          'Qualite'                      '14' \r\n"      // spécialité de l'intervenant
                           "INTERVENANTS_TITRE         'Titre'                        '17' \r\n"      // titre de l'intervenant (Dr Pr Mr Mm etc...)
                           "INTERVENANTS_RUE           'Adresse'                      '5'  \r\n"      // rue de l'intervenant
                           "INTERVENANTS_CODE_POST     'CodePostal'                   '6'  \r\n"      // Code postal de l'intervenant
                           "INTERVENANTS_VILLE         'Ville'                        '7'  \r\n"      // Ville de l'intervenant
                           "DOSS_HISTO_TBL_NAME        'historic_2002'                     \r\n"
                           "DOSS_HISTO_GUID            'HistN0_IDDos'                 '0'  \r\n"
                           "DOSS_HISTO_DATE            'HistN0_Date'                  '1'  \r\n"
                           "DOSS_HISTO_DUREE           'HistN0_Duree'                 '2'  \r\n"
                           "DOSS_HISTO_USER            'HistN0_NomUtil'               '3'  \r\n"
                           "DOSS_RUB_HEAD_TBL_NAME     'RubriquesHead'                     \r\n"      // nom de la table de l'header des RUBRIQUES
                           "DOSS_RUB_HEAD_PRIMKEY      'RbDate_PrimKey'               '0'  \r\n"      // clef primaire de cet enregistrement
                           "DOSS_RUB_HEAD_GUID         'RbDate_IDDos'                 '1'  \r\n"      // GUID du dossier auquel l'enregistrement fait reference
                           "DOSS_RUB_HEAD_TYPE         'RbDate_TypeRub'               '2'  \r\n"      // Type de rubrique
                           "DOSS_RUB_HEAD_NOM_DATE     'RbDate_NomDate'               '3'  \r\n"      // Court texte descriptif de l'enregistrement.
                           "DOSS_RUB_HEAD_DATE         'RbDate_Date'                  '4'  \r\n"      // date de l'enregistrement
                           "DOSS_RUB_HEAD_USER         'RbDate_CreateUser'            '5'  \r\n"      // utilisateur associé à rubrique
                           "DOSS_RUB_HEAD_REF_BLOBS_PK 'RbDate_RefBlobs_PrimKey'      '6'  \r\n"      // Primary key du blobs rataché à cet enregistrement
                           "DOSS_RUB_HEAD_FIN          'RbDate_Fin'                   '7'  \r\n"      // date de fin de l'enregistrement
                           "DOSS_RUB_HEAD_REF_DOSS_PK  'RbDate_Ref_NumDoss'           '8'  \r\n"      // Clef primaire du dossier auquel l'enregistrement fait reference (doublon avec m_DOSS_RUB_HEAD_GUID)
                           "DOSS_RUB_DATA_TBL_NAME     'RubriquesBlobs'                    \r\n"      // nom de la table des données des RUBRIQUES
                           "DOSS_RUB_DATA_PRIMKEY      'RbDate_PrimKey'               '0'  \r\n"      // clef primaire de cet enregistrement  (le meme que le header)
                           "DOSS_RUB_DATA_BLOB         'RbDate_DataRub'               '1'  \r\n"      // données binaires
                           "USER_IDENT_TBL_NAME        'Personnes'                         \r\n"      // nom de la table des données des RUBRIQUES
                           "USER_IDENT_NOM             'Nom'                          '0'  \r\n"      // Nom
                           "USER_IDENT_PRENOM          'Prenom'                       '1'  \r\n"      // Prenom
                           "USER_IDENT_TITRE           'Titre'                        '2'  \r\n"      // Titre( Dr Mr Md Pr ...)
                           "USER_IDENT_LOGIN           'Login'                        '3'  \r\n"      // Identifiant d'utilisateur
                           "USER_IDENT_PASSWORD        'Password'                     '4'  \r\n"      // mot de passe
                           "USER_IDENT_DROITS          'Droits'                       '5'  \r\n"      // Droits de cet utilisateur
                           "USER_IDENT_NUM_ORDRE       'NumOrdre'                     '6'  \r\n"      // Numéro d'ordre (si il y en a un)
                           "USER_IDENT_PRIMKEY         'ID_PrimKey'                   '7'  \r\n"      // clef primaire de cet enregistrement
                           "USER_IDENT_GUID            'GUID'                         '8'  \r\n"      // Identifiant unique de cet utilisateur
                           "USER_IDENT_CONVENTION      'Convention'                   '9'  \r\n"      // convention exple "01 MEDECINE GENERALE"
                           "USER_IDENT_CODE_POST       'CodePostal'                   '10' \r\n"      // Code postal
                           "USER_IDENT_VILLE           'Ville'                        '11' \r\n"      // Ville d'exercice
                           "USER_IDENT_RUE             'Adresse'                      '12' \r\n"      // Rue d'exercice
                           "USER_IDENT_QUALITE         'Qualite'                      '13' \r\n"      // Type d'intervenant (exple: Medecin Urgentiste)
                           "USER_DATA_TBL_NAME         'UserDoc'                           \r\n"      // nom de la table des données des RUBRIQUES
                           "USER_DATA_PK               'ID_PrimKey'                   '0'  \r\n"      // clef primaire de cet enregistrement
                           "USER_DATA_REF_PK           'ID_PrimKeyFromUser'           '1'  \r\n"      // Ref à la clef primaire de l'utilisateur auquel appartiennent les données
                           "USER_DATA_NAMEDOC          'NameDoc'                      '2'  \r\n"      // nom des données
                           "USER_DATA_TYPE             'TypeDocuments'                '3'  \r\n"      // type de données
                           "USER_DATA_BLOB             'DataDocuments'                '4'  \r\n";     // données proprement dites

//=============================================== IMPLEMENTATION =====================================================
//-----------------------------------------------------  CMoteurBase -------------------------------------------------
CMoteurBase::CMoteurBase( )
{ m_DriverName  = "";
  m_BaseName    = "";
  m_UserName    = "";
  m_PassWord    = "";
  m_HostName    = "";
  m_DataBase    = 0;


  QSqlDatabase::removeDatabase (BASE_DRTUX);
}
//-----------------------------------------------------  CMoteurBase -------------------------------------------
/**
 *
 * @param driver nom du driver: "QODBC3" "QMYSQL3" "QPSQL7"
 * @param DataBaseName
 * @param user
 * @param password
 * @param hostname
 * @param confFile
 * @param baseLabel
 * @param errMess
 * @return
 */
CMoteurBase::CMoteurBase(const char* driver,        // nom du driver: "QODBC3" "QMYSQL3" "QPSQL7"
                         const char* DataBaseName,  // nom de la base: si QODBC3 -> nom de la source de données (userDSN)
                         const char* user,          // = "root"
                         const char* password,      // = ""
                         const char* hostname,
                         const char* confFile,
                         const char* baseLabel,
                                     QString*    errMess)
{ initBase   ( driver,        // nom du driver: "QODBC3" "QMYSQL3" "QPSQL7"
               DataBaseName,  // nom de la base: si QODBC3 -> nom de la source de données (userDSN)
               user,          // = "root"
               password,      // = ""
               hostname,
               confFile,
               baseLabel,
               errMess);
}

//-----------------------------------------------------  GetMedinTuxVersion -------------------------------------------
double CMoteurBase::GetMedinTuxVersion(QString &version)
{   if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;
    version = "0.0";
    QString tmp;
    QSqlQuery sqlQuery ("SELECT NumVers FROM version " , m_DataBase );
    if (sqlQuery.isActive())
       {while (sqlQuery.next())
              {tmp     = sqlQuery.value(0).toString();
               if (tmp.toFloat() > version.toFloat())  version = tmp;
              }
       }
    m_DataBase->close();
    return version.toDouble();
}

//-----------------------------------------------------  initBase -------------------------------------------
/**
 *
 * @param driver
 * @param DataBaseName
 * @param user
 * @param password
 * @param hostname
 * @param confFile
 * @param baseLabel
 * @param errMess
 */
void CMoteurBase::initBase   (const char* driver,        // nom du driver: "QODBC3" "QMYSQL3" "QPSQL7"
                              const char* DataBaseName,  // nom de la base: si QODBC3 -> nom de la source de données (userDSN)
                              const char* user,          // = "root"
                              const char* password,      // = ""
                                  const char* hostname,
                                          const char* confFile,
                              const char* baseLabel,
                                          QString*    errMess)
{ int ret;
  m_DriverName  = driver;
  m_BaseName    = DataBaseName;
  m_UserName    = user;
  m_PassWord    = password;
  m_HostName    = hostname;
  m_DataBase    = 0;
  m_ConvertRun  = FALSE;
  QString mess;

  //................ configurer la classe .............................................
  if (confFile==0)                 {ret = SetConfBase(DEFAULT_CONF_BASE, &mess); qDebug(mess + "\r\n ConfFile absent: " );}
  else if (confFile[0]==0)         {ret = SetConfBase(DEFAULT_CONF_BASE, &mess); qDebug(mess + "\r\n ConfFile vide: "   );}
  else                             {ret = SetConfBase(confFile, &mess);          }

  if (ret==0)
     {qDebug(mess);
      if (errMess) *errMess = mess;
      return;
     }

  m_DataBase    = BaseConnect(driver,        // nom du driver: "QODBC3" "QMYSQL3" "QPSQL7"
                              DataBaseName,  // nom de la base: si QODBC3 -> nom de la source de données (userDSN)
                              user,          // = "root"
                              password,      // = ""
                              hostname,      // = "localhost"
                              errMess,
                              baseLabel);
}

//-----------------------------------------------------  CMoteurBase -------------------------------------------
CMoteurBase::CMoteurBase(const char* driver,        // nom du driver: "QODBC3" "QMYSQL3" "QPSQL7"
                         const char* DataBaseName,  // nom de la base: si QODBC3 -> nom de la source de données (userDSN)
                         const char* user,          // = "root"
                         const char* password,      // = ""
                         const char* hostname,
                         const char* confFile,
                         QString*    errMess)

{

  initBase   (driver,        // nom du driver: "QODBC3" "QMYSQL3" "QPSQL7"
              DataBaseName,  // nom de la base: si QODBC3 -> nom de la source de données (userDSN)
              user,          // = "root"
              password,      // = ""
              hostname,
              confFile,
              BASE_DRTUX,
              errMess);

}

//-----------------------------------------------------  ~CMoteurBase -------------------------------------------
CMoteurBase::~CMoteurBase()
{if (m_DataBase)
    {if (m_DataBase->isOpen()) m_DataBase->close();
     QSqlDatabase::removeDatabase (m_BaseLabel);
 //    delete m_DataBase;
 //    m_DataBase = 0;
    }
}

//-----------------------------------------------------  BaseConnect -------------------------------------------
QSqlDatabase*  CMoteurBase::BaseConnect(const char* driver,        // nom du driver: "QODBC3" "QMYSQL3" "QPSQL7"
                                        const char* DataBaseName,  // nom de la base: si QODBC3 -> nom de la source de données (userDSN)
                                        const char* user,          // = "root"
                                        const char* pasword,       // = ""
                                        const char* hostname,      // = "localhost"
                                        QString*    errMess,
                                        QString     baseLabel)
    {
        m_BaseLabel             = baseLabel;
        QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( driver , baseLabel);
        if (defaultDB<=0) return 0;
        defaultDB->setDatabaseName( DataBaseName );
        defaultDB->setUserName( user );
        defaultDB->setPassword( pasword );
        defaultDB->setHostName( hostname);
        if ( ! defaultDB->open() )
           {QString qstr = "";
            qstr += TR("Failed to open database: ") + QString(driver) + "  " + QString(DataBaseName) + "\r\n" +
                     defaultDB->lastError().driverText() + "\r\n" + defaultDB->lastError().databaseText();
            qWarning(qstr);
            if (errMess) *errMess = qstr;
            return 0;
           }
        return defaultDB;
    }

//-----------------------------------------------------  SetConfBase -------------------------------------------
int CMoteurBase::SetConfBase(const char* confFile, QString *errMess)
{
 QString  err = "";
  char    *deb = (char*) confFile;
  char     *pt = (char*) confFile;
  int     line = 0;
  //.............................. DOSS_INDEX_TBL_NAME .........................................................
  pt = SetConfBase_SetProperties(deb, m_DOSS_INDEX_TBL_NAME,      "DOSS_INDEX_TBL_NAME",       &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,  m_DOSS_INDEX_GUID,          "DOSS_INDEX_GUID",           &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,  m_DOSS_INDEX_NOM,           "DOSS_INDEX_NOM",            &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,  m_DOSS_INDEX_PRENOM,        "DOSS_INDEX_PRENOM",         &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,  m_DOSS_INDEX_PRIM_KEY,      "DOSS_INDEX_PRIM_KEY",       &line , err); if (err.length())     goto SetConfBase_Error;

  //............................ DOSS_IDENT_TBL_NAME ...........................................................
  pt = SetConfBase_SetProperties(deb,  m_DOSS_IDENT_TBL_NAME,     "DOSS_IDENT_TBL_NAME",       &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_GUID,         "DOSS_IDENT_GUID",           &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_JFNOM,        "DOSS_IDENT_JFNOM",          &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_NSS,          "DOSS_IDENT_NSS",            &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_SEX,          "DOSS_IDENT_SEX",            &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_NB_ENF,       "DOSS_IDENT_NB_ENF",         &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_RUE,          "DOSS_IDENT_RUE",            &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_CODE_POST,    "DOSS_IDENT_CODE_POST",      &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_VILLE,        "DOSS_IDENT_VILLE",          &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_CEDEX,        "DOSS_IDENT_CEDEX",          &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_PAYS,         "DOSS_IDENT_PAYS",           &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_TEL1,         "DOSS_IDENT_TEL1",           &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_TEL1_TYP,     "DOSS_IDENT_TEL1_TYP",       &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_TEL2,         "DOSS_IDENT_TEL2",           &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_TEL2_TYP,     "DOSS_IDENT_TEL2_TYP",       &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_TEL3,         "DOSS_IDENT_TEL3",           &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_TEL3_TYP,     "DOSS_IDENT_TEL3_TYP",       &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_EMAIL,        "DOSS_IDENT_EMAIL",          &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_NUMSS,        "DOSS_IDENT_NUMSS",          &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_IS_ASS,       "DOSS_IDENT_IS_ASS",         &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_NOM_ASS,      "DOSS_IDENT_NOM_ASS",        &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_PRENOM_ASS,   "DOSS_IDENT_PRENOM_ASS",     &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_PROF,         "DOSS_IDENT_PROF",           &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_TITRE,        "DOSS_IDENT_TITRE",          &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_IDENT_REF_PK,       "DOSS_IDENT_REF_PK",         &line , err); if (err.length())     goto SetConfBase_Error;

  //................. DOSS_NOTE_TBL_NAME ............................
  pt = SetConfBase_SetProperties(deb,  m_DOSS_NOTE_TBL_NAME,       "DOSS_NOTE_TBL_NAME",         &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_NOTE_PK,             "DOSS_NOTE_PK",               &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_NOTE_PAT_GUID,       "DOSS_NOTE_PAT_GUID",         &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_NOTE_PAT_PK,         "DOSS_NOTE_PAT_PK",           &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_NOTE_HTML,           "DOSS_NOTE_HTML",             &line , err); if (err.length())     goto SetConfBase_Error;

  //................. DOSS_INTERVENANTS_TBL_NAME ............................
  pt = SetConfBase_SetProperties(deb,  m_DOSS_INTERVENANTS_TBL_NAME,       "DOSS_INTERVENANTS_TBL_NAME",         &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_INTERVENANTS_PK,             "DOSS_INTERVENANTS_PK",               &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_INTERVENANTS_PAT_GUID,       "DOSS_INTERVENANTS_PAT_GUID",         &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_INTERVENANTS_PAT_PK,         "DOSS_INTERVENANTS_PAT_PK",           &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_INTERVENANTS_INTERVPK,       "DOSS_INTERVENANTS_INTERVPK",         &line , err); if (err.length())     goto SetConfBase_Error;

  //................. INTERVENANTS_TBL_NAME ............................
  pt = SetConfBase_SetProperties(deb,  m_INTERVENANTS_TBL_NAME,       "INTERVENANTS_TBL_NAME",         &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_INTERVENANTS_PK,             "INTERVENANTS_PK",               &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_INTERVENANTS_NOM,            "INTERVENANTS_NOM",              &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_INTERVENANTS_PRENOM,         "INTERVENANTS_PRENOM",           &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_INTERVENANTS_SPEC,           "INTERVENANTS_SPEC",             &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_INTERVENANTS_TITRE,          "INTERVENANTS_TITRE",            &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_INTERVENANTS_RUE,            "INTERVENANTS_RUE",              &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_INTERVENANTS_CODE_POST,      "INTERVENANTS_CODE_POST",        &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_INTERVENANTS_VILLE,          "INTERVENANTS_VILLE",            &line , err); if (err.length())     goto SetConfBase_Error;

  //............................ DOSS_HISTO_TBL_NAME ...........................................................
  pt = SetConfBase_SetProperties(deb,  m_DOSS_HISTO_TBL_NAME,       "DOSS_HISTO_TBL_NAME",         &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_HISTO_GUID,           "DOSS_HISTO_GUID",             &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_HISTO_DATE,           "DOSS_HISTO_DATE",             &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_HISTO_DUREE,          "DOSS_HISTO_DUREE",            &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_HISTO_USER,           "DOSS_HISTO_USER",             &line , err); if (err.length())     goto SetConfBase_Error;

  //............................ DOSS_RUB_HEAD_TBL_NAME ...........................................................
  pt = SetConfBase_SetProperties(deb,  m_DOSS_RUB_HEAD_TBL_NAME,      "DOSS_RUB_HEAD_TBL_NAME",         &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_RUB_HEAD_PRIMKEY,       "DOSS_RUB_HEAD_PRIMKEY",          &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_RUB_HEAD_GUID,          "DOSS_RUB_HEAD_GUID",             &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_RUB_HEAD_TYPE,          "DOSS_RUB_HEAD_TYPE",             &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_RUB_HEAD_SUBTYPE,       "DOSS_RUB_HEAD_SUBTYPE",          &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_RUB_HEAD_NOM_DATE,      "DOSS_RUB_HEAD_NOM_DATE",         &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_RUB_HEAD_DATE,          "DOSS_RUB_HEAD_DATE",             &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_RUB_HEAD_USER,          "DOSS_RUB_HEAD_USER",             &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_RUB_HEAD_SIGN_USER,     "DOSS_RUB_HEAD_SIGN_USER",        &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_RUB_HEAD_REF_BLOBS_PK,  "DOSS_RUB_HEAD_REF_BLOBS_PK",     &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_RUB_HEAD_FIN,           "DOSS_RUB_HEAD_FIN",              &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_RUB_HEAD_REF_DOSS_PK,   "DOSS_RUB_HEAD_REF_DOSS_PK",      &line , err); if (err.length())     goto SetConfBase_Error;

  //................. DOSS_RUB_DATA_TBL_NAME ......................................................................................
  pt = SetConfBase_SetProperties(deb,  m_DOSS_RUB_DATA_TBL_NAME,      "DOSS_RUB_DATA_TBL_NAME",         &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_RUB_DATA_GUID,          "DOSS_RUB_DATA_GUID",             &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_RUB_DATA_PRIMKEY,       "DOSS_RUB_DATA_PRIMKEY",          &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_DOSS_RUB_DATA_BLOB,          "DOSS_RUB_DATA_BLOB",             &line , err); if (err.length())     goto SetConfBase_Error;

  //................. USER_IDENT_TBL_NAME ......................................................................................
  pt = SetConfBase_SetProperties(deb,  m_USER_IDENT_TBL_NAME,      "USER_IDENT_TBL_NAME",         &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_NOM,           "USER_IDENT_NOM",              &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_PRENOM,        "USER_IDENT_PRENOM",           &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_TITRE,         "USER_IDENT_TITRE",            &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_LOGIN,         "USER_IDENT_LOGIN",            &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_PASSWORD,      "USER_IDENT_PASSWORD",         &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_DROITS,        "USER_IDENT_DROITS",           &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_SEXE,          "USER_IDENT_SEXE",             &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_NUM_ORDRE,     "USER_IDENT_NUM_ORDRE",        &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_PRIMKEY,       "USER_IDENT_PRIMKEY",          &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_GUID,          "USER_IDENT_GUID",             &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_CONVENTION,    "USER_IDENT_CONVENTION",       &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_CODE_POST,     "USER_IDENT_CODE_POST",        &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_VILLE,         "USER_IDENT_VILLE",            &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_RUE,           "USER_IDENT_RUE",              &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_QUALITE,       "USER_IDENT_QUALITE",          &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_TEL_1,         "USER_IDENT_TEL_1",            &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_TEL_2,         "USER_IDENT_TEL_2",            &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_TEL_3,         "USER_IDENT_TEL_3",            &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_EMAIL,         "USER_IDENT_EMAIL",            &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_NOTE,          "USER_IDENT_NOTE",             &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_CODE_REGIME,   "USER_IDENT_CODE_REGIME",      &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_CHER,          "USER_IDENT_CHER",             &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_TEL_TYPE_1,    "USER_IDENT_TEL_TYPE_1",       &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_TEL_TYPE_2,    "USER_IDENT_TEL_TYPE_2",       &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_TEL_TYPE_3,    "USER_IDENT_TEL_TYPE_3",       &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_TEL_ABR_1,     "USER_IDENT_TEL_ABR_1",        &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_TEL_ABR_2,     "USER_IDENT_TEL_ABR_2",        &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_IDENT_TEL_ABR_3,     "USER_IDENT_TEL_ABR_3",        &line , err); if (err.length())     goto SetConfBase_Error;

  //................. USER_DATA_TBL_NAME ............................
  pt = SetConfBase_SetProperties(deb,  m_USER_DATA_TBL_NAME,      "USER_DATA_TBL_NAME",         &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_DATA_PK,            "USER_DATA_PK",               &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_DATA_REF_PK,        "USER_DATA_REF_PK",           &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_DATA_NAMEDOC,       "USER_DATA_NAMEDOC",          &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_DATA_TYPE,          "USER_DATA_TYPE",             &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_USER_DATA_BLOB,          "USER_DATA_BLOB",             &line , err); if (err.length())     goto SetConfBase_Error;

  //................. VERROUS ............................
  pt = SetConfBase_SetProperties(deb,  m_VERROU_TBL_NAME,         "VERROU_TBL_NAME",            &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_VERROU_PK,               "VERROU_PK",                  &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_VERROU_DOSS_PK,          "VERROU_DOSS_PK",             &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_VERROU_DOSS_GUID,        "VERROU_DOSS_GUID",           &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_VERROU_RUB_NAME,         "VERROU_RUB_NAME",            &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_VERROU_RUB_PK,           "VERROU_RUB_PK",              &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_VERROU_USER_NAME,        "VERROU_USER_NAME",           &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_VERROU_SIGN_USER_NAME,   "VERROU_SIGN_USER_NAME",      &line , err); if (err.length())     goto SetConfBase_Error;
  pt = SetConfBase_SetProperties(pt,   m_VERROU_DATE_TIME,        "VERROU_DATE_TIME",           &line , err); if (err.length())     goto SetConfBase_Error;

 //................. USER_PERMS ............................
  pt = SetConfBase_SetProperties(deb,  m_USER_PERMS_TBL_NAME,      "USER_PERMS_TBL_NAME",       &line , err); if (err.length())     goto SetConfBase_Error;       // nom de la table des droits des utilisateurs non prescripteurs
  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_PK,            "USER_PERMS_PK",             &line , err); if (err.length())     goto SetConfBase_Error;       // clef primaire de cet enregistrement
  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_SIGN_GUID,     "USER_PERMS_SIGN_GUID",      &line , err); if (err.length())     goto SetConfBase_Error;       // Ref au GUID du signataire autorisant cet utilisateur
  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_GUID,   "USER_PERMS_FRIEND_GUID",    &line , err); if (err.length())     goto SetConfBase_Error;       // GUID de cet utilisateur
  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_DROITS, "USER_PERMS_FRIEND_DROITS",  &line , err); if (err.length())     goto SetConfBase_Error;       // Droits que le signataire attribue à cet utilisateur
  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_BLOBS,  "USER_PERMS_FRIEND_BLOBS",   &line , err); if (err.length())     goto SetConfBase_Error;       // Configuration des autorisations fines (liste des fichiers autorisés avec les droits)
  return 1;

SetConfBase_Error:
  if (errMess) *errMess = err;
  qDebug(err);
  return 0;

}

//--------------------------------------------- SetConfBase_SetProperties ------------------------------------------------
char  *CMoteurBase::SetConfBase_SetProperties(char *pt, QString &propertie, const char *token, int *line , QString &err)
{int nLine = *line;
 err  = "";
 long len_token = strlen (token);
 while(*pt)
    {SKIP_BLANK_CAR(pt);
     if (strncmp(pt, token, len_token)==0)
        {//return pt+len_token;
         pt         += len_token;
         err         = "";
         propertie   = "";
         //............. chercher premier delimiteur ...............................
          while(*pt && *pt!='\r' && *pt !='\n' && *pt !='\'' ) pt++;
          if (*pt=='\'')         // si delimiteur pas trouve erreur
             {pt++;               // passer le delimiteur
              char *end = pt;
              //............. chercher deuxiéme delimiteur ...............................
              while(*end && *end!='\r' && *end !='\n' && *end !='\'')end++;
              if (*end=='\'')
                 {propertie.setLatin1(pt, end-pt);
                  if (line) *line = nLine;
                  return end +1;
                 }
              else
                {err  = TR("Syntax Error: SetConfBaseGetValue()\r\n End delimiter \"'\"  not find at line N°: ");
                 err += QString::number(nLine);
                 if (line) *line = nLine;
                 return 0;
                }
             }
           else
             {err  = TR("Syntax Error: SetConfBaseGetValue()\r\n Start delimiter \"'\"  not find at line N°: ");
              err += QString::number(nLine);
              if (line) *line = nLine;
              return 0;
             }
        } //endif (strncmp(pt, token, len_token)==0)

     NEXT_LINE(pt);
     ++nLine;

    }
 err  = "Syntax Error: SetConfBase()\r\n";
 err += token;
 err += TR(" non trouvé à la ligne N°: ");
 err += QString::number(nLine);
 if (line) *line = nLine;
 return pt;
}


//-----------------------------------------------------  GotoDebug -------------------------------------------
void CMoteurBase::GotoDebug()
{
}
//----------------------------------------------- GetNbRecord ---------------------------------------------------
QString CMoteurBase::GetNbRecord(const QString &table)
{ QString result = "";
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE) return QString::null;

  //................. SI un nom ou prenom est donné en entrée alors filtrer selon ...................
  QString requete = QString("SELECT COUNT(*) FROM ") + table;
  QSqlQuery query(requete , m_DataBase );
  if (query.isActive() && query.next())
     {result = query.value(0).toString();
     }
  m_DataBase->close();
  return result;
}

//--------------------------------- Utf8_Query ------------------------------------------------------------
QString CMoteurBase::Utf8_Query(QSqlQuery &cur, int field)
{QCString     cString  = cur.value(field).toCString ();
 char *ptr             =  cString.data();
 if (CGestIni::IsUtf8( ptr ))
    {return QString::fromUtf8 ( ptr );
    }
 else
    {return QString(ptr) ;
    }
}

//************************************************************************************************************************
//=================================== GESTION DES CONVERSIONS DE BASE ET INTEGRITE ======================================
//************************************************************************************************************************
void CMoteurBase::RenameTableWhithCorrectName()
{if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return;
     QSqlQuery query(QString::null, m_DataBase);
     //.................. renommer correctement les tables .....................................
     //                   (ces foutus dump de windows ne respectent pas la casse)
     RenameTableWhithCorrectName(m_DOSS_INDEX_TBL_NAME,        &query);
     RenameTableWhithCorrectName(m_DOSS_IDENT_TBL_NAME,        &query);
     RenameTableWhithCorrectName(m_DOSS_NOTE_TBL_NAME,         &query);
     RenameTableWhithCorrectName(m_DOSS_INTERVENANTS_TBL_NAME, &query);
     RenameTableWhithCorrectName(m_INTERVENANTS_TBL_NAME,      &query);
     RenameTableWhithCorrectName(m_DOSS_RUB_HEAD_TBL_NAME,     &query);
     RenameTableWhithCorrectName(m_DOSS_RUB_DATA_TBL_NAME,     &query);
     RenameTableWhithCorrectName(m_USER_IDENT_TBL_NAME,        &query);
     RenameTableWhithCorrectName(m_USER_DATA_TBL_NAME,         &query);
     RenameTableWhithCorrectName(m_VERROU_TBL_NAME,            &query);
     RenameTableWhithCorrectName("Agenda_Mask",                                &query);
 m_DataBase->close();
}

//---------------------------------------- RenameTableWhithCorrectName ------------------------------------------------
void CMoteurBase::RenameTableWhithCorrectName(const QString &correct_name_table, QSqlQuery *pQSqlQuery)
{QStringList list = m_DataBase->tables();
 QStringList::Iterator it = list.begin();
 while( it != list.end() )
      {if (correct_name_table.lower()== (*it).lower())
          {pQSqlQuery->exec(QString("ALTER TABLE `") + (*it) + "` RENAME `"+correct_name_table+"` ;");
          }
       ++it;
      }
}

//-----------------------------------------------------  ConvertToNew -------------------------------------------
int CMoteurBase::ConvertToNew(QLabel* pQlabelMess /* = 0 */, QProgressBar* pQProgressBar /* = 0 */)
{int i=0;
 QString qstr;
 m_ConvertRun = TRUE;

 m_ConvertRun = 1;
 if (pQProgressBar)  pQProgressBar->setTotalSteps ( GetNbRecord(m_DOSS_RUB_HEAD_TBL_NAME).toLong() );

 //................. Preparer la requete .....................................
 if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)
    {if (pQlabelMess) pQlabelMess->setText(qstr.sprintf(TR("ConvertToNew(): database can't be open")));
     return i;
    }

 //................. Preparer la requete .....................................
 QString      requete  = "SELECT ";
              requete += m_DOSS_RUB_HEAD_PRIMKEY + "," + m_DOSS_RUB_HEAD_GUID + " FROM " + m_DOSS_RUB_HEAD_TBL_NAME;
 QSqlQuery sqlQuery(requete , m_DataBase );
 if (sqlQuery.isActive())
    { QSqlQuery     queryTarget (QString::null, m_DataBase  );
      //............................ Pour tous les enregistrements maitres ...............................
      while (sqlQuery.next() && m_ConvertRun)
        {//......................... Recuperer Infos maitres .............................................
         QString primKey_Master     = sqlQuery.value( 0 ).toString();   // Recuperer PrimKey maitre
         QString GUID_Master        = sqlQuery.value( 1 ).toString();   // Recuperer GUID    maitre
         requete                    = "";
         requete                   += "UPDATE "                     + m_DOSS_RUB_HEAD_TBL_NAME   + " SET "    +
                                       m_DOSS_RUB_HEAD_REF_BLOBS_PK + " = '" + primKey_Master    + "' WHERE " +
                                       m_DOSS_RUB_HEAD_PRIMKEY      + " ='"  + primKey_Master    + "'";
         queryTarget.exec (requete);
         if (queryTarget.isActive())
            {requete                    = "";
             requete                   += "UPDATE "                     + m_DOSS_RUB_DATA_TBL_NAME   + " SET "    +
                                          m_DOSS_RUB_DATA_GUID          + " = '" + GUID_Master       + "' WHERE " +
                                          m_DOSS_RUB_DATA_PRIMKEY       + " ='"  + primKey_Master    + "'";
             queryTarget.exec (requete);
             if (queryTarget.isActive())
                {
                 if (pQlabelMess)
                    {pQlabelMess->setText(qstr.sprintf("indexation N°: %i", i));
                     if (pQProgressBar)  pQProgressBar->setProgress ( ++m_ConvertRun );
                     qApp->processEvents();qApp->processEvents();
                    }
                }
            }
         else
            {qstr   = "";
                 qstr  += requete;
             qstr  += TR("\r\nIndexation error: ");
             switch(queryTarget.lastError().type())
               {case QSqlError::None :        qstr  += "no error occurred";          break;
                case QSqlError::Connection :  qstr  += "connection error";           break;
                case QSqlError::Statement :   qstr  += "SQL statement syntax error"; break;
                case QSqlError::Transaction : qstr  += "transaction failed error";   break;
                case QSqlError::Unknown :     qstr  += "unknown error";              break;
               }
             if (pQlabelMess)
                 {pQlabelMess->setText(qstr);
                  qApp->processEvents();qApp->processEvents();
                 }
             return i;
            }
         i++;
        } //end while (pSqlQuery->next())
    } //end if (pSqlQuery && pSqlQuery->isActive())
 m_DataBase->close();
 if (pQlabelMess) pQlabelMess->setText(qstr.sprintf("Opération terminée °: %i enregistrements traités", i));
 if (pQProgressBar)  pQProgressBar->setTotalSteps ( 0 );
 return i;
}

//************************************************************************************************************************
//=================================== GESTION CODE POSTAL ================================================================
//************************************************************************************************************************

//-----------------------------------------------------  GetVilleFromCodePostal -------------------------------------------
QString CMoteurBase::GetVilleFromCodePostal(const QString &codePostal)
{ QString result  ("");
  QString requete ("SELECT ville FROM codes_postaux WHERE code_postal = ");
          requete +=  codePostal ;
  if (m_DataBase==0)                                              return result;
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)   return result;
  QSqlQuery query(requete , m_DataBase );
  if (query.isActive() && query.next())
     {result = Utf8_Query(query, 0);
     }
  m_DataBase->close();
  return result;
}

//-----------------------------------------------------  GetCodePostalFromVille -------------------------------------------
QString CMoteurBase::GetCodePostalFromVille(const QString &ville)
{ QString result  ("");
  QString requete ("SELECT code_postal FROM codes_postaux WHERE ville = '");
          requete +=  ville + "'";
  if (m_DataBase==0)                                              return result;
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)   return result;
  QSqlQuery query(requete , m_DataBase );
  if (query.isActive() && query.next())
     {result = Utf8_Query(query,0);
     }
  m_DataBase->close();
  return result;
}

//-----------------------------------------------------  GetVilleFromCodePostal -------------------------------------------
void CMoteurBase::GetVilleFromCodePostal(const QString &codePostal, QStringList &villeList)
{ QString cdPost (codePostal);
  if (cdPost[0]=='0') cdPost.remove(0,1);
  villeList.clear();
  QString requete ("SELECT ville FROM codes_postaux WHERE code_postal = ");
          requete +=  cdPost ;
  if (m_DataBase==0)                                              return ;
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)   return ;
  QSqlQuery query(requete , m_DataBase );
  if (query.isActive())
     {while(query.next()) villeList.append( Utf8_Query(query,0));
     }
  m_DataBase->close();
  return;
}

//-----------------------------------------------------  GetCodePostalFromVille -------------------------------------------
void CMoteurBase::GetCodePostalFromVille(const QString &ville, QStringList &codePostalList)
{ codePostalList.clear();
  QString requete ("SELECT code_postal , ville FROM codes_postaux WHERE ville  LIKE '");
          requete +=  ville + "%'";
  if (m_DataBase==0)                                              return ;
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)   return ;
  QSqlQuery query(requete , m_DataBase );
  if (query.isActive())
     {while(query.next())
         {QString codePostal (query.value(0).toString());
          if (codePostal.length()<5) codePostal.prepend("0");
          codePostalList.append( codePostal +" "+ Utf8_Query(query,1));
         }
     }
  m_DataBase->close();
  return;
}

//************************************************************************************************************************
//=================================== GESTION DOSSIER PATIENT ============================================================
//************************************************************************************************************************

//-----------------------------------------------------  GetPatientList -------------------------------------------
/*! \brief Remplit la QListView avec les patients retrouvés dans la base de données.
 *  \param pQlistView : ListView qui recevra les patients recherchés
 *  \param qsrt_nom : Nom à rechercher
 *  \param qsrt_prenom : Prenom à rechercher
 *  \param statusMess : message de retour
 *  \param errMess : Message d'erreur.
 *  \return nombre d'enregistrements insérés dans la QListView passée en paramètre
*/ 
long CMoteurBase::GetPatientList(       QListView *pQlistView,
                                  const QString   &qstr_nom,
                                  const QString   &qstr_prenom,
                                        QLabel    *statutMess, /* = 0  */
                                        QLabel    *errMess     /* = 0  */
                                )
{QString   q_nom    = "";
 QString   q_prenom = "";
 QString tmp = "";
 //................. Preparer la requete .....................................
  if (m_DataBase==0)
     {if (errMess) errMess->setText("CMoteurBase::GetPatientList(): m_DataBase = 0 (create error) ");
      return 0;
     }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)
     {if (errMess) errMess->setText("CMoteurBase::GetPatientList(): data base can't be open");
      return 0;
     }
  QString requete, requete_ident;
  if (qstr_nom != ""||qstr_prenom!="")
     {q_nom    = qstr_nom;
      q_prenom = qstr_prenom;
     }
  q_nom.replace("\'","\\\'");
  int nb_columns = pQlistView->columns();
  requete        = "SELECT ";
  requete       += m_DOSS_INDEX_NOM + ", " + m_DOSS_INDEX_PRENOM + ", \n";
  requete	+= m_DOSS_INDEX_PRIM_KEY + ", " + m_DOSS_INDEX_GUID + " \n";
  requete       += " FROM "            + m_DOSS_INDEX_TBL_NAME   + " \nWHERE ";
  requete       += m_DOSS_INDEX_NOM    + " LIKE '"+ q_nom        + "%' \nAND ";
  requete       += m_DOSS_INDEX_PRENOM + " LIKE '"+ q_prenom     + "%' \n";
  requete       += " ORDER BY "        + m_DOSS_INDEX_NOM;

  QSqlQuery query(requete , m_DataBase );
  QSqlQuery query_ident;

  //................ scanner les enregistrements ................................................
  //                 pour remplir la listview

  int i  = 0;
  int nb = 0;
  //.................. si la requète a un resultat ..............................................
  if (query.isActive())
  {pQlistView->clear();
   while (query.next())
   { if (i < 200)
     { QListViewItem *element = 0;
       CPrtQListViewItem* line = 0;
       //............... on rempli la listbox selon son nombre de colonnes .....................
       switch (nb_columns)
       {case 1:
		element = new QListViewItem( pQlistView,
						Utf8_Query(query, 0 ) );
		break;
	case 2:
		element = new QListViewItem( pQlistView,
						Utf8_Query(query, 0 ),
						Utf8_Query(query, 1 ) );
                        break;
	case 3:
		element = new QListViewItem( pQlistView,
						Utf8_Query(query, 0 ),
						Utf8_Query(query, 1 ),
						Utf8_Query(query, 2 ) );
		break;
	case 4:
		element = new QListViewItem( pQlistView,
						Utf8_Query(query, 0 ), 		// Nom
						Utf8_Query(query, 1 ),  	// Prenom
						Utf8_Query(query, 2 ),		// PK
						Utf8_Query(query, 3 ) );	// GUID
		break;
	case 8 : // Récupère les élèments d'identité en plus
	{ requete_ident	= "SELECT " + m_DOSS_IDENT_RUE + ", " + m_DOSS_IDENT_CODE_POST + ", \n";
	  requete_ident	+= m_DOSS_IDENT_VILLE + ", " + m_DOSS_IDENT_JFNOM + ", \n";
	  requete_ident	+= m_DOSS_IDENT_TEL1 + ", " + m_DOSS_IDENT_TEL2 + " \n";
	  requete_ident	+= " FROM " + m_DOSS_IDENT_TBL_NAME + " \nWHERE ";
	  requete_ident	+= m_DOSS_IDENT_REF_PK    + " = "+ query.value(2).toString() + "; \n";
	  query_ident = QSqlQuery(requete_ident , m_DataBase );
	  if ( query_ident.isActive() && query_ident.next())
	  { line = new CPrtQListViewItem( pQlistView , line, Utf8_Query(query, 0 )); // Nom 
	    // Si pas de CP enregistré alors il est == 0 ==> ne pas l'afficher
	    tmp = Utf8_Query(query_ident, 1) ;
	    if (tmp == "0") tmp ="";
	    line->setText( 1, Utf8_Query(query_ident, 3) );	// Nom JF
	    line->setText( 2, Utf8_Query(query, 1 ) );		// Prenom
	    line->setText( 3, Utf8_Query(query_ident, 0) );	// Rue
	    line->setText( 4, tmp );	// CP
	    line->setText( 5, Utf8_Query(query_ident, 2));	// Ville
	    line->setText( 6, Utf8_Query(query_ident, 4));	// Tél 1
	    line->setText( 7, Utf8_Query(query_ident, 5));	// Tél 2
	    line->setMultiLinesEnabled ( FALSE );		//Plusieurs lignes par item si nécessaire
	    // Dichotomiser Affichage et données à exploiter +++
	    line->setNom(    Utf8_Query(query, 0 ) );		// Nom
	    line->setPrenom( Utf8_Query(query, 1 ) );		// Prenom
	    line->setPkDoc(  Utf8_Query(query, 2 ) );		// PK
	    line->setGUID(   Utf8_Query(query, 3 ) );		// GUID

	  }
	  break;
	}
       } // end switch (nb_columns)
       if (element) pQlistView->insertItem ( element );
       else if (line) pQlistView->insertItem ( line );
       i++;
     } // // fin if i < 200
     nb++;
   } //end while (pSqlQuery->next())

   // Cacher les contenus des colonnes 8 et 9 si 10 demandés
   if (nb_columns == 10)
   { pQlistView->hideColumn ( 8 );
     pQlistView->hideColumn ( 9 );
   }
  } //endif (pSqlQuery && pSqlQuery->isActive())

  //ListViewPatient->setCurrentItem(0);   // se placer sur le premier enregistrement de la liste
  //....................... sortir le message d'erreur si besoin ..........................................

  if (statutMess)
     { statutMess->setText( QString( TR("Trouvé(s) %1 parmi %2") ).arg(i).arg(nb) );
     }
  m_DataBase->close();
  return i;
}

//-------------------------------------- GetIdentiteFromPrimKey ----------------------------------------------------------------------------
/*! \brief Sélectionne l'enregistrement de la table: DOSS_IDENT  correspondant au bon primary key
*   \return QSqlQuery*  zero si echec valide sinon et AUQUEL CAS IL FAUDRA DETRUIRE ce pointeur par: delete  pSqlQuery et AUQUEL CAS IL FAUDRA FERMER la base par:       m_DataBase->close()
*/
QSqlQuery*  CMoteurBase::GetIdentiteFromPrimKey(const char *primKey )
{QString requete;

 requete   = "SELECT * FROM "    + m_DOSS_IDENT_TBL_NAME + " WHERE ";
 requete  += m_DOSS_IDENT_REF_PK + " ='"                 + primKey + "'";

 if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)
     {return 0;
     }
 QSqlQuery* pSqlQuery = new QSqlQuery(requete , m_DataBase );
 if (pSqlQuery && pSqlQuery->isActive() && pSqlQuery->next())
    {return pSqlQuery;
    } //if (pSqlQuery && pSqlQuery->isActive() && pSqlQuery->next())
 if (pSqlQuery) delete  pSqlQuery;
 m_DataBase->close();
 return 0;
}


//************************************************************************************************************************
//=================================== GESTION DES FUSIONS ================================================================
//************************************************************************************************************************


//------------------------------------------------------- GetFieldValue --------------------------------------------------
QString CMoteurBase::GetFieldValue(QString table, QString fieldToGet, QString fieldToMatch, QString valueToMatch,  QVariant *pQVariant /*= 0*/ )
{QString   ret("");
 //............... ouvrir la base  ..................................................
 if  (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return ret;
 ret = GetFieldValue_WithoutOpenCloseBase( table,  fieldToGet,  fieldToMatch,  valueToMatch,  pQVariant);
 m_DataBase->close();
 return ret;
 }

//------------------------------------------------------- GetFieldValue_WithoutOpenCloseBase --------------------------------------------------
QString CMoteurBase::GetFieldValue_WithoutOpenCloseBase(QString table, QString fieldToGet, QString fieldToMatch, QString valueToMatch,  QVariant *pQVariant /*= 0*/ )
{QString   ret("");
 //............... crer un curseur SQL ..................................................
 QSqlCursor cur(table, TRUE, m_DataBase);                                          // ouvrir un curseur sur la table
 if (!cur.select( fieldToMatch+"='"+valueToMatch+"'" )) goto  GetFieldValueError;       // se placer sur le bon record
 if (cur.next())                             {QCString     cString  = cur.value(fieldToGet).toCString ();
                                              char *ptr             =  cString.data();
                                              if (pQVariant)  *pQVariant = cur.value( fieldToGet);

                                              if (CGestIni::IsUtf8( ptr ))
                                                 {ret = QString::fromUtf8 ( ptr );
                                                 }
                                              else
                                                 {ret = QString(ptr) ;
                                                 }
                                              return ret;
                                             }
GetFieldValueError:
     OutSQL_error(cur, "GetFieldValue()", cur.filter());
     return QString("");
 }

//************************************************************************************************************************
//=================================== GESTION DES NOTES ET INTERVENANTS PATIENT ==========================================
//************************************************************************************************************************

//-------------------------------------- PatientIntervenantsGetData ----------------------------------------------------------------------------
void CMoteurBase::PatientIntervenantsGetData(const char *primKeyPat , QListView *pQListView, QString *errMess /*=0*/)
{ QStringList pkIntervList;
  pQListView->clear();
  //................. Preparer la requete .....................................
  if (m_DataBase==0)
     {if (errMess) *errMess = "CMoteurBase::PatientIntervenantsGetData(): m_DataBase = 0 (create error) ";
      return ;
     }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)
     {if (errMess) *errMess = "CMoteurBase::PatientIntervenantsGetData(): database can't be opened";
      return ;
     }
  //................. recuperer tous les PK des intervenants sur ce patient ..................................................
  QString requete("");
  requete  += "SELECT " + m_DOSS_INTERVENANTS_INTERVPK  + " FROM " + m_DOSS_INTERVENANTS_TBL_NAME   + " WHERE ";
  requete  +=             m_DOSS_INTERVENANTS_PAT_PK    + " = '"   + primKeyPat                     + "' ";
  QSqlQuery* pSqlQuery = new QSqlQuery(requete , m_DataBase );
  //.................. si la requète a un resultat ..............................................
  if (pSqlQuery && pSqlQuery->isActive())
     { while (pSqlQuery->next())
         {pkIntervList.append( pSqlQuery->value( 0 ).toString());
         }
     }
  if (pSqlQuery) delete  pSqlQuery;
  if (pkIntervList.count()==0)  {m_DataBase->close(); return;}
  for ( QStringList::Iterator it = pkIntervList.begin(); it != pkIntervList.end(); ++it )
      {requete   = "SELECT ";
       requete  +=   m_INTERVENANTS_SPEC+ "," +m_INTERVENANTS_NOM+ ","  +m_INTERVENANTS_PRENOM+ " FROM " +m_INTERVENANTS_TBL_NAME+ " WHERE ";
       requete  +=   m_INTERVENANTS_PK  + " = '"   + *(it) + "' ";
       QSqlQuery  query(requete , m_DataBase );
       if (query.isActive())
          { while (query.next())
              {//Utf8_Query(query, 0 );
               new QListViewItem(pQListView,
                                 Utf8_Query(query, 0  ),
                                 Utf8_Query(query, 1  ),
                                 Utf8_Query(query, 2  ),
                                 *(it)
                                 );
              }
          }
      }
  m_DataBase->close();
  return ;
}


//-------------------------------------- PatientIntervenantsGetData ----------------------------------------------------------------------------
void CMoteurBase::PatientIntervenantsGetData(const char *primKeyPat , QStringList &intervList, const QString &specialite, const char *validStr, const char *decalage) //Médecin généraliste
{ QStringList pkIntervList;
  //................. Preparer la requete .....................................
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return ;

  //................. recuperer tous les PK des intervenants sur ce patient ..................................................
  QString requete("");
  requete  += "SELECT " + m_DOSS_INTERVENANTS_INTERVPK  + " FROM " + m_DOSS_INTERVENANTS_TBL_NAME   + " WHERE ";
  requete  +=             m_DOSS_INTERVENANTS_PAT_PK    + " = '"   + primKeyPat                     + "' ";
  QSqlQuery query(requete , m_DataBase );
  //.................. si la requète a un resultat ..............................................
  if (query.isActive())
     { while (query.next())
         {pkIntervList.append( query.value( 0 ).toString());
         }
     }
  intervList.clear();
  QString fieldToRetrieve = "SELECT ";
  char *pt = (char *) validStr;
  while (*pt)
      {if (pt[0]!= ',')
          {fieldToRetrieve += IdentValidCarToFieldName(pt[0]);
           ++pt;
           if (*pt) fieldToRetrieve += ",";
          }
       else ++pt;
      }
  if (pkIntervList.count()==0)  {m_DataBase->close(); return;}
  for ( QStringList::Iterator it = pkIntervList.begin(); it != pkIntervList.end(); ++it )
      {requete   = fieldToRetrieve;
       requete  += " FROM " + m_INTERVENANTS_TBL_NAME+ " WHERE ";
       requete  +=   m_INTERVENANTS_PK  + " = '"   + *(it) + "' ";
       if (specialite.length()) requete  += "AND " + m_INTERVENANTS_SPEC + " = '" + specialite + "'";
       query.exec( requete );
       if (query.isActive())
          {QString ofset = decalage ;
           while (query.next())
              {QString str = ofset;        // on commence au decalage
               int       i = 0;
                        pt = (char *) validStr;
               while (*pt)
                     {if (pt[0]== ',') str +=  QString("<br>") + ofset ; // la prochaine ligne commence au decalage
                      else
                                      {QString  result = Utf8_Query(  query, i++  );
                                       result = result.replace("\r\n", "\n");
                                       result = result.replace("\n",   QString("<br>") + ofset) ;
                                       str   += result + " ";
                                      }
                      ++pt;
                     }
              intervList.append(str);
              }
          }
      }
  m_DataBase->close();
  return ;
}

//-------------------------------------- IdentValidCarToFieldName ----------------------------------------------------------------------------
QString CMoteurBase::IdentValidCarToFieldName(int c)
{switch (c)
   {case 'N': return m_INTERVENANTS_NOM;
    case 'P': return m_INTERVENANTS_PRENOM;
    case 'A': return m_INTERVENANTS_RUE;
    case 'C': return m_INTERVENANTS_CODE_POST;
    case 'V': return m_INTERVENANTS_VILLE;
    case 'T': return m_INTERVENANTS_TITRE;
    case 'S': return m_INTERVENANTS_SPEC;
   }
 return QString("");
}

//-------------------------------------- PatientIntervenantsWrite ----------------------------------------------------------------------------
int CMoteurBase::PatientIntervenantsWrite( const char *primKeyPat , const char* guidPat,  const char* intervPk)
{QString pk = PatientIntervenantsIsThisExist(intervPk, primKeyPat);
 if (pk.length()>0) return 0;                                                   // existe déjà donc à ne pas créer
 else               return PatientIntervenantsCreate(primKeyPat , guidPat,   intervPk);     // n'existe pas donc créer
}

//---------------------------------------------------- PatientIntervenantsIsThisExist -----------------------------------------------
// RETOUR:    la primKey des données si elles existent sinon ""
QString CMoteurBase::PatientIntervenantsIsThisExist( const char* intervPk, const char *primKeyPat, QLabel *errMess )
{ QString ret("");
  //................. Preparer la requete .....................................
  if (m_DataBase==0)
     {if (errMess) errMess->setText("CMoteurBase::PatientIntervenantIsThisExist(): m_DataBase = 0 (create error) ");
      return ret;
     }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)
     {if (errMess) errMess->setText("CMoteurBase::PatientIntervenantIsThisExist(): database can't be opened");
      return ret;
     }
  //................. filtrer selon donnée d'entrée ..................................................
  QString requete("");
  requete  += "SELECT " + m_DOSS_INTERVENANTS_PK          + " FROM " + m_DOSS_INTERVENANTS_TBL_NAME   + "  WHERE ";
  requete  +=             m_DOSS_INTERVENANTS_INTERVPK    + " = '"   + intervPk                       + "' AND ";
  requete  +=             m_DOSS_INTERVENANTS_PAT_PK      + " = '"   + primKeyPat                     + "'  ";

  QSqlQuery query(requete , m_DataBase );

  //.................. si la requète a un resultat ..............................................
  if (query.isActive() && query.next())
     {ret = Utf8_Query(query, 0 );
     }
  m_DataBase->close();
  return ret;
}

//-------------------------------------- PatientIntervenantsCreate ----------------------------------------------------------------------------
int CMoteurBase::PatientIntervenantsCreate(const char *primKeyPat , const char* guidPat,  const char* intervPk)
{
  //................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  int ok  = FALSE;
  //............... ouvrir la base .......................................................
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;
  //............... crer un curseur SQL ..................................................
  QSqlCursor cur(m_DOSS_INTERVENANTS_TBL_NAME, TRUE, m_DataBase);
  if ( !cur.canInsert ()) {m_DataBase->close(); return FALSE;}
  //............... si OK on recupere le buffer et on le charge avec les données .........
  QSqlRecord *buffer = cur.primeInsert();                         // recuperer le buffer d'insertion
  buffer->setValue( m_DOSS_INTERVENANTS_PAT_PK,        primKeyPat );  // y placer les données
  buffer->setValue( m_DOSS_INTERVENANTS_PAT_GUID,      guidPat );     // y placer les données
  buffer->setValue( m_DOSS_INTERVENANTS_INTERVPK,      intervPk    );     // y placer les données
  ok = cur.insert();                                          // ecrire le buffer avec les données du header
  //......................... fermer la base ..............................................
  m_DataBase->close();
  return ok;
}

//-------------------------------------- PatientIntervenantsDelete ----------------------------------------------------------------------------
int CMoteurBase::PatientIntervenantsDelete( const char *primKey, const char *path_GUID /* = 0 */)
{ //................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  int ok  = FALSE;
  
  //............... ouvrir la base .......................................................
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;
  QString requete("DELETE FROM ");
          requete += m_DOSS_INTERVENANTS_TBL_NAME  + " WHERE ";
          requete += m_DOSS_INTERVENANTS_INTERVPK  + "= '" + primKey + "' ";
  if (path_GUID) 
         {requete += " AND " + m_DOSS_INTERVENANTS_PAT_GUID  + "= '" + path_GUID + "' ";
         }
 QSqlQuery* pSqlQuery = new QSqlQuery(QString::null , m_DataBase );
 if (pSqlQuery) ok = pSqlQuery->exec(requete);
 if (pSqlQuery) delete  pSqlQuery;
 m_DataBase->close();
 return ok;
}

//-------------------------------------- PatientIntervenantsAllDelete ----------------------------------------------------------------------------
int CMoteurBase::PatientIntervenantsAllDelete( const char *primKeyPat)
{ //................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  int ok  = FALSE;
  //............... ouvrir la base .......................................................
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;
  QString requete("DELETE FROM ");
          requete += m_DOSS_INTERVENANTS_TBL_NAME  + " WHERE ";
          requete += m_DOSS_INTERVENANTS_PAT_PK    + "= '" + primKeyPat + "' ";
 QSqlQuery* pSqlQuery = new QSqlQuery(QString::null , m_DataBase );
 if (pSqlQuery) ok = pSqlQuery->exec(requete);
 if (pSqlQuery) delete  pSqlQuery;
 m_DataBase->close();
 return ok;
}

//---------------------------------------------------- PatientNoteIsThisExist -----------------------------------------------
/*! \brief  RETOUR:    la primKey des données si elles existent sinon "" */
QString CMoteurBase::PatientNoteIsThisExist(  const char *primKeyPat,
                                              QLabel          *errMess          /* = 0  */
                                           )
{ QString ret("");
  //................. Preparer la requete .....................................
  if (m_DataBase==0)
     {if (errMess) errMess->setText("CMoteurBase::IsThisPatientNoteExist(): m_DataBase = 0 (create error) ");
      return ret;
     }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)
     {if (errMess) errMess->setText("CMoteurBase::IsThisPatientNoteExist(): database can't be opened");
      return ret;
     }
  //................. filtrer selon donnée d'entrée ..................................................
  QString requete("");
  requete  += "SELECT " + m_DOSS_NOTE_PK        + " FROM " + m_DOSS_NOTE_TBL_NAME   + " WHERE ";
  requete  +=             m_DOSS_NOTE_PAT_PK    + " = '"   + primKeyPat             + "' ";

  QSqlQuery query(requete , m_DataBase );

  //.................. si la requète a un resultat ..............................................
  if (query.isActive() && query.next())
     {ret = Utf8_Query(query, 0 );
     }
  m_DataBase->close();
  return ret;
}

//-------------------------------------- PatientNoteDelete ----------------------------------------------------------------------------
int CMoteurBase::PatientNoteDelete( const char *primKey)
{ //................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  int ok  = FALSE;
  //............... ouvrir la base .......................................................
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;
  QString requete("DELETE FROM ");
          requete += m_DOSS_NOTE_TBL_NAME + " WHERE ";
          requete += m_DOSS_NOTE_PK       + "= '" + primKey                  + "' ";
 QSqlQuery* pSqlQuery = new QSqlQuery(QString::null , m_DataBase );
 if (pSqlQuery) ok = pSqlQuery->exec(requete);
 if (pSqlQuery) delete  pSqlQuery;
 m_DataBase->close();
 return ok;
}

//-------------------------------------- PatientNoteCreate ----------------------------------------------------------------------------
int CMoteurBase::PatientNoteCreate(const char *primKeyPat , const char* guidPat,  const char* data)
{
  //................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  int ok  = FALSE;
  //............... ouvrir la base .......................................................
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;
  //............... crer un curseur SQL ..................................................
  QSqlCursor cur(m_DOSS_NOTE_TBL_NAME, TRUE, m_DataBase);
  if ( !cur.canInsert ()) {m_DataBase->close(); return FALSE;}
  //............... si OK on recupere le buffer et on le charge avec les données .........
  QSqlRecord *buffer = cur.primeInsert();                         // recuperer le buffer d'insertion
  buffer->setValue( m_DOSS_NOTE_PAT_PK,        primKeyPat );  // y placer les données
  buffer->setValue( m_DOSS_NOTE_PAT_GUID,      guidPat );     // y placer les données
  buffer->setValue( m_DOSS_NOTE_HTML,          data    );     // y placer les données
  ok = cur.insert();                                          // ecrire le buffer avec les données du header
  //......................... fermer la base ..............................................
  m_DataBase->close();
  return ok;
}

//-------------------------------------- PatientNoteWrite ----------------------------------------------------------------------------
int CMoteurBase::PatientNoteWrite( const char *primKeyPat , const char* guidPat,  const char* data)
{QString pk = PatientNoteIsThisExist(primKeyPat);
 if (pk.length()>0)
    {if (data[0]==0) return PatientNoteDelete(pk);
     else            return PatientNoteUpdate(pk, primKeyPat , guidPat,   data);
    }
 else
    {if (data[0]!=0) return PatientNoteCreate(primKeyPat , guidPat,   data);
    }
 return 0;
}

//-------------------------------------- PatientNoteUpdate ----------------------------------------------------------------------------
int CMoteurBase::PatientNoteUpdate(const char* primKey, const char *primKeyPat , const char* guidPat,  const char* data)
{
 //................................. methode QSqlCursor .................................
 //                         ne pose pas de PB avec valeur avec une apostrophe
 //............... crer un curseur SQL ..................................................
 if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return FALSE;
 int ok = FALSE;
 QSqlCursor cur(m_DOSS_NOTE_TBL_NAME, TRUE, m_DataBase);
 if ( !cur.canUpdate ()) {m_DataBase->close(); return FALSE;}
 //............... placer ce curseur sur le bon enregistrement ..........................
 cur.select(m_DOSS_NOTE_PK  + "='" + primKey  + "'" );
  //............... si OK on recupere le buffer et on le charge avec les données .........
 if ( cur.next() )
    {QSqlRecord *buffer = cur.primeUpdate();                             // recuperer le buffer ( pas de delete à la fin !!)
     buffer->setValue( m_DOSS_NOTE_PAT_PK,        primKeyPat );  // y placer les données
     buffer->setValue( m_DOSS_NOTE_PAT_GUID,      guidPat );     // y placer les données
     buffer->setValue( m_DOSS_NOTE_HTML,          data    );     // y placer les données
     ok    = cur.update();                                               // ecrire le buffer avec les données du header
    }
 if (ok==0) OutSQL_error(cur, "PatientNoteUpdate()");

  //......................... fermer la base ..............................................
  m_DataBase->close();
  return ok;
}

//-------------------------------------- PatientNoteGetData ----------------------------------------------------------------------------
void CMoteurBase::PatientNoteGetData(const char *primKeyPat ,  QString& data, QString *errMess /*=0*/)
{ data = "";
  //................. Preparer la requete .....................................
  if (m_DataBase==0)
     {if (errMess) *errMess = "CMoteurBase::PatientNoteGetData(): m_DataBase = 0 (create error) ";
      return ;
     }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)
     {if (errMess) *errMess = "CMoteurBase::PatientNoteGetData(): database can't be opened";
      return ;
     }
  //................. filtrer selon donnée d'entrée ..................................................
  QString requete("");
  requete  += "SELECT " + m_DOSS_NOTE_HTML        + " FROM " + m_DOSS_NOTE_TBL_NAME   + " WHERE ";
  requete  +=             m_DOSS_NOTE_PAT_PK      + " = '"   + primKeyPat             + "' ";

  QSqlQuery query(requete , m_DataBase );

  //.................. si la requète a un resultat ..............................................
  if (query.isActive() && query.next())
     {data = Utf8_Query(query, 0 );
     }
  m_DataBase->close();
  return ;
}

//************************************************************************************************************************
//=================================== GESTION DES UTILISATEURS ===========================================================
//************************************************************************************************************************
//************************************************************************************************************************
//=================================== GESTION DES PARAMETRES =============================================================
//************************************************************************************************************************

 //................. USER_PERMS ............................
 //  pt = SetConfBase_SetProperties(deb,  m_USER_PERMS_TBL_NAME,      "USER_PERMS_TBL_NAME",       &line , err); if (err.length())     goto SetConfBase_Error;       // nom de la table des droits des utilisateurs non prescripteurs
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_PK,            "USER_PERMS_PK",             &line , err); if (err.length())     goto SetConfBase_Error;       // clef primaire de cet enregistrement
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_SIGN_GUID,     "USER_PERMS_SIGN_GUID",      &line , err); if (err.length())     goto SetConfBase_Error;       // Ref au GUID du signataire autorisant cet utilisateur
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_GUID,   "USER_PERMS_FRIEND_GUID",    &line , err); if (err.length())     goto SetConfBase_Error;       // GUID de cet utilisateur
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_DROITS, "USER_PERMS_FRIEND_DROITS",  &line , err); if (err.length())     goto SetConfBase_Error;       // Droits que le signataire attribue à cet utilisateur
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_BLOBS,  "USER_PERMS_FRIEND_BLOBS",   &line , err); if (err.length())     goto SetConfBase_Error;       // Configuration des autorisations fines (liste des fichiers autorisés avec les droits)
//-------------------------------------- PermsUserCreateOrUpdate ----------------------------------------------------------------------------
QString CMoteurBase::PermsUserCreateOrUpdate(const QString &primKey , const QString &droits , const QString &signGUID, const QString &permsGUID,  const QString &blobs)
{if (primKey.length()<=0)
    {return PermsUserCreate(droits , signGUID, permsGUID,  blobs);
    }
 PermsUserUpdate(primKey , droits , signGUID, permsGUID,  blobs);
 return primKey;
}

//-------------------------------------- PermsUserUpdate ----------------------------------------------------------------------------
int CMoteurBase::PermsUserUpdate(const QString &primKey , const QString &droits , const QString &signGUID, const QString &permsGUID,  const QString &blobs)
{ //................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  int ok  = FALSE;
  //............... ouvrir la base .......................................................
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;

  //............... crer un curseur SQL ..................................................
  QSqlCursor cur(m_USER_PERMS_TBL_NAME, TRUE, m_DataBase);
  if ( !cur.canUpdate ()) {/*DeVerrouilleTable(m_DataBase); */m_DataBase->close(); return FALSE;}
  //............... placer ce curseur sur le bon enregistrement ..........................
  cur.select(  m_USER_PERMS_PK + "='" + primKey + "'");
  //............... si OK on recupere le buffer et on le charge avec les données .........
 if ( cur.next() )
    {QSqlRecord *buffer = cur.primeUpdate();                        // recuperer le buffer ( pas de delete à la fin !!)
     buffer->setValue( m_USER_PERMS_FRIEND_DROITS,        droits );      // y placer les données
     buffer->setValue( m_USER_PERMS_SIGN_GUID,            signGUID );    // y placer les données
     buffer->setValue( m_USER_PERMS_FRIEND_GUID,          permsGUID );   // y placer les données
     buffer->setValue( m_USER_PERMS_FRIEND_BLOBS,         blobs );       // y placer les données
     ok = cur.update();                                                  // ecrire le buffer avec les données du header
    }
  //......................... fermer la base ..............................................
  //DeVerrouilleTable(m_DataBase);
  m_DataBase->close();
  return ok;
}

//-------------------------------------- PermsUserCreate ----------------------------------------------------------------------------
QString CMoteurBase::PermsUserCreate(const QString &droits , const QString &signGUID, const QString &permsGUID,  const QString &blobs)
{
  //................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  int ok  = FALSE;
  //............... ouvrir la base .......................................................
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;
  //............... crer un curseur SQL ..................................................
  QSqlCursor cur(m_USER_PERMS_TBL_NAME, TRUE, m_DataBase);
  if ( !cur.canInsert ()) {m_DataBase->close(); return FALSE;}
  //............... si OK on recupere le buffer et on le charge avec les données .........
  QSqlRecord *buffer = cur.primeInsert();                             // recuperer le buffer d'insertion
  buffer->setValue( m_USER_PERMS_FRIEND_DROITS,        droits );      // y placer les données
  buffer->setValue( m_USER_PERMS_SIGN_GUID,            signGUID );    // y placer les données
  buffer->setValue( m_USER_PERMS_FRIEND_GUID,          permsGUID );   // y placer les données
  buffer->setValue( m_USER_PERMS_FRIEND_BLOBS,         blobs );       // y placer les données
  ok = cur.insert();                                                  // ecrire le buffer avec les données du header

  //................. reselectionner l'enregistrement créé pour retrouver son PK avec le GUID temporaire........................
  QString prim_key = QString::null;
  QString   requete("SELECT ");
  requete += m_USER_PERMS_PK            + " FROM " + m_USER_PERMS_TBL_NAME   + " WHERE "
          +  m_USER_PERMS_SIGN_GUID     + "='"     + signGUID                + "' AND  "
          +  m_USER_PERMS_FRIEND_GUID   + "='"     + permsGUID               + "' "; // retrouver le Pk de l'enregistrement créé avec le GUID temporaire
  QSqlQuery sqlQuery(requete , m_DataBase );
  if (sqlQuery.isActive() && sqlQuery.next()) prim_key = sqlQuery.value(0).toString();
  //......................... fermer la base ..............................................
  m_DataBase->close();
  return prim_key;
}

//-------------------------------------- PermsUserDeleteFromPk ----------------------------------------------------------------------------
int CMoteurBase::PermsUserDeleteFromPk( const char *primKey)
{ //................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  int ok  = FALSE;
  //............... ouvrir la base .......................................................
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;
  QString requete("DELETE FROM ");
          requete += m_USER_PERMS_TBL_NAME  + " WHERE ";
          requete += m_USER_PERMS_PK        + "= '" + primKey + "' ";
 QSqlQuery* pSqlQuery = new QSqlQuery(QString::null , m_DataBase );
 if (pSqlQuery) ok = pSqlQuery->exec(requete);
 if (pSqlQuery) delete  pSqlQuery;
 m_DataBase->close();
 return ok;
}
//-------------------------------------- PermsUserRefToUserDelete ----------------------------------------------------------------------------
int  CMoteurBase::PermsUserRefToUserDelete( const char *userGUID)
{//................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  int ok  = FALSE;
  //............... ouvrir la base .......................................................
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;
  QString requete("DELETE FROM ");
          requete += m_USER_PERMS_TBL_NAME       + " WHERE ";
          requete += m_USER_PERMS_FRIEND_GUID    + "= '" + userGUID + "' ";
 QSqlQuery* pSqlQuery = new QSqlQuery(QString::null , m_DataBase );
 if (pSqlQuery) ok = pSqlQuery->exec(requete);
 if (pSqlQuery) delete  pSqlQuery;
 m_DataBase->close();
 return ok;
}

//-------------------------------------- PermsUserListDelete ----------------------------------------------------------------------------
int CMoteurBase::PermsUserListDelete( const char *signUserGUID)
{ //................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  int ok  = FALSE;
  //............... ouvrir la base .......................................................
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;
  QString requete("DELETE FROM ");
          requete += m_USER_PERMS_TBL_NAME     + " WHERE ";
          requete += m_USER_PERMS_SIGN_GUID    + "= '" + signUserGUID + "' ";
 QSqlQuery* pSqlQuery = new QSqlQuery(QString::null , m_DataBase );
 if (pSqlQuery) ok = pSqlQuery->exec(requete);
 if (pSqlQuery) delete  pSqlQuery;
 m_DataBase->close();
 return ok;
}

//-----------------------------------------------------  PermsUserGetList -------------------------------------------
//   QString      m_USER_IDENT_TBL_NAME;           // nom de la table des données des RUBRIQUES
//   QString      m_USER_IDENT_NOM;                // Nom
//   QString      m_USER_IDENT_PRENOM;             // Prenom

long CMoteurBase::PermsUserGetList(          QListView *pQlistView,
                                       const QString   &signGUID,
                                       const QString   &imagePath,
                                        QLabel    *statutMess, /* = 0  */
                                        QLabel    *errMess     /* = 0  */
                             )
{//................. Preparer la requete .....................................
  if (m_DataBase==0)
     {if (errMess) errMess->setText("CMoteurBase::GetUserPermsList(): m_DataBase = 0 (create error) ");
      return 0;
     }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)
     {if (errMess) errMess->setText("CMoteurBase::GetUserPermsList(): database can't be opened");
      return 0;
     }
//  pt = SetConfBase_SetProperties(deb,  m_USER_PERMS_TBL_NAME,      "USER_PERMS_TBL_NAME",       &line , err); if (err.length())     goto SetConfBase_Error;       // nom de la table des droits des utilisateurs non prescripteurs
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_PK,            "USER_PERMS_PK",             &line , err); if (err.length())     goto SetConfBase_Error;       // clef primaire de cet enregistrement
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_SIGN_GUID,     "USER_PERMS_SIGN_GUID",      &line , err); if (err.length())     goto SetConfBase_Error;       // Ref au GUID du signataire autorisant cet utilisateur
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_GUID,   "USER_PERMS_FRIEND_GUID",    &line , err); if (err.length())     goto SetConfBase_Error;       // GUID de cet utilisateur
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_DROITS, "USER_PERMS_FRIEND_DROITS",  &line , err); if (err.length())     goto SetConfBase_Error;       // Droits que le signataire attribue à cet utilisateur
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_BLOBS,  "USER_PERMS_FRIEND_BLOBS",   &line , err); if (err.length())     goto SetConfBase_Error;       // Configuration des autorisations fines (liste des fichiers autorisés avec les droits)
 /*
 QString requete ="SELECT " + m_USER_IDENT_TBL_NAME  + "." + m_USER_IDENT_LOGIN                + ", "       // 0
                            + m_USER_IDENT_TBL_NAME  + "." + m_USER_IDENT_NOM                  + ", "       // 1
                            + m_USER_IDENT_TBL_NAME  + "." + m_USER_IDENT_PRENOM               + ", "       // 2
                            + m_USER_PERMS_TBL_NAME  + "." + m_USER_PERMS_FRIEND_DROITS        + ", "       // 3
                            + m_USER_PERMS_TBL_NAME  + "." + m_USER_PERMS_PK                   + ", "       // 4
                            + m_USER_IDENT_TBL_NAME  + "." + m_USER_IDENT_GUID                 + " FROM "   // 5
                            + m_USER_PERMS_TBL_NAME  + " INNER JOIN " + m_USER_IDENT_TBL_NAME  + " ON "
                            + m_USER_IDENT_TBL_NAME  + "." + m_USER_IDENT_GUID + " = " + m_USER_PERMS_TBL_NAME + "." + m_USER_PERMS_SIGN_GUID + " WHERE "
                            + m_USER_PERMS_SIGN_GUID + " = '" + signGUID  + "' ORDER BY " +  m_USER_IDENT_TBL_NAME  + "." + m_USER_IDENT_LOGIN;
*/
pQlistView->clear();
QString requete = "SELECT "  + m_USER_PERMS_PK                + ", "                                                // 0
                             + m_USER_PERMS_SIGN_GUID         + ", "                                                // 1
                             + m_USER_PERMS_FRIEND_GUID       + ", "                                                // 2
                             + m_USER_PERMS_FRIEND_DROITS     + ", "                                                // 3
                             + m_USER_PERMS_FRIEND_BLOBS      + " FROM " + m_USER_PERMS_TBL_NAME + " WHERE "        // 4
                             + m_USER_PERMS_SIGN_GUID         + " = '"   + signGUID +"'";
  QSqlQuery query(requete , m_DataBase );
  //Param_UpdateToDisk("/home/ro/TestSql.txt", requete);
  //................ scanner les enregistrements ....................................................
  //                 pour remplir la listview
  int       nb = 0;
  //.................. si la requète a un resultat ..............................................
  if (query.isActive())
     {pQlistView->clear();
      while (query.next())
        {QString requetePermsUser = "SELECT "  + m_USER_IDENT_LOGIN                + ", "                                                 // 0
                                               + m_USER_IDENT_NOM                  + ", "                                                 // 1
                                               + m_USER_IDENT_PRENOM               + " FROM " + m_USER_IDENT_TBL_NAME + " WHERE  "        // 2
                                               + m_USER_IDENT_GUID                 + " = '"   + Utf8_Query(query, 2 ) + "'";              // m_USER_PERMS_FRIEND_GUID
         QSqlQuery queryPermsUser(requetePermsUser , m_DataBase );
          if (queryPermsUser.isActive())
            {
             while (queryPermsUser.next())
                   { QListViewItem *pQListViewItem = new QListViewItem( pQlistView ,
                                                                        Utf8_Query(queryPermsUser, 0 ),       // login
                                                                        Utf8_Query(queryPermsUser, 1 ),       // nom
                                                                        Utf8_Query(queryPermsUser, 2 ),       // prenom
                                                                        "",                                   // +
                                                                        "",                                   // -
                                                                        Utf8_Query(query,          3 ),       // droits
                                                                        Utf8_Query(query,          0 ),       // pk
                                                                        Utf8_Query(query,          2 )        // GUID du permsUser
                                                                      );
                     if (pQListViewItem)
                        {pQListViewItem->setText(8,Utf8_Query(query,          4 ) );          // BLOBS du permsUser
                         pQListViewItem->setPixmap (3, QPixmap(imagePath+"Plus.png") ) ;
                         pQListViewItem->setPixmap (4, QPixmap(imagePath+"Moins.png") ) ;
                        }

                     nb++;
                  }  //endwhile (queryPermsUser.next())
           } //endif (queryPermsUser.isActive())
        } //end while (pSqlQuery->next())
     } //endif (pSqlQuery && pSqlQuery->isActive())

  //....................... sortir le message d'erreur si besoin ..........................................
  if (statutMess)
     { statutMess->setText(TR("Trouvés: ") + QString::number(nb));
     }
  m_DataBase->close();
  return nb;
}
//-----------------------------------------------------  TypeDoc_To_PrintTypeDoc -------------------------------------------
int  CMoteurBase::TypeDoc_To_PrintTypeDoc(int typeDoc)
{if (typeDoc >= TYP_ORDO_CALC && typeDoc <= TYP_ORDONNANCE)
    {return TYP_ORDONNANCE;  // sub type 0->RECTO   1->VERSO
    }
 else if (typeDoc == TYP_COURRIER)
    {return TYP_COURRIER;
    }
 else if (typeDoc == TYP_CERTIFICAT)
    {return TYP_CERTIFICAT;
    }
 else if (typeDoc == TYP_OBSERVATION)
    {return TYP_OBSERVATION;
    }
 else if (typeDoc >= TYP_PRESCRIPTION &&  typeDoc <= TYP_PRESCRIPTION+999)
    {return  TYP_ORDONNANCE;
    }
 else if (typeDoc >= TYP_DOCUMENTS &&  typeDoc <= TYP_DOCUMENTS+999)
    {return  TYP_DOCUMENTS;
    }
 return 0;
}

//-----------------------------------------------------  GetUserPrimKeyFromNumOrdre -------------------------------------------
QString  CMoteurBase::GetUserPrimKeyFromNumOrdre(QString nir, QString droit /* = QString::null*/, QStringList *pFiedList /*=0*/)
{ //................. Preparer la requete .....................................
  QString ret = "";
  int nbField = 0;
  int       i = 0;
  if (m_DataBase==0)                                             { return QString::null; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  { return QString::null; }
  nir = nir.remove(' ').left(9);      // corriger les évntuels espace parasites rentrés à la main et infos suplémentaires
  //................. SI un nom ou prenom est donné en entrée alors filtrer selon ...................
  QString requete("SELECT ");
  requete += m_USER_IDENT_PRIMKEY + "," + m_USER_IDENT_NUM_ORDRE;
  if (pFiedList)
     {nbField = pFiedList->count();
      for ( QStringList::Iterator it = pFiedList->begin(); it != pFiedList->end(); ++it )
          {requete += "," + *it;
          }
     }
  requete += " FROM " + m_USER_IDENT_TBL_NAME;
  if (droit.length())
     {if (droit[0]!='-') droit.prepend('-');
      requete += " WHERE " + m_USER_IDENT_DROITS + " LIKE'%" +droit +"%'";
     }
  QSqlQuery query(requete , m_DataBase );
  if (query.isActive())
     {while (query.next())
           {QString numOrdre = query.value( 1 ).toString();
            numOrdre         = numOrdre.remove(' ').left(9);
            if (numOrdre == nir)
               {if (nbField)
                   {pFiedList->clear();
                    for ( i = 0; i < nbField; ++i ) pFiedList->append(query.value( 2+i ).toString());
                   }
                ret = query.value( 0 ).toString();
                break;
               }
           }
     } //endif (pSqlQuery && pSqlQuery->isActive())
  m_DataBase->close();
  return ret;
}
//-----------------------------------------------------  GetUserPrimKeyFromGUID -------------------------------------------
QString  CMoteurBase::GetUserPrimKeyFromGUID(const QString &guid)
{ //................. Preparer la requete .....................................
  QString ret = "";
  if (m_DataBase==0)                                             { return QString::null; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  { return QString::null; }
  //................. SI un nom ou prenom est donné en entrée alors filtrer selon ...................
  QString requete("SELECT ");
  requete += m_USER_IDENT_PRIMKEY + " FROM " + m_USER_IDENT_TBL_NAME + " WHERE " + m_USER_IDENT_GUID + "='" + guid +"'";
  QSqlQuery query(requete , m_DataBase );
  if (query.isActive() && query.next())
     {ret = query.value( 0 ).toString();
     } //endif (pSqlQuery && pSqlQuery->isActive())
  m_DataBase->close();
  return ret;
}

//-----------------------------------------------------  TypeDoc_To_PrintTypeDoc -------------------------------------------
QString  CMoteurBase::TypeDoc_To_PrintTypeDoc(const QString &typeDoc)
{return QString::number(TypeDoc_To_PrintTypeDoc(typeDoc.toInt()));
}

//-----------------------------------------------------  GetUserPrimKey -------------------------------------------
QString CMoteurBase::GetUserPrimKey(QString user, QString *cripted_password   /* = 0  */)
{if (cripted_password) *cripted_password = "";
 QString   ret="";
 //............... chaines d'erreurs  ..................................................
 if  (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return ret;

 //............... crer un curseur SQL ..................................................
 QSqlCursor cur(m_USER_IDENT_TBL_NAME, TRUE, m_DataBase);                     // ouvrir un curseur sur la table
 if (!cur.select( m_USER_IDENT_LOGIN  + "='" + user + "'" ))  goto GetUserPrimKeyError;

 if (cur.next())
    {ret = cur.value( m_USER_IDENT_PRIMKEY).toString();
     if (cripted_password) *cripted_password = cur.value( m_USER_IDENT_PASSWORD).toString();
     m_DataBase->close();
     return ret;
    }

GetUserPrimKeyError:
   OutSQL_error(cur, "GetUserPrimKey()");
   //m_DataBase->close();
   return ret;
}

//-----------------------------------------------------  SaveUserPassWord --------------------------------------------------
int CMoteurBase::VerifyUserPassWord(QString user, QString password)
{QString  cripted_password;
 if (GetUserPrimKey(user, &cripted_password )   == "")             return FALSE;
 if (password.length()==0 && cripted_password.length()==0)         return TRUE;
 if (cripted_password == password)                                 return TRUE;
 if (PassWordDecode(cripted_password, password) == ERR_PASS_MAX)   return FALSE;
 return TRUE;
}

//-----------------------------------------------------  SaveUserPassWord --------------------------------------------------
int CMoteurBase::SaveUserPassWord(QString user, QString cripted_password)
{//............... chaines d'erreurs  ..................................................
 if  (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return FALSE;

 //............... crer un curseur SQL ..................................................
 QSqlCursor cur(m_USER_IDENT_TBL_NAME, TRUE, m_DataBase);                      // ouvrir un curseur sur la table
 if ( !cur.canUpdate ()) {m_DataBase->close(); return FALSE;}                  // cassos si peut pas etre mis a jour
 if ( !cur.select( m_USER_IDENT_LOGIN  + "='" + user + "'" ))  goto SaveUserPassWordError;

 if (cur.next())
    {QSqlRecord *buffer = cur.primeUpdate();                                   // recuperer le buffer ( pas de delete à la fin !!)
     buffer->setValue( m_USER_IDENT_PASSWORD,   cripted_password);
     cur.update();                                                     // ecrire le buffer avec les données
    }
 m_DataBase->close();
   return TRUE;

SaveUserPassWordError:
   OutSQL_error(cur, "SaveUserPassWord()");
   m_DataBase->close();
   return FALSE;
}

//-----------------------------------------------------  GetUserDocument -------------------------------------------
QString CMoteurBase::GetUserDocument(const char*     user,
                                     const char*     nameDocType,
                                     int             type,        // TYP_ORDONNANCE 2  TYP_CERTIFICAT 3 TYP_OBSERVATION 4 TYP_OBSERVATION  5 TYP_PARAM
                                     QString*        pFoot,       // adresse de la chaine où l'on veut recuperer le pied de page
                                     int             sub_type,    // 0 par defaut (RECTO) 1 si l'on veut le DUPLICATA (que pour TYP_ORDONNANCE)
                                     QString*        pk_record)   // = 0;
{QString       ret = "";
 if (pFoot) *pFoot = "";
 //..................... rechercher PK de l'utilisateur ...................
 QString userPk = GetUserPrimKey(user);
 if (userPk == "")   return ret;

 //..................... rechercher PK des données ........................
 QString dataPk = IsThisUserDocExist(type, userPk, nameDocType);
 if (pk_record)  *pk_record = dataPk;
 if (dataPk == "")   return ret;
 return GetUserDocument(dataPk, type,  pFoot,  sub_type );
}

//-----------------------------------------------------  GetUserDocument -------------------------------------------
QString CMoteurBase::GetUserDocument(QString         dataPk,
                                     int             type,
                                     QString*        pFoot,       // adresse de la chaine où l'on veut recuperer le pied de page
                                     int             sub_type     // 0 par defaut (RECTO) 1 si l'on veut le DUPLICATA (que pour TYP_ORDONNANCE)
                                     )
{QString       ret = "";
 //..................... rechercher les données ...........................
 QString text = GetUserDataFromPrimKey(dataPk);
 if (text == "")     return ret;

 //..................... retirer les bonnes données ........................
 //                     a priori on considère que le recto
 if (type == 0)
    {if (text.find("}} /r/n{{") != -1)           type = TYP_ORDONNANCE;
     else if (text.find("}}==/r/n=={{") != -1)   type = TYP_CERTIFICAT;
     else  return text;
    }
 int pos_end;
 int pos_deb ;
 if (type==TYP_PARAM)     return text;
 if (type==TYP_ORDONNANCE)
    {//............... RECTO ....................
     pos_end  = text.find("}} /r/n{{");
     pos_deb  = 2;
     if (pos_end == -1)    return ret;
     ret = text.mid (pos_deb, pos_end-pos_deb );

     pos_deb      = text.find("{{", pos_end);
     if (pos_deb  == -1)   return ret;
     pos_deb     += 2;
     pos_end      = text.find("}} /r/n{{", pos_deb);
     if (pos_end  ==-1)    return ret;
     if (pFoot) *pFoot = text.mid (pos_deb, pos_end-pos_deb );
     //............... DUPLICATA ....................
     if (sub_type)
        {ret = "";
         pos_deb      = text.find("{{", pos_end);
         if (pos_deb  == -1)   return ret;
         pos_deb     += 2;
         pos_end      = text.find("}} /r/n{{", pos_deb);
         if (pos_end  ==-1)    return ret;
         ret = text.mid (pos_deb, pos_end-pos_deb );

         pos_deb      = text.find("{{", pos_end);
         if (pos_deb  == -1)   return ret;
         pos_deb     += 2;
         pos_end      = text.find("}} /r/n", pos_deb);
         if (pos_end  ==-1)    return ret;
         if (pFoot) *pFoot = text.mid (pos_deb, pos_end-pos_deb );
        }
    }
 else
   {pos_end  = text.find("}}==/r/n=={{");            // header
    pos_deb  = 4;
    if (pos_end == -1)    return ret;
    ret = text.mid (pos_deb, pos_end-pos_deb );

    pos_deb      = text.find("=={{", pos_end);       // foot
    if (pos_deb  == -1)   return ret;
    pos_deb     += 4;
    pos_end      = text.find("}}==/r/n", pos_deb);
    if (pos_end  ==-1) return ret;
    if (pFoot) *pFoot = text.mid (pos_deb, pos_end-pos_deb );
   }
 return ret;
}


//-------------------------------------------------- OutSQL_error -----------------------------------------------
void CMoteurBase::OutSQL_error(QSqlQuery &cur, const char *messFunc /*=0*/, const char *requete /*=0*/)
{    QSqlError error = cur.lastError();
     QString   qserr("");

     if (error.type() != QSqlError::None)
        {switch (error.type())
           { case    QSqlError::None:           qserr =" - no error occurred: "          ; break;
             case    QSqlError::Connection:     qserr =" - connection error: "           ; break;
             case    QSqlError::Statement:      qserr =" - SQL statement syntax error: " ; break;
             case    QSqlError::Transaction:    qserr =" - transaction failed error: "   ; break;
             case    QSqlError::Unknown:        qserr =" - unknown error: "              ; break;
             default:                           qserr =" - unknown error: "              ; break;
           }
         if (messFunc) qDebug(messFunc);
         qDebug(qserr + error.databaseText ());
         if (requete) qDebug(requete);
        }
}


//-----------------------------------------------------  GetUserPermisions -------------------------------------------
QString CMoteurBase::GetUserPermisions( QString &user, QString    *errMess /* = 0 */ )
{ //................. Preparer la requete .....................................
  if (m_DataBase==0)                                             {if (errMess) *errMess = TR("CMoteurBase::GetUserPermisions(): m_DataBase = 0 (create error) "); return QString::null; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  {if (errMess) *errMess = TR("CMoteurBase::GetUserPermisions(): database can't be opened");       return QString::null; }
  //................. SI un nom ou prenom est donné en entrée alors filtrer selon ...................
  QString droits = "";
  QString requete("SELECT ");
  requete       += m_USER_IDENT_DROITS  +  " FROM " + m_USER_IDENT_TBL_NAME + " WHERE " + m_USER_IDENT_LOGIN + " = '" + user +"'";
  QSqlQuery query(requete , m_DataBase );
  if (query.isActive())
     {while (query.next())  droits = Utf8_Query(query, 0 );
     } //endif (pSqlQuery && pSqlQuery->isActive())
  m_DataBase->close();
  return droits;
}

//-----------------------------------------------------  UserDroitsCount -------------------------------------------
int CMoteurBase::UserDroitsCount(const QString &droitToFind , QString    *errMess)
{ int nb = 0;
  //................. Preparer la requete .....................................
  if (m_DataBase==0)                                             {if (errMess) *errMess = TR("CMoteurBase::GetUserPermisions(): m_DataBase = 0 (create error) "); return -1; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  {if (errMess) *errMess = TR("CMoteurBase::GetUserPermisions(): database can't be opened");       return -1; }
  //................. SI un nom ou prenom est donné en entrée alors filtrer selon ...................
  QString droits = "";
  QString requete("SELECT ");
  requete       += m_USER_IDENT_DROITS  +  " FROM " + m_USER_IDENT_TBL_NAME + " WHERE " + m_USER_IDENT_DROITS + " LIKE '%"+droitToFind+"%'";
  QSqlQuery query(requete , m_DataBase );
  if (query.isActive())
     {while (query.next())  ++nb;
     } //endif (pSqlQuery && pSqlQuery->isActive())
  m_DataBase->close();
  return nb;
}
//-----------------------------------------------------  GetUserList -------------------------------------------
void CMoteurBase::GetUserList( QListView *pQlistView, const QStringList &listUserAlreadyPresent, QString    *errMess /* = 0 */ )
{ //................. Preparer la requete .....................................
  if (m_DataBase==0)                                             {if (errMess) *errMess = "CMoteurBase::GetUserList(): m_DataBase = 0 (create error) "; return ; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  {if (errMess) *errMess = "CMoteurBase::GetUserList(): database can't be opened";       return ; }
  //................. SI un nom ou prenom est donné en entrée alors filtrer selon ...................
  QString requete("SELECT ");
  requete       += m_USER_IDENT_LOGIN    + "," +            // 0
                   m_USER_IDENT_NOM      + "," +            // 1
                   m_USER_IDENT_PRENOM   + "," +            // 2
                   m_USER_IDENT_PRIMKEY  + "," +            // 3
                   m_USER_IDENT_GUID     + " FROM  " +      // 4
                   m_USER_IDENT_TBL_NAME + " WHERE " + m_USER_IDENT_DROITS + " LIKE '%-med%' ORDER BY " + m_USER_IDENT_LOGIN;
  QSqlQuery query(requete , m_DataBase );
  if (query.isActive())
     {
      while (query.next())
            {QString str = Utf8_Query(query, 0 );
             if (listUserAlreadyPresent.findIndex(str)==-1) new QListViewItem(     pQlistView,
                                                                                   str,
                                                                                   Utf8_Query(query, 1 ),
                                                                                   Utf8_Query(query, 2 ),
                                                                                   Utf8_Query(query, 3 ),
                                                                                   Utf8_Query(query, 4 )
                                                                              );
            }
     } //endif (pSqlQuery && pSqlQuery->isActive())
  m_DataBase->close();
}

//-----------------------------------------------------  GetUserList -------------------------------------------
void CMoteurBase::GetUserList( QStringList &qstringList, QLabel    *errMess /* = 0 */ )
{ //................. Preparer la requete .....................................
  if (m_DataBase==0)                                             {if (errMess) errMess->setText("CMoteurBase::GetUserList(): m_DataBase = 0 (create error) "); return ; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  {if (errMess) errMess->setText("CMoteurBase::GetUserList(): database can't be opened");       return ; }
  //................. SI un nom ou prenom est donné en entrée alors filtrer selon ...................
  QString requete("SELECT ");
  requete       += m_USER_IDENT_LOGIN + ", " + m_USER_IDENT_DROITS  +  " FROM " +
                   m_USER_IDENT_TBL_NAME     + " WHERE " + m_USER_IDENT_DROITS + " LIKE '%-sgn%' ORDER BY " + m_USER_IDENT_LOGIN;
  QSqlQuery query(requete , m_DataBase );
  if (query.isActive())
     {qstringList.clear();
      while (query.next())  qstringList.append(Utf8_Query(query, 0 ));
     } //endif (pSqlQuery && pSqlQuery->isActive())
  m_DataBase->close();
}

//-----------------------------------------------------  PermsUserFatherGetQlistView -------------------------------------------
//   QString      m_USER_IDENT_TBL_NAME;           // nom de la table des données des RUBRIQUES
//   QString      m_USER_IDENT_NOM;                // Nom
//   QString      m_USER_IDENT_PRENOM;             // Prenom

void CMoteurBase::PermsUserFatherGetQlistView( QListView* pQlistView, const QString  &friendUser , const QString  &imagePath , QString    *errMess /* = 0 */)
{//  pt = SetConfBase_SetProperties(deb,  m_USER_PERMS_TBL_NAME,      "USER_PERMS_TBL_NAME",       &line , err); if (err.length())     goto SetConfBase_Error;       // nom de la table des droits des utilisateurs non prescripteurs
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_PK,            "USER_PERMS_PK",             &line , err); if (err.length())     goto SetConfBase_Error;       // clef primaire de cet enregistrement
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_SIGN_GUID,     "USER_PERMS_SIGN_GUID",      &line , err); if (err.length())     goto SetConfBase_Error;       // Ref au GUID du signataire autorisant cet utilisateur
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_GUID,   "USER_PERMS_FRIEND_GUID",    &line , err); if (err.length())     goto SetConfBase_Error;       // GUID de cet utilisateur
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_DROITS, "USER_PERMS_FRIEND_DROITS",  &line , err); if (err.length())     goto SetConfBase_Error;       // Droits que le signataire attribue à cet utilisateur
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_BLOBS,  "USER_PERMS_FRIEND_BLOBS",   &line , err); if (err.length())     goto SetConfBase_Error;       // Configuration des autorisations fines (liste des fichiers autorisés avec les droits)
  //QString signGUID   = GetFieldValue( m_USER_IDENT_TBL_NAME, m_USER_IDENT_GUID, m_USER_IDENT_LOGIN, signUser);
  QString friendGUID = GetFieldValue( m_USER_IDENT_TBL_NAME, m_USER_IDENT_GUID, m_USER_IDENT_LOGIN, friendUser);

  if (m_DataBase==0)                                             {if (errMess) *errMess = "CMoteurBase::GetUserList(): m_DataBase = 0 (create error) "; return ; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  {if (errMess) *errMess = "CMoteurBase::GetUserList(): database can't be opened";       return ; }

  QString requete ="SELECT "  + m_USER_IDENT_LOGIN                + ", "    // 0                                             // 0
                              + m_USER_IDENT_NOM                  + ", "    // 1                                             // 1
                              + m_USER_IDENT_PRENOM               + ", "    // 2
                              + m_USER_IDENT_PRIMKEY              + ", "    // 3
                              + m_USER_IDENT_GUID                 + "  "    // 4
                              + " FROM " + m_USER_IDENT_TBL_NAME  + " WHERE " + m_USER_IDENT_DROITS + " LIKE '%-sgn%' ORDER BY " + m_USER_IDENT_LOGIN;
  QSqlQuery query(requete , m_DataBase );
  //.................. si la requète a un resultat ..............................................
  if (query.isActive())
     {while (query.next())
        {QString login = Utf8_Query(query, 0 );
         if (login != friendUser)
            { QListViewItem *pQListViewItem = new QListViewItem(  pQlistView ,
                                                                  Utf8_Query(query, 0 ),         // login
                                                                  Utf8_Query(query, 1 ),         // nom
                                                                  Utf8_Query(query, 2 ),         // prenom
                                                                  "",                            // droits delegues
                                                                  query.value( 3 ).toString(),   // pk
                                                                  query.value( 4 ).toString()    // GUID du permsUser
                                                               );
             if (pQListViewItem)
                {QString requetePermsUser = "SELECT "  + m_USER_PERMS_FRIEND_DROITS  + ", "
                                                       + m_USER_PERMS_PK             + " FROM " + m_USER_PERMS_TBL_NAME       + " WHERE  "
                                                       + m_USER_PERMS_SIGN_GUID      + " = '"   + query.value( 4 ).toString() + "' AND "
                                                       + m_USER_PERMS_FRIEND_GUID    + " = '"   + friendGUID                  + "'";
                 QSqlQuery queryPermsUser(requetePermsUser , m_DataBase );
                 if (queryPermsUser.isActive() && queryPermsUser.next())
                    {QString droits = queryPermsUser.value( 0 ).toString();
                     droits = droits.remove("-sgn");
                     droits = droits.remove("-med");
                     pQListViewItem->setText(3, droits );          //  droits delegues
                     pQListViewItem->setText(6, queryPermsUser.value( 1 ).toString() );          //  pk de la table des permissions
                     pQListViewItem->setPixmap (0, QPixmap(imagePath+"CheckBoxOn.png") ) ;
                    }
                else
                    {pQListViewItem->setText(3, "" );                                            //  droits delegues
                     pQListViewItem->setText(6, "" );                                            //  pk de la table des permissions
                     pQListViewItem->setPixmap (0, QPixmap(imagePath+"CheckBoxOff.png") ) ;
                    }
               } // endif (pQListViewItem)
           } // endif (login != friendUser)
       }  //endwhile (query.next())
    } //endif (query.isActive())
  m_DataBase->close();
}
//-----------------------------------------------------  PermsUserChildGetList -------------------------------------------
//   QString      m_USER_IDENT_TBL_NAME;           // nom de la table des données des RUBRIQUES
//   QString      m_USER_IDENT_NOM;                // Nom
//   QString      m_USER_IDENT_PRENOM;             // Prenom

void CMoteurBase::PermsUserChildGetList(          QListViewItem *pQlistViewItem,
                                                  const QString  &signGUID )
{//  pt = SetConfBase_SetProperties(deb,  m_USER_PERMS_TBL_NAME,      "USER_PERMS_TBL_NAME",       &line , err); if (err.length())     goto SetConfBase_Error;       // nom de la table des droits des utilisateurs non prescripteurs
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_PK,            "USER_PERMS_PK",             &line , err); if (err.length())     goto SetConfBase_Error;       // clef primaire de cet enregistrement
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_SIGN_GUID,     "USER_PERMS_SIGN_GUID",      &line , err); if (err.length())     goto SetConfBase_Error;       // Ref au GUID du signataire autorisant cet utilisateur
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_GUID,   "USER_PERMS_FRIEND_GUID",    &line , err); if (err.length())     goto SetConfBase_Error;       // GUID de cet utilisateur
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_DROITS, "USER_PERMS_FRIEND_DROITS",  &line , err); if (err.length())     goto SetConfBase_Error;       // Droits que le signataire attribue à cet utilisateur
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_BLOBS,  "USER_PERMS_FRIEND_BLOBS",   &line , err); if (err.length())     goto SetConfBase_Error;       // Configuration des autorisations fines (liste des fichiers autorisés avec les droits)

  QString requete = "SELECT "  + m_USER_PERMS_FRIEND_GUID       + " FROM " + m_USER_PERMS_TBL_NAME + " WHERE "        // 4
                               + m_USER_PERMS_SIGN_GUID         + " = '"   + signGUID              + "'";
  QSqlQuery query(requete , m_DataBase );
  //Param_UpdateToDisk("/home/ro/TestSql.txt", requete);
  //................ scanner les enregistrements ....................................................
  //                 pour remplir la listview
  //.................. si la requète a un resultat ..............................................
  if (query.isActive())
     {
      while (query.next())
        {QString requetePermsUser = "SELECT "  + m_USER_IDENT_LOGIN                + ", "    // 0                                             // 0
                                               + m_USER_IDENT_NOM                  + ", "    // 1                                             // 1
                                               + m_USER_IDENT_PRENOM               + ", "    // 2
                                               + m_USER_IDENT_PRIMKEY              + ", "    // 3
                                               + m_USER_IDENT_GUID                 + "  "    // 4
                                               + " FROM " + m_USER_IDENT_TBL_NAME  + " WHERE  " + m_USER_IDENT_GUID + " = '"   + Utf8_Query(query, 0 ) + "'";              // m_USER_PERMS_FRIEND_GUID
         QSqlQuery queryPermsUser(requetePermsUser , m_DataBase );
          if (queryPermsUser.isActive())
            {
             while (queryPermsUser.next())
                   { /*QListViewItem *pQListViewItem = */ new QListViewItem( pQlistViewItem ,
                                                                        Utf8_Query(queryPermsUser, 0 ),       // login
                                                                        Utf8_Query(queryPermsUser, 1 ),       // nom
                                                                        Utf8_Query(queryPermsUser, 2 ),       // prenom
                                                                        Utf8_Query(queryPermsUser, 3 ),       // PK
                                                                        Utf8_Query(queryPermsUser, 4 )        // GUID
                                                                       );
                  }  //endwhile (queryPermsUser.next())
           } //endif (queryPermsUser.isActive())
        } //end while (pSqlQuery->next())4
     } //endif (pSqlQuery && pSqlQuery->isActive())
}

//-----------------------------------------------------  PermsUserIsThisUserFriendFromName -------------------------------------------
// ACTION : retourne les droits autorisés par signUser pour friendUser
//
QString CMoteurBase::PermsUserIsThisUserFriendFromName(   const QString  &signUser, const QString  &friendUser)
{
 QString signGUID   = GetFieldValue( m_USER_IDENT_TBL_NAME, m_USER_IDENT_GUID, m_USER_IDENT_LOGIN, signUser);
 QString friendGUID = GetFieldValue( m_USER_IDENT_TBL_NAME, m_USER_IDENT_GUID, m_USER_IDENT_LOGIN, friendUser);
 return PermsUserIsThisUserFriendFromGUID(   signGUID, friendGUID);
}

//-----------------------------------------------------  PermsUserSignUserListForThisUser -------------------------------------------
// ACTION : retourne la liste :userList des utilisateurs signataires ayant autorise : user pour le droit : pDroit
//
int CMoteurBase::PermsUserSignUserListForThisUser(   const QString  &user, QStringList  &userList,  const char  *pDroit  /* = 0 */)
{//  pt = SetConfBase_SetProperties(deb,  m_USER_PERMS_TBL_NAME,      "USER_PERMS_TBL_NAME",       &line , err); if (err.length())     goto SetConfBase_Error;       // nom de la table des droits des utilisateurs non prescripteurs
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_PK,            "USER_PERMS_PK",             &line , err); if (err.length())     goto SetConfBase_Error;       // clef primaire de cet enregistrement
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_SIGN_GUID,     "USER_PERMS_SIGN_GUID",      &line , err); if (err.length())     goto SetConfBase_Error;       // Ref au GUID du signataire autorisant cet utilisateur
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_GUID,   "USER_PERMS_FRIEND_GUID",    &line , err); if (err.length())     goto SetConfBase_Error;       // GUID de cet utilisateur
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_DROITS, "USER_PERMS_FRIEND_DROITS",  &line , err); if (err.length())     goto SetConfBase_Error;       // Droits que le signataire attribue à cet utilisateur
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_BLOBS,  "USER_PERMS_FRIEND_BLOBS",   &line , err); if (err.length())     goto SetConfBase_Error;       // Configuration des autorisations fines (liste des fichiers autorisés avec les droits)
  //................. Preparer la requete .....................................
  if (m_DataBase==0)                                             { return 0; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  { return 0; }

  QString userGUID   = GetFieldValue_WithoutOpenCloseBase( m_USER_IDENT_TBL_NAME, m_USER_IDENT_GUID, m_USER_IDENT_LOGIN, user);

  QString requete = "SELECT "  + m_USER_PERMS_SIGN_GUID + ", "    +  m_USER_PERMS_FRIEND_DROITS   + " FROM " + m_USER_PERMS_TBL_NAME + " WHERE "        // 4
                               + m_USER_PERMS_FRIEND_GUID         + " = '"                        + userGUID                         + "' ;";
  QSqlQuery query(requete , m_DataBase );
  //.................. si la requète a un resultat ..............................................
  QString sign_guid       ="";
  QString friend_droits   ="";
  QString sign_name       ="";
  if (query.isActive())
     {userList.clear();
      while (query.next())
        { sign_guid          = query.value(0).toString();
          sign_name          = GetFieldValue_WithoutOpenCloseBase( m_USER_IDENT_TBL_NAME, m_USER_IDENT_LOGIN, m_USER_IDENT_GUID, sign_guid);
          if (pDroit)
             {friend_droits  = query.value(1).toString();
              if (IsThisDroitExist(friend_droits, pDroit)) userList.append(sign_name);
             }
          else
             {userList.append(sign_name);
             }
        } //end while (pSqlQuery->next())4
     } //endif (pSqlQuery && pSqlQuery->isActive())
  m_DataBase->close();
  return userList.count();
}

//--------------------------------------------- IsThisDroitExist -------------------------------------------------------------------
// ACTION vérifie si le droit : droitToFind  (trois caractères style med adm sgn ....) existe dans la chaine de droits : listDroits
//        6 fois plus rapide que : listDroits.find(droitToFind) != -1
bool CMoteurBase::IsThisDroitExist(const char *listDroits, const char *droitToFind)
{char *pt  = (char*)listDroits;
 while (*pt)
    {if (pt[1]==droitToFind[0] && pt[2]==droitToFind[1] &&pt[3]==droitToFind[2]) return TRUE;
     pt += 4;
    }
 return FALSE;
}
//-----------------------------------------------------  PermsUserIsThisUserFriendFromGUID -------------------------------------------
// ACTION : retourne les droits autorisés par signGUID pour friendGUID
//
QString CMoteurBase::PermsUserIsThisUserFriendFromGUID(   const QString  &signGUID, const QString  &friendGUID)
{//  pt = SetConfBase_SetProperties(deb,  m_USER_PERMS_TBL_NAME,      "USER_PERMS_TBL_NAME",       &line , err); if (err.length())     goto SetConfBase_Error;       // nom de la table des droits des utilisateurs non prescripteurs
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_PK,            "USER_PERMS_PK",             &line , err); if (err.length())     goto SetConfBase_Error;       // clef primaire de cet enregistrement
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_SIGN_GUID,     "USER_PERMS_SIGN_GUID",      &line , err); if (err.length())     goto SetConfBase_Error;       // Ref au GUID du signataire autorisant cet utilisateur
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_GUID,   "USER_PERMS_FRIEND_GUID",    &line , err); if (err.length())     goto SetConfBase_Error;       // GUID de cet utilisateur
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_DROITS, "USER_PERMS_FRIEND_DROITS",  &line , err); if (err.length())     goto SetConfBase_Error;       // Droits que le signataire attribue à cet utilisateur
 //  pt = SetConfBase_SetProperties(pt,   m_USER_PERMS_FRIEND_BLOBS,  "USER_PERMS_FRIEND_BLOBS",   &line , err); if (err.length())     goto SetConfBase_Error;       // Configuration des autorisations fines (liste des fichiers autorisés avec les droits)
  //................. Preparer la requete .....................................
  if (m_DataBase==0)                                             { return NULL; }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  { return NULL; }
  QString droits  = "";
  QString requete = "SELECT "  + m_USER_PERMS_FRIEND_DROITS       + " FROM " + m_USER_PERMS_TBL_NAME + " WHERE "        // 4
                               + m_USER_PERMS_SIGN_GUID           + " = '"   + signGUID              + "' AND  "
                               + m_USER_PERMS_FRIEND_GUID         + " = '"   + friendGUID            + "';";
  QSqlQuery query(requete , m_DataBase );
  //.................. si la requète a un resultat ..............................................
  if (query.isActive())
     {while (query.next())
        {droits = Utf8_Query(query, 0 );
        } //end while (pSqlQuery->next())4
     } //endif (pSqlQuery && pSqlQuery->isActive())
  m_DataBase->close();
  return droits;
}

//-----------------------------------------------------  GetUserListType -------------------------------------------
void CMoteurBase::GetUserListType( QStringList &typList , QString    *errMess /* = 0 */ )
{//................. Preparer la requete .....................................
  if (m_DataBase==0) {if (errMess) *errMess = "CMoteurBase::GetUserList(): m_DataBase = 0 (create error) "; return ;  }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE) {if (errMess) *errMess = "CMoteurBase::GetUserList(): database can't be opened"; return ; }
  //................. SI un nom ou prenom est donné en entrée alors filtrer selon ...................
  QString        requete;
  requete        = "SELECT ";
  requete       += m_USER_IDENT_QUALITE ; // 0
  requete       += " FROM "      + m_USER_IDENT_TBL_NAME     + " WHERE ";
  requete       += m_USER_IDENT_DROITS + " LIKE '%-med%'";
  requete       += " ORDER BY "  + m_USER_IDENT_QUALITE;

  QSqlQuery query(requete , m_DataBase );
  //.................. si la requète a un resultat ..............................................
  if (query.isActive())
     {typList.clear();
      while (query.next())
        {QString str = Utf8_Query(query, 0 );
         if (typList.findIndex ( str)==-1) typList.append(str);
        } //end while (pSqlQuery->next())
     } //endif (pSqlQuery && pSqlQuery->isActive())
  m_DataBase->close();
}

//-----------------------------------------------------  GetUserList -------------------------------------------
//   QString      m_USER_IDENT_TBL_NAME;           // nom de la table des données des RUBRIQUES
//   QString      m_USER_IDENT_NOM;                // Nom
//   QString      m_USER_IDENT_PRENOM;             // Prenom

long CMoteurBase::GetUserList(          QListView *pQlistView,
                                  const QString   &qstr_nom,
                                  const QString   &qstr_prenom,

                                  const bool       childsMustBeFind,  /* = TRUE */
                                  const QString   *qstr_UserQualite,  /* = 0 */
                                  QLabel    *statutMess, /* = 0  */
                                  QLabel    *errMess     /* = 0  */
                             )
{//................. Preparer la requete .....................................
  if (m_DataBase==0)
     {if (errMess) errMess->setText("CMoteurBase::GetUserList(): m_DataBase = 0 (create error) ");
      return 0;
     }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)
     {if (errMess) errMess->setText("CMoteurBase::GetUserList(): database can't be opened");
      return 0;
     }
  //................. SI un nom ou prenom est donné en entrée alors filtrer selon ...................
  QString requete;
  requete        = "SELECT ";
  requete       += m_USER_IDENT_LOGIN    + "," +      // 0
                   m_USER_IDENT_NOM      + "," +      // 1
                   m_USER_IDENT_PRENOM   + "," +      // 2
                   m_USER_IDENT_PRIMKEY  + "," +      // 3
                   m_USER_IDENT_GUID     + "," +      // 4
                   m_USER_IDENT_DROITS;

  if (qstr_nom != ""||qstr_prenom!="")
     {requete       += " FROM "            + m_USER_IDENT_TBL_NAME        + " WHERE ";
      requete       += m_USER_IDENT_NOM    + " LIKE '"+ qstr_nom          + "%' AND ";
      requete       += m_USER_IDENT_PRENOM + " LIKE '"+ qstr_prenom       + "%' AND ";
      if (qstr_UserQualite && qstr_UserQualite->length())
         {requete   += m_USER_IDENT_QUALITE + " = '"  + *qstr_UserQualite  + "' AND ";
         }
      requete       += m_USER_IDENT_DROITS + " LIKE '%-med%'";
      requete       += " ORDER BY "        + m_USER_IDENT_NOM;
     }
  //................. SINON pas de filtre ...........................................................
  else
     {requete       += " FROM "      + m_USER_IDENT_TBL_NAME     + " WHERE ";
      requete       += m_USER_IDENT_DROITS + " LIKE '%-med%'";
      if (qstr_UserQualite && qstr_UserQualite->length())
         {requete   += " AND " + m_USER_IDENT_QUALITE + " = '"  + *qstr_UserQualite  + "' ";
         }
      requete       += " ORDER BY "  + m_USER_IDENT_NOM;
     }

  QSqlQuery query(requete , m_DataBase );

  //................ scanner les enregistrements ....................................................
  //                 pour remplir la listview
  int nb = 0;
  //.................. si la requète a un resultat ..............................................
  if (query.isActive())
     {pQlistView->clear();
      while (query.next())
        {QListViewItem *element = 0;
         QString droits         = query.value( 5 ).toString();
         //............... on rempli la listbox selon son nombre de colonnes .....................
         //if (  /*droits.find("adm")!=-1 ||  (droits.find("med") != -1  ) */)
            {if (childsMustBeFind )
                {if (droits.find("-sgn") != -1)
                    {element = new QListViewItem(     pQlistView,
                                                      Utf8_Query(query, 0 ),
                                                      Utf8_Query(query, 1 ),
                                                      Utf8_Query(query, 2 ),
                                                      Utf8_Query(query, 3 ),
                                                      Utf8_Query(query, 4 )
                                                 );
                    if (element)
                        {PermsUserChildGetList(element, element->text(4));
                         //element->setOpen ( TRUE );
                         ++nb;
                        }
                   } // endif (droits.find("sgn") != -1)
               }
            else
               {element = new QListViewItem(          pQlistView,
                                                      Utf8_Query(query, 0 ),
                                                      Utf8_Query(query, 1 ),
                                                      Utf8_Query(query, 2 ),
                                                      Utf8_Query(query, 3 ),
                                                      Utf8_Query(query, 4 )
                                                 );
                if (element) ++nb;
               }
           }
          //if (element) pQlistView->insertItem ( element );
        } //end while (pSqlQuery->next())
     } //endif (pSqlQuery && pSqlQuery->isActive())

  //....................... sortir le message d'erreur si besoin ..........................................
  if (statutMess)
     { statutMess->setText(TR("Trouvés: ") + QString::number(nb));
     }
  m_DataBase->close();
  return nb;
}

//-----------------------------------------------------  InitComboWithUserDocList -------------------------------------------
//   QString      m_USER_DATA_TBL_NAME;           // nom de la table des données des RUBRIQUES
//   QString      m_USER_DATA_REF_PK;             // Ref à la clef primaire de l'utilisateur auquel appartiennent les données
//   QString      m_USER_DATA_NAMEDOC;            // nom des données
//   QString      m_USER_DATA_TYPE;               // type de données
//   QString      m_USER_DATA_BLOB;               // données proprement dites
//   ACTION: cette fonction rempli la combo box de choix du type de masque d'impression à utiliser
long CMoteurBase::InitComboWithUserDocList( QComboBox       *pQComboBox,
                                            QString         user,
                                            QString       rubName,
                                            QString         type1, /* = QString::null  ou RUBNAME alors type2 contient le nom de la rubrique*/
                                            QString         type2, /* = QString::null  ou nom de la rubrique */
                                            int clear             /* = 1 */
                                          )
{ //................. tester l'utilisateur .....................................
  QString primKey = GetUserPrimKey(user);
  bool       oldSyntax = TRUE;
  if (primKey=="") return 0;

  //................. tester disponibilite des bases .....................................
  if (m_DataBase==0)                                             return 0;
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;

  //................. SI un nom ou prenom est donné en entrée alors filtrer selon ...................
  QString requete("SELECT ");
          requete       += m_USER_DATA_NAMEDOC +","+
                           m_USER_DATA_TYPE    +","+
                           m_USER_DATA_PK;
          requete       += " FROM "       + m_USER_DATA_TBL_NAME       + " WHERE ";
  //................. forme particulière des nouvelles rubriques à venir où ..................................
  //                  le libelle du document d'entete et de pied de page doit être
  //                  de la forme : [NOM DE LA RUBRIQUE] LIBELLE DE LA RUBRIQUE (avec le # ou * et eventuels préfixages)
  if (type1.left(7) == "RUBNAME")
     {oldSyntax      = FALSE;
      requete       += m_USER_DATA_REF_PK     + " = '"   + primKey  + "' ";
      requete       += " ORDER BY "           + m_USER_DATA_NAMEDOC;
     }
  else if (type1 != QString::null && type2 != QString::null)
     {requete       += m_USER_DATA_REF_PK     + " =  '"   + primKey         + "' AND ";
      requete       += m_USER_DATA_TYPE       + " >= '"   + type1           + "' AND ";
      requete       += m_USER_DATA_TYPE       + " <= '"   + type2           + "'    ";
      requete       += " ORDER BY "           + m_USER_DATA_NAMEDOC;
     }
  else if (type1 != QString::null && type2 == QString::null)
     {requete       += m_USER_DATA_REF_PK     + " =  '"   + primKey         + "' AND ";
      requete       += m_USER_DATA_TYPE       + " = '"    + type1           + "' ";
      requete       += " ORDER BY "           + m_USER_DATA_NAMEDOC;
     }
  //................. SINON pas de filtre ...........................................................
  else
     {requete       += m_USER_DATA_REF_PK     + " = '"   + primKey  + "' ";
      requete       += " ORDER BY "           + m_USER_DATA_NAMEDOC;
     }

  QSqlQuery query(requete , m_DataBase );

  //................ scanner les enregistrements ....................................................
  //                 pour remplir la listview
  int nb   = 0;
  int pos  = -1;
  QString text;
  QString type_doc;
  QString rubNameInTitle;
  QString subTypeInTitle;
  //.................. si la requète a un resultat ..............................................
  if (query.isActive())
     {if (clear) pQComboBox->clear();
      while (query.next())
        {text = Utf8_Query(query, 0 );        // libelle du document d'entete
         if (text[0] == '[' )          //>>>>>>>............... NOUVELLE SYNTAXE : [NOM DE LA RUBRIQUE @ sous type ] .....................
            {rubNameInTitle          = "";
             subTypeInTitle          = "ComboDef SubType";
             int deb_rubNameInTitle  = text.find('[');
             int end_rubNameInTitle  = text.find(']');
             if (deb_rubNameInTitle != -1 && end_rubNameInTitle != -1) 
                {pos = text.find('@');
                 ++deb_rubNameInTitle;         // passer le premier crochet
                 if (pos != -1)                // si '@' c'est que le nom de la rubrique est suivi du sous type
                    {rubNameInTitle = text.mid(deb_rubNameInTitle, pos - deb_rubNameInTitle).stripWhiteSpace();
                     ++pos;                    // passer '@'
                     subTypeInTitle = text.mid(pos, end_rubNameInTitle - pos).stripWhiteSpace();
                    }
                 else
                    {rubNameInTitle = text.mid(deb_rubNameInTitle, end_rubNameInTitle - deb_rubNameInTitle).stripWhiteSpace();
                    }
                 text = text.mid(end_rubNameInTitle+1).stripWhiteSpace();
                } // endif (deb_rubNameInTitle != -1 && end_rubNameInTitle != -1)
             } // endif ( text[0] == '[' )
          else if ( oldSyntax )                      //>>>>>>>.... la on est sur l'ancien systeme donc ne filtrer qu'avec la requete SQL .......................
             {rubNameInTitle = rubName;
              subTypeInTitle = "ComboDef SubType";
             }
          if ( rubNameInTitle == rubName)   // si on trouve le nom de la rubrique [NOM DE LA RUBRIQUE]
             {new CPrtQListBoxItem(pQComboBox->listBox() ,                                 // list box du combobox
                                          text ,      // libelle
                                          Utf8_Query(query, 2 ) ,          // Pk document
                                          Utf8_Query(query, 1 ) ,          // type document
                                          user,                            // user
                                          subTypeInTitle );             // sous type (non utilisé ici)
                     nb++;

             } 
        } //end while (pSqlQuery->next())
     } //endif (pSqlQuery && pSqlQuery->isActive())
  m_DataBase->close();
  return nb;
}

//-----------------------------------------------------  GetUserDocList -------------------------------------------
//   QString      m_USER_DATA_TBL_NAME;           // nom de la table des données des RUBRIQUES
//   QString      m_USER_DATA_REF_PK;             // Ref à la clef primaire de l'utilisateur auquel appartiennent les données
//   QString      m_USER_DATA_NAMEDOC;            // nom des données
//   QString      m_USER_DATA_TYPE;               // type de données
//   QString      m_USER_DATA_BLOB;               // données proprement dites

long CMoteurBase::GetUserDocList( QListView       *pQlistView,
                                  const char      *primKey,
                                  const char      *qstr_nom,  /* = 0 */
                                  QLabel    *statutMess,      /* = 0  */
                                  QLabel    *errMess          /* = 0  */
                                 )
{//................. Preparer la requete .....................................
  if (m_DataBase==0)
     {if (errMess) errMess->setText("CMoteurBase::GetUserDocList(): m_DataBase = 0 (create error) ");
      return 0;
     }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)
     {if (errMess) errMess->setText("CMoteurBase::GetUserDocList(): database can't be opened");
      return 0;
     }
  //................. SI un nom ou prenom est donné en entrée alors filtrer selon ...................
  QString requete("SELECT ");
          requete       += m_USER_DATA_NAMEDOC + ","+
                           m_USER_DATA_TYPE    + ","+
                           m_USER_DATA_PK;
          requete       += " FROM "            + m_USER_DATA_TBL_NAME      + " WHERE ";

  if (qstr_nom && qstr_nom[0])
     {requete       += m_USER_DATA_NAMEDOC    + " LIKE '"+ qstr_nom        + "%' AND ";
      requete       += m_USER_DATA_REF_PK     + " = '"   + primKey         + "' ";
      requete       += " ORDER BY "           + m_USER_DATA_NAMEDOC;
     }
  //................. SINON pas de filtre ...........................................................
  else
     {requete       += m_USER_DATA_REF_PK     + " = '"   + primKey  + "' ";
      requete       += " ORDER BY "           + m_USER_DATA_NAMEDOC;
     }
  QSqlQuery query(requete , m_DataBase );

  //................ scanner les enregistrements ....................................................
  //                 pour remplir la listview
  int nb = 0;
  //.................. si la requète a un resultat ..............................................
  if (query.isActive())
     {pQlistView->clear();
      while (query.next())
        {//............... on rempli la listbox selon son nombre de colonnes .....................
         new QListViewItem( pQlistView,
                            Utf8_Query(query, 0 ),   ////Utf8_Query(query,0);
                            Utf8_Query(query, 1 ),
                            Utf8_Query(query, 2 )
                          );
          nb++;
        } //end while (pSqlQuery->next())
     } //endif (pSqlQuery && pSqlQuery->isActive())
  //....................... sortir le message d'erreur si besoin ..........................................
  if (statutMess)
     { statutMess->setText(TR("Trouvés: ") + QString::number(nb));
     }
  m_DataBase->close();
  return nb;
}

//-------------------------------------- CreateNewUser ----------------------------------------------------------------------------
// ACTION: crée un nouvel utilisateur et retourne son GUID
//m_pCMoteurBase->CreateNewUser(m_pCps->m_Nom, m_pCps->m_Prenom, user, "med", pass, m_pCps->m_NIR);

QString CMoteurBase::CreateNewUser(const QString &nom,
                                   const QString &prenom,
                                   const QString &login,
                                   const QString &droit /*="med" */,
                                   const QString &pass/*=""*/,
                                   const QString &nir/*=""*/ )
{ //................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  QString ok("");
  //............... ouvrir la base .......................................................
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return ok;
  //............... crer un curseur SQL ..................................................
  QSqlCursor cur(m_USER_IDENT_TBL_NAME, TRUE, m_DataBase);
  if ( !cur.canInsert ())                                        return ok;
  //............... si OK on recupere le buffer et on le charge avec les données .........
  QSqlRecord *buffer = cur.primeInsert();                         // recuperer le buffer d'insertion
  QString       guid = GUID_Create();
  buffer->setValue( m_USER_IDENT_GUID,   guid);                   // y placer les données
  buffer->setValue( m_USER_IDENT_NOM,    nom);                    // y placer les données
  buffer->setValue( m_USER_IDENT_PRENOM, prenom);                 // y placer les données
  buffer->setValue( m_USER_IDENT_LOGIN,  login);                  // y placer les données
  if (droit.length())buffer->setValue( m_USER_IDENT_DROITS,     droit);                  // y placer les données
  if (pass.length())
     {QString pass_cripted = pass;
      PassWordEncode(pass_cripted);
      buffer->setValue(  m_USER_IDENT_PASSWORD, pass_cripted);                   // y placer les données
     }
  if (nir.length())buffer->setValue(   m_USER_IDENT_NUM_ORDRE,  nir);                    // y placer les données


  if (cur.insert()) ok = guid;                                    // ecrire le buffer

  if (ok=="") OutSQL_error(cur, "CreateNewUser()");

  //......................... fermer la base ..............................................
  m_DataBase->close();
  return ok;
}
//---------------------------------------------------- IsThisUserDocExist -----------------------------------------------
//   QString      m_USER_DATA_TBL_NAME;           // nom de la table des données des RUBRIQUES
//   QString      m_USER_DATA_REF_PK;             // Ref à la clef primaire de l'utilisateur auquel appartiennent les données
//   QString      m_USER_DATA_NAMEDOC;            // nom des données
//   QString      m_USER_DATA_TYPE;               // type de données
//   QString      m_USER_DATA_BLOB;               // données proprement dites
// RETOUR:    la primKey des données si elles existent sinon ""
QString CMoteurBase::IsThisUserDocExist(  int              type,
                                          const char      *refUserPrimKey,
                                          const char      *nom,
                                          QLabel          *errMess          /* = 0  */
                                       )
{ QString ret("");
  //................. Preparer la requete .....................................
  if (m_DataBase==0)
     {if (errMess) errMess->setText("CMoteurBase::IsThisUserDocExist(): m_DataBase = 0 (create error) ");
      return 0;
     }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)
     {if (errMess) errMess->setText("CMoteurBase::IsThisUserDocExist(): database can't be opened");
      return 0;
     }
  //................. filtrer selon donnée d'entrée ..................................................
  QString  requete("SELECT " );
           requete       += m_USER_DATA_PK;
           requete       += " FROM "               + m_USER_DATA_TBL_NAME              + " WHERE ";
  if (nom) requete       += m_USER_DATA_NAMEDOC    + " = '"   + nom                    + "' AND ";
           requete       += m_USER_DATA_REF_PK     + " = '"   + refUserPrimKey         + "' AND ";
           requete       += m_USER_DATA_TYPE       + " = '"   + QString::number(type)  + "'";

  QSqlQuery query(requete , m_DataBase );

  //.................. si la requète a un resultat ..............................................

  if (query.isActive() && query.next())
     {ret = query.value(0).toString();
     }
  //if (ret.length()<=0) ret = IsThisUserDocExist( type, refUserPrimKey, QString (nom).utf8 (), errMess ); // essayer en utf8
  m_DataBase->close();
  return ret;
}

//---------------------------------------------------- IsThisUserDocExist -----------------------------------------------
//   QString      m_USER_DATA_TBL_NAME;           // nom de la table des données des RUBRIQUES
//   QString      m_USER_DATA_REF_PK;             // Ref à la clef primaire de l'utilisateur auquel appartiennent les données
//   QString      m_USER_DATA_NAMEDOC;            // nom des données
//   QString      m_USER_DATA_TYPE;               // type de données
//   QString      m_USER_DATA_BLOB;               // données proprement dites
// RETOUR:    la primKey des données si elles existent sinon ""

QString CMoteurBase::User_GetBestHeadFoot_ToPrintDoc( RUBREC_LIST::iterator it,
                                                      const QString &rubName,
                                                      const char      *refUserPrimKey,
                                                      QLabel          *errMess          /* = 0  */
                                                    )
{ QString ret("");
  QString defaultRet(""); // retiendra le document du type '* Nom de la rubrique' exple : '* Documents' '* Prescription' 
  //................. Preparer la requete .....................................
  if (m_DataBase==0)
     {if (errMess) errMess->setText("CMoteurBase::IsThisUserDocExist(): m_DataBase = 0 (create error) ");
      return 0;
     }
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)
     {if (errMess) errMess->setText("CMoteurBase::IsThisUserDocExist(): database can't be opened");
      return 0;
     }
  //................. filtrer selon donnée d'entrée ..................................................
  QString  requete("SELECT " );
           requete       += m_USER_DATA_PK   + "," + m_USER_DATA_NAMEDOC         + "," + m_USER_DATA_TYPE;
           requete       += " FROM "               + m_USER_DATA_TBL_NAME              + " WHERE ";
           requete       += m_USER_DATA_REF_PK     + " = '"   + refUserPrimKey         + "' ";


  QSqlQuery query(requete , m_DataBase );
  //.................. si la requète a un resultat ..............................................
  QString type_modele      = "";
  QString libelle_modele   = "";
  QString type_document    = TypeDoc_To_PrintTypeDoc(  (*it).m_Type );

  QString libelle_document = (*it).m_Libelle.lower();
  if (query.isActive())               //Utf8_Query(query,0);
     {
      while (query.next())
             {libelle_modele = Utf8_Query(query,1);        // nom du document utilisateur type
              type_modele    = Utf8_Query(query,2);
              if (type_modele == type_document)
                 {ret = Utf8_Query(query,0);
                  break;
                 }
              else if ( libelle_modele.at(0)=='#')
                 {libelle_modele = libelle_modele.remove('#');;            // se placer après le '# '
                  libelle_modele = libelle_modele.stripWhiteSpace().lower();
                  if (libelle_document.find(libelle_modele) != -1)           // si on trouve le nom du modele utilisateur dans le
                     {ret = Utf8_Query(query,0);                             // nom du document de la liste patient
                      break;
                     }
                 }
              else if ( libelle_modele.at(0)=='*')
                 {libelle_modele = libelle_modele.remove('*');
                  libelle_modele = libelle_modele.stripWhiteSpace().lower();
                  if (rubName == libelle_modele)           // si on trouve le nom du modele utilisateur dans le
                     {defaultRet = Utf8_Query(query,0);                             // nom du document de la liste patient
                     }
                 }
             }
     }
  m_DataBase->close();
  if (ret.length()==0) return defaultRet;
  return ret;
}


//------------------------------------------ Param_SavParam ---------------------------------------------------------------
void CMoteurBase::Param_SavParam(QString user, QString *pParam /* = 0 */)
{   //......................... sauver les parametres dans données utilisateur ....................
    if (pParam==0) pParam = &m_ParamData;
    QString us_pk         = GetUserPrimKey(user);
    QString docPrimKey    = IsThisUserDocExist(TYP_PARAM, us_pk, TR("Parametres"));
     if (docPrimKey!="")
        {UpdateUserDataFromPrimKey(docPrimKey, TYP_PARAM, us_pk, TR("Parametres"), *pParam);
        }
     else
        {CreateUserDataFromPrimKey(TYP_PARAM, us_pk ,TR("Parametres"), *pParam);
        }
}

//-------------------------------------- UpdateUserDataFromPrimKey ----------------------------------------------------------------------------
int CMoteurBase::UpdateUserDataFromPrimKey( const char *primKey, int type, const char *refUserPrimKey , const char* name,  const char* data)
{
 //................................. methode QSqlCursor .................................
 //                         ne pose pas de PB avec valeur avec une apostrophe
 //............... crer un curseur SQL ..................................................
 if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return FALSE;
 int ok = FALSE;
 QSqlCursor cur(m_USER_DATA_TBL_NAME, TRUE, m_DataBase);
 if ( !cur.canUpdate ()) {m_DataBase->close(); return FALSE;}
 //............... placer ce curseur sur le bon enregistrement ..........................
 cur.select(m_USER_DATA_PK  + "='" + primKey  + "'" );
  //............... si OK on recupere le buffer et on le charge avec les données .........
 if ( cur.next() )
    {QSqlRecord *buffer = cur.primeUpdate();                                                 // recuperer le buffer ( pas de delete à la fin !!)
     if (refUserPrimKey) buffer->setValue( m_USER_DATA_REF_PK,    refUserPrimKey         );  // y placer les données
     if (name)           buffer->setValue( m_USER_DATA_NAMEDOC,   name                   );  // y placer les données
     if (type)           buffer->setValue( m_USER_DATA_TYPE,      type                   );  // y placer les données
     buffer->setValue( m_USER_DATA_BLOB,      data                   );  // y placer les données
     ok    = cur.update();                                               // ecrire le buffer avec les données du header
    }

 if (ok==0) OutSQL_error(cur, "UpdateUserDataFromPrimKey()");

  //......................... fermer la base ..............................................
  m_DataBase->close();
  return ok;
}

//------------------------------------------ ReadDrTuxUserParametres ---------------------------------------------------------------
QString  CMoteurBase::ReadDrTuxUserParametres(const QString &user)
{return GetUserDocument(user, TR("Parametres"), TYP_PARAM );
}

//------------------------------------------ Param_GetParam ---------------------------------------------------------------
void  CMoteurBase::Param_GetParam(QString user, QString *pParam /* = 0 */)
{if (pParam==0) pParam = &m_ParamData;
 *pParam = ReadDrTuxUserParametres(user);
}

//-------------------------------------- DeleteUserDataFromPrimKey ----------------------------------------------------------------------------
int CMoteurBase::DeleteUserDataFromPrimKey( const char *primKey)
{ //................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  int ok  = FALSE;
  //............... ouvrir la base .......................................................
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;
  QString requete("DELETE FROM ");
          requete += m_USER_DATA_TBL_NAME + " WHERE ";
          requete += m_USER_DATA_PK       + "= '" + primKey                  + "' ";
 QSqlQuery* pSqlQuery = new QSqlQuery(QString::null , m_DataBase );
 if (pSqlQuery) ok = pSqlQuery->exec(requete);
 if (pSqlQuery) delete  pSqlQuery;
 m_DataBase->close();
 return ok;
}

//-------------------------------------- CreateUserDataFromPrimKey ----------------------------------------------------------------------------
int CMoteurBase::CreateUserDataFromPrimKey(int type, const char *primKey , const char* name,  const char* data)
{//  "USER_DATA_TBL_NAME        'UtilisateursDocuments'        \r\n"      // nom de la table des données des RUBRIQUES
 //  "USER_DATA_REF_PK          'ID_PrimKeyFromUser'      '0' \r\n"       // Ref à la clef primaire de l'utilisateur auquel appartiennent les données
 //  "USER_DATA_NAMEDOC         'NameDoc'                 '1' \r\n"       // nom des données
 //  "USER_DATA_TYPE            'TypeDocuments'           '2' \r\n"       // type de données
 //  "USER_DATA_BLOB            'DataDocuments'           '3' \r\n";      // données proprement dites
 //   QString      m_USER_DATA_TBL_NAME;           // nom de la table des données des RUBRIQUES
 //   QString      m_USER_DATA_REF_PK;             // Ref à la clef primaire de l'utilisateur auquel appartiennent les données
 //   QString      m_USER_DATA_NAMEDOC;            // nom des données
 //   QString      m_USER_DATA_TYPE;               // type de données
 //   QString      m_USER_DATA_BLOB;               // données proprement dites

  //................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  int ok  = FALSE;
  //............... ouvrir la base .......................................................
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;
  //............... crer un curseur SQL ..................................................
  QSqlCursor cur(m_USER_DATA_TBL_NAME, TRUE, m_DataBase);
  if ( !cur.canInsert ()) {m_DataBase->close(); return FALSE;}
  //............... si OK on recupere le buffer et on le charge avec les données .........
  QSqlRecord *buffer = cur.primeInsert();                         // recuperer le buffer d'insertion
  buffer->setValue( m_USER_DATA_REF_PK,         primKey );  // y placer les données
  buffer->setValue( m_USER_DATA_NAMEDOC,        name    );  // y placer les données
  buffer->setValue( m_USER_DATA_TYPE,           type    );  // y placer les données
  buffer->setValue( m_USER_DATA_BLOB,           data    );  // y placer les données
  ok = cur.insert();                                               // ecrire le buffer avec les données du header

  //......................... fermer la base ..............................................
  m_DataBase->close();
  return ok;
}

//-------------------------------------- DeleteUserFromPrimKey ----------------------------------------------------------------------------
int CMoteurBase::DeleteUserFromPrimKey(const char *refUserPrimKey )
{ //............... ouvrir la base .......................................................
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;
  QSqlQuery* pSqlQuery;
  QString requete;
  int ok  = FALSE;
  //................................. effacer tous les documents liés à l'utilisateur.....................................
          requete  = "DELETE FROM ";
          requete += m_USER_DATA_TBL_NAME + " WHERE ";
          requete += m_USER_DATA_REF_PK       + "= '" + refUserPrimKey + "' ";
 pSqlQuery = new QSqlQuery(QString::null , m_DataBase );
 if (pSqlQuery) ok = pSqlQuery->exec(requete);
 if (pSqlQuery) delete  pSqlQuery;
 if (ok==0)             {m_DataBase->close();  return 0;}  // si erreur on arrete là

 //................................. effacer l'utilisateur .....................................
          requete  = "DELETE FROM ";
          requete += m_USER_IDENT_TBL_NAME      + " WHERE ";
          requete += m_USER_IDENT_PRIMKEY       + "= '" + refUserPrimKey + "' ";
 pSqlQuery = new QSqlQuery(QString::null , m_DataBase );
 if (pSqlQuery) ok = pSqlQuery->exec(requete);
 if (pSqlQuery) delete  pSqlQuery;
 m_DataBase->close();
 return ok;
}

//-------------------------------------- GetUserDataFromPrimKey ----------------------------------------------------------------------------
QString CMoteurBase::GetUserDataFromPrimKey(const char *primKey)
{//   QString      m_USER_DATA_TBL_NAME;           // nom de la table des données des RUBRIQUES
 //   QString      m_USER_DATA_PK;                 // clef primaire des données
 //   QString      m_USER_DATA_NAMEDOC;            // nom des données
 //   QString      m_USER_DATA_TYPE;               // type de données
 //   QString      m_USER_DATA_BLOB;               // données proprement dites

 QString requete("SELECT ");
 requete  += m_USER_DATA_BLOB      + " FROM "      + m_USER_DATA_TBL_NAME  + " WHERE ";
 requete  += m_USER_DATA_PK        + " ='"         + primKey + "'";


 if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;

 QSqlQuery query(requete , m_DataBase );
 requete = "";
 if (query.isActive() && query.next())
    {requete = Utf8_Query(query,0);
    } //if (pSqlQuery && pSqlQuery->isActive() && pSqlQuery->next())
 m_DataBase->close();
 return requete;
}

//-------------------------------------- GetUserIdentiteFromPrimKey ----------------------------------------------------------------------------
// ACTION: selectionne l'enregistrement de la table: DOSS_IDENT  correspondant au bon primary key
// RETOUR: QSqlQuery*  zero si echec
//                     valide sinon et AUQUEL CAS IL FAUDRA DETRUIRE ce pointeur par: delete  pSqlQuery
//                                  et AUQUEL CAS IL FAUDRA FERMER la base par:       m_DataBase->close()
QSqlQuery*   CMoteurBase::GetUserIdentiteFromPrimKey(const char *primKey , QStringList &fiedList )
{QString requete("SELECT ");
 //................... ajouter les champs à selectionner .......................
 for ( QStringList::Iterator it = fiedList.begin(); it != fiedList.end(); ++it )
     {requete  += *(it) + ",";
     }
 //.............. virer la dernière virgule ....................................
 int pos = requete.findRev(',');
 if (pos !=-1) requete.remove (pos, 1);
 //............... continuer à construire la requete ...........................
 requete  += " FROM "     + m_USER_IDENT_TBL_NAME + " WHERE ";
 requete  += m_USER_IDENT_PRIMKEY + " ='"         + primKey + "'";

 if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)
     {return 0;
     }
 QSqlQuery* pSqlQuery = new QSqlQuery(requete , m_DataBase );
 if (pSqlQuery && pSqlQuery->isActive() && pSqlQuery->next())
    {return pSqlQuery;
    } //if (pSqlQuery && pSqlQuery->isActive() && pSqlQuery->next())
 if (pSqlQuery) delete  pSqlQuery;
 m_DataBase->close();
 return 0;
}


//----------------------------------- ChangeRubUserName ---------------------------------------------------------
// ACTION: change le nom d'utilisateur d'une rubrique.
//
int CMoteurBase::ChangeRubUserName(QString userName, QString rubPrimKey, QString *errMess /*=0 */)
{QString qstr;
 QString requete            = "";
 requete                   += "UPDATE "                  + m_DOSS_RUB_HEAD_TBL_NAME   + " SET ";
 requete                   +=  m_DOSS_RUB_HEAD_USER      + " = '" + userName          + "' WHERE ";
 requete                   +=  m_DOSS_RUB_HEAD_PRIMKEY   + " ='"  + rubPrimKey        + "'";
 if  (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)
     {return 0;
     }
 QSqlQuery* pSqlQueryTarget = new QSqlQuery(requete , m_DataBase  );

 if (pSqlQueryTarget && pSqlQueryTarget ->isActive())
    {if (errMess) *errMess = TR("Changement d'utilisateur réussi");
    }
 else
   {qstr   = "";
    qstr  += requete;
    qstr  += TR("\r\nÉchec du changement d'utilisateur : CMoteur_Base. ");
    switch(pSqlQueryTarget->lastError().type())
          {case QSqlError::None :        qstr  += TR("no error occurred");          break;
           case QSqlError::Connection :  qstr  += TR("connection error");           break;
           case QSqlError::Statement :   qstr  += TR("SQL statement syntax error"); break;
           case QSqlError::Transaction : qstr  += TR("transaction failed error");   break;
           case QSqlError::Unknown :     qstr  += TR("unknown error");              break;
          }
   if (errMess) *errMess = qstr;
   return FALSE;
  }
if (pSqlQueryTarget) delete  pSqlQueryTarget;
return TRUE;
}
//********************************************************************************************************************************
//=================================== GESTION DES IDENTITES PATIENT ==============================================================
//********************************************************************************************************************************
//-------------------------------------- DossIdentIndexCreate --------------------------------------------------------------------
// ACTION: cree un nouveau dosier: en retour le PrimaryKey de ce dossier
QString  CMoteurBase::DossIdentIndexCreate(QString& nom, QString& prenom,    QString& numGUID,
                                           PtrListIdentFieldData *plist_field)
{ //................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  QString ok  = "";
  //............... ouvrir la base .......................................................
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return ok;

  //............... creer un curseur SQL de creation de l'enregistrement dans la table d'index des identités .................
  QSqlCursor cur(m_DOSS_INDEX_TBL_NAME, TRUE, m_DataBase);
  if ( !cur.canInsert ()) return ok;
  //............... si OK on recupere le buffer et on le charge avec les données .........
  QSqlRecord *buffer = cur.primeInsert();                         // recuperer le buffer d'insertion
  buffer->setValue( m_DOSS_INDEX_GUID,     numGUID         );     // y placer les données
  buffer->setValue( m_DOSS_INDEX_NOM,      nom.upper()     );     // y placer les données
  buffer->setValue( m_DOSS_INDEX_PRENOM,   prenom.upper()  );     // y placer les données
  if (cur.insert())                                               // ecrire le buffer avec les données du header
     {ok = "TRUE";                                                  // s'occuper des données binaires BLOB
     }

  //......................... Creer l'enregistrement dans la table des données des identités .................................
  QSqlCursor cur_refPk(m_DOSS_INDEX_TBL_NAME, TRUE, m_DataBase);
  if (ok!="")
     {if (!cur_refPk.select( m_DOSS_INDEX_GUID+"='"+numGUID+"'" )) goto  DossIndexCreateError;
      if (cur_refPk.next()) {//..... ok prend la valeur du primary key qui sera retourné ............
                             ok = cur_refPk.value( m_DOSS_INDEX_PRIM_KEY).toString();
                             DossIdentDataCreate(ok, numGUID, plist_field);
                            }
      else                  {ok = "";
                            }
     }
  m_DataBase->close();
  //........................ recuperer la clef ...........................................
  return ok;

DossIndexCreateError:
  OutSQL_error(cur_refPk, "DossIndexCreate()", cur_refPk.filter());
  m_DataBase->close();
  return QString("");
}

//-------------------------------------- DossIdentDataCreate --------------------------------------------------------------------
// ATTENTION: doit toujours etre appelée avec la base ouverte !!!
//
long  CMoteurBase::DossIdentDataCreate(QString& refDossPk,               QString& numGUID,
                                       PtrListIdentFieldData *plist_field)
{QString ref_pk;
  //................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  int ok  = FALSE;
  //............... creer un curseur SQL de creation de l'enregistrement dans la table d'index des identités .................
  QSqlCursor cur(m_DOSS_IDENT_TBL_NAME, TRUE, m_DataBase);
  if ( !cur.canInsert ()) return FALSE;
  //............... si OK on recupere le buffer et on le charge avec les données .........
  QSqlRecord *buffer = cur.primeInsert();                         // recuperer le buffer d'insertion
  //................... y placer les valeurs des champs ...................................
  //......... inserer les valeurs fondamentales ..................
  buffer->setValue( m_DOSS_IDENT_REF_PK, refDossPk );
  buffer->setValue( m_DOSS_IDENT_GUID,   numGUID );
  //......... inserer les autres valeurs .........................
  DossIdentBufferSetValue(buffer, plist_field );

  if (cur.insert())                                               // ecrire le buffer avec les données du header
     {ok = TRUE;                                                  // s'occuper des données binaires BLOB
     }
  //........................ recuperer la clef ...........................................
  return ok;
}

//-------------------------------------- DossIdentDelete --------------------------------------------------------------------
void  CMoteurBase::DossIdentDelete(RUBREC_LIST *pRubList, QString /*num_GUID*/, QString id_doss)
{//....................... effacement de toutes les rubriques ...............................................
 RUBREC_LIST::iterator it;
 for (it = pRubList->begin(); it !=  pRubList->end(); ++it )
     {if ((*it).m_PrimKey != "" && (*it).m_PrimKey != "-1" && (*it).m_PrimKey != "0")
         {RubListDelete(it);                                      // effacer la rubrique
         }
     } //end while (pSqlQuery->next())

 //........................... effacement du header et données de l'identité ................................

 int          ok  = FALSE;
 //.............................. ouvrir la base ............................................................
 if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return ;

 //............................. effacer les données identitaires ...........................................
 QString requete("DELETE FROM ");
         requete +=  m_DOSS_IDENT_TBL_NAME + " WHERE " + m_DOSS_IDENT_REF_PK + "='" + id_doss + "'";

 QSqlQuery* pSqlQuery = new QSqlQuery(QString::null , m_DataBase );
 if (pSqlQuery) ok = pSqlQuery->exec(requete);
 if (pSqlQuery) delete  pSqlQuery;
 if (ok == FALSE) {m_DataBase->close(); return ;}        // si erreur cassos

 //............................. effacer les blobs ...........................................................
 requete  = "DELETE FROM ";
 requete +=  m_DOSS_INDEX_TBL_NAME + " WHERE " + m_DOSS_INDEX_PRIM_KEY + "='" + id_doss + "'";

 pSqlQuery = new QSqlQuery(QString::null, m_DataBase);
 if (pSqlQuery) ok = pSqlQuery->exec(requete);
 if (pSqlQuery) delete  pSqlQuery;
 //............................. fermer la base .............................................................
 m_DataBase->close();
 return ;
}

//-------------------------------------- DossIdentIndexUpdate --------------------------------------------------------------------
// POUR QUE CELA MARCHE il faut imperativement une primarykey dans la table sinon: cur.update() ne fonctionne pas !!!
// SI plist_field est egal à zero alors seulement le nom et prenom sont mis à jour.

long  CMoteurBase::DossIdentIndexUpdate(QString& refDossPk, QString& nom, QString& prenom,
                                        PtrListIdentFieldData *plist_field /* =0 */)
{ int ok  = FALSE;
  //............... ouvrir la base .......................................................
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return FALSE;
  //............... crer un curseur SQL ..................................................
  QSqlCursor cur(m_DOSS_INDEX_TBL_NAME, TRUE, m_DataBase);
  if ( !cur.canUpdate ()) {m_DataBase->close(); return FALSE;}
  //............... placer ce curseur sur le bon enregistrement ..........................
  cur.select(  m_DOSS_INDEX_PRIM_KEY + "='" + refDossPk+"'");
  //............... si OK on recupere le buffer et on le charge avec les données .........
 if ( cur.next() )
    {QSqlRecord *buffer = cur.primeUpdate();                                // recuperer le buffer ( pas de delete à la fin !!)
     buffer->setValue( m_DOSS_INDEX_NOM,     nom.upper()    );              // y placer les données
     buffer->setValue( m_DOSS_INDEX_PRENOM,  prenom.upper() );              // y placer les données
     cur.update();      // ecrire le buffer avec les données du header
     ok  = TRUE;
    }
  //......................... fermer la base ..............................................
  if (ok && plist_field)  // si
     {ok = DossIdentDataUpdate(refDossPk, plist_field );
     }
  m_DataBase->close();
  return ok;
}

//-------------------------------------- DossIdentDataUpdate --------------------------------------------------------------------
// POUR QUE CELA MARCHE il faut imperativement une primarykey dans la table sinon: cur.update() ne fonctionne pas !!!
// ATTENTION: doit toujours etre appelée avec la base ouverte !!!
//
long  CMoteurBase::DossIdentDataUpdate(QString& refDossPk, PtrListIdentFieldData *plist_field )
{ //............... crer un curseur SQL ..................................................
  QSqlCursor cur(m_DOSS_IDENT_TBL_NAME, TRUE, m_DataBase);
  if ( !cur.canUpdate ()) return FALSE;
  //............... placer ce curseur sur le bon enregistrement ..........................
  cur.select(  m_DOSS_IDENT_REF_PK + "='" + refDossPk+"'");
  //............... si OK on recupere le buffer et on le charge avec les données .........
  if ( cur.next() )
     {QSqlRecord *buffer = cur.primeUpdate();                        // recuperer le buffer ( pas de delete à la fin !!)
      DossIdentBufferSetValue(buffer, plist_field );
      cur.update();
      return TRUE;
     }
  return FALSE;
}

//-------------------------------------- DossIdentBufferSetValue ---------------------------------------------------------------------

long  CMoteurBase::DossIdentBufferSetValue(QSqlRecord *buffer, PtrListIdentFieldData *plist_field  )
{//......... inserer les autres valeurs .........................
 CIdentFieldData *pCIdentFieldData;
 for ( pCIdentFieldData = plist_field->first(); pCIdentFieldData; pCIdentFieldData = plist_field->next() )
     {switch(pCIdentFieldData->m_Type)
            {case FTN_MAJ_STRING:
                  buffer->setValue( pCIdentFieldData->m_Name, pCIdentFieldData->m_Value.upper() );     // y placer les données
                  break;
             case FTN_STRING:
                  buffer->setValue( pCIdentFieldData->m_Name, pCIdentFieldData->m_Value);              // y placer les données
                  break;
             case FTN_NUM_STRING:
                  buffer->setValue( pCIdentFieldData->m_Name, pCIdentFieldData->m_Value);              // y placer les données
                  break;
             case FTN_INTEGER:
                  buffer->setValue( pCIdentFieldData->m_Name, pCIdentFieldData->m_Value.toInt());              // y placer les données
                  break;
             case FTN_CHAR:
                  {char c =  pCIdentFieldData->m_Value.at(1).latin1();
                   buffer->setValue( pCIdentFieldData->m_Name, c);
                  }
                  break;
             case FTN_DATETIME:   // "ddMMyyyy"
                  {QDate  qDteNss (pCIdentFieldData->m_Value.mid(4).toInt(),
                                           pCIdentFieldData->m_Value.mid(2,2).toInt(),
                                           pCIdentFieldData->m_Value.mid(0,2).toInt()
                                  );
                   buffer->setValue( pCIdentFieldData->m_Name, qDteNss);
                  }
              break;
         case FTN_DATETIME_TIRET:   // "yyyy-MM-dd hh:mn:ss"
                  {QDate  qDteNss (pCIdentFieldData->m_Value.mid(0,4).toInt(),
                                           pCIdentFieldData->m_Value.mid(5,2).toInt(),
                                           pCIdentFieldData->m_Value.mid(8,2).toInt()
                                  );
                   buffer->setValue( pCIdentFieldData->m_Name, qDteNss);
                  }
                  break;
            }
     }
 return 1;
}


//************************************************************************************************************************
//=================================== GESTION DE LA LISTE DES RUBRIQUES ==================================================
//************************************************************************************************************************

//-------------------------------------------- initRubriquesList ---------------------------------------------------------
long  CMoteurBase::initRubriquesList(RUBREC_LIST *pRubList, QString numGUID)
{if  (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;

 QString requete("SELECT ");
 int nb   = 0;

 //............... requete utilisant la base virtuelle .....................................................
 requete +=      m_DOSS_RUB_HEAD_PRIMKEY          + "," +      // 0
                 m_DOSS_RUB_HEAD_NOM_DATE         + "," +      // 1
                 m_DOSS_RUB_HEAD_TYPE             + "," +      // 2
                 m_DOSS_RUB_HEAD_SUBTYPE          + "," +      // 3
                 m_DOSS_RUB_HEAD_DATE             + "," +      // 4
                 m_DOSS_RUB_HEAD_USER             + "," +      // 5
                 m_DOSS_RUB_HEAD_SIGN_USER        + "," +      // 6
                 m_DOSS_RUB_HEAD_REF_BLOBS_PK     + " FROM ";  // 7
 requete +=  m_DOSS_RUB_HEAD_TBL_NAME         + " WHERE ";
 requete +=  m_DOSS_RUB_HEAD_GUID             + "='"  + numGUID   + "' ORDER BY ";                               //RbDate_Date RbDate_TypeRub='20030000'
 requete +=  m_DOSS_RUB_HEAD_DATE;

 QSqlQuery query(requete , m_DataBase );
 if (query.isActive())
    {while (query.next())
          {QString sign_user = Utf8_Query(query,6);
           QString user      = Utf8_Query(query,5);
           if (sign_user.length()<=0) sign_user = user;
           pRubList->append(CRubRecord(query.value(0).toString(),         // PrimKey
                                       Utf8_Query(query,1),               // libelle
                                       Utf8_Query(query,2),               // type
                                       Utf8_Query(query,3),               // sous type
                                       query.value(4).toString(),         // date l'enregistrement
                                       user,                              // utilisateur
                                       sign_user,                         // utilisateur signataire
                                       0,
                                       0,
                                       query.value(7).toString()          // reference au PK du Blobs
                                      )
                            );
         ++nb;
        }
    } //if (pSqlQuery && pSqlQuery->isActive() && pSqlQuery->next())
 m_DataBase->close();
 return nb;
}

//-------------------------------------------- GetRecorFromHeadPk ---------------------------------------------------------
long  CMoteurBase::GetRecorFromHeadPk(CRubRecord &record, const QString &headPk)
{if  (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;
 long nb = 0;
 QString requete("SELECT ");
 //............... requete utilisant la base virtuelle .....................................................
 requete +=      m_DOSS_RUB_HEAD_PRIMKEY          + "," +      // 0
                 m_DOSS_RUB_HEAD_NOM_DATE         + "," +      // 1
                 m_DOSS_RUB_HEAD_TYPE             + "," +      // 2
                 m_DOSS_RUB_HEAD_SUBTYPE          + "," +      // 3
                 m_DOSS_RUB_HEAD_DATE             + "," +      // 4
                 m_DOSS_RUB_HEAD_USER             + "," +      // 5
                 m_DOSS_RUB_HEAD_SIGN_USER        + "," +      // 6
                 m_DOSS_RUB_HEAD_REF_BLOBS_PK     + " FROM ";  // 7
 requete +=      m_DOSS_RUB_HEAD_TBL_NAME         + " WHERE ";
 requete +=      m_DOSS_RUB_HEAD_PRIMKEY          + "='"  + headPk   + "'";                               //RbDate_Date RbDate_TypeRub='20030000'

 QSqlQuery query(requete , m_DataBase );
 if (query.isActive())
    {while (query.next())
          {QString sign_user = Utf8_Query(query,6);
           QString user      = Utf8_Query(query,5);
           if (sign_user.length()<=0) sign_user = user;
           record.m_PrimKey      = query.value(0).toString();         // PrimKey
           record.m_Libelle      = Utf8_Query(query,1);               // libelle
           record.m_Type         = Utf8_Query(query,2);               // type
           record.m_SubType      = Utf8_Query(query,3);               // sous type
           record.m_Date         = query.value(4).toString();         // date l'enregistrement
           record.m_User         = user;                              // utilisateur
           record.m_SignUser     = sign_user;                         // utilisateur signataire
           record.m_State        = 0;                                      // etat
           record.m_Ref_Blobs_PK = query.value(7).toString();          // reference au PK du Blobs
           //record.SetData(0, 0);
           GetDataFromRub(record, record.m_Ref_Blobs_PK);
           ++nb;
          }
    } //if (pSqlQuery && pSqlQuery->isActive() && pSqlQuery->next())
 m_DataBase->close();
 return nb;
}

//-------------------------------------- GetRubPrimKeyFromGUID ---------------------------------------------------
QString CMoteurBase::GetRubPrimKeyFromGUID(const QString &guid, QString *ref_blobsPk)
{QString   ret("");
 //............... ouvrir la base  ..................................................
 if  (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return ret;

 //............... crer un curseur SQL ..................................................
 QSqlCursor cur(m_DOSS_RUB_HEAD_TBL_NAME, TRUE, m_DataBase);                                     // ouvrir un curseur sur la table
 if (!cur.select( m_DOSS_RUB_HEAD_GUID+"='"+guid+"'" )) goto  GetRubPrimKeyFromGUIDError;       // se placer sur le bon record
 if (cur.next())
    {if (ref_blobsPk) *ref_blobsPk = cur.value( m_DOSS_RUB_HEAD_REF_BLOBS_PK ).toString();
     ret = cur.value( m_DOSS_RUB_HEAD_PRIMKEY).toString();
     m_DataBase->close();
     return ret;
    }
GetRubPrimKeyFromGUIDError:
     OutSQL_error(cur, "GetRubPrimKeyFromGUID()");
     m_DataBase->close();
     return ret;
}


//-------------------------------------- GetDossPrimKeyFromGUID ---------------------------------------------------
QString CMoteurBase::GetDossPrimKeyFromGUID(const QString &guid)
{QString   ret("");
 //............... ouvrir la base  ..................................................
 if  (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return ret;

 //............... crer un curseur SQL ..................................................
 QSqlCursor cur(m_DOSS_INDEX_TBL_NAME, TRUE, m_DataBase);                                     // ouvrir un curseur sur la table
 if (!cur.select( m_DOSS_INDEX_GUID+"='"+guid+"'" )) goto  GetRubPrimKeyFromGUIDError;       // se placer sur le bon record
 if (cur.next())
    {ret = cur.value( m_DOSS_INDEX_PRIM_KEY).toString();
     m_DataBase->close();
     return ret;
    }
GetRubPrimKeyFromGUIDError:
     OutSQL_error(cur, "GetDossPrimKeyFromGUID()");
     m_DataBase->close();
     return ret;
}

//-------------------------------------- initConboBoxWithRubList -------------------------------------------------
/*! \brief Initialise le QComboBox passé en paramètre avec les documents de la liste selon leur type.
 * L'utilisation de la classe CPrtQListBoxItem permet et d'insérer un item dans le QComboBox et de lier ces items avec quelques données non affichées.

 * Types de documents :
 * 2001-0000 à 2001-9999   --> Courier
 * 2002-0000 à 2002-9999   --> Prescription avec: 2002-0000 à 2002-0000  --> OldPrescription
 *                                                2002-0200 à 2002-0299  --> NewPrescription
 *                                                2002-0300 à 2002-0399  --> NewCertificat
 * 2003-0000 à 2003-9999   --> Observations

 * \return Nombre de documents insérés dans le QComboBox.
 * \sa CPrtQListBoxItem
*/
long  CMoteurBase::initConboBoxWithRubList(RUBREC_LIST *pRubList, QComboBox* pComboBox, QString type)
{    RUBREC_LIST::iterator it;
     long  i = 0;
     int pos = 0;
     pComboBox->clear();
     int num_type = atoi(type);
     for(it = pRubList->begin(); it !=  pRubList->end(); ++it )   // it != m_RecSpeclist.end();
        { if ((*it).m_Type >= type && atoi((*it).m_Type) <= num_type+999)
             {QString qstr = (*it).m_Date.left(10) + " " +(*it).m_Libelle;
              // qstr.replace ( QChar('\r'), QChar(' ') );
              // qstr.replace ( QChar('\n'), QChar(' ') );
              // qstr.replace ( QChar('\t'), QChar(' ') );
              // qstr += " " + QString::number(pos);
              //pComboBox->insertItem (qstr);
              new CPrtQListBoxItem(pComboBox->listBox() ,           // list box du combobox
                                   qstr ,                           // libelle
                                   QString::number(pos) ,           //  position du document dans la liste RUBREC_LIST
                                   (*it).m_Date ,                   //  date document
                                   (*it).m_PrimKey,                 //  pk du document
                                   (*it).m_SubType    );            //  sous type du document
              ++i;
             }
         ++pos;
        } //end while (pSqlQuery->next())
     return i;
}

//-------------------------------------- GetAllRubriqueFromDate -------------------------------------------------
// 2001-0000 à 2001-9999   --> Courier
// 2002-0000 à 2002-9999   --> Prescription avec: 2002-0000 à 2002-0000  --> OldPrescription
//                                                2002-0200 à 2002-0299  --> NewPrescription
//                                                2002-0300 à 2002-0399  --> NewCertificat
// 2003-0000 à 2003-9999   --> Observations
long  CMoteurBase::GetAllRubriqueFromDate(RUBREC_LIST *pRubList, const QDate &qdtRef, QString type/*="ALL_TYP"*/, QStringList *pRubNameList /*=0*/)
{    RUBREC_LIST::iterator it;
     long  i = 0;
     int pos = 0;
     if (pRubNameList) pRubNameList->clear();
     int num_type = atoi(type);
     for(it = pRubList->begin(); it !=  pRubList->end(); ++it )   // it != m_RecSpeclist.end();
        { if ( (type=="ALL_TYP" || ((*it).m_Type >= type && atoi((*it).m_Type) <= num_type+999)))
             { QDate qdtRub( atoi((*it).m_Date.mid(0,4)),
                             atoi((*it).m_Date.mid(5,2)),
                             atoi((*it).m_Date.mid(8,2))
                           );
                if ( qdtRub == qdtRef )
                   {if (pRubNameList)
                       {QString qstr = (*it).m_Date.left(10) + " " +(*it).m_Libelle;
                        qstr.replace ( QChar('\r'), QChar(' ') );
                        qstr.replace ( QChar('\n'), QChar(' ') );
                        qstr.replace ( QChar('\t'), QChar(' ') );
                        qstr += " " + QString::number(pos);
                        pRubNameList->append(qstr);
                       }
                    ++i;
                   }
             }
         ++pos;
        } //end while (pSqlQuery->next())
     return i;
}

//-------------------------------------- ReplaceDataInRubList ---------------------------------------------------------
// ACTION: place des données sur un des elements de la liste des rubriques
//
void  CMoteurBase::ReplaceDataInRubList(const QString & qString, RUBREC_LIST *pRubList, int id)
{  RUBREC_LIST::iterator it = pRubList->at(id);           // recuperer pointeur sur le CRubRecord correspondant à id
   ReplaceDataInRubList( qString, it );
   /*
   QCString cs    = qString.utf8 ();
   const char *pt = cs;
   if (IsUtf8(  pt ))
      {(*it).SetData (cs.data(), cs.count());
      }
   else
      {(*it).SetData (qString, qString.length());
      }
  */
}

//-------------------------------------- ReplaceDataInRubList ---------------------------------------------------------
// ACTION: place des données sur un des elements de la liste des rubriques
//
void  CMoteurBase::ReplaceDataInRubList(const QString & qString, RUBREC_LIST::iterator it)
{  //RUBREC_LIST::iterator it = pRubList->at(id);           // recuperer pointeur sur le CRubRecord correspondant à id
   QCString cs              = qString.utf8 ();
   const char *pt = cs;
   if (IsUtf8(  pt ))
      {(*it).SetData (cs.data(), cs.count());
      }
   else
      {(*it).SetData (qString, qString.length());
      }
}

//-------------------------------------- ReplaceDataInRubList ---------------------------------------------------------
// ACTION: place des données sur un des elements de la liste des rubriques
//
void  CMoteurBase::ReplaceDataInRubList(const char* text, long len_data, RUBREC_LIST *pRubList, int id)
{RUBREC_LIST::iterator it = pRubList->at(id);           // recuperer pointeur sur le CRubRecord correspondant à id
 (*it).SetData (text, len_data);
}

//-------------------------------------- ReplaceDataInRubList ---------------------------------------------------------
// ACTION: place des données sur un des elements de la liste des rubriques
//
void  CMoteurBase::ReplaceDataInRubList(const char* text, long len_data,  RUBREC_LIST::iterator it)
{//RUBREC_LIST::iterator it = pRubList->at(id);           // recuperer pointeur sur le CRubRecord correspondant à id
 (*it).SetData (text, len_data);
}
//-------------------------------------- RubList_SetItemDeleted ---------------------------------------------------------
void  CMoteurBase::RubList_SetItemDeleted(RUBREC_LIST *pRubList, int id)
{(*pRubList->at(id)).m_State |= RUB_IS_TO_DELETE;
}

//-------------------------------------- RubList_SetItemDeleted ---------------------------------------------------------
int  CMoteurBase::RubList_IsItemDeleted(RUBREC_LIST *pRubList, int id)
{return (*pRubList->at(id)).m_State & RUB_IS_TO_DELETE;
}

//-------------------------------------- RubList_SetItemNotDeleted ---------------------------------------------------------
void  CMoteurBase::RubList_SetItemNotDeleted(RUBREC_LIST *pRubList, int id)
{(*pRubList->at(id)).m_State &= ~RUB_IS_TO_DELETE;
}

//-------------------------------------- GetDataFromRub ---------------------------------------------------------
int CMoteurBase::GetDataFromRub(QByteArray &qByteArray, const QString &blobsPrimKey)  // query.value(1).toByteArray() -> m_DOSS_RUB_HEAD_PRIMKEY
{   if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;
    QString   requete("SELECT ");
    requete += m_DOSS_RUB_DATA_BLOB     + " FROM " + m_DOSS_RUB_DATA_TBL_NAME + " WHERE ";
    requete += m_DOSS_RUB_DATA_PRIMKEY  + "='"     + blobsPrimKey             + "'";

    QSqlQuery query (requete , m_DataBase );
    if (query.isActive() && query.next())
       {qByteArray = query.value(0).toByteArray();
        return 1;
       }
    return 0;
}
//-------------------------------------- GetDataFromRubList ---------------------------------------------------------
QString  CMoteurBase::GetDataFromRubList( CRubRecord  *pCRubRecord )
{QString stringDST;
 GetDataFromRubList( stringDST, pCRubRecord);
 return  stringDST;
}

//-------------------------------------- GetDataFromRubList ---------------------------------------------------------
/*! \brief Recupere les donnees d'un enregistrement CRubRecord  *pCRubRecord en lisant la base de donnee.
 *  \param CRubRecord = pointeur vers l'enregistrement dont il faut recuperer les donnees
 *  \param stringDST : QString où seront placées les donnees
 *  \note cette fonction place les donnees dans l'espace pCRubRecord->data() et donc si elle est utilisee
 *        pour recuperer les donnees d'un  RubRecord appartenant a la liste des rubriques : RUBREC_LIST de drtux 
 *        ce RubRecord sera considere comme modifie donc à enregistrer. 
*/
int CMoteurBase::GetDataFromRubList( QString &stringDST, CRubRecord  *pCRubRecord)
{
 if (pCRubRecord==0) return 0;
 stringDST         = "";
 int           ret = 0;

 if ( pCRubRecord->isEmpty() )
   {QString   requete("SELECT ");
    requete += m_DOSS_RUB_DATA_BLOB     + " FROM " + m_DOSS_RUB_DATA_TBL_NAME + " WHERE ";
    requete += m_DOSS_RUB_DATA_PRIMKEY  + "='"     + pCRubRecord->m_Ref_Blobs_PK + "'";

    if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)                           return 0;

    QSqlQuery sqlQuery (requete , m_DataBase );
    if (sqlQuery.isActive() && sqlQuery.next())
       { // QMemArray<type> & QMemArray::operator= ( const QMemArray<type> & a )
         // Assigns a shallow copy of a to this array and returns a reference to this array.
         // Equivalent to assign( a ).
         pCRubRecord->assign(sqlQuery.value(0).toByteArray());
         //data = sqlQuery.value(0).toByteArray()/*.copy()*/;
         ret = RUB_READ_ON_DISK;
       }
   }
 //....................... SI c'est une rubrique nouvellement crée ou en édition ..............................
 //                        on se sert directement des données stockées dans: CRubRecord
 else
   {ret = RUB_READ_IN_LIST;
   }

 char *ptr     = pCRubRecord->data();
 long  len     = pCRubRecord->size();
 if (ptr)
    {if ( len>=10 && CHtmlTools::IsRtf (ptr, 10) )
        {CHtmlTools::RtfToQtextEdit_HTML(ptr+4, len-4, stringDST, 1);
        }
     else
        {if (CGestIni::IsUtf8( ptr )) stringDST = QString::fromUtf8 ( ptr );
         else                         stringDST = ptr;
        }
    }
 return ret;
}


//-------------------------------------- GetDataFromRubList ---------------------------------------------------------
int  CMoteurBase::GetDataFromRubList( QString &stringDST, RUBREC_LIST *pRubList, int id )
{QByteArray data;
 stringDST = "";
 if (id==-1) return -1;
 int   ret = GetDataFromRubList(data, pRubList->at(id));

 if (ret == RUB_READ_ON_DISK || ret == RUB_READ_IN_LIST)      // en fait cela veut dire que ça été lu sur le disque
    {char *ptr     = data.data();
     long  len     = data.size();
     if (ptr)
        {if ( len>=10 && CHtmlTools::IsRtf (ptr, 10) )
            {CHtmlTools::RtfToQtextEdit_HTML(ptr+4, len-4, stringDST, 1);
            }
         else
            {if (CGestIni::IsUtf8( ptr )) stringDST = QString::fromUtf8 ( ptr );
             else                         stringDST = ptr;
            }
        }
    }
 return ret;
}

//-------------------------------------- GetDataFromRubList ---------------------------------------------------------
int  CMoteurBase::GetDataFromRubList(QByteArray &pQByteArray, RUBREC_LIST *pRubList, int id)
{return GetDataFromRubList(pQByteArray, pRubList->at(id));
}

//-------------------------------------- GetDataFromRubList ---------------------------------------------------------
int  CMoteurBase::GetDataFromRubList(QByteArray &pQByteArray, RUBREC_LIST::iterator it)
{
 int       ret = 0;
 //....................... SI c'est une rubrique nouvellement crée ou en édition ..............................
 //                        on se sert directement des données stockées dans: CRubRecord
 if (!(*it).isEmpty())
    {pQByteArray = (*it)             /*.copy()*/;
     return RUB_READ_IN_LIST;
    }
 //....................... SINON on va chercher sur le disque ..............................
 else
   {QString   requete("SELECT ");
    requete += m_DOSS_RUB_DATA_BLOB     + " FROM " + m_DOSS_RUB_DATA_TBL_NAME + " WHERE ";
    requete += m_DOSS_RUB_DATA_PRIMKEY  + "='"     + (*it).m_Ref_Blobs_PK + "'";

    if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;

    QSqlQuery sqlQuery (requete , m_DataBase );
    if (sqlQuery.isActive() && sqlQuery.next())
       {pQByteArray = sqlQuery.value(0).toByteArray()/*.copy()*/;
        ret = RUB_READ_ON_DISK;
       }
    return ret;
   }
}

//-------------------------------------- RubNbToSave ----------------------------------------------------------------------
long  CMoteurBase::RubNbToSave( RUBREC_LIST *pRubList)
{long nb_to_save = 0;
 long          i = 0;
 RUBREC_LIST::iterator it;
 for (it = pRubList->begin(); it !=  pRubList->end(); ++it )
     {if ((*it).m_State & RUB_IS_TO_DELETE) // a effacer
         {//.... si nouvelles données et mises sur effacer ..............
          //     alors on conptabilise pas
          if ((*it).m_PrimKey !=  "0") ++nb_to_save;
         }
      else if ((*it).m_PrimKey == "0")      // nouvelles données
         {if (! (*it).isEmpty())
             {++nb_to_save;
             }
         }
      else if (! (*it).isEmpty() )          // si les datas ont ete misee en cache c'est qu'elles on ete modifiées
         {++nb_to_save;
         }
      ++i;
     } //end while (pSqlQuery->next())
 return nb_to_save;
}

//-------------------------------------- RubListSave ----------------------------------------------------------------------
long  CMoteurBase::RubListSave( RUBREC_LIST *pRubList, QString numGUID)
{
 long  i = 0;
 RUBREC_LIST::iterator it;
 for (it = pRubList->begin(); it !=  pRubList->end(); ++it )
     {if ((*it).m_State & RUB_IS_TO_DELETE)
         {RubListDelete(it);                                         // effacer la rubrique
          (*it).m_PrimKey = "-1";
         }
      else if ((*it).m_PrimKey == "0")
         {if (! (*it).isEmpty() )
             {RubListCreate(it, numGUID);                            // creer la rubrique
              (*it).m_PrimKey = GetRubPrimKeyFromGUID(numGUID,0);    // noter le primKey nouvellement créé
             }
         }
      else if (! (*it).isEmpty() )
         {RubListUpdate(it);                                         // updater la rubrique
         }
      ++i;
     } //end while (pSqlQuery->next())
 return i;
}


//-------------------------------------- RubListCreate ----------------------------------------------------------------------
int  CMoteurBase::RubListCreate(RUBREC_LIST::iterator it, QString numGUID)
{
  //............... ouvrir la base .......................................................
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return FALSE;
  //if (VerrouilleTable(m_DOSS_RUB_DATA_TBL_NAME, m_DataBase)==0)  return 0;
  //if (VerrouilleTable(m_DOSS_RUB_HEAD_TBL_NAME, m_DataBase)==0)  return 0;


  /*
  const char *pt_m_User    = (*it).m_User;
  const char *pt_m_Libelle = (*it).m_Libelle;
  const char *pt_m_Date    = (*it).m_Date;
  const char *pt_m_Type    = (*it).m_Type;
  const char *pt_m_data    = (*it);
  */
  QString blobs_Pk = RubListBlobCreate(it, numGUID);
  if (blobs_Pk.length())
     {//............... crer un curseur SQL ..................................................
      QSqlCursor cur(m_DOSS_RUB_HEAD_TBL_NAME, TRUE, m_DataBase);
      if ( !cur.canInsert ()) {m_DataBase->close();             return FALSE;}
      (*it).m_Ref_Blobs_PK = blobs_Pk;
      //............... si OK on recupere le buffer et on le charge avec les données .........
      QSqlRecord *buffer = cur.primeInsert();                               // recuperer le buffer d'insertion
      buffer->setValue( m_DOSS_RUB_HEAD_GUID,           numGUID               );  // y placer les données
      buffer->setValue( m_DOSS_RUB_HEAD_USER,           (*it).m_User          );  // y placer les données
      buffer->setValue( m_DOSS_RUB_HEAD_SIGN_USER,      (*it).m_SignUser      );  // y placer les données
      buffer->setValue( m_DOSS_RUB_HEAD_NOM_DATE,       (*it).m_Libelle       );  // y placer les données
      buffer->setValue( m_DOSS_RUB_HEAD_DATE,           (*it).m_Date          );  // y placer les données
      buffer->setValue( m_DOSS_RUB_HEAD_TYPE,           (*it).m_Type          );  // y placer les données
      buffer->setValue( m_DOSS_RUB_HEAD_SUBTYPE,        (*it).m_SubType       );  // y placer les données
      buffer->setValue( m_DOSS_RUB_HEAD_REF_BLOBS_PK,   (*it).m_Ref_Blobs_PK  );
      if (!cur.insert())  {m_DataBase->close();             return FALSE;}
     }
  //......................... fermer la base ..............................................
  m_DataBase->close();
  return TRUE;
}

//-------------------------------------- RubListBlobCreate ----------------------------------------------------------------------
QString  CMoteurBase::RubListBlobCreate(RUBREC_LIST::iterator it, QString numGUID)
{//............... crer un curseur SQL ...................................................................................
 QSqlCursor cur(m_DOSS_RUB_DATA_TBL_NAME, TRUE, m_DataBase);
 if ( !cur.canInsert() )                                           return QString::null;
 //............... se creer un GUID temporaire permettant par la suite de retrouver le Pk de l'enregistrement créé .................
 QString temp_GUID  = GUID_Create();
 //............... si OK on recupere le buffer et on le charge avec les données ..........................................
 QSqlRecord *buffer = cur.primeInsert();                        // recuperer le buffer d'insertion
 buffer->setValue( m_DOSS_RUB_DATA_BLOB, (*it) );               // y placer les données
 buffer->setValue( m_DOSS_RUB_DATA_GUID, temp_GUID );           // y placer le GUID temporaire (permettra de retrouver l'enregistrement créé)
 if (!cur.insert())                                                return QString::null;                   // ecrire les données

 //................. reselectionner l'enregistrement pour retrouver son PK avec le GUID temporaire........................
 QString prim_key = QString::null;
 QString   requete("SELECT ");
 requete += m_DOSS_RUB_DATA_PRIMKEY  + " FROM " + m_DOSS_RUB_DATA_TBL_NAME + " WHERE ";
 requete += m_DOSS_RUB_DATA_GUID     + "='"     + temp_GUID                + "'"; // retrouver le Pk de l'enregistrement créé avec le GUID temporaire
 QSqlQuery sqlQuery(requete , m_DataBase );
 if (sqlQuery.isActive() && sqlQuery.next()) prim_key = sqlQuery.value(0).toString();

 //................. replacer le bon GUID dans l'enregistrement  .........................................................
 QSqlCursor cur_u(m_DOSS_RUB_DATA_TBL_NAME, TRUE, m_DataBase);
 if ( !cur_u.canUpdate ())                                         return QString::null;
 cur_u.select(  m_DOSS_RUB_DATA_PRIMKEY + "=" + prim_key);
 //............... si OK on recupere le buffer et on le charge avec les données .........
 if ( cur_u.next() )
    {QSqlRecord *buffer = cur_u.primeUpdate();                      // recuperer le buffer
     buffer->setValue( m_DOSS_RUB_DATA_GUID, numGUID );             // y placer le vrai GUID
     if (cur_u.update()<=0)                                        return QString::null;         // ecrire les données
    }
 return prim_key;
}

//-------------------------------------- RubListDelete ----------------------------------------------------------------------
int  CMoteurBase::RubListDelete(RUBREC_LIST::iterator it)
{int          ok  = FALSE;
 //.............................. ouvrir la base ..........................................................
 if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;
 //if (VerrouilleTable(m_DOSS_RUB_DATA_TBL_NAME, m_DataBase)==0)  return 0;
 //if (VerrouilleTable(m_DOSS_RUB_HEAD_TBL_NAME, m_DataBase)==0)  return 0;
 //............................. effacer le header .........................................................
  QString requete("DELETE FROM ");
         requete +=  m_DOSS_RUB_HEAD_TBL_NAME + " WHERE " + m_DOSS_RUB_HEAD_PRIMKEY + "='" +(*it).m_PrimKey + "'";

 QSqlQuery sqlQuery(QString::null , m_DataBase );
 ok = sqlQuery.exec(requete);
 if (ok == FALSE) {/*DeVerrouilleTable(m_DataBase);*/ m_DataBase->close(); return FALSE;}        // si erreur cassos

 //............................. effacer le blob ...........................................................
 requete  = "DELETE FROM ";
 requete +=  m_DOSS_RUB_DATA_TBL_NAME + " WHERE " + m_DOSS_RUB_DATA_PRIMKEY + "='" +(*it).m_Ref_Blobs_PK + "'";
 ok = sqlQuery.exec(requete);
 //............................. fermer la base .............................................................
 //DeVerrouilleTable(m_DataBase);
 m_DataBase->close();
 return ok;
}

//-------------------------------------- RubListUpdate ----------------------------------------------------------------------
/*
               m_PrimKey        = primKey;
               m_Libelle        = libelle;
               m_Type           = type;
               m_Date           = date;
               m_User           = user;
               m_pCharData      = 0;        // n'est initialisé avec des données d'une rubrique que lors modification
               m_LenData        = 0;
               m_State          = 0;

   QString      m_DOSS_RUB_HEAD_TBL_NAME;        // nom de la table de l'header des RUBRIQUES
   QString      m_DOSS_RUB_HEAD_PRIMKEY;         // clef primaire de cet enregistrement
   QString      m_DOSS_RUB_HEAD_GUID;            // GUID du dossier auquel l'enregistrement fait reference
   QString      m_DOSS_RUB_HEAD_REF_DOSS_PK;     // Clef primaire du dossier auquel l'enregistrement fait reference (doublon avec m_DOSS_RUB_HEAD_GUID)
   QString      m_DOSS_RUB_HEAD_NOM_DATE;        // Court texte descriptif de l'enregistrement.
   QString      m_DOSS_RUB_HEAD_DATE;            // date de l'enregistrement
   QString      m_DOSS_RUB_HEAD_DUREE;           // duree de l'enregistrement
   QString      m_DOSS_RUB_HEAD_TYPE;            // Type de rubrique
   QString      m_DOSS_RUB_HEAD_USER;            // utilisateur associé à rubrique

*/
int  CMoteurBase::RubListUpdate(RUBREC_LIST::iterator it)
{ /*............................... methode requete ............................................
  //                       pose un PB avec les valeurs litérales comportant une apostrophe
  //                       car sont évaluées comme delimiteurs de valeurs
  int          ok  = FALSE;
  (*it).m_Libelle.replace( QChar('\''), " ");             // sinon erreur syntaxe sql avec "'"
  QString requete  = "UPDATE ";
          requete +=  m_DOSS_RUB_HEAD_TBL_NAME   + " SET ";
          requete +=  m_DOSS_RUB_HEAD_USER       + " = '" + (*it).m_User           + "' , ";
          requete +=  m_DOSS_RUB_HEAD_NOM_DATE   + " = '" + (*it).m_Libelle        + "' , ";
          requete +=  m_DOSS_RUB_HEAD_DATE       + " = '" + (*it).m_Date           + "' , ";
          requete +=  m_DOSS_RUB_HEAD_TYPE       + " = '" + (*it).m_Type           + "' , ";
          requete +=  m_DOSS_RUB_HEAD_USER       + " = '" + (*it).m_User           + "' WHERE ";
          requete +=  m_DOSS_RUB_HEAD_PRIMKEY    + " = '" + (*it).m_PrimKey        + "'";

  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;

  QSqlQuery* pSqlQuery = new QSqlQuery(requete , m_DataBase );
  if (pSqlQuery && pSqlQuery ->isActive())  ok = TRUE;
  if (ok) ok = RubListBlobUpdate(it);                    // au tour des données binaires
  if (pSqlQuery) delete  pSqlQuery;
  m_DataBase->close();

  */
  //................................. methode QSqlCursor .....................................
  //                         ne pose pas de PB avec valeur avec une apostrophe
  int ok  = FALSE;
  //............... ouvrir la base .......................................................
  if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return 0;
  //if (VerrouilleTable(m_DOSS_RUB_DATA_TBL_NAME, m_DataBase)==0)  return 0;
  //if (VerrouilleTable(m_DOSS_RUB_HEAD_TBL_NAME, m_DataBase)==0)  return 0;

  //............... crer un curseur SQL ..................................................
  QSqlCursor cur(m_DOSS_RUB_HEAD_TBL_NAME, TRUE, m_DataBase);
  if ( !cur.canUpdate ()) {/*DeVerrouilleTable(m_DataBase); */m_DataBase->close(); return FALSE;}
  //............... placer ce curseur sur le bon enregistrement ..........................
  cur.select(  m_DOSS_RUB_HEAD_PRIMKEY + "=" + (*it).m_PrimKey);
  //............... si OK on recupere le buffer et on le charge avec les données .........
 if ( cur.next() )
    {QSqlRecord *buffer = cur.primeUpdate();                        // recuperer le buffer ( pas de delete à la fin !!)
     buffer->setValue( m_DOSS_RUB_HEAD_USER,       (*it).m_User     ); // y placer les données
     buffer->setValue( m_DOSS_RUB_HEAD_SIGN_USER,  (*it).m_SignUser ); // y placer les données
     buffer->setValue( m_DOSS_RUB_HEAD_NOM_DATE,   (*it).m_Libelle  ); // y placer les données
     buffer->setValue( m_DOSS_RUB_HEAD_DATE,       (*it).m_Date     ); // y placer les données
     buffer->setValue( m_DOSS_RUB_HEAD_TYPE,       (*it).m_Type     ); // y placer les données
     buffer->setValue( m_DOSS_RUB_HEAD_SUBTYPE,    (*it).m_SubType  ); // y placer les données
     cur.update();                                                  // ecrire le buffer avec les données du header
     ok = RubListBlobUpdate(it);                                    // s'occuper des données binaires BLOB
    }
  //......................... fermer la base ..............................................
  //DeVerrouilleTable(m_DataBase);
  m_DataBase->close();
  return ok;
}

//-------------------------------------- RubListBlobUpdate ----------------------------------------------------------------------
/*
   QString      m_DOSS_RUB_DATA_TBL_NAME;        // nom de la table des données des RUBRIQUES
   QString      m_DOSS_RUB_DATA_PRIMKEY;         // clef primaire de cet enregistrement  (le meme que le header)
   QString      m_DOSS_RUB_DATA_BLOB;            // données binaires
   int          m_DOSS_RUB_DATA_FP_PRIMKEY;      // position du champ clef primaire de cet enregistrement
   int          m_DOSS_RUB_DATA_FP_BLOB;         // position du champ données binaires  de l'enregistrement
*/

int  CMoteurBase::RubListBlobUpdate(RUBREC_LIST::iterator it)
{//............... crer un curseur SQL ..................................................
 QSqlCursor cur(m_DOSS_RUB_DATA_TBL_NAME, TRUE, m_DataBase);
 if ( !cur.canUpdate ()) return FALSE;
 cur.select(  m_DOSS_RUB_DATA_PRIMKEY + "=" + (*it).m_Ref_Blobs_PK);
 //............... si OK on recupere le buffer et on le charge avec les données .........
 if ( cur.next() )
    {QSqlRecord *buffer = cur.primeUpdate();                        // recuperer le buffer
     //char *pt = (char*)(const char*)(*it);
     buffer->setValue( m_DOSS_RUB_DATA_BLOB, (*it) );               // y placer les données
     cur.update();                                                  // ecrire les données
     //delete buffer; A NE SURTOUT PAS FAIRE !!!!
    }
 return TRUE;
}

//**********************************************************************************************************************************
//=================================== GESTION DU VERROUILLAGE DES BASES ============================================================
//**********************************************************************************************************************************
//------------------------------------------------ VerrouilleDossier  --------------------------------------------------------------
int CMoteurBase::VerrouilleDossier     ( const QString &dossGUID,
                                         const QString &userName,
                                         QString &usedBy
                                       )
{ usedBy =  VerrouilleRubrique("", dossGUID, "All Rubriques", "", userName, "" );
  if (usedBy=="+") return 1;

  return 0;
}

//------------------------------------------------ VerrouilleTable  --------------------------------------------------------------
int CMoteurBase::VerrouilleTable(const QString &tableName, QSqlDatabase* dataBase)
{QSqlQuery query(QString("LOCK TABLES ") + tableName + " WRITE", dataBase);
 if (query.isActive()) return 1;
 return 0;
}

//------------------------------------------------ DeVerrouilleTable  --------------------------------------------------------------
int CMoteurBase::DeVerrouilleTable(QSqlDatabase* dataBase)
{QSqlQuery query("UNLOCK TABLES  ", dataBase);
 if (query.isActive()) return 1;
 return 0;
}

//------------------------------------------------ IsDossierVerrouille  --------------------------------------------------------------
int CMoteurBase::IsDossierVerrouille   ( const QString &dossGUID, QString &usedBy )
{ if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return -1;  // si point = erreur d'ouverture de la base
  //QString dateTimeR;
  if (dossGUID.length()==0) return -1; // si GUID vide (cas d'un nouveau dossier) retourner modif valide
  //.................. verifier si pas déjà utilisé ......................................................................................
  //                   et si c'est le cas retourner le proprietaire
  QString requete("");
  requete += QString("SELECT ") + m_VERROU_USER_NAME + " FROM " + m_VERROU_TBL_NAME + " WHERE " + m_VERROU_DOSS_GUID  + " = '" +   dossGUID + "'";
  QSqlQuery query(requete , m_DataBase );
  if (query.isActive() && query.next())
    {usedBy = Utf8_Query(query,0);    // retourne l'utilisateur déjà propriétaire
     return 1;                         // et cassos car c'est deja verrouillé par un autre
    }
  usedBy = "";
  return 0;
}

//------------------------------------------------ VerrouilleRubrique --------------------------------------------------------------
QString CMoteurBase::VerrouilleRubrique( const QString &dossPk,
                                         const QString &dossGUID,
                                         const QString &rubName,
                                         const QString &rubPk,
                                         const QString &userName,
                                         const QString &dateTime
                                       )
{if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return QString(".");  // si point = erreur d'ouverture de la base
 QString ret("");
 QString dateTimeR;
 if (dossGUID.length()==0) return QString("+"); // si GUID vide (cas d'un nouveau dossier) retourner modif valide
 //.................. verifier si pas déjà utilisé ......................................................................................
 //                   et si c'est le cas retourner le proprietaire
 QString requete("");
 requete += QString("SELECT ") + m_VERROU_USER_NAME + " FROM " + m_VERROU_TBL_NAME + " WHERE " + m_VERROU_DOSS_GUID  + " = '" +   dossGUID + "'";
 QSqlQuery query(requete , m_DataBase );
 if (query.isActive() && query.next())
    {ret = query.value(0).toString();    // retourne l'utilisateur déjà propriétaire
     return ret;                         // et cassos car c'est deja verrouillé par un autre
    }

 //.................. si pas dèjà verrouillé inserer notre verrou .......................................................................
 //.................. verouiller la table ................................................
 query.exec(QString("LOCK TABLES ") + m_VERROU_TBL_NAME + " WRITE");
 //.................. crer un curseur SQL ................................................
 QSqlCursor cur(m_VERROU_TBL_NAME, TRUE, m_DataBase);
 if ( !cur.canInsert ())                                    return QString(".");
 QDateTime dt ( QDate::currentDate (), QTime::currentTime() );
 if (dateTime.length()==0) dateTimeR = dt.toString("yyyyMMddhhmmsszzz");
 else                      dateTimeR = dateTime;
 //............... si OK on recupere le buffer et on le charge avec les données ..........
 QSqlRecord *buffer = cur.primeInsert();
 buffer->setValue( m_VERROU_DOSS_PK,     dossPk.toInt()                     );  // y placer les données
 buffer->setValue( m_VERROU_DOSS_GUID,   dossGUID                           );  // y placer les données
 buffer->setValue( m_VERROU_RUB_NAME,    rubName                            );  // y placer les données
 buffer->setValue( m_VERROU_RUB_PK,      rubPk.toInt()                      );  // y placer les données
 buffer->setValue( m_VERROU_USER_NAME,   userName                           );  // y placer les données
 buffer->setValue( m_VERROU_DATE_TIME,   dateTimeR                          );  // y placer les données
 if (cur.insert())   ret = "+";
 else                ret = "-";
 //................. deverouiller la table ................................................................................................
 query.exec("UNLOCK TABLES ");
 return ret;
}

//------------------------------------------------ DeVerrouilleDossier --------------------------------------------------------------
void    CMoteurBase::DeVerrouilleDossier ( const QString &dossGUID)
{DeVerrouilleRubrique("",dossGUID,"", "","","" );
}

//------------------------------------------------ DeVerrouilleRubrique --------------------------------------------------------------
void    CMoteurBase::DeVerrouilleRubrique( const QString &/*dossPk*/,
                                           const QString &dossGUID,
                                           const QString &/*rubName*/,
                                           const QString &/*rubPk*/,
                                           const QString &/*userName*/,
                                           const QString &/*dateTime*/
                                       )
{if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return ;  // si point = erreur d'ouverture de la base
 //................. verouiller la table ..................................................................................................
 QSqlQuery query(QString("LOCK TABLES ") + m_VERROU_TBL_NAME + " WRITE", m_DataBase);
 //............................. effacer le header .........................................................
 query.exec(QString("DELETE FROM ")      + m_VERROU_TBL_NAME + " WHERE " + m_VERROU_DOSS_GUID + "='" + dossGUID + "'");
 //................. deverouiller la table ................................................................................................
 query.exec("UNLOCK TABLES ");
}

//------------------------------------------------ DeVerrouilleTout --------------------------------------------------------------
void    CMoteurBase::DeVerrouilleTout(  )
{if (m_DataBase->isOpen()==FALSE && m_DataBase->open()==FALSE)  return ;  // si point = erreur d'ouverture de la base
 //................. verouiller la table ..................................................................................................
 QSqlQuery query(QString("LOCK TABLES ") + m_VERROU_TBL_NAME + " WRITE", m_DataBase);
 //............................. effacer le header .........................................................
 query.exec(QString("DELETE FROM ")      + m_VERROU_TBL_NAME );
 //................. deverouiller la table ................................................................................................
 query.exec("UNLOCK TABLES ");

}
//**********************************************************************************************************************************
//=================================== GESTION DES IDENTIFICATEURS UNIQUES GUID, PASSWORD ===========================================
//**********************************************************************************************************************************

//-----------------------------------------------------  PassWordEncode --------------------------------------------------
// Algo minimal pour l'instant
// chaque octet tourne de sa position dans la chaine + 1, et Xor final avec le mot de passe en clair puis converti en hexa
// resultat final en hexa;
int CMoteurBase::PassWordEncode(QString &pass)
{char str[34];
 INT16    val;
 int len         = pass.length();

 if (len>32)       return ERR_PASS_MAX;
 if (len==0)       return ERR_PASS_ZERO;
 strcpy(str , pass);
 pass = "";
 for (int i=0; i<len; ++i)
     { val   =  str[i];
       val   =  (val << ((i+1)&0x000F) )^val;
      pass  += UINTtoHex(val);
     }
 return ERR_PASS_OK;
}

//-----------------------------------------------------  PassWordDecode --------------------------------------------------
// Algo minimal pour l'instant
int CMoteurBase::PassWordDecode(const char* str_to_decode, const char* str_pass)
{char     buf[16];
 UINT16   val;
 if (str_to_decode == 0 || str_pass == 0) return ERR_PASS_MAX;
 int len_to_decode      = strlen(str_to_decode);
 if (len_to_decode==0)             return ERR_PASS_ZERO;
 int len_pass           = strlen(str_pass);
 if (len_pass != len_to_decode/4)  return ERR_PASS_MAX;
 QString result;
 int end = len_to_decode/4;
 buf[4 ] = 0;
 for (int i=0; i<end; ++i)
     {memcpy(buf, str_to_decode + i*4, 4);  // recuperer les 4 caractere hexa
      val = HexToUINT(buf);                 // les convertir en UINT16
      val = val ^ str_pass[i];              // xor avec le mot de passe
      val = val >> ((i+1)&0x000F);          // rotation inverse maxi de 8 et on devrait avoir le code ASCII
      if (val != str_pass[i])      return ERR_PASS_MAX;    // erreur si pas egal
     }
 return ERR_PASS_OK;
}

//-----------------------------------------------------  UINTtoHex --------------------------------------------------------
QString CMoteurBase::UINTtoHex( UINT16 val)
{char hex[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};   // là on peut mettre une table Bidon
 QString res="";
 res += hex[(val>>12)& 0x000F];
 res += hex[(val>>8) & 0x000F];
 res += hex[(val>>4) & 0x000F];
 res += hex[val&0x000F];
 return res;
}

//-----------------------------------------------------  HexToUINT --------------------------------------------------------
UINT16 CMoteurBase::HexToUINT( const char *str)
{int i   = strlen(str);
 if (i==0) return 0;
 UINT16 val = 0;
 int    dec = 0;
 while (i>0)
   {--i;
    unsigned char car = str[i] | 32;     // mettre en minuscules
    if      (car>='a'&& car<= 'f')  val  += (car-'W')<<dec;  //a (97) - W (87) --> 10
    else                            val  += (car-'0')<<dec;  //0 (48) - 0 (48) --> 0
    dec += 4;
   }
 return val;
}


//-----------------------------------------------------  GUID_Create --------------------------------------------------
QString CMoteurBase::GUID_Create(/*const char *format   ="%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X" */)
{
    QString guid ( QUuid::createUuid ().toString());
    return  guid.mid(1, 36);

/*
#ifdef Q_WS_X11
   uuid_t out;
   uuid_generate(out);
   return GuidToString((GUID*) out, format);
#else
   GUID out;
   ::CoCreateGuid(&out);
   return GuidToString(&out, format);
#endif
*/
}
/*
//-----------------------------------------------------  GuidToString -------------------------------------------------
QString CMoteurBase::GuidToString(GUID *guid  , const char *format / * ="%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X" * /)
{QString rString;
    rString.sprintf(format,
                        guid->Data1, guid->Data2, guid->Data3,
                        guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
                        guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
    return      rString;
}
*/

//-----------------------------------------------------  CalculeDiffAge_Num -------------------------------------------------
// ACTION: calcule l'age entre deux dates de début et de fin.
// ENTREE: QDate *pDebut: pointe sur une QDate de debut (exemple date de naissance)
//         QDate *pFin:   pointe sur une QDate de  fin (peut etre zero alors il sera pris la date en cours)
int CMoteurBase::CalculeDiffAge_Num(QDate *pDebut, QDate *pFin /*=0*/, int *mois_ret /*=0*/, int *jours_ret /*=0*/)
{
 char finMois[12]={31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
 int an   = 0;
 int mois = 0;
 int jour = 0;
 int dayYearDebut;
 int dayYearFin;

 bool bFinAlloue = FALSE;
 long lEtatDayYear;

 if (pDebut && pDebut->isValid ())
    {
     if (pFin==NULL)
        {pFin       = new QDate (QDate::currentDate ());
         bFinAlloue = TRUE;
        }//if

     if (pFin->isValid ())
        {
         //.........................................Partie calcul ..........................................
         //........Le jour de l'année .................
         dayYearDebut = pDebut->dayOfYear ();
         dayYearFin   = pFin->dayOfYear ();
         //................................ bisextiles and cie ..................................................
         //ATTENTION A L'ANNEE BISEXTILLE (sauf en l'an 1900, car les débuts de siecles ne sont pas bisextille sauf les débuts de millénaire
         //60eme jour => 29 Février
         if (pDebut->year()%4==0 && pDebut->year()%100 && pDebut->year()%1000    &&  dayYearDebut>60 )
             dayYearDebut--;
         if (pFin->year()%4==0   && pFin->year()%100   && pFin->year()%1000      &&  dayYearFin>60)
             dayYearFin--;

          //....................Position des jours l'un par rapport à l'autre ....................................
          if      (dayYearFin<dayYearDebut)     lEtatDayYear = -1;
          else if (dayYearFin>dayYearDebut)     lEtatDayYear =  1;
          else                                  lEtatDayYear =  0;

          //...................Calcul année (-1 si le jour de l'année en cours est <) .............................
          an = pFin->year() - pDebut->year() - (lEtatDayYear<0? 1 :0);

          if (lEtatDayYear!=0)
             {
              //.......................Calcul mois .....................................
              if (lEtatDayYear<0)
                  mois = 12 - pDebut->month() + pFin->month()   - (pFin->day()<pDebut->day()? 1 :0);
              else
                  mois = pFin->month()        - pDebut->month() - (pFin->day()<pDebut->day()? 1 :0);

              //...................... Calcul du jour ...................................
              if (pFin->day() < pDebut->day())
                  jour=(finMois[pFin->month()>1 ? pFin->month()-2 : 11] - pDebut->day()) + pFin->day();
              else
                  jour=pFin->day() - pDebut->day();
             } //if(lEtatDayYear!=0)
        } // endif (pFin->isValid ())
     }// endif (pDebut && pDebut->isValid ())
     if(bFinAlloue)  delete pFin;
     if (mois_ret)  *mois_ret  = mois;
     if (jours_ret) *jours_ret = jour;
     return an;
}



//-----------------------------------------------------  CalculeDiffAge -------------------------------------------------
// ACTION: calcule l'age entre deux dates de début et de fin.
// ENTREE: QDate *pDebut: pointe sur une QDate de debut (exemple date de naissance)
//         QDate *pFin:   pointe sur une QDate de  fin (peut etre zero alors il sera pris la date en cours)
//         bool bTexte:   TRUE   alors la date sera exprimée comme: 4 ans 6 mois 3 jours
//                        FALSE  alors la date sera exprimée comme un chiffre
//         int bAbrege:   2  et alors seules les années seront sorties sous la forme: "0" ou "35" etc ...
//                        1  et alors seules les années seront sorties sous la forme: "0" ou "35" etc ...
//                        0  et alors les sorties seront detaillées avec si age<3 avec les mois et jours:
QString CMoteurBase::CalculeDiffAge(QDate *pDebut, QDate *pFin/*=NULL*/, bool bTexte/*=TRUE*/, int bAbrege/*=1*/)
{
 int an   = 0;
 int mois = 0;
 int jour = 0;
 QString buffer;
 QString sRes("");


 an = CalculeDiffAge_Num(pDebut, pFin , &mois, &jour);
 //.............................................. Partie texte .........................................
 if (an)
    {
     if (bTexte)
     //buffer.sprintf("%d an%s ", an, an>1 ? "s" : "");
         buffer = QString::number(an) + TR(" an") + ((an>1) ? "s " : " ");
     else
         buffer.sprintf("%d ", an);
     sRes = buffer;
    } //if (an)
          //.................... si bAbrege==2 alors on ne sort que les années .......................................
 if (bAbrege==2)
    {if (an==0) sRes="0";
     return sRes;
    }
 if (!bAbrege || an < 3 /* || an<3*/) // age Inferieur à 3 ans et version detaillée
    {
     if (mois || !bTexte)
        {
         if (bTexte)
         //buffer.sprintf("%d mois ", mois);  // en fançais " mois " à déjà un s en [4] donc ne pas rajouter si plusieurs
            {QString ms = TR(" mois");  // va bien y avoir un dialecte où ça ne va pas marcher
             buffer     = QString::number(mois)+ ms + ((mois>1&&ms[4]!='s') ? "s " : " ");
            }
         else
             buffer.sprintf("%d ", mois);
         sRes+=buffer;
        } // if (mois || !bTexte)

     if (jour || !bTexte)
        {
         if (bTexte)
         //buffer.sprintf("%d jour%s ", jour, jour>1 ? "s" : "");
            buffer = QString::number(jour) + TR(" jour") + ((jour>1) ? "s " : " ");
         else
            buffer.sprintf("%d ", jour);
         sRes += buffer;
        } // if  (jour || !bTexte)
     }// if (!bAbrege || an<3) //Inferieure à 3 ans
 return sRes;
}


//------------------------------ GotoNextDebLigne -----------------------------------------
char *CMoteurBase::GotoNextDebLigne(const char* txt)
{char *pt  = (char*) txt;
 while (*pt)
    {if      ( pt [0]=='\\'&& pt [1] !=0)            (pt+=2);
     else if ( pt [0]=='\r'&& pt [1] =='\n')  return (pt+=2);
     else if ( pt [0]=='\n'&& pt [1] =='\r')  return (pt+=2);
     else if ( pt [0]=='\n'|| pt [0] =='\r')  return (pt+1);
     else pt++;
    }
 return pt;
}

//------------------------------ GotoEndOfLigne -----------------------------------------
char *CMoteurBase::GotoEndOfLigne(const char* txt)
{char *pt  = (char*) txt;
 while (*pt)
    {if      ( pt [0]=='\\'&& pt [1] !=0)            (pt+=2);
     else if ( pt [0]=='\r'&& pt [1] =='\n')  return pt;
     else if ( pt [0]=='\n'&& pt [1] =='\r')  return pt;
     else if ( pt [0]=='\n'|| pt [0] =='\r')  return pt;
     else pt++;
    }
 return pt;
}

//------------------------------ GotoNextSignifiant -----------------------------------------
char *CMoteurBase::GotoNextSignifiant(const char* txt)
{char *pt  = (char*) txt;
 while (*pt && (*pt==' ' || *pt=='\t'))
    {pt++;
    }
 return pt;
}

/*------------------------------ RTF_ToASCII ---------------------------------------*/
QString CMoteurBase::RTF_ToASCII(const char *ptIn, long len)
{//........ une petite QString de destination ....................
 QString stringDST;
 int fonttbl=0;
 //........ recuperer un pointeur sur la source ...................
 char *pt = (char*) ptIn;
 if (pt==0)             return 0;
 if (len==0) len = strlen(pt);
 if (len<=0)            return 0;
 char *end_rtf   = pt + len;

 /*............ aller à la premiere acolade ..............*/
 while(pt<end_rtf && *pt != '{') pt++;
 pt++;
 /*........scan et analyse du texte .......................*/
 while(pt<end_rtf)
   {int car = *pt;
    switch(car)
       {case '\r':
        case '\n':
        case '}':
             if (fonttbl) fonttbl--;
             pt++;
             break;
        case '{':
             if (fonttbl) fonttbl++;
             pt++;
             break;
        case  '\\':                // anti Slash
             if (pt[1]=='o' && (strncmp(pt+1,"object",6)==0))
                {pt = JumpObject(pt, end_rtf);
                }
             else if (strncmp(pt+1,"fonttbl",7)==0)
                {fonttbl++;
                 pt += 7;
                }
             else if (strncmp(pt+1,"fnil",4)==0     ||
                      strncmp(pt+1,"froman",6)==0   ||
                      strncmp(pt+1,"fswiss",6)==0   ||
                      strncmp(pt+1,"fmodern",7)==0  ||
                      strncmp(pt+1,"fscript",7)==0  ||
                      strncmp(pt+1,"fdecor",6)==0   ||
                      strncmp(pt+1,"ftech",5)==0    ||
                      strncmp(pt+1,"snext",5)==0    ||
                      strncmp(pt+1,"colortbl",8)==0 ||
                      strncmp(pt+1,"red",3)==0      ||
                      strncmp(pt+1,"green",5)==0    ||
                      strncmp(pt+1,"blue",4)==0
                     )
                {while(pt<end_rtf && *pt != ';') pt++;
                 pt++;
                }
             else if (strncmp(pt+1,"tab",3)==0    // et le tag 'tab' est rencontré
                     )
                {stringDST += "\t";
                 pt    += 4;
                 if (*pt==' ') pt++;
                }
             else if (pt[4] !='d'&&               // faut pas que ce soit 'pard'
                      strncmp(pt+1,"par",3)==0    // mais 'par' isolé
                     )
                {stringDST +="\r\n";
                 pt  += 4;
                 if (*pt==' ') pt++;
                }
             else if (pt[1]== '\'')     // apostrophe
                {char val;
                 if (pt[2]>'a'&&pt[2]<='f')      val  = (pt[2]-'W')*16;
                 else if (pt[2]>'A'&&pt[2]<='A') val  = (pt[2]-'W')*16;
                 else                            val  = (pt[2]-'0')*16;
                 if (pt[3]>'a'&&pt[3]<='f')      val += (pt[3]-'W');
                 else if (pt[2]>'A'&&pt[2]<='A') val += (pt[3]-'W');
                 else                            val += (pt[3]-'0');
                 stringDST += val;
                 pt  +=4;
                }
             else
                {pt++;
                 while  (pt<end_rtf && IsRtfControlCar(pt)) pt++;
                 if (*pt==' ') pt++;
                }
             break;
         default:
             if (fonttbl==0) stringDST += pt[0];
             pt++;
       }   /* endswitch */
   }
 return stringDST;
}

/*------------------------------ JumpObject ----------------------------------------*/
char* CMoteurBase::JumpObject(char *pt, char *end_rtf)
{long acco=1;
 while(pt < end_rtf && acco)
   {int car = *pt;
    switch(car)
       {case '}':
             acco--;
             pt++;
             break;
        case '{':
             acco++;
             pt++;
             break;
        default:
             pt++;
       } /* endswitch(car) */
   } /*endwhile(pt < end_rtf && acco) */
 return pt;
}

/*------------------------------ IsRtfControlCar --------------------------------------*/
int CMoteurBase::IsRtfControlCar(char *pt)
{if       (*pt >='a' && *pt<= 'z') return 1;
 else if  (*pt >='A' && *pt<= 'Z') return 1;
 else if  (*pt >='0' && *pt<= '9') return 1;
 return 0;
}

