[FIX] crm: crm_to_lead tests, force assignation, to check round robin
[odoo/odoo.git] / addons / crm / crm.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-today OpenERP SA (<http://www.openerp.com>)
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import calendar
23 from datetime import date, datetime
24 from dateutil import relativedelta
25
26 from openerp import tools
27 from openerp.osv import fields
28 from openerp.osv import osv
29
30 AVAILABLE_PRIORITIES = [
31     ('1', 'Highest'),
32     ('2', 'High'),
33     ('3', 'Normal'),
34     ('4', 'Low'),
35     ('5', 'Lowest'),
36 ]
37
38 class crm_case_channel(osv.osv):
39     _name = "crm.case.channel"
40     _description = "Channels"
41     _order = 'name'
42     _columns = {
43         'name': fields.char('Channel Name', size=64, required=True),
44         'active': fields.boolean('Active'),
45     }
46     _defaults = {
47         'active': lambda *a: 1,
48     }
49
50 class crm_case_stage(osv.osv):
51     """ Model for case stages. This models the main stages of a document
52         management flow. Main CRM objects (leads, opportunities, project
53         issues, ...) will now use only stages, instead of state and stages.
54         Stages are for example used to display the kanban view of records.
55     """
56     _name = "crm.case.stage"
57     _description = "Stage of case"
58     _rec_name = 'name'
59     _order = "sequence"
60
61     _columns = {
62         'name': fields.char('Stage Name', size=64, required=True, translate=True),
63         'sequence': fields.integer('Sequence', help="Used to order stages. Lower is better."),
64         'probability': fields.float('Probability (%)', required=True, help="This percentage depicts the default/average probability of the Case for this stage to be a success"),
65         'on_change': fields.boolean('Change Probability Automatically', help="Setting this stage will change the probability automatically on the opportunity."),
66         'requirements': fields.text('Requirements'),
67         'section_ids': fields.many2many('crm.case.section', 'section_stage_rel', 'stage_id', 'section_id', string='Sections',
68                         help="Link between stages and sales teams. When set, this limitate the current stage to the selected sales teams."),
69         'case_default': fields.boolean('Default to New Sales Team',
70                         help="If you check this field, this stage will be proposed by default on each sales team. It will not assign this stage to existing teams."),
71         'fold': fields.boolean('Folded in Kanban View',
72                                help='This stage is folded in the kanban view when'
73                                'there are no records in that stage to display.'),
74         'type': fields.selection([('lead', 'Lead'),
75                                     ('opportunity', 'Opportunity'),
76                                     ('both', 'Both')],
77                                     string='Type', size=16, required=True,
78                                     help="This field is used to distinguish stages related to Leads from stages related to Opportunities, or to specify stages available for both types."),
79     }
80
81     _defaults = {
82         'sequence': 1,
83         'probability': 0.0,
84         'on_change': True,
85         'fold': False,
86         'type': 'both',
87         'case_default': True,
88     }
89
90
91 class crm_case_section(osv.osv):
92     """ Model for sales teams. """
93     _name = "crm.case.section"
94     _inherits = {'mail.alias': 'alias_id'}
95     _inherit = "mail.thread"
96     _description = "Sales Teams"
97     _order = "complete_name"
98     # number of periods for lead/opportunities/... tracking in salesteam kanban dashboard/kanban view
99     _period_number = 5
100
101     def get_full_name(self, cr, uid, ids, field_name, arg, context=None):
102         return dict(self.name_get(cr, uid, ids, context=context))
103
104     def __get_bar_values(self, cr, uid, obj, domain, read_fields, value_field, groupby_field, context=None):
105         """ Generic method to generate data for bar chart values using SparklineBarWidget.
106             This method performs obj.read_group(cr, uid, domain, read_fields, groupby_field).
107
108             :param obj: the target model (i.e. crm_lead)
109             :param domain: the domain applied to the read_group
110             :param list read_fields: the list of fields to read in the read_group
111             :param str value_field: the field used to compute the value of the bar slice
112             :param str groupby_field: the fields used to group
113
114             :return list section_result: a list of dicts: [
115                                                 {   'value': (int) bar_column_value,
116                                                     'tootip': (str) bar_column_tooltip,
117                                                 }
118                                             ]
119         """
120         month_begin = date.today().replace(day=1)
121         section_result = [{
122                           'value': 0,
123                           'tooltip': (month_begin + relativedelta.relativedelta(months=-i)).strftime('%B %Y'),
124                           } for i in range(self._period_number - 1, -1, -1)]
125         group_obj = obj.read_group(cr, uid, domain, read_fields, groupby_field, context=context)
126         pattern = tools.DEFAULT_SERVER_DATE_FORMAT if obj.fields_get(cr, uid, groupby_field)[groupby_field]['type'] == 'date' else tools.DEFAULT_SERVER_DATETIME_FORMAT
127         for group in group_obj:
128             group_begin_date = datetime.strptime(group['__domain'][0][2], pattern)
129             month_delta = relativedelta.relativedelta(month_begin, group_begin_date)
130             section_result[self._period_number - (month_delta.months + 1)] = {'value': group.get(value_field, 0), 'tooltip': group.get(groupby_field, 0)}
131         return section_result
132
133     def _get_opportunities_data(self, cr, uid, ids, field_name, arg, context=None):
134         """ Get opportunities-related data for salesteam kanban view
135             monthly_open_leads: number of open lead during the last months
136             monthly_planned_revenue: planned revenu of opportunities during the last months
137         """
138         obj = self.pool.get('crm.lead')
139         res = dict.fromkeys(ids, False)
140         month_begin = date.today().replace(day=1)
141         date_begin = month_begin - relativedelta.relativedelta(months=self._period_number - 1)
142         date_end = month_begin.replace(day=calendar.monthrange(month_begin.year, month_begin.month)[1])
143         lead_pre_domain = [('create_date', '>=', date_begin.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)), 
144                               ('create_date', '<=', date_end.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)),
145                               ('type', '=', 'lead')]
146         opp_pre_domain = [('date_deadline', '>=', date_begin.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT)), 
147                       ('date_deadline', '<=', date_end.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT)),
148                       ('type', '=', 'opportunity')]
149         for id in ids:
150             res[id] = dict()
151             lead_domain = lead_pre_domain + [('section_id', '=', id)]
152             opp_domain = opp_pre_domain + [('section_id', '=', id)]
153             res[id]['monthly_open_leads'] = self.__get_bar_values(cr, uid, obj, lead_domain, ['create_date'], 'create_date_count', 'create_date', context=context)
154             res[id]['monthly_planned_revenue'] = self.__get_bar_values(cr, uid, obj, opp_domain, ['planned_revenue', 'date_deadline'], 'planned_revenue', 'date_deadline', context=context)
155         return res
156
157     _columns = {
158         'name': fields.char('Sales Team', size=64, required=True, translate=True),
159         'complete_name': fields.function(get_full_name, type='char', size=256, readonly=True, store=True),
160         'code': fields.char('Code', size=8),
161         'active': fields.boolean('Active', help="If the active field is set to "\
162                         "true, it will allow you to hide the sales team without removing it."),
163         'change_responsible': fields.boolean('Reassign Escalated', help="When escalating to this team override the salesman with the team leader."),
164         'user_id': fields.many2one('res.users', 'Team Leader'),
165         'member_ids': fields.many2many('res.users', 'sale_member_rel', 'section_id', 'member_id', 'Team Members'),
166         'reply_to': fields.char('Reply-To', size=64, help="The email address put in the 'Reply-To' of all emails sent by OpenERP about cases in this sales team"),
167         'parent_id': fields.many2one('crm.case.section', 'Parent Team'),
168         'child_ids': fields.one2many('crm.case.section', 'parent_id', 'Child Teams'),
169         'resource_calendar_id': fields.many2one('resource.calendar', "Working Time", help="Used to compute open days"),
170         'note': fields.text('Description'),
171         'working_hours': fields.float('Working Hours', digits=(16, 2)),
172         'stage_ids': fields.many2many('crm.case.stage', 'section_stage_rel', 'section_id', 'stage_id', 'Stages'),
173         'alias_id': fields.many2one('mail.alias', 'Alias', ondelete="restrict", required=True,
174                                     help="The email address associated with this team. New emails received will automatically "
175                                          "create new leads assigned to the team."),
176         'color': fields.integer('Color Index'),
177         'use_leads': fields.boolean('Leads',
178             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."),
179
180         'monthly_open_leads': fields.function(_get_opportunities_data,
181             type="string", readonly=True, multi='_get_opportunities_data',
182             string='Open Leads per Month'),
183         'monthly_planned_revenue': fields.function(_get_opportunities_data,
184             type="string", readonly=True, multi='_get_opportunities_data',
185             string='Planned Revenue per Month')
186     }
187
188     def _get_stage_common(self, cr, uid, context):
189         ids = self.pool.get('crm.case.stage').search(cr, uid, [('case_default', '=', 1)], context=context)
190         return ids
191
192     _defaults = {
193         'active': 1,
194         'stage_ids': _get_stage_common,
195         'use_leads': True,
196     }
197
198     _sql_constraints = [
199         ('code_uniq', 'unique (code)', 'The code of the sales team must be unique !')
200     ]
201
202     _constraints = [
203         (osv.osv._check_recursion, 'Error ! You cannot create recursive Sales team.', ['parent_id'])
204     ]
205
206     def name_get(self, cr, uid, ids, context=None):
207         """Overrides orm name_get method"""
208         if not isinstance(ids, list):
209             ids = [ids]
210         res = []
211         if not ids:
212             return res
213         reads = self.read(cr, uid, ids, ['name', 'parent_id'], context)
214
215         for record in reads:
216             name = record['name']
217             if record['parent_id']:
218                 name = record['parent_id'][1] + ' / ' + name
219             res.append((record['id'], name))
220         return res
221
222     def create(self, cr, uid, vals, context=None):
223         if context is None:
224             context = {}
225         create_context = dict(context, alias_model_name='crm.lead', alias_parent_model_name=self._name)
226         section_id = super(crm_case_section, self).create(cr, uid, vals, context=create_context)
227         section = self.browse(cr, uid, section_id, context=context)
228         self.pool.get('mail.alias').write(cr, uid, [section.alias_id.id], {'alias_parent_thread_id': section_id, 'alias_defaults': {'section_id': section_id, 'type': 'lead'}}, context=context)
229         return section_id
230
231     def unlink(self, cr, uid, ids, context=None):
232         # Cascade-delete mail aliases as well, as they should not exist without the sales team.
233         mail_alias = self.pool.get('mail.alias')
234         alias_ids = [team.alias_id.id for team in self.browse(cr, uid, ids, context=context) if team.alias_id]
235         res = super(crm_case_section, self).unlink(cr, uid, ids, context=context)
236         mail_alias.unlink(cr, uid, alias_ids, context=context)
237         return res
238
239 class crm_case_categ(osv.osv):
240     """ Category of Case """
241     _name = "crm.case.categ"
242     _description = "Category of Case"
243     _columns = {
244         'name': fields.char('Name', size=64, required=True, translate=True),
245         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
246         'object_id': fields.many2one('ir.model', 'Object Name'),
247     }
248     def _find_object_id(self, cr, uid, context=None):
249         """Finds id for case object"""
250         context = context or {}
251         object_id = context.get('object_id', False)
252         ids = self.pool.get('ir.model').search(cr, uid, ['|',('id', '=', object_id),('model', '=', context.get('object_name', False))])
253         return ids and ids[0] or False
254     _defaults = {
255         'object_id' : _find_object_id
256     }
257
258 class crm_case_resource_type(osv.osv):
259     """ Resource Type of case """
260     _name = "crm.case.resource.type"
261     _description = "Campaign"
262     _rec_name = "name"
263     _columns = {
264         'name': fields.char('Campaign Name', size=64, required=True, translate=True),
265         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
266     }
267
268 class crm_payment_mode(osv.osv):
269     """ Payment Mode for Fund """
270     _name = "crm.payment.mode"
271     _description = "CRM Payment Mode"
272     _columns = {
273         'name': fields.char('Name', size=64, required=True),
274         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
275     }
276
277
278 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: