ctrl2analytique.py 32 KB

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