Bladeren bron

Script suiviactivité2pda.py testé et validé

FREYD Dominique 7 jaren geleden
bovenliggende
commit
5ea1113cde
4 gewijzigde bestanden met toevoegingen van 224 en 1 verwijderingen
  1. 2 0
      core/sqlformatter.py
  2. 5 1
      logging.yaml
  3. 30 0
      resources/test_suiviactivite2pda.py
  4. 187 0
      suiviactivite2pda.py

+ 2 - 0
core/sqlformatter.py

@@ -24,6 +24,8 @@ class SqlFormatter(string.Formatter):
             return "#{:%Y-%m-%d %H:%M:%S}#".format(value)
         elif format_spec == "text":
             return "'{}'".format(SqlFormatter._escape(str(value)))
+        elif format_spec == "float":
+            return str(value).replace(",", ".")
         else:
             return SqlFormatter._escape(value.__format__(format_spec))
 

+ 5 - 1
logging.yaml

@@ -87,7 +87,11 @@ loggers:
         level: DEBUG
         handlers: [console, file,mail]
         propagate: no
-        
+    suiviactivite2pda:
+        level: DEBUG
+        handlers: [console, file,mail]
+        propagate: no
+
 root:
     level: DEBUG
     handlers: [console]

+ 30 - 0
resources/test_suiviactivite2pda.py

@@ -0,0 +1,30 @@
+'''
+
+@author: olivier.massot
+'''
+from path import Path
+
+from core.pde import AgrhumDb, PdaDb
+
+if __name__ == "__main__":
+
+    # reinitialise les données pour les tests de ctrl2analytique.py
+
+    PdaDb._path = Path(r"\\h2o\local\4-transversal\BDD\mdb_test\PDA\db_PDA.mdb")
+    AgrhumDb._path = Path(r"\\h2o\local\4-transversal\BDD\mdb_test\BDD_ParcRH.mdb")
+    pda_db = PdaDb(autocommit=True)
+    agrhum_db = AgrhumDb(autocommit=False)
+
+    moisrh = 6
+    anneerh = 2018
+
+    for codeagent in ("T5", "T30", "T9"):
+
+        pda_db.execute("DELETE * FROM tbl_Import_tmp1 WHERE [CodeAgent]='{}' and month([ddebut])={} and year([ddebut])={}".format(codeagent, moisrh, anneerh))
+        agrhum_db.execute("DELETE * FROM tbl_ImportRH WHERE [CodeAgent]='{}' and month([DateRH])={} and year([DateRH])={}".format(codeagent, moisrh, anneerh))
+        agrhum_db.execute("DELETE * FROM tbl_SuiviRH WHERE [CodeAgent]='{}' and MoisRH={} and AnneeRH={}".format(codeagent, moisrh, anneerh))
+
+    pda_db.commit()
+    agrhum_db.commit()
+
+

+ 187 - 0
suiviactivite2pda.py

@@ -0,0 +1,187 @@
+import requests
+from lxml import etree
+from requests_ntlm.requests_ntlm import HttpNtlmAuth
+import codecs
+import json
+from core.pde import PdaDb, CommunDb, AgrhumDb, PDA_FILES_DEST
+from core.model import Sql
+from path import Path
+import datetime
+import logging
+from core import logconf
+
+
+
+AUTH = HttpNtlmAuth(r'CG67\LectureAD', 'Adlecture!')    
+JSONHEADERS  = {'accept': 'application/json;odata=verbose'}
+XMLEADERS  = {'accept': 'text/xml; charset=utf-8'}
+SHAREPOINTBASE = "http://backweb.bas-rhin.fr/perstein/parc-erstein"
+SHAREPOINTDIR = SHAREPOINTBASE + "/export/"
+SHAREPOINTJSON = SHAREPOINTBASE + "/_vti_bin/listdata.svc/Export"
+
+logger = logging.getLogger("suiviactivite2pda")
+logconf.start("suiviactivite2pda", logging.DEBUG)
+
+
+# # POUR TESTER, décommenter les lignes suivantes
+##-----------------------------------------------
+
+PdaDb._path = Path(r"\\h2o\local\4-transversal\BDD\mdb_test\PDA\db_PDA.mdb")
+CommunDb._path = Path(r"\\h2o\local\4-transversal\BDD\mdb_test\Commun_Data.mdb")
+AgrhumDb._path = Path(r"\\h2o\local\4-transversal\BDD\mdb_test\BDD_ParcRH.mdb")
+logger.handlers = [h for h in logger.handlers if (type(h) == logging.StreamHandler)]
+logger.warning("Mode TEST")
+
+##-----------------------------------------------
+
+# pour acceder à la base PDA
+pda_db = PdaDb(autocommit=True)
+commun_db = CommunDb(autocommit=True)
+agrhum_db = AgrhumDb(autocommit=False)
+
+def make_request(url,typeheaders):
+    r = requests.get( url,  auth=AUTH, headers=typeheaders)
+    return r.json()
+
+
+#traite le fichier dont le nom est passé en param
+def TraiteUnFichier(fichier):   
+    
+    if agrhum_db.exists("select * from tbl_importrh where FichierXml='{}'".format(fichier) ):
+        logger.debug(">> Le fichier a déjà été importé, import annulé")
+        return
+
+    logger.info("Traitement du fichier %s",fichier )
+
+    # on recupere le contenu du fichier dans la bibliothèque sp
+    # on applique le bon décodage de manière a pouvoir le
+    # parser avec etree
+    reponse = requests.get((SHAREPOINTDIR + fichier), auth=AUTH, headers=XMLEADERS)   
+    byte =reponse.content    
+    if "encoding=\"UTF-8\"" in reponse.text:
+        xmldata = byte.decode("utf-8")
+        xmldata = xmldata.replace( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>","")        
+    else:
+        xmldata = byte.decode("utf-16-le")
+    tree = etree.fromstring(xmldata)
+
+
+    # code ligne est un compteur qui serveur pour le srapports et les congées 
+    CodeLigne = 1
+    moisrh = 0
+    anneerh = 0
+    # traitement des rapports
+    for rapport in tree.xpath("/ArrayOfAction/ArrayOfRapport/Rapport"):       
+       Id = rapport.find("Id").text     
+       CodeAttelage = rapport.find("CodeAttelage").text     
+       CodeAgent= rapport.find("CodeAgent").text     
+       CodeChantier= rapport.find("CodeChantier").text     
+       Duree= rapport.find("Duree").text     
+       if "T" in rapport.find("DateDebut").text:
+            DateDebut= datetime.datetime.strptime(rapport.find("DateDebut").text, "%Y-%m-%dT%H:%M:%S")
+       else:
+            DateDebut= datetime.datetime.strptime(rapport.find("DateDebut").text, "%d/%m/%Y")
+       if not moisrh: moisrh = DateDebut.month
+       if not anneerh: anneerh = DateDebut.year
+       if len(rapport.find("CodeNatureRealisation").text) < 2:
+            CodeNatureRealisation= ("00" + rapport.find("CodeNatureRealisation").text)[-2:]     
+       else:
+            CodeNatureRealisation= rapport.find("CodeNatureRealisation").text     
+       CodeLocalisation= rapport.find("CodeLocalisation").text     
+       Remarque= rapport.find("Remarque").text     
+       HeureSup1= rapport.find("HeureSup1").text     
+       HeureSup2= rapport.find("HeureSup2").text     
+       HeureSupDimanche= rapport.find("HeureSupDimanche").text     
+       Repas= rapport.find("Repas").text     
+       DistanceTranche1= rapport.find("DistanceTranche1").text     
+       VehiculePersoTranche1= rapport.find("VehiculePersoTranche1").text     
+       DistanceTranche2= rapport.find("DistanceTranche2").text     
+       VehiculePersoTranche2= rapport.find("VehiculePersoTranche2").text     
+                
+       DateFin = DateDebut  
+       
+       # recuperation de l'identifiant de la période concernée  
+       IdPeriode= commun_db.first(Sql.format("select intPeriodeValiditeId as d from tblTarifValidite where dtmValiditeDebut<={:date} and dtmValiditeFin>{:date}",DateDebut,DateFin)).d
+
+       Localisation= commun_db.first("select strTiersMnemo from tblTiers where lngTiersId={}".format(CodeLocalisation)).strTiersMnemo
+
+
+       # ecriture dans la table tbl_Import_tmp1
+       sql = Sql.format("INSERT INTO tbl_Import_tmp1 ("
+              "Id, CodeAgent, CodeChantier, CodeLocalisation, Localisation, CodeAttelage, CodeNatureRealisation, DDebut, DFin, Duree, Remarque, FichierXml, intPeriode, strTest, strArticleId, ConcatACE, GRP, CodeChantier_verif ) " 
+              " VALUES "
+              "({},{:text},{:text},{:text},{:text},{:text},{:text},{:date},{:date},{:float},{:text},{:text}, {},{:text},{:text},{:text},{:text},{})",
+                 CodeLigne,CodeAgent,CodeChantier,CodeLocalisation,Localisation,CodeAttelage,CodeNatureRealisation,DateDebut,DateFin,Duree,Remarque,fichier, IdPeriode,'scriptauto',CodeAttelage,'en_cours','Non', 0
+             )
+       
+       #print (sql) 
+       pda_db.execute(sql) 
+       
+       ## ecriture dans la table tbl_ImportRH   
+       
+       sql = Sql.format( "INSERT INTO tbl_ImportRH "
+                "(CodeLigne, CodeAgent, DateRH, CodeChantier, CodeLocalisation, Localisation,"
+                "strCategorieInterventionId, HeureSup1, HeureSup2, HeureSupDimanche, Repas, DistanceTranche1,"
+                "VehiculePersoTranche1, DistanceTranche2, VehiculePersoTranche2, Remarque, Depart, FichierXML,"
+                "DateImport, ResponsableImport )" 
+                    "VALUES "
+                "({:text},{:text}, {:date},{:text}, {:text}, {:text},"
+                "{:text}, {:float}, {:float}, {:float},{}, {:float},"
+                "{:text}, {:float}, {:text}, {:text},{:text},{:text},"
+                "{:date}, {:text})",CodeLigne,CodeAgent, DateDebut, CodeChantier, CodeLocalisation, Localisation,
+                CodeNatureRealisation, HeureSup1, HeureSup2, HeureSupDimanche, Repas, DistanceTranche1,
+                "True" if VehiculePersoTranche1 != "0" else "False", DistanceTranche2, "True" if VehiculePersoTranche2 != "0" else "False", Remarque, "", fichier,
+                datetime.datetime.today(), 'scriptauto'
+                )
+            
+       #print (sql)
+       agrhum_db.execute(sql)
+       CodeLigne +=1
+       
+
+   # traitement des congées
+    for conges in tree.xpath("/ArrayOfAction/ArrayOfConges/Conges"):
+       if "T" in conges.find("DateDebut").text:
+            DateDebut= datetime.datetime.strptime(conges.find("DateDebut").text, "%Y-%m-%dT%H:%M:%S")
+       else:
+            DateDebut= datetime.datetime.strptime(conges.find("DateDebut").text, "%d/%m/%Y")
+       if "T" in conges.find("DateFin").text:
+            DateFin= datetime.datetime.strptime(conges.find("DateFin").text, "%Y-%m-%dT%H:%M:%S")
+       else:
+            DateFin= datetime.datetime.strptime(conges.find("DateFin").text, "%d/%m/%Y")
+       Duree= rapport.find("Duree").text    
+       
+       sql = Sql.format("INSERT INTO tbl_Import_tmp1 ("
+              "Id, DDebut, DFin, Duree, CodeAttelage, CodeNatureRealisation,FichierXml, intPeriode, ConcatACE, GRP, strTest, strArticleId, CodeAgent ) " 
+              " VALUES "
+              "( {},{:date},{:date},{:float},{:text},{:text}, {:text},{},{:text},{:text},{:text},{:text},{:text})",
+                 CodeLigne,DateDebut,DateFin,Duree,'22MAOE','02',fichier, IdPeriode,'en_cours','Non','scriptauto','22MAOE',CodeAgent
+             )
+       CodeLigne +=1   
+       #print (sql)
+       pda_db.execute(sql)
+
+    # ecrite dans la table suivirh 
+    sql = Sql.format("INSERT INTO tbl_SuiviRH ( CodeAgent, MoisRH, AnneeRH, Etat, Valide ) " 
+           "VALUES ({:text},{},{},'Importé',True)",CodeAgent,moisrh,anneerh)
+    agrhum_db.execute(sql)
+
+#   traite fichier de la bibliotheque SP contenant les export
+#   Param  : aucun
+#   retour : 
+#   aucun         
+
+
+def main():
+    data = make_request(SHAREPOINTJSON,JSONHEADERS)             
+    for item in data['d']['results']:
+        filename=item['Nom']                
+        TraiteUnFichier(filename)
+    # on valide qui si tout est ok
+    pda_db.commit()
+    agrhum_db.commit()
+
+
+if __name__ == "__main__" :   
+    main()
+    logger.info("-- Fin --")