Переглянути джерело

ctrl2analytique - Script d'insertions terminé [pas testés]

olivier.massot 7 роки тому
батько
коміт
0fd210c262
1 змінених файлів з 209 додано та 57 видалено
  1. 209 57
      ctrl2analytique.py

+ 209 - 57
ctrl2analytique.py

@@ -120,6 +120,7 @@ sql = """ SELECT tblCommandes.lngChantierId, tblCommandes.bytCommandeId, tblChan
 
 for data in controles_db.read(sql):
 
+    # Création de l'affaire
     affaire = Affaire()
     affaire.strLiaisonControle = "{}/{}".format(data.lngChantierId, data.bytCommandeId)
     affaire.strMOeId = data.strSubdivisionId
@@ -140,6 +141,10 @@ for data in controles_db.read(sql):
     with open(affaires_file, 'a') as f:
         f.write(affaire.to_csv())
 
+    # pour garder le lien avec la donnée d'origine:
+    affaire.lngChantierId = data.lngChantierId
+    affaire.bytCommandeId = data.bytCommandeId
+
     compteur += 1
 
 logger.info("> {} affaires ajoutées à {}".format(compteur, affaires_file))
@@ -214,7 +219,7 @@ for data in controles_db.read(sql):
     interv.strunite = "u"
     interv.dtmIntervention = data.dtmEssai
     interv.dtmDureeIntervention = data.dtmDuree
-    interv.dtmDureeInstallation = 0  # Les temps d'installation seront recalculés en fin de traitement
+    interv.dtmDureeInstallation = 0  # Les temps d'installation seront calculés en fin de traitement
     interv.strLiaisonControle = "{}/{}/{}".format(data.lngChantierId, data.bytCommandeId, data.bytIntervId)
     interv.strArticleId = data.strEnginId
     interv.intPeriode = get_periode_validite(data.dtmEssai)
@@ -225,6 +230,9 @@ for data in controles_db.read(sql):
     interv.strcaracteristique1 = "Matériau remblai"
     interv.strcaracteristique2 = "Matériau lit de pose"
     interv.strcaracteristique3 = "Matériau enrobage"
+    interv.strunite1 = ""
+    interv.strunite2 = ""
+    interv.strunite3 = ""
     interv.dtmImportation = "{}".format(datetime.now().strftime("%Y-%m-%d"))
     interv.strTest = "{}/{}/{}/{}".format(data.lngChantierId, data.bytCommandeId, data.bytIntervId, data.bytPartChantierId)
     interv.LienAff = "{}/{}".format(data.lngChantierId, data.bytCommandeId)
@@ -234,7 +242,7 @@ for data in controles_db.read(sql):
 
     compteur += 1
 
-logger.info("> {} interventions Compactage ajoutées à {}".format(compteur, intervs_file))
+logger.info("> {} interventions Compactage ajoutées au fichier".format(compteur))
 
 # *** 3- Import des interventions de contrôle d'étanchéité dans le fichier intervs.csv
 compteur = 0
@@ -282,6 +290,7 @@ for data in controles_db.read(sql):
     interv.strcaracteristique1 = "Matériau"
     interv.strcaracteristique2 = "Diamètre"
     interv.strcaracteristique3 = "Longueur"
+    interv.strunite1 = ""
     interv.strunite2 = "mm"
     interv.strunite3 = "m"
     interv.dtmImportation = "{}".format(datetime.now().strftime("%Y-%m-%d"))
@@ -293,7 +302,7 @@ for data in controles_db.read(sql):
 
     compteur += 1
 
-logger.info("> {} interventions Etanchéité ajoutées à {}".format(compteur, intervs_file))
+logger.info("> {} interventions Etanchéité ajoutées au fichier".format(compteur))
 
 # *** 4- Import des interventions d'inspection vidéo dans le fichier intervs.csv
 compteur = 0
@@ -315,9 +324,7 @@ for data in controles_db.read(sql):
     interv = Interv()
 
 
-    if not engin_existe(data.strEnginId):
-        errors.append("""Intervention compactage {}/{}/{}/1: l'engin {} n'existe pas"""
-                      .format(data.lngChantierId, data.bytCommandeId, data.bytIntervId, data.strEnginId))
+
 
     interv.strEquipeId = "C{}".format(data.strEquipeId)
     interv.strEnginId = data.strEnginId
@@ -339,6 +346,7 @@ for data in controles_db.read(sql):
     interv.strcaracteristique1 = "Matériau"
     interv.strcaracteristique2 = "Diamètre"
     interv.strcaracteristique3 = "Longueur inspectée"
+    interv.strunite1 = ""
     interv.strunite2 = "mm"
     interv.strunite3 = "m"
     interv.dtmImportation = "{}".format(datetime.now().strftime("%Y-%m-%d"))
@@ -350,74 +358,218 @@ for data in controles_db.read(sql):
 
     compteur += 1
 
-logger.info("> {} interventions ITV ajoutées à {}".format(compteur, intervs_file))
-
-# *** 5- Interruption pour corection manuelle des données (si nécessaire)
-logging.info("Les données à importer ont été ajoutées aux fichiers '{}' et '{}'".format(affaires_file, intervs_file))
+logger.info("> {} interventions ITV ajoutées au fichier".format(compteur))
 
-if errors:
-    logging.error("<!> Des erreurs ont été détectées dans les données à importer. <!>")
-    for msg in errors:
-        logging.error(msg)
 
-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)
-
-
-# *** 6- Insertion des données dans les tables Analytique
+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)")
+
+
+# *** 6- Recherche d'erreurs
+errors = -1
+
+while errors:
+    errors = []
+
+    with open(affaires_file) as f:
+        next(f)  # saute la première ligne
+
+        for line in f:
+            affaire = Affaire.from_csv(line)
+
+            prefix = "Affaire {}: ".format(affaire.strLiaisonControle)
+            if not affaire.strMOId:
+                errors.append(prefix + "MO manquant")
+            else:
+                if not commun_db.exists("SELECT [lngTiersId] FROM tblTiers WHERE [lngTiersId]={}".format(affaire.strMOId)):
+                    errors.append(prefix + "Le MO {} n'existe pas dans tblTiers".format(affaire.strMOId))
+            if not affaire.strMOeId:
+                errors.append(prefix + "MOe manquant")
+            else:
+                if not commun_db.exists("SELECT [lngTiersId] FROM tblTiers WHERE [lngTiersId]={}".format(affaire.strMOeId)):
+                    errors.append(prefix + "Le MOe {} n'existe pas dans tblTiers".format(affaire.strMOeId))
+            if not affaire.strEntrepriseId:
+                errors.append(prefix + "Entreprise manquante")
+            else:
+                if not commun_db.exists("SELECT [lngTiersId] FROM tblTiers WHERE [lngTiersId]={}".format(affaire.strEntrepriseId)):
+                    errors.append(prefix + "L'entreprise {} n'existe pas dans tblTiers".format(affaire.strEntrepriseId))
+            if not affaire.strCommneId:
+                errors.append(prefix + "Commune manquante")
+            else:
+                if not commun_db.exists("SELECT [lngTiersId] FROM tblTiers WHERE [lngTiersId]={}".format(affaire.strCommneId)):
+                    errors.append(prefix + "La commune {} n'existe pas dans tblTiers".format(affaire.strCommneId))
+            if not affaire.strTypeId:
+                errors.append(prefix + "Type d'affaire manquant")
+            if not affaire.dtmCommande:
+                errors.append(prefix + "Date de commande manquante")
+            if affaire.blnMarche == True and not affaire.intDevisId:
+                errors.append(prefix + "Numéro de devis manquant")
+
+            if analytique_db.exists("SELECT dblAffaireId FROM tbl_Affaires WHERE [strLiaisonControle]='{}'".format(affaire.strLiaisonControle)):
+                errors.append(prefix + "Une affaire portant ce code existe déjà: {}".format(affaire.strLiaisonControle))
+
+    with open(intervs_file) as f:
+        next(f)  # saute la première ligne
+
+        for line in f:
+            interv = Interv.from_csv(line)
+
+            prefix = "Intervention {}: ".format(interv.strLiaisonControle)
+            if not interv.strEquipeId:
+                errors.append(prefix + "Equipe manquante")
+            if not interv.strEnginId:
+                errors.append(prefix + "Engin manquant")
+            if not interv.strRapportId:
+                errors.append(prefix + "Rapport manquant")
+            if not interv.strCatégorieInterventionId:
+                errors.append(prefix + "Catégorie de l'intervention manquante")
+            if not interv.strTypeInterventionId:
+                errors.append(prefix + "Type d'intervention manquant")
+            if not interv.dblquantite:
+                errors.append(prefix + "Quantité nulle")
+            if not interv.strunite:
+                errors.append(prefix + "Unité non renseignée")
+            if not interv.dtmIntervention:
+                errors.append(prefix + "Erreur : date d'intervention")
+            if not interv.dtmDureeIntervention:
+                errors.append(prefix + "Durée d'intervention nulle")
+            if not interv.strunite:
+                errors.append(prefix + "Unité non renseignée")
+
+            if not engin_existe(interv.strEnginId):
+                errors.append(prefix + "l'engin {} n'existe pas".format(interv.strEnginId))
+
+    # *** 6- Interruption pour corection manuelle des données (si nécessaire)
+    if errors:
+        logging.error("<!> Des erreurs ont été détectées dans les données à importer. <!>")
+        for msg in errors:
+            logging.error(msg)
+
+    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)
+
+
+# *** 7- Insertion des données dans les tables Analytique
+
+affaires = {}
 with open(affaires_file) as f:
     next(f)  # saute la première ligne
 
     for line in f:
         affaire = Affaire.from_csv(line)
 
-        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 )
-           SELECT {strMOId}, {strMOeId}, {strEntrepriseId}, {strCommneId}, {strLieux}, {strTypeId}, {dtmCommande},
-           {Ref}, {blnMarche}, {dblMarche}, {intTypeContrat}, {strCT}, {strAvancement}, {strLiaisonControle}, {intDevisId},
-           {blnTarification}, {blnAnalyse}, {remarques}, {strSituation}, {dtmFin}, {intCoefFG}
-           """.format(strMOId=affaire.strMOId,
-                      strMOeId=affaire.strMOeId,
-                      strEntrepriseId=affaire.strEntrepriseId,
-                      strCommneId=affaire.strCommneId,
-                      dtmCommande=affaire.dtmCommande,
-                      Ref=affaire.Ref,
-                      blnMarche=affaire.blnMarche,
-                      dblMarche=affaire.dblMarche,
-                      intTypeContrat=affaire.intTypeContrat,
-                      strCT=affaire.strCT,
-                      strAvancement=affaire.strAvancement,
-                      strLiaisonControle=affaire.strLiaisonControle,
-                      intDevisId=affaire.intDevisId,
-                      blnTarification=affaire.blnTarification,
-                      blnAnalyse=affaire.blnAnalyse,
-                      remarques=affaire.remarques,
-                      strSituation=affaire.strSituation,
-                      dtmFin=affaire.dtmFin,
-                      intCoefFG=affaire.intCoefFG)
+with open(intervs_file) as f:
+    next(f)  # saute la première ligne
 
-        analytique_db.execute(sql)
+    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))
+
+class Tarification(Model):
+    _FIELDS = ["DblAffaireId", "strRapportId", "strArticleId", "dblQuantite", "strUnite",
+               "dtmDebut", "dtmFin", "bytPeriode", "dblPrixUnitaire", "dblPrixTotal", "strStatut"]
+
+for affaire in affaires.values():
+
+    # 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 )
+       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})
+       """.format(affaire=affaire)
+
+    analytique_db.execute(sql)
+
+    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)
 
-        affaire.affaireId = analytique_db.first("SELECT TOP 1 DblAffaireId FROM tbl_Affaires ORDER BY DblAffaireId DESC").DblAffaireId
-        # Stocker cette valeur dans un dico associéeau strLiaisonControle, pour la maj de tblIntervs
+        analytique_db.execute(sql)
 
-        # Insérer ici les intervs liées à l'affaire (?)
 
-        # Maj champs MOS, puis committer
+    # 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)
 
 
-with open(intervs_file) as f:
-    next(f)  # saute la première ligne
+    # Maj champs MOS
+    # (champs utilisés dans les tables Controles pour savoir si une ligne a déjà été importée)
+    sql = """UPDATE tblCommandes SET tblCommandes.sngAffaireIdMos = {DblAffaireId}
+            WHERE [lngChantierId]={lngChantierId} AND [bytCommandeId]={bytCommandeId}
+            """.format(DblAffaireId=affaire.DblAffaireId,
+                       lngChantierId=affaire.lngChantierId,
+                       bytCommandeId=affaire.bytCommandeId)
+    analytique_db.execute(sql)
+
+    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)
 
-    for line in f:
-        interv = Interv.from_csv(line)
+    # On commit les modifications
+    analytique_db.commit()
 
+    logger.info("> Affaire créée: {}".format(affaire.strLiaisonControle))
+    for interv in affaire.intervs:
+        logger.info("> Intervention créée: {}".format(interv.strLiaisonControle))
 
-# Reprendre la fonction PostVerif
 
 # Maj des temps d'installation