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 _
33 ('open', 'In Progress'),
34 ('cancel', 'Cancelled'),
36 ('pending', 'Pending'),
39 AVAILABLE_PRIORITIES = [
47 class crm_case_channel(osv.osv):
48 _name = "crm.case.channel"
49 _description = "Channels"
52 'name': fields.char('Channel Name', size=64, required=True),
53 'active': fields.boolean('Active'),
56 'active': lambda *a: 1,
59 class crm_case_stage(osv.osv):
62 _name = "crm.case.stage"
63 _description = "Stage of case"
68 'name': fields.char('Stage Name', size=64, required=True, translate=True),
69 'sequence': fields.integer('Sequence', help="Used to order stages."),
70 'probability': fields.float('Probability (%)', required=True, help="This percentage depicts the default/average probability of the Case for this stage to be a success"),
71 'on_change': fields.boolean('Change Probability Automatically', help="Setting this stage will change the probability automatically on the opportunity."),
72 'requirements': fields.text('Requirements'),
73 'section_ids':fields.many2many('crm.case.section', 'section_stage_rel', 'stage_id', 'section_id', 'Sections'),
74 'case_default': fields.boolean('Common to All Teams', help="If you check this field, this stage will be proposed by default on each sales team. It will not assign this stage to existing teams."),
78 'sequence': lambda *args: 1,
79 'probability': lambda *args: 0.0,
82 class crm_case_section(osv.osv):
85 _name = "crm.case.section"
86 _description = "Sales Teams"
87 _order = "complete_name"
89 def get_full_name(self, cr, uid, ids, field_name, arg, context=None):
90 return dict(self.name_get(cr, uid, ids, context=context))
93 'name': fields.char('Sales Team', size=64, required=True, translate=True),
94 'complete_name': fields.function(get_full_name, type='char', size=256, readonly=True, store=True),
95 'code': fields.char('Code', size=8),
96 'active': fields.boolean('Active', help="If the active field is set to "\
97 "true, it will allow you to hide the sales team without removing it."),
98 'allow_unlink': fields.boolean('Allow Delete', help="Allows to delete non draft cases"),
99 'change_responsible': fields.boolean('Reassign Escalated', help="When escalating to this team override the saleman with the team leader."),
100 'user_id': fields.many2one('res.users', 'Team Leader'),
101 'member_ids':fields.many2many('res.users', 'sale_member_rel', 'section_id', 'member_id', 'Team Members'),
102 '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"),
103 'parent_id': fields.many2one('crm.case.section', 'Parent Team'),
104 'child_ids': fields.one2many('crm.case.section', 'parent_id', 'Child Teams'),
105 'resource_calendar_id': fields.many2one('resource.calendar', "Working Time", help="Used to compute open days"),
106 'note': fields.text('Description'),
107 'working_hours': fields.float('Working Hours', digits=(16,2 )),
108 'stage_ids': fields.many2many('crm.case.stage', 'section_stage_rel', 'section_id', 'stage_id', 'Stages'),
110 def _get_stage_common(self, cr, uid, context):
111 ids = self.pool.get('crm.case.stage').search(cr, uid, [('case_default','=',1)], context=context)
115 'active': lambda *a: 1,
116 'allow_unlink': lambda *a: 1,
117 'stage_ids': _get_stage_common
121 ('code_uniq', 'unique (code)', 'The code of the sales team must be unique !')
125 (osv.osv._check_recursion, 'Error ! You cannot create recursive Sales team.', ['parent_id'])
128 def name_get(self, cr, uid, ids, context=None):
129 """Overrides orm name_get method"""
130 if not isinstance(ids, list) :
135 reads = self.read(cr, uid, ids, ['name', 'parent_id'], context)
138 name = record['name']
139 if record['parent_id']:
140 name = record['parent_id'][1] + ' / ' + name
141 res.append((record['id'], name))
144 class crm_case_categ(osv.osv):
145 """ Category of Case """
146 _name = "crm.case.categ"
147 _description = "Category of Case"
149 'name': fields.char('Name', size=64, required=True, translate=True),
150 'section_id': fields.many2one('crm.case.section', 'Sales Team'),
151 'object_id': fields.many2one('ir.model', 'Object Name'),
154 def _find_object_id(self, cr, uid, context=None):
155 """Finds id for case object"""
156 object_id = context and context.get('object_id', False) or False
157 ids = self.pool.get('ir.model').search(cr, uid, [('id', '=', object_id)])
158 return ids and ids[0] or False
161 'object_id' : _find_object_id
164 class crm_case_resource_type(osv.osv):
165 """ Resource Type of case """
166 _name = "crm.case.resource.type"
167 _description = "Campaign"
170 'name': fields.char('Campaign Name', size=64, required=True, translate=True),
171 'section_id': fields.many2one('crm.case.section', 'Sales Team'),
174 class crm_base(object):
175 """ Base utility mixin class for crm objects,
176 Object subclassing this should define colums:
182 def _get_default_partner_address(self, cr, uid, context=None):
183 """Gives id of default address for current user
184 :param context: if portal in context is false return false anyway
188 if not context.get('portal'):
190 # was user.address_id.id, but address_id has been removed
191 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
192 if hasattr(user, 'partner_address_id') and user.partner_address_id:
193 return user.partner_address_id
196 def _get_default_partner(self, cr, uid, context=None):
197 """Gives id of partner for current user
198 :param context: if portal in context is false return false anyway
202 if not context.get('portal', False):
204 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
205 if hasattr(user, 'partner_address_id') and user.partner_address_id:
206 return user.partner_address_id
207 return user.company_id.partner_id.id
209 def _get_default_email(self, cr, uid, context=None):
210 """Gives default email address for current user
211 :param context: if portal in context is false return false anyway
213 if not context.get('portal', False):
215 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
216 return user.user_email
218 def _get_default_user(self, cr, uid, context=None):
219 """Gives current user id
220 :param context: if portal in context is false return false anyway
222 if context and context.get('portal', False):
226 def _get_section(self, cr, uid, context=None):
227 """Gives section id for current User
229 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
230 return user.context_section_id.id or False
232 def onchange_partner_address_id(self, cr, uid, ids, add, email=False):
233 """This function returns value of partner email based on Partner Address
234 :param ids: List of case IDs
235 :param add: Id of Partner's address
236 :param email: Partner's email ID
238 data = {'value': {'email_from': False, 'phone':False}}
240 address = self.pool.get('res.partner').browse(cr, uid, add)
241 data['value'] = {'email_from': address and address.email or False ,
242 'phone': address and address.phone or False}
243 if 'phone' not in self._columns:
244 del data['value']['phone']
247 def onchange_partner_id(self, cr, uid, ids, part, email=False):
248 """This function returns value of partner address based on partner
249 :param ids: List of case IDs
250 :param part: Partner's id
251 :param email: Partner's email ID
255 addr = self.pool.get('res.partner').address_get(cr, uid, [part], ['contact'])
256 data.update(self.onchange_partner_address_id(cr, uid, ids, addr['contact'])['value'])
257 return {'value': data}
259 def case_open(self, cr, uid, ids, *args):
261 :param ids: List of case Ids
263 cases = self.browse(cr, uid, ids)
265 data = {'state': 'open', 'active': True}
267 data['user_id'] = uid
268 self.write(cr, uid, [case.id], data)
270 self._action(cr, uid, cases, 'open')
273 def case_close(self, cr, uid, ids, *args):
275 :param ids: List of case Ids
277 cases = self.browse(cr, uid, ids)
278 cases[0].state # to fill the browse record cache
279 self.write(cr, uid, ids, {'state': 'done', 'date_closed': time.strftime('%Y-%m-%d %H:%M:%S'), })
280 # We use the cache of cases to keep the old case state
281 self._action(cr, uid, cases, 'done')
284 def case_cancel(self, cr, uid, ids, *args):
286 :param ids: List of case Ids
288 cases = self.browse(cr, uid, ids)
289 cases[0].state # to fill the browse record cache
290 self.write(cr, uid, ids, {'state': 'cancel', 'active': True})
291 # We use the cache of cases to keep the old case state
292 self._action(cr, uid, cases, 'cancel')
295 def case_pending(self, cr, uid, ids, *args):
296 """Marks case as pending
297 :param ids: List of case Ids
299 cases = self.browse(cr, uid, ids)
300 cases[0].state # to fill the browse record cache
301 self.write(cr, uid, ids, {'state': 'pending', 'active': True})
302 self._action(cr, uid, cases, 'pending')
305 def case_reset(self, cr, uid, ids, *args):
306 """Resets case as draft
307 :param ids: List of case Ids
309 cases = self.browse(cr, uid, ids)
310 cases[0].state # to fill the browse record cache
311 self.write(cr, uid, ids, {'state': 'draft', 'active': True})
312 self._action(cr, uid, cases, 'draft')
315 def _action(self, cr, uid, cases, state_to, scrit=None, context=None):
318 context['state_to'] = state_to
319 rule_obj = self.pool.get('base.action.rule')
320 model_obj = self.pool.get('ir.model')
321 model_ids = model_obj.search(cr, uid, [('model','=',self._name)])
322 rule_ids = rule_obj.search(cr, uid, [('model_id','=',model_ids[0])])
323 return rule_obj._action(cr, uid, rule_ids, cases, scrit=scrit, context=context)
325 class crm_case(crm_base):
326 """ A simple python class to be used for common functions
327 Object that inherit from this class should inherit from mailgate.thread
328 And need a stage_id field
329 And object that inherit (orm inheritance) from a class the overwrite copy
332 def stage_find(self, cr, uid, section_id, domain=[], order='sequence'):
333 domain = list(domain)
335 domain.append(('section_ids', '=', section_id))
336 stage_ids = self.pool.get('crm.case.stage').search(cr, uid, domain, order=order)
341 def stage_set(self, cr, uid, ids, stage_id, context=None):
343 if hasattr(self,'onchange_stage_id'):
344 value = self.onchange_stage_id(cr, uid, ids, stage_id)['value']
345 value['stage_id'] = stage_id
346 return self.write(cr, uid, ids, value, context=context)
348 def stage_change(self, cr, uid, ids, op, order, context=None):
351 for case in self.browse(cr, uid, ids, context=context):
354 seq = case.stage_id.sequence
357 section_id = case.section_id.id
358 next_stage_id = self.stage_find(cr, uid, section_id, [('sequence',op,seq)],order)
360 return self.stage_set(cr, uid, [case.id], next_stage_id, context=context)
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
367 return self.stage_change(cr, uid, ids, '>','sequence', context)
369 def stage_previous(self, cr, uid, ids, context=None):
370 """This function computes previous stage for case from its current
371 stage using available stage for that case type
373 return self.stage_change(cr, uid, ids, '<', 'sequence desc', context)
375 def copy(self, cr, uid, id, default=None, context=None):
376 """Overrides orm copy method to avoid copying messages,
377 as well as date_closed and date_open columns if they
382 default.update({ 'message_ids': [], })
383 if hasattr(self, '_columns'):
384 if self._columns.get('date_closed'):
385 default.update({ 'date_closed': False, })
386 if self._columns.get('date_open'):
387 default.update({ 'date_open': False })
388 return super(crm_case, self).copy(cr, uid, id, default, context=context)
391 def case_open(self, cr, uid, ids, *args):
393 cases = self.browse(cr, uid, ids)
395 data = {'state': 'open', 'active': True }
397 data['user_id'] = uid
398 self.write(cr, uid, [case.id], data)
399 self._action(cr, uid, cases, 'open')
402 def case_close(self, cr, uid, ids, *args):
404 cases = self.browse(cr, uid, ids)
405 cases[0].state # to fill the browse record cache
406 self.write(cr, uid, ids, {'state': 'done',
407 'date_closed': time.strftime('%Y-%m-%d %H:%M:%S'),
410 # We use the cache of cases to keep the old case state
412 self._action(cr, uid, cases, 'done')
415 def case_escalate(self, cr, uid, ids, *args):
416 """Escalates case to parent level"""
417 cases = self.browse(cr, uid, ids)
419 data = {'active': True}
420 if case.section_id.parent_id:
421 data['section_id'] = case.section_id.parent_id.id
422 if case.section_id.parent_id.change_responsible:
423 if case.section_id.parent_id.user_id:
424 data['user_id'] = case.section_id.parent_id.user_id.id
426 raise osv.except_osv(_('Error !'), _('You can not escalate, you are already at the top level regarding your sales-team category.'))
427 self.write(cr, uid, [case.id], data)
428 cases = self.browse(cr, uid, ids)
429 self._action(cr, uid, cases, 'escalate')
432 def case_cancel(self, cr, uid, ids, *args):
434 cases = self.browse(cr, uid, ids)
435 cases[0].state # to fill the browse record cache
436 self.write(cr, uid, ids, {'state': 'cancel',
438 self._action(cr, uid, cases, 'cancel')
440 message = _("The case '%s' has been cancelled.") % (case.name,)
441 self.log(cr, uid, case.id, message)
444 def case_pending(self, cr, uid, ids, *args):
445 """Marks case as pending"""
446 cases = self.browse(cr, uid, ids)
447 cases[0].state # to fill the browse record cache
448 self.write(cr, uid, ids, {'state': 'pending', 'active': True})
449 self._action(cr, uid, cases, 'pending')
452 def case_reset(self, cr, uid, ids, *args):
453 """Resets case as draft"""
455 if 'crm.phonecall' in args:
457 cases = self.browse(cr, uid, ids)
458 cases[0].state # to fill the browse record cache
459 self.write(cr, uid, ids, {'state': state, 'active': True})
460 self._action(cr, uid, cases, state)
463 def remind_partner(self, cr, uid, ids, context=None, attach=False):
464 return self.remind_user(cr, uid, ids, context, attach,
467 def remind_user(self, cr, uid, ids, context=None, attach=False, destination=True):
468 mail_message = self.pool.get('mail.message')
469 for case in self.browse(cr, uid, ids, context=context):
470 if not destination and not case.email_from:
472 if not case.user_id.user_email:
474 if destination and case.section_id.user_id:
475 case_email = case.section_id.user_id.user_email
477 case_email = case.user_id.user_email
480 dest = case.user_id.user_email or ""
481 body = case.description or ""
482 for message in case.message_ids:
483 if message.email_from and message.body_text:
484 body = message.body_text
488 src, dest = dest, case.email_from
489 if body and case.user_id.signature:
491 body += '\n\n%s' % (case.user_id.signature)
493 body = '\n\n%s' % (case.user_id.signature)
495 body = self.format_body(body)
500 attach_ids = self.pool.get('ir.attachment').search(cr, uid, [('res_model', '=', self._name), ('res_id', '=', case.id)])
501 attach_to_send = self.pool.get('ir.attachment').read(cr, uid, attach_ids, ['datas_fname', 'datas'])
502 attach_to_send = dict(map(lambda x: (x['datas_fname'], base64.decodestring(x['datas'])), attach_to_send))
505 subject = "Reminder: [%s] %s" % (str(case.id), case.name, )
506 mail_message.schedule_with_attach(cr, uid,
512 reply_to=case.section_id.reply_to,
514 attachments=attach_to_send,
519 def _check(self, cr, uid, ids=False, context=None):
520 """Function called by the scheduler to process cases for date actions
521 Only works on not done and cancelled cases
523 cr.execute('select * from crm_case \
524 where (date_action_last<%s or date_action_last is null) \
525 and (date_action_next<=%s or date_action_next is null) \
526 and state not in (\'cancel\',\'done\')',
527 (time.strftime("%Y-%m-%d %H:%M:%S"),
528 time.strftime('%Y-%m-%d %H:%M:%S')))
530 ids2 = map(lambda x: x[0], cr.fetchall() or [])
531 cases = self.browse(cr, uid, ids2, context=context)
532 return self._action(cr, uid, cases, False, context=context)
534 def format_body(self, body):
535 return self.pool.get('base.action.rule').format_body(body)
537 def format_mail(self, obj, body):
538 return self.pool.get('base.action.rule').format_mail(obj, body)
540 def message_thread_followers(self, cr, uid, ids, context=None):
542 for case in self.browse(cr, uid, ids, context=context):
545 l.append(case.email_cc)
546 if case.user_id and case.user_id.user_email:
547 l.append(case.user_id.user_email)
551 def _links_get(self, cr, uid, context=None):
552 """Gets links value for reference field"""
553 obj = self.pool.get('res.request.link')
554 ids = obj.search(cr, uid, [])
555 res = obj.read(cr, uid, ids, ['object', 'name'], context)
556 return [(r['object'], r['name']) for r in res]
558 class users(osv.osv):
559 _inherit = 'res.users'
560 _description = "Users"
562 'context_section_id': fields.many2one('crm.case.section', 'Sales Team'),
565 def create(self, cr, uid, vals, context=None):
566 res = super(users, self).create(cr, uid, vals, context=context)
567 section_obj=self.pool.get('crm.case.section')
568 if vals.get('context_section_id'):
569 section_obj.write(cr, uid, [vals['context_section_id']], {'member_ids':[(4, res)]}, context)
574 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: