[IMP] sale order line invisible type
[odoo/odoo.git] / addons / mail / mail_group.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2010-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 datetime as DT
23 import openerp
24 import openerp.tools as tools
25 from operator import itemgetter
26 from osv import osv
27 from osv import fields
28 from tools.translate import _
29
30 class mail_group(osv.Model):
31     """
32     A mail_group is a collection of users sharing messages in a discussion
33     group. Group users are users that follow the mail group, using the
34     subscription/follow mechanism of OpenSocial. A mail group has nothing
35     in common with res.users.group.
36     """
37     
38     _description = 'Discussion group'
39     _name = 'mail.group'
40     _inherit = ['mail.thread']
41     _inherits = {'mail.alias': 'alias_id', 'ir.ui.menu': 'menu_id'}
42
43     def _get_image(self, cr, uid, ids, name, args, context=None):
44         result = dict.fromkeys(ids, False)
45         for obj in self.browse(cr, uid, ids, context=context):
46             result[obj.id] = tools.image_get_resized_images(obj.image)
47         return result
48     
49     def _set_image(self, cr, uid, id, name, value, args, context=None):
50         return self.write(cr, uid, [id], {'image': tools.image_resize_image_big(value)}, context=context)
51     
52     def _get_last_month_msg_nbr(self, cr, uid, ids, name, args, context=None):
53         result = {}
54         for id in ids:
55             lower_date = (DT.datetime.now() - DT.timedelta(days=30)).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
56             result[id] = self.message_search(cr, uid, [id], limit=None, domain=[('date', '>=', lower_date)], count=True, context=context)
57         return result
58     
59     def _get_default_image(self, cr, uid, context=None):
60         image_path = openerp.modules.get_module_resource('mail', 'static/src/img', 'groupdefault.png')
61         return tools.image_resize_image_big(open(image_path, 'rb').read().encode('base64'))
62     
63     _columns = {
64         'description': fields.text('Description'),
65         'menu_id': fields.many2one('ir.ui.menu', string='Related Menu', required=True, ondelete="cascade"),
66         'responsible_id': fields.many2one('res.users', string='Responsible',
67             ondelete='set null', required=True, select=1,
68             help="Responsible of the group that has all rights on the record."),
69         'public': fields.selection([('public', 'Public'), ('private', 'Private'), ('groups', 'Selected Group Only')],
70             string='Privacy', required=True,
71             help='This group is visible by non members. '\
72                  'Invisible groups can add members through the invite button.'),
73         'group_public_id': fields.many2one('res.groups', string='Authorized Group'),
74         'group_ids': fields.many2many('res.groups', rel='mail_group_res_group_rel',
75             id1='mail_group_id', id2='groups_id', string='Auto Subscription',
76             help="Members of those groups will automatically added as followers. "\
77                  "Note that they will be able to manage their subscription manually "\
78                  "if necessary."),
79         'image': fields.binary("Photo",
80             help="This field holds the image used as photo for the "\
81                  "user. The image is base64 encoded, and PIL-supported. "\
82                  "It is limited to a 12024x1024 px image."),
83         'image_medium': fields.function(_get_image, fnct_inv=_set_image,
84             string="Medium-sized photo", type="binary", multi="_get_image",
85             store = {
86                 'mail.group': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
87             },
88             help="Medium-sized photo of the group. It is automatically "\
89                  "resized as a 180x180px image, with aspect ratio preserved. "\
90                  "Use this field in form views or some kanban views."),
91         'image_small': fields.function(_get_image, fnct_inv=_set_image,
92             string="Small-sized photo", type="binary", multi="_get_image",
93             store = {
94                 'mail.group': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
95             },
96             help="Small-sized photo of the group. It is automatically "\
97                  "resized as a 50x50px image, with aspect ratio preserved. "\
98                  "Use this field anywhere a small image is required."),
99         'last_month_msg_nbr': fields.function(_get_last_month_msg_nbr, type='integer',
100             string='Messages count for last month'),
101         'alias_id': fields.many2one('mail.alias', 'Alias', ondelete="cascade", 
102                                     help="The email address associated with this group. New emails received will automatically "
103                                          "create new topics."),
104     }
105
106     def _get_default_employee_group(self, cr, uid, context=None):
107         ref = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'group_user')
108         return ref and ref[1] or False
109
110     def _get_menu_parent(self, cr, uid, context=None):
111         ref = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'mail', 'mail_group_root')
112         return ref and ref[1] or False
113
114     _defaults = {
115         'public': 'groups',
116         'group_public_id': _get_default_employee_group,
117         'responsible_id': (lambda s, cr, uid, ctx: uid),
118         'image': _get_default_image,
119         'parent_id': _get_menu_parent,
120         'alias_domain': False, # always hide alias during creation 
121     }
122
123     def _subscribe_user_with_group_m2m_command(self, cr, uid, ids, group_ids_command, context=None):
124         # form: {'group_ids': [(3, 10), (3, 3), (4, 10), (4, 3)]} or {'group_ids': [(6, 0, [ids]}
125         user_group_ids = [command[1] for command in group_ids_command if command[0] == 4]
126         user_group_ids += [id for command in group_ids_command if command[0] == 6 for id in command[2]]
127         # retrieve the user member of those groups
128         user_ids = []
129         res_groups_obj = self.pool.get('res.groups')
130         for group in res_groups_obj.browse(cr, uid, user_group_ids, context=context):
131             user_ids += [user.id for user in group.users]
132         # subscribe the users
133         return self.message_subscribe(cr, uid, ids, user_ids, context=context)
134
135     def create(self, cr, uid, vals, context=None):
136         mail_alias = self.pool.get('mail.alias')
137         if not vals.get('alias_id'):
138             vals.pop('alias_name', None) # prevent errors during copy()
139             alias_id = mail_alias.create_unique_alias(cr, uid, 
140                           # Using '+' allows using subaddressing for those who don't
141                           # have a catchall domain setup.
142                           {'alias_name': "group+"+vals['name']},
143                           model_name=self._name, context=context)
144             vals['alias_id'] = alias_id
145
146         mail_group_id = super(mail_group, self).create(cr, uid, vals, context)
147
148         # Create client action for this group and link the menu to it
149         ref = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'mail', 'action_mail_group_feeds')
150         if ref:
151             search_ref = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'mail', 'view_message_search_wall')
152             params = {
153                 'search_view_id': search_ref and search_ref[1] or False,
154                 'domain': [('model','=','mail.group'),('res_id','=',mail_group_id)],
155                 'res_model': 'mail.group',
156                 'res_id': mail_group_id,
157                 'thread_level': 2
158             }
159             cobj = self.pool.get('ir.actions.client')
160             newref = cobj.copy(cr, uid, ref[1], default={'params': str(params), 'name': vals['name']}, context=context)
161             self.write(cr, uid, [mail_group_id], {'action': 'ir.actions.client,'+str(newref), 'mail_group_id': mail_group_id}, context=context)
162
163         mail_alias.write(cr, uid, [vals['alias_id']], {"alias_force_thread_id": mail_group_id}, context)
164        
165         if vals.get('group_ids'):
166             self._subscribe_user_with_group_m2m_command(cr, uid, [mail_group_id], vals.get('group_ids'), context=context)
167
168         return mail_group_id
169
170     def unlink(self, cr, uid, ids, context=None):
171         # Cascade-delete mail aliases as well, as they should not exist without the mail group.
172         mail_alias = self.pool.get('mail.alias')
173         alias_ids = [group.alias_id.id for group in self.browse(cr, uid, ids, context=context) if group.alias_id]
174         res = super(mail_group, self).unlink(cr, uid, ids, context=context)
175         mail_alias.unlink(cr, uid, alias_ids, context=context)
176         return res
177
178     def write(self, cr, uid, ids, vals, context=None):
179         if vals.get('group_ids'):
180             self._subscribe_user_with_group_m2m_command(cr, uid, ids, vals.get('group_ids'), context=context)
181         return super(mail_group, self).write(cr, uid, ids, vals, context=context)
182
183     def action_group_join(self, cr, uid, ids, context=None):
184         return self.message_subscribe(cr, uid, ids, context=context)
185
186     def action_group_leave(self, cr, uid, ids, context=None):
187         return self.message_unsubscribe(cr, uid, ids, context=context)
188
189     # ----------------------------------------
190     # OpenChatter methods and notifications
191     # ----------------------------------------
192
193     def message_get_monitored_follower_fields(self, cr, uid, ids, context=None):
194         """ Add 'responsible_id' to the monitored fields """
195         res = super(mail_group, self).message_get_monitored_follower_fields(cr, uid, ids, context=context)
196         return res + ['responsible_id']