Initial commit: Crm packages

This commit is contained in:
Ernad Husremovic 2025-08-29 15:20:49 +02:00
commit 21a345b5b9
654 changed files with 418312 additions and 0 deletions

View file

@ -0,0 +1,18 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import res_users
from . import calendar
from . import crm_lead
from . import crm_lost_reason
from . import crm_stage
from . import crm_team
from . import crm_team_member
from . import ir_config_parameter
from . import res_config_settings
from . import res_partner
from . import digest
from . import crm_lead_scoring_frequency
from . import utm
from . import crm_recurring_plan
from . import mail_activity

View file

@ -0,0 +1,55 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class CalendarEvent(models.Model):
_inherit = 'calendar.event'
@api.model
def default_get(self, fields):
if self.env.context.get('default_opportunity_id'):
self = self.with_context(
default_res_model_id=self.env.ref('crm.model_crm_lead').id,
default_res_id=self.env.context['default_opportunity_id']
)
defaults = super(CalendarEvent, self).default_get(fields)
# sync res_model / res_id to opportunity id (aka creating meeting from lead chatter)
if 'opportunity_id' not in defaults:
if self._is_crm_lead(defaults, self.env.context):
defaults['opportunity_id'] = defaults.get('res_id', False) or self.env.context.get('default_res_id', False)
return defaults
opportunity_id = fields.Many2one(
'crm.lead', 'Opportunity', domain="[('type', '=', 'opportunity')]",
index=True, ondelete='set null')
def _compute_is_highlighted(self):
super(CalendarEvent, self)._compute_is_highlighted()
if self.env.context.get('active_model') == 'crm.lead':
opportunity_id = self.env.context.get('active_id')
for event in self:
if event.opportunity_id.id == opportunity_id:
event.is_highlighted = True
@api.model_create_multi
def create(self, vals):
events = super(CalendarEvent, self).create(vals)
for event in events:
if event.opportunity_id and not event.activity_ids:
event.opportunity_id.log_meeting(event.name, event.start, event.duration)
return events
def _is_crm_lead(self, defaults, ctx=None):
"""
This method checks if the concerned model is a CRM lead.
The information is not always in the defaults values,
this is why it is necessary to check the context too.
"""
res_model = defaults.get('res_model', False) or ctx and ctx.get('default_res_model')
res_model_id = defaults.get('res_model_id', False) or ctx and ctx.get('default_res_model_id')
return res_model and res_model == 'crm.lead' or res_model_id and self.env['ir.model'].sudo().browse(res_model_id).model == 'crm.lead'

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,23 @@
# -*- coding: utf-8 -*-
from odoo import fields, models
class LeadScoringFrequency(models.Model):
_name = 'crm.lead.scoring.frequency'
_description = 'Lead Scoring Frequency'
variable = fields.Char('Variable', index=True)
value = fields.Char('Value')
won_count = fields.Float('Won Count', digits=(16, 1)) # Float because we add 0.1 to avoid zero Frequency issue
lost_count = fields.Float('Lost Count', digits=(16, 1)) # Float because we add 0.1 to avoid zero Frequency issue
team_id = fields.Many2one('crm.team', 'Sales Team', ondelete="cascade")
class FrequencyField(models.Model):
_name = 'crm.lead.scoring.frequency.field'
_description = 'Fields that can be used for predictive lead scoring computation'
name = fields.Char(related="field_id.field_description")
field_id = fields.Many2one(
'ir.model.fields', domain=[('model_id.model', '=', 'crm.lead')], required=True,
ondelete='cascade',
)

View file

@ -0,0 +1,33 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, _
class LostReason(models.Model):
_name = "crm.lost.reason"
_description = 'Opp. Lost Reason'
name = fields.Char('Description', required=True, translate=True)
active = fields.Boolean('Active', default=True)
leads_count = fields.Integer('Leads Count', compute='_compute_leads_count')
def _compute_leads_count(self):
lead_data = self.env['crm.lead'].with_context(active_test=False)._read_group(
[('lost_reason_id', 'in', self.ids)],
['lost_reason_id'],
['lost_reason_id']
)
mapped_data = dict((data['lost_reason_id'][0], data['lost_reason_id_count']) for data in lead_data)
for reason in self:
reason.leads_count = mapped_data.get(reason.id, 0)
def action_lost_leads(self):
return {
'name': _('Leads'),
'view_mode': 'tree,form',
'domain': [('lost_reason_id', 'in', self.ids)],
'res_model': 'crm.lead',
'type': 'ir.actions.act_window',
'context': {'create': False, 'active_test': False},
}

View file

@ -0,0 +1,19 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class RecurringPlan(models.Model):
_name = "crm.recurring.plan"
_description = "CRM Recurring revenue plans"
_order = "sequence"
name = fields.Char('Plan Name', required=True, translate=True)
number_of_months = fields.Integer('# Months', required=True)
active = fields.Boolean('Active', default=True)
sequence = fields.Integer('Sequence', default=10)
_sql_constraints = [
('check_number_of_months', 'CHECK(number_of_months >= 0)', 'The number of month can\'t be negative.'),
]

View file

@ -0,0 +1,50 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
AVAILABLE_PRIORITIES = [
('0', 'Low'),
('1', 'Medium'),
('2', 'High'),
('3', 'Very High'),
]
class Stage(models.Model):
""" Model for case stages. This models the main stages of a document
management flow. Main CRM objects (leads, opportunities, project
issues, ...) will now use only stages, instead of state and stages.
Stages are for example used to display the kanban view of records.
"""
_name = "crm.stage"
_description = "CRM Stages"
_rec_name = 'name'
_order = "sequence, name, id"
@api.model
def default_get(self, fields):
""" As we have lots of default_team_id in context used to filter out
leads and opportunities, we pop this key from default of stage creation.
Otherwise stage will be created for a given team only which is not the
standard behavior of stages. """
if 'default_team_id' in self.env.context:
ctx = dict(self.env.context)
ctx.pop('default_team_id')
self = self.with_context(ctx)
return super(Stage, self).default_get(fields)
name = fields.Char('Stage Name', required=True, translate=True)
sequence = fields.Integer('Sequence', default=1, help="Used to order stages. Lower is better.")
is_won = fields.Boolean('Is Won Stage?')
requirements = fields.Text('Requirements', help="Enter here the internal requirements for this stage (ex: Offer sent to customer). It will appear as a tooltip over the stage's name.")
team_id = fields.Many2one('crm.team', string='Sales Team', ondelete="set null",
help='Specific team that uses this stage. Other teams will not be able to see or use this stage.')
fold = fields.Boolean('Folded in Pipeline',
help='This stage is folded in the kanban view when there are no records in that stage to display.')
# This field for interface only
team_count = fields.Integer('team_count', compute='_compute_team_count')
@api.depends('team_id')
def _compute_team_count(self):
self.team_count = self.env['crm.team'].search_count([])

View file

@ -0,0 +1,662 @@
# -*- 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 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(
'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 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.")
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', readonly=False, inherited=True,
domain=lambda self: [('groups_id', 'in', self.env.ref('sales_team.group_sale_salesman_all_leads').id)])
# 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'], ['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
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 = '<br />'.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 = "<p>%s<br /><br />%s</p>" % (log_action, html_message)
self._message_log_batch(bodies=dict((team.id, log_message) for team in self))
return {
'type': 'ir.actions.client',
'tag': 'display_notification',
'params': {
'type': 'success',
'title': _("Leads Assigned"),
'message': notif_message,
'next': {
'type': 'ir.actions.act_window_close'
},
}
}
def _action_assign_leads(self, work_days=1):
""" Private method for lead 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: see ``CrmTeam.action_assign_leads()``;
:return teams_data, members_data: structure-based result of assignment
process. For more details about data see ``CrmTeam._allocate_leads()``
and ``CrmTeamMember._assign_and_convert_leads``;
"""
if not self.env.user.has_group('sales_team.group_sale_manager') and not self.env.user.has_group('base.group_system'):
raise exceptions.UserError(_('Lead/Opportunities automatic assignment is limited to managers or administrators'))
_logger.info('### START Lead Assignment (%d teams, %d sales persons, %.2f work_days)', len(self), len(self.crm_team_member_ids), work_days)
teams_data = self._allocate_leads(work_days=work_days)
_logger.info('### Team repartition done. Starting salesmen assignment.')
members_data = self.crm_team_member_ids._assign_and_convert_leads(work_days=work_days)
_logger.info('### END Lead Assignment')
return teams_data, members_data
def _action_assign_leads_logs(self, teams_data, members_data):
""" Tool method to prepare notification about assignment process result.
:param teams_data: see ``CrmTeam._allocate_leads()``;
:param members_data: see ``CrmTeamMember._assign_and_convert_leads()``;
:return list: list of formatted logs, ready to be formatted into a nice
plaintext or html message at caller's will
"""
# extract some statistics
assigned = sum(len(teams_data[team]['assigned']) + len(teams_data[team]['merged']) for team in teams_data)
duplicates = sum(len(teams_data[team]['duplicates']) for team in teams_data)
members = len(members_data)
members_assigned = sum(len(member_data['assigned']) for member_data in members_data.values())
# format user notification
message_parts = []
# 1- duplicates removal
if duplicates:
message_parts.append(_("%(duplicates)s duplicates leads have been merged.",
duplicates=duplicates))
# 2- nothing assigned at all
if not assigned and not members_assigned:
if len(self) == 1:
if not self.assignment_max:
message_parts.append(
_("No allocated leads to %(team_name)s team because it has no capacity. Add capacity to its salespersons.",
team_name=self.name))
else:
message_parts.append(
_("No allocated leads to %(team_name)s team and its salespersons because no unassigned lead matches its domain.",
team_name=self.name))
else:
message_parts.append(
_("No allocated leads to any team or salesperson. Check your Sales Teams and Salespersons configuration as well as unassigned leads."))
# 3- team allocation
if not assigned and members_assigned:
if len(self) == 1:
message_parts.append(
_("No new lead allocated to %(team_name)s team because no unassigned lead matches its domain.",
team_name=self.name))
else:
message_parts.append(_("No new lead allocated to the teams because no lead match their domains."))
elif assigned:
if len(self) == 1:
message_parts.append(
_("%(assigned)s leads allocated to %(team_name)s team.",
assigned=assigned, team_name=self.name))
else:
message_parts.append(
_("%(assigned)s leads allocated among %(team_count)s teams.",
assigned=assigned, team_count=len(self)))
# 4- salespersons assignment
if not members_assigned and assigned:
message_parts.append(
_("No lead assigned to salespersons because no unassigned lead matches their domains."))
elif members_assigned:
message_parts.append(
_("%(members_assigned)s leads assigned among %(member_count)s salespersons.",
members_assigned=members_assigned, member_count=members))
return message_parts
def _allocate_leads(self, work_days=1):
""" Allocate leads to teams given by self. This method sets ``team_id``
field on lead records that are unassigned (no team and no responsible).
No salesperson is assigned in this process. Its purpose is simply to
allocate leads within teams.
This process allocates all available leads on teams weighted by their
maximum assignment by month that indicates their relative workload.
Heuristic of this method is the following:
* find unassigned leads for each team, aka leads being
* without team, without user -> not assigned;
* not in a won stage, and not having False/0 (lost) or 100 (won)
probability) -> live leads;
* if set, a delay after creation can be applied (see BUNDLE_HOURS_DELAY)
parameter explanations here below;
* matching the team's assignment domain (empty means
everything);
* assign a weight to each team based on their assignment_max that
indicates their relative workload;
* pick a random team using a weighted random choice and find a lead
to assign:
* remove already assigned leads from the available leads. If there
is not any lead spare to assign, remove team from active teams;
* pick the first lead and set the current team;
* when setting a team on leads, leads are also merged with their
duplicates. Purpose is to clean database and avoid assigning
duplicates to same or different teams;
* add lead and its duplicates to already assigned leads;
* pick another random team until their is no more leads to assign
to any team;
This process ensure that teams having overlapping domains will all
receive leads as lead allocation is done one lead at a time. This
allocation will be proportional to their size (assignment of their
members).
:config int crm.assignment.bundle: deprecated
:config int crm.assignment.commit.bundle: optional config parameter allowing
to set size of lead batch to be committed together. By default 100
which is a good trade-off between transaction time and speed
:config int crm.assignment.delay: optional config parameter giving a
delay before taking a lead into assignment process (BUNDLE_HOURS_DELAY)
given in hours. Purpose if to allow other crons or automated actions
to make their job. This option is mainly historic as its purpose was
to let automated actions prepare leads and score before PLS was added
into CRM. This is now not required anymore but still supported;
:param float work_days: see ``CrmTeam.action_assign_leads()``;
:return teams_data: dict() with each team assignment result:
team: {
'assigned': set of lead IDs directly assigned to the team (no
duplicate or merged found);
'merged': set of lead IDs merged and assigned to the team (main
leads being results of merge process);
'duplicates': set of lead IDs found as duplicates and merged into
other leads. Those leads are unlinked during assign process and
are already removed at return of this method;
}, ...
"""
if work_days < 0.2 or work_days > 30:
raise ValueError(
_('Leads team allocation should be done for at least 0.2 or maximum 30 work days, not %.2f.', work_days)
)
BUNDLE_HOURS_DELAY = int(self.env['ir.config_parameter'].sudo().get_param('crm.assignment.delay', default=0))
BUNDLE_COMMIT_SIZE = int(self.env['ir.config_parameter'].sudo().get_param('crm.assignment.commit.bundle', 100))
auto_commit = not getattr(threading.current_thread(), 'testing', False)
# leads
max_create_dt = self.env.cr.now() - datetime.timedelta(hours=BUNDLE_HOURS_DELAY)
duplicates_lead_cache = dict()
# teams data
teams_data, population, weights = dict(), list(), list()
for team in self:
if not team.assignment_max:
continue
lead_domain = expression.AND([
literal_eval(team.assignment_domain or '[]'),
[('create_date', '<=', max_create_dt)],
['&', ('team_id', '=', False), ('user_id', '=', False)],
['|', ('stage_id', '=', False), ('stage_id.is_won', '=', False)]
])
leads = self.env["crm.lead"].search(lead_domain)
# Fill duplicate cache: search for duplicate lead before the assignation
# avoid to flush during the search at every assignation
for lead in leads:
if lead not in duplicates_lead_cache:
duplicates_lead_cache[lead] = lead._get_lead_duplicates(email=lead.email_from)
teams_data[team] = {
"team": team,
"leads": leads,
"assigned": set(),
"merged": set(),
"duplicates": set(),
}
population.append(team)
weights.append(team.assignment_max)
# Start a new transaction, since data fetching take times
# and the first commit occur at the end of the bundle,
# the first transaction can be long which we want to avoid
if auto_commit:
self._cr.commit()
# assignment process data
global_data = dict(assigned=set(), merged=set(), duplicates=set())
leads_done_ids, lead_unlink_ids, counter = set(), set(), 0
while population:
counter += 1
team = random.choices(population, weights=weights, k=1)[0]
# filter remaining leads, remove team if no more leads for it
teams_data[team]["leads"] = teams_data[team]["leads"].filtered(lambda l: l.id not in leads_done_ids).exists()
if not teams_data[team]["leads"]:
population_index = population.index(team)
population.pop(population_index)
weights.pop(population_index)
continue
# assign + deduplicate and concatenate results in teams_data to keep some history
candidate_lead = teams_data[team]["leads"][0]
assign_res = team._allocate_leads_deduplicate(candidate_lead, duplicates_cache=duplicates_lead_cache)
for key in ('assigned', 'merged', 'duplicates'):
teams_data[team][key].update(assign_res[key])
leads_done_ids.update(assign_res[key])
global_data[key].update(assign_res[key])
lead_unlink_ids.update(assign_res['duplicates'])
# auto-commit except in testing mode. As this process may be time consuming or we
# may encounter errors, already commit what is allocated to avoid endless cron loops.
if auto_commit and counter % BUNDLE_COMMIT_SIZE == 0:
# unlink duplicates once
self.env['crm.lead'].browse(lead_unlink_ids).unlink()
lead_unlink_ids = set()
self._cr.commit()
# unlink duplicates once
self.env['crm.lead'].browse(lead_unlink_ids).unlink()
if auto_commit:
self._cr.commit()
# some final log
_logger.info('## Assigned %s leads', (len(global_data['assigned']) + len(global_data['merged'])))
for team, team_data in teams_data.items():
_logger.info(
'## Assigned %s leads to team %s',
len(team_data['assigned']) + len(team_data['merged']), team.id)
_logger.info(
'\tLeads: direct assign %s / merge result %s / duplicates merged: %s',
team_data['assigned'], team_data['merged'], team_data['duplicates'])
return teams_data
def _allocate_leads_deduplicate(self, leads, duplicates_cache=None):
""" Assign leads to sales team given by self by calling lead tool
method _handle_salesmen_assignment. In this method we deduplicate leads
allowing to reduce number of resulting leads before assigning them
to salesmen.
:param leads: recordset of leads to assign to current team;
:param duplicates_cache: if given, avoid to perform a duplicate search
and fetch information in it instead;
"""
self.ensure_one()
duplicates_cache = duplicates_cache if duplicates_cache is not None else dict()
# classify leads
leads_assigned = self.env['crm.lead'] # direct team assign
leads_done_ids, leads_merged_ids, leads_dup_ids = set(), set(), set() # classification
leads_dups_dict = dict() # lead -> its duplicate
for lead in leads:
if lead.id not in leads_done_ids:
# fill cache if not already done
if lead not in duplicates_cache:
duplicates_cache[lead] = lead._get_lead_duplicates(email=lead.email_from)
lead_duplicates = duplicates_cache[lead].exists()
if len(lead_duplicates) > 1:
leads_dups_dict[lead] = lead_duplicates
leads_done_ids.update((lead + lead_duplicates).ids)
else:
leads_assigned += lead
leads_done_ids.add(lead.id)
# assign team to direct assign (leads_assigned) + dups keys (to ensure their team
# if they are elected master of merge process)
dups_to_assign = [lead for lead in leads_dups_dict]
leads_assigned.union(*dups_to_assign)._handle_salesmen_assignment(user_ids=None, team_id=self.id)
for lead in leads.filtered(lambda lead: lead in leads_dups_dict):
lead_duplicates = leads_dups_dict[lead]
merged = lead_duplicates._merge_opportunity(user_id=False, team_id=False, auto_unlink=False, max_length=0)
leads_dup_ids.update((lead_duplicates - merged).ids)
leads_merged_ids.add(merged.id)
return {
'assigned': set(leads_assigned.ids),
'merged': leads_merged_ids,
'duplicates': leads_dup_ids,
}
# ------------------------------------------------------------
# ACTIONS
# ------------------------------------------------------------
#TODO JEM : refactor this stuff with xml action, proper customization,
@api.model
def action_your_pipeline(self):
action = self.env["ir.actions.actions"]._for_xml_id("crm.crm_lead_action_pipeline")
return self._action_update_to_pipeline(action)
@api.model
def action_opportunity_forecast(self):
action = self.env['ir.actions.actions']._for_xml_id('crm.crm_lead_action_forecast')
return self._action_update_to_pipeline(action)
@api.model
def _action_update_to_pipeline(self, action):
user_team_id = self.env.user.sale_team_id.id
if not user_team_id:
user_team_id = self.search([], limit=1).id
action['help'] = "<p class='o_view_nocontent_smiling_face'>%s</p><p>" % _("Create an Opportunity")
if user_team_id:
if self.user_has_groups('sales_team.group_sale_manager'):
action['help'] += "<p>%s</p>" % _("""As you are a member of no Sales Team, you are showed the Pipeline of the <b>first team by default.</b>
To work with the CRM, you should <a name="%d" type="action" tabindex="-1">join a team.</a>""",
self.env.ref('sales_team.crm_team_action_config').id)
else:
action['help'] += "<p>%s</p>" % _("""As you are a member of no Sales Team, you are showed the Pipeline of the <b>first team by default.</b>
To work with the CRM, you should join a team.""")
action_context = safe_eval(action['context'], {'uid': self.env.uid})
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()

View file

@ -0,0 +1,212 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
import logging
import math
import threading
import random
from ast import literal_eval
from odoo import api, exceptions, fields, models, _
from odoo.osv import expression
_logger = logging.getLogger(__name__)
class TeamMember(models.Model):
_inherit = 'crm.team.member'
# assignment
assignment_enabled = fields.Boolean(related="crm_team_id.assignment_enabled")
assignment_domain = fields.Char('Assignment Domain', tracking=True)
assignment_optout = fields.Boolean('Skip auto assignment')
assignment_max = fields.Integer('Average Leads Capacity (on 30 days)', default=30)
lead_month_count = fields.Integer(
'Leads (30 days)', compute='_compute_lead_month_count',
help='Lead assigned to this member those last 30 days')
@api.depends('user_id', 'crm_team_id')
def _compute_lead_month_count(self):
for member in self:
if member.user_id.id and member.crm_team_id.id:
member.lead_month_count = self.env['crm.lead'].with_context(active_test=False).search_count(
member._get_lead_month_domain()
)
else:
member.lead_month_count = 0
@api.constrains('assignment_domain')
def _constrains_assignment_domain(self):
for member in self:
try:
domain = literal_eval(member.assignment_domain or '[]')
if domain:
self.env['crm.lead'].search(domain, limit=1)
except Exception:
raise exceptions.ValidationError(_(
'Member assignment domain for user %(user)s and team %(team)s is incorrectly formatted',
user=member.user_id.name, team=member.crm_team_id.name
))
def _get_lead_month_domain(self):
limit_date = fields.Datetime.now() - datetime.timedelta(days=30)
return [
('user_id', '=', self.user_id.id),
('team_id', '=', self.crm_team_id.id),
('date_open', '>=', limit_date),
]
# ------------------------------------------------------------
# LEAD ASSIGNMENT
# ------------------------------------------------------------
def _assign_and_convert_leads(self, work_days=1):
""" Main processing method to assign leads to sales team members. It also
converts them into opportunities. This method should be called after
``_allocate_leads`` as this method assigns leads already allocated to
the member's team. Its main purpose is therefore to distribute team
workload on its members based on their capacity.
Preparation
* prepare lead domain for each member. It is done using a logical
AND with team's domain and member's domain. Member domains further
restricts team domain;
* prepare a set of available leads for each member by searching for
leads matching domain with a sufficient limit to ensure all members
will receive leads;
* prepare a weighted population sample. Population are members that
should received leads. Initial weight is the number of leads to
assign to that specific member. This is minimum value between
* remaining this month: assignment_max - number of lead already
assigned this month;
* days-based assignment: assignment_max with a ratio based on
``work_days`` parameter (see ``CrmTeam.action_assign_leads()``)
* e.g. Michel Poilvache (max: 30 - currently assigned: 15) limit
for 2 work days: min(30-15, 30/15) -> 2 leads assigned
* e.g. Michel Tartopoil (max: 30 - currently assigned: 26) limit
for 10 work days: min(30-26, 30/3) -> 4 leads assigned
This method then follows the following heuristic
* take a weighted random choice in population;
* find first available (not yet assigned) lead in its lead set;
* if found:
* convert it into an opportunity and assign member as salesperson;
* lessen member's weight so that other members have an higher
probability of being picked up next;
* if not found: consider this member is out of assignment process,
remove it from population so that it is not picked up anymore;
Assignment is performed one lead at a time for fairness purpose. Indeed
members may have overlapping domains within a given team. To ensure
some fairness in process once a member receives a lead, a new choice is
performed with updated weights. This is not optimal from performance
point of view but increases probability leads are correctly distributed
within the team.
:param float work_days: see ``CrmTeam.action_assign_leads()``;
:return members_data: dict() with each member assignment result:
membership: {
'assigned': set of lead IDs directly assigned to the member;
}, ...
"""
if work_days < 0.2 or work_days > 30:
raise ValueError(
_('Leads team allocation should be done for at least 0.2 or maximum 30 work days, not %.2f.', work_days)
)
members_data, population, weights = dict(), list(), list()
members = self.filtered(lambda member: not member.assignment_optout and member.assignment_max > 0)
if not members:
return members_data
# prepare a global lead count based on total leads to assign to salespersons
lead_limit = sum(
member._get_assignment_quota(work_days=work_days)
for member in members
)
# could probably be optimized
for member in members:
lead_domain = expression.AND([
literal_eval(member.assignment_domain or '[]'),
['&', '&', ('user_id', '=', False), ('date_open', '=', False), ('team_id', '=', member.crm_team_id.id)]
])
leads = self.env["crm.lead"].search(lead_domain, order='probability DESC, id', limit=lead_limit)
to_assign = member._get_assignment_quota(work_days=work_days)
members_data[member.id] = {
"team_member": member,
"max": member.assignment_max,
"to_assign": to_assign,
"leads": leads,
"assigned": self.env["crm.lead"],
}
population.append(member.id)
weights.append(to_assign)
leads_done_ids = set()
counter = 0
# auto-commit except in testing mode
auto_commit = not getattr(threading.current_thread(), 'testing', False)
commit_bundle_size = int(self.env['ir.config_parameter'].sudo().get_param('crm.assignment.commit.bundle', 100))
while population and any(weights):
counter += 1
member_id = random.choices(population, weights=weights, k=1)[0]
member_index = population.index(member_id)
member_data = members_data[member_id]
lead = next((lead for lead in member_data['leads'] if lead.id not in leads_done_ids), False)
if lead:
leads_done_ids.add(lead.id)
members_data[member_id]["assigned"] += lead
weights[member_index] = weights[member_index] - 1
lead.with_context(mail_auto_subscribe_no_notify=True).convert_opportunity(
lead.partner_id,
user_ids=member_data['team_member'].user_id.ids
)
if auto_commit and counter % commit_bundle_size == 0:
self._cr.commit()
else:
weights[member_index] = 0
if weights[member_index] <= 0:
population.pop(member_index)
weights.pop(member_index)
# failsafe
if counter > 100000:
population = list()
if auto_commit:
self._cr.commit()
# log results and return
result_data = dict(
(member_info["team_member"], {"assigned": member_info["assigned"]})
for member_id, member_info in members_data.items()
)
_logger.info('Assigned %s leads to %s salesmen', len(leads_done_ids), len(members))
for member, member_info in result_data.items():
_logger.info('-> member %s: assigned %d leads (%s)', member.id, len(member_info["assigned"]), member_info["assigned"])
return result_data
def _get_assignment_quota(self, work_days=1):
""" Compute assignment quota based on work_days. This quota includes
a compensation to speedup getting to the lead average (``assignment_max``).
As this field is a counter for "30 days" -> divide by requested work
days in order to have base assign number then add compensation.
:param float work_days: see ``CrmTeam.action_assign_leads()``;
"""
assign_ratio = work_days / 30.0
to_assign = self.assignment_max * assign_ratio
compensation = max(0, self.assignment_max - (self.lead_month_count + to_assign)) * 0.2
return round(to_assign + compensation)

View file

@ -0,0 +1,46 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import AccessError
class Digest(models.Model):
_inherit = 'digest.digest'
kpi_crm_lead_created = fields.Boolean('New Leads')
kpi_crm_lead_created_value = fields.Integer(compute='_compute_kpi_crm_lead_created_value')
kpi_crm_opportunities_won = fields.Boolean('Opportunities Won')
kpi_crm_opportunities_won_value = fields.Integer(compute='_compute_kpi_crm_opportunities_won_value')
def _compute_kpi_crm_lead_created_value(self):
if not self.env.user.has_group('sales_team.group_sale_salesman'):
raise AccessError(_("Do not have access, skip this data for user's digest email"))
for record in self:
start, end, company = record._get_kpi_compute_parameters()
record.kpi_crm_lead_created_value = self.env['crm.lead'].search_count([
('create_date', '>=', start),
('create_date', '<', end),
('company_id', '=', company.id)
])
def _compute_kpi_crm_opportunities_won_value(self):
if not self.env.user.has_group('sales_team.group_sale_salesman'):
raise AccessError(_("Do not have access, skip this data for user's digest email"))
for record in self:
start, end, company = record._get_kpi_compute_parameters()
record.kpi_crm_opportunities_won_value = self.env['crm.lead'].search_count([
('type', '=', 'opportunity'),
('probability', '=', '100'),
('date_closed', '>=', start),
('date_closed', '<', end),
('company_id', '=', company.id)
])
def _compute_kpis_actions(self, company, user):
res = super(Digest, self)._compute_kpis_actions(company, user)
res['kpi_crm_lead_created'] = 'crm.crm_lead_action_pipeline&menu_id=%s' % self.env.ref('crm.crm_menu_root').id
res['kpi_crm_opportunities_won'] = 'crm.crm_lead_action_pipeline&menu_id=%s' % self.env.ref('crm.crm_menu_root').id
if user.has_group('crm.group_use_lead'):
res['kpi_crm_lead_created'] = 'crm.crm_lead_all_leads&menu_id=%s' % self.env.ref('crm.crm_menu_root').id
return res

View file

@ -0,0 +1,32 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models
from odoo.addons.base.models.ir_model import MODULE_UNINSTALL_FLAG
class IrConfigParameter(models.Model):
_inherit = 'ir.config_parameter'
def write(self, vals):
result = super(IrConfigParameter, self).write(vals)
if any(record.key == "crm.pls_fields" for record in self):
self.env.flush_all()
self.env.registry.setup_models(self.env.cr)
return result
@api.model_create_multi
def create(self, vals_list):
records = super(IrConfigParameter, self).create(vals_list)
if any(record.key == "crm.pls_fields" for record in records):
self.env.flush_all()
self.env.registry.setup_models(self.env.cr)
return records
def unlink(self):
pls_emptied = any(record.key == "crm.pls_fields" for record in self)
result = super(IrConfigParameter, self).unlink()
if pls_emptied and not self._context.get(MODULE_UNINSTALL_FLAG):
self.env.flush_all()
self.env.registry.setup_models(self.env.cr)
return result

View file

@ -0,0 +1,26 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class MailActivity(models.Model):
_inherit = "mail.activity"
def action_create_calendar_event(self):
""" Small override of the action that creates a calendar.
If the activity is linked to a crm.lead through the "opportunity_id" field, we include in
the action context the default values used when scheduling a meeting from the crm.lead form
view.
e.g: It will set the partner_id of the crm.lead as default attendee of the meeting. """
action = super(MailActivity, self).action_create_calendar_event()
opportunity = self.calendar_event_id.opportunity_id
if opportunity:
opportunity_action_context = opportunity.action_schedule_meeting(smart_calendar=False).get('context', {})
opportunity_action_context['initial_date'] = self.calendar_event_id.start
action['context'].update(opportunity_action_context)
return action

View file

@ -0,0 +1,170 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import timedelta
from dateutil.relativedelta import relativedelta
from odoo import api, exceptions, fields, models, _
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
group_use_lead = fields.Boolean(string="Leads", implied_group='crm.group_use_lead')
group_use_recurring_revenues = fields.Boolean(string="Recurring Revenues", implied_group='crm.group_use_recurring_revenues')
# Membership
is_membership_multi = fields.Boolean(string='Multi Teams', config_parameter='sales_team.membership_multi')
# Lead assignment
crm_use_auto_assignment = fields.Boolean(
string='Rule-Based Assignment', config_parameter='crm.lead.auto.assignment')
crm_auto_assignment_action = fields.Selection([
('manual', 'Manually'), ('auto', 'Repeatedly')],
string='Auto Assignment Action', compute='_compute_crm_auto_assignment_data',
readonly=False, store=True,
help='Manual assign allow to trigger assignment from team form view using an action button. Automatic configures a cron running repeatedly assignment in all teams.')
crm_auto_assignment_interval_type = fields.Selection([
('minutes', 'Minutes'), ('hours', 'Hours'),
('days', 'Days'), ('weeks', 'Weeks')],
string='Auto Assignment Interval Unit', compute='_compute_crm_auto_assignment_data',
readonly=False, store=True,
help='Interval type between each cron run (e.g. each 2 days or each 2 hours)')
crm_auto_assignment_interval_number = fields.Integer(
string="Repeat every", compute='_compute_crm_auto_assignment_data',
readonly=False, store=True,
help='Number of interval type between each cron run (e.g. each 2 days or each 4 days)')
crm_auto_assignment_run_datetime = fields.Datetime(
string="Auto Assignment Next Execution Date", compute='_compute_crm_auto_assignment_data',
readonly=False, store=True)
# IAP
module_crm_iap_mine = fields.Boolean("Generate new leads based on their country, industries, size, etc.")
module_crm_iap_enrich = fields.Boolean("Enrich your leads automatically with company data based on their email address.")
module_website_crm_iap_reveal = fields.Boolean("Create Leads/Opportunities from your website's traffic")
lead_enrich_auto = fields.Selection([
('manual', 'Enrich leads on demand only'),
('auto', 'Enrich all leads automatically'),
], string='Enrich lead automatically', default='auto', config_parameter='crm.iap.lead.enrich.setting')
lead_mining_in_pipeline = fields.Boolean("Create a lead mining request directly from the opportunity pipeline.", config_parameter='crm.lead_mining_in_pipeline')
predictive_lead_scoring_start_date = fields.Date(string='Lead Scoring Starting Date', compute="_compute_pls_start_date", inverse="_inverse_pls_start_date_str")
predictive_lead_scoring_start_date_str = fields.Char(string='Lead Scoring Starting Date in String', config_parameter='crm.pls_start_date')
predictive_lead_scoring_fields = fields.Many2many('crm.lead.scoring.frequency.field', string='Lead Scoring Frequency Fields', compute="_compute_pls_fields", inverse="_inverse_pls_fields_str")
predictive_lead_scoring_fields_str = fields.Char(string='Lead Scoring Frequency Fields in String', config_parameter='crm.pls_fields')
predictive_lead_scoring_field_labels = fields.Char(compute='_compute_predictive_lead_scoring_field_labels')
@api.depends('crm_use_auto_assignment')
def _compute_crm_auto_assignment_data(self):
assign_cron = self.sudo().env.ref('crm.ir_cron_crm_lead_assign', raise_if_not_found=False)
for setting in self:
if setting.crm_use_auto_assignment and assign_cron:
setting.crm_auto_assignment_action = 'auto' if assign_cron.active else 'manual'
setting.crm_auto_assignment_interval_type = assign_cron.interval_type or 'days'
setting.crm_auto_assignment_interval_number = assign_cron.interval_number or 1
setting.crm_auto_assignment_run_datetime = assign_cron.nextcall
else:
setting.crm_auto_assignment_action = 'manual'
setting.crm_auto_assignment_interval_type = setting.crm_auto_assignment_run_datetime = False
setting.crm_auto_assignment_interval_number = 1
@api.onchange('crm_auto_assignment_interval_type', 'crm_auto_assignment_interval_number')
def _onchange_crm_auto_assignment_run_datetime(self):
if self.crm_auto_assignment_interval_number <= 0:
raise exceptions.UserError(_('Repeat frequency should be positive.'))
elif self.crm_auto_assignment_interval_number >= 100:
raise exceptions.UserError(_('Invalid repeat frequency. Consider changing frequency type instead of using large numbers.'))
self.crm_auto_assignment_run_datetime = self._get_crm_auto_assignmment_run_datetime(
self.crm_auto_assignment_run_datetime,
self.crm_auto_assignment_interval_type,
self.crm_auto_assignment_interval_number
)
@api.depends('predictive_lead_scoring_fields_str')
def _compute_pls_fields(self):
""" As config_parameters does not accept m2m field,
we get the fields back from the Char config field, to ease the configuration in config panel """
for setting in self:
if setting.predictive_lead_scoring_fields_str:
names = setting.predictive_lead_scoring_fields_str.split(',')
fields = self.env['ir.model.fields'].search([('name', 'in', names), ('model', '=', 'crm.lead')])
setting.predictive_lead_scoring_fields = self.env['crm.lead.scoring.frequency.field'].search([('field_id', 'in', fields.ids)])
else:
setting.predictive_lead_scoring_fields = None
def _inverse_pls_fields_str(self):
""" As config_parameters does not accept m2m field,
we store the fields with a comma separated string into a Char config field """
for setting in self:
if setting.predictive_lead_scoring_fields:
setting.predictive_lead_scoring_fields_str = ','.join(setting.predictive_lead_scoring_fields.mapped('field_id.name'))
else:
setting.predictive_lead_scoring_fields_str = ''
@api.depends('predictive_lead_scoring_start_date_str')
def _compute_pls_start_date(self):
""" As config_parameters does not accept Date field,
we get the date back from the Char config field, to ease the configuration in config panel """
for setting in self:
lead_scoring_start_date = setting.predictive_lead_scoring_start_date_str
# if config param is deleted / empty, set the date 8 days prior to current date
if not lead_scoring_start_date:
setting.predictive_lead_scoring_start_date = fields.Date.to_date(fields.Date.today() - timedelta(days=8))
else:
try:
setting.predictive_lead_scoring_start_date = fields.Date.to_date(lead_scoring_start_date)
except ValueError:
# the config parameter is malformed, so set the date 8 days prior to current date
setting.predictive_lead_scoring_start_date = fields.Date.to_date(fields.Date.today() - timedelta(days=8))
def _inverse_pls_start_date_str(self):
""" As config_parameters does not accept Date field,
we store the date formated string into a Char config field """
for setting in self:
if setting.predictive_lead_scoring_start_date:
setting.predictive_lead_scoring_start_date_str = fields.Date.to_string(setting.predictive_lead_scoring_start_date)
@api.depends('predictive_lead_scoring_fields')
def _compute_predictive_lead_scoring_field_labels(self):
for setting in self:
if setting.predictive_lead_scoring_fields:
field_names = [_('Stage')] + [field.name for field in setting.predictive_lead_scoring_fields]
setting.predictive_lead_scoring_field_labels = _('%s and %s', ', '.join(field_names[:-1]), field_names[-1])
else:
setting.predictive_lead_scoring_field_labels = _('Stage')
def set_values(self):
group_use_lead_id = self.env['ir.model.data']._xmlid_to_res_id('crm.group_use_lead')
has_group_lead_before = group_use_lead_id in self.env.user.groups_id.ids
super(ResConfigSettings, self).set_values()
# update use leads / opportunities setting on all teams according to settings update
has_group_lead_after = group_use_lead_id in self.env.user.groups_id.ids
if has_group_lead_before != has_group_lead_after:
teams = self.env['crm.team'].search([])
teams.filtered('use_opportunities').use_leads = has_group_lead_after
for team in teams:
team.alias_id.write(team._alias_get_creation_values())
# synchronize cron with settings
assign_cron = self.sudo().env.ref('crm.ir_cron_crm_lead_assign', raise_if_not_found=False)
if assign_cron:
# Writing on a cron tries to grab a write-lock on the table. This
# could be avoided when saving a res.config without modifying this specific
# configuration
cron_vals = {
'active': self.crm_use_auto_assignment and self.crm_auto_assignment_action == 'auto',
'interval_type': self.crm_auto_assignment_interval_type,
'interval_number': self.crm_auto_assignment_interval_number,
# keep nextcall on cron as it is required whatever the setting
'nextcall': self.crm_auto_assignment_run_datetime if self.crm_auto_assignment_run_datetime else assign_cron.nextcall,
}
cron_vals = {field_name: value for field_name, value in cron_vals.items() if assign_cron[field_name] != value}
if cron_vals:
assign_cron.write(cron_vals)
# TDE FIXME: re create cron if not found ?
def _get_crm_auto_assignmment_run_datetime(self, run_datetime, run_interval, run_interval_number):
if not run_interval:
return False
if run_interval == 'manual':
return run_datetime if run_datetime else False
return fields.Datetime.now() + relativedelta(**{run_interval: run_interval_number})
def action_crm_assign_leads(self):
self.ensure_one()
return self.env['crm.team'].search([('assignment_optout', '=', False)]).action_assign_leads(work_days=2, log=False)

View file

@ -0,0 +1,77 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.osv import expression
class Partner(models.Model):
_name = 'res.partner'
_inherit = 'res.partner'
team_id = fields.Many2one(
'crm.team', string='Sales Team',
compute='_compute_team_id',
precompute=True, # avoid queries post-create
ondelete='set null', readonly=False, store=True)
opportunity_ids = fields.One2many('crm.lead', 'partner_id', string='Opportunities', domain=[('type', '=', 'opportunity')])
opportunity_count = fields.Integer("Opportunity", compute='_compute_opportunity_count')
@api.model
def default_get(self, fields):
rec = super(Partner, self).default_get(fields)
active_model = self.env.context.get('active_model')
if active_model == 'crm.lead' and len(self.env.context.get('active_ids', [])) <= 1:
lead = self.env[active_model].browse(self.env.context.get('active_id')).exists()
if lead:
rec.update(
phone=lead.phone,
mobile=lead.mobile,
function=lead.function,
title=lead.title.id,
website=lead.website,
street=lead.street,
street2=lead.street2,
city=lead.city,
state_id=lead.state_id.id,
country_id=lead.country_id.id,
zip=lead.zip,
)
return rec
@api.depends('parent_id')
def _compute_team_id(self):
for partner in self.filtered(lambda partner: not partner.team_id and partner.company_type == 'person' and partner.parent_id.team_id):
partner.team_id = partner.parent_id.team_id
def _compute_opportunity_count(self):
# retrieve all children partners and prefetch 'parent_id' on them
all_partners = self.with_context(active_test=False).search([('id', 'child_of', self.ids)])
all_partners.read(['parent_id'])
opportunity_data = self.env['crm.lead'].with_context(active_test=False)._read_group(
domain=[('partner_id', 'in', all_partners.ids)],
fields=['partner_id'], groupby=['partner_id']
)
self.opportunity_count = 0
for group in opportunity_data:
partner = self.browse(group['partner_id'][0])
while partner:
if partner in self:
partner.opportunity_count += group['partner_id_count']
partner = partner.parent_id
def action_view_opportunity(self):
'''
This function returns an action that displays the opportunities from partner.
'''
action = self.env['ir.actions.act_window']._for_xml_id('crm.crm_lead_opportunities')
action['context'] = {}
if self.is_company:
action['domain'] = [('partner_id.commercial_partner_id', '=', self.id)]
else:
action['domain'] = [('partner_id', '=', self.id)]
action['domain'] = expression.AND([action['domain'], [('active', 'in', [True, False])]])
return action

View file

@ -0,0 +1,11 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class Users(models.Model):
_inherit = 'res.users'
target_sales_won = fields.Integer('Won in Opportunities Target')
target_sales_done = fields.Integer('Activities Done Target')

View file

@ -0,0 +1,30 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class UtmCampaign(models.Model):
_inherit = 'utm.campaign'
use_leads = fields.Boolean('Use Leads', compute='_compute_use_leads')
crm_lead_count = fields.Integer('Leads/Opportunities count', groups='sales_team.group_sale_salesman', compute="_compute_crm_lead_count")
def _compute_use_leads(self):
self.use_leads = self.env.user.has_group('crm.group_use_lead')
def _compute_crm_lead_count(self):
lead_data = self.env['crm.lead'].with_context(active_test=False)._read_group([
('campaign_id', 'in', self.ids)],
['campaign_id'], ['campaign_id'])
mapped_data = {datum['campaign_id'][0]: datum['campaign_id_count'] for datum in lead_data}
for campaign in self:
campaign.crm_lead_count = mapped_data.get(campaign.id, 0)
def action_redirect_to_leads_opportunities(self):
view = 'crm.crm_lead_all_leads' if self.use_leads else 'crm.crm_lead_opportunities'
action = self.env['ir.actions.act_window']._for_xml_id(view)
action['view_mode'] = 'tree,kanban,graph,pivot,form,calendar'
action['domain'] = [('campaign_id', 'in', self.ids)]
action['context'] = {'active_test': False, 'create': False}
return action