[FIX] crm: fixed bug in m2m between sales teams and stages introduced
[odoo/odoo.git] / addons / crm / sales_team.py
1 # -*- coding: utf-8 -*-
2
3 import calendar
4 from datetime import date
5 from dateutil import relativedelta
6 import json
7
8 from openerp import tools
9 from openerp.osv import fields, osv
10
11
12 class crm_team(osv.Model):
13     _inherit = 'crm.team'
14     _inherits = {'mail.alias': 'alias_id'}
15
16     def _get_opportunities_data(self, cr, uid, ids, field_name, arg, context=None):
17         """ Get opportunities-related data for salesteam kanban view
18             monthly_open_leads: number of open lead during the last months
19             monthly_planned_revenue: planned revenu of opportunities during the last months
20         """
21         obj = self.pool.get('crm.lead')
22         res = dict.fromkeys(ids, False)
23         month_begin = date.today().replace(day=1)
24         date_begin = month_begin - relativedelta.relativedelta(months=self._period_number - 1)
25         date_end = month_begin.replace(day=calendar.monthrange(month_begin.year, month_begin.month)[1])
26         lead_pre_domain = [('create_date', '>=', date_begin.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)),
27                 ('create_date', '<=', date_end.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)),
28                               ('type', '=', 'lead')]
29         opp_pre_domain = [('date_deadline', '>=', date_begin.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT)),
30                       ('date_deadline', '<=', date_end.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT)),
31                       ('type', '=', 'opportunity')]
32         for id in ids:
33             res[id] = dict()
34             lead_domain = lead_pre_domain + [('team_id', '=', id)]
35             opp_domain = opp_pre_domain + [('team_id', '=', id)]
36             res[id]['monthly_open_leads'] = json.dumps(self.__get_bar_values(cr, uid, obj, lead_domain, ['create_date'], 'create_date_count', 'create_date', context=context))
37             res[id]['monthly_planned_revenue'] = json.dumps(self.__get_bar_values(cr, uid, obj, opp_domain, ['planned_revenue', 'date_deadline'], 'planned_revenue', 'date_deadline', context=context))
38         return res
39
40     _columns = {
41         'resource_calendar_id': fields.many2one('resource.calendar', "Working Time", help="Used to compute open days"),
42         'stage_ids': fields.many2many('crm.stage', 'crm_team_stage_rel', 'team_id', 'stage_id', 'Stages'),
43         'use_leads': fields.boolean('Leads',
44             help="The first contact you get with a potential customer is a lead you qualify before converting it into a real business opportunity. Check this box to manage leads in this sales team."),
45         'use_opportunities': fields.boolean('Opportunities', help="Check this box to manage opportunities in this sales team."),
46         'monthly_open_leads': fields.function(_get_opportunities_data,
47             type="char", readonly=True, multi='_get_opportunities_data',
48             string='Open Leads per Month'),
49         'monthly_planned_revenue': fields.function(_get_opportunities_data,
50             type="char", readonly=True, multi='_get_opportunities_data',
51             string='Planned Revenue per Month'),
52         'alias_id': fields.many2one('mail.alias', 'Alias', ondelete="restrict", required=True, help="The email address associated with this team. New emails received will automatically create new leads assigned to the team."),
53     }
54
55     def _auto_init(self, cr, context=None):
56         """Installation hook to create aliases for all lead and avoid constraint errors."""
57         return self.pool.get('mail.alias').migrate_to_alias(cr, self._name, self._table, super(crm_team, self)._auto_init,
58             'crm.lead', self._columns['alias_id'], 'name', alias_prefix='Lead+', alias_defaults={}, context=context)
59
60     def _get_stage_common(self, cr, uid, context):
61         ids = self.pool.get('crm.stage').search(cr, uid, [('case_default', '=', 1)], context=context)
62         return ids
63
64     _defaults = {
65         'stage_ids': _get_stage_common,
66         'use_leads': True,
67         'use_opportunities': True,
68     }
69
70     def create(self, cr, uid, vals, context=None):
71         if context is None:
72             context = {}
73         create_context = dict(context, alias_model_name='crm.lead', alias_parent_model_name=self._name)
74         team_id = super(crm_team, self).create(cr, uid, vals, context=create_context)
75         team = self.browse(cr, uid, team_id, context=context)
76         self.pool.get('mail.alias').write(cr, uid, [team.alias_id.id], {'alias_parent_thread_id': team_id, 'alias_defaults': {'team_id': team_id, 'type': 'lead'}}, context=context)
77         return team_id
78
79     def unlink(self, cr, uid, ids, context=None):
80         # Cascade-delete mail aliases as well, as they should not exist without the sales team.
81         mail_alias = self.pool.get('mail.alias')
82         alias_ids = [team.alias_id.id for team in self.browse(cr, uid, ids, context=context) if team.alias_id]
83         res = super(crm_team, self).unlink(cr, uid, ids, context=context)
84         mail_alias.unlink(cr, uid, alias_ids, context=context)
85         return res