[IMP] mail: improvements in email message form view and removed msg.get_unixfrom...
[odoo/odoo.git] / addons / crm_helpdesk / crm_helpdesk.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 from crm import crm
23 from osv import fields, osv
24 import time
25 from crm import wizard
26 import binascii
27 import tools
28
29 wizard.email_compose_message.email_model.append('crm.helpdesk')
30 CRM_HELPDESK_STATES = (
31     crm.AVAILABLE_STATES[2][0], # Cancelled
32     crm.AVAILABLE_STATES[3][0], # Done
33     crm.AVAILABLE_STATES[4][0], # Pending
34 )
35
36 class crm_helpdesk(crm.crm_case, osv.osv):
37     """ Helpdesk Cases """
38
39     _name = "crm.helpdesk"
40     _description = "Helpdesk"
41     _order = "id desc"
42     _inherit = ['email.thread']
43     _columns = {
44             'id': fields.integer('ID', readonly=True),
45             'name': fields.char('Name', size=128, required=True),
46             'active': fields.boolean('Active', required=False),
47             'date_action_last': fields.datetime('Last Action', readonly=1),
48             'date_action_next': fields.datetime('Next Action', readonly=1),
49             'description': fields.text('Description'),
50             'create_date': fields.datetime('Creation Date' , readonly=True),
51             'write_date': fields.datetime('Update Date' , readonly=True),
52             'date_deadline': fields.date('Deadline'),
53             'user_id': fields.many2one('res.users', 'Responsible'),
54             'section_id': fields.many2one('crm.case.section', 'Sales Team', \
55                             select=True, help='Sales team to which Case belongs to.\
56                                  Define Responsible user and Email account for mail gateway.'),
57             'company_id': fields.many2one('res.company', 'Company'),
58             'date_closed': fields.datetime('Closed', readonly=True),
59             'partner_id': fields.many2one('res.partner', 'Partner'),
60             'partner_address_id': fields.many2one('res.partner.address', 'Partner Contact', \
61                                  domain="[('partner_id','=',partner_id)]"),
62             'email_cc': fields.text('Watchers Emails', size=252 , help="These email addresses will be added to the CC field of all inbound and outbound emails for this record before being sent. Separate multiple email addresses with a comma"),
63             'email_from': fields.char('Email', size=128, help="These people will receive email."),
64             'date': fields.datetime('Date'),
65             'ref' : fields.reference('Reference', selection=crm._links_get, size=128),
66             'ref2' : fields.reference('Reference 2', selection=crm._links_get, size=128),
67             'canal_id': fields.many2one('res.partner.canal', 'Channel', \
68                             help="The channels represent the different communication \
69  modes available with the customer."),
70             'planned_revenue': fields.float('Planned Revenue'),
71             'planned_cost': fields.float('Planned Costs'),
72             'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority'),
73             'probability': fields.float('Probability (%)'),
74             'categ_id': fields.many2one('crm.case.categ', 'Category', \
75                             domain="[('section_id','=',section_id),\
76                             ('object_id.model', '=', 'crm.helpdesk')]"),
77             'duration': fields.float('Duration', states={'done': [('readonly', True)]}),
78             'state': fields.selection(crm.AVAILABLE_STATES, 'State', size=16, readonly=True,
79                                   help='The state is set to \'Draft\', when a case is created.\
80                                   \nIf the case is in progress the state is set to \'Open\'.\
81                                   \nWhen the case is over, the state is set to \'Done\'.\
82                                   \nIf the case needs to be reviewed then the state is set to \'Pending\'.'),
83             'message_ids': fields.one2many('email.message', 'res_id', 'Messages', domain=[('model','=',_name)]),
84     }
85
86     _defaults = {
87         'active': lambda *a: 1,
88         'user_id': crm.crm_case._get_default_user,
89         'partner_id': crm.crm_case._get_default_partner,
90         'partner_address_id': crm.crm_case._get_default_partner_address,
91         'email_from': crm.crm_case. _get_default_email,
92         'state': lambda *a: 'draft',
93         'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
94         'section_id': crm.crm_case. _get_section,
95         'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid, 'crm.helpdesk', context=c),
96         'priority': lambda *a: crm.AVAILABLE_PRIORITIES[2][0],
97     }
98
99     def message_new(self, cr, uid, msg, context=None):
100         """
101         Automatically calls when new email message arrives
102
103         @param self: The object pointer
104         @param cr: the current row, from the database cursor,
105         @param uid: the current user’s ID for security checks
106         @param msg: dictionary object to contain email message data
107         """
108         thread_pool = self.pool.get('email.thread')
109
110         subject = msg.get('subject')
111         body = msg.get('body')
112         msg_from = msg.get('from')
113         priority = msg.get('priority')
114
115         vals = {
116             'name': subject,
117             'email_from': msg_from,
118             'email_cc': msg.get('cc'),
119             'description': body,
120             'user_id': False,
121         }
122         if msg.get('priority', False):
123             vals['priority'] = priority
124
125         res = thread_pool.get_partner(cr, uid, msg.get('from', False))
126         if res:
127             vals.update(res)
128
129         res = self.create(cr, uid, vals, context)
130         attachents = msg.get('attachments', [])
131         for attactment in attachents or []:
132             data_attach = {
133                 'name': attactment,
134                 'datas':binascii.b2a_base64(str(attachents.get(attactment))),
135                 'datas_fname': attactment,
136                 'description': 'Mail attachment',
137                 'res_model': self._name,
138                 'res_id': res,
139             }
140             self.pool.get('ir.attachment').create(cr, uid, data_attach)
141
142         return res
143
144     def message_update(self, cr, uid, ids, vals={}, msg="", default_act='pending', context=None):
145         """
146         @param self: The object pointer
147         @param cr: the current row, from the database cursor,
148         @param uid: the current user’s ID for security checks,
149         @param ids: List of update mail’s IDs
150         """
151         if isinstance(ids, (str, int, long)):
152             ids = [ids]
153
154         if msg.get('priority') in dict(crm.AVAILABLE_PRIORITIES):
155             vals['priority'] = msg.get('priority')
156
157         maps = {
158             'cost':'planned_cost',
159             'revenue': 'planned_revenue',
160             'probability':'probability'
161         }
162         vls = {}
163         for line in msg['body'].split('\n'):
164             line = line.strip()
165             res = tools.misc.command_re.match(line)
166             if res and maps.get(res.group(1).lower()):
167                 key = maps.get(res.group(1).lower())
168                 vls[key] = res.group(2).lower()
169         vals.update(vls)
170
171         # Unfortunately the API is based on lists
172         # but we want to update the state based on the
173         # previous state, so we have to loop:
174         for case in self.browse(cr, uid, ids, context=context):
175             values = dict(vals)
176             if case.state in CRM_HELPDESK_STATES:
177                 values.update(state=crm.AVAILABLE_STATES[1][0]) #re-open
178             res = self.write(cr, uid, [case.id], values, context=context)
179         return res
180
181 crm_helpdesk()
182
183 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
184