email.addresss_id_repalce_by_user_email
[odoo/odoo.git] / addons / crm / crm.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
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.
11 #
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.
16 #
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/>.
19 #
20 ##############################################################################
21
22 import time
23 import base64
24 import tools
25
26 from osv import fields
27 from osv import osv
28 from tools.translate import _
29
30 MAX_LEVEL = 15
31 AVAILABLE_STATES = [
32     ('draft', 'Draft'),
33     ('open', 'Open'),
34     ('cancel', 'Cancelled'),
35     ('done', 'Closed'),
36     ('pending', 'Pending'),
37 ]
38
39 AVAILABLE_PRIORITIES = [
40     ('1', 'Highest'),
41     ('2', 'High'),
42     ('3', 'Normal'),
43     ('4', 'Low'),
44     ('5', 'Lowest'),
45 ]
46
47 class crm_base(object):
48     """
49         Base classe for crm object,
50         Object that inherit from this class should have
51             date_open
52             date_closed
53             user_id
54             partner_id
55             partner_address_id
56         as field to be compatible with this class
57         
58     """
59     def _get_default_partner_address(self, cr, uid, context=None):
60
61         """Gives id of default address for current user
62         :param context: if portal in context is false return false anyway
63         """
64         if context is None:
65             context = {}
66         if not context.get('portal'):
67             return False
68         return self.pool.get('res.partner.address').browse(cr, uid, uid, context)
69
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
73         """
74         if context is None:
75             context = {}
76         if not context.get('portal', False):
77             return False
78         part_id = self.pool.get('res.partner.address').browse(cr, uid, uid, context=context)
79         return part_id.partner_id
80     
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
84         """
85         if not context.get('portal', False):
86             return False
87         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
88         return user.user_email
89     
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
93         """
94         if context and context.get('portal', False):
95             return False
96         return uid
97
98     def _get_section(self, cr, uid, context=None):
99         """Gives section id for current User
100         """
101         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
102         return user.context_section_id.id or False
103     
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
109         """
110         if not add:
111             return {'value': {'email_from': False}}
112         address = self.pool.get('res.partner.address').browse(cr, uid, add)
113         if address.email:
114             return {'value': {'email_from': address.email, 'phone': address.phone}}
115         else:
116             return {'value': {'phone': address.phone}}
117         
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
123         """
124         data={}
125         if  part:
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}
130     
131     
132     def case_open(self, cr, uid, ids, *args):
133         """Opens Case
134         @param ids: List of case Ids
135         """
136         cases = self.browse(cr, uid, ids)
137         for case in cases:
138             data = {'state': 'open', 'active': True}
139             if not case.user_id:
140                 data['user_id'] = uid
141             self.write(cr, uid, case.id, data)
142
143
144         self._action(cr, uid, cases, 'open')
145         return True
146
147     def case_close(self, cr, uid, ids, *args):
148         """Closes Case
149         @param ids: List of case Ids
150         """
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'),
155                                   })
156         #
157         # We use the cache of cases to keep the old case state
158         #
159         self._action(cr, uid, cases, 'done')
160         return True
161
162     def case_cancel(self, cr, uid, ids, *args):
163         """Cancels Case
164         @param ids: List of case Ids
165         """
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',
169                                   'active': True})
170         self._action(cr, uid, cases, 'cancel')
171         for case in cases:
172             message = _("The case '%s' has been cancelled.") % (case.name,)
173             self.log(cr, uid, case.id, message)
174         return True
175
176     def case_pending(self, cr, uid, ids, *args):
177         """Marks case as pending
178         @param ids: List of case Ids
179         """
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')
184         return True
185
186     def case_reset(self, cr, uid, ids, *args):
187         """Resets case as draft
188         @param ids: List of case Ids
189         """
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')
194         return True
195     
196     def _action(self, cr, uid, cases, state_to, scrit=None, context=None):
197         if context is None:
198             context = {}
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)
205
206 class crm_case(crm_base):
207     """
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
211         
212         And object that inherit (orm inheritance) from a class the overwrite copy 
213     """
214
215     def _find_lost_stage(self, cr, uid, type, section_id):
216         return self._find_percent_stage(cr, uid, 0.0, type, section_id)
217
218     def _find_won_stage(self, cr, uid, type, section_id):
219         return self._find_percent_stage(cr, uid, 100.0, type, section_id)
220
221     def _find_percent_stage(self, cr, uid, percent, type, section_id):
222         """
223             Return the first stage with a probability == percent
224         """
225         stage_pool = self.pool.get('crm.case.stage')
226         if section_id :
227             ids = stage_pool.search(cr, uid, [("probability", '=', percent), ("type", 'like', type), ("section_ids", 'in', [section_id])])
228         else :
229             ids = stage_pool.search(cr, uid, [("probability", '=', percent), ("type", 'like', type)])
230
231         if ids:
232             return ids[0]
233         return False
234
235
236     def _find_first_stage(self, cr, uid, type, section_id):
237         """
238             return the first stage that has a sequence number equal or higher than sequence
239         """
240         stage_pool = self.pool.get('crm.case.stage')
241         if section_id :
242             ids = stage_pool.search(cr, uid, [("sequence", '>', 0), ("type", 'like', type), ("section_ids", 'in', [section_id])])
243         else :
244             ids = stage_pool.search(cr, uid, [("sequence", '>', 0), ("type", 'like', type)])
245
246         if ids:
247             stages = stage_pool.browse(cr, uid, ids)
248             stage_min = stages[0]
249             for stage in stages:
250                 if stage_min.sequence > stage.sequence:
251                     stage_min = stage
252             return stage_min.id
253         else :
254             return False
255
256     def onchange_stage_id(self, cr, uid, ids, stage_id, context={}):
257
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 """
263
264         if not stage_id:
265             return {'value':{}}
266
267         stage = self.pool.get('crm.case.stage').browse(cr, uid, stage_id, context)
268
269         if not stage.on_change:
270             return {'value':{}}
271         return {'value':{'probability': stage.probability}}
272
273     
274
275     def copy(self, cr, uid, id, default=None, context=None):
276         """
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
284         """
285         
286         if context is None:
287             context = {}
288         if default is None:
289             default = {}
290
291         default.update({
292                     'message_ids': [],
293                 })
294         if hasattr(self, '_columns'):
295             if self._columns.get('date_closed'):
296                 default.update({
297                     'date_closed': False,
298                 })
299             if self._columns.get('date_open'):
300                 default.update({
301                     'date_open': False
302                 })
303         return super(osv.osv, self).copy(cr, uid, id, default, context=context)
304
305     
306
307     
308
309     def _find_next_stage(self, cr, uid, stage_list, index, current_seq, stage_pool, context=None):
310         if index + 1 == len(stage_list):
311             return False
312         next_stage_id = stage_list[index + 1]
313         next_stage = stage_pool.browse(cr, uid, next_stage_id, context=context)
314         if not next_stage:
315             return False
316         next_seq = next_stage.sequence
317         if not current_seq :
318             current_seq = 0
319
320         if (abs(next_seq - current_seq)) >= 1:
321             return next_stage
322         else :
323             return self._find_next_stage(cr, uid, stage_list, index + 1, current_seq, stage_pool)
324
325     def stage_change(self, cr, uid, ids, context=None, order='sequence'):
326         if context is None:
327             context = {}
328
329         stage_pool = self.pool.get('crm.case.stage')
330         stage_type = context and context.get('stage_type','')
331         current_seq = False
332         next_stage_id = False
333
334         for case in self.browse(cr, uid, ids, context=context):
335
336             next_stage = False
337             value = {}
338             if case.section_id.id :
339                 domain = [('type', '=', stage_type),('section_ids', '=', case.section_id.id)]
340             else :
341                 domain = [('type', '=', stage_type)]
342
343
344             stages = stage_pool.search(cr, uid, domain, order=order)
345             current_seq = case.stage_id.sequence
346             index = -1
347             if case.stage_id and case.stage_id.id in stages:
348                 index = stages.index(case.stage_id.id)
349
350             next_stage = self._find_next_stage(cr, uid, stages, index, current_seq, stage_pool, context=context)
351
352             if next_stage:
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)
358
359
360         return next_stage_id #FIXME should return a list of all id
361
362
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"""
371
372         return self.stage_change(cr, uid, ids, context=context, order='sequence')
373
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')
383
384     
385
386     
387
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, \
394                                        context=context)
395
396     def case_open(self, cr, uid, ids, *args):
397         """Opens Case
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
403         """
404
405         cases = self.browse(cr, uid, ids)
406         self._history(cr, uid, cases, _('Open'))
407         for case in cases:
408             data = {'state': 'open', 'active': True}
409             if not case.user_id:
410                 data['user_id'] = uid
411             self.write(cr, uid, case.id, data)
412         self._action(cr, uid, cases, 'open')
413         return True
414
415     def case_close(self, cr, uid, ids, *args):
416         """Closes Case
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
422         """
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'),
428                                   })
429         #
430         # We use the cache of cases to keep the old case state
431         #
432         self._action(cr, uid, cases, 'done')
433         return True
434
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
442         """
443         cases = self.browse(cr, uid, ids)
444         for case in cases:
445             data = {'active': True}
446
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
452             else:
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')
458         return True
459
460     def case_cancel(self, cr, uid, ids, *args):
461         """Cancels Case
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
467         """
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',
472                                   'active': True})
473         self._action(cr, uid, cases, 'cancel')
474         for case in cases:
475             message = _("The case '%s' has been cancelled.") % (case.name,)
476             self.log(cr, uid, case.id, message)
477         return True
478
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
486         """
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')
492         return True
493
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
501         """
502         state = 'draft' 
503         if 'crm.phonecall' in args:
504             state = 'open' 
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)
510         return True
511
512     def remind_partner(self, cr, uid, ids, context=None, attach=False):
513
514         """
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
520
521         """
522
523         return self.remind_user(cr, uid, ids, context, attach,
524                 destination=False)
525
526     def remind_user(self, cr, uid, ids, context=None, attach=False, destination=True):
527         """
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
533         """
534         for case in self.browse(cr, uid, ids, context=context):
535             if not destination and not case.email_from:
536                 return False
537             if not case.user_id.user_email:
538                 return False
539             
540             if destination and case.section_id.user_id:
541                 case_email = case.section_id.user_id.user_email
542             else:
543                 case_email = case.user_id.user_email
544
545             src = case_email
546             dest = case.user_id
547             body = case.description or ""
548             if case.message_ids:
549                 body = case.message_ids[0].description or ""
550             if not destination:
551                 src, dest = dest, case.email_from
552                 if body and case.user_id.signature:
553                     if body:
554                         body += '\n\n%s' % (case.user_id.signature)
555                     else:
556                         body = '\n\n%s' % (case.user_id.signature)
557
558             body = self.format_body(body)
559
560             attach_to_send = None
561
562             if attach:
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)
566
567                 # Send an email
568             subject = "Reminder: [%s] %s" % (str(case.id), case.name,)
569             tools.email_send(
570                 src,
571                 [dest],
572                 subject,
573                 body,
574                 reply_to=case.section_id.reply_to or '',
575                 openobject_id=str(case.id),
576                 attach=attach_to_send
577             )
578             self._history(cr, uid, [case], _('Send'), history=True, subject=subject, email=dest, details=body, email_from=src)
579
580         return True
581
582     def _check(self, cr, uid, ids=False, context=None):
583         """
584         Function called by the scheduler to process cases for date actions
585         Only works on not done and cancelled cases
586
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
591         """
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')))
598
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)
602
603     
604
605     def format_body(self, body):
606         return self.pool.get('base.action.rule').format_body(body)
607
608     def format_mail(self, obj, body):
609         return self.pool.get('base.action.rule').format_mail(obj, body)
610
611     def message_followers(self, cr, uid, ids, context=None):
612         """ Get a list of emails of the people following this thread
613         """
614         res = {}
615         for case in self.browse(cr, uid, ids, context=context):
616             l=[]
617             if case.email_cc:
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)
621             res[case.id] = l
622         return res
623
624
625 class crm_case_stage(osv.osv):
626     """ Stage of case """
627
628     _name = "crm.case.stage"
629     _description = "Stage of case"
630     _rec_name = 'name'
631     _order = "sequence"
632
633
634
635     def _get_type_value(self, cr, user, context):
636         return [('lead','Lead'),('opportunity','Opportunity')]
637
638
639     _columns = {
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),
647     }
648
649
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
656         """
657         type = context and context.get('type', '') or ''
658         return type
659
660     _defaults = {
661         'sequence': lambda *args: 1,
662         'probability': lambda *args: 0.0,
663         'type': _find_stage_type,
664     }
665
666 crm_case_stage()
667
668
669 class crm_case_section(osv.osv):
670     """Sales Team"""
671
672     _name = "crm.case.section"
673     _description = "Sales Teams"
674     _order = "complete_name"
675
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))
678
679     _columns = {
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'),
696     }
697
698     _defaults = {
699         'active': lambda *a: 1,
700         'allow_unlink': lambda *a: 1,
701     }
702
703     _sql_constraints = [
704         ('code_uniq', 'unique (code)', 'The code of the sales team must be unique !')
705     ]
706
707     def _check_recursion(self, cr, uid, ids, context=None):
708
709         """
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
715         """
716         level = 100
717
718         while len(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()))
721             if not level:
722                 return False
723             level -= 1
724
725         return True
726
727     _constraints = [
728         (_check_recursion, 'Error ! You cannot create recursive Sales team.', ['parent_id'])
729     ]
730
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
737         """
738         if context is None:
739             context = {}
740         if not isinstance(ids, list) : 
741             ids = [ids]
742         res = []
743         if not ids:
744             return res
745         reads = self.read(cr, uid, ids, ['name', 'parent_id'], context)
746
747         for record in reads:
748             name = record['name']
749             if record['parent_id']:
750                 name = record['parent_id'][1] + ' / ' + name
751             res.append((record['id'], name))
752         return res
753
754 crm_case_section()
755
756
757 class crm_case_categ(osv.osv):
758     """ Category of Case """
759     _name = "crm.case.categ"
760     _description = "Category of Case"
761     _columns = {
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'),
765     }
766
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
773         """
774
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]
778
779     _defaults = {
780         'object_id' : _find_object_id
781
782     }
783 crm_case_categ()
784
785
786 class crm_case_stage(osv.osv):
787     _inherit = "crm.case.stage"
788     _columns = {
789         'section_ids':fields.many2many('crm.case.section', 'section_stage_rel', 'stage_id', 'section_id', 'Sections'),
790     }
791
792 crm_case_stage()
793
794
795 class crm_case_resource_type(osv.osv):
796     """ Resource Type of case """
797     _name = "crm.case.resource.type"
798     _description = "Campaign"
799     _rec_name = "name"
800     _columns = {
801         'name': fields.char('Campaign Name', size=64, required=True, translate=True),
802         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
803     }
804 crm_case_resource_type()
805
806
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
813     """
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]
818
819 class users(osv.osv):
820     _inherit = 'res.users'
821     _description = "Users"
822     _columns = {
823         'context_section_id': fields.many2one('crm.case.section', 'Sales Team'),
824     }
825
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')
829
830         if vals.get('context_section_id', False):
831             section_obj.write(cr, uid, [vals['context_section_id']], {'member_ids':[(4, res)]}, context)
832         return res
833 users()
834
835
836 class res_partner(osv.osv):
837     _inherit = 'res.partner'
838     _columns = {
839         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
840     }
841 res_partner()
842