7003bba2a8e4f3e1daaaaf9c2bc5102b4b896bbf
[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.users').browse(cr, uid, uid, context).address_id.id
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         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
79         if not user.address_id:
80             return False
81         return user.address_id.partner_id.id
82     
83     def _get_default_email(self, cr, uid, context=None):
84         """Gives default email address for current user
85         :param context: if portal in context is false return false anyway
86         """
87         if not context.get('portal', False):
88             return False
89         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
90         if not user.address_id:
91             return False
92         return user.address_id.email
93     
94     def _get_default_user(self, cr, uid, context=None):
95         """Gives current user id
96        :param context: if portal in context is false return false anyway
97         """
98         if context and context.get('portal', False):
99             return False
100         return uid
101
102     def _get_section(self, cr, uid, context=None):
103         """Gives section id for current User
104         """
105         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
106         return user.context_section_id.id or False
107     
108     def onchange_partner_address_id(self, cr, uid, ids, add, email=False):
109         """This function returns value of partner email based on Partner Address
110         @param ids: List of case IDs
111         @param add: Id of Partner's address
112         @email: Partner's email ID
113         """
114         if not add:
115             return {'value': {'email_from': False}}
116         address = self.pool.get('res.partner.address').browse(cr, uid, add)
117         if address.email:
118             return {'value': {'email_from': address.email, 'phone': address.phone}}
119         else:
120             return {'value': {'phone': address.phone}}
121         
122     def onchange_partner_id(self, cr, uid, ids, part, email=False):
123         """This function returns value of partner address based on partner
124         @param ids: List of case IDs
125         @param part: Partner's id
126         @email: Partner's email ID
127         """
128         data={}
129         if  part:
130             addr = self.pool.get('res.partner').address_get(cr, uid, [part], ['contact'])
131             data = {'partner_address_id': addr['contact']}
132             data.update(self.onchange_partner_address_id(cr, uid, ids, addr['contact'])['value'])
133         return {'value': data}
134     
135     
136     def case_open(self, cr, uid, ids, *args):
137         """Opens Case
138         @param ids: List of case Ids
139         """
140         cases = self.browse(cr, uid, ids)
141         for case in cases:
142             data = {'state': 'open', 'active': True}
143             if not case.user_id:
144                 data['user_id'] = uid
145             self.write(cr, uid, case.id, data)
146
147
148         self._action(cr, uid, cases, 'open')
149         return True
150
151     def case_close(self, cr, uid, ids, *args):
152         """Closes Case
153         @param ids: List of case Ids
154         """
155         cases = self.browse(cr, uid, ids)
156         cases[0].state # to fill the browse record cache
157         self.write(cr, uid, ids, {'state': 'done',
158                                   'date_closed': time.strftime('%Y-%m-%d %H:%M:%S'),
159                                   })
160         #
161         # We use the cache of cases to keep the old case state
162         #
163         self._action(cr, uid, cases, 'done')
164         return True
165
166     def case_cancel(self, cr, uid, ids, *args):
167         """Cancels Case
168         @param ids: List of case Ids
169         """
170         cases = self.browse(cr, uid, ids)
171         cases[0].state # to fill the browse record cache
172         self.write(cr, uid, ids, {'state': 'cancel',
173                                   'active': True})
174         self._action(cr, uid, cases, 'cancel')
175         for case in cases:
176             message = _("The case '%s' has been cancelled.") % (case.name,)
177             self.log(cr, uid, case.id, message)
178         return True
179
180     def case_pending(self, cr, uid, ids, *args):
181         """Marks case as pending
182         @param ids: List of case Ids
183         """
184         cases = self.browse(cr, uid, ids)
185         cases[0].state # to fill the browse record cache
186         self.write(cr, uid, ids, {'state': 'pending', 'active': True})
187         self._action(cr, uid, cases, 'pending')
188         return True
189
190     def case_reset(self, cr, uid, ids, *args):
191         """Resets case as draft
192         @param ids: List of case Ids
193         """
194         cases = self.browse(cr, uid, ids)
195         cases[0].state # to fill the browse record cache
196         self.write(cr, uid, ids, {'state': 'draft', 'active': True})
197         self._action(cr, uid, cases, 'draft')
198         return True
199     
200     def _action(self, cr, uid, cases, state_to, scrit=None, context=None):
201         if context is None:
202             context = {}
203         context['state_to'] = state_to
204         rule_obj = self.pool.get('base.action.rule')
205         model_obj = self.pool.get('ir.model')
206         model_ids = model_obj.search(cr, uid, [('model','=',self._name)])
207         rule_ids = rule_obj.search(cr, uid, [('model_id','=',model_ids[0])])
208         return rule_obj._action(cr, uid, rule_ids, cases, scrit=scrit, context=context)
209
210 class crm_case(crm_base):
211     """
212         A simple python class to be used for common functions 
213         Object that inherit from this class should inherit from mailgate.thread
214         And need a stage_id field
215         
216         And object that inherit (orm inheritance) from a class the overwrite copy 
217     """
218
219     def _find_lost_stage(self, cr, uid, type, section_id):
220         return self._find_percent_stage(cr, uid, 0.0, type, section_id)
221
222     def _find_won_stage(self, cr, uid, type, section_id):
223         return self._find_percent_stage(cr, uid, 100.0, type, section_id)
224
225     def _find_percent_stage(self, cr, uid, percent, type, section_id):
226         """
227             Return the first stage with a probability == percent
228         """
229         stage_pool = self.pool.get('crm.case.stage')
230         if section_id :
231             ids = stage_pool.search(cr, uid, [("probability", '=', percent), ("type", 'like', type), ("section_ids", 'in', [section_id])])
232         else :
233             ids = stage_pool.search(cr, uid, [("probability", '=', percent), ("type", 'like', type)])
234
235         if ids:
236             return ids[0]
237         return False
238
239
240     def _find_first_stage(self, cr, uid, type, section_id):
241         """
242             return the first stage that has a sequence number equal or higher than sequence
243         """
244         stage_pool = self.pool.get('crm.case.stage')
245         if section_id :
246             ids = stage_pool.search(cr, uid, [("sequence", '>', 0), ("type", 'like', type), ("section_ids", 'in', [section_id])])
247         else :
248             ids = stage_pool.search(cr, uid, [("sequence", '>', 0), ("type", 'like', type)])
249
250         if ids:
251             stages = stage_pool.browse(cr, uid, ids)
252             stage_min = stages[0]
253             for stage in stages:
254                 if stage_min.sequence > stage.sequence:
255                     stage_min = stage
256             return stage_min.id
257         else :
258             return False
259
260     def onchange_stage_id(self, cr, uid, ids, stage_id, context={}):
261
262         """ @param self: The object pointer
263             @param cr: the current row, from the database cursor,
264             @param uid: the current user’s ID for security checks,
265             @param ids: List of stage’s IDs
266             @stage_id: change state id on run time """
267
268         if not stage_id:
269             return {'value':{}}
270
271         stage = self.pool.get('crm.case.stage').browse(cr, uid, stage_id, context)
272
273         if not stage.on_change:
274             return {'value':{}}
275         return {'value':{'probability': stage.probability}}
276
277     
278
279     def copy(self, cr, uid, id, default=None, context=None):
280         """
281         Overrides orm copy method.
282         @param self: the object pointer
283         @param cr: the current row, from the database cursor,
284         @param uid: the current user’s ID for security checks,
285         @param id: Id of mailgate thread
286         @param default: Dictionary of default values for copy.
287         @param context: A standard dictionary for contextual values
288         """
289         
290         if context is None:
291             context = {}
292         if default is None:
293             default = {}
294
295         default.update({
296                     'message_ids': [],
297                 })
298         if hasattr(self, '_columns'):
299             if self._columns.get('date_closed'):
300                 default.update({
301                     'date_closed': False,
302                 })
303             if self._columns.get('date_open'):
304                 default.update({
305                     'date_open': False
306                 })
307         return super(osv.osv, self).copy(cr, uid, id, default, context=context)
308
309     
310
311     
312
313     def _find_next_stage(self, cr, uid, stage_list, index, current_seq, stage_pool, context=None):
314         if index + 1 == len(stage_list):
315             return False
316         next_stage_id = stage_list[index + 1]
317         next_stage = stage_pool.browse(cr, uid, next_stage_id, context=context)
318         if not next_stage:
319             return False
320         next_seq = next_stage.sequence
321         if not current_seq :
322             current_seq = 0
323
324         if (abs(next_seq - current_seq)) >= 1:
325             return next_stage
326         else :
327             return self._find_next_stage(cr, uid, stage_list, index + 1, current_seq, stage_pool)
328
329     def stage_change(self, cr, uid, ids, context=None, order='sequence'):
330         if context is None:
331             context = {}
332
333         stage_pool = self.pool.get('crm.case.stage')
334         stage_type = context and context.get('stage_type','')
335         current_seq = False
336         next_stage_id = False
337
338         for case in self.browse(cr, uid, ids, context=context):
339
340             next_stage = False
341             value = {}
342             if case.section_id.id :
343                 domain = [('type', '=', stage_type),('section_ids', '=', case.section_id.id)]
344             else :
345                 domain = [('type', '=', stage_type)]
346
347
348             stages = stage_pool.search(cr, uid, domain, order=order)
349             current_seq = case.stage_id.sequence
350             index = -1
351             if case.stage_id and case.stage_id.id in stages:
352                 index = stages.index(case.stage_id.id)
353
354             next_stage = self._find_next_stage(cr, uid, stages, index, current_seq, stage_pool, context=context)
355
356             if next_stage:
357                 next_stage_id = next_stage.id
358                 value.update({'stage_id': next_stage.id})
359                 if next_stage.on_change:
360                     value.update({'probability': next_stage.probability})
361             self.write(cr, uid, [case.id], value, context=context)
362
363
364         return next_stage_id #FIXME should return a list of all id
365
366
367     def stage_next(self, cr, uid, ids, context=None):
368         """This function computes next stage for case from its current stage
369              using available stage for that case type
370         @param self: The object pointer
371         @param cr: the current row, from the database cursor,
372         @param uid: the current user’s ID for security checks,
373         @param ids: List of case IDs
374         @param context: A standard dictionary for contextual values"""
375
376         return self.stage_change(cr, uid, ids, context=context, order='sequence')
377
378     def stage_previous(self, cr, uid, ids, context=None):
379         """This function computes previous stage for case from its current stage
380              using available stage for that case type
381         @param self: The object pointer
382         @param cr: the current row, from the database cursor,
383         @param uid: the current user’s ID for security checks,
384         @param ids: List of case IDs
385         @param context: A standard dictionary for contextual values"""
386         return self.stage_change(cr, uid, ids, context=context, order='sequence desc')
387
388     
389
390     
391
392     def _history(self, cr, uid, cases, keyword, history=False, subject=None, email=False, details=None, email_from=False, message_id=False, attach=[], context=None):
393         mailgate_pool = self.pool.get('mailgate.thread')
394         return mailgate_pool.history(cr, uid, cases, keyword, history=history,\
395                                        subject=subject, email=email, \
396                                        details=details, email_from=email_from,\
397                                        message_id=message_id, attach=attach, \
398                                        context=context)
399
400     def case_open(self, cr, uid, ids, *args):
401         """Opens Case
402         @param self: The object pointer
403         @param cr: the current row, from the database cursor,
404         @param uid: the current user’s ID for security checks,
405         @param ids: List of case Ids
406         @param *args: Tuple Value for additional Params
407         """
408
409         cases = self.browse(cr, uid, ids)
410         self._history(cr, uid, cases, _('Open'))
411         for case in cases:
412             data = {'state': 'open', 'active': True}
413             if not case.user_id:
414                 data['user_id'] = uid
415             self.write(cr, uid, case.id, data)
416         self._action(cr, uid, cases, 'open')
417         return True
418
419     def case_close(self, cr, uid, ids, *args):
420         """Closes Case
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
426         """
427         cases = self.browse(cr, uid, ids)
428         cases[0].state # to fill the browse record cache
429         self._history(cr, uid, cases, _('Close'))
430         self.write(cr, uid, ids, {'state': 'done',
431                                   'date_closed': time.strftime('%Y-%m-%d %H:%M:%S'),
432                                   })
433         #
434         # We use the cache of cases to keep the old case state
435         #
436         self._action(cr, uid, cases, 'done')
437         return True
438
439     def case_escalate(self, cr, uid, ids, *args):
440         """Escalates case to top level
441         @param self: The object pointer
442         @param cr: the current row, from the database cursor,
443         @param uid: the current user’s ID for security checks,
444         @param ids: List of case Ids
445         @param *args: Tuple Value for additional Params
446         """
447         cases = self.browse(cr, uid, ids)
448         for case in cases:
449             data = {'active': True}
450
451             if case.section_id.parent_id:
452                 data['section_id'] = case.section_id.parent_id.id
453                 if case.section_id.parent_id.change_responsible:
454                     if case.section_id.parent_id.user_id:
455                         data['user_id'] = case.section_id.parent_id.user_id.id
456             else:
457                 raise osv.except_osv(_('Error !'), _('You can not escalate, You are already at the top level regarding your sales-team category.'))
458             self.write(cr, uid, [case.id], data)
459         cases = self.browse(cr, uid, ids)
460         self._history(cr, uid, cases, _('Escalate'))
461         self._action(cr, uid, cases, 'escalate')
462         return True
463
464     def case_cancel(self, cr, uid, ids, *args):
465         """Cancels Case
466         @param self: The object pointer
467         @param cr: the current row, from the database cursor,
468         @param uid: the current user’s ID for security checks,
469         @param ids: List of case Ids
470         @param *args: Tuple Value for additional Params
471         """
472         cases = self.browse(cr, uid, ids)
473         cases[0].state # to fill the browse record cache
474         self._history(cr, uid, cases, _('Cancel'))
475         self.write(cr, uid, ids, {'state': 'cancel',
476                                   'active': True})
477         self._action(cr, uid, cases, 'cancel')
478         for case in cases:
479             message = _("The case '%s' has been cancelled.") % (case.name,)
480             self.log(cr, uid, case.id, message)
481         return True
482
483     def case_pending(self, cr, uid, ids, *args):
484         """Marks case as pending
485         @param self: The object pointer
486         @param cr: the current row, from the database cursor,
487         @param uid: the current user’s ID for security checks,
488         @param ids: List of case Ids
489         @param *args: Tuple Value for additional Params
490         """
491         cases = self.browse(cr, uid, ids)
492         cases[0].state # to fill the browse record cache
493         self._history(cr, uid, cases, _('Pending'))
494         self.write(cr, uid, ids, {'state': 'pending', 'active': True})
495         self._action(cr, uid, cases, 'pending')
496         return True
497
498     def case_reset(self, cr, uid, ids, *args):
499         """Resets case as draft
500         @param self: The object pointer
501         @param cr: the current row, from the database cursor,
502         @param uid: the current user’s ID for security checks,
503         @param ids: List of case Ids
504         @param *args: Tuple Value for additional Params
505         """
506         state = 'draft' 
507         if 'crm.phonecall' in args:
508             state = 'open' 
509         cases = self.browse(cr, uid, ids)
510         cases[0].state # to fill the browse record cache
511         self._history(cr, uid, cases, _('Draft'))
512         self.write(cr, uid, ids, {'state': state, 'active': True})
513         self._action(cr, uid, cases, state)
514         return True
515
516     def remind_partner(self, cr, uid, ids, context=None, attach=False):
517
518         """
519         @param self: The object pointer
520         @param cr: the current row, from the database cursor,
521         @param uid: the current user’s ID for security checks,
522         @param ids: List of Remind Partner's IDs
523         @param context: A standard dictionary for contextual values
524
525         """
526
527         return self.remind_user(cr, uid, ids, context, attach,
528                 destination=False)
529
530     def remind_user(self, cr, uid, ids, context=None, attach=False, destination=True):
531         """
532         @param self: The object pointer
533         @param cr: the current row, from the database cursor,
534         @param uid: the current user’s ID for security checks,
535         @param ids: List of case's IDs to remind
536         @param context: A standard dictionary for contextual values
537         """
538         for case in self.browse(cr, uid, ids, context=context):
539             if not destination and not case.email_from:
540                 return False
541             if not case.user_id.user_email:
542                 return False
543             
544             if destination and case.section_id.user_id:
545                 case_email = case.section_id.user_id.user_email
546             else:
547                 case_email = case.user_id.user_email
548
549             src = case_email
550             dest = case.user_id
551             body = case.description or ""
552             if case.message_ids:
553                 body = case.message_ids[0].description or ""
554             if not destination:
555                 src, dest = dest, case.email_from
556                 if body and case.user_id.signature:
557                     if body:
558                         body += '\n\n%s' % (case.user_id.signature)
559                     else:
560                         body = '\n\n%s' % (case.user_id.signature)
561
562             body = self.format_body(body)
563
564             attach_to_send = None
565
566             if attach:
567                 attach_ids = self.pool.get('ir.attachment').search(cr, uid, [('res_model', '=', self._name), ('res_id', '=', case.id)])
568                 attach_to_send = self.pool.get('ir.attachment').read(cr, uid, attach_ids, ['datas_fname', 'datas'])
569                 attach_to_send = map(lambda x: (x['datas_fname'], base64.decodestring(x['datas'])), attach_to_send)
570
571                 # Send an email
572             subject = "Reminder: [%s] %s" % (str(case.id), case.name,)
573             tools.email_send(
574                 src,
575                 [dest],
576                 subject,
577                 body,
578                 reply_to=case.section_id.reply_to or '',
579                 openobject_id=str(case.id),
580                 attach=attach_to_send
581             )
582             self._history(cr, uid, [case], _('Send'), history=True, subject=subject, email=dest, details=body, email_from=src)
583
584         return True
585
586     def _check(self, cr, uid, ids=False, context=None):
587         """
588         Function called by the scheduler to process cases for date actions
589         Only works on not done and cancelled cases
590
591         @param self: The object pointer
592         @param cr: the current row, from the database cursor,
593         @param uid: the current user’s ID for security checks,
594         @param context: A standard dictionary for contextual values
595         """
596         cr.execute('select * from crm_case \
597                 where (date_action_last<%s or date_action_last is null) \
598                 and (date_action_next<=%s or date_action_next is null) \
599                 and state not in (\'cancel\',\'done\')',
600                 (time.strftime("%Y-%m-%d %H:%M:%S"),
601                     time.strftime('%Y-%m-%d %H:%M:%S')))
602
603         ids2 = map(lambda x: x[0], cr.fetchall() or [])
604         cases = self.browse(cr, uid, ids2, context=context)
605         return self._action(cr, uid, cases, False, context=context)
606
607     
608
609     def format_body(self, body):
610         return self.pool.get('base.action.rule').format_body(body)
611
612     def format_mail(self, obj, body):
613         return self.pool.get('base.action.rule').format_mail(obj, body)
614
615     def message_followers(self, cr, uid, ids, context=None):
616         """ Get a list of emails of the people following this thread
617         """
618         res = {}
619         for case in self.browse(cr, uid, ids, context=context):
620             l=[]
621             if case.email_cc:
622                 l.append(case.email_cc)
623             if case.user_id and case.user_id.user_email:
624                 l.append(case.user_id.user_email)
625             res[case.id] = l
626         return res
627
628
629 class crm_case_stage(osv.osv):
630     """ Stage of case """
631
632     _name = "crm.case.stage"
633     _description = "Stage of case"
634     _rec_name = 'name'
635     _order = "sequence"
636
637
638
639     def _get_type_value(self, cr, user, context):
640         return [('lead','Lead'),('opportunity','Opportunity')]
641
642
643     _columns = {
644         'name': fields.char('Stage Name', size=64, required=True, translate=True),
645         'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of case stages."),
646         'probability': fields.float('Probability (%)', required=True, help="This percentage depicts the default/average probability of the Case for this stage to be a success"),
647         'on_change': fields.boolean('Change Probability Automatically', \
648                          help="Change Probability on next and previous stages."),
649         'requirements': fields.text('Requirements'),
650         'type': fields.selection(_get_type_value, 'Type', required=True),
651     }
652
653
654     def _find_stage_type(self, cr, uid, context=None):
655         """Finds type of stage according to object.
656         @param self: The object pointer
657         @param cr: the current row, from the database cursor,
658         @param uid: the current user’s ID for security checks,
659         @param context: A standard dictionary for contextual values
660         """
661         type = context and context.get('type', '') or ''
662         return type
663
664     _defaults = {
665         'sequence': lambda *args: 1,
666         'probability': lambda *args: 0.0,
667         'type': _find_stage_type,
668     }
669
670 crm_case_stage()
671
672
673 class crm_case_section(osv.osv):
674     """Sales Team"""
675
676     _name = "crm.case.section"
677     _description = "Sales Teams"
678     _order = "complete_name"
679
680     def get_full_name(self, cr, uid, ids, field_name, arg, context=None):
681         return  dict(self.name_get(cr, uid, ids, context=context))
682
683     _columns = {
684         'name': fields.char('Sales Team', size=64, required=True, translate=True),
685         'complete_name': fields.function(get_full_name, method=True, type='char', size=256, readonly=True, store=True),
686         'code': fields.char('Code', size=8),
687         'active': fields.boolean('Active', help="If the active field is set to "\
688                         "true, it will allow you to hide the sales team without removing it."),
689         'allow_unlink': fields.boolean('Allow Delete', help="Allows to delete non draft cases"),
690         'change_responsible': fields.boolean('Change Responsible', help="Thick this box if you want that on escalation, the responsible of this sale team automatically becomes responsible of the lead/opportunity escaladed"),
691         'user_id': fields.many2one('res.users', 'Responsible User'),
692         'member_ids':fields.many2many('res.users', 'sale_member_rel', 'section_id', 'member_id', 'Team Members'),
693         'reply_to': fields.char('Reply-To', size=64, help="The email address put in the 'Reply-To' of all emails sent by OpenERP about cases in this sales team"),
694         'parent_id': fields.many2one('crm.case.section', 'Parent Team'),
695         'child_ids': fields.one2many('crm.case.section', 'parent_id', 'Child Teams'),
696         'resource_calendar_id': fields.many2one('resource.calendar', "Working Time"),
697         'note': fields.text('Description'),
698         'working_hours': fields.float('Working Hours', digits=(16,2 )),
699         'stage_ids': fields.many2many('crm.case.stage', 'section_stage_rel', 'section_id', 'stage_id', 'Stages'),
700     }
701
702     _defaults = {
703         'active': lambda *a: 1,
704         'allow_unlink': lambda *a: 1,
705     }
706
707     _sql_constraints = [
708         ('code_uniq', 'unique (code)', 'The code of the sales team must be unique !')
709     ]
710
711     def _check_recursion(self, cr, uid, ids, context=None):
712
713         """
714         Checks for recursion level for sales team
715         @param self: The object pointer
716         @param cr: the current row, from the database cursor,
717         @param uid: the current user’s ID for security checks,
718         @param ids: List of Sales team ids
719         """
720         level = 100
721
722         while len(ids):
723             cr.execute('select distinct parent_id from crm_case_section where id IN %s', (tuple(ids),))
724             ids = filter(None, map(lambda x: x[0], cr.fetchall()))
725             if not level:
726                 return False
727             level -= 1
728
729         return True
730
731     _constraints = [
732         (_check_recursion, 'Error ! You cannot create recursive Sales team.', ['parent_id'])
733     ]
734
735     def name_get(self, cr, uid, ids, context=None):
736         """Overrides orm name_get method
737         @param self: The object pointer
738         @param cr: the current row, from the database cursor,
739         @param uid: the current user’s ID for security checks,
740         @param ids: List of sales team ids
741         """
742         if context is None:
743             context = {}
744         if not isinstance(ids, list) : 
745             ids = [ids]
746         res = []
747         if not ids:
748             return res
749         reads = self.read(cr, uid, ids, ['name', 'parent_id'], context)
750
751         for record in reads:
752             name = record['name']
753             if record['parent_id']:
754                 name = record['parent_id'][1] + ' / ' + name
755             res.append((record['id'], name))
756         return res
757
758 crm_case_section()
759
760
761 class crm_case_categ(osv.osv):
762     """ Category of Case """
763     _name = "crm.case.categ"
764     _description = "Category of Case"
765     _columns = {
766         'name': fields.char('Name', size=64, required=True, translate=True),
767         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
768         'object_id': fields.many2one('ir.model', 'Object Name'),
769     }
770
771     def _find_object_id(self, cr, uid, context=None):
772         """Finds id for case object
773         @param self: The object pointer
774         @param cr: the current row, from the database cursor,
775         @param uid: the current user’s ID for security checks,
776         @param context: A standard dictionary for contextual values
777         """
778
779         object_id = context and context.get('object_id', False) or False
780         ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', object_id)])
781         return ids and ids[0]
782
783     _defaults = {
784         'object_id' : _find_object_id
785
786     }
787 crm_case_categ()
788
789
790 class crm_case_stage(osv.osv):
791     _inherit = "crm.case.stage"
792     _columns = {
793         'section_ids':fields.many2many('crm.case.section', 'section_stage_rel', 'stage_id', 'section_id', 'Sections'),
794     }
795
796 crm_case_stage()
797
798
799 class crm_case_resource_type(osv.osv):
800     """ Resource Type of case """
801     _name = "crm.case.resource.type"
802     _description = "Campaign"
803     _rec_name = "name"
804     _columns = {
805         'name': fields.char('Campaign Name', size=64, required=True, translate=True),
806         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
807     }
808 crm_case_resource_type()
809
810
811 def _links_get(self, cr, uid, context=None):
812     """Gets links value for reference field
813     @param self: The object pointer
814     @param cr: the current row, from the database cursor,
815     @param uid: the current user’s ID for security checks,
816     @param context: A standard dictionary for contextual values
817     """
818     obj = self.pool.get('res.request.link')
819     ids = obj.search(cr, uid, [])
820     res = obj.read(cr, uid, ids, ['object', 'name'], context)
821     return [(r['object'], r['name']) for r in res]
822
823 class users(osv.osv):
824     _inherit = 'res.users'
825     _description = "Users"
826     _columns = {
827         'context_section_id': fields.many2one('crm.case.section', 'Sales Team'),
828     }
829
830     def create(self, cr, uid, vals, context=None):
831         res = super(users, self).create(cr, uid, vals, context=context)
832         section_obj=self.pool.get('crm.case.section')
833
834         if vals.get('context_section_id', False):
835             section_obj.write(cr, uid, [vals['context_section_id']], {'member_ids':[(4, res)]}, context)
836         return res
837 users()
838
839
840 class res_partner(osv.osv):
841     _inherit = 'res.partner'
842     _columns = {
843         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
844     }
845 res_partner()
846