[IMP] notification for crm meeting and crm phonecall.
[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     ('open', 'In Progress'),
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         '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         partner_address_id
182     """
183     def _get_default_partner_address(self, cr, uid, context=None):
184         """Gives id of default address for current user
185         :param context: if portal in context is false return false anyway
186         """
187         if context is None:
188             context = {}
189         if not context.get('portal'):
190             return False
191         # was user.address_id.id, but address_id has been removed
192         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
193         if hasattr(user, 'partner_address_id') and user.partner_address_id:
194             return user.partner_address_id
195         return False
196
197     def _get_default_partner(self, cr, uid, context=None):
198         """Gives id of partner for current user
199         :param context: if portal in context is false return false anyway
200         """
201         if context is None:
202             context = {}
203         if not context.get('portal', False):
204             return False
205         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
206         if hasattr(user, 'partner_address_id') and user.partner_address_id:
207             return user.partner_address_id
208         return user.company_id.partner_id.id
209
210     def _get_default_email(self, cr, uid, context=None):
211         """Gives default email address for current user
212         :param context: if portal in context is false return false anyway
213         """
214         if not context.get('portal', False):
215             return False
216         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
217         return user.user_email
218
219     def _get_default_user(self, cr, uid, context=None):
220         """Gives current user id
221        :param context: if portal in context is false return false anyway
222         """
223         if context and context.get('portal', False):
224             return False
225         return uid
226
227     def _get_section(self, cr, uid, context=None):
228         """Gives section id for current User
229         """
230         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
231         return user.context_section_id.id or False
232
233     def onchange_partner_address_id(self, cr, uid, ids, add, email=False):
234         """This function returns value of partner email based on Partner Address
235         :param ids: List of case IDs
236         :param add: Id of Partner's address
237         :param email: Partner's email ID
238         """
239         data = {'value': {'email_from': False, 'phone':False}}
240         if add:
241             address = self.pool.get('res.partner.address').browse(cr, uid, add)
242             data['value'] = {'email_from': address and address.email or False ,
243                              'phone':  address and address.phone or False}
244         if 'phone' not in self._columns:
245             del data['value']['phone']
246         return data
247
248     def onchange_partner_id(self, cr, uid, ids, part, email=False):
249         """This function returns value of partner address based on partner
250         :param ids: List of case IDs
251         :param part: Partner's id
252         :param email: Partner's email ID
253         """
254         data={}
255         if  part:
256             addr = self.pool.get('res.partner').address_get(cr, uid, [part], ['contact'])
257             data = {'partner_address_id': addr['contact']}
258             data.update(self.onchange_partner_address_id(cr, uid, ids, addr['contact'])['value'])
259         return {'value': data}
260
261     def _case_opportunity_meeting_notification(self, cr, uid, ids, context=None):
262         return True
263
264     def _case_open_notification(self, case, context=None):
265         return True
266
267     def _case_close_notification(self, case, context=None):
268         return True
269
270     def _case_cancel_notification(self, case, context=None):
271         return True
272
273     def _case_pending_notification(self, case, context=None):
274         return True
275
276     def _case_reset_notification(self, case, context=None):
277         return True
278
279     def _case_escalate_notification(self, case, context=None):
280         return True
281
282     def _case_phonecall_notification(self, case, action, context=None):
283         return True
284
285     def case_open(self, cr, uid, ids, context=None):
286         """Opens Case
287         :param ids: List of case Ids
288         """
289         cases = self.browse(cr, uid, ids)
290         for case in cases:
291             data = {'state': 'open', 'active': True}
292             if not case.user_id:
293                 data['user_id'] = uid
294             self.write(cr, uid, [case.id], data)
295             self._case_open_notification(case, context=context)
296         self._action(cr, uid, cases, 'open')
297
298         return True
299
300     def case_close(self, cr, uid, ids, context=None):
301         """Closes Case
302         :param ids: List of case Ids
303         """
304         cases = self.browse(cr, uid, ids)
305         cases[0].state # to fill the browse record cache
306         self.write(cr, uid, ids, {'state': 'done', 'date_closed': time.strftime('%Y-%m-%d %H:%M:%S'), })
307         # We use the cache of cases to keep the old case state
308         self._case_close_notification(cases, context=context)
309         self._action(cr, uid, cases, 'done')
310         return True
311
312     def case_cancel(self, cr, uid, ids, context=None):
313         """Cancels Case
314         :param ids: List of case Ids
315         """
316         cases = self.browse(cr, uid, ids)
317         cases[0].state # to fill the browse record cache
318         self.write(cr, uid, ids, {'state': 'cancel', 'active': True})
319         # We use the cache of cases to keep the old case state
320         self._case_cancel_notification(cases, context=context)
321         self._action(cr, uid, cases, 'cancel')
322         return True
323
324     def case_pending(self, cr, uid, ids, context=None):
325         """Marks case as pending
326         :param ids: List of case Ids
327         """
328         cases = self.browse(cr, uid, ids)
329         cases[0].state # to fill the browse record cache
330         self.write(cr, uid, ids, {'state': 'pending', 'active': True})
331         self._case_pending_notification(cases, context=context)
332         self._action(cr, uid, cases, 'pending')
333         return True
334
335     def case_reset(self, cr, uid, ids, context=None):
336         """Resets case as draft
337         :param ids: List of case Ids
338         """
339         cases = self.browse(cr, uid, ids)
340         cases[0].state # to fill the browse record cache
341         self.write(cr, uid, ids, {'state': 'draft', 'active': True})
342         self._case_reset_notification(cases, context=context)
343         self._action(cr, uid, cases, 'draft')
344         return True
345
346     def _action(self, cr, uid, cases, state_to, scrit=None, context=None):
347         if context is None:
348             context = {}
349         context['state_to'] = state_to
350         rule_obj = self.pool.get('base.action.rule')
351         model_obj = self.pool.get('ir.model')
352         model_ids = model_obj.search(cr, uid, [('model','=',self._name)])
353         rule_ids = rule_obj.search(cr, uid, [('model_id','=',model_ids[0])])
354         return rule_obj._action(cr, uid, rule_ids, cases, scrit=scrit, context=context)
355
356 class crm_case(crm_base):
357     """ A simple python class to be used for common functions
358     Object that inherit from this class should inherit from mailgate.thread
359     And need a stage_id field
360     And object that inherit (orm inheritance) from a class the overwrite copy
361     """
362
363     def stage_find(self, cr, uid, section_id, domain=[], order='sequence'):
364         domain = list(domain)
365         if section_id:
366             domain.append(('section_ids', '=', section_id))
367         stage_ids = self.pool.get('crm.case.stage').search(cr, uid, domain, order=order)
368         if stage_ids:
369             return stage_ids[0]
370         return False
371
372     def stage_set(self, cr, uid, ids, stage_id, context=None):
373         value = {}
374         if hasattr(self,'onchange_stage_id'):
375             value = self.onchange_stage_id(cr, uid, ids, stage_id)['value']
376         value['stage_id'] = stage_id
377         return self.write(cr, uid, ids, value, context=context)
378
379     def stage_change(self, cr, uid, ids, op, order, context=None):
380         if context is None:
381             context = {}
382         for case in self.browse(cr, uid, ids, context=context):
383             seq = 0
384             if case.stage_id:
385                 seq = case.stage_id.sequence
386             section_id = None
387             if case.section_id:
388                 section_id = case.section_id.id
389             next_stage_id = self.stage_find(cr, uid, section_id, [('sequence',op,seq)],order)
390             if next_stage_id:
391                 return self.stage_set(cr, uid, [case.id], next_stage_id, context=context)
392         return False
393
394     def stage_next(self, cr, uid, ids, context=None):
395         """This function computes next stage for case from its current stage
396         using available stage for that case type
397         """
398         return self.stage_change(cr, uid, ids, '>','sequence', context)
399
400     def stage_previous(self, cr, uid, ids, context=None):
401         """This function computes previous stage for case from its current
402         stage using available stage for that case type
403         """
404         return self.stage_change(cr, uid, ids, '<', 'sequence desc', context)
405
406     def copy(self, cr, uid, id, default=None, context=None):
407         """Overrides orm copy method to avoid copying messages,
408            as well as date_closed and date_open columns if they
409            exist."""
410         if default is None:
411             default = {}
412
413         default.update({ 'message_ids': [], })
414         if hasattr(self, '_columns'):
415             if self._columns.get('date_closed'):
416                 default.update({ 'date_closed': False, })
417             if self._columns.get('date_open'):
418                 default.update({ 'date_open': False })
419         return super(crm_case, self).copy(cr, uid, id, default, context=context)
420
421     def case_open(self, cr, uid, ids, context=None):
422         """Opens Case"""
423         cases = self.browse(cr, uid, ids)
424         for case in cases:
425             data = {'state': 'open', 'active': True }
426             if not case.user_id:
427                 data['user_id'] = uid
428             self.write(cr, uid, [case.id], data)
429             self._case_open_notification(case, context=context)
430         self._action(cr, uid, cases, 'open')
431         return True
432
433     def case_close(self, cr, uid, ids, context=None):
434         """Closes Case"""
435         cases = self.browse(cr, uid, ids)
436         cases[0].state # to fill the browse record cache
437         self.write(cr, uid, ids, {'state': 'done',
438                                   'date_closed': time.strftime('%Y-%m-%d %H:%M:%S'),
439                                   })
440         #
441         # We use the cache of cases to keep the old case state
442         #
443         self._case_close_notification(cases, context=context)
444         self._action(cr, uid, cases, 'done')
445         return True
446
447     def case_escalate(self, cr, uid, ids, context=None):
448         """Escalates case to parent level"""
449         cases = self.browse(cr, uid, ids)
450         for case in cases:
451             data = {'active': True}
452             if case.section_id.parent_id:
453                 data['section_id'] = case.section_id.parent_id.id
454                 if case.section_id.parent_id.change_responsible:
455                     if case.section_id.parent_id.user_id:
456                         data['user_id'] = case.section_id.parent_id.user_id.id
457             else:
458                 raise osv.except_osv(_('Error !'), _('You can not escalate, you are already at the top level regarding your sales-team category.'))
459             self.write(cr, uid, [case.id], data)
460         cases = self.browse(cr, uid, ids)
461         self._case_escalate_notification(cases, context=context)
462         self._action(cr, uid, cases, 'escalate')
463         return True
464
465     def case_cancel(self, cr, uid, ids, context=None):
466         """Cancels Case"""
467         cases = self.browse(cr, uid, ids)
468         cases[0].state # to fill the browse record cache
469         self.write(cr, uid, ids, {'state': 'cancel',
470                                   'active': True})
471         self._case_cancel_notification(cases, context=context)
472         self._action(cr, uid, cases, 'cancel')
473         return True
474
475     def case_pending(self, cr, uid, ids, context=None):
476         """Marks case as pending"""
477         cases = self.browse(cr, uid, ids)
478         cases[0].state # to fill the browse record cache
479         self.write(cr, uid, ids, {'state': 'pending', 'active': True})
480         self._case_pending_notification(cases, context=context)
481         self._action(cr, uid, cases, 'pending')
482         return True
483
484     def case_reset(self, cr, uid, ids, context=None):
485         """Resets case as draft"""
486         state = 'draft'
487         if 'crm.phonecall' in context: #TO fix: move into crm_phonecall.py?
488             state = 'open'
489         cases = self.browse(cr, uid, ids)
490         cases[0].state # to fill the browse record cache
491         self.write(cr, uid, ids, {'state': state, 'active': True})
492         self._case_reset_notification(cases, context=context);
493         self._action(cr, uid, cases, state)
494         return True
495
496     def remind_partner(self, cr, uid, ids, context=None, attach=False):
497         return self.remind_user(cr, uid, ids, context, attach,
498                 destination=False)
499
500     def remind_user(self, cr, uid, ids, context=None, attach=False, destination=True):
501         mail_message = self.pool.get('mail.message')
502         for case in self.browse(cr, uid, ids, context=context):
503             if not destination and not case.email_from:
504                 return False
505             if not case.user_id.user_email:
506                 return False
507             if destination and case.section_id.user_id:
508                 case_email = case.section_id.user_id.user_email
509             else:
510                 case_email = case.user_id.user_email
511
512             src = case_email
513             dest = case.user_id.user_email or ""
514             body = case.description or ""
515             for message in case.message_ids:
516                 if message.email_from:
517                     body = message.description
518                     break
519
520             if not destination:
521                 src, dest = dest, case.email_from
522                 if body and case.user_id.signature:
523                     if body:
524                         body += '\n\n%s' % (case.user_id.signature)
525                     else:
526                         body = '\n\n%s' % (case.user_id.signature)
527
528             body = self.format_body(body)
529
530             attach_to_send = {}
531
532             if attach:
533                 attach_ids = self.pool.get('ir.attachment').search(cr, uid, [('res_model', '=', self._name), ('res_id', '=', case.id)])
534                 attach_to_send = self.pool.get('ir.attachment').read(cr, uid, attach_ids, ['datas_fname', 'datas'])
535                 attach_to_send = dict(map(lambda x: (x['datas_fname'], base64.decodestring(x['datas'])), attach_to_send))
536
537             # Send an email
538             subject = "Reminder: [%s] %s" % (str(case.id), case.name, )
539             mail_message.schedule_with_attach(cr, uid,
540                 src,
541                 [dest],
542                 subject,
543                 body,
544                 model='crm.case',
545                 reply_to=case.section_id.reply_to,
546                 res_id=case.id,
547                 attachments=attach_to_send,
548                 context=context
549             )
550         return True
551
552     def _check(self, cr, uid, ids=False, context=None):
553         """Function called by the scheduler to process cases for date actions
554            Only works on not done and cancelled cases
555         """
556         cr.execute('select * from crm_case \
557                 where (date_action_last<%s or date_action_last is null) \
558                 and (date_action_next<=%s or date_action_next is null) \
559                 and state not in (\'cancel\',\'done\')',
560                 (time.strftime("%Y-%m-%d %H:%M:%S"),
561                     time.strftime('%Y-%m-%d %H:%M:%S')))
562
563         ids2 = map(lambda x: x[0], cr.fetchall() or [])
564         cases = self.browse(cr, uid, ids2, context=context)
565         return self._action(cr, uid, cases, False, context=context)
566
567     def format_body(self, body):
568         return self.pool.get('base.action.rule').format_body(body)
569
570     def format_mail(self, obj, body):
571         return self.pool.get('base.action.rule').format_mail(obj, body)
572
573     def message_thread_followers(self, cr, uid, ids, context=None):
574         res = {}
575         for case in self.browse(cr, uid, ids, context=context):
576             l=[]
577             if case.email_cc:
578                 l.append(case.email_cc)
579             if case.user_id and case.user_id.user_email:
580                 l.append(case.user_id.user_email)
581             res[case.id] = l
582         return res
583
584 def _links_get(self, cr, uid, context=None):
585     """Gets links value for reference field"""
586     obj = self.pool.get('res.request.link')
587     ids = obj.search(cr, uid, [])
588     res = obj.read(cr, uid, ids, ['object', 'name'], context)
589     return [(r['object'], r['name']) for r in res]
590
591 class users(osv.osv):
592     _inherit = 'res.users'
593     _description = "Users"
594     _columns = {
595         'context_section_id': fields.many2one('crm.case.section', 'Sales Team'),
596     }
597
598     def create(self, cr, uid, vals, context=None):
599         res = super(users, self).create(cr, uid, vals, context=context)
600         section_obj=self.pool.get('crm.case.section')
601         if vals.get('context_section_id'):
602             section_obj.write(cr, uid, [vals['context_section_id']], {'member_ids':[(4, res)]}, context)
603         return res
604
605 users()
606
607 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: