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