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