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