[fix] mail: double clicking on post on the chatter
[odoo/odoo.git] / addons / survey / wizard / survey_send_invitation.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 from random import choice
24 import string
25 import os
26 import datetime
27 import socket
28
29 from openerp import addons, netsvc, tools
30 from openerp.osv import fields, osv
31 from openerp.tools.translate import _
32
33
34 class survey_send_invitation(osv.osv_memory):
35     _name = 'survey.send.invitation'
36     _columns = {
37         'partner_ids': fields.many2many('res.partner','survey_res_partner','partner_id',\
38                                 'survey_id', "Answer", required=1),
39         'send_mail': fields.boolean('Send Mail for New User'),
40         'send_mail_existing': fields.boolean('Send Reminder for Existing User'),
41         'mail_subject': fields.char('Subject', size=256),
42         'mail_subject_existing': fields.char('Subject', size=256),
43         'mail_from': fields.char('From', size=256, required=1),
44         'mail': fields.text('Body')
45     }
46
47     _defaults = {
48         'send_mail': lambda *a: 1,
49         'send_mail_existing': lambda *a: 1,
50     }
51
52     def genpasswd(self):
53         chars = string.letters + string.digits
54         return ''.join([choice(chars) for i in range(6)])
55
56     def default_get(self, cr, uid, fields_list, context=None):
57         if context is None:
58             context = {}
59         data = super(survey_send_invitation, self).default_get(cr, uid, fields_list, context)
60         survey_obj = self.pool.get('survey')
61         msg = ""
62         name = ""
63         for sur in survey_obj.browse(cr, uid, context.get('active_ids', []), context=context):
64             name += "\n --> " + sur.title + "\n"
65             if sur.state != 'open':
66                 msg +=  sur.title + "\n"
67             data['mail_subject'] = _("Invitation for %s") % (sur.title)
68             data['mail_subject_existing'] = _("Invitation for %s") % (sur.title)
69             data['mail_from'] = sur.responsible_id.email
70         if msg:
71             raise osv.except_osv(_('Warning!'), _('The following surveys are not in open state: %s') % msg)
72         data['mail'] = _('''
73 Hello %%(name)s, \n\n
74 Would you please spent some of your time to fill-in our survey: \n%s\n
75 You can access this survey with the following parameters:
76  URL: %s
77  Your login ID: %%(login)s\n
78  Your password: %%(passwd)s\n
79 \n\n
80 Thanks,''') % (name, self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url', default='http://localhost:8069', context=context))
81         return data
82
83     def create_report(self, cr, uid, res_ids, report_name=False, file_name=False):
84         if not report_name or not res_ids:
85             return (False, Exception('Report name and Resources ids are required !!!'))
86         try:
87             ret_file_name = addons.get_module_resource('survey', 'report') + file_name + '.pdf'
88             service = netsvc.LocalService(report_name);
89             (result, format) = service.create(cr, uid, res_ids, {}, {})
90             fp = open(ret_file_name, 'wb+');
91             fp.write(result);
92             fp.close();
93         except Exception,e:
94             print 'Exception in create report:',e
95             return (False, str(e))
96         return (True, ret_file_name)
97
98
99     def action_send(self, cr, uid, ids, context=None):
100         if context is None:
101             context = {}
102         record = self.read(cr, uid, ids, [],context=context)
103         survey_ids =  context.get('active_ids', [])
104         record = record and record[0]
105         partner_ids = record['partner_ids']
106         user_ref= self.pool.get('res.users')
107         survey_ref= self.pool.get('survey')
108         mail_message = self.pool.get('mail.message')
109
110         model_data_obj = self.pool.get('ir.model.data')
111         group_id = model_data_obj._get_id(cr, uid, 'base', 'group_survey_user')
112         group_id = model_data_obj.browse(cr, uid, group_id, context=context).res_id
113
114         act_id = self.pool.get('ir.actions.act_window')
115         act_id = act_id.search(cr, uid, [('res_model', '=' , 'survey.name.wiz'), \
116                         ('view_type', '=', 'form')])
117         out = "login,password\n"
118         skipped = 0
119         existing = ""
120         created = ""
121         error = ""
122         new_user = []
123         attachments = {}
124         current_sur = survey_ref.browse(cr, uid, context.get('active_id'), context=context)
125         exist_user = current_sur.invited_user_ids
126         if exist_user:
127             for use in exist_user:
128                 new_user.append(use.id)
129         for id in survey_ref.browse(cr, uid, survey_ids):
130             report = self.create_report(cr, uid, [id.id], 'report.survey.form', id.title)
131             file = open(addons.get_module_resource('survey', 'report') + id.title +".pdf")
132             file_data = ""
133             while 1:
134                 line = file.readline()
135                 file_data += line
136                 if not line:
137                     break
138             file.close()
139             attachments[id.title +".pdf"] = file_data
140             os.remove(addons.get_module_resource('survey', 'report') + id.title +".pdf")
141
142         for partner in self.pool.get('res.partner').browse(cr, uid, partner_ids):
143             if not partner.email:
144                 skipped+= 1
145                 continue
146             user = user_ref.search(cr, uid, [('login', "=", partner.email)])
147             if user:
148                 if user[0] not in new_user:
149                     new_user.append(user[0])
150                 user = user_ref.browse(cr, uid, user[0])
151                 user_ref.write(cr, uid, user.id, {'survey_id':[[6, 0, survey_ids]]})
152                 mail = record['mail']%{'login':partner.email, 'passwd':user.password, \
153                                             'name' : partner.name}
154                 if record['send_mail_existing']:
155                     vals = {
156                         'state': 'outgoing',
157                         'subject': record['mail_subject_existing'],
158                         'body_html': '<pre>%s</pre>' % mail,
159                         'email_to': partner.email,
160                         'email_from': record['mail_from'],
161                     }
162                     self.pool.get('mail.mail').create(cr, uid, vals, context=context)
163                     existing+= "- %s (Login: %s,  Password: %s)\n" % (user.name, partner.email, \
164                                                                       user.password)
165                 continue
166
167             passwd= self.genpasswd()
168             out+= partner.email + ',' + passwd + '\n'
169             mail= record['mail'] % {'login' : partner.email, 'passwd' : passwd, 'name' : partner.name}
170             if record['send_mail']:
171                 vals = {
172                         'state': 'outgoing',
173                         'subject': record['mail_subject'],
174                         'body_html': '<pre>%s</pre>' % mail,
175                         'email_to': partner.email,
176                         'email_from': record['mail_from'],
177                 }
178                 if attachments:
179                     vals['attachment_ids'] = [(0,0,{'name': a_name,
180                                                     'datas_fname': a_name,
181                                                     'datas': str(a_content).encode('base64')})
182                                                     for a_name, a_content in attachments.items()]
183                 ans = self.pool.get('mail.mail').create(cr, uid, vals, context=context)
184                 if ans:
185                     res_data = {'name': partner.name or _('Unknown'),
186                                 'login': partner.email,
187                                 'password': passwd,
188                                 'address_id': partner.id,
189                                 'groups_id': [[6, 0, [group_id]]],
190                                 'action_id': act_id[0],
191                                 'survey_id': [[6, 0, survey_ids]]
192                                }
193                     user = user_ref.create(cr, uid, res_data)
194                     if user not in new_user:
195                         new_user.append(user)
196                     created+= "- %s (Login: %s,  Password: %s)\n" % (partner.name or _('Unknown'),\
197                                                                       partner.email, passwd)
198                 else:
199                     error+= "- %s (Login: %s,  Password: %s)\n" % (partner.name or _('Unknown'),\
200                                                                     partner.email, passwd)
201
202         new_vals = {}
203         new_vals.update({'invited_user_ids':[[6,0,new_user]]})
204         survey_ref.write(cr, uid, context.get('active_id'),new_vals)
205         note= ""
206         if created:
207             note += 'Created users:\n%s\n\n' % (created)
208         if existing:
209             note +='Already existing users:\n%s\n\n' % (existing)
210         if skipped:
211             note += "%d contacts where ignored (an email address is missing).\n\n" % (skipped)
212         if error:
213             note += 'Email not send successfully:\n====================\n%s\n' % (error)
214         context.update({'note' : note})
215         return {
216             'view_type': 'form',
217             "view_mode": 'form',
218             'res_model': 'survey.send.invitation.log',
219             'type': 'ir.actions.act_window',
220             'target': 'new',
221             'context': context
222         }
223 survey_send_invitation()
224
225 class survey_send_invitation_log(osv.osv_memory):
226     _name = 'survey.send.invitation.log'
227     _columns = {
228         'note' : fields.text('Log', readonly=1)
229     }
230
231     def default_get(self, cr, uid, fields_list, context=None):
232         if context is None:
233             context = {}
234         data = super(survey_send_invitation_log, self).default_get(cr, uid, fields_list, context)
235         data['note'] = context.get('note', '')
236         return data
237
238 survey_send_invitation_log()
239
240 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: