dolibarr.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/python3
  2. # Style Guide for Python Code https://www.python.org/dev/peps/pep-0008/
  3. # Docstring Conventions https://www.python.org/dev/peps/pep-0257/
  4. import psycopg2.sql as sql # >= 2.7
  5. class Instance:
  6. def __init__(self, conn):
  7. """Create an instance
  8. Arguments:
  9. conn - Database connection (psycopg2)"""
  10. self._conn = conn
  11. self._cur = conn.cursor()
  12. def get_adherent(self, fields=None, extrafields=None, activeonly=True):
  13. if fields is None:
  14. fields = ["firstname", "lastname", "email"]
  15. if extrafields is None:
  16. extrafields = []
  17. if activeonly:
  18. sqlcond = sql.SQL('adh.statut = 1')
  19. else:
  20. sqlcond = sql.SQL('1 = 1')
  21. # Prepare query
  22. sqlfields = [sql.SQL('adh.') + sql.Identifier(a) for a in fields] + [sql.SQL('adhx.') + sql.Identifier(b) for b in extrafields]
  23. sqlfields = sql.SQL(',').join(sqlfields)
  24. sqljoin = sql.SQL('LEFT OUTER JOIN llx_adherent_extrafields AS adhx ON (adh.rowid = adhx.fk_object)')
  25. sqlquery = sql.SQL("SELECT {0} FROM llx_adherent AS adh {1} WHERE {2}").format(sqlfields, sqljoin, sqlcond)
  26. self._cur.execute(sqlquery.as_string(self._cur))
  27. return self._cur
  28. def get_adherent_count(self, activeonly=True):
  29. if activeonly:
  30. sqlcond = sql.SQL('adh.statut = 1')
  31. else:
  32. sqlcond = sql.SQL('1 = 1')
  33. # Prepare query
  34. sqlquery = sql.SQL("SELECT COUNT(*) FROM llx_adherent WHERE {2}").format(sqlcond)
  35. # Execute query
  36. self._cur.execute(sqlquery)
  37. return self._cur.fetchone()[0]
  38. def get_subscriber(self, productRef, fields=None, activeonly=True):
  39. # Prepare query
  40. if fields is None:
  41. fields = ['email']
  42. sqlfields = [sql.SQL('llx_societe.') + sql.Identifier(field) for field in fields]
  43. sqlfields = sql.SQL(',').join(sqlfields)
  44. sqlcond = sql.SQL("""llx_societe.rowid=llx_contrat.fk_soc
  45. AND llx_contrat.rowid=llx_contratdet.fk_contrat
  46. AND llx_product.rowid=llx_contratdet.fk_product
  47. AND llx_product.ref LIKE {0}
  48. AND llx_contratdet.statut=4""").format(sql.Literal(productRef))
  49. if activeonly:
  50. sqlcond += sql.SQL('AND llx_contrat.statut=1')
  51. sqlquery = sql.SQL("""SELECT {0}
  52. FROM llx_societe, llx_contrat, llx_contratdet, llx_product
  53. WHERE {1}
  54. ORDER BY llx_product.ref, llx_contrat.rowid ASC""").format(sqlfields, sqlcond)
  55. self._cur.execute(sqlquery.as_string(self._cur))
  56. return self._cur
  57. def get_bank_accounts(self, fields=None):
  58. # Prepare query
  59. if fields is None:
  60. fields = ['bank', 'proprio', 'iban_prefix']
  61. sqlquery = sql.SQL('SELECT {0} FROM llx_bank_account WHERE courant = 1 AND clos = 0'.format(','.join(fields)))
  62. self._cur.execute(sqlquery.as_string(self._cur))
  63. return self._cur