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.users').browse(cr, uid, uid, context).address_id.id
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 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
79 if not user.address_id:
81 return user.address_id.partner_id.id
83 def _get_default_email(self, cr, uid, context=None):
84 """Gives default email address for current user
85 :param context: if portal in context is false return false anyway
87 if not context.get('portal', False):
89 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
90 if not user.address_id:
92 return user.address_id.email
94 def _get_default_user(self, cr, uid, context=None):
95 """Gives current user id
96 :param context: if portal in context is false return false anyway
98 if context and context.get('portal', False):
102 def _get_section(self, cr, uid, context=None):
103 """Gives section id for current User
105 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
106 return user.context_section_id.id or False
108 def onchange_partner_address_id(self, cr, uid, ids, add, email=False):
109 """This function returns value of partner email based on Partner Address
110 @param ids: List of case IDs
111 @param add: Id of Partner's address
112 @email: Partner's email ID
115 return {'value': {'email_from': False}}
116 address = self.pool.get('res.partner.address').browse(cr, uid, add)
118 return {'value': {'email_from': address.email, 'phone': address.phone}}
120 return {'value': {'phone': address.phone}}
122 def onchange_partner_id(self, cr, uid, ids, part, email=False):
123 """This function returns value of partner address based on partner
124 @param ids: List of case IDs
125 @param part: Partner's id
126 @email: Partner's email ID
130 addr = self.pool.get('res.partner').address_get(cr, uid, [part], ['contact'])
131 data = {'partner_address_id': addr['contact']}
132 data.update(self.onchange_partner_address_id(cr, uid, ids, addr['contact'])['value'])
133 return {'value': data}
136 def case_open(self, cr, uid, ids, *args):
138 @param ids: List of case Ids
140 cases = self.browse(cr, uid, ids)
142 data = {'state': 'open', 'active': True}
144 data['user_id'] = uid
145 self.write(cr, uid, case.id, data)
148 self._action(cr, uid, cases, 'open')
151 def case_close(self, cr, uid, ids, *args):
153 @param ids: List of case Ids
155 cases = self.browse(cr, uid, ids)
156 cases[0].state # to fill the browse record cache
157 self.write(cr, uid, ids, {'state': 'done',
158 'date_closed': time.strftime('%Y-%m-%d %H:%M:%S'),
161 # We use the cache of cases to keep the old case state
163 self._action(cr, uid, cases, 'done')
166 def case_cancel(self, cr, uid, ids, *args):
168 @param ids: List of case Ids
170 cases = self.browse(cr, uid, ids)
171 cases[0].state # to fill the browse record cache
172 self.write(cr, uid, ids, {'state': 'cancel',
174 self._action(cr, uid, cases, 'cancel')
176 message = _("The case '%s' has been cancelled.") % (case.name,)
177 self.log(cr, uid, case.id, message)
180 def case_pending(self, cr, uid, ids, *args):
181 """Marks case as pending
182 @param ids: List of case Ids
184 cases = self.browse(cr, uid, ids)
185 cases[0].state # to fill the browse record cache
186 self.write(cr, uid, ids, {'state': 'pending', 'active': True})
187 self._action(cr, uid, cases, 'pending')
190 def case_reset(self, cr, uid, ids, *args):
191 """Resets case as draft
192 @param ids: List of case Ids
194 cases = self.browse(cr, uid, ids)
195 cases[0].state # to fill the browse record cache
196 self.write(cr, uid, ids, {'state': 'draft', 'active': True})
197 self._action(cr, uid, cases, 'draft')
200 def _action(self, cr, uid, cases, state_to, scrit=None, context=None):
203 context['state_to'] = state_to
204 rule_obj = self.pool.get('base.action.rule')
205 model_obj = self.pool.get('ir.model')
206 model_ids = model_obj.search(cr, uid, [('model','=',self._name)])
207 rule_ids = rule_obj.search(cr, uid, [('model_id','=',model_ids[0])])
208 return rule_obj._action(cr, uid, rule_ids, cases, scrit=scrit, context=context)
210 class crm_case(crm_base):
212 A simple python class to be used for common functions
213 Object that inherit from this class should inherit from mailgate.thread
214 And need a stage_id field
216 And object that inherit (orm inheritance) from a class the overwrite copy
219 def _find_lost_stage(self, cr, uid, type, section_id):
220 return self._find_percent_stage(cr, uid, 0.0, type, section_id)
222 def _find_won_stage(self, cr, uid, type, section_id):
223 return self._find_percent_stage(cr, uid, 100.0, type, section_id)
225 def _find_percent_stage(self, cr, uid, percent, type, section_id):
227 Return the first stage with a probability == percent
229 stage_pool = self.pool.get('crm.case.stage')
231 ids = stage_pool.search(cr, uid, [("probability", '=', percent), ("type", 'like', type), ("section_ids", 'in', [section_id])])
233 ids = stage_pool.search(cr, uid, [("probability", '=', percent), ("type", 'like', type)])
240 def _find_first_stage(self, cr, uid, type, section_id):
242 return the first stage that has a sequence number equal or higher than sequence
244 stage_pool = self.pool.get('crm.case.stage')
246 ids = stage_pool.search(cr, uid, [("sequence", '>', 0), ("type", 'like', type), ("section_ids", 'in', [section_id])])
248 ids = stage_pool.search(cr, uid, [("sequence", '>', 0), ("type", 'like', type)])
251 stages = stage_pool.browse(cr, uid, ids)
252 stage_min = stages[0]
254 if stage_min.sequence > stage.sequence:
260 def onchange_stage_id(self, cr, uid, ids, stage_id, context={}):
262 """ @param self: The object pointer
263 @param cr: the current row, from the database cursor,
264 @param uid: the current user’s ID for security checks,
265 @param ids: List of stage’s IDs
266 @stage_id: change state id on run time """
271 stage = self.pool.get('crm.case.stage').browse(cr, uid, stage_id, context)
273 if not stage.on_change:
275 return {'value':{'probability': stage.probability}}
279 def copy(self, cr, uid, id, default=None, context=None):
281 Overrides orm copy method.
282 @param self: the object pointer
283 @param cr: the current row, from the database cursor,
284 @param uid: the current user’s ID for security checks,
285 @param id: Id of mailgate thread
286 @param default: Dictionary of default values for copy.
287 @param context: A standard dictionary for contextual values
298 if hasattr(self, '_columns'):
299 if self._columns.get('date_closed'):
301 'date_closed': False,
303 if self._columns.get('date_open'):
307 return super(osv.osv, self).copy(cr, uid, id, default, context=context)
313 def _find_next_stage(self, cr, uid, stage_list, index, current_seq, stage_pool, context=None):
314 if index + 1 == len(stage_list):
316 next_stage_id = stage_list[index + 1]
317 next_stage = stage_pool.browse(cr, uid, next_stage_id, context=context)
320 next_seq = next_stage.sequence
324 if (abs(next_seq - current_seq)) >= 1:
327 return self._find_next_stage(cr, uid, stage_list, index + 1, current_seq, stage_pool)
329 def stage_change(self, cr, uid, ids, context=None, order='sequence'):
333 stage_pool = self.pool.get('crm.case.stage')
334 stage_type = context and context.get('stage_type','')
336 next_stage_id = False
338 for case in self.browse(cr, uid, ids, context=context):
342 if case.section_id.id :
343 domain = [('type', '=', stage_type),('section_ids', '=', case.section_id.id)]
345 domain = [('type', '=', stage_type)]
348 stages = stage_pool.search(cr, uid, domain, order=order)
349 current_seq = case.stage_id.sequence
351 if case.stage_id and case.stage_id.id in stages:
352 index = stages.index(case.stage_id.id)
354 next_stage = self._find_next_stage(cr, uid, stages, index, current_seq, stage_pool, context=context)
357 next_stage_id = next_stage.id
358 value.update({'stage_id': next_stage.id})
359 if next_stage.on_change:
360 value.update({'probability': next_stage.probability})
361 self.write(cr, uid, [case.id], value, context=context)
364 return next_stage_id #FIXME should return a list of all id
367 def stage_next(self, cr, uid, ids, context=None):
368 """This function computes next stage for case from its current stage
369 using available stage for that case type
370 @param self: The object pointer
371 @param cr: the current row, from the database cursor,
372 @param uid: the current user’s ID for security checks,
373 @param ids: List of case IDs
374 @param context: A standard dictionary for contextual values"""
376 return self.stage_change(cr, uid, ids, context=context, order='sequence')
378 def stage_previous(self, cr, uid, ids, context=None):
379 """This function computes previous stage for case from its current stage
380 using available stage for that case type
381 @param self: The object pointer
382 @param cr: the current row, from the database cursor,
383 @param uid: the current user’s ID for security checks,
384 @param ids: List of case IDs
385 @param context: A standard dictionary for contextual values"""
386 return self.stage_change(cr, uid, ids, context=context, order='sequence desc')
392 def _history(self, cr, uid, cases, keyword, history=False, subject=None, email=False, details=None, email_from=False, message_id=False, attach=[], context=None):
393 mailgate_pool = self.pool.get('mailgate.thread')
394 return mailgate_pool.history(cr, uid, cases, keyword, history=history,\
395 subject=subject, email=email, \
396 details=details, email_from=email_from,\
397 message_id=message_id, attach=attach, \
400 def case_open(self, cr, uid, ids, *args):
402 @param self: The object pointer
403 @param cr: the current row, from the database cursor,
404 @param uid: the current user’s ID for security checks,
405 @param ids: List of case Ids
406 @param *args: Tuple Value for additional Params
409 cases = self.browse(cr, uid, ids)
410 self._history(cr, uid, cases, _('Open'))
412 data = {'state': 'open', 'active': True}
414 data['user_id'] = uid
415 self.write(cr, uid, case.id, data)
416 self._action(cr, uid, cases, 'open')
419 def case_close(self, cr, uid, ids, *args):
421 @param self: The object pointer
422 @param cr: the current row, from the database cursor,
423 @param uid: the current user’s ID for security checks,
424 @param ids: List of case Ids
425 @param *args: Tuple Value for additional Params
427 cases = self.browse(cr, uid, ids)
428 cases[0].state # to fill the browse record cache
429 self._history(cr, uid, cases, _('Close'))
430 self.write(cr, uid, ids, {'state': 'done',
431 'date_closed': time.strftime('%Y-%m-%d %H:%M:%S'),
434 # We use the cache of cases to keep the old case state
436 self._action(cr, uid, cases, 'done')
439 def case_escalate(self, cr, uid, ids, *args):
440 """Escalates case to top level
441 @param self: The object pointer
442 @param cr: the current row, from the database cursor,
443 @param uid: the current user’s ID for security checks,
444 @param ids: List of case Ids
445 @param *args: Tuple Value for additional Params
447 cases = self.browse(cr, uid, ids)
449 data = {'active': True}
451 if case.section_id.parent_id:
452 data['section_id'] = case.section_id.parent_id.id
453 if case.section_id.parent_id.change_responsible:
454 if case.section_id.parent_id.user_id:
455 data['user_id'] = case.section_id.parent_id.user_id.id
457 raise osv.except_osv(_('Error !'), _('You can not escalate, You are already at the top level regarding your sales-team category.'))
458 self.write(cr, uid, [case.id], data)
459 cases = self.browse(cr, uid, ids)
460 self._history(cr, uid, cases, _('Escalate'))
461 self._action(cr, uid, cases, 'escalate')
464 def case_cancel(self, cr, uid, ids, *args):
466 @param self: The object pointer
467 @param cr: the current row, from the database cursor,
468 @param uid: the current user’s ID for security checks,
469 @param ids: List of case Ids
470 @param *args: Tuple Value for additional Params
472 cases = self.browse(cr, uid, ids)
473 cases[0].state # to fill the browse record cache
474 self._history(cr, uid, cases, _('Cancel'))
475 self.write(cr, uid, ids, {'state': 'cancel',
477 self._action(cr, uid, cases, 'cancel')
479 message = _("The case '%s' has been cancelled.") % (case.name,)
480 self.log(cr, uid, case.id, message)
483 def case_pending(self, cr, uid, ids, *args):
484 """Marks case as pending
485 @param self: The object pointer
486 @param cr: the current row, from the database cursor,
487 @param uid: the current user’s ID for security checks,
488 @param ids: List of case Ids
489 @param *args: Tuple Value for additional Params
491 cases = self.browse(cr, uid, ids)
492 cases[0].state # to fill the browse record cache
493 self._history(cr, uid, cases, _('Pending'))
494 self.write(cr, uid, ids, {'state': 'pending', 'active': True})
495 self._action(cr, uid, cases, 'pending')
498 def case_reset(self, cr, uid, ids, *args):
499 """Resets case as draft
500 @param self: The object pointer
501 @param cr: the current row, from the database cursor,
502 @param uid: the current user’s ID for security checks,
503 @param ids: List of case Ids
504 @param *args: Tuple Value for additional Params
507 if 'crm.phonecall' in args:
509 cases = self.browse(cr, uid, ids)
510 cases[0].state # to fill the browse record cache
511 self._history(cr, uid, cases, _('Draft'))
512 self.write(cr, uid, ids, {'state': state, 'active': True})
513 self._action(cr, uid, cases, state)
516 def remind_partner(self, cr, uid, ids, context=None, attach=False):
519 @param self: The object pointer
520 @param cr: the current row, from the database cursor,
521 @param uid: the current user’s ID for security checks,
522 @param ids: List of Remind Partner's IDs
523 @param context: A standard dictionary for contextual values
527 return self.remind_user(cr, uid, ids, context, attach,
530 def remind_user(self, cr, uid, ids, context=None, attach=False, destination=True):
532 @param self: The object pointer
533 @param cr: the current row, from the database cursor,
534 @param uid: the current user’s ID for security checks,
535 @param ids: List of case's IDs to remind
536 @param context: A standard dictionary for contextual values
538 for case in self.browse(cr, uid, ids, context=context):
539 if not destination and not case.email_from:
541 if not case.user_id.user_email:
544 if destination and case.section_id.user_id:
545 case_email = case.section_id.user_id.user_email
547 case_email = case.user_id.user_email
551 body = case.description or ""
553 body = case.message_ids[0].description or ""
555 src, dest = dest, case.email_from
556 if body and case.user_id.signature:
558 body += '\n\n%s' % (case.user_id.signature)
560 body = '\n\n%s' % (case.user_id.signature)
562 body = self.format_body(body)
564 attach_to_send = None
567 attach_ids = self.pool.get('ir.attachment').search(cr, uid, [('res_model', '=', self._name), ('res_id', '=', case.id)])
568 attach_to_send = self.pool.get('ir.attachment').read(cr, uid, attach_ids, ['datas_fname', 'datas'])
569 attach_to_send = map(lambda x: (x['datas_fname'], base64.decodestring(x['datas'])), attach_to_send)
572 subject = "Reminder: [%s] %s" % (str(case.id), case.name,)
578 reply_to=case.section_id.reply_to or '',
579 openobject_id=str(case.id),
580 attach=attach_to_send
582 self._history(cr, uid, [case], _('Send'), history=True, subject=subject, email=dest, details=body, email_from=src)
586 def _check(self, cr, uid, ids=False, context=None):
588 Function called by the scheduler to process cases for date actions
589 Only works on not done and cancelled cases
591 @param self: The object pointer
592 @param cr: the current row, from the database cursor,
593 @param uid: the current user’s ID for security checks,
594 @param context: A standard dictionary for contextual values
596 cr.execute('select * from crm_case \
597 where (date_action_last<%s or date_action_last is null) \
598 and (date_action_next<=%s or date_action_next is null) \
599 and state not in (\'cancel\',\'done\')',
600 (time.strftime("%Y-%m-%d %H:%M:%S"),
601 time.strftime('%Y-%m-%d %H:%M:%S')))
603 ids2 = map(lambda x: x[0], cr.fetchall() or [])
604 cases = self.browse(cr, uid, ids2, context=context)
605 return self._action(cr, uid, cases, False, context=context)
609 def format_body(self, body):
610 return self.pool.get('base.action.rule').format_body(body)
612 def format_mail(self, obj, body):
613 return self.pool.get('base.action.rule').format_mail(obj, body)
615 def message_followers(self, cr, uid, ids, context=None):
616 """ Get a list of emails of the people following this thread
619 for case in self.browse(cr, uid, ids, context=context):
622 l.append(case.email_cc)
623 if case.user_id and case.user_id.user_email:
624 l.append(case.user_id.user_email)
629 class crm_case_stage(osv.osv):
630 """ Stage of case """
632 _name = "crm.case.stage"
633 _description = "Stage of case"
639 def _get_type_value(self, cr, user, context):
640 return [('lead','Lead'),('opportunity','Opportunity')]
644 'name': fields.char('Stage Name', size=64, required=True, translate=True),
645 'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of case stages."),
646 'probability': fields.float('Probability (%)', required=True, help="This percentage depicts the default/average probability of the Case for this stage to be a success"),
647 'on_change': fields.boolean('Change Probability Automatically', \
648 help="Change Probability on next and previous stages."),
649 'requirements': fields.text('Requirements'),
650 'type': fields.selection(_get_type_value, 'Type', required=True),
654 def _find_stage_type(self, cr, uid, context=None):
655 """Finds type of stage according to object.
656 @param self: The object pointer
657 @param cr: the current row, from the database cursor,
658 @param uid: the current user’s ID for security checks,
659 @param context: A standard dictionary for contextual values
661 type = context and context.get('type', '') or ''
665 'sequence': lambda *args: 1,
666 'probability': lambda *args: 0.0,
667 'type': _find_stage_type,
673 class crm_case_section(osv.osv):
676 _name = "crm.case.section"
677 _description = "Sales Teams"
678 _order = "complete_name"
680 def get_full_name(self, cr, uid, ids, field_name, arg, context=None):
681 return dict(self.name_get(cr, uid, ids, context=context))
684 'name': fields.char('Sales Team', size=64, required=True, translate=True),
685 'complete_name': fields.function(get_full_name, method=True, type='char', size=256, readonly=True, store=True),
686 'code': fields.char('Code', size=8),
687 'active': fields.boolean('Active', help="If the active field is set to "\
688 "true, it will allow you to hide the sales team without removing it."),
689 'allow_unlink': fields.boolean('Allow Delete', help="Allows to delete non draft cases"),
690 '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"),
691 'user_id': fields.many2one('res.users', 'Responsible User'),
692 'member_ids':fields.many2many('res.users', 'sale_member_rel', 'section_id', 'member_id', 'Team Members'),
693 '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"),
694 'parent_id': fields.many2one('crm.case.section', 'Parent Team'),
695 'child_ids': fields.one2many('crm.case.section', 'parent_id', 'Child Teams'),
696 'resource_calendar_id': fields.many2one('resource.calendar', "Working Time"),
697 'note': fields.text('Description'),
698 'working_hours': fields.float('Working Hours', digits=(16,2 )),
699 'stage_ids': fields.many2many('crm.case.stage', 'section_stage_rel', 'section_id', 'stage_id', 'Stages'),
703 'active': lambda *a: 1,
704 'allow_unlink': lambda *a: 1,
708 ('code_uniq', 'unique (code)', 'The code of the sales team must be unique !')
711 def _check_recursion(self, cr, uid, ids, context=None):
714 Checks for recursion level for sales team
715 @param self: The object pointer
716 @param cr: the current row, from the database cursor,
717 @param uid: the current user’s ID for security checks,
718 @param ids: List of Sales team ids
723 cr.execute('select distinct parent_id from crm_case_section where id IN %s', (tuple(ids),))
724 ids = filter(None, map(lambda x: x[0], cr.fetchall()))
732 (_check_recursion, 'Error ! You cannot create recursive Sales team.', ['parent_id'])
735 def name_get(self, cr, uid, ids, context=None):
736 """Overrides orm name_get method
737 @param self: The object pointer
738 @param cr: the current row, from the database cursor,
739 @param uid: the current user’s ID for security checks,
740 @param ids: List of sales team ids
744 if not isinstance(ids, list) :
749 reads = self.read(cr, uid, ids, ['name', 'parent_id'], context)
752 name = record['name']
753 if record['parent_id']:
754 name = record['parent_id'][1] + ' / ' + name
755 res.append((record['id'], name))
761 class crm_case_categ(osv.osv):
762 """ Category of Case """
763 _name = "crm.case.categ"
764 _description = "Category of Case"
766 'name': fields.char('Name', size=64, required=True, translate=True),
767 'section_id': fields.many2one('crm.case.section', 'Sales Team'),
768 'object_id': fields.many2one('ir.model', 'Object Name'),
771 def _find_object_id(self, cr, uid, context=None):
772 """Finds id for case object
773 @param self: The object pointer
774 @param cr: the current row, from the database cursor,
775 @param uid: the current user’s ID for security checks,
776 @param context: A standard dictionary for contextual values
779 object_id = context and context.get('object_id', False) or False
780 ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', object_id)])
781 return ids and ids[0]
784 'object_id' : _find_object_id
790 class crm_case_stage(osv.osv):
791 _inherit = "crm.case.stage"
793 'section_ids':fields.many2many('crm.case.section', 'section_stage_rel', 'stage_id', 'section_id', 'Sections'),
799 class crm_case_resource_type(osv.osv):
800 """ Resource Type of case """
801 _name = "crm.case.resource.type"
802 _description = "Campaign"
805 'name': fields.char('Campaign Name', size=64, required=True, translate=True),
806 'section_id': fields.many2one('crm.case.section', 'Sales Team'),
808 crm_case_resource_type()
811 def _links_get(self, cr, uid, context=None):
812 """Gets links value for reference field
813 @param self: The object pointer
814 @param cr: the current row, from the database cursor,
815 @param uid: the current user’s ID for security checks,
816 @param context: A standard dictionary for contextual values
818 obj = self.pool.get('res.request.link')
819 ids = obj.search(cr, uid, [])
820 res = obj.read(cr, uid, ids, ['object', 'name'], context)
821 return [(r['object'], r['name']) for r in res]
823 class users(osv.osv):
824 _inherit = 'res.users'
825 _description = "Users"
827 'context_section_id': fields.many2one('crm.case.section', 'Sales Team'),
830 def create(self, cr, uid, vals, context=None):
831 res = super(users, self).create(cr, uid, vals, context=context)
832 section_obj=self.pool.get('crm.case.section')
834 if vals.get('context_section_id', False):
835 section_obj.write(cr, uid, [vals['context_section_id']], {'member_ids':[(4, res)]}, context)
840 class res_partner(osv.osv):
841 _inherit = 'res.partner'
843 'section_id': fields.many2one('crm.case.section', 'Sales Team'),