Debian Codegraph @

addons/portal/wizard/portal_wizard.py

raw symbols SCIP
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 import logging
4
5 from odoo.tools.translate import _
6 from odoo.tools import email_normalize
7 from odoo.exceptions import UserError
8
9 from odoo import api, fields, models, Command
10
11
12 _logger = logging.getLogger(__name__)
13
14
15 class PortalWizard(models.TransientModel):
16 """
17 A wizard to manage the creation/removal of portal users.
18 """
19
20 _name = 'portal.wizard'
21 _description = 'Grant Portal Access'
22
23 def _default_partner_ids(self):
24 partner_ids = self.env.context.get('default_partner_ids', []) or self.env.context.get('active_ids', [])
25 contact_ids = set()
26 for partner in self.env['res.partner'].sudo().browse(partner_ids):
27 contact_partners = partner.child_ids.filtered(lambda p: p.type in ('contact', 'other')) | partner
28 contact_ids |= set(contact_partners.ids)
29
30 return [Command.link(contact_id) for contact_id in contact_ids]
31
32 partner_ids = fields.Many2many('res.partner', string='Partners', default=_default_partner_ids)
33 user_ids = fields.One2many('portal.wizard.user', 'wizard_id', string='Users', compute='_compute_user_ids', store=True, readonly=False)
34 welcome_message = fields.Text('Invitation Message', help="This text is included in the email sent to new users of the portal.")
35
36 @api.depends('partner_ids')
37 def _compute_user_ids(self):
38 for portal_wizard in self:
39 portal_wizard.user_ids = [
40 Command.create({
41 'partner_id': partner.id,
42 'email': partner.email,
43 })
44 for partner in portal_wizard.partner_ids
45 ]
46
47 @api.model
48 def action_open_wizard(self):
49 """Create a "portal.wizard" and open the form view.
50
51 We need a server action for that because the one2many "user_ids" records need to
52 exist to be able to execute an a button action on it. If they have no ID, the
53 buttons will be disabled and we won't be able to click on them.
54
55 That's why we need a server action, to create the records and then open the form
56 view on them.
57 """
58 portal_wizard = self.create({})
59 return portal_wizard._action_open_modal()
60
61 def _action_open_modal(self):
62 """Allow to keep the wizard modal open after executing the action."""
63 return {
64 'name': _('Portal Access Management'),
65 'type': 'ir.actions.act_window',
66 'res_model': 'portal.wizard',
67 'view_mode': 'form',
68 'res_id': self.id,
69 'target': 'new',
70 }
71
72
73 class PortalWizardUser(models.TransientModel):
74 """
75 A model to configure users in the portal wizard.
76 """
77
78 _name = 'portal.wizard.user'
79 _description = 'Portal User Config'
80
81 wizard_id = fields.Many2one('portal.wizard', string='Wizard', required=True, ondelete='cascade')
82 partner_id = fields.Many2one('res.partner', string='Contact', required=True, readonly=True, ondelete='cascade')
83 email = fields.Char('Email')
84
85 user_id = fields.Many2one('res.users', string='User', compute='_compute_user_id', compute_sudo=True)
86 login_date = fields.Datetime(related='user_id.login_date', string='Latest Authentication')
87 is_portal = fields.Boolean('Is Portal', compute='_compute_group_details')
88 is_internal = fields.Boolean('Is Internal', compute='_compute_group_details')
89 email_state = fields.Selection([
90 ('ok', 'Valid'),
91 ('ko', 'Invalid'),
92 ('exist', 'Already Registered')],
93 string='Status', compute='_compute_email_state', default='ok')
94
95 @api.depends('email')
96 def _compute_email_state(self):
97 portal_users_with_email = self.filtered(lambda user: email_normalize(user.email))
98 (self - portal_users_with_email).email_state = 'ko'
99
100 existing_users = self.env['res.users'].with_context(active_test=False).sudo().search_read(
101 self._get_similar_users_domain(portal_users_with_email),
102 self._get_similar_users_fields()
103 )
104 for portal_user in portal_users_with_email:
105 if next((user for user in existing_users if self._is_portal_similar_than_user(user, portal_user)), None):
106 portal_user.email_state = 'exist'
107 else:
108 portal_user.email_state = 'ok'
109
110 @api.depends('partner_id')
111 def _compute_user_id(self):
112 for portal_wizard_user in self:
113 user = portal_wizard_user.partner_id.with_context(active_test=False).user_ids
114 portal_wizard_user.user_id = user[0] if user else False
115
116 @api.depends('user_id', 'user_id.group_ids')
117 def _compute_group_details(self):
118 for portal_wizard_user in self:
119 user = portal_wizard_user.user_id
120
121 if user and user._is_internal():
122 portal_wizard_user.is_internal = True
123 portal_wizard_user.is_portal = False
124 elif user and user._is_portal():
125 portal_wizard_user.is_internal = False
126 portal_wizard_user.is_portal = True
127 else:
128 portal_wizard_user.is_internal = False
129 portal_wizard_user.is_portal = False
130
131 def action_grant_access(self):
132 """Grant the portal access to the partner.
133
134 If the partner has no linked user, we will create a new one in the same company
135 as the partner (or in the current company if not set).
136
137 An invitation email will be sent to the partner.
138 """
139 self.ensure_one()
140 self._assert_user_email_uniqueness()
141
142 if self.is_portal or self.is_internal:
143 raise UserError(_('The partner "%s" already has the portal access.', self.partner_id.name))
144
145 group_portal = self.env.ref('base.group_portal')
146 group_public = self.env.ref('base.group_public')
147
148 self._update_partner_email()
149 user_sudo = self.user_id.sudo()
150
151 if not user_sudo:
152 # create a user if necessary and make sure it is in the portal group
153 company = self.partner_id.company_id or self.env.company
154 user_sudo = self.sudo().with_company(company.id)._create_user()
155
156 if not user_sudo.active or not self.is_portal:
157 user_sudo.write({'active': True, 'group_ids': [(4, group_portal.id), (3, group_public.id)]})
158 # prepare for the signup process
159 user_sudo.partner_id.signup_prepare()
160
161 self.with_context(active_test=True)._send_email()
162
163 return self.action_refresh_modal()
164
165 def action_revoke_access(self):
166 """Remove the user of the partner from the portal group.
167
168 If the user was only in the portal group, we archive it.
169 """
170 self.ensure_one()
171 if not self.is_portal:
172 raise UserError(_('The partner "%s" has no portal access or is internal.', self.partner_id.name))
173
174 group_portal = self.env.ref('base.group_portal')
175 group_public = self.env.ref('base.group_public')
176
177 self._update_partner_email()
178
179 # Remove the sign up token, so it can not be used
180 self.partner_id.sudo().signup_type = None
181
182 user_sudo = self.user_id.sudo()
183
184 # remove the user from the portal group
185 if user_sudo and user_sudo._is_portal():
186 user_sudo.write({'group_ids': [(3, group_portal.id), (4, group_public.id)], 'active': False})
187
188 return self.action_refresh_modal()
189
190 def action_invite_again(self):
191 """Re-send the invitation email to the partner."""
192 self.ensure_one()
193 self._assert_user_email_uniqueness()
194
195 if not self.is_portal:
196 raise UserError(_('You should first grant the portal access to the partner "%s".', self.partner_id.name))
197
198 self._update_partner_email()
199 self.with_context(active_test=True)._send_email()
200
201 return self.action_refresh_modal()
202
203 def action_refresh_modal(self):
204 """Refresh the portal wizard modal and keep it open. Used as fallback action of email state icon buttons,
205 required as they must be non-disabled buttons to fire mouse events to show tooltips on email state."""
206 return self.wizard_id._action_open_modal()
207
208 def _create_user(self):
209 """ create a new user for wizard_user.partner_id
210 :returns record of res.users
211 """
212 return self.env['res.users'].with_context(no_reset_password=True)._create_user_from_template({
213 'email': email_normalize(self.email),
214 'login': email_normalize(self.email),
215 'partner_id': self.partner_id.id,
216 'company_id': self.env.company.id,
217 'company_ids': [(6, 0, self.env.company.ids)],
218 })
219
220 def _send_email(self):
221 """ send notification email to a new portal user """
222 self.ensure_one()
223
224 template = self.env.ref('auth_signup.portal_set_password_email')
225 if not template:
226 raise UserError(_('The template "Portal: new user" not found for sending email to the portal user.'))
227
228 lang = self.user_id.sudo().lang
229 partner = self.user_id.sudo().partner_id
230 partner.signup_prepare()
231
232 template.with_context(dbname=self.env.cr.dbname, lang=lang, welcome_message=self.wizard_id.welcome_message, medium='portalinvite').send_mail(self.user_id.id, force_send=True)
233
234 return True
235
236 def _assert_user_email_uniqueness(self):
237 """Check that the email can be used to create a new user."""
238 self.ensure_one()
239 if self.email_state == 'ko':
240 raise UserError(_('The contact "%s" does not have a valid email.', self.partner_id.name))
241 if self.email_state == 'exist':
242 raise UserError(_('The contact "%s" has the same email as an existing user', self.partner_id.name))
243
244 def _update_partner_email(self):
245 """Update partner email on portal action, if a new one was introduced and is valid."""
246 email_normalized = email_normalize(self.email)
247 if self.email_state == 'ok' and email_normalize(self.partner_id.email) != email_normalized:
248 self.partner_id.write({'email': email_normalized})
249
250 def _get_similar_users_domain(self, portal_users_with_email):
251 """ Returns the domain needed to find the users that have the same email
252 as portal users.
253 :param portal_users_with_email: portal users that have an email address.
254 """
255 normalized_emails = [email_normalize(portal_user.email) for portal_user in portal_users_with_email]
256 return [('login', 'in', normalized_emails)]
257
258 def _get_similar_users_fields(self):
259 """ Returns a list of field elements to extract from users.
260 """
261 return ['id', 'login']
262
263 def _is_portal_similar_than_user(self, user, portal_user):
264 """ Checks if the credentials of a portal user and a user are the same
265 (users are distinct and their emails are similar).
266 """
267 return user['login'] == email_normalize(portal_user.email) and user['id'] != portal_user.user_id.id