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 _get_default_partner_address(self, cr, uid, context=None):
51 """Gives id of default address for current user
52 @param self: The object pointer
53 @param cr: the current row, from the database cursor,
54 @param uid: the current user’s ID for security checks,
55 @param context: A standard dictionary for contextual values
59 if not context.get('portal', False):
61 return self.pool.get('res.users').browse(cr, uid, uid, context).address_id.id
63 def _get_default_partner(self, cr, uid, context=None):
64 """Gives id of partner for current user
65 @param self: The object pointer
66 @param cr: the current row, from the database cursor,
67 @param uid: the current user’s ID for security checks,
68 @param context: A standard dictionary for contextual values
72 if not context.get('portal', False):
74 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
75 if not user.address_id:
77 return user.address_id.partner_id.id
79 def copy(self, cr, uid, id, default=None, context=None):
81 Overrides orm copy method.
82 @param self: the object pointer
83 @param cr: the current row, from the database cursor,
84 @param uid: the current user’s ID for security checks,
85 @param id: Id of mailgate thread
86 @param default: Dictionary of default values for copy.
87 @param context: A standard dictionary for contextual values
97 if hasattr(self, '_columns'):
98 if self._columns.get('date_closed'):
100 'date_closed': False,
102 if self._columns.get('date_open'):
106 return super(osv.osv, self).copy(cr, uid, id, default, context=context)
108 def _get_default_email(self, cr, uid, context=None):
109 """Gives default email address for current user
110 @param self: The object pointer
111 @param cr: the current row, from the database cursor,
112 @param uid: the current user’s ID for security checks,
113 @param context: A standard dictionary for contextual values
115 if not context.get('portal', False):
117 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
118 if not user.address_id:
120 return user.address_id.email
122 def _get_default_user(self, cr, uid, context=None):
123 """Gives current user id
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
129 if context and context.get('portal', False):
133 def _get_section(self, cr, uid, context=None):
134 """Gives section id for current User
135 @param self: The object pointer
136 @param cr: the current row, from the database cursor,
137 @param uid: the current user’s ID for security checks,
138 @param context: A standard dictionary for contextual values
140 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
141 return user.context_section_id.id or False
143 def _find_next_stage(self, cr, uid, stage_list, index, current_seq, stage_pool, context=None):
144 if index + 1 == len(stage_list):
146 next_stage_id = stage_list[index + 1]
147 next_stage = stage_pool.browse(cr, uid, next_stage_id, context=context)
151 next_seq = next_stage.sequence
152 if (abs(next_seq - current_seq)) >= 1:
155 return self._find_next_stage(cr, uid, stage_list, index + 1, current_seq, stage_pool)
157 def stage_change(self, cr, uid, ids, context=None, order='sequence'):
160 stage_pool = self.pool.get('crm.case.stage')
161 stage_type = context and context.get('stage_type','')
163 next_stage_id = False
164 for case in self.browse(cr, uid, ids, context=context):
168 domain = [('type', '=', stage_type),('section_ids', '=', case.section_id.id)]
169 if case.section_id and case.section_id.stage_ids:
170 domain.append(('id', 'in', map(lambda x: x.id, case.section_id.stage_ids)))
172 stages = stage_pool.search(cr, uid, domain, order=order)
173 current_seq = case.stage_id.sequence
175 if case.stage_id and case.stage_id.id in stages:
176 index = stages.index(case.stage_id.id)
178 next_stage = self._find_next_stage(cr, uid, stages, index, current_seq, stage_pool, context=context)
180 next_stage_id = next_stage.id
181 data = {'stage_id': next_stage.id}
182 if next_stage.on_change:
183 data.update({'probability': next_stage.probability})
184 self.write(cr, uid, [case.id], data, context=context)
189 def stage_next(self, cr, uid, ids, context=None):
190 """This function computes next stage for case from its current stage
191 using available stage for that case type
192 @param self: The object pointer
193 @param cr: the current row, from the database cursor,
194 @param uid: the current user’s ID for security checks,
195 @param ids: List of case IDs
196 @param context: A standard dictionary for contextual values"""
199 return self.stage_change(cr, uid, ids, context=context, order='sequence')
201 def stage_previous(self, cr, uid, ids, context=None):
202 """This function computes previous stage for case from its current stage
203 using available stage for that case type
204 @param self: The object pointer
205 @param cr: the current row, from the database cursor,
206 @param uid: the current user’s ID for security checks,
207 @param ids: List of case IDs
208 @param context: A standard dictionary for contextual values"""
209 return self.stage_change(cr, uid, ids, context=context, order='sequence desc')
211 def onchange_partner_id(self, cr, uid, ids, part, email=False):
212 """This function returns value of partner address based on partner
213 @param self: The object pointer
214 @param cr: the current row, from the database cursor,
215 @param uid: the current user’s ID for security checks,
216 @param ids: List of case IDs
217 @param part: Partner's id
218 @email: Partner's email ID
221 return {'value': {'partner_address_id': False,
225 addr = self.pool.get('res.partner').address_get(cr, uid, [part], ['contact'])
226 data = {'partner_address_id': addr['contact']}
227 data.update(self.onchange_partner_address_id(cr, uid, ids, addr['contact'])['value'])
228 return {'value': data}
230 def onchange_partner_address_id(self, cr, uid, ids, add, email=False):
231 """This function returns value of partner email based on Partner Address
232 @param self: The object pointer
233 @param cr: the current row, from the database cursor,
234 @param uid: the current user’s ID for security checks,
235 @param ids: List of case IDs
236 @param add: Id of Partner's address
237 @email: Partner's email ID
240 return {'value': {'email_from': False}}
241 address = self.pool.get('res.partner.address').browse(cr, uid, add)
242 return {'value': {'email_from': address.email, 'phone': address.phone}}
244 def _history(self, cr, uid, cases, keyword, history=False, subject=None, email=False, details=None, email_from=False, message_id=False, attach=[], context=None):
245 mailgate_pool = self.pool.get('mailgate.thread')
246 return mailgate_pool.history(cr, uid, cases, keyword, history=history,\
247 subject=subject, email=email, \
248 details=details, email_from=email_from,\
249 message_id=message_id, attach=attach, \
252 def case_open(self, cr, uid, ids, *args):
254 @param self: The object pointer
255 @param cr: the current row, from the database cursor,
256 @param uid: the current user’s ID for security checks,
257 @param ids: List of case Ids
258 @param *args: Tuple Value for additional Params
260 cases = self.browse(cr, uid, ids)
261 self._history(cr, uid, cases, _('Open'))
263 data = {'state': 'open', 'active': True}
265 data['user_id'] = uid
266 self.write(cr, uid, case.id, data)
267 self._action(cr, uid, cases, 'open')
270 def case_close(self, cr, uid, ids, *args):
272 @param self: The object pointer
273 @param cr: the current row, from the database cursor,
274 @param uid: the current user’s ID for security checks,
275 @param ids: List of case Ids
276 @param *args: Tuple Value for additional Params
278 cases = self.browse(cr, uid, ids)
279 cases[0].state # to fill the browse record cache
280 self._history(cr, uid, cases, _('Close'))
281 self.write(cr, uid, ids, {'state': 'done',
282 'date_closed': time.strftime('%Y-%m-%d %H:%M:%S'),
285 # We use the cache of cases to keep the old case state
287 self._action(cr, uid, cases, 'done')
290 def case_escalate(self, cr, uid, ids, *args):
291 """Escalates case to top level
292 @param self: The object pointer
293 @param cr: the current row, from the database cursor,
294 @param uid: the current user’s ID for security checks,
295 @param ids: List of case Ids
296 @param *args: Tuple Value for additional Params
298 cases = self.browse(cr, uid, ids)
300 data = {'active': True}
302 if case.section_id.parent_id:
303 data['section_id'] = case.section_id.parent_id.id
304 if case.section_id.parent_id.change_responsible:
305 if case.section_id.parent_id.user_id:
306 data['user_id'] = case.section_id.parent_id.user_id.id
308 raise osv.except_osv(_('Error !'), _('You can not escalate, You are already at the top level regarding your sales-team category.'))
309 self.write(cr, uid, [case.id], data)
310 cases = self.browse(cr, uid, ids)
311 self._history(cr, uid, cases, _('Escalate'))
312 self._action(cr, uid, cases, 'escalate')
315 def case_cancel(self, cr, uid, ids, *args):
317 @param self: The object pointer
318 @param cr: the current row, from the database cursor,
319 @param uid: the current user’s ID for security checks,
320 @param ids: List of case Ids
321 @param *args: Tuple Value for additional Params
323 cases = self.browse(cr, uid, ids)
324 cases[0].state # to fill the browse record cache
325 self._history(cr, uid, cases, _('Cancel'))
326 self.write(cr, uid, ids, {'state': 'cancel',
328 self._action(cr, uid, cases, 'cancel')
330 message = _("The case '%s' has been cancelled.") % (case.name,)
331 self.log(cr, uid, case.id, message)
334 def case_pending(self, cr, uid, ids, *args):
335 """Marks case as pending
336 @param self: The object pointer
337 @param cr: the current row, from the database cursor,
338 @param uid: the current user’s ID for security checks,
339 @param ids: List of case Ids
340 @param *args: Tuple Value for additional Params
342 cases = self.browse(cr, uid, ids)
343 cases[0].state # to fill the browse record cache
344 self._history(cr, uid, cases, _('Pending'))
345 self.write(cr, uid, ids, {'state': 'pending', 'active': True})
346 self._action(cr, uid, cases, 'pending')
349 def case_reset(self, cr, uid, ids, *args):
350 """Resets case as draft
351 @param self: The object pointer
352 @param cr: the current row, from the database cursor,
353 @param uid: the current user’s ID for security checks,
354 @param ids: List of case Ids
355 @param *args: Tuple Value for additional Params
357 cases = self.browse(cr, uid, ids)
358 cases[0].state # to fill the browse record cache
359 self._history(cr, uid, cases, _('Draft'))
360 self.write(cr, uid, ids, {'state': 'draft', 'active': True})
361 self._action(cr, uid, cases, 'draft')
364 def remind_partner(self, cr, uid, ids, context=None, attach=False):
367 @param self: The object pointer
368 @param cr: the current row, from the database cursor,
369 @param uid: the current user’s ID for security checks,
370 @param ids: List of Remind Partner's IDs
371 @param context: A standard dictionary for contextual values
374 return self.remind_user(cr, uid, ids, context, attach,
377 def remind_user(self, cr, uid, ids, context=None, attach=False, destination=True):
379 @param self: The object pointer
380 @param cr: the current row, from the database cursor,
381 @param uid: the current user’s ID for security checks,
382 @param ids: List of Remind user's IDs
383 @param context: A standard dictionary for contextual values
386 for case in self.browse(cr, uid, ids, context=context):
387 if not case.section_id.reply_to:
388 raise osv.except_osv(_('Error!'), ("Reply To is not specified in the sales team"))
389 if not case.email_from:
390 raise osv.except_osv(_('Error!'), ("Partner Email is not specified in Case"))
391 if case.section_id.reply_to and case.email_from:
392 src = case.email_from
393 dest = case.section_id.reply_to
394 body = case.description or ""
396 body = case.message_ids[0].description or ""
398 src, dest = dest, src
399 if body and case.user_id.signature:
401 body += '\n\n%s' % (case.user_id.signature)
403 body = '\n\n%s' % (case.user_id.signature)
405 body = self.format_body(body)
407 attach_to_send = None
410 attach_ids = self.pool.get('ir.attachment').search(cr, uid, [('res_model', '=', self._name), ('res_id', '=', case.id)])
411 attach_to_send = self.pool.get('ir.attachment').read(cr, uid, attach_ids, ['datas_fname','datas'])
412 attach_to_send = map(lambda x: (x['datas_fname'], base64.decodestring(x['datas'])), attach_to_send)
415 subject = "Reminder: [%s] %s" % (str(case.id), case.name, )
421 reply_to=case.section_id.reply_to,
422 openobject_id=str(case.id),
423 attach=attach_to_send
425 self._history(cr, uid, [case], _('Send'), history=True, subject=subject, email=dest, details=body, email_from=src)
428 def _check(self, cr, uid, ids=False, context=None):
430 Function called by the scheduler to process cases for date actions
431 Only works on not done and cancelled cases
433 @param self: The object pointer
434 @param cr: the current row, from the database cursor,
435 @param uid: the current user’s ID for security checks,
436 @param context: A standard dictionary for contextual values
438 cr.execute('select * from crm_case \
439 where (date_action_last<%s or date_action_last is null) \
440 and (date_action_next<=%s or date_action_next is null) \
441 and state not in (\'cancel\',\'done\')',
442 (time.strftime("%Y-%m-%d %H:%M:%S"),
443 time.strftime('%Y-%m-%d %H:%M:%S')))
445 ids2 = map(lambda x: x[0], cr.fetchall() or [])
446 cases = self.browse(cr, uid, ids2, context=context)
447 return self._action(cr, uid, cases, False, context=context)
449 def _action(self, cr, uid, cases, state_to, scrit=None, context=None):
452 context['state_to'] = state_to
453 rule_obj = self.pool.get('base.action.rule')
454 model_obj = self.pool.get('ir.model')
455 model_ids = model_obj.search(cr, uid, [('model','=',self._name)])
456 rule_ids = rule_obj.search(cr, uid, [('model_id','=',model_ids[0])])
457 return rule_obj._action(cr, uid, rule_ids, cases, scrit=scrit, context=context)
459 def format_body(self, body):
460 return self.pool.get('base.action.rule').format_body(body)
462 def format_mail(self, obj, body):
463 return self.pool.get('base.action.rule').format_mail(obj, body)
465 def message_followers(self, cr, uid, ids, context=None):
466 """ Get a list of emails of the people following this thread
469 for case in self.browse(cr, uid, ids, context=context):
472 l.append(case.email_cc)
473 if case.user_id and case.user_id.user_email:
474 l.append(case.user_id.user_email)
479 class crm_case_stage(osv.osv):
480 """ Stage of case """
482 _name = "crm.case.stage"
483 _description = "Stage of case"
488 'name': fields.char('Stage Name', size=64, required=True, translate=True),
489 'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of case stages."),
490 'probability': fields.float('Probability (%)', required=True, help="This percentage depicts the default/average probability of the Case for this stage to be a success"),
491 'on_change': fields.boolean('Change Probability Automatically', \
492 help="Change Probability on next and previous stages."),
493 'requirements': fields.text('Requirements'),
494 'type': fields.selection([('lead','Lead'),('opportunity','Opportunity'),('claim','Claim'), ('fundraising','Fundraising')], 'Type'),
497 def _find_stage_type(self, cr, uid, context=None):
498 """Finds type of stage according to object.
499 @param self: The object pointer
500 @param cr: the current row, from the database cursor,
501 @param uid: the current user’s ID for security checks,
502 @param context: A standard dictionary for contextual values
504 type = context and context.get('type', '') or ''
508 'sequence': lambda *args: 1,
509 'probability': lambda *args: 0.0,
510 'type': _find_stage_type,
516 class crm_case_section(osv.osv):
519 _name = "crm.case.section"
520 _description = "Sales Teams"
521 _order = "complete_name"
523 def get_full_name(self, cr, uid, ids, field_name, arg, context=None):
524 return dict(self.name_get(cr, uid, ids, context=context))
527 'name': fields.char('Sales Team', size=64, required=True, translate=True),
528 'complete_name': fields.function(get_full_name, method=True, type='char', size=256, readonly=True, store=True),
529 'code': fields.char('Code', size=8),
530 'active': fields.boolean('Active', help="If the active field is set to "\
531 "true, it will allow you to hide the sales team without removing it."),
532 'allow_unlink': fields.boolean('Allow Delete', help="Allows to delete non draft cases"),
533 '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"),
534 'user_id': fields.many2one('res.users', 'Responsible User'),
535 'member_ids':fields.many2many('res.users', 'sale_member_rel', 'section_id', 'member_id', 'Team Members'),
536 '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"),
537 'parent_id': fields.many2one('crm.case.section', 'Parent Team'),
538 'child_ids': fields.one2many('crm.case.section', 'parent_id', 'Child Teams'),
539 'resource_calendar_id': fields.many2one('resource.calendar', "Resource's Calendar"),
540 'note': fields.text('Description'),
541 'working_hours': fields.float('Working Hours', digits=(16,2 )),
542 'stage_ids': fields.many2many('crm.case.stage', 'section_stage_rel', 'section_id', 'stage_id', 'Stages'),
546 'active': lambda *a: 1,
547 'allow_unlink': lambda *a: 1,
551 ('code_uniq', 'unique (code)', 'The code of the sales team must be unique !')
554 def _check_recursion(self, cr, uid, ids, context=None):
557 Checks for recursion level for sales team
558 @param self: The object pointer
559 @param cr: the current row, from the database cursor,
560 @param uid: the current user’s ID for security checks,
561 @param ids: List of Sales team ids
566 cr.execute('select distinct parent_id from crm_case_section where id IN %s', (tuple(ids),))
567 ids = filter(None, map(lambda x: x[0], cr.fetchall()))
575 (_check_recursion, 'Error ! You cannot create recursive Sales team.', ['parent_id'])
578 def name_get(self, cr, uid, ids, context=None):
579 """Overrides orm name_get method
580 @param self: The object pointer
581 @param cr: the current row, from the database cursor,
582 @param uid: the current user’s ID for security checks,
583 @param ids: List of sales team ids
591 reads = self.read(cr, uid, ids, ['name', 'parent_id'], context)
594 name = record['name']
595 if record['parent_id']:
596 name = record['parent_id'][1] + ' / ' + name
597 res.append((record['id'], name))
603 class crm_case_categ(osv.osv):
604 """ Category of Case """
605 _name = "crm.case.categ"
606 _description = "Category of Case"
608 'name': fields.char('Name', size=64, required=True, translate=True),
609 'section_id': fields.many2one('crm.case.section', 'Sales Team'),
610 'object_id': fields.many2one('ir.model', 'Object Name'),
613 def _find_object_id(self, cr, uid, context=None):
614 """Finds id for case object
615 @param self: The object pointer
616 @param cr: the current row, from the database cursor,
617 @param uid: the current user’s ID for security checks,
618 @param context: A standard dictionary for contextual values
621 object_id = context and context.get('object_id', False) or False
622 ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', object_id)])
623 return ids and ids[0]
626 'object_id' : _find_object_id
632 class crm_case_stage(osv.osv):
633 _inherit = "crm.case.stage"
635 'section_ids':fields.many2many('crm.case.section', 'section_stage_rel', 'stage_id', 'section_id', 'Sections'),
641 class crm_case_resource_type(osv.osv):
642 """ Resource Type of case """
643 _name = "crm.case.resource.type"
644 _description = "Campaign"
647 'name': fields.char('Campaign Name', size=64, required=True, translate=True),
648 'section_id': fields.many2one('crm.case.section', 'Sales Team'),
650 crm_case_resource_type()
653 def _links_get(self, cr, uid, context=None):
654 """Gets links value for reference field
655 @param self: The object pointer
656 @param cr: the current row, from the database cursor,
657 @param uid: the current user’s ID for security checks,
658 @param context: A standard dictionary for contextual values
660 obj = self.pool.get('res.request.link')
661 ids = obj.search(cr, uid, [])
662 res = obj.read(cr, uid, ids, ['object', 'name'], context)
663 return [(r['object'], r['name']) for r in res]
665 class users(osv.osv):
666 _inherit = 'res.users'
667 _description = "Users"
669 'context_section_id': fields.many2one('crm.case.section', 'Sales Team'),
674 class res_partner(osv.osv):
675 _inherit = 'res.partner'
677 'section_id': fields.many2one('crm.case.section', 'Sales Team'),