1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
26 from osv import fields
28 from tools.translate import _
34 ('cancel', 'Cancelled'),
36 ('pending', 'Pending'),
39 AVAILABLE_PRIORITIES = [
47 class crm_base(object):
49 Base classe for crm object,
50 Object that inherit from this class should have
56 as field to be compatible with this class
59 def _get_default_partner_address(self, cr, uid, context=None):
61 """Gives id of default address for current user
62 :param context: if portal in context is false return false anyway
66 if not context.get('portal'):
68 return self.pool.get('res.partner.address').browse(cr, uid, uid, context)
70 def _get_default_partner(self, cr, uid, context=None):
71 """Gives id of partner for current user
72 :param context: if portal in context is false return false anyway
76 if not context.get('portal', False):
78 part_id = self.pool.get('res.partner.address').browse(cr, uid, uid, context=context)
79 return part_id.partner_id
81 def _get_default_email(self, cr, uid, context=None):
82 """Gives default email address for current user
83 :param context: if portal in context is false return false anyway
85 if not context.get('portal', False):
87 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
88 return user.user_email
90 def _get_default_user(self, cr, uid, context=None):
91 """Gives current user id
92 :param context: if portal in context is false return false anyway
94 if context and context.get('portal', False):
98 def _get_section(self, cr, uid, context=None):
99 """Gives section id for current User
101 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
102 return user.context_section_id.id or False
104 def onchange_partner_address_id(self, cr, uid, ids, add, email=False):
105 """This function returns value of partner email based on Partner Address
106 @param ids: List of case IDs
107 @param add: Id of Partner's address
108 @email: Partner's email ID
111 return {'value': {'email_from': False}}
112 address = self.pool.get('res.partner.address').browse(cr, uid, add)
114 return {'value': {'email_from': address.email, 'phone': address.phone}}
116 return {'value': {'phone': address.phone}}
118 def onchange_partner_id(self, cr, uid, ids, part, email=False):
119 """This function returns value of partner address based on partner
120 @param ids: List of case IDs
121 @param part: Partner's id
122 @email: Partner's email ID
126 addr = self.pool.get('res.partner').address_get(cr, uid, [part], ['contact'])
127 data = {'partner_address_id': addr['contact']}
128 data.update(self.onchange_partner_address_id(cr, uid, ids, addr['contact'])['value'])
129 return {'value': data}
132 def case_open(self, cr, uid, ids, *args):
134 @param ids: List of case Ids
136 cases = self.browse(cr, uid, ids)
138 data = {'state': 'open', 'active': True}
140 data['user_id'] = uid
141 self.write(cr, uid, case.id, data)
144 self._action(cr, uid, cases, 'open')
147 def case_close(self, cr, uid, ids, *args):
149 @param ids: List of case Ids
151 cases = self.browse(cr, uid, ids)
152 cases[0].state # to fill the browse record cache
153 self.write(cr, uid, ids, {'state': 'done',
154 'date_closed': time.strftime('%Y-%m-%d %H:%M:%S'),
157 # We use the cache of cases to keep the old case state
159 self._action(cr, uid, cases, 'done')
162 def case_cancel(self, cr, uid, ids, *args):
164 @param ids: List of case Ids
166 cases = self.browse(cr, uid, ids)
167 cases[0].state # to fill the browse record cache
168 self.write(cr, uid, ids, {'state': 'cancel',
170 self._action(cr, uid, cases, 'cancel')
172 message = _("The case '%s' has been cancelled.") % (case.name,)
173 self.log(cr, uid, case.id, message)
176 def case_pending(self, cr, uid, ids, *args):
177 """Marks case as pending
178 @param ids: List of case Ids
180 cases = self.browse(cr, uid, ids)
181 cases[0].state # to fill the browse record cache
182 self.write(cr, uid, ids, {'state': 'pending', 'active': True})
183 self._action(cr, uid, cases, 'pending')
186 def case_reset(self, cr, uid, ids, *args):
187 """Resets case as draft
188 @param ids: List of case Ids
190 cases = self.browse(cr, uid, ids)
191 cases[0].state # to fill the browse record cache
192 self.write(cr, uid, ids, {'state': 'draft', 'active': True})
193 self._action(cr, uid, cases, 'draft')
196 def _action(self, cr, uid, cases, state_to, scrit=None, context=None):
199 context['state_to'] = state_to
200 rule_obj = self.pool.get('base.action.rule')
201 model_obj = self.pool.get('ir.model')
202 model_ids = model_obj.search(cr, uid, [('model','=',self._name)])
203 rule_ids = rule_obj.search(cr, uid, [('model_id','=',model_ids[0])])
204 return rule_obj._action(cr, uid, rule_ids, cases, scrit=scrit, context=context)
206 class crm_case(crm_base):
208 A simple python class to be used for common functions
209 Object that inherit from this class should inherit from mailgate.thread
210 And need a stage_id field
212 And object that inherit (orm inheritance) from a class the overwrite copy
215 def _find_lost_stage(self, cr, uid, type, section_id):
216 return self._find_percent_stage(cr, uid, 0.0, type, section_id)
218 def _find_won_stage(self, cr, uid, type, section_id):
219 return self._find_percent_stage(cr, uid, 100.0, type, section_id)
221 def _find_percent_stage(self, cr, uid, percent, type, section_id):
223 Return the first stage with a probability == percent
225 stage_pool = self.pool.get('crm.case.stage')
227 ids = stage_pool.search(cr, uid, [("probability", '=', percent), ("type", 'like', type), ("section_ids", 'in', [section_id])])
229 ids = stage_pool.search(cr, uid, [("probability", '=', percent), ("type", 'like', type)])
236 def _find_first_stage(self, cr, uid, type, section_id):
238 return the first stage that has a sequence number equal or higher than sequence
240 stage_pool = self.pool.get('crm.case.stage')
242 ids = stage_pool.search(cr, uid, [("sequence", '>', 0), ("type", 'like', type), ("section_ids", 'in', [section_id])])
244 ids = stage_pool.search(cr, uid, [("sequence", '>', 0), ("type", 'like', type)])
247 stages = stage_pool.browse(cr, uid, ids)
248 stage_min = stages[0]
250 if stage_min.sequence > stage.sequence:
256 def onchange_stage_id(self, cr, uid, ids, stage_id, context={}):
258 """ @param self: The object pointer
259 @param cr: the current row, from the database cursor,
260 @param uid: the current user’s ID for security checks,
261 @param ids: List of stage’s IDs
262 @stage_id: change state id on run time """
267 stage = self.pool.get('crm.case.stage').browse(cr, uid, stage_id, context)
269 if not stage.on_change:
271 return {'value':{'probability': stage.probability}}
275 def copy(self, cr, uid, id, default=None, context=None):
277 Overrides orm copy method.
278 @param self: the object pointer
279 @param cr: the current row, from the database cursor,
280 @param uid: the current user’s ID for security checks,
281 @param id: Id of mailgate thread
282 @param default: Dictionary of default values for copy.
283 @param context: A standard dictionary for contextual values
294 if hasattr(self, '_columns'):
295 if self._columns.get('date_closed'):
297 'date_closed': False,
299 if self._columns.get('date_open'):
303 return super(osv.osv, self).copy(cr, uid, id, default, context=context)
309 def _find_next_stage(self, cr, uid, stage_list, index, current_seq, stage_pool, context=None):
310 if index + 1 == len(stage_list):
312 next_stage_id = stage_list[index + 1]
313 next_stage = stage_pool.browse(cr, uid, next_stage_id, context=context)
316 next_seq = next_stage.sequence
320 if (abs(next_seq - current_seq)) >= 1:
323 return self._find_next_stage(cr, uid, stage_list, index + 1, current_seq, stage_pool)
325 def stage_change(self, cr, uid, ids, context=None, order='sequence'):
329 stage_pool = self.pool.get('crm.case.stage')
330 stage_type = context and context.get('stage_type','')
332 next_stage_id = False
334 for case in self.browse(cr, uid, ids, context=context):
338 if case.section_id.id :
339 domain = [('type', '=', stage_type),('section_ids', '=', case.section_id.id)]
341 domain = [('type', '=', stage_type)]
344 stages = stage_pool.search(cr, uid, domain, order=order)
345 current_seq = case.stage_id.sequence
347 if case.stage_id and case.stage_id.id in stages:
348 index = stages.index(case.stage_id.id)
350 next_stage = self._find_next_stage(cr, uid, stages, index, current_seq, stage_pool, context=context)
353 next_stage_id = next_stage.id
354 value.update({'stage_id': next_stage.id})
355 if next_stage.on_change:
356 value.update({'probability': next_stage.probability})
357 self.write(cr, uid, [case.id], value, context=context)
360 return next_stage_id #FIXME should return a list of all id
363 def stage_next(self, cr, uid, ids, context=None):
364 """This function computes next stage for case from its current stage
365 using available stage for that case type
366 @param self: The object pointer
367 @param cr: the current row, from the database cursor,
368 @param uid: the current user’s ID for security checks,
369 @param ids: List of case IDs
370 @param context: A standard dictionary for contextual values"""
372 return self.stage_change(cr, uid, ids, context=context, order='sequence')
374 def stage_previous(self, cr, uid, ids, context=None):
375 """This function computes previous stage for case from its current stage
376 using available stage for that case type
377 @param self: The object pointer
378 @param cr: the current row, from the database cursor,
379 @param uid: the current user’s ID for security checks,
380 @param ids: List of case IDs
381 @param context: A standard dictionary for contextual values"""
382 return self.stage_change(cr, uid, ids, context=context, order='sequence desc')
388 def _history(self, cr, uid, cases, keyword, history=False, subject=None, email=False, details=None, email_from=False, message_id=False, attach=[], context=None):
389 mailgate_pool = self.pool.get('mailgate.thread')
390 return mailgate_pool.history(cr, uid, cases, keyword, history=history,\
391 subject=subject, email=email, \
392 details=details, email_from=email_from,\
393 message_id=message_id, attach=attach, \
396 def case_open(self, cr, uid, ids, *args):
398 @param self: The object pointer
399 @param cr: the current row, from the database cursor,
400 @param uid: the current user’s ID for security checks,
401 @param ids: List of case Ids
402 @param *args: Tuple Value for additional Params
405 cases = self.browse(cr, uid, ids)
406 self._history(cr, uid, cases, _('Open'))
408 data = {'state': 'open', 'active': True}
410 data['user_id'] = uid
411 self.write(cr, uid, case.id, data)
412 self._action(cr, uid, cases, 'open')
415 def case_close(self, cr, uid, ids, *args):
417 @param self: The object pointer
418 @param cr: the current row, from the database cursor,
419 @param uid: the current user’s ID for security checks,
420 @param ids: List of case Ids
421 @param *args: Tuple Value for additional Params
423 cases = self.browse(cr, uid, ids)
424 cases[0].state # to fill the browse record cache
425 self._history(cr, uid, cases, _('Close'))
426 self.write(cr, uid, ids, {'state': 'done',
427 'date_closed': time.strftime('%Y-%m-%d %H:%M:%S'),
430 # We use the cache of cases to keep the old case state
432 self._action(cr, uid, cases, 'done')
435 def case_escalate(self, cr, uid, ids, *args):
436 """Escalates case to top level
437 @param self: The object pointer
438 @param cr: the current row, from the database cursor,
439 @param uid: the current user’s ID for security checks,
440 @param ids: List of case Ids
441 @param *args: Tuple Value for additional Params
443 cases = self.browse(cr, uid, ids)
445 data = {'active': True}
447 if case.section_id.parent_id:
448 data['section_id'] = case.section_id.parent_id.id
449 if case.section_id.parent_id.change_responsible:
450 if case.section_id.parent_id.user_id:
451 data['user_id'] = case.section_id.parent_id.user_id.id
453 raise osv.except_osv(_('Error !'), _('You can not escalate, You are already at the top level regarding your sales-team category.'))
454 self.write(cr, uid, [case.id], data)
455 cases = self.browse(cr, uid, ids)
456 self._history(cr, uid, cases, _('Escalate'))
457 self._action(cr, uid, cases, 'escalate')
460 def case_cancel(self, cr, uid, ids, *args):
462 @param self: The object pointer
463 @param cr: the current row, from the database cursor,
464 @param uid: the current user’s ID for security checks,
465 @param ids: List of case Ids
466 @param *args: Tuple Value for additional Params
468 cases = self.browse(cr, uid, ids)
469 cases[0].state # to fill the browse record cache
470 self._history(cr, uid, cases, _('Cancel'))
471 self.write(cr, uid, ids, {'state': 'cancel',
473 self._action(cr, uid, cases, 'cancel')
475 message = _("The case '%s' has been cancelled.") % (case.name,)
476 self.log(cr, uid, case.id, message)
479 def case_pending(self, cr, uid, ids, *args):
480 """Marks case as pending
481 @param self: The object pointer
482 @param cr: the current row, from the database cursor,
483 @param uid: the current user’s ID for security checks,
484 @param ids: List of case Ids
485 @param *args: Tuple Value for additional Params
487 cases = self.browse(cr, uid, ids)
488 cases[0].state # to fill the browse record cache
489 self._history(cr, uid, cases, _('Pending'))
490 self.write(cr, uid, ids, {'state': 'pending', 'active': True})
491 self._action(cr, uid, cases, 'pending')
494 def case_reset(self, cr, uid, ids, *args):
495 """Resets case as draft
496 @param self: The object pointer
497 @param cr: the current row, from the database cursor,
498 @param uid: the current user’s ID for security checks,
499 @param ids: List of case Ids
500 @param *args: Tuple Value for additional Params
503 if 'crm.phonecall' in args:
505 cases = self.browse(cr, uid, ids)
506 cases[0].state # to fill the browse record cache
507 self._history(cr, uid, cases, _('Draft'))
508 self.write(cr, uid, ids, {'state': state, 'active': True})
509 self._action(cr, uid, cases, state)
512 def remind_partner(self, cr, uid, ids, context=None, attach=False):
515 @param self: The object pointer
516 @param cr: the current row, from the database cursor,
517 @param uid: the current user’s ID for security checks,
518 @param ids: List of Remind Partner's IDs
519 @param context: A standard dictionary for contextual values
523 return self.remind_user(cr, uid, ids, context, attach,
526 def remind_user(self, cr, uid, ids, context=None, attach=False, destination=True):
528 @param self: The object pointer
529 @param cr: the current row, from the database cursor,
530 @param uid: the current user’s ID for security checks,
531 @param ids: List of case's IDs to remind
532 @param context: A standard dictionary for contextual values
534 for case in self.browse(cr, uid, ids, context=context):
535 if not destination and not case.email_from:
537 if not case.user_id.user_email:
540 if destination and case.section_id.user_id:
541 case_email = case.section_id.user_id.user_email
543 case_email = case.user_id.user_email
547 body = case.description or ""
549 body = case.message_ids[0].description or ""
551 src, dest = dest, case.email_from
552 if body and case.user_id.signature:
554 body += '\n\n%s' % (case.user_id.signature)
556 body = '\n\n%s' % (case.user_id.signature)
558 body = self.format_body(body)
560 attach_to_send = None
563 attach_ids = self.pool.get('ir.attachment').search(cr, uid, [('res_model', '=', self._name), ('res_id', '=', case.id)])
564 attach_to_send = self.pool.get('ir.attachment').read(cr, uid, attach_ids, ['datas_fname', 'datas'])
565 attach_to_send = map(lambda x: (x['datas_fname'], base64.decodestring(x['datas'])), attach_to_send)
568 subject = "Reminder: [%s] %s" % (str(case.id), case.name,)
574 reply_to=case.section_id.reply_to or '',
575 openobject_id=str(case.id),
576 attach=attach_to_send
578 self._history(cr, uid, [case], _('Send'), history=True, subject=subject, email=dest, details=body, email_from=src)
582 def _check(self, cr, uid, ids=False, context=None):
584 Function called by the scheduler to process cases for date actions
585 Only works on not done and cancelled cases
587 @param self: The object pointer
588 @param cr: the current row, from the database cursor,
589 @param uid: the current user’s ID for security checks,
590 @param context: A standard dictionary for contextual values
592 cr.execute('select * from crm_case \
593 where (date_action_last<%s or date_action_last is null) \
594 and (date_action_next<=%s or date_action_next is null) \
595 and state not in (\'cancel\',\'done\')',
596 (time.strftime("%Y-%m-%d %H:%M:%S"),
597 time.strftime('%Y-%m-%d %H:%M:%S')))
599 ids2 = map(lambda x: x[0], cr.fetchall() or [])
600 cases = self.browse(cr, uid, ids2, context=context)
601 return self._action(cr, uid, cases, False, context=context)
605 def format_body(self, body):
606 return self.pool.get('base.action.rule').format_body(body)
608 def format_mail(self, obj, body):
609 return self.pool.get('base.action.rule').format_mail(obj, body)
611 def message_followers(self, cr, uid, ids, context=None):
612 """ Get a list of emails of the people following this thread
615 for case in self.browse(cr, uid, ids, context=context):
618 l.append(case.email_cc)
619 if case.user_id and case.user_id.user_email:
620 l.append(case.user_id.user_email)
625 class crm_case_stage(osv.osv):
626 """ Stage of case """
628 _name = "crm.case.stage"
629 _description = "Stage of case"
635 def _get_type_value(self, cr, user, context):
636 return [('lead','Lead'),('opportunity','Opportunity')]
640 'name': fields.char('Stage Name', size=64, required=True, translate=True),
641 'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of case stages."),
642 'probability': fields.float('Probability (%)', required=True, help="This percentage depicts the default/average probability of the Case for this stage to be a success"),
643 'on_change': fields.boolean('Change Probability Automatically', \
644 help="Change Probability on next and previous stages."),
645 'requirements': fields.text('Requirements'),
646 'type': fields.selection(_get_type_value, 'Type', required=True),
650 def _find_stage_type(self, cr, uid, context=None):
651 """Finds type of stage according to object.
652 @param self: The object pointer
653 @param cr: the current row, from the database cursor,
654 @param uid: the current user’s ID for security checks,
655 @param context: A standard dictionary for contextual values
657 type = context and context.get('type', '') or ''
661 'sequence': lambda *args: 1,
662 'probability': lambda *args: 0.0,
663 'type': _find_stage_type,
669 class crm_case_section(osv.osv):
672 _name = "crm.case.section"
673 _description = "Sales Teams"
674 _order = "complete_name"
676 def get_full_name(self, cr, uid, ids, field_name, arg, context=None):
677 return dict(self.name_get(cr, uid, ids, context=context))
680 'name': fields.char('Sales Team', size=64, required=True, translate=True),
681 'complete_name': fields.function(get_full_name, type='char', size=256, readonly=True, store=True),
682 'code': fields.char('Code', size=8),
683 'active': fields.boolean('Active', help="If the active field is set to "\
684 "true, it will allow you to hide the sales team without removing it."),
685 'allow_unlink': fields.boolean('Allow Delete', help="Allows to delete non draft cases"),
686 'change_responsible': fields.boolean('Change Responsible', help="Thick this box if you want that on escalation, the responsible of this sale team automatically becomes responsible of the lead/opportunity escaladed"),
687 'user_id': fields.many2one('res.users', 'Responsible User'),
688 'member_ids':fields.many2many('res.users', 'sale_member_rel', 'section_id', 'member_id', 'Team Members'),
689 '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"),
690 'parent_id': fields.many2one('crm.case.section', 'Parent Team'),
691 'child_ids': fields.one2many('crm.case.section', 'parent_id', 'Child Teams'),
692 'resource_calendar_id': fields.many2one('resource.calendar', "Working Time"),
693 'note': fields.text('Description'),
694 'working_hours': fields.float('Working Hours', digits=(16,2 )),
695 'stage_ids': fields.many2many('crm.case.stage', 'section_stage_rel', 'section_id', 'stage_id', 'Stages'),
699 'active': lambda *a: 1,
700 'allow_unlink': lambda *a: 1,
704 ('code_uniq', 'unique (code)', 'The code of the sales team must be unique !')
707 def _check_recursion(self, cr, uid, ids, context=None):
710 Checks for recursion level for sales team
711 @param self: The object pointer
712 @param cr: the current row, from the database cursor,
713 @param uid: the current user’s ID for security checks,
714 @param ids: List of Sales team ids
719 cr.execute('select distinct parent_id from crm_case_section where id IN %s', (tuple(ids),))
720 ids = filter(None, map(lambda x: x[0], cr.fetchall()))
728 (_check_recursion, 'Error ! You cannot create recursive Sales team.', ['parent_id'])
731 def name_get(self, cr, uid, ids, context=None):
732 """Overrides orm name_get method
733 @param self: The object pointer
734 @param cr: the current row, from the database cursor,
735 @param uid: the current user’s ID for security checks,
736 @param ids: List of sales team ids
740 if not isinstance(ids, list) :
745 reads = self.read(cr, uid, ids, ['name', 'parent_id'], context)
748 name = record['name']
749 if record['parent_id']:
750 name = record['parent_id'][1] + ' / ' + name
751 res.append((record['id'], name))
757 class crm_case_categ(osv.osv):
758 """ Category of Case """
759 _name = "crm.case.categ"
760 _description = "Category of Case"
762 'name': fields.char('Name', size=64, required=True, translate=True),
763 'section_id': fields.many2one('crm.case.section', 'Sales Team'),
764 'object_id': fields.many2one('ir.model', 'Object Name'),
767 def _find_object_id(self, cr, uid, context=None):
768 """Finds id for case object
769 @param self: The object pointer
770 @param cr: the current row, from the database cursor,
771 @param uid: the current user’s ID for security checks,
772 @param context: A standard dictionary for contextual values
775 object_id = context and context.get('object_id', False) or False
776 ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', object_id)])
777 return ids and ids[0]
780 'object_id' : _find_object_id
786 class crm_case_stage(osv.osv):
787 _inherit = "crm.case.stage"
789 'section_ids':fields.many2many('crm.case.section', 'section_stage_rel', 'stage_id', 'section_id', 'Sections'),
795 class crm_case_resource_type(osv.osv):
796 """ Resource Type of case """
797 _name = "crm.case.resource.type"
798 _description = "Campaign"
801 'name': fields.char('Campaign Name', size=64, required=True, translate=True),
802 'section_id': fields.many2one('crm.case.section', 'Sales Team'),
804 crm_case_resource_type()
807 def _links_get(self, cr, uid, context=None):
808 """Gets links value for reference field
809 @param self: The object pointer
810 @param cr: the current row, from the database cursor,
811 @param uid: the current user’s ID for security checks,
812 @param context: A standard dictionary for contextual values
814 obj = self.pool.get('res.request.link')
815 ids = obj.search(cr, uid, [])
816 res = obj.read(cr, uid, ids, ['object', 'name'], context)
817 return [(r['object'], r['name']) for r in res]
819 class users(osv.osv):
820 _inherit = 'res.users'
821 _description = "Users"
823 'context_section_id': fields.many2one('crm.case.section', 'Sales Team'),
826 def create(self, cr, uid, vals, context=None):
827 res = super(users, self).create(cr, uid, vals, context=context)
828 section_obj=self.pool.get('crm.case.section')
830 if vals.get('context_section_id', False):
831 section_obj.write(cr, uid, [vals['context_section_id']], {'member_ids':[(4, res)]}, context)
836 class res_partner(osv.osv):
837 _inherit = 'res.partner'
839 'section_id': fields.many2one('crm.case.section', 'Sales Team'),