<commit_before># -*- coding: utf-8 -*-
from openerp import fields, models, api, _
from dateutil.tz import tzlocal
from datetime import datetime, timedelta
from dateutil.parser import parse as dateparse
from random import randint
from suds.client import Client
import xml.etree.ElementTree as ET
import logging
from openerp.exceptions import Warning
import openerp.tools as tools
import os

_logger = logging.getLogger(__name__)

_login_message = """\
<?xml version="1.0" encoding="UTF-8"?>
<loginTicketRequest version="1.0">
<header>
    <uniqueId>{uniqueid}</uniqueId>
    <generationTime>{generationtime}</generationTime>
    <expirationTime>{expirationtime}</expirationTime>
</header>
<service>{service}</service>
</loginTicketRequest>"""

_intmin = -2147483648
_intmax = 2147483647


class res_company(models.Model):

    _inherit = "res.company"

    alias_ids = fields.One2many(
        'afipws.certificate_alias',
        'company_id',
        'Aliases',
        )
    connection_ids = fields.One2many(
        'afipws.connection',
        'company_id',
        'Connections',
        readonly=True,
        )

    @api.model
    def _get_environment_type(self):
        """
        Function to define homologation/production environment
        First it search for a paramter "afip.ws.env.type" if exists and:
        * is production --> production
        * is homologation --> homologation
        Else
        Search for 'server_mode' parameter on conf file. If that parameter is:
        * 'test' or 'develop' -->  homologation
        * other or no parameter -->  production
        """
        parameter_env_type = self.env[
            'ir.config_parameter'].get_param('afip.ws.env.type')
        if parameter_env_type == 'production':
            environment_type = 'production'
        elif parameter_env_type == 'homologation':
            environment_type = 'homologation'
        else:
            if tools.config.get('server_mode') in ('test', 'develop'):
                environment_type = 'homologation'
            else:
                environment_type = 'production'
        _logger.info(
            'Running arg electronic invoice on %s mode' % environment_type)
        return environment_type

    @api.multi
    def get_key_and_certificate(self, environment_type):
        """
        Funcion que busca para el environment_type definido,
        una clave y un certificado en los siguientes lugares y segun estas
        prioridades:
        * en el conf del server de odoo
        * en registros de esta misma clase
        """
        self.ensure_one
        pkey = False
        cert = False
        msg = False
        certificate = self.env['afipws.certificate'].search([
            ('alias_id.company_id', '=', self.id),
            ('alias_id.type', '=', environment_type),
            ('state', '=', 'confirmed'),
            ], limit=1)
        if certificate:
            pkey = certificate.alias_id.key
            cert = certificate.crt
            _logger.info('Using DB certificates')
        # not certificate on bd, we search on odo conf file
        else:
            msg = _('Not confirmed certificate for %s on company %s') % (
                environment_type, self.name)
            pkey_path = False
            cert_path = False
            if environment_type == 'production':
                pkey_path = tools.config.get('afip_prod_pkey_file')
                cert_path = tools.config.get('afip_prod_cert_file')
            else:
                pkey_path = tools.config.get('afip_homo_pkey_file')
                cert_path = tools.config.get('afip_homo_cert_file')
            if pkey_path and cert_path:
                try:
                    if os.path.isfile(pkey_path) and os.path.isfile(cert_path):
                        with open(pkey_path, "r") as pkey_file:
                            pkey = pkey_file.read()
                        with open(cert_path, "r") as cert_file:
                            cert = cert_file.read()
                    msg = 'Could not find %s or %s files' % (
                        pkey_path, cert_path)
                except:
                    msg = 'Could not read %s or %s files' % (
                        pkey_path, cert_path)
                else:
                    _logger.info('Using odoo conf certificates')
        if not pkey or not cert:
            raise Warning(msg)
        return (pkey, cert)

    @api.multi
    def get_connection(self, afip_ws):
        self.ensure_one()
        _logger.info('Getting connection for company %s and ws %s' % (
            self.name, afip_ws))
        now = fields.Datetime.now()
        environment_type = self._get_environment_type()

        connection = self.connection_ids.search([
            ('type', '=', environment_type),
            ('generationtime', '<=', now),
            ('expirationtime', '>', now),
            ('afip_ws', '=', afip_ws),
            ], limit=1)
        if not connection:
            connection = self._create_connection(afip_ws, environment_type)
        return connection
<commit_msg>FIX company con connection search<commit_after># -*- coding: utf-8 -*-
from openerp import fields, models, api, _
from dateutil.tz import tzlocal
from datetime import datetime, timedelta
from dateutil.parser import parse as dateparse
from random import randint
from suds.client import Client
import xml.etree.ElementTree as ET
import logging
from openerp.exceptions import Warning
import openerp.tools as tools
import os

_logger = logging.getLogger(__name__)

_login_message = """\
<?xml version="1.0" encoding="UTF-8"?>
<loginTicketRequest version="1.0">
<header>
    <uniqueId>{uniqueid}</uniqueId>
    <generationTime>{generationtime}</generationTime>
    <expirationTime>{expirationtime}</expirationTime>
</header>
<service>{service}</service>
</loginTicketRequest>"""

_intmin = -2147483648
_intmax = 2147483647


class res_company(models.Model):

    _inherit = "res.company"

    alias_ids = fields.One2many(
        'afipws.certificate_alias',
        'company_id',
        'Aliases',
        )
    connection_ids = fields.One2many(
        'afipws.connection',
        'company_id',
        'Connections',
        readonly=True,
        )

    @api.model
    def _get_environment_type(self):
        """
        Function to define homologation/production environment
        First it search for a paramter "afip.ws.env.type" if exists and:
        * is production --> production
        * is homologation --> homologation
        Else
        Search for 'server_mode' parameter on conf file. If that parameter is:
        * 'test' or 'develop' -->  homologation
        * other or no parameter -->  production
        """
        parameter_env_type = self.env[
            'ir.config_parameter'].get_param('afip.ws.env.type')
        if parameter_env_type == 'production':
            environment_type = 'production'
        elif parameter_env_type == 'homologation':
            environment_type = 'homologation'
        else:
            if tools.config.get('server_mode') in ('test', 'develop'):
                environment_type = 'homologation'
            else:
                environment_type = 'production'
        _logger.info(
            'Running arg electronic invoice on %s mode' % environment_type)
        return environment_type

    @api.multi
    def get_key_and_certificate(self, environment_type):
        """
        Funcion que busca para el environment_type definido,
        una clave y un certificado en los siguientes lugares y segun estas
        prioridades:
        * en el conf del server de odoo
        * en registros de esta misma clase
        """
        self.ensure_one
        pkey = False
        cert = False
        msg = False
        certificate = self.env['afipws.certificate'].search([
            ('alias_id.company_id', '=', self.id),
            ('alias_id.type', '=', environment_type),
            ('state', '=', 'confirmed'),
            ], limit=1)
        if certificate:
            pkey = certificate.alias_id.key
            cert = certificate.crt
            _logger.info('Using DB certificates')
        # not certificate on bd, we search on odo conf file
        else:
            msg = _('Not confirmed certificate for %s on company %s') % (
                environment_type, self.name)
            pkey_path = False
            cert_path = False
            if environment_type == 'production':
                pkey_path = tools.config.get('afip_prod_pkey_file')
                cert_path = tools.config.get('afip_prod_cert_file')
            else:
                pkey_path = tools.config.get('afip_homo_pkey_file')
                cert_path = tools.config.get('afip_homo_cert_file')
            if pkey_path and cert_path:
                try:
                    if os.path.isfile(pkey_path) and os.path.isfile(cert_path):
                        with open(pkey_path, "r") as pkey_file:
                            pkey = pkey_file.read()
                        with open(cert_path, "r") as cert_file:
                            cert = cert_file.read()
                    msg = 'Could not find %s or %s files' % (
                        pkey_path, cert_path)
                except:
                    msg = 'Could not read %s or %s files' % (
                        pkey_path, cert_path)
                else:
                    _logger.info('Using odoo conf certificates')
        if not pkey or not cert:
            raise Warning(msg)
        return (pkey, cert)

    @api.multi
    def get_connection(self, afip_ws):
        self.ensure_one()
        _logger.info('Getting connection for company %s and ws %s' % (
            self.name, afip_ws))
        now = fields.Datetime.now()
        environment_type = self._get_environment_type()

        connection = self.connection_ids.search([
            ('type', '=', environment_type),
            ('generationtime', '<=', now),
            ('expirationtime', '>', now),
            ('afip_ws', '=', afip_ws),
            ('company_id', '=', self.id),
            ], limit=1)
        if not connection:
            connection = self._create_connection(afip_ws, environment_type)
        return connection

{'fraction_non_alphanumeric': 0.10111589663273297, 'fraction_numerical': 0.005873140172278779, 'mean_word_length': 1.9953092934623278, 'pattern_counts': {'":': 0, '<': 31, '<?xml version=': 2, '>': 39, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7642369', 'n_tokens_mistral': 2939, 'n_tokens_neox': 2822, 'n_words': 726}