# -*- 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 odoo import api, exceptions, fields, models, _
from odoo.osv import expression
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(
'mail.alias', string='Alias', ondelete="restrict", required=True,
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 Capacity', compute='_compute_assignment_max',
help='Monthly leads 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.")
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',)
# alias: improve fields coming from _inherits, use inherited to avoid replacing them
alias_user_id = fields.Many2one(
'res.users', related='alias_id.alias_user_id', inherited=True,
domain=lambda self: [('groups_id', 'in', self.env.ref('sales_team.group_sale_salesman_all_leads').id)])
@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'], ['team_id'])
counts = {datum['team_id'][0]: datum['team_id_count'] for datum 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')
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)
def _compute_opportunities_data(self):
opportunity_data = self.env['crm.lead'].read_group([
('team_id', 'in', self.ids),
('probability', '<', 100),
('type', '=', 'opportunity'),
], ['expected_revenue:sum', 'team_id'], ['team_id'])
counts = {datum['team_id'][0]: datum['team_id_count'] for datum in opportunity_data}
amounts = {datum['team_id'][0]: datum['expected_revenue'] for datum in opportunity_data}
for team in self:
team.opportunities_count = counts.get(team.id, 0)
team.opportunities_amount = amounts.get(team.id, 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()))
], ['expected_revenue', 'team_id'], ['team_id'])
counts = {datum['team_id'][0]: datum['team_id_count'] for datum in opportunity_data}
amounts = {datum['team_id'][0]: (datum['expected_revenue']) for datum in opportunity_data}
for team in self:
team.opportunities_overdue_count = counts.get(team.id, 0)
team.opportunities_overdue_amount = amounts.get(team.id, 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
# ------------------------------------------------------------
# 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):
""" Cron method assigning leads. Leads are allocated to all teams and
assigned to their members. It is based on cron configuration to
deduce parameters of assignment to perform. Purpose of cron is to assign
leads to sales persons. Assigned workload is set to 2 times the workload
those sales people should perform between two cron iterations. Giving
more allows more flexibility in their organization. If their maximum
capacity is reached assign process won't give more leads to those people.
e.g. cron is active with interval_number 3, interval_type days. This
means cron runs every 3 days. Cron will assign leads for 6 work days
to salespersons each 3 days unless their maximum capacity is reached.
If cron runs on an hour-based schedule minimum assignment performed is
equivalent to 2 workdays. Max assignment performed is for 30 days as it
is better to run more often than planning for more than one month.
See ``CrmTeam.action_assign_leads()`` and its sub methods for more
details about assign process.
"""
assign_cron = self.sudo().env.ref('crm.ir_cron_crm_lead_assign', raise_if_not_found=False)
work_days = 2
if 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 = 2 * assign_cron.interval_number * 7
elif assign_cron.interval_type == 'days':
work_days = 2 * assign_cron.interval_number * 1
work_days = 30 if work_days > 30 else work_days
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=2, 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 int 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 = '
'.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 = "
%s
%s
Add new opportunities
Looks like you are not a member of a Sales Team. You should add yourself as a member of one of the Sales Team.
""") if user_team_id: action['help'] += "As you don't belong to any Sales Team, Odoo opens the first one by default.
" 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): if self.use_opportunities: return self.env["ir.actions.actions"]._for_xml_id("crm.crm_case_form_view_salesteams_opportunity") 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()