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