Debian Codegraph @

addons/website_crm_iap_reveal/models/crm_reveal_rule.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # Part of Odoo. See LICENSE file for full copyright and licensing details.
3
4 import datetime
5 import itertools
6 import logging
7 import re
8 from dateutil.relativedelta import relativedelta
9
10 import odoo
11 from odoo import api, fields, models, tools, _
12 from odoo.addons.iap.tools import iap_tools
13 from odoo.addons.crm.models import crm_stage
14 from odoo.exceptions import ValidationError
15
16 _logger = logging.getLogger(__name__)
17
18 DEFAULT_ENDPOINT = 'https://iap-services.odoo.com'
19 DEFAULT_REVEAL_BATCH_LIMIT = 25
20 DEFAULT_REVEAL_MONTH_VALID = 6
21
22
23 class CrmRevealRule(models.Model):
24 _name = 'crm.reveal.rule'
25 _description = 'CRM Lead Generation Rules'
26 _order = 'sequence'
27
28 name = fields.Char(string='Rule Name', required=True)
29 active = fields.Boolean(default=True)
30
31 # Website Traffic Filter
32 country_ids = fields.Many2many('res.country', string='Countries', help='Only visitors of following countries will be converted into leads/opportunities (using GeoIP).')
33 website_id = fields.Many2one('website', help='Restrict Lead generation to this website.')
34 state_ids = fields.Many2many('res.country.state', string='States', help='Only visitors of following states will be converted into leads/opportunities.')
35 regex_url = fields.Char(string='URL Expression', help='Regex to track website pages. Leave empty to track the entire website, or / to target the homepage. Example: /page* to track all the pages which begin with /page')
36 sequence = fields.Integer(help='Used to order the rules with same URL and countries. '
37 'Rules with a lower sequence number will be processed first.')
38
39 # Company Criteria Filter
40 industry_tag_ids = fields.Many2many('crm.iap.lead.industry', string='Industries', help='Leave empty to always match. Odoo will not create lead if no match')
41 filter_on_size = fields.Boolean(string="Filter on Size", default=True, help="Filter companies based on their size.")
42 company_size_min = fields.Integer(string='Company Size', default=0)
43 company_size_max = fields.Integer(default=1000)
44
45 # Contact Generation Filter
46 contact_filter_type = fields.Selection([('role', 'Role'), ('seniority', 'Seniority')], string="Filter On", required=True, default='role')
47 preferred_role_id = fields.Many2one('crm.iap.lead.role', string='Preferred Role')
48 other_role_ids = fields.Many2many('crm.iap.lead.role', string='Other Roles')
49 seniority_id = fields.Many2one('crm.iap.lead.seniority', string='Seniority')
50 extra_contacts = fields.Integer(string='Number of Contacts', help='This is the number of contacts to track if their role/seniority match your criteria. Their details will show up in the history thread of generated leads/opportunities. One credit is consumed per tracked contact.', default=1)
51
52 # Lead / Opportunity Data
53 lead_for = fields.Selection([('companies', 'Companies'), ('people', 'Companies and their Contacts')], string='Data Tracking', required=True, default='companies', help='Choose whether to track companies only or companies and their contacts')
54 lead_type = fields.Selection([('lead', 'Lead'), ('opportunity', 'Opportunity')], string='Type', required=True, default='opportunity')
55 suffix = fields.Char(string='Suffix', help='This will be appended in name of generated lead so you can identify lead/opportunity is generated with this rule')
56 team_id = fields.Many2one('crm.team', string='Sales Team', ondelete="set null")
57 tag_ids = fields.Many2many('crm.tag', string='Tags')
58 user_id = fields.Many2one('res.users', string='Salesperson')
59 priority = fields.Selection(crm_stage.AVAILABLE_PRIORITIES, string='Priority')
60 lead_ids = fields.One2many('crm.lead', 'reveal_rule_id', string='Generated Lead / Opportunity')
61 lead_count = fields.Integer(compute='_compute_lead_count', string='Number of Generated Leads')
62 opportunity_count = fields.Integer(compute='_compute_lead_count', string='Number of Generated Opportunity')
63
64 # This limits the number of extra contact.
65 # Even if more than 5 extra contacts provided service will return only 5 contacts (see service module for more)
66 _limit_extra_contacts = models.Constraint(
67 'check(extra_contacts >= 1 and extra_contacts <= 5)',
68 'Maximum 5 contacts are allowed!',
69 )
70
71 def _compute_lead_count(self):
72 leads = self.env['crm.lead']._read_group([
73 ('reveal_rule_id', 'in', self.ids)
74 ], groupby=['reveal_rule_id', 'type'], aggregates=['__count'])
75 mapping = {(reveal_rule.id, type_crm): count for reveal_rule, type_crm, count in leads}
76 for rule in self:
77 rule.lead_count = mapping.get((rule.id, 'lead'), 0)
78 rule.opportunity_count = mapping.get((rule.id, 'opportunity'), 0)
79
80 @api.constrains('regex_url')
81 def _check_regex_url(self):
82 try:
83 if self.regex_url:
84 re.compile(self.regex_url)
85 except Exception:
86 raise ValidationError(_('Enter Valid Regex.'))
87
88 @api.model_create_multi
89 def create(self, vals_list):
90 self.env.registry.clear_cache() # Clear the cache in order to recompute _get_active_rules
91 return super().create(vals_list)
92
93 def write(self, vals):
94 fields_set = {
95 'country_ids', 'regex_url', 'active'
96 }
97 if set(vals.keys()) & fields_set:
98 self.env.registry.clear_cache() # Clear the cache in order to recompute _get_active_rules
99 return super().write(vals)
100
101 def unlink(self):
102 self.env.registry.clear_cache() # Clear the cache in order to recompute _get_active_rules
103 return super().unlink()
104
105 def action_get_lead_tree_view(self):
106 action = self.env["ir.actions.actions"]._for_xml_id("crm.crm_lead_all_leads")
107 action['domain'] = [('id', 'in', self.lead_ids.ids), ('type', '=', 'lead')]
108 action['context'] = dict(self.env.context, create=False)
109 return action
110
111 def action_get_opportunity_tree_view(self):
112 action = self.env["ir.actions.actions"]._for_xml_id("crm.crm_lead_opportunities")
113 action['domain'] = [('id', 'in', self.lead_ids.ids), ('type', '=', 'opportunity')]
114 action['context'] = dict(self.env.context, create=False)
115 return action
116
117 @api.model
118 @tools.ormcache()
119 def _get_active_rules(self):
120 """
121 Returns informations about the all rules.
122 The return is in the form :
123 {
124 'country_rules': {
125 'BE': [0, 1],
126 'US': [0]
127 },
128 'rules': [
129 {
130 'id': 0,
131 'regex': ***,
132 'website_id': 1,
133 'country_codes': ['BE', 'US'],
134 'state_codes': [('BE', False), ('US', 'NY'), ('US', 'CA')]
135 },
136 {
137 'id': 1,
138 'regex': ***,
139 'website_id': 1,
140 'country_codes': ['BE'],
141 'state_codes': [('BE', False)]
142 }
143 ]
144 }
145 """
146 country_rules = {}
147 rules_records = self.search([])
148 rules = []
149 # Fixes for special cases
150 for rule in rules_records:
151 regex_url = rule['regex_url']
152 if not regex_url:
153 regex_url = '.*' # for all pages if url not given
154 elif regex_url == '/':
155 regex_url = '.*/$' # for home
156 countries = rule.country_ids.mapped('code')
157
158 # First apply rules for any state in countries
159 states = [(country_id.code, False) for country_id in rule.country_ids]
160 if rule.state_ids:
161 for state_id in rule.state_ids:
162 if (state_id.country_id.code, False) in states:
163 # Remove country because rule doesn't apply to any state
164 states.remove((state_id.country_id.code, False))
165 states += [(state_id.country_id.code, state_id.code)]
166
167 rules.append({
168 'id': rule.id,
169 'regex': regex_url,
170 'website_id': rule.website_id.id if rule.website_id else False,
171 'country_codes': countries,
172 'state_codes': states
173 })
174 for country in countries:
175 country_rules = self._add_to_country(country_rules, country, len(rules) - 1)
176 return {
177 'country_rules': country_rules,
178 'rules': rules,
179 }
180
181 def _add_to_country(self, country_rules, country, rule_index):
182 """
183 Add the rule index to the country code in the country_rules
184 """
185 if country not in country_rules:
186 country_rules[country] = []
187 country_rules[country].append(rule_index)
188 return country_rules
189
190 def _match_url(self, website_id, url, country_code, state_code, rules_excluded):
191 """
192 Return the matching rule based on the country, the website and URL.
193 """
194 all_rules = self._get_active_rules()
195 rules_id = all_rules['country_rules'].get(country_code, [])
196
197 rules_matched = []
198 for rule_index in rules_id:
199 rule = all_rules['rules'][rule_index]
200 if ((country_code, state_code) in rule['state_codes'] or (country_code, False) in rule['state_codes'])\
201 and (not rule['website_id'] or rule['website_id'] == website_id)\
202 and str(rule['id']) not in rules_excluded\
203 and re.search(rule['regex'], url):
204 rules_matched.append(rule)
205 return rules_matched
206
207 @api.model
208 def _process_lead_generation(self, autocommit=True):
209 """ Cron Job for lead generation from page view """
210 _logger.info('Start Reveal Lead Generation')
211 self.env['crm.reveal.view']._clean_reveal_views()
212 self._unlink_unrelevant_reveal_view()
213 reveal_views = self._get_reveal_views_to_process()
214 view_count = 0
215 while reveal_views:
216 view_count += len(reveal_views)
217 server_payload = self._prepare_iap_payload(dict(reveal_views))
218 enough_credit = self._perform_reveal_service(server_payload)
219 if autocommit:
220 # auto-commit for batch processing
221 self.env.cr.commit()
222 if enough_credit:
223 reveal_views = self._get_reveal_views_to_process()
224 else:
225 reveal_views = False
226 _logger.info('End Reveal Lead Generation - %s views processed', view_count)
227
228 @api.model
229 def _unlink_unrelevant_reveal_view(self):
230 """
231 We don't want to create the lead if in past (<6 months) we already
232 created lead with given IP. So, we unlink crm.reveal.view with same IP
233 as a already created lead.
234 """
235 months_valid = self.env['ir.config_parameter'].sudo().get_param('reveal.lead_month_valid', DEFAULT_REVEAL_MONTH_VALID)
236 try:
237 months_valid = int(months_valid)
238 except ValueError:
239 months_valid = DEFAULT_REVEAL_MONTH_VALID
240 domain = []
241 domain.append(('reveal_ip', '!=', False))
242 domain.append(('create_date', '>', fields.Datetime.to_string(datetime.date.today() - relativedelta(months=months_valid))))
243 leads = self.env['crm.lead'].with_context(active_test=False).search(domain)
244 self.env['crm.reveal.view'].search([('reveal_ip', 'in', [lead.reveal_ip for lead in leads])]).unlink()
245
246 @api.model
247 def _get_reveal_views_to_process(self):
248 """ Return list of reveal rule ids grouped by IPs """
249 batch_limit = DEFAULT_REVEAL_BATCH_LIMIT
250 query = """
251 SELECT v.reveal_ip, array_agg(v.reveal_rule_id ORDER BY r.sequence)
252 FROM crm_reveal_view v
253 INNER JOIN crm_reveal_rule r
254 ON v.reveal_rule_id = r.id
255 WHERE v.reveal_state='to_process'
256 GROUP BY v.reveal_ip
257 LIMIT %s
258 """
259
260 self.env.cr.execute(query, [batch_limit])
261 return self.env.cr.fetchall()
262
263 def _prepare_iap_payload(self, pgv):
264 """ This will prepare the page view and returns payload
265 Payload sample
266 {
267 ips: {
268 '192.168.1.1': [1,4],
269 '192.168.1.6': [2,4]
270 },
271 rules: {
272 1: {rule_data},
273 2: {rule_data},
274 4: {rule_data}
275 }
276 }
277 """
278 new_list = list(set(itertools.chain.from_iterable(pgv.values())))
279 rule_records = self.browse(new_list)
280 return {
281 'ips': pgv,
282 'rules': rule_records._get_rules_payload()
283 }
284
285 def _get_rules_payload(self):
286 company_country = self.env.company.country_id
287 rule_payload = {}
288 for rule in self:
289 # accumulate all reveal_ids (separated by ',') into one list
290 # eg: 3 records with values: "175,176", "177" and "190,191"
291 # will become ['175','176','177','190','191']
292 reveal_ids = [
293 reveal_id.strip()
294 for reveal_ids in rule.mapped('industry_tag_ids.reveal_ids')
295 for reveal_id in reveal_ids.split(',')
296 ]
297 data = {
298 'rule_id': rule.id,
299 'lead_for': rule.lead_for,
300 'countries': rule.country_ids.mapped('code'),
301 'filter_on_size': rule.filter_on_size,
302 'company_size_min': rule.company_size_min,
303 'company_size_max': rule.company_size_max,
304 'industry_tags': reveal_ids,
305 'user_country': company_country and company_country.code or False
306 }
307 if rule.lead_for == 'people':
308 data.update({
309 'contact_filter_type': rule.contact_filter_type,
310 'preferred_role': rule.preferred_role_id.reveal_id or '',
311 'other_roles': rule.other_role_ids.mapped('reveal_id'),
312 'seniority': rule.seniority_id.reveal_id or '',
313 'extra_contacts': rule.extra_contacts - 1
314 })
315 rule_payload[rule.id] = data
316 return rule_payload
317
318 def _perform_reveal_service(self, server_payload):
319 result = False
320 account = self.env['iap.account'].get('reveal')
321 params = {
322 'account_token': account.sudo().account_token,
323 'data': server_payload
324 }
325 result = self._iap_contact_reveal(params, timeout=300)
326
327 all_ips, done_ips = list(server_payload['ips'].keys()), []
328 for res in result.get('reveal_data', []):
329 done_ips.append(res['ip'])
330 if not res.get('not_found'):
331 lead = self._create_lead_from_response(res)
332 self.env['crm.reveal.view'].search([('reveal_ip', '=', res['ip'])]).unlink()
333 else:
334 views = self.env['crm.reveal.view'].search([('reveal_ip', '=', res['ip'])])
335 views.write({'reveal_state': 'not_found'})
336 views.flush_recordset()
337
338 if result.get('credit_error'):
339 self.env['crm.iap.lead.helpers']._notify_no_more_credit('reveal', self._name, 'reveal.already_notified')
340 return False
341 else:
342 # avoid loops if IAP return result is broken: otherwise some IP may create loops
343 views = self.env['crm.reveal.view'].search([
344 ('reveal_ip', 'in', [ip for ip in all_ips if ip not in done_ips])
345 ])
346 views.write({'reveal_state': 'not_found'})
347 views.flush_recordset()
348 # reset notified parameter to re-send credit notice if appears again
349 self.env['ir.config_parameter'].sudo().set_param('reveal.already_notified', False)
350 return True
351
352 def _iap_contact_reveal(self, params, timeout=300):
353 endpoint = self.env['ir.config_parameter'].sudo().get_param('reveal.endpoint', DEFAULT_ENDPOINT) + '/iap/clearbit/1/reveal'
354 return iap_tools.iap_jsonrpc(endpoint, params=params, timeout=timeout)
355
356 def _create_lead_from_response(self, result):
357 """ This method will get response from service and create the lead accordingly """
358 if result['rule_id']:
359 rule = self.browse(result['rule_id'])
360 else:
361 # Not create a lead if the information match no rule
362 # If there is no match, the service still returns all informations
363 # in order to let custom code use it.
364 return False
365 if not result['clearbit_id']:
366 return False
367 already_created_lead = self.env['crm.lead'].search_count([('reveal_id', '=', result['clearbit_id'])], limit=1)
368 if already_created_lead:
369 _logger.info('Existing lead for this clearbit_id [%s]', result['clearbit_id'])
370 # Does not create a lead if the reveal_id is already known
371 return False
372 lead_vals = rule._lead_vals_from_response(result)
373
374 lead = self.env['crm.lead'].create(lead_vals)
375
376 template_values = result['reveal_data']
377 template_values.update({
378 'flavor_text': _("Opportunity created by Odoo Lead Generation"),
379 'people_data': result.get('people_data'),
380 })
381 lead.message_post_with_source(
382 'iap_mail.enrich_company',
383 render_values=template_values,
384 subtype_xmlid='mail.mt_note',
385 )
386
387 return lead
388
389 # Methods responsible for format response data in to valid odoo lead data
390 def _lead_vals_from_response(self, result):
391 self.ensure_one()
392 company_data = result['reveal_data']
393 people_data = result.get('people_data')
394 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)
395
396 lead_vals.update({
397 'priority': self.priority,
398 'reveal_ip': result['ip'],
399 'reveal_rule_id': self.id,
400 'referred': 'Website Visitor',
401 'reveal_iap_credits': result['credit'],
402 })
403
404 if self.suffix:
405 lead_vals['name'] = '%s - %s' % (lead_vals['name'], self.suffix)
406
407 return lead_vals