gf2analytique.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. '''
  2. Created on 29 juin 2017
  3. @author: olivier.massot
  4. '''
  5. from datetime import datetime
  6. import logging
  7. import re
  8. from path import Path
  9. from core.pde import AnalytiqueDb
  10. from core.webservice import GfWebservice
  11. # TODO: proposer une méthode de correction des erreurs
  12. # TODO: configurer logging
  13. # TODO: envoi mail auto
  14. logger = logging.getLogger("factures")
  15. logging.basicConfig(filename=r'log\factures_{:%Y%m%d_%H%M}.log'.format(datetime.now()),
  16. level=logging.INFO)
  17. logger.info("Initialization")
  18. # Connect to factures.mdb
  19. analytique_db = AnalytiqueDb(autocommit=False)
  20. # Connect to the astre gf webservice
  21. ws = GfWebservice("GetPDEFactures")
  22. workdir = Path(r".\work")
  23. workdir.mkdir_p()
  24. workdir /= "gf2analytique"
  25. workdir.mkdir_p()
  26. errfile = workdir / "err.csv"
  27. class AlreadyImported(Exception):
  28. pass
  29. class NotImported(Exception):
  30. pass
  31. class InvalidData(Exception):
  32. pass
  33. class InvalidAxe(Exception):
  34. pass
  35. class Facture():
  36. def __init__(self):
  37. self._factureId = None
  38. self.numExBudget = None
  39. self.codeColl = None
  40. self.codeBudg = None
  41. self.numEnv = None
  42. self.codeSection = None
  43. self.typeMvt = None
  44. self.numMandat = None
  45. self.numLiqMandat = None
  46. self.numLigneMandat = None
  47. self.codeAxe = None
  48. self.libAxe = None
  49. self.codeCout = None
  50. self.libCout = None
  51. self.dateMandat = None
  52. self.numBj = None
  53. self.numTiers = None
  54. self.libRai = None
  55. self.refIntMandat = None
  56. self.codePeriode = None
  57. self.dateDepDelai = None
  58. self.typeNomencMarche = None
  59. self.mntTtcMandat = None
  60. self.mntTvaMandat = None
  61. self.mntVent = None
  62. @property
  63. def factureId(self):
  64. if self._factureId is None:
  65. try:
  66. self._factureId = self._get_facture_id()
  67. except (KeyError, AttributeError, TypeError):
  68. raise NotImported()
  69. return self._factureId
  70. @classmethod
  71. def from_webservice(cls, wsdata):
  72. facture = cls()
  73. for key, value in wsdata.items():
  74. facture.__dict__[key] = value
  75. facture.autocorrection()
  76. return facture
  77. def is_imported(self):
  78. try:
  79. return self.factureId > 0
  80. except NotImported:
  81. return False
  82. def autocorrection(self):
  83. # correction auto des codes chantiers
  84. if re.match(r"\d{2}5\d{3}", self.codeCout):
  85. self.codeCout += "/1"
  86. self.libRai = self.libRai.replace("'", "''")
  87. def is_valid(self):
  88. """ controle la validité des données d'une facture """
  89. if not int(self.numExBudget) > 2000:
  90. logger.warning("Exercice budgetaire invalide: %s", self.numExBudget)
  91. return False
  92. if self.codeColl != "CG67":
  93. logger.warning("Code collectivité invalide: %s", self.codeColl)
  94. return False
  95. if self.codeBudg != "02":
  96. logger.warning("Code budgetaire invalide: %s", self.codeBudg)
  97. return False
  98. if self.codeAxe == "ENGIN":
  99. # Controle l'existence du materiel
  100. if not analytique_db.first("SELECT intlMaterielID FROM tbl_materiel WHERE txtMateriel='{}'".format(self.codeCout)):
  101. logger.warning("Le materiel n'existe pas: %s", self.codeCout)
  102. return False
  103. elif self.codeAxe == "AFFAI":
  104. # Controle l'existence de l'affaire
  105. if not analytique_db.first("SELECT dblAffaireId FROM tbl_Affaires WHERE strLiaisonControle='{}'".format(self.codeCout)):
  106. logger.warning("L'affaire n'existe pas: %s", self.codeCout)
  107. return False
  108. else:
  109. # CodeAxe invalide
  110. logger.warning("Code axe inconnu: %s", self.codeAxe)
  111. return False
  112. return True
  113. def send_to_db(self):
  114. if self.is_imported():
  115. raise AlreadyImported()
  116. if not self.is_valid():
  117. raise InvalidData()
  118. self._insert_factures()
  119. if self.codeAxe == "ENGIN":
  120. self._insert_factures_engins()
  121. elif self.codeAxe == "AFFAI":
  122. self._insert_factures_affaires()
  123. self._insert_mandatement()
  124. analytique_db.commit()
  125. logger.info("* imported: %s", self.factureId)
  126. def _get_facture_id(self):
  127. sql = """SELECT dblFactureId FROM tbl_Factures
  128. WHERE intExercice = {}
  129. AND strEnveloppe = '{}'
  130. AND strLiquidation = '{}'
  131. AND strAxe = '{}'
  132. AND
  133. ((intLiquidationLigne = {} AND strCentreCout='{}')
  134. OR (intLiquidationLigne IS NULL))
  135. """.format(self.numExBudget,
  136. self.numEnv,
  137. self.numLiqMandat,
  138. self.codeAxe,
  139. self.numLigneMandat,
  140. self.codeCout)
  141. # logger.debug("> %s", sql)
  142. factureId = analytique_db.first(sql)["dblfactureid"]
  143. # logger.debug("retrieve dblFactureId: %s", factureId)
  144. return factureId
  145. def _insert_factures(self):
  146. sql = """INSERT INTO tbl_Factures ( intExercice,
  147. strLiquidation,
  148. intLiquidationLigne,
  149. strEngagement,
  150. strEnveloppe,
  151. strService,
  152. strTiers,
  153. strTiersLibelle,
  154. strMotsClefs,
  155. dtmDeb,
  156. intOperation,
  157. strNomenclature0,
  158. strAXE,
  159. strCentreCout,
  160. strObjet,
  161. dblMontantTotal,
  162. dblMontantTVA,
  163. strORIGINE_DONNEES
  164. )
  165. VALUES ({intExercice},
  166. '{strLiquidation}',
  167. {intLiquidationLigne},
  168. '{strEngagement}',
  169. '{strEnveloppe}',
  170. '{strService}',
  171. '{strTiers}',
  172. '{strTiersLibelle}',
  173. '{strMotsClefs}',
  174. #{dtmDeb}#,
  175. {intOperation},
  176. '{strNomenclature0}',
  177. '{strAxe}',
  178. '{strCentreCout}',
  179. '{strObjet}',
  180. {dblMontantTotal},
  181. {dblMontantTVA},
  182. '{strORIGINE_DONNEES}'
  183. )
  184. """.format(
  185. intExercice=self.numExBudget,
  186. strLiquidation=self.numLiqMandat,
  187. intLiquidationLigne=self.numLigneMandat,
  188. strEngagement=self.numMandat,
  189. strEnveloppe=self.numEnv,
  190. strService='7710',
  191. strTiers=self.numTiers,
  192. strTiersLibelle=self.libRai,
  193. strMotsClefs=AnalytiqueDb.nz(self.refIntMandat),
  194. dtmDeb=AnalytiqueDb.format_date(self.dateDepDelai),
  195. intOperation=AnalytiqueDb.nz(self.codePeriode, "Null"),
  196. strNomenclature0=self.typeNomencMarche,
  197. strAxe=self.codeAxe,
  198. strCentreCout=self.codeCout,
  199. strObjet=AnalytiqueDb.format_date(self.dateMandat, out_format="%d/%m/%Y"),
  200. dblMontantTVA=self.mntTvaMandat,
  201. dblMontantTotal=self.mntVent,
  202. strORIGINE_DONNEES='ASTRE'
  203. )
  204. logger.debug("> %s", sql)
  205. analytique_db.execute(sql)
  206. def _insert_factures_engins(self):
  207. if self.codeAxe != "ENGIN":
  208. raise InvalidAxe()
  209. materiel = analytique_db.first("SELECT intlMaterielID FROM tbl_Materiel WHERE [txtMateriel]='{}'".format(self.codeCout))
  210. materielId = materiel["intlmaterielid"] if materiel else '859'
  211. logger.debug("retrieve intlMaterielID: %s", materielId)
  212. sql = """INSERT INTO tbl_Facture_Engin ( intlMaterielID, txtMateriel, dblFactureId, strLibelle, dblMontant, strType )
  213. VALUES ({}, '{}', {}, '{}', {}, '{}')
  214. """.format(materielId,
  215. self.codeCout,
  216. self.factureId,
  217. AnalytiqueDb.nz(self.libCout),
  218. self.mntVent,
  219. self.libRai
  220. )
  221. logger.debug("> %s", sql)
  222. analytique_db.execute(sql)
  223. def _insert_factures_affaires(self):
  224. if self.codeAxe != "AFFAI":
  225. raise InvalidAxe()
  226. sql = """INSERT INTO tbl_Facture_Affaire ( strAffaireId, dblFactureId, strLibelle, dblMontant, strType )
  227. VALUES ('{}', {}, '{}', {}, '{}')
  228. """.format(self.codeCout,
  229. self.factureId,
  230. self.libRai ,
  231. self.mntVent,
  232. AnalytiqueDb.nz(self.libCout),
  233. )
  234. logger.debug("> %s", sql)
  235. analytique_db.execute(sql)
  236. def _insert_mandatement(self):
  237. sql = """INSERT INTO tbl_Mandatement ( dblFacture, strNumMandat, dtmMandat, strBordereau )
  238. VALUES ({}, '{}', #{}#, '{}')
  239. """.format(self.factureId,
  240. self.numMandat,
  241. AnalytiqueDb.format_date(self.dateMandat),
  242. self.numBj
  243. )
  244. logger.debug("> %s", sql)
  245. analytique_db.execute(sql)
  246. def dump_to_err(self):
  247. fields = ["numExBudget", "numEnv", "numLiqMandat", "codeAxe", "codeCout"]
  248. try:
  249. with open(errfile, 'r') as f:
  250. content = f.read()
  251. except FileNotFoundError:
  252. content = ""
  253. if not content:
  254. line = "\t".join(fields)
  255. with open(errfile, 'a') as f:
  256. f.writelines([line])
  257. line = "\t".join([getattr(self, field) for field in fields])
  258. with open(errfile, 'a') as f:
  259. f.writelines([line])
  260. ########
  261. if __name__ == "__main__":
  262. analysed, updated, errors = 0, 0, 0
  263. for wsdata in ws:
  264. analysed += 1
  265. facture = Facture.from_webservice(wsdata)
  266. try:
  267. facture.send_to_db()
  268. updated += 1
  269. except AlreadyImported:
  270. pass
  271. except InvalidData:
  272. facture.dump_to_err()
  273. errors += 1
  274. logger.info("Import terminé: {} lignes traitées / {} importées / {} erreurs".format(analysed, updated, errors))