浏览代码

NEW ctrl2analytique: Script se termine sans erreurs particulière
[résultats encore partiellement vérifiés]

olivier.massot 7 年之前
父节点
当前提交
41f54aa785
共有 1 个文件被更改,包括 151 次插入109 次删除
  1. 151 109
      ctrl2analytique.py

+ 151 - 109
ctrl2analytique.py

@@ -62,8 +62,9 @@ class Affaire(Model):
     """ Modèle de données d'une affaire Analytique """
     _FIELDS = ["strLiaisonControle", "strMOeId", "strCommneId", "strLieux",
                "strEntrepriseId", "strMOId", "dtmCommande", "Ref", "blnMarche",
-               "dblMarche", "intDevisId", "strCT", "strTypeId",
-               "intCoefFG", "strSituation"]
+               "dblMarche", "intTypeContrat", "strCT", "strTypeId",
+               "intCoefFG", "strSituation",
+               "lngChantierId", "bytCommandeId"]
 
 def get_type_id(lngChantierId, bytCommandeId):
     """ Recupère le type de chantier.
@@ -123,19 +124,19 @@ for data in controles_db.read(sql):
     affaire.Ref = data.strRefCommande
     affaire.blnMarche = data.blnMarche
     affaire.dblMarche = data.dblMtMarche
-    affaire.intDevisId = data.strdevis
+    affaire.intTypeContrat = 1
     affaire.strCT = '1'
     affaire.strTypeId = get_type_id(data.lngChantierId, data.bytCommandeId)
     affaire.intCoefFG = get_coeff_k(data.lngChantierId)
     affaire.strSituation = "En cours"
 
-    # Créé la ligne dans le fichier affaires.csv
-    affaire.dump(affaires_file)
-
     # pour garder le lien avec la donnée d'origine:
     affaire.lngChantierId = data.lngChantierId
     affaire.bytCommandeId = data.bytCommandeId
 
+    # Créé la ligne dans le fichier affaires.csv
+    affaire.dump(affaires_file)
+
     compteur += 1
 
 logger.info("> {} affaires ajoutées à {}".format(compteur, affaires_file))
@@ -150,11 +151,13 @@ logger.info("> {} affaires ajoutées à {}".format(compteur, affaires_file))
 class Interv(Model):
     """ Modèle de données d'une intervention de contrôle réseaux """
     _FIELDS = ["strEquipeId", "strEnginId", "strRapportId", "strTypeInterventionId",
-               "strTypeInterventionId", "strCatégorieInterventionId", "dblquantite", "strunite", "dtmIntervention",
-               "dtmDureeIntervention", "dtmDureeInstallation", "strLiaisonControle", "strArticleId", "intPeriode",
+               "strCatégorieInterventionId", "dblquantite", "strunite", "dtmIntervention",
+               "dtmDureeIntervention", "strLiaisonControle", "strArticleId", "intPeriode",
                "remarques", "strgrandeur1", "strgrandeur2", "strgrandeur3",
                "strcaracteristique1", "strcaracteristique2", "strcaracteristique3",
-               "dtmImportation", "strTest", "LienAff"
+               "strunite1", "strunite2", "strunite3",
+               "dtmImportation", "strTest", "LienAff",
+               "lngChantierId", "bytCommandeId", "bytIntervId"
                ]
 
 def engin_existe(strEnginId):
@@ -203,7 +206,7 @@ for data in controles_db.read(sql):
 
     interv.strEquipeId = "C{}".format(data.strEquipeId)
     interv.strEnginId = data.strEnginId
-    interv.strRapportId = data.strRapportId
+    interv.strRapportId = data.lngRapportId
     interv.strTypeInterventionId = get_type_compactage_interv(data.memTravaux)
     interv.strCatégorieInterventionId = "CC"
     interv.dblquantite = 1
@@ -228,6 +231,11 @@ for data in controles_db.read(sql):
     interv.strTest = "{}/{}/{}/{}".format(data.lngChantierId, data.bytCommandeId, data.bytIntervId, data.bytPartChantierId)
     interv.LienAff = "{}/{}".format(data.lngChantierId, data.bytCommandeId)
 
+    # pour garder le lien avec la donnée d'origine:
+    interv.lngChantierId = data.lngChantierId
+    interv.bytCommandeId = data.bytCommandeId
+    interv.bytIntervId = data.bytIntervId
+
     # Créé la ligne dans le fichier intervs.csv
     interv.dump(intervs_file)
 
@@ -271,7 +279,7 @@ for data in controles_db.read(sql):
     interv.strRapportId = data.lngRapportId
     interv.strTypeInterventionId = "CE{}".format(data.bytTypeEssai)
     interv.strCatégorieInterventionId = "CE"
-    interv.dblquantite = data.intNbJoint
+    interv.dblquantite = int(data.intNbJoint)
     interv.strunite = "u"
     interv.dtmIntervention = data.dtmEssai
     interv.dtmDureeIntervention = data.dtmDuree
@@ -293,6 +301,11 @@ for data in controles_db.read(sql):
     interv.strTest = "{}/{}/{}/{}".format(data.lngChantierId, data.bytCommandeId, data.bytIntervId, data.bytPartChantierId)
     interv.LienAff = "{}/{}".format(data.lngChantierId, data.bytCommandeId)
 
+    # pour garder le lien avec la donnée d'origine:
+    interv.lngChantierId = data.lngChantierId
+    interv.bytCommandeId = data.bytCommandeId
+    interv.bytIntervId = data.bytIntervId
+
     # Créé la ligne dans le fichier intervs.csv
     interv.dump(intervs_file)
 
@@ -330,7 +343,7 @@ for data in controles_db.read(sql):
     interv.strRapportId = data.lngRapportId
     interv.strTypeInterventionId = "CI1" if data.strEntrepriseId != 195 else "CI2"
     interv.strCatégorieInterventionId = "CI"
-    interv.dblquantite = data.sngNbJourFact
+    interv.dblquantite = int(data.sngNbJourFact)
     interv.strunite = "j"
     interv.dtmIntervention = data.dtmIntervDu
     interv.dtmDureeIntervention = data.dtmDuree
@@ -352,6 +365,11 @@ for data in controles_db.read(sql):
     interv.strTest = "{}/{}/{}/1".format(data.lngChantierId, data.bytCommandeId, data.bytIntervId)
     interv.LienAff = "{}/{}".format(data.lngChantierId, data.bytCommandeId)
 
+    # pour garder le lien avec la donnée d'origine:
+    interv.lngChantierId = data.lngChantierId
+    interv.bytCommandeId = data.bytCommandeId
+    interv.bytIntervId = data.bytIntervId
+
     # Créé la ligne dans le fichier intervs.csv
     interv.dump(intervs_file)
 
@@ -447,36 +465,39 @@ while errors:
         logging.error("<!> Des erreurs ont été détectées dans les données à importer. <!>")
         for msg in errors:
             logging.error(msg)
+    else:
+        logging.info("Aucune erreur n'a été détéctée dans les données.")
+        if no_prompt:
+            break
 
-    prompt = ""
-    while prompt != "v":
-        prompt = input(">> Veuillez contrôler les données, puis taper 'v' pour continuer, ou 'q' pour quitter...")
-        if prompt == "q":
-            sys.exit(1)
+#     prompt = ""
+#     while prompt != "v":
+#         prompt = input(">> Veuillez contrôler les données, puis taper 'v' pour continuer, ou 'q' pour quitter...")
+#         if prompt == "q":
+#             sys.exit(1)
 
 
 
 
 # ########## MISE A JOUR DE LA BASE DE DONNEES ANALYTIQUE ##########
 
-# On charge en mémoire les affaires et les interventions qui leurs sont associées
+# On charge en mémoire les affaires et les interventions
+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.")
 
-affaires = {}
+affaires = []
 with open(affaires_file) as f:
     next(f)  # saute la première ligne
-
     for line in f:
         affaire = Affaire.from_csv(line)
+        affaires.append(affaire)
 
+intervs = []
 with open(intervs_file) as f:
     next(f)  # saute la première ligne
-
     for line in f:
         interv = Interv.from_csv(line)
-        try:
-            affaires[interv.LienAff].append(interv)
-        except KeyError:
-            logger.error("L'intervention {} n'est liée à aucune affaire. Elle ne sera pas importée.".format(interv.strLiaisonControle))
+        intervs.append(interv)
 
 class Tarification(Model):
     """ Modèle de donnée d'une ligne de tarification """
@@ -486,104 +507,126 @@ class Tarification(Model):
 
 # 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.values():
+for affaire in affaires:
 
     # insertion dans tbl_Affaires
     sql = """ INSERT INTO tbl_Affaires ( strMOId, strMOeId, strEntrepriseId, strCommneId, strLieux, strTypeId, dtmCommande, Ref,
-                                        blnMarche, dblMarche, intTypeContrat, strCT, strAvancement, strLiaisonControle, intDevisId, blnTarification,
-                                        blnAnalyse, remarques, strSituation, dtmFin, intCoefFG )
+                                        blnMarche, dblMarche, intTypeContrat, strCT, strLiaisonControle, blnTarification,
+                                        blnAnalyse, strSituation, intCoefFG )
        VALUES ('{affaire.strMOId}', '{affaire.strMOeId}', '{affaire.strEntrepriseId}', '{affaire.strCommneId}', '{affaire.strLieux}', '{affaire.strTypeId}',
        #{affaire.dtmCommande}#, '{affaire.Ref}', {affaire.blnMarche}, {affaire.dblMarche}, {affaire.intTypeContrat}, '{affaire.strCT}',
-       '{affaire.strAvancement}', '{affaire.strLiaisonControle}', {affaire.intDevisId},True, {affaire.blnAnalyse},
-       '{affaire.remarques}', '{affaire.strSituation}', #{affaire.dtmFin}#, {affaire.intCoefFG})
+       '{affaire.strLiaisonControle}', True, False, '{affaire.strSituation}', {affaire.intCoefFG})
        """.format(affaire=affaire)
 
     analytique_db.execute(sql)
     logger.info("> Ajout de l'affaire: {}".format(affaire.strLiaisonControle))
 
-    affaire.DblAffaireId = analytique_db.first("SELECT TOP 1 DblAffaireId FROM tbl_Affaires WHERE [strLiaisonControle]='{}'".format(affaire.strLiaisonControle)).DblAffaireId
-
-    # insertions des interventions dans tbl_Intervention
-    for interv in affaire.intervs:
-
-        sql = """INSERT INTO tbl_Intervention ( DblAffaireId, strEquipeId, strEnginId, strRapportId, strCatégorieInterventionId, strTypeInterventionId,
-                  dblquantite, strunite, dtmIntervention, dtmDureeIntervention, dtmDureeInstallation, strcaracteristique1, strgrandeur1, strunite1,
-                  strcaracteristique2, strgrandeur2, strunite2, strcaracteristique3, strgrandeur3, strunite3, strLiaisonControle, strarticleId,
-                  intPeriode, blnTarification, blnAnalyse, blnFacturer, remarques, blnPeriode, dtnPeriodeDebut, dtmImportation, blnVerifFacture, strTest )
-          VALUES ({dblAffaireId}, '{interv.strEquipeId}', '{interv.strEnginId}', '{interv.strRapportId}', '{interv.strCatégorieInterventionId}',
-              '{interv.strTypeInterventionId}', {interv.dblquantite}, '{interv.strunite}', #{interv.dtmIntervention}#, #{interv.dtmDureeIntervention}#,
-              #{interv.dtmDureeInstallation}#, '{interv.strcaracteristique1}', '{interv.strgrandeur1}', '{interv.strunite1}', '{interv.strcaracteristique2}',
-              '{interv.strgrandeur2}', '{interv.strunite2}', '{interv.strcaracteristique3}', '{interv.strgrandeur3}', '{interv.strunite3}', '{interv.strLiaisonControle}',
-              '{interv.strarticleId}', {interv.intPeriode}, True, {interv.blnAnalyse}, {interv.blnFacturer}, '{interv.remarques}',
-              {interv.blnPeriode},#{interv.dtnPeriodeDebut}#, #{interv.dtmImportation}#, {interv.blnVerifFacture}, '{interv.strTest}')
-          """.format(dblAffaireId=affaire.DblAffaireId,
-                     interv=interv)
-
-        analytique_db.execute(sql)
-
-        logger.info("> Ajout de l'intervention: {}".format(interv.strLiaisonControle))
-
-
-
-    # Calcul de la tarification et ajout à tbl_Tarification
-    # > On va créer une ligne de tarification pour chaque engin (cad. pour chaque strArticleId)
-    for strArticleId in set([interv.strArticleId for interv in affaires.intervs]):
-
-        # recupere le prix unitaire de l'engin
-        prix_unitaire = commun_db.first("""SELECT dblPU FROM tblTarif WHERE [strArticleId]='{}' AND [intPeriodeValiditeId]={}
-                                        """.format(affaire.strArticleId, affaire.intPeriode)).dblPU
-        # recupere le taux de tva applicable à l'engin
-        taux_tva = commun_db.first("""SELECT tblTVATaux.dblTVATaux FROM tblArticle INNER JOIN tblTVATaux ON tblArticle.bytTVAArticleId = tblTVATaux.bytTVAId
-                                      WHERE (((tblArticle.strArticleId)='{}'));""".format(strArticleId)).dblTVATaux
-
-        tarif = Tarification()
-        tarif.intervs = [interv for interv in affaires.intervs if interv.strArticleId == strArticleId]
-
-        tarif.DblAffaireId = affaire.DblAffaireId
-        tarif.strRapportId = tarif.intervs[0].strRapportId
-        tarif.strArticleId = strArticleId
-        tarif.dblQuantite = sum([interv.dblquantite for interv in tarif.intervs])
-        tarif.strUnite = tarif.intervs[0].strUnite
-        tarif.dtmDebut = min([interv.dtmIntervention for interv in tarif.intervs])
-        tarif.dtmFin = max([interv.dtmIntervention for interv in tarif.intervs])
-        tarif.bytPeriode = tarif.intervs[0].intPeriode
-        tarif.dblPrixUnitaire = prix_unitaire
-        tarif.dblPrixTotal = tarif.dblQuantite * tarif.dblPrixUnitaire
-        tarif.dblTauxTVA = taux_tva
-        tarif.dblPrixTVA = tarif.dblPrixTotal * (0.01 * tarif.dblTauxTVA)
-        tarif.strStatut = 'A facturer'
-
-        sql = """ INSERT INTO tbl_Tarification ( DblAffaireId, strRapportId, strArticleId, dblQuantite, strUnite, dtmDebut, dtmFin, bytPeriode, dblPrixUnitaire, dblPrixTotal, strStatut )
-                  VALUES ({tarif.DblAffaireId}, {tarif.strRapportId}, {tarif.strArticleId}, {tarif.dblQuantite}, {tarif.strUnite}, {tarif.dtmDebut},
-                           {tarif.dtmFin}, {tarif.bytPeriode}, {tarif.dblPrixUnitaire}, {tarif.dblPrixUnitaire}, {tarif.dblPrixTotal},
-                           {tarif.dblTauxTVA}, {tarif.dblPrixTVA}, {tarif.strStatut})
-                """.format(tarif=tarif)
-        analytique_db.execute(sql)
-
-        logger.info("> Génération d'une ligne de tarification pour l'article: {}".format(affaire.strLiaisonControle, strArticleId))
-
-
-    # Maj champs MOS
-    # Ces champs sont utilisés dans les tables Controles pour savoir si une ligne a déjà été importée
+
+# On insère les interventions dans tbl_Intervention
+for interv in intervs:
+
+    affaire = analytique_db.first("SELECT TOP 1 DblAffaireId FROM tbl_Affaires WHERE [strLiaisonControle]='{}'".format(interv.LienAff))
+    if not affaire:
+        logger.error("Intervention {} : Impossible de trouver l'affaire {}".format(interv.strTest, interv.LienAff))
+        continue
+
+    interv.dblAffaireId = affaire.DblAffaireId
+
+    sql = """INSERT INTO tbl_Intervention ( DblAffaireId, strEquipeId, strEnginId, strRapportId, strCatégorieInterventionId, strTypeInterventionId,
+              dblquantite, strunite, dtmIntervention, dtmDureeIntervention, strcaracteristique1, strgrandeur1, strunite1,
+              strcaracteristique2, strgrandeur2, strunite2, strcaracteristique3, strgrandeur3, strunite3, strLiaisonControle, strarticleId,
+              intPeriode, blnTarification, blnAnalyse, blnFacturer, remarques, blnPeriode, dtmImportation, strTest )
+      VALUES ({interv.dblAffaireId}, '{interv.strEquipeId}', '{interv.strEnginId}', '{interv.strRapportId}', '{interv.strCatégorieInterventionId}',
+          '{interv.strTypeInterventionId}', {interv.dblquantite}, '{interv.strunite}', #{interv.dtmIntervention}#, #{interv.dtmDureeIntervention}#,
+          '{interv.strcaracteristique1}', '{interv.strgrandeur1}', '{interv.strunite1}', '{interv.strcaracteristique2}',
+          '{interv.strgrandeur2}', '{interv.strunite2}', '{interv.strcaracteristique3}', '{interv.strgrandeur3}', '{interv.strunite3}', '{interv.strLiaisonControle}',
+          '{interv.strArticleId}', {interv.intPeriode}, True, False, False, '{interv.remarques}',
+          False, #{interv.dtmImportation}#, '{interv.strTest}')
+      """.format(interv=interv)
+
+    analytique_db.execute(sql)
+
+    logger.info("> Ajout de l'intervention: {}".format(interv.strTest))
+
+
+
+# Calcul de la tarification et ajout à tbl_Tarification
+
+# > 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)
+for strRapportId, strArticleId in set([(interv.strRapportId, interv.strArticleId) for interv in intervs]):
+
+    tarif = Tarification()
+    tarif.intervs = [interv for interv in intervs if interv.strRapportId == strRapportId and interv.strArticleId == strArticleId]
+
+    # recupere le prix unitaire de l'engin
+    prix_unitaire = commun_db.first("""SELECT dblPU FROM tblTarif WHERE [strArticleId]='{}' AND [intPeriodeValiditeId]={}
+                                    """.format(strArticleId, tarif.intervs[0].intPeriode)).dblPU
+    # recupere le taux de tva applicable à l'engin
+    taux_tva = commun_db.first("""SELECT tblTVATaux.dblTVATaux FROM tblArticle INNER JOIN tblTVATaux ON tblArticle.bytTVAArticleId = tblTVATaux.bytTVAId
+                                  WHERE (((tblArticle.strArticleId)='{}'));""".format(strArticleId)).dblTVATaux
+
+    tarif.DblAffaireId = tarif.intervs[0].dblAffaireId
+    tarif.strRapportId = strRapportId
+    tarif.strArticleId = strArticleId
+    tarif.dblQuantite = sum([int(interv.dblquantite) for interv in tarif.intervs])
+    tarif.strUnite = tarif.intervs[0].strunite
+    tarif.dtmDebut = min([interv.dtmIntervention for interv in tarif.intervs])
+    tarif.dtmFin = max([interv.dtmIntervention for interv in tarif.intervs])
+    tarif.bytPeriode = tarif.intervs[0].intPeriode
+    tarif.dblPrixUnitaire = prix_unitaire
+    tarif.dblPrixTotal = tarif.dblQuantite * tarif.dblPrixUnitaire
+    tarif.dblTauxTVA = taux_tva
+    tarif.dblPrixTVA = tarif.dblPrixTotal * (0.01 * tarif.dblTauxTVA)
+    tarif.strStatut = 'A facturer'
+
+    sql = """ INSERT INTO tbl_Tarification ( DblAffaireId, strRapportId, strArticleId, dblQuantite, strUnite, dtmDebut, dtmFin, bytPeriode,
+                                             dblPrixUnitaire, dblPrixTotal, dblTauxTVA, dblPrixTVA, strStatut )
+              VALUES ({tarif.DblAffaireId}, '{tarif.strRapportId}', '{tarif.strArticleId}', {tarif.dblQuantite}, '{tarif.strUnite}', #{tarif.dtmDebut}#,
+                       #{tarif.dtmFin}#, {tarif.bytPeriode}, {tarif.dblPrixUnitaire}, {tarif.dblPrixTotal},
+                       {tarif.dblTauxTVA}, {tarif.dblPrixTVA}, '{tarif.strStatut}')
+            """.format(tarif=tarif)
+    analytique_db.execute(sql)
+
+    logger.info("> Génération d'une ligne de tarification pour l'affaire {} (rapport {}, article: {})".format(tarif.intervs[0].LienAff, strRapportId, strArticleId))
+
+
+# Maj champs MOS
+# Ces champs sont utilisés dans les tables Controles pour savoir si une ligne a déjà été importée
+for affaire in affaires:
+    dblAffaireId = analytique_db.first("SELECT TOP 1 DblAffaireId FROM tbl_Affaires WHERE [strLiaisonControle]='{}'".format(affaire.strLiaisonControle)).DblAffaireId
+
     sql = """UPDATE tblCommandes SET tblCommandes.sngAffaireIdMos = {DblAffaireId}
             WHERE [lngChantierId]={lngChantierId} AND [bytCommandeId]={bytCommandeId}
-            """.format(DblAffaireId=affaire.DblAffaireId,
+            """.format(DblAffaireId=dblAffaireId,
                        lngChantierId=affaire.lngChantierId,
                        bytCommandeId=affaire.bytCommandeId)
-    analytique_db.execute(sql)
+    controles_db.execute(sql)
+
+for interv in intervs:
+    if interv.strCatégorieInterventionId == "CC":
+        tbl = "tblCompactageIntervs"
+    elif interv.strCatégorieInterventionId == "CE":
+        tbl = "tblEtancheiteIntervs"
+    elif interv.strCatégorieInterventionId == "CI":
+        tbl = "tblVideoIntervs"
+    else:
+        continue
 
-    for tbl in ("tblCompactageIntervs", "tblEtancheiteIntervs", "tblVideoIntervs"):
-        sql = """UPDATE {tbl} SET {tbl}.sngIntervIdMos = {DblAffaireId}
-                WHERE [lngChantierId]={lngChantierId} AND [bytCommandeId]={bytCommandeId}
-                """.format(DblAffaireId=affaire.DblAffaireId,
-                           lngChantierId=affaire.lngChantierId,
-                           bytCommandeId=affaire.bytCommandeId)
-        analytique_db.execute(sql)
-    logger.info("> Mise à jour des champs MOS")
+    sql = """UPDATE {tbl} SET {tbl}.sngIntervIdMos = {DblAffaireId}
+            WHERE [lngChantierId]={lngChantierId} AND [bytCommandeId]={bytCommandeId} AND [bytIntervId]={bytIntervId}
+            """.format(tbl=tbl,
+                       DblAffaireId=interv.dblAffaireId,
+                       lngChantierId=interv.lngChantierId,
+                       bytCommandeId=interv.bytCommandeId,
+                       bytIntervId=interv.bytIntervId)
+    controles_db.execute(sql)
 
-    # On commit les modifications
-    logger.info("Commit des modifications...")
-    analytique_db.commit()
+logger.info("> Mise à jour des champs MOS")
+
+# On commit les modifications
+logger.info("Commit des modifications...")
+analytique_db.commit()
 
 
 
@@ -596,7 +639,7 @@ logger.info("Mise à jour des temps d'installation...")
 
 sql = """ SELECT First(tbl_Intervention.dblInterventionId) AS dblInterventionId,
         tbl_Intervention.strEquipeId, tbl_Intervention.dtmIntervention,
-        Year([dtmIntervention]) AS annee, Sum(tbl_Intervention.dtmDureeIntervention) AS SD,
+        Year([dtmIntervention]) AS annee, Sum(tbl_Intervention.dtmDureeIntervention) AS SD
         FROM tbl_Intervention
         WHERE (((tbl_Intervention.strLiaisonControle) Like '*/*'))
         GROUP BY tbl_Intervention.strEquipeId, Year([dtmIntervention]), tbl_Intervention.dtmIntervention
@@ -616,5 +659,4 @@ for interv in analytique_db.read(sql):
         logger.debug("* Mise à jour du temps d'installation de l'intervention {}".format(interv.dblInterventionId))
 
 
-
 logger.info("# Import terminé")