~anybox/aeroo/openerp6

« back to all changes in this revision

Viewing changes to report_aeroo/report_aeroo.py

  • Committer: root
  • Date: 2013-05-16 15:46:46 UTC
  • Revision ID: root@erp.kndati.lv-20130516154646-5lesr8tyzl1vdc0k
1.2.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# -*- encoding: utf-8 -*-
2
2
##############################################################################
3
3
#
4
 
# Copyright (c) 2009-2012 Alistek Ltd (http://www.alistek.com) All Rights Reserved.
 
4
# Copyright (c) 2009-2013 Alistek Ltd (http://www.alistek.com) All Rights Reserved.
5
5
#                    General contacts <info@alistek.com>
6
6
# Copyright (C) 2009  Domsense s.r.l.                                   
7
7
#
32
32
##############################################################################
33
33
 
34
34
import os, sys, traceback
35
 
import tempfile
 
35
from tempfile import NamedTemporaryFile
36
36
import report
37
 
from report.report_sxw import report_sxw, report_rml, browse_record_list, _fields_process
 
37
from report.report_sxw import report_sxw, report_rml, browse_record_list
38
38
from report.pyPdf import PdfFileWriter, PdfFileReader
39
39
#import zipfile
40
40
try:
49
49
import time
50
50
import re
51
51
import copy
 
52
import threading
 
53
from random import randint
52
54
 
53
55
try:
54
56
    from addons import load_information_from_description_file # for OpenERP 6.0.x
59
61
import aeroolib
60
62
from aeroolib.plugins.opendocument import Template, OOSerializer
61
63
from genshi.template import NewTextTemplate
 
64
from genshi import __version__ as genshi_version
62
65
import pooler
63
66
import netsvc
64
67
from lxml import etree
66
69
 
67
70
from ExtraFunctions import ExtraFunctions
68
71
 
69
 
def _aeroo_ooo_test(cr):
 
72
try:
 
73
    aeroo_lock = threading.Lock()
 
74
    msg = "Aeroo lock instantiated."
 
75
    logger.notifyChannel('report_aeroo', netsvc.LOG_INFO, msg)
 
76
except Exception:
 
77
    err_msg = "Could not instantiate Aeroo lock!!!"
 
78
    logger.notifyChannel('report_aeroo', netsvc.LOG_CRITICAL, err_msg)
 
79
 
 
80
def aeroo_ooo_test(cr):
70
81
    '''
71
82
    Detect report_aeroo_ooo module
72
83
    '''
83
94
        self._number = start
84
95
        self._interval = interval
85
96
 
86
 
    def next(self):
87
 
        curr_number = self._number
88
 
        self._number += self._interval
89
 
        return curr_number
 
97
    def next(self, increment=True):
 
98
        if increment:
 
99
            self._number += self._interval
 
100
            return self._number
 
101
        else:
 
102
            return self._number + self._interval
90
103
 
91
104
    def get_inc(self):
92
105
        return self._number
93
106
 
94
 
    def prev(self):
95
 
        return self._number-self._interval
 
107
    def prev(self, decrement=True):
 
108
        if decrement:
 
109
            self._number -= self._interval
 
110
            return self._number
 
111
        else:
 
112
            return self._number-self._interval
 
113
 
 
114
class AerooPrint(object):
 
115
    print_ids = [] # static property
 
116
    def __init__(self):
 
117
        print_id = False
 
118
        while(not print_id or print_id in self.print_ids):
 
119
            print_id = randint(1, 99999)
 
120
        self.print_ids.append(print_id)
 
121
        self.id = print_id
 
122
        self.subreports = []
 
123
        self.epl_images = []
 
124
        self.counters = {}
 
125
        self.start_time = 0
 
126
        self.start_total_time = 0
96
127
 
97
128
class Aeroo_report(report_sxw):
98
129
 
102
133
    def __init__(self, cr, name, table, rml=False, parser=False, header=True, store=False):
103
134
        super(Aeroo_report, self).__init__(name, table, rml, parser, header, store)
104
135
        self.logger("registering %s (%s)" % (name, table), netsvc.LOG_INFO)
105
 
        self.oo_subreports = []
106
 
        self.epl_images = []
107
 
        self.counters = {}
108
 
        self.start_time = 0
 
136
        self.active_prints = {}
109
137
 
110
138
        pool = pooler.get_pool(cr.dbname)
111
139
        ir_obj = pool.get('ir.actions.report.xml')
138
166
        return super(Aeroo_report, self).getObjects(cr, uid, ids, context)
139
167
 
140
168
    ##### Counter functions #####
141
 
    def _def_inc(self, name, start=0, interval=1):
142
 
        self.counters[name] = Counter(name, start, interval)
143
 
 
144
 
    def _get_inc(self, name):
145
 
        return self.counters[name].get_inc()
146
 
 
147
 
    def _prev(self, name):
148
 
        return self.counters[name].prev()
149
 
 
150
 
    def _next(self, name):
151
 
        return self.counters[name].next()
 
169
    def _def_inc(self, aeroo_print):
 
170
        def def_inc(name, start=0, interval=1):
 
171
            aeroo_print.counters[name] = Counter(name, start, interval)
 
172
        return def_inc
 
173
 
 
174
    def _get_inc(self, aeroo_print):
 
175
        def get_inc(name):
 
176
            return aeroo_print.counters[name].get_inc()
 
177
        return get_inc
 
178
 
 
179
    def _prev(self, aeroo_print):
 
180
        def prev(name):
 
181
            return aeroo_print.counters[name].prev()
 
182
        return prev
 
183
 
 
184
    def _next(self, aeroo_print):
 
185
        def next(name):
 
186
            return aeroo_print.counters[name].next()
 
187
        return next
152
188
    #############################
153
189
 
154
 
    def _epl_asimage(self, data):
 
190
    def _epl_asimage(self, data, aeroo_print):
155
191
        from PIL import Image
156
192
        from math import ceil
157
193
        if not data:
169
205
        new_data = ''
170
206
        for d in temp_data:
171
207
            new_data += chr(ord(d)^255)
172
 
        self.epl_images.append(new_data)
 
208
        aeroo_print.epl_images.append(new_data)
173
209
        return img.size
174
210
 
175
 
    def _epl2_gw(self, start_x, start_y, data):
176
 
        if not data:
177
 
            return None
178
 
        size_x, size_y = self._epl_asimage(data)
179
 
        return 'GW'+str(start_x)+','+str(start_y)+','+str(int(size_x/8))+','+str(size_y)+',<binary_data>'
 
211
    def _epl2_gw(self, aeroo_print):
 
212
        def epl2_gw(start_x, start_y, data):
 
213
            if not data:
 
214
                return None
 
215
            size_x, size_y = self._epl_asimage(data, aeroo_print)
 
216
            return 'GW'+str(start_x)+','+str(start_y)+','+str(int(size_x/8))+','+str(size_y)+',<binary_data>'
 
217
        return epl2_gw
180
218
 
181
 
    def _include_document(self, aeroo_ooo=False):
 
219
    def _include_document(self, print_id, aeroo_ooo=False):
182
220
        def include_document(data, silent=False):
183
221
            if not aeroo_ooo:
184
222
                return _("Error! Include document not available!")
185
223
            import binascii, urllib2
186
 
            dummy_fd, temp_file_name = tempfile.mkstemp(suffix='.odt', prefix='aeroo-report-')
187
 
            temp_file = open(temp_file_name, 'wb')
 
224
            temp_file = NamedTemporaryFile(suffix='.odt', prefix='aeroo-report-', delete=False)
188
225
            if os.path.isfile(data):
189
226
                fd = file(data, 'rb')
190
227
                data = fd.read()
194
231
                    url_file = urllib2.urlopen(data)
195
232
                    data = url_file.read()
196
233
                except urllib2.HTTPError, e:
197
 
                    os.unlink(temp_file_name)
 
234
                    os.unlink(temp_file.name)
198
235
                    error = _('HTTP Error %s! File not found:') % e.getcode() + ' %s' % data
199
236
                except urllib2.URLError, e:
200
 
                    os.unlink(temp_file_name)
 
237
                    os.unlink(temp_file.name)
201
238
                    error = _('Error!')+' %s' % e
202
239
                except IOError, e:
203
 
                    os.unlink(temp_file_name)
 
240
                    os.unlink(temp_file.name)
204
241
                    error = _('Error!')+' %s' % e
205
242
                except Exception, e:
206
243
                    try:
207
244
                        data = base64.decodestring(data)
208
245
                    except binascii.Error:
209
 
                        os.unlink(temp_file_name)
 
246
                        os.unlink(temp_file.name)
210
247
                        error = _('Error! File not found:')+' %s' % data
211
248
                if error:
212
249
                    if not silent:
217
254
                temp_file.write(data)
218
255
            finally:
219
256
                temp_file.close()
220
 
            self.oo_subreports.append(temp_file_name)
221
 
            return "<insert_doc('%s')>" % temp_file_name
 
257
            #self.oo_subreports[print_id].append(temp_file.name)
 
258
            self.active_prints[print_id].subreports.append(temp_file.name)
 
259
            return "<insert_doc('%s')>" % temp_file.name
222
260
        return include_document
223
261
 
224
 
    def _subreport(self, cr, uid, output='odt', aeroo_ooo=False, context={}):
 
262
    def _subreport(self, cr, uid, aeroo_print, output='odt', aeroo_ooo=False, context={}):
225
263
        pool = pooler.get_pool(cr.dbname)
226
264
        ir_obj = pool.get('ir.actions.report.xml')
227
265
        #### for odt documents ####
230
268
                return _("Error! Subreports not available!")
231
269
            report_xml_ids = ir_obj.search(cr, uid, [('report_name', '=', name)], context=context)
232
270
            if report_xml_ids:
 
271
                service = netsvc.Service._services['report.%s' % name]
233
272
                report_xml = ir_obj.browse(cr, uid, report_xml_ids[0], context=context)
234
273
                data = {'model': obj._table_name, 'id': obj.id, 'report_type': 'aeroo', 'in_format': 'oo-odt'}
235
 
                report, output = netsvc.Service._services['report.%s' % name].create_aeroo_report(cr, uid, \
 
274
                ### Get new printing object ###
 
275
                sub_aeroo_print = AerooPrint()
 
276
                service.active_prints[sub_aeroo_print.id] = sub_aeroo_print
 
277
                context['print_id'] = sub_aeroo_print.id
 
278
                ###############################
 
279
                sub_aeroo_print.start_time = time.time()
 
280
                report, output = service.create_aeroo_report(cr, uid, \
236
281
                                            [obj.id], data, report_xml, context=context, output='odt') # change for OpenERP 6.0 - Service class usage
237
282
 
238
 
                dummy_fd, temp_file_name = tempfile.mkstemp(suffix='.odt', prefix='aeroo-report-')
239
 
                temp_file = open(temp_file_name, 'wb')
240
 
                try:
 
283
                ### Delete printing object ###
 
284
                AerooPrint.print_ids.remove(sub_aeroo_print.id)
 
285
                del service.active_prints[sub_aeroo_print.id]
 
286
                ##############################
 
287
                with NamedTemporaryFile(suffix='.odt', prefix='aeroo-report-', delete=False) as temp_file:
241
288
                    temp_file.write(report)
242
 
                finally:
243
 
                    temp_file.close()
244
 
 
245
 
                self.oo_subreports.append(temp_file_name)
246
 
 
247
 
                return "<insert_doc('%s')>" % temp_file_name
 
289
 
 
290
                #self.oo_subreports[print_id].append(temp_file.name)
 
291
                aeroo_print.subreports.append(temp_file.name)
 
292
 
 
293
                return "<insert_doc('%s')>" % temp_file.name
248
294
            return None
249
295
        #### for text documents ####
250
296
        def raw_subreport(name=None, obj=None):
299
345
        return style_io
300
346
 
301
347
    def create_genshi_raw_report(self, cr, uid, ids, data, report_xml, context=None, output='raw', tmpl=False):
302
 
        def preprocess(data):
303
 
            self.epl_images.reverse()
304
 
            while self.epl_images:
305
 
                img = self.epl_images.pop()
 
348
        def preprocess(data, aeroo_print):
 
349
            aeroo_print.epl_images.reverse()
 
350
            while aeroo_print.epl_images:
 
351
                img = aeroo_print.epl_images.pop()
306
352
                data = data.replace('<binary_data>', img, 1)
307
353
            return data.replace('\n', '\r\n')
308
354
 
309
 
        if not self.start_time:
310
 
            self.start_time = time.time()
 
355
        print_id = context.get('print_id', False)
 
356
        aeroo_print = self.active_prints[print_id] # Aeroo print object
 
357
        if not aeroo_print.start_time:
 
358
            aeroo_print.start_time = time.time()
311
359
        if not context:
312
360
            context={}
313
361
        context = context.copy()
315
363
        oo_parser = self.parser(cr, uid, self.name2, context=context)
316
364
        oo_parser.localcontext.update(context)
317
365
        oo_parser.set_context(objects, data, ids, report_xml.report_type)
318
 
        #oo_parser.objects = objects
319
366
        self.set_xml_data_fields(oo_parser.objects, oo_parser) # Get/Set XML
320
 
        oo_parser.localcontext['objects'] = oo_parser.objects
 
367
        #oo_parser.localcontext['objects'] = oo_parser.objects
321
368
        oo_parser.localcontext['data'] = data
322
369
        oo_parser.localcontext['user_lang'] = context.get('lang', False)
323
370
        if len(objects)>0:
325
372
        xfunc = ExtraFunctions(cr, uid, report_xml.id, oo_parser.localcontext)
326
373
        oo_parser.localcontext.update(xfunc.functions)
327
374
        file_data = tmpl or self.get_other_template(cr, uid, data, oo_parser) or report_xml.report_sxw_content # Get other Tamplate
328
 
        if file_data=='False':
 
375
        if not file_data or file_data=='False':
329
376
            raise osv.except_osv(_('Error!'), _('No template found!'))
330
377
        ################################################
331
378
        if not file_data:
332
 
            self.logger("End process %s (%s), elapsed time: %s" % (self.name, self.table, time.time() - self.start_time), netsvc.LOG_INFO) # debug mode
 
379
            self.logger("End process %s (%s), elapsed time: %s" % (self.name, self.table, time.time() - aeroo_print.start_time), netsvc.LOG_INFO) # debug mode
333
380
            return False, output
334
381
 
335
 
        oo_parser.localcontext['include_subreport'] = self._subreport(cr, uid, output='raw', aeroo_ooo=False, context=context)
336
 
        oo_parser.localcontext['epl2_gw'] = self._epl2_gw
337
 
 
338
 
        self.epl_images = []
 
382
        print_id = context.get('print_id', False)
 
383
        aeroo_print = self.active_prints[print_id]
 
384
 
 
385
        oo_parser.localcontext['include_subreport'] = self._subreport(cr, uid, aeroo_print, output='raw', aeroo_ooo=False, context=context)
 
386
        oo_parser.localcontext['epl2_gw'] = self._epl2_gw(aeroo_print)
 
387
        deferred = context.get('deferred_process')
 
388
        oo_parser.localcontext['progress_update'] = deferred and deferred.progress_update or (lambda:True)
 
389
 
 
390
        aeroo_print.epl_images = []
339
391
        basic = NewTextTemplate(source=base64.decodestring(file_data))
340
392
        #try:
341
 
        data = preprocess(basic.generate(**oo_parser.localcontext).render().decode('utf8').encode(report_xml.charset))
 
393
        if genshi_version<='0.6':
 
394
            data = preprocess(basic.generate(**oo_parser.localcontext).render().decode('utf8').encode(report_xml.charset), aeroo_print)
 
395
        else:
 
396
            data = preprocess(basic.generate(**oo_parser.localcontext).render().encode(report_xml.charset), aeroo_print)
342
397
        #except Exception, e:
343
398
        #    self.logger(str(e), netsvc.LOG_ERROR)
344
399
        #    return False, output
345
400
 
346
401
        if report_xml.content_fname:
347
402
            output = report_xml.content_fname
348
 
        self.logger("End process %s (%s), elapsed time: %s" % (self.name, self.table, time.time() - self.start_time), netsvc.LOG_INFO) # debug mode
 
403
        self.logger("End process %s (%s), elapsed time: %s" % (self.name, self.table, time.time() - aeroo_print.start_time), netsvc.LOG_INFO) # debug mode
349
404
        return data, output
350
405
 
 
406
    def _generate_doc(self, DC, data, report_xml, print_id):
 
407
        with aeroo_lock:
 
408
            DC.putDocument(data)
 
409
            #subreports = self.oo_subreports.get(print_id)
 
410
            aeroo_print = self.active_prints.get(print_id, False)
 
411
            if aeroo_print:
 
412
                DC.insertSubreports(aeroo_print.subreports)
 
413
                #self.oo_subreports = []
 
414
                #del self.oo_subreports[print_id]
 
415
            if report_xml.out_format.code=='oo-dbf':
 
416
                data = DC.saveByStream(report_xml.out_format.filter_name, "78")
 
417
            else:
 
418
                data = DC.saveByStream(report_xml.out_format.filter_name)
 
419
            DC.closeDocument()
 
420
        return data
 
421
 
 
422
    def _raise_exception(self, e, print_id):
 
423
        tb_s = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
 
424
        self.logger(_("Report generation error!")+'\n'+tb_s, netsvc.LOG_ERROR)
 
425
        #subreports = self.oo_subreports.get(print_id, [])
 
426
        aeroo_print = self.active_prints.get(print_id, [])
 
427
        if aeroo_print:
 
428
            for sub_report in aeroo_print.subreports:
 
429
                if os.path.isfile(sub_report):
 
430
                    os.unlink(sub_report)
 
431
        raise Exception(_("Aeroo Reports: Error while generating the report."), e, str(e), _("For more reference inspect error logs."))
 
432
 
351
433
    def create_aeroo_report(self, cr, uid, ids, data, report_xml, context=None, output='odt'):
352
434
        """ Returns an aeroo report generated with aeroolib
353
435
        """
359
441
            context['model'] = data['model']
360
442
            context['ids'] = ids
361
443
        
 
444
        print_id = context.get('print_id', False)
 
445
        aeroo_print = self.active_prints[print_id] # Aeroo print object
 
446
        aeroo_print.subreports = []
 
447
        #self.oo_subreports[print_id] = []
 
448
        oo_parser = self.parser(cr, uid, self.name2, context=context)
 
449
        if not report_xml.process_sep and getattr(oo_parser, 'single', False):
 
450
            ids = [ids[0]]
362
451
        objects = self.getObjects_mod(cr, uid, ids, report_xml.report_type, context) or []
363
 
        oo_parser = self.parser(cr, uid, self.name2, context=context)
364
452
        oo_parser.localcontext.update(context)
365
453
        oo_parser.set_context(objects, data, ids, report_xml.report_type)
366
454
 
367
455
        #oo_parser.objects = objects
368
 
        self.set_xml_data_fields(objects, oo_parser) # Get/Set XML
 
456
        #self.set_xml_data_fields(objects, oo_parser) # Get/Set XML
369
457
 
370
 
        oo_parser.localcontext['objects'] = oo_parser.objects
 
458
        #oo_parser.localcontext['objects'] = oo_parser.objects
371
459
        oo_parser.localcontext['data'] = data
372
460
        oo_parser.localcontext['user_lang'] = context.get('lang', False)
373
 
        if len(objects)==1:
 
461
        if len(objects)>0:
374
462
            oo_parser.localcontext['o'] = objects[0]
375
463
        xfunc = ExtraFunctions(cr, uid, report_xml.id, oo_parser.localcontext)
376
464
        oo_parser.localcontext.update(xfunc.functions)
381
469
        style_io=self.get_styles_file(cr, uid, report_xml, company=company_id, context=context)
382
470
 
383
471
        if report_xml.tml_source in ('file', 'database'):
384
 
            if report_xml.report_sxw_content=='False':
 
472
            if not report_xml.report_sxw_content or report_xml.report_sxw_content=='False':
385
473
                raise osv.except_osv(_('Error!'), _('No template found!'))
386
474
            file_data = base64.decodestring(report_xml.report_sxw_content)
387
475
        else:
388
476
            file_data = self.get_other_template(cr, uid, data, oo_parser)
389
477
        if not file_data and not report_xml.report_sxw_content:
390
 
            self.logger("End process %s (%s), elapsed time: %s" % (self.name, self.table, time.time() - self.start_time), netsvc.LOG_INFO) # debug mode
 
478
            self.logger("End process %s (%s), elapsed time: %s" % (self.name, self.table, time.time() - aeroo_print.start_time), netsvc.LOG_INFO) # debug mode
391
479
            return False, output
392
480
        #elif file_data:
393
481
        #    template_io = StringIO()
402
490
                template_io = StringIO()
403
491
                template_io.write(file_data or base64.decodestring(report_xml.report_sxw_content) )
404
492
                serializer = OOSerializer(template_io, oo_styles=style_io)
405
 
            basic = Template(source=template_io, serializer=serializer)
 
493
            try:
 
494
                basic = Template(source=template_io, serializer=serializer)
 
495
            except Exception, e:
 
496
                self._raise_exception(e, print_id)
406
497
 
407
498
        #if not file_data:
408
499
        #    return False, output
410
501
        #basic = Template(source=template_io, serializer=serializer)
411
502
 
412
503
        aeroo_ooo = context.get('aeroo_ooo', False)
413
 
        oo_parser.localcontext['include_subreport'] = self._subreport(cr, uid, output='odt', aeroo_ooo=aeroo_ooo, context=context)
414
 
        oo_parser.localcontext['include_document'] = self._include_document(aeroo_ooo)
415
 
 
 
504
        oo_parser.localcontext['include_subreport'] = self._subreport(cr, uid, aeroo_print, output='odt', aeroo_ooo=aeroo_ooo, context=context)
 
505
        oo_parser.localcontext['include_document'] = self._include_document(aeroo_ooo, print_id)
 
506
        deferred = context.get('deferred_process')
 
507
        oo_parser.localcontext['progress_update'] = deferred and deferred.progress_update or (lambda:True)
416
508
        ####### Add counter functons to localcontext #######
417
 
        oo_parser.localcontext.update({'def_inc':self._def_inc,
418
 
                                      'get_inc':self._get_inc,
419
 
                                      'prev':self._prev,
420
 
                                      'next':self._next})
 
509
        oo_parser.localcontext.update({'def_inc':self._def_inc(aeroo_print),
 
510
                                      'get_inc':self._get_inc(aeroo_print),
 
511
                                      'prev':self._prev(aeroo_print),
 
512
                                      'next':self._next(aeroo_print)})
421
513
 
422
514
        user_name = pool.get('res.users').browse(cr, uid, uid, {}).name
423
515
        model_id = pool.get('ir.model').search(cr, uid, [('model','=',context.get('active_model', data['model']) or data['model'])])[0]
440
532
        except osv.except_osv, e:
441
533
            raise
442
534
        except Exception, e:
443
 
            tb_s = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
444
 
            self.logger(_("Report generation error!")+'\n'+tb_s, netsvc.LOG_ERROR)
445
 
            for sub_report in self.oo_subreports:
446
 
                if os.path.isfile(sub_report):
447
 
                    os.unlink(sub_report)
448
 
            raise Exception(_("Aeroo Reports: Error while generating the report."), e, str(e), _("For more reference inspect error logs."))
 
535
            self._raise_exception(e, print_id)
449
536
 
450
537
        ######### OpenOffice extras #########
451
538
        DC = netsvc.Service._services.get('openoffice')
452
 
        if (output!=report_xml.in_format[3:] or self.oo_subreports):
 
539
        #if (output!=report_xml.in_format[3:] or self.oo_subreports.get(print_id)):
 
540
        if output!=report_xml.in_format[3:] or aeroo_print.subreports:
453
541
            if aeroo_ooo and DC:
454
542
                try:
455
 
                    DC.putDocument(data)
456
 
                    if self.oo_subreports:
457
 
                        DC.insertSubreports(self.oo_subreports)
458
 
                        self.oo_subreports = []
459
 
                    if report_xml.out_format.code=='oo-dbf':
460
 
                        data = DC.saveByStream(report_xml.out_format.filter_name, "78")
461
 
                    else:
462
 
                        data = DC.saveByStream(report_xml.out_format.filter_name)
463
 
                    DC.closeDocument()
464
 
                    #del DC
 
543
                    data = self._generate_doc(DC, data, report_xml, print_id)
465
544
                except Exception, e:
466
545
                    self.logger(_("OpenOffice.org related error!")+'\n'+str(e), netsvc.LOG_ERROR)
467
 
                    if report_xml.fallback_false:
468
 
                        raise osv.except_osv(_('OpenOffice.org related error!'), str(e))
469
 
                    else:
 
546
                    if DC._restart_ooo():
 
547
                        # We try again
 
548
                        try:
 
549
                            data = self._generate_doc(DC, data, report_xml, print_id)
 
550
                        except Exception, e:
 
551
                            self.logger(_("OpenOffice.org related error!")+'\n'+str(e), netsvc.LOG_ERROR)
 
552
                            if not report_xml.fallback_false:
 
553
                                output=report_xml.in_format[3:]
 
554
                    elif not report_xml.fallback_false:
470
555
                        output=report_xml.in_format[3:]
471
 
                    self.oo_subreports = []
 
556
                    aeroo_print.subreports = []
472
557
            else:
473
558
                if report_xml.fallback_false:
474
559
                    if not aeroo_ooo:
476
561
                    elif not DC:
477
562
                        raise osv.except_osv(_('OpenOffice.org related error!'), _('Can not connect to OpenOffice.org.'))
478
563
                else:
 
564
                    self.logger(_("PDF generator temporarily offline, please wait a minute"), netsvc.LOG_WARNING)
479
565
                    output=report_xml.in_format[3:]
480
566
        elif output in ('pdf', 'doc', 'xls'):
481
567
            output=report_xml.in_format[3:]
483
569
 
484
570
        if report_xml.content_fname:
485
571
            output = report_xml.content_fname
486
 
        self.logger("End process %s (%s), elapsed time: %s" % (self.name, self.table, time.time() - self.start_time), netsvc.LOG_INFO) # debug mode
 
572
        self.logger("End process %s (%s), elapsed time: %s" % (self.name, self.table, time.time() - aeroo_print.start_time), netsvc.LOG_INFO) # debug mode
487
573
        return data, output
488
574
 
489
575
    # override needed to keep the attachments' storing procedure
517
603
            context={}
518
604
        pool = pooler.get_pool(cr.dbname)
519
605
        attach = report_xml.attachment
520
 
        aeroo_ooo = _aeroo_ooo_test(cr) # Detect report_aeroo_ooo module
 
606
        aeroo_ooo = aeroo_ooo_test(cr) # Detect report_aeroo_ooo module
521
607
        context['aeroo_ooo'] = aeroo_ooo
 
608
        print_id = context.get('print_id', False)
 
609
        aeroo_print = self.active_prints[print_id] # Aeroo print object
522
610
        if attach or aeroo_ooo and report_xml.process_sep:
523
 
            objs = self.getObjects(cr, uid, ids, context)
 
611
            objs = self.getObjects_mod(cr, uid, ids, report_xml.report_type, context)
 
612
            deferred = context.get('deferred_process')
524
613
            results = []
525
614
            for obj in objs:
 
615
                aeroo_print.start_time = time.time()
 
616
                if deferred:
 
617
                    deferred.progress_update()
526
618
                aname = attach and eval(attach, {'object':obj, 'time':time}) or False
527
619
                result = False
528
620
                if report_xml.attachment_use and aname and context.get('attachment_use', True):
589
681
        pool = pooler.get_pool(cr.dbname)
590
682
        results = []
591
683
        attach = report_xml.attachment
592
 
        aeroo_ooo = _aeroo_ooo_test(cr) # Detect report_aeroo_ooo module
 
684
        aeroo_ooo = aeroo_ooo_test(cr) # Detect report_aeroo_ooo module
593
685
        context['aeroo_ooo'] = aeroo_ooo
 
686
        print_id = context.get('print_id', False)
 
687
        aeroo_print = self.active_prints[print_id] # Aeroo print object
594
688
        if attach or aeroo_ooo and report_xml.process_sep:
595
689
            objs = self.getObjects_mod(cr, uid, ids, report_xml.report_type, context)
 
690
            deferred = context.get('deferred_process')
596
691
            for obj in objs:
 
692
                aeroo_print.start_time = time.time()
 
693
                if deferred:
 
694
                    deferred.progress_update()
597
695
                aname = attach and eval(attach, {'object':obj, 'time':time}) or False
598
696
                result = False
599
697
                if report_xml.attachment_use and aname and context.get('attachment_use', True):
644
742
                raise osv.except_osv(_('Error!'), _('Unsupported combination of formats!'))
645
743
            results.reverse()
646
744
            data = results.pop()
647
 
            DC.putDocument(data[0])
648
 
            DC.joinDocuments([r[0] for r in results])
649
 
            result = DC.saveByStream()
650
 
            DC.closeDocument()
 
745
            with aeroo_lock:
 
746
                DC.putDocument(data[0])
 
747
                DC.joinDocuments([r[0] for r in results])
 
748
                result = DC.saveByStream()
 
749
                DC.closeDocument()
651
750
            return (result, data[1])
652
751
        else:
653
752
            return self.create_single_pdf(cr, uid, ids, data, report_xml, context)
654
753
 
655
754
    # override needed to intercept the call to the proper 'create' method
656
755
    def create(self, cr, uid, ids, data, context=None):
657
 
        self.start_time = time.time()
 
756
        #### Get Aeroo print object ###
 
757
        aeroo_print = AerooPrint()
 
758
        aeroo_print.start_total_time = time.time()
 
759
        aeroo_print.start_time = time.time()
 
760
        self.active_prints[aeroo_print.id] = aeroo_print
 
761
        context['print_id'] = aeroo_print.id
 
762
        ###############################
658
763
        self.logger("Start process %s (%s)" % (self.name, self.table), netsvc.LOG_INFO) # debug mode
 
764
        pool = pooler.get_pool(cr.dbname)
 
765
        if context is None:
 
766
            context = {}
 
767
        if 'tz' not in context:
 
768
            context['tz'] = pool.get('res.users').browse(cr, uid, uid).context_tz
 
769
 
659
770
        data.setdefault('model', context.get('active_model',False))
660
 
        pool = pooler.get_pool(cr.dbname)
661
771
        ir_obj = pool.get('ir.actions.report.xml')
662
772
        name = self.name.startswith('report.') and self.name[7:] or self.name
663
773
        report_xml_ids = ir_obj.search(cr, uid,
707
817
                return super(Aeroo_report, self).create(cr, uid, ids, data, context)
708
818
        else:
709
819
            raise Exception(_('Unknown report type: %s') % report_type)
710
 
        return fnct(cr, uid, ids, data, report_xml, context)
 
820
        res = fnct(cr, uid, ids, data, report_xml, context)
 
821
        ### Delete printing object ###
 
822
        AerooPrint.print_ids.remove(aeroo_print.id)
 
823
        del self.active_prints[aeroo_print.id]
 
824
        ##############################
 
825
        self.logger("End total process %s (%s), total elapsed time: %s" % (self.name, self.table, time.time() - aeroo_print.start_total_time), netsvc.LOG_INFO) # debug mode
 
826
        return res
711
827
 
712
828
class ReportTypeException(Exception):
713
829
    def __init__(self, value):