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_case(object):
48 """A simple python class to be used for common functions """
50 def _find_lost_stage(self, cr, uid, type, section_id):
51 return self._find_percent_stage(cr, uid, 0.0, type, section_id)
53 def _find_won_stage(self, cr, uid, type, section_id):
54 return self._find_percent_stage(cr, uid, 100.0, type, section_id)
56 def _find_percent_stage(self, cr, uid, percent, type, section_id):
58 Return the first stage with a probability == percent
60 stage_pool = self.pool.get('crm.case.stage')
62 ids = stage_pool.search(cr, uid, [("probability", '=', percent), ("type", 'like', type), ("section_ids", 'in', [section_id])])
64 ids = stage_pool.search(cr, uid, [("probability", '=', percent), ("type", 'like', type)])
71 def _find_first_stage(self, cr, uid, type, section_id):
73 return the first stage that has a sequence number equal or higher than sequence
75 stage_pool = self.pool.get('crm.case.stage')
77 ids = stage_pool.search(cr, uid, [("sequence", '>', 0), ("type", 'like', type), ("section_ids", 'in', [section_id])])
79 ids = stage_pool.search(cr, uid, [("sequence", '>', 0), ("type", 'like', type)])
82 stages = stage_pool.browse(cr, uid, ids)
85 if stage_min.sequence > stage.sequence:
91 def onchange_stage_id(self, cr, uid, ids, stage_id, context={}):
93 """ @param self: The object pointer
94 @param cr: the current row, from the database cursor,
95 @param uid: the current user’s ID for security checks,
96 @param ids: List of stage’s IDs
97 @stage_id: change state id on run time """
102 stage = self.pool.get('crm.case.stage').browse(cr, uid, stage_id, context)
104 if not stage.on_change:
106 return {'value':{'probability': stage.probability}}
108 def _get_default_partner_address(self, cr, uid, context=None):
110 """Gives id of default address for current user
111 @param self: The object pointer
112 @param cr: the current row, from the database cursor,
113 @param uid: the current user’s ID for security checks,
114 @param context: A standard dictionary for contextual values
118 if not context.get('portal', False):
120 return self.pool.get('res.users').browse(cr, uid, uid, context).address_id.id
122 def _get_default_partner(self, cr, uid, context=None):
123 """Gives id of partner for current user
124 @param self: The object pointer
125 @param cr: the current row, from the database cursor,
126 @param uid: the current user’s ID for security checks,
127 @param context: A standard dictionary for contextual values
131 if not context.get('portal', False):
133 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
134 if not user.address_id:
136 return user.address_id.partner_id.id
138 def copy(self, cr, uid, id, default=None, context=None):
140 Overrides orm copy method.
141 @param self: the object pointer
142 @param cr: the current row, from the database cursor,
143 @param uid: the current user’s ID for security checks,
144 @param id: Id of mailgate thread
145 @param default: Dictionary of default values for copy.
146 @param context: A standard dictionary for contextual values
156 if hasattr(self, '_columns'):
157 if self._columns.get('date_closed'):
159 'date_closed': False,
161 if self._columns.get('date_open'):
165 return super(osv.osv, self).copy(cr, uid, id, default, context=context)
167 def _get_default_email(self, cr, uid, context=None):
168 """Gives default email address for current user
169 @param self: The object pointer
170 @param cr: the current row, from the database cursor,
171 @param uid: the current user’s ID for security checks,
172 @param context: A standard dictionary for contextual values
174 if not context.get('portal', False):
176 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
177 if not user.address_id:
179 return user.address_id.email
181 def _get_default_user(self, cr, uid, context=None):
182 """Gives current user id
183 @param self: The object pointer
184 @param cr: the current row, from the database cursor,
185 @param uid: the current user’s ID for security checks,
186 @param context: A standard dictionary for contextual values
188 if context and context.get('portal', False):
192 def _get_section(self, cr, uid, context=None):
193 """Gives section id for current User
194 @param self: The object pointer
195 @param cr: the current row, from the database cursor,
196 @param uid: the current user’s ID for security checks,
197 @param context: A standard dictionary for contextual values
199 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
200 return user.context_section_id.id or False
202 def _find_next_stage(self, cr, uid, stage_list, index, current_seq, stage_pool, context=None):
203 if index + 1 == len(stage_list):
205 next_stage_id = stage_list[index + 1]
206 next_stage = stage_pool.browse(cr, uid, next_stage_id, context=context)
209 next_seq = next_stage.sequence
213 if (abs(next_seq - current_seq)) >= 1:
216 return self._find_next_stage(cr, uid, stage_list, index + 1, current_seq, stage_pool)
218 def stage_change(self, cr, uid, ids, context=None, order='sequence'):
221 stage_pool = self.pool.get('crm.case.stage')
222 stage_type = context and context.get('stage_type','')
224 next_stage_id = False
226 for case in self.browse(cr, uid, ids, context=context):
229 if case.section_id.id :
230 domain = [('type', '=', stage_type),('section_ids', '=', case.section_id.id)]
232 domain = [('type', '=', stage_type)]
235 stages = stage_pool.search(cr, uid, domain, order=order)
236 current_seq = case.stage_id.sequence
238 if case.stage_id and case.stage_id.id in stages:
239 index = stages.index(case.stage_id.id)
241 next_stage = self._find_next_stage(cr, uid, stages, index, current_seq, stage_pool, context=context)
244 next_stage_id = next_stage.id
245 value.update({'stage_id': next_stage.id})
246 if next_stage.on_change:
247 value.update({'probability': next_stage.probability})
248 self.write(cr, uid, [case.id], value, context=context)
251 return next_stage_id #FIXME should return a list of all id
254 def stage_next(self, cr, uid, ids, context=None):
255 """This function computes next stage for case from its current stage
256 using available stage for that case type
257 @param self: The object pointer
258 @param cr: the current row, from the database cursor,
259 @param uid: the current user’s ID for security checks,
260 @param ids: List of case IDs
261 @param context: A standard dictionary for contextual values"""
263 return self.stage_change(cr, uid, ids, context=context, order='sequence')
265 def stage_previous(self, cr, uid, ids, context=None):
266 """This function computes previous stage for case from its current stage
267 using available stage for that case type
268 @param self: The object pointer
269 @param cr: the current row, from the database cursor,
270 @param uid: the current user’s ID for security checks,
271 @param ids: List of case IDs
272 @param context: A standard dictionary for contextual values"""
273 return self.stage_change(cr, uid, ids, context=context, order='sequence desc')
275 def onchange_partner_id(self, cr, uid, ids, part, email=False):
276 """This function returns value of partner address based on partner
277 @param self: The object pointer
278 @param cr: the current row, from the database cursor,
279 @param uid: the current user’s ID for security checks,
280 @param ids: List of case IDs
281 @param part: Partner's id
282 @email: Partner's email ID
285 return {'value': {'partner_address_id': False,
289 addr = self.pool.get('res.partner').address_get(cr, uid, [part], ['contact'])
290 data = {'partner_address_id': addr['contact']}
291 data.update(self.onchange_partner_address_id(cr, uid, ids, addr['contact'])['value'])
292 return {'value': data}
294 def onchange_partner_address_id(self, cr, uid, ids, add, email=False):
295 """This function returns value of partner email based on Partner Address
296 @param self: The object pointer
297 @param cr: the current row, from the database cursor,
298 @param uid: the current user’s ID for security checks,
299 @param ids: List of case IDs
300 @param add: Id of Partner's address
301 @email: Partner's email ID
304 return {'value': {'email_from': False}}
305 address = self.pool.get('res.partner.address').browse(cr, uid, add)
307 return {'value': {'email_from': address.email, 'phone': address.phone}}
309 return {'value': {'phone': address.phone}}
311 def _history(self, cr, uid, cases, keyword, history=False, subject=None, email=False, details=None, email_from=False, message_id=False, attach=[], context=None):
312 mailgate_pool = self.pool.get('mailgate.thread')
313 return mailgate_pool.history(cr, uid, cases, keyword, history=history,\
314 subject=subject, email=email, \
315 details=details, email_from=email_from,\
316 message_id=message_id, attach=attach, \
319 def case_open(self, cr, uid, ids, *args):
321 @param self: The object pointer
322 @param cr: the current row, from the database cursor,
323 @param uid: the current user’s ID for security checks,
324 @param ids: List of case Ids
325 @param *args: Tuple Value for additional Params
328 cases = self.browse(cr, uid, ids)
329 self._history(cr, uid, cases, _('Open'))
331 data = {'state': 'open', 'active': True}
333 data['user_id'] = uid
334 self.write(cr, uid, case.id, data)
337 self._action(cr, uid, cases, 'open')
340 def case_close(self, cr, uid, ids, *args):
342 @param self: The object pointer
343 @param cr: the current row, from the database cursor,
344 @param uid: the current user’s ID for security checks,
345 @param ids: List of case Ids
346 @param *args: Tuple Value for additional Params
348 cases = self.browse(cr, uid, ids)
349 cases[0].state # to fill the browse record cache
350 self._history(cr, uid, cases, _('Close'))
351 self.write(cr, uid, ids, {'state': 'done',
352 'date_closed': time.strftime('%Y-%m-%d %H:%M:%S'),
355 # We use the cache of cases to keep the old case state
357 self._action(cr, uid, cases, 'done')
360 def case_escalate(self, cr, uid, ids, *args):
361 """Escalates case to top level
362 @param self: The object pointer
363 @param cr: the current row, from the database cursor,
364 @param uid: the current user’s ID for security checks,
365 @param ids: List of case Ids
366 @param *args: Tuple Value for additional Params
368 cases = self.browse(cr, uid, ids)
370 data = {'active': True}
372 if case.section_id.parent_id:
373 data['section_id'] = case.section_id.parent_id.id
374 if case.section_id.parent_id.change_responsible:
375 if case.section_id.parent_id.user_id:
376 data['user_id'] = case.section_id.parent_id.user_id.id
378 raise osv.except_osv(_('Error !'), _('You can not escalate, You are already at the top level regarding your sales-team category.'))
379 self.write(cr, uid, [case.id], data)
380 cases = self.browse(cr, uid, ids)
381 self._history(cr, uid, cases, _('Escalate'))
382 self._action(cr, uid, cases, 'escalate')
385 def case_cancel(self, cr, uid, ids, *args):
387 @param self: The object pointer
388 @param cr: the current row, from the database cursor,
389 @param uid: the current user’s ID for security checks,
390 @param ids: List of case Ids
391 @param *args: Tuple Value for additional Params
393 cases = self.browse(cr, uid, ids)
394 cases[0].state # to fill the browse record cache
395 self._history(cr, uid, cases, _('Cancel'))
396 self.write(cr, uid, ids, {'state': 'cancel',
398 self._action(cr, uid, cases, 'cancel')
400 message = _("The case '%s' has been cancelled.") % (case.name,)
401 self.log(cr, uid, case.id, message)
404 def case_pending(self, cr, uid, ids, *args):
405 """Marks case as pending
406 @param self: The object pointer
407 @param cr: the current row, from the database cursor,
408 @param uid: the current user’s ID for security checks,
409 @param ids: List of case Ids
410 @param *args: Tuple Value for additional Params
412 cases = self.browse(cr, uid, ids)
413 cases[0].state # to fill the browse record cache
414 self._history(cr, uid, cases, _('Pending'))
415 self.write(cr, uid, ids, {'state': 'pending', 'active': True})
416 self._action(cr, uid, cases, 'pending')
419 def case_reset(self, cr, uid, ids, *args):
420 """Resets case as draft
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, _('Draft'))
430 self.write(cr, uid, ids, {'state': 'draft', 'active': True})
431 self._action(cr, uid, cases, 'draft')
434 def remind_partner(self, cr, uid, ids, context=None, attach=False):
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 Remind Partner's IDs
441 @param context: A standard dictionary for contextual values
444 return self.remind_user(cr, uid, ids, context, attach,
447 def remind_user(self, cr, uid, ids, context=None, attach=False, destination=True):
449 @param self: The object pointer
450 @param cr: the current row, from the database cursor,
451 @param uid: the current user’s ID for security checks,
452 @param ids: List of Remind user's IDs
453 @param context: A standard dictionary for contextual values
456 email_message_obj = self.pool.get('email.message')
457 for case in self.browse(cr, uid, ids, context=context):
458 if not case.section_id.reply_to:
459 raise osv.except_osv(_('Error!'), ("Reply To is not specified in the sales team"))
460 if not case.email_from:
461 raise osv.except_osv(_('Error!'), ("Partner Email is not specified in Case"))
462 if case.section_id.reply_to and case.email_from:
463 src = case.email_from
464 dest = case.section_id.reply_to
465 body = case.description or ""
467 body = case.message_ids[0].description or ""
469 src, dest = dest, src
470 if body and case.user_id.signature:
472 body += '\n\n%s' % (case.user_id.signature)
474 body = '\n\n%s' % (case.user_id.signature)
476 body = self.format_body(body)
478 attach_to_send = None
481 attach_ids = self.pool.get('ir.attachment').search(cr, uid, [('res_model', '=', self._name), ('res_id', '=', case.id)])
482 attach_to_send = self.pool.get('ir.attachment').read(cr, uid, attach_ids, ['datas_fname','datas'])
483 attach_to_send = map(lambda x: (x['datas_fname'], base64.decodestring(x['datas'])), attach_to_send)
486 subject = "Reminder: [%s] %s" % (str(case.id), case.name, )
487 email_message_obj.email_send(cr, uid,
493 reply_to=case.section_id.reply_to,
494 openobject_id=str(case.id),
495 attach=attach_to_send
497 self._history(cr, uid, [case], _('Send'), history=True, subject=subject, email=dest, details=body, email_from=src)
500 def _check(self, cr, uid, ids=False, context=None):
502 Function called by the scheduler to process cases for date actions
503 Only works on not done and cancelled cases
505 @param self: The object pointer
506 @param cr: the current row, from the database cursor,
507 @param uid: the current user’s ID for security checks,
508 @param context: A standard dictionary for contextual values
510 cr.execute('select * from crm_case \
511 where (date_action_last<%s or date_action_last is null) \
512 and (date_action_next<=%s or date_action_next is null) \
513 and state not in (\'cancel\',\'done\')',
514 (time.strftime("%Y-%m-%d %H:%M:%S"),
515 time.strftime('%Y-%m-%d %H:%M:%S')))
517 ids2 = map(lambda x: x[0], cr.fetchall() or [])
518 cases = self.browse(cr, uid, ids2, context=context)
519 return self._action(cr, uid, cases, False, context=context)
521 def _action(self, cr, uid, cases, state_to, scrit=None, context=None):
524 context['state_to'] = state_to
525 rule_obj = self.pool.get('base.action.rule')
526 model_obj = self.pool.get('ir.model')
527 model_ids = model_obj.search(cr, uid, [('model','=',self._name)])
528 rule_ids = rule_obj.search(cr, uid, [('model_id','=',model_ids[0])])
529 return rule_obj._action(cr, uid, rule_ids, cases, scrit=scrit, context=context)
531 def format_body(self, body):
532 return self.pool.get('base.action.rule').format_body(body)
534 def format_mail(self, obj, body):
535 return self.pool.get('base.action.rule').format_mail(obj, body)
537 def message_followers(self, cr, uid, ids, context=None):
538 """ Get a list of emails of the people following this thread
541 for case in self.browse(cr, uid, ids, context=context):
544 l.append(case.email_cc)
545 if case.user_id and case.user_id.user_email:
546 l.append(case.user_id.user_email)
551 class crm_case_stage(osv.osv):
552 """ Stage of case """
554 _name = "crm.case.stage"
555 _description = "Stage of case"
561 def _get_type_value(self, cr, user, context):
562 return [('lead','Lead'),('opportunity','Opportunity')]
566 'name': fields.char('Stage Name', size=64, required=True, translate=True),
567 'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of case stages."),
568 'probability': fields.float('Probability (%)', required=True, help="This percentage depicts the default/average probability of the Case for this stage to be a success"),
569 'on_change': fields.boolean('Change Probability Automatically', \
570 help="Change Probability on next and previous stages."),
571 'requirements': fields.text('Requirements'),
572 'type': fields.selection(_get_type_value, 'Type'),
576 def _find_stage_type(self, cr, uid, context=None):
577 """Finds type of stage according to object.
578 @param self: The object pointer
579 @param cr: the current row, from the database cursor,
580 @param uid: the current user’s ID for security checks,
581 @param context: A standard dictionary for contextual values
583 type = context and context.get('type', '') or ''
587 'sequence': lambda *args: 1,
588 'probability': lambda *args: 0.0,
589 'type': _find_stage_type,
595 class crm_case_section(osv.osv):
598 _name = "crm.case.section"
599 _description = "Sales Teams"
600 _order = "complete_name"
602 def get_full_name(self, cr, uid, ids, field_name, arg, context=None):
603 return dict(self.name_get(cr, uid, ids, context=context))
606 'name': fields.char('Sales Team', size=64, required=True, translate=True),
607 'complete_name': fields.function(get_full_name, method=True, type='char', size=256, readonly=True, store=True),
608 'code': fields.char('Code', size=8),
609 'active': fields.boolean('Active', help="If the active field is set to "\
610 "true, it will allow you to hide the sales team without removing it."),
611 'allow_unlink': fields.boolean('Allow Delete', help="Allows to delete non draft cases"),
612 '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"),
613 'user_id': fields.many2one('res.users', 'Responsible User'),
614 'member_ids':fields.many2many('res.users', 'sale_member_rel', 'section_id', 'member_id', 'Team Members'),
615 '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"),
616 'parent_id': fields.many2one('crm.case.section', 'Parent Team'),
617 'child_ids': fields.one2many('crm.case.section', 'parent_id', 'Child Teams'),
618 'resource_calendar_id': fields.many2one('resource.calendar', "Working Time"),
619 'note': fields.text('Description'),
620 'working_hours': fields.float('Working Hours', digits=(16,2 )),
621 'stage_ids': fields.many2many('crm.case.stage', 'section_stage_rel', 'section_id', 'stage_id', 'Stages'),
625 'active': lambda *a: 1,
626 'allow_unlink': lambda *a: 1,
630 ('code_uniq', 'unique (code)', 'The code of the sales team must be unique !')
633 def _check_recursion(self, cr, uid, ids, context=None):
636 Checks for recursion level for sales team
637 @param self: The object pointer
638 @param cr: the current row, from the database cursor,
639 @param uid: the current user’s ID for security checks,
640 @param ids: List of Sales team ids
645 cr.execute('select distinct parent_id from crm_case_section where id IN %s', (tuple(ids),))
646 ids = filter(None, map(lambda x: x[0], cr.fetchall()))
654 (_check_recursion, 'Error ! You cannot create recursive Sales team.', ['parent_id'])
657 def name_get(self, cr, uid, ids, context=None):
658 """Overrides orm name_get method
659 @param self: The object pointer
660 @param cr: the current row, from the database cursor,
661 @param uid: the current user’s ID for security checks,
662 @param ids: List of sales team ids
670 reads = self.read(cr, uid, ids, ['name', 'parent_id'], context)
673 name = record['name']
674 if record['parent_id']:
675 name = record['parent_id'][1] + ' / ' + name
676 res.append((record['id'], name))
682 class crm_case_categ(osv.osv):
683 """ Category of Case """
684 _name = "crm.case.categ"
685 _description = "Category of Case"
687 'name': fields.char('Name', size=64, required=True, translate=True),
688 'section_id': fields.many2one('crm.case.section', 'Sales Team'),
689 'object_id': fields.many2one('ir.model', 'Object Name'),
692 def _find_object_id(self, cr, uid, context=None):
693 """Finds id for case object
694 @param self: The object pointer
695 @param cr: the current row, from the database cursor,
696 @param uid: the current user’s ID for security checks,
697 @param context: A standard dictionary for contextual values
700 object_id = context and context.get('object_id', False) or False
701 ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', object_id)])
702 return ids and ids[0]
705 'object_id' : _find_object_id
711 class crm_case_stage(osv.osv):
712 _inherit = "crm.case.stage"
714 'section_ids':fields.many2many('crm.case.section', 'section_stage_rel', 'stage_id', 'section_id', 'Sections'),
720 class crm_case_resource_type(osv.osv):
721 """ Resource Type of case """
722 _name = "crm.case.resource.type"
723 _description = "Campaign"
726 'name': fields.char('Campaign Name', size=64, required=True, translate=True),
727 'section_id': fields.many2one('crm.case.section', 'Sales Team'),
729 crm_case_resource_type()
732 def _links_get(self, cr, uid, context=None):
733 """Gets links value for reference field
734 @param self: The object pointer
735 @param cr: the current row, from the database cursor,
736 @param uid: the current user’s ID for security checks,
737 @param context: A standard dictionary for contextual values
739 obj = self.pool.get('res.request.link')
740 ids = obj.search(cr, uid, [])
741 res = obj.read(cr, uid, ids, ['object', 'name'], context)
742 return [(r['object'], r['name']) for r in res]
744 class users(osv.osv):
745 _inherit = 'res.users'
746 _description = "Users"
748 'context_section_id': fields.many2one('crm.case.section', 'Sales Team'),
751 def create(self, cr, uid, vals, context=None):
752 res = super(users, self).create(cr, uid, vals, context=context)
753 section_obj=self.pool.get('crm.case.section')
755 if vals.get('context_section_id', False):
756 section_obj.write(cr, uid, [vals['context_section_id']], {'member_ids':[(4, res)]}, context)
761 class res_partner(osv.osv):
762 _inherit = 'res.partner'
764 'section_id': fields.many2one('crm.case.section', 'Sales Team'),