Browse Source

maj fcn-dolibarr, ajout du paquet python 'fcntoolbox'

Guillaume 7 years ago
parent
commit
64a909fe0d
5 changed files with 123 additions and 24 deletions
  1. 10 24
      fcn-dolibarr
  2. 0 0
      fcntoolbox/__init__.py
  3. 62 0
      fcntoolbox/dolibarr.py
  4. 32 0
      fcntoolbox/mail.py
  5. 19 0
      fcntoolbox/sympa.py

+ 10 - 24
fcn-dolibarr

@@ -3,13 +3,14 @@
 import argparse
 import configparser
 import psycopg2
+import fcntoolbox.dolibarr as dolibarr
 
 parser = argparse.ArgumentParser()
 
 parser.add_argument("selection", type=str,
-                    choices=["get-subscribers"])
+                    choices=["get-adherents", "get-subscribers"])
 parser.add_argument("-c", "--config", type=str,
-                    default="/etc/fcn-toolbox/config.ini",
+                    default="/etc/fcntoolbox/config.ini",
                     help="specify a configuration file")
 parser.add_argument("--product", type=str,
                     default="%",
@@ -22,28 +23,13 @@ config.read(args.config)
 configdb = config['database']
 
 conn = psycopg2.connect(database=configdb['database'],
-  user=configdb['user'], password=configdb['password'])
+  user=configdb['user'], password=configdb['password'], host=configdb['host'])
 
-cur = conn.cursor()
+doli = dolibarr.Instance(conn)
 
-def getMemberCount():
-  cur.execute("SELECT count(*) FROM llx_adherent WHERE statut = '1'")
-  return cur.fetchone()[0]
-
-def getSubscriberInfo(product, fields):
-  fieldsel = ','.join(fields)
-  cur.execute("""SELECT %s
-    FROM llx_societe, llx_contrat, llx_contratdet, llx_product
-    WHERE llx_societe.rowid=llx_contrat.fk_soc
-        AND llx_contrat.rowid=llx_contratdet.fk_contrat
-        AND llx_product.rowid=llx_contratdet.fk_product
-        AND llx_product.ref LIKE %s
-        AND llx_contrat.statut=1
-        AND llx_contratdet.statut=4
-    ORDER BY llx_product.ref, llx_contrat.rowid ASC;""" % (fieldsel, '%s'), (product, ))
-  return cur.fetchall()
-
-
-if args.selection == "get-subscribers":
-  subscribers = getSubscriberInfo(args.product, ['llx_societe.email'])
+if args.selection == "get-adherents":
+  adherents = doli.get_adherent(fields = ['email'])
+  print("\n".join(map(lambda x: x[0], adherents)))
+elif args.selection == "get-subscribers":
+  subscribers = doli.get_subscriber(args.product, ['email'])
   print("\n".join(map(lambda x: x[0], subscribers)))

+ 0 - 0
fcntoolbox/__init__.py


+ 62 - 0
fcntoolbox/dolibarr.py

@@ -0,0 +1,62 @@
+#!/usr/bin/python3
+# Style Guide for Python Code https://www.python.org/dev/peps/pep-0008/
+# Docstring Conventions https://www.python.org/dev/peps/pep-0257/
+
+import psycopg2.sql as sql # >= 2.7
+
+class Instance:
+  def __init__(self, conn):
+    """Create an instance
+    
+    Arguments:
+    conn - Database connection (psycopg2)"""
+    self._conn = conn
+    self._cur = conn.cursor()
+  
+  def get_adherent(self, fields=None, extrafields=None, activeonly=True):
+    if fields is None:
+      fields = ["firstname", "lastname", "email"]
+    if extrafields is None:
+      extrafields = []
+    if activeonly:
+      sqlcond = sql.SQL('adh.statut = 1')
+    else:
+      sqlcond = sql.SQL('1 = 1')
+    # Prepare query
+    sqlfields = [sql.SQL('adh.') + sql.Identifier(a) for a in fields] + [sql.SQL('adhx.') + sql.Identifier(b) for b in extrafields]
+    sqlfields = sql.SQL(',').join(sqlfields)
+    sqljoin = sql.SQL('LEFT OUTER JOIN llx_adherent_extrafields AS adhx ON (adh.rowid = adhx.fk_object)')
+    sqlquery = sql.SQL("SELECT {0} FROM llx_adherent AS adh {1} WHERE {2}").format(sqlfields, sqljoin, sqlcond)
+    self._cur.execute(sqlquery)
+    return self._cur
+  
+  def get_adherent_count(self, activeonly=True):
+    if activeonly:
+      sqlcond = sql.SQL('adh.statut = 1')
+    else:
+      sqlcond = sql.SQL('1 = 1')
+    # Prepare query
+    sqlquery = sql.SQL("SELECT COUNT(*) FROM llx_adherent WHERE {2}").format(sqlcond)
+    # Execute query
+    self._cur.execute(sqlquery)
+    return self._cur.fetchone()[0]
+  
+  def get_subscriber(self, productRef, fields=None, activeonly=True):
+    # Prepare query
+    if fields is None:
+      fields = ['email']
+    sqlfields = [sql.SQL('llx_societe.') + sql.Identifier(field) for field in fields]
+    sqlfields = sql.SQL(',').join(sqlfields)
+    sqlcond = sql.SQL("""llx_societe.rowid=llx_contrat.fk_soc
+        AND llx_contrat.rowid=llx_contratdet.fk_contrat
+        AND llx_product.rowid=llx_contratdet.fk_product
+        AND llx_product.ref LIKE {0}
+        AND llx_contratdet.statut=4""").format(sql.Literal(productRef))
+    if activeonly:
+      sqlcond += sql.SQL('AND llx_contrat.statut=1')
+    sqlquery = sql.SQL("""SELECT {0}
+    FROM llx_societe, llx_contrat, llx_contratdet, llx_product
+    WHERE {1}
+    ORDER BY llx_product.ref, llx_contrat.rowid ASC""").format(sqlfields, sqlcond)
+    self._cur.execute(sqlquery)
+    return self._cur

+ 32 - 0
fcntoolbox/mail.py

@@ -0,0 +1,32 @@
+#!/usr/bin/python3
+# Style Guide for Python Code https://www.python.org/dev/peps/pep-0008/
+# Docstring Conventions https://www.python.org/dev/peps/pep-0257/
+
+import re
+
+class Aliases:
+  def __init__(self, filename, domain):
+    self.filename = filename
+    self.aliases = dict()
+    self.domain = domain.lower()
+    with open(self.filename, "r") as f:
+      for line in f: 
+        match = re.search('^([^#:]+):([^#:]+)(?:#.*|)$', line)
+        if match: 
+          alias = match.group(1).strip() + '@' + self.domain
+          to = match.group(2).strip()
+          if '@' in to:
+            self.aliases[alias] = to
+          else:
+            self.aliases[alias] = to + '@' + self.domain
+  def get_alias(self, key):
+    return self.aliases[key.lower()]
+  def get_aliases(self):
+    return self.aliases
+  def __contains__(self, key):
+    return key.lower() in self.aliases
+  def __getitem__(self, key):
+    return self.aliases[key.lower()]
+  def items(self):
+    return self.aliases.items()
+

+ 19 - 0
fcntoolbox/sympa.py

@@ -0,0 +1,19 @@
+#!/usr/bin/python3
+# Style Guide for Python Code https://www.python.org/dev/peps/pep-0008/
+# Docstring Conventions https://www.python.org/dev/peps/pep-0257/
+
+# Based upon:
+# https://www.sympa.org/distribution/contrib/sympa_extract.pl
+
+class Instance:
+  def __init__(self, conn):
+    self._conn = conn
+  def get_subscribers(self, list, robot):
+    rows = ["user_subscriber", "list_subscriber"]
+    cur = self._conn.cursor()
+    cur.execute("""SELECT %s FROM subscriber_table WHERE list_subscriber LIKE %%s AND robot_subscriber LIKE %%s""" % (",".join(rows)) , (list, robot))
+    subscribers = []
+    for item in cur:
+      email = item[0].lower()
+      subscribers.append(email)
+    return subscribers