size
int64
0
304k
ext
stringclasses
1 value
lang
stringclasses
1 value
branch
stringclasses
1 value
content
stringlengths
0
304k
avg_line_length
float64
0
238
max_line_length
int64
0
304k
698
py
PYTHON
15.0
# Copyright 2013 Camptocamp SA - Guewen Baconnier # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Stock Reservation", "summary": "Stock reservations on products", "version": "15.0.1.1.0", "author": "Camptocamp, Odoo Community Association (OCA)", "category": "Warehouse", "license": "AGPL-3", "complexity": "normal", "website": "https://github.com/OCA/stock-logistics-warehouse", "depends": ["stock"], "data": [ "view/stock_reserve.xml", "view/product.xml", "data/stock_data.xml", "security/ir.model.access.csv", "data/cron.xml", ], "auto_install": False, "installable": True, }
31.727273
698
2,963
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields from odoo.tests import Form, common class TestStockReserve(common.TransactionCase): def setUp(self): super().setUp() warehouse_form = Form(self.env["stock.warehouse"]) warehouse_form.name = "Test warehouse" warehouse_form.code = "TEST" self.warehouse = warehouse_form.save() product_form = Form(self.env["product.product"]) product_form.name = "Test Product" product_form.type = "product" product_form.detailed_type = "product" self.product = product_form.save() self.env["stock.quant"].create( { "product_id": self.product.id, "location_id": self.warehouse.lot_stock_id.id, "quantity": 10.0, } ) def _create_stock_reservation(self, qty): form_reservation = Form(self.env["stock.reservation"]) form_reservation.product_id = self.product form_reservation.product_uom_qty = qty form_reservation.location_id = self.warehouse.lot_stock_id return form_reservation.save() def test_reservation_and_reservation_release(self): reservation_1 = self._create_stock_reservation(6) reservation_1.reserve() self.assertFalse(reservation_1.picking_id) self.assertEqual(self.product.virtual_available, 4) reservation_2 = self._create_stock_reservation(1) reservation_2.reserve() self.assertFalse(reservation_2.picking_id) self.assertEqual(self.product.virtual_available, 3) reservation_1.release_reserve() self.assertEqual(self.product.virtual_available, 9) def test_cron_release(self): reservation_1 = self._create_stock_reservation(6) reservation_1.date_validity = fields.Date.from_string("2021-01-01") reservation_1.reserve() self.assertFalse(reservation_1.picking_id) self.assertEqual(self.product.virtual_available, 4) cron = self.env.ref("stock_reserve.ir_cron_release_stock_reservation") cron.method_direct_trigger() self.assertEqual(self.product.virtual_available, 10) def test_cron_reserve(self): reservation_1 = self._create_stock_reservation(11) reservation_1.reserve() self.assertFalse(reservation_1.picking_id) self.assertEqual(reservation_1.state, "partially_available") self.env["stock.quant"].create( { "product_id": self.product.id, "location_id": self.warehouse.lot_stock_id.id, "quantity": 10.0, } ) cron = self.env.ref("stock_reserve.ir_cron_reserve_waiting_confirmed") cron.method_direct_trigger() self.assertEqual(reservation_1.state, "assigned") self.assertEqual(self.product.virtual_available, 9)
41.732394
2,963
7,403
py
PYTHON
15.0
# Copyright 2013 Camptocamp SA - Guewen Baconnier # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models from odoo.exceptions import except_orm from odoo.tools import float_compare from odoo.tools.translate import _ class StockReservation(models.Model): """Allow to reserve products. The fields mandatory for the creation of a reservation are: * product_id * product_uom_qty * product_uom * name The following fields are required but have default values that you may want to override: * company_id * location_id * location_dest_id Optionally, you may be interested to define: * date_validity (once passed, the reservation will be released) * note """ _name = "stock.reservation" _description = "Stock Reservation" _inherits = {"stock.move": "move_id"} note = fields.Text(string="Notes") move_id = fields.Many2one( "stock.move", "Reservation Move", required=True, readonly=True, ondelete="cascade", index=True, ) date_validity = fields.Date("Validity Date") @api.model def default_get(self, fields_list): """Fix default values - Ensure default value of computed field `product_qty` is not set as it would raise an error - Compute default `location_id` based on default `picking_type_id`. Note: `default_picking_type_id` may be present in context, so code that looks for default `location_id` is implemented here, because it relies on already calculated default `picking_type_id`. """ # if there is 'location_id' field requested, ensure that # picking_type_id is also requested, because it is required # to compute location_id if "location_id" in fields_list and "picking_type_id" not in fields_list: fields_list = fields_list + ["picking_type_id"] res = super().default_get(fields_list) if "product_qty" in res: del res["product_qty"] # At this point picking_type_id and location_id # should be computed in default way: # 1. look up context # 2. look up ir_values # 3. look up property fields # 4. look up field.default # 5. delegate to parent model # # If picking_type_id is present and location_id is not, try to find # default value for location_id if not res.get("picking_type_id", None): res["picking_type_id"] = self._default_picking_type_id() picking_type_id = res.get("picking_type_id") if picking_type_id and not res.get("location_id", False): picking = self.env["stock.picking"].new( {"picking_type_id": picking_type_id} ) picking._onchange_picking_type() res["location_id"] = picking.location_id.id if "location_dest_id" in fields_list: res["location_dest_id"] = self._default_location_dest_id() if "product_uom_qty" in fields_list: res["product_uom_qty"] = 1.0 return res @api.model def get_location_from_ref(self, ref): """Get a location from a xmlid if allowed :param ref: tuple (module, xmlid) """ try: location = self.env.ref(ref, raise_if_not_found=True) location.check_access_rule("read") location_id = location.id except (except_orm, ValueError): location_id = False return location_id @api.model def _default_picking_type_id(self): ref = "stock.picking_type_out" return self.env.ref(ref, raise_if_not_found=False).id @api.model def _default_location_dest_id(self): ref = "stock_reserve.stock_location_reservation" return self.get_location_from_ref(ref) def reserve(self): """Confirm reservations The reservation is done using the default UOM of the product. A date until which the product is reserved can be specified. """ self.write({"date": fields.Datetime.now()}) # Don't call _action_confirm() method to prevent assign picking self.mapped("move_id").write({"state": "confirmed"}) self.mapped("move_id")._action_assign() return True def release_reserve(self): """ Release moves from reservation """ moves = self.mapped("move_id") moves._action_cancel() return True def _get_state_domain_release_reserve(self, mode): if mode == "reserve": return elif mode == "release": return "cancel" @api.model def release_validity_exceeded(self, ids=None): """Release all the reservation having an exceeded validity date""" domain = [ ("date_validity", "<", fields.date.today()), ("state", "!=", "cancel"), ] if ids: domain.append(("id", "in", ids)) self.env["stock.reservation"].search(domain).release_reserve() return True def unlink(self): """Release the reservation before the unlink""" self.release_reserve() return super().unlink() @api.onchange("product_id") def _onchange_product_id(self): """set product_uom and name from product onchange""" # save value before reading of self.move_id as this last one erase # product_id value self.move_id.product_id = self.product_id self.move_id._onchange_product_id() self.name = self.move_id.name self.product_uom = self.move_id.product_uom @api.onchange("product_uom_qty") def _onchange_quantity(self): """On change of product quantity avoid negative quantities""" if not self.product_id or self.product_uom_qty <= 0.0: self.product_uom_qty = 0.0 def open_move(self): self.ensure_one() action_dict = self.env["ir.actions.act_window"]._for_xml_id( "stock.stock_move_action" ) action_dict["name"] = _("Reservation Move") # open directly in the form view view_id = self.env.ref("stock.view_move_form").id action_dict.update( views=[(view_id, "form")], res_id=self.move_id.id, ) return action_dict def write(self, vals): res = super().write(vals) rounding = self.product_uom.rounding if ( "product_uom_qty" in vals and self.state in ["confirmed", "waiting", "partially_available"] and float_compare( self.product_id.virtual_available, 0, precision_rounding=rounding ) >= 0 ): self.reserve() return res def _get_reservations_to_assign_domain(self): return [ ("state", "in", ["confirmed", "waiting", "partially_available"]), "|", ("date_validity", ">=", fields.date.today()), ("date_validity", "=", False), ] @api.model def assign_waiting_confirmed_reserve_moves(self): reservations_to_assign = self.search(self._get_reservations_to_assign_domain()) for reservation in reservations_to_assign: reservation.reserve() return True
33.803653
7,403
2,090
py
PYTHON
15.0
# Copyright 2013 Camptocamp SA - Guewen Baconnier # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class ProductTemplate(models.Model): _inherit = "product.template" reservation_count = fields.Float( compute="_compute_reservation_count", string="# Sales" ) def _compute_reservation_count(self): for product in self: product.reservation_count = sum( product.product_variant_ids.mapped("reservation_count") ) def action_view_reservations(self): self.ensure_one() action_dict = self.env["ir.actions.act_window"]._for_xml_id( "stock_reserve.action_stock_reservation_tree" ) product_ids = self.mapped("product_variant_ids.id") action_dict["domain"] = [("product_id", "in", product_ids)] action_dict["context"] = { "search_default_draft": 1, "search_default_reserved": 1, "default_product_id": self.product_variant_ids[0].id, } return action_dict class ProductProduct(models.Model): _inherit = "product.product" reservation_count = fields.Float( compute="_compute_reservation_count", string="# Sales" ) def _compute_reservation_count(self): for product in self: domain = [ ("product_id", "=", product.id), ("state", "in", ["draft", "assigned"]), ] reservations = self.env["stock.reservation"].search(domain) product.reservation_count = sum(reservations.mapped("product_qty")) def action_view_reservations(self): self.ensure_one() action_dict = self.env["ir.actions.act_window"]._for_xml_id( "stock_reserve.action_stock_reservation_tree" ) action_dict["domain"] = [("product_id", "=", self.id)] action_dict["context"] = { "search_default_draft": 1, "search_default_reserved": 1, "default_product_id": self.id, } return action_dict
34.262295
2,090
612
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com) { "name": "Stock Picking Show Linked", "summary": """ This addon allows to easily access related pickings (in the case of chained routes) through a button in the parent picking view. """, "version": "15.0.1.0.0", "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-warehouse", "category": "Warehouse Management", "depends": [ "stock", ], "data": ["views/stock_picking.xml"], "license": "AGPL-3", "installable": True, }
32.210526
612
1,863
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com) from odoo import api, fields, models class StockPicking(models.Model): _inherit = "stock.picking" dest_picking_count = fields.Integer(compute="_compute_picking_count") origin_picking_count = fields.Integer(compute="_compute_picking_count") @api.depends("move_lines") def _compute_picking_count(self): for record in self: origin_pickings = record.mapped("move_lines.move_orig_ids.picking_id") dest_pickings = record.mapped("move_lines.move_dest_ids.picking_id") record.origin_picking_count = len(origin_pickings) record.dest_picking_count = len(dest_pickings) def _get_action_link(self, pickings): result = self.env["ir.actions.actions"]._for_xml_id( "stock.action_picking_tree_all" ) # choose the view_mode accordingly if not pickings or len(pickings) > 1: result["domain"] = "[('id','in',%s)]" % pickings elif len(pickings) == 1: res = self.env.ref("stock.view_picking_form", False) form_view = [(res and res.id or False, "form")] if "views" in result: result["views"] = form_view + [ (state, view) for state, view in result["views"] if view != "form" ] else: result["views"] = form_view result["res_id"] = pickings[0] return result def action_stock_picking_origin(self): pick_ids = self.mapped("move_lines.move_orig_ids.picking_id") result = self._get_action_link(pick_ids.ids) return result def action_stock_picking_destination(self): pick_ids = self.mapped("move_lines.move_dest_ids.picking_id") result = self._get_action_link(pick_ids.ids) return result
39.638298
1,863
1,837
py
PYTHON
15.0
# License AGPL-3.0 or later (https://www.gnuorg/licenses/agpl.html). import os from odoo import SUPERUSER_ID, api def post_init_hook(cr, registry): """ Loaded after installing this module, and before the next module starts installing. Add XSD Validation Schema for a demo report if it's in the system. Demo data records are always created with `noupdate == True` and render of tag `report` doesn't support new `ir.actions.report` field `xsd_schema`. Thus it is impossible to define `xsd_schema` in the demo definition or add schema after that via xml update record. Therefore it possible to add value to `xsd_schema` field for demo record only via hook. Args: * cr(odoo.sql_db.Cursor) - database cursor. * registry(odoo.modules.registry.RegistryManager) - a mapping between model names and model classes. """ env = api.Environment(cr, SUPERUSER_ID, {}) report_domain = [ ("report_name", "=", "report_xml.demo_report_xml_view") # report tech name ] demo_report = env["ir.actions.report"].search(report_domain, limit=1) if demo_report: dir_path = os.path.dirname(__file__) xsd_file_relative_path = "demo/demo_report.xsd" xsd_file_full_path = os.path.join(dir_path, xsd_file_relative_path) with open(xsd_file_full_path, "r") as xsd: # `xsd_schema` is binary fields with an attribute # `attachment=True` so XSD Schema will be added as attachment attach_vals = { "name": "Demo Report.xsd", "datas": xsd.read(), "res_model": "ir.actions.report", "res_id": demo_report.id, "res_field": "xsd_schema", "type": "binary", } env["ir.attachment"].create(attach_vals)
39.934783
1,837
1,097
py
PYTHON
15.0
# Copyright (C) 2014-2015 Grupo ESOC <www.grupoesoc.es> # License AGPL-3.0 or later (https://www.gnuorg/licenses/agpl.html). { "name": "XML Reports", "version": "15.0.1.0.1", "category": "Reporting", "website": "https://github.com/OCA/reporting-engine", "development_status": "Production/Stable", "author": "Tecnativa, Odoo Community Association (OCA), Avoin.Systems", "license": "AGPL-3", "installable": True, "application": False, "summary": "Allow to generate XML reports", "depends": ["web"], "data": [ "views/ir_actions_report_view.xml", ], "assets": { "web.assets_backend": [ "report_xml/static/src/js/report/action_manager_report.esm.js", ], }, "demo": [ "demo/report.xml", # register report in the system "demo/demo_report.xml", # report body definition ], "external_dependencies": { "python": [ # Python third party libraries required for module "lxml" # XML and HTML with Python ] }, "post_init_hook": "post_init_hook", }
33.242424
1,097
732
py
PYTHON
15.0
# Copyright 2017 Creu Blanca # License AGPL-3.0 or later (https://www.gnuorg/licenses/agpl). from lxml import etree from odoo.tests import common class TestXmlReport(common.TransactionCase): def test_xml(self): report_object = self.env["ir.actions.report"] report_name = "report_xml.demo_report_xml_view" report = report_object._get_report_from_name(report_name) docs = self.env["res.company"].search([], limit=1) self.assertEqual(report.report_type, "qweb-xml") result_report = report._render(docs.ids, {}) result_tree = etree.fromstring(result_report[0]) el = result_tree.xpath("/root/user/name") self.assertEqual(el[0].text, docs.ensure_one().name)
38.526316
732
2,118
py
PYTHON
15.0
# Copyright (C) 2014-2015 Grupo ESOC <www.grupoesoc.es> # License AGPL-3.0 or later (https://www.gnuorg/licenses/agpl.html). from odoo import fields, models class IrActionsReport(models.Model): _inherit = "ir.actions.report" report_type = fields.Selection( selection_add=[("qweb-xml", "XML")], ondelete={"qweb-xml": "set default"} ) xsd_schema = fields.Binary( string="XSD Validation Schema", attachment=True, help=( "File with XSD Schema for checking content of result report. " "Can be empty if validation is not required." ), ) xml_encoding = fields.Selection( selection=[ ("UTF-8", "UTF-8") # will be used as default even if nothing is selected ], string="XML Encoding", help=( "Encoding for XML reports. If nothing is selected, " "then UTF-8 will be applied." ), ) xml_declaration = fields.Boolean( string="XML Declaration", help=( """Add `<?xml encoding="..." version="..."?>` at the start """ """of final report file.""" ), ) def _render_qweb_xml(self, docids, data=None): """ Call `generate_report` method of report abstract class `report.<report technical name>` or of standard class for XML report rendering - `report.report_xml.abstract` Args: * docids(list) - IDs of instances for those report will be generated * data(dict, None) - variables for report rendering Returns: * str - result content of report * str - type of result content """ report_model_name = "report.{}".format(self.report_name) report_model = self.env.get(report_model_name) if report_model is None: report_model = self.env["report.report_xml.abstract"] content, ttype = report_model.generate_report( ir_report=self, # will be used to get settings of report docids=docids, data=data, ) return content, ttype
33.09375
2,118
4,182
py
PYTHON
15.0
# Copyright (C) 2014-2015 Grupo ESOC <www.grupoesoc.es> # License AGPL-3.0 or later (https://www.gnuorg/licenses/agpl.html). import json from werkzeug.urls import url_decode from odoo.http import content_disposition, request, route, serialize_exception from odoo.tools import html_escape from odoo.tools.safe_eval import safe_eval, time from odoo.addons.web.controllers import main as report class ReportController(report.ReportController): @route() def report_routes(self, reportname, docids=None, converter=None, **data): if converter == "xml": report = request.env["ir.actions.report"]._get_report_from_name(reportname) context = dict(request.env.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"]) xml = report.with_context(**context)._render_qweb_xml(docids, data=data)[0] xmlhttpheaders = [ ("Content-Type", "text/xml"), ("Content-Length", len(xml)), ] return request.make_response(xml, headers=xmlhttpheaders) else: return super().report_routes(reportname, docids, converter, **data) @route() def report_download(self, data, context=None): requestcontent = json.loads(data) url, report_type = requestcontent[0], requestcontent[1] if report_type == "qweb-xml": try: reportname = url.split("/report/xml/")[1].split("?")[0] docids = None if "/" in reportname: reportname, docids = reportname.split("/") if docids: # Generic report: response = self.report_routes( reportname, docids=docids, converter="xml", context=context, ) else: # Particular report: # decoding the args represented in JSON data = dict(url_decode(url.split("?")[1]).items()) if "context" in data: context = json.loads(context or "{}") data_context = json.loads(data.pop("context")) context = json.dumps({**context, **data_context}) response = self.report_routes( reportname, converter="xml", context=context, **data ) report_obj = request.env["ir.actions.report"] report = report_obj._get_report_from_name(reportname) filename = "%s.xml" % (report.name) if docids: ids = [int(doc_id) for doc_id in docids.split(",")] records = request.env[report.model].browse(ids) if report.print_report_name and not len(records) > 1: report_name = safe_eval( report.print_report_name, {"object": records, "time": time} ) filename = "{}.xml".format(report_name) response.headers.add( "Content-Disposition", content_disposition(filename) ) return response except Exception as e: se = serialize_exception(e) error = {"code": 200, "message": "Odoo Server Error", "data": se} return request.make_response(html_escape(json.dumps(error))) else: return super().report_download(data, context)
43.113402
4,182
3,995
py
PYTHON
15.0
# License AGPL-3.0 or later (https://www.gnuorg/licenses/agpl.html). from base64 import b64decode from xml.dom import minidom from lxml import etree from odoo import api, models from odoo.exceptions import ValidationError class ReportXmlAbstract(models.AbstractModel): """ Model `report.report_xml.abstract`. This class provide basic methods for rendering XML report and it's validation by XSD schema. """ _name = "report.report_xml.abstract" _description = "Abstract XML Report" @api.model def generate_report(self, ir_report, docids, data=None): """ Generate and validate XML report. Use incoming `ir_report` settings to setup encoding and XMl declaration for result `xml`. Methods: * `_get_rendering_context` `ir.actions.report` - get report variables. It will call `_get_report_values` of report's class if it's exist. * `render_template` of `ir.actions.report` - get report content * `validate_report` - check result content Args: * ir_report(`ir.actions.report`) - report definition instance in Odoo * docids(list) - IDs of instances for those report will be generated * data(dict, None) - variables for report rendering Returns: * str - result content of report * str - `"xml"` Extra Info: * Default encoding is `UTF-8` """ # collect variable for rendering environment if not data: data = {} data.setdefault("report_type", "text") data = ir_report._get_rendering_context(docids, data) # render template result_bin = ir_report._render_template(ir_report.report_name, data) # prettify result content # normalize indents parsed_result_bin = minidom.parseString(result_bin) result = parsed_result_bin.toprettyxml(indent=" " * 4) # remove empty lines utf8 = "UTF-8" result = "\n".join( line for line in result.splitlines() if line and not line.isspace() ).encode(utf8) content = etree.tostring( etree.fromstring(result), encoding=ir_report.xml_encoding or utf8, xml_declaration=ir_report.xml_declaration, pretty_print=True, ) # validate content xsd_schema_doc = ir_report.xsd_schema self.validate_report(xsd_schema_doc, content) return content, "xml" @api.model def validate_report(self, xsd_schema_doc, content): """ Validate final report content against value of `xsd_schema` field ("XSD Validation Schema") of `ir.actions.report` via `etree` lib. Args: * xsd_schema_doc(byte-string) - report validation schema * content(str) - report content for validation Raises: * odoo.exceptions.ValidationError - Syntax of final report is wrong Returns: * bool - True """ if xsd_schema_doc: # create validation parser decoded_xsd_schema_doc = b64decode(xsd_schema_doc) parsed_xsd_schema = etree.XML(decoded_xsd_schema_doc) xsd_schema = etree.XMLSchema(parsed_xsd_schema) parser = etree.XMLParser(schema=xsd_schema) try: # check content etree.fromstring(content, parser) except etree.XMLSyntaxError as error: raise ValidationError(error.msg) from error return True @api.model def _get_report_values(self, docids, data=None): """ Allow to generate extra variables for report environment. Args: * docids(list) - IDs of instances for those report will be generated * data(dict, None) - variables for report rendering Returns: * dict - extra variables for report render """ if not data: data = {} return data
32.479675
3,995
712
py
PYTHON
15.0
# Copyright (C) 2017 - Today: GRAP (http://www.grap.coop) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "SQL Request Abstract", "version": "15.0.1.0.0", "author": "GRAP,Akretion,Odoo Community Association (OCA)", "maintainers": ["legalsylvain"], "website": "https://github.com/OCA/reporting-engine", "license": "AGPL-3", "category": "Tools", "summary": "Abstract Model to manage SQL Requests", "depends": ["base"], "data": [ "security/ir_module_category.xml", "security/res_groups.xml", "security/ir.model.access.csv", ], "installable": True, }
33.904762
712
9,841
py
PYTHON
15.0
# Copyright (C) 2015 Akretion (<http://www.akretion.com>) # Copyright (C) 2017 - Today: GRAP (http://www.grap.coop) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import base64 import logging import re import uuid from io import BytesIO from psycopg2 import ProgrammingError from psycopg2.sql import SQL from odoo import _, api, fields, models from odoo.exceptions import UserError logger = logging.getLogger(__name__) class SQLRequestMixin(models.AbstractModel): _name = "sql.request.mixin" _description = "SQL Request Mixin" _clean_query_enabled = True _check_prohibited_words_enabled = True _check_execution_enabled = True _sql_request_groups_relation = False _sql_request_users_relation = False STATE_SELECTION = [("draft", "Draft"), ("sql_valid", "SQL Valid")] PROHIBITED_WORDS = [ "delete", "drop", "insert", "alter", "truncate", "execute", "create", "update", "ir_config_parameter", ] # Default Section @api.model def _default_group_ids(self): ir_model_obj = self.env["ir.model.data"] return [ ir_model_obj._xmlid_to_res_id("sql_request_abstract.group_sql_request_user") ] @api.model def _default_user_ids(self): return [] # Columns Section name = fields.Char(required=True) query = fields.Text( required=True, help="You can't use the following words" ": DELETE, DROP, CREATE, INSERT, ALTER, TRUNCATE, EXECUTE, UPDATE.", ) state = fields.Selection( selection=STATE_SELECTION, default="draft", help="State of the Request:\n" " * 'Draft': Not tested\n" " * 'SQL Valid': SQL Request has been checked and is valid", ) group_ids = fields.Many2many( comodel_name="res.groups", string="Allowed Groups", relation=_sql_request_groups_relation, column1="sql_id", column2="group_id", default=_default_group_ids, ) user_ids = fields.Many2many( comodel_name="res.users", string="Allowed Users", relation=_sql_request_users_relation, column1="sql_id", column2="user_id", default=_default_user_ids, ) # Action Section def button_validate_sql_expression(self): for item in self: if item._clean_query_enabled: item._clean_query() if item._check_prohibited_words_enabled: item._check_prohibited_words() if item._check_execution_enabled: item._check_execution() item.state = "sql_valid" def button_set_draft(self): self.write({"state": "draft"}) # API Section def _execute_sql_request( self, params=None, mode="fetchall", rollback=True, view_name=False, copy_options="CSV HEADER DELIMITER ';'", header=False, ): """Execute a SQL request on the current database. ??? This function checks before if the user has the right to execute the request. :param params: (dict) of keys / values that will be replaced in the sql query, before executing it. :param mode: (str) result type expected. Available settings : * 'view': create a view with the select query. Extra param required 'view_name'. * 'materialized_view': create a MATERIALIZED VIEW with the select query. Extra parameter required 'view_name'. * 'fetchall': execute the select request, and return the result of 'cr.fetchall()'. * 'fetchone' : execute the select request, and return the result of 'cr.fetchone()' :param rollback: (boolean) mention if a rollback should be played after the execution of the query. Please keep this feature enabled for security reason, except if necessary. (Ignored if @mode in ('view', 'materialized_view')) :param view_name: (str) name of the view. (Ignored if @mode not in ('view', 'materialized_view')) :param copy_options: (str) mentions extra options for "COPY request STDOUT WITH xxx" request. (Ignored if @mode != 'stdout') :param header: (boolean) if true, the header of the query will be returned as first element of the list if the mode is fetchall. (Ignored if @mode != fetchall) ..note:: The following exceptions could be raised: psycopg2.ProgrammingError: Error in the SQL Request. odoo.exceptions.UserError: * 'mode' is not implemented. * materialized view is not supported by the Postgresql Server. """ self.ensure_one() res = False # Check if the request is in a valid state if self.state == "draft": raise UserError(_("It is not allowed to execute a not checked request.")) # Disable rollback if a creation of a view is asked if mode in ("view", "materialized_view"): rollback = False query = self.env.cr.mogrify(self.query, params).decode("utf-8") if mode in ("fetchone", "fetchall"): pass elif mode == "stdout": query = SQL("COPY ({0}) TO STDOUT WITH {1}").format( SQL(query), SQL(copy_options) ) elif mode in "view": query = SQL("CREATE VIEW {0} AS ({1});").format(SQL(query), SQL(view_name)) elif mode in "materialized_view": self._check_materialized_view_available() query = SQL("CREATE MATERIALIZED VIEW {0} AS ({1});").format( SQL(query), SQL(view_name) ) else: raise UserError(_("Unimplemented mode : '%s'") % mode) if rollback: rollback_name = self._create_savepoint() try: if mode == "stdout": output = BytesIO() self.env.cr.copy_expert(query, output) res = base64.b64encode(output.getvalue()) output.close() else: self.env.cr.execute(query) if mode == "fetchall": res = self.env.cr.fetchall() if header: colnames = [desc[0] for desc in self.env.cr.description] res.insert(0, colnames) elif mode == "fetchone": res = self.env.cr.fetchone() finally: self._rollback_savepoint(rollback_name) return res # Private Section @api.model def _create_savepoint(self): rollback_name = "{}_{}".format(self._name.replace(".", "_"), uuid.uuid1().hex) # pylint: disable=sql-injection req = "SAVEPOINT %s" % (rollback_name) self.env.cr.execute(req) return rollback_name @api.model def _rollback_savepoint(self, rollback_name): # pylint: disable=sql-injection req = "ROLLBACK TO SAVEPOINT %s" % (rollback_name) self.env.cr.execute(req) @api.model def _check_materialized_view_available(self): self.env.cr.execute("SHOW server_version;") res = self.env.cr.fetchone()[0].split(".") minor_version = float(".".join(res[:2])) if minor_version < 9.3: raise UserError( _( "Materialized View requires PostgreSQL 9.3 or greater but" " PostgreSQL %s is currently installed." ) % (minor_version) ) def _clean_query(self): self.ensure_one() query = self.query.strip() while query[-1] == ";": query = query[:-1] self.query = query def _check_prohibited_words(self): """Check if the query contains prohibited words, to avoid maliscious SQL requests""" self.ensure_one() query = self.query.lower() for word in self.PROHIBITED_WORDS: expr = r"\b%s\b" % word is_not_safe = re.search(expr, query) if is_not_safe: raise UserError( _( "The query is not allowed because it contains unsafe word" " '%s'" ) % (word) ) def _check_execution(self): """Ensure that the query is valid, trying to execute it. A rollback is done after.""" self.ensure_one() query = self._prepare_request_check_execution() rollback_name = self._create_savepoint() res = False try: self.env.cr.execute(query) res = self._hook_executed_request() except ProgrammingError as e: logger.exception("Failed query: %s", query) raise UserError(_("The SQL query is not valid:\n\n %s") % e) from e finally: self._rollback_savepoint(rollback_name) return res def _prepare_request_check_execution(self): """Overload me to replace some part of the query, if it contains parameters""" self.ensure_one() return self.query def _hook_executed_request(self): """Overload me to insert custom code, when the SQL request has been executed, before the rollback. """ self.ensure_one() return False def button_preview_sql_expression(self): self.button_validate_sql_expression() res = self._execute_sql_request() raise UserError("\n".join(map(lambda x: str(x), res[:100])))
33.817869
9,841
767
py
PYTHON
15.0
# © 2013-2014 Nicolas Bessi (Camptocamp SA) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Base Comments Templates", "summary": "Add conditional mako template to any report" "on models that inherits comment.template.", "version": "15.0.3.0.0", "category": "Reporting", "website": "https://github.com/OCA/reporting-engine", "author": "Camptocamp, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": ["base", "mail"], "data": [ "security/ir.model.access.csv", "security/security.xml", "wizard/base_comment_template_preview_views.xml", "views/base_comment_template_view.xml", "views/res_partner_view.xml", ], }
34.818182
766
722
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openupgradelib import openupgrade @openupgrade.migrate() def migrate(env, version): openupgrade.logged_query( env.cr, "ALTER TABLE base_comment_template ADD COLUMN IF NOT EXISTS models text" ) openupgrade.logged_query( env.cr, """ UPDATE base_comment_template template SET models = ( SELECT string_agg(model.model, ',') FROM base_comment_template_ir_model_rel AS rel JOIN ir_model AS model ON rel.ir_model_id = model.id WHERE rel.base_comment_template_id = template.id ) """, )
31.304348
720
525
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import re from openupgradelib import openupgrade @openupgrade.migrate() def migrate(env, version): """In v15 mail engine is inline_template, we try to replace the following: - ${object} > {{object}} - ${user} > {{user}} - ${ctx} > {{ctx}} """ for item in env["base.comment.template"].search([("text", "ilike", "${")]): item.text = re.sub(r"\${(.+)}", r"{{\1}}", item.text)
30.764706
523
1,000
py
PYTHON
15.0
# Copyright 2017 LasLabs Inc. # Copyright 2018 ACSONE # Copyright 2018 Camptocamp # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). from odoo import models def setup_test_model(env, model_cls): """Pass a test model class and initialize it. Courtesy of SBidoul from https://github.com/OCA/mis-builder :) """ model_cls._build_model(env.registry, env.cr) env.registry.setup_models(env.cr) env.registry.init_models( env.cr, [model_cls._name], dict(env.context, update_custom_fields=True) ) def teardown_test_model(env, model_cls): """Pass a test model class and deinitialize it. Courtesy of SBidoul from https://github.com/OCA/mis-builder :) """ if not getattr(model_cls, "_teardown_no_delete", False): del env.registry.models[model_cls._name] env.registry.setup_models(env.cr) class ResUsers(models.Model): _name = "res.users" _inherit = ["res.users", "comment.template"] _teardown_no_delete = True
29.411765
1,000
6,964
py
PYTHON
15.0
# Copyright 2020 NextERP Romania SRL # Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.exceptions import ValidationError from odoo.tests import common from odoo.tools.misc import mute_logger from .fake_models import ResUsers, setup_test_model, teardown_test_model class TestCommentTemplate(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() setup_test_model(cls.env, ResUsers) cls.user_obj = cls.env.ref("base.model_res_users") cls.user = cls.env.ref("base.user_demo") cls.user2 = cls.env.ref("base.demo_user0") cls.partner_id = cls.env.ref("base.res_partner_12") cls.partner2_id = cls.env.ref("base.res_partner_10") cls.ResPartnerTitle = cls.env["res.partner.title"] cls.main_company = cls.env.ref("base.main_company") cls.company = cls.env["res.company"].create({"name": "Test company"}) cls.before_template_id = cls.env["base.comment.template"].create( { "name": "Top template", "text": "Text before lines", "models": cls.user_obj.model, "company_id": cls.company.id, } ) cls.after_template_id = cls.env["base.comment.template"].create( { "name": "Bottom template", "position": "after_lines", "text": "Text after lines", "models": cls.user_obj.model, "company_id": cls.company.id, } ) cls.user.partner_id.base_comment_template_ids = [ (4, cls.before_template_id.id), (4, cls.after_template_id.id), ] @classmethod def tearDownClass(cls): teardown_test_model(cls.env, ResUsers) return super(TestCommentTemplate, cls).tearDownClass() def test_template_model_ids(self): self.assertIn( self.user_obj.model, self.before_template_id.mapped("model_ids.model") ) self.assertEqual(len(self.before_template_id.model_ids), 1) self.assertIn( self.user_obj.model, self.after_template_id.mapped("model_ids.model") ) self.assertEqual(len(self.after_template_id.model_ids), 1) def test_template_models_constrains(self): with self.assertRaises(ValidationError): self.env["base.comment.template"].create( { "name": "Custom template", "text": "Text", "models": "incorrect.model", "company_id": self.company.id, } ) def test_template_name_get(self): self.assertEqual( self.before_template_id.display_name, "Top template (Top)", ) self.assertEqual( self.after_template_id.display_name, "Bottom template (Bottom)", ) def test_general_template(self): # Need to force _compute because only trigger when partner_id have changed self.user._compute_comment_template_ids() # Check getting default comment template self.assertTrue(self.before_template_id in self.user.comment_template_ids) self.assertTrue(self.after_template_id in self.user.comment_template_ids) def test_partner_template(self): self.partner2_id.base_comment_template_ids = [ (4, self.before_template_id.id), (4, self.after_template_id.id), ] self.assertTrue( self.before_template_id in self.partner2_id.base_comment_template_ids ) self.assertTrue( self.after_template_id in self.partner2_id.base_comment_template_ids ) def test_partner_template_domain(self): # Check getting the comment template if domain is set self.partner2_id.base_comment_template_ids = [ (4, self.before_template_id.id), (4, self.after_template_id.id), ] self.before_template_id.domain = "[('id', 'in', %s)]" % self.user.ids self.assertTrue( self.before_template_id in self.partner2_id.base_comment_template_ids ) self.assertTrue( self.before_template_id not in self.partner_id.base_comment_template_ids ) def test_render_comment_text(self): expected_text = "Test comment render %s" % self.user.name self.before_template_id.text = "Test comment render {{object.name}}" with self.with_user(self.user.login): self.assertEqual( self.user.render_comment(self.before_template_id), expected_text ) def test_render_comment_text_(self): with mute_logger("odoo.addons.base.models.ir_translation"): self.env["base.language.install"].create( {"lang": "ro_RO", "overwrite": True} ).lang_install() with mute_logger("odoo.tools.translate"): self.env["base.update.translations"].create({"lang": "ro_RO"}).act_update() partner_title = self.ResPartnerTitle.create( {"name": "Ambassador", "shortcut": "Amb."} ) # Adding translated terms ctx = dict(lang="ro_RO") partner_title.with_context(**ctx).write( {"name": "Ambasador", "shortcut": "Amb."} ) self.user.partner_id.title = partner_title self.before_template_id.text = "Test comment render {{object.title.name}}" expected_en_text = "Test comment render Ambassador" expected_ro_text = "Test comment render Ambasador" with self.with_user(self.user.login): self.assertEqual( self.user.render_comment(self.before_template_id), expected_en_text ) self.assertEqual( self.user.with_context(**ctx).render_comment(self.before_template_id), expected_ro_text, ) def test_partner_template_wizaard(self): partner_preview = ( self.env["base.comment.template.preview"] .with_context(default_base_comment_template_id=self.before_template_id.id) .create({}) ) self.assertTrue(partner_preview) default = ( self.env["base.comment.template.preview"] .with_context(default_base_comment_template_id=self.before_template_id.id) .default_get(partner_preview._fields) ) self.assertTrue(default.get("base_comment_template_id")) resource_ref = partner_preview._selection_target_model() self.assertTrue(len(resource_ref) >= 2) partner_preview._compute_no_record() self.assertTrue(partner_preview.no_record) def test_partner_commercial_fields(self): self.assertTrue( "base_comment_template_ids" in self.env["res.partner"]._commercial_fields() )
40.242775
6,962
3,128
py
PYTHON
15.0
from odoo import api, fields, models from odoo.tools.safe_eval import safe_eval from odoo.addons.base.models.res_partner import _lang_get class BaseCommentTemplatePreview(models.TransientModel): _name = "base.comment.template.preview" _description = "Base Comment Template Preview" @api.model def _selection_target_model(self): models = self.env["ir.model"].search([("is_comment_template", "=", True)]) return [(model.model, model.name) for model in models] @api.model def default_get(self, fields): result = super().default_get(fields) base_comment_template_id = self.env.context.get( "default_base_comment_template_id" ) if not base_comment_template_id or "resource_ref" not in fields: return result base_comment_template = self.env["base.comment.template"].browse( base_comment_template_id ) result["model_ids"] = base_comment_template.model_ids domain = safe_eval(base_comment_template.domain) model = ( base_comment_template.model_ids[0] if base_comment_template.model_ids else False ) res = self.env[model.model].search(domain, limit=1) if res: result["resource_ref"] = "%s,%s" % (model.model, res.id) return result base_comment_template_id = fields.Many2one( "base.comment.template", required=True, ondelete="cascade" ) lang = fields.Selection(_lang_get, string="Template Preview Language") engine = fields.Selection( [ ("inline_template", "Inline template"), ("qweb", "QWeb"), ("qweb_view", "QWeb view"), ], string="Template Preview Engine", default="inline_template", ) model_ids = fields.Many2many( "ir.model", related="base_comment_template_id.model_ids" ) model_id = fields.Many2one("ir.model") body = fields.Char(compute="_compute_base_comment_template_fields") resource_ref = fields.Reference( string="Record reference", selection="_selection_target_model" ) no_record = fields.Boolean(compute="_compute_no_record") @api.depends("model_id") def _compute_no_record(self): for preview in self: domain = safe_eval(self.base_comment_template_id.domain) preview.no_record = ( (self.env[preview.model_id.model].search_count(domain) == 0) if preview.model_id else True ) @api.depends("lang", "resource_ref", "engine") def _compute_base_comment_template_fields(self): for wizard in self: if ( wizard.model_id and wizard.resource_ref and wizard.lang and wizard.engine ): wizard.body = wizard.resource_ref.with_context( lang=wizard.lang ).render_comment(self.base_comment_template_id, engine=wizard.engine) else: wizard.body = wizard.base_comment_template_id.text
36.8
3,128
1,077
py
PYTHON
15.0
# Copyright 2020 NextERP Romania SRL # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class IrModel(models.Model): _inherit = "ir.model" is_comment_template = fields.Boolean( string="Comment Template", default=False, help="Whether this model supports in reports to add comment templates.", ) def _reflect_model_params(self, model): vals = super()._reflect_model_params(model) vals["is_comment_template"] = issubclass( type(model), self.pool["comment.template"] ) return vals @api.model def _instanciate(self, model_data): model_class = super()._instanciate(model_data) if ( model_data.get("is_comment_template") and model_class._name != "comment.template" ): parents = model_class._inherit or [] parents = [parents] if isinstance(parents, str) else parents model_class._inherit = parents + ["comment.template"] return model_class
32.636364
1,077
4,497
py
PYTHON
15.0
# Copyright 2014 Guewen Baconnier (Camptocamp SA) # Copyright 2013-2014 Nicolas Bessi (Camptocamp SA) # Copyright 2020 NextERP Romania SRL # Copyright 2021-2022 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class BaseCommentTemplate(models.Model): """Comment templates printed on reports""" _name = "base.comment.template" _inherit = "mail.render.mixin" _description = "Comments Template" _order = "sequence,id" active = fields.Boolean(default=True) position = fields.Selection( string="Position on document", selection=[("before_lines", "Top"), ("after_lines", "Bottom")], required=True, default="before_lines", help="This field allows to select the position of the comment on reports.", ) name = fields.Char( translate=True, required=True, help="Name/description of this comment template", ) text = fields.Html( string="Template", translate=True, required=True, sanitize=False, help="This is the text template that will be inserted into reports.", ) company_id = fields.Many2one( comodel_name="res.company", string="Company", ondelete="cascade", index=True, help="If set, the comment template will be available only for the selected " "company.", ) partner_ids = fields.Many2many( comodel_name="res.partner", relation="base_comment_template_res_partner_rel", column1="base_comment_template_id", column2="res_partner_id", string="Partner", readonly=True, help="If set, the comment template will be available only for the selected " "partner.", ) models = fields.Text(required=True) model_ids = fields.Many2many( comodel_name="ir.model", compute="_compute_model_ids", compute_sudo=True, string="IR Model", help="This comment template will be available on this models. " "You can see here only models allowed to set the coment template.", search="_search_model_ids", ) domain = fields.Char( string="Filter Domain", required=True, default="[]", help="This comment template will be available only for objects " "that satisfy the condition", ) sequence = fields.Integer( required=True, default=10, help="The smaller number = The higher priority" ) def _get_ir_model_items(self, models): return ( self.env["ir.model"] .sudo() .search( [ ("is_comment_template", "=", True), ("model", "!=", "comment.template"), ("model", "in", models), ] ) ) @api.depends("models") def _compute_model_ids(self): im_model = self.env["ir.model"] for item in self: models = im_model.browse() if item.models: models = self._get_ir_model_items(item.models.split(",")) item.model_ids = [(6, 0, models.ids)] @api.constrains("models") def check_models(self): """Avoid non-existing or not allowed models (is_comment_template=True)""" for item in self.filtered("models"): models = item.models.split(",") res = self._get_ir_model_items(item.models.split(",")) if not res or len(res) != len(models): raise ValidationError(_("Some model (%s) not found") % item.models) def name_get(self): """Redefine the name_get method to show the template name with the position.""" res = [] for item in self: name = "{} ({})".format( item.name, dict(self._fields["position"].selection).get(item.position) ) if self.env.context.get("comment_template_model_display"): name += " (%s)" % ", ".join(item.model_ids.mapped("name")) res.append((item.id, name)) return res def _search_model_ids(self, operator, value): # We cannot use model_ids.model in search() method to avoid recursion. allowed_items = ( self.sudo().search([]).filtered(lambda x: x.model_ids.model == value) ) return [("id", "in", allowed_items.ids)]
35.96
4,495
2,518
py
PYTHON
15.0
# Copyright 2014 Guewen Baconnier (Camptocamp SA) # Copyright 2013-2014 Nicolas Bessi (Camptocamp SA) # Copyright 2020 NextERP Romania SRL # Copyright 2021-2022 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models from odoo.osv import expression from odoo.tools.safe_eval import safe_eval class CommentTemplate(models.AbstractModel): _name = "comment.template" _description = ( "base.comment.template to put header and footer " "in reports based on created comment templates" ) # This field allows to set any given field that determines the source partner for # the comment templates downstream. # E.g.: other models where the partner field is called customer_id. _comment_template_partner_field_name = "partner_id" comment_template_ids = fields.Many2many( compute="_compute_comment_template_ids", compute_sudo=True, comodel_name="base.comment.template", string="Comment Template", domain=lambda self: [("model_ids", "=", self._name)], store=True, readonly=False, ) @api.depends(_comment_template_partner_field_name) def _compute_comment_template_ids(self): template_model = self.env["base.comment.template"] template_domain = template_model._search_model_ids("=", self._name) for record in self: partner = record[self._comment_template_partner_field_name] record.comment_template_ids = [(5,)] templates = template_model.search( expression.AND( [ [("id", "in", partner.base_comment_template_ids.ids)], template_domain, ] ) ) for template in templates: domain = safe_eval(template.domain) if not domain or record.filtered_domain(domain): record.comment_template_ids = [(4, template.id)] def render_comment( self, comment, engine="inline_template", add_context=None, post_process=False ): self.ensure_one() comment_texts = self.env["mail.render.mixin"]._render_template( template_src=comment.text, model=self._name, res_ids=[self.id], engine=engine, add_context=add_context, post_process=post_process, ) return comment_texts[self.id] or ""
39.3125
2,516
786
py
PYTHON
15.0
# Copyright 2020 NextERP Romania SRL # Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class ResPartner(models.Model): _inherit = "res.partner" base_comment_template_ids = fields.Many2many( comodel_name="base.comment.template", relation="base_comment_template_res_partner_rel", column1="res_partner_id", column2="base_comment_template_id", string="Comment Templates", help="Specific partner comments that can be included in reports", ) @api.model def _commercial_fields(self): """Add comment templates to commercial fields""" return super()._commercial_fields() + ["base_comment_template_ids"]
34.086957
784
401
py
PYTHON
15.0
# Copyright 2019 Creu Blanca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Web QR Manager", "version": "15.0.1.0.0", "author": "Creu Blanca, " "Odoo Community Association (OCA)", "category": "Reporting", "website": "https://github.com/OCA/reporting-engine", "license": "AGPL-3", "depends": ["web"], "data": [], "installable": True, }
28.642857
401
644
py
PYTHON
15.0
# Copyright 2019 Creu Blanca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import HttpCase class TestReportQr(HttpCase): def test_qr_generation(self): data = "TEST" image = self.url_open("/report/qr?value=%s" % data) self.assertEqual(image.headers["Content-type"], "image/png") def test_qr_overflow(self): """There is a QR limitation for 4296 characters, we will test that an Exception is raised""" new_data = "".join(["TEST"] * 1500) with self.assertRaises(ValueError): self.env["ir.actions.report"].qr_generate(new_data)
35.777778
644
1,150
py
PYTHON
15.0
import io import qrcode from qrcode.image import pil, svg from odoo import api, models class IrActionsReport(models.Model): _inherit = "ir.actions.report" @api.model def qr_generate(self, value, box_size=3, border=5, factory="png", **kwargs): factories = { "png": pil.PilImage, "svg": svg.SvgImage, "svg-fragment": svg.SvgFragmentImage, "svg-path": svg.SvgPathImage, } back_color = kwargs.pop("back_color", "white") fill_color = kwargs.pop("fill_color", "black") try: # Defaults to png if the argument is unknown image_factory = factories.get(factory, pil.PilImage) qr = qrcode.QRCode( box_size=box_size, border=border, image_factory=image_factory, **kwargs ) qr.add_data(value) qr.make() img = qr.make_image(fill_color=fill_color, back_color=back_color) arr = io.BytesIO() img.save(arr) return arr.getvalue() except Exception as e: raise ValueError("Cannot convert into barcode.") from e
32.857143
1,150
839
py
PYTHON
15.0
import werkzeug from odoo import http from odoo.http import request class Home(http.Controller): @http.route("/report/qr", type="http", auth="public") def report_qr(self, value, box_size=3, border=3, factory="png", **kwargs): try: barcode = request.env["ir.actions.report"].qr_generate( value, box_size=box_size, border=border, factory=factory, **kwargs ) except (ValueError, AttributeError) as e: raise werkzeug.exceptions.HTTPException( description="Cannot convert into barcode." ) from e if factory != "png": return request.make_response( barcode, headers=[("Content-Type", "image/svg+xml")] ) return request.make_response(barcode, headers=[("Content-Type", "image/png")])
38.136364
839
776
py
PYTHON
15.0
# Copyright 2015-2019 Onestein (<https://www.onestein.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). def uninstall_hook(cr, registry): # delete dirty data that could cause problems # while re-installing the module cr.execute( """ delete from ir_model where model like 'x_bve.%' """ ) cr.execute( """ delete from bve_view where model_name like 'x_bve.%' """ ) cr.execute( """ SELECT 'DROP VIEW ' || table_name FROM information_schema.views WHERE table_schema NOT IN ('pg_catalog', 'information_schema') AND table_name like 'x_bve_%' """ ) results = list(cr.fetchall()) for result in results: cr.execute(result[0])
27.714286
776
1,291
py
PYTHON
15.0
# Copyright 2015-2020 Onestein (<https://www.onestein.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "BI View Editor", "summary": "Graphical BI views builder for Odoo", "images": ["static/description/main_screenshot.png"], "author": "Onestein,Odoo Community Association (OCA)", "license": "AGPL-3", "website": "https://github.com/OCA/reporting-engine", "category": "Productivity", "version": "15.0.1.0.0", "development_status": "Beta", "depends": ["web"], "external_dependencies": { "deb": ["graphviz"], }, "data": [ "security/ir.model.access.csv", "security/rules.xml", "views/bve_view.xml", ], "assets": { "web.assets_backend": [ "bi_view_editor/static/src/css/bve.css", "bi_view_editor/static/src/js/bi_view_editor.js", "bi_view_editor/static/src/js/bi_view_editor.JoinNodeDialog.js", "bi_view_editor/static/src/js/bi_view_editor.ModelList.js", "bi_view_editor/static/src/js/bi_view_editor.FieldList.js", ], "web.assets_qweb": [ "bi_view_editor/static/src/xml/bi_view_editor.xml", ], }, "uninstall_hook": "uninstall_hook", "installable": True, }
34.891892
1,291
15,175
py
PYTHON
15.0
# Copyright 2017-2019 Onestein (<https://www.onestein.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import json import odoo from odoo.exceptions import UserError, ValidationError from odoo.tests.common import TransactionCase from odoo.tools import mute_logger from ..hooks import uninstall_hook class TestBiViewEditor(TransactionCase): def setUp(self): def _get_models(model_name_list): return ( self.env["ir.model"].sudo().search([("model", "=", name)]) for name in model_name_list ) def _get_fields(model_field_list): return ( self.env["ir.model.fields"] .sudo() .search( [("model", "=", model_field[0]), ("name", "=", model_field[1])], limit=1, ) for model_field in model_field_list ) def get_new_field(self): return { "model_id": self.partner_model.id, "name": self.partner_field_name, "id": self.partner_field.id, "model": self.partner_model_name, "type": self.partner_field.ttype, "model_name": self.partner_model.name, "description": self.partner_field.field_description, } super().setUp() self.partner_model_name = "res.partner" self.partner_field_name = "name" self.partner_company_field_name = "company_id" self.company_model_name = "res.company" self.company_field_name = "name" self.bi_view1 = None self.partner_model, self.company_model = _get_models( [self.partner_model_name, self.company_model_name] ) ( self.partner_field, self.partner_company_field, self.company_field, ) = _get_fields( [ (self.partner_model_name, self.partner_field_name), (self.partner_model_name, self.partner_company_field_name), (self.company_model_name, self.company_field_name), ] ) self.data = [ { "model_id": self.partner_model.id, "model_name": self.partner_model.name, "model": self.partner_model_name, "type": self.partner_field.ttype, "id": self.partner_field.id, "description": self.partner_field.field_description, "table_alias": "t0", "row": 0, "column": 1, "list": 1, "measure": 0, }, { "model_id": self.partner_model.id, "table_alias": "t0", "relation": self.company_model_name, "model": self.partner_model_name, "model_name": self.partner_model.name, "type": self.partner_company_field.ttype, "id": self.partner_company_field.id, "join_node": "t1", "description": self.partner_company_field.field_description, "row": 0, "column": 0, "list": 1, "measure": 0, }, { "model_id": self.company_model.id, "model_name": self.company_model.name, "model": self.company_model_name, "type": self.company_field.ttype, "id": self.company_field.id, "description": self.company_field.field_description, "table_alias": "t1", "row": 1, "column": 0, "list": 0, "measure": 0, }, ] self.bi_view1_vals = {"state": "draft", "data": json.dumps(self.data)} self.new_field = get_new_field(self) def test_01_get_fields(self): fields = self.env["ir.model"].get_fields(self.partner_model.id) self.assertIsInstance(fields, list) self.assertGreater(len(fields), 0) def test_02_get_join_nodes(self): field_res_users = ( self.env["ir.model.fields"] .sudo() .search([("name", "=", "login"), ("model", "=", "res.users")], limit=1) ) field_data = [ { "model_id": field_res_users.model_id.id, "name": "login", "column": False, "table_alias": "t0", "measure": False, "id": field_res_users.id, "model": "res.users", "row": False, "type": "char", "model_name": "Users", "description": "Login", } ] new_field = self.new_field nodes = self.env["ir.model"].get_join_nodes(field_data, new_field) self.assertIsInstance(nodes, list) self.assertGreater(len(nodes), 0) def test_03_get_join_nodes(self): new_field = self.new_field nodes = self.env["ir.model"].get_join_nodes([], new_field) self.assertIsInstance(nodes, list) self.assertEqual(len(nodes), 0) def test_04_get_related_models(self): all_models = self.env["ir.model"].get_models() self.assertIsInstance(all_models, list) self.assertGreater(len(all_models), 0) related_models = self.env["ir.model"].get_models( {"t0": self.partner_model.id, "t1": self.company_model.id} ) self.assertIsInstance(related_models, list) self.assertGreater(len(related_models), 0) def test_05_create_copy_view(self): vals = self.bi_view1_vals vals.update({"name": "Test View1"}) # create bi_view1 = self.env["bve.view"].create(vals) self.assertIsNotNone(bi_view1) self.assertEqual(len(bi_view1), 1) self.assertEqual(bi_view1.state, "draft") # copy bi_view2 = bi_view1.copy() self.assertEqual(bi_view2.name, "Test View1 (copy)") def test_06_create_group_bve_object(self): vals = self.bi_view1_vals employees_group = self.env.ref("base.group_user") vals.update({"name": "Test View2", "group_ids": [(6, 0, [employees_group.id])]}) bi_view2 = self.env["bve.view"].create(vals) self.assertEqual(len(bi_view2.user_ids), len(employees_group.users)) def test_07_check_empty_data(self): vals = {"name": "Test View Empty", "state": "draft", "data": ""} bi_view4 = self.env["bve.view"].create(vals) self.assertEqual(len(bi_view4), 1) self.assertTrue(bi_view4.er_diagram_image) # create sql view with self.assertRaises(ValidationError): bi_view4.action_create() def test_08_get_models(self): models = self.env["ir.model"].get_models() self.assertIsInstance(models, list) self.assertGreater(len(models), 0) @odoo.tests.tagged("post_install", "-at_install") def test_09_create_open_bve_object(self): vals = self.bi_view1_vals employees_group = self.env.ref("base.group_user") vals.update({"name": "Test View4", "group_ids": [(6, 0, [employees_group.id])]}) bi_view = self.env["bve.view"].create(vals) self.assertEqual(len(bi_view), 1) self.assertEqual(len(bi_view.line_ids), 3) self.assertTrue(bi_view.er_diagram_image) # check lines line1 = bi_view.line_ids[0] line2 = bi_view.line_ids[1] line3 = bi_view.line_ids[2] self.assertTrue(line1.in_list) self.assertTrue(line2.in_list) self.assertFalse(line3.in_list) self.assertFalse(line1.row) self.assertTrue(line1.column) self.assertFalse(line1.measure) self.assertFalse(line2.row) self.assertFalse(line2.column) self.assertFalse(line2.measure) self.assertTrue(line3.row) self.assertFalse(line3.column) self.assertFalse(line3.measure) # create bve object bi_view.action_create() model = ( self.env["ir.model"] .sudo() .search([("model", "=", "x_bve.testview4"), ("name", "=", "Test View4")]) ) self.assertEqual(len(model), 1) # open view open_action = bi_view.open_view() self.assertEqual(isinstance(open_action, dict), True) self.assertEqual(bi_view.state, "created") # try to remove view with self.assertRaises(UserError): bi_view.unlink() # reset to draft bi_view.action_reset() self.assertEqual(bi_view.state, "draft") # remove view bi_view.unlink() @odoo.tests.tagged("post_install", "-at_install") def test_10_create_open_bve_object_apostrophe(self): vals = self.bi_view1_vals vals.update({"name": "Test View5"}) data_list = list() for r in json.loads(vals["data"]): r["model_name"] = "model'name" data_list.append(r) new_format_data = json.dumps(data_list) vals.update({"data": new_format_data}) bi_view = self.env["bve.view"].create(vals) self.assertEqual(len(bi_view), 1) # create bve object bi_view.action_create() def test_11_clean_nodes(self): data_dict1 = { "sequence": 1, "model_id": 74, "id": 858, "name": "name", "model_name": "Contact", "model": "res.partner", "type": "char", "table_alias": "t74", "description": "Name", "row": False, "column": False, "measure": False, "list": True, } data_dict2 = { "sequence": 2, "model_id": 74, "id": 896, "name": "company_id", "model_name": "Contact", "model": "res.partner", "type": "many2one", "table_alias": "t74", "description": "Company", "row": False, "column": False, "measure": False, "list": True, "join_node": "t83", "relation": "res.company", "join_left": False, } old_data = json.dumps([data_dict1, data_dict2]) new_data = self.env["bve.view"].get_clean_list(old_data) new_data_dict = json.loads(new_data) self.assertEqual(len(new_data_dict), 1) for key in data_dict1.keys(): self.assertEqual(new_data_dict[0][key], data_dict1[key]) def test_12_check_groups(self): vals = self.bi_view1_vals group_system = self.env.ref("base.group_system") vals.update({"name": "Test View1", "group_ids": [(6, 0, [group_system.id])]}) bi_view1 = self.env["bve.view"].create(vals) with self.assertRaises(UserError): bi_view1.action_create() def test_13_check_lines_missing_model(self): vals = self.bi_view1_vals group_user = self.env.ref("base.group_user") vals.update({"name": "Test View1", "group_ids": [(6, 0, [group_user.id])]}) bi_view1 = self.env["bve.view"].create(vals) for line in bi_view1.line_ids: self.assertTrue(line.model_id) self.assertTrue(line.model_name) self.env.cr.execute("UPDATE bve_view_line SET model_id = null") bi_view1.invalidate_cache() for line in bi_view1.line_ids: self.assertFalse(line.model_id) self.assertTrue(line.model_name) with self.assertRaises(ValidationError): bi_view1.action_create() def test_14_check_lines_missing_fieldl(self): vals = self.bi_view1_vals group_user = self.env.ref("base.group_user") vals.update({"name": "Test View1", "group_ids": [(6, 0, [group_user.id])]}) bi_view1 = self.env["bve.view"].create(vals) for line in bi_view1.line_ids: self.assertTrue(line.field_id) self.assertTrue(line.field_name) self.env.cr.execute("UPDATE bve_view_line SET field_id = null") bi_view1.invalidate_cache() for line in bi_view1.line_ids: self.assertFalse(line.field_id) self.assertTrue(line.field_name) with self.assertRaises(ValidationError): bi_view1.action_create() def test_15_create_lines(self): vals = self.bi_view1_vals vals.update({"name": "Test View1"}) bi_view1 = self.env["bve.view"].create(vals) bi_view1._compute_serialized_data() data = json.loads(bi_view1.data) self.assertTrue(data) self.assertTrue(isinstance(data, list)) def test_17_uninstall_hook(self): uninstall_hook(self.cr, self.env) def test_18_action_translations(self): self.env["res.lang"]._activate_lang("it_IT") vals = self.bi_view1_vals vals.update({"name": "Test View1"}) bi_view1 = self.env["bve.view"].create(vals) res = bi_view1.action_translations() self.assertFalse(res) bi_view1.action_create() res = bi_view1.action_translations() self.assertTrue(res) @odoo.tests.tagged("post_install", "-at_install") def test_19_field_selection(self): field = ( self.env["ir.model.fields"] .sudo() .search( [ ("model", "=", self.company_model_name), ("name", "=", "base_onboarding_company_state"), ], limit=1, ) ) selection_data = [ { "model_id": self.company_model.id, "model_name": self.company_model.name, "model": self.company_model_name, "type": field.ttype, "id": field.id, "description": "State of the onboarding company step", "table_alias": "t1", "row": 0, "column": 0, "list": 1, "measure": 0, } ] vals = {"state": "draft", "data": json.dumps(self.data + selection_data)} vals.update({"name": "Test View6"}) bi_view1 = self.env["bve.view"].create(vals) bi_view1.action_create() self.assertEqual(len(bi_view1.line_ids), 4) @mute_logger("odoo.sql_db") def test_20_broken_view(self): """ Create a broken query, a nice UserError should be raised. odoo.sql_db logger is muted to avoid the ERROR: bad_query line in the logs. """ vals = self.bi_view1_vals vals.update({"name": "Test View broken", "over_condition": "bad SQL code"}) bi_view = self.env["bve.view"].create(vals) with self.assertRaises(UserError) as ue: bi_view.action_create() self.assertEqual(bi_view.state, "draft") self.assertIn(bi_view.over_condition, str(ue.exception)) # remove view bi_view.unlink()
35.705882
15,175
1,636
py
PYTHON
15.0
# Copyright 2017-2020 Onestein (<https://www.onestein.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class WizardModelMenuCreate(models.TransientModel): _inherit = "wizard.ir.model.menu.create" def menu_create(self): if self.env.context.get("active_model") == "bve.view": self.ensure_one() active_id = self.env.context.get("active_id") bve_view = self.env["bve.view"].browse(active_id) menu = self.env["ir.ui.menu"].create( { "name": self.name, "parent_id": self.menu_id.id, "action": "ir.actions.act_window,%d" % (bve_view.action_id,), } ) self.env["ir.model.data"].sudo().create( { "name": bve_view.name and str(bve_view.name).replace(" ", "") + ",id=" + str(menu.id), "noupdate": True, "module": "bi_view_editor", "model": "ir.ui.menu", "res_id": menu.id, } ) return {"type": "ir.actions.client", "tag": "reload"} return super().menu_create() @api.model def default_get(self, fields_list): defaults = super().default_get(fields_list) if self.env.context.get("active_model") == "bve.view": active_id = self.env.context.get("active_id") bve_view = self.env["bve.view"].browse(active_id) defaults.setdefault("name", bve_view.name) return defaults
38.952381
1,636
7,490
py
PYTHON
15.0
# Copyright 2015-2019 Onestein (<https://www.onestein.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from collections import defaultdict from odoo import api, models NO_BI_MODELS = ["fetchmail.server"] NO_BI_TTYPES = ["many2many", "one2many", "html", "binary", "reference"] def dict_for_field(field): return { "id": field.id, "name": field.name, "description": field.field_description, "type": field.ttype, "relation": field.relation, "custom": False, "model_id": field.model_id.id, "model": field.model_id.model, "model_name": field.model_id.name, } def dict_for_model(model): return {"id": model.id, "name": model.name, "model": model.model} class IrModel(models.Model): _inherit = "ir.model" @api.model def _filter_bi_models(self, model): def _check_name(model_model): if model_model in NO_BI_MODELS: return 1 return 0 def _check_startswith(model_model): if ( model_model.startswith("workflow") or model_model.startswith("ir.") or model_model.startswith("base_") ): return 1 return 0 def _check_contains(model_model): if ( "mail" in model_model or "report" in model_model or "edi." in model_model ): return 1 return 0 def _check_unknown(model_name): if model_name == "Unknown" or "." in model_name: return 1 return 0 model_model = model["model"] model_name = model["name"] count_check = 0 count_check += _check_name(model_model) count_check += _check_startswith(model_model) count_check += _check_contains(model_model) count_check += _check_unknown(model_name) if not count_check: return ( self.env["ir.model.access"].sudo().check(model["model"], "read", False) ) return False def get_model_list(self, model_table_map): if not model_table_map: return [] domain = [ ("model_id", "in", list(model_table_map.keys())), ("store", "=", True), ("ttype", "=", "many2one"), ] fields = self.env["ir.model.fields"].sudo().search(domain) model_list = [] for field in fields: for table_alias in model_table_map[field.model_id.id]: model_list.append( dict( dict_for_field(field), table_alias=table_alias, join_node=-1, ) ) return model_list def get_relation_list(self, model_table_map): if not model_table_map: return [] model_names = {} for model in self.sudo().browse(model_table_map.keys()): model_names.update({model.model: model.id}) domain = [ ("relation", "in", list(model_names.keys())), ("store", "=", True), ("ttype", "=", "many2one"), ] fields = self.env["ir.model.fields"].sudo().search(domain) relation_list = [] for field in fields: model_id = model_names[field.relation] for join_node in model_table_map[model_id]: relation_list.append( dict(dict_for_field(field), join_node=join_node, table_alias=-1) ) return relation_list @api.model def _get_related_models_domain(self, model_table_map): domain = [("transient", "=", False)] if model_table_map: model_list = self.get_model_list(model_table_map) relation_list = self.get_relation_list(model_table_map) model_ids = [f["model_id"] for f in relation_list + model_list] model_ids += list(model_table_map.keys()) relations = [f["relation"] for f in model_list] domain += ["|", ("id", "in", model_ids), ("model", "in", relations)] return domain @api.model def get_related_models(self, model_table_map): """Return list of model dicts for all models that can be joined with the already selected models. """ domain = self._get_related_models_domain(model_table_map) return self.sudo().search(domain, order="name asc") @api.model def get_models(self, table_model_map=None): """Return list of model dicts for all available models.""" self = self.with_context(lang=self.env.user.lang) model_table_map = defaultdict(list) for k, v in (table_model_map or {}).items(): model_table_map[v].append(k) models = self.get_related_models(model_table_map) # filter out abstract models (they do not have DB tables) non_abstract_models = self.env.registry.models.keys() models = models.filtered(lambda m: m.model in non_abstract_models) return list(map(dict_for_model, models)) @api.model def get_join_nodes(self, field_data, new_field): """Return list of field dicts of join nodes Return all possible join nodes to add new_field to the query containing model_ids. """ def remove_duplicate_nodes(join_nodes): seen = set() nodes_list = [] for node in join_nodes: node_tuple = tuple(node.items()) if node_tuple not in seen: seen.add(node_tuple) nodes_list.append(node) return nodes_list self = self.with_context(lang=self.env.user.lang) keys = [] model_table_map = defaultdict(list) for field in field_data: model_table_map[field["model_id"]].append(field["table_alias"]) if field.get("join_node", -1) != -1: keys.append((field["table_alias"], field["id"])) # nodes in current model existing_aliases = model_table_map[new_field["model_id"]] join_nodes = [{"table_alias": alias} for alias in existing_aliases] # nodes in past selected models for field in self.get_model_list(model_table_map): if new_field["model"] == field["relation"]: if (field["table_alias"], field["id"]) not in keys: join_nodes.append(field) # nodes in new model for field in self.get_relation_list(model_table_map): if new_field["model_id"] == field["model_id"]: if (field["table_alias"], field["id"]) not in keys: join_nodes.append(field) return remove_duplicate_nodes(join_nodes) @api.model def get_fields(self, model_id): self = self.with_context(lang=self.env.user.lang) fields = ( self.env["ir.model.fields"] .sudo() .search( [ ("model_id", "=", model_id), ("store", "=", True), ("name", "not in", models.MAGIC_COLUMNS), ("ttype", "not in", NO_BI_TTYPES), ], order="field_description desc", ) ) fields_dict = list(map(dict_for_field, fields)) return fields_dict
34.200913
7,490
1,282
py
PYTHON
15.0
# Copyright 2017-2020 Onestein (<https://www.onestein.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import logging from odoo import _, api, models from odoo.exceptions import UserError _logger = logging.getLogger(__name__) @api.model def _bi_view(_name): return _name.startswith("x_bve.") _auto_init_orig = models.BaseModel._auto_init def _auto_init(self): # This monkey patch is meant to fix an error (probably # introduced by https://github.com/odoo/odoo/pull/15412), while # running an update all. The _auto_init() method invoked during # an update all is the one of BaseModel, and not the one of Base. # This monkey patch seems not working if defined inside the post_load() if _bi_view(self._name): return return _auto_init_orig(self) models.BaseModel._auto_init = _auto_init class Base(models.AbstractModel): _inherit = "base" @api.model def _read_group_process_groupby(self, gb, query): if not _bi_view(self._name): return super()._read_group_process_groupby(gb, query) split = gb.split(":") if split[0] not in self._fields: raise UserError(_("No data to be displayed.")) return super()._read_group_process_groupby(gb, query)
26.708333
1,282
4,852
py
PYTHON
15.0
# Copyright 2015-2020 Onestein (<https://www.onestein.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class BveViewLine(models.Model): _name = "bve.view.line" _description = "BI View Editor Lines" name = fields.Char(compute="_compute_name") sequence = fields.Integer(default=1) bve_view_id = fields.Many2one("bve.view", ondelete="cascade") model_id = fields.Many2one("ir.model") model_name = fields.Char(related="model_id.model", store=True, string="Model Name") table_alias = fields.Char(required=True) join_model_id = fields.Many2one("ir.model") field_id = fields.Many2one("ir.model.fields") field_name = fields.Char(compute="_compute_model_field_name", store=True) ttype = fields.Char(string="Type") description = fields.Char(translate=True) relation = fields.Char() join_node = fields.Char() left_join = fields.Boolean() row = fields.Boolean() column = fields.Boolean() measure = fields.Boolean() in_list = fields.Boolean() list_attr = fields.Selection( [("sum", "Sum"), ("avg", "Average")], string="List Attribute", default="sum" ) view_field_type = fields.Char(compute="_compute_view_field_type") @api.depends("row", "column", "measure") def _compute_view_field_type(self): for line in self: row = line.row and "row" column = line.column and "col" measure = line.measure and "measure" line.view_field_type = row or column or measure @api.constrains("row", "column", "measure") def _constrains_options_check(self): measure_types = ["float", "integer", "monetary"] for line in self.filtered(lambda l: l.row or l.column): if line.join_model_id or line.ttype in measure_types: err_msg = _("This field cannot be a row or a column.") raise ValidationError(err_msg) for line in self.filtered(lambda l: l.measure): if line.join_model_id or line.ttype not in measure_types: err_msg = _("This field cannot be a measure.") raise ValidationError(err_msg) @api.constrains("table_alias", "field_id") def _constrains_unique_fields_check(self): seen = set() for line in self.mapped("bve_view_id.field_ids"): if ( line.table_alias, line.field_id.id, ) not in seen: seen.add( ( line.table_alias, line.field_id.id, ) ) else: field_model = line.field_id.model field_name = line.field_id.name raise ValidationError( _( "Field %(field_model)s/%(field_name)s is duplicated.\n" "Please remove the duplications." ) % {"field_model": field_model, "field_name": field_name} ) @api.depends("field_id", "sequence") def _compute_name(self): for line in self: line.name = False if line.field_id: line.name = "x_bve_{}_{}".format(line.table_alias, line.field_id.name) @api.depends("field_id") def _compute_model_field_name(self): for line in self: line.field_name = False if line.field_id: line.field_name = "{} ({})".format(line.description, line.model_name) def _prepare_field_vals(self): vals_list = [] for line in self: field = line.field_id vals = { "name": line.name, "complete_name": field.complete_name, "model": line.bve_view_id.model_name, "relation": field.relation, "field_description": line.description, "ttype": field.ttype, "selection": field.selection, "size": field.size, "state": "manual", "readonly": True, "groups": [(6, 0, field.groups.ids)], } if vals["ttype"] == "monetary": vals.update({"ttype": "float"}) if field.ttype == "selection" and not field.selection: model_obj = self.env[field.model_id.model] selection = model_obj._fields[field.name].selection if callable(selection): selection_domain = selection(model_obj) else: selection_domain = selection vals.update({"selection": str(selection_domain)}) vals_list.append(vals) return vals_list
39.447154
4,852
24,219
py
PYTHON
15.0
# Copyright 2015-2020 Onestein (<https://www.onestein.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import base64 import json import pydot from psycopg2.extensions import AsIs from odoo import _, api, fields, models, tools from odoo.exceptions import UserError, ValidationError class BveView(models.Model): _name = "bve.view" _description = "BI View Editor" @api.depends("group_ids", "group_ids.users") def _compute_users(self): for bve_view in self.sudo(): if bve_view.group_ids: bve_view.user_ids = bve_view.group_ids.mapped("users") else: bve_view.user_ids = self.env["res.users"].sudo().search([]) @api.depends("name") def _compute_model_name(self): for bve_view in self: name = [x for x in bve_view.name.lower() if x.isalnum()] model_name = "".join(name).replace("_", ".").replace(" ", ".") bve_view.model_name = "x_bve." + model_name def _compute_serialized_data(self): for bve_view in self: serialized_data = [] for line in bve_view.line_ids.sorted(key=lambda r: r.sequence): serialized_data.append( { "sequence": line.sequence, "model_id": line.model_id.id, "id": line.field_id.id, "name": line.name, "model_name": line.model_id.name, "model": line.model_id.model, "type": line.ttype, "table_alias": line.table_alias, "description": line.description, "row": line.row, "column": line.column, "measure": line.measure, "list": line.in_list, "join_node": line.join_node, "relation": line.relation, } ) bve_view.data = json.dumps(serialized_data) def _inverse_serialized_data(self): for bve_view in self: line_ids = self._sync_lines_and_data(bve_view.data) bve_view.write({"line_ids": line_ids}) name = fields.Char(required=True, copy=False, default="") model_name = fields.Char(compute="_compute_model_name", store=True) note = fields.Text(string="Notes") state = fields.Selection( [("draft", "Draft"), ("created", "Created")], default="draft", copy=False ) data = fields.Char( compute="_compute_serialized_data", inverse="_inverse_serialized_data", help="Use the special query builder to define the query " "to generate your report dataset. " "NOTE: To be edited, the query should be in 'Draft' status.", ) line_ids = fields.One2many("bve.view.line", "bve_view_id", string="Lines") field_ids = fields.One2many( "bve.view.line", "bve_view_id", domain=["|", ("join_node", "=", -1), ("join_node", "=", False)], string="Fields", ) relation_ids = fields.One2many( "bve.view.line", "bve_view_id", domain=[("join_node", "!=", -1), ("join_node", "!=", False)], string="Relations", ) action_id = fields.Many2one("ir.actions.act_window", string="Action") view_id = fields.Many2one("ir.ui.view", string="View") group_ids = fields.Many2many( "res.groups", string="Groups", help="User groups allowed to see the generated report; " "if NO groups are specified the report will be public " "for everyone.", ) user_ids = fields.Many2many( "res.users", string="Users", compute="_compute_users", store=True ) query = fields.Text(compute="_compute_sql_query") over_condition = fields.Text( states={"draft": [("readonly", False)]}, readonly=True, help="Condition to be inserted in the OVER part " "of the ID's row_number function.\n" "For instance, 'ORDER BY t1.id' would create " "IDs ordered in the same way as t1's IDs; otherwise " "IDs are assigned with no specific order.", ) er_diagram_image = fields.Binary(compute="_compute_er_diagram_image") _sql_constraints = [ ("name_uniq", "unique(name)", _("Custom BI View names must be unique!")), ] @api.depends("line_ids") def _compute_er_diagram_image(self): for bve_view in self: graph = pydot.Dot(graph_type="graph") table_model_map = {} for line in bve_view.field_ids: if line.table_alias not in table_model_map: table_alias_node = pydot.Node( line.model_id.name + " " + line.table_alias, style="filled", shape="box", fillcolor="#DDDDDD", ) table_model_map[line.table_alias] = table_alias_node graph.add_node(table_model_map[line.table_alias]) field_node = pydot.Node( line.table_alias + "." + line.field_id.field_description, label=line.description, style="filled", fillcolor="green", ) graph.add_node(field_node) graph.add_edge( pydot.Edge(table_model_map[line.table_alias], field_node) ) for line in bve_view.relation_ids: field_description = line.field_id.field_description table_alias = line.table_alias diamond_node = pydot.Node( line.ttype + " " + table_alias + "." + field_description, label=table_alias + "." + field_description, style="filled", shape="diamond", fillcolor="#D2D2FF", ) graph.add_node(diamond_node) graph.add_edge( pydot.Edge( table_model_map[table_alias], diamond_node, labelfontcolor="#D2D2FF", color="blue", ) ) graph.add_edge( pydot.Edge( diamond_node, table_model_map[line.join_node], labelfontcolor="black", color="blue", ) ) try: png_base64_image = base64.b64encode(graph.create_png()) bve_view.er_diagram_image = png_base64_image except Exception: bve_view.er_diagram_image = False def _create_view_arch(self): self.ensure_one() def _get_field_def(line): field_type = line.view_field_type return '<field name="{}" type="{}" />'.format(line.name, field_type) bve_field_lines = self.field_ids.filtered("view_field_type") return list(map(_get_field_def, bve_field_lines)) def _create_tree_view_arch(self): self.ensure_one() def _get_field_attrs(line): attr = line.list_attr res = attr and '{}="{}"'.format(attr, line.description) or "" return '<field name="{}" {} />'.format(line.name, res) bve_field_lines = self.field_ids.filtered(lambda l: l.in_list) return list(map(_get_field_attrs, bve_field_lines.sorted("sequence"))) def _create_bve_view(self): self.ensure_one() View = self.env["ir.ui.view"].sudo() # delete old views View.search([("model", "=", self.model_name)]).unlink() # create views View.create( [ { "name": "Pivot Analysis", "type": "pivot", "model": self.model_name, "priority": 16, "arch": """<?xml version="1.0"?> <pivot string="Pivot Analysis"> {} </pivot> """.format( "".join(self._create_view_arch()) ), }, { "name": "Graph Analysis", "type": "graph", "model": self.model_name, "priority": 16, "arch": """<?xml version="1.0"?> <graph string="Graph Analysis" type="bar" stacked="True"> {} </graph> """.format( "".join(self._create_view_arch()) ), }, { "name": "Search BI View", "type": "search", "model": self.model_name, "priority": 16, "arch": """<?xml version="1.0"?> <search> {} </search> """.format( "".join(self._create_view_arch()) ), }, ] ) # create Tree view tree_view = View.create( { "name": "Tree Analysis", "type": "tree", "model": self.model_name, "priority": 16, "arch": """<?xml version="1.0"?> <tree create="false"> {} </tree> """.format( "".join(self._create_tree_view_arch()) ), } ) # set the Tree view as the default one action = ( self.env["ir.actions.act_window"] .sudo() .create( { "name": self.name, "res_model": self.model_name, "type": "ir.actions.act_window", "view_mode": "tree,graph,pivot", "view_id": tree_view.id, "context": "{'service_name': '%s'}" % self.name, } ) ) self.write( {"action_id": action.id, "view_id": tree_view.id, "state": "created"} ) def _build_access_rules(self, model): self.ensure_one() if not self.group_ids: self.env["ir.model.access"].sudo().create( { "name": "read access to " + self.model_name, "model_id": model.id, "perm_read": True, } ) else: # read access only to model access_vals = [ { "name": "read access to " + self.model_name, "model_id": model.id, "group_id": group.id, "perm_read": True, } for group in self.group_ids ] self.env["ir.model.access"].sudo().create(access_vals) def _create_sql_view(self): self.ensure_one() view_name = self.model_name.replace(".", "_") query = self.query and self.query.replace("\n", " ") # robustness in case something went wrong self._cr.execute("DROP TABLE IF EXISTS %s", (AsIs(view_name),)) # create postgres view try: with self.env.cr.savepoint(): self.env.cr.execute( "CREATE or REPLACE VIEW %s as (%s)", ( AsIs(view_name), AsIs(query), ), ) except Exception as e: raise UserError( _("Error creating the view '{query}':\n{error}").format( query=query, error=e ) ) from e @api.depends("line_ids", "state", "over_condition") def _compute_sql_query(self): for bve_view in self: tables_map = {} select_str = "\n CAST(row_number() OVER ({}) as integer) AS id".format( bve_view.over_condition or "" ) for line in bve_view.field_ids: table = line.table_alias select = line.field_id.name as_name = line.name select_str += ",\n {}.{} AS {}".format(table, select, as_name) if line.table_alias not in tables_map: table = self.env[line.field_id.model_id.model]._table tables_map[line.table_alias] = table seen = set() from_str = "" if not bve_view.relation_ids and bve_view.field_ids: first_line = bve_view.field_ids[0] table = tables_map[first_line.table_alias] from_str = "{} AS {}".format(table, first_line.table_alias) for line in bve_view.relation_ids: table = tables_map[line.table_alias] table_format = "{} AS {}".format(table, line.table_alias) if not from_str: from_str += table_format seen.add(line.table_alias) if line.table_alias not in seen: seen.add(line.table_alias) from_str += "\n" from_str += " LEFT" if line.left_join else "" from_str += " JOIN {} ON {}.id = {}.{}".format( table_format, line.join_node, line.table_alias, line.field_id.name, ) if line.join_node not in seen: from_str += "\n" seen.add(line.join_node) from_str += " LEFT" if line.left_join else "" from_str += " JOIN {} AS {} ON {}.{} = {}.id".format( tables_map[line.join_node], line.join_node, line.table_alias, line.field_id.name, line.join_node, ) bve_view.query = """SELECT %s\n\nFROM %s """ % ( AsIs(select_str), AsIs(from_str), ) def action_translations(self): self.ensure_one() if self.state != "created": return self = self.sudo() model = self.env["ir.model"].sudo().search([("model", "=", self.model_name)]) IrTranslation = self.env["ir.translation"] IrTranslation.translate_fields("ir.model", model.id) for field in model.field_id: IrTranslation.translate_fields("ir.model.fields", field.id) return { "name": "Translations", "res_model": "ir.translation", "type": "ir.actions.act_window", "view_mode": "tree", "view_id": self.env.ref("base.view_translation_dialog_tree").id, "target": "current", "flags": {"search_view": True, "action_buttons": True}, "domain": [ "|", "&", ("res_id", "in", model.field_id.ids), ("name", "=", "ir.model.fields,field_description"), "&", ("res_id", "=", model.id), ("name", "=", "ir.model,name"), ], } def action_create(self): self.ensure_one() # consistency checks self._check_invalid_lines() self._check_groups_consistency() # force removal of dirty views in case something went wrong self.sudo().action_reset() # create sql view self._create_sql_view() # create model and fields bve_fields = self.line_ids.filtered(lambda l: not l.join_node) model = ( self.env["ir.model"] .sudo() .with_context(bve=True) .create( { "name": self.name, "model": self.model_name, "state": "manual", "field_id": [(0, 0, f) for f in bve_fields._prepare_field_vals()], } ) ) # give access rights self._build_access_rules(model) # create tree, graph and pivot views self._create_bve_view() def _check_groups_consistency(self): self.ensure_one() if not self.group_ids: return for line_model in self.line_ids.mapped("model_id"): res_count = ( self.env["ir.model.access"] .sudo() .search( [ ("model_id", "=", line_model.id), ("perm_read", "=", True), "|", ("group_id", "=", False), ("group_id", "in", self.group_ids.ids), ], limit=1, ) ) if not res_count: access_records = ( self.env["ir.model.access"] .sudo() .search( [("model_id", "=", line_model.id), ("perm_read", "=", True)] ) ) group_list = "" for group in access_records.mapped("group_id"): group_list += " * {}\n".format(group.full_name) msg_title = _( 'The model "%s" cannot be accessed by users with the selected groups only.' ) % (line_model.name,) msg_details = _("At least one of the following groups must be added:") raise UserError( _("%(msg_title)s\n\n%(msg_details)s\n%(group_list)s") % { "msg_title": msg_title, "msg_details": msg_details, "group_list": group_list, } ) def _check_invalid_lines(self): self.ensure_one() if not self.line_ids: raise ValidationError(_("No data to process.")) invalid_lines = self.line_ids.filtered(lambda l: not l.model_id) if invalid_lines: missing_models = ", ".join(set(invalid_lines.mapped("model_name"))) raise ValidationError( _( "Following models are missing: %s.\nProbably some modules were uninstalled." ) % (missing_models,) ) invalid_lines = self.line_ids.filtered(lambda l: not l.field_id) if invalid_lines: missing_fields = ", ".join(set(invalid_lines.mapped("field_name"))) raise ValidationError( _("Following fields are missing: %(missing_fields)s.") % ({"missing_fields": missing_fields}) ) def open_view(self): self.ensure_one() self._check_invalid_lines() [action] = self.action_id.read() action["display_name"] = _("BI View") return action def copy(self, default=None): self.ensure_one() default = dict(default or {}, name=_("%s (copy)") % self.name) return super().copy(default=default) def action_reset(self): self.ensure_one() has_menus = False if self.action_id: action = "ir.actions.act_window,%d" % (self.action_id.id,) menus = self.env["ir.ui.menu"].search([("action", "=", action)]) has_menus = True if menus else False menus.unlink() if self.action_id.view_id: self.sudo().action_id.view_id.unlink() self.sudo().action_id.unlink() self.env["ir.ui.view"].sudo().search([("model", "=", self.model_name)]).unlink() models_to_delete = ( self.env["ir.model"].sudo().search([("model", "=", self.model_name)]) ) if models_to_delete: models_to_delete.with_context(_force_unlink=True).unlink() table_name = self.model_name.replace(".", "_") tools.drop_view_if_exists(self.env.cr, table_name) self.state = "draft" if has_menus: return {"type": "ir.actions.client", "tag": "reload"} def unlink(self): if self.filtered(lambda v: v.state == "created"): raise UserError( _("You cannot delete a created view! " "Reset the view to draft first.") ) return super().unlink() @api.model def _sync_lines_and_data(self, data): line_ids = [(5, 0, 0)] fields_info = [] if data: fields_info = json.loads(data) table_model_map = {} for item in fields_info: if item.get("join_node", -1) == -1: table_model_map[item["table_alias"]] = item["model_id"] for sequence, field_info in enumerate(fields_info, start=1): join_model_id = False join_node = field_info.get("join_node", -1) if join_node != -1 and table_model_map.get(join_node): join_model_id = int(table_model_map[join_node]) line_ids += [ ( 0, False, { "sequence": sequence, "model_id": field_info["model_id"], "table_alias": field_info["table_alias"], "description": field_info["description"], "field_id": field_info["id"], "ttype": field_info["type"], "row": field_info["row"], "column": field_info["column"], "measure": field_info["measure"], "in_list": field_info["list"], "relation": field_info.get("relation"), "join_node": field_info.get("join_node"), "join_model_id": join_model_id, }, ) ] return line_ids @api.constrains("line_ids") def _constraint_line_ids(self): models_with_tables = self.env.registry.models.keys() for view in self: nodes = view.line_ids.filtered(lambda n: n.join_node) nodes_models = nodes.mapped("table_alias") nodes_models += nodes.mapped("join_node") not_nodes = view.line_ids.filtered(lambda n: not n.join_node) not_nodes_models = not_nodes.mapped("table_alias") err_msg = _("Inconsistent lines.") if set(nodes_models) - set(not_nodes_models): raise ValidationError(err_msg) if len(set(not_nodes_models) - set(nodes_models)) > 1: raise ValidationError(err_msg) models = view.line_ids.mapped("model_id") if models.filtered(lambda m: m.model not in models_with_tables): raise ValidationError(_("Abstract models not supported.")) @api.model def get_clean_list(self, data_dict): serialized_data = data_dict if type(data_dict) == str: serialized_data = json.loads(data_dict) table_alias_list = set() for item in serialized_data: if item.get("join_node", -1) in [-1, False]: table_alias_list.add(item["table_alias"]) for item in serialized_data: if item.get("join_node", -1) not in [-1, False]: if item["table_alias"] not in table_alias_list: serialized_data.remove(item) elif item["join_node"] not in table_alias_list: serialized_data.remove(item) return json.dumps(serialized_data)
37.490712
24,219
837
py
PYTHON
15.0
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) { "name": "Report Async", "summary": "Central place to run reports live or async", "version": "15.0.1.0.0", "author": "Ecosoft, Odoo Community Association (OCA)", "license": "AGPL-3", "website": "https://github.com/OCA/reporting-engine", "category": "Generic Modules", "depends": ["queue_job"], "data": [ "security/ir.model.access.csv", "security/ir_rule.xml", "data/mail_template.xml", "data/queue_job_function_data.xml", "views/report_async.xml", "wizard/print_report_wizard.xml", ], "demo": ["demo/report_async_demo.xml"], "installable": True, "maintainers": ["kittiu"], "development_status": "Beta", }
34.875
837
2,491
py
PYTHON
15.0
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo.exceptions import UserError from odoo.tests import common from odoo.tests.common import Form class TestJobChannel(common.TransactionCase): def setUp(self): super(TestJobChannel, self).setUp() self.print_doc = self.env.ref("report_async.report_async_print_document") self.test_rec = self.env.ref("base.module_mail") self.test_rpt = self.env.ref("base.ir_module_reference_print") def _print_wizard(self, res): obj = self.env[res["res_model"]] with Form( obj.with_context( active_model=self.print_doc._name, active_id=self.print_doc.id, async_process=res["context"].get("async_process"), ) ) as form: form.reference = "{},{}".format(self.test_rec._name, self.test_rec.id) form.action_report_id = self.test_rpt print_wizard = form.save() return print_wizard def test_1_run_now(self): """Run now will return report action as normal""" res = self.print_doc.run_now() report_action = self._print_wizard(res).print_report() self.assertEqual(report_action["type"], "ir.actions.report") def test_2_run_async(self): """Run background will return nothing, job started""" self.print_doc.write({"allow_async": False}) with self.assertRaises(UserError): self.print_doc.run_async() self.print_doc.write({"allow_async": True, "email_notify": True}) res = self.print_doc.run_async() print_wizard = self._print_wizard(res) report_action = print_wizard.print_report() self.assertEqual(report_action, {}) # Do not run report yet self.assertEqual(self.print_doc.job_status, "pending") # Job started # Test produce file (as queue will not run in test mode) docids = [print_wizard.reference.id] data = None report_id = self.test_rpt.id user_id = self.env.user.id self.print_doc.run_report(docids, data, report_id, user_id) # Check name of the newly producted file # Note: on env with test-enable, always fall back to render_qweb_html self.assertIn(self.test_rpt.name, self.print_doc.file_ids[0].name) # View fileds/jobs self.print_doc.view_files() self.print_doc.view_jobs()
43.701754
2,491
1,375
py
PYTHON
15.0
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import api, fields, models class PrintReportWizard(models.TransientModel): _name = "print.report.wizard" _description = "Print Report Wizard" reference = fields.Reference( string="Document", selection="_reference_models", required=True, ) action_report_id = fields.Many2one( comodel_name="ir.actions.report", string="Report Template", required=True, ) @api.model def _reference_models(self): excludes = ["res.company"] models = self.env["ir.model"].search( [ ("state", "!=", "manual"), ("transient", "=", False), ("model", "not in", excludes), ] ) return [(model.model, model.name) for model in models] @api.onchange("reference") def _onchange_reference(self): self.ensure_one() domain = [("id", "in", [])] self.action_report_id = False if self.reference: domain = [("model", "=", self.reference._name)] return {"domain": {"action_report_id": domain}} def print_report(self): self.ensure_one() return self.action_report_id.report_action(self.reference, config=False)
30.555556
1,375
5,629
py
PYTHON
15.0
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) import base64 from odoo import _, api, fields, models from odoo.exceptions import UserError from odoo.tools.safe_eval import safe_eval # Define all supported report_type REPORT_TYPES_FUNC = { "qweb-pdf": "_render_qweb_pdf", "qweb-text": "_render_qweb_text", "qweb-xml": "_render_qweb_xml", "csv": "_render_csv", "excel": "render_excel", "xlsx": "_render_xlsx", } class ReportAsync(models.Model): _name = "report.async" _description = "Report Async" action_id = fields.Many2one( comodel_name="ir.actions.act_window", string="Reports", required=True, ) allow_async = fields.Boolean( default=False, help="This is not automatic field, please check if you want to allow " "this report in background process", ) name = fields.Char( string="Name", related="action_id.display_name", ) email_notify = fields.Boolean( string="Email Notification", help="Send email with link to report, when it is ready", ) group_ids = fields.Many2many( string="Groups", comodel_name="res.groups", help="Only user in selected groups can use this report." "If left blank, everyone can use", ) job_ids = fields.Many2many( comodel_name="queue.job", compute="_compute_job", help="List all jobs related to this running report", ) job_status = fields.Selection( selection=[ ("pending", "Pending"), ("enqueued", "Enqueued"), ("started", "Started"), ("done", "Done"), ("failed", "Failed"), ], compute="_compute_job", help="Latest Job Status", ) job_info = fields.Text( compute="_compute_job", help="Latest Job Error Message", ) file_ids = fields.Many2many( comodel_name="ir.attachment", compute="_compute_file", help="List all files created by this report background process", ) def _compute_job(self): for rec in self: rec.job_ids = ( self.sudo() .env["queue.job"] .search( [ ("func_string", "like", "report.async(%s,)" % rec.id), ("user_id", "=", self._uid), ], order="id desc", ) ) rec.job_status = rec.job_ids[0].sudo().state if rec.job_ids else False rec.job_info = rec.job_ids[0].sudo().exc_info if rec.job_ids else False def _compute_file(self): files = self.env["ir.attachment"].search( [ ("res_model", "=", "report.async"), ("res_id", "in", self.ids), ("create_uid", "=", self._uid), ], order="id desc", ) for rec in self: rec.file_ids = files.filtered(lambda l: l.res_id == rec.id) def run_now(self): self.ensure_one() action = self.env.ref(self.action_id.xml_id) result = action.sudo().read()[0] ctx = safe_eval(result.get("context", {})) ctx.update({"async_process": False}) result["context"] = ctx return result def run_async(self): self.ensure_one() if not self.allow_async: raise UserError(_("Background process not allowed.")) action = self.env.ref(self.action_id.xml_id) result = action.sudo().read()[0] ctx = safe_eval(result.get("context", {})) ctx.update({"async_process": True}) result["context"] = ctx return result def view_files(self): self.ensure_one() action = self.env.ref("report_async.action_view_files") result = action.sudo().read()[0] result["domain"] = [("id", "in", self.file_ids.ids)] return result def view_jobs(self): self.ensure_one() action = self.env.ref("queue_job.action_queue_job") result = action.sudo().read()[0] result["domain"] = [("id", "in", self.job_ids.ids)] result["context"] = {} return result @api.model def run_report(self, docids, data, report_id, user_id): report = self.env["ir.actions.report"].browse(report_id) func = REPORT_TYPES_FUNC[report.report_type] # Run report out_file, file_ext = getattr(report, func)(docids, data) out_file = base64.b64encode(out_file) out_name = "{}.{}".format(report.name, file_ext) # Save report to attachment attachment = ( self.env["ir.attachment"] .sudo() .create( { "name": out_name, "datas": out_file, "type": "binary", "res_model": "report.async", "res_id": self.id, } ) ) self._cr.execute( """ UPDATE ir_attachment SET create_uid = %s, write_uid = %s WHERE id = %s""", (self._uid, self._uid, attachment.id), ) # Send email if self.email_notify: self._send_email(attachment) def _send_email(self, attachment): template = self.env.ref("report_async.async_report_delivery") template.send_mail( attachment.id, notif_layout="mail.mail_notification_light", force_send=False )
32.350575
5,629
908
py
PYTHON
15.0
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import models # Define all supported report_type REPORT_TYPES = ["qweb-pdf", "qweb-text", "qweb-xml", "csv", "excel", "xlsx"] class Report(models.Model): _inherit = "ir.actions.report" def report_action(self, docids, data=None, config=True): res = super(Report, self).report_action(docids, data=data, config=config) if res["context"].get("async_process", False): rpt_async_id = res["context"]["active_id"] report_async = self.env["report.async"].browse(rpt_async_id) if res["report_type"] in REPORT_TYPES: report_async.with_delay().run_report( res["context"].get("active_ids", []), data, self.id, self._uid ) return {} return res
39.478261
908
935
py
PYTHON
15.0
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import api, models class IrActionsActWindow(models.Model): _inherit = "ir.actions.act_window" @api.model def name_search(self, name, args=None, operator="ilike", limit=100): if self._context.get("access_sudo", False): self = self.sudo() return super().name_search(name, args, operator, limit) @api.model def search(self, args, offset=0, limit=None, order=None, count=False): if self._context.get("access_sudo", False): self = self.sudo() return super().search(args, offset, limit, order, count) def _read(self, fields): """Add permission to read analytic account for do something.""" if self._context.get("access_sudo", False): self = self.sudo() return super()._read(fields)
35.961538
935
1,448
py
PYTHON
15.0
import setuptools with open('VERSION.txt', 'r') as f: version = f.read().strip() setuptools.setup( name="odoo-addons-oca-reporting-engine", description="Meta package for oca-reporting-engine Odoo addons", version=version, install_requires=[ 'odoo-addon-base_comment_template>=15.0dev,<15.1dev', 'odoo-addon-bi_sql_editor>=15.0dev,<15.1dev', 'odoo-addon-bi_view_editor>=15.0dev,<15.1dev', 'odoo-addon-board_eval_context>=15.0dev,<15.1dev', 'odoo-addon-report_async>=15.0dev,<15.1dev', 'odoo-addon-report_csv>=15.0dev,<15.1dev', 'odoo-addon-report_qr>=15.0dev,<15.1dev', 'odoo-addon-report_qweb_element_page_visibility>=15.0dev,<15.1dev', 'odoo-addon-report_qweb_encrypt>=15.0dev,<15.1dev', 'odoo-addon-report_qweb_parameter>=15.0dev,<15.1dev', 'odoo-addon-report_qweb_pdf_watermark>=15.0dev,<15.1dev', 'odoo-addon-report_wkhtmltopdf_param>=15.0dev,<15.1dev', 'odoo-addon-report_xlsx>=15.0dev,<15.1dev', 'odoo-addon-report_xlsx_helper>=15.0dev,<15.1dev', 'odoo-addon-report_xml>=15.0dev,<15.1dev', 'odoo-addon-sql_export>=15.0dev,<15.1dev', 'odoo-addon-sql_export_excel>=15.0dev,<15.1dev', 'odoo-addon-sql_request_abstract>=15.0dev,<15.1dev', ], classifiers=[ 'Programming Language :: Python', 'Framework :: Odoo', 'Framework :: Odoo :: 15.0', ] )
41.371429
1,448
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
820
py
PYTHON
15.0
# Copyright 2020 Creu Blanca # Copyright 2020 Ecosoft Co., Ltd. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Report Qweb Encrypt", "summary": "Allow to encrypt qweb pdfs", "version": "15.0.1.0.0", "license": "AGPL-3", "author": "Creu Blanca,Ecosoft,Odoo Community Association (OCA)", "website": "https://github.com/OCA/reporting-engine", "depends": [ "web", ], "data": [ "views/ir_actions_report.xml", ], "assets": { "web.assets_backend": [ "report_qweb_encrypt/static/src/js/report/action_manager_report.esm.js", ], }, "external_dependencies": { "python": ["PyPDF2"] # Python third party libraries required for module }, "installable": True, "maintainers": ["kittiu"], }
29.285714
820
2,012
py
PYTHON
15.0
# © 2016 Therp BV <http://therp.nl> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.exceptions import ValidationError from odoo.tests.common import HttpCase class TestReportQwebEncrypt(HttpCase): def test_report_qweb_no_encrypt(self): ctx = {"force_report_rendering": True} report = self.env.ref("web.action_report_internalpreview") report.encrypt = False pdf, _ = report.with_context(**ctx)._render_qweb_pdf([1]) self.assertFalse(pdf.count(b"/Encrypt")) def test_report_qweb_auto_encrypt(self): ctx = {"force_report_rendering": True} report = self.env.ref("web.action_report_internalpreview") report.encrypt = "auto" report.encrypt_password = False # If no encrypt_password, still not encrypted pdf, _ = report.with_context(**ctx)._render_qweb_pdf([1]) self.assertFalse(pdf.count(b"/Encrypt")) # If invalid encrypt_password, show error report.encrypt_password = "invalid python syntax" with self.assertRaises(ValidationError): pdf, _ = report.with_context(**ctx)._render_qweb_pdf([1]) # Valid python string for password report.encrypt_password = "'secretcode'" pdf, _ = report.with_context(**ctx)._render_qweb_pdf([1]) self.assertTrue(pdf.count(b"/Encrypt")) def test_report_qweb_manual_encrypt(self): ctx = {"force_report_rendering": True} report = self.env.ref("web.action_report_internalpreview") report.encrypt = "manual" # If no encrypt_password, still not encrypted pdf, _ = report.with_context(**ctx)._render_qweb_pdf([1]) self.assertFalse(pdf.count(b"/Encrypt")) # Valid python string for password ctx.update({"encrypt_password": "secretcode"}) pdf, _ = report.with_context(**ctx)._render_qweb_pdf([1]) self.assertTrue(pdf.count(b"/Encrypt")) # TODO: test_report_qweb_manual_encrypt, require JS test?
41.040816
2,011
2,938
py
PYTHON
15.0
# Copyright 2020 Creu Blanca # Copyright 2020 Ecosoft Co., Ltd. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from io import BytesIO from PyPDF2 import PdfFileReader, PdfFileWriter from odoo import _, fields, models from odoo.exceptions import ValidationError from odoo.tools.safe_eval import safe_eval class IrActionsReport(models.Model): _inherit = "ir.actions.report" encrypt = fields.Selection( [("manual", "Manual Input Password"), ("auto", "Auto Generated Password")], string="Encryption", help="* Manual Input Password: allow user to key in password on the fly. " "This option available only on document print action.\n" "* Auto Generated Password: system will auto encrypt password when PDF " "created, based on provided python syntax.", ) encrypt_password = fields.Char( help="Python code syntax to gnerate password.", ) def _render_qweb_pdf(self, res_ids=None, data=None): document, ttype = super(IrActionsReport, self)._render_qweb_pdf( res_ids=res_ids, data=data ) if res_ids: password = self._get_pdf_password(res_ids[:1]) document = self._encrypt_pdf(document, password) return document, ttype def _get_pdf_password(self, res_ids): encrypt_password = False if self.encrypt == "manual": # If use document print action, report_download() is called, # but that can't pass context (encrypt_password) here. # As such, file will be encrypted by report_download() again. # -- # Following is used just in case when context is passed in. encrypt_password = self._context.get("encrypt_password", False) elif self.encrypt == "auto" and self.encrypt_password: # access the report details with sudo() but evaluation context as sudo(False) self_sudo = self.sudo() Model = self.env[self_sudo.model] record_ids = Model.browse(res_ids) try: encrypt_password = safe_eval( self.encrypt_password, {"object": record_ids} ) except Exception as e: raise ValidationError( _("Python code used for encryption password is invalid.\n%s") % self.encrypt_password ) from e return encrypt_password @staticmethod def _encrypt_pdf(data, password): if not password: return data output_pdf = PdfFileWriter() in_buff = BytesIO(data) pdf = PdfFileReader(in_buff) output_pdf.appendPagesFromReader(pdf) output_pdf.encrypt(password) buff = BytesIO() output_pdf.write(buff) return buff.getvalue() def _get_readable_fields(self): return super()._get_readable_fields() | {"encrypt"}
38.155844
2,938
1,583
py
PYTHON
15.0
# Copyright 2020 Creu Blanca # Copyright 2020 Ecosoft Co., Ltd. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import json from werkzeug.urls import url_decode from odoo.http import request, route from odoo.addons.web.controllers import main as report class ReportController(report.ReportController): @route() def report_download(self, data, context=None): result = super(ReportController, self).report_download(data, context=context) # When report is downloaded from print action, this function is called, # but this function cannot pass context (manually entered password) to # report.render_qweb_pdf(), encrypton for manual password is done here. requestcontent = json.loads(data) url, ttype = requestcontent[0], requestcontent[1] if ( ttype in ["qweb-pdf"] and result.headers["Content-Type"] == "application/pdf" and "?" in url ): data = dict( url_decode(url.split("?")[1]).items() ) # decoding the args represented in JSON if "context" in data: context, data_context = json.loads(context or "{}"), json.loads( data.pop("context") ) if "encrypt_password" in data_context: encrypted_data = request.env["ir.actions.report"]._encrypt_pdf( result.get_data(), data_context["encrypt_password"] ) result.set_data(encrypted_data) return result
40.589744
1,583
624
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Board Eval Context", "summary": "Add some keys to board.board eval context", "version": "15.0.1.0.0", "author": "Camptocamp, Odoo Community Association (OCA)", "maintainer": "gurneyalex", "depends": [ "board", ], "category": "Extra Tools", "website": "https://github.com/OCA/reporting-engine", "installable": True, "auto_install": False, "license": "AGPL-3", "application": False, "development_status": "Alpha", "maintainers": ["gurneyalex"], }
31.2
624
1,596
py
PYTHON
15.0
# Copyright 2021-2023 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import datetime from dateutil.relativedelta import relativedelta from odoo import api, models from odoo.tools.safe_eval import safe_eval class Board(models.AbstractModel): _inherit = "board.board" def _get_eval_context(self): """Prepare the context used when evaluating python code :returns: dict -- evaluation context given to safe_eval """ return { "datetime": datetime.datetime, "date": datetime.date, "timedelta": datetime.timedelta, "timezone": datetime.timezone, "tzinfo": datetime.tzinfo, "relativedelta": relativedelta, "uid": self.env.uid, } @api.model def _arch_preprocessing(self, arch): # keeping it inside the method as in the # original code, for perf reason at startup from lxml import etree arch = super()._arch_preprocessing(arch) eval_context = self._get_eval_context() def fix_domain(node): for child in node.iterchildren(): if child.tag == "action" and child.get("domain"): domain = safe_eval(child.get("domain"), eval_context) child.set("domain", str(domain)) else: fix_domain(child) return node archnode = etree.fromstring(arch) archnode = fix_domain(archnode) return etree.tostring(archnode, pretty_print=True, encoding="unicode")
33.25
1,596
773
py
PYTHON
15.0
# Copyright (C) 2015 Akretion (<http://www.akretion.com>) # @author: Florian da Costa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "SQL Export", "version": "15.0.1.0.0", "author": "Akretion,Odoo Community Association (OCA)", "website": "https://github.com/OCA/reporting-engine", "license": "AGPL-3", "category": "Generic Modules/Others", "summary": "Export data in csv file with SQL requests", "depends": [ "sql_request_abstract", ], "data": [ "views/sql_export_view.xml", "wizard/wizard_file_view.xml", "security/sql_export_security.xml", "security/ir.model.access.csv", ], "demo": [ "demo/sql_export.xml", ], "installable": True, }
29.730769
773
2,699
py
PYTHON
15.0
# Copyright (C) 2015 Akretion (<http://www.akretion.com>) # @author: Florian da Costa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import base64 from odoo import fields from odoo.exceptions import UserError from odoo.tests.common import TransactionCase, tagged @tagged("post_install", "-at_install") class TestExportSqlQuery(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.sql_export_obj = cls.env["sql.export"] cls.wizard_obj = cls.env["sql.file.wizard"] cls.sql_report_demo = cls.env.ref("sql_export.sql_export_partner") def test_sql_query(self): wizard = self.wizard_obj.create( { "sql_export_id": self.sql_report_demo.id, } ) wizard.export_sql() export = base64.b64decode(wizard.binary_file).decode("utf-8") self.assertEqual(export.split(";")[0], "name") self.assertTrue(len(export.split(";")) > 6) def test_prohibited_queries(self): prohibited_queries = [ "upDaTe res_partner SET name = 'test' WHERE id = 1", "DELETE FROM sql_export WHERE name = 'test';", " DELETE FROM sql_export WHERE name = 'test' ;", """DELETE FROM sql_export WHERE name = 'test' """, ] for query in prohibited_queries: with self.assertRaises(UserError): sql_export = self.sql_export_obj.create( {"name": "test_prohibited", "query": query} ) sql_export.button_validate_sql_expression() def test_authorized_queries(self): authorized_queries = [ "SELECT create_date FROM res_partner", ] for query in authorized_queries: sql_export = self.sql_export_obj.create( {"name": "test_authorized", "query": query} ) sql_export.button_validate_sql_expression() self.assertEqual( sql_export.state, "sql_valid", "%s is a valid request" % (query) ) def test_sql_query_with_params(self): query = self.env.ref("sql_export.sql_export_partner_with_variables") categ_id = self.env.ref("base.res_partner_category_0").id wizard = self.wizard_obj.create( { "sql_export_id": query.id, "x_date": fields.Date.today(), "x_id": 1, "x_partner_categ_ids": [(6, 0, [categ_id])], } ) wizard.export_sql() export = base64.b64decode(wizard.binary_file) self.assertTrue(export)
35.051948
2,699
4,037
py
PYTHON
15.0
# Copyright (C) 2015 Akretion (<http://www.akretion.com>) # @author: Florian da Costa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import json from datetime import datetime from lxml import etree from odoo import api, fields, models from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT class SqlFileWizard(models.TransientModel): _name = "sql.file.wizard" _description = "Allow the user to save the file with sql request's data" binary_file = fields.Binary("File", readonly=True) file_name = fields.Char(readonly=True) sql_export_id = fields.Many2one(comodel_name="sql.export", required=True) @api.model def fields_view_get( self, view_id=None, view_type="form", toolbar=False, submenu=False ): """ Display dynamically parameter fields depending on the sql_export. """ res = super(SqlFileWizard, self).fields_view_get( view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu ) export_obj = self.env["sql.export"] if view_type == "form": sql_export = export_obj.browse(self.env.context.get("active_id")) if sql_export.field_ids: eview = etree.fromstring(res["arch"]) group = etree.Element("group", name="variables_group", colspan="4") toupdate_fields = [] for field in sql_export.field_ids: toupdate_fields.append(field.name) attrib = {"name": field.name, "required": "0", "readonly": "0"} view_field = etree.SubElement(group, "field", attrib=attrib) modifiers = json.loads(view_field.get("modifiers", "{}")) if field.required: modifiers["required"] = True view_field.set("modifiers", json.dumps(modifiers)) res["fields"].update(self.fields_get(toupdate_fields)) placeholder = eview.xpath( "//separator[@string='variables_placeholder']" )[0] placeholder.getparent().replace(placeholder, group) res["arch"] = etree.tostring(eview, pretty_print=True) return res def export_sql(self): self.ensure_one() sql_export = self.sql_export_id # Manage Params variable_dict = {} now_tz = fields.Datetime.context_timestamp(sql_export, datetime.now()) date = now_tz.strftime(DEFAULT_SERVER_DATETIME_FORMAT) if sql_export.field_ids: for field in sql_export.field_ids: if field.ttype == "many2one": variable_dict[field.name] = self[field.name].id elif field.ttype == "many2many": variable_dict[field.name] = tuple(self[field.name].ids) else: variable_dict[field.name] = self[field.name] if "%(company_id)s" in sql_export.query: company_id = self.env.company.id variable_dict["company_id"] = company_id if "%(user_id)s" in sql_export.query: user_id = self.env.user.id variable_dict["user_id"] = user_id # Call different method depending on file_type since the logic will be # different method_name = "%s_get_data_from_query" % sql_export.file_format data = getattr(sql_export, method_name)(variable_dict) extension = sql_export._get_file_extension() self.write( { "binary_file": data, "file_name": "%(name)s_%(date)s.%(extension)s" % {"name": sql_export.name, "date": date, "extension": extension}, } ) return { "view_mode": "form", "res_model": "sql.file.wizard", "res_id": self.id, "type": "ir.actions.act_window", "target": "new", "context": self.env.context, "nodestroy": True, }
40.777778
4,037
3,432
py
PYTHON
15.0
# Copyright (C) 2015 Akretion (<http://www.akretion.com>) # @author: Florian da Costa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class SqlExport(models.Model): _name = "sql.export" _inherit = ["sql.request.mixin"] _description = "SQL export" _sql_request_groups_relation = "groups_sqlquery_rel" _sql_request_users_relation = "users_sqlquery_rel" _check_execution_enabled = False copy_options = fields.Char(required=False, default="CSV HEADER DELIMITER ';'") file_format = fields.Selection([("csv", "CSV")], default="csv", required=True) field_ids = fields.Many2many( "ir.model.fields", "fields_sqlquery_rel", "sql_id", "field_id", "Parameters", domain=[("model", "=", "sql.file.wizard"), ("state", "=", "manual")], help="Before adding parameters, make sure you have created one that fill your " "need in the dedicated menu with the right type and label. \n" "Then, when you add a parameter here, you have to include it in the SQL " "query in order to have dynamic values depending on the user choice.\n" "The format of the parameters in the SQL query must be like this :" " %(parameter_field_name)s. \n" "Example : from the variable menu, create an variable with type 'char', " "having field name 'x_name' and field label : 'Name' \n" "Then, you can create a SQL query like this : " "SELECT * FROM res_partner WHERE name = %(x_name)s the variable " "can be used in any number of different SQL queries. \n" "In the SQL query, you can also include these 2 special parameters " "%(user_id)s and %(company_id)s which will be replaced respectively by " "the user executing the query and the company of the user executing the" " query.", ) encoding = fields.Selection( [ ("utf-8", "utf-8"), ("utf-16", "utf-16"), ("windows-1252", "windows-1252"), ("latin1", "latin1"), ("latin2", "latin2"), ("big5", "big5"), ("gb18030", "gb18030"), ("shift_jis", "shift_jis"), ("windows-1251", "windows-1251"), ("koir8_r", "koir8_r"), ], required=True, default="utf-8", ) def export_sql_query(self): self.ensure_one() wiz = self.env["sql.file.wizard"].create({"sql_export_id": self.id}) # no variable input, we can return the file directly if not self.field_ids: return wiz.export_sql() else: return { "view_mode": "form", "res_model": "sql.file.wizard", "res_id": wiz.id, "type": "ir.actions.act_window", "target": "new", "context": self.env.context, "nodestroy": True, } def _get_file_extension(self): self.ensure_one() if self.file_format == "csv": return "csv" def csv_get_data_from_query(self, variable_dict): self.ensure_one() # Execute Request res = self._execute_sql_request( params=variable_dict, mode="stdout", copy_options=self.copy_options ) if self.encoding: res = res.decode(self.encoding) return res
36.903226
3,432
701
py
PYTHON
15.0
# Copyright 2017 Avoin.Systems # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). # noinspection PyStatementEffect { "name": "Report Wkhtmltopdf Param", "version": "15.0.1.0.0", "license": "AGPL-3", "summary": """ Add new parameters for a paper format to be used by wkhtmltopdf command as arguments. """, "author": "Avoin.Systems, Eficent, Odoo Community Association (OCA)", "website": "https://github.com/OCA/reporting-engine", "category": "Technical Settings", "depends": ["web"], "data": ["security/ir.model.access.csv", "views/paperformat.xml"], "installable": True, "auto_install": False, "application": False, }
33.380952
701
1,257
py
PYTHON
15.0
# Copyright 2017 Avoin.Systems # Copyright 2017 Eficent Business and IT Consulting Services, S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import odoo.tests from odoo.exceptions import ValidationError from odoo.tests.common import tagged @tagged("post_install", "-at_install") class TestWkhtmltopdf(odoo.tests.TransactionCase): def test_wkhtmltopdf_incorrect_parameter(self): for report_paperformat in self.env["report.paperformat"].search([]): with self.assertRaises(ValidationError): report_paperformat.update( {"custom_params": [(0, 0, {"name": "bad-parameter"})]} ) def test_wkhtmltopdf_valid_parameter(self): for report_paperformat in self.env["report.paperformat"].search([]): error = False try: report_paperformat.update( {"custom_params": [(0, 0, {"name": "--disable-smart-shrinking"})]} ) except ValidationError: error = True self.assertEqual( error, False, "There was an error adding wkhtmltopdf " "parameter --disable-smart-shrinking", )
38.090909
1,257
543
py
PYTHON
15.0
# Copyright 2017 Avoin.Systems # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class ReportPaperformatParameter(models.Model): _name = "report.paperformat.parameter" _description = "wkhtmltopdf parameters" paperformat_id = fields.Many2one( "report.paperformat", "Paper Format", required=True, ) name = fields.Char( required=True, help="The command argument name. Remember to add prefix -- or -", ) value = fields.Char()
24.681818
543
1,362
py
PYTHON
15.0
# Copyright 2017 Avoin.Systems # Copyright 2017 Eficent Business and IT Consulting Services, S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import logging from odoo import _, api, fields, models from odoo.exceptions import ValidationError _logger = logging.getLogger(__name__) class Paper(models.Model): _inherit = "report.paperformat" custom_params = fields.One2many( "report.paperformat.parameter", "paperformat_id", "Custom Parameters", help="Custom Parameters passed forward as wkhtmltopdf command arguments", ) @api.constrains("custom_params") def _check_recursion(self): for paperformat in self: sample_html = """ <!DOCTYPE html> <html style="height: 0;"> <body> <div> <span itemprop="name">Hello World!</span> </div> </body> </html> """ report = self.env["ir.actions.report"].new( {"paperformat_id": paperformat.id} ) content = report._run_wkhtmltopdf(sample_html) if not content: raise ValidationError( _("Failed to create a PDF using the provided parameters.") )
31.674419
1,362
894
py
PYTHON
15.0
# Copyright 2017 Avoin.Systems # Copyright 2017 Eficent Business and IT Consulting Services, S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class IrActionsReport(models.Model): _inherit = "ir.actions.report" @api.model def _build_wkhtmltopdf_args( self, paperformat_id, landscape, specific_paperformat_args=None, set_viewport_size=False, ): # noinspection PyUnresolvedReferences,PyProtectedMember command_args = super(IrActionsReport, self)._build_wkhtmltopdf_args( paperformat_id, landscape, specific_paperformat_args, set_viewport_size ) for param in paperformat_id.custom_params: command_args.extend([param.name]) if param.value: command_args.extend([param.value]) return command_args
30.827586
894
818
py
PYTHON
15.0
# © 2016 Therp BV <http://therp.nl> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Pdf watermark", "version": "15.0.1.0.0", "author": "Therp BV, " "Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Technical Settings", "development_status": "Production/Stable", "summary": "Add watermarks to your QWEB PDF reports", "website": "https://github.com/OCA/reporting-engine", "depends": ["web"], "data": [ "demo/report.xml", "views/ir_actions_report_xml.xml", "views/res_company.xml", ], "assets": { "web.report_assets_pdf": [ "/report_qweb_pdf_watermark/static/src/css/report_qweb_pdf_watermark.css" ], }, "demo": ["demo/report.xml"], "installable": True, }
32.68
817
1,996
py
PYTHON
15.0
# © 2016 Therp BV <http://therp.nl> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from PIL import Image from odoo.tests.common import HttpCase class TestReportQwebPdfWatermark(HttpCase): def test_report_qweb_pdf_watermark(self): Image.init() # with our image, we have three self._test_report_images(3) self.env.ref("report_qweb_pdf_watermark.demo_report").write( {"pdf_watermark_expression": False} ) # without, we have two self._test_report_images(2) self.env.ref("report_qweb_pdf_watermark.demo_report").write( {"pdf_watermark": self.env.user.company_id.logo} ) # and now we should have three again self._test_report_images(3) # test use company watermark self.env.ref("report_qweb_pdf_watermark.demo_report").write( {"pdf_watermark": False} ) self.env.ref("report_qweb_pdf_watermark.demo_report").write( {"use_company_watermark": True} ) self.env.ref("base.main_company").write( {"pdf_watermark": self.env.user.company_id.logo} ) self._test_report_images(3) def _test_report_images(self, number): report = self.env.ref("report_qweb_pdf_watermark.demo_report") pdf, _ = report.with_context(force_report_rendering=True)._render_qweb_pdf( self.env["res.users"].search([]).ids ) self.assertEqual(pdf.count(b"/Subtype /Image"), number) def test_pdf_has_usable_pages(self): # test 0 numpages = 0 # pdf_has_usable_pages(self, pdf_watermark) self.assertFalse(self.env["ir.actions.report"].pdf_has_usable_pages(numpages)) # test 1 numpages = 1 self.assertTrue(self.env["ir.actions.report"].pdf_has_usable_pages(numpages)) # test 2 numpages = 2 self.assertTrue(self.env["ir.actions.report"].pdf_has_usable_pages(numpages))
36.272727
1,995
265
py
PYTHON
15.0
# Copyright 2022 360 ERP (<https://www.360erp.nl>) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import fields, models class ResCompany(models.Model): _inherit = "res.company" pdf_watermark = fields.Binary("Watermark")
26.5
265
4,668
py
PYTHON
15.0
# © 2016 Therp BV <http://therp.nl> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from base64 import b64decode from io import BytesIO from logging import getLogger from PIL import Image from odoo import api, fields, models from odoo.tools.safe_eval import safe_eval logger = getLogger(__name__) try: # we need this to be sure PIL has loaded PDF support from PIL import PdfImagePlugin # noqa: F401 except ImportError: logger.error("ImportError: The PdfImagePlugin could not be imported") try: from PyPDF2 import PdfFileReader, PdfFileWriter # pylint: disable=W0404 from PyPDF2.utils import PdfReadError # pylint: disable=W0404 except ImportError: logger.debug("Can not import PyPDF2") class Report(models.Model): _inherit = "ir.actions.report" use_company_watermark = fields.Boolean( default=False, help="Use the pdf watermark defined globally in the company settings.", ) pdf_watermark = fields.Binary( "Watermark", help="Upload an pdf file to use as an watermark on this report." ) pdf_watermark_expression = fields.Char( "Watermark expression", help="An expression yielding the base64 " "encoded data to be used as watermark. \n" "You have access to variables `env` and `docs`", ) def _render_qweb_pdf(self, res_ids=None, data=None): if not self.env.context.get("res_ids"): return super(Report, self.with_context(res_ids=res_ids))._render_qweb_pdf( res_ids=res_ids, data=data ) return super(Report, self)._render_qweb_pdf(res_ids=res_ids, data=data) def pdf_has_usable_pages(self, numpages): if numpages < 1: logger.error("Your watermark pdf does not contain any pages") return False if numpages > 1: logger.debug( "Your watermark pdf contains more than one page, " "all but the first one will be ignored" ) return True @api.model def _run_wkhtmltopdf( self, bodies, header=None, footer=None, landscape=False, specific_paperformat_args=None, set_viewport_size=False, ): result = super(Report, self)._run_wkhtmltopdf( bodies, header=header, footer=footer, landscape=landscape, specific_paperformat_args=specific_paperformat_args, set_viewport_size=set_viewport_size, ) docids = self.env.context.get("res_ids", False) watermark = None if self.pdf_watermark: watermark = b64decode(self.pdf_watermark) elif self.use_company_watermark and self.env.company.pdf_watermark: watermark = b64decode(self.env.company.pdf_watermark) elif docids: watermark = safe_eval( self.pdf_watermark_expression or "None", dict(env=self.env, docs=self.env[self.model].browse(docids)), ) if watermark: watermark = b64decode(watermark) if not watermark: return result pdf = PdfFileWriter() pdf_watermark = None try: pdf_watermark = PdfFileReader(BytesIO(watermark)) except PdfReadError: # let's see if we can convert this with pillow try: Image.init() image = Image.open(BytesIO(watermark)) pdf_buffer = BytesIO() if image.mode != "RGB": image = image.convert("RGB") resolution = image.info.get("dpi", self.paperformat_id.dpi or 90) if isinstance(resolution, tuple): resolution = resolution[0] image.save(pdf_buffer, "pdf", resolution=resolution) pdf_watermark = PdfFileReader(pdf_buffer) except Exception as e: logger.exception("Failed to load watermark", e) if not pdf_watermark: logger.error("No usable watermark found, got %s...", watermark[:100]) return result if not self.pdf_has_usable_pages(pdf_watermark.numPages): return result for page in PdfFileReader(BytesIO(result)).pages: watermark_page = pdf.addBlankPage( page.mediaBox.getWidth(), page.mediaBox.getHeight() ) watermark_page.mergePage(pdf_watermark.getPage(0)) watermark_page.mergePage(page) pdf_content = BytesIO() pdf.write(pdf_content) return pdf_content.getvalue()
34.57037
4,667
765
py
PYTHON
15.0
# Copyright 2015 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Base report xlsx", "summary": "Base module to create xlsx report", "author": "ACSONE SA/NV," "Creu Blanca," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/reporting-engine", "category": "Reporting", "version": "15.0.1.1.3", "development_status": "Mature", "license": "AGPL-3", "external_dependencies": {"python": ["xlsxwriter", "xlrd"]}, "depends": ["base", "web"], "demo": ["demo/report.xml"], "installable": True, "assets": { "web.assets_backend": [ "report_xlsx/static/src/js/report/action_manager_report.esm.js", ], }, }
36.428571
765
2,271
py
PYTHON
15.0
# Copyright 2017 Creu Blanca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import logging from odoo.tests import common _logger = logging.getLogger(__name__) try: from xlrd import open_workbook except ImportError: _logger.debug("Can not import xlrd`.") class TestReport(common.TransactionCase): def setUp(self): super().setUp() report_object = self.env["ir.actions.report"] self.xlsx_report = self.env["report.report_xlsx.abstract"].with_context( active_model="res.partner" ) self.report_name = "report_xlsx.partner_xlsx" self.report = report_object._get_report_from_name(self.report_name) self.docs = self.env["res.company"].search([], limit=1).partner_id def test_report(self): report = self.report self.assertEqual(report.report_type, "xlsx") rep = report._render(self.docs.ids, {}) wb = open_workbook(file_contents=rep[0]) sheet = wb.sheet_by_index(0) self.assertEqual(sheet.cell(0, 0).value, self.docs.name) def test_id_retrieval(self): # Typical call from WebUI with wizard objs = self.xlsx_report._get_objs_for_report( False, {"context": {"active_ids": self.docs.ids}} ) self.assertEqual(objs, self.docs) # Typical call from within code not to report_action objs = self.xlsx_report.with_context( active_ids=self.docs.ids )._get_objs_for_report(False, False) self.assertEqual(objs, self.docs) # Typical call from WebUI objs = self.xlsx_report._get_objs_for_report( self.docs.ids, {"data": [self.report_name, self.report.report_type]} ) self.assertEqual(objs, self.docs) # Typical call from render objs = self.xlsx_report._get_objs_for_report(self.docs.ids, {}) self.assertEqual(objs, self.docs) def test_currency_format(self): usd = self.env.ref("base.USD") self.assertEqual( self.xlsx_report._report_xlsx_currency_format(usd), "$#,##0.00" ) eur = self.env.ref("base.EUR") self.assertEqual( self.xlsx_report._report_xlsx_currency_format(eur), "#,##0.00 €" )
33.865672
2,269
1,358
py
PYTHON
15.0
# Copyright 2015 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import UserError class ReportAction(models.Model): _inherit = "ir.actions.report" report_type = fields.Selection( selection_add=[("xlsx", "XLSX")], ondelete={"xlsx": "set default"} ) @api.model def _render_xlsx(self, docids, data): report_model_name = "report.%s" % self.report_name report_model = self.env.get(report_model_name) if report_model is None: raise UserError(_("%s model was not found") % report_model_name) return ( report_model.with_context(active_model=self.model) .sudo(False) .create_xlsx_report(docids, data) # noqa ) @api.model def _get_report_from_name(self, report_name): res = super(ReportAction, self)._get_report_from_name(report_name) if res: return res report_obj = self.env["ir.actions.report"] qwebtypes = ["xlsx"] conditions = [ ("report_type", "in", qwebtypes), ("report_name", "=", report_name), ] context = self.env["res.users"].context_get() return report_obj.with_context(**context).search(conditions, limit=1)
34.820513
1,358
555
py
PYTHON
15.0
# Copyright 2017 Creu Blanca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import models class PartnerXlsx(models.AbstractModel): _name = "report.report_xlsx.partner_xlsx" _inherit = "report.report_xlsx.abstract" _description = "Partner XLSX Report" def generate_xlsx_report(self, workbook, data, partners): sheet = workbook.add_worksheet("Report") for i, obj in enumerate(partners): bold = workbook.add_format({"bold": True}) sheet.write(i, 0, obj.name, bold)
34.6875
555
5,198
py
PYTHON
15.0
# Copyright 2015 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import logging import re from io import BytesIO from odoo import models _logger = logging.getLogger(__name__) try: import xlsxwriter class PatchedXlsxWorkbook(xlsxwriter.Workbook): def _check_sheetname(self, sheetname, is_chartsheet=False): """We want to avoid duplicated sheet names exceptions the same following the same philosophy that Odoo implements overriding the main library to avoid the 31 characters limit triming the strings before sending them to the library. In some cases, there's not much control over this as the reports send automated data and the potential exception is hidden underneath making it hard to debug the original issue. Even so, different names can become the same one as their strings are trimmed to those 31 character limit. This way, once we come across with a duplicated, we set that final 3 characters with a sequence that we evaluate on the fly. So for instance: - 'Sheet name' will be 'Sheet name~01' - The next 'Sheet name' will try to rename to 'Sheet name~01' as well and then that will give us 'Sheet name~02'. - And the next 'Sheet name' will try to rename to 'Sheet name~01' and then to 'Sheet name~02' and finally it will be able to 'Sheet name~03'. - An so on as many times as duplicated sheet names come to the workbook up to 100 for each sheet name. We set such limit as we don't want to truncate the strings too much and keeping in mind that this issue don't usually ocurrs. """ try: return super()._check_sheetname(sheetname, is_chartsheet=is_chartsheet) except xlsxwriter.exceptions.DuplicateWorksheetName: pattern = re.compile(r"~[0-9]{2}$") duplicated_secuence = ( re.search(pattern, sheetname) and int(sheetname[-2:]) or 0 ) # Only up to 100 duplicates deduplicated_secuence = "~{:02d}".format(duplicated_secuence + 1) if duplicated_secuence > 99: raise xlsxwriter.exceptions.DuplicateWorksheetName # noqa: B904 if duplicated_secuence: sheetname = re.sub(pattern, deduplicated_secuence, sheetname) elif len(sheetname) <= 28: sheetname += deduplicated_secuence else: sheetname = sheetname[:28] + deduplicated_secuence # Refeed the method until we get an unduplicated name return self._check_sheetname(sheetname, is_chartsheet=is_chartsheet) # "Short string" xlsxwriter.Workbook = PatchedXlsxWorkbook except ImportError: _logger.debug("Can not import xlsxwriter`.") class ReportXlsxAbstract(models.AbstractModel): _name = "report.report_xlsx.abstract" _description = "Abstract XLSX Report" def _get_objs_for_report(self, docids, data): """ Returns objects for xlx report. From WebUI these are either as docids taken from context.active_ids or in the case of wizard are in data. Manual calls may rely on regular context, setting docids, or setting data. :param docids: list of integers, typically provided by qwebactionmanager for regular Models. :param data: dictionary of data, if present typically provided by qwebactionmanager for TransientModels. :param ids: list of integers, provided by overrides. :return: recordset of active model for ids. """ if docids: ids = docids elif data and "context" in data: ids = data["context"].get("active_ids", []) else: ids = self.env.context.get("active_ids", []) return self.env[self.env.context.get("active_model")].browse(ids) def _report_xlsx_currency_format(self, currency): """Get the format to be used in cells (symbol included). Used in account_financial_report addon""" s_before = currency.symbol if currency.position == "before" else "" s_after = " %s" % currency.symbol if currency.position == "after" else "" return f"{f'{s_before}'}#,##0.{'0' * currency.decimal_places}{f'{s_after}'}" def create_xlsx_report(self, docids, data): objs = self._get_objs_for_report(docids, data) file_data = BytesIO() workbook = xlsxwriter.Workbook(file_data, self.get_workbook_options()) self.generate_xlsx_report(workbook, data, objs) workbook.close() file_data.seek(0) return file_data.read(), "xlsx" def get_workbook_options(self): """ See https://xlsxwriter.readthedocs.io/workbook.html constructor options :return: A dictionary of options """ return {} def generate_xlsx_report(self, workbook, data, objs): raise NotImplementedError()
44.050847
5,198
4,303
py
PYTHON
15.0
# Copyright (C) 2017 Creu Blanca # Copyright 2021 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnuorg/licenses/agpl.html). import json import logging from werkzeug.urls import url_decode from odoo.http import ( content_disposition, request, route, serialize_exception as _serialize_exception, ) from odoo.tools import html_escape from odoo.tools.safe_eval import safe_eval, time from odoo.addons.web.controllers import main as report _logger = logging.getLogger(__name__) class ReportController(report.ReportController): @route() def report_routes(self, reportname, docids=None, converter=None, **data): if converter == "xlsx": report = request.env["ir.actions.report"]._get_report_from_name(reportname) context = dict(request.env.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"): data["context"] = json.loads(data["context"]) context.update(data["context"]) xlsx = report.with_context(**context)._render_xlsx(docids, data=data)[0] xlsxhttpheaders = [ ( "Content-Type", "application/vnd.openxmlformats-" "officedocument.spreadsheetml.sheet", ), ("Content-Length", len(xlsx)), ] return request.make_response(xlsx, headers=xlsxhttpheaders) return super(ReportController, self).report_routes( reportname, docids, converter, **data ) @route() def report_download(self, data, context=None): requestcontent = json.loads(data) url, report_type = requestcontent[0], requestcontent[1] if report_type == "xlsx": reportname = url try: reportname = url.split("/report/xlsx/")[1].split("?")[0] docids = None if "/" in reportname: reportname, docids = reportname.split("/") if docids: # Generic report: response = self.report_routes( reportname, docids=docids, converter="xlsx", context=context ) else: # Particular report: data = dict( url_decode(url.split("?")[1]).items() ) # decoding the args represented in JSON if "context" in data: context, data_context = json.loads(context or "{}"), json.loads( data.pop("context") ) context = json.dumps({**context, **data_context}) response = self.report_routes( reportname, converter="xlsx", context=context, **data ) report = request.env["ir.actions.report"]._get_report_from_name( reportname ) filename = "%s.%s" % (report.name, "xlsx") if docids: ids = [int(x) for x in docids.split(",")] obj = request.env[report.model].browse(ids) if report.print_report_name and not len(obj) > 1: report_name = safe_eval( report.print_report_name, {"object": obj, "time": time} ) filename = "%s.%s" % (report_name, "xlsx") if not response.headers.get("Content-Disposition"): response.headers.add( "Content-Disposition", content_disposition(filename) ) return response except Exception as e: _logger.exception("Error while generating report %s", reportname) se = _serialize_exception(e) error = {"code": 200, "message": "Odoo Server Error", "data": se} return request.make_response(html_escape(json.dumps(error))) return super(ReportController, self).report_download(data, context)
41.375
4,303
477
py
PYTHON
15.0
# Copyright 2015 Agile Business Group # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Report Qweb Element Page Visibility", "version": "15.0.1.0.2", "author": "Agile Business Group, Odoo Community Association (OCA)", "category": "Tools", "website": "https://github.com/OCA/reporting-engine", "license": "AGPL-3", "application": False, "installable": True, "data": ["views/layouts.xml"], "depends": ["web"], }
31.8
477
426
py
PYTHON
15.0
# Copyright 2009-2019 Noviat. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Report xlsx helpers", "author": "Noviat, Odoo Community Association (OCA)", "website": "https://github.com/OCA/reporting-engine", "category": "Reporting", "version": "15.0.1.0.1", "license": "AGPL-3", "depends": ["report_xlsx"], "development_status": "Mature", "installable": True, }
30.428571
426
890
py
PYTHON
15.0
# Copyright 2009-2019 Noviat. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from datetime import date from odoo.tests.common import TransactionCase class TestReportXlsxHelper(TransactionCase): def setUp(self): super(TestReportXlsxHelper, self).setUp() today = date.today() p1 = self.env.ref("base.res_partner_1") p2 = self.env.ref("base.res_partner_2") p1.date = today p2.date = today self.partners = p1 + p2 ctx = { "report_name": "report_xlsx_helper.test_partner_xlsx", "active_model": "res.partner", "active_ids": self.partners.ids, } self.report = self.env["ir.actions.report"].with_context(**ctx) def test_report_xlsx_helper(self): report_xls = self.report._render_xlsx(None, None) self.assertEqual(report_xls[1], "xlsx")
32.962963
890
739
py
PYTHON
15.0
# Copyright 2009-2018 Noviat. # License AGPL-3.0 or later (https://www.gnuorg/licenses/agpl.html). from odoo import _, api, models from odoo.exceptions import UserError class IrActionsReport(models.Model): _inherit = "ir.actions.report" @api.model def _render_xlsx(self, docids, data): if not self and self.env.context.get("report_name"): report_model_name = "report.{}".format(self.env.context["report_name"]) report_model = self.env.get(report_model_name) if report_model is None: raise UserError(_("%s model was not found") % report_model_name) return report_model.create_xlsx_report(docids, data) return super()._render_xlsx(docids, data)
38.894737
739
35,530
py
PYTHON
15.0
# Copyright 2009-2018 Noviat. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import re from datetime import date, datetime from types import CodeType from xlsxwriter.utility import xl_rowcol_to_cell from odoo import _, fields, models from odoo.exceptions import UserError from .report_xlsx_format import FORMATS, XLS_HEADERS class ReportXlsxAbstract(models.AbstractModel): _inherit = "report.report_xlsx.abstract" def generate_xlsx_report(self, workbook, data, objects): self._define_formats(workbook) for ws_params in self._get_ws_params(workbook, data, objects): ws_name = ws_params.get("ws_name") ws_name = self._check_ws_name(ws_name) ws = workbook.add_worksheet(ws_name) generate_ws_method = getattr(self, ws_params["generate_ws_method"]) generate_ws_method(workbook, ws, ws_params, data, objects) def _check_ws_name(self, name, sanitize=True): pattern = re.compile(r"[/\\*\[\]:?]") # invalid characters: /\*[]:? max_chars = 31 if sanitize: # we could drop these two lines since a similar # sanitize is done in tools.misc PatchedXlsxWorkbook name = pattern.sub("", name) name = name[:max_chars] else: if len(name) > max_chars: raise UserError( _( "Programming Error:\n\n" "Excel Sheet name '%(name)s' should not exceed %(max_chars)s " "characters." ) % {"name": name, "max_chars": max_chars} ) special_chars = pattern.findall(name) if special_chars: raise UserError( _( "Programming Error:\n\n" "Excel Sheet name '%(name)s' contains unsupported special " "characters: '%(special_chars)s'." ) % {"name": name, "special_chars": special_chars} ) return name def _get_ws_params(self, workbook, data, objects): """ Return list of dictionaries with parameters for the worksheets. Keywords: - 'generate_ws_method': mandatory - 'ws_name': name of the worksheet - 'title': title of the worksheet - 'wanted_list': list of column names - 'col_specs': cf. XXX The 'generate_ws_method' must be present in your report and contain the logic to generate the content of the worksheet. """ return [] def _define_xls_headers(self, workbook): """ Predefined worksheet headers/footers. """ hf_params = { "font_size": 8, "font_style": "I", # B: Bold, I: Italic, U: Underline } XLS_HEADERS["xls_headers"] = {"standard": ""} report_date = fields.Datetime.context_timestamp( self.env.user, datetime.now() ).strftime("%Y-%m-%d %H:%M") XLS_HEADERS["xls_footers"] = { "standard": ( "&L&%(font_size)s&%(font_style)s" + report_date + "&R&%(font_size)s&%(font_style)s&P / &N" ) % hf_params } def _define_formats(self, workbook): """ This section contains a number of pre-defined formats. It is recommended to use these in order to have a consistent look & feel between your XLSX reports. """ self._define_xls_headers(workbook) border_grey = "#D3D3D3" border = {"border": True, "border_color": border_grey} theader = dict(border, bold=True) bg_grey = "#CCCCCC" bg_yellow = "#FFFFCC" bg_blue = "#CCFFFF" num_format = "#,##0.00" num_format_conditional = "{0};[Red]-{0};{0}".format(num_format) pct_format = "#,##0.00%" pct_format_conditional = "{0};[Red]-{0};{0}".format(pct_format) int_format = "#,##0" int_format_conditional = "{0};[Red]-{0};{0}".format(int_format) date_format = "YYYY-MM-DD" theader_grey = dict(theader, bg_color=bg_grey) theader_yellow = dict(theader, bg_color=bg_yellow) theader_blue = dict(theader, bg_color=bg_blue) # format for worksheet title FORMATS["format_ws_title"] = workbook.add_format( {"bold": True, "font_size": 14} ) # no border formats FORMATS["format_left"] = workbook.add_format({"align": "left"}) FORMATS["format_center"] = workbook.add_format({"align": "center"}) FORMATS["format_right"] = workbook.add_format({"align": "right"}) FORMATS["format_amount_left"] = workbook.add_format( {"align": "left", "num_format": num_format} ) FORMATS["format_amount_center"] = workbook.add_format( {"align": "center", "num_format": num_format} ) FORMATS["format_amount_right"] = workbook.add_format( {"align": "right", "num_format": num_format} ) FORMATS["format_amount_conditional_left"] = workbook.add_format( {"align": "left", "num_format": num_format_conditional} ) FORMATS["format_amount_conditional_center"] = workbook.add_format( {"align": "center", "num_format": num_format_conditional} ) FORMATS["format_amount_conditional_right"] = workbook.add_format( {"align": "right", "num_format": num_format_conditional} ) FORMATS["format_percent_left"] = workbook.add_format( {"align": "left", "num_format": pct_format} ) FORMATS["format_percent_center"] = workbook.add_format( {"align": "center", "num_format": pct_format} ) FORMATS["format_percent_right"] = workbook.add_format( {"align": "right", "num_format": pct_format} ) FORMATS["format_percent_conditional_left"] = workbook.add_format( {"align": "left", "num_format": pct_format_conditional} ) FORMATS["format_percent_conditional_center"] = workbook.add_format( {"align": "center", "num_format": pct_format_conditional} ) FORMATS["format_percent_conditional_right"] = workbook.add_format( {"align": "right", "num_format": pct_format_conditional} ) FORMATS["format_integer_left"] = workbook.add_format( {"align": "left", "num_format": int_format} ) FORMATS["format_integer_center"] = workbook.add_format( {"align": "center", "num_format": int_format} ) FORMATS["format_integer_right"] = workbook.add_format( {"align": "right", "num_format": int_format} ) FORMATS["format_integer_conditional_left"] = workbook.add_format( {"align": "right", "num_format": int_format_conditional} ) FORMATS["format_integer_conditional_center"] = workbook.add_format( {"align": "center", "num_format": int_format_conditional} ) FORMATS["format_integer_conditional_right"] = workbook.add_format( {"align": "right", "num_format": int_format_conditional} ) FORMATS["format_date_left"] = workbook.add_format( {"align": "left", "num_format": date_format} ) FORMATS["format_date_center"] = workbook.add_format( {"align": "center", "num_format": date_format} ) FORMATS["format_date_right"] = workbook.add_format( {"align": "right", "num_format": date_format} ) FORMATS["format_left_bold"] = workbook.add_format( {"align": "left", "bold": True} ) FORMATS["format_center_bold"] = workbook.add_format( {"align": "center", "bold": True} ) FORMATS["format_right_bold"] = workbook.add_format( {"align": "right", "bold": True} ) FORMATS["format_amount_left_bold"] = workbook.add_format( {"align": "left", "bold": True, "num_format": num_format} ) FORMATS["format_amount_center_bold"] = workbook.add_format( {"align": "center", "bold": True, "num_format": num_format} ) FORMATS["format_amount_right_bold"] = workbook.add_format( {"align": "right", "bold": True, "num_format": num_format} ) FORMATS["format_amount_conditional_left_bold"] = workbook.add_format( {"align": "left", "bold": True, "num_format": num_format_conditional} ) FORMATS["format_amount_conditional_center_bold"] = workbook.add_format( {"align": "center", "bold": True, "num_format": num_format_conditional} ) FORMATS["format_amount_conditional_right_bold"] = workbook.add_format( {"align": "right", "bold": True, "num_format": num_format_conditional} ) FORMATS["format_percent_left_bold"] = workbook.add_format( {"align": "left", "bold": True, "num_format": pct_format} ) FORMATS["format_percent_center_bold"] = workbook.add_format( {"align": "center", "bold": True, "num_format": pct_format} ) FORMATS["format_percent_right_bold"] = workbook.add_format( {"align": "right", "bold": True, "num_format": pct_format} ) FORMATS["format_percent_conditional_left_bold"] = workbook.add_format( {"align": "left", "bold": True, "num_format": pct_format_conditional} ) FORMATS["format_percent_conditional_center_bold"] = workbook.add_format( {"align": "center", "bold": True, "num_format": pct_format_conditional} ) FORMATS["format_percent_conditional_right_bold"] = workbook.add_format( {"align": "right", "bold": True, "num_format": pct_format_conditional} ) FORMATS["format_integer_left_bold"] = workbook.add_format( {"align": "left", "bold": True, "num_format": int_format} ) FORMATS["format_integer_center_bold"] = workbook.add_format( {"align": "center", "bold": True, "num_format": int_format} ) FORMATS["format_integer_right_bold"] = workbook.add_format( {"align": "right", "bold": True, "num_format": int_format} ) FORMATS["format_integer_conditional_left_bold"] = workbook.add_format( {"align": "left", "bold": True, "num_format": int_format_conditional} ) FORMATS["format_integer_conditional_center_bold"] = workbook.add_format( {"align": "center", "bold": True, "num_format": int_format_conditional} ) FORMATS["format_integer_conditional_right_bold"] = workbook.add_format( {"align": "right", "bold": True, "num_format": int_format_conditional} ) FORMATS["format_date_left_bold"] = workbook.add_format( {"align": "left", "bold": True, "num_format": date_format} ) FORMATS["format_date_center_bold"] = workbook.add_format( {"align": "center", "bold": True, "num_format": date_format} ) FORMATS["format_date_right_bold"] = workbook.add_format( {"align": "right", "bold": True, "num_format": date_format} ) # formats for worksheet table column headers FORMATS["format_theader_grey_left"] = workbook.add_format(theader_grey) FORMATS["format_theader_grey_center"] = workbook.add_format( dict(theader_grey, align="center") ) FORMATS["format_theader_grey_right"] = workbook.add_format( dict(theader_grey, align="right") ) FORMATS["format_theader_grey_amount_left"] = workbook.add_format( dict(theader_grey, num_format=num_format, align="left") ) FORMATS["format_theader_grey_amount_center"] = workbook.add_format( dict(theader_grey, num_format=num_format, align="center") ) FORMATS["format_theader_grey_amount_right"] = workbook.add_format( dict(theader_grey, num_format=num_format, align="right") ) FORMATS["format_theader_grey_amount_conditional_left"] = workbook.add_format( dict(theader_grey, num_format=num_format_conditional, align="left") ) FORMATS["format_theader_grey_amount_conditional_center"] = workbook.add_format( dict(theader_grey, num_format=num_format_conditional, align="center") ) FORMATS["format_theader_grey_amount_conditional_right"] = workbook.add_format( dict(theader_grey, num_format=num_format_conditional, align="right") ) FORMATS["format_theader_grey_percent_left"] = workbook.add_format( dict(theader_grey, num_format=pct_format, align="left") ) FORMATS["format_theader_grey_percent_center"] = workbook.add_format( dict(theader_grey, num_format=pct_format, align="center") ) FORMATS["format_theader_grey_percent_right"] = workbook.add_format( dict(theader_grey, num_format=pct_format, align="right") ) FORMATS["format_theader_grey_percent_conditional_left"] = workbook.add_format( dict(theader_grey, num_format=pct_format_conditional, align="left") ) FORMATS["format_theader_grey_percent_conditional_center"] = workbook.add_format( dict(theader_grey, num_format=pct_format_conditional, align="center") ) FORMATS["format_theader_grey_percent_conditional_right"] = workbook.add_format( dict(theader_grey, num_format=pct_format_conditional, align="right") ) FORMATS["format_theader_grey_integer_left"] = workbook.add_format( dict(theader_grey, num_format=int_format, align="left") ) FORMATS["format_theader_grey_integer_center"] = workbook.add_format( dict(theader_grey, num_format=int_format, align="center") ) FORMATS["format_theader_grey_integer_right"] = workbook.add_format( dict(theader_grey, num_format=int_format, align="right") ) FORMATS["format_theader_grey_integer_conditional_left"] = workbook.add_format( dict(theader_grey, num_format=int_format_conditional, align="left") ) FORMATS["format_theader_grey_integer_conditional_center"] = workbook.add_format( dict(theader_grey, num_format=int_format_conditional, align="center") ) FORMATS["format_theader_grey_integer_conditional_right"] = workbook.add_format( dict(theader_grey, num_format=int_format_conditional, align="right") ) FORMATS["format_theader_yellow_left"] = workbook.add_format(theader_yellow) FORMATS["format_theader_yellow_center"] = workbook.add_format( dict(theader_yellow, align="center") ) FORMATS["format_theader_yellow_right"] = workbook.add_format( dict(theader_yellow, align="right") ) FORMATS["format_theader_yellow_amount_left"] = workbook.add_format( dict(theader_yellow, num_format=num_format, align="left") ) FORMATS["format_theader_yellow_amount_center"] = workbook.add_format( dict(theader_yellow, num_format=num_format, align="center") ) FORMATS["format_theader_yellow_amount_right"] = workbook.add_format( dict(theader_yellow, num_format=num_format, align="right") ) FORMATS["format_theader_yellow_amount_conditional_left"] = workbook.add_format( dict(theader_yellow, num_format=num_format_conditional, align="left") ) FORMATS[ "format_theader_yellow_amount_conditional_center" ] = workbook.add_format( dict(theader_yellow, num_format=num_format_conditional, align="center") ) FORMATS["format_theader_yellow_amount_conditional_right"] = workbook.add_format( dict(theader_yellow, num_format=num_format_conditional, align="right") ) FORMATS["format_theader_yellow_percent_left"] = workbook.add_format( dict(theader_yellow, num_format=pct_format, align="left") ) FORMATS["format_theader_yellow_percent_center"] = workbook.add_format( dict(theader_yellow, num_format=pct_format, align="center") ) FORMATS["format_theader_yellow_percent_right"] = workbook.add_format( dict(theader_yellow, num_format=pct_format, align="right") ) FORMATS["format_theader_yellow_percent_conditional_left"] = workbook.add_format( dict(theader_yellow, num_format=pct_format_conditional, align="left") ) FORMATS[ "format_theader_yellow_percent_conditional_center" ] = workbook.add_format( dict(theader_yellow, num_format=pct_format_conditional, align="center") ) FORMATS[ "format_theader_yellow_percent_conditional_right" ] = workbook.add_format( dict(theader_yellow, num_format=pct_format_conditional, align="right") ) FORMATS["format_theader_yellow_integer_left"] = workbook.add_format( dict(theader_yellow, num_format=int_format, align="left") ) FORMATS["format_theader_yellow_integer_center"] = workbook.add_format( dict(theader_yellow, num_format=int_format, align="center") ) FORMATS["format_theader_yellow_integer_right"] = workbook.add_format( dict(theader_yellow, num_format=int_format, align="right") ) FORMATS["format_theader_yellow_integer_conditional_left"] = workbook.add_format( dict(theader_yellow, num_format=int_format_conditional, align="left") ) FORMATS[ "format_theader_yellow_integer_conditional_center" ] = workbook.add_format( dict(theader_yellow, num_format=int_format_conditional, align="center") ) FORMATS[ "format_theader_yellow_integer_conditional_right" ] = workbook.add_format( dict(theader_yellow, num_format=int_format_conditional, align="right") ) FORMATS["format_theader_blue_left"] = workbook.add_format(theader_blue) FORMATS["format_theader_blue_center"] = workbook.add_format( dict(theader_blue, align="center") ) FORMATS["format_theader_blue_right"] = workbook.add_format( dict(theader_blue, align="right") ) FORMATS["format_theader_blue_amount_left"] = workbook.add_format( dict(theader_blue, num_format=num_format, align="left") ) FORMATS["format_theader_blue_amount_center"] = workbook.add_format( dict(theader_blue, num_format=num_format, align="center") ) FORMATS["format_theader_blue_amount_right"] = workbook.add_format( dict(theader_blue, num_format=num_format, align="right") ) FORMATS["format_theader_blue_amount_conditional_left"] = workbook.add_format( dict(theader_blue, num_format=num_format_conditional, align="left") ) FORMATS["format_theader_blue_amount_conditional_center"] = workbook.add_format( dict(theader_blue, num_format=num_format_conditional, align="center") ) FORMATS["format_theader_blue_amount_conditional_right"] = workbook.add_format( dict(theader_blue, num_format=num_format_conditional, align="right") ) FORMATS["format_theader_blue_percent_left"] = workbook.add_format( dict(theader_blue, num_format=pct_format, align="left") ) FORMATS["format_theader_blue_percent_center"] = workbook.add_format( dict(theader_blue, num_format=pct_format, align="center") ) FORMATS["format_theader_blue_percent_right"] = workbook.add_format( dict(theader_blue, num_format=pct_format, align="right") ) FORMATS["format_theader_blue_percent_conditional_left"] = workbook.add_format( dict(theader_blue, num_format=pct_format_conditional, align="left") ) FORMATS["format_theader_blue_percent_conditional_center"] = workbook.add_format( dict(theader_blue, num_format=pct_format_conditional, align="center") ) FORMATS["format_theader_blue_percent_conditional_right"] = workbook.add_format( dict(theader_blue, num_format=pct_format_conditional, align="right") ) FORMATS["format_theader_blue_integer_left"] = workbook.add_format( dict(theader_blue, num_format=int_format, align="left") ) FORMATS["format_theader_blue_integer_center"] = workbook.add_format( dict(theader_blue, num_format=int_format, align="center") ) FORMATS["format_theader_blue_integer_right"] = workbook.add_format( dict(theader_blue, num_format=int_format, align="right") ) FORMATS["format_theader_blue_integer_conditional_left"] = workbook.add_format( dict(theader_blue, num_format=int_format_conditional, align="left") ) FORMATS["format_theader_blue_integer_conditional_center"] = workbook.add_format( dict(theader_blue, num_format=int_format_conditional, align="center") ) FORMATS["format_theader_blue_integer_conditional_right"] = workbook.add_format( dict(theader_blue, num_format=int_format_conditional, align="right") ) # formats for worksheet table cells FORMATS["format_tcell_left"] = workbook.add_format(dict(border, align="left")) FORMATS["format_tcell_center"] = workbook.add_format( dict(border, align="center") ) FORMATS["format_tcell_right"] = workbook.add_format(dict(border, align="right")) FORMATS["format_tcell_amount_left"] = workbook.add_format( dict(border, num_format=num_format, align="left") ) FORMATS["format_tcell_amount_center"] = workbook.add_format( dict(border, num_format=num_format, align="center") ) FORMATS["format_tcell_amount_right"] = workbook.add_format( dict(border, num_format=num_format, align="right") ) FORMATS["format_tcell_amount_conditional_left"] = workbook.add_format( dict(border, num_format=num_format_conditional, align="left") ) FORMATS["format_tcell_amount_conditional_center"] = workbook.add_format( dict(border, num_format=num_format_conditional, align="center") ) FORMATS["format_tcell_amount_conditional_right"] = workbook.add_format( dict(border, num_format=num_format_conditional, align="right") ) FORMATS["format_tcell_percent_left"] = workbook.add_format( dict(border, num_format=pct_format, align="left") ) FORMATS["format_tcell_percent_center"] = workbook.add_format( dict(border, num_format=pct_format, align="center") ) FORMATS["format_tcell_percent_right"] = workbook.add_format( dict(border, num_format=pct_format, align="right") ) FORMATS["format_tcell_percent_conditional_left"] = workbook.add_format( dict(border, num_format=pct_format_conditional, align="left") ) FORMATS["format_tcell_percent_conditional_center"] = workbook.add_format( dict(border, num_format=pct_format_conditional, align="center") ) FORMATS["format_tcell_percent_conditional_right"] = workbook.add_format( dict(border, num_format=pct_format_conditional, align="right") ) FORMATS["format_tcell_integer_left"] = workbook.add_format( dict(border, num_format=int_format, align="left") ) FORMATS["format_tcell_integer_center"] = workbook.add_format( dict(border, num_format=int_format, align="center") ) FORMATS["format_tcell_integer_right"] = workbook.add_format( dict(border, num_format=int_format, align="right") ) FORMATS["format_tcell_integer_conditional_left"] = workbook.add_format( dict(border, num_format=int_format_conditional, align="left") ) FORMATS["format_tcell_integer_conditional_center"] = workbook.add_format( dict(border, num_format=int_format_conditional, align="center") ) FORMATS["format_tcell_integer_conditional_right"] = workbook.add_format( dict(border, num_format=int_format_conditional, align="right") ) FORMATS["format_tcell_date_left"] = workbook.add_format( dict(border, num_format=date_format, align="left") ) FORMATS["format_tcell_date_center"] = workbook.add_format( dict(border, num_format=date_format, align="center") ) FORMATS["format_tcell_date_right"] = workbook.add_format( dict(border, num_format=date_format, align="right") ) FORMATS["format_tcell_left_bold"] = workbook.add_format( dict(border, align="left", bold=True) ) FORMATS["format_tcell_center_bold"] = workbook.add_format( dict(border, align="center", bold=True) ) FORMATS["format_tcell_right_bold"] = workbook.add_format( dict(border, align="right", bold=True) ) FORMATS["format_tcell_amount_left_bold"] = workbook.add_format( dict(border, num_format=num_format, align="left", bold=True) ) FORMATS["format_tcell_amount_center_bold"] = workbook.add_format( dict(border, num_format=num_format, align="center", bold=True) ) FORMATS["format_tcell_amount_right_bold"] = workbook.add_format( dict(border, num_format=num_format, align="right", bold=True) ) FORMATS["format_tcell_amount_conditional_left_bold"] = workbook.add_format( dict(border, num_format=num_format_conditional, align="left", bold=True) ) FORMATS["format_tcell_amount_conditional_center_bold"] = workbook.add_format( dict(border, num_format=num_format_conditional, align="center", bold=True) ) FORMATS["format_tcell_amount_conditional_right_bold"] = workbook.add_format( dict(border, num_format=num_format_conditional, align="right", bold=True) ) FORMATS["format_tcell_percent_left_bold"] = workbook.add_format( dict(border, num_format=pct_format, align="left", bold=True) ) FORMATS["format_tcell_percent_center_bold"] = workbook.add_format( dict(border, num_format=pct_format, align="center", bold=True) ) FORMATS["format_tcell_percent_right_bold"] = workbook.add_format( dict(border, num_format=pct_format, align="right", bold=True) ) FORMATS["format_tcell_percent_conditional_left_bold"] = workbook.add_format( dict(border, num_format=pct_format_conditional, align="left", bold=True) ) FORMATS["format_tcell_percent_conditional_center_bold"] = workbook.add_format( dict(border, num_format=pct_format_conditional, align="center", bold=True) ) FORMATS["format_tcell_percent_conditional_right_bold"] = workbook.add_format( dict(border, num_format=pct_format_conditional, align="right", bold=True) ) FORMATS["format_tcell_integer_left_bold"] = workbook.add_format( dict(border, num_format=int_format, align="left", bold=True) ) FORMATS["format_tcell_integer_center_bold"] = workbook.add_format( dict(border, num_format=int_format, align="center", bold=True) ) FORMATS["format_tcell_integer_right_bold"] = workbook.add_format( dict(border, num_format=int_format, align="right", bold=True) ) FORMATS["format_tcell_integer_conditional_left_bold"] = workbook.add_format( dict(border, num_format=int_format_conditional, align="left", bold=True) ) FORMATS["format_tcell_integer_conditional_center_bold"] = workbook.add_format( dict(border, num_format=int_format_conditional, align="center", bold=True) ) FORMATS["format_tcell_integer_conditional_right_bold"] = workbook.add_format( dict(border, num_format=int_format_conditional, align="right", bold=True) ) FORMATS["format_tcell_date_left_bold"] = workbook.add_format( dict(border, num_format=date_format, align="left", bold=True) ) FORMATS["format_tcell_date_center_bold"] = workbook.add_format( dict(border, num_format=date_format, align="center", bold=True) ) FORMATS["format_tcell_date_right_bold"] = workbook.add_format( dict(border, num_format=date_format, align="right", bold=True) ) def _set_column_width(self, ws, ws_params): """ Set width for all columns included in the 'wanted_list'. """ col_specs = ws_params.get("col_specs") wl = ws_params.get("wanted_list") or [] for pos, col in enumerate(wl): if col not in col_specs: raise UserError( _( "Programming Error:\n\n" "The '%s' column is not defined in the worksheet " "column specifications." ) % col ) ws.set_column(pos, pos, col_specs[col]["width"]) def _write_ws_title(self, ws, row_pos, ws_params, merge_range=False): """ Helper function to ensure consistent title formats troughout all worksheets. Requires 'title' keyword in ws_params. """ title = ws_params.get("title") if not title: raise UserError( _( "Programming Error:\n\n" "The 'title' parameter is mandatory " "when calling the '_write_ws_title' method." ) ) if merge_range: wl = ws_params.get("wanted_list") if wl and len(wl) > 1: ws.merge_range( row_pos, 0, row_pos, len(wl) - 1, title, FORMATS["format_ws_title"] ) else: ws.write_string(row_pos, 0, title, FORMATS["format_ws_title"]) return row_pos + 2 def _write_line( self, ws, row_pos, ws_params, col_specs_section=None, render_space=None, default_format=None, col_specs="col_specs", wanted_list="wanted_list", ): """ Write a line with all columns included in the 'wanted_list'. Use the entry defined by the col_specs_section. An empty cell will be written if no col_specs_section entry for a column. """ col_specs = ws_params.get(col_specs) wl = ws_params.get(wanted_list) or [] pos = 0 for col in wl: if col not in col_specs: raise UserError( _( "Programming Error:\n\n" "The '%s' column is not defined the worksheet " "column specifications." ) % col ) colspan = col_specs[col].get("colspan") or 1 cell_spec = col_specs[col].get(col_specs_section) or {} if not cell_spec: cell_value = None cell_type = "blank" cell_format = default_format else: cell_value = cell_spec.get("value") if isinstance(cell_value, CodeType): cell_value = self._eval(cell_value, render_space) cell_type = cell_spec.get("type") cell_format = cell_spec.get("format") or default_format if not cell_type: # test bool first since isinstance(val, int) returns # True when type(val) is bool if isinstance(cell_value, bool): cell_type = "boolean" elif isinstance(cell_value, str): cell_type = "string" elif isinstance(cell_value, (int, float)): cell_type = "number" elif isinstance(cell_value, datetime): cell_type = "datetime" elif isinstance(cell_value, date): cell_value = datetime.combine(cell_value, datetime.min.time()) cell_type = "datetime" else: if not cell_value: cell_type = "blank" else: msg = _( "%(__name__)s, _write_line : programming error " "detected while processing " "col_specs_section %(col_specs_section)s, column %(col)s" ) % { "__name__": __name__, "col_specs_section": col_specs_section, "col": col, } if cell_value: msg += _(", cellvalue %s") % cell_value raise UserError(msg) colspan = cell_spec.get("colspan") or colspan args_pos = [row_pos, pos] args_data = [cell_value] if cell_format: if isinstance(cell_format, CodeType): cell_format = self._eval(cell_format, render_space) args_data.append(cell_format) self._apply_formula_quirk(args_data, cell_type, cell_format) if colspan > 1: args_pos += [row_pos, pos + colspan - 1] args = args_pos + args_data ws.merge_range(*args) else: ws_method = getattr(ws, "write_%s" % cell_type) args = args_pos + args_data ws_method(*args) pos += colspan return row_pos + 1 @staticmethod def _apply_formula_quirk(args_data, cell_type, cell_format): """Insert empty value to force LibreOffice to recompute the value""" if cell_type == "formula": if not cell_format: # Insert positional argument for missing format args_data.append(None) args_data.append("") @staticmethod def _render(code): return compile(code, "<string>", "eval") @staticmethod def _eval(val, render_space): if not render_space: render_space = {} if "datetime" not in render_space: render_space["datetime"] = datetime # the use of eval is not a security thread as long as the # col_specs template is defined in a python module return eval(val, render_space) # pylint: disable=W0123,W8112 @staticmethod def _rowcol_to_cell(row, col, row_abs=False, col_abs=False): return xl_rowcol_to_cell(row, col, row_abs=row_abs, col_abs=col_abs)
46.202861
35,530
7,581
py
PYTHON
15.0
# Global Formatting XLS_HEADERS = {"xls_headers": "", "xls_footers": ""} FORMATS = { "format_ws_title": False, "format_left": False, "format_center": False, "format_right": False, "format_amount_left": False, "format_amount_center": False, "format_amount_right": False, "format_amount_conditional_left": False, "format_amount_conditional_center": False, "format_amount_conditional_right": False, "format_percent_left": False, "format_percent_center": False, "format_percent_right": False, "format_percent_conditional_left": False, "format_percent_conditional_center": False, "format_percent_conditional_right": False, "format_integer_left": False, "format_integer_center": False, "format_integer_right": False, "format_integer_conditional_left": False, "format_integer_conditional_center": False, "format_integer_conditional_right": False, "format_date_left": False, "format_date_center": False, "format_date_right": False, "format_left_bold": False, "format_center_bold": False, "format_right_bold": False, "format_amount_left_bold": False, "format_amount_center_bold": False, "format_amount_right_bold": False, "format_amount_conditional_left_bold": False, "format_amount_conditional_center_bold": False, "format_amount_conditional_right_bold": False, "format_percent_left_bold": False, "format_percent_center_bold": False, "format_percent_right_bold": False, "format_percent_conditional_left_bold": False, "format_percent_conditional_center_bold": False, "format_percent_conditional_right_bold": False, "format_integer_left_bold": False, "format_integer_center_bold": False, "format_integer_right_bold": False, "format_integer_conditional_left_bold": False, "format_integer_conditional_center_bold": False, "format_integer_conditional_right_bold": False, "format_date_left_bold": False, "format_date_center_bold": False, "format_date_right_bold": False, "format_theader_grey_left": False, "format_theader_grey_center": False, "format_theader_grey_right": False, "format_theader_grey_amount_left": False, "format_theader_grey_amount_center": False, "format_theader_grey_amount_right": False, "format_theader_grey_amount_conditional_left": False, "format_theader_grey_amount_conditional_center": False, "format_theader_grey_amount_conditional_right": False, "format_theader_grey_percent_left": False, "format_theader_grey_percent_center": False, "format_theader_grey_percent_right": False, "format_theader_grey_percent_conditional_left": False, "format_theader_grey_percent_conditional_center": False, "format_theader_grey_percent_conditional_right": False, "format_theader_grey_integer_left": False, "format_theader_grey_integer_center": False, "format_theader_grey_integer_right": False, "format_theader_grey_integer_conditional_left": False, "format_theader_grey_integer_conditional_center": False, "format_theader_grey_integer_conditional_right": False, "format_theader_yellow_left": False, "format_theader_yellow_center": False, "format_theader_yellow_right": False, "format_theader_yellow_amount_left": False, "format_theader_yellow_amount_center": False, "format_theader_yellow_amount_right": False, "format_theader_yellow_amount_conditional_left": False, "format_theader_yellow_amount_conditional_center": False, "format_theader_yellow_amount_conditional_right": False, "format_theader_yellow_percent_left": False, "format_theader_yellow_percent_center": False, "format_theader_yellow_percent_right": False, "format_theader_yellow_percent_conditional_left": False, "format_theader_yellow_percent_conditional_center": False, "format_theader_yellow_percent_conditional_right": False, "format_theader_yellow_integer_left": False, "format_theader_yellow_integer_center": False, "format_theader_yellow_integer_right": False, "format_theader_yellow_integer_conditional_left": False, "format_theader_yellow_integer_conditional_center": False, "format_theader_yellow_integer_conditional_right": False, "format_theader_blue_left": False, "format_theader_blue_center": False, "format_theader_blue_right": False, "format_theader_blue_amount_left": False, "format_theader_blue_amount_center": False, "format_theader_blue_amount_right": False, "format_theader_blue_amount_conditional_left": False, "format_theader_blue_amount_conditional_center": False, "format_theader_blue_amount_conditional_right": False, "format_theader_blue_percent_left": False, "format_theader_blue_percent_center": False, "format_theader_blue_percent_right": False, "format_theader_blue_percent_conditional_left": False, "format_theader_blue_percent_conditional_center": False, "format_theader_blue_percent_conditional_right": False, "format_theader_blue_integer_left": False, "format_theader_blue_integer_center": False, "format_theader_blue_integer_right": False, "format_theader_blue_integer_conditional_left": False, "format_theader_blue_integer_conditional_center": False, "format_theader_blue_integer_conditional_right": False, "format_tcell_left": False, "format_tcell_center": False, "format_tcell_right": False, "format_tcell_amount_left": False, "format_tcell_amount_center": False, "format_tcell_amount_right": False, "format_tcell_amount_conditional_left": False, "format_tcell_amount_conditional_center": False, "format_tcell_amount_conditional_right": False, "format_tcell_percent_left": False, "format_tcell_percent_center": False, "format_tcell_percent_right": False, "format_tcell_percent_conditional_left": False, "format_tcell_percent_conditional_center": False, "format_tcell_percent_conditional_right": False, "format_tcell_integer_left": False, "format_tcell_integer_center": False, "format_tcell_integer_right": False, "format_tcell_integer_conditional_left": False, "format_tcell_integer_conditional_center": False, "format_tcell_integer_conditional_right": False, "format_tcell_date_left": False, "format_tcell_date_center": False, "format_tcell_date_right": False, "format_tcell_left_bold": False, "format_tcell_center_bold": False, "format_tcell_right_bold": False, "format_tcell_amount_left_bold": False, "format_tcell_amount_center_bold": False, "format_tcell_amount_right_bold": False, "format_tcell_amount_conditional_left_bold": False, "format_tcell_amount_conditional_center_bold": False, "format_tcell_amount_conditional_right_bold": False, "format_tcell_percent_left_bold": False, "format_tcell_percent_center_bold": False, "format_tcell_percent_right_bold": False, "format_tcell_percent_conditional_left_bold": False, "format_tcell_percent_conditional_center_bold": False, "format_tcell_percent_conditional_right_bold": False, "format_tcell_integer_left_bold": False, "format_tcell_integer_center_bold": False, "format_tcell_integer_right_bold": False, "format_tcell_integer_conditional_left_bold": False, "format_tcell_integer_conditional_center_bold": False, "format_tcell_integer_conditional_right_bold": False, "format_tcell_date_left_bold": False, "format_tcell_date_center_bold": False, "format_tcell_date_right_bold": False, }
46.22561
7,581
2,410
py
PYTHON
15.0
# Copyright 2009-2019 Noviat. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models from .report_xlsx_format import FORMATS, XLS_HEADERS # TODO: # make PR to move this class as well as the report_xlsx test class # to the tests folder (requires dynamic update Odoo registry when # running unit tests. class TestPartnerXlsx(models.AbstractModel): _name = "report.report_xlsx_helper.test_partner_xlsx" _inherit = "report.report_xlsx.abstract" _description = "Test Partner XLSX Report" def _get_ws_params(self, wb, data, partners): partner_template = { "name": { "header": {"value": "Name"}, "data": {"value": self._render("partner.name")}, "width": 20, }, "number_of_contacts": { "header": {"value": "# Contacts"}, "data": {"value": self._render("len(partner.child_ids)")}, "width": 10, }, "date": { "header": {"value": "Date"}, "data": {"value": self._render("partner.date")}, "width": 13, }, } ws_params = { "ws_name": "Partners", "generate_ws_method": "_partner_report", "title": "Partners", "wanted_list": [k for k in partner_template], "col_specs": partner_template, } return [ws_params] def _partner_report(self, workbook, ws, ws_params, data, partners): ws.set_portrait() ws.fit_to_pages(1, 0) ws.set_header(XLS_HEADERS["xls_headers"]["standard"]) ws.set_footer(XLS_HEADERS["xls_footers"]["standard"]) self._set_column_width(ws, ws_params) row_pos = 0 row_pos = self._write_ws_title(ws, row_pos, ws_params) row_pos = self._write_line( ws, row_pos, ws_params, col_specs_section="header", default_format=FORMATS["format_theader_yellow_left"], ) ws.freeze_panes(row_pos, 0) for partner in partners: row_pos = self._write_line( ws, row_pos, ws_params, col_specs_section="data", render_space={"partner": partner}, default_format=FORMATS["format_tcell_left"], )
32.133333
2,410
1,939
py
PYTHON
15.0
# Copyright 2009-2018 Noviat. # License AGPL-3.0 or later (https://www.gnuorg/licenses/agpl.html). import json from odoo.http import content_disposition, request, route from odoo.addons.report_xlsx.controllers.main import ReportController class ReportController(ReportController): @route( [ "/report/<converter>/<reportname>", "/report/<converter>/<reportname>/<docids>", ], type="http", auth="user", website=True, ) def report_routes(self, reportname, docids=None, converter=None, **data): report = request.env["ir.actions.report"]._get_report_from_name(reportname) if converter == "xlsx" and not report: context = dict(request.env.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"): data["context"] = json.loads(data["context"]) context.update(data["context"]) context["report_name"] = reportname xlsx = report.with_context(**context)._render_xlsx(docids, data=data)[0] report_file = context.get("report_file") if not report_file: active_model = context.get("active_model", "export") report_file = active_model.replace(".", "_") xlsxhttpheaders = [ ( "Content-Type", "application/vnd.openxmlformats-" "officedocument.spreadsheetml.sheet", ), ("Content-Length", len(xlsx)), ("Content-Disposition", content_disposition(report_file + ".xlsx")), ] return request.make_response(xlsx, headers=xlsxhttpheaders) return super().report_routes(reportname, docids, converter, **data)
38.78
1,939
615
py
PYTHON
15.0
# Copyright 2019 Creu Blanca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Base report csv", "summary": "Base module to create csv report", "author": "Creu Blanca, Odoo Community Association (OCA)", "website": "https://github.com/OCA/reporting-engine", "category": "Reporting", "version": "15.0.1.0.0", "license": "AGPL-3", "depends": ["base", "web"], "demo": ["demo/report.xml"], "assets": { "web.assets_backend": [ "report_csv/static/src/js/report/qwebactionmanager.esm.js" ] }, "installable": True, }
32.368421
615
1,990
py
PYTHON
15.0
# Copyright 2019 Creu Blanca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import logging from io import StringIO from odoo.tests import common _logger = logging.getLogger(__name__) try: import csv except ImportError: _logger.debug("Can not import csv.") class TestReport(common.TransactionCase): def setUp(self): super().setUp() report_object = self.env["ir.actions.report"] self.csv_report = self.env["report.report_csv.abstract"].with_context( active_model="res.partner" ) self.report_name = "report_csv.partner_csv" self.report = report_object._get_report_from_name(self.report_name) self.docs = self.env["res.company"].search([], limit=1).partner_id def test_report(self): # Test if not res: report = self.report self.assertEqual(report.report_type, "csv") rep = report._render(self.docs.ids, {}) str_io = StringIO(rep[0]) dict_report = list(csv.DictReader(str_io, delimiter=";", quoting=csv.QUOTE_ALL)) self.assertEqual(self.docs.name, dict(dict_report[0])["name"]) def test_id_retrieval(self): # Typical call from WebUI with wizard objs = self.csv_report._get_objs_for_report( False, {"context": {"active_ids": self.docs.ids}} ) self.assertEqual(objs, self.docs) # Typical call from within code not to report_action objs = self.csv_report.with_context( active_ids=self.docs.ids )._get_objs_for_report(False, False) self.assertEqual(objs, self.docs) # Typical call from WebUI objs = self.csv_report._get_objs_for_report( self.docs.ids, {"data": [self.report_name, self.report.report_type]} ) self.assertEqual(objs, self.docs) # Typical call from render objs = self.csv_report._get_objs_for_report(self.docs.ids, {}) self.assertEqual(objs, self.docs)
34.912281
1,990
1,282
py
PYTHON
15.0
# Copyright 2019 Creu Blanca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import UserError class ReportAction(models.Model): _inherit = "ir.actions.report" report_type = fields.Selection( selection_add=[("csv", "csv")], ondelete={"csv": "set default"} ) @api.model def _render_csv(self, docids, data): report_model_name = "report.%s" % self.report_name report_model = self.env.get(report_model_name) if report_model is None: raise UserError(_("%s model was not found") % report_model_name) return report_model.with_context(active_model=self.model).create_csv_report( docids, data ) @api.model def _get_report_from_name(self, report_name): res = super(ReportAction, self)._get_report_from_name(report_name) if res: return res report_obj = self.env["ir.actions.report"] qwebtypes = ["csv"] conditions = [ ("report_type", "in", qwebtypes), ("report_name", "=", report_name), ] context = self.env["res.users"].context_get() return report_obj.with_context(**context).search(conditions, limit=1)
34.648649
1,282
744
py
PYTHON
15.0
# Copyright 2019 Creu Blanca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import csv from odoo import models class PartnerCSV(models.AbstractModel): _name = "report.report_csv.partner_csv" _inherit = "report.report_csv.abstract" _description = "Report Partner to CSV" def generate_csv_report(self, writer, data, partners): writer.writeheader() for obj in partners: writer.writerow({"name": obj.name, "email": obj.email}) def csv_report_options(self): res = super().csv_report_options() res["fieldnames"].append("name") res["fieldnames"].append("email") res["delimiter"] = ";" res["quoting"] = csv.QUOTE_ALL return res
31
744
2,195
py
PYTHON
15.0
# Copyright 2019 Creu Blanca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import logging from io import StringIO from odoo import models _logger = logging.getLogger(__name__) try: import csv except ImportError: _logger.debug("Can not import csvwriter`.") class ReportCSVAbstract(models.AbstractModel): _name = "report.report_csv.abstract" _description = "Abstract Model for CSV reports" def _get_objs_for_report(self, docids, data): """ Returns objects for csv report. From WebUI these are either as docids taken from context.active_ids or in the case of wizard are in data. Manual calls may rely on regular context, setting docids, or setting data. :param docids: list of integers, typically provided by qwebactionmanager for regular Models. :param data: dictionary of data, if present typically provided by qwebactionmanager for TransientModels. :param ids: list of integers, provided by overrides. :return: recordset of active model for ids. """ if docids: ids = docids elif data and "context" in data: ids = data["context"].get("active_ids", []) else: ids = self.env.context.get("active_ids", []) return self.env[self.env.context.get("active_model")].browse(ids) def create_csv_report(self, docids, data): objs = self._get_objs_for_report(docids, data) file_data = StringIO() file = csv.DictWriter(file_data, **self.csv_report_options()) self.generate_csv_report(file, data, objs) file_data.seek(0) return file_data.read(), "csv" def csv_report_options(self): """ :return: dictionary of parameters. At least return 'fieldnames', but you can optionally return parameters that define the export format. Valid parameters include 'delimiter', 'quotechar', 'escapechar', 'doublequote', 'skipinitialspace', 'lineterminator', 'quoting'. """ return {"fieldnames": []} def generate_csv_report(self, file, data, objs): raise NotImplementedError()
35.983607
2,195
4,330
py
PYTHON
15.0
# Copyright (C) 2019 Creu Blanca # License AGPL-3.0 or later (https://www.gnuorg/licenses/agpl.html). import json import logging from werkzeug.urls import url_decode from odoo.http import ( content_disposition, request, route, serialize_exception as _serialize_exception, ) from odoo.tools import html_escape from odoo.tools.safe_eval import safe_eval, time from odoo.addons.web.controllers import main as report _logger = logging.getLogger(__name__) class ReportController(report.ReportController): @route() def report_routes(self, reportname, docids=None, converter=None, **data): if converter == "csv": report = request.env["ir.actions.report"]._get_report_from_name(reportname) context = dict(request.env.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"]) csv = report.with_context(**context)._render_csv(docids, data=data)[0] csvhttpheaders = [ ("Content-Type", "text/csv"), ("Content-Length", len(csv)), ] return request.make_response(csv, headers=csvhttpheaders) return super(ReportController, self).report_routes( reportname, docids, converter, **data ) @route() def report_download(self, data, context=None): requestcontent = json.loads(data) url, report_type = requestcontent[0], requestcontent[1] try: if report_type == "csv": reportname = url.split("/report/csv/")[1].split("?")[0] docids = None if "/" in reportname: reportname, docids = reportname.split("/") if docids: # Generic report: response = self.report_routes( reportname, docids=docids, converter="csv", context=context ) else: # Particular report: data = dict( url_decode(url.split("?")[1]).items() ) # decoding the args represented in JSON if "context" in data: context, data_context = json.loads(context or "{}"), json.loads( data.pop("context") ) context = json.dumps({**context, **data_context}) response = self.report_routes( reportname, converter="csv", context=context, **data ) report = request.env["ir.actions.report"]._get_report_from_name( reportname ) filename = "%s.%s" % (report.name, "csv") if docids: ids = [int(x) for x in docids.split(",")] obj = request.env[report.model].browse(ids) if report.print_report_name and not len(obj) > 1: report_name = safe_eval( report.print_report_name, {"object": obj, "time": time} ) filename = "%s.%s" % (report_name, "csv") response.headers.add( "Content-Disposition", content_disposition(filename) ) return response else: return super(ReportController, self).report_download(data, context) except Exception as e: _logger.exception("Error while generating report %s", reportname) se = _serialize_exception(e) error = {"code": 200, "message": "Odoo Server Error", "data": se} return request.make_response(html_escape(json.dumps(error)))
42.038835
4,330