← Back to team overview

openerp-dev-web team mailing list archive

lp:~openerp-dev/openobject-addons/trunk-automated_rules-base_rules_generic-jam into lp:~openerp-dev/openobject-addons/trunk-automated_rules

 

Jigar Amin - OpenERP has proposed merging lp:~openerp-dev/openobject-addons/trunk-automated_rules-base_rules_generic-jam into lp:~openerp-dev/openobject-addons/trunk-automated_rules.

Requested reviews:
  OpenERP Core Team (openerp)

For more details, see:
https://code.launchpad.net/~openerp-dev/openobject-addons/trunk-automated_rules-base_rules_generic-jam/+merge/51098

Hello,
  Changes with the merge proposal :

Backlog 2 : Make good triggering
--------------------------------------------------
    * A filter to select a sub set of object from that model
         * on those object the action should apply
            * Directly if there is no time condition
            * when the time condition is filled 
    * select object from that model that filled the filter and the time condition
    * apply the server actions
    * Make sure that this action will trigger one and only one time no more no less
    * Time triggering : when the action is trigger by a condition on time
    * avoid circle triggering
    * Create Filter will open the ir_filters view to create new filter.
Kindly review this
Thank You



-- 
https://code.launchpad.net/~openerp-dev/openobject-addons/trunk-automated_rules-base_rules_generic-jam/+merge/51098
Your team OpenERP R&D Team is subscribed to branch lp:~openerp-dev/openobject-addons/trunk-automated_rules.
=== modified file 'base_action_rule/__openerp__.py'
--- base_action_rule/__openerp__.py	2011-02-22 07:03:39 +0000
+++ base_action_rule/__openerp__.py	2011-02-24 10:17:59 +0000
@@ -28,7 +28,7 @@
     'website': 'http://www.openerp.com',
     'depends': ['base'],
     'init_xml': [
-#        'base_action_rule_data.xml'
+        'base_action_rule_data.xml'
     ],
     'update_xml': [
         'base_action_rule_view.xml',        

=== modified file 'base_action_rule/base_action_rule.py'
--- base_action_rule/base_action_rule.py	2011-02-22 09:07:54 +0000
+++ base_action_rule/base_action_rule.py	2011-02-24 10:17:59 +0000
@@ -23,14 +23,9 @@
 from tools.translate import _
 from datetime import datetime
 from datetime import timedelta
-from tools.safe_eval import safe_eval
-import pooler 
-import re
-import time
-import tools
-
 
 def get_datetime(date_field):
+    """Method to covert string to datetime object"""
     return datetime.strptime(date_field[:19], '%Y-%m-%d %H:%M:%S')
 
 class action_rule_state(osv.osv):
@@ -54,21 +49,48 @@
 
 
     def btn_create_filter(self, cr, uid, ids, context=None):
-        
-        return True
-
+        """
+        This will open ir.filter view view on button click of create filter in form.
+        """
+        if context == None:
+            context = {}
+        current_record = self.browse(cr, uid, ids, context=context)
+        model=None
+        for obj in current_record:
+            model = obj.model_id.id 
+        data_model_pool = self.pool.get('ir.model.data')
+        tree_view_id = data_model_pool.search(cr,uid,[('model','=','ir.ui.view'),('name','=','ir_filters_view_tree')])
+        tree_id = data_model_pool.read(cr, uid, tree_view_id, fields=['res_id'])[0]['res_id']
+        form_view_id = data_model_pool.search(cr,uid,[('model','=','ir.ui.view'),('name','=','ir_filters_view_form')])
+        form_id = data_model_pool.read(cr, uid, form_view_id, fields=['res_id'])[0]['res_id']
+        search_view_id = data_model_pool.search(cr,uid,[('model','=','ir.ui.view'),('name','=','ir_filters_view_search')])
+        search_id = data_model_pool.read(cr, uid, search_view_id, fields=['res_id'])[0]['res_id']
+        context.update({"model_id":model})
+        value =  {
+            'name' : _("Filters"),
+            'context': context,
+            'view_type': 'form',
+            'view_mode': 'from,tree',
+            'res_model': 'ir.filters',
+            'view_id': False, 
+            'views': [(tree_id,'tree'), ( form_id, 'form')],
+            'type': 'ir.actions.act_window',
+            'search_view_id': search_id,
+            'nodestroy' : True,
+        }
+        return value
 
     _columns = {
         'name':  fields.char('Rule Name', size=64, required=True), 
-        'model_id': fields.many2one('ir.model', 'Object', required=True), 
+        'model_id': fields.many2one('ir.model', 'Object', required=True, help="Model on which action rule to be applied"), 
         'create_date': fields.datetime('Create Date', readonly=1), 
         'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the rule without removing it."), 
         'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of rules."), 
         'server_action_id': fields.many2one('ir.actions.server', 'Server Action', help="Describes the action name.\neg:on which object which action to be taken on basis of which condition"),
-        'filter_id':fields.many2one('ir.filters', 'Filter', required=False), 
-        'last_run': fields.datetime('Last Run', readonly=1),
-        'field_id' : fields.many2one('ir.model.fields', 'Field'),
-        'from_state_id': fields.many2one('action.rule.state', 'State'),
+        'filter_id':fields.many2one('ir.filters', 'Filter', required=False, help="Allows to apply filter on select model, to create new filter click to button Create Filter"), 
+        'last_run': fields.datetime('Last Run', readonly=1, help="Date when last action rule executed by server action."),
+        'field_id' : fields.many2one('ir.model.fields', 'Field', help="Date time and date filed to trigger action on date."),
+        'from_state_id': fields.many2one('action.rule.state', 'State', help="State shows the all available states of the selected model and Model documents will be filter on select state."),
  
     }
     _defaults = {
@@ -102,355 +124,45 @@
                             
         return {'value':{'from_state_id':None, 'field_id':None}}
 
-
-    def pre_action(self, cr, uid, ids, model, context=None):
-        # 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")
-        res = cr.fetchall()
-        # Check if any rule matching with current object
-        for obj_name, rule_id in res:
-            if not (model == obj_name):
-                continue
-            else:
-                obj = self.pool.get(obj_name)
-                # 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 context is None:
-            context  = {}
-        def make_call_old(cr, uid, vals, context=context):
-            new_id = old_create(cr, uid, vals, context=context)
-            if not context.get('action'):
-                self.pre_action(cr, uid, [new_id], model, context=context)
-            return new_id
-        return make_call_old
-    
-    def _write(self, old_write, model, context=None):
-        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'):
-                self.pre_action(cr, uid, ids, model, context=context)
-            return old_write(cr, uid, ids, vals, context=context)
-        return make_call_old
-
-    def _register_hook(self, cr, uid, ids, context=None):
-        if context is None:
-            context = {}
-        for action_rule in self.browse(cr, uid, ids, context=context):
-            model = action_rule.model_id.model
-            obj_pool = self.pool.get(model)
-            if not hasattr(obj_pool, 'base_action_ruled'):
-                obj_pool.create = self._create(obj_pool.create, model, context=context)
-                obj_pool.write = self._write(obj_pool.write, model, context=context)
-                obj_pool.base_action_ruled = True
-
-        return True
-
-
-    def _check(self, cr, uid, automatic=False, use_new_cursor=False, \
-                       context=None):
+    def _check(self, cr, uid, automatic=False, use_new_cursor=False, context=None):
         """
         This Function is call by scheduler.
         """
+        if context == None:
+            context = {}
         rule_pool = self.pool.get('base.action.rule')
-        rule_ids = rule_pool.search(cr, uid, [], 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)
+        rule_ids = rule_pool.search(cr, uid, [('active','=','True')], context=context)
+        # Checking filter and action for all active for the record rules 
+        for rule in self.browse(cr, uid, rule_ids, context=context):
+            model_pool = self.pool.get(rule.model_id.model)
+            #Updaqting the Rule execution date by corn
             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
-            @param self: The object pointer """
-        return body and tools.ustr(body) or ''
-
-    def format_mail(self, obj, body):
-        """ Foramat Mail
-            @param self: The object pointer """
-
-        data = {
-            'object_id': obj.id, 
-            'object_subject': hasattr(obj, 'name') and obj.name or False, 
-            'object_date': hasattr(obj, 'date') and obj.date or False, 
-            '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 '/', 
-            '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 '/', 
-        }
-        return self.format_body(body % data)
-
-    def email_send(self, cr, uid, obj, emails, body, emailfrom=None, context=None):
-        """ send email
-            @param self: The object pointer
-            @param cr: the current row, from the database cursor,
-            @param uid: the current user’s ID for security checks,
-            @param email: pass the emails
-            @param emailfrom: Pass name the email From else False
-            @param context: A standard dictionary for contextual values """
-
-        if not emailfrom:
-            emailfrom = tools.config.get('email_from', False)
-
-        if context is None:
-            context = {}
-
-        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
-
-        name = '[%d] %s' % (obj.id, tools.ustr(obj.name))
-        emailfrom = tools.ustr(emailfrom)
-        reply_to = emailfrom
-        if not emailfrom:
-            raise osv.except_osv(_('Error!'), 
-                    _("No E-Mail ID Found for your Company address!"))
-        return tools.email_send(emailfrom, emails, name, body, reply_to=reply_to, openobject_id=str(obj.id))
-
-
-    def do_check(self, cr, uid, action, obj, context=None):
-        """ check Action
-            @param self: The object pointer
-            @param cr: the current row, from the database cursor,
-            @param uid: the current user’s ID for security checks,
-            @param context: A standard dictionary for contextual values """
-        if context is None:
-            context = {}
-        ok = True 
-        if action.filter_id:
-            if action.model_id.model == action.filter_id.model_id:
-                context.update(eval(action.filter_id.context))
-                obj_ids = obj._table.search(cr, uid, eval(action.filter_id.domain), context=context)
-                if not obj.id in obj_ids:
-                    ok = False
-            else:
-                ok = False
-        if getattr(obj, 'user_id', False):
-            ok = ok and (not action.trg_user_id.id or action.trg_user_id.id==obj.user_id.id)
-        if getattr(obj, 'partner_id', False):
-            ok = ok and (not action.trg_partner_id.id or action.trg_partner_id.id==obj.partner_id.id)
-            ok = ok and (
-                not action.trg_partner_categ_id.id or
-                (
-                    obj.partner_id.id and
-                    (action.trg_partner_categ_id.id in map(lambda x: x.id, obj.partner_id.category_id or []))
-                )
-            )
-        state_to = context.get('state_to', False)
-        state = getattr(obj, 'state', False)
-        if state:
-            ok = ok and (not action.trg_state_from or action.trg_state_from==state)
-        if state_to:
-            ok = ok and (not action.trg_state_to or action.trg_state_to==state_to)
-        elif action.trg_state_to:
-            ok = False
-        reg_name = action.regex_name
-        result_name = True
-        if reg_name:
-            ptrn = re.compile(str(reg_name))
-            _result = ptrn.search(str(obj.name))
-            if not _result:
-                result_name = False
-        regex_n = not reg_name or result_name
-        ok = ok and regex_n
-        return ok
-
-    def do_action(self, cr, uid, action, model_obj, obj, context=None):
-        """ Do Action
-            @param self: The object pointer
-            @param cr: the current row, from the database cursor,
-            @param uid: the current user’s ID for security checks,
-            @param action: pass action
-            @param model_obj: pass Model object
-            @param context: A standard dictionary for contextual values """
-        if context is None:
-            context = {}
-
-        if action.server_action_id:
-            context.update({'active_id':obj.id, 'active_ids':[obj.id]})
-            self.pool.get('ir.actions.server').run(cr, uid, [action.server_action_id.id], context)
-        write = {}
-
-        if hasattr(obj, 'user_id') and action.act_user_id:
-            obj.user_id = action.act_user_id
-            write['user_id'] = action.act_user_id.id
-        if hasattr(obj, 'date_action_last'):
-            write['date_action_last'] = time.strftime('%Y-%m-%d %H:%M:%S')
-        if hasattr(obj, 'state') and action.act_state:
-            obj.state = action.act_state
-            write['state'] = action.act_state
-
-        if hasattr(obj, 'categ_id') and action.act_categ_id:
-            obj.categ_id = action.act_categ_id
-            write['categ_id'] = action.act_categ_id.id
-
-        model_obj.write(cr, uid, [obj.id], write, context)
-
-        if hasattr(model_obj, 'remind_user') and action.act_remind_user:
-            model_obj.remind_user(cr, uid, [obj.id], context, attach=action.act_remind_attach)
-        if hasattr(model_obj, 'remind_partner') and action.act_remind_partner:
-            model_obj.remind_partner(cr, uid, [obj.id], context, attach=action.act_remind_attach)
-        if action.act_method:
-            getattr(model_obj, 'act_method')(cr, uid, [obj.id], action, context)
-
-        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 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, {}, 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):
-        """ Do Action
-            @param self: The object pointer
-            @param cr: the current row, from the database cursor,
-            @param uid: the current user’s ID for security checks,
-            @param ids: List of Basic Action Rule’s IDs,
-            @param objects: pass objects
-            @param context: A standard dictionary for contextual values """
-        if context is None:
-            context = {}
-
-        context.update({'action': True})
-        if not scrit:
-            scrit = []
-
-        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
-
-                if ok:
-                    self.do_action(cr, uid, action, model_obj, obj, context)
-                    break
-        context.update({'action': False})
-        return True
-
-    def _check_mail(self, cr, uid, ids, context=None):
-        """ Check Mail
-            @param self: The object pointer
-            @param cr: the current row, from the database cursor,
-            @param uid: the current user’s ID for security checks,
-            @param ids: List of Action Rule’s IDs
-            @param context: A standard dictionary for contextual values """
-
-        empty = orm.browse_null()
-        rule_obj = self.pool.get('base.action.rule')
-        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)
-                except (ValueError, KeyError, TypeError):
-                    return False
-        return True
-
-
+            rule_pool.write(cr, uid, [rule.id], {'last_run': now},context=context)
+            # Preparing the domain using the filters and sate and filed.            
+            state_filter = []
+            field_filter = []
+            domain = [] 
+            if rule.from_state_id:
+                state_filter = [('state','=',rule.from_state_id.key)]
+            if rule.field_id:
+                field_filter = [(rule.field_id.name,"!=",None)]
+            domain.extend(state_filter) 
+            domain.extend(field_filter)
+            if rule.filter_id:
+                if rule.model_id.model == rule.filter_id.model_id:
+                    context.update(eval(rule.filter_id.context))
+                    domain.extend(eval(rule.filter_id.domain))
+            # Triggering the server actiob for all Match model documnets. 
+            for object_rec in model_pool.search(cr, uid, domain, context=context):
+                obj = model_pool.browse(cr, uid, object_rec, context=context)
+                ctx= {}
+                if rule.server_action_id:
+                    #updating the context for current model document.
+                    ctx.update({'active_id':obj.id, 'active_ids':[obj.id]})
+                    #calling server action for filtered document.
+                    try:
+                        self.pool.get('ir.actions.server').run(cr, uid, [rule.server_action_id.id], context=ctx)
+                    except:
+                        pass
 base_action_rule()
-
-
-class ir_cron(osv.osv):
-    _inherit = 'ir.cron' 
-    
-    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()
-
-        super(ir_cron, self)._poolJobs(db_name, check=check)
-
-ir_cron()
-
-
 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

=== modified file 'base_action_rule/base_action_rule_view.xml'
--- base_action_rule/base_action_rule_view.xml	2011-02-22 09:07:54 +0000
+++ base_action_rule/base_action_rule_view.xml	2011-02-24 10:17:59 +0000
@@ -45,31 +45,34 @@
                         <group col="4" colspan="4">
                             <field name="name" colspan="2"/>
                             <field name="sequence" colspan="2"/>
+                            <field name="model_id" select="1" on_change="onchange_model_id(model_id)" colspan="2"/>
                             <field name="active" colspan="2"/>
                         </group>
                         <notebook colspan="4">
-                            <page string="Filter">
-                                <group col="2" colspan="2" name="model">
-                                    <separator colspan="4" string="Model"/>
-                                    <field name="model_id" select="1" on_change="onchange_model_id(model_id)" colspan="2"/>
-                                    <field name="filter_id" colspan="2"/>
+                            <page string="Action Parameters">
+                                <group col="2" colspan="2">
+                                    <separator colspan="4" string="Server Action"/>
+                                    <field name="server_action_id" colspan="2" required="True" domain="[('model_id','=',model_id)]"/>
                                 </group>
                                 <group col="2" colspan="2" name="partner">
                                     <separator colspan="4" string="Conditions on Field and State"/>
-                                    <field name="field_id" domain="[('ttype','in',['datetime','date']),('model_id','=',model_id)]" colspan="2"/>
+                                    <field name="field_id" domain="[('ttype','in',['datetime','date']),
+                                                            ('model_id','=',model_id)]" colspan="2"/>
                                     <field name="from_state_id" domain="[('model_id','=',model_id)]"/> 
-                               </group>
-                                <group col="2" colspan="2"/>
+                                </group>
+                                <group col="2" colspan="2" >
+                                    <separator colspan="4" string="Filters"/>
+                                    <group col="4" colspan="4">
+                                        <field name="filter_id" colspan="2"/>
+                                        <button name="btn_create_filter" type="object" string="Create _Filter" 
+                                                icon="terp-document-new" help="To create filter go to on search viewmake your filter and save it, that lead to the search (and list) view of the object."/>
+                                    </group>
+                                </group>
                                 <group col="2" colspan="2">
-                                    <button name="btn_create_filter" type="object" string="Create Filter" icon="terp-document-new" 
-                                            help="To create filter go to on search view make your filter and save it, that lead to the search (and list) view of the object."/>
+                                    <separator colspan="4" string="Misecellenious"/>
+                                    <field name="last_run"/>
                                 </group>
                             </page>
-                            <page string="Actions">
-                                <field name="server_action_id" colspan="2"/>
-                                <separator colspan="4" string="Information"/>
-                                <field name="last_run"/>
-                            </page>
                         </notebook>
                     </form>
                 </field>


Follow ups