[IMP] document_page_reference: black, isort, prettier

This commit is contained in:
Jaime Arroyo 2020-09-30 11:43:20 +02:00 committed by Anusha
parent e242bef1f1
commit 3e22a1ea44
7 changed files with 99 additions and 102 deletions

View File

@ -2,21 +2,18 @@
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{ {
'name': 'Document Page Reference', "name": "Document Page Reference",
'summary': """ "summary": """
Include references on document pages""", Include references on document pages""",
'version': '12.0.1.0.0', "version": "12.0.1.0.0",
'license': 'AGPL-3', "license": "AGPL-3",
'author': 'Creu Blanca,Odoo Community Association (OCA)', "author": "Creu Blanca,Odoo Community Association (OCA)",
'website': 'https://github.com/OCA/knowledge', "website": "https://github.com/OCA/knowledge",
'depends': [ "depends": ["document_page", "web_editor"],
'document_page', "data": [
'web_editor', "views/assets.xml",
"views/document_page.xml",
"views/report_document_page.xml",
], ],
'data': [ "maintainers": ["etobella"],
'views/assets.xml',
'views/document_page.xml',
'views/report_document_page.xml',
],
'maintainers': ['etobella'],
} }

View File

@ -1,11 +1,12 @@
# Copyright 2019 Creu Blanca # Copyright 2019 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models, tools, _ import logging
from odoo import _, api, fields, models, tools
from odoo.exceptions import ValidationError from odoo.exceptions import ValidationError
from odoo.tools.misc import html_escape from odoo.tools.misc import html_escape
import logging
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
try: try:
@ -14,14 +15,14 @@ try:
from jinja2.lexer import name_re as old_name_re from jinja2.lexer import name_re as old_name_re
import re import re
name_re = re.compile(u'^%s$' % old_name_re.pattern) name_re = re.compile(u"^%s$" % old_name_re.pattern)
class Context(SandboxedEnvironment.context_class): class Context(SandboxedEnvironment.context_class):
def resolve(self, key): def resolve(self, key):
res = super().resolve(key) res = super().resolve(key)
if not isinstance(res, Undefined): if not isinstance(res, Undefined):
return res return res
return self.parent['ref'](key) return self.parent["ref"](key)
class Environment(SandboxedEnvironment): class Environment(SandboxedEnvironment):
context_class = Context context_class = Context
@ -35,7 +36,7 @@ try:
comment_end_string="</%doc>", comment_end_string="</%doc>",
line_statement_prefix="%", line_statement_prefix="%",
line_comment_prefix="##", line_comment_prefix="##",
trim_blocks=True, # do not output newline after blocks trim_blocks=True, # do not output newline after blocks
autoescape=False, autoescape=False,
) )
except Exception: except Exception:
@ -44,34 +45,33 @@ except Exception:
class DocumentPage(models.Model): class DocumentPage(models.Model):
_inherit = 'document.page' _inherit = "document.page"
reference = fields.Char( reference = fields.Char(
help="Used to find the document, it can contain letters, numbers and _" help="Used to find the document, it can contain letters, numbers and _"
) )
content_parsed = fields.Html(compute='_compute_content_parsed') content_parsed = fields.Html(compute="_compute_content_parsed")
@api.depends('history_head') @api.depends("history_head")
def _compute_content_parsed(self): def _compute_content_parsed(self):
for record in self: for record in self:
record.content_parsed = record.get_content() record.content_parsed = record.get_content()
@api.constrains('reference') @api.constrains("reference")
def _check_reference(self): def _check_reference(self):
for record in self: for record in self:
if not record.reference: if not record.reference:
continue continue
if not name_re.match(record.reference): if not name_re.match(record.reference):
raise ValidationError(_('Reference is not valid')) raise ValidationError(_("Reference is not valid"))
if self.search([ if self.search(
('reference', '=', record.reference), [("reference", "=", record.reference), ("id", "!=", record.id)]
('id', '!=', record.id)]
): ):
raise ValidationError(_('Reference must be unique')) raise ValidationError(_("Reference must be unique"))
def _get_document(self, code): def _get_document(self, code):
# Hook created in order to add check on other models # Hook created in order to add check on other models
document = self.search([('reference', '=', code)]) document = self.search([("reference", "=", code)])
if document: if document:
return document return document
else: else:
@ -79,23 +79,23 @@ class DocumentPage(models.Model):
def get_reference(self, code): def get_reference(self, code):
element = self._get_document(code) element = self._get_document(code)
if self.env.context.get('raw_reference', False): if self.env.context.get("raw_reference", False):
return html_escape(element.display_name) return html_escape(element.display_name)
text = """<a href="#" class="oe_direct_line" text = """<a href="#" class="oe_direct_line"
data-oe-model="%s" data-oe-id="%s" name="%s">%s</a> data-oe-model="%s" data-oe-id="%s" name="%s">%s</a>
""" """
if not element: if not element:
text = '<i>%s</i>' % text text = "<i>%s</i>" % text
res = text % ( res = text % (
element._name, element._name,
element and element.id or '', element and element.id or "",
code, code,
html_escape(element.display_name or code), html_escape(element.display_name or code),
) )
return res return res
def _get_template_variables(self): def _get_template_variables(self):
return {'ref': self.get_reference} return {"ref": self.get_reference}
def get_content(self): def get_content(self):
try: try:
@ -104,8 +104,7 @@ class DocumentPage(models.Model):
template = mako_env.from_string(tools.ustr(content)) template = mako_env.from_string(tools.ustr(content))
return template.render(self._get_template_variables()) return template.render(self._get_template_variables())
except Exception: except Exception:
_logger.error( _logger.error("Template from page %s cannot be processed" % self.id)
'Template from page %s cannot be processed' % self.id)
return self.content return self.content
def get_raw_content(self): def get_raw_content(self):

View File

@ -1,37 +1,36 @@
odoo.define('document_page_reference.backend', function (require) { odoo.define("document_page_reference.backend", function(require) {
'use strict'; "use strict";
var field_registry = require('web.field_registry'); var field_registry = require("web.field_registry");
var backend = require('web_editor.backend'); var backend = require("web_editor.backend");
var FieldTextHtmlSimple = backend.FieldTextHtmlSimple; var FieldTextHtmlSimple = backend.FieldTextHtmlSimple;
var FieldDocumentPage = FieldTextHtmlSimple.extend({ var FieldDocumentPage = FieldTextHtmlSimple.extend({
events: _.extend({}, FieldTextHtmlSimple.prototype.events, { events: _.extend({}, FieldTextHtmlSimple.prototype.events, {
'click .oe_direct_line': '_onClickDirectLink', "click .oe_direct_line": "_onClickDirectLink",
}), }),
_onClickDirectLink: function (event) { _onClickDirectLink: function(event) {
var self = this; var self = this;
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
var element = $(event.target).closest('.oe_direct_line')[0]; var element = $(event.target).closest(".oe_direct_line")[0];
var default_reference = element.name; var default_reference = element.name;
var model = $(event.target).data('oe-model'); var model = $(event.target).data("oe-model");
var id = $(event.target).data('oe-id'); var id = $(event.target).data("oe-id");
var context = this.record.getContext(this.recordParams); var context = this.record.getContext(this.recordParams);
if (default_reference){ if (default_reference) {
context['default_reference'] = default_reference context.default_reference = default_reference;
} }
this._rpc({ this._rpc({
model: model, model: model,
method: 'get_formview_action', method: "get_formview_action",
args: [[parseInt(id)]], args: [[parseInt(id, 10)]],
context: context, context: context,
}) }).then(function(action) {
.then(function (action) { self.trigger_up("do_action", {action: action});
self.trigger_up('do_action', {action: action});
}); });
}, },
}); });
field_registry.add('document_page_reference', FieldDocumentPage); field_registry.add("document_page_reference", FieldDocumentPage);
return FieldDocumentPage; return FieldDocumentPage;
}); });

View File

@ -1,49 +1,41 @@
# Copyright 2019 Creu Blanca # Copyright 2019 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests.common import TransactionCase
from odoo.exceptions import ValidationError from odoo.exceptions import ValidationError
from odoo.tests.common import TransactionCase
class TestDocumentReference(TransactionCase): class TestDocumentReference(TransactionCase):
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.page_obj = self.env['document.page'] self.page_obj = self.env["document.page"]
self.history_obj = self.env['document.page.history'] self.history_obj = self.env["document.page.history"]
self.page1 = self.page_obj.create({ self.page1 = self.page_obj.create(
'name': 'Test Page 1', {"name": "Test Page 1", "content": "${r2}", "reference": "R1"}
'content': '${r2}', )
'reference': 'R1' self.page2 = self.page_obj.create(
}) {"name": "Test Page 1", "content": "${r1}", "reference": "r2"}
self.page2 = self.page_obj.create({ )
'name': 'Test Page 1',
'content': '${r1}',
'reference': 'r2'
})
def test_constrains_01(self): def test_constrains_01(self):
with self.assertRaises(ValidationError): with self.assertRaises(ValidationError):
self.page2.write({'reference': self.page1.reference}) self.page2.write({"reference": self.page1.reference})
def test_constrains_02(self): def test_constrains_02(self):
with self.assertRaises(ValidationError): with self.assertRaises(ValidationError):
self.page2.write({'reference': self.page2.reference + '-02'}) self.page2.write({"reference": self.page2.reference + "-02"})
def test_no_contrains(self): def test_no_contrains(self):
self.page1.write({'reference': False}) self.page1.write({"reference": False})
self.page2.write({'reference': False}) self.page2.write({"reference": False})
self.assertEqual(self.page1.reference, self.page2.reference) self.assertEqual(self.page1.reference, self.page2.reference)
def test_check_raw(self): def test_check_raw(self):
self.assertEqual(self.page2.display_name, self.page1.get_raw_content()) self.assertEqual(self.page2.display_name, self.page1.get_raw_content())
def test_check_reference(self): def test_check_reference(self):
self.assertRegex( self.assertRegex(self.page1.content_parsed, ".*%s.*" % self.page2.display_name)
self.page1.content_parsed,
'.*%s.*' % self.page2.display_name
)
def test_no_reference(self): def test_no_reference(self):
self.page2.reference = 'r3' self.page2.reference = "r3"
self.assertRegex(self.page1.content_parsed, '.*r2.*') self.assertRegex(self.page1.content_parsed, ".*r2.*")

View File

@ -1,8 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8" ?>
<odoo> <odoo>
<template id="assets_backend" name="document_page_reference assets" inherit_id="web_editor.assets_backend"> <template
id="assets_backend"
name="document_page_reference assets"
inherit_id="web_editor.assets_backend"
>
<xpath expr="." position="inside"> <xpath expr="." position="inside">
<script type="text/javascript" src="/document_page_reference/static/src/js/editor.js"></script> <script
type="text/javascript"
src="/document_page_reference/static/src/js/editor.js"
/>
</xpath> </xpath>
</template> </template>
</odoo> </odoo>

View File

@ -1,62 +1,64 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8" ?>
<!-- Copyright 2019 Creu Blanca <!-- Copyright 2019 Creu Blanca
License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). --> License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). -->
<odoo> <odoo>
<record model="ir.ui.view" id="document_page_form_view"> <record model="ir.ui.view" id="document_page_form_view">
<field name="name">document.page.form (in knowledge_reference)</field> <field name="name">document.page.form (in knowledge_reference)</field>
<field name="model">document.page</field> <field name="model">document.page</field>
<field name="inherit_id" ref="document_page.view_wiki_form"/> <field name="inherit_id" ref="document_page.view_wiki_form" />
<field name="arch" type="xml"> <field name="arch" type="xml">
<xpath expr="//h1" position="before"> <xpath expr="//h1" position="before">
<h2> <h2>
<field name="reference" placeholder="internal_reference"/> <field name="reference" placeholder="internal_reference" />
</h2> </h2>
</xpath> </xpath>
<field name="content" position="attributes"> <field name="content" position="attributes">
<attribute name="class">oe_edit_only</attribute> <attribute name="class">oe_edit_only</attribute>
</field> </field>
<field name="content" position="before"> <field name="content" position="before">
<field name="content_parsed" class="oe_read_only" widget="document_page_reference"/> <field
name="content_parsed"
class="oe_read_only"
widget="document_page_reference"
/>
</field> </field>
</field> </field>
</record> </record>
<record id="view_wiki_menu_form" model="ir.ui.view"> <record id="view_wiki_menu_form" model="ir.ui.view">
<field name="name">document.page.menu.form</field> <field name="name">document.page.menu.form</field>
<field name="model">document.page</field> <field name="model">document.page</field>
<field name="inherit_id" ref="document_page.view_wiki_menu_form"/> <field name="inherit_id" ref="document_page.view_wiki_menu_form" />
<field name="arch" type="xml"> <field name="arch" type="xml">
<field name="content" position="attributes"> <field name="content" position="attributes">
<attribute name="invisible">1</attribute> <attribute name="invisible">1</attribute>
</field> </field>
<field name="content" position="before"> <field name="content" position="before">
<field name="content_parsed" class="oe_read_only" widget="document_page_reference"/> <field
name="content_parsed"
class="oe_read_only"
widget="document_page_reference"
/>
</field> </field>
</field> </field>
</record> </record>
<record model="ir.ui.view" id="document_page_search_view"> <record model="ir.ui.view" id="document_page_search_view">
<field name="name">document.page.search (in knowledge_reference)</field> <field name="name">document.page.search (in knowledge_reference)</field>
<field name="model">document.page</field> <field name="model">document.page</field>
<field name="inherit_id" ref="document_page.view_wiki_filter"/> <field name="inherit_id" ref="document_page.view_wiki_filter" />
<field name="arch" type="xml"> <field name="arch" type="xml">
<field name="parent_id" position="before"> <field name="parent_id" position="before">
<field name="reference"/> <field name="reference" />
</field> </field>
</field> </field>
</record> </record>
<record model="ir.ui.view" id="document_page_tree_view"> <record model="ir.ui.view" id="document_page_tree_view">
<field name="name">document.page.tree (in knowledge_reference)</field> <field name="name">document.page.tree (in knowledge_reference)</field>
<field name="model">document.page</field> <field name="model">document.page</field>
<field name="inherit_id" ref="document_page.view_wiki_tree"/> <field name="inherit_id" ref="document_page.view_wiki_tree" />
<field name="arch" type="xml"> <field name="arch" type="xml">
<field name="name" position="before"> <field name="name" position="before">
<field name="reference"/> <field name="reference" />
</field> </field>
</field> </field>
</record> </record>
</odoo> </odoo>

11
document_page_reference/views/report_document_page.xml Executable file → Normal file
View File

@ -1,13 +1,14 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8" ?>
<odoo> <odoo>
<template
<template id="report_documentpage_doc" inherit_id="document_page.report_documentpage_doc"> id="report_documentpage_doc"
inherit_id="document_page.report_documentpage_doc"
>
<xpath expr="//div[@t-raw='doc.content']" position="attributes"> <xpath expr="//div[@t-raw='doc.content']" position="attributes">
<attribute name="t-if">1==0</attribute> <attribute name="t-if">1==0</attribute>
</xpath> </xpath>
<xpath expr="//div[@t-raw='doc.content']" position="after"> <xpath expr="//div[@t-raw='doc.content']" position="after">
<div t-raw="doc.get_raw_content()"/> <div t-raw="doc.get_raw_content()" />
</xpath> </xpath>
</template> </template>
</odoo> </odoo>