[FIX] mail.alias: fix constraint creation warnings + properly hide alias on creation...
[odoo/odoo.git] / addons / mail / res_users.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2009-Today OpenERP SA (<http://www.openerp.com>)
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 import logging
23
24 from osv import osv, fields
25 from openerp.modules.registry import RegistryManager
26 from openerp import SUPERUSER_ID
27 from tools.translate import _
28
29 _logger = logging.getLogger(__name__)
30
31 class res_users(osv.osv):
32     """ Update of res.users class
33         - add a preference about sending emails about notifications
34         - make a new user follow itself
35         - add a welcome message
36     """
37     _name = 'res.users'
38     _inherit = ['res.users', 'mail.thread']
39     _inherits = {'mail.alias': 'alias_id'}
40     
41     _columns = {
42         'notification_email_pref': fields.selection([
43             ('all', 'All feeds'),
44             ('comments', 'Only comments'),
45             ('to_me', 'Only when sent directly to me'),
46             ('none', 'Never')
47             ], 'Receive Feeds by Email', required=True,
48             help="Choose in which case you want to receive an email when you "\
49                   "receive new feeds."),
50         'alias_id': fields.many2one('mail.alias', 'Alias', ondelete="cascade", required=True, 
51                                     help="Email address internally associated with this user. Incoming emails will appear "
52                                          "in the user's notifications."),
53     }
54     
55     _defaults = {
56         'notification_email_pref': 'to_me',
57         'alias_domain': False, # always hide alias during creation
58     }
59
60     def __init__(self, pool, cr):
61         """ Override of __init__ to add access rights on notification_email_pref
62             field. Access rights are disabled by default, but allowed on
63             fields defined in self.SELF_WRITEABLE_FIELDS.
64         """
65         init_res = super(res_users, self).__init__(pool, cr)
66         # duplicate list to avoid modifying the original reference
67         self.SELF_WRITEABLE_FIELDS = list(self.SELF_WRITEABLE_FIELDS)
68         self.SELF_WRITEABLE_FIELDS.append('notification_email_pref')
69         return init_res
70
71     def _auto_init(self, cr, context=None):
72         """Installation hook to create aliases for all users and avoid constraint errors."""
73         
74         # disable the unique alias_id not null constraint, to avoid spurious warning during 
75         # super.auto_init. We'll reinstall it afterwards.
76         self._columns['alias_id'].required = False
77
78         super(res_users,self)._auto_init(cr, context=context)
79         
80         registry = RegistryManager.get(cr.dbname)
81         mail_alias = registry.get('mail.alias')
82         res_users_model = registry.get('res.users')
83         users_no_alias = res_users_model.search(cr, SUPERUSER_ID, [('alias_id', '=', False)])
84         # Use read() not browse(), to avoid prefetching uninitialized inherited fields
85         for user_data in res_users_model.read(cr, SUPERUSER_ID, users_no_alias, ['login']):
86             alias_id = mail_alias.create_unique_alias(cr, SUPERUSER_ID, {'alias_name': user_data['login'],
87                                                                          'alias_force_id': user_data['id']},
88                                                       model_name=self._name)
89             res_users_model.write(cr, SUPERUSER_ID, user_data['id'], {'alias_id': alias_id})
90             _logger.info('Mail alias created for user %s (uid %s)', user_data['login'], user_data['id'])
91
92         # Finally attempt to reinstate the missing constraint
93         try:
94             cr.execute('ALTER TABLE res_users ALTER COLUMN alias_id SET NOT NULL')
95         except Exception:
96             _logger.warning("Table '%s': unable to set a NOT NULL constraint on column '%s' !\n"\
97                             "If you want to have it, you should update the records and execute manually:\n"\
98                             "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL",
99                             self._table, 'alias_id', self._table, 'alias_id')
100
101         self._columns['alias_id'].required = True
102
103
104     def create(self, cr, uid, data, context=None):
105         # create default alias same as the login
106         mail_alias = self.pool.get('mail.alias')
107         alias_id = mail_alias.create_unique_alias(cr, uid, {'alias_name': data['login']}, model_name=self._name, context=context)
108         data['alias_id'] = alias_id
109         data.pop('alias_name', None) # prevent errors during copy()
110         user_id = super(res_users, self).create(cr, uid, data, context=context)
111         mail_alias.write(cr, SUPERUSER_ID, [alias_id], {"alias_force_thread_id": user_id}, context)
112
113         user = self.browse(cr, uid, user_id, context=context)
114         # make user follow itself
115         self.message_subscribe(cr, uid, [user_id], [user_id], context=context)
116         # create a welcome message
117         company_name = user.company_id.name if user.company_id else _('the company')
118         message = _('%s joined the %s network! Take a moment to welcome %s.') % (user.name, company_name, user.name)
119         self.message_append_note(cr, uid, [user_id], body=message, type='comment', context=context)
120         return user_id
121     
122     def write(self, cr, uid, ids, vals, context=None):
123         # User alias is sync'ed with login
124         if vals.get('login'): vals['alias_name'] = vals['login']
125         return super(res_users, self).write(cr, uid, ids, vals, context=context)
126
127     def unlink(self, cr, uid, ids, context=None):
128         # Cascade-delete mail aliases as well, as they should not exist without the user.
129         alias_pool = self.pool.get('mail.alias')
130         alias_ids = [user.alias_id.id for user in self.browse(cr, uid, ids, context=context) if user.alias_id]
131         res = super(res_users, self).unlink(cr, uid, ids, context=context)
132         alias_pool.unlink(cr, uid, alias_ids, context=context)
133         return res
134     
135     def message_search_get_domain(self, cr, uid, ids, context=None):
136         """ Override of message_search_get_domain for partner discussion page.
137             The purpose is to add messages directly sent to user using
138             @user_login.
139         """
140         initial_domain = super(res_users, self).message_search_get_domain(cr, uid, ids, context=context)
141         custom_domain = []
142         for user in self.browse(cr, uid, ids, context=context):
143             if custom_domain:
144                 custom_domain += ['|']
145             custom_domain += ['|', ('body_text', 'like', '@%s' % (user.login)), ('body_html', 'like', '@%s' % (user.login))]
146         return ['|'] + initial_domain + custom_domain
147
148 class res_users_mail_group(osv.osv):
149     """ Update of res.groups class
150         - if adding/removing users from a group, check mail.groups linked to
151           this user group, and subscribe / unsubscribe them from the discussion
152           group. This is done by overriding the write method.
153     """
154     _name = 'res.users'
155     _inherit = ['res.users', 'mail.thread']
156
157     def write(self, cr, uid, ids, vals, context=None):
158         write_res = super(res_users_mail_group, self).write(cr, uid, ids, vals, context=context)
159         if vals.get('groups_id'):
160             # form: {'group_ids': [(3, 10), (3, 3), (4, 10), (4, 3)]} or {'group_ids': [(6, 0, [ids]}
161             user_group_ids = [command[1] for command in vals['groups_id'] if command[0] == 4]
162             user_group_ids += [id for command in vals['groups_id'] if command[0] == 6 for id in command[2]]
163             mail_group_obj = self.pool.get('mail.group')
164             mail_group_ids = mail_group_obj.search(cr, uid, [('group_ids', 'in', user_group_ids)], context=context)
165             mail_group_obj.message_subscribe(cr, uid, mail_group_ids, ids, context=context)
166         return write_res
167         
168
169 class res_groups_mail_group(osv.osv):
170     """ Update of res.groups class
171         - if adding/removing users from a group, check mail.groups linked to
172           this user group, and subscribe / unsubscribe them from the discussion
173           group. This is done by overriding the write method.
174     """
175     _name = 'res.groups'
176     _inherit = 'res.groups'
177
178     def write(self, cr, uid, ids, vals, context=None):
179         if vals.get('users'):
180             # form: {'group_ids': [(3, 10), (3, 3), (4, 10), (4, 3)]} or {'group_ids': [(6, 0, [ids]}
181             user_ids = [command[1] for command in vals['users'] if command[0] == 4]
182             user_ids += [id for command in vals['users'] if command[0] == 6 for id in command[2]]
183             mail_group_obj = self.pool.get('mail.group')
184             mail_group_ids = mail_group_obj.search(cr, uid, [('group_ids', 'in', ids)], context=context)
185             mail_group_obj.message_subscribe(cr, uid, mail_group_ids, user_ids, context=context)
186         return super(res_groups_mail_group, self).write(cr, uid, ids, vals, context=context)