[FIX] Record rule/Expression : If wrong domain is supplied,system should notify inste...
[odoo/odoo.git] / bin / addons / base / ir / ir_rule.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution   
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
6 #    $Id$
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 from osv import fields,osv
24 import time
25 import tools
26 from tools.safe_eval import safe_eval as eval
27 from tools.translate import _
28
29 class ir_rule_group(osv.osv):
30     _name = 'ir.rule.group'
31
32     _columns = {
33         'name': fields.char('Name', size=128, select=1),
34         'model_id': fields.many2one('ir.model', 'Object',select=1, required=True),
35         'global': fields.boolean('Global', select=1, help="Make the rule global, otherwise it needs to be put on a group"),
36         'rules': fields.one2many('ir.rule', 'rule_group', 'Tests', help="The rule is satisfied if at least one test is True"),
37         'groups': fields.many2many('res.groups', 'group_rule_group_rel', 'rule_group_id', 'group_id', 'Groups'),
38         'users': fields.many2many('res.users', 'user_rule_group_rel', 'rule_group_id', 'user_id', 'Users'),
39     }
40
41     _order = 'model_id, global DESC'
42
43     _defaults={
44         'global': lambda *a: True,
45     }
46
47 ir_rule_group()
48
49
50 class ir_rule(osv.osv):
51     _name = 'ir.rule'
52     _rec_name = 'field_id'
53
54     def _operand(self,cr,uid,context):
55
56         def get(object, level=3, recur=None, root_tech='', root=''):
57             res = []
58             if not recur:
59                 recur = []
60             fields = self.pool.get(object).fields_get(cr,uid)
61             key = fields.keys()
62             key.sort()
63             for k in key:
64
65                 if fields[k]['type'] in ('many2one'):
66                     res.append((root_tech+'.'+k+'.id',
67                         root+'/'+fields[k]['string']))
68
69                 elif fields[k]['type'] in ('many2many', 'one2many'):
70                     res.append(('\',\'.join(map(lambda x: str(x.id), '+root_tech+'.'+k+'))',
71                         root+'/'+fields[k]['string']))
72
73                 else:
74                     res.append((root_tech+'.'+k,
75                         root+'/'+fields[k]['string']))
76
77                 if (fields[k]['type'] in recur) and (level>0):
78                     res.extend(get(fields[k]['relation'], level-1,
79                         recur, root_tech+'.'+k, root+'/'+fields[k]['string']))
80
81             return res
82
83         res = [("False", "False"), ("True", "True"), ("user.id", "User")]
84         res += get('res.users', level=1,
85                 recur=['many2one'], root_tech='user', root='User')
86         return res
87
88     def _domain_force_get(self, cr, uid, ids, field_name, arg, context={}):
89         res = {}
90         for rule in self.browse(cr, uid, ids, context):
91             eval_user_data = {'user': self.pool.get('res.users').browse(cr, 1, uid),
92                             'time':time}
93             
94             if rule.domain_force:
95                 res[rule.id] = eval(rule.domain_force, eval_user_data)
96             else:
97                 if rule.operand and rule.operand.startswith('user.') and rule.operand.count('.') > 1:
98                     #Need to check user.field.field1.field2(if field  is False,it will break the chain)
99                     op = rule.operand[5:]
100                     rule.operand = rule.operand[:5+len(op[:op.find('.')])] +' and '+ rule.operand + ' or False'
101                 if rule.operator in ('in', 'child_of'):
102                     dom = eval("[('%s', '%s', [%s])]" % (rule.field_id.name, rule.operator,
103                         eval(rule.operand,eval_user_data)), eval_user_data)
104                 else:
105                     dom = eval("[('%s', '%s', %s)]" % (rule.field_id.name, rule.operator,
106                         rule.operand), eval_user_data)
107                 res[rule.id] = dom
108         return res
109
110     _columns = {
111         'field_id': fields.many2one('ir.model.fields', 'Field',domain= "[('model_id','=', parent.model_id)]", select=1),
112         'operator':fields.selection((('=', '='), ('<>', '<>'), ('<=', '<='), ('>=', '>='), ('in', 'in'), ('child_of', 'child_of')), 'Operator'),
113         'operand':fields.selection(_operand,'Operand', size=64),
114         'rule_group': fields.many2one('ir.rule.group', 'Group', select=2, required=True, ondelete="cascade"),
115         'domain_force': fields.char('Force Domain', size=250),
116         'domain': fields.function(_domain_force_get, method=True, string='Domain', type='char', size=250)
117     }
118     
119     def _check_domain_validity(self, cr, uid, ids, context={}):
120         for record in self.browse(cr, uid, ids, context=context):
121             dom = record.domain
122             if dom:
123                 try:
124                     rule_domain = self.pool.get(record.rule_group.model_id.model)._where_calc(cr, uid, dom, active_test=False)
125                 except Exception:
126                     return False
127         return True
128     
129     _constraints = [
130         (_check_domain_validity, _('The domain contains wrong reference of fields! Kindly double check the domain you provided !'),['domain_force']),
131     ]
132     
133     def onchange_all(self, cr, uid, ids, field_id, operator, operand):
134         if not (field_id or operator or operand):
135             return {}
136
137     def domain_get(self, cr, uid, model_name):
138         # root user above constraint
139         if uid == 1:
140             return '', []
141
142         cr.execute("""SELECT r.id FROM
143             ir_rule r
144                 JOIN (ir_rule_group g
145                     JOIN ir_model m ON (g.model_id = m.id))
146                     ON (g.id = r.rule_group)
147                 WHERE m.model = %s
148                 AND (g.id IN (SELECT rule_group_id FROM group_rule_group_rel g_rel
149                             JOIN res_groups_users_rel u_rel ON (g_rel.group_id = u_rel.gid)
150                             WHERE u_rel.uid = %s) OR g.global)""", (model_name, uid))
151         ids = map(lambda x:x[0], cr.fetchall())
152         if not ids:
153             return '', []
154         obj = self.pool.get(model_name)
155         add = []
156         add_str = []
157         sub = []
158         sub_str = []
159         clause={}
160         clause_global={}
161         for rule in self.browse(cr, uid, ids):
162             dom = rule.domain
163             if rule.rule_group['global']:
164                 clause_global.setdefault(rule.rule_group.id, [])
165                 clause_global[rule.rule_group.id].append(obj._where_calc(cr, uid, dom, active_test=False))
166             else:
167                 clause.setdefault(rule.rule_group.id, [])
168                 clause[rule.rule_group.id].append(obj._where_calc(cr, uid, dom, active_test=False))
169
170         def _query(clause, test):
171             query = ''
172             val = []
173             for g in clause.values():
174                 if not g:
175                     continue
176                 if len(query):
177                     query += ' '+test+' '
178                 query += '('
179                 first = True
180                 for c in g:
181                     if not first:
182                         query += ' AND '
183                     first = False
184                     query += '('
185                     first2 = True
186                     for clause in c[0]:
187                         if not first2:
188                             query += ' AND '
189                         first2 = False
190                         query += clause
191                     query += ')'
192                     val += c[1]
193                 query += ')'
194             return query, val
195
196         query, val = _query(clause, 'OR')
197         query_global, val_global = _query(clause_global, 'OR')
198         if query_global:
199             if query:
200                 query = '('+query+') OR '+query_global
201                 val.extend(val_global)
202             else:
203                 query = query_global
204                 val = val_global
205
206
207         if query:
208             query = '('+query+')'
209         return query, val
210
211 ir_rule()
212
213 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
214