gf2analytique.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. '''
  2. Script d'import des données de facturation depuis
  3. la base de données ASTRE-GF vers les tables de la base Analytique
  4. du Parc Départemental d'Erstein
  5. En cas d'erreur avec les données importées:
  6. 1. une tentative d'autocorrection est effectuée
  7. 2. Si les données sont toujours invalides, une ligne est ajoutée au fichier .\\work\\gf2analytique\\err.csv
  8. pour une correction manuelle.
  9. IMPORTANT: Si le fichier 'err.csv' contient des lignes, le script tentera d'importer
  10. ces lignes à la place de celles issues de Astre Gf.
  11. Pour forcer un imprt depuis AstreGf, supprimez le fichier 'err.csv'
  12. Info: Les données sont obtenues via le web service CG67.AstreGf
  13. '''
  14. import logging
  15. import re
  16. from core import logconf
  17. from core.pde import AnalytiqueDb, mk_workdir
  18. from core.webservice import GfWebservice
  19. # TODO: envoi mail auto
  20. logger = logging.getLogger("gf2analytique")
  21. logconf.start("gf2analytique", logging.INFO)
  22. logger.info("Initialization")
  23. # Connect to factures.mdb
  24. analytique_db = AnalytiqueDb(autocommit=False)
  25. # Connect to the astre gf webservice
  26. ws = GfWebservice("GetPDEFactures")
  27. # Make the working directory
  28. workdir = mk_workdir("gf2analytique")
  29. errfile = workdir / "err.csv"
  30. class AlreadyImported(Exception):
  31. pass
  32. class NotImported(Exception):
  33. pass
  34. class InvalidData(Exception):
  35. pass
  36. class InvalidAxe(Exception):
  37. pass
  38. class Facture():
  39. WS_FIELDS = ["numExBudget", "codeColl", "codeBudg", "numEnv", "codeSection", "typeMvt", "numMandat", "numLiqMandat",
  40. "numLigneMandat", "codeAxe", "libAxe", "codeCout", "libCout", "dateMandat", "numBj", "numTiers",
  41. "libRai", "refIntMandat", "codePeriode", "dateDepDelai", "typeNomencMarche", "mntTtcMandat",
  42. "mntTvaMandat", "mntVent"]
  43. def __init__(self):
  44. self._factureId = None
  45. for fld in self.WS_FIELDS:
  46. setattr(self, fld, None)
  47. @property
  48. def factureId(self):
  49. if self._factureId is None:
  50. try:
  51. self._factureId = self._get_facture_id()
  52. except (KeyError, AttributeError, TypeError):
  53. raise NotImported()
  54. return self._factureId
  55. @classmethod
  56. def from_webservice(cls, wsdata):
  57. facture = cls()
  58. for key, value in wsdata.items():
  59. setattr(facture, key, value)
  60. # facture.__dict__[key] = value
  61. facture.autocorrection()
  62. return facture
  63. @classmethod
  64. def from_errfile(cls, line):
  65. return cls.from_webservice(dict(zip(cls.WS_FIELDS, line.split("\t"))))
  66. def is_imported(self):
  67. try:
  68. return self.factureId > 0
  69. except NotImported:
  70. return False
  71. def _init_errfile(self):
  72. try:
  73. with open(errfile, 'r') as f:
  74. if f.read(100):
  75. # File already exists and is not empty
  76. return
  77. except FileNotFoundError:
  78. pass
  79. firstline = "\t".join(self.WS_FIELDS + ["\n"])
  80. with open(errfile, 'a') as f:
  81. f.write(firstline)
  82. def dump_to_err(self):
  83. self._init_errfile()
  84. line = "\t".join([str(getattr(self, field)).replace("\t", " ") for field in self.WS_FIELDS] + ["\n"])
  85. with open(errfile, 'a') as f:
  86. f.write(line)
  87. def autocorrection(self):
  88. # correction auto des codes chantiers
  89. if self.codeAxe == "AFFAI" and re.match(r"\d{2}5\d{3}", self.codeCout):
  90. self.codeCout += "/1"
  91. # echappe les apostrophes
  92. self.libRai = self.libRai.replace("'", "''")
  93. # renomme automatiquement les noms de materiels
  94. if self.codeAxe == "ENGIN":
  95. row = analytique_db.first("""SELECT txtMateriel FROM tbl_materiel
  96. WHERE txtMateriel='{codeCout}' or txtMateriel='ZZ {codeCout}'
  97. """.format(codeCout=self.codeCout))
  98. if row:
  99. self.codeCout = row["txtmateriel"]
  100. def is_valid(self):
  101. """ controle la validité des données d'une facture """
  102. if not int(self.numExBudget) > 2000:
  103. logger.warning("Exercice budgetaire invalide: %s", self.numExBudget)
  104. return False
  105. if self.codeColl != "CG67":
  106. logger.warning("Code collectivité invalide: %s", self.codeColl)
  107. return False
  108. if self.codeBudg != "02":
  109. logger.warning("Code budgetaire invalide: %s", self.codeBudg)
  110. return False
  111. if self.codeAxe == "ENGIN":
  112. # Controle l'existence du materiel
  113. if not analytique_db.first("SELECT intlMaterielID FROM tbl_materiel WHERE txtMateriel='{}'".format(self.codeCout)):
  114. logger.warning("Le materiel n'existe pas: %s", self.codeCout)
  115. return False
  116. elif self.codeAxe == "AFFAI":
  117. # Controle l'existence de l'affaire
  118. if not analytique_db.first("SELECT dblAffaireId FROM tbl_Affaires WHERE strLiaisonControle='{}'".format(self.codeCout)):
  119. logger.warning("L'affaire n'existe pas: %s", self.codeCout)
  120. return False
  121. else:
  122. # CodeAxe invalide
  123. logger.warning("Code axe inconnu: %s", self.codeAxe)
  124. return False
  125. return True
  126. def send_to_db(self):
  127. if self.is_imported():
  128. raise AlreadyImported()
  129. if not self.is_valid():
  130. raise InvalidData()
  131. self._insert_factures()
  132. if self.codeAxe == "ENGIN":
  133. self._insert_factures_engins()
  134. elif self.codeAxe == "AFFAI":
  135. self._insert_factures_affaires()
  136. self._insert_mandatement()
  137. analytique_db.commit()
  138. logger.info("* imported: %s", self.factureId)
  139. def _get_facture_id(self):
  140. sql = """SELECT dblFactureId FROM tbl_Factures
  141. WHERE intExercice = {}
  142. AND strEnveloppe = '{}'
  143. AND strLiquidation = '{}'
  144. AND strAxe = '{}'
  145. AND
  146. ((intLiquidationLigne = {} AND strCentreCout='{}')
  147. OR (intLiquidationLigne IS NULL))
  148. """.format(self.numExBudget,
  149. self.numEnv,
  150. self.numLiqMandat,
  151. self.codeAxe,
  152. self.numLigneMandat,
  153. self.codeCout)
  154. # logger.debug("> %s", sql)
  155. factureId = analytique_db.first(sql)["dblfactureid"]
  156. # logger.debug("retrieve dblFactureId: %s", factureId)
  157. return factureId
  158. def _insert_factures(self):
  159. sql = """INSERT INTO tbl_Factures ( intExercice,
  160. strLiquidation,
  161. intLiquidationLigne,
  162. strEngagement,
  163. strEnveloppe,
  164. strService,
  165. strTiers,
  166. strTiersLibelle,
  167. strMotsClefs,
  168. dtmDeb,
  169. intOperation,
  170. strNomenclature0,
  171. strAXE,
  172. strCentreCout,
  173. strObjet,
  174. dblMontantTotal,
  175. dblMontantTVA,
  176. strORIGINE_DONNEES
  177. )
  178. VALUES ({intExercice},
  179. '{strLiquidation}',
  180. {intLiquidationLigne},
  181. '{strEngagement}',
  182. '{strEnveloppe}',
  183. '{strService}',
  184. '{strTiers}',
  185. '{strTiersLibelle}',
  186. '{strMotsClefs}',
  187. #{dtmDeb}#,
  188. {intOperation},
  189. '{strNomenclature0}',
  190. '{strAxe}',
  191. '{strCentreCout}',
  192. '{strObjet}',
  193. {dblMontantTotal},
  194. {dblMontantTVA},
  195. '{strORIGINE_DONNEES}'
  196. )
  197. """.format(
  198. intExercice=self.numExBudget,
  199. strLiquidation=self.numLiqMandat,
  200. intLiquidationLigne=self.numLigneMandat,
  201. strEngagement=self.numMandat,
  202. strEnveloppe=self.numEnv,
  203. strService='7710',
  204. strTiers=self.numTiers,
  205. strTiersLibelle=self.libRai,
  206. strMotsClefs=AnalytiqueDb.nz(self.refIntMandat),
  207. dtmDeb=AnalytiqueDb.format_date(self.dateDepDelai),
  208. intOperation=AnalytiqueDb.nz(self.codePeriode, "Null"),
  209. strNomenclature0=self.typeNomencMarche,
  210. strAxe=self.codeAxe,
  211. strCentreCout=self.codeCout,
  212. strObjet=AnalytiqueDb.format_date(self.dateMandat, out_format="%d/%m/%Y"),
  213. dblMontantTVA=self.mntTvaMandat,
  214. dblMontantTotal=self.mntVent,
  215. strORIGINE_DONNEES='ASTRE'
  216. )
  217. logger.debug("> %s", sql)
  218. analytique_db.execute(sql)
  219. def _insert_factures_engins(self):
  220. if self.codeAxe != "ENGIN":
  221. raise InvalidAxe()
  222. materiel = analytique_db.first("SELECT intlMaterielID FROM tbl_Materiel WHERE [txtMateriel]='{}'".format(self.codeCout))
  223. materielId = materiel["intlmaterielid"] if materiel else '859'
  224. logger.debug("retrieve intlMaterielID: %s", materielId)
  225. sql = """INSERT INTO tbl_Facture_Engin ( intlMaterielID, txtMateriel, dblFactureId, strLibelle, dblMontant, strType )
  226. VALUES ({}, '{}', {}, '{}', {}, '{}')
  227. """.format(materielId,
  228. self.codeCout,
  229. self.factureId,
  230. AnalytiqueDb.nz(self.libCout),
  231. self.mntVent,
  232. self.libRai
  233. )
  234. logger.debug("> %s", sql)
  235. analytique_db.execute(sql)
  236. def _insert_factures_affaires(self):
  237. if self.codeAxe != "AFFAI":
  238. raise InvalidAxe()
  239. sql = """INSERT INTO tbl_Facture_Affaire ( strAffaireId, dblFactureId, strLibelle, dblMontant, strType )
  240. VALUES ('{}', {}, '{}', {}, '{}')
  241. """.format(self.codeCout,
  242. self.factureId,
  243. self.libRai ,
  244. self.mntVent,
  245. AnalytiqueDb.nz(self.libCout),
  246. )
  247. logger.debug("> %s", sql)
  248. analytique_db.execute(sql)
  249. def _insert_mandatement(self):
  250. sql = """INSERT INTO tbl_Mandatement ( dblFacture, strNumMandat, dtmMandat, strBordereau )
  251. VALUES ({}, '{}', #{}#, '{}')
  252. """.format(self.factureId,
  253. self.numMandat,
  254. AnalytiqueDb.format_date(self.dateMandat),
  255. self.numBj
  256. )
  257. logger.debug("> %s", sql)
  258. analytique_db.execute(sql)
  259. @staticmethod
  260. def load_errfile_data():
  261. factures = []
  262. try:
  263. firstline = True
  264. with open(errfile, "r") as f:
  265. for line in f:
  266. if firstline:
  267. firstline = False
  268. continue
  269. facture = Facture.from_errfile(line)
  270. factures.append(facture)
  271. except FileNotFoundError:
  272. pass
  273. return factures
  274. @staticmethod
  275. def process(factures):
  276. analysed, updated, errors = 0, 0, 0
  277. for facture in factures:
  278. analysed += 1
  279. try:
  280. facture.send_to_db()
  281. updated += 1
  282. except AlreadyImported:
  283. pass
  284. except InvalidData:
  285. facture.dump_to_err()
  286. errors += 1
  287. return analysed, updated, errors
  288. ########
  289. if __name__ == "__main__":
  290. to_retry = Facture.load_errfile_data()
  291. errfile.remove_p()
  292. if to_retry:
  293. logger.info("# Ré-import depuis le fichier d'erreurs")
  294. logger.info("{} lignes chargées depuis {}".format(len(to_retry), errfile))
  295. res = Facture.process(to_retry)
  296. logger.info("> {} lignes traitées / {} importées / {} erreurs".format(res[0], res[1], res[2]))
  297. else:
  298. logger.info("# Import depuis Astre-Gf")
  299. res = Facture.process([Facture.from_webservice(wsdata) for wsdata in ws])
  300. logger.info("> {} lignes traitées / {} importées / {} erreurs".format(res[0], res[1], res[2]))