Selaa lähdekoodia

TMP pour tests

olivier.massot 7 vuotta sitten
vanhempi
commit
80786f6822
1 muutettua tiedostoa jossa 198 lisäystä ja 138 poistoa
  1. 198 138
      ctrl2analytique.py

+ 198 - 138
ctrl2analytique.py

@@ -4,7 +4,7 @@
 
 
 
 
     **IMPORTANT**: pour lancer le script sans interaction avec l'utilisateur
     **IMPORTANT**: pour lancer le script sans interaction avec l'utilisateur
-    (par ex, dans le cas d'une tâche planifiée), appeller le script avec l'option '-n'.
+    (par ex, dans le cas d'une tâche planifiée), appeller le script avec l'option '--auto'.
 
 
     @author: olivier.massot, févr. 2018
     @author: olivier.massot, févr. 2018
 '''
 '''
@@ -15,7 +15,6 @@ import sys
 from path import Path  # @UnusedImport
 from path import Path  # @UnusedImport
 
 
 from core import logconf
 from core import logconf
-from core.db import AccessSqlHelper
 from core.pde import ControlesDb, AnalytiqueDb, mk_workdir, CommunDb, Affaire, \
 from core.pde import ControlesDb, AnalytiqueDb, mk_workdir, CommunDb, Affaire, \
     Interv, Tarification
     Interv, Tarification
 from core.sqlformatter import SqlFormatter
 from core.sqlformatter import SqlFormatter
@@ -28,11 +27,11 @@ logconf.start("ctrl2analytique", logging.DEBUG)
 # > Lancer le script /resources/test_ctrl2analytique.py pour reinitialiser les données de la base de test
 # > Lancer le script /resources/test_ctrl2analytique.py pour reinitialiser les données de la base de test
 ##-----------------------------------------------
 ##-----------------------------------------------
 
 
-# ControlesDb._path = Path(r"\\h2o\local\4-transversal\BDD\mdb_test\cg67Parc_data.mdb")
-# AnalytiqueDb._path = Path(r"\\h2o\local\4-transversal\BDD\mdb_test\Db_analytique.mdb")
-# CommunDb._path = Path(r"\\h2o\local\4-transversal\BDD\mdb_test\Commun_Data.mdb")
-# logger.handlers = [h for h in logger.handlers if (type(h) == logging.StreamHandler)]
-# logger.warning("<<<<<<<<<<<<<<   Mode TEST   >>>>>>>>>>>>>>>>>")
+ControlesDb._path = Path(r"\\h2o\local\4-transversal\BDD\mdb_test\cg67Parc_data.mdb")
+AnalytiqueDb._path = Path(r"\\h2o\local\4-transversal\BDD\mdb_test\Db_analytique.mdb")
+CommunDb._path = Path(r"\\h2o\local\4-transversal\BDD\mdb_test\Commun_Data.mdb")
+logger.handlers = [h for h in logger.handlers if (type(h) == logging.StreamHandler)]
+logger.warning("<<<<<<<<<<<<<<   Mode TEST   >>>>>>>>>>>>>>>>>")
 
 
 ##-----------------------------------------------
 ##-----------------------------------------------
 
 
@@ -42,7 +41,7 @@ def main():
 
 
     Sql = SqlFormatter()
     Sql = SqlFormatter()
 
 
-    no_prompt = ("-n" in sys.argv)
+    no_prompt = ("--auto" in sys.argv)
     if no_prompt:
     if no_prompt:
         logger.info("> Lancé en mode automatique (sans interruption)")
         logger.info("> Lancé en mode automatique (sans interruption)")
 
 
@@ -55,17 +54,6 @@ def main():
     # Connexion à CommunDb
     # Connexion à CommunDb
     commun_db = CommunDb(autocommit=False)
     commun_db = CommunDb(autocommit=False)
 
 
-    # Créé le répertoire de travail
-    workdir = mk_workdir("ctrl2analytique")
-    affaires_file = workdir / "affaires.csv"
-    intervs_file = workdir / "intervs.csv"
-
-    # > Supprime les fichiers d'import s'il existent
-    for file in (affaires_file, intervs_file):
-        if file.exists():
-            logger.debug("Supprime le fichier %s", file)
-            file.remove()
-
     # date zéro pour Access
     # date zéro pour Access
     date_zero = datetime(1899, 12, 30, 0, 0, 0)
     date_zero = datetime(1899, 12, 30, 0, 0, 0)
 
 
@@ -101,17 +89,16 @@ def main():
 
 
 
 
 
 
-
     # ##########   IMPORT DES AFFAIRES    ##########
     # ##########   IMPORT DES AFFAIRES    ##########
 
 
-    # Parcourt les chantiers de contrôle pour lesquels aucune affaire n'a été créée, et les ajoute au fichier affaire.csv
+    # Parcourt les chantiers de contrôle pour lesquels aucune affaire n'a été créée
 
 
-    compteur = 0
     sql = """ SELECT tblCommandes.lngChantierId, tblCommandes.bytCommandeId, tblChantiers.strSubdivisionId, tblChantiers.strCollectiviteId as ChantierCollectiviteId, tblChantiers.strLocChantier,
     sql = """ SELECT tblCommandes.lngChantierId, tblCommandes.bytCommandeId, tblChantiers.strSubdivisionId, tblChantiers.strCollectiviteId as ChantierCollectiviteId, tblChantiers.strLocChantier,
               tblChantiers.strEntrepriseId, tblCommandes.strCollectiviteId as CommandeCollectiviteId, tblCommandes.dtmCommande, tblCommandes.strRefCommande, tblCommandes.blnMarche, tblCommandes.dblMtMarche, tblCommandes.strdevis
               tblChantiers.strEntrepriseId, tblCommandes.strCollectiviteId as CommandeCollectiviteId, tblCommandes.dtmCommande, tblCommandes.strRefCommande, tblCommandes.blnMarche, tblCommandes.dblMtMarche, tblCommandes.strdevis
               FROM tblChantiers INNER JOIN tblCommandes ON tblChantiers.lngChantierId = tblCommandes.lngChantierId
               FROM tblChantiers INNER JOIN tblCommandes ON tblChantiers.lngChantierId = tblCommandes.lngChantierId
               WHERE (((tblCommandes.sngAffaireIdMos) Is Null Or (tblCommandes.sngAffaireIdMos)=0))
               WHERE (((tblCommandes.sngAffaireIdMos) Is Null Or (tblCommandes.sngAffaireIdMos)=0))
               """
               """
+    affaires = []
 
 
     for data in controles_db.read(sql):
     for data in controles_db.read(sql):
 
 
@@ -138,23 +125,18 @@ def main():
         affaire.lngChantierId = data.lngChantierId
         affaire.lngChantierId = data.lngChantierId
         affaire.bytCommandeId = data.bytCommandeId
         affaire.bytCommandeId = data.bytCommandeId
 
 
-        # Créé la ligne dans le fichier affaires.csv
-        affaire.dump_to_csv(affaires_file)
+        affaires.append(affaire)
 
 
-        compteur += 1
-
-    logger.info("> {} affaires ajoutées au fichier".format(compteur))
+    logger.info("> {} affaires".format(len(affaires)))
 
 
 
 
 
 
 
 
     # ########## IMPORT DES INTERVENTIONS DE COMPACTAGE ##########
     # ########## IMPORT DES INTERVENTIONS DE COMPACTAGE ##########
 
 
-    # Importe les interventions de contrôle du compactage dans le fichier intervs.csv
 
 
-    def engin_existe(strEnginId):
-        """ retourne True si le code de l'engin existe dans la table tbl_Engin """
-        return analytique_db.exists(Sql.format("SELECT strEnginId FROM tbl_Engin WHERE strEnginId={:text}", strEnginId))
+
+    # Importe les interventions de contrôle du compactage
 
 
     def get_periode_validite(date_interv):
     def get_periode_validite(date_interv):
         """ retourne la préiode comptable correspondant à la date de l'intervention """
         """ retourne la préiode comptable correspondant à la date de l'intervention """
@@ -163,9 +145,23 @@ def main():
         sql = Sql.format("""SELECT intPeriodeValiditeId FROM tblTarifValidite
         sql = Sql.format("""SELECT intPeriodeValiditeId FROM tblTarifValidite
                             WHERE [dtmValiditeDebut] <= {date_interv:date} AND [dtmValiditeFin] > {date_interv:date} AND [bytClasseTarifId]=1
                             WHERE [dtmValiditeDebut] <= {date_interv:date} AND [dtmValiditeFin] > {date_interv:date} AND [bytClasseTarifId]=1
                         """, date_interv=date_interv)
                         """, date_interv=date_interv)
-        return commun_db.first(sql).intPeriodeValiditeId
+        periode = commun_db.first(sql)
+        return periode.intPeriodeValiditeId if periode else None
+
+    def get_type_compactage_interv(observation):
+        """ retourne le sous-type d'intervention à partir du commentaire associé """
+        if "ASSAINISEMENT" or "ASSAINISEMENT" in observation:
+            return "CC3"
+        elif "CABLE" in observation:
+            return "CC1"
+        elif "A.E.P" in observation:
+            return "CC2"
+        elif "GAZ" in observation:
+            return "CC4"
+        else:
+            return "CC3"
 
 
-    compteur = 0
+    interventions_cc = []
 
 
     sql = """SELECT tblCompactageIntervs.lngChantierId, tblCompactageIntervs.bytCommandeId, tblCompactageIntervs.bytIntervId, tblCompactageIntervs.strEquipeId,
     sql = """SELECT tblCompactageIntervs.lngChantierId, tblCompactageIntervs.bytCommandeId, tblCompactageIntervs.bytIntervId, tblCompactageIntervs.strEquipeId,
                 tblCompactageEngins.strEnginId, tblCompactageIntervs.lngRapportId, tblCompactageBases.memTravaux, tblCompactageResultats.dtmEssai, tblCompactageResultats.dtmDuree,
                 tblCompactageEngins.strEnginId, tblCompactageIntervs.lngRapportId, tblCompactageBases.memTravaux, tblCompactageResultats.dtmEssai, tblCompactageResultats.dtmDuree,
@@ -183,18 +179,6 @@ def main():
             WHERE (((tblCompactageIntervs.sngIntervIdMos)=0 Or (tblCompactageIntervs.sngIntervIdMos) Is Null))
             WHERE (((tblCompactageIntervs.sngIntervIdMos)=0 Or (tblCompactageIntervs.sngIntervIdMos) Is Null))
           """
           """
 
 
-    def get_type_compactage_interv(observation):
-        """ retourne le sous-type d'intervention à partir du commentaire associé """
-        if "ASSAINISEMENT" or "ASSAINISEMENT" in observation:
-            return "CC3"
-        elif "CABLE" in observation:
-            return "CC1"
-        elif "A.E.P" in observation:
-            return "CC2"
-        elif "GAZ" in observation:
-            return "CC4"
-        else:
-            return "CC3"
 
 
     for data in controles_db.read(sql):
     for data in controles_db.read(sql):
         interv = Interv()
         interv = Interv()
@@ -231,20 +215,17 @@ def main():
         interv.bytCommandeId = data.bytCommandeId
         interv.bytCommandeId = data.bytCommandeId
         interv.bytIntervId = data.bytIntervId
         interv.bytIntervId = data.bytIntervId
 
 
-        # Créé la ligne dans le fichier intervs.csv
-        interv.dump_to_csv(intervs_file)
+        interventions_cc.append(interv)
 
 
-        compteur += 1
-
-    logger.info("> {} interventions Compactage ajoutées au fichier".format(compteur))
+    logger.info("> {} interventions Compactage".format(len(interventions_cc)))
 
 
 
 
 
 
     # ########## IMPORT DES INTERVENTIONS D'ETANCHEITE ##########
     # ########## IMPORT DES INTERVENTIONS D'ETANCHEITE ##########
 
 
-    # Importe les interventions de contrôle d'étanchéité dans le fichier intervs.csv
+    # Importe les interventions de contrôle d'étanchéité
 
 
-    compteur = 0
+    interventions_ce = []
 
 
     sql = """SELECT tblEtancheiteIntervs.lngChantierId, tblEtancheiteIntervs.bytCommandeId, tblEtancheiteIntervs.bytIntervId, tblEtancheiteIntervs.strEquipeId,
     sql = """SELECT tblEtancheiteIntervs.lngChantierId, tblEtancheiteIntervs.bytCommandeId, tblEtancheiteIntervs.bytIntervId, tblEtancheiteIntervs.strEquipeId,
                 tblEtancheiteIntervs.lngRapportId, tblEtancheitePartChantiers.bytTypeEssai, tblMateriaux.strMateriauId, tblMateriaux.strMatériau,
                 tblEtancheiteIntervs.lngRapportId, tblEtancheitePartChantiers.bytTypeEssai, tblMateriaux.strMateriauId, tblMateriaux.strMatériau,
@@ -301,21 +282,18 @@ def main():
         interv.bytCommandeId = data.bytCommandeId
         interv.bytCommandeId = data.bytCommandeId
         interv.bytIntervId = data.bytIntervId
         interv.bytIntervId = data.bytIntervId
 
 
-        # Créé la ligne dans le fichier intervs.csv
-        interv.dump_to_csv(intervs_file)
-
-        compteur += 1
+        interventions_ce.append(interv)
 
 
-    logger.info("> {} interventions Etanchéité ajoutées au fichier".format(compteur))
+    logger.info("> {} interventions Etanchéité".format(len(interventions_ce)))
 
 
 
 
 
 
     # ########## IMPORT DES INTERVENTIONS D'INSPECTION VIDEO ##########
     # ########## IMPORT DES INTERVENTIONS D'INSPECTION VIDEO ##########
 
 
 
 
-    # Importe les interventions d'inspection vidéo dans le fichier intervs.csv
+    # Importe les interventions d'inspection vidéo
 
 
-    compteur = 0
+    interventions_ci = []
 
 
     sql = """SELECT tblVideoIntervs.lngChantierId, tblVideoIntervs.bytCommandeId, tblVideoIntervs.bytIntervId, tblVideoIntervs.strEquipeId,
     sql = """SELECT tblVideoIntervs.lngChantierId, tblVideoIntervs.bytCommandeId, tblVideoIntervs.bytIntervId, tblVideoIntervs.strEquipeId,
             tblVideoEngins.strEnginId, tblVideoIntervs.lngRapportId, First(tblso_rate_Analyse.MateriauCourt) AS strmateriau, tblVideoIntervs.lngTroncon,
             tblVideoEngins.strEnginId, tblVideoIntervs.lngRapportId, First(tblso_rate_Analyse.MateriauCourt) AS strmateriau, tblVideoIntervs.lngTroncon,
@@ -365,130 +343,215 @@ def main():
         interv.bytCommandeId = data.bytCommandeId
         interv.bytCommandeId = data.bytCommandeId
         interv.bytIntervId = data.bytIntervId
         interv.bytIntervId = data.bytIntervId
 
 
-        # Créé la ligne dans le fichier intervs.csv
-        interv.dump_to_csv(intervs_file)
-
-        compteur += 1
-
-    logger.info("> {} interventions ITV ajoutées au fichier".format(compteur))
-
-
-    logging.info("Les données à importer ont été ajoutées aux fichiers '{}' et '{}'".format(affaires_file, intervs_file))
-    logging.info("Ces fichiers sont au format CSV (séparateur: tabulation)")
-
+        interventions_ci.append(interv)
 
 
+    logger.info("> {} interventions ITV".format(len(interventions_ci)))
 
 
 
 
+    interventions = interventions_cc + interventions_ce + interventions_ci
 
 
     # ########## CONTROLE ET CORRECTION DES DONNEES ##########
     # ########## CONTROLE ET CORRECTION DES DONNEES ##########
 
 
     errors = -1
     errors = -1
 
 
     while errors:
     while errors:
-        errors = []
+        errors = 0
+        to_remove = []
 
 
-        for affaire in Affaire.load_csv(affaires_file):
+        for affaire in affaires:
 
 
             prefix = "Affaire {}: ".format(affaire.strLiaisonControle)
             prefix = "Affaire {}: ".format(affaire.strLiaisonControle)
+
+            logger.info("Contrôle de %s: %s", prefix, affaire)
+
             if not affaire.strMOId:
             if not affaire.strMOId:
-                errors.append(prefix + "MO manquant")
+                logging.error(prefix + "MO manquant")
+                errors += 1
+                if not no_prompt:
+                    affaire.strMOId = input("Saisir la nouvelle valeur:")
             else:
             else:
                 if not commun_db.exists(Sql.format("SELECT [lngTiersId] FROM tblTiers WHERE [lngTiersId]={}", affaire.strMOId)):
                 if not commun_db.exists(Sql.format("SELECT [lngTiersId] FROM tblTiers WHERE [lngTiersId]={}", affaire.strMOId)):
-                    errors.append(prefix + "Le MO {} n'existe pas dans tblTiers".format(affaire.strMOId))
+                    logging.error(prefix + "Le MO %s n'existe pas dans tblTiers", affaire.strMOId)
+                    errors += 1
+                    if not no_prompt:
+                        affaire.strMOId = input("Saisir la nouvelle valeur:")
+
             if not affaire.strMOeId:
             if not affaire.strMOeId:
-                errors.append(prefix + "MOe manquant")
+                logging.error(prefix + "MOe manquant")
+                errors += 1
+                if not no_prompt:
+                    affaire.strMOeId = input("Saisir la nouvelle valeur:")
             else:
             else:
                 if not commun_db.exists(Sql.format("SELECT [lngTiersId] FROM tblTiers WHERE [lngTiersId]={}", affaire.strMOeId)):
                 if not commun_db.exists(Sql.format("SELECT [lngTiersId] FROM tblTiers WHERE [lngTiersId]={}", affaire.strMOeId)):
-                    errors.append(prefix + "Le MOe {} n'existe pas dans tblTiers".format(affaire.strMOeId))
+                    logging.error(prefix + "Le MOe %s n'existe pas dans tblTiers", affaire.strMOeId)
+                    errors += 1
+                    if not no_prompt:
+                        affaire.strMOeId = input("Saisir la nouvelle valeur:")
+
             if not affaire.strEntrepriseId:
             if not affaire.strEntrepriseId:
-                errors.append(prefix + "Entreprise manquante")
+                logging.error(prefix + "Entreprise manquante")
+                errors += 1
+                if not no_prompt:
+                    affaire.strEntrepriseId = input("Saisir la nouvelle valeur:")
             else:
             else:
                 if not commun_db.exists(Sql.format("SELECT [lngTiersId] FROM tblTiers WHERE [lngTiersId]={}", affaire.strEntrepriseId)):
                 if not commun_db.exists(Sql.format("SELECT [lngTiersId] FROM tblTiers WHERE [lngTiersId]={}", affaire.strEntrepriseId)):
-                    errors.append(prefix + "L'entreprise {} n'existe pas dans tblTiers".format(affaire.strEntrepriseId))
+                    logging.error(prefix + "L'entreprise %s n'existe pas dans tblTiers", affaire.strEntrepriseId)
+                    errors += 1
+                    if not no_prompt:
+                        affaire.strEntrepriseId = input("Saisir la nouvelle valeur:")
+
             if not affaire.strCommneId:
             if not affaire.strCommneId:
-                errors.append(prefix + "Commune manquante")
+                logging.error(prefix + "Commune manquante")
+                errors += 1
+                if not no_prompt:
+                    affaire.strCommneId = input("Saisir la nouvelle valeur:")
             else:
             else:
                 if not commun_db.exists(Sql.format("SELECT [lngTiersId] FROM tblTiers WHERE [lngTiersId]={}", affaire.strCommneId)):
                 if not commun_db.exists(Sql.format("SELECT [lngTiersId] FROM tblTiers WHERE [lngTiersId]={}", affaire.strCommneId)):
-                    errors.append(prefix + "La commune {} n'existe pas dans tblTiers".format(affaire.strCommneId))
+                    logging.error(prefix + "La commune %s n'existe pas dans tblTiers", affaire.strCommneId)
+                    errors += 1
+                    if not no_prompt:
+                        affaire.strCommneId = input("Saisir la nouvelle valeur:")
+
             if not affaire.strTypeId:
             if not affaire.strTypeId:
-                errors.append(prefix + "Type d'affaire manquant")
+                logging.error(prefix + "Type d'affaire manquant")
+                errors += 1
+                if not no_prompt:
+                    affaire.strTypeId = input("Saisir la nouvelle valeur:")
+
             if not affaire.dtmCommande:
             if not affaire.dtmCommande:
-                errors.append(prefix + "Date de commande manquante")
+                logging.error(prefix + "Date de commande manquante")
+                errors += 1
+                if not no_prompt:
+                    affaire.strTypeId = datetime.strptime(input("Saisir la nouvelle valeur (au format jj/mm/aaaa):"), "%d/%m/%Y")
+
             if affaire.blnMarche == True:
             if affaire.blnMarche == True:
                 if not affaire.intDevisId:
                 if not affaire.intDevisId:
-                    errors.append(prefix + "Numéro de devis manquant")
+                    logging.error(prefix + "Numéro de devis manquant")
+                    errors += 1
+                    if not no_prompt:
+                        affaire.intDevisId = input("Saisir la nouvelle valeur:")
 
 
-            if analytique_db.exists(Sql.format("SELECT dblAffaireId FROM tbl_Affaires WHERE [strLiaisonControle]='{}'", affaire.strLiaisonControle)):
-                errors.append(prefix + "Une affaire portant ce code existe déjà: {}".format(affaire.strLiaisonControle))
+            if analytique_db.exists(Sql.format("SELECT dblAffaireId FROM tbl_Affaires WHERE [strLiaisonControle]={:text}", affaire.strLiaisonControle)):
+                logging.error(prefix + "Une affaire portant ce code existe déjà: %s", affaire.strLiaisonControle)
+                errors += 1
+                if not no_prompt:
+                    if input("Tapez 'n' pour retirer cette affaire de la liste des affaires à créer:") == 'n':
+                        to_remove.append(affaire.strLiaisonControle)
 
 
-        for interv in Interv.load_csv(intervs_file):
+        if to_remove:
+            affaires = [affaire for affaire in affaires if not affaire.strLiaisonControle in to_remove]
+
+
+        for interv in interventions:
 
 
             prefix = "Intervention {}: ".format(interv.strTest)
             prefix = "Intervention {}: ".format(interv.strTest)
+            logger.info("Contrôle de %s: %s", prefix, interv)
+
             if not interv.strEquipeId:
             if not interv.strEquipeId:
-                errors.append(prefix + "Equipe manquante")
+                logging.error(prefix + "Equipe manquante")
+                errors += 1
+                if not no_prompt:
+                    interv.strEquipeId = input("Saisir la nouvelle valeur:")
+            else:
+                if not analytique_db.exists(Sql.format("SELECT [strEquipesId] FROM tbl_Equipe WHERE [strEquipesId]={:text}", interv.strEquipeId)):
+                    logging.error(prefix + "L'equipe %s n'existe pas dans tbl_Equipe", interv.strEquipeId)
+                    errors += 1
+                    if not no_prompt:
+                        interv.strEquipeId = input("Saisir la nouvelle valeur:")
+
             if not interv.strEnginId:
             if not interv.strEnginId:
-                errors.append(prefix + "Engin manquant")
+                logging.error(prefix + "Engin manquant")
+                errors += 1
+                if not no_prompt:
+                    interv.strEnginId = input("Saisir la nouvelle valeur:")
+            else:
+                if not analytique_db.exists(Sql.format("SELECT [strEnginId] FROM tbl_Engin WHERE [strEnginId]={:text}", interv.strEnginId)):
+                    logging.error(prefix + "L'engin %s n'existe pas dans tbl_Engin", interv.strEnginId)
+                    errors += 1
+                    if not no_prompt:
+                        interv.strEnginId = input("Saisir la nouvelle valeur:")
+
             if not interv.strRapportId:
             if not interv.strRapportId:
-                errors.append(prefix + "Rapport manquant")
+                logging.error(prefix + "Rapport manquant")
+                errors += 1
+                if not no_prompt:
+                    interv.strRapportId = input("Saisir la nouvelle valeur:")
+
             if not interv.strCatégorieInterventionId:
             if not interv.strCatégorieInterventionId:
-                errors.append(prefix + "Catégorie de l'intervention manquante")
+                logging.error(prefix + "Catégorie de l'intervention manquante")
+                errors += 1
+                if not no_prompt:
+                    interv.strCatégorieInterventionId = input("Saisir la nouvelle valeur:")
+            else:
+                if not analytique_db.exists(Sql.format("SELECT [strCategorieInterventioinId] FROM tbl_CategorieIntervention WHERE [strCategorieInterventioinId]={:text}", interv.strCatégorieInterventionId)):
+                    logging.error(prefix + "La catégorie d'intervention %s n'existe pas dans tbl_CategorieIntervention", interv.strCatégorieInterventionId)
+                    errors += 1
+                    if not no_prompt:
+                        interv.strCatégorieInterventionId = input("Saisir la nouvelle valeur:")
+
             if not interv.strTypeInterventionId:
             if not interv.strTypeInterventionId:
-                errors.append(prefix + "Type d'intervention manquant")
+                logging.error(prefix + "Type d'intervention manquant")
+                errors += 1
+                if not no_prompt:
+                    interv.strTypeInterventionId = input("Saisir la nouvelle valeur:")
+            else:
+                if not analytique_db.exists(Sql.format("SELECT [strTypeInterventionId] FROM tbl_TypeIntervention WHERE [strTypeInterventionId]={:text}", interv.strTypeInterventionId)):
+                    logging.error(prefix + "Le type d'intervention %s n'existe pas dans tbl_TypeIntervention", interv.strTypeInterventionId)
+                    errors += 1
+                    if not no_prompt:
+                        interv.strTypeInterventionId = input("Saisir la nouvelle valeur:")
+
             if not interv.dblquantite:
             if not interv.dblquantite:
-                errors.append(prefix + "Quantité nulle")
+                logging.error(prefix + "Quantité nulle")
+                errors += 1
+                if not no_prompt:
+                    interv.dblquantite = input("Saisir la nouvelle valeur:")
+
             if not interv.strunite:
             if not interv.strunite:
-                errors.append(prefix + "Unité non renseignée")
+                logging.error(prefix + "Unité non renseignée")
+                errors += 1
+                if not no_prompt:
+                    interv.strunite = input("Saisir la nouvelle valeur:")
+            else:
+                if not commun_db.exists(Sql.format("SELECT [strUniteCourt] FROM tblUnite WHERE [strUniteCourt]={:text}", interv.strunite)):
+                    logging.error(prefix + "L'unité %s n'existe pas dans tblUnite", interv.strunite)
+                    errors += 1
+                    if not no_prompt:
+                        interv.strunite = input("Saisir la nouvelle valeur:")
+
             if not interv.dtmIntervention:
             if not interv.dtmIntervention:
-                errors.append(prefix + "Erreur : date d'intervention")
-            if not interv.dtmDureeIntervention or interv.dtmDureeIntervention == date_zero:
-                errors.append(prefix + "Durée d'intervention nulle")
-            if not interv.strunite:
-                errors.append(prefix + "Unité non renseignée")
+                logging.error(prefix + "Erreur : date d'intervention")
+                errors += 1
+                if not no_prompt:
+                    interv.dtmIntervention = datetime.strptime(input("Saisir la nouvelle valeur (au format jj/mm/aaaa):"), "%d/%m/%Y")
 
 
-            if not engin_existe(interv.strEnginId):
-                errors.append(prefix + "l'engin {} n'existe pas".format(interv.strEnginId))
+            if not interv.dtmDureeIntervention or interv.dtmDureeIntervention == date_zero:
+                logging.error(prefix + "Durée d'intervention nulle")
+                errors += 1
+                if not no_prompt:
+                    try:
+                        reponse = input("Saisir la nouvelle valeur (en heures):")
+                        interv.dtmDureeIntervention = date_zero + timedelta(hours=int(reponse))
+                    except ValueError:
+                        logger.error("Valeur corrigée invalide ('%s')", reponse)
 
 
         # *** 6- Interruption pour corection manuelle des données (si nécessaire)
         # *** 6- Interruption pour corection manuelle des données (si nécessaire)
         if errors:
         if errors:
-            logging.error("<!> Des erreurs ont été détectées dans les données à importer. <!>")
-            for msg in errors:
-                logging.error(msg)
+            logging.error("<!> %s erreurs ont été détectées dans les données à importer. <!>", errors)
             if no_prompt:
             if no_prompt:
                 logger.info("# Annulation de l'import")
                 logger.info("# Annulation de l'import")
                 sys.exit(1)
                 sys.exit(1)
         else:
         else:
             logging.info("Aucune erreur n'a été détectée dans les données.")
             logging.info("Aucune erreur n'a été détectée dans les données.")
-            if no_prompt:
-                break
-
-        # Même si aucune erreur n'a été détectée, on demande un controle visuel.
-        prompt = ""
-        while prompt != "v":
-            logger.info(">> Veuillez contrôler les données, puis taper: \n\t'v' pour continuer\n\t'f' pour forcer le traitement à se poursuivre\n\t'q' pour annuler")
-            try:
-                from core import tsv_editor
-                tsv_editor.exec_(affaires_file.abspath())
-                tsv_editor.exec_(intervs_file.abspath())
-            except:
-                logger.error("Erreur à l'ouverture du fichier %s", affaires_file)
-                logger.error("Erreur à l'ouverture du fichier %s", intervs_file)
-
-            prompt = input("")
-            if prompt == "f":
-                break
-            if prompt == "q":
-                logger.info("# Annulation de l'import")
-                sys.exit(1)
+            if not no_prompt:
+                input("Presser Entrée pour continuer...")
+
 
 
     # ########## MISE A JOUR DE LA BASE DE DONNEES ANALYTIQUE ##########
     # ########## MISE A JOUR DE LA BASE DE DONNEES ANALYTIQUE ##########
 
 
-    # On charge en mémoire les affaires et les interventions
     logger.info("# Mise à jour de la base Analytique")
     logger.info("# Mise à jour de la base Analytique")
     logger.info("> NB: Les modifications ne seront appliquées à la base que si toutes les opérations se déroulent normalement.")
     logger.info("> NB: Les modifications ne seront appliquées à la base que si toutes les opérations se déroulent normalement.")
 
 
-    affaires = list(Affaire.load_csv(affaires_file))
-    intervs = list(Interv.load_csv(intervs_file))
-
     # On insère les affaires, interventions dans Analytique, et on génère la ou les lignes de tarification associées
     # On insère les affaires, interventions dans Analytique, et on génère la ou les lignes de tarification associées
 
 
     for affaire in affaires:
     for affaire in affaires:
@@ -509,7 +572,7 @@ def main():
 
 
 
 
     # On insère les interventions dans tbl_Intervention
     # On insère les interventions dans tbl_Intervention
-    for interv in intervs:
+    for interv in interventions:
 
 
         affaire = analytique_db.first(Sql.format("SELECT TOP 1 DblAffaireId FROM tbl_Affaires WHERE [strLiaisonControle]='{}'", interv.LienAff))
         affaire = analytique_db.first(Sql.format("SELECT TOP 1 DblAffaireId FROM tbl_Affaires WHERE [strLiaisonControle]='{}'", interv.LienAff))
         if not affaire:
         if not affaire:
@@ -542,14 +605,14 @@ def main():
 
 
     # > On va créer une ligne de tarification pour chaque groupe d'interventions
     # > On va créer une ligne de tarification pour chaque groupe d'interventions
     # > partageant le même lngRapportid et strArticleId (cad le même engin)
     # > partageant le même lngRapportid et strArticleId (cad le même engin)
-    for strRapportId, strArticleId in set([(interv.strRapportId, interv.strArticleId) for interv in intervs]):
+    for strRapportId, strArticleId in set([(interv.strRapportId, interv.strArticleId) for interv in interventions]):
 
 
         tarif = Tarification()
         tarif = Tarification()
-        tarif.intervs = [interv for interv in intervs if interv.strRapportId == strRapportId and interv.strArticleId == strArticleId]
+        tarif.intervs = [interv for interv in interventions if interv.strRapportId == strRapportId and interv.strArticleId == strArticleId]
 
 
         # recupere le prix unitaire de l'engin
         # recupere le prix unitaire de l'engin
         tarif_engin = commun_db.first(Sql.format("""SELECT dblPU FROM tblTarif WHERE [strArticleId]={:text} AND [intPeriodeValiditeId]={}
         tarif_engin = commun_db.first(Sql.format("""SELECT dblPU FROM tblTarif WHERE [strArticleId]={:text} AND [intPeriodeValiditeId]={}
-                                                 """, strArticleId, get_periode_validite(intervs[0].dtmIntervention)))
+                                                 """, strArticleId, get_periode_validite(interventions[0].dtmIntervention)))
         if not tarif_engin:
         if not tarif_engin:
             logger.error("Aucun tarif trouvé dans tblTarif pour l'article {}, periode {}".format(strArticleId, tarif.intervs[0].intPeriode))
             logger.error("Aucun tarif trouvé dans tblTarif pour l'article {}, periode {}".format(strArticleId, tarif.intervs[0].intPeriode))
         prix_unitaire = tarif_engin.dblPU
         prix_unitaire = tarif_engin.dblPU
@@ -593,7 +656,7 @@ def main():
                 """, DblAffaireId=dblAffaireId, lngChantierId=affaire.lngChantierId, bytCommandeId=affaire.bytCommandeId)
                 """, DblAffaireId=dblAffaireId, lngChantierId=affaire.lngChantierId, bytCommandeId=affaire.bytCommandeId)
         controles_db.execute(sql)
         controles_db.execute(sql)
 
 
-    for interv in intervs:
+    for interv in interventions:
         if interv.strCatégorieInterventionId == "CC":
         if interv.strCatégorieInterventionId == "CC":
             tbl = "tblCompactageIntervs"
             tbl = "tblCompactageIntervs"
         elif interv.strCatégorieInterventionId == "CE":
         elif interv.strCatégorieInterventionId == "CE":
@@ -617,6 +680,7 @@ def main():
     # On commit les modifications
     # On commit les modifications
     logger.info("Commit des modifications...")
     logger.info("Commit des modifications...")
     analytique_db.commit()
     analytique_db.commit()
+    controles_db.commit()
 
 
 
 
 
 
@@ -656,12 +720,8 @@ def main():
     analytique_db.commit()
     analytique_db.commit()
 
 
 
 
-
-    logger.info("# Import terminé")
-
-
 if __name__ == "__main__":
 if __name__ == "__main__":
 
 
     main()
     main()
 
 
-    logger.info("-- Fin --")
+    logger.info("-- Fin --")