<commit_before># Copyright 2019-2020 Akretion - <NAME> <<EMAIL>>
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).

import logging

from lxml import etree
from lxml.builder import E
from odoo import models, api
from odoo.osv.orm import setup_modifiers

_logger = logging.getLogger(__name__)

TAB_NAME = "NFe"  # TODO dynamic
FIELD_PREFIX = "nfe40_"
CHOICE_PREFIX = "nfe40_choice"
# TODO use schema name as default root key unless a key is provided in the
#  class


# TODO use MetaModel._get_concrete

class SpecViewMixin(models.AbstractModel):
    _inherit = 'spec.mixin'

    @api.model
    def fields_view_get(self, view_id=None, view_type='form', toolbar=False,
                        submenu=False):
        res = super(SpecViewMixin, self.with_context(no_subcall=True)
                    ).fields_view_get(view_id, view_type, toolbar)
        # _logger.info("+++++++++++++++", self, type(self), self._context)
        if self._context.get('no_subcall'):
            return res
        # TODO collect class ancestors of StackedModel kind and
        # extract the different XSD schemas injected. Then add a tab/page
        # per schema unless context specify some specific schemas.

        # TODO override only if special dev or fiscal group or if spec_class in
        # context
        # TODO allow special XML placeholders to be replaced by proper fragment
        if view_type == 'form':
            doc = etree.XML(res['arch'])
            fields = []
            if len(doc.xpath("//notebook")) > 0:
                arch, fields = self._build_spec_fragment()
                # arch.set("col", "4") TODO ex res.partner
                node = doc.xpath("//notebook")[0]
                page = E.page(string=TAB_NAME)
                page.append(arch)
                node.insert(1000, page)
            elif len(doc.xpath("//sheet")) > 0:
                arch, fields = self._build_spec_fragment()
                node = doc.xpath("//sheet")[0]
                arch.set("string", TAB_NAME)
                arch.set("col", "2")  # TODO ex fleet
                if res['name'] == 'default':
                    # we replace the default view by our own
                    # _logger.info("Defaulttttttt view:")
                    # _logger.info(etree.tostring(node, pretty_print=True).decode())
                    for c in node.getchildren():
                        node.remove(c)
                    arch = arch.getchildren()[0]
                    arch.set("col", "4")
                    node.insert(1000, arch)
                    # _logger.info("Specccccccccc View:")
                    # _logger.info(etree.tostring(node, pretty_print=True).decode())
                else:
                    node.insert(1000, arch)
            elif len(doc.xpath("//form")) > 0:  # ex invoice.line
                arch, fields = self._build_spec_fragment()
                node = doc.xpath("//form")[0]
                arch.set("string", TAB_NAME)
                arch.set("col", "2")
                node.insert(1000, arch)

            # print("VIEW IS NOW:")
            # print(etree.tostring(doc, pretty_print=True).decode())
            for field_name in fields:
                if not self.fields_get().get(field_name):
                    continue
                field = self.fields_get()[field_name]
                if field['type'] in ['one2many', 'many2one']:
                    field['views'] = {}  # no inline views
                res['fields'][field_name] = field
                field_nodes = doc.xpath("//field[@name='%s']" %
                                        (field_name,))
                for field_node in field_nodes:
                    setup_modifiers(field_node, field)

            res['arch'] = etree.tostring(doc)
        return res

    @api.model
    def _build_spec_fragment(self, container=None):
        if container is None:
            container = E.group()

            view_child = E.group()
            view_child.append(E.button(
                name='export_xml',
                type='object',
                string='Export',
            ))

        container.append(view_child)
        fields = []
        if hasattr(type(self), '_stacked') and type(self)._stacked:
            # we want the root of what is stacked to recreate the hierarchy<commit_msg>disable Gabriel debug export_xml button as it breaks views<commit_after># Copyright 2019-2020 Akretion - <NAME> <<EMAIL>>
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).

import logging

from lxml import etree
from lxml.builder import E
from odoo import models, api
from odoo.osv.orm import setup_modifiers

_logger = logging.getLogger(__name__)

TAB_NAME = "NFe"  # TODO dynamic
FIELD_PREFIX = "nfe40_"
CHOICE_PREFIX = "nfe40_choice"
# TODO use schema name as default root key unless a key is provided in the
#  class


# TODO use MetaModel._get_concrete

class SpecViewMixin(models.AbstractModel):
    _inherit = 'spec.mixin'

    @api.model
    def fields_view_get(self, view_id=None, view_type='form', toolbar=False,
                        submenu=False):
        res = super(SpecViewMixin, self.with_context(no_subcall=True)
                    ).fields_view_get(view_id, view_type, toolbar)
        # _logger.info("+++++++++++++++", self, type(self), self._context)
        if self._context.get('no_subcall'):
            return res
        # TODO collect class ancestors of StackedModel kind and
        # extract the different XSD schemas injected. Then add a tab/page
        # per schema unless context specify some specific schemas.

        # TODO override only if special dev or fiscal group or if spec_class in
        # context
        # TODO allow special XML placeholders to be replaced by proper fragment
        if view_type == 'form':
            doc = etree.XML(res['arch'])
            fields = []
            if len(doc.xpath("//notebook")) > 0:
                arch, fields = self._build_spec_fragment()
                # arch.set("col", "4") TODO ex res.partner
                node = doc.xpath("//notebook")[0]
                page = E.page(string=TAB_NAME)
                page.append(arch)
                node.insert(1000, page)
            elif len(doc.xpath("//sheet")) > 0:
                arch, fields = self._build_spec_fragment()
                node = doc.xpath("//sheet")[0]
                arch.set("string", TAB_NAME)
                arch.set("col", "2")  # TODO ex fleet
                if res['name'] == 'default':
                    # we replace the default view by our own
                    # _logger.info("Defaulttttttt view:")
                    # _logger.info(etree.tostring(node, pretty_print=True).decode())
                    for c in node.getchildren():
                        node.remove(c)
                    arch = arch.getchildren()[0]
                    arch.set("col", "4")
                    node.insert(1000, arch)
                    # _logger.info("Specccccccccc View:")
                    # _logger.info(etree.tostring(node, pretty_print=True).decode())
                else:
                    node.insert(1000, arch)
            elif len(doc.xpath("//form")) > 0:  # ex invoice.line
                arch, fields = self._build_spec_fragment()
                node = doc.xpath("//form")[0]
                arch.set("string", TAB_NAME)
                arch.set("col", "2")
                node.insert(1000, arch)

            # print("VIEW IS NOW:")
            # print(etree.tostring(doc, pretty_print=True).decode())
            for field_name in fields:
                if not self.fields_get().get(field_name):
                    continue
                field = self.fields_get()[field_name]
                if field['type'] in ['one2many', 'many2one']:
                    field['views'] = {}  # no inline views
                res['fields'][field_name] = field
                field_nodes = doc.xpath("//field[@name='%s']" %
                                        (field_name,))
                for field_node in field_nodes:
                    setup_modifiers(field_node, field)

            res['arch'] = etree.tostring(doc)
        return res

    @api.model
    def _build_spec_fragment(self, container=None):
        if container is None:
            container = E.group()
#            an export button that can help debug but messes views
#            view_child = E.group()
#            view_child.append(E.button(
#                name='export_xml',
#                type='object',
#                string='Export',
#            ))

#        container.append(view_child)
        fields = []
        if hasattr(type(self), '_stacked') and type(self)._stacked:
            # we want the root of what is stacked to recreate the hierarchy
{'fraction_non_alphanumeric': 0.11470186618115612, 'fraction_numerical': 0.010241238051888939, 'mean_word_length': 1.7673173803526447, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 15, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 7}, 'pii_count': 0, 'substrings_counts': 4, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4923019', 'n_tokens_mistral': 2577, 'n_tokens_neox': 2398, 'n_words': 611}