| 1 |
# Part of Odoo. See LICENSE file for full copyright and licensing details. |
| 2 |
|
| 3 |
import datetime |
| 4 |
import logging |
| 5 |
|
| 6 |
from odoo import _, api, fields, models, modules, tools |
| 7 |
from odoo.addons.iap.tools import iap_tools |
| 8 |
from odoo.tools import OrderedSet |
| 9 |
|
| 10 |
_logger = logging.getLogger(__name__) |
| 11 |
|
| 12 |
|
| 13 |
class CrmLead(models.Model): |
| 14 |
_inherit = 'crm.lead' |
| 15 |
|
| 16 |
iap_enrich_done = fields.Boolean(string='Enrichment done', help='Whether IAP service for lead enrichment based on email has been performed on this lead.') |
| 17 |
show_enrich_button = fields.Boolean(string='Allow manual enrich', compute="_compute_show_enrich_button") |
| 18 |
|
| 19 |
@api.depends('email_from', 'probability', 'iap_enrich_done', 'reveal_id') |
| 20 |
def _compute_show_enrich_button(self): |
| 21 |
for lead in self: |
| 22 |
if not lead.active or not lead.email_from or lead.email_state == 'incorrect' or lead.iap_enrich_done or lead.reveal_id or lead.probability == 100: |
| 23 |
lead.show_enrich_button = False |
| 24 |
else: |
| 25 |
lead.show_enrich_button = True |
| 26 |
|
| 27 |
@api.model |
| 28 |
def _iap_enrich_leads_cron(self, enrich_hours_delay=24, batch_size=50): |
| 29 |
timeDelta = self.env.cr.now() - datetime.timedelta(hours=enrich_hours_delay) |
| 30 |
# Get all leads not lost nor won (lost: active = False) |
| 31 |
leads = self.search([ |
| 32 |
('iap_enrich_done', '=', False), |
| 33 |
'|', ('probability', '<', 100), ('probability', '=', False), |
| 34 |
('email_from', '!=', False), |
| 35 |
('reveal_id', '=', False), |
| 36 |
('create_date', '>', timeDelta), |
| 37 |
('active', '=', True), |
| 38 |
]) |
| 39 |
leads.iap_enrich(batch_size=batch_size) |
| 40 |
|
| 41 |
@api.model_create_multi |
| 42 |
def create(self, vals_list): |
| 43 |
leads = super().create(vals_list) |
| 44 |
enrich_mode = self.env['ir.config_parameter'].sudo().get_param('crm.iap.lead.enrich.setting', 'auto') |
| 45 |
if enrich_mode == 'auto': |
| 46 |
cron = self.env.ref('crm_iap_enrich.ir_cron_lead_enrichment', raise_if_not_found=False) |
| 47 |
if cron: |
| 48 |
cron._trigger() |
| 49 |
return leads |
| 50 |
|
| 51 |
def iap_enrich(self, *, batch_size=50): |
| 52 |
from_cron = bool(self.env.context.get('cron_id')) |
| 53 |
send_notification = not from_cron |
| 54 |
|
| 55 |
def process_leads(leads): |
| 56 |
lead_emails = {} |
| 57 |
for lead in leads: |
| 58 |
# If lead is lost, active == False, but is anyway removed from the search in the cron. |
| 59 |
if lead.probability == 100 or lead.iap_enrich_done: |
| 60 |
continue |
| 61 |
# Skip if no email (different from wrong email leading to no email_normalized) |
| 62 |
if not lead.email_from: |
| 63 |
continue |
| 64 |
|
| 65 |
normalized_email = tools.email_normalize(lead.email_from) |
| 66 |
if not normalized_email: |
| 67 |
lead.write({'iap_enrich_done': True}) |
| 68 |
lead.message_post_with_source( |
| 69 |
'crm_iap_enrich.mail_message_lead_enrich_no_email', |
| 70 |
subtype_xmlid='mail.mt_note', |
| 71 |
) |
| 72 |
continue |
| 73 |
|
| 74 |
email_domain = normalized_email.split('@')[1] |
| 75 |
# Discard domains of generic email providers as it won't return relevant information |
| 76 |
if email_domain in iap_tools._MAIL_PROVIDERS: |
| 77 |
lead.write({'iap_enrich_done': True}) |
| 78 |
lead.message_post_with_source( |
| 79 |
'crm_iap_enrich.mail_message_lead_enrich_notfound', |
| 80 |
subtype_xmlid='mail.mt_note', |
| 81 |
) |
| 82 |
else: |
| 83 |
lead_emails[lead.id] = email_domain |
| 84 |
if not lead_emails: |
| 85 |
return |
| 86 |
|
| 87 |
try: |
| 88 |
iap_response = self.env['iap.enrich.api']._request_enrich(lead_emails) |
| 89 |
except iap_tools.InsufficientCreditError: |
| 90 |
_logger.info('Lead enrichment failed because of insufficient credit') |
| 91 |
if send_notification: |
| 92 |
self.env['iap.account']._send_no_credit_notification( |
| 93 |
service_name='reveal', |
| 94 |
title=_("Not enough credits for Lead Enrichment")) |
| 95 |
raise |
| 96 |
except Exception as e: |
| 97 |
if send_notification: |
| 98 |
self.env['iap.account']._send_error_notification( |
| 99 |
message=_('An error occurred during lead enrichment')) |
| 100 |
_logger.info('An error occurred during lead enrichment: %s', e) |
| 101 |
return |
| 102 |
else: |
| 103 |
if send_notification: |
| 104 |
self.env['iap.account']._send_success_notification( |
| 105 |
message=_("The leads/opportunities have successfully been enriched")) |
| 106 |
_logger.info('Batch of %s leads successfully enriched', len(lead_emails)) |
| 107 |
self._iap_enrich_from_response(iap_response) |
| 108 |
|
| 109 |
if from_cron: |
| 110 |
self.env['ir.cron']._commit_progress(remaining=len(self)) |
| 111 |
all_lead_ids = OrderedSet(self.ids) |
| 112 |
while all_lead_ids: |
| 113 |
leads = self.browse(all_lead_ids).try_lock_for_update(limit=batch_size) |
| 114 |
if not leads: |
| 115 |
_logger.error('A batch of leads could not be enriched (locked): %s', repr(self.browse(all_lead_ids))) |
| 116 |
# all are locked, schedule the cron later when the records might be unlocked |
| 117 |
self.env.ref('crm_iap_enrich.ir_cron_lead_enrichment')._trigger(self.env.cr.now() + datetime.timedelta(minutes=5)) |
| 118 |
if from_cron: |
| 119 |
# mark the cron as fully done to prevent immediate reschedule |
| 120 |
self.env['ir.cron']._commit_progress(remaining=0) |
| 121 |
break |
| 122 |
all_lead_ids -= set(leads._ids) |
| 123 |
|
| 124 |
if from_cron: |
| 125 |
# Using commit progress for processed leads |
| 126 |
try: |
| 127 |
process_leads(leads) |
| 128 |
time_left = self.env['ir.cron']._commit_progress(len(leads)) |
| 129 |
except iap_tools.InsufficientCreditError: |
| 130 |
# Since there are no credits left, there is no point to process the other batches |
| 131 |
# set remaining=0 to avoid being called again |
| 132 |
self.env['ir.cron']._commit_progress(remaining=0) |
| 133 |
break |
| 134 |
except Exception: |
| 135 |
self.env.cr.rollback() |
| 136 |
_logger.error('A batch of leads could not be enriched: %s', repr(leads)) |
| 137 |
time_left = self.env['ir.cron']._commit_progress(len(leads)) |
| 138 |
if not time_left: |
| 139 |
break |
| 140 |
else: |
| 141 |
# Commit processed batch to avoid complete rollbacks and therefore losing credits. |
| 142 |
try: |
| 143 |
if modules.module.current_test: |
| 144 |
with self.env.cr.savepoint(): |
| 145 |
process_leads(leads) |
| 146 |
else: |
| 147 |
process_leads(leads) |
| 148 |
self.env.cr.commit() |
| 149 |
except iap_tools.InsufficientCreditError: |
| 150 |
# Since there are no credits left, there is no point to process the other batches |
| 151 |
break |
| 152 |
except Exception: |
| 153 |
if not modules.module.current_test: |
| 154 |
self.env.cr.rollback() |
| 155 |
_logger.error('A batch of leads could not be enriched: %s', repr(leads)) |
| 156 |
|
| 157 |
@api.model |
| 158 |
def _iap_enrich_from_response(self, iap_response): |
| 159 |
""" Handle from the service and enrich the lead accordingly |
| 160 |
|
| 161 |
:param iap_response: dict{lead_id: company data or False} |
| 162 |
""" |
| 163 |
for lead in self.search([('id', 'in', list(iap_response.keys()))]): # handle unlinked data by performing a search |
| 164 |
iap_data = iap_response.get(str(lead.id)) |
| 165 |
if not iap_data: |
| 166 |
lead.write({'iap_enrich_done': True}) |
| 167 |
lead.message_post_with_source( |
| 168 |
'crm_iap_enrich.mail_message_lead_enrich_notfound', |
| 169 |
subtype_xmlid='mail.mt_note', |
| 170 |
) |
| 171 |
continue |
| 172 |
|
| 173 |
values = {'iap_enrich_done': True} |
| 174 |
lead_fields = ['partner_name', 'reveal_id', 'street', 'city', 'zip'] |
| 175 |
iap_fields = ['name', 'clearbit_id', 'location', 'city', 'postal_code'] |
| 176 |
for lead_field, iap_field in zip(lead_fields, iap_fields): |
| 177 |
if not lead[lead_field] and iap_data.get(iap_field): |
| 178 |
values[lead_field] = iap_data[iap_field] |
| 179 |
|
| 180 |
if not lead.phone and iap_data.get('phone_numbers'): |
| 181 |
values['phone'] = iap_data['phone_numbers'][0] |
| 182 |
if not lead.country_id and iap_data.get('country_code'): |
| 183 |
country = self.env['res.country'].search([('code', '=', iap_data['country_code'].upper())]) |
| 184 |
values['country_id'] = country.id |
| 185 |
else: |
| 186 |
country = lead.country_id |
| 187 |
if not lead.state_id and country and iap_data.get('state_code'): |
| 188 |
state = self.env['res.country.state'].search([ |
| 189 |
('code', '=', iap_data['state_code']), |
| 190 |
('country_id', '=', country.id) |
| 191 |
]) |
| 192 |
values['state_id'] = state.id |
| 193 |
|
| 194 |
lead.write(values) |
| 195 |
|
| 196 |
template_values = iap_data |
| 197 |
template_values['flavor_text'] = _("Lead enriched based on email address") |
| 198 |
lead.message_post_with_source( |
| 199 |
'iap_mail.enrich_company', |
| 200 |
render_values=template_values, |
| 201 |
subtype_xmlid='mail.mt_note', |
| 202 |
) |
| 203 |
|
| 204 |
def _merge_get_fields_specific(self): |
| 205 |
return { |
| 206 |
** super()._merge_get_fields_specific(), |
| 207 |
'iap_enrich_done': lambda fname, leads: any(lead.iap_enrich_done for lead in leads), |
| 208 |
} |