~school-dev-team/school-base-openerp-module/school-openerp-v2.0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
# -*- encoding: utf-8 -*-
##############################################################################
#
#    school module for OpenERP
#    Copyright (C) 2010 Tecnoba S.L. (http://www.tecnoba.com)
#       Pere Ramon Erro Mas <pereerro@tecnoba.com> All Rights Reserved.
#
#    This file is a part of school modules
#
#    school OpenERP module is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    school OpenERP module is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

import time
from osv import osv, fields
import collections
import netsvc
from tools.translate import _
import base64
import re
import tempfile
from datetime import datetime
import shutil
import zipfile
import cStringIO

def normal_unicode(string):
    return type(string) == str and string.decode('utf-8') or type(string) == unicode and string or ''    

def total_seconds(timedelta_obj):
    return timedelta_obj.days * 3600 * 24 + timedelta_obj.seconds

class wizard_communication(osv.osv_memory):
    _name = 'contact.states.comms'
    
    def _email_contact_data(self, cr, uid, ids, field_name, arg, context = None):
        ret = {}
        for item in self.browse(cr, uid, ids):
            first_address = item.partner_id.address and item.partner_id.address[0] or False
            ret[item.id] = item.type == 'email' and (first_address and first_address.email or item.partner_id.email) or False
        return ret
        
    def _recipient_number_data(self, cr, uid, ids, field_name, arg, context = None):
        ret = dict.fromkeys(ids, False)
        for item in self.browse(cr, uid, ids):
            first_address = item.partner_id.address and item.partner_id.address[0] or False
            ret[item.id] = (first_address and first_address.mobile) or False
        return ret
        
    def _address_contact_data(self, cr, uid, ids, field_name, arg, context = None):
        ret = {}
        for item in self.browse(cr, uid, ids):
            address = item.partner_id.address
            ret[item.id] = ''
            if item.type == 'postmail' and address:
                first_address = address[0]
                ret[item.id] = first_address and self.pool.get('crm.postmail')._get_address(cr, uid, first_address.id, context = context) or False
        return ret
    
    def _generate_content(self, cr, uid, ids, field_name, arg, context = None):
        ret = {}
        items = self.browse(cr, uid, ids, context = context)
        wizards = collections.defaultdict(set)
        annos = collections.defaultdict(list)
        sums = collections.defaultdict(float)
        num_annos = collections.defaultdict(int)
        for item in items:
            wizards[item.wizard_id].add( item )
        for wizard,item_set in wizards.items():
            state_ids = [x.id for x in wizard.sets_id.state_ids]
            contact_ids = len(item_set)>0 and [x.contact_id.id for x in list(item_set)] or [0]
            sr_ids = self.pool.get('contact.state_range2').search(cr, uid, [
                ('lstate.id','in',state_ids),
                ('contact_id','in',contact_ids),
                ('datetime_from','<',wizard.date_to),
                ('datetime_to','>',wizard.date_from),
                ])
            for state in self.pool.get('contact.state_range2').browse(cr, uid, sr_ids, context = context):
                td = datetime.strptime(min(wizard.date_to+' 23:59:59',state.datetime_to),'%Y-%m-%d %H:%M:%S') - datetime.strptime(max(wizard.date_from+' 00:00:00',state.datetime_from),'%Y-%m-%d %H:%M:%S')
                if total_seconds(td) < 0:
                    raise 'Error'
                sums[wizard.id,state.contact_id.id] += float(total_seconds(td)) / 3600
                for anno in state.annotation_ids:
                    if wizard.date_from+' 00:00:00' < anno.valid_to and \
                       wizard.date_to+' 23:59:59' > anno.valid_from :
                        num_annos[wizard.id,state.contact_id.id] += 1
                        annos[wizard.id,state.contact_id.id].append({
                            'anno': anno.anno_type.name,
                            'from': max(wizard.date_from,state.datetime_from,anno.valid_from),
                            'to': min(wizard.date_to,state.datetime_to,anno.valid_to),   })
        for item in items:
            vals = {
                        'contact_name': item.contact_id.first_name + ' ' + item.contact_id.name,
                        'partner_name': item.partner_id.name,
                        'date_from' : datetime.strptime(item.wizard_id.date_from,'%Y-%m-%d').strftime('%d/%m/%Y'),
                        'date_to' : datetime.strptime(item.wizard_id.date_to,'%Y-%m-%d').strftime('%d/%m/%Y'),
                        'time_all_states' : sums[(item.wizard_id.id,item.contact_id.id)],
                        'num_annotations' : num_annos[(item.wizard_id.id,item.contact_id.id)],
                        'range_states' : "\n" + "\n".join([_("%(anno)s - from %(from)s to %(to)s") % x for x in annos[(item.wizard_id.id,item.contact_id.id)]]),
                    }
            if annos[(item.wizard_id.id,item.contact_id.id)] \
                and item.wizard_id.sets_id.min_state_hours <= sums[(item.wizard_id.id,item.contact_id.id)]:
                    if field_name == 'default_text':
                        ret[item.id] = wizard.sets_id.intro and wizard.sets_id.intro % vals or ''
                    else:
                        ret[item.id] = ''
            else:
                if field_name == 'default_text':
                    ret[item.id] = wizard.sets_id.intro_none and wizard.sets_id.intro_none % vals or ''
                else:
                    ret[item.id] = ''
        return ret
            
    def _generate_content_sms(self, cr, uid, ids, field_name, arg, context = None):
        ret = {}
        items = self.browse(cr, uid, ids, context = context)
        wizards = collections.defaultdict(set)
        annos = collections.defaultdict(list)
        sums = collections.defaultdict(float)
        num_annos = collections.defaultdict(int)
        for item in items:
            wizards[item.wizard_id].add( item )
        for wizard,item_set in wizards.items():
            state_ids = [x.id for x in wizard.sets_id.state_ids]
            contact_ids = len(item_set)>0 and [x.contact_id.id for x in list(item_set)] or [0]
            sr_ids = self.pool.get('contact.state_range2').search(cr, uid, [
                ('lstate.id','in',state_ids),
                ('contact_id','in',contact_ids),
                ('datetime_from','<',wizard.date_to),
                ('datetime_to','>',wizard.date_from),
                ])
            for state in self.pool.get('contact.state_range2').browse(cr, uid, sr_ids, context = context):
                td = datetime.strptime(min(wizard.date_to+' 23:59:59',state.datetime_to),'%Y-%m-%d %H:%M:%S') - datetime.strptime(max(wizard.date_from+' 00:00:00',state.datetime_from),'%Y-%m-%d %H:%M:%S')
                if total_seconds(td) < 0:
                    raise 'Error'
                sums[wizard.id,state.contact_id.id] += float(total_seconds(td)) / 3600
                for anno in state.annotation_ids:
                    if wizard.date_from+' 00:00:00' < anno.valid_to and \
                       wizard.date_to+' 23:59:59' > anno.valid_from :
                        num_annos[wizard.id,state.contact_id.id] += 1
                        annos[wizard.id,state.contact_id.id].append({
                            'anno': anno.anno_type.name,
                            'from': max(wizard.date_from,state.datetime_from,anno.valid_from),
                            'to': min(wizard.date_to,state.datetime_to,anno.valid_to),   })
        for item in items:
            vals = {
                        'contact_name': item.contact_id.first_name + ' ' + item.contact_id.name,
                        'partner_name': item.partner_id.name,
                        'date_from' : datetime.strptime(item.wizard_id.date_from,'%Y-%m-%d').strftime('%d/%m/%Y'),
                        'date_to' : datetime.strptime(item.wizard_id.date_to,'%Y-%m-%d').strftime('%d/%m/%Y'),
                        'time_all_states' : sums[(item.wizard_id.id,item.contact_id.id)],
                        'num_annotations' : num_annos[(item.wizard_id.id,item.contact_id.id)],
                        'range_states' : "\n" + "\n".join([_("%(anno)s - from %(from)s to %(to)s") % x for x in annos[(item.wizard_id.id,item.contact_id.id)]]),
                    }
            if annos[(item.wizard_id.id,item.contact_id.id)] \
                and item.wizard_id.sets_id.min_state_hours_sms <= sums[(item.wizard_id.id,item.contact_id.id)]:
                    if field_name == 'default_sms_text':
                        ret[item.id] = wizard.sets_id.intro_sms and wizard.sets_id.intro_sms % vals or ''
                    else:
                        ret[item.id] = ''
            else:
                if field_name == 'default_sms_text':
                    ret[item.id] = wizard.sets_id.intro_none_sms and wizard.sets_id.intro_none_sms % vals or ''
                else:
                    ret[item.id] = ''
        return ret
            
    def _get_time_all_states(self, cr, uid, ids, field_name, arg, context = None):
        ret = {}
        items = self.browse(cr, uid, ids, context = context)
        wizards = collections.defaultdict(set)
        sums = collections.defaultdict(float)
        for item in items:
            wizards[item.wizard_id].add( item )
        for wizard,item_set in wizards.items():
            state_ids = [x.id for x in wizard.sets_id.state_ids]
            contact_ids = len(item_set)>0 and [x.contact_id.id for x in list(item_set)] or [0]
            sr_ids = self.pool.get('contact.state_range2').search(cr, uid, [
                ('lstate.id','in',state_ids),
                ('contact_id','in',contact_ids),
                ('datetime_from','<',wizard.date_to),
                ('datetime_to','>',wizard.date_from),
                ])
            for state in self.pool.get('contact.state_range2').browse(cr, uid, sr_ids, context = context):
                td = datetime.strptime(min(wizard.date_to+' 23:59:59',state.datetime_to),'%Y-%m-%d %H:%M:%S') - datetime.strptime(max(wizard.date_from+' 00:00:00',state.datetime_from),'%Y-%m-%d %H:%M:%S')
                if total_seconds(td) < 0:
                    raise 'Error'
                sums[wizard.id,state.contact_id.id] += float(total_seconds(td)) / 3600
        for item in items:
            ret[item.id] = sums.get((item.wizard_id.id,item.contact_id.id),0)
        return ret
            
    def _generate_subject(self, cr, uid, ids, field_name, arg, context = None):
        ret = {}
        for item in self.browse(cr, uid, ids, context = context):
            ret[item.id] = item.wizard_id.sets_id.subject % {'contact_name': item.contact_id.name, 'partner_name': item.partner_id.name,}
        return ret
            
    def _is_to_send(self, cr, uid, ids, field_name, arg, context = None):
        ret = {}
        for item in self.browse(cr, uid, ids, context = context):
            ret[item.id] = ( item.type != 'sms' and item.time_all_states >= item.wizard_id.sets_id.min_state_hours )
        return ret
    
    def _is_to_send_sms(self, cr, uid, ids, field_name, arg, context = None):
        ret = {}
        for item in self.browse(cr, uid, ids, context = context):
            ret[item.id] = ( (item.wizard_id.sets_id.sms_option == 'both' or item.type == 'sms') and item.time_all_states >= item.wizard_id.sets_id.min_state_hours_sms )
        return ret
    
    _columns = {
        'wizard_id' : fields.many2one('contact.states.send_communications',string='Wizard',),
        'contact_id' : fields.many2one('res.partner.contact',string = 'Contacts',),        
        'partner_id' : fields.many2one('res.partner',string='Partner',),
        'type' : fields.selection([('postmail','Post Mail'),('email','E-mail'),('sms','SMS')],string='Type',),
        'email' : fields.char('Email', size=200),
        'default_email' : fields.function(_email_contact_data, type='char', size=200, method=True, string='Default Email',),
        'address' : fields.text('Address'),
        'default_address' : fields.function(_address_contact_data, type='text', method=True, string='Default Address',),
        'recipient_number' : fields.char('SMS recipient number', size=15,),
        'default_recipient_number' : fields.function(_recipient_number_data, type='char', size=15, method=True, string='Default Recipient Number'),
        'subject' : fields.char('Subject',size = 200),
        'default_subject' : fields.function(_generate_subject, string='Default Subject',type='char',size=200,method=True,),
        'text' : fields.text('Content',),
        'default_text' : fields.function(_generate_content, string='Default Content', type='text', method=True, ),
        'sms_text' : fields.text('SMS Content',),
        'default_sms_text' : fields.function(_generate_content_sms, string='SMS Default Content', type='text', method=True, ),
        'time_all_states' : fields.function(_get_time_all_states, string='Time all states', type='float', method=True,),
	'to_send' : fields.boolean('To Send'),
	'to_send_sms' :fields.boolean('To Send SMS'),
        'default_to_send' : fields.function(_is_to_send, string='To Send', type='boolean', method=True,),
        'default_to_send_sms' : fields.function(_is_to_send_sms, string='To Send SMS', type='boolean', method=True,),
    }
wizard_communication()

class res_partner(osv.osv):
    _name = 'res.partner'
    _inherit = 'res.partner'
    
    _columns = {
        'preferred_state_comunication_channel': fields.selection([('','None'),('email','Email'),('postmail','PostMail'),('sms','SMS')],string='Preferred channel',help='Preferred communication channel'),
    }
res_partner()

def merge_message(self, cr, uid, message, object, partner):
    
    def merge(match):
        exp = str(match.group()[2:-2]).strip()
        result = eval(exp, {'object':object, 'partner':partner})
        if result in (None, False):
            return str("--------")
        return str(result)
    
    com = re.compile('(\[\[.+?\]\])')
    msg = com.sub(merge, message)
    
    return msg

class contact_send_communications_report(osv.osv):
    _name = 'contact.send_communications.report'
    
    _columns = {
        'name' : fields.char('Name', size=50,required=True,),
        'method' : fields.char('Method', size=100, help='Method of contact.states.send_communications model returning pdf data', required=True,),
        'file_name' : fields.char('Report file name', size=20, required=True,),
    }
contact_send_communications_report()

class contact_send_communications_sets(osv.osv):
    _name = 'contact.send_communications.sets'
    
    _columns = {
        'name' : fields.char('Name', size=50,),
        'state_ids' : fields.many2many('contact.annotation.state','contact_states_send_comm_contact_rel','wizard_id','state_id',string = 'States',),
        'function_id' : fields.many2one('contact.annotation.function',string='Function',),
        'case_categ_id' : fields.many2one('crm.case.categ',string='Case Category',help='Case Category to Open'),
        'report_ids' : fields.many2many('contact.send_communications.report', 'contact_reports_to_attach_comms', 'sets_id', 'report_id', string='Reports', help='Reports to attach'),
        'intro' : fields.text('Introduction', help='Use %(x)s for fields when x could be contact_name or partner_name'),
        'intro_none' : fields.text('Content on no states', help='Use %(x)s for fields when x could be contact_name or partner_name'),
        'intro_sms' : fields.text('SMS Message', help='Use %(x)s for fields when x could be contact_name or partner_name'),
        'intro_none_sms' : fields.text('SMS Message on no states', help='Use %(x)s for fields when x could be contact_name or partner_name'),
        'subject' : fields.char('Subject message', size=250, help='Use %(x)s for fields when x could be contact_name or partner_name'),
        'gateway': fields.many2one('sms.smsclient', string='SMS Gateway', domain=[('state','=','confirm')],),
        'num_partners' : fields.integer('Num partners', help='Num max. partners to communicate',),
        'min_state_hours' : fields.float('Min state hours', help='Minimun hours on state by contact for send communication'),
        'min_state_hours_sms' : fields.float('SMS Min state hours', help='SMS Minimmun hours on state by contact for send communication'),
        'sms_option' : fields.selection([('one','Only one method'),('both','SMS and other')],string='SMS option',),
    }

    _defaults = {
        'intro' : lambda *a : 'Dear %(partner_name)s, \nThis message communicates these states ranges for the contact %(contact_name)s.',
        'intro_none' : lambda *a : 'Dear %(partner_name)s, \nNo states ranges to communicate for the contact %(contact_name)s.',
        'subject' : lambda *a : 'Communication contact states',
        'num_partners' : lambda *a : 1,
    }
    
contact_send_communications_sets()

class wizard_send_communications(osv.osv_memory):
    _name = 'contact.states.send_communications'
    
    _columns = {
        'name': fields.char('Filename', 16, readonly=True),                
        'contact_ids' : fields.many2many('res.partner.contact','contact_states_send_comm_contact_rel','wizard_id','contact_id',string = 'Contacts',),
        'date_from' : fields.date('From',),
        'date_to' : fields.date('To',),
        'comm_ids' : fields.one2many('contact.states.comms','wizard_id',string='Communications',),
        'sets_id' : fields.many2one('contact.send_communications.sets', string='Sets', required=True,),
        'file' : fields.binary('Reports to send',),
    }
    
    _defaults = {
        'name' : lambda *a : 'reports.zip',
        'date_from' : lambda *a : time.strftime('%Y-%m-%d 00:00:00'),
        'date_to' : lambda *a : time.strftime('%Y-%m-%d 23:59:59'),
    }
    
    def default_get(self, cr, uid, fields, context = None):
        if not context:
            context = {}
        ret = super(wizard_send_communications, self).default_get(cr, uid, fields, context = context)
        ret.update({
            'contact_ids': self.pool.get('res.partner.contact').search(cr, uid, [('id','in',context.get('active_ids',[]))], context = context),
        })
        return fields and dict( (k,v) for (k,v) in ret.items() if k in fields ) or ret
        
    def act_preview(self, cr, uid, ids, context = None):
        for wizard in self.browse(cr, uid, ids, context = context):
            all_contacts = {}
            for contact in wizard.contact_ids:
                all_contacts[contact.id] = False
                vals2 = {
                    'wizard_id' : wizard.id,
                }
                cfp_ids = self.pool.get('contact.partner.function').search(cr, uid, [('contact_id','=',contact.id),('function_id','=',wizard.sets_id.function_id.id)], limit=wizard.sets_id.num_partners)
                cfps = self.pool.get('contact.partner.function').browse(cr, uid, cfp_ids)
                for cfp in cfps:
                    all_contacts[contact.id] = True
                    preferred_channel = cfp.partner_id.preferred_state_comunication_channel
                    if preferred_channel or True: # Preferred channel required ?
                        vals = dict(vals2)
                        vals['contact_id'] = contact.id
                        vals['partner_id'] = cfp.partner_id.id
                        vals['type'] = preferred_channel or 'sms'
                        comm_id = self.pool.get('contact.states.comms').create(cr, uid, vals, context = context)
                        comm = self.pool.get('contact.states.comms').browse(cr, uid, comm_id)
                        if comm.type == 'sms' and not comm.default_recipient_number:
                            self.pool.get('contact.states.comms').write(cr, uid, [comm_id], {'type': 'postmail',})
                        fields = ('email','address','subject','text','sms_text','recipient_number','to_send','to_send_sms',)
                        data = self.pool.get('contact.states.comms').read(cr, uid, [comm_id], ['default_'+x for x in fields])[0]
                        self.pool.get('contact.states.comms').write(cr, uid, [comm_id], dict([(x,data['default_'+x]) for x in fields]))
            if not reduce(lambda x,y: x and y,all_contacts.values(),True):
                pass
        
        view_id = self.pool.get('ir.ui.view').search(cr, uid, [('name','=','contact.send_communications.wizard1')])
        return {
                'name': _('Wizard to send communications: Confirm actions'),
                'view_type': 'form',
                'view_mode': 'form',
                'res_model': 'contact.states.send_communications',
                'res_id' : ids[0],
                'views' : [(x,'form') for x in view_id],
                'view_id': False,
                'target' : 'new',
                'type': 'ir.actions.act_window',
                'context' : {},
        }

    def _get_attachment(self, cr, uid, comm, context = None):
        return False

    def act_send(self, cr, uid, ids, context = None):
        for wizard in self.browse(cr, uid, ids, context = context):
            zipfile0 = cStringIO.StringIO()
            myzip = zipfile.ZipFile(zipfile0, 'w');c=0
            for comm in wizard.comm_ids:
                if comm.to_send_sms:
                    gateway = self.pool.get('sms.smsclient')
                    to = comm.recipient_number
                    if to:
                        message = merge_message(self, cr, uid, (comm.sms_text or u''), comm, comm.partner_id)
                        gateway.send_message(cr, uid, wizard.sets_id.gateway.id, to, normal_unicode(message))
                        
                        
                        self.pool.get('res.partner.event').create(cr, uid,
                                {'name': _('SMS sent through communication states wizard'),
                                 'partner_id': comm.partner_id.id,
                                 'contact_id' : comm.contact_id.id,
                                 'description': u'' + _('To: ') + to +
                                                _('\n\nText:\n') + normal_unicode(message),
                                 'document': '',})
                    
                if comm.to_send and comm.type == 'email':
                    communications_smtpserver_id = self.pool.get('email.smtpclient').search(cr, uid, [('type','=','communications'),('state','=','confirm'),('active','=',True)], context=False)
                    if not communications_smtpserver_id:
                        default_smtpserver_id = self.pool.get('email.smtpclient').search(cr, uid, [('type','=','default'),('state','=','confirm'),('active','=',True)], context=False)
                    smtpserver_id = communications_smtpserver_id or default_smtpserver_id
                    if smtpserver_id:
                        smtpserver_id = smtpserver_id[0]
                    else:
                        raise osv.except_osv(_('Error'), _('No SMTP Server has been defined!'))

                    files = []
                    path = False
                    for report in wizard.sets_id.report_ids:
                        pdf = getattr(self,report.method)(cr, uid, comm, context = context)
                        try:
                            if not path:
                                path = tempfile.mkdtemp()                            
                            files.append(path + '/' + report.file_name + '.pdf')
                            fp = open(files[-1], 'wb+');
                            fp.write(pdf);
                            fp.close();
                        except Exception,e:
                            print 'Exception in create report:',e
                            return (False, str(e))

                    #print email, data['form']['subject'], data['ids'], data['form']['text'], data['model'], file_name
                    comm_subject = normal_unicode(comm.subject)
                    comm_text = normal_unicode(comm.text)
                    state = self.pool.get('email.smtpclient').send_email(cr, uid, smtpserver_id, comm.email, comm_subject, comm_text, files)
                    if path:
                        shutil.rmtree(path)
                    if not state:
                        raise osv.except_osv(_('Error sending email'), _('Please check the Server Configuration!'))

                    # Add a partner event
                    c_id = c_id and c_id[0] or False
                    self.pool.get('res.partner.event').create(cr, uid,
                            {'name': _('Email sent through communication states wizard'),
                                     'partner_id': comm.partner_id.id,
                                     'contact_id' : comm.contact_id.id,
                             'description': _('To: ') + comm.email +
                                            _('\n\nSubject: ') + normal_unicode(comm.subject) +
                                            _('\n\nText:\n') + normal_unicode(comm.text),
                             'document': '',
                             'user_id': uid, })
                elif comm.to_send:
                    pdf = self._get_attachment(cr, uid, comm, context = context)                    
                    first_address = comm.partner_id.address[0]
                    postmail_id = self.pool.get('crm.postmail').create(cr, uid, {
                        'partner_id': comm.partner_id.id,
                        'name': comm.subject,
                        'categ_id' : comm.wizard_id.sets_id.case_categ_id.id,
                        'partner_address_id': first_address.id,
                        'partner_address' : comm.address,
                    }, context = context)
                    for report in wizard.sets_id.report_ids:
                        pdf = getattr(self,report.method)(cr, uid, comm, context = context)
                        self.pool.get('ir.attachment').create(cr, uid, {
                                'name': comm.subject+'.pdf',
                                'datas': base64.encodestring(pdf),
                                'datas_fname': comm.subject,
                                'res_model': 'crm.postmail',
                                'res_id': postmail_id,
                            }, context = context)
                    self.pool.get('res.partner.event').create(cr, uid,
                            {'name': _('Post Mail sent through communication states wizard'),
                                     'partner_id': comm.partner_id.id,
                                     'contact_id' : comm.contact_id.id,
                             'description': u'' + _('To: ') + normal_unicode(comm.address) +
                                            _('\n\nSubject: ') + normal_unicode(comm.subject)  +
                                            _('\n\nText:\n') + normal_unicode(comm.text),
                             'document': '',
                             'user_id': uid, })
                else:
                    for report in wizard.sets_id.report_ids:
                        pdf = getattr(self,report.method)(cr, uid, comm, context = context)
                        myzip.writestr("report_%000d.pdf" % c, pdf);c+=1                        
                        
                    self.pool.get('res.partner.event').create(cr, uid,
                            {'name': _('A intend of send through communication states wizard'),
                                     'partner_id': comm.partner_id.id,
                                     'contact_id' : comm.contact_id.id,
                             'description': u'' + _('\n\nSubject: ') + normal_unicode(comm.subject)  +
                                            _('\n\nText:\n') + normal_unicode(comm.text),
                             'document': '',
                             'user_id': uid, })
            myzip.close()
            self.write(cr, uid, [wizard.id], {'file': base64.encodestring(zipfile0.getvalue()) })
            zipfile0.close()
            
        act_obj = self.pool.get('ir.actions.act_window')
        dicci = act_obj.read(cr, uid, act_obj.search(cr, uid, [
            ('name','=','Send Communications : Reports to print'),]), [], context = context)[0]
        dicci['res_id'] = ids[0]
        return dicci 

wizard_send_communications()
                            
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: