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