Example #1
0
 def get_report(self,
                model,
                options,
                output_format,
                token,
                report_id=None,
                **kw):
     uid = request.session.uid
     report_obj = request.env[model].sudo(uid)
     options = json.loads(options)
     if report_id:
         report_obj = report_obj.browse(int(report_id))
     report_name = report_obj.get_report_filename(options)
     try:
         if output_format == 'xlsx':
             response = request.make_response(
                 None,
                 headers=[('Content-Type', 'application/vnd.ms-excel'),
                          ('Content-Disposition',
                           content_disposition(report_name + '.xlsx'))])
             report_obj.get_xlsx(options, response)
         if output_format == 'pdf':
             response = request.make_response(
                 report_obj.get_pdf(options),
                 headers=[('Content-Type', 'application/pdf'),
                          ('Content-Disposition',
                           content_disposition(report_name + '.pdf'))])
         response.set_cookie('fileToken', token)
         return response
     except Exception as e:
         se = _serialize_exception(e)
         error = {'code': 200, 'message': 'Odoo Server Error', 'data': se}
         return request.make_response(html_escape(json.dumps(error)))
Example #2
0
    def get_report_xlsx(self, model, output_format, report_name, **kw):

        uid = request.session.uid

        report_obj = request.env[model].sudo(uid)
        data = {
            'start_date': time.strftime('%Y-%m-01'),
            'end_date': datetime.datetime.now()
        }

        options = json.loads(json.dumps(data, default=date_utils.json_default))

        try:

            if output_format == 'xlsx':

                response = request.make_response(
                    None,
                    headers=[('Content-Type', 'application/vnd.ms-excel'),
                             ('Content-Disposition',
                              content_disposition(report_name + '.xlsx'))])

                report_obj.get_xlsx_report(options, response)

            return response

        except Exception as e:

            se = _serialize_exception(e)

            error = {'code': 200, 'message': 'Odoo Server Error', 'data': se}

            return request.make_response(html_escape(json.dumps(error)))
Example #3
0
    def report(self, output_format, report_name, token, report_id=None, **kw):
        uid = request.session.uid
        context_obj = request.env['ss.forecast.renew.service.report.context']
        context = context_obj.sudo().browse(int(report_id))

        try:
            if output_format == 'xlsx':
                response = request.make_response(
                    None,
                    headers=[('Content-Type', 'application/vnd.ms-excel'),
                             ('Content-Disposition',
                              'attachment; filename=service_report.xlsx;')])
                context.get_xlsx(response)
                response.set_cookie('fileToken', token)
                return response
            if output_format == 'pdf':
                response = request.make_response(
                    context.get_pdf(),
                    headers=[('Content-Type', 'application/pdf'),
                             ('Content-Disposition',
                              'attachment; filename=service_report.pdf;')])
                response.set_cookie('fileToken', token)
                return response
        except Exception, e:
            se = _serialize_exception(e)
            error = {'code': 200, 'message': 'Odoo Server Error', 'data': se}
            return request.make_response(html_escape(json.dumps(error)))
Example #4
0
 def wrap(*args, **kwargs):
     try:
         return f(*args, **kwargs)
     except Exception, e:
         _logger.exception("An exception occured during an http request")
         se = _serialize_exception(e)
         error = {'code': 200, 'message': "Odoo Server Error", 'data': se}
         return werkzeug.exceptions.InternalServerError(
             simplejson.dumps(error))
Example #5
0
 def report(self, output_format, report_name, token, report_id=None, **kw):
     uid = request.session.uid
     domain = [('create_uid', '=', uid)]
     report_model = request.env['account.report.context.common'].get_full_report_name_by_report_name(report_name)
     report_obj = request.env[report_model].sudo(uid)
     if report_name == 'financial_report':
         report_id = int(report_id)
         domain.append(('report_id', '=', report_id))
         report_obj = report_obj.browse(report_id)
     context_obj = request.env['account.report.context.common'].get_context_by_report_name(report_name)
     context_id = context_obj.sudo(uid).search(domain, limit=1)
     try:
         if output_format == 'xlsx':
             response = request.make_response(
                 None,
                 headers=[
                     ('Content-Type', 'application/vnd.ms-excel'),
                     ('Content-Disposition', 'attachment; filename=' + report_obj.get_name() + '.xlsx;')
                 ]
             )
             context_id.get_xlsx(response)
             response.set_cookie('fileToken', token)
             return response
         if output_format == 'pdf':
             response = request.make_response(
                 context_id.get_pdf(),
                 headers=[
                     ('Content-Type', 'application/pdf'),
                     ('Content-Disposition', 'attachment; filename=' + report_obj.get_name() + '.pdf;')
                 ]
             )
             response.set_cookie('fileToken', token)
             return response
         if output_format == 'xml':
             content = context_id.get_xml()
             response = request.make_response(
                 content,
                 headers=[
                     ('Content-Type', 'application/vnd.sun.xml.writer'),
                     ('Content-Disposition', 'attachment; filename=' + report_obj.get_name() + '.xml;'),
                     ('Content-Length', len(content))
                 ]
             )
             response.set_cookie('fileToken', token)
             return response
     except Exception, e:
         se = _serialize_exception(e)
         error = {
             'code': 200,
             'message': 'Odoo Server Error',
             'data': se
         }
         return request.make_response(html_escape(json.dumps(error)))
Example #6
0
    def report_download(self, data, token):
        """This function is used by 'qwebactionmanager.js' in order to trigger the download of
        a pdf/controller report.

        :param data: a javascript array JSON.stringified containg report internal url ([0]) and
        type [1]
        :returns: Response with a filetoken cookie and an attachment header
        """
        requestcontent = json.loads(data)
        url, type = requestcontent[0], requestcontent[1]
        try:
            if type == 'qweb-pdf':
                reportname = url.split('/report/pdf/')[1].split('?')[0]

                docids = None
                if '/' in reportname:
                    reportname, docids = reportname.split('/')

                if docids:
                    # Generic report:
                    response = self.report_routes(reportname, docids=docids, converter='pdf')
                else:
                    # Particular report:
                    data = url_decode(url.split('?')[1]).items()  # decoding the args represented in JSON
                    response = self.report_routes(reportname, converter='pdf', **dict(data))

                report = request.env['report']._get_report_from_name(reportname)
                filename = "%s.%s" % (report.name, "pdf")
                if docids:
                    ids = [int(x) for x in docids.split(",")]
                    obj = request.env[report.model].browse(ids)
                    if report.print_report_name and not len(obj) > 1:
                        report_name = safe_eval(report.print_report_name, {'object': obj, 'time': time})
                        filename = "%s.%s" % (report_name, "pdf")
                response.headers.add('Content-Disposition', content_disposition(filename))
                response.set_cookie('fileToken', token)
                return response
            elif type == 'controller':
                reqheaders = Headers(request.httprequest.headers)
                response = Client(request.httprequest.app, BaseResponse).get(url, headers=reqheaders, follow_redirects=True)
                response.set_cookie('fileToken', token)
                return response
            else:
                return
        except Exception, e:
            se = _serialize_exception(e)
            error = {
                'code': 200,
                'message': "Odoo Server Error",
                'data': se
            }
            return request.make_response(html_escape(json.dumps(error)))
Example #7
0
File: main.py Project: befks/odoo
    def report_download(self, data, token):
        """This function is used by 'qwebactionmanager.js' in order to trigger the download of
        a pdf/controller report.

        :param data: a javascript array JSON.stringified containg report internal url ([0]) and
        type [1]
        :returns: Response with a filetoken cookie and an attachment header
        """
        requestcontent = json.loads(data)
        url, type = requestcontent[0], requestcontent[1]
        try:
            if type == 'qweb-pdf':
                reportname = url.split('/report/pdf/')[1].split('?')[0]

                docids = None
                if '/' in reportname:
                    reportname, docids = reportname.split('/')

                if docids:
                    # Generic report:
                    response = self.report_routes(reportname, docids=docids, converter='pdf')
                else:
                    # Particular report:
                    data = url_decode(url.split('?')[1]).items()  # decoding the args represented in JSON
                    response = self.report_routes(reportname, converter='pdf', **dict(data))

                report = request.env['report']._get_report_from_name(reportname)
                filename = "%s.%s" % (report.name, "pdf")
                if docids:
                    ids = [int(x) for x in docids.split(",")]
                    obj = request.env[report.model].browse(ids)
                    if report.print_report_name and not len(obj) > 1:
                        report_name = safe_eval(report.print_report_name, {'object': obj, 'time': time})
                        filename = "%s.%s" % (report_name, "pdf")
                response.headers.add('Content-Disposition', content_disposition(filename))
                response.set_cookie('fileToken', token)
                return response
            elif type == 'controller':
                reqheaders = Headers(request.httprequest.headers)
                response = Client(request.httprequest.app, BaseResponse).get(url, headers=reqheaders, follow_redirects=True)
                response.set_cookie('fileToken', token)
                return response
            else:
                return
        except Exception as e:
            se = _serialize_exception(e)
            error = {
                'code': 200,
                'message': "Odoo Server Error",
                'data': se
            }
            return request.make_response(html_escape(json.dumps(error)))
 def wrap(*args, **kwargs):
     try:
         return f(*args, **kwargs)
     except Exception, e:
         _logger.exception("An exception occured during an http request")
         se = _serialize_exception(e)
         error = {
             'code': 200,
             'message': "Odoo Server Error",
             'data': se
         }
         return werkzeug.exceptions.InternalServerError(
             simplejson.dumps(error))
Example #9
0
 def report(self, output_format, report_name, token, report_id=False, **kw):
     coa = request.env['account.open.chart'].browse(report_id)
     #         line_data = json.loads(kw['data'])
     try:
         if output_format == 'pdf':
             response = request.make_response(
                 coa.with_context(active_id=report_id).get_pdf(report_id),
                 headers=[('Content-Type', 'application/pdf'),
                          ('Content-Disposition',
                           'attachment; filename=coa_report.pdf;')])
             response.set_cookie('fileToken', token)
             return response
     except Exception as e:
         se = _serialize_exception(e)
         error = {'code': 200, 'message': 'Odoo Server Error', 'data': se}
         return request.make_response(html_escape(json.dumps(error)))
Example #10
0
 def dispatch_file(self, data, token):
     _data = json.loads(data)
     _obj_class = request.env[_data['model']]
     _obj = _obj_class.search([('id', '=', _data['record_id'])])[0]
     try:
         response = request.make_response(
             _obj.get_file(),
             headers=[('Content-Type', _obj.get_content_type()),
                      ('Content-Disposition',
                       u'attachment; filename=' + _obj.get_filename() + ';')
                      ],
             cookies={'fileToken': token})
         return response
     except Exception, e:
         se = _serialize_exception(e)
         error = {'code': 200, 'message': 'Odoo Server Error', 'data': se}
         return request.make_response(html_escape(json.dumps(error)))
 def get_report(self, body_html, output_format, token, **kw):
     uid = request.session.uid
     report_obj = request.env['sale.subscription'].with_user(uid)
     report_name = report_obj.get_report_filename()
     try:
         if output_format == 'pdf':
             response = request.make_response(
                 report_obj.get_pdf(body_html),
                 headers=[('Content-Type',
                           report_obj.get_export_mime_type('pdf')),
                          ('Content-Disposition',
                           content_disposition(report_name + '.pdf'))])
         response.set_cookie('fileToken', token)
         return response
     except Exception as e:
         se = _serialize_exception(e)
         error = {'code': 200, 'message': 'Odoo Server Error', 'data': se}
         return request.make_response(html_escape(json.dumps(error)))
Example #12
0
File: main.py Project: veivaa/odoo
 def report(self, output_format, report_name, report_id=False, **kw):
     uid = request.session.uid
     domain = [('create_uid', '=', uid)]
     stock_traceability = request.env[
         'stock.traceability.report'].with_user(uid).search(domain, limit=1)
     line_data = json.loads(kw['data'])
     try:
         if output_format == 'pdf':
             response = request.make_response(
                 stock_traceability.with_context(
                     active_id=report_id).get_pdf(line_data),
                 headers=[('Content-Type', 'application/pdf'),
                          ('Content-Disposition', 'attachment; filename=' +
                           'stock_traceability' + '.pdf;')])
             return response
     except Exception as e:
         se = _serialize_exception(e)
         error = {'code': 200, 'message': 'Odoo Server Error', 'data': se}
         return request.make_response(html_escape(json.dumps(error)))
Example #13
0
 def get_report(self, report_id, **kw):
     output_format = 'xlsx'
     model = 'payroll.wage.history.excel.report'
     options = {'report_id': report_id}
     report_obj = request.env[model].sudo()
     report_name = 'Payroll Wage History Summary'
     try:
         if output_format == 'xlsx':
             response = request.make_response(
                 None,
                 headers=[('Content-Type', 'application/vnd.ms-excel'),
                          ('Content-Disposition',
                           content_disposition(report_name + '.xlsx'))])
             report_obj.get_xlsx(options, response)
         return response
     except Exception as e:
         se = _serialize_exception(e)
         error = {'code': 200, 'message': 'Odoo Server Error', 'data': se}
         return request.make_response(html_escape(json.dumps(error)))
Example #14
0
 def followup(self, partners, token, **kw):
     uid = request.session.uid
     try:
         context_obj = request.env['account.report.context.followup']
         partners = request.env['res.partner'].browse(
             [int(i) for i in partners.split(',')])
         context_ids = context_obj.search([('partner_id', 'in',
                                            partners.ids),
                                           ('create_uid', '=', uid)])
         response = request.make_response(
             context_ids.with_context(public=True).get_pdf(log=True),
             headers=[('Content-Type', 'application/pdf'),
                      ('Content-Disposition',
                       'attachment; filename=payment_reminder.pdf;')])
         response.set_cookie('fileToken', token)
         return response
     except Exception, e:
         se = _serialize_exception(e)
         error = {'code': 200, 'message': 'Odoo Server Error', 'data': se}
         return request.make_response(html_escape(json.dumps(error)))
Example #15
0
    def report_download(self, data, token):
        """This function is used by 'qwebactionmanager.js' in order to trigger
        the download of a py3o/controller report.

        :param data: a javascript array JSON.stringified containg report
        internal url ([0]) and type [1]
        :returns: Response with a filetoken cookie and an attachment header
        """
        requestcontent = json.loads(data)
        url, type = requestcontent[0], requestcontent[1]
        if type != 'aeroo':
            return super(ReportController, self).report_download(data, token)
        try:
            reportname = url.split('/report/aeroo/')[1].split('?')[0]
            docids = None
            if '/' in reportname:
                reportname, docids = reportname.split('/')

            # on aeroo we support docids + data
            data = url_decode(url.split('?')[1]).items()
            response = self.report_routes(reportname,
                                          docids=docids,
                                          converter='aeroo',
                                          **dict(data))
            # if docids:
            #     # Generic report:
            #     response = self.report_routes(
            #         reportname, docids=docids, converter='aeroo')
            # else:
            #     # Particular report:
            #     # decoding the args represented in JSON
            #     data = url_decode(url.split('?')[1]).items()
            #     response = self.report_routes(
            #         reportname, converter='aeroo', **dict(data))
            response.set_cookie('fileToken', token)
            return response
        except Exception as e:
            se = _serialize_exception(e)
            error = {'code': 200, 'message': "Odoo Server Error", 'data': se}
            return request.make_response(html_escape(json.dumps(error)))
Example #16
0
 def report_excel(self,
                  id=None,
                  model='ir.attachment',
                  output_format='xlsx',
                  report_name=None,
                  token=None,
                  report_id=None,
                  filename=None,
                  download=None,
                  **kw):
     uid = request.session.uid
     domain = [('id', '=', id), ('create_uid', '=', uid)]
     context_id = request.env[model].sudo().search(domain, limit=1)
     attach_fpath = ''
     attach_fname = ''
     if context_id:
         attach_fname = context_id['name']
         store_fname = context_id['store_fname']
         attach_fpath = context_id._full_path(store_fname)
     filename = attach_fname if not filename else filename
     filename_attachment = 'attachment; filename=' + filename + ';'
     filename_attachment = filename_attachment.encode('utf-8')
     try:
         with open(attach_fpath, "rb") as f:
             content = f.read()
             f.close()
         if ".".join(filename.split('.')[1:]) in SUPPORTED_FORMATS:
             response = request.make_response(
                 content,
                 headers=[('Content-Type', 'application/vnd.ms-excel'),
                          ('Content-Disposition', filename_attachment),
                          ('Content-Length', len(content))])
             return response
     except Exception as e:
         se = _serialize_exception(e)
         error = {'code': 200, 'message': 'Odoo Server Error', 'data': se}
         return request.make_response(html_escape(json.dumps(error)))
     else:
         return request.not_found()
Example #17
0
    def get_report_xlsx(self, model, options, output_format, token,
                        report_data, report_name, dfr_data, **kw):

        uid = request.session.uid
        report_obj = request.env[model].with_user(uid)
        dfr_data = dfr_data
        options = options
        try:
            if output_format == 'xlsx':
                response = request.make_response(
                    None,
                    headers=[('Content-Type', 'application/vnd.ms-excel'),
                             ('Content-Disposition',
                              content_disposition(report_name + '.xlsx'))])
                report_obj.get_dynamic_xlsx_report(options, response,
                                                   report_data, dfr_data)
            response.set_cookie('fileToken', token)
            return response
        except Exception as e:
            se = _serialize_exception(e)
            error = {'code': 200, 'message': 'Odoo Server Error', 'data': se}
            return request.make_response(html_escape(json.dumps(error)))
Example #18
0
    def report_download(self, data, token, context=None):
        """This function is used by 'qwebactionmanager.js' in order to trigger
        the download of a py3o/controller report.

        :param data: a javascript array JSON.stringified containg report
        internal url ([0]) and type [1]
        :returns: Response with a filetoken cookie and an attachment header
        """
        requestcontent = json.loads(data)
        url, report_type = requestcontent[0], requestcontent[1]
        if "py3o" not in report_type:
            return super(ReportController,
                         self).report_download(data, token, context)
        try:
            reportname = url.split("/report/py3o/")[1].split("?")[0]
            docids = None
            if "/" in reportname:
                reportname, docids = reportname.split("/")

            if docids:
                # Generic report:
                response = self.report_routes(reportname,
                                              docids=docids,
                                              converter="py3o")
            else:
                # Particular report:
                # decoding the args represented in JSON
                data = list(url_decode(url.split("?")[1]).items())
                response = self.report_routes(reportname,
                                              converter="py3o",
                                              **dict(data))
            response.set_cookie("fileToken", token)
            return response
        except Exception as e:
            se = _serialize_exception(e)
            error = {"code": 200, "message": "Odoo Server Error", "data": se}
            return request.make_response(html_escape(json.dumps(error)))
Example #19
0
File: main.py Project: 10537/odoo
 def report(self, output_format, report_name, token, report_id=False, **kw):
     uid = request.session.uid
     domain = [('create_uid', '=', uid)]
     stock_traceability = request.env['stock.traceability.report'].sudo(uid).search(domain, limit=1)
     line_data = json.loads(kw['data'])
     try:
         if output_format == 'pdf':
             response = request.make_response(
                 stock_traceability.with_context(active_id=report_id).get_pdf(line_data),
                 headers=[
                     ('Content-Type', 'application/pdf'),
                     ('Content-Disposition', 'attachment; filename=' + 'stock_traceability' + '.pdf;')
                 ]
             )
             response.set_cookie('fileToken', token)
             return response
     except Exception as e:
         se = _serialize_exception(e)
         error = {
             'code': 200,
             'message': 'Odoo Server Error',
             'data': se
         }
         return request.make_response(html_escape(json.dumps(error)))
Example #20
0
 def get_report(self,
                model,
                options,
                output_format,
                token,
                financial_id=None,
                **kw):
     uid = request.session.uid
     account_report_model = request.env['account.report']
     options = json.loads(options)
     cids = request.httprequest.cookies.get(
         'cids', str(request.env.user.company_id.id))
     allowed_company_ids = [int(cid) for cid in cids.split(',')]
     report_obj = request.env[model].with_user(uid).with_context(
         allowed_company_ids=allowed_company_ids)
     if financial_id and financial_id != 'null':
         report_obj = report_obj.browse(int(financial_id))
     report_name = report_obj.get_report_filename(options)
     try:
         response = None
         if output_format == 'xlsx':
             response = request.make_response(
                 None,
                 headers=[
                     ('Content-Type',
                      account_report_model.get_export_mime_type('xlsx')),
                     ('Content-Disposition',
                      content_disposition(report_name + '.xlsx'))
                 ])
             response.stream.write(report_obj.advanced_get_xlsx(options))
         response.set_cookie('fileToken', token)
         return response
     except Exception as e:
         se = _serialize_exception(e)
         error = {'code': 200, 'message': 'Odoo Server Error', 'data': se}
         return request.make_response(html_escape(json.dumps(error)))
Example #21
0
 def get_statement_report_custom(self, model, **kw):
     if not request.env.user.partner_id.allow_print_statement_portal:
         return request.redirect("/")
     if kw.get('report_type') == 'excel':
         uid = request.session.uid
         account_report_model = request.env['account.report']
         options = self._get_statement_report_options_custom(**kw)
         cids = request.httprequest.cookies.get(
             'cids',
             str(request.website.company_id.id
                 or request.env.user.company_id.id))
         allowed_company_ids = [int(cid) for cid in cids.split(',')]
         report_obj = request.env[model].with_user(uid).with_context(
             allowed_company_ids=allowed_company_ids).sudo()
         report_name = report_obj.get_report_filename(options)
         try:
             response = request.make_response(
                 report_obj.get_xlsx(options),
                 headers=[
                     ('Content-Type',
                      account_report_model.get_export_mime_type('xlsx')),
                     ('Content-Disposition',
                      content_disposition(report_name + '.xlsx'))
                 ])
             return response
         except Exception as e:
             se = _serialize_exception(e)
             error = {
                 'code': 200,
                 'message': 'Odoo Server Error',
                 'data': se
             }
             return request.make_response(html_escape(json.dumps(error)))
     else:
         return super(CustomerPortal,
                      self).get_statement_report_custom(model, **kw)
Example #22
0
 def get_report(self,
                model,
                options,
                output_format,
                token,
                financial_id=None,
                **kw):
     uid = request.session.uid
     account_report_model = request.env['account.report']
     options = json.loads(options)
     report_obj = request.env[model].with_user(uid)
     if not options.get('multi_company'):
         cids = request.httprequest.cookies.get(
             'cids', str(request.env.user.company_id.id))
         allowed_company_ids = [int(cid) for cid in cids.split(',')]
         report_obj = report_obj.with_context(
             allowed_company_ids=allowed_company_ids)
     if financial_id and financial_id != 'null':
         report_obj = report_obj.browse(int(financial_id))
     report_name = report_obj.get_report_filename(options)
     try:
         if output_format == 'xlsx':
             response = request.make_response(
                 None,
                 headers=[
                     ('Content-Type',
                      account_report_model.get_export_mime_type('xlsx')),
                     ('Content-Disposition',
                      content_disposition(report_name + '.xlsx'))
                 ])
             response.stream.write(report_obj.get_xlsx(options))
         if output_format == 'pdf':
             response = request.make_response(
                 report_obj.get_pdf(options),
                 headers=[
                     ('Content-Type',
                      account_report_model.get_export_mime_type('pdf')),
                     ('Content-Disposition',
                      content_disposition(report_name + '.pdf'))
                 ])
         if output_format == 'xml':
             content = report_obj.get_xml(options)
             response = request.make_response(
                 content,
                 headers=[
                     ('Content-Type',
                      account_report_model.get_export_mime_type('xml')),
                     ('Content-Disposition',
                      content_disposition(report_name + '.xml')),
                     ('Content-Length', len(content))
                 ])
         if output_format == 'xaf':
             content = report_obj.get_xaf(options)
             response = request.make_response(
                 content,
                 headers=[
                     ('Content-Type',
                      account_report_model.get_export_mime_type('xaf')),
                     ('Content-Disposition',
                      content_disposition(report_name + '.xaf')),
                     ('Content-Length', len(content))
                 ])
         if output_format == 'txt':
             content = report_obj.get_txt(options)
             response = request.make_response(
                 content,
                 headers=[
                     ('Content-Type',
                      account_report_model.get_export_mime_type('txt')),
                     ('Content-Disposition',
                      content_disposition(report_name + '.txt')),
                     ('Content-Length', len(content))
                 ])
         if output_format == 'csv':
             content = report_obj.get_csv(options)
             response = request.make_response(
                 content,
                 headers=[
                     ('Content-Type',
                      account_report_model.get_export_mime_type('csv')),
                     ('Content-Disposition',
                      content_disposition(report_name + '.csv')),
                     ('Content-Length', len(content))
                 ])
         if output_format == 'zip':
             content = report_obj.get_zip(options)
             response = request.make_response(
                 content,
                 headers=[
                     ('Content-Type',
                      account_report_model.get_export_mime_type('zip')),
                     ('Content-Disposition',
                      content_disposition(report_name + '.zip')),
                 ])
             # Adding direct_passthrough to the response and giving it a file
             # as content means that we will stream the content of the file to the user
             # Which will prevent having the whole file in memory
             response.direct_passthrough = True
         response.set_cookie('fileToken', token)
         return response
     except Exception as e:
         se = _serialize_exception(e)
         error = {'code': 200, 'message': 'Odoo Server Error', 'data': se}
         return request.make_response(html_escape(json.dumps(error)))
Example #23
0
 def process_error(self, e, debug=False):
     error = _serialize_exception(e)
     if error.get('debug') and not debug:
         del error['debug']
     return error
Example #24
0
    def report(self, output_format, report_name, token, report_id=False, **kw):
        accounts_hierarchy_obj = request.env['accounts.hierarchy'].sudo(
        ).browse(report_id)
        try:
            if output_format == 'pdf':
                response = request.make_response(
                    accounts_hierarchy_obj.with_context(
                        active_id=report_id).get_pdf(),
                    headers=[('Content-Type', 'application/pdf'),
                             ('Content-Disposition', 'attachment; filename=' +
                              'accounts_hierarchy' + '.pdf;')])
                response.set_cookie('fileToken', token)
                return response
            if output_format == "xls":
                wizard_obj = request.env['accounts.hierarchy'].sudo().browse(
                    report_id)
                heading = request.env['res.company'].browse(
                    wizard_obj.company_id.id).name
                lines = request.env['accounts.hierarchy'].with_context(
                    print_mode=True,
                    output_format=output_format).sudo().get_pdf_lines(
                        report_id)
                if lines:
                    if len(lines) > 65535:
                        raise UserError(
                            _('There are too many rows (%s rows, limit: 65535) to export as Excel 97-2003 (.xls) format.'
                              ) % len(lines))
                    workbook = xlwt.Workbook()
                    sheet = workbook.add_sheet('Chart of Account')

                    normal = xlwt.easyxf(
                        'font: name Times New Roman ;align: horiz left;',
                        num_format_str='#,##0.00')
                    bold = xlwt.easyxf(
                        'font: name Times New Roman bold ;align: horiz left;',
                        num_format_str='#,##0.00')
                    head = xlwt.easyxf(
                        'font: name Times New Roman bold ;align: horiz centre, vert centre;',
                        num_format_str='#,##0.00')
                    if heading:
                        sheet.write_merge(
                            0, 1, 0, 5,
                            'Chart of Account Hierarchy for ' + heading + '',
                            bold)
                    else:
                        sheet.write_merge(0, 1, 0, 5,
                                          'Chart of Account Hierarchy', head)

                    sheet.write(3, 0, 'Code', bold)
                    sheet.write(3, 1, 'Name', bold)
                    sheet.write(3, 2, 'Type', bold)
                    sheet.write(3, 3, 'Debit', bold)
                    sheet.write(3, 4, 'Credit', bold)
                    sheet.write(3, 5, 'Balance', bold)

                    i = 4

                    for line in lines:
                        sheet.write(i, 0, line['columns'][0] or '', normal)
                        sheet.write(i, 1, line['columns'][1] or '', normal)
                        sheet.write(i, 2, line['columns'][2] or '', normal)
                        sheet.write(i, 3,
                                    html2plaintext(line['columns'][3]) or '0',
                                    normal)
                        sheet.write(i, 4,
                                    html2plaintext(line['columns'][4]) or '0',
                                    normal)
                        sheet.write(i, 5,
                                    html2plaintext(line['columns'][5]) or '0',
                                    normal)
                        i += 1
                    fp = io.BytesIO()
                    workbook.save(fp)
                    data = fp.getvalue()
                    fp.close()

                response = request.make_response(
                    data,
                    headers=[('Content-Type', 'application/vnd.ms-excel'),
                             ('Content-Disposition',
                              'attachment; filename=coahiearchy.xls')],
                    cookies={'fileToken': token})
                return response

        except Exception as e:
            se = _serialize_exception(e)
            error = {'code': 200, 'message': 'Odoo Server Error', 'data': se}
            return request.make_response(html_escape(json.dumps(error)))
Example #25
0
    def report_download(self, data, token):

        requestcontent = json.loads(data)

        url, type = requestcontent[0], requestcontent[1]
        try:
            if type == 'qweb-pdf':
                reportname = url.split('/report/pdf/')[1].split('?')[0]
                docids = None
                if '/' in reportname:
                    reportname, docids = reportname.split('/')

                if docids:
                    # Generic report:
                    response = self.report_routes(reportname,
                                                  docids=docids,
                                                  converter='pdf')
                else:
                    # Particular report:
                    data = url_decode(url.split(
                        '?')[1])  # decoding the args represented in JSON
                    response = self.report_routes(reportname,
                                                  converter='pdf',
                                                  **dict(data))
                    temp_dict = {}
                    temp_dict.update(json.loads(dict(data).pop('options')))

                    if 'skit_report_type' in temp_dict.keys(
                    ) and temp_dict['skit_report_type'] == 'XLS':
                        report = request.env[
                            'ir.actions.report']._get_report_from_name(
                                reportname)
                        filename = "%s.%s" % (report.name, "xls")
                        # Customize the report name must be what we want
                        # from print xls report ,pass the report_name and customize it.
                        # code added for skit.event.report module execute same model for all event report
                        if 'report_name' in temp_dict.keys(
                        ) and temp_dict['skit_report_type'] == 'XLS':
                            filename = "%s.%s" % (temp_dict['report_name'],
                                                  "xls")
                        response.headers.add('Content-Disposition',
                                             content_disposition(filename))
                        response.set_cookie('fileToken', token)
                        return response

                report = request.env[
                    'ir.actions.report']._get_report_from_name(reportname)
                filename = "%s.%s" % (report.name, "pdf")
                response.headers.add('Content-Disposition',
                                     content_disposition(filename))
                response.set_cookie('fileToken', token)
                return response
            elif type == 'controller':
                reqheaders = Headers(request.httprequest.headers)
                response = Client(request.httprequest.app,
                                  BaseResponse).get(url,
                                                    headers=reqheaders,
                                                    follow_redirects=True)
                response.set_cookie('fileToken', token)
                return response
            else:
                return
        except Exception as e:
            se = _serialize_exception(e)
            error = {'code': 200, 'message': "Odoo Server Error", 'data': se}
            return request.make_response(html_escape(json.dumps(error)))
Example #26
0
 def get_report(self,
                model,
                options,
                output_format,
                token,
                financial_id=None,
                **kw):
     uid = request.session.uid
     report_obj = request.env[model].sudo(uid)
     options = json.loads(options)
     if financial_id and financial_id != 'null':
         report_obj = report_obj.browse(int(financial_id))
     report_name = report_obj.get_report_filename(options)
     try:
         if output_format == 'xlsx':
             response = request.make_response(
                 None,
                 headers=[('Content-Type', 'application/vnd.ms-excel'),
                          ('Content-Disposition',
                           content_disposition(report_name + '.xlsx'))])
             report_obj.get_xlsx(options, response)
         if output_format == 'pdf':
             response = request.make_response(
                 report_obj.get_pdf(options),
                 headers=[('Content-Type', 'application/pdf'),
                          ('Content-Disposition',
                           content_disposition(report_name + '.pdf'))])
         if output_format == 'xml':
             content = report_obj.get_xml(options)
             response = request.make_response(
                 content,
                 headers=[('Content-Type',
                           'application/vnd.sun.xml.writer'),
                          ('Content-Disposition',
                           content_disposition(report_name + '.xml')),
                          ('Content-Length', len(content))])
         if output_format == 'xaf':
             content = report_obj.get_xaf(options)
             response = request.make_response(
                 content,
                 headers=[('Content-Type',
                           'application/vnd.sun.xml.writer'),
                          ('Content-Disposition',
                           content_disposition(report_name + '.xaf')),
                          ('Content-Length', len(content))])
         if output_format == 'txt':
             content = report_obj.get_txt(options)
             response = request.make_response(
                 content,
                 headers=[('Content-Type', 'text/plain'),
                          ('Content-Disposition',
                           content_disposition(report_name + '.txt')),
                          ('Content-Length', len(content))])
         if output_format == 'csv':
             content = report_obj.get_csv(options)
             response = request.make_response(
                 content,
                 headers=[('Content-Type', 'text/csv'),
                          ('Content-Disposition',
                           content_disposition(report_name + '.csv')),
                          ('Content-Length', len(content))])
         if output_format == 'zip':
             content = report_obj._get_zip(options)
             response = request.make_response(
                 content,
                 headers=[
                     ('Content-Type', 'application/zip'),
                     ('Content-Disposition',
                      content_disposition(report_name + '.zip')),
                 ])
             # Adding direct_passthrough to the response and giving it a file
             # as content means that we will stream the content of the file to the user
             # Which will prevent having the whole file in memory
             response.direct_passthrough = True
         response.set_cookie('fileToken', token)
         return response
     except Exception as e:
         se = _serialize_exception(e)
         error = {'code': 200, 'message': 'Odoo Server Error', 'data': se}
         return request.make_response(html_escape(json.dumps(error)))
    def report_download(self, data, token):
        """This function is used by 'qwebactionmanager.js' in order to trigger
        the download of a py3o/controller report, and convert report from ods
        to xlsx with libreoffice

        :param data: a javascript array JSON.stringified containg report
        internal url ([0]) and type [1]
        :returns: Response with a filetoken cookie and an attachment header
        """
        response = super(ReportController, self).report_download(data, token)
        if self.ODS_FILE_TYPE in response.content_type:
            requestcontent = json.loads(data)
            url, type = requestcontent[0], requestcontent[1]
            if type != 'py3o':
                return super(ReportController, self).report_download(
                    data,
                    token
                )
            try:
                reportname = url.split('/report/py3o/')[1].split('?')[0]
                if '/' in reportname:
                    reportname, docids = reportname.split('/')
                with open(os.path.dirname(__file__) + '/' +
                          reportname + '.ods', 'a+') as create_ods:
                    create_ods.write(response.data)
                os.system(
                    "libreoffice --headless --convert-to xlsx --outdir '" +
                    os.path.dirname(
                        __file__) + "' '" + os.path.dirname(
                        __file__) + "/" + reportname + ".ods'")
                with open(os.path.dirname(__file__) + '/' +
                          reportname + '.xlsx', 'r+') as create_xlsx:
                    res = create_xlsx.read()
                os.remove(
                    os.path.dirname(__file__) + '/' + reportname + '.ods'
                )
                os.remove(
                    os.path.dirname(__file__) + '/' + reportname + '.xlsx'
                )
                ir_action = request.env['ir.actions.report.xml']
                action_py3o_report = ir_action.get_from_report_name(
                    reportname, "py3o").with_context(request.env.context)
                filename = action_py3o_report.gen_report_download_filename(
                    docids, data)
                filename_without_type = filename.split('.')[0]
                content_type = mimetypes.guess_type("x.xlsx")[0]
                http_headers = [
                    ('Content-Type',
                     content_type),
                    ('Content-Length',
                     len(res)),
                    ('Content-Disposition',
                     content_disposition(
                         filename_without_type +
                         '.xlsx'))]
                response = request.make_response(res, headers=http_headers)
                response.set_cookie('fileToken', token)
                return response
            except Exception as e:
                se = _serialize_exception(e)
                error = {
                    'code': 200,
                    'message': "Odoo Server Error",
                    'data': se
                }
                return request.make_response(html_escape(json.dumps(error)))
        else:
            return response
Example #28
0
    def report_download(self, data, token):
        """This function is used by 'qwebactionmanager.js' in order to trigger the download of
        a pdf/controller report.

        :param data: a javascript array JSON.stringified containg report internal url ([0]) and
        type [1]
        :returns: Response with a filetoken cookie and an attachment header
        """
        requestcontent = json.loads(data)
        url, type = requestcontent[0], requestcontent[1]
        try:
            if type == 'qweb-pdf':
                reportname = url.split('/report/pdf/')[1].split('?')[0]

                docids = None
                if '/' in reportname:
                    reportname, docids = reportname.split('/')

                if docids:
                    # Generic report:
                    response = self.report_routes(reportname, docids=docids, converter='pdf')
                else:
                    # Particular report:
                    data = url_decode(url.split('?')[1]).items()  # decoding the args represented in JSON
                    response = self.report_routes(reportname, converter='pdf', **dict(data))

                report = request.env['report']._get_report_from_name(reportname)
                filename = "%s.%s" % (report.name, "pdf")
                #Sale Order
                if report.report_name == 'solum_sale.sol_quotation_report_template_id':
                    so_pool = request.env['sale.order']
                    lst_so = []
                    lst_so = docids.split(",")
                    for ele_inv in lst_so:
                        so_obj = so_pool.browse([int(ele_inv)])
                        filename = so_obj.name +'-'+'Sol Luminaire'
                if report.report_name == 'solum_sale.idesign_quotation_report_template_id':
                    so_pool = request.env['sale.order']
                    lst_so = []
                    lst_so = docids.split(",")
                    for ele_inv in lst_so:
                        so_obj = so_pool.browse([int(ele_inv)])
                        filename = so_obj.name +'-'+'iDesign'
                #Invoice
                if report.report_name == 'solum_invoice.sol_invoice_report_template_id':
                    inv_pool = request.env['account.invoice']
                    lst_inv = []
                    lst_inv = docids.split(",")
                    for ele_inv in lst_inv:
                        inv_obj = inv_pool.browse([int(ele_inv)])
                        if inv_obj.number:
                            filename = inv_obj.number +'-'+'Sol Luminaire Customer'
                        else:
                            filename = inv_obj.partner_id.name +'-'+'Sol Luminaire Customer'
                if report.report_name == 'solum_invoice.idesign_invoice_report_template_id':
                    inv_pool = request.env['account.invoice']
                    lst_inv = []
                    lst_inv = docids.split(",")
                    for ele_inv in lst_inv:
                        inv_obj = inv_pool.browse([int(ele_inv)])
                        if inv_obj.number:
                            filename = inv_obj.number +'-'+'iDesign'
                        else:
                            filename = inv_obj.partner_id.name +'-'+'iDesign'
                if report.report_name == 'solum_invoice.sol_commission_invoice_report_template_id':
                    inv_pool = request.env['account.invoice']
                    lst_inv = []
                    lst_inv = docids.split(",")
                    for ele_inv in lst_inv:
                        inv_obj = inv_pool.browse([int(ele_inv)])
                        if inv_obj.number:
                            filename = inv_obj.number +'-'+'Sol Luminaire Commission'
                        else:
                            filename = inv_obj.partner_id.name +'-'+'Sol Luminaire Commission'
                #Delivery Order
                if report.report_name == 'solum_delivery_order.sol_do_report_template_id':
                    picking_pool = request.env['stock.picking']
                    lst_picking = []
                    lst_picking = docids.split(",")
                    for ele_picking in lst_picking:
                        picking_obj = picking_pool.browse([int(ele_picking)])
                        filename = picking_obj.name +'-'+'Sol Luminaire'
                if report.report_name == 'solum_delivery_order.idesign_do_report_template_id':
                    picking_pool = request.env['stock.picking']
                    lst_picking = []
                    lst_picking = docids.split(",")
                    for ele_picking in lst_picking:
                        picking_obj = picking_pool.browse([int(ele_picking)])
                        filename = picking_obj.name +'-'+'iDesign'
                filename = "%s.%s" % (filename, "pdf")
                if docids:
                    ids = [int(x) for x in docids.split(",")]
                    obj = request.env[report.model].browse(ids)
                    if report.print_report_name and not len(obj) > 1:
                        filename = safe_eval(report.print_report_name, {'object': obj, 'time': time})
                response.headers.add('Content-Disposition', content_disposition(filename))
                response.set_cookie('fileToken', token)
                return response
            elif type == 'controller':
                reqheaders = Headers(request.httprequest.headers)
                response = Client(request.httprequest.app, BaseResponse).get(url, headers=reqheaders, follow_redirects=True)
                response.set_cookie('fileToken', token)
                return response
            else:
                return
        except Exception, e:
            se = _serialize_exception(e)
            error = {
                'code': 200,
                'message': "Odoo Server Error",
                'data': se
            }
            return request.make_response(html_escape(json.dumps(error)))
Example #29
0
 def get_report(self,
                model,
                options,
                output_format,
                token,
                financial_id=None,
                **kw):
     uid = request.session.uid
     report_obj = request.env[model].sudo(uid)
     options = json.loads(options)
     if financial_id:
         report_obj = report_obj.browse(int(financial_id))
     report_name = report_obj.get_report_filename(options)
     try:
         if output_format == 'xlsx':
             response = request.make_response(
                 None,
                 headers=[('Content-Type', 'application/vnd.ms-excel'),
                          ('Content-Disposition',
                           content_disposition(report_name + '.xlsx'))])
             report_obj.get_xlsx(options, response)
         if output_format == 'pdf':
             response = request.make_response(
                 report_obj.get_pdf(options),
                 headers=[('Content-Type', 'application/pdf'),
                          ('Content-Disposition',
                           content_disposition(report_name + '.pdf'))])
         if output_format == 'xml':
             content = report_obj.get_xml(options)
             response = request.make_response(
                 content,
                 headers=[('Content-Type',
                           'application/vnd.sun.xml.writer'),
                          ('Content-Disposition',
                           content_disposition(report_name + '.xml')),
                          ('Content-Length', len(content))])
         if output_format == 'xaf':
             content = report_obj.get_xaf(options)
             response = request.make_response(
                 content,
                 headers=[('Content-Type',
                           'application/vnd.sun.xml.writer'),
                          ('Content-Disposition',
                           'attachment; filename=' + report_name + '.xaf;'),
                          ('Content-Length', len(content))])
         if output_format == 'txt':
             content = report_obj.get_txt(options)
             response = request.make_response(
                 content,
                 headers=[('Content-Type', 'text/plain'),
                          ('Content-Disposition',
                           content_disposition(report_name + '.txt')),
                          ('Content-Length', len(content))])
         if output_format == 'csv':
             content = report_obj.get_csv(options)
             response = request.make_response(
                 content,
                 headers=[('Content-Type', 'text/csv'),
                          ('Content-Disposition',
                           'attachment; filename=' + report_name + '.csv;'),
                          ('Content-Length', len(content))])
         response.set_cookie('fileToken', token)
         return response
     except Exception as e:
         se = _serialize_exception(e)
         error = {'code': 200, 'message': 'ERP Server Error', 'data': se}
         return request.make_response(html_escape(json.dumps(error)))
Example #30
0
    def report_download(self, data, token, context=None):
        request_content = json.loads(data)
        url, content_type = request_content[0], request_content[1]

        if content_type not in ['qweb-pdf', 'qweb-text']:
            return

        if content_type == 'qweb-pdf':
            converter = 'pdf'
            extension = 'pdf'
            pattern = '/report/pdf/'
        else:
            converter = 'text'
            extension = 'txt'
            pattern = '/report/text/'

        try:
            reportname = url.split(pattern)[1].split('?')[0]

            docids = None
            if '/' in reportname:
                reportname, docids = reportname.split('/')

            if docids:
                # Generic report:
                response = self.report_routes(
                    reportname,
                    docids=docids,
                    converter=converter,
                    context=context,
                )
            else:
                # Particular report:
                data = dict(url_decode(url.split('?')[1]).items())
                if 'context' in data:
                    context, data_context = (
                        json.loads(context or '{}'),  # noqa: P103
                        json.loads(data.pop('context')))
                    context = json.dumps({**context, **data_context})
                response = self.report_routes(
                    reportname,
                    converter=converter,
                    context=context,
                    **data,
                )

            report = request.env['ir.actions.report']._get_report_from_name(
                reportname)

            report_name = report.name

            if docids:
                ids = [int(x) for x in docids.split(',')]
                obj = request.env[report.model].browse(ids)

                # change: Special file names provided by German Documents
                if hasattr(obj, 'eco_report_name'):
                    report_name = '{name}'.format(name=obj.with_context(
                        lang=obj[0].partner_id.lang,
                        report_xml_id=reportname,
                    ).eco_report_name(), )
                elif report.print_report_name and not len(obj) > 1:
                    report_name = safe_eval(report.print_report_name, {
                        'object': obj,
                        'time': time,
                    })

            # change: Odoo cannot handle too long file names
            filename = '{name:.100}.{extension}'.format(
                name=report_name,
                extension=extension,
            )

            response.headers.add(
                'Content-Disposition',
                content_disposition(filename),
            )
            response.set_cookie('fileToken', token)
            return response
        except Exception as e:
            se = _serialize_exception(e)
            error = {
                'code': 200,
                'message': 'Odoo Server Error',
                'data': se,
            }
            return request.make_response(html_escape(json.dumps(error)))