[IMP] email: email cleanup
[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         """
107         thread_pool = self.pool.get('email.thread')
108
109         subject = msg.get('subject')
110         body = msg.get('body')
111         msg_from = msg.get('from')
112         priority = msg.get('priority')
113
114         vals = {
115             'name': subject,
116             'email_from': msg_from,
117             'email_cc': msg.get('cc'),
118             'description': body,
119             'user_id': False,
120         }
121         if msg.get('priority', False):
122             vals['priority'] = priority
123
124         res = thread_pool.get_partner(cr, uid, msg.get('from') or msg.get_unixfrom())
125         if res:
126             vals.update(res)
127
128         res = self.create(cr, uid, vals, context)
129         attachents = msg.get('attachments', [])
130         for attactment in attachents or []:
131             data_attach = {
132                 'name': attactment,
133                 'datas':binascii.b2a_base64(str(attachents.get(attactment))),
134                 'datas_fname': attactment,
135                 'description': 'Mail attachment',
136                 'res_model': self._name,
137                 'res_id': res,
138             }
139             self.pool.get('ir.attachment').create(cr, uid, data_attach)
140
141         return res
142
143     def message_update(self, cr, uid, ids, vals={}, msg="", default_act='pending', context=None):
144         """
145         @param self: The object pointer
146         @param cr: the current row, from the database cursor,
147         @param uid: the current user’s ID for security checks,
148         @param ids: List of update mail’s IDs
149         """
150         if isinstance(ids, (str, int, long)):
151             ids = [ids]
152
153         if msg.get('priority') in dict(crm.AVAILABLE_PRIORITIES):
154             vals['priority'] = msg.get('priority')
155
156         maps = {
157             'cost':'planned_cost',
158             'revenue': 'planned_revenue',
159             'probability':'probability'
160         }
161         vls = {}
162         for line in msg['body'].split('\n'):
163             line = line.strip()
164             res = tools.misc.command_re.match(line)
165             if res and maps.get(res.group(1).lower()):
166                 key = maps.get(res.group(1).lower())
167                 vls[key] = res.group(2).lower()
168         vals.update(vls)
169
170         # Unfortunately the API is based on lists
171         # but we want to update the state based on the
172         # previous state, so we have to loop:
173         for case in self.browse(cr, uid, ids, context=context):
174             values = dict(vals)
175             if case.state in CRM_HELPDESK_STATES:
176                 values.update(state=crm.AVAILABLE_STATES[1][0]) #re-open
177             res = self.write(cr, uid, [case.id], values, context=context)
178         return res
179
180     def msg_send(self, cr, uid, id, *args, **argv):
181
182         """ Send The Message
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 ids: List of email’s IDs
187             @param *args: Return Tuple Value
188             @param **args: Return Dictionary of Keyword Value
189         """
190         return True
191
192 crm_helpdesk()
193
194 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
195