184eb2b502ebecc57432672b986b3f6785c2fca7
[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']
39     _inherits = {'mail.alias': 'alias_id'}
40     
41     _columns = {
42         'notification_email_pref': fields.selection([
43             ('all', 'All Feeds'),
44             ('to_me', 'Only send directly to me'),
45             ('none', 'Never')
46             ], 'Receive Feeds by Email', required=True,
47             help="Choose in which case you want to receive an email when you "\
48                  "receive new feeds."),
49         'alias_id': fields.many2one('mail.alias', 'Alias', ondelete="cascade", required=True, 
50             help="Email address internally associated with this user. Incoming "\
51                  "emails will appear in the user's notifications."),
52     }
53     
54     _defaults = {
55         'notification_email_pref': 'to_me',
56         'alias_domain': False, # always hide alias during creation
57     }
58
59     def __init__(self, pool, cr):
60         """ Override of __init__ to add access rights on notification_email_pref
61             field. Access rights are disabled by default, but allowed on
62             fields defined in self.SELF_WRITEABLE_FIELDS.
63         """
64         init_res = super(res_users, self).__init__(pool, cr)
65         # duplicate list to avoid modifying the original reference
66         self.SELF_WRITEABLE_FIELDS = list(self.SELF_WRITEABLE_FIELDS)
67         self.SELF_WRITEABLE_FIELDS.append('notification_email_pref')
68         return init_res
69
70     def _auto_init(self, cr, context=None):
71         """Installation hook to create aliases for all users and avoid constraint errors."""
72         
73         # disable the unique alias_id not null constraint, to avoid spurious warning during 
74         # super.auto_init. We'll reinstall it afterwards.
75         self._columns['alias_id'].required = False
76
77         super(res_users,self)._auto_init(cr, context=context)
78         
79         registry = RegistryManager.get(cr.dbname)
80         mail_alias = registry.get('mail.alias')
81         res_users_model = registry.get('res.users')
82         users_no_alias = res_users_model.search(cr, SUPERUSER_ID, [('alias_id', '=', False)])
83         # Use read() not browse(), to avoid prefetching uninitialized inherited fields
84         for user_data in res_users_model.read(cr, SUPERUSER_ID, users_no_alias, ['login']):
85             alias_id = mail_alias.create_unique_alias(cr, SUPERUSER_ID, {'alias_name': user_data['login'],
86                                                                          'alias_force_id': user_data['id']},
87                                                       model_name=self._name)
88             res_users_model.write(cr, SUPERUSER_ID, user_data['id'], {'alias_id': alias_id})
89             _logger.info('Mail alias created for user %s (uid %s)', user_data['login'], user_data['id'])
90
91         # Finally attempt to reinstate the missing constraint
92         try:
93             cr.execute('ALTER TABLE res_users ALTER COLUMN alias_id SET NOT NULL')
94         except Exception:
95             _logger.warning("Table '%s': unable to set a NOT NULL constraint on column '%s' !\n"\
96                             "If you want to have it, you should update the records and execute manually:\n"\
97                             "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL",
98                             self._table, 'alias_id', self._table, 'alias_id')
99
100         self._columns['alias_id'].required = True
101
102     def create(self, cr, uid, data, context=None):
103         # create default alias same as the login
104         mail_alias = self.pool.get('mail.alias')
105         alias_id = mail_alias.create_unique_alias(cr, uid, {'alias_name': data['login']}, model_name=self._name, context=context)
106         data['alias_id'] = alias_id
107         data.pop('alias_name', None) # prevent errors during copy()
108         user_id = super(res_users, self).create(cr, uid, data, context=context)
109         mail_alias.write(cr, SUPERUSER_ID, [alias_id], {"alias_force_thread_id": user_id}, context)
110
111         user = self.browse(cr, uid, user_id, context=context)
112         # make user follow itself
113         self.message_subscribe(cr, uid, [user_id], [user_id], context=context)
114         # create a welcome message
115         company_name = user.company_id.name if user.company_id else _('the company')
116         message = '''%s has joined %s! Welcome in OpenERP !
117
118 Your homepage is a summary of messages you received and key information about documents you follow.
119
120 The top menu bar contains all applications you installed. You can use this <i>Settings</i> menu to install more applications, activate others features or give access to new users.
121
122 To setup your preferences (name, email signature, avatar), click on the top right corner.''' % (user.name, company_name)
123         self.message_append_note(cr, uid, [user_id], subject='Welcome to OpenERP', body=message, type='comment', content_subtype='html', context=context)
124         return user_id
125     
126     def write(self, cr, uid, ids, vals, context=None):
127         # User alias is sync'ed with login
128         if vals.get('login'): vals['alias_name'] = vals['login']
129         return super(res_users, self).write(cr, uid, ids, vals, context=context)
130
131     def unlink(self, cr, uid, ids, context=None):
132         # Cascade-delete mail aliases as well, as they should not exist without the user.
133         alias_pool = self.pool.get('mail.alias')
134         alias_ids = [user.alias_id.id for user in self.browse(cr, uid, ids, context=context) if user.alias_id]
135         res = super(res_users, self).unlink(cr, uid, ids, context=context)
136         alias_pool.unlink(cr, uid, alias_ids, context=context)
137         return res
138     
139     def message_append(self, cr, uid, threads, subject, body_text=None, body_html=None,
140                         type='email', email_date=None, parent_id=False,
141                         content_subtype='plain', state=None,
142                         partner_ids=None, email_from=False, email_to=False,
143                         email_cc=None, email_bcc=None, reply_to=None,
144                         headers=None, message_id=False, references=None,
145                         attachments=None, original=None, context=None):
146         """ Override of message_append. Messages appened to res.users are
147             redirected to the related partner. Using partner_id.message_append,
148             messages will have correct model and id, set to res_partner and
149             partner_id.id.
150         """
151         for user in self.browse(cr, uid, threads, context=context):
152             user.partner_id.message_append(subject, body_text, body_html, type, email_date, parent_id,
153                 content_subtype, state, partner_ids, email_from, email_to, email_cc, email_bcc, reply_to,
154                 headers, message_id, references, attachments, original)
155
156     def message_search_get_domain(self, cr, uid, ids, context=None):
157         """ Override of message_search_get_domain for partner discussion page.
158             The purpose is to add messages directly sent to user using
159             @user_login.
160         """
161         initial_domain = super(res_users, self).message_search_get_domain(cr, uid, ids, context=context)
162         custom_domain = []
163         for user in self.browse(cr, uid, ids, context=context):
164             if custom_domain:
165                 custom_domain += ['|']
166             custom_domain += ['|', ('body_text', 'like', '@%s' % (user.login)), ('body_html', 'like', '@%s' % (user.login))]
167         return ['|'] + initial_domain + custom_domain
168
169 class res_users_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.users'
176     _inherit = ['res.users', 'mail.thread']
177
178     def write(self, cr, uid, ids, vals, context=None):
179         write_res = super(res_users_mail_group, self).write(cr, uid, ids, vals, context=context)
180         if vals.get('groups_id'):
181             # form: {'group_ids': [(3, 10), (3, 3), (4, 10), (4, 3)]} or {'group_ids': [(6, 0, [ids]}
182             user_group_ids = [command[1] for command in vals['groups_id'] if command[0] == 4]
183             user_group_ids += [id for command in vals['groups_id'] if command[0] == 6 for id in command[2]]
184             mail_group_obj = self.pool.get('mail.group')
185             mail_group_ids = mail_group_obj.search(cr, uid, [('group_ids', 'in', user_group_ids)], context=context)
186             mail_group_obj.message_subscribe(cr, uid, mail_group_ids, ids, context=context)
187         return write_res
188         
189
190 class res_groups_mail_group(osv.osv):
191     """ Update of res.groups class
192         - if adding/removing users from a group, check mail.groups linked to
193           this user group, and subscribe / unsubscribe them from the discussion
194           group. This is done by overriding the write method.
195     """
196     _name = 'res.groups'
197     _inherit = 'res.groups'
198
199     def write(self, cr, uid, ids, vals, context=None):
200         if vals.get('users'):
201             # form: {'group_ids': [(3, 10), (3, 3), (4, 10), (4, 3)]} or {'group_ids': [(6, 0, [ids]}
202             user_ids = [command[1] for command in vals['users'] if command[0] == 4]
203             user_ids += [id for command in vals['users'] if command[0] == 6 for id in command[2]]
204             mail_group_obj = self.pool.get('mail.group')
205             mail_group_ids = mail_group_obj.search(cr, uid, [('group_ids', 'in', ids)], context=context)
206             mail_group_obj.message_subscribe(cr, uid, mail_group_ids, user_ids, context=context)
207         return super(res_groups_mail_group, self).write(cr, uid, ids, vals, context=context)