30ef2b25124fc61fd31d21c16d574f9efed40b80
[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     }
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 init(self, cr):
71         # Installation hook to create aliases for all users, right after _auto_init
72         registry = RegistryManager.get(cr.dbname)
73         mail_alias = registry.get('mail.alias')
74         res_users = registry.get('res.users')
75         users_no_alias = res_users.search(cr, SUPERUSER_ID, [('alias_id', '=', False)])
76         # Use read() not browse(), to avoid prefetching uninitialized inherited fields
77         for user_data in res_users.read(cr, SUPERUSER_ID, users_no_alias, ['login']):
78             alias_id = mail_alias.create_unique_alias(cr, SUPERUSER_ID, {'alias_name': user_data['login'],
79                                                                          'alias_force_id': user_data['id']},
80                                                       model_name=self._name)
81             res_users.write(cr, SUPERUSER_ID, user_data['id'], {'alias_id': alias_id})
82             _logger.info('Mail alias created for user %s (uid %s)', user_data['login'], user_data['id'])
83
84         # Finally attempt to reinstate the missing constraint
85         try:
86             cr.execute('ALTER TABLE res_users ALTER COLUMN alias_id SET NOT NULL')
87         except Exception:
88             pass
89
90     def create(self, cr, uid, data, context=None):
91         # create default alias same as the login
92         mail_alias = self.pool.get('mail.alias')
93         alias_id = mail_alias.create_unique_alias(cr, uid, {'alias_name': data['login']}, model_name=self._name, context=context)
94         data['alias_id'] = alias_id
95         data.pop('alias_name', None) # prevent errors during copy()
96         user_id = super(res_users, self).create(cr, uid, data, context=context)
97         mail_alias.write(cr, SUPERUSER_ID, [alias_id], {"alias_force_thread_id": user_id}, context)
98
99         user = self.browse(cr, uid, user_id, context=context)
100         # make user follow itself
101         self.message_subscribe(cr, uid, [user_id], [user_id], context=context)
102         # create a welcome message
103         company_name = user.company_id.name if user.company_id else _('the company')
104         message = _('%s joined the %s network! Take a moment to welcome %s.') % (user.name, company_name, user.name)
105         self.message_append_note(cr, uid, [user_id], body=message, type='comment', context=context)
106         return user_id
107     
108     def write(self, cr, uid, ids, vals, context=None):
109         # User alias is sync'ed with login
110         if vals.get('login'): vals['alias_name'] = vals['login']
111         return super(res_users, self).write(cr, uid, ids, vals, context=context)
112
113     def unlink(self, cr, uid, ids, context=None):
114         # Cascade-delete mail aliases as well, as they should not exist without the user.
115         alias_pool = self.pool.get('mail.alias')
116         alias_ids = [user.alias_id.id for user in self.browse(cr, uid, ids, context=context) if user.alias_id]
117         res = super(res_users, self).unlink(cr, uid, ids, context=context)
118         alias_pool.unlink(cr, uid, alias_ids, context=context)
119         return res
120     
121     def message_search_get_domain(self, cr, uid, ids, context=None):
122         """ Override of message_search_get_domain for partner discussion page.
123             The purpose is to add messages directly sent to user using
124             @user_login.
125         """
126         initial_domain = super(res_users, self).message_search_get_domain(cr, uid, ids, context=context)
127         custom_domain = []
128         for user in self.browse(cr, uid, ids, context=context):
129             if custom_domain:
130                 custom_domain += ['|']
131             custom_domain += ['|', ('body_text', 'like', '@%s' % (user.login)), ('body_html', 'like', '@%s' % (user.login))]
132         return ['|'] + initial_domain + custom_domain
133
134 class res_users_mail_group(osv.osv):
135     """ Update of res.groups class
136         - if adding/removing users from a group, check mail.groups linked to
137           this user group, and subscribe / unsubscribe them from the discussion
138           group. This is done by overriding the write method.
139     """
140     _name = 'res.users'
141     _inherit = ['res.users', 'mail.thread']
142
143     def write(self, cr, uid, ids, vals, context=None):
144         write_res = super(res_users_mail_group, self).write(cr, uid, ids, vals, context=context)
145         if vals.get('groups_id'):
146             # form: {'group_ids': [(3, 10), (3, 3), (4, 10), (4, 3)]} or {'group_ids': [(6, 0, [ids]}
147             user_group_ids = [command[1] for command in vals['groups_id'] if command[0] == 4]
148             user_group_ids += [id for command in vals['groups_id'] if command[0] == 6 for id in command[2]]
149             mail_group_obj = self.pool.get('mail.group')
150             mail_group_ids = mail_group_obj.search(cr, uid, [('group_ids', 'in', user_group_ids)], context=context)
151             mail_group_obj.message_subscribe(cr, uid, mail_group_ids, ids, context=context)
152         return write_res
153         
154
155 class res_groups_mail_group(osv.osv):
156     """ Update of res.groups class
157         - if adding/removing users from a group, check mail.groups linked to
158           this user group, and subscribe / unsubscribe them from the discussion
159           group. This is done by overriding the write method.
160     """
161     _name = 'res.groups'
162     _inherit = 'res.groups'
163
164     def write(self, cr, uid, ids, vals, context=None):
165         if vals.get('users'):
166             # form: {'group_ids': [(3, 10), (3, 3), (4, 10), (4, 3)]} or {'group_ids': [(6, 0, [ids]}
167             user_ids = [command[1] for command in vals['users'] if command[0] == 4]
168             user_ids += [id for command in vals['users'] if command[0] == 6 for id in command[2]]
169             mail_group_obj = self.pool.get('mail.group')
170             mail_group_ids = mail_group_obj.search(cr, uid, [('group_ids', 'in', ids)], context=context)
171             mail_group_obj.message_subscribe(cr, uid, mail_group_ids, user_ids, context=context)
172         return super(res_groups_mail_group, self).write(cr, uid, ids, vals, context=context)