Exemple #1
0
    def event_track_proposal_post(self, event, **post):
        cr, uid, context = request.cr, request.uid, request.context

        tags = []
        for tag in event.allowed_track_tag_ids:
            if post.get('tag_' + str(tag.id)):
                tags.append(tag.id)

        track_obj = request.registry['event.track']
        track_id = track_obj.create(
            cr,
            openerp.SUPERUSER_ID, {
                'name': post['track_name'],
                'partner_name': post['partner_name'],
                'partner_email': post['email_from'],
                'partner_phone': post['phone'],
                'partner_biography': html_escape(post['biography']),
                'event_id': event.id,
                'tag_ids': [(6, 0, tags)],
                'user_id': False,
                'description': html_escape(post['description']),
            },
            context=context)
        track = track_obj.browse(cr, uid, track_id, context=context)
        values = {'track': track, 'event': event}
        return request.website.render(
            "website_event_track.event_track_proposal_success", values)
Exemple #2
0
    def remove(self, ids, **kwargs):
        """ Removes a web-based image attachment if it is used by no view (template)

        Returns a dict mapping attachments which would not be removed (if any)
        mapped to the views preventing their removal
        """
        cr, uid, context = request.cr, request.uid, request.context
        Attachment = request.registry['ir.attachment']
        Views = request.registry['ir.ui.view']

        attachments_to_remove = []
        # views blocking removal of the attachment
        removal_blocked_by = {}

        for attachment in Attachment.browse(cr, uid, ids, context=context):
            # in-document URLs are html-escaped, a straight search will not
            # find them
            url = tools.html_escape(attachment.local_url)
            ids = Views.search(cr,
                               uid, [
                                   "|", ('arch_db', 'like', '"%s"' % url),
                                   ('arch_db', 'like', "'%s'" % url)
                               ],
                               context=context)

            if ids:
                removal_blocked_by[attachment.id] = Views.read(cr,
                                                               uid,
                                                               ids, ['name'],
                                                               context=context)
            else:
                attachments_to_remove.append(attachment.id)
        if attachments_to_remove:
            Attachment.unlink(cr, uid, attachments_to_remove, context=context)
        return removal_blocked_by
    def remove(self, ids, **kwargs):
        """ Removes a web-based image attachment if it is used by no view (template)

        Returns a dict mapping attachments which would not be removed (if any)
        mapped to the views preventing their removal
        """
        cr, uid, context = request.cr, request.uid, request.context
        Attachment = request.registry['ir.attachment']
        Views = request.registry['ir.ui.view']

        attachments_to_remove = []
        # views blocking removal of the attachment
        removal_blocked_by = {}

        for attachment in Attachment.browse(cr, uid, ids, context=context):
            # in-document URLs are html-escaped, a straight search will not
            # find them
            url = tools.html_escape(attachment.local_url)
            ids = Views.search(cr, uid, ["|", ('arch_db', 'like', '"%s"' % url), ('arch_db', 'like', "'%s'" % url)], context=context)

            if ids:
                removal_blocked_by[attachment.id] = Views.read(
                    cr, uid, ids, ['name'], context=context)
            else:
                attachments_to_remove.append(attachment.id)
        if attachments_to_remove:
            Attachment.unlink(cr, uid, attachments_to_remove, context=context)
        return removal_blocked_by
Exemple #4
0
    def create_pageview(self, vals, test=False):
        # returns True if the operation in the db was successful, False otherwise
        lead_id = vals.get('lead_id', 0)
        user_id = vals.get('user_id')
        url = vals.get('url', '')
        view_date = fields.Datetime.now()

        with self.pool.cursor() as pv_cr:
            if test:
                pv_cr = self._cr
            pv_cr.execute('''
                UPDATE website_crm_pageview SET view_date=%s WHERE lead_id=%s AND url=%s RETURNING id;
                ''', (view_date, lead_id, url))
            fetch = pv_cr.fetchone()
            if fetch:
                return True
            else:
                # update failed
                try:
                    with tools.mute_logger('openerp.sql_db'):
                        pv_cr.execute('''
                            INSERT INTO website_crm_pageview (lead_id, user_id, url, view_date)
                            SELECT %s,%s,%s,%s
                            RETURNING id;
                            ''', (lead_id, user_id, url, view_date))
                    fetch = pv_cr.fetchone()
                    if fetch:
                        # a new pageview has been created, a message is posted
                        url = html_escape(url)
                        body = '<a href="%s" target="_blank"><b>%s</b></a>' % (url, url)
                        ctx = dict(self._context, mail_notify_noemail=True)
                        self.pool['crm.lead'].message_post(self._cr, SUPERUSER_ID, [lead_id], body=body, subject="Page visited", context=ctx)
                        return True
                except IntegrityError:
                    return False
Exemple #5
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)))
    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)))
Exemple #7
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)))
Exemple #8
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)))
Exemple #9
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)))
Exemple #10
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)))
Exemple #11
0
 def backup_log(self):
     """Log a backup result."""
     try:
         _logger.info("Starting database backup: %s", self.name)
         yield
     except:
         _logger.exception("Database backup failed: %s", self.name)
         escaped_tb = tools.html_escape(traceback.format_exc())
         self.message_post("<p>%s</p><pre>%s</pre>" %
                           (_("Database backup failed."), escaped_tb),
                           subtype=self.env.ref("auto_backup.failure"))
     else:
         _logger.info("Database backup succeeded: %s", self.name)
         self.message_post(_("Database backup succeeded."))
Exemple #12
0
    def event_track_proposal_post(self, event, **post):
        cr, uid, context = request.cr, request.uid, request.context

        tags = []
        for tag in event.allowed_track_tag_ids:
            if post.get('tag_'+str(tag.id)):
                tags.append(tag.id)

        track_obj = request.registry['event.track']
        track_id = track_obj.create(cr, openerp.SUPERUSER_ID, {
            'name': post['track_name'],
            'partner_name': post['partner_name'],
            'partner_email': post['email_from'],
            'partner_phone': post['phone'],
            'partner_biography': html_escape(post['biography']),
            'event_id': event.id,
            'tag_ids': [(6, 0, tags)],
            'user_id': False,
            'description': html_escape(post['description']),
        }, context=context)
        track = track_obj.browse(cr, uid, track_id, context=context)
        values = {'track': track, 'event': event}
        return request.website.render("website_event_track.event_track_proposal_success", values)
Exemple #13
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 == 'xls':
             response = request.make_response(
                 None,
                 headers=[('Content-Type', 'application/vnd.ms-excel'),
                          ('Content-Disposition', 'attachment; filename=' +
                           report_obj.get_name() + '.xls;')])
             context_id.get_xls(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)))
Exemple #14
0
 def cleanup_log(self):
     """Log a possible cleanup failure."""
     try:
         _logger.info("Starting cleanup process after database backup: %s",
                      self.name)
         yield
     except:
         _logger.exception("Cleanup of old database backups failed: %s")
         escaped_tb = tools.html_escape(traceback.format_exc())
         self.message_post(
             "<p>%s</p><pre>%s</pre>" %
             (_("Cleanup of old database backups failed."), escaped_tb),
             subtype=self.env.ref("auto_backup.failure"))
     else:
         _logger.info("Cleanup of old database backups succeeded: %s",
                      self.name)
Exemple #15
0
 def backup_log(self):
     """Log a backup result."""
     try:
         _logger.info("Starting database backup: %s", self.name)
         yield
     except:
         _logger.exception("Database backup failed: %s", self.name)
         escaped_tb = tools.html_escape(traceback.format_exc())
         self.message_post(
             "<p>%s</p><pre>%s</pre>" % (
                 _("Database backup failed."),
                 escaped_tb),
             subtype=self.env.ref("auto_backup.failure"))
     else:
         _logger.info("Database backup succeeded: %s", self.name)
         self.message_post(_("Database backup succeeded."))
Exemple #16
0
 def cleanup_log(self):
     """Log a possible cleanup failure."""
     try:
         _logger.info("Starting cleanup process after database backup: %s",
                      self.name)
         yield
     except:
         _logger.exception("Cleanup of old database backups failed: %s")
         escaped_tb = tools.html_escape(traceback.format_exc())
         self.message_post(
             "<p>%s</p><pre>%s</pre>" % (
                 _("Cleanup of old database backups failed."),
                 escaped_tb),
             subtype=self.env.ref("auto_backup.failure"))
     else:
         _logger.info("Cleanup of old database backups succeeded: %s",
                      self.name)
Exemple #17
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")
                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)))
Exemple #18
0
    def create_pageview(self, vals, test=False):
        # returns True if the operation in the db was successful, False otherwise
        lead_id = vals.get('lead_id', 0)
        user_id = vals.get('user_id')
        url = vals.get('url', '')
        view_date = fields.Datetime.now()

        with self.pool.cursor() as pv_cr:
            if test:
                pv_cr = self._cr
            pv_cr.execute(
                '''
                UPDATE website_crm_pageview SET view_date=%s WHERE lead_id=%s AND url=%s RETURNING id;
                ''', (view_date, lead_id, url))
            fetch = pv_cr.fetchone()
            if fetch:
                return True
            else:
                # update failed
                try:
                    with tools.mute_logger('openerp.sql_db'):
                        pv_cr.execute(
                            '''
                            INSERT INTO website_crm_pageview (lead_id, user_id, url, view_date)
                            SELECT %s,%s,%s,%s
                            RETURNING id;
                            ''', (lead_id, user_id, url, view_date))
                    fetch = pv_cr.fetchone()
                    if fetch:
                        # a new pageview has been created, a message is posted
                        url = html_escape(url)
                        body = '<a href="%s" target="_blank"><b>%s</b></a>' % (
                            url, url)
                        ctx = dict(self._context, mail_notify_noemail=True)
                        self.pool['crm.lead'].message_post(
                            self._cr,
                            SUPERUSER_ID, [lead_id],
                            body=body,
                            subject="Page visited",
                            context=ctx)
                        return True
                except IntegrityError:
                    return False
Exemple #19
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)))
Exemple #20
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 != 'py3o':
            return super(ReportController, self).report_download(data, token)
        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')
                print "response", response
            else:

                # Particular report:
                # decoding the args represented in JSON
                data = url_decode(url.split('?')[1]).items()
                response = self.report_routes(reportname,
                                              converter='py3o',
                                              **dict(data))
            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)))
Exemple #21
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)))
Exemple #22
0
    def insert_record(self, request, model, values, custom, meta=None):
        if model.model != 'crm.lead':
            return super(ContactController,
                         self).insert_record(request, model, values, custom,
                                             meta)

        cr, context = request.cr, request.context

        lead_model = request.registry["crm.lead"]
        lead_id = lead_model.decode(request)

        # domain: leads that are still open:
        # NOT [ on_change AND (proba = 0 OR proba = 100) ]
        # the condition on the lead_id is prepended
        domain = [('id', '=', lead_id), '|',
                  ('stage_id.on_change', '=', False), '&',
                  ('stage_id.probability', '!=', 0),
                  ('stage_id.probability', '!=', 100)]
        lead_instance = lead_model.search(cr,
                                          SUPERUSER_ID,
                                          domain,
                                          context=context)

        if lead_instance:
            # a lead_id cookie exists and it has not been altered and the lead is not closed
            lead = lead_model.browse(cr,
                                     SUPERUSER_ID,
                                     lead_id,
                                     context=context)

            # NOTE: the following should be changed when dynamic forms exist
            changed_values = {}
            for fieldname, fieldvalue in values.items():
                if fieldname in lead._all_columns and fieldvalue:
                    if lead[fieldname] and lead[fieldname] != fieldvalue:
                        changed_values[fieldname] = fieldvalue
                    else:
                        lead[fieldname] = fieldvalue
            # Post a message to indicate the updated field (if any)
            if changed_values:
                body = 'Other value given for field '
                for fieldname in changed_values.keys():
                    body += '<br/><b>%s</b>: <b>%s</b>' % (
                        fieldname, html_escape(changed_values[fieldname]))
                request.registry['crm.lead'].message_post(
                    cr,
                    SUPERUSER_ID, [lead_id],
                    body=body,
                    subject="Field value changed",
                    context=context)

            return lead_id

        else:
            # either no lead_id cookie OR the lead_id doesn't exist in db OR the current one is closed -> a lead is created
            lang = context.get('lang', False)
            lang_id = request.registry["res.lang"].search(
                cr, SUPERUSER_ID, [('code', '=', lang)], context=context)
            lang_id = lang_id and lang_id[0] or False
            values['lang_id'] = lang_id
            body = None

            if 'pages_viewed' in request.session:
                score_pageview_ids = []
                url_list = []
                pages_viewed = request.session['pages_viewed']
                for url, date in pages_viewed.iteritems():
                    vals = {
                        'user_id': request.session.get('uid'),
                        'url': url,
                        'view_date': date
                    }
                    score_pageview_ids.append((0, 0, vals))
                    url_list.append(url)
                del request.session['pages_viewed']
                values['score_pageview_ids'] = score_pageview_ids
                urls = []
                for url in url_list:
                    url_encoded = html_escape(url)
                    urls.append('<a href="%s" target="_blank"><b>%s</b></a>' %
                                (url_encoded, url_encoded))
                body = '<br/>'.join(urls)

            new_lead_id = self.create_real_lead(request, model, values, custom,
                                                meta)

            # if pages were seen, a message is posted
            if body:
                request.registry['crm.lead'].message_post(
                    cr,
                    SUPERUSER_ID, [new_lead_id],
                    body=body,
                    subject="Pages visited",
                    context=context)

            return new_lead_id
 def escape_node(node):
     node.text = node.text and html_escape(node.text)
     node.tail = node.tail and html_escape(node.tail)
Exemple #24
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 = 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)))
Exemple #25
0
 def escape_node(node):
     node.text = node.text and html_escape(node.text)
     node.tail = node.tail and html_escape(node.tail)
Exemple #26
0
    def report_download(self, data, token):
        """This function is used by 'report_xls.js' in order to
        trigger the download of xls/ods report.
        :param token: token received by controller
        :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]
        try:
            if report_type == 'qweb-xls':
                reportname = url.split('/reportxlstemplate/xls/')[1].split(
                    '?')[0]
                docids = None
                if '/' in reportname:
                    reportname, docids = reportname.split('/')
                if docids:
                    # Generic report:
                    response = self.report_routes(reportname,
                                                  docids=docids,
                                                  converter='xls')
                else:
                    # Particular report:
                    # Decoding the args represented in JSON
                    data = url_decode(url.split('?')[1]).items()
                    response = self.report_routes(reportname,
                                                  converter='xls',
                                                  **dict(data))

                cr, uid = request.cr, request.uid
                report = request.registry['report']._get_xls_report_from_name(
                    cr, uid, reportname)
                filename = "%s.%s" % (report.name, "xlsx")
                response.headers.add('Content-Disposition',
                                     content_disposition(filename))
                response.set_cookie('fileToken', token)
                return response

            elif report_type == 'qweb-ods':
                reportname = url.split('/reportxlstemplate/ods/')[1].split(
                    '?')[0]
                docids = None
                if '/' in reportname:
                    reportname, docids = reportname.split('/')
                if docids:
                    # Generic report:
                    response = self.report_routes(reportname,
                                                  docids=docids,
                                                  converter='ods')
                else:
                    # Particular report:
                    # Decoding the args represented in JSON
                    data = url_decode(url.split('?')[1]).items()
                    response = self.report_routes(reportname,
                                                  converter='ods',
                                                  **dict(data))

                cr, uid = request.cr, request.uid
                report = request.registry['report']._get_xls_report_from_name(
                    cr, uid, reportname)
                filename = "%s.%s" % (report.name, "ods")
                response.headers.add('Content-Disposition',
                                     content_disposition(filename))
                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)))
Exemple #27
0
    def create_lead(self, request, values, kwargs):
        cr, context = request.cr, request.context

        lead_model = request.registry["crm.lead"]
        lead_id = lead_model.decode(request)

        # domain: leads that are still open:
        # NOT [ on_change AND (proba = 0 OR proba = 100) ]
        # the condition on the lead_id is prepended
        domain = [
            ('id', '=', lead_id),
            '|',
            ('stage_id.on_change', '=', False),
            '&',
            ('stage_id.probability', '!=', 0),
            ('stage_id.probability', '!=', 100)
        ]
        lead_instance = lead_model.search(cr, SUPERUSER_ID, domain, context=context)

        if lead_instance:
            # a lead_id cookie exists and it has not been altered and the lead is not closed
            lead = lead_model.browse(cr, SUPERUSER_ID, lead_id, context=context)

            # NOTE: the following should be changed when dynamic forms exist
            changed_values = {}
            for fieldname, fieldvalue in values.items():
                if fieldname in lead._all_columns and fieldvalue:
                    if lead[fieldname] and lead[fieldname] != fieldvalue:
                        changed_values[fieldname] = fieldvalue
                    else:
                        lead[fieldname] = fieldvalue
            # Post a message to indicate the updated field (if any)
            if changed_values:
                body = 'Other value given for field '
                for fieldname in changed_values.keys():
                    body += '<br/><b>%s</b>: <b>%s</b>' % (fieldname, html_escape(changed_values[fieldname]))
                request.registry['crm.lead'].message_post(cr, SUPERUSER_ID, [lead_id], body=body, subject="Field value changed", context=context)

        else:
            # either no lead_id cookie OR the lead_id doesn't exist in db OR the current one is closed -> a lead is created
            lang = context.get('lang', False)
            lang_id = request.registry["res.lang"].search(cr, SUPERUSER_ID, [('code', '=', lang)], context=context)
            lang_id = lang_id and lang_id[0] or False
            values['lang_id'] = lang_id
            body = None

            if 'pages_viewed' in request.session:
                score_pageview_ids = []
                url_list = []
                pages_viewed = request.session['pages_viewed']
                for url, date in pages_viewed.iteritems():
                    vals = {'user_id': request.session.get('uid'), 'url': url, 'view_date': date}
                    score_pageview_ids.append((0, 0, vals))
                    url_list.append(url)
                del request.session['pages_viewed']
                values['score_pageview_ids'] = score_pageview_ids
                urls = []
                for url in url_list:
                    url_encoded = html_escape(url)
                    urls.append('<a href="%s" target="_blank"><b>%s</b></a>' % (url_encoded, url_encoded))
                body = '<br/>'.join(urls)

            new_lead_id = self.create_real_lead(request, values, kwargs)

            # if pages were seen, a message is posted
            if body:
                request.registry['crm.lead'].message_post(cr, SUPERUSER_ID, [new_lead_id], body=body, subject="Pages visited", context=context)

            return new_lead_id
Exemple #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 = 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))

#################### TO CHANGE NAME OF THE QWEB REPORT PDF FILE ##################

                if docids:
                    if reportname == "account.report_invoice":
                        inv_obj = request.registry['account.invoice']
                        lst_inv = []
                        lst_inv = docids.split(",")
                        for ele_inv in lst_inv:
                            inv_browse = inv_obj.browse(request.cr, request.uid, [int(ele_inv)])
                            if inv_browse[0].type == 'out_invoice' or inv_browse[0].type == 'in_invoice':
                                if inv_browse[0].number:
                                    reportname = 'Invoice' + '(' + str(inv_browse[0].number or '') + ')'
                                else:
                                    reportname = 'Invoice'
                            else:
                                if inv_browse[0].number:
                                    reportname = "Refund" + '(' + str(inv_browse[0].number or '') + ')'
                                else:
                                    reportname = 'Refund'
                                    
                    if reportname == "sale.report_saleorder":
                        sale_obj = request.registry['sale.order']
                        lst = []
                        lst = docids.split(",")
                        for ele in lst:
                            sale_browse = sale_obj.browse(request.cr, request.uid, [int(ele)])
                            if sale_browse[0].state in ['draft', 'sent']:
                                if sale_browse[0].name:
                                    reportname = "Quotation" + '(' + str(sale_browse[0].name) + ')'
                                else:
                                    reportname = "Quotation"
                            else :
                                if sale_browse[0].name:
                                    reportname = "Order" + '(' + str(sale_browse[0].name) + ')'
                                else:
                                    reportname = "Order"

                    if reportname == "purchase.report_purchaseorder":
                        purchase_obj = request.registry['purchase.order']
                        lst = []
                        lst = docids.split(",")
                        for ele in lst:
                            purchase_browse = purchase_obj.browse(request.cr, request.uid, [int(ele)])
                            if purchase_browse[0].state in ['draft', 'sent']:
                                if purchase_browse[0].name:
                                    reportname = "Purchase Order" + '(' + str(purchase_browse[0].name) + ')'
                                else:
                                    reportname = "Purchase Order"
                            else :
                                if purchase_browse[0].name:
                                    reportname = "Purchase Order" + '(' + str(purchase_browse[0].name) + ')'
                                else:
                                    reportname = "Purchase Order"
                                    
####################################################################################                    

                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)))
Exemple #29
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, 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)

        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('/')

            ir_action = request.env['ir.actions.report.xml']
            action_py3o_report = ir_action.get_from_report_name(
                reportname, "py3o").with_context(request.env.context)
            outputfile = action_py3o_report.py3o_filetype
            doutputfile = '.' + outputfile
            tdoutfile = 'x.' + outputfile
            if not action_py3o_report.py3o_filetype_template:
                rftype = action_py3o_report.py3o_template_id.filetype
            else:
                rftype = action_py3o_report.py3o_filetype_template
            ftype = '.' + rftype

            with open(
                    os.path.dirname(__file__) + '/' + reportname + ftype,
                    'a+') as create_ods:
                create_ods.write(response.data)
            os.system("unoconv -f " + outputfile + " '" +
                      os.path.dirname(__file__) + "/" + reportname + ftype +
                      "'")
            with open(
                    os.path.dirname(__file__) + '/' + reportname + doutputfile,
                    'r+') as create_xlsx:
                res = create_xlsx.read()
            os.remove(os.path.dirname(__file__) + '/' + reportname + ftype)
            os.remove(
                os.path.dirname(__file__) + '/' + reportname + doutputfile)
            filename = action_py3o_report.gen_report_download_filename(
                docids, data)
            filename_without_type = filename.split('.')[0]

            content_type = mimetypes.guess_type(tdoutfile)[0]
            http_headers = [
                ('Content-Type', content_type), ('Content-Length', len(res)),
                ('Content-Disposition',
                 content_disposition(filename_without_type + doutputfile))
            ]
            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)))
Exemple #30
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)))
Exemple #31
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)))
Exemple #32
0
    def report_download(self, data, token):
        """Hook to change file name, using employee/partner name and resume format
        """
        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))

                # ----- Hook to rename file -------
                model = request.registry['ir.actions.report.xml'].search_read(
                    request.cr,
                    request.uid, [('report_name', '=', reportname)],
                    ['model', 'report_file'],
                    context=request.context)
                model_name = model and model[0]['model']
                model_obj = request.registry[model_name]
                # If model prepared to hook report filename, get filename to use
                if hasattr(model_obj, 'get_report_filename'):
                    # Set specific filename
                    record_ids = [int(id) for id in docids.split(",")]
                    reportfile_prefix = model[0]['report_file']
                    report_file = model_obj.get_report_filename(
                        request.cr,
                        request.uid,
                        record_ids,
                        reportfile_prefix,
                        context=request.context)
                    reportname = report_file or reportfile_prefix
                # ----- End --------------------------

                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)))
Exemple #33
0
 def _body(commit):
     body = html_escape(commit['message']).replace('\r\n', '<br/>')
     body += '<br/>'
     body += '<a href="%s">%s</a>' % (commit['url'], commit['id'])
     return body