gf2analytique.py 13 KB

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