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