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