<commit_before>import logging
import re
from datetime import datetime

from odoo import api, fields, models, registry
from odoo.exceptions import UserError
from odoo.fields import first
from odoo.tools import float_is_zero
from odoo.tools.translate import _

from odoo.addons.base_iban.models.res_partner_bank import pretty_iban

from . import efattura

_logger = logging.getLogger(__name__)

WT_CODES_MAPPING = {
    "RT01": "ritenuta",
    "RT02": "ritenuta",
    "RT03": "inps",
    "RT04": "enasarco",
    "RT05": "enpam",
    "RT06": "other",
}


class WizardImportFatturapa(models.TransientModel):
    _name = "wizard.import.fatturapa"
    _description = "Import E-bill"

    e_invoice_detail_level = fields.Selection(
        [
            ("0", "Minimum"),
            ("1", "Tax rate"),
            ("2", "Maximum"),
        ],
        string="E-bills Detail Level",
        help="Minimum level: Bill is created with no lines; "
        "User will have to create them, according to what specified in "
        "the electronic bill.\n"
        "Tax rate level: Rate level: an invoice line is created for each "
        "rate present in the electronic invoice\n"
        "Maximum level: every line contained in the electronic bill "
        "will create a line in the bill.",
        required=True,
    )
    price_decimal_digits = fields.Integer(
        "Prices decimal digits",
        required=True,
        help="Decimal digits used in prices computation. This is needed to correctly "
        "import e-invoices with many decimal digits, not being forced to "
        "increase decimal digits of all your prices. "
        'Otherwise, increase "Product Price" precision.',
    )
    quantity_decimal_digits = fields.Integer(
        "Quantities decimal digits",
        required=True,
        help='Decimal digits used for quantity field. See "Prices decimal digits".',
    )
    discount_decimal_digits = fields.Integer(
        "Discounts decimal digits",
        required=True,
        help='Decimal digits used for discount field. See "Prices decimal digits".',
    )

    @api.model
    def default_get(self, fields):
        res = super(WizardImportFatturapa, self).default_get(fields)
        res["price_decimal_digits"] = self.env["decimal.precision"].precision_get(
            "Product Price"
        )
        res["quantity_decimal_digits"] = self.env["decimal.precision"].precision_get(
            "Product Unit of Measure"
        )
        res["discount_decimal_digits"] = self.env["decimal.precision"].precision_get(
            "Discount"
        )
        res["e_invoice_detail_level"] = "2"
        fatturapa_attachment_ids = self.env.context.get("active_ids", False)
        fatturapa_attachment_obj = self.env["fatturapa.attachment.in"]
        partners = self.env["res.partner"]
        for fatturapa_attachment_id in fatturapa_attachment_ids:
            fatturapa_attachment = fatturapa_attachment_obj.browse(
                fatturapa_attachment_id
            )
            if fatturapa_attachment.in_invoice_ids:
                raise UserError(
                    _("File %s is linked to bills yet.") % fatturapa_attachment.name
                )
            partners |= fatturapa_attachment.xml_supplier_id
            if len(partners) == 1:
                res["e_invoice_detail_level"] = partners[0].e_invoice_detail_level
                if partners[0].e_invoice_price_decimal_digits >= 0:
                    res["price_decimal_digits"] = partners[
                        0
                    ].e_invoice_price_decimal_digits
                if partners[0].e_invoice_quantity_decimal_digits >= 0:
                    res["quantity_decimal_digits"] = partners[
                        0
                    ].e_invoice_quantity_decimal_digits
                if partners[0].e_invoice_discount_decimal_digits >= 0:
                    res["discount_decimal_digits"] = partners[
                        0
                    ].e_invoice_discount_decimal_digits
        return res

    def CountryByCode(self, CountryCode):
        country_model = self.env["res.country"]
        return country_model.search([("code", "=", CountryCode)])

    def ProvinceByCode(self, provinceCode):
        province_model = self.env["res.country.state"]
        return province_model.search(
            [("code", "=", provinceCode), ("country_id.code", "=", "IT")]
        )

    def log_inconsistency(self, message):
        inconsistencies = self.env.context.get("inconsistencies", "")
        if inconsistencies:
            inconsistencies += "\n"
        inconsistencies += message
        # convert to dict in order to be able to modify context
        self.env.context = dict(self.env.context)
        self.env.context.update(inconsistencies=inconsistencies)

    def check_partner_base_data(self, partner_id, DatiAnagrafici):
        partner = self.env["res.partner"].browse(partner_id)
        if (
            DatiAnagrafici.Anagrafica.Denominazione
            and partner.name != DatiAnagrafici.Anagrafica.Denominazione
        ):
            self.log_inconsistency(
                _("Company Name field contains '%s'." " Your System contains '%s'")
                % (DatiAnagrafici.Anagrafica.Denominazione, partner.name)
            )
        if (
            DatiAnagrafici.Anagrafica.Nome
            and partner.firstname != DatiAnagrafici.Anagrafica.Nome
        ):
            self.log_inconsistency(
                _("Name field contains '%s'." " Your System contains '%s'")
                % (DatiAnagrafici.Anagrafica.Nome, partner.firstname)
            )
        if (
            DatiAnagrafici.Anagrafica.Cognome
            and partner.lastname != DatiAnagrafici.Anagrafica.Cognome
        ):
            self.log_inconsistency(
                _("Surname field contains '%s'." " Your System contains '%s'")
                % (DatiAnagrafici.Anagrafica.Cognome, partner.lastname)
            )

    def getPartnerBase(self, DatiAnagrafici):  # noqa: C901
        if not DatiAnagrafici:
            return False
        partner_model = self.env["res.partner"]
        cf = DatiAnagrafici.CodiceFiscale or False
        vat = False
        if DatiAnagrafici.IdFiscaleIVA:
            # Format Italian VAT ID to always have 11 char
            # to avoid validation error when creating the given partner
            if DatiAnagrafici.IdFiscaleIVA.IdPaese.upper() == "IT":
                vat = "{}{}".format(
                    DatiAnagrafici.IdFiscaleIVA.IdPaese.upper(),
                    DatiAnagrafici.IdFiscaleIVA.IdCodice.rjust(11, "0")[:11],
                )
            else:
                vat = "{}{}".format(
                    DatiAnagrafici.IdFiscaleIVA.IdPaese.upper(),
                    re.sub(r"\W+", "", DatiAnagrafici.IdFiscaleIVA.IdCodice).upper(),
                )
        partners = partner_model
        res_partner_rule = (
            self.env["ir.model.data"]
            .sudo()
            .xmlid_to_object("base.res_partner_rule", raise_if_not_found=False)
        )
        if vat:
            domain = [("vat", "=", vat)]
            if (
                self.env.context.get("from_attachment")
                and res_partner_rule
                and res_partner_rule.active
            ):
                att = self.env.context.get("from_attachment")
                domain.extend(
                    [
                        "|",
                        ("company_id", "child_of", att.company_id.id),
                        ("company_id", "=", False),
                    ]
                )
            partners = partner_model.search(domain)
        if not partners and cf:
            domain = [("fiscalcode", "=", cf)]
            if (
                self.env.context.get("from_attachment")
                and res_partner_rule
                and res_partner_rule.active
            ):
                att = self.env.context.get("from_attachment")
                domain.extend(
                    [
                        "|",
                        ("company_id", "child_of", att.company_id.id),
                        ("company_id", "=", False),
                    ]
                )
            partners = partner_model.search(domain)
        commercial_partner_id = False
        if len(partners) > 1:
            for partner in partners:
                if (
                    commercial_partner_id
                    and partner.commercial_partner_id.id != commercial_partner_id
                ):
                    self.log_inconsistency(
                        _(
                            "Two distinct partners with "
                            "VAT number %s or Fiscal Code %s already "
                            "present in db." % (vat, cf)
                        )
                    )
                    return False
                commercial_partner_id = partner.commercial_partner_id.id
        if partners:
            if not commercial_partner_id:
                commercial_partner_id = partners[0].commercial_partner_id.id
            self.check_partner_base_data(commercial_partner_id, DatiAnagrafici)
            return commercial_partner_id
        else:
            # partner to be created
            country_id = False
            if DatiAnagrafici.IdFiscaleIVA:
                CountryCode = DatiAnagrafici.IdFiscaleIVA.IdPaese
                countries = self.CountryByCode(CountryCode)
                if countries:
                    country_id = countries[0].id
                else:
                    raise UserError(
                        _("Country Code %s not found in system.") % CountryCode
                    )
            vals = {
                "vat": vat,
                "fiscalcode": cf,
                "is_company": (
                    DatiAnagrafici.Anagrafica.Denominazione and True or False
                ),
                "eori_code": DatiAnagrafici.Anagrafica.CodEORI or "",
                "country_id": country_id,
            }
            if DatiAnagrafici.Anagrafica.Nome:
                vals["firstname"] = DatiAnagrafici.Anagrafica.Nome
            if DatiAnagrafici.Anagrafica.Cognome:
                vals["lastname"] = DatiAnagrafici.Anagrafica.Cognome
            if DatiAnagrafici.Anagrafica.Denominazione:
                vals["name"] = DatiAnagrafici.Anagrafica.Denominazione

            return partner_model.create(vals).id

    def getCedPrest(self, cedPrest):
        partner_model = self.env["res.partner"]
        partner_id = self.getPartnerBase(cedPrest.DatiAnagrafici)
        no_contact_update = False
        if partner_id:
            no_contact_update = partner_model.browse(
                partner_id
            ).electronic_invoice_no_contact_update
        fiscalPosModel = self.env["fatturapa.fiscal_position"]
        if partner_id and not no_contact_update:
            partner_company_id = partner_model.browse(partner_id).company_id.id
            vals = {
                "street": " ".join(
                    map(
                        str,
                        filter(
                            None, (cedPrest.Sede.Indirizzo, cedPrest.Sede.NumeroCivico)
                        ),
                    )
                ),
                "zip": cedPrest.Sede.CAP,
                "city": cedPrest.Sede.Comune,
                "register": cedPrest.DatiAnagrafici.AlboProfessionale or "",
            }
            if cedPrest.DatiAnagrafici.ProvinciaAlbo:
                ProvinciaAlbo = cedPrest.DatiAnagrafici.ProvinciaAlbo
                prov = self.ProvinceByCode(ProvinciaAlbo)
                if not prov:
                    self.log_inconsistency(
                        _("Register Province ( %s ) not present " "in your system")
                        % ProvinciaAlbo
                    )
                else:
                    vals["register_province"] = prov[0].id
            if cedPrest.Sede.Provincia:
                Provincia = cedPrest.Sede.Provincia
                prov_sede = self.ProvinceByCode(Provincia)
                if not prov_sede:
                    self.log_inconsistency(
                        _("Province ( %s ) not present in your system") % Provincia
                    )
                else:
                    vals["state_id"] = prov_sede[0].id

            vals["register_code"] = cedPrest.DatiAnagrafici.NumeroIscrizioneAlbo
            vals["register_regdate"] = cedPrest.DatiAnagrafici.DataIscrizioneAlbo

            if cedPrest.DatiAnagrafici.RegimeFiscale:
                rfPos = cedPrest.DatiAnagrafici.RegimeFiscale
                FiscalPos = fiscalPosModel.search([("code", "=", rfPos)])
                if not FiscalPos:
                    raise UserError(
                        _("Tax Regime %s not present in your system.") % rfPos
                    )
                else:
                    vals["register_fiscalpos"] = FiscalPos[0].id

            if cedPrest.IscrizioneREA:
                REA = cedPrest.IscrizioneREA
                offices = self.ProvinceByCode(REA.Ufficio)
                rea_nr = REA.NumeroREA

                if not offices:
                    office_id = False
                    self.log_inconsistency(
                        _(
                            "REA Office Province Code ( %s ) not present in "
                            "your system"
                        )
                        % REA.Ufficio
                    )
                else:
                    office_id = offices[0].id
                    vals["rea_office"] = office_id

                rea_domain = [
                    ("rea_code", "=", rea_nr),
                    ("company_id", "=", partner_company_id),
                    ("id", "!=", partner_id),
                ]
                if office_id:
                    rea_domain.append(("rea_office", "=", office_id))
                rea_partners = partner_model.search(rea_domain)
                if rea_partners:
                    rea_names = ", ".join(rea_partners.mapped("name"))
                    p_name = partner_model.browse(partner_id).name
                    self.log_inconsistency(
                        _(
                            "Current invoice is from {} with REA Code"
                            " {}. Yet it seems that partners {} have the same"
                            " REA Code. This code should be unique; please fix"
                            " it.".format(p_name, rea_nr, rea_names)
                        )
                    )
                else:
                    vals["rea_code"] = REA.NumeroREA

                vals["rea_capital"] = REA.CapitaleSociale or 0.0
                vals["rea_member_type"] = REA.SocioUnico or False
                vals["rea_liquidation_state"] = REA.StatoLiquidazione or False

            if cedPrest.Contatti:
                vals["phone"] = cedPrest.Contatti.Telefono
                vals["email"] = cedPrest.Contatti.Email
            partner_model.browse(partner_id).write(vals)
        return partner_id

    def getCarrirerPartner(self, Carrier):<commit_msg>[14.0][FIX] Do not overwrite missing value<commit_after>import logging
import re
from datetime import datetime

from odoo import api, fields, models, registry
from odoo.exceptions import UserError
from odoo.fields import first
from odoo.tools import float_is_zero
from odoo.tools.translate import _

from odoo.addons.base_iban.models.res_partner_bank import pretty_iban

from . import efattura

_logger = logging.getLogger(__name__)

WT_CODES_MAPPING = {
    "RT01": "ritenuta",
    "RT02": "ritenuta",
    "RT03": "inps",
    "RT04": "enasarco",
    "RT05": "enpam",
    "RT06": "other",
}


class WizardImportFatturapa(models.TransientModel):
    _name = "wizard.import.fatturapa"
    _description = "Import E-bill"

    e_invoice_detail_level = fields.Selection(
        [
            ("0", "Minimum"),
            ("1", "Tax rate"),
            ("2", "Maximum"),
        ],
        string="E-bills Detail Level",
        help="Minimum level: Bill is created with no lines; "
        "User will have to create them, according to what specified in "
        "the electronic bill.\n"
        "Tax rate level: Rate level: an invoice line is created for each "
        "rate present in the electronic invoice\n"
        "Maximum level: every line contained in the electronic bill "
        "will create a line in the bill.",
        required=True,
    )
    price_decimal_digits = fields.Integer(
        "Prices decimal digits",
        required=True,
        help="Decimal digits used in prices computation. This is needed to correctly "
        "import e-invoices with many decimal digits, not being forced to "
        "increase decimal digits of all your prices. "
        'Otherwise, increase "Product Price" precision.',
    )
    quantity_decimal_digits = fields.Integer(
        "Quantities decimal digits",
        required=True,
        help='Decimal digits used for quantity field. See "Prices decimal digits".',
    )
    discount_decimal_digits = fields.Integer(
        "Discounts decimal digits",
        required=True,
        help='Decimal digits used for discount field. See "Prices decimal digits".',
    )

    @api.model
    def default_get(self, fields):
        res = super(WizardImportFatturapa, self).default_get(fields)
        res["price_decimal_digits"] = self.env["decimal.precision"].precision_get(
            "Product Price"
        )
        res["quantity_decimal_digits"] = self.env["decimal.precision"].precision_get(
            "Product Unit of Measure"
        )
        res["discount_decimal_digits"] = self.env["decimal.precision"].precision_get(
            "Discount"
        )
        res["e_invoice_detail_level"] = "2"
        fatturapa_attachment_ids = self.env.context.get("active_ids", False)
        fatturapa_attachment_obj = self.env["fatturapa.attachment.in"]
        partners = self.env["res.partner"]
        for fatturapa_attachment_id in fatturapa_attachment_ids:
            fatturapa_attachment = fatturapa_attachment_obj.browse(
                fatturapa_attachment_id
            )
            if fatturapa_attachment.in_invoice_ids:
                raise UserError(
                    _("File %s is linked to bills yet.") % fatturapa_attachment.name
                )
            partners |= fatturapa_attachment.xml_supplier_id
            if len(partners) == 1:
                res["e_invoice_detail_level"] = partners[0].e_invoice_detail_level
                if partners[0].e_invoice_price_decimal_digits >= 0:
                    res["price_decimal_digits"] = partners[
                        0
                    ].e_invoice_price_decimal_digits
                if partners[0].e_invoice_quantity_decimal_digits >= 0:
                    res["quantity_decimal_digits"] = partners[
                        0
                    ].e_invoice_quantity_decimal_digits
                if partners[0].e_invoice_discount_decimal_digits >= 0:
                    res["discount_decimal_digits"] = partners[
                        0
                    ].e_invoice_discount_decimal_digits
        return res

    def CountryByCode(self, CountryCode):
        country_model = self.env["res.country"]
        return country_model.search([("code", "=", CountryCode)])

    def ProvinceByCode(self, provinceCode):
        province_model = self.env["res.country.state"]
        return province_model.search(
            [("code", "=", provinceCode), ("country_id.code", "=", "IT")]
        )

    def log_inconsistency(self, message):
        inconsistencies = self.env.context.get("inconsistencies", "")
        if inconsistencies:
            inconsistencies += "\n"
        inconsistencies += message
        # convert to dict in order to be able to modify context
        self.env.context = dict(self.env.context)
        self.env.context.update(inconsistencies=inconsistencies)

    def check_partner_base_data(self, partner_id, DatiAnagrafici):
        partner = self.env["res.partner"].browse(partner_id)
        if (
            DatiAnagrafici.Anagrafica.Denominazione
            and partner.name != DatiAnagrafici.Anagrafica.Denominazione
        ):
            self.log_inconsistency(
                _("Company Name field contains '%s'." " Your System contains '%s'")
                % (DatiAnagrafici.Anagrafica.Denominazione, partner.name)
            )
        if (
            DatiAnagrafici.Anagrafica.Nome
            and partner.firstname != DatiAnagrafici.Anagrafica.Nome
        ):
            self.log_inconsistency(
                _("Name field contains '%s'." " Your System contains '%s'")
                % (DatiAnagrafici.Anagrafica.Nome, partner.firstname)
            )
        if (
            DatiAnagrafici.Anagrafica.Cognome
            and partner.lastname != DatiAnagrafici.Anagrafica.Cognome
        ):
            self.log_inconsistency(
                _("Surname field contains '%s'." " Your System contains '%s'")
                % (DatiAnagrafici.Anagrafica.Cognome, partner.lastname)
            )

    def getPartnerBase(self, DatiAnagrafici):  # noqa: C901
        if not DatiAnagrafici:
            return False
        partner_model = self.env["res.partner"]
        cf = DatiAnagrafici.CodiceFiscale or False
        vat = False
        if DatiAnagrafici.IdFiscaleIVA:
            # Format Italian VAT ID to always have 11 char
            # to avoid validation error when creating the given partner
            if DatiAnagrafici.IdFiscaleIVA.IdPaese.upper() == "IT":
                vat = "{}{}".format(
                    DatiAnagrafici.IdFiscaleIVA.IdPaese.upper(),
                    DatiAnagrafici.IdFiscaleIVA.IdCodice.rjust(11, "0")[:11],
                )
            else:
                vat = "{}{}".format(
                    DatiAnagrafici.IdFiscaleIVA.IdPaese.upper(),
                    re.sub(r"\W+", "", DatiAnagrafici.IdFiscaleIVA.IdCodice).upper(),
                )
        partners = partner_model
        res_partner_rule = (
            self.env["ir.model.data"]
            .sudo()
            .xmlid_to_object("base.res_partner_rule", raise_if_not_found=False)
        )
        if vat:
            domain = [("vat", "=", vat)]
            if (
                self.env.context.get("from_attachment")
                and res_partner_rule
                and res_partner_rule.active
            ):
                att = self.env.context.get("from_attachment")
                domain.extend(
                    [
                        "|",
                        ("company_id", "child_of", att.company_id.id),
                        ("company_id", "=", False),
                    ]
                )
            partners = partner_model.search(domain)
        if not partners and cf:
            domain = [("fiscalcode", "=", cf)]
            if (
                self.env.context.get("from_attachment")
                and res_partner_rule
                and res_partner_rule.active
            ):
                att = self.env.context.get("from_attachment")
                domain.extend(
                    [
                        "|",
                        ("company_id", "child_of", att.company_id.id),
                        ("company_id", "=", False),
                    ]
                )
            partners = partner_model.search(domain)
        commercial_partner_id = False
        if len(partners) > 1:
            for partner in partners:
                if (
                    commercial_partner_id
                    and partner.commercial_partner_id.id != commercial_partner_id
                ):
                    self.log_inconsistency(
                        _(
                            "Two distinct partners with "
                            "VAT number %s or Fiscal Code %s already "
                            "present in db." % (vat, cf)
                        )
                    )
                    return False
                commercial_partner_id = partner.commercial_partner_id.id
        if partners:
            if not commercial_partner_id:
                commercial_partner_id = partners[0].commercial_partner_id.id
            self.check_partner_base_data(commercial_partner_id, DatiAnagrafici)
            return commercial_partner_id
        else:
            # partner to be created
            country_id = False
            if DatiAnagrafici.IdFiscaleIVA:
                CountryCode = DatiAnagrafici.IdFiscaleIVA.IdPaese
                countries = self.CountryByCode(CountryCode)
                if countries:
                    country_id = countries[0].id
                else:
                    raise UserError(
                        _("Country Code %s not found in system.") % CountryCode
                    )
            vals = {
                "vat": vat,
                "fiscalcode": cf,
                "is_company": (
                    DatiAnagrafici.Anagrafica.Denominazione and True or False
                ),
                "eori_code": DatiAnagrafici.Anagrafica.CodEORI or "",
                "country_id": country_id,
            }
            if DatiAnagrafici.Anagrafica.Nome:
                vals["firstname"] = DatiAnagrafici.Anagrafica.Nome
            if DatiAnagrafici.Anagrafica.Cognome:
                vals["lastname"] = DatiAnagrafici.Anagrafica.Cognome
            if DatiAnagrafici.Anagrafica.Denominazione:
                vals["name"] = DatiAnagrafici.Anagrafica.Denominazione

            return partner_model.create(vals).id

    def getCedPrest(self, cedPrest):
        partner_model = self.env["res.partner"]
        partner_id = self.getPartnerBase(cedPrest.DatiAnagrafici)
        no_contact_update = False
        if partner_id:
            no_contact_update = partner_model.browse(
                partner_id
            ).electronic_invoice_no_contact_update
        fiscalPosModel = self.env["fatturapa.fiscal_position"]
        if partner_id and not no_contact_update:
            partner_company_id = partner_model.browse(partner_id).company_id.id
            vals = {
                "street": " ".join(
                    map(
                        str,
                        filter(
                            None, (cedPrest.Sede.Indirizzo, cedPrest.Sede.NumeroCivico)
                        ),
                    )
                ),
                "zip": cedPrest.Sede.CAP,
                "city": cedPrest.Sede.Comune,
                "register": cedPrest.DatiAnagrafici.AlboProfessionale or "",
            }
            if cedPrest.DatiAnagrafici.ProvinciaAlbo:
                ProvinciaAlbo = cedPrest.DatiAnagrafici.ProvinciaAlbo
                prov = self.ProvinceByCode(ProvinciaAlbo)
                if not prov:
                    self.log_inconsistency(
                        _("Register Province ( %s ) not present " "in your system")
                        % ProvinciaAlbo
                    )
                else:
                    vals["register_province"] = prov[0].id
            if cedPrest.Sede.Provincia:
                Provincia = cedPrest.Sede.Provincia
                prov_sede = self.ProvinceByCode(Provincia)
                if not prov_sede:
                    self.log_inconsistency(
                        _("Province ( %s ) not present in your system") % Provincia
                    )
                else:
                    vals["state_id"] = prov_sede[0].id

            vals["register_code"] = cedPrest.DatiAnagrafici.NumeroIscrizioneAlbo
            vals["register_regdate"] = cedPrest.DatiAnagrafici.DataIscrizioneAlbo

            if cedPrest.DatiAnagrafici.RegimeFiscale:
                rfPos = cedPrest.DatiAnagrafici.RegimeFiscale
                FiscalPos = fiscalPosModel.search([("code", "=", rfPos)])
                if not FiscalPos:
                    raise UserError(
                        _("Tax Regime %s not present in your system.") % rfPos
                    )
                else:
                    vals["register_fiscalpos"] = FiscalPos[0].id

            if cedPrest.IscrizioneREA:
                REA = cedPrest.IscrizioneREA
                offices = self.ProvinceByCode(REA.Ufficio)
                rea_nr = REA.NumeroREA

                if not offices:
                    office_id = False
                    self.log_inconsistency(
                        _(
                            "REA Office Province Code ( %s ) not present in "
                            "your system"
                        )
                        % REA.Ufficio
                    )
                else:
                    office_id = offices[0].id
                    vals["rea_office"] = office_id

                rea_domain = [
                    ("rea_code", "=", rea_nr),
                    ("company_id", "=", partner_company_id),
                    ("id", "!=", partner_id),
                ]
                if office_id:
                    rea_domain.append(("rea_office", "=", office_id))
                rea_partners = partner_model.search(rea_domain)
                if rea_partners:
                    rea_names = ", ".join(rea_partners.mapped("name"))
                    p_name = partner_model.browse(partner_id).name
                    self.log_inconsistency(
                        _(
                            "Current invoice is from {} with REA Code"
                            " {}. Yet it seems that partners {} have the same"
                            " REA Code. This code should be unique; please fix"
                            " it.".format(p_name, rea_nr, rea_names)
                        )
                    )
                else:
                    vals["rea_code"] = REA.NumeroREA

                vals["rea_capital"] = REA.CapitaleSociale or 0.0
                vals["rea_member_type"] = REA.SocioUnico or False
                vals["rea_liquidation_state"] = REA.StatoLiquidazione or False

            if cedPrest.Contatti:
                if cedPrest.Contatti.Telefono:
                    vals["phone"] = cedPrest.Contatti.Telefono
                if cedPrest.Contatti.Email:
                    vals["email"] = cedPrest.Contatti.Email
            partner_model.browse(partner_id).write(vals)
        return partner_id

    def getCarrirerPartner(self, Carrier):
{'fraction_non_alphanumeric': 0.08920110555409318, 'fraction_numerical': 0.0031258225848907607, 'mean_word_length': 1.544837980406933, 'pattern_counts': {'":': 32, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5391685', 'n_tokens_mistral': 9000, 'n_tokens_neox': 8440, 'n_words': 1608}