<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2014 OpenERP S.A. <http://www.openerp.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from functools import partial
import logging
import operator
import os
import time
import datetime
import dateutil

import openerp
from openerp import SUPERUSER_ID
from openerp import tools
from openerp import workflow
from openerp.osv import fields, osv
from openerp.osv.orm import browse_record
import openerp.report.interface
from openerp.report.report_sxw import report_sxw, report_rml
from openerp.tools.safe_eval import safe_eval as eval
from openerp.tools.translate import _
import openerp.workflow

_logger = logging.getLogger(__name__)

class actions(osv.osv):
    _name = 'ir.actions.actions'
    _table = 'ir_actions'
    _order = 'name'
    _columns = {
        'name': fields.char('Name', size=64, required=True),
        'type': fields.char('Action Type', required=True, size=32),
        'usage': fields.char('Action Usage', size=32),
        'help': fields.text('Action description',
            help='Optional help text for the users with a description of the target view, such as its usage and purpose.',
            translate=True),
    }
    _defaults = {
        'usage': lambda *a: False,
    }


class ir_actions_report_xml(osv.osv):

    def _report_content(self, cursor, user, ids, name, arg, context=None):
        res = {}
        for report in self.browse(cursor, user, ids, context=context):
            data = report[name + '_data']
            if not data and report[name[:-8]]:
                fp = None
                try:
                    fp = tools.file_open(report[name[:-8]], mode='rb')
                    data = fp.read()
                except:
                    data = False
                finally:
                    if fp:
                        fp.close()
            res[report.id] = data
        return res

    def _report_content_inv(self, cursor, user, id, name, value, arg, context=None):
        self.write(cursor, user, id, {name+'_data': value}, context=context)

    def _report_sxw(self, cursor, user, ids, name, arg, context=None):
        res = {}
        for report in self.browse(cursor, user, ids, context=context):
            if report.report_rml:
                res[report.id] = report.report_rml.replace('.rml', '.sxw')
            else:
                res[report.id] = False
        return res

    def _lookup_report(self, cr, name):
        """
        Look up a report definition.
        """
        opj = os.path.join

        # First lookup in the deprecated place, because if the report definition
        # has not been updated, it is more likely the correct definition is there.
        # Only reports with custom parser sepcified in Python are still there.
        if 'report.' + name in openerp.report.interface.report_int._reports:
            new_report = openerp.report.interface.report_int._reports['report.' + name]
        else:
            cr.execute("SELECT * FROM ir_act_report_xml WHERE report_name=%s", (name,))
            r = cr.dictfetchone()
            if r:
                if r['report_rml'] or r['report_rml_content_data']:
                    if r['parser']:
                        kwargs = { 'parser': operator.attrgetter(r['parser'])(openerp.addons) }
                    else:
                        kwargs = {}
                    new_report = report_sxw('report.'+r['report_name'], r['model'],
                            opj('addons',r['report_rml'] or '/'), header=r['header'], register=False, **kwargs)
                elif r['report_xsl'] and r['report_xml']:
                    new_report = report_rml('report.'+r['report_name'], r['model'],
                            opj('addons',r['report_xml']),
                            r['report_xsl'] and opj('addons',r['report_xsl']), register=False)
                else:
                    raise Exception, "Unhandled report type: %s" % r
            else:
                raise Exception, "Required report does not exist: %s" % r

        return new_report

    def render_report(self, cr, uid, res_ids, name, data, context=None):
        """
        Look up a report definition and render the report for the provided IDs.
        """
        new_report = self._lookup_report(cr, name)
        return new_report.create(cr, uid, res_ids, data, context)

    _name = 'ir.actions.report.xml'
    _inherit = 'ir.actions.actions'
    _table = 'ir_act_report_xml'
    _sequence = 'ir_actions_id_seq'
    _order = 'name'
    _columns = {
        'type': fields.char('Action Type', size=32, required=True),
        'name': fields.char('Name', size=64, required=True, translate=True),

        'model': fields.char('Model', required=True),
        'report_type': fields.char('Report Type', required=True, help="Report Type: qweb-html, qweb-pdf, custom"),
        'report_name': fields.char('Service Name', required=True, help="URL of the report is /report/<service name>/<ids>"),
        'groups_id': fields.many2many('res.groups', 'res_groups_report_rel', 'uid', 'gid', 'Groups'),

        # options
        'multi': fields.boolean('On Multiple Doc.', help="If set to true, the action will not be displayed on the right toolbar of a form view."),
        'attachment_use': fields.boolean('Reload from Attachment', help='If you check this, then the second time the user prints with same attachment name, it returns the previous report.'),
        'attachment': fields.char('Save as Attachment Prefix', size=128, help='This is the filename of the attachment used to store the printing result. Keep empty to not save the printed reports. You can use a python expression with the object and time variables.'),

        # Deprecated rml stuff
        'usage': fields.char('Action Usage', size=32),
        'header': fields.boolean('Add RML Header', help="Add or not the corporate RML header"),
        'parser': fields.char('Parser Class'),
        'auto': fields.boolean('Custom Python Parser'),

        'report_xsl': fields.char('XSL Path'),
        'report_xml': fields.char('XML Path'),

        'report_rml': fields.char('Main Report File Path', help="The path to the main report file (depending on Report Type) or NULL if the content is in another data field"),
        'report_file': fields.related('report_rml', type="char", required=False, readonly=False, string='Report File', help="The path to the main report file (depending on Report Type) or NULL if the content is in another field", store=True),

        'report_sxw': fields.function(_report_sxw, type='char', string='SXW Path'),
        'report_sxw_content_data': fields.binary('SXW Content'),
        'report_rml_content_data': fields.binary('RML Content'),
        'report_sxw_content': fields.function(_report_content, fnct_inv=_report_content_inv, type='binary', string='SXW Content',),
        'report_rml_content': fields.function(_report_content, fnct_inv=_report_content_inv, type='binary', string='RML Content'),
    }
    _defaults = {
        'type': 'ir.actions.report.xml',
        'multi': False,
        'auto': True,
        'header': True,
        'report_sxw_content': False,
        'report_type': 'qweb-pdf',
        'attachment': False,
    }


class ir_actions_act_window(osv.osv):
    _name = 'ir.actions.act_window'
    _table = 'ir_act_window'
    _inherit = 'ir.actions.actions'
    _sequence = 'ir_actions_id_seq'
    _order = 'name'

    def _check_model(self, cr, uid, ids, context=None):<commit_msg>[FIX] ir.actions.report.xml keep report_type pdf until full report conversion is completed<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2014 OpenERP S.A. <http://www.openerp.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from functools import partial
import logging
import operator
import os
import time
import datetime
import dateutil

import openerp
from openerp import SUPERUSER_ID
from openerp import tools
from openerp import workflow
from openerp.osv import fields, osv
from openerp.osv.orm import browse_record
import openerp.report.interface
from openerp.report.report_sxw import report_sxw, report_rml
from openerp.tools.safe_eval import safe_eval as eval
from openerp.tools.translate import _
import openerp.workflow

_logger = logging.getLogger(__name__)

class actions(osv.osv):
    _name = 'ir.actions.actions'
    _table = 'ir_actions'
    _order = 'name'
    _columns = {
        'name': fields.char('Name', size=64, required=True),
        'type': fields.char('Action Type', required=True, size=32),
        'usage': fields.char('Action Usage', size=32),
        'help': fields.text('Action description',
            help='Optional help text for the users with a description of the target view, such as its usage and purpose.',
            translate=True),
    }
    _defaults = {
        'usage': lambda *a: False,
    }


class ir_actions_report_xml(osv.osv):

    def _report_content(self, cursor, user, ids, name, arg, context=None):
        res = {}
        for report in self.browse(cursor, user, ids, context=context):
            data = report[name + '_data']
            if not data and report[name[:-8]]:
                fp = None
                try:
                    fp = tools.file_open(report[name[:-8]], mode='rb')
                    data = fp.read()
                except:
                    data = False
                finally:
                    if fp:
                        fp.close()
            res[report.id] = data
        return res

    def _report_content_inv(self, cursor, user, id, name, value, arg, context=None):
        self.write(cursor, user, id, {name+'_data': value}, context=context)

    def _report_sxw(self, cursor, user, ids, name, arg, context=None):
        res = {}
        for report in self.browse(cursor, user, ids, context=context):
            if report.report_rml:
                res[report.id] = report.report_rml.replace('.rml', '.sxw')
            else:
                res[report.id] = False
        return res

    def _lookup_report(self, cr, name):
        """
        Look up a report definition.
        """
        opj = os.path.join

        # First lookup in the deprecated place, because if the report definition
        # has not been updated, it is more likely the correct definition is there.
        # Only reports with custom parser sepcified in Python are still there.
        if 'report.' + name in openerp.report.interface.report_int._reports:
            new_report = openerp.report.interface.report_int._reports['report.' + name]
        else:
            cr.execute("SELECT * FROM ir_act_report_xml WHERE report_name=%s", (name,))
            r = cr.dictfetchone()
            if r:
                if r['report_rml'] or r['report_rml_content_data']:
                    if r['parser']:
                        kwargs = { 'parser': operator.attrgetter(r['parser'])(openerp.addons) }
                    else:
                        kwargs = {}
                    new_report = report_sxw('report.'+r['report_name'], r['model'],
                            opj('addons',r['report_rml'] or '/'), header=r['header'], register=False, **kwargs)
                elif r['report_xsl'] and r['report_xml']:
                    new_report = report_rml('report.'+r['report_name'], r['model'],
                            opj('addons',r['report_xml']),
                            r['report_xsl'] and opj('addons',r['report_xsl']), register=False)
                else:
                    raise Exception, "Unhandled report type: %s" % r
            else:
                raise Exception, "Required report does not exist: %s" % r

        return new_report

    def render_report(self, cr, uid, res_ids, name, data, context=None):
        """
        Look up a report definition and render the report for the provided IDs.
        """
        new_report = self._lookup_report(cr, name)
        return new_report.create(cr, uid, res_ids, data, context)

    _name = 'ir.actions.report.xml'
    _inherit = 'ir.actions.actions'
    _table = 'ir_act_report_xml'
    _sequence = 'ir_actions_id_seq'
    _order = 'name'
    _columns = {
        'type': fields.char('Action Type', size=32, required=True),
        'name': fields.char('Name', size=64, required=True, translate=True),

        'model': fields.char('Model', required=True),
        'report_type': fields.char('Report Type', required=True, help="Report Type: qweb-html, qweb-pdf, custom"),
        'report_name': fields.char('Service Name', required=True, help="URL of the report is /report/<service name>/<ids>"),
        'groups_id': fields.many2many('res.groups', 'res_groups_report_rel', 'uid', 'gid', 'Groups'),

        # options
        'multi': fields.boolean('On Multiple Doc.', help="If set to true, the action will not be displayed on the right toolbar of a form view."),
        'attachment_use': fields.boolean('Reload from Attachment', help='If you check this, then the second time the user prints with same attachment name, it returns the previous report.'),
        'attachment': fields.char('Save as Attachment Prefix', size=128, help='This is the filename of the attachment used to store the printing result. Keep empty to not save the printed reports. You can use a python expression with the object and time variables.'),

        # Deprecated rml stuff
        'usage': fields.char('Action Usage', size=32),
        'header': fields.boolean('Add RML Header', help="Add or not the corporate RML header"),
        'parser': fields.char('Parser Class'),
        'auto': fields.boolean('Custom Python Parser'),

        'report_xsl': fields.char('XSL Path'),
        'report_xml': fields.char('XML Path'),

        'report_rml': fields.char('Main Report File Path', help="The path to the main report file (depending on Report Type) or NULL if the content is in another data field"),
        'report_file': fields.related('report_rml', type="char", required=False, readonly=False, string='Report File', help="The path to the main report file (depending on Report Type) or NULL if the content is in another field", store=True),

        'report_sxw': fields.function(_report_sxw, type='char', string='SXW Path'),
        'report_sxw_content_data': fields.binary('SXW Content'),
        'report_rml_content_data': fields.binary('RML Content'),
        'report_sxw_content': fields.function(_report_content, fnct_inv=_report_content_inv, type='binary', string='SXW Content',),
        'report_rml_content': fields.function(_report_content, fnct_inv=_report_content_inv, type='binary', string='RML Content'),
    }
    _defaults = {
        'type': 'ir.actions.report.xml',
        'multi': False,
        'auto': True,
        'header': True,
        'report_sxw_content': False,
        'report_type': 'pdf',
        'attachment': False,
    }


class ir_actions_act_window(osv.osv):
    _name = 'ir.actions.act_window'
    _table = 'ir_act_window'
    _inherit = 'ir.actions.actions'
    _sequence = 'ir_actions_id_seq'
    _order = 'name'

    def _check_model(self, cr, uid, ids, context=None):
{'fraction_non_alphanumeric': 0.13192706471219162, 'fraction_numerical': 0.003336908592539626, 'mean_word_length': 2.755426269859029, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 17}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5508756', 'n_tokens_mistral': 4840, 'n_tokens_neox': 4644, 'n_words': 1477}