ctrl2analytique.py 32 KB

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