ctrl2analytique.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. '''
  2. Génère les affaires dans la base Analytique à partir des données de la base Contrôles.
  3. **IMPORTANT**: pour lancer le script sans interaction avec l'utilisateur
  4. (par ex, dans le cas d'une tâche planifiée), appeller le script avec l'option '-n'.
  5. @author: olivier.massot, févr. 2018
  6. '''
  7. from datetime import datetime, timedelta
  8. import logging
  9. import sys
  10. from path import Path # @UnusedImport
  11. from core import logconf
  12. from core.db import AccessSqlHelper
  13. from core.pde import ControlesDb, AnalytiqueDb, mk_workdir, CommunDb, Affaire, \
  14. Interv, Tarification
  15. from core.sqlformatter import SqlFormatter
  16. logger = logging.getLogger("ctrl2analytique")
  17. logconf.start("ctrl2analytique", logging.DEBUG)
  18. # # POUR TESTER, décommenter les lignes suivantes
  19. # > Lancer le script /resources/test_ctrl2analytique.py pour reinitialiser les données de la base de test
  20. ##-----------------------------------------------
  21. # ControlesDb._path = Path(r"\\h2o\local\4-transversal\BDD\mdb_test\cg67Parc_data.mdb")
  22. # AnalytiqueDb._path = Path(r"\\h2o\local\4-transversal\BDD\mdb_test\Db_analytique.mdb")
  23. # CommunDb._path = Path(r"\\h2o\local\4-transversal\BDD\mdb_test\Commun_Data.mdb")
  24. # logger.handlers = [h for h in logger.handlers if (type(h) == logging.StreamHandler)]
  25. # logger.warning("<<<<<<<<<<<<<< Mode TEST >>>>>>>>>>>>>>>>>")
  26. ##-----------------------------------------------
  27. def main():
  28. # ######### INITIALISATION ##########
  29. logger.info("Initialisation...")
  30. Sql = SqlFormatter()
  31. no_prompt = ("-n" in sys.argv)
  32. if no_prompt:
  33. logger.info("> Lancé en mode automatique (sans interruption)")
  34. # Connexion à Analytique
  35. analytique_db = AnalytiqueDb(autocommit=False)
  36. # Connexion à Controles
  37. controles_db = ControlesDb(autocommit=False)
  38. # Connexion à CommunDb
  39. commun_db = CommunDb(autocommit=False)
  40. # Créé le répertoire de travail
  41. workdir = mk_workdir("ctrl2analytique")
  42. affaires_file = workdir / "affaires.csv"
  43. intervs_file = workdir / "intervs.csv"
  44. # > Supprime les fichiers d'import s'il existent
  45. for file in (affaires_file, intervs_file):
  46. if file.exists():
  47. logger.debug("Supprime le fichier %s", file)
  48. file.remove()
  49. sqlHelper = AccessSqlHelper
  50. # date zéro pour Access
  51. date_zero = datetime(1899, 12, 30, 0, 0, 0)
  52. def get_type_id(lngChantierId, bytCommandeId):
  53. """ Recupère le type de chantier.
  54. 'ZP': Chantier de contrôle d'étanchéité
  55. 'ZC': Chantier de contrôle du compactage
  56. 'ZI': Chantier d'inspection vidéo
  57. 'ZZ': Chantier mixte.
  58. '': Inconnu
  59. """
  60. sql = """SELECT lngChantierId, 'ZP' as type FROM tblEtancheiteBases WHERE [lngChantierId] = {chantier} AND [bytCommandeId] = {commande}
  61. UNION
  62. SELECT lngChantierId, 'ZC' as type FROM tblCompactageBases WHERE [lngChantierId] = {chantier}
  63. UNION
  64. SELECT lngChantierId, 'ZI' as type FROM tblVideoBases WHERE [lngChantierId] = {chantier};
  65. """.format(chantier=lngChantierId,
  66. commande=bytCommandeId)
  67. res = controles_db.read_all(sql)
  68. if len(res) == 0:
  69. return ""
  70. elif len(res) == 1:
  71. return res[0].type
  72. else:
  73. return "ZZ"
  74. def get_coeff_k(lngChantierId):
  75. """ Récupère le coefficient de calcul des frais généraux (batiments, frais administratifs...Etc.) """
  76. # On déduit l'année du chantier à partir du code chantier
  77. annee = "20" + str(lngChantierId)[:2] if len(str(lngChantierId)) == 6 else "200" + str(lngChantierId)[:1]
  78. return analytique_db.first(Sql.format("SELECT [COEFFG] FROM tbl_COEFFG WHERE [ANNEE] = {}", annee)).COEFFG / 100
  79. # ########## IMPORT DES AFFAIRES ##########
  80. # Parcourt les chantiers de contrôle pour lesquels aucune affaire n'a été créée, et les ajoute au fichier affaire.csv
  81. compteur = 0
  82. sql = """ SELECT tblCommandes.lngChantierId, tblCommandes.bytCommandeId, tblChantiers.strSubdivisionId, tblChantiers.strCollectiviteId as ChantierCollectiviteId, tblChantiers.strLocChantier,
  83. tblChantiers.strEntrepriseId, tblCommandes.strCollectiviteId as CommandeCollectiviteId, tblCommandes.dtmCommande, tblCommandes.strRefCommande, tblCommandes.blnMarche, tblCommandes.dblMtMarche, tblCommandes.strdevis
  84. FROM tblChantiers INNER JOIN tblCommandes ON tblChantiers.lngChantierId = tblCommandes.lngChantierId
  85. WHERE (((tblCommandes.sngAffaireIdMos) Is Null Or (tblCommandes.sngAffaireIdMos)=0))
  86. """
  87. for data in controles_db.read(sql):
  88. # Création de l'affaire
  89. affaire = Affaire()
  90. affaire.strLiaisonControle = "{}/{}".format(data.lngChantierId, data.bytCommandeId)
  91. affaire.strMOeId = data.strSubdivisionId
  92. affaire.strCommneId = data.ChantierCollectiviteId
  93. affaire.strLieux = data.strLocChantier
  94. affaire.strEntrepriseId = data.strEntrepriseId
  95. affaire.strMOId = data.CommandeCollectiviteId
  96. affaire.dtmCommande = data.dtmCommande
  97. affaire.Ref = data.strRefCommande
  98. affaire.blnMarche = data.blnMarche
  99. affaire.dblMarche = data.dblMtMarche
  100. affaire.intDevisId = data.strdevis if data.strdevis else 0
  101. affaire.intTypeContrat = 1
  102. affaire.strCT = '1'
  103. affaire.strTypeId = get_type_id(data.lngChantierId, data.bytCommandeId)
  104. affaire.intCoefFG = get_coeff_k(data.lngChantierId)
  105. affaire.strSituation = "En cours"
  106. # pour garder le lien avec la donnée d'origine:
  107. affaire.lngChantierId = data.lngChantierId
  108. affaire.bytCommandeId = data.bytCommandeId
  109. # Créé la ligne dans le fichier affaires.csv
  110. affaire.dump_to_csv(affaires_file)
  111. compteur += 1
  112. logger.info("> {} affaires ajoutées au fichier".format(compteur))
  113. # ########## IMPORT DES INTERVENTIONS DE COMPACTAGE ##########
  114. # Importe les interventions de contrôle du compactage dans le fichier intervs.csv
  115. def engin_existe(strEnginId):
  116. """ retourne True si le code de l'engin existe dans la table tbl_Engin """
  117. return analytique_db.exists(Sql.format("SELECT strEnginId FROM tbl_Engin WHERE strEnginId={:text}", strEnginId))
  118. def get_periode_validite(date_interv):
  119. """ retourne la préiode comptable correspondant à la date de l'intervention """
  120. if not date_interv:
  121. return None
  122. sql = Sql.format("""SELECT intPeriodeValiditeId FROM tblTarifValidite
  123. WHERE [dtmValiditeDebut] <= {date_interv:date} AND [dtmValiditeFin] > {date_interv:date} AND [bytClasseTarifId]=1
  124. """, date_interv=date_interv)
  125. return commun_db.first(sql).intPeriodeValiditeId
  126. compteur = 0
  127. sql = """SELECT tblCompactageIntervs.lngChantierId, tblCompactageIntervs.bytCommandeId, tblCompactageIntervs.bytIntervId, tblCompactageIntervs.strEquipeId,
  128. tblCompactageEngins.strEnginId, tblCompactageIntervs.lngRapportId, tblCompactageBases.memTravaux, tblCompactageResultats.dtmEssai, tblCompactageResultats.dtmDuree,
  129. tblCompactagePartChantiers.strTrcRegard, tblMateriaux.strMatériau AS str_materiau_remblai, tblMateriaux_1.strMatériau AS str_materiau_enrobage,
  130. tblMateriaux_2.strMatériau AS str_materiau_lit, tblCompactageResultats.bytPartChantierId, tblCompactageIntervs.sngIntervIdMos
  131. FROM ((tblMateriaux RIGHT JOIN ((((tblCompactageIntervs LEFT JOIN tblCompactageEngins ON tblCompactageIntervs.strEquipeId = tblCompactageEngins.strEquipeId)
  132. INNER JOIN tblCompactageResultats ON (tblCompactageIntervs.lngChantierId = tblCompactageResultats.lngChantierId) AND
  133. (tblCompactageIntervs.bytIntervId = tblCompactageResultats.bytIntervId)) INNER JOIN tblCompactagePartChantiers ON
  134. (tblCompactageResultats.lngChantierId = tblCompactagePartChantiers.lngChantierId) AND
  135. (tblCompactageResultats.bytPartChantierId = tblCompactagePartChantiers.bytPartChantierId))
  136. INNER JOIN tblCompactageBases ON tblCompactageIntervs.lngChantierId = tblCompactageBases.lngChantierId)
  137. ON tblMateriaux.strMateriauId = tblCompactagePartChantiers.strMateriauRemblaiId) LEFT JOIN tblMateriaux AS tblMateriaux_1
  138. ON tblCompactagePartChantiers.strMateriauEnrobageId = tblMateriaux_1.strMateriauId) LEFT JOIN tblMateriaux AS tblMateriaux_2
  139. ON tblCompactagePartChantiers.strMateriauLitId = tblMateriaux_2.strMateriauId
  140. WHERE (((tblCompactageIntervs.sngIntervIdMos)=0 Or (tblCompactageIntervs.sngIntervIdMos) Is Null))
  141. """
  142. def get_type_compactage_interv(observation):
  143. """ retourne le sous-type d'intervention à partir du commentaire associé """
  144. if "ASSAINISEMENT" or "ASSAINISEMENT" in observation:
  145. return "CC3"
  146. elif "CABLE" in observation:
  147. return "CC1"
  148. elif "A.E.P" in observation:
  149. return "CC2"
  150. elif "GAZ" in observation:
  151. return "CC4"
  152. else:
  153. return "CC3"
  154. for data in controles_db.read(sql):
  155. interv = Interv()
  156. interv.strEquipeId = "C{}".format(data.strEquipeId)
  157. interv.strEnginId = data.strEnginId
  158. interv.strRapportId = data.lngRapportId
  159. interv.strTypeInterventionId = get_type_compactage_interv(data.memTravaux)
  160. interv.strCatégorieInterventionId = "CC"
  161. interv.dblquantite = 1.0
  162. interv.strunite = "u"
  163. interv.dtmIntervention = data.dtmEssai
  164. interv.dtmDureeIntervention = data.dtmDuree
  165. interv.dtmDureeInstallation = date_zero # Les temps d'installation seront calculés en fin de traitement
  166. interv.strLiaisonControle = "{}/{}/{}".format(data.lngChantierId, data.bytCommandeId, data.bytIntervId)
  167. interv.strArticleId = data.strEnginId
  168. interv.intPeriode = get_periode_validite(data.dtmEssai)
  169. interv.remarques = data.strTrcRegard if data.strTrcRegard else "-"
  170. interv.strgrandeur1 = data.str_materiau_remblai
  171. interv.strgrandeur2 = data.str_materiau_lit
  172. interv.strgrandeur3 = data.str_materiau_enrobage
  173. interv.strcaracteristique1 = "Matériau remblai"
  174. interv.strcaracteristique2 = "Matériau lit de pose"
  175. interv.strcaracteristique3 = "Matériau enrobage"
  176. interv.strunite1 = ""
  177. interv.strunite2 = ""
  178. interv.strunite3 = ""
  179. interv.dtmImportation = "{}".format(datetime.now().strftime("%Y-%m-%d"))
  180. interv.strTest = "{}/{}/{}/{}".format(data.lngChantierId, data.bytCommandeId, data.bytIntervId, data.bytPartChantierId)
  181. interv.LienAff = "{}/{}".format(data.lngChantierId, data.bytCommandeId)
  182. # pour garder le lien avec la donnée d'origine:
  183. interv.lngChantierId = data.lngChantierId
  184. interv.bytCommandeId = data.bytCommandeId
  185. interv.bytIntervId = data.bytIntervId
  186. # Créé la ligne dans le fichier intervs.csv
  187. interv.dump_to_csv(intervs_file)
  188. compteur += 1
  189. logger.info("> {} interventions Compactage ajoutées au fichier".format(compteur))
  190. # ########## IMPORT DES INTERVENTIONS D'ETANCHEITE ##########
  191. # Importe les interventions de contrôle d'étanchéité dans le fichier intervs.csv
  192. compteur = 0
  193. sql = """SELECT tblEtancheiteIntervs.lngChantierId, tblEtancheiteIntervs.bytCommandeId, tblEtancheiteIntervs.bytIntervId, tblEtancheiteIntervs.strEquipeId,
  194. tblEtancheiteIntervs.lngRapportId, tblEtancheitePartChantiers.bytTypeEssai, tblMateriaux.strMateriauId, tblMateriaux.strMatériau,
  195. tblEtancheitePartChantiers.intDiametre, tblEtancheitePartChantiers.sngLgHt, tblEtancheitePartChantiers.intNbJoint, tblEtancheiteResultats.dtmDuree,
  196. tblEtancheiteResultats.dtmEssai, tblEtancheitePartChantiers.strTrcRegard, tblEtancheiteResultats.bytPartChantierId
  197. FROM ((tblEtancheiteIntervs INNER JOIN tblEtancheiteResultats ON (tblEtancheiteIntervs.lngChantierId = tblEtancheiteResultats.lngChantierId)
  198. AND (tblEtancheiteIntervs.bytIntervId = tblEtancheiteResultats.bytIntervId)) INNER JOIN tblEtancheitePartChantiers
  199. ON (tblEtancheiteResultats.lngChantierId = tblEtancheitePartChantiers.lngChantierId)
  200. AND (tblEtancheiteResultats.bytPartChantierId = tblEtancheitePartChantiers.bytPartChantierId)) INNER JOIN tblMateriaux
  201. ON tblEtancheitePartChantiers.strMateriauId = tblMateriaux.strMateriauId
  202. WHERE (((tblEtancheiteIntervs.sngIntervIdMos)=0 Or (tblEtancheiteIntervs.sngIntervIdMos) Is Null));
  203. """
  204. def get_engin_etancheite(equipe, diametre, materiau, type_essai):
  205. """ retourne l'engin correspondant à l'essai en fonction eds caractéristiques de l'essai """
  206. sql = """SELECT strEnginId FROM tblEtancheiteEngins
  207. WHERE ([strEquipeId] = '{}') AND ([intDiametre] = {}) AND ([strMateriauId] = '{}') AND ([bytTypeEssaiId] ={})
  208. """.format(equipe, diametre, materiau, type_essai)
  209. row = controles_db.first(sql)
  210. return row.strEnginId if row else ""
  211. for data in controles_db.read(sql):
  212. interv = Interv()
  213. interv.strEquipeId = "C{}".format(data.strEquipeId)
  214. interv.strEnginId = get_engin_etancheite(data.strEquipeId, data.intDiametre, data.strMateriauId, data.bytTypeEssai)
  215. interv.strRapportId = data.lngRapportId
  216. interv.strTypeInterventionId = "CE{}".format(data.bytTypeEssai)
  217. interv.strCatégorieInterventionId = "CE"
  218. interv.dblquantite = float(data.intNbJoint)
  219. interv.strunite = "u"
  220. interv.dtmIntervention = data.dtmEssai
  221. interv.dtmDureeIntervention = data.dtmDuree
  222. interv.dtmDureeInstallation = date_zero # Les temps d'installation seront recalculés en fin de traitement
  223. interv.strLiaisonControle = "{}/{}/{}".format(data.lngChantierId, data.bytCommandeId, data.bytIntervId)
  224. interv.strArticleId = interv.strEnginId
  225. interv.intPeriode = get_periode_validite(data.dtmEssai)
  226. interv.remarques = data.strTrcRegard if data.strTrcRegard else "-"
  227. interv.strgrandeur1 = data.strMatériau
  228. interv.strgrandeur2 = data.intDiametre
  229. interv.strgrandeur3 = data.sngLgHt
  230. interv.strcaracteristique1 = "Matériau"
  231. interv.strcaracteristique2 = "Diamètre"
  232. interv.strcaracteristique3 = "Longueur"
  233. interv.strunite1 = ""
  234. interv.strunite2 = "mm"
  235. interv.strunite3 = "m"
  236. interv.dtmImportation = "{}".format(datetime.now().strftime("%Y-%m-%d"))
  237. interv.strTest = "{}/{}/{}/{}".format(data.lngChantierId, data.bytCommandeId, data.bytIntervId, data.bytPartChantierId)
  238. interv.LienAff = "{}/{}".format(data.lngChantierId, data.bytCommandeId)
  239. # pour garder le lien avec la donnée d'origine:
  240. interv.lngChantierId = data.lngChantierId
  241. interv.bytCommandeId = data.bytCommandeId
  242. interv.bytIntervId = data.bytIntervId
  243. # Créé la ligne dans le fichier intervs.csv
  244. interv.dump_to_csv(intervs_file)
  245. compteur += 1
  246. logger.info("> {} interventions Etanchéité ajoutées au fichier".format(compteur))
  247. # ########## IMPORT DES INTERVENTIONS D'INSPECTION VIDEO ##########
  248. # Importe les interventions d'inspection vidéo dans le fichier intervs.csv
  249. compteur = 0
  250. sql = """SELECT tblVideoIntervs.lngChantierId, tblVideoIntervs.bytCommandeId, tblVideoIntervs.bytIntervId, tblVideoIntervs.strEquipeId,
  251. tblVideoEngins.strEnginId, tblVideoIntervs.lngRapportId, First(tblso_rate_Analyse.MateriauCourt) AS strmateriau, tblVideoIntervs.lngTroncon,
  252. tblVideoIntervs.sngNbJourFact, First(tblso_rate_Analyse.MaxDeDiametre) AS diam, tblVideoIntervs.dtmDuree, tblVideoIntervs.dtmIntervDu,
  253. First(tblVideoIntervs.memObservation) AS memObservation, tblChantiers.strEntrepriseId
  254. FROM ((tblVideoEngins RIGHT JOIN tblVideoIntervs ON tblVideoEngins.strEquipeId = tblVideoIntervs.strEquipeId) INNER JOIN tblso_rate_Analyse ON
  255. (tblVideoIntervs.lngChantierId = tblso_rate_Analyse.lngChantierId) AND (tblVideoIntervs.bytIntervId = tblso_rate_Analyse.bytIntervId)) INNER JOIN
  256. tblChantiers ON tblVideoIntervs.lngChantierId = tblChantiers.lngChantierId
  257. WHERE (((tblVideoIntervs.sngIntervIdMos) Is Null Or (tblVideoIntervs.sngIntervIdMos)=0))
  258. GROUP BY tblVideoIntervs.lngChantierId, tblVideoIntervs.bytCommandeId, tblVideoIntervs.bytIntervId, tblVideoIntervs.strEquipeId,
  259. tblVideoIntervs.lngRapportId, tblVideoIntervs.lngTroncon, tblVideoIntervs.sngNbJourFact, tblVideoIntervs.dtmDuree,
  260. tblVideoIntervs.dtmIntervDu, tblVideoEngins.strEnginId, tblChantiers.strEntrepriseId
  261. """
  262. for data in controles_db.read(sql):
  263. interv = Interv()
  264. interv.strEquipeId = "C{}".format(data.strEquipeId)
  265. interv.strEnginId = data.strEnginId
  266. interv.strRapportId = data.lngRapportId
  267. interv.strTypeInterventionId = "CI1" if data.strEntrepriseId != 195 else "CI2"
  268. interv.strCatégorieInterventionId = "CI"
  269. interv.dblquantite = float(data.sngNbJourFact)
  270. interv.strunite = "j"
  271. interv.dtmIntervention = data.dtmIntervDu
  272. interv.dtmDureeIntervention = data.dtmDuree
  273. interv.dtmDureeInstallation = date_zero # Les temps d'installation seront recalculés en fin de traitement
  274. interv.strLiaisonControle = "{}/{}/{}".format(data.lngChantierId, data.bytCommandeId, data.bytIntervId)
  275. interv.strArticleId = data.strEnginId
  276. interv.intPeriode = get_periode_validite(data.dtmIntervDu)
  277. interv.remarques = data.memObservation if data.memObservation else "-"
  278. interv.strgrandeur1 = data.strmateriau
  279. interv.strgrandeur2 = data.diam
  280. interv.strgrandeur3 = data.lngTroncon
  281. interv.strcaracteristique1 = "Matériau"
  282. interv.strcaracteristique2 = "Diamètre"
  283. interv.strcaracteristique3 = "Longueur inspectée"
  284. interv.strunite1 = ""
  285. interv.strunite2 = "mm"
  286. interv.strunite3 = "m"
  287. interv.dtmImportation = "{}".format(datetime.now().strftime("%Y-%m-%d"))
  288. interv.strTest = "{}/{}/{}/1".format(data.lngChantierId, data.bytCommandeId, data.bytIntervId)
  289. interv.LienAff = "{}/{}".format(data.lngChantierId, data.bytCommandeId)
  290. # pour garder le lien avec la donnée d'origine:
  291. interv.lngChantierId = data.lngChantierId
  292. interv.bytCommandeId = data.bytCommandeId
  293. interv.bytIntervId = data.bytIntervId
  294. # Créé la ligne dans le fichier intervs.csv
  295. interv.dump_to_csv(intervs_file)
  296. compteur += 1
  297. logger.info("> {} interventions ITV ajoutées au fichier".format(compteur))
  298. logging.info("Les données à importer ont été ajoutées aux fichiers '{}' et '{}'".format(affaires_file, intervs_file))
  299. logging.info("Ces fichiers sont au format CSV (séparateur: tabulation)")
  300. # ########## CONTROLE ET CORRECTION DES DONNEES ##########
  301. errors = -1
  302. while errors:
  303. errors = []
  304. for affaire in Affaire.load_csv(affaires_file):
  305. prefix = "Affaire {}: ".format(affaire.strLiaisonControle)
  306. if not affaire.strMOId:
  307. errors.append(prefix + "MO manquant")
  308. else:
  309. if not commun_db.exists(Sql.format("SELECT [lngTiersId] FROM tblTiers WHERE [lngTiersId]={}", affaire.strMOId)):
  310. errors.append(prefix + "Le MO {} n'existe pas dans tblTiers".format(affaire.strMOId))
  311. if not affaire.strMOeId:
  312. errors.append(prefix + "MOe manquant")
  313. else:
  314. if not commun_db.exists(Sql.format("SELECT [lngTiersId] FROM tblTiers WHERE [lngTiersId]={}", affaire.strMOeId)):
  315. errors.append(prefix + "Le MOe {} n'existe pas dans tblTiers".format(affaire.strMOeId))
  316. if not affaire.strEntrepriseId:
  317. errors.append(prefix + "Entreprise manquante")
  318. else:
  319. if not commun_db.exists(Sql.format("SELECT [lngTiersId] FROM tblTiers WHERE [lngTiersId]={}", affaire.strEntrepriseId)):
  320. errors.append(prefix + "L'entreprise {} n'existe pas dans tblTiers".format(affaire.strEntrepriseId))
  321. if not affaire.strCommneId:
  322. errors.append(prefix + "Commune manquante")
  323. else:
  324. if not commun_db.exists(Sql.format("SELECT [lngTiersId] FROM tblTiers WHERE [lngTiersId]={}", affaire.strCommneId)):
  325. errors.append(prefix + "La commune {} n'existe pas dans tblTiers".format(affaire.strCommneId))
  326. if not affaire.strTypeId:
  327. errors.append(prefix + "Type d'affaire manquant")
  328. if not affaire.dtmCommande:
  329. errors.append(prefix + "Date de commande manquante")
  330. if affaire.blnMarche == True:
  331. if not affaire.intDevisId:
  332. errors.append(prefix + "Numéro de devis manquant")
  333. if analytique_db.exists(Sql.format("SELECT dblAffaireId FROM tbl_Affaires WHERE [strLiaisonControle]='{}'", affaire.strLiaisonControle)):
  334. errors.append(prefix + "Une affaire portant ce code existe déjà: {}".format(affaire.strLiaisonControle))
  335. for interv in Interv.load_csv(intervs_file):
  336. prefix = "Intervention {}: ".format(interv.strTest)
  337. if not interv.strEquipeId:
  338. errors.append(prefix + "Equipe manquante")
  339. if not interv.strEnginId:
  340. errors.append(prefix + "Engin manquant")
  341. if not interv.strRapportId:
  342. errors.append(prefix + "Rapport manquant")
  343. if not interv.strCatégorieInterventionId:
  344. errors.append(prefix + "Catégorie de l'intervention manquante")
  345. if not interv.strTypeInterventionId:
  346. errors.append(prefix + "Type d'intervention manquant")
  347. if not interv.dblquantite:
  348. errors.append(prefix + "Quantité nulle")
  349. if not interv.strunite:
  350. errors.append(prefix + "Unité non renseignée")
  351. if not interv.dtmIntervention:
  352. errors.append(prefix + "Erreur : date d'intervention")
  353. if not interv.dtmDureeIntervention or interv.dtmDureeIntervention == date_zero:
  354. errors.append(prefix + "Durée d'intervention nulle")
  355. if not interv.strunite:
  356. errors.append(prefix + "Unité non renseignée")
  357. if not engin_existe(interv.strEnginId):
  358. errors.append(prefix + "l'engin {} n'existe pas".format(interv.strEnginId))
  359. # *** 6- Interruption pour corection manuelle des données (si nécessaire)
  360. if errors:
  361. logging.error("<!> Des erreurs ont été détectées dans les données à importer. <!>")
  362. for msg in errors:
  363. logging.error(msg)
  364. if no_prompt:
  365. logger.info("# Annulation de l'import")
  366. sys.exit(1)
  367. else:
  368. logging.info("Aucune erreur n'a été détectée dans les données.")
  369. if no_prompt:
  370. break
  371. # Même si aucune erreur n'a été détectée, on demande un controle visuel.
  372. prompt = ""
  373. while prompt != "v":
  374. 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")
  375. try:
  376. from core import tsv_editor
  377. tsv_editor.exec_(affaires_file.abspath())
  378. tsv_editor.exec_(intervs_file.abspath())
  379. except:
  380. logger.error("Erreur à l'ouverture du fichier %s", affaires_file)
  381. logger.error("Erreur à l'ouverture du fichier %s", intervs_file)
  382. prompt = input("")
  383. if prompt == "f":
  384. break
  385. if prompt == "q":
  386. logger.info("# Annulation de l'import")
  387. sys.exit(1)
  388. # ########## MISE A JOUR DE LA BASE DE DONNEES ANALYTIQUE ##########
  389. # On charge en mémoire les affaires et les interventions
  390. logger.info("# Mise à jour de la base Analytique")
  391. logger.info("> NB: Les modifications ne seront appliquées à la base que si toutes les opérations se déroulent normalement.")
  392. affaires = list(Affaire.load_csv(affaires_file))
  393. intervs = list(Interv.load_csv(intervs_file))
  394. # On insère les affaires, interventions dans Analytique, et on génère la ou les lignes de tarification associées
  395. for affaire in affaires:
  396. # insertion dans tbl_Affaires
  397. sql = Sql.format(""" INSERT INTO tbl_Affaires ( strMOId, strMOeId, strEntrepriseId, strCommneId, strLieux, strTypeId, dtmCommande, Ref,
  398. blnMarche, dblMarche, intTypeContrat, strCT, strLiaisonControle, blnTarification,
  399. blnAnalyse, strSituation, intCoefFG )
  400. VALUES ({affaire.strMOId:text}, {affaire.strMOeId:text}, {affaire.strEntrepriseId:text}, {affaire.strCommneId:text}, {affaire.strLieux:text}, {affaire.strTypeId:text},
  401. {affaire.dtmCommande:date}, {affaire.Ref:text}, {affaire.blnMarche}, {affaire.dblMarche}, {affaire.intTypeContrat}, {affaire.strCT:text},
  402. {affaire.strLiaisonControle:text}, True, False, {affaire.strSituation:text}, {affaire.intCoefFG})
  403. """, affaire=affaire)
  404. analytique_db.execute(sql)
  405. logger.info("> Ajout de l'affaire: {}".format(affaire.strLiaisonControle))
  406. # On insère les interventions dans tbl_Intervention
  407. for interv in intervs:
  408. affaire = analytique_db.first(Sql.format("SELECT TOP 1 DblAffaireId FROM tbl_Affaires WHERE [strLiaisonControle]='{}'", interv.LienAff))
  409. if not affaire:
  410. logger.error("Intervention {} : Impossible de trouver l'affaire {}".format(interv.strTest, interv.LienAff))
  411. continue
  412. interv.dblAffaireId = affaire.DblAffaireId
  413. if not interv.intPeriode:
  414. interv.intPeriode = get_periode_validite(data.dtmIntervDu) # Si la date d'interv manquait avant la validation, la periode n'a pa été mise à jour
  415. sql = Sql.format("""INSERT INTO tbl_Intervention ( DblAffaireId, strEquipeId, strEnginId, strRapportId, strCatégorieInterventionId, strTypeInterventionId,
  416. dblquantite, strunite, dtmIntervention, dtmDureeIntervention, dtmDureeInstallation, strcaracteristique1, strgrandeur1, strunite1,
  417. strcaracteristique2, strgrandeur2, strunite2, strcaracteristique3, strgrandeur3, strunite3, strLiaisonControle, strarticleId,
  418. intPeriode, blnTarification, blnAnalyse, blnFacturer, remarques, blnPeriode, dtmImportation, strTest )
  419. VALUES ({interv.dblAffaireId}, {interv.strEquipeId:text}, {interv.strEnginId:text}, {interv.strRapportId:text}, {interv.strCatégorieInterventionId:text},
  420. {interv.strTypeInterventionId:text}, {interv.dblquantite}, {interv.strunite:text}, {interv.dtmIntervention:date}, {interv.dtmDureeIntervention:date}, {date_zero:date},
  421. {interv.strcaracteristique1:text}, {interv.strgrandeur1:text}, {interv.strunite1:text}, {interv.strcaracteristique2:text},
  422. {interv.strgrandeur2:text}, {interv.strunite2:text}, {interv.strcaracteristique3:text}, {interv.strgrandeur3:text}, {interv.strunite3:text},
  423. {interv.strLiaisonControle:text}, {interv.strArticleId:text}, {interv.intPeriode}, True, False, False, {interv.remarques:text},
  424. False, {interv.dtmImportation:date}, {interv.strTest:text})
  425. """, interv=interv, date_zero=date_zero)
  426. analytique_db.execute(sql)
  427. logger.info("> Ajout de l'intervention: {}".format(interv.strTest))
  428. # Calcul de la tarification et ajout à tbl_Tarification
  429. # > On va créer une ligne de tarification pour chaque groupe d'interventions
  430. # > partageant le même lngRapportid et strArticleId (cad le même engin)
  431. for strRapportId, strArticleId in set([(interv.strRapportId, interv.strArticleId) for interv in intervs]):
  432. tarif = Tarification()
  433. tarif.intervs = [interv for interv in intervs if interv.strRapportId == strRapportId and interv.strArticleId == strArticleId]
  434. # recupere le prix unitaire de l'engin
  435. tarif_engin = commun_db.first(Sql.format("""SELECT dblPU FROM tblTarif WHERE [strArticleId]={:text} AND [intPeriodeValiditeId]={}
  436. """, strArticleId, get_periode_validite(intervs[0].dtmIntervention)))
  437. if not tarif_engin:
  438. logger.error("Aucun tarif trouvé dans tblTarif pour l'article {}, periode {}".format(strArticleId, tarif.intervs[0].intPeriode))
  439. prix_unitaire = tarif_engin.dblPU
  440. # recupere le taux de tva applicable à l'engin
  441. taux_tva = commun_db.first(Sql.format("""SELECT tblTVATaux.dblTVATaux FROM tblArticle INNER JOIN tblTVATaux ON tblArticle.bytTVAArticleId = tblTVATaux.bytTVAId
  442. WHERE tblArticle.strArticleId={:text};""", strArticleId)).dblTVATaux
  443. tarif.DblAffaireId = tarif.intervs[0].dblAffaireId
  444. tarif.strRapportId = strRapportId
  445. tarif.strArticleId = strArticleId
  446. tarif.dblQuantite = sum([float(interv.dblquantite) for interv in tarif.intervs])
  447. tarif.strUnite = tarif.intervs[0].strunite
  448. tarif.dtmDebut = min([interv.dtmIntervention for interv in tarif.intervs])
  449. tarif.dtmFin = max([interv.dtmIntervention for interv in tarif.intervs])
  450. tarif.bytPeriode = tarif.intervs[0].intPeriode
  451. tarif.dblPrixUnitaire = prix_unitaire
  452. tarif.dblPrixTotal = tarif.dblQuantite * tarif.dblPrixUnitaire
  453. tarif.dblTauxTVA = taux_tva
  454. tarif.dblPrixTVA = tarif.dblPrixTotal * (0.01 * tarif.dblTauxTVA)
  455. tarif.strStatut = 'A facturer'
  456. sql = Sql.format(""" INSERT INTO tbl_Tarification ( DblAffaireId, strRapportId, strArticleId, dblQuantite, strUnite, dtmDebut, dtmFin, bytPeriode,
  457. dblPrixUnitaire, dblPrixTotal, dblTauxTVA, dblPrixTVA, strStatut )
  458. VALUES ({tarif.DblAffaireId}, {tarif.strRapportId:text}, {tarif.strArticleId:text}, {tarif.dblQuantite}, {tarif.strUnite:text}, {tarif.dtmDebut:date},
  459. {tarif.dtmFin:date}, {tarif.bytPeriode}, {tarif.dblPrixUnitaire}, {tarif.dblPrixTotal},
  460. {tarif.dblTauxTVA}, {tarif.dblPrixTVA}, {tarif.strStatut:text})
  461. """, tarif=tarif)
  462. analytique_db.execute(sql)
  463. logger.info("> Génération d'une ligne de tarification pour l'affaire {} (rapport {}, article: {})".format(tarif.intervs[0].LienAff, strRapportId, strArticleId))
  464. # Maj champs MOS
  465. # Ces champs sont utilisés dans les tables Controles pour savoir si une ligne a déjà été importée
  466. for affaire in affaires:
  467. dblAffaireId = analytique_db.first(Sql.format("SELECT TOP 1 DblAffaireId FROM tbl_Affaires WHERE [strLiaisonControle]={:text}", affaire.strLiaisonControle)).DblAffaireId
  468. sql = Sql.format("""UPDATE tblCommandes SET tblCommandes.sngAffaireIdMos = {DblAffaireId}
  469. WHERE [lngChantierId]={lngChantierId} AND [bytCommandeId]={bytCommandeId}
  470. """, DblAffaireId=dblAffaireId, lngChantierId=affaire.lngChantierId, bytCommandeId=affaire.bytCommandeId)
  471. controles_db.execute(sql)
  472. for interv in intervs:
  473. if interv.strCatégorieInterventionId == "CC":
  474. tbl = "tblCompactageIntervs"
  475. elif interv.strCatégorieInterventionId == "CE":
  476. tbl = "tblEtancheiteIntervs"
  477. elif interv.strCatégorieInterventionId == "CI":
  478. tbl = "tblVideoIntervs"
  479. else:
  480. continue
  481. sql = Sql.format("""UPDATE {tbl} SET {tbl}.sngIntervIdMos = {DblAffaireId}
  482. WHERE [lngChantierId]={lngChantierId} AND [bytCommandeId]={bytCommandeId} AND [bytIntervId]={bytIntervId}
  483. """, tbl=tbl,
  484. DblAffaireId=interv.dblAffaireId,
  485. lngChantierId=interv.lngChantierId,
  486. bytCommandeId=interv.bytCommandeId,
  487. bytIntervId=interv.bytIntervId)
  488. controles_db.execute(sql)
  489. logger.info("> Mise à jour des champs MOS")
  490. # On commit les modifications
  491. logger.info("Commit des modifications...")
  492. analytique_db.commit()
  493. # ########## MISE A JOUR DES TEMPS D'INSTALLATION ##########
  494. # > Le temps d'installation est le temps passé par chaque agent en transport, préparation, reporting...etc.
  495. # > C'est donc le temps de travail théorique, moins le temps d'intervention.
  496. # > pour des raisons de performances, on ne commence le traitement qu'à partir de l'année N-1
  497. logger.info("Mise à jour des temps d'installation...")
  498. # On parcourt les interventions.
  499. # Lorsque le temps d'intervention total d'une même équipe un même jour est inférieur à 8h,
  500. # On affecte la différence de temps à la première intervention en tant que 'temps d'installation'
  501. sql = Sql.format("""SELECT First(tbl_Intervention.dblInterventionId) AS dblInterventionId, tbl_Intervention.strEquipeId,
  502. tbl_Intervention.dtmIntervention, CDate(Sum(tbl_Intervention.dtmDureeIntervention)) AS SD
  503. FROM tbl_Intervention
  504. WHERE tbl_Intervention.strLiaisonControle Like '%/%'
  505. AND Year([dtmIntervention])>={}
  506. AND tbl_Intervention.dtmDureeIntervention > 0
  507. AND tbl_Intervention.strEquipeId Is Not Null
  508. GROUP BY tbl_Intervention.strEquipeId, tbl_Intervention.dtmIntervention
  509. HAVING (((CDate(Sum(tbl_Intervention.dtmDureeIntervention)))<#1899/12/30 8:0:0#))
  510. """, datetime.now().year - 1)
  511. for interv in analytique_db.read_all(sql):
  512. tps_install = (date_zero + timedelta(hours=8) - interv.SD)
  513. sql = Sql.format("""UPDATE tbl_Intervention SET dtmDureeInstallation = #{}#
  514. WHERE dblInterventionId={}""", date_zero + tps_install, interv.dblInterventionId)
  515. analytique_db.execute(sql)
  516. logger.debug("* Mise à jour du temps d'installation de l'intervention {}".format(interv.dblInterventionId))
  517. logger.info("Commit des modifications...")
  518. analytique_db.commit()
  519. logger.info("# Import terminé")
  520. if __name__ == "__main__":
  521. main()
  522. logger.info("-- Fin --")