[IMP] moved openerpweb into base.common to be renamed web.commom
[odoo/odoo.git] / addons / base_action_rule / base_action_rule.py
index ff6321e..2db23e7 100644 (file)
@@ -29,13 +29,18 @@ import re
 import time
 import tools
 
+
+def get_datetime(date_field):
+    return datetime.strptime(date_field[:19], '%Y-%m-%d %H:%M:%S')
+
+
 class base_action_rule(osv.osv):
     """ Base Action Rules """
 
     _name = 'base.action.rule'
     _description = 'Action Rules'
     
-    def _state_get(self, cr, uid, context={}):
+    def _state_get(self, cr, uid, context=None):
         """ Get State
             @param self: The object pointer
             @param cr: the current row, from the database cursor,
@@ -43,7 +48,7 @@ class base_action_rule(osv.osv):
             @param context: A standard dictionary for contextual values """
         return self.state_get(cr, uid, context=context)
 
-    def state_get(self, cr, uid, context={}):
+    def state_get(self, cr, uid, context=None):
         """ Get State
             @param self: The object pointer
             @param cr: the current row, from the database cursor,
@@ -51,7 +56,7 @@ class base_action_rule(osv.osv):
             @param context: A standard dictionary for contextual values """
         return [('', '')]
   
-    def priority_get(self, cr, uid, context={}):
+    def priority_get(self, cr, uid, context=None):
         """ Get Priority
             @param self: The object pointer
             @param cr: the current row, from the database cursor,
@@ -113,6 +118,9 @@ the rule to mark CC(mail to any other person defined in actions)."),
         'filter_id':fields.many2one('ir.filters', 'Filter', required=False), 
         'act_email_from' : fields.char('Email From', size=64, required=False,
                 help="Use a python expression to specify the right field on which one than we will use for the 'From' field of the header"),
+        'act_email_to' : fields.char('Email To', size=64, required=False,
+                                     help="Use a python expression to specify the right field on which one than we will use for the 'To' field of the header"),
+        'last_run': fields.datetime('Last Run', readonly=1),
     }
 
     _defaults = {
@@ -143,7 +151,7 @@ the rule to mark CC(mail to any other person defined in actions)."),
         # Searching for action rules
         cr.execute("SELECT model.model, rule.id  FROM base_action_rule rule \
                         LEFT JOIN ir_model model on (model.id = rule.model_id) \
-                        where active")
+                        WHERE active")
         res = cr.fetchall()
         # Check if any rule matching with current object
         for obj_name, rule_id in res:
@@ -151,11 +159,14 @@ the rule to mark CC(mail to any other person defined in actions)."),
                 continue
             else:
                 obj = self.pool.get(obj_name)
-                self._action(cr, uid, [rule_id], obj.browse(cr, uid, ids, context=context), context=context)
+                # If the rule doesn't involve a time condition, run it immediately
+                # Otherwise we let the scheduler run the action
+                if self.browse(cr, uid, rule_id, context=context).trg_date_type == 'none':
+                    self._action(cr, uid, [rule_id], obj.browse(cr, uid, ids, context=context), context=context)
         return True
 
     def _create(self, old_create, model, context=None):
-        if not context:
+        if context is None:
             context  = {}
         def make_call_old(cr, uid, vals, context=context):
             new_id = old_create(cr, uid, vals, context=context)
@@ -165,9 +176,11 @@ the rule to mark CC(mail to any other person defined in actions)."),
         return make_call_old
     
     def _write(self, old_write, model, context=None):
-        if not context:
+        if context is None:
             context  = {}
         def make_call_old(cr, uid, ids, vals, context=context):
+            if context is None:
+               context = {}
             if isinstance(ids, (str, int, long)):
                 ids = [ids]
             if not context.get('action'):
@@ -176,7 +189,7 @@ the rule to mark CC(mail to any other person defined in actions)."),
         return make_call_old
 
     def _register_hook(self, cr, uid, ids, context=None):
-        if not context:
+        if context is None:
             context = {}
         for action_rule in self.browse(cr, uid, ids, context=context):
             model = action_rule.model_id.model
@@ -188,12 +201,12 @@ the rule to mark CC(mail to any other person defined in actions)."),
 
         return True
     def create(self, cr, uid, vals, context=None):
-        res_id = super(base_action_rule, self).create(cr, uid, vals, context)
+        res_id = super(base_action_rule, self).create(cr, uid, vals, context=context)
         self._register_hook(cr, uid, [res_id], context=context)        
         return res_id
     
     def write(self, cr, uid, ids, vals, context=None):
-        res = super(base_action_rule, self).write(cr, uid, ids, vals, context)
+        res = super(base_action_rule, self).write(cr, uid, ids, vals, context=context)
         self._register_hook(cr, uid, ids, context=context)
         return res
 
@@ -204,8 +217,50 @@ the rule to mark CC(mail to any other person defined in actions)."),
         """
         rule_pool = self.pool.get('base.action.rule')
         rule_ids = rule_pool.search(cr, uid, [], context=context)
-        return self._register_hook(cr, uid, rule_ids, context=context)
-        
+        self._register_hook(cr, uid, rule_ids, context=context)
+
+        rules = self.browse(cr, uid, rule_ids, context=context)
+        for rule in rules:
+            model = rule.model_id.model
+            model_pool = self.pool.get(model)
+            last_run = False
+            if rule.last_run:
+                last_run = get_datetime(rule.last_run)
+            now = datetime.now()
+            for obj_id in model_pool.search(cr, uid, [], context=context):
+                obj = model_pool.browse(cr, uid, obj_id, context=context)
+                # Calculate when this action should next occur for this object
+                base = False
+                if rule.trg_date_type=='create' and hasattr(obj, 'create_date'):
+                    base = obj.create_date
+                elif (rule.trg_date_type=='action_last'
+                        and hasattr(obj, 'create_date')):
+                    if hasattr(obj, 'date_action_last') and obj.date_action_last:
+                        base = obj.date_action_last
+                    else:
+                        base = obj.create_date
+                elif (rule.trg_date_type=='deadline'
+                        and hasattr(obj, 'date_deadline')
+                        and obj.date_deadline):
+                    base = obj.date_deadline
+                elif (rule.trg_date_type=='date'
+                        and hasattr(obj, 'date')
+                        and obj.date):
+                    base = obj.date
+                if base:
+                    fnct = {
+                        'minutes': lambda interval: timedelta(minutes=interval),
+                        'day': lambda interval: timedelta(days=interval),
+                        'hour': lambda interval: timedelta(hours=interval),
+                        'month': lambda interval: timedelta(months=interval),
+                    }
+                    base = get_datetime(base)
+                    delay = fnct[rule.trg_date_range_type](rule.trg_date_range)
+                    action_date = base + delay
+                    if (not last_run or (last_run <= action_date < now)):
+                        self._action(cr, uid, [rule.id], [obj], context=context)
+            rule_pool.write(cr, uid, [rule.id], {'last_run': now},
+                            context=context)
 
     def format_body(self, body):
         """ Foramat Action rule's body
@@ -223,9 +278,9 @@ the rule to mark CC(mail to any other person defined in actions)."),
             'object_description': hasattr(obj, 'description') and obj.description or False, 
             'object_user': hasattr(obj, 'user_id') and (obj.user_id and obj.user_id.name) or '/', 
             'object_user_email': hasattr(obj, 'user_id') and (obj.user_id and \
-                                    obj.user_id.address_id and obj.user_id.address_id.email) or '/', 
-            'object_user_phone': hasattr(obj, 'user_id') and (obj.user_id and\
-                                     obj.user_id.address_id and obj.user_id.address_id.phone) or '/', 
+                                     obj.user_id.user_email) or '/',
+            'object_user_phone': hasattr(obj, 'partner_address_id') and (obj.partner_address_id and \
+                                     obj.partner_address_id.phone) or '/',
             'partner': hasattr(obj, 'partner_id') and (obj.partner_id and obj.partner_id.name) or '/', 
             'partner_email': hasattr(obj, 'partner_address_id') and (obj.partner_address_id and\
                                          obj.partner_address_id.email) or '/', 
@@ -249,9 +304,8 @@ the rule to mark CC(mail to any other person defined in actions)."),
 
         body = self.format_mail(obj, body)
         if not emailfrom:
-            if hasattr(obj, 'user_id')  and obj.user_id and obj.user_id.address_id and\
-                        obj.user_id.address_id.email:
-                emailfrom = obj.user_id.address_id.email
+            if hasattr(obj, 'user_id') and obj.user_id and obj.user_id.user_email:
+                emailfrom = obj.user_id.user_email
 
         name = '[%d] %s' % (obj.id, tools.ustr(obj.name))
         emailfrom = tools.ustr(emailfrom)
@@ -349,21 +403,33 @@ the rule to mark CC(mail to any other person defined in actions)."),
 
         emails = []
         if hasattr(obj, 'user_id') and action.act_mail_to_user:
-            if obj.user_id and obj.user_id.address_id:
-                emails.append(obj.user_id.address_id.email)
+            if obj.user_id:
+                emails.append(obj.user_id.user_email)
 
         if action.act_mail_to_watchers:
             emails += (action.act_email_cc or '').split(',')
         if action.act_mail_to_email:
             emails += (action.act_mail_to_email or '').split(',')
+
+        locals_for_emails = {
+            'user' : self.pool.get('res.users').browse(cr, uid, uid, context=context),
+            'obj' : obj,
+        }
+
+        if action.act_email_to:
+            emails.append(safe_eval(action.act_email_to, {}, locals_for_emails))
+
         emails = filter(None, emails)
         if len(emails) and action.act_mail_body:
             emails = list(set(emails))
-            email_from = safe_eval(action.act_email_from, {}, {
-                'user' : self.pool.get('res.users').browse(cr, uid, uid, context=context),
-                'obj' : obj,
-            })
-            self.email_send(cr, uid, obj, emails, action.act_mail_body, emailfrom=email_from)
+            email_from = safe_eval(action.act_email_from, {}, locals_for_emails)
+
+            def to_email(text):
+                return re.findall(r'([^ ,<@]+@[^> ,]+)', text or '')
+            emails = to_email(','.join(filter(None, emails)))
+            email_froms = to_email(email_from)
+            if email_froms:
+                self.email_send(cr, uid, obj, emails, action.act_mail_body, emailfrom=email_froms[0])
         return True
 
     def _action(self, cr, uid, ids, objects, scrit=None, context=None):
@@ -377,53 +443,17 @@ the rule to mark CC(mail to any other person defined in actions)."),
         if context is None:
             context = {}
 
-
         context.update({'action': True})
         if not scrit:
             scrit = []
 
-        for action in self.browse(cr, uid, ids, context):
+        for action in self.browse(cr, uid, ids, context=context):
             model_obj = self.pool.get(action.model_id.model)
             for obj in objects:
                 ok = self.do_check(cr, uid, action, obj, context=context)
                 if not ok:
                     continue
 
-                base = False
-                if action.trg_date_type=='create' and hasattr(obj, 'create_date'):
-                    base = datetime.strptime(obj.create_date[:19], '%Y-%m-%d %H:%M:%S')
-                elif action.trg_date_type=='action_last' and hasattr(obj, 'create_date'):
-                    if hasattr(obj, 'date_action_last') and obj.date_action_last:
-                        base = datetime.strptime(obj.date_action_last, '%Y-%m-%d %H:%M:%S')
-                    else:
-                        base = datetime.strptime(obj.create_date[:19], '%Y-%m-%d %H:%M:%S')
-                elif action.trg_date_type=='deadline' and hasattr(obj, 'date_deadline') \
-                                and obj.date_deadline:
-                    base = datetime.strptime(obj.date_deadline, '%Y-%m-%d %H:%M:%S')
-                elif action.trg_date_type=='date' and hasattr(obj, 'date') and obj.date:
-                    base = datetime.strptime(obj.date, '%Y-%m-%d %H:%M:%S')
-                if base:
-                    fnct = {
-                        'minutes': lambda interval: timedelta(minutes=interval), 
-                        'day': lambda interval: timedelta(days=interval), 
-                        'hour': lambda interval: timedelta(hours=interval), 
-                        'month': lambda interval: timedelta(months=interval), 
-                    }
-                    d = base + fnct[action.trg_date_range_type](action.trg_date_range)
-                    dt = d.strftime('%Y-%m-%d %H:%M:%S')
-                    ok = False
-                    if hasattr(obj, 'date_action_last') and hasattr(obj, 'date_action_next'):
-                        ok = (dt <= time.strftime('%Y-%m-%d %H:%M:%S')) and \
-                                ((not obj.date_action_next) or \
-                                (dt >= obj.date_action_next and \
-                                obj.date_action_last < obj.date_action_next))
-                        if not ok:
-                            if not obj.date_action_next or dt < obj.date_action_next:
-                                obj.date_action_next = dt
-                                model_obj.write(cr, uid, [obj.id], {'date_action_next': dt}, context)
-                else:
-                    ok = action.trg_date_type == 'none'
-
                 if ok:
                     self.do_action(cr, uid, action, model_obj, obj, context)
                     break
@@ -440,7 +470,7 @@ the rule to mark CC(mail to any other person defined in actions)."),
 
         empty = orm.browse_null()
         rule_obj = self.pool.get('base.action.rule')
-        for rule in self.browse(cr, uid, ids):
+        for rule in self.browse(cr, uid, ids, context=context):
             if rule.act_mail_body:
                 try:
                     rule_obj.format_mail(empty, rule.act_mail_body)
@@ -456,21 +486,24 @@ base_action_rule()
 
 
 class ir_cron(osv.osv):
-    _inherit = 'ir.cron' 
-    
+    _inherit = 'ir.cron'
+    _init_done = False
+
     def _poolJobs(self, db_name, check=False):
-        try:
-            db = pooler.get_db(db_name)
-        except:
-            return False
-        cr = db.cursor()
-        try:
-            next = datetime.now().strftime('%Y-%m-%d %H:00:00')
-            # Putting nextcall always less than current time in order to call it every time
-            cr.execute('UPDATE ir_cron set nextcall = \'%s\' where numbercall<>0 and active and model=\'base.action.rule\' ' % (next))
-        finally:
-            cr.commit()
-            cr.close()
+        if not self._init_done:
+            self._init_done = True
+            try:
+                db = pooler.get_db(db_name)
+            except:
+                return False
+            cr = db.cursor()
+            try:
+                next = datetime.now().strftime('%Y-%m-%d %H:00:00')
+                # Putting nextcall always less than current time in order to call it every time
+                cr.execute('UPDATE ir_cron set nextcall = \'%s\' where numbercall<>0 and active and model=\'base.action.rule\' ' % (next))
+            finally:
+                cr.commit()
+                cr.close()
 
         super(ir_cron, self)._poolJobs(db_name, check=check)