Ejemplo n.º 1
0
    def _jasper_execute(self,
                        ex,
                        current_document,
                        js_conf,
                        pdf_list,
                        reload=False,
                        ids=None,
                        context=None):
        """
        After retrieve datas to launch report, execute it and
        return the content
        """
        # Issue 934068 with web client with model is missing from the context
        if not self.model:
            self.model = current_document.model_id.model
            self.model_obj = self.pool.get(self.model)

        if context is None:
            context = self.context.copy()

        if ids is None:
            ids = []

        cur_obj = self.model_obj.browse(self.cr, self.uid, ex, context=context)
        aname = False
        if self.attrs['attachment']:
            aname = self._eval_attachment(cur_obj)

        duplicate = 1
        if current_document.duplicate:
            duplicate = self._eval_duplicate(cur_obj, current_document)

        log_debug('Number of duplicate copy: %d' % int(duplicate))

        language = context.get('lang', 'en_US')
        if current_document.lang:
            language = self._eval_lang(cur_obj,
                                       current_document,
                                       context=context)

        # Check if we can launch this reports
        # Test can be simple, or un a function
        if current_document.check_sel != 'none':
            try:
                if current_document.check_sel == 'simple' and \
                   not eval(current_document.check_simple, {'o': cur_obj}):
                    raise JasperException(
                        _('Check Print Error'),
                        current_document.message_simple)  # noqa
                elif current_document.check_sel == 'func' and \
                        not hasattr(self.model_obj, 'check_print'):
                    raise JasperException(
                        _('Check Print Error'),
                        _('"check_print" function not found in "%s" object') %
                        self.model)  # noqa
                elif current_document.check_sel == 'func' and \
                        hasattr(self.model_obj, 'check_print') and \
                        not self.model_obj.check_print(self.cr, self.uid,
                                                       cur_obj,
                                                       context=context):
                    raise JasperException(
                        _('Check Print Error'),
                        _('Function "check_print" return an error'))  # noqa

            except SyntaxError, e:
                _logger.warning('Error %s' % str(e))
                raise EvalError(
                    _('Check Error'),
                    _('Syntax error when check condition\n\nMessage: "%s"') %
                    str(e))  # noqa
            except NameError, e:
                _logger.warning('Error %s' % str(e))
                raise EvalError(
                    _('Check Error'),
                    _('Error when check condition\n\nMessage: "%s"') %
                    str(e))  # noqa
Ejemplo n.º 2
0
    def execute(self):
        """Launch the report and return it"""
        context = self.context.copy()

        ids = self.ids
        log_debug('DATA:')
        log_debug('\n'.join(['%s: %s' % (x, self.data[x]) for x in self.data]))

        ##
        # For each IDS, launch a query, and return only one result
        #
        pdf_list = []
        doc_ids = self.doc_obj.search(self.cr,
                                      self.uid, [('id', '=', self.service)],
                                      context=context)
        if not doc_ids:
            raise JasperException(_('Configuration Error'),
                                  _("Service name doesn't match!"))

        doc = self.doc_obj.browse(self.cr,
                                  self.uid,
                                  doc_ids[0],
                                  context=context)
        self.outputFormat = doc.format
        log_debug('Format: %s' % doc.format)

        if doc.server_id:
            js_ids = [doc.server_id.id]
        else:
            js_ids = self.js_obj.search(self.cr, self.uid,
                                        [('enable', '=', True)])
            if not len(js_ids):
                raise JasperException(
                    _('Configuration Error'),
                    _('No JasperServer configuration found!'))  # noqa

        js = self.js_obj.read(self.cr, self.uid, js_ids[0], context=context)

        def compose_path(basename):
            return js['prefix'] and '/' + js[
                'prefix'] + '/instances/%s/%s' or basename  # noqa

        self.attrs['attachment'] = doc.attachment
        self.attrs['reload'] = doc.attachment_use
        if not self.attrs.get('params'):
            uri = compose_path('/openerp/bases/%s/%s') % (self.cr.dbname,
                                                          doc.report_unit)
            self.attrs['params'] = (doc.format, uri, doc.mode, doc.depth, {})

        one_check = {}
        one_check[doc.id] = False
        content = ''
        duplicate = 1
        for ex in ids:
            if doc.mode == 'multi' and self.outputFormat == 'PDF':
                for d in doc.child_ids:
                    if d.only_one and one_check.get(d.id, False):
                        continue
                    self.path = compose_path('/openerp/bases/%s/%s') % (
                        self.cr.dbname, d.report_unit)  # noqa
                    (content,
                     duplicate) = self._jasper_execute(ex,
                                                       d,
                                                       js,
                                                       pdf_list,
                                                       reload,
                                                       ids,
                                                       context=self.context)
                    one_check[d.id] = True
            else:
                if doc.only_one and one_check.get(doc.id, False):
                    continue
                (content,
                 duplicate) = self._jasper_execute(ex,
                                                   doc,
                                                   js,
                                                   pdf_list,
                                                   reload,
                                                   ids,
                                                   context=self.context)
                one_check[doc.id] = True

        # If format is not PDF, we return it directly
        # ONLY PDF CAN BE MERGE!
        if self.outputFormat != 'PDF':
            self.obj = external_pdf(content, self.outputFormat)
            return (self.obj.content, self.outputFormat)

        def find_pdf_attachment(pdfname, current_obj):
            """
            Evaluate the pdfname, and return it as a fiel object
            """
            if not pdfname:
                return None

            filename = self._eval_field(current_obj, pdfname)
            att_obj = self.pool.get('ir.attachment')
            aids = att_obj.search(self.cr, self.uid,
                                  [('name', '=', filename),
                                   ('res_model', '=', self.model_obj._name),
                                   ('res_id', '=', ex)])
            if not aids:
                return None

            att = att_obj.browse(self.cr, self.uid, aids[0], context=context)
            datas = StringIO()
            if att.datas:
                datas.write(base64.decodestring(att.datas))
                return datas
            return None

        # If We must add begin and end file in the current PDF
        cur_obj = self.model_obj.browse(self.cr, self.uid, ex, context=context)
        pdf_fo_begin = find_pdf_attachment(doc.pdf_begin, cur_obj)
        pdf_fo_ended = find_pdf_attachment(doc.pdf_ended, cur_obj)

        # We use pyPdf to merge all PDF in unique file
        c = StringIO()
        if len(pdf_list) > 1 or duplicate > 1:
            # content = ''
            tmp_content = PdfFileWriter()

            # We add all PDF file in a list of file pointer to close them
            # at the end of treatment
            tmp_pdf_list = []
            for curpdf in pdf_list:
                tmp_pdf_list.append(open(curpdf, 'r'))

            for fo_pdf in tmp_pdf_list:
                for x in range(0, duplicate):
                    fo_pdf.seek(0)
                    tmp_pdf = PdfFileReader(fo_pdf)
                    for page in range(tmp_pdf.getNumPages()):
                        tmp_content.addPage(tmp_pdf.getPage(page))
            else:
                tmp_content.write(c)
                # content = c.getvalue()

            # It seem there is a bug on PyPDF if we close the "fp" file,
            # we cannot call tmp_content.write(c) We received
            # an exception "ValueError: I/O operation on closed file"
            for fo_pdf in tmp_pdf_list:
                if not fo_pdf.closed:
                    fo_pdf.close()

        elif len(pdf_list) == 1:
            fp = open(pdf_list[0], 'r')
            c.write(fp.read())
            fp.close()

        # Remove all files on the disk
        for f in pdf_list:
            os.remove(f)

        # If covers, we merge PDF
        fo_merge = merge_pdf([pdf_fo_begin, c, pdf_fo_ended])
        content = fo_merge.getvalue()
        fo_merge.close()

        if not c.closed:
            c.close()

        self.obj = external_pdf(content, self.outputFormat)
        return (self.obj.content, self.outputFormat)
Ejemplo n.º 3
0
                    str(e))  # noqa
            except NameError, e:
                _logger.warning('Error %s' % str(e))
                raise EvalError(
                    _('Check Error'),
                    _('Error when check condition\n\nMessage: "%s"') %
                    str(e))  # noqa
            except AttributeError, e:
                _logger.warning('Error %s' % str(e))
                raise EvalError(
                    _('Check Error'),
                    _('Attribute error when check condition\nVerify if specify field exists and valid\n\nMessage: "%s"'
                      ) % str(e))  # noqa
            except JasperException, e:
                _logger.warning('Error %s' % str(e))
                raise JasperException(e.title, e.message)
            except Exception, e:
                _logger.warning('Error %s' % str(e))
                raise EvalError(
                    _('Check Error'),
                    _('Unknown error when check condition\nMessage: "%s"') %
                    str(e))  # noqa

        reload_ok = False
        if self.attrs['reload'] and aname:
            _logger.info(
                'Printing must be reload from attachment if exists (%s)' %
                aname)  # noqa
            aids = self.pool.get('ir.attachment').search(
                self.cr, self.uid, [('name', '=', aname),
                                    ('res_model', '=', self.model),
Ejemplo n.º 4
0
    def execute(self):
        """Launch the report and return it"""
        context = self.context.copy()

        ids = self.ids
        js_ids = self.js_obj.search(self.cr, self.uid, [('enable', '=', True)])
        if not len(js_ids):
            raise JasperException(_('Configuration Error'), _('No JasperServer configuration found!'))

        js = self.js_obj.read(self.cr, self.uid, js_ids, context=context)[0]
        log_debug('DATA:')
        log_debug('\n'.join(['%s: %s' % (x, self.data[x]) for x in self.data]))

        ##
        # For each IDS, launch a query, and return only one result
        #
        pdf_list = []
        doc_ids = self.doc_obj.search(self.cr, self.uid, [('service', '=', self.service)], context=context)
        if not doc_ids:
            raise JasperException(_('Configuration Error'), _("Service name doesn't match!"))

        def compose_path(basename):
            return js['prefix'] and '/' + js['prefix'] + '/instances/%s/%s' or basename

        doc = self.doc_obj.browse(self.cr, self.uid, doc_ids[0], context=context)
        self.attrs['attachment'] = doc.attachment
        self.attrs['reload'] = doc.attachment_use
        if not self.attrs.get('params'):
            uri = compose_path('/openerp/bases/%s/%s') % (self.cr.dbname, doc.report_unit)
            self.attrs['params'] = (doc.format, uri, doc.mode, doc.depth, {})

        one_check = {}
        one_check[doc.id] = False
        content = ''
        duplicate = 1
        for ex in ids:
            if doc.mode == 'multi':
                for d in doc.child_ids:
                    if d.only_one and one_check.get(d.id, False):
                        continue
                    self.path = compose_path('/openerp/bases/%s/%s') % (self.cr.dbname, d.report_unit)
                    (content, duplicate) = self._jasper_execute(ex, d, js, pdf_list, reload, ids, context=self.context)
                    one_check[d.id] = True
            else:
                if doc.only_one and one_check.get(doc.id, False):
                    continue
                (content, duplicate) = self._jasper_execute(ex, doc, js, pdf_list, reload, ids, context=self.context)
                one_check[doc.id] = True

        ##
        ## We use pyPdf to merge all PDF in unique file
        #
        if len(pdf_list) > 1 or duplicate > 1:
            tmp_content = PdfFileWriter()
            for pdf in pdf_list:
                for x in range(0, duplicate):
                    fp = open(pdf, 'r')
                    tmp_pdf = PdfFileReader(fp)
                    for page in range(tmp_pdf.getNumPages()):
                        tmp_content.addPage(tmp_pdf.getPage(page))
                    c = StringIO()
                    tmp_content.write(c)
                    content = c.getvalue()
                    c.close()
                    fp.close()
                    del fp
                    del c
        elif len(pdf_list) == 1:
            fp = open(pdf_list[0], 'r')
            content = fp.read()
            fp.close()
            del fp

        for f in pdf_list:
            os.remove(f)

        self.obj = external_pdf(content)
        self.obj.set_output_type(self.outputFormat)
        return (self.obj.content, self.outputFormat)
Ejemplo n.º 5
0
            except NameError, e:
                logger.warning('Error %s' % str(e))
                raise EvalError(_('Language Error'), _('Error when evaluate language\n\nMessage: "%s"') % str(e))
            except AttributeError, e:
                logger.warning('Error %s' % str(e))
                raise EvalError(_('Language Error'), _('Attribute error when evaluate language\nVerify if specify field exists and valid\n\nMessage: "%s"') % str(e))
            except Exception, e:
                logger.warning('Error %s' % str(e))
                raise EvalError(_('Language Error'), _('Unknown error when evaluate language\nMessage: "%s"') % str(e))

        # Check if we can launch this reports
        # Test can be simple, or un a function
        if current_document.check_sel != 'none':
            try:
                if current_document.check_sel == 'simple' and not eval(current_document.check_simple, {'o': cur_obj}):
                    raise JasperException(_('Check Print Error'), current_document.message_simple)
                elif current_document.check_sel == 'func' and not hasattr(self.model_obj, 'check_print'):
                    raise JasperException(_('Check Print Error'), _('"check_print" function not found in "%s" object') % self.model)
                elif current_document.check_sel == 'func' and hasattr(self.model_obj, 'check_print') and \
                        not self.model_obj.check_print(self.cr, self.uid, cur_obj, context=context):
                    raise JasperException(_('Check Print Error'), _('Function "check_print" return an error'))

            except SyntaxError, e:
                logger.warning('Error %s' % str(e))
                raise EvalError(_('Check Error'), _('Syntax error when check condition\n\nMessage: "%s"') % str(e))
            except NameError, e:
                logger.warning('Error %s' % str(e))
                raise EvalError(_('Check Error'), _('Error when check condition\n\nMessage: "%s"') % str(e))
            except AttributeError, e:
                logger.warning('Error %s' % str(e))
                raise EvalError(_('Check Error'), _('Attribute error when check condition\nVerify if specify field exists and valid\n\nMessage: "%s"') % str(e))
Ejemplo n.º 6
0
                    _('Syntax error when check condition\n\nMessage: "%s"') %
                    str(e))
            except NameError, e:
                logger.warning('Error %s' % str(e))
                raise EvalError(
                    _('Check Error'),
                    _('Error when check condition\n\nMessage: "%s"') % str(e))
            except AttributeError, e:
                logger.warning('Error %s' % str(e))
                raise EvalError(
                    _('Check Error'),
                    _('Attribute error when check condition\nVerify if specify field exists and valid\n\nMessage: "%s"'
                      ) % str(e))
            except JasperException, e:
                logger.warning('Error %s' % str(e))
                raise JasperException(e.title, e.message)
            except Exception, e:
                logger.warning('Error %s' % str(e))
                raise EvalError(
                    _('Check Error'),
                    _('Unknown error when check condition\nMessage: "%s"') %
                    str(e))

        reload_ok = False
        if self.attrs['reload'] and aname:
            logger.info(
                'Printing must be reload from attachment if exists (%s)' %
                aname)
            aids = self.pool.get('ir.attachment').search(
                self.cr, self.uid, [('name', '=', aname),
                                    ('res_model', '=', self.model),
Ejemplo n.º 7
0
                    _('Attribute error when evaluate language\nVerify if specify field exists and valid\n\nMessage: "%s"'
                      ) % str(e))
            except Exception, e:
                _logger.warning('Error %s' % str(e))
                raise EvalError(
                    _('Language Error'),
                    _('Unknown error when evaluate language\nMessage: "%s"') %
                    str(e))

        # Check if we can launch this reports
        # Test can be simple, or un a function
        if current_document.check_sel != 'none':
            try:
                if current_document.check_sel == 'simple' and not eval(
                        current_document.check_simple, {'o': cur_obj}):
                    raise JasperException(_('Check Print Error'),
                                          current_document.message_simple)
                elif current_document.check_sel == 'func' and not hasattr(
                        self.model_obj, 'check_print'):
                    raise JasperException(
                        _('Check Print Error'),
                        _('"check_print" function not found in "%s" object') %
                        self.model)
                elif current_document.check_sel == 'func' and hasattr(self.model_obj, 'check_print') and \
                        not self.model_obj.check_print(self.cr, self.uid, cur_obj, context=context):
                    raise JasperException(
                        _('Check Print Error'),
                        _('Function "check_print" return an error'))

            except SyntaxError, e:
                _logger.warning('Error %s' % str(e))
                raise EvalError(