Merge branch 'master' of openobject-server into mdv-gpl3-py26
[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
27
28 class ir_rule_group(osv.osv):
29     _name = 'ir.rule.group'
30
31     _columns = {
32         'name': fields.char('Name', size=128, select=1),
33         'model_id': fields.many2one('ir.model', 'Object',select=1, required=True),
34         'global': fields.boolean('Global', select=1, help="Make the rule global, otherwise it needs to be put on a group or user"),
35         'rules': fields.one2many('ir.rule', 'rule_group', 'Tests', help="The rule is satisfied if at least one test is True"),
36         'groups': fields.many2many('res.groups', 'group_rule_group_rel', 'rule_group_id', 'group_id', 'Groups'),
37         'users': fields.many2many('res.users', 'user_rule_group_rel', 'rule_group_id', 'user_id', 'Users'),
38     }
39
40     _order = 'model_id, global DESC'
41
42     _defaults={
43         'global': lambda *a: True,
44     }
45
46     def unlink(self, cr, uid, ids, context=None):
47         res = super(ir_rule_group, self).unlink(cr, uid, ids, context=context)
48         # Restart the cache on the domain_get method of ir.rule
49         self.pool.get('ir.rule').domain_get.clear_cache(cr.dbname)
50         return res
51
52     def create(self, cr, user, vals, context=None):
53         res = super(ir_rule_group, self).create(cr, user, vals, context=context)
54         # Restart the cache on the domain_get method of ir.rule
55         self.pool.get('ir.rule').domain_get.clear_cache(cr.dbname)
56         return res
57
58     def write(self, cr, uid, ids, vals, context=None):
59         res = super(ir_rule_group, self).write(cr, uid, ids, vals, context=context)
60         # Restart the cache on the domain_get method of ir.rule
61         self.pool.get('ir.rule').domain_get.clear_cache(cr.dbname)
62         return res
63
64 ir_rule_group()
65
66
67 class ir_rule(osv.osv):
68     _name = 'ir.rule'
69     _rec_name = 'field_id'
70
71     def _operand(self,cr,uid,context):
72
73         def get(object, level=3, recur=None, root_tech='', root=''):
74             res = []
75             if not recur:
76                 recur = []
77             fields = self.pool.get(object).fields_get(cr,uid)
78             key = fields.keys()
79             key.sort()
80             for k in key:
81
82                 if fields[k]['type'] in ('many2one'):
83                     res.append((root_tech+'.'+k+'.id',
84                         root+'/'+fields[k]['string']))
85
86                 elif fields[k]['type'] in ('many2many', 'one2many'):
87                     res.append(('\',\'.join(map(lambda x: str(x.id), '+root_tech+'.'+k+'))',
88                         root+'/'+fields[k]['string']))
89
90                 else:
91                     res.append((root_tech+'.'+k,
92                         root+'/'+fields[k]['string']))
93
94                 if (fields[k]['type'] in recur) and (level>0):
95                     res.extend(get(fields[k]['relation'], level-1,
96                         recur, root_tech+'.'+k, root+'/'+fields[k]['string']))
97
98             return res
99
100         res = [("False", "False"), ("True", "True"), ("user.id", "User")]
101         res += get('res.users', level=1,
102                 recur=['many2one'], root_tech='user', root='User')
103         return res
104
105     def _domain_force_get(self, cr, uid, ids, field_name, arg, context={}):
106         res = {}
107         for rule in self.browse(cr, uid, ids, context):
108             if rule.domain_force:
109                 res[rule.id] = eval(rule.domain_force, {'user': self.pool.get('res.users').browse(cr, 1, uid),
110                             'time':time})
111             else:
112                 if rule.operator in ('in', 'child_of'):
113                     dom = eval("[('%s', '%s', [%s])]" % (rule.field_id.name, rule.operator,
114                         rule.operand), {'user': self.pool.get('res.users').browse(cr, 1, uid),
115                             'time':time})
116                 else:
117                     dom = eval("[('%s', '%s', %s)]" % (rule.field_id.name, rule.operator,
118                         rule.operand), {'user': self.pool.get('res.users').browse(cr, 1, uid),
119                             'time':time})
120                 res[rule.id] = dom
121         return res
122
123     _columns = {
124         'field_id': fields.many2one('ir.model.fields', 'Field',domain= "[('model_id','=', parent.model_id)]", select=1, required=True),
125         'operator':fields.selection((('=', '='), ('<>', '<>'), ('<=', '<='), ('>=', '>='), ('in', 'in'), ('child_of', 'child_of')), 'Operator', required=True),
126         'operand':fields.selection(_operand,'Operand', size=64, required=True),
127         'rule_group': fields.many2one('ir.rule.group', 'Group', select=2, required=True, ondelete="cascade"),
128         'domain_force': fields.char('Force Domain', size=250),
129         'domain': fields.function(_domain_force_get, method=True, string='Domain', type='char', size=250)
130     }
131
132     def onchange_all(self, cr, uid, ids, field_id, operator, operand):
133         if not (field_id or operator or operand):
134             return {}
135
136     def domain_get(self, cr, uid, model_name):
137         # root user above constraint
138         if uid == 1:
139             return '', []
140
141         cr.execute("""SELECT r.id FROM
142             ir_rule r
143                 JOIN (ir_rule_group g
144                     JOIN ir_model m ON (g.model_id = m.id))
145                     ON (g.id = r.rule_group)
146                 WHERE m.model = %s
147                 AND (g.id IN (SELECT rule_group_id FROM group_rule_group_rel g_rel
148                             JOIN res_groups_users_rel u_rel ON (g_rel.group_id = u_rel.gid)
149                             WHERE u_rel.uid = %s) OR g.global)""", (model_name, uid))
150         ids = map(lambda x:x[0], cr.fetchall())
151         if not ids:
152             return '', []
153         obj = self.pool.get(model_name)
154         add = []
155         add_str = []
156         sub = []
157         sub_str = []
158         clause={}
159         clause_global={}
160         for rule in self.browse(cr, uid, ids):
161             dom = rule.domain
162             if rule.rule_group['global']:
163                 clause_global.setdefault(rule.rule_group.id, [])
164                 clause_global[rule.rule_group.id].append(obj._where_calc(cr, uid, dom, active_test=False))
165             else:
166                 clause.setdefault(rule.rule_group.id, [])
167                 clause[rule.rule_group.id].append(obj._where_calc(cr, uid, dom, active_test=False))
168
169         def _query(clause, test):
170             query = ''
171             val = []
172             for g in clause.values():
173                 if not g:
174                     continue
175                 if len(query):
176                     query += ' '+test+' '
177                 query += '('
178                 first = True
179                 for c in g:
180                     if not first:
181                         query += ' AND '
182                     first = False
183                     query += '('
184                     first2 = True
185                     for clause in c[0]:
186                         if not first2:
187                             query += ' AND '
188                         first2 = False
189                         query += clause
190                     query += ')'
191                     val += c[1]
192                 query += ')'
193             return query, val
194
195         query, val = _query(clause, 'OR')
196         query_global, val_global = _query(clause_global, 'OR')
197         if query_global:
198             if query:
199                 query = '('+query+') OR '+query_global
200                 val.extend(val_global)
201             else:
202                 query = query_global
203                 val = val_global
204
205
206         if query:
207             query = '('+query+')'
208         return query, val
209     domain_get = tools.cache()(domain_get)
210
211     def unlink(self, cr, uid, ids, context=None):
212         res = super(ir_rule, self).unlink(cr, uid, ids, context=context)
213         # Restart the cache on the domain_get method of ir.rule
214         self.domain_get.clear_cache(cr.dbname)
215         return res
216
217     def create(self, cr, user, vals, context=None):
218         res = super(ir_rule, self).create(cr, user, vals, context=context)
219         # Restart the cache on the domain_get method of ir.rule
220         self.domain_get.clear_cache(cr.dbname)
221         return res
222
223     def write(self, cr, uid, ids, vals, context=None):
224         if not context:
225             context={}
226         res = super(ir_rule, self).write(cr, uid, ids, vals, context=context)
227         # Restart the cache on the domain_get method
228         self.domain_get.clear_cache(cr.dbname)
229         return res
230
231 ir_rule()
232
233 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
234