Debian Codegraph @

addons/crm_iap_mine/models/crm_iap_lead_mining_request.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # Part of Odoo. See LICENSE file for full copyright and licensing details.
3
4 import logging
5
6 from odoo import api, fields, models, _, release
7 from odoo.addons.iap.tools import iap_tools
8 from odoo.exceptions import UserError
9 from odoo.tools import is_html_empty
10
11 _logger = logging.getLogger(__name__)
12
13 DEFAULT_ENDPOINT = 'https://iap-services.odoo.com'
14
15 MAX_LEAD = 200
16
17 MAX_CONTACT = 5
18
19 CREDIT_PER_COMPANY = 1
20 CREDIT_PER_CONTACT = 1
21
22
23 class CrmIapLeadMiningRequest(models.Model):
24 _name = 'crm.iap.lead.mining.request'
25 _description = 'CRM Lead Mining Request'
26
27 def _default_lead_type(self):
28 if self.env.user.has_group('crm.group_use_lead'):
29 return 'lead'
30 else:
31 return 'opportunity'
32
33 def _default_country_ids(self):
34 return self.env.user.company_id.country_id
35
36 name = fields.Char(string='Request Number', required=True, readonly=True, default=lambda self: _('New'), copy=False)
37 state = fields.Selection([('draft', 'Draft'), ('error', 'Error'), ('done', 'Done')], string='Status', required=True, default='draft')
38
39 # Request Data
40 lead_number = fields.Integer(string='Number of Leads', required=True, default=3)
41 search_type = fields.Selection([('companies', 'Companies'), ('people', 'Companies and their Contacts')], string='Target', required=True, default='companies')
42 error_type = fields.Selection([
43 ('credits', 'Insufficient Credits'),
44 ('no_result', 'No Result'),
45 ], string='Error Type', copy=False, readonly=True)
46
47 # Lead / Opportunity Data
48
49 lead_type = fields.Selection([('lead', 'Leads'), ('opportunity', 'Opportunities')], string='Type', required=True, default=_default_lead_type)
50 team_id = fields.Many2one(
51 'crm.team', string='Sales Team', ondelete="set null",
52 domain="[('use_opportunities', '=', True)]", readonly=False, compute='_compute_team_id', store=True)
53 user_id = fields.Many2one('res.users', string='Salesperson', default=lambda self: self.env.user)
54 tag_ids = fields.Many2many('crm.tag', string='Tags')
55 lead_ids = fields.One2many('crm.lead', 'lead_mining_request_id', string='Generated Lead / Opportunity')
56 lead_count = fields.Integer(compute='_compute_lead_count', string='Number of Generated Leads')
57
58 # Company Criteria Filter
59 filter_on_size = fields.Boolean(string='Filter on Size', default=False)
60 company_size_min = fields.Integer(string='Size', default=1)
61 company_size_max = fields.Integer(default=1000)
62 country_ids = fields.Many2many('res.country', string='Countries', default=_default_country_ids)
63 state_ids = fields.Many2many('res.country.state', string='States')
64 available_state_ids = fields.One2many('res.country.state', compute='_compute_available_state_ids')
65 industry_ids = fields.Many2many('crm.iap.lead.industry', string='Industries')
66
67 # Contact Generation Filter
68 contact_number = fields.Integer(string='Number of Contacts', default=10)
69 contact_filter_type = fields.Selection([('role', 'Role'), ('seniority', 'Seniority')], string='Filter on', default='role')
70 preferred_role_id = fields.Many2one('crm.iap.lead.role', string='Preferred Role')
71 role_ids = fields.Many2many('crm.iap.lead.role', string='Other Roles')
72 seniority_id = fields.Many2one('crm.iap.lead.seniority', string='Seniority')
73
74 # Fields for the blue tooltip
75 lead_credits = fields.Char(compute='_compute_tooltip', readonly=True)
76 lead_contacts_credits = fields.Char(compute='_compute_tooltip', readonly=True)
77 lead_total_credits = fields.Char(compute='_compute_tooltip', readonly=True)
78
79 @api.onchange('lead_number', 'contact_number')
80 def _compute_tooltip(self):
81 for record in self:
82 company_credits = CREDIT_PER_COMPANY * record.lead_number
83 contact_credits = CREDIT_PER_CONTACT * record.contact_number
84 total_contact_credits = contact_credits * record.lead_number
85 record.lead_contacts_credits = _(
86 "Up to %(credit_count)d additional credits will be consumed to identify %(contact_count)d contacts per company.",
87 credit_count=contact_credits * company_credits,
88 contact_count=record.contact_number,
89 )
90 record.lead_credits = _(
91 "%(credit_count)d credits will be consumed to find %(company_count)d companies.",
92 credit_count=company_credits,
93 company_count=record.lead_number,
94 )
95 record.lead_total_credits = _("This makes a total of %d credits for this request.", total_contact_credits + company_credits)
96
97 @api.depends('lead_ids.lead_mining_request_id')
98 def _compute_lead_count(self):
99 leads_data = self.env['crm.lead']._read_group(
100 [('lead_mining_request_id', 'in', self.ids)],
101 ['lead_mining_request_id'], ['__count'])
102 mapped_data = {
103 lead_mining_request.id: count
104 for lead_mining_request, count in leads_data}
105 for request in self:
106 request.lead_count = mapped_data.get(request.id, 0)
107
108 @api.depends('user_id', 'lead_type')
109 def _compute_team_id(self):
110 """ When changing the user, also set a team_id or restrict team id
111 to the ones user_id is member of. """
112 for mining in self:
113 # setting user as void should not trigger a new team computation
114 if not mining.user_id:
115 continue
116 user = mining.user_id
117 if mining.team_id and user in mining.team_id.member_ids | mining.team_id.user_id:
118 continue
119 team_domain = [('use_leads', '=', True)] if mining.lead_type == 'lead' else [('use_opportunities', '=', True)]
120 team = self.env['crm.team']._get_default_team_id(user_id=user.id, domain=team_domain)
121 mining.team_id = team.id
122
123 @api.depends('country_ids')
124 def _compute_available_state_ids(self):
125 """ States for some specific countries should not be offered as filtering options because
126 they drastically reduce the amount of IAP reveal results.
127
128 For example, in Belgium, only 11% of companies have a defined state within the
129 reveal service while the rest of them have no state defined at all.
130
131 Meaning specifying states for that country will yield a lot less results than what you could
132 expect, which is not the desired behavior.
133 Obviously all companies are active within a state, it's just a lack of data in the reveal
134 service side.
135
136 To help users create meaningful iap searches, we only keep the states filtering for several
137 whitelisted countries (based on their country code).
138 The complete list and reasons for this change can be found on task-2471703. """
139
140 for lead_mining_request in self:
141 countries = lead_mining_request.country_ids.filtered(lambda country:
142 country.code in iap_tools._STATES_FILTER_COUNTRIES_WHITELIST)
143 lead_mining_request.available_state_ids = self.env['res.country.state'].search([
144 ('country_id', 'in', countries.ids)
145 ])
146
147 @api.onchange('available_state_ids')
148 def _onchange_available_state_ids(self):
149 self.state_ids -= self.state_ids.filtered(
150 lambda state: (state._origin.id or state.id) not in self.available_state_ids.ids
151 )
152
153 @api.onchange('lead_number')
154 def _onchange_lead_number(self):
155 if self.lead_number <= 0:
156 self.lead_number = 1
157 elif self.lead_number > MAX_LEAD:
158 self.lead_number = MAX_LEAD
159
160 @api.onchange('contact_number')
161 def _onchange_contact_number(self):
162 if self.contact_number <= 0:
163 self.contact_number = 1
164 elif self.contact_number > MAX_CONTACT:
165 self.contact_number = MAX_CONTACT
166
167 @api.onchange('country_ids')
168 def _onchange_country_ids(self):
169 self.state_ids = []
170
171 @api.onchange('company_size_min')
172 def _onchange_company_size_min(self):
173 if self.company_size_min <= 0:
174 self.company_size_min = 1
175 elif self.company_size_min > self.company_size_max:
176 self.company_size_min = self.company_size_max
177
178 @api.onchange('company_size_max')
179 def _onchange_company_size_max(self):
180 if self.company_size_max < self.company_size_min:
181 self.company_size_max = self.company_size_min
182
183 @api.model
184 def get_empty_list_help(self, help_message):
185 if not is_html_empty(help_message):
186 return help_message
187
188 help_title = _('Create a Lead Mining Request')
189 sub_title = _('Generate new leads based on their country, industry, size, etc.')
190 return super().get_empty_list_help(
191 f'<p class="o_view_nocontent_smiling_face">{help_title}</p><p class="oe_view_nocontent_alias">{sub_title}</p>'
192 )
193
194 def _prepare_iap_payload(self):
195 """
196 This will prepare the data to send to the server
197 """
198 self.ensure_one()
199 payload = {
200 'lead_number': self.lead_number,
201 'search_type': self.search_type,
202 'countries': [{
203 'code': country.code,
204 'states': self.state_ids.filtered(lambda state: state in country.state_ids).mapped('code'),
205 } for country in self.country_ids],
206 }
207
208 if self.filter_on_size:
209 payload.update({'company_size_min': self.company_size_min,
210 'company_size_max': self.company_size_max})
211 if self.industry_ids:
212 # accumulate all reveal_ids (separated by ',') into one list
213 # eg: 3 records with values: "175,176", "177" and "190,191"
214 # will become ['175','176','177','190','191']
215 all_industry_ids = [
216 reveal_id.strip()
217 for reveal_ids in self.mapped('industry_ids.reveal_ids')
218 for reveal_id in reveal_ids.split(',')
219 ]
220 payload['industry_ids'] = all_industry_ids
221 if self.search_type == 'people':
222 payload.update({'contact_number': self.contact_number,
223 'contact_filter_type': self.contact_filter_type})
224 if self.contact_filter_type == 'role':
225 payload.update({'preferred_role': self.preferred_role_id.reveal_id,
226 'other_roles': self.role_ids.mapped('reveal_id')})
227 elif self.contact_filter_type == 'seniority':
228 payload['seniority'] = self.seniority_id.reveal_id
229 return payload
230
231 def _perform_request(self):
232 """
233 This will perform the request and create the corresponding leads.
234 The user will be notified if they don't have enough credits.
235 """
236 self.error_type = False
237 server_payload = self._prepare_iap_payload()
238 reveal_account = self.env['iap.account'].get('reveal')
239 dbuuid = self.env['ir.config_parameter'].sudo().get_param('database.uuid')
240 reveal_ids = [lead['reveal_id'] for lead in self.env['crm.lead'].search_read([('reveal_id', '!=', False)], ['reveal_id'])]
241 params = {
242 'account_token': reveal_account.sudo().account_token,
243 'db_uuid': dbuuid,
244 'query': server_payload,
245 'db_version': release.version,
246 'db_lang': self.env.lang,
247 'country_code': self.env.company.country_id.code,
248 'reveal_ids': reveal_ids,
249 }
250 try:
251 response = self._iap_contact_mining(params, timeout=300)
252 if not response.get('data'):
253 self.error_type = 'no_result'
254 return False
255
256 return response['data']
257 except iap_tools.InsufficientCreditError as e:
258 self.error_type = 'credits'
259 self.state = 'error'
260 return False
261 except Exception as e:
262 raise UserError(_("Your request could not be executed: %s", e))
263
264 def _iap_contact_mining(self, params, timeout=300):
265 endpoint = self.env['ir.config_parameter'].sudo().get_param('reveal.endpoint', DEFAULT_ENDPOINT) + '/api/dnb/1/search_by_criteria'
266 return iap_tools.iap_jsonrpc(endpoint, params=params, timeout=timeout)
267
268 def _create_leads_from_response(self, result):
269 """ This method will get the response from the service and create the leads accordingly """
270 self.ensure_one()
271 lead_vals_list = []
272 messages_to_post = {}
273 for data in result:
274 country = self.env['res.country'].search([('code', '=', data['country_code'])])
275 lead_vals_list.append(self._lead_vals_from_response(data))
276
277 template_values = data
278 template_values.update({
279 'flavor_text': _("Opportunity created by Odoo Lead Generation"),
280 'people_data': data.get('people_data'),
281 'country': country.name,
282 'zip_code': data.get('zip'),
283 'country_id': country.id,
284 })
285 messages_to_post[data['duns']] = template_values
286 leads = self.env['crm.lead'].create(lead_vals_list)
287 for lead in leads:
288 if messages_to_post.get(lead.reveal_id):
289 lead.message_post_with_source(
290 'iap_mail.enrich_company',
291 render_values=messages_to_post[lead.reveal_id],
292 subtype_xmlid='mail.mt_note',
293 )
294
295 # Methods responsible for format response data into valid odoo lead data
296 @api.model
297 def _lead_vals_from_response(self, data):
298 self.ensure_one()
299 company_data = data
300 people_data = []
301 lead_vals = self.env['crm.iap.lead.helpers'].lead_vals_from_response(self.lead_type, self.team_id.id, self.tag_ids.ids, self.user_id.id, company_data, people_data)
302 lead_vals['lead_mining_request_id'] = self.id
303 return lead_vals
304
305 def action_draft(self):
306 self.ensure_one()
307 self.name = _('New')
308 self.state = 'draft'
309
310 def action_submit(self):
311 self.ensure_one()
312 if self.name == _('New'):
313 self.name = self.env['ir.sequence'].next_by_code('crm.iap.lead.mining.request') or _('New')
314 results = self._perform_request()
315
316 if results:
317 self._create_leads_from_response(results)
318 self.state = 'done'
319 if self.lead_type == 'lead':
320 return self.action_get_lead_action()
321 elif self.lead_type == 'opportunity':
322 return self.action_get_opportunity_action()
323 elif self.env.context.get('is_modal'):
324 # when we are inside a modal already, we re-open the same record
325 # that way, the form view is updated and the correct error message appears
326 # (sadly, there is no way to simply 'reload' a form view within a modal)
327 return {
328 'name': _('Generate Leads'),
329 'res_model': 'crm.iap.lead.mining.request',
330 'views': [[False, 'form']],
331 'target': 'new',
332 'type': 'ir.actions.act_window',
333 'res_id': self.id,
334 'context': dict(self.env.context, edit=True)
335 }
336 else:
337 # will reload the form view and show the error message on top
338 return False
339
340 def action_get_lead_action(self):
341 self.ensure_one()
342 action = self.env["ir.actions.actions"]._for_xml_id("crm.crm_lead_all_leads")
343 action['domain'] = [('id', 'in', self.lead_ids.ids), ('type', '=', 'lead')]
344 return action
345
346 def action_get_opportunity_action(self):
347 self.ensure_one()
348 action = self.env["ir.actions.actions"]._for_xml_id("crm.crm_lead_opportunities")
349 action['domain'] = [('id', 'in', self.lead_ids.ids), ('type', '=', 'opportunity')]
350 return action
351
352 def action_buy_credits(self):
353 return {
354 'type': 'ir.actions.act_url',
355 'url': self.env['iap.account'].get_credits_url(service_name='reveal'),
356 }