Example #1
0
    def report_routes(self, reportname, docids=None, converter=None, **data):
        report_obj = request.registry['report']
        cr, uid, context = request.cr, request.uid, request.context

        if docids:
            docids = [int(i) for i in docids.split(',')]
        options_data = None
        if data.get('options'):
            options_data = simplejson.loads(data['options'])
        if data.get('context'):
            context.update(simplejson.loads(data['context']))

        if converter == 'html':
            html = report_obj.get_html(cr,
                                       uid,
                                       docids,
                                       reportname,
                                       data=options_data,
                                       context=context)
            return request.make_response(html)
        elif converter == 'pdf':
            pdf = report_obj.get_pdf(cr,
                                     uid,
                                     docids,
                                     reportname,
                                     data=options_data,
                                     context=context)
            pdfhttpheaders = [('Content-Type', 'application/pdf'),
                              ('Content-Length', len(pdf))]
            return request.make_response(pdf, headers=pdfhttpheaders)
        else:
            raise exceptions.HTTPException(
                description='Converter %s not implemented.' % converter)
Example #2
0
    def report_routes(self, reportname, docids=None, converter=None, **data):
        report_obj = request.registry["report"]
        cr, uid, context = request.cr, request.uid, request.context

        if docids:
            docids = [int(i) for i in docids.split(",")]
        options_data = None
        if data.get("options"):
            options_data = simplejson.loads(data["options"])
        if data.get("context"):
            # Ignore 'lang' here, because the context in data is the one from the webclient *but* if
            # the user explicitely wants to change the lang, this mechanism overwrites it.
            data_context = simplejson.loads(data["context"])
            if data_context.get("lang"):
                del data_context["lang"]
            context.update(data_context)

        if converter == "html":
            html = report_obj.get_html(cr, uid, docids, reportname, data=options_data, context=context)
            return request.make_response(html)
        elif converter == "pdf":
            pdf = report_obj.get_pdf(cr, uid, docids, reportname, data=options_data, context=context)
            pdfhttpheaders = [("Content-Type", "application/pdf"), ("Content-Length", len(pdf))]
            return request.make_response(pdf, headers=pdfhttpheaders)
        else:
            raise exceptions.HTTPException(description="Converter %s not implemented." % converter)
Example #3
0
    def get_lists(self, name, options):
        options = simplejson.loads(options)

        model_obj = self._get_model(name)
        if options.get('type', 'tree') == 'tree':
            headers = self._get_fields_list(name)
            domain = self._get_format_domain(name, options.get('domain', ''))
            order = self._get_order(name, options.get('order', ''))
            limit = self._get_limit(name)

            return request.make_response(simplejson.dumps({
                'headers': headers,
                'max_count': self._get_max_count(name, domain),
                'values': [{
                    'left': record.get(headers.get('left').get('name')),
                    'center': record.get(headers.get('center').get('name')),
                    'right': record.get(headers.get('right').get('name')),
                    'id': record.get('id'),
                } for record in model_obj.with_context(options.get('context') or {}).search_read(
                    domain=domain, fields=map(lambda field: field.get('name'), headers.values()),
                    offset=self._parse_int(options.get('offset', 0)), limit=limit, order=order)]
            }))
        else:
            headers = self._get_form_fields_list(name)
            return request.make_response(simplejson.dumps([{
                'name': key,
                'value': value,
                'string': headers.get(key, {}).get('string'),
                'column': headers.get(key, {}).get('column'),
            } for key, value in model_obj.with_context(options.get('context') or {}).browse(self._parse_int(
                options.get('record_id'))).read(headers.keys())[0].iteritems()
            ]))
Example #4
0
    def wechat_binding(self, user_id, mobile, login, password, **args):
        db = RegistryManager.get(request.db)
        user = openerp.registry(request.db)['res.users']

        with closing(db.cursor()) as cr:
            users = user.search(cr, 1, [('login', '=', login)])
            if not users:
                return request.make_response(
                    simplejson.dumps({
                        'message': u'账户不存在',
                        'state': 'error',
                    }))

            try:
                user.check_credentials(cr, users[0], password)
            except:
                return request.make_response(
                    simplejson.dumps({
                        'message': u'密码错误',
                        'state': 'error',
                    }))

            user.write(cr, 1, users[0], {
                'oauth_access_token': mobile,
                'weixin_id': user_id,
            })
            cr.commit()

        return request.make_response(
            simplejson.dumps({
                'state': 'done',
                'message': u'绑定成功,请使用手机微信扫码登录'
            }))
Example #5
0
    def report_routes(self, reportname, docids=None, converter=None, **data):
        report_obj = request.registry['report']
        cr, uid, context = request.cr, request.uid, request.context

        if docids:
            docids = [int(i) for i in docids.split(',')]
        options_data = None
        if data.get('options'):
            options_data = simplejson.loads(data['options'])
        if data.get('context'):
            # Ignore 'lang' here, because the context in data is the one from the webclient *but* if
            # the user explicitely wants to change the lang, this mechanism overwrites it. 
            data_context = simplejson.loads(data['context'])
            if data_context.get('lang'):
                del data_context['lang']
            context.update(data_context)

        if converter == 'html':
            html = report_obj.get_html(cr, uid, docids, reportname, data=options_data, context=context)
            return request.make_response(html)
        elif converter == 'pdf':
            pdf = report_obj.get_pdf(cr, uid, docids, reportname, data=options_data, context=context)
            pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))]
            return request.make_response(pdf, headers=pdfhttpheaders)
        else:
            raise exceptions.HTTPException(description='Converter %s not implemented.' % converter)
 def report_routes(self, directory, documentname, tokenid, **data):
     cr, uid, context = request.cr, request.uid, request.context
     attached_obj = request.registry['ir.attachment']
     attachment_doc_id = attached_obj.browse(cr, uid, [int(tokenid)])
     pdf_data = (attachment_doc_id.datas).decode('base64')
     pdfhttpheaders = [('Content-Type', 'application/pdf'),
                       ('Content-Length', len(pdf_data))]
     print("Pdf htp headers"), pdfhttpheaders
     print("Reponse is:"), request.make_response(pdf_data,
                                                 headers=pdfhttpheaders)
     return request.make_response(pdf_data, headers=pdfhttpheaders)
Example #7
0
 def many2one_search(self, word, model, domain):
     return request.make_response(simplejson.dumps([
         {
         'id': record[0], 'value': record[1]
         } for record in request.env[model].name_search(
             word, args=eval(domain), limit=20)
     ]))
    def document(self, template, model=None, docids='', **data):

        template_obj = request.env['document.template']
        target = template_obj.search([
            ('name', '=', template),
        ])

        model_obj = request.env[model] if model else False

        data.update({
            'objects':
            model_obj.browse([int(rec) for rec in docids.split(',')])
            if model_obj is not False else [],
            'request':
            request,
            'target_model':
            model_obj
        })

        doc = target.render(data)

        httpheaders = [('Content-Type', target.content_type),
                       ('Content-Length', len(doc)),
                       ('Content-Disposition',
                        'attachment; filename="{title}.{ext}"'.format(
                            title=target.title, ext=target.extension))]

        return request.make_response(doc, headers=httpheaders)
Example #9
0
    def report_barcode(self,
                       type,
                       value,
                       width=600,
                       height=100,
                       humanreadable=0):
        """Contoller able to render barcode images thanks to reportlab.
        Samples: 
            <img t-att-src="'/report/barcode/QR/%s' % o.name"/>
            <img t-att-src="'/report/barcode/?type=%s&amp;value=%s&amp;width=%s&amp;height=%s' % 
                ('QR', o.name, 200, 200)"/>

        :param type: Accepted types: 'Codabar', 'Code11', 'Code128', 'EAN13', 'EAN8', 'Extended39',
        'Extended93', 'FIM', 'I2of5', 'MSI', 'POSTNET', 'QR', 'Standard39', 'Standard93',
        'UPCA', 'USPS_4State'
        :param humanreadable: Accepted values: 0 (default) or 1. 1 will insert the readable value
        at the bottom of the output image
        """
        try:
            barcode = request.registry['report'].barcode(
                type,
                value,
                width=width,
                height=height,
                humanreadable=humanreadable)
        except (ValueError, AttributeError):
            raise exceptions.HTTPException(
                description='Cannot convert into barcode.')

        return request.make_response(barcode,
                                     headers=[('Content-Type', 'image/png')])
Example #10
0
    def report_routes(self, reportname, docids=None, converter=None, **data):
        report_obj = request.registry['report']
        cr, uid, context = request.cr, request.uid, request.context
        origin_docids = docids
        if docids:
            docids = [int(idx) for idx in docids.split(',')]
        options_data = None
        if data.get('options'):
            options_data = simplejson.loads(data['options'])
        if data.get('context'):
            # Ignore 'lang' here, because the context in data is the one from
            # the webclient *but* if the user explicitely wants to change the
            # lang, this mechanism overwrites it.
            data_context = simplejson.loads(data['context']) or {}

            if data_context.get('lang'):
                del data_context['lang']
            context.update(data_context)

        if not context.get('xls_report'):
            return super(ReportController, self).report_routes(
                reportname, docids=origin_docids, converter=converter, **data)

        html = report_obj.get_html(cr, uid, docids, reportname,
                                   data=options_data, context=context)
        xls_stream = self.get_xls(html)
        xlshttpheaders = [('Content-Type', 'application/vnd.ms-excel'),
                          ('Content-Length', len(xls_stream)),
                          ]
        return request.make_response(xls_stream, headers=xlshttpheaders)
Example #11
0
    def labels_download(self, wizard_id):
        cr, uid, context = request.cr, request.uid, request.context

        wizard_model = request.registry['labelling.sheets.print.wizard']
        wizard = wizard_model.browse(cr, uid, int(wizard_id), context=context)

        spec = wizard.spec_id.get_specification()

        template = wizard.content_template_id

        ids_str = wizard.object_ids
        obj_ids = map(int, ids_str.split(',')) if ids_str else []
        objects = template.get_objects(obj_ids)
        pdf = template.get_pdf(spec,
                               objects,
                               print_options=wizard.get_print_options())

        pdfhttpheaders = [
            ('Content-Type', 'application/pdf'),
            ('Content-Length', len(pdf)),
            ('Content-Disposition', content_disposition("labels.pdf")),
        ]
        # This is to assist with debugging
        dump_dir = os.getenv('ODOO_LABELLING_DUMP_DIR')
        if dump_dir:
            dump_filepath = os.path.join(dump_dir, 'labels.pdf')
            with open(dump_filepath, 'wb') as df:
                df.write(pdf)
            _logger.info('Dumped labels to {}'.format(dump_filepath))
        return request.make_response(pdf, headers=pdfhttpheaders)
Example #12
0
    def report_attachment(self, data, token):
        """This function is used by 'qwebactionmanager.js' in order to trigger the download of
        a report of any type.

        :param data: a javasscript array JSON.stringified containg report internal url ([0]) and
        type [1]
        :returns: Response with a filetoken cookie and an attachment header
        """
        requestcontent = simplejson.loads(data)
        url, type = requestcontent[0], requestcontent[1]
        file, fileheaders = self._get_url_content(url)

        if type == 'qweb-pdf':
            response = self._make_pdf_response(file)
            response.headers.add('Content-Disposition', 'attachment; filename=report.pdf;')
        elif type == 'controller':
            response = request.make_response(file)
            response.headers.add('Content-Disposition', fileheaders['Content-Disposition'])
            response.headers.add('Content-Type', fileheaders['Content-Type'])
        else:
            return

        response.headers.add('Content-Length', len(file))
        response.set_cookie('fileToken', token)
        return response
Example #13
0
    def report_routes(self, reportname, docids=None, converter=None, **data):
        """Intercepts original method from report module by using a key in context
        sticked when print a report from a wizard ('xls_report') if True this
        method will return a XLS File otherwise it will return the customary
        PDF File"""
        report_obj = request.registry['report']
        cr, uid, context = request.cr, request.uid, request.context
        origin_docids = docids
        if docids:
            docids = [int(idx) for idx in docids.split(',')]
        options_data = None
        if data.get('options'):
            options_data = simplejson.loads(data['options'])
        if data.get('context'):
            # Ignore 'lang' here, because the context in data is the one from
            # the webclient *but* if the user explicitely wants to change the
            # lang, this mechanism overwrites it.
            data_context = simplejson.loads(data['context']) or {}

            if data_context.get('lang'):
                del data_context['lang']
            context.update(data_context)

        if not context.get('xls_report'):
            return super(ReportController, self).report_routes(
                reportname, docids=origin_docids, converter=converter, **data)

        html = report_obj.get_html(cr, uid, docids, reportname,
                                   data=options_data, context=context)
        xls_stream = get_xls(html, get_lang_sep(request, context))
        xlshttpheaders = [('Content-Type', 'application/vnd.ms-excel'),
                          ('Content-Length', len(xls_stream)),
                          ]
        return request.make_response(xls_stream, headers=xlshttpheaders)
Example #14
0
 def view(self, order_id, pdf=None, token=None, message=False, **post):
     # use SUPERUSER_ID allow to access/view order for public user
     # only if he knows the private token
     order = request.registry.get('sale.order').browse(request.cr, token and SUPERUSER_ID or request.uid, order_id, request.context)
     now = time.strftime('%Y-%m-%d')
     dummy, action = request.registry.get('ir.model.data').get_object_reference(request.cr, request.uid, 'sale', 'action_quotations')
     if token:
         if token != order.access_token:
             return request.website.render('website.404')
         # Log only once a day
         if request.session.get('view_quote',False)!=now:
             request.session['view_quote'] = now
             body=_('Quotation viewed by customer')
             self.__message_post(body, order_id, message_type='comment')
     days = 0
     if order.validity_date:
         days = (datetime.datetime.strptime(order.validity_date, '%Y-%m-%d') - datetime.datetime.now()).days + 1
     if pdf:
         report_obj = request.registry['report']
         pdf = report_obj.get_pdf(request.cr, SUPERUSER_ID, [order_id], 'website_quote.report_quote', data=None, context=request.context)
         pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))]
         return request.make_response(pdf, headers=pdfhttpheaders)
     values = {
         'quotation': order,
         'message': message and int(message) or False,
         'option': bool(filter(lambda x: not x.line_id, order.options)),
         'order_valid': (not order.validity_date) or (now <= order.validity_date),
         'days_valid': days,
         'action': action
     }
     return request.website.render('website_quote.so_quotation', values)
Example #15
0
    def get_wizard_view(self, name):
        view = request.env['mobile.view'].search([('name', '=', name)])
        tree = ElementTree.parse(StringIO(view.arch.encode('utf-8')))

        return request.make_response(simplejson.dumps(
            [dict(node.attrib, value='') for node in tree.findall('.//wizard/field')]
        ))
Example #16
0
    def report_barcode(self, type, value, width=600, height=100):
        """Contoller able to render barcode images thanks to reportlab.
        Samples: 
            <img t-att-src="'/report/barcode/QR/%s' % o.name"/>
            <img t-att-src="'/report/barcode/?type=%s&amp;value=%s&amp;width=%s&amp;height=%s' % 
                ('QR', o.name, 200, 200)"/>

        :param type: Accepted types: 'Codabar', 'Code11', 'Code128', 'EAN13', 'EAN8', 'Extended39',
        'Extended93', 'FIM', 'I2of5', 'MSI', 'POSTNET', 'QR', 'Standard39', 'Standard93',
        'UPCA', 'USPS_4State'
        """
        try:
            width, height = int(width), int(height)
            barcode = createBarcodeDrawing(type,
                                           value=value,
                                           format='png',
                                           width=width,
                                           height=height)
            barcode = barcode.asString('png')
        except (ValueError, AttributeError):
            raise exceptions.HTTPException(
                description='Cannot convert into barcode.')

        return request.make_response(barcode,
                                     headers=[('Content-Type', 'image/png')])
Example #17
0
    def rss_xml_index(self):
        cr, uid, context = request.cr, openerp.SUPERUSER_ID, request.context
        ira = request.registry['ir.attachment']
        iuv = request.registry['ir.ui.view']
        product_obj = request.registry['product.template']
        mimetype = 'application/xml;charset=utf-8'
        content = None
        product_rss = ira.search_read(cr,
                                      uid, [('name', '=', '/product_rss.xml'),
                                            ('type', '=', 'binary')],
                                      ('datas', 'create_date'),
                                      context=context)
        if product_rss:
            # Check if stored version is still valid
            server_format = openerp.tools.misc.DEFAULT_SERVER_DATETIME_FORMAT
            create_date = datetime.datetime.strptime(
                product_rss[0]['create_date'], server_format)
            delta = datetime.datetime.now() - create_date
            if delta < PRODUCT_RSS_CACHE_TIME:
                content = product_rss[0]['datas'].decode('base64')

        if not content:
            # Remove all RSS in ir.attachments as we're going to regenerate
            product_rss_ids = ira.search(
                cr,
                uid, [('name', '=like', '/product_rss%.xml'),
                      ('type', '=', 'binary')],
                context=context)
            if product_rss_ids:
                ira.unlink(cr, uid, product_rss_ids, context=context)

            pages = 0
            first_page = None
            values = {}
            product_ids = product_obj.search(
                cr, uid, [('website_published', '=', True)])
            if product_ids:
                values['products'] = product_obj.browse(
                    cr, uid, product_ids, context)
            values['url_root'] = request.httprequest.url_root
            urls = iuv.render(cr,
                              uid,
                              'website_product_rss.product_rss_locs',
                              values,
                              context=context)
            if urls:
                page = iuv.render(cr,
                                  uid,
                                  'website_product_rss.product_rss_xml',
                                  dict(content=urls),
                                  context=context)
                if not first_page:
                    first_page = page
                pages += 1
                self.create_product_rss('/product_rss-%d.xml' % pages, page)
            if not pages:
                return request.not_found()
            elif pages == 1:
                content = first_page
        return request.make_response(content, [('Content-Type', mimetype)])
    def report_routes(self, reportname, docids=None, converter=None, **data):
        report_obj = request.registry['report']
        cr, uid, context = request.cr, request.uid, request.context
        origin_docids = docids
        if docids:
            docids = [int(idx) for idx in docids.split(',')]
        options_data = None
        if data.get('options'):
            options_data = simplejson.loads(data['options'])
        if data.get('context'):
            # Ignore 'lang' here, because the context in data is the one from
            # the webclient *but* if the user explicitely wants to change the
            # lang, this mechanism overwrites it.
            data_context = simplejson.loads(data['context']) or {}

            if data_context.get('lang'):
                del data_context['lang']
            context.update(data_context)

        if not context.get('xls_report'):
            return super(ReportController, self).report_routes(
                reportname, docids=origin_docids, converter=converter, **data)

        html = report_obj.get_html(cr, uid, docids, reportname,
                                   data=options_data, context=context)
        xls_stream = get_xls(html)
        xlshttpheaders = [('Content-Type', 'application/vnd.ms-excel'),
                          ('Content-Length', len(xls_stream)),
                          ]
        return request.make_response(xls_stream, headers=xlshttpheaders)
Example #19
0
 def many2one_search(self, word, model, domain):
     return request.make_response(
         simplejson.dumps([{
             'id': record[0],
             'value': record[1]
         } for record in request.env[model].name_search(
             word, args=eval(domain), limit=20)]))
Example #20
0
 def view(self, order_id, pdf=None, token=None, message=False, **post):
     # use SUPERUSER_ID allow to access/view order for public user
     # only if he knows the private token
     order = request.registry.get('sale.order').browse(request.cr, token and SUPERUSER_ID or request.uid, order_id, request.context)
     now = time.strftime('%Y-%m-%d')
     dummy, action = request.registry.get('ir.model.data').get_object_reference(request.cr, request.uid, 'sale', 'action_quotations')
     if token:
         if token != order.access_token:
             return request.website.render('website.404')
         # Log only once a day
         if request.session.get('view_quote',False)!=now:
             request.session['view_quote'] = now
             body=_('Quotation viewed by customer')
             self.__message_post(body, order_id, type='comment')
     days = 0
     if order.validity_date:
         days = (datetime.datetime.strptime(order.validity_date, '%Y-%m-%d') - datetime.datetime.now()).days + 1
     if pdf:
         report_obj = request.registry['report']
         pdf = report_obj.get_pdf(request.cr, SUPERUSER_ID, [order_id], 'website_quote.report_quote', data=None, context=request.context)
         pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))]
         return request.make_response(pdf, headers=pdfhttpheaders)
     values = {
         'quotation': order,
         'message': message and int(message) or False,
         'option': bool(filter(lambda x: not x.line_id, order.options)),
         'order_valid': (not order.validity_date) or (now <= order.validity_date),
         'days_valid': max(days, 0),
         'action': action
     }
     return request.website.render('website_quote.so_quotation', values)
Example #21
0
    def wechat_codes(self, email):
        db = RegistryManager.get(request.db)
        user = openerp.registry(request.db)['res.users']

        with closing(db.cursor()) as cr:
            users = user.search(cr, 1, [('login', '=', email)])
            if not users:
                return request.make_response(
                    simplejson.dumps({
                        'wrong': True,
                        'text': u'错误, 账户不存在',
                    }))

            user_browse = user.browse(cr, 1, users[0])

            if not user_browse.weixin_id:
                return request.make_response(
                    simplejson.dumps({
                        'wrong': True,
                        'text': u'错误,当前账户未在微信端绑定',
                    }))

            random_codes = str(random.randint(100000, 999999))
            codes_time = datetime.strptime(fields.datetime.now(
                cr, 1), '%Y-%m-%d %H:%M:%S') + timedelta(minutes=3)
            user_browse.write({
                'random_codes':
                random_codes,
                'codes_time':
                codes_time.strftime('%Y-%m-%d %H:%M:%S'),
            })

            cr.commit()

            response = self._send_text(user_browse.weixin_id, random_codes)
            if response:
                return request.make_response(
                    simplejson.dumps({
                        'wrong':
                        True,
                        'text':
                        '微信端发送消息错误,错误码:%s,请联系管理员' % response,
                    }))

            return request.make_response(simplejson.dumps({
                'wrong': False,
            }))
Example #22
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 = simplejson.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('/')

                attach_name = reportname
                if docids:
                    so_ids = [int(i) for i in docids.split(',')]
                    if reportname.find(
                            'cebis_sale_order_report.report_sale_order') != -1:
                        cr, uid, context = request.cr, request.uid, request.context
                        so = request.registry['sale.order'].browse(
                            cr, uid, so_ids, context=context)[0]
                        attach_name = so.name
                    # 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))

                response.headers.add(
                    'Content-Disposition',
                    'attachment; filename=%s.pdf;' % attach_name)
                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(simplejson.dumps(error)))
Example #23
0
    def view(self, order_id, pdf=None, token=None, message=False, **post):
        # use SUPERUSER_ID allow to access/view order for public user
        # only if he knows the private token
        order = request.registry.get('sale.order').browse(request.cr, token and SUPERUSER_ID or request.uid, order_id, request.context)
        now = time.strftime('%Y-%m-%d')
        dummy, action = request.registry.get('ir.model.data').get_object_reference(request.cr, request.uid, 'sale', 'action_quotations')
        if token:
            if token != order.access_token:
                return request.website.render('website.404')
            # Log only once a day
            if request.session.get('view_quote',False)!=now:
                request.session['view_quote'] = now
                body=_('Quotation viewed by customer')
                _message_post_helper(res_model='sale.order', res_id=order.id, message=body, token=token, token_field="access_token", message_type='notification')
        days = 0
        if order.validity_date:
            days = (datetime.datetime.strptime(order.validity_date, '%Y-%m-%d') - datetime.datetime.now()).days + 1
        if pdf:
            report_obj = request.registry['report']
            pdf = report_obj.get_pdf(request.cr, SUPERUSER_ID, [order_id], 'website_quote.report_quote', data=None, context=dict(request.context, set_viewport_size=True))
            pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))]
            return request.make_response(pdf, headers=pdfhttpheaders)
        user = request.registry['res.users'].browse(request.cr, SUPERUSER_ID, request.uid, context=request.context)
        tx_id = request.registry['payment.transaction'].search(request.cr, SUPERUSER_ID, [('reference', '=', order.name)], context=request.context)
        tx = request.registry['payment.transaction'].browse(request.cr, SUPERUSER_ID, tx_id, context=request.context) if tx_id else False
        values = {
            'quotation': order,
            'message': message and int(message) or False,
            'option': bool(filter(lambda x: not x.line_id, order.options)),
            'order_valid': (not order.validity_date) or (now <= order.validity_date),
            'days_valid': days,
            'action': action,
            'breadcrumb': user.partner_id == order.partner_id,
            'tx_id': tx_id,
            'tx_state': tx.state if tx else False,
            'tx_post_msg': tx.acquirer_id.post_msg if tx else False,
            'need_payment': not tx_id and order.state == 'manual',
            'token': token,
        }

        if order.require_payment or (not tx_id and order.state == 'manual'):
            payment_obj = request.registry.get('payment.acquirer')
            acquirer_ids = payment_obj.search(request.cr, SUPERUSER_ID, [('website_published', '=', True), ('company_id', '=', order.company_id.id)], context=request.context)
            values['acquirers'] = list(payment_obj.browse(request.cr, token and SUPERUSER_ID or request.uid, acquirer_ids, context=request.context))
            render_ctx = dict(request.context, submit_class='btn btn-primary', submit_txt=_('Pay & Confirm'))
            for acquirer in values['acquirers']:
                acquirer.button = payment_obj.render(
                    request.cr, SUPERUSER_ID, acquirer.id,
                    order.name,
                    order.amount_total,
                    order.pricelist_id.currency_id.id,
                    partner_id=order.partner_id.id,
                    tx_values={
                        'return_url': '/quote/%s/%s' % (order_id, token) if token else '/quote/%s' % order_id,
                        'type': 'form',
                        'alias_usage': _('If we store your payment information on our server, subscription payments will be made automatically.')
                    },
                    context=render_ctx)
        return request.website.render('website_quote.so_quotation', values)
Example #24
0
    def view(self, order_id, pdf=None, token=None, message=False, **post):
        # use SUPERUSER_ID allow to access/view order for public user
        # only if he knows the private token
        order = request.registry.get('sale.order').browse(request.cr, token and SUPERUSER_ID or request.uid, order_id, request.context)
        now = time.strftime('%Y-%m-%d')
        dummy, action = request.registry.get('ir.model.data').get_object_reference(request.cr, request.uid, 'sale', 'action_quotations')
        if token:
            if token != order.access_token:
                return request.website.render('website.404')
            # Log only once a day
            if request.session.get('view_quote',False)!=now:
                request.session['view_quote'] = now
                body=_('Quotation viewed by customer')
                _message_post_helper(res_model='sale.order', res_id=order.id, message=body, token=token, token_field="access_token", message_type='notification')
        days = 0
        if order.validity_date:
            days = (datetime.datetime.strptime(order.validity_date, '%Y-%m-%d') - datetime.datetime.now()).days + 1
        if pdf:
            report_obj = request.registry['report']
            pdf = report_obj.get_pdf(request.cr, SUPERUSER_ID, [order_id], 'website_quote.report_quote', data=None, context=dict(request.context, set_viewport_size=True))
            pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))]
            return request.make_response(pdf, headers=pdfhttpheaders)
        user = request.registry['res.users'].browse(request.cr, SUPERUSER_ID, request.uid, context=request.context)
        tx_id = request.registry['payment.transaction'].search(request.cr, SUPERUSER_ID, [('reference', '=', order.name)], context=request.context)
        tx = request.registry['payment.transaction'].browse(request.cr, SUPERUSER_ID, tx_id, context=request.context) if tx_id else False
        values = {
            'quotation': order,
            'message': message and int(message) or False,
            'option': bool(filter(lambda x: not x.line_id, order.options)),
            'order_valid': (not order.validity_date) or (now <= order.validity_date),
            'days_valid': days,
            'action': action,
            'breadcrumb': user.partner_id == order.partner_id,
            'tx_id': tx_id,
            'tx_state': tx.state if tx else False,
            'tx_post_msg': tx.acquirer_id.post_msg if tx else False,
            'need_payment': order.invoice_status == 'to invoice' and (not tx or tx.state in ['draft', 'cancel', 'error']),
            'token': token,
        }

        if order.require_payment or values['need_payment']:
            payment_obj = request.registry.get('payment.acquirer')
            acquirer_ids = payment_obj.search(request.cr, SUPERUSER_ID, [('website_published', '=', True), ('company_id', '=', order.company_id.id)], context=request.context)
            values['acquirers'] = list(payment_obj.browse(request.cr, token and SUPERUSER_ID or request.uid, acquirer_ids, context=request.context))
            render_ctx = dict(request.context, submit_class='btn btn-primary', submit_txt=_('Pay & Confirm'))
            for acquirer in values['acquirers']:
                acquirer.button = payment_obj.render(
                    request.cr, SUPERUSER_ID, acquirer.id,
                    order.name,
                    order.amount_total,
                    order.pricelist_id.currency_id.id,
                    values={
                        'return_url': '/quote/%s/%s' % (order_id, token) if token else '/quote/%s' % order_id,
                        'type': 'form',
                        'alias_usage': _('If we store your payment information on our server, subscription payments will be made automatically.'),
                        'partner_id': order.partner_id.id,
                    },
                    context=render_ctx)
        return request.website.render('website_quote.so_quotation', values)
Example #25
0
    def get_search_view(self, name):
        view = request.env['mobile.view'].search([('name', '=', name)])
        tree = ElementTree.parse(StringIO(view.arch.encode('utf-8')))

        return request.make_response(simplejson.dumps(
            [dict(node.attrib, column=view.column_type(
                node.attrib.get('name', ''))) for node in tree.findall('.//search/field')]
        ))
Example #26
0
    def get_lists(self, name, options):
        options = simplejson.loads(options)

        model_obj = self._get_model(name)
        if options.get('type', 'tree') == 'tree':
            headers = self._get_fields_list(name)
            domain = self._get_format_domain(name, options.get('domain', ''))
            order = self._get_order(name, options.get('order', ''))
            limit = self._get_limit(name)

            return request.make_response(
                simplejson.dumps({
                    'headers':
                    headers,
                    'max_count':
                    self._get_max_count(name, domain),
                    'values': [{
                        'left':
                        record.get(headers.get('left').get('name')),
                        'center':
                        record.get(headers.get('center').get('name')),
                        'right':
                        record.get(headers.get('right').get('name')),
                        'id':
                        record.get('id'),
                    } for record in model_obj.with_context(
                        options.get('context') or {}).search_read(
                            domain=domain,
                            fields=map(lambda field: field.get('name'),
                                       headers.values()),
                            offset=self._parse_int(options.get('offset', 0)),
                            limit=limit,
                            order=order)]
                }))
        else:
            headers = self._get_form_fields_list(name)
            return request.make_response(
                simplejson.dumps([{
                    'name': key,
                    'value': value,
                    'string': headers.get(key, {}).get('string'),
                    'column': headers.get(key, {}).get('column'),
                } for key, value in model_obj.with_context(
                    options.get('context') or {}).browse(
                        self._parse_int(options.get('record_id'))).read(
                            headers.keys())[0].iteritems()]))
Example #27
0
    def report_routes(self, reportname, docids=None, converter=None, **data):
        report_obj = request.registry['report']
        cr, uid, context = request.cr, request.uid, request.context

        if docids:
            docids = [int(i) for i in docids.split(',')]
        if data.get('options'):
            data.update(json.loads(data.pop('options')))
        if data.get('context'):
            # Ignore 'lang' here, because the context in data is the
            # one from the webclient *but* if the user explicitely
            # wants to change the lang, this mechanism overwrites it.
            data['context'] = json.loads(data['context'])
            if data['context'].get('lang'):
                del data['context']['lang']
            context.update(data['context'])

        if converter == 'xls':
            xls = report_obj.get_xls(cr,
                                     uid,
                                     docids,
                                     reportname,
                                     data=data,
                                     context=context)
            xlsxhttpheaders = [
                ('Content-Type',
                 'application/vnd.openxmlformats-officedocument.'
                 'spreadsheetml.sheet'), ('Content-Length', len(xls))
            ]
            return request.make_response(xls, headers=xlsxhttpheaders)
        elif converter == 'ods':
            ods = report_obj.get_ods(cr,
                                     uid,
                                     docids,
                                     reportname,
                                     data=data,
                                     context=context)
            odshttpheaders = [
                ('Content-Type',
                 'application/vnd.oasis.opendocument.spreadsheet'),
                ('Content-Length', len(ods))
            ]
            return request.make_response(ods, headers=odshttpheaders)
        else:
            raise exceptions.HTTPException(
                description='Converter %s not implemented.' % converter)
Example #28
0
 def user_avatar(self, user_id=0, **post):
     status, headers, content = binary_content(model='res.users', id=user_id, field='image', default_mimetype='image/png', env=request.env(user=openerp.SUPERUSER_ID))
     if status == 304:
         return werkzeug.wrappers.Response(status=304)
     image_base64 = base64.b64decode(content)
     headers.append(('Content-Length', len(image_base64)))
     response = request.make_response(image_base64, headers)
     response.status = str(status)
     return response
Example #29
0
    def get_wizard_view(self, name):
        view = request.env['mobile.view'].search([('name', '=', name)])
        tree = ElementTree.parse(StringIO(view.arch.encode('utf-8')))

        return request.make_response(
            simplejson.dumps([
                dict(node.attrib, value='')
                for node in tree.findall('.//wizard/field')
            ]))
Example #30
0
 def user_avatar(self, user_id=0, **post):
     status, headers, content = binary_content(model='res.users', id=user_id, field='image', default_mimetype='image/png', env=request.env(openerp.SUPERUSER_ID))
     if status == 304:
         return werkzeug.wrappers.Response(status=304)
     image_base64 = base64.b64decode(content)
     headers.append(('Content-Length', len(image_base64)))
     response = request.make_response(image_base64, headers)
     response.status = str(status)
     return response
Example #31
0
    def _make_pdf_response(self, pdf):
        """Make a request response for a PDF file with correct http headers.

        :param pdf: content of a pdf in a string
        :returns: request response for a pdf document
        """
        pdfhttpheaders = [('Content-Type', 'application/pdf'),
                          ('Content-Length', len(pdf))]
        return request.make_response(pdf, headers=pdfhttpheaders)
Example #32
0
    def export(self, module, format, **kwargs):

        filename = "{name}.{ext}".format(name=module.name, ext=format)

        fileIO = getattr(module, '_export_{format}'.format(format=format))()

        return request.make_response(
                    fileIO.getvalue(),
                    headers=[('Content-Type', 'application/octet-stream'),
                             ('Content-Disposition', content_disposition(filename))])
Example #33
0
    def get_search_view(self, name):
        view = request.env['mobile.view'].search([('name', '=', name)])
        tree = ElementTree.parse(StringIO(view.arch.encode('utf-8')))

        return request.make_response(
            simplejson.dumps([
                dict(node.attrib,
                     column=view.column_type(node.attrib.get('name', '')))
                for node in tree.findall('.//search/field')
            ]))
Example #34
0
 def weixin_login_qrcode(self, type, width=300, height=300, **args):
     width, height = int(width), int(height)
     barcode = createBarcodeDrawing(type,
                                    value=request.session_id,
                                    format='png',
                                    width=width,
                                    height=height)
     barcode = barcode.asString('png')
     return request.make_response(barcode,
                                  headers=[('Content-Type', 'image/png')])
Example #35
0
    def download(self, module, **kwargs):

        filename = "{name}.{ext}".format(name=module.name, ext="zip")

        zfileIO = module.get_zipped_module()

        return request.make_response(
            zfileIO.getvalue(),
            headers=[('Content-Type', 'plain/text' or 'application/octet-stream'),
                     ('Content-Disposition', content_disposition(filename))])
    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 = simplejson.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 = super(Extension, self).report_routes(reportname, docids=docids, converter='pdf')
                    # response = self.report_routes(reportname, docids=docids, converter='pdf')
                    ##### FIX START: switch reportname with the evaluated attachment attribute of the action if available
                    docids = [int(i) for i in docids.split(',')]
                    report_obj = request.registry['report']
                    cr, uid, context = request.cr, request.uid, request.context
                    report = report_obj._get_report_from_name(cr, uid, reportname)
                    obj = report_obj.pool[report.model].browse(cr, uid, docids[0])
                    if hasattr(obj, 'name') and obj.name:
                        reportname = obj.name
                    ##### FIX END
                else:
                    # Particular report:
                    data = url_decode(url.split('?')[1]).items()  # decoding the args represented in JSON
                    response = super(Extension, self).report_routes(reportname, converter='pdf', **dict(data))
                    # response = self.report_routes(reportname, converter='pdf', **dict(data))

                response.headers.add('Content-Disposition', 'attachment; filename=%s.pdf;' % reportname)
                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(simplejson.dumps(error)))
    def rss_xml_index(self):
        cr, uid, context = request.cr, openerp.SUPERUSER_ID, request.context
        ira = request.registry['ir.attachment']
        user_obj = request.registry['res.users']
        user_brw = user_obj.browse(cr, uid, [uid], context=context)
        iuv = request.registry['ir.ui.view']
        product_obj = request.registry['product.template']
        mimetype = 'application/xml;charset=utf-8'
        content = None
        product_rss = ira.search_read(cr, uid, [
            ('name', '=', '/product_rss.xml'),
            ('type', '=', 'binary')],
            ('datas', 'create_date'), context=context)
        if product_rss:
            # Check if stored version is still valid
            server_format = openerp.tools.misc.DEFAULT_SERVER_DATETIME_FORMAT
            create_date = datetime.datetime.strptime(
                product_rss[0]['create_date'], server_format)
            delta = datetime.datetime.now() - create_date
            if delta < PRODUCT_RSS_CACHE_TIME:
                content = product_rss[0]['datas'].decode('base64')

        if not content:
            # Remove all RSS in ir.attachments as we're going to regenerate
            product_rss_ids = ira.search(cr, uid, [
                ('name', '=like', '/product_rss%.xml'),
                ('type', '=', 'binary')], context=context)
            if product_rss_ids:
                ira.unlink(cr, uid, product_rss_ids, context=context)

            pages = 0
            first_page = None
            values = {}
            product_ids = product_obj.search(cr, uid, [
                ('website_published', '=', True)])
            if product_ids:
                values['products'] = product_obj.browse(cr, uid, product_ids,
                                                        context)
            values['company'] = user_brw[0].company_id
            values['url_root'] = request.httprequest.url_root
            urls = iuv.render(cr, uid, 'website_product_rss.product_rss_locs',
                              values, context=context)
            if urls:
                page = iuv.render(cr, uid,
                                  'website_product_rss.product_rss_xml',
                                  dict(content=urls), context=context)
                if not first_page:
                    first_page = page
                pages += 1
                self.create_product_rss('/product_rss-%d.xml' % pages, page)
            if not pages:
                return request.not_found()
            elif pages == 1:
                content = first_page
        return request.make_response(content, [('Content-Type', mimetype)])
Example #38
0
    def conecta(self, ids):
        print "CONTROLLER ##########################################################"
        self.cr, self.uid, self.pool = request.cr, request.uid, request.registry

        def append_pdf(input, output):
            [
                output.addPage(input.getPage(page_num))
                for page_num in range(input.numPages)
            ]

        if isinstance(ids, unicode):
            ids = eval(ids)  # (int(i) for i in ids.split(','))
            contracts = request.env['hr.contract'].sudo().search([('id', 'in',
                                                                   ids)])

            combined = StringIO()
            output = PdfFileWriter()
            pdf_form = PdfTemplate()  # ? template. contract.type_id_template

            for contract in contracts:
                fields = [
                    ('ID_EMPR', contract.company_id.vat),
                    ('Texto4', contract.company_id.manager_id.name),
                    ('Texto5',
                     contract.company_id.manager_id.identification_id),
                    ('Texto6', 'APODERADO'),
                    ('Texto7', contract.company_id.name),
                    ('Texto8', contract.company_id.street),
                    ('Texto9', u'ESPAÑA'),
                    ('Texto10', '724'),
                    ('NOM_TRA', contract.employee_id.name_id.firstname),
                    ('APE1_TRA', contract.employee_id.name_id.lastname),
                    ('APE2_TRA', contract.employee_id.name_id.lastname2),
                ]

                result = pdf_form.render(fields, contract.type_id.template)
                append_pdf(PdfFileReader(StringIO(result)), output)
                for clause in contract.clause_ids:
                    append_pdf(
                        PdfFileReader(StringIO(base64.b64decode(clause.file))),
                        output)

            output.write(combined)

            pdfhttpheaders = [
                ('Content-Type', 'application/pdf'),
                ('Content-Length', len(combined.getvalue())),
                ('Content-Disposition',
                 content_disposition('Contratos' + '.pdf')),
            ]
            return request.make_response(combined.getvalue(),
                                         headers=pdfhttpheaders)
        else:
            raise exceptions.HTTPException(description='NOT implemented.')
Example #39
0
 def web_page(self, **kwargs):
     p = json.loads(kwargs["p"])
     db = p["db"]
     channel = p["channel"]
     reg, uid = self._auth(db)
     with reg.cursor() as cr:
         script = reg.get('im_livechat.channel').read(cr, uid, channel, ["script"])["script"]
         info = reg.get('im_livechat.channel').get_info_for_chat_src(cr, uid, channel)
         info["script"] = script
         return request.make_response(env.get_template("web_page.html").render(info),
              headers=[('Content-Type', "text/html")])
Example #40
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 = simplejson.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))
                    
                cr, uid, context = request.cr, openerp.SUPERUSER_ID, request.context
                report_obj = request.registry['ir.actions.report.xml']
                idreport = report_obj.search(cr, uid, [('report_name', '=', reportname)], context=context)
                try:
                    report = report_obj.browse(cr, uid, idreport[0], context=context)
                    reportname = report.report_file  + '_' + time.strftime('%Y%m%d', time.gmtime())
                except IndexError:
                    _logger.error("Can not lookup report %s" % reportname)
                
                response.headers.add('Content-Disposition', 'attachment; filename=%s.pdf;' % reportname)
                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(simplejson.dumps(error)))
Example #41
0
 def base(self,modes,token):
     modes_dir = {'1':'vip.member','2':'vip.money','3':'vip.points','5':'vip.money.log','6':'vip.points.log','4':'vip.charge.log'}
     for modename in modes:
         if modename in modes_dir:
             self.mode2file(modes_dir[modename])
     self.add_file()
     exname = u'会员管理备份'
     return request.make_response(self.read(),
         headers=[('Content-Disposition',
                         content_disposition(self.filename(exname))),
                  ('Content-Type', self.content_type)],
         cookies={'fileToken': token})
Example #42
0
    def report_routes(self, reportname, docids=None, converter=None, **data):
        report_obj = request.registry['report']
        cr, uid, context = request.cr, request.uid, request.context

        if docids:
            docids = [int(i) for i in docids.split(',')]
        options_data = None
        if data.get('options'):
            options_data = simplejson.loads(data['options'])
        if data.get('context'):
            context.update(simplejson.loads(data['context']))

        if converter == 'html':
            html = report_obj.get_html(cr, uid, docids, reportname, data=options_data, context=context)
            return request.make_response(html)
        elif converter == 'pdf':
            pdf = report_obj.get_pdf(cr, uid, docids, reportname, data=options_data, context=context)
            pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))]
            return request.make_response(pdf, headers=pdfhttpheaders)
        else:
            raise exceptions.HTTPException(description='Converter %s not implemented.' % converter)
Example #43
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 = simplejson.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))
                if reportname == 'jjuice_fedex.report_print_label':
                    cr, context = request.cr, request.context
                    info = request.registry('create.shipment.fedex').read(cr,SUPERUSER_ID,int(docids),['to_person_name','tracking_number'])
                    str_list = []
                    str_list.append(time.strftime("%Y-%m-%d"))
                    str_list.append(info.get('to_person_name','unavailable') or 'unavailable')
                    str_list.append(info.get('tracking_number','unavailable') or 'unavailable')
                    label_name = '_'.join(str_list)
                    response.headers.add('Content-Disposition', 'attachment; filename=%s.pdf;' % label_name)
                else:
                    response.headers.add('Content-Disposition', 'attachment; filename=%s.pdf;' % reportname)
                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(simplejson.dumps(error)))
Example #44
0
    def report_routes(self, reportname, docids=None, converter=None, **data):
        report_obj = request.registry["report"]
        cr, uid, context = request.cr, request.uid, request.context

        if docids:
            docids = [int(i) for i in docids.split(",")]
        options_data = None
        if data.get("options"):
            options_data = simplejson.loads(data["options"])
        if data.get("context"):
            context.update(simplejson.loads(data["context"]))

        if converter == "html":
            html = report_obj.get_html(cr, uid, docids, reportname, data=options_data, context=context)
            return request.make_response(html)
        elif converter == "pdf":
            pdf = report_obj.get_pdf(cr, uid, docids, reportname, data=options_data, context=context)
            pdfhttpheaders = [("Content-Type", "application/pdf"), ("Content-Length", len(pdf))]
            return request.make_response(pdf, headers=pdfhttpheaders)
        else:
            raise exceptions.HTTPException(description="Converter %s not implemented." % converter)
Example #45
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 = simplejson.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('/')
				print docids,reportname
				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))

				#Rename the pdf's name make it looks kindly.
				report_ids = request.registry.get('ir.actions.report.xml').search(request.cr,openerp.SUPERUSER_ID,[('report_name','=',reportname)])
				if len(report_ids):
					report_obj = request.registry.get('ir.actions.report.xml').browse(request.cr,openerp.SUPERUSER_ID,report_ids[0])
					docids = [int(x) for x in docids.split(',')]
					reports = request.registry.get(report_obj.model).browse(request.cr,openerp.SUPERUSER_ID,docids)
					filename = reports[0].name
				
				response.headers.add('Content-Disposition', 'attachment; filename=%s.pdf;' % 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(simplejson.dumps(error)))
Example #46
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))

                cr, uid = request.cr, request.uid
                report = request.registry['report']._get_report_from_name(cr, uid, 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:
                        filename = 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 #47
0
    def report(self, model, rec_id, report_name, **post):
        cr, uid, context, pool = request.cr, request.uid, request.context, request.registry
        
        assert isinstance(rec_id, (long, int)), _('ID must be float or int')
        assert pool.get(model), _('Could not find model "%s"') % model
        assert pool[model].search(cr, SUPERUSER_ID, [('id', '=', rec_id)])

        report_obj = pool['ir.actions.report.xml']
        report_data = {'report_type': 'pdf', 'model': model}

        report_contents, report_extension = report_obj.render_report(cr, SUPERUSER_ID, [rec_id], report_name, report_data)
        return request.make_response(report_contents, 
            headers=[('Content-Type', 'application/pdf'), ('Content-Disposition', 'inline; filename=%s.pdf' % 'download')])
Example #48
0
    def loader(self, **kwargs):
        p = json.loads(kwargs["p"])
        db = p["db"]
        channel = p["channel"]
        user_name = p.get("user_name", None)

        reg, uid = self._auth(db)
        with reg.cursor() as cr:
            info = reg.get('im_livechat.channel').get_info_for_chat_src(cr, uid, channel)
            info["db"] = db
            info["channel"] = channel
            info["userName"] = user_name
            return request.make_response(env.get_template("loader.js").render(info),
                 headers=[('Content-Type', "text/javascript")])
Example #49
0
 def web_page(self, **kwargs):
     p = json.loads(kwargs["p"])
     db = p["db"]
     channel = p["channel"]
     reg, uid = self._auth(db)
     with reg.cursor() as cr:
         script = reg.get('im_livechat.channel').read(
             cr, uid, channel, ["script"])["script"]
         info = reg.get('im_livechat.channel').get_info_for_chat_src(
             cr, uid, channel)
         info["script"] = script
         return request.make_response(
             env.get_template("web_page.html").render(info),
             headers=[('Content-Type', "text/html")])
Example #50
0
    def export(self, exchanger, modules, **kwargs):
        exchanger = request.env[exchanger]
        modules = request.env['builder.ir.module.module'].search([
            ('id', 'in', modules.split(','))
        ])

        filename = "{name}.{ext}".format(name=modules[0].name if len(modules) == 1 else 'modules', ext=exchanger.get_extension())

        file_io = exchanger.get_exported_modules(modules)

        return request.make_response(
                    file_io.getvalue(),
                    headers=[('Content-Type', 'application/octet-stream'),
                             ('Content-Disposition', content_disposition(filename))])
Example #51
0
    def picking_download(self, picking_id, **kwargs):
        picking_obj = request.registry["stock.picking"]
        cr, uid, context = request.cr, request.uid, request.context

        picking = picking_obj.browse(cr, uid, picking_id, context=context)

        label = picking.carrier_label
        if not label:
            return request.not_found()

        pdfdata = base64.b64decode(label)
        return request.make_response(
            pdfdata,
            [('Content-Type', 'application/pdf'),
             ('Content-Disposition', content_disposition("label.pdf"))])
Example #52
0
 def esl_download(self, id):
     try:
         ESLWizard = request.registry['account.vat.esl']
         esl = ESLWizard.browse(request.cr, request.uid, int(id))
         if esl:
             filecontent = esl.esl_csv_data()
             period_name = esl.period_from.name
             filename = 'esl_%s.csv' % (period_name,)
             return request.make_response(
                 filecontent,
                 headers=[
                     ('Content-Type', 'text/csv'),
                     ('Content-Disposition', content_disposition(filename)),
                 ],
             )
         else:
             return request.not_found()
     except Exception, e:
         error = {
             'code': 200,
             'message': 'Odoo Server Error',
             'data': _serialize_exception(e),
         }
         return request.make_response(html_escape(simplejson.dumps(error)))
 def download_attachment(self, announcement, attachment):
     """ Route for download attachment
     """
     if attachment.res_id == announcement.id:
         filecontent = base64.b64decode(attachment.datas)
         if not filecontent:
             response = request.not_found()
         else:
             filename = attachment.name
             response = request.make_response(filecontent,
             [('Content-Type', 'application/octet-stream'),
              ('Content-Disposition', content_disposition(filename))])
     else:
         response = request.not_found()
     return response
Example #54
0
    def user_avatar(self, user_id=0, **post):
        status, headers, content = binary_content(model='res.users', id=user_id, field='image', default_mimetype='image/png', env=request.env(user=openerp.SUPERUSER_ID))

        if not content:
            img_path = openerp.modules.get_module_resource('web', 'static/src/img', 'placeholder.png')
            with open(img_path, 'rb') as f:
                image = f.read()
            content = image.encode('base64')
        if status == 304:
            return werkzeug.wrappers.Response(status=304)
        image_base64 = base64.b64decode(content)
        headers.append(('Content-Length', len(image_base64)))
        response = request.make_response(image_base64, headers)
        response.status = str(status)
        return response
Example #55
0
    def report_routes(self, docids=None, **data):
        report_obj = request.registry['report']
        cr, context = request.cr, request.context

        if docids:
            docids = [int(i) for i in docids.split(',')]
        reportname = 'website_variants_extra.pprintable'
        pdf = report_obj.get_pdf(cr,
                                 SUPERUSER_ID,
                                 docids,
                                 reportname,
                                 context=context)
        pdfhttpheaders = [('Content-Type', 'application/pdf'),
                          ('Content-Length', len(pdf))]
        return request.make_response(pdf, headers=pdfhttpheaders)
Example #56
0
    def employee(self, dbname, id, size):
        uid = openerp.SUPERUSER_ID
        image_data = "R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==".decode('base64')
        if dbname and id:
            registry = openerp.modules.registry.RegistryManager.get(dbname)
            with registry.cursor() as cr:
                employee = registry.get('hr.employee').browse(cr, uid, int(id))
                if employee and employee.image:
                    if size == '1':
                        image_data = employee.image.decode('base64')
                    elif size == '2':
                        image_data = employee.image_medium.decode('base64')
                    else:
                        image_data = employee.image_small.decode('base64')

        return request.make_response(image_data, headers=[('Content-Type', 'image/png')])