[REV] crm: reverted most changes about stages for this branch.
[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': lambda *args: 1,
83         'probability': lambda *args: 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'),
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         for group in group_obj:
127             group_begin_date = datetime.strptime(group['__domain'][0][2], tools.DEFAULT_SERVER_DATE_FORMAT)
128             month_delta = relativedelta.relativedelta(month_begin, group_begin_date)
129             section_result[self._period_number - (month_delta.months + 1)] = {'value': group.get(value_field, 0), 'tooltip': group_begin_date.strftime('%B')}
130         return section_result
131
132     def _get_opportunities_data(self, cr, uid, ids, field_name, arg, context=None):
133         """ Get opportunities-related data for salesteam kanban view
134             monthly_open_leads: number of open lead during the last months
135             monthly_planned_revenue: planned revenu of opportunities during the last months
136         """
137         obj = self.pool.get('crm.lead')
138         res = dict.fromkeys(ids, False)
139         month_begin = date.today().replace(day=1)
140         date_begin = month_begin - relativedelta.relativedelta(months=self._period_number - 1)
141         date_end = month_begin.replace(day=calendar.monthrange(month_begin.year, month_begin.month)[1])
142         date_domain = [('create_date', '>=', date_begin.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)), ('create_date', '<=', date_end.strftime(tools.DEFAULT_SERVER_DATE_FORMAT))]
143         for id in ids:
144             res[id] = dict()
145             lead_domain = date_domain + [('type', '=', 'lead'), ('section_id', '=', id)]
146             res[id]['monthly_open_leads'] = self.__get_bar_values(cr, uid, obj, lead_domain, ['create_date'], 'create_date_count', 'create_date', context=context)
147             opp_domain = date_domain + [('type', '=', 'opportunity'), ('section_id', '=', id)]
148             res[id]['monthly_planned_revenue'] = self.__get_bar_values(cr, uid, obj, opp_domain, ['planned_revenue', 'create_date'], 'planned_revenue', 'create_date', context=context)
149         return res
150
151     _columns = {
152         'name': fields.char('Sales Team', size=64, required=True, translate=True),
153         'complete_name': fields.function(get_full_name, type='char', size=256, readonly=True, store=True),
154         'code': fields.char('Code', size=8),
155         'active': fields.boolean('Active', help="If the active field is set to "\
156                         "true, it will allow you to hide the sales team without removing it."),
157         'change_responsible': fields.boolean('Reassign Escalated', help="When escalating to this team override the salesman with the team leader."),
158         'user_id': fields.many2one('res.users', 'Team Leader'),
159         'member_ids': fields.many2many('res.users', 'sale_member_rel', 'section_id', 'member_id', 'Team Members'),
160         '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"),
161         'parent_id': fields.many2one('crm.case.section', 'Parent Team'),
162         'child_ids': fields.one2many('crm.case.section', 'parent_id', 'Child Teams'),
163         'resource_calendar_id': fields.many2one('resource.calendar', "Working Time", help="Used to compute open days"),
164         'note': fields.text('Description'),
165         'working_hours': fields.float('Working Hours', digits=(16, 2)),
166         'stage_ids': fields.many2many('crm.case.stage', 'section_stage_rel', 'section_id', 'stage_id', 'Stages'),
167         'alias_id': fields.many2one('mail.alias', 'Alias', ondelete="restrict", required=True,
168                                     help="The email address associated with this team. New emails received will automatically "
169                                          "create new leads assigned to the team."),
170         'color': fields.integer('Color Index'),
171         'use_leads': fields.boolean('Leads',
172             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."),
173
174         'monthly_open_leads': fields.function(_get_opportunities_data,
175             type="string", readonly=True, multi='_get_opportunities_data',
176             string='Open Leads per Month'),
177         'monthly_planned_revenue': fields.function(_get_opportunities_data,
178             type="string", readonly=True, multi='_get_opportunities_data',
179             string='Planned Revenue per Month')
180     }
181
182     def _get_stage_common(self, cr, uid, context):
183         ids = self.pool.get('crm.case.stage').search(cr, uid, [('case_default', '=', 1)], context=context)
184         return ids
185
186     _defaults = {
187         'active': 1,
188         'stage_ids': _get_stage_common,
189         'use_leads': True,
190     }
191
192     _sql_constraints = [
193         ('code_uniq', 'unique (code)', 'The code of the sales team must be unique !')
194     ]
195
196     _constraints = [
197         (osv.osv._check_recursion, 'Error ! You cannot create recursive Sales team.', ['parent_id'])
198     ]
199
200     def name_get(self, cr, uid, ids, context=None):
201         """Overrides orm name_get method"""
202         if not isinstance(ids, list):
203             ids = [ids]
204         res = []
205         if not ids:
206             return res
207         reads = self.read(cr, uid, ids, ['name', 'parent_id'], context)
208
209         for record in reads:
210             name = record['name']
211             if record['parent_id']:
212                 name = record['parent_id'][1] + ' / ' + name
213             res.append((record['id'], name))
214         return res
215
216     def create(self, cr, uid, vals, context=None):
217         if context is None:
218             context = {}
219         create_context = dict(context, alias_model_name='crm.lead', alias_parent_model_name=self._name)
220         section_id = super(crm_case_section, self).create(cr, uid, vals, context=create_context)
221         section = self.browse(cr, uid, section_id, context=context)
222         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)
223         return section_id
224
225     def unlink(self, cr, uid, ids, context=None):
226         # Cascade-delete mail aliases as well, as they should not exist without the sales team.
227         mail_alias = self.pool.get('mail.alias')
228         alias_ids = [team.alias_id.id for team in self.browse(cr, uid, ids, context=context) if team.alias_id]
229         res = super(crm_case_section, self).unlink(cr, uid, ids, context=context)
230         mail_alias.unlink(cr, uid, alias_ids, context=context)
231         return res
232
233 class crm_case_categ(osv.osv):
234     """ Category of Case """
235     _name = "crm.case.categ"
236     _description = "Category of Case"
237     _columns = {
238         'name': fields.char('Name', size=64, required=True, translate=True),
239         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
240         'object_id': fields.many2one('ir.model', 'Object Name'),
241     }
242     def _find_object_id(self, cr, uid, context=None):
243         """Finds id for case object"""
244         context = context or {}
245         object_id = context.get('object_id', False)
246         ids = self.pool.get('ir.model').search(cr, uid, ['|',('id', '=', object_id),('model', '=', context.get('object_name', False))])
247         return ids and ids[0] or False
248     _defaults = {
249         'object_id' : _find_object_id
250     }
251
252 class crm_case_resource_type(osv.osv):
253     """ Resource Type of case """
254     _name = "crm.case.resource.type"
255     _description = "Campaign"
256     _rec_name = "name"
257     _columns = {
258         'name': fields.char('Campaign Name', size=64, required=True, translate=True),
259         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
260     }
261
262 def _links_get(self, cr, uid, context=None):
263     """Gets links value for reference field"""
264     obj = self.pool.get('res.request.link')
265     ids = obj.search(cr, uid, [])
266     res = obj.read(cr, uid, ids, ['object', 'name'], context)
267     return [(r['object'], r['name']) for r in res]
268
269 class crm_payment_mode(osv.osv):
270     """ Payment Mode for Fund """
271     _name = "crm.payment.mode"
272     _description = "CRM Payment Mode"
273     _columns = {
274         'name': fields.char('Name', size=64, required=True),
275         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
276     }
277
278
279 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: