[IMP] crm*: update crm modules to new mail module (wip)
[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 python class to be used as common abstract class for CRM business objects"""
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         """Return the first stage with a probability == percent"""
58         stage_pool = self.pool.get('crm.case.stage')
59         if section_id :
60             ids = stage_pool.search(cr, uid, [("probability", '=', percent), ("type", 'like', type), ("section_ids", 'in', [section_id])])
61         else :
62             ids = stage_pool.search(cr, uid, [("probability", '=', percent), ("type", 'like', type)])
63
64         if ids:
65             return ids[0]
66         return False
67
68
69     def _find_first_stage(self, cr, uid, type, section_id):
70         """Returns the first stage that has a sequence number equal or higher than sequence"""
71         stage_pool = self.pool.get('crm.case.stage')
72         if section_id :
73             ids = stage_pool.search(cr, uid, [("sequence", '>', 0), ("type", 'like', type), ("section_ids", 'in', [section_id])])
74         else :
75             ids = stage_pool.search(cr, uid, [("sequence", '>', 0), ("type", 'like', type)])
76
77         if ids:
78             stages = stage_pool.browse(cr, uid, ids)
79             stage_min = stages[0]
80             for stage in stages:
81                 if stage_min.sequence > stage.sequence:
82                     stage_min = stage
83             return stage_min.id
84         else :
85             return False
86
87     def onchange_stage_id(self, cr, uid, ids, stage_id, context={}):
88         if not stage_id:
89             return {'value':{}}
90
91         stage = self.pool.get('crm.case.stage').browse(cr, uid, stage_id, context)
92
93         if not stage.on_change:
94             return {'value':{}}
95         return {'value':{'probability': stage.probability}}
96
97     def _get_default_partner_address(self, cr, uid, context=None):
98         """Gives id of default address for current user"""
99         if context is None:
100             context = {}
101         if not context.get('portal', False):
102             return False
103         return self.pool.get('res.users').browse(cr, uid, uid, context).address_id.id
104
105     def _get_default_partner(self, cr, uid, context=None):
106         """Gives id of partner for current user"""
107         if context is None:
108             context = {}
109         if not context.get('portal', False):
110             return False
111         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
112         if not user.address_id:
113             return False
114         return user.address_id.partner_id.id
115
116     def copy(self, cr, uid, id, default=None, context=None):
117         """Overrides orm copy method to avoid copying messages,
118            as well as date_closed and date_open columns if they
119            exist."""
120         if default is None:
121             default = {}
122
123         default.update({
124                     'message_ids': [],
125                 })
126         if hasattr(self, '_columns'):
127             if self._columns.get('date_closed'):
128                 default.update({
129                     'date_closed': False,
130                 })
131             if self._columns.get('date_open'):
132                 default.update({
133                     'date_open': False
134                 })
135         return super(osv.osv, self).copy(cr, uid, id, default, context=context)
136
137     def _get_default_email(self, cr, uid, context=None):
138         """Gives default email address for current user"""
139         if context and not context.get('portal'):
140             return False
141         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
142         if not user.address_id:
143             return False
144         return user.address_id.email
145
146     def _get_default_user(self, cr, uid, context=None):
147         if context and context.get('portal'):
148             return False
149         return uid
150
151     def _get_section(self, cr, uid, context=None):
152         """Gives section id for current User"""
153         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
154         return user.context_section_id.id or False
155
156     def _find_next_stage(self, cr, uid, stage_list, index, current_seq, stage_pool, context=None):
157         if index + 1 == len(stage_list):
158             return False
159         next_stage_id = stage_list[index + 1]
160         next_stage = stage_pool.browse(cr, uid, next_stage_id, context=context)
161         if not next_stage:
162             return False
163         next_seq = next_stage.sequence
164         if not current_seq :
165             current_seq = 0
166
167         if (abs(next_seq - current_seq)) >= 1:
168             return next_stage
169         else :
170             return self._find_next_stage(cr, uid, stage_list, index + 1, current_seq, stage_pool)
171
172     def stage_change(self, cr, uid, ids, context=None, order='sequence'):
173         stage_pool = self.pool.get('crm.case.stage')
174         stage_type = context and context.get('stage_type','')
175         current_seq = False
176         next_stage_id = False
177
178         for case in self.browse(cr, uid, ids, context=context):
179
180             next_stage = False
181             value = {}
182             if case.section_id.id :
183                 domain = [('type', '=', stage_type),('section_ids', '=', case.section_id.id)]
184             else :
185                 domain = [('type', '=', stage_type)]
186
187
188             stages = stage_pool.search(cr, uid, domain, order=order)
189             current_seq = case.stage_id.sequence
190             index = -1
191             if case.stage_id and case.stage_id.id in stages:
192                 index = stages.index(case.stage_id.id)
193
194             next_stage = self._find_next_stage(cr, uid, stages, index, current_seq, stage_pool, context=context)
195
196             if next_stage:
197                 next_stage_id = next_stage.id
198                 value.update({'stage_id': next_stage.id})
199                 if next_stage.on_change:
200                     value.update({'probability': next_stage.probability})
201             self.write(cr, uid, [case.id], value, context=context)
202
203
204         return next_stage_id #FIXME should return a list of all id
205
206
207     def stage_next(self, cr, uid, ids, context=None):
208         """This function computes next stage for case from its current stage
209            using available stage for that case type
210         """
211
212         return self.stage_change(cr, uid, ids, context=context, order='sequence')
213
214     def stage_previous(self, cr, uid, ids, context=None):
215         """This function computes previous stage for case from its current stage
216            using available stage for that case type
217         """
218         return self.stage_change(cr, uid, ids, context=context, order='sequence desc')
219
220     def onchange_partner_id(self, cr, uid, ids, part, email=False):
221         """This function returns value of partner address based on partner
222
223            :param part: Partner id
224            :param email: unused
225         """
226         data={}
227         if  part:
228             addr = self.pool.get('res.partner').address_get(cr, uid, [part], ['contact'])
229             data = {'partner_address_id': addr['contact']}
230             data.update(self.onchange_partner_address_id(cr, uid, ids, addr['contact'])['value'])
231         return {'value': data}
232
233     def onchange_partner_address_id(self, cr, uid, ids, add, email=False):
234         """Set partner email and phone based on selected address
235
236            :param add: selected address id
237            :param email: unused
238         """
239         if not add:
240             return {'value': {'email_from': False}}
241         address = self.pool.get('res.partner.address').browse(cr, uid, add)
242         if address.email:
243             return {'value': {'email_from': address.email, 'phone': address.phone}}
244         else:
245             return {'value': {'phone': address.phone}}
246
247     def case_open(self, cr, uid, ids, *args):
248         """Opens Case"""
249         cases = self.browse(cr, uid, ids)
250         self.history(cr, uid, cases, _('Open'))
251         for case in cases:
252             data = {'state': 'open', 'active': True}
253             if not case.user_id:
254                 data['user_id'] = uid
255             self.write(cr, uid, case.id, data)
256         self._action(cr, uid, cases, 'open')
257         return True
258
259     def case_close(self, cr, uid, ids, *args):
260         """Closes Case"""
261         cases = self.browse(cr, uid, ids)
262         cases[0].state # to fill the browse record cache
263         self.history(cr, uid, cases, _('Close'))
264         self.write(cr, uid, ids, {'state': 'done',
265                                   'date_closed': time.strftime('%Y-%m-%d %H:%M:%S'),
266                                   })
267         #
268         # We use the cache of cases to keep the old case state
269         #
270         self._action(cr, uid, cases, 'done')
271         return True
272
273     def case_escalate(self, cr, uid, ids, *args):
274         """Escalates case to parent level"""
275         cases = self.browse(cr, uid, ids)
276         for case in cases:
277             data = {'active': True}
278             if case.section_id.parent_id:
279                 data['section_id'] = case.section_id.parent_id.id
280                 if case.section_id.parent_id.change_responsible:
281                     if case.section_id.parent_id.user_id:
282                         data['user_id'] = case.section_id.parent_id.user_id.id
283             else:
284                 raise osv.except_osv(_('Error !'), _('You can not escalate, You are already at the top level regarding your sales-team category.'))
285             self.write(cr, uid, [case.id], data)
286         cases = self.browse(cr, uid, ids)
287         self.history(cr, uid, cases, _('Escalate'))
288         self._action(cr, uid, cases, 'escalate')
289         return True
290
291     def case_cancel(self, cr, uid, ids, *args):
292         """Cancels Case"""
293         cases = self.browse(cr, uid, ids)
294         cases[0].state # to fill the browse record cache
295         self.history(cr, uid, cases, _('Cancel'))
296         self.write(cr, uid, ids, {'state': 'cancel',
297                                   'active': True})
298         self._action(cr, uid, cases, 'cancel')
299         for case in cases:
300             message = _("The case '%s' has been cancelled.") % (case.name,)
301             self.log(cr, uid, case.id, message)
302         return True
303
304     def case_pending(self, cr, uid, ids, *args):
305         """Marks case as pending"""
306         cases = self.browse(cr, uid, ids)
307         cases[0].state # to fill the browse record cache
308         self.history(cr, uid, cases, _('Pending'))
309         self.write(cr, uid, ids, {'state': 'pending', 'active': True})
310         self._action(cr, uid, cases, 'pending')
311         return True
312
313     def case_reset(self, cr, uid, ids, *args):
314         """Resets case as draft"""
315         cases = self.browse(cr, uid, ids)
316         cases[0].state # to fill the browse record cache
317         self.history(cr, uid, cases, _('Draft'))
318         self.write(cr, uid, ids, {'state': 'draft', 'active': True})
319         self._action(cr, uid, cases, 'draft')
320         return True
321
322     def remind_partner(self, cr, uid, ids, context=None, attach=False):
323         return self.remind_user(cr, uid, ids, context, attach,
324                 destination=False)
325
326     def remind_user(self, cr, uid, ids, context=None, attach=False, destination=True):
327         mail_message = self.pool.get('mail.message')
328         for case in self.browse(cr, uid, ids, context=context):
329             if not destination and not case.email_from:
330                 raise osv.except_osv(_('Error!'), ("Partner Email is not specified in Case"))
331             if not case.user_id.user_email:
332                raise osv.except_osv(_('Error!'), ("User Email is not specified in Case"))
333
334             if destination and case.section_id.user_id:
335                 case_email = case.section_id.user_id.user_email
336             else:
337                 case_email = case.user_id.user_email
338
339             src = case_email
340             dest = case.user_id
341             body = case.description or ""
342             if case.message_ids:
343                 body = case.message_ids[0].description or ""
344             if not destination:
345                 src, dest = dest, case.email_from
346                 if body and case.user_id.signature:
347                     if body:
348                         body += '\n\n%s' % (case.user_id.signature)
349                     else:
350                         body = '\n\n%s' % (case.user_id.signature)
351
352             body = self.format_body(body)
353
354             attach_to_send = {}
355
356             if attach:
357                 attach_ids = self.pool.get('ir.attachment').search(cr, uid, [('res_model', '=', self._name), ('res_id', '=', case.id)])
358                 attach_to_send = self.pool.get('ir.attachment').read(cr, uid, attach_ids, ['datas_fname', 'datas'])
359                 attach_to_send = dict(map(lambda x: (x['datas_fname'], base64.decodestring(x['datas'])), attach_to_send))
360
361             # Send an email
362             subject = "Reminder: [%s] %s" % (str(case.id), case.name, )
363             mail_message.schedule_with_attach(cr, uid,
364                 src,
365                 [dest],
366                 subject,
367                 body,
368                 model='crm.case',
369                 reply_to=case.section_id.reply_to,
370                 res_id=str(case.id),
371                 attachments=attach_to_send
372             )
373         return True
374
375     def _check(self, cr, uid, ids=False, context=None):
376         """Function called by the scheduler to process cases for date actions
377            Only works on not done and cancelled cases
378         """
379         cr.execute('select * from crm_case \
380                 where (date_action_last<%s or date_action_last is null) \
381                 and (date_action_next<=%s or date_action_next is null) \
382                 and state not in (\'cancel\',\'done\')',
383                 (time.strftime("%Y-%m-%d %H:%M:%S"),
384                     time.strftime('%Y-%m-%d %H:%M:%S')))
385
386         ids2 = map(lambda x: x[0], cr.fetchall() or [])
387         cases = self.browse(cr, uid, ids2, context=context)
388         return self._action(cr, uid, cases, False, context=context)
389
390     def _action(self, cr, uid, cases, state_to, scrit=None, context=None):
391         if context is None:
392             context = {}
393         context['state_to'] = state_to
394         rule_obj = self.pool.get('base.action.rule')
395         model_obj = self.pool.get('ir.model')
396         model_ids = model_obj.search(cr, uid, [('model','=',self._name)])
397         rule_ids = rule_obj.search(cr, uid, [('model_id','=',model_ids[0])])
398         return rule_obj._action(cr, uid, rule_ids, cases, scrit=scrit, context=context)
399
400     def format_body(self, body):
401         return self.pool.get('base.action.rule').format_body(body)
402
403     def format_mail(self, obj, body):
404         return self.pool.get('base.action.rule').format_mail(obj, body)
405
406     def thread_followers(self, cr, uid, ids, context=None):
407         res = {}
408         for case in self.browse(cr, uid, ids, context=context):
409             l=[]
410             if case.email_cc:
411                 l.append(case.email_cc)
412             if case.user_id and case.user_id.user_email:
413                 l.append(case.user_id.user_email)
414             res[case.id] = l
415         return res
416
417
418 class crm_case_stage(osv.osv):
419     """Stage of case"""
420
421     _name = "crm.case.stage"
422     _description = "Stage of case"
423     _rec_name = 'name'
424     _order = "sequence"
425
426     def _get_type_value(self, cr, user, context):
427         return [('lead','Lead'),('opportunity','Opportunity')]
428
429     _columns = {
430         'name': fields.char('Stage Name', size=64, required=True, translate=True),
431         'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of case stages."),
432         'probability': fields.float('Probability (%)', required=True, help="This percentage depicts the default/average probability of the Case for this stage to be a success"),
433         'on_change': fields.boolean('Change Probability Automatically', \
434                          help="Change Probability on next and previous stages."),
435         'requirements': fields.text('Requirements'),
436         'type': fields.selection(_get_type_value, 'Type', required=True),
437     }
438
439     def _find_stage_type(self, cr, uid, context=None):
440         """Finds type of stage according to record"""
441         type = context and context.get('type', '') or ''
442         return type
443
444     _defaults = {
445         'sequence': lambda *args: 1,
446         'probability': lambda *args: 0.0,
447         'type': _find_stage_type,
448     }
449
450
451 class crm_case_section(osv.osv):
452     """Sales Team"""
453
454     _name = "crm.case.section"
455     _description = "Sales Teams"
456     _order = "complete_name"
457
458     def get_full_name(self, cr, uid, ids, field_name, arg, context=None):
459         return  dict(self.name_get(cr, uid, ids, context=context))
460
461     _columns = {
462         'name': fields.char('Sales Team', size=64, required=True, translate=True),
463         'complete_name': fields.function(get_full_name, method=True, type='char', size=256, readonly=True, store=True),
464         'code': fields.char('Code', size=8),
465         'active': fields.boolean('Active', help="If the active field is set to "\
466                         "true, it will allow you to hide the sales team without removing it."),
467         'allow_unlink': fields.boolean('Allow Delete', help="Allows to delete non draft cases"),
468         '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"),
469         'user_id': fields.many2one('res.users', 'Responsible User'),
470         'member_ids':fields.many2many('res.users', 'sale_member_rel', 'section_id', 'member_id', 'Team Members'),
471         '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"),
472         'parent_id': fields.many2one('crm.case.section', 'Parent Team'),
473         'child_ids': fields.one2many('crm.case.section', 'parent_id', 'Child Teams'),
474         'resource_calendar_id': fields.many2one('resource.calendar', "Working Time"),
475         'note': fields.text('Description'),
476         'working_hours': fields.float('Working Hours', digits=(16,2 )),
477         'stage_ids': fields.many2many('crm.case.stage', 'section_stage_rel', 'section_id', 'stage_id', 'Stages'),
478     }
479
480     _defaults = {
481         'active': lambda *a: 1,
482         'allow_unlink': lambda *a: 1,
483     }
484
485     _sql_constraints = [
486         ('code_uniq', 'unique (code)', 'The code of the sales team must be unique !')
487     ]
488
489     _constraints = [
490         (osv.osv._check_recursion, 'Error ! You cannot create recursive Sales team.', ['parent_id'])
491     ]
492
493     def name_get(self, cr, uid, ids, context=None):
494         """Overrides orm name_get method"""
495         if not isinstance(ids, list) : 
496             ids = [ids]
497         res = []
498         if not ids:
499             return res
500         reads = self.read(cr, uid, ids, ['name', 'parent_id'], context)
501
502         for record in reads:
503             name = record['name']
504             if record['parent_id']:
505                 name = record['parent_id'][1] + ' / ' + name
506             res.append((record['id'], name))
507         return res
508
509
510 class crm_case_categ(osv.osv):
511     """Category of Case"""
512     _name = "crm.case.categ"
513     _description = "Category of Case"
514     _columns = {
515         'name': fields.char('Name', size=64, required=True, translate=True),
516         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
517         'object_id': fields.many2one('ir.model', 'Object Name'),
518     }
519
520     def _find_object_id(self, cr, uid, context=None):
521         """Finds id for case object"""
522         object_id = context and context.get('object_id', False) or False
523         ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', object_id)])
524         return ids and ids[0]
525
526     _defaults = {
527         'object_id' : _find_object_id
528     }
529
530 class crm_case_stage(osv.osv):
531     _inherit = "crm.case.stage"
532     _columns = {
533         'section_ids':fields.many2many('crm.case.section', 'section_stage_rel', 'stage_id', 'section_id', 'Sections'),
534     }
535
536 class crm_case_resource_type(osv.osv):
537     """Resource Type of case"""
538     _name = "crm.case.resource.type"
539     _description = "Campaign"
540     _rec_name = "name"
541     _columns = {
542         'name': fields.char('Campaign Name', size=64, required=True, translate=True),
543         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
544     }
545
546 def _links_get(self, cr, uid, context=None):
547     """Gets links value for reference field"""
548     obj = self.pool.get('res.request.link')
549     ids = obj.search(cr, uid, [])
550     res = obj.read(cr, uid, ids, ['object', 'name'], context)
551     return [(r['object'], r['name']) for r in res]
552
553 class users(osv.osv):
554     _inherit = 'res.users'
555     _description = "Users"
556     _columns = {
557         'context_section_id': fields.many2one('crm.case.section', 'Sales Team'),
558     }
559
560     def create(self, cr, uid, vals, context=None):
561         res = super(users, self).create(cr, uid, vals, context=context)
562         section_obj=self.pool.get('crm.case.section')
563         if vals.get('context_section_id'):
564             section_obj.write(cr, uid, [vals['context_section_id']], {'member_ids':[(4, res)]}, context)
565         return res
566
567
568 class res_partner(osv.osv):
569     _inherit = 'res.partner'
570     _columns = {
571         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
572     }