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