# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
import logging
import random
import threading
from ast import literal_eval
from markupsafe import Markup
from odoo import api, exceptions, fields, models, _
from odoo.osv import expression
from odoo.tools import float_compare, float_round
from odoo.tools.safe_eval import safe_eval
_logger = logging.getLogger(__name__)
class Team(models.Model):
_name = 'crm.team'
_inherit = ['mail.alias.mixin', 'crm.team']
_description = 'Sales Team'
use_leads = fields.Boolean('Leads', help="Check this box to filter and qualify incoming requests as leads before converting them into opportunities and assigning them to a salesperson.")
use_opportunities = fields.Boolean('Pipeline', default=True, help="Check this box to manage a presales process with opportunities.")
alias_id = fields.Many2one(help="The email address associated with this channel. New emails received will automatically create new leads assigned to the channel.")
# assignment
assignment_enabled = fields.Boolean('Lead Assign', compute='_compute_assignment_enabled')
assignment_auto_enabled = fields.Boolean('Auto Assignment', compute='_compute_assignment_enabled')
assignment_optout = fields.Boolean('Skip auto assignment')
assignment_max = fields.Integer(
'Lead Average Capacity', compute='_compute_assignment_max',
help='Monthly average leads capacity for all salesmen belonging to the team')
assignment_domain = fields.Char(
'Assignment Domain', tracking=True,
help='Additional filter domain when fetching unassigned leads to allocate to the team.')
# statistics about leads / opportunities / both
lead_unassigned_count = fields.Integer(
string='# Unassigned Leads', compute='_compute_lead_unassigned_count')
lead_all_assigned_month_count = fields.Integer(
string='# Leads/Opps assigned this month', compute='_compute_lead_all_assigned_month_count',
help="Number of leads and opportunities assigned this last month.")
lead_all_assigned_month_exceeded = fields.Boolean('Exceed monthly lead assignement', compute="_compute_lead_all_assigned_month_count",
help="True if the monthly lead assignment count is greater than the maximum assignment limit, false otherwise."
)
opportunities_count = fields.Integer(
string='# Opportunities', compute='_compute_opportunities_data')
opportunities_amount = fields.Monetary(
string='Opportunities Revenues', compute='_compute_opportunities_data')
opportunities_overdue_count = fields.Integer(
string='# Overdue Opportunities', compute='_compute_opportunities_overdue_data')
opportunities_overdue_amount = fields.Monetary(
string='Overdue Opportunities Revenues', compute='_compute_opportunities_overdue_data',)
# properties
lead_properties_definition = fields.PropertiesDefinition('Lead Properties')
@api.depends('crm_team_member_ids.assignment_max')
def _compute_assignment_max(self):
for team in self:
team.assignment_max = sum(member.assignment_max for member in team.crm_team_member_ids)
def _compute_assignment_enabled(self):
assign_enabled = self.env['ir.config_parameter'].sudo().get_param('crm.lead.auto.assignment', False)
auto_assign_enabled = False
if assign_enabled:
assign_cron = self.sudo().env.ref('crm.ir_cron_crm_lead_assign', raise_if_not_found=False)
auto_assign_enabled = assign_cron.active if assign_cron else False
self.assignment_enabled = assign_enabled
self.assignment_auto_enabled = auto_assign_enabled
def _compute_lead_unassigned_count(self):
leads_data = self.env['crm.lead']._read_group([
('team_id', 'in', self.ids),
('type', '=', 'lead'),
('user_id', '=', False),
], ['team_id'], ['__count'])
counts = {team.id: count for team, count in leads_data}
for team in self:
team.lead_unassigned_count = counts.get(team.id, 0)
@api.depends('crm_team_member_ids.lead_month_count', 'assignment_max')
def _compute_lead_all_assigned_month_count(self):
for team in self:
team.lead_all_assigned_month_count = sum(member.lead_month_count for member in team.crm_team_member_ids)
team.lead_all_assigned_month_exceeded = team.lead_all_assigned_month_count > team.assignment_max
def _compute_opportunities_data(self):
opportunity_data = self.env['crm.lead']._read_group([
('team_id', 'in', self.ids),
('probability', '<', 100),
('type', '=', 'opportunity'),
], ['team_id'], ['__count', 'expected_revenue:sum'])
counts_amounts = {team.id: (count, expected_revenue_sum) for team, count, expected_revenue_sum in opportunity_data}
for team in self:
team.opportunities_count, team.opportunities_amount = counts_amounts.get(team.id, (0, 0))
def _compute_opportunities_overdue_data(self):
opportunity_data = self.env['crm.lead']._read_group([
('team_id', 'in', self.ids),
('probability', '<', 100),
('type', '=', 'opportunity'),
('date_deadline', '<', fields.Date.to_string(fields.Datetime.now()))
], ['team_id'], ['__count', 'expected_revenue:sum'])
counts_amounts = {team.id: (count, expected_revenue_sum) for team, count, expected_revenue_sum in opportunity_data}
for team in self:
team.opportunities_overdue_count, team.opportunities_overdue_amount = counts_amounts.get(team.id, (0, 0))
@api.onchange('use_leads', 'use_opportunities')
def _onchange_use_leads_opportunities(self):
if not self.use_leads and not self.use_opportunities:
self.alias_name = False
@api.constrains('assignment_domain')
def _constrains_assignment_domain(self):
for team in self:
try:
domain = literal_eval(team.assignment_domain or '[]')
if domain:
self.env['crm.lead'].search(domain, limit=1)
except Exception:
raise exceptions.ValidationError(_('Assignment domain for team %(team)s is incorrectly formatted', team=team.name))
# ------------------------------------------------------------
# ORM
# ------------------------------------------------------------
def write(self, vals):
result = super(Team, self).write(vals)
if 'use_leads' in vals or 'use_opportunities' in vals:
for team in self:
alias_vals = team._alias_get_creation_values()
team.write({
'alias_name': alias_vals.get('alias_name', team.alias_name),
'alias_defaults': alias_vals.get('alias_defaults'),
})
return result
def unlink(self):
""" When unlinking, concatenate ``crm.lead.scoring.frequency`` linked to
the team into "no team" statistics. """
frequencies = self.env['crm.lead.scoring.frequency'].search([('team_id', 'in', self.ids)])
if frequencies:
existing_noteam = self.env['crm.lead.scoring.frequency'].sudo().search([
('team_id', '=', False),
('variable', 'in', frequencies.mapped('variable'))
])
for frequency in frequencies:
# skip void-like values
if float_compare(frequency.won_count, 0.1, 2) != 1 and float_compare(frequency.lost_count, 0.1, 2) != 1:
continue
match = existing_noteam.filtered(lambda frequ_nt: frequ_nt.variable == frequency.variable and frequ_nt.value == frequency.value)
if match:
# remove extra .1 that may exist in db as those are artifacts of initializing
# frequency table. Final value of 0 will be set to 0.1.
exist_won_count = float_round(match.won_count, precision_digits=0, rounding_method='HALF-UP')
exist_lost_count = float_round(match.lost_count, precision_digits=0, rounding_method='HALF-UP')
add_won_count = float_round(frequency.won_count, precision_digits=0, rounding_method='HALF-UP')
add_lost_count = float_round(frequency.lost_count, precision_digits=0, rounding_method='HALF-UP')
new_won_count = exist_won_count + add_won_count
new_lost_count = exist_lost_count + add_lost_count
match.won_count = new_won_count if float_compare(new_won_count, 0.1, 2) == 1 else 0.1
match.lost_count = new_lost_count if float_compare(new_lost_count, 0.1, 2) == 1 else 0.1
else:
existing_noteam += self.env['crm.lead.scoring.frequency'].sudo().create({
'lost_count': frequency.lost_count if float_compare(frequency.lost_count, 0.1, 2) == 1 else 0.1,
'team_id': False,
'value': frequency.value,
'variable': frequency.variable,
'won_count': frequency.won_count if float_compare(frequency.won_count, 0.1, 2) == 1 else 0.1,
})
return super(Team, self).unlink()
# ------------------------------------------------------------
# MESSAGING
# ------------------------------------------------------------
def _alias_get_creation_values(self):
values = super(Team, self)._alias_get_creation_values()
values['alias_model_id'] = self.env['ir.model']._get('crm.lead').id
if self.id:
if not self.use_leads and not self.use_opportunities:
values['alias_name'] = False
values['alias_defaults'] = defaults = literal_eval(self.alias_defaults or "{}")
has_group_use_lead = self.env.user.has_group('crm.group_use_lead')
defaults['type'] = 'lead' if has_group_use_lead and self.use_leads else 'opportunity'
defaults['team_id'] = self.id
return values
# ------------------------------------------------------------
# LEAD ASSIGNMENT
# ------------------------------------------------------------
@api.model
def _cron_assign_leads(self, work_days=None):
""" Cron method assigning leads. Leads are allocated to all teams and
assigned to their members. It is based on either cron configuration
either forced through ``work_days`` parameter.
When based on cron configuration purpose of cron is to assign leads to
sales persons. Assigned workload is set to the workload those sales
people should perform between two cron iterations. If their maximum
capacity is reached assign process will not assign them any more lead.
e.g. cron is active with interval_number 3, interval_type days. This
means cron runs every 3 days. Cron will assign leads for 3 work days
to salespersons each 3 days unless their maximum capacity is reached.
If cron runs on an hour- or minute-based schedule minimum assignment
performed is equivalent to 0.2 workdays to avoid rounding issues.
Max assignment performed is for 30 days as it is better to run more
often than planning for more than one month. Assign process is best
designed to run every few hours (~4 times / day) or each few days.
See ``CrmTeam.action_assign_leads()`` and its sub methods for more
details about assign process.
:param float work_days: see ``CrmTeam.action_assign_leads()``;
"""
assign_cron = self.sudo().env.ref('crm.ir_cron_crm_lead_assign', raise_if_not_found=False)
if not work_days and assign_cron and assign_cron.active:
if assign_cron.interval_type == 'months':
work_days = 30 # maximum one month of work
elif assign_cron.interval_type == 'weeks':
work_days = min(30, assign_cron.interval_number * 7) # max at 30 (better lead repartition)
elif assign_cron.interval_type == 'days':
work_days = min(30, assign_cron.interval_number * 1) # max at 30 (better lead repartition)
elif assign_cron.interval_type == 'hours':
work_days = max(0.2, assign_cron.interval_number / 24) # min at 0.2 to avoid small numbers issues
elif assign_cron.interval_type == 'minutes':
work_days = max(0.2, assign_cron.interval_number / 1440) # min at 0.2 to avoid small numbers issues
work_days = work_days if work_days else 1 # avoid void values
self.env['crm.team'].search([
'&', '|', ('use_leads', '=', True), ('use_opportunities', '=', True),
('assignment_optout', '=', False)
])._action_assign_leads(work_days=work_days)
return True
def action_assign_leads(self, work_days=1, log=True):
""" Manual (direct) leads assignment. This method both
* assigns leads to teams given by self;
* assigns leads to salespersons belonging to self;
See sub methods for more details about assign process.
:param float work_days: number of work days to consider when assigning leads
to teams or salespersons. We consider that Member.assignment_max (or
its equivalent on team model) targets 30 work days. We make a ratio
between expected number of work days and maximum assignment for those
30 days to know lead count to assign.
:return action: a client notification giving some insights on assign
process;
"""
teams_data, members_data = self._action_assign_leads(work_days=work_days)
# format result messages
logs = self._action_assign_leads_logs(teams_data, members_data)
html_message = Markup('
').join(logs)
notif_message = ' '.join(logs)
# log a note in case of manual assign (as this method will mainly be called
# on singleton record set, do not bother doing a specific message per team)
log_action = _("Lead Assignment requested by %(user_name)s", user_name=self.env.user.name)
log_message = Markup("
%s
%s
%s
" % _("Create an Opportunity") if user_team_id: if self.user_has_groups('sales_team.group_sale_manager'): action['help'] += "
%s
" % _("""As you are a member of no Sales Team, you are showed the Pipeline of the first team by default. To work with the CRM, you should join a team.""", self.env.ref('sales_team.crm_team_action_config').id) else: action['help'] += "%s
" % _("""As you are a member of no Sales Team, you are showed the Pipeline of the first team by default. To work with the CRM, you should join a team.""") action_context = safe_eval(action['context'], {'uid': self.env.uid}) if user_team_id: action_context['default_team_id'] = user_team_id action['context'] = action_context return action def _compute_dashboard_button_name(self): super(Team, self)._compute_dashboard_button_name() team_with_pipelines = self.filtered(lambda el: el.use_opportunities) team_with_pipelines.update({'dashboard_button_name': _("Pipeline")}) def action_primary_channel_button(self): self.ensure_one() if self.use_opportunities: action = self.env['ir.actions.actions']._for_xml_id('crm.crm_case_form_view_salesteams_opportunity') rcontext = { 'team': self, } action['help'] = self.env['ir.ui.view']._render_template('crm.crm_action_helper', values=rcontext) return action return super(Team,self).action_primary_channel_button() def _graph_get_model(self): if self.use_opportunities: return 'crm.lead' return super(Team,self)._graph_get_model() def _graph_date_column(self): if self.use_opportunities: return 'create_date' return super(Team,self)._graph_date_column() def _graph_y_query(self): if self.use_opportunities: return 'count(*)' return super(Team,self)._graph_y_query() def _extra_sql_conditions(self): if self.use_opportunities: return "AND type LIKE 'opportunity'" return super(Team,self)._extra_sql_conditions() def _graph_title_and_key(self): if self.use_opportunities: return ['', _('New Opportunities')] # no more title return super(Team, self)._graph_title_and_key()