[MERGE] latest trunk
[odoo/odoo.git] / addons / crm / crm.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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 time
23 import base64
24 import tools
25
26 from osv import fields
27 from osv import osv
28 from tools.translate import _
29
30 MAX_LEVEL = 15
31 AVAILABLE_STATES = [
32     ('draft', 'Draft'),
33     ('open', 'Open'),
34     ('cancel', 'Cancelled'),
35     ('done', 'Closed'),
36     ('pending', 'Pending'),
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     """ Stage of case """
61
62     _name = "crm.case.stage"
63     _description = "Stage of case"
64     _rec_name = 'name'
65     _order = "sequence"
66
67     _columns = {
68         'name': fields.char('Stage Name', size=64, required=True, translate=True),
69         'sequence': fields.integer('Sequence', help="Used to order stages."),
70         'probability': fields.float('Probability (%)', required=True, help="This percentage depicts the default/average probability of the Case for this stage to be a success"),
71         'on_change': fields.boolean('Change Probability Automatically', help="Setting this stage will change the probability automatically on the opportunity."),
72         'requirements': fields.text('Requirements'),
73         'section_ids':fields.many2many('crm.case.section', 'section_stage_rel', 'stage_id', 'section_id', 'Sections'),
74     }
75
76     _defaults = {
77         'sequence': lambda *args: 1,
78         'probability': lambda *args: 0.0,
79     }
80
81 class crm_case_section(osv.osv):
82     """Sales Team"""
83
84     _name = "crm.case.section"
85     _description = "Sales Teams"
86     _order = "complete_name"
87
88     def get_full_name(self, cr, uid, ids, field_name, arg, context=None):
89         return  dict(self.name_get(cr, uid, ids, context=context))
90
91     _columns = {
92         'name': fields.char('Sales Team', size=64, required=True, translate=True),
93         'complete_name': fields.function(get_full_name, type='char', size=256, readonly=True, store=True),
94         'code': fields.char('Code', size=8),
95         'active': fields.boolean('Active', help="If the active field is set to "\
96                         "true, it will allow you to hide the sales team without removing it."),
97         'allow_unlink': fields.boolean('Allow Delete', help="Allows to delete non draft cases"),
98         'change_responsible': fields.boolean('Reassign Escalated', help="When escalating to this team override the saleman with the team leader."),
99         'user_id': fields.many2one('res.users', 'Team Leader'),
100         'member_ids':fields.many2many('res.users', 'sale_member_rel', 'section_id', 'member_id', 'Team Members'),
101         '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"),
102         'parent_id': fields.many2one('crm.case.section', 'Parent Team'),
103         'child_ids': fields.one2many('crm.case.section', 'parent_id', 'Child Teams'),
104         'resource_calendar_id': fields.many2one('resource.calendar', "Working Time", help="Used to compute open days"),
105         'note': fields.text('Description'),
106         'working_hours': fields.float('Working Hours', digits=(16,2 )),
107         'stage_ids': fields.many2many('crm.case.stage', 'section_stage_rel', 'section_id', 'stage_id', 'Stages'),
108     }
109
110     _defaults = {
111         'active': lambda *a: 1,
112         'allow_unlink': lambda *a: 1,
113     }
114
115     _sql_constraints = [
116         ('code_uniq', 'unique (code)', 'The code of the sales team must be unique !')
117     ]
118
119     _constraints = [
120         (osv.osv._check_recursion, 'Error ! You cannot create recursive Sales team.', ['parent_id'])
121     ]
122
123     def name_get(self, cr, uid, ids, context=None):
124         """Overrides orm name_get method"""
125         if not isinstance(ids, list) : 
126             ids = [ids]
127         res = []
128         if not ids:
129             return res
130         reads = self.read(cr, uid, ids, ['name', 'parent_id'], context)
131
132         for record in reads:
133             name = record['name']
134             if record['parent_id']:
135                 name = record['parent_id'][1] + ' / ' + name
136             res.append((record['id'], name))
137         return res
138
139 class crm_case_categ(osv.osv):
140     """ Category of Case """
141     _name = "crm.case.categ"
142     _description = "Category of Case"
143     _columns = {
144         'name': fields.char('Name', size=64, required=True, translate=True),
145         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
146         'object_id': fields.many2one('ir.model', 'Object Name'),
147     }
148
149     def _find_object_id(self, cr, uid, context=None):
150         """Finds id for case object"""
151         object_id = context and context.get('object_id', False) or False
152         ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', object_id)])
153         return ids and ids[0]
154
155     _defaults = {
156         'object_id' : _find_object_id
157     }
158
159 class crm_case_resource_type(osv.osv):
160     """ Resource Type of case """
161     _name = "crm.case.resource.type"
162     _description = "Campaign"
163     _rec_name = "name"
164     _columns = {
165         'name': fields.char('Campaign Name', size=64, required=True, translate=True),
166         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
167     }
168
169 class crm_base(object):
170     """ Base utility mixin class for crm objects,
171     Object subclassing this should define colums:
172         date_open
173         date_closed
174         user_id
175         partner_id
176         partner_address_id
177     """
178     def _get_default_partner_address(self, cr, uid, context=None):
179         """Gives id of default address for current user
180         :param context: if portal in context is false return false anyway
181         """
182         if context is None:
183             context = {}
184         if not context.get('portal'):
185             return False
186         # was user.address_id.id, but address_id has been removed
187         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
188         if hasattr(user, 'partner_address_id') and user.partner_address_id:
189             return user.partner_address_id
190         return False
191
192     def _get_default_partner(self, cr, uid, context=None):
193         """Gives id of partner for current user
194         :param context: if portal in context is false return false anyway
195         """
196         if context is None:
197             context = {}
198         if not context.get('portal', False):
199             return False
200         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
201         if hasattr(user, 'partner_address_id') and user.partner_address_id:
202             return user.partner_address_id
203         return user.company_id.partner_id.id
204
205     def _get_default_email(self, cr, uid, context=None):
206         """Gives default email address for current user
207         :param context: if portal in context is false return false anyway
208         """
209         if not context.get('portal', False):
210             return False
211         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
212         return user.user_email
213
214     def _get_default_user(self, cr, uid, context=None):
215         """Gives current user id
216        :param context: if portal in context is false return false anyway
217         """
218         if context and context.get('portal', False):
219             return False
220         return uid
221
222     def _get_section(self, cr, uid, context=None):
223         """Gives section id for current User
224         """
225         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
226         return user.context_section_id.id or False
227
228     def onchange_partner_address_id(self, cr, uid, ids, add, email=False):
229         """This function returns value of partner email based on Partner Address
230         :param ids: List of case IDs
231         :param add: Id of Partner's address
232         :param email: Partner's email ID
233         """
234         if not add:
235             return {'value': {'email_from': False}}
236         address = self.pool.get('res.partner.address').browse(cr, uid, add)
237         if address.email:
238             return {'value': {'email_from': address.email, 'phone': address.phone}}
239         else:
240             return {'value': {'phone': address.phone}}
241
242     def onchange_partner_id(self, cr, uid, ids, part, email=False):
243         """This function returns value of partner address based on partner
244         :param ids: List of case IDs
245         :param part: Partner's id
246         :param email: Partner's email ID
247         """
248         data={}
249         if  part:
250             addr = self.pool.get('res.partner').address_get(cr, uid, [part], ['contact'])
251             data = {'partner_address_id': addr['contact']}
252             data.update(self.onchange_partner_address_id(cr, uid, ids, addr['contact'])['value'])
253         return {'value': data}
254
255     def case_open(self, cr, uid, ids, *args):
256         """Opens Case
257         :param ids: List of case Ids
258         """
259         cases = self.browse(cr, uid, ids)
260         for case in cases:
261             data = {'state': 'open', 'active': True}
262             if not case.user_id:
263                 data['user_id'] = uid
264             self.write(cr, uid, case.id, data)
265
266         self._action(cr, uid, cases, 'open')
267         return True
268
269     def case_close(self, cr, uid, ids, *args):
270         """Closes Case
271         :param ids: List of case Ids
272         """
273         cases = self.browse(cr, uid, ids)
274         cases[0].state # to fill the browse record cache
275         self.write(cr, uid, ids, {'state': 'done', 'date_closed': time.strftime('%Y-%m-%d %H:%M:%S'), })
276         # We use the cache of cases to keep the old case state
277         self._action(cr, uid, cases, 'done')
278         return True
279
280     def case_cancel(self, cr, uid, ids, *args):
281         """Cancels Case
282         :param ids: List of case Ids
283         """
284         cases = self.browse(cr, uid, ids)
285         cases[0].state # to fill the browse record cache
286         self.write(cr, uid, ids, {'state': 'cancel', 'active': True})
287         # We use the cache of cases to keep the old case state
288         self._action(cr, uid, cases, 'cancel')
289         return True
290
291     def case_pending(self, cr, uid, ids, *args):
292         """Marks case as pending
293         :param ids: List of case Ids
294         """
295         cases = self.browse(cr, uid, ids)
296         cases[0].state # to fill the browse record cache
297         self.write(cr, uid, ids, {'state': 'pending', 'active': True})
298         self._action(cr, uid, cases, 'pending')
299         return True
300
301     def case_reset(self, cr, uid, ids, *args):
302         """Resets case as draft
303         :param ids: List of case Ids
304         """
305         cases = self.browse(cr, uid, ids)
306         cases[0].state # to fill the browse record cache
307         self.write(cr, uid, ids, {'state': 'draft', 'active': True})
308         self._action(cr, uid, cases, 'draft')
309         return True
310
311     def _action(self, cr, uid, cases, state_to, scrit=None, context=None):
312         if context is None:
313             context = {}
314         context['state_to'] = state_to
315         rule_obj = self.pool.get('base.action.rule')
316         model_obj = self.pool.get('ir.model')
317         model_ids = model_obj.search(cr, uid, [('model','=',self._name)])
318         rule_ids = rule_obj.search(cr, uid, [('model_id','=',model_ids[0])])
319         return rule_obj._action(cr, uid, rule_ids, cases, scrit=scrit, context=context)
320
321 class crm_case(crm_base):
322     """ A simple python class to be used for common functions 
323     Object that inherit from this class should inherit from mailgate.thread
324     And need a stage_id field
325     And object that inherit (orm inheritance) from a class the overwrite copy 
326     """
327
328     def stage_find(self, cr, uid, section_id, domain=[], order='sequence'):
329         domain = list(domain)
330         if section_id:
331             domain.append(('section_ids', '=', section_id))
332         stage_ids = self.pool.get('crm.case.stage').search(cr, uid, domain, order=order)
333         if stage_ids:
334             return stage_ids[0]
335         return False
336
337     def stage_set(self, cr, uid, ids, stage_id, context=None):
338         value = {}
339         if hasattr(self,'onchange_stage_id'):
340             value = self.onchange_stage_id(cr, uid, ids, stage_id)['value']
341         value['stage_id'] = stage_id
342         return self.write(cr, uid, ids, value, context=context)
343
344     def stage_change(self, cr, uid, ids, op, order, context=None):
345         if context is None:
346             context = {}
347         for case in self.browse(cr, uid, ids, context=context):
348             seq = 0
349             if case.stage_id:
350                 seq = case.stage_id.sequence
351             section_id = None
352             if case.section_id:
353                 section_id = case.section_id.id
354             next_stage_id = self.stage_find(cr, uid, section_id, [('sequence',op,seq)],order)
355             if next_stage_id:
356                 return self.stage_set(cr, uid, [case.id], next_stage_id, context=context)
357         return False
358
359     def stage_next(self, cr, uid, ids, context=None):
360         """This function computes next stage for case from its current stage
361         using available stage for that case type
362         """
363         return self.stage_change(cr, uid, ids, '>','sequence', context)
364
365     def stage_previous(self, cr, uid, ids, context=None):
366         """This function computes previous stage for case from its current
367         stage using available stage for that case type
368         """
369         return self.stage_change(cr, uid, ids, '<', 'sequence desc', context)
370
371     def copy(self, cr, uid, id, default=None, context=None):
372         """Overrides orm copy method to avoid copying messages,
373            as well as date_closed and date_open columns if they
374            exist."""
375         if default is None:
376             default = {}
377
378         default.update({ 'message_ids': [], })
379         if hasattr(self, '_columns'):
380             if self._columns.get('date_closed'):
381                 default.update({ 'date_closed': False, })
382             if self._columns.get('date_open'):
383                 default.update({ 'date_open': False })
384         return super(osv.osv, self).copy(cr, uid, id, default, context=context)
385
386
387     def case_open(self, cr, uid, ids, *args):
388         """Opens Case"""
389         cases = self.browse(cr, uid, ids)
390         self.message_append(cr, uid, cases, _('Open'))
391         for case in cases:
392             data = {'state': 'open', 'active': True }
393             if not case.user_id:
394                 data['user_id'] = uid
395             self.write(cr, uid, case.id, data)
396         self._action(cr, uid, cases, 'open')
397         return True
398
399     def case_close(self, cr, uid, ids, *args):
400         """Closes Case"""
401         cases = self.browse(cr, uid, ids)
402         cases[0].state # to fill the browse record cache
403         self.message_append(cr, uid, cases, _('Close'))
404         self.write(cr, uid, ids, {'state': 'done',
405                                   'date_closed': time.strftime('%Y-%m-%d %H:%M:%S'),
406                                   })
407         #
408         # We use the cache of cases to keep the old case state
409         #
410         self._action(cr, uid, cases, 'done')
411         return True
412
413     def case_escalate(self, cr, uid, ids, *args):
414         """Escalates case to parent level"""
415         cases = self.browse(cr, uid, ids)
416         for case in cases:
417             data = {'active': True}
418             if case.section_id.parent_id:
419                 data['section_id'] = case.section_id.parent_id.id
420                 if case.section_id.parent_id.change_responsible:
421                     if case.section_id.parent_id.user_id:
422                         data['user_id'] = case.section_id.parent_id.user_id.id
423             else:
424                 raise osv.except_osv(_('Error !'), _('You can not escalate, You are already at the top level regarding your sales-team category.'))
425             self.write(cr, uid, [case.id], data)
426         cases = self.browse(cr, uid, ids)
427         self.message_append(cr, uid, cases, _('Escalate'))
428         self._action(cr, uid, cases, 'escalate')
429         return True
430
431     def case_cancel(self, cr, uid, ids, *args):
432         """Cancels Case"""
433         cases = self.browse(cr, uid, ids)
434         cases[0].state # to fill the browse record cache
435         self.message_append(cr, uid, cases, _('Cancel'))
436         self.write(cr, uid, ids, {'state': 'cancel',
437                                   'active': True})
438         self._action(cr, uid, cases, 'cancel')
439         for case in cases:
440             message = _("The case '%s' has been cancelled.") % (case.name,)
441             self.log(cr, uid, case.id, message)
442         return True
443
444     def case_pending(self, cr, uid, ids, *args):
445         """Marks case as pending"""
446         cases = self.browse(cr, uid, ids)
447         cases[0].state # to fill the browse record cache
448         self.message_append(cr, uid, cases, _('Pending'))
449         self.write(cr, uid, ids, {'state': 'pending', 'active': True})
450         self._action(cr, uid, cases, 'pending')
451         return True
452
453     def case_reset(self, cr, uid, ids, *args):
454         """Resets case as draft"""
455         state = 'draft'
456         if 'crm.phonecall' in args:
457             state = 'open'
458         cases = self.browse(cr, uid, ids)
459         cases[0].state # to fill the browse record cache
460         self.message_append(cr, uid, cases, _('Draft'))
461         self.write(cr, uid, ids, {'state': state, 'active': True})
462         self._action(cr, uid, cases, state)
463         return True
464
465     def remind_partner(self, cr, uid, ids, context=None, attach=False):
466         return self.remind_user(cr, uid, ids, context, attach,
467                 destination=False)
468
469     def remind_user(self, cr, uid, ids, context=None, attach=False, destination=True):
470         mail_message = self.pool.get('mail.message')
471         for case in self.browse(cr, uid, ids, context=context):
472             if not destination and not case.email_from:
473                 return False
474             if not case.user_id.user_email:
475                 return False
476             if destination and case.section_id.user_id:
477                 case_email = case.section_id.user_id.user_email
478             else:
479                 case_email = case.user_id.user_email
480
481             src = case_email
482             dest = case.user_id
483             body = case.description or ""
484             if case.message_ids:
485                 body = case.message_ids[0].description or ""
486             if not destination:
487                 src, dest = dest, case.email_from
488                 if body and case.user_id.signature:
489                     if body:
490                         body += '\n\n%s' % (case.user_id.signature)
491                     else:
492                         body = '\n\n%s' % (case.user_id.signature)
493
494             body = self.format_body(body)
495
496             attach_to_send = {}
497
498             if attach:
499                 attach_ids = self.pool.get('ir.attachment').search(cr, uid, [('res_model', '=', self._name), ('res_id', '=', case.id)])
500                 attach_to_send = self.pool.get('ir.attachment').read(cr, uid, attach_ids, ['datas_fname', 'datas'])
501                 attach_to_send = dict(map(lambda x: (x['datas_fname'], base64.decodestring(x['datas'])), attach_to_send))
502
503             # Send an email
504             subject = "Reminder: [%s] %s" % (str(case.id), case.name, )
505             mail_message.schedule_with_attach(cr, uid,
506                 src,
507                 [dest],
508                 subject,
509                 body,
510                 model='crm.case',
511                 reply_to=case.section_id.reply_to,
512                 res_id=case.id,
513                 attachments=attach_to_send,
514                 context=context
515             )
516         return True
517
518     def _check(self, cr, uid, ids=False, context=None):
519         """Function called by the scheduler to process cases for date actions
520            Only works on not done and cancelled cases
521         """
522         cr.execute('select * from crm_case \
523                 where (date_action_last<%s or date_action_last is null) \
524                 and (date_action_next<=%s or date_action_next is null) \
525                 and state not in (\'cancel\',\'done\')',
526                 (time.strftime("%Y-%m-%d %H:%M:%S"),
527                     time.strftime('%Y-%m-%d %H:%M:%S')))
528
529         ids2 = map(lambda x: x[0], cr.fetchall() or [])
530         cases = self.browse(cr, uid, ids2, context=context)
531         return self._action(cr, uid, cases, False, context=context)
532
533     def format_body(self, body):
534         return self.pool.get('base.action.rule').format_body(body)
535
536     def format_mail(self, obj, body):
537         return self.pool.get('base.action.rule').format_mail(obj, body)
538
539     def message_thread_followers(self, cr, uid, ids, context=None):
540         res = {}
541         for case in self.browse(cr, uid, ids, context=context):
542             l=[]
543             if case.email_cc:
544                 l.append(case.email_cc)
545             if case.user_id and case.user_id.user_email:
546                 l.append(case.user_id.user_email)
547             res[case.id] = l
548         return res
549
550 def _links_get(self, cr, uid, context=None):
551     """Gets links value for reference field"""
552     obj = self.pool.get('res.request.link')
553     ids = obj.search(cr, uid, [])
554     res = obj.read(cr, uid, ids, ['object', 'name'], context)
555     return [(r['object'], r['name']) for r in res]
556
557 class users(osv.osv):
558     _inherit = 'res.users'
559     _description = "Users"
560     _columns = {
561         'context_section_id': fields.many2one('crm.case.section', 'Sales Team'),
562     }
563
564     def create(self, cr, uid, vals, context=None):
565         res = super(users, self).create(cr, uid, vals, context=context)
566         section_obj=self.pool.get('crm.case.section')
567         if vals.get('context_section_id'):
568             section_obj.write(cr, uid, [vals['context_section_id']], {'member_ids':[(4, res)]}, context)
569         return res
570
571 users()