merge
[odoo/odoo.git] / bin / addons / base / res / res_user.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #    
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.     
19 #
20 ##############################################################################
21
22 from osv import fields,osv
23 from osv.orm import except_orm
24 import tools
25 import pytz
26 from tools.translate import _
27
28 class groups(osv.osv):
29     _name = "res.groups"
30     _order = 'name'
31     _columns = {
32         'name': fields.char('Group Name', size=64, required=True),
33         'model_access': fields.one2many('ir.model.access', 'group_id', 'Access Controls'),
34         'rule_groups': fields.many2many('ir.rule.group', 'group_rule_group_rel',
35             'group_id', 'rule_group_id', 'Rules', domain="[('global', '<>', True)]"),
36         'menu_access': fields.many2many('ir.ui.menu', 'ir_ui_menu_group_rel', 'gid', 'menu_id', 'Access Menu'),
37         'comment' : fields.text('Comment',size=250),
38     }
39     _sql_constraints = [
40         ('name_uniq', 'unique (name)', 'The name of the group must be unique !')
41     ]
42     def copy(self, cr, uid, id, default=None, context={}):
43         group_name = self.read(cr, uid, [id], ['name'])[0]['name']
44         default.update({'name': group_name +' (copy)'})
45         return super(groups, self).copy(cr, uid, id, default, context)
46
47     def write(self, cr, uid, ids, vals, context=None):
48         if 'name' in vals:
49             if vals['name'].startswith('-'):
50                 raise osv.except_osv(_('Error'),
51                         _('The name of the group can not start with "-"'))
52         res = super(groups, self).write(cr, uid, ids, vals, context=context)
53         # Restart the cache on the company_get method
54         self.pool.get('ir.rule').domain_get.clear_cache(cr.dbname)
55         self.pool.get('ir.model.access').call_cache_clearing_methods(cr)
56         return res
57
58     def create(self, cr, uid, vals, context=None):
59         if 'name' in vals:
60             if vals['name'].startswith('-'):
61                 raise osv.except_osv(_('Error'),
62                         _('The name of the group can not start with "-"'))
63         gid = super(groups, self).create(cr, uid, vals, context=context)        
64         if context and context.get('noadmin', False):
65             pass
66         else:
67             # assign this new group to user_root
68             user_obj = self.pool.get('res.users')
69             aid = user_obj.browse(cr, 1, user_obj._get_admin_id(cr))
70             if aid:
71                 aid.write({'groups_id': [(4, gid)]})
72         return gid
73
74     def copy(self, cr, uid, id, default={}, context={}, done_list=[], local=False):
75         group = self.browse(cr, uid, id, context=context)
76         default = default.copy()
77         if not 'name' in default:
78             default['name'] = group['name']
79         default['name'] = default['name'] + _(' (copy)')
80         return super(groups, self).copy(cr, uid, id, default, context=context)
81
82 groups()
83
84
85 class roles(osv.osv):
86     _name = "res.roles"
87     _columns = {
88         'name': fields.char('Role Name', size=64, required=True),
89         'parent_id': fields.many2one('res.roles', 'Parent', select=True),
90         'child_id': fields.one2many('res.roles', 'parent_id', 'Children'),
91         'users': fields.many2many('res.users', 'res_roles_users_rel', 'rid', 'uid', 'Users'),
92     }
93     _defaults = {
94     }
95     def check(self, cr, uid, ids, role_id):
96         if role_id in ids:
97             return True
98         cr.execute('select parent_id from res_roles where id=%s', (role_id,))
99         roles = cr.fetchone()[0]
100         if roles:
101             return self.check(cr, uid, ids, roles)
102         return False
103 roles()
104
105 def _lang_get(self, cr, uid, context={}):
106     obj = self.pool.get('res.lang')
107     ids = obj.search(cr, uid, [])
108     res = obj.read(cr, uid, ids, ['code', 'name'], context)
109     res = [(r['code'], r['name']) for r in res]
110     return res
111 def _tz_get(self,cr,uid, context={}):
112     return [(x, x) for x in pytz.all_timezones]
113
114 def _companies_get(self,cr, uid, context={}):
115     res=[]
116     ids = self.pool.get('res.users').browse(cr, uid, uid, context).company_ids
117     res = [(i.id,i.name) for i in ids]
118     return res
119
120 class users(osv.osv):
121     __admin_ids = {}
122     _name = "res.users"
123     #_log_access = False
124     
125     def get_current_company(self, cr, uid):
126         res=[]
127         cr.execute('select company_id, res_company.name from res_users left join res_company on res_company.id = company_id where res_users.id=%s' %uid)
128         res = cr.fetchall()
129         return res     
130     
131     _columns = {
132         'name': fields.char('Name', size=64, required=True, select=True),
133         'login': fields.char('Login', size=64, required=True),
134         'password': fields.char('Password', size=64, invisible=True, help="Keep empty if you don't want the user to be able to connect on the system."),
135         'signature': fields.text('Signature', size=64),
136         'address_id': fields.many2one('res.partner.address', 'Address'),
137         'active': fields.boolean('Active'),
138         'action_id': fields.many2one('ir.actions.actions', 'Home Action'),
139         'menu_id': fields.many2one('ir.actions.actions', 'Menu Action'),
140         'groups_id': fields.many2many('res.groups', 'res_groups_users_rel', 'uid', 'gid', 'Groups'),
141         'roles_id': fields.many2many('res.roles', 'res_roles_users_rel', 'uid', 'rid', 'Roles'),
142         'rules_id': fields.many2many('ir.rule.group', 'user_rule_group_rel', 'user_id', 'rule_group_id', 'Rules'),
143         'company_id': fields.many2one('res.company', 'Company', help="The company this user is currently working on.", required=True),
144         'company_ids':fields.many2many('res.company','res_company_users_rel','user_id','cid','Accepted Companies'),
145         'context_lang': fields.selection(_lang_get, 'Language', required=True),
146         'context_tz': fields.selection(_tz_get,  'Timezone', size=64),
147         'company': fields.selection(_companies_get,  'Company', size=64),        
148     }
149     def read(self,cr, uid, ids, fields=None, context=None, load='_classic_read'):
150         def override_password(o):
151             if 'password' in o and ( 'id' not in o or o['id'] != uid ):
152                 o['password'] = '********'
153             return o
154
155         result = super(users, self).read(cr, uid, ids, fields, context, load)
156         canwrite = self.pool.get('ir.model.access').check(cr, uid, 'res.users', 'write', raise_exception=False)
157         if not canwrite:
158             if isinstance(ids, (int, float)):
159                 result = override_password(result)
160             else:
161                 result = map(override_password, result)
162         return result
163
164     _sql_constraints = [
165         ('login_key', 'UNIQUE (login)',  _('You can not have two users with the same login !'))
166     ]
167
168     def _get_admin_id(self, cr):
169         if self.__admin_ids.get(cr.dbname) is None:
170             ir_model_data_obj = self.pool.get('ir.model.data')
171             mdid = ir_model_data_obj._get_id(cr, 1, 'base', 'user_root')
172             self.__admin_ids[cr.dbname] = ir_model_data_obj.read(cr, 1, [mdid], ['res_id'])[0]['res_id']
173         return self.__admin_ids[cr.dbname]
174
175     def _get_action(self,cr, uid, context={}):
176         ids = self.pool.get('ir.ui.menu').search(cr, uid, [('usage','=','menu')])
177         return ids and ids[0] or False
178
179     def _get_company(self,cr, uid, context={}):
180         return self.pool.get('res.users').browse(cr, uid, uid, context).company_id.id
181
182     def _get_menu(self,cr, uid, context={}):
183         ids = self.pool.get('ir.actions.act_window').search(cr, uid, [('usage','=','menu')])
184         return ids and ids[0] or False
185
186     def _get_group(self,cr, uid, context={}):
187         ids = self.pool.get('res.groups').search(cr, uid, [('name','=','Employee')])
188         return ids or False
189
190     _defaults = {
191         'password' : lambda obj,cr,uid,context={} : '',
192         'context_lang': lambda *args: 'en_US',
193         'active' : lambda obj,cr,uid,context={} : True,
194         'menu_id': _get_menu,
195         'action_id': _get_menu,
196         'company_id': _get_company,
197         'groups_id': _get_group,
198     }
199     def company_get(self, cr, uid, uid2):
200         company_id = self.pool.get('res.users').browse(cr, uid, uid2).company_id.id
201         return company_id
202     company_get = tools.cache()(company_get)
203
204     def write(self, cr, uid, ids, values, *args, **argv):
205         if (ids == [uid]):
206             ok = True
207             for k in values.keys():
208                 if k not in ('password','signature','action_id', 'context_lang', 'context_tz'):
209                     ok=False
210             if ok:
211                 uid = 1
212         res = super(users, self).write(cr, uid, ids, values, *args, **argv)
213         self.company_get.clear_cache(cr.dbname)
214         # Restart the cache on the company_get method
215         self.pool.get('ir.rule').domain_get.clear_cache(cr.dbname)
216         self.pool.get('ir.model.access').call_cache_clearing_methods(cr)
217         return res
218
219     def unlink(self, cr, uid, ids, context=None):
220         if 1 in ids:
221             raise osv.except_osv(_('Can not remove root user!'), _('You can not remove the admin user as it is used internally for resources created by OpenERP (updates, module installation, ...)'))
222         return super(users, self).unlink(cr, uid, ids, context=context)
223
224     def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=80):
225         if not args:
226             args=[]
227         if not context:
228             context={}
229         ids = []
230         if name:
231             ids = self.search(cr, user, [('login','=',name)]+ args, limit=limit)
232         if not ids:
233             ids = self.search(cr, user, [('name',operator,name)]+ args, limit=limit)
234         return self.name_get(cr, user, ids)
235
236     def copy(self, cr, uid, id, default=None, context={}):
237         login = self.read(cr, uid, [id], ['login'])[0]['login']
238         default.update({'login': login+' (copy)'})
239         return super(users, self).copy(cr, uid, id, default, context)
240
241     def context_get(self, cr, uid, context=None):
242         user = self.browse(cr, uid, uid, context)
243         result = {}
244         for k in self._columns.keys():
245             if k.startswith('context_'):
246                 result[k[8:]] = getattr(user,k)
247         return result
248
249     def action_get(self, cr, uid, context={}):
250         dataobj = self.pool.get('ir.model.data')
251         data_id = dataobj._get_id(cr, 1, 'base', 'action_res_users_my')
252         return dataobj.browse(cr, uid, data_id, context).res_id
253
254     def action_next(self,cr,uid,ids,context=None):
255         return {
256                 'view_type': 'form',
257                 "view_mode": 'form',
258                 'res_model': 'ir.actions.configuration.wizard',
259                 'type': 'ir.actions.act_window',
260                 'target':'new',
261         }
262
263     def action_continue(self,cr,uid,ids,context={}):
264         return {
265                 'view_type': 'form',
266                 "view_mode": 'form',
267                 'res_model': 'ir.actions.configuration.wizard',
268                 'type': 'ir.actions.act_window',
269                 'target':'new',
270         }
271     def action_new(self,cr,uid,ids,context={}):
272         return {
273                 'view_type': 'form',
274                 "view_mode": 'form',
275                 'res_model': 'res.users',
276                 'view_id':self.pool.get('ir.ui.view').search(cr,uid,[('name','=','res.users.confirm.form')]),
277                 'type': 'ir.actions.act_window',
278                 'target':'new',
279                }
280
281     def _check_company(self, cursor, user, ids):
282         for user in self.browse(cursor, user, ids):
283             if user.company_ids and (user.company_id.id not in map(lambda x: x.id, user.company_ids)):
284                 return False
285         return True
286
287     _constraints = [
288         (_check_company, 'This user can not connect using this company !', ['company_id']),
289     ]
290 users()
291
292 class groups2(osv.osv): ##FIXME: Is there a reason to inherit this object ?
293     _inherit = 'res.groups'
294     _columns = {
295         'users': fields.many2many('res.users', 'res_groups_users_rel', 'gid', 'uid', 'Users'),
296     }
297 groups2()
298
299
300 class res_config_view(osv.osv_memory):
301     _name='res.config.view'
302     _columns = {
303         'name':fields.char('Name', size=64),
304         'view': fields.selection([('simple','Simplified Interface'),('extended','Extended Interface')], 'View Mode', required=True ),
305     }
306     _defaults={
307         'view':lambda *args: 'simple',
308     }
309
310     def action_cancel(self,cr,uid,ids,conect=None):
311         return {
312                 'view_type': 'form',
313                 "view_mode": 'form',
314                 'res_model': 'ir.actions.configuration.wizard',
315                 'type': 'ir.actions.act_window',
316                 'target':'new',
317          }
318     def action_set(self, cr, uid, ids, context=None):
319         res=self.read(cr,uid,ids)[0]
320         users_obj = self.pool.get('res.users')
321         group_obj=self.pool.get('res.groups')
322         if 'view' in res and res['view'] and res['view']=='extended':
323             group_ids=group_obj.search(cr,uid,[('name','ilike','Extended')])
324             if group_ids and len(group_ids):
325                 users_obj.write(cr, uid, [uid],{
326                                 'groups_id':[(4,group_ids[0])]
327                             }, context=context)
328         return {
329                 'view_type': 'form',
330                 "view_mode": 'form',
331                 'res_model': 'ir.actions.configuration.wizard',
332                 'type': 'ir.actions.act_window',
333                 'target':'new',
334             }
335
336 res_config_view()
337
338 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
339