891187f6a8767aed4d6423f7b32ab2a03023f799
[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 base64
23 import time
24 from lxml import etree
25 from osv import fields
26 from osv import osv
27 import tools
28 from tools.translate import _
29
30 MAX_LEVEL = 15
31 AVAILABLE_STATES = [
32     ('draft', 'New'),
33     ('cancel', 'Cancelled'),
34     ('open', 'In Progress'),
35     ('pending', 'Pending'),
36     ('done', 'Closed')
37 ]
38
39 AVAILABLE_PRIORITIES = [
40     ('1', 'Highest'),
41     ('2', 'High'),
42     ('3', 'Normal'),
43     ('4', 'Low'),
44     ('5', 'Lowest'),
45 ]
46
47 class crm_case_channel(osv.osv):
48     _name = "crm.case.channel"
49     _description = "Channels"
50     _order = 'name'
51     _columns = {
52         'name': fields.char('Channel Name', size=64, required=True),
53         'active': fields.boolean('Active'),
54     }
55     _defaults = {
56         'active': lambda *a: 1,
57     }
58
59 class crm_case_stage(osv.osv):
60     """ Model for case stages. This models the main stages of a document
61         management flow. Main CRM objects (leads, opportunities, project 
62         issues, ...) will now use only stages, instead of state and stages.
63         Stages are for example used to display the kanban view of records.
64     """
65     _name = "crm.case.stage"
66     _description = "Stage of case"
67     _rec_name = 'name'
68     _order = "sequence"
69
70     _columns = {
71         'name': fields.char('Stage Name', size=64, required=True, translate=True),
72         'sequence': fields.integer('Sequence', help="Used to order stages. Lower is better."),
73         'probability': fields.float('Probability (%)', required=True, help="This percentage depicts the default/average probability of the Case for this stage to be a success"),
74         'on_change': fields.boolean('Change Probability Automatically', help="Setting this stage will change the probability automatically on the opportunity."),
75         'requirements': fields.text('Requirements'),
76         'section_ids':fields.many2many('crm.case.section', 'section_stage_rel', 'stage_id', 'section_id', string='Sections',
77                         help="Link between stages and sales teams. When set, this limitate the current stage to the selected sales teams."),
78         'state': fields.selection(AVAILABLE_STATES, 'State', required=True, help="The related state for the stage. The state of your document will automatically change regarding the selected stage. For example, if a stage is related to the state 'Close', when your document reaches this stage, it will be automatically have the 'closed' state."),
79         'case_default': fields.boolean('Common to All Teams',
80                         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."),
81         'fold': fields.boolean('Hide in Views when Empty',
82                         help="This stage is not visible, for example in status bar or kanban view, when there are no records in that stage to display."),
83         'type': fields.selection([  ('lead','Lead'),
84                                     ('opportunity', 'Opportunity'),
85                                     ('both', 'Both')],
86                                     string='Type', size=16, required=True,
87                                     help="This field is used to distinguish stages related to Leads from stages related to Opportunities, or to specify stages available for both types."),
88     }
89
90     _defaults = {
91         'sequence': lambda *args: 1,
92         'probability': lambda *args: 0.0,
93         'state': 'draft',
94         'fold': False,
95         'type': 'both',
96     }
97
98 class crm_case_section(osv.osv):
99     """ Model for sales teams. """
100     _name = "crm.case.section"
101     _inherits = {'mail.alias': 'alias_id'}
102     _description = "Sales Teams"
103     _order = "complete_name"
104
105     def get_full_name(self, cr, uid, ids, field_name, arg, context=None):
106         return  dict(self.name_get(cr, uid, ids, context=context))
107
108     _columns = {
109         'name': fields.char('Sales Team', size=64, required=True, translate=True),
110         'complete_name': fields.function(get_full_name, type='char', size=256, readonly=True, store=True),
111         'code': fields.char('Code', size=8),
112         'active': fields.boolean('Active', help="If the active field is set to "\
113                         "true, it will allow you to hide the sales team without removing it."),
114         'allow_unlink': fields.boolean('Allow Delete', help="Allows to delete non draft cases"),
115         'change_responsible': fields.boolean('Reassign Escalated', help="When escalating to this team override the salesman with the team leader."),
116         'user_id': fields.many2one('res.users', 'Team Leader'),
117         'member_ids':fields.many2many('res.users', 'sale_member_rel', 'section_id', 'member_id', 'Team Members'),
118         '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"),
119         'parent_id': fields.many2one('crm.case.section', 'Parent Team'),
120         'child_ids': fields.one2many('crm.case.section', 'parent_id', 'Child Teams'),
121         'resource_calendar_id': fields.many2one('resource.calendar', "Working Time", help="Used to compute open days"),
122         'note': fields.text('Description'),
123         'working_hours': fields.float('Working Hours', digits=(16,2 )),
124         'stage_ids': fields.many2many('crm.case.stage', 'section_stage_rel', 'section_id', 'stage_id', 'Stages'),
125         'alias_id': fields.many2one('mail.alias', 'Alias', ondelete="cascade", required=True, 
126                                     help="The email address associated with this team. New emails received will automatically "
127                                          "create new leads assigned to the team."),
128     }
129     
130     def _get_stage_common(self, cr, uid, context):
131         ids = self.pool.get('crm.case.stage').search(cr, uid, [('case_default','=',1)], context=context)
132         return ids
133
134     _defaults = {
135         'active': lambda *a: 1,
136         'allow_unlink': lambda *a: 1,
137         'stage_ids': _get_stage_common
138     }
139
140     _sql_constraints = [
141         ('code_uniq', 'unique (code)', 'The code of the sales team must be unique !')
142     ]
143
144     _constraints = [
145         (osv.osv._check_recursion, 'Error ! You cannot create recursive Sales team.', ['parent_id'])
146     ]
147
148     def name_get(self, cr, uid, ids, context=None):
149         """Overrides orm name_get method"""
150         if not isinstance(ids, list) :
151             ids = [ids]
152         res = []
153         if not ids:
154             return res
155         reads = self.read(cr, uid, ids, ['name', 'parent_id'], context)
156
157         for record in reads:
158             name = record['name']
159             if record['parent_id']:
160                 name = record['parent_id'][1] + ' / ' + name
161             res.append((record['id'], name))
162         return res
163     
164     def create(self, cr, uid, vals, context=None):
165         mail_alias = self.pool.get('mail.alias')
166         if not vals.get('alias_id'):
167             vals.pop('alias_name', None) # prevent errors during copy()
168             alias_id = mail_alias.create_unique_alias(cr, uid, 
169                     {'alias_name': vals['name']},
170                     model_name="crm.lead",
171                     context=context)
172             vals['alias_id'] = alias_id
173         res = super(crm_case_section, self).create(cr, uid, vals, context)
174         mail_alias.write(cr, uid, [vals['alias_id']], {'alias_defaults': {'section_id': res, 'type':'lead'}}, context)
175         return res
176         
177     def unlink(self, cr, uid, ids, context=None):
178         # Cascade-delete mail aliases as well, as they should not exist without the sales team.
179         mail_alias = self.pool.get('mail.alias')
180         alias_ids = [team.alias_id.id for team in self.browse(cr, uid, ids, context=context) if team.alias_id ]
181         res = super(crm_case_section, self).unlink(cr, uid, ids, context=context)
182         mail_alias.unlink(cr, uid, alias_ids, context=context)
183         return res
184
185 class crm_case_categ(osv.osv):
186     """ Category of Case """
187     _name = "crm.case.categ"
188     _description = "Category of Case"
189     _columns = {
190         'name': fields.char('Name', size=64, required=True, translate=True),
191         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
192         'object_id': fields.many2one('ir.model', 'Object Name'),
193     }
194
195     def _find_object_id(self, cr, uid, context=None):
196         """Finds id for case object"""
197         object_id = context and context.get('object_id', False) or False
198         ids = self.pool.get('ir.model').search(cr, uid, [('id', '=', object_id)])
199         return ids and ids[0] or False
200
201     _defaults = {
202         'object_id' : _find_object_id
203     }
204
205 class crm_case_resource_type(osv.osv):
206     """ Resource Type of case """
207     _name = "crm.case.resource.type"
208     _description = "Campaign"
209     _rec_name = "name"
210     _columns = {
211         'name': fields.char('Campaign Name', size=64, required=True, translate=True),
212         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
213     }
214
215
216 def _links_get(self, cr, uid, context=None):
217     """Gets links value for reference field"""
218     obj = self.pool.get('res.request.link')
219     ids = obj.search(cr, uid, [])
220     res = obj.read(cr, uid, ids, ['object', 'name'], context)
221     return [(r['object'], r['name']) for r in res]
222
223 class crm_payment_mode(osv.osv):
224     """ Payment Mode for Fund """
225     _name = "crm.payment.mode"
226     _description = "CRM Payment Mode"
227     _columns = {
228         'name': fields.char('Name', size=64, required=True),
229         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
230     }
231
232 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: