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