gf2analytique.py 13 KB

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