<commit_before># -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
import logging
import urlparse
from werkzeug import url_encode
from openerp.addons.payment.models.payment_acquirer import ValidationError
from openerp.addons.payment_todopago.controllers.main import (
    TodoPagoController)
from openerp import api, fields, models, _
import string
from ast import literal_eval
from openerp.http import request
from email.utils import parseaddr
from openerp.addons.payment_todopago.todopago import todopagoconnector as tp
_logger = logging.getLogger(__name__)


# configAuthorization.set('PRISMA f3d8b72c94ab4a06be2ef7c95490f7d3')

class AcquirerMercadopago(models.Model):
    _inherit = 'payment.acquirer'

    @api.model
    def _get_providers(self):
        """
        We add todopago on providers selection field
        """
        providers = super(AcquirerMercadopago, self)._get_providers()
        providers.append(['todopago', 'TodoPago'])
        return providers

    todopago_client_id = fields.Char(
        'TodoPago Merchant Id',
        required_if_provider='todopago',
        help='For eg. 11123',
    )
    todopago_secret_key = fields.Char(
        'TodoPago Secret Key',
        help='For eg. TODOPAGO 4C841713E65FBC7719D666CCAC531234',
        required_if_provider='todopago',
    )

    @api.multi
    def get_TodoPagoConnector(self):
        self.ensure_one()
        j_header_http = {"Authorization": self.todopago_secret_key}
        return tp.TodoPagoConnector(j_header_http, self.environment)

    @api.multi
    def todopago_compute_fees(self, amount, currency_id, country_id):
        """ We add [provider]_compute_fees method
            Compute todopago fees.

            :param float amount: the amount to pay
            :param integer country_id: an ID of a res.country, or None. This is
                                       the customer's country, to be compared
                                       to the acquirer company country.
            :return float fees: computed fees
        """
        self.ensure_one()
        if not self.fees_active:
            return 0.0
        country = self.env['res.country'].browse(country_id)
        if country and self.company_id.country_id.id == country.id:
            percentage = self.fees_dom_var
            fixed = self.fees_dom_fixed
        else:
            percentage = self.fees_int_var
            fixed = self.fees_int_fixed
        fees = (percentage / 100.0 * amount + fixed) / (1 - percentage / 100.0)
        return fees

    @api.multi
    def todopago_form_generate_values(self, values):
        """
        Por ahora stamos haciendo que si no vienen datos se usen datos del
        commercial partner, pero esto seguro lo podriamos mejorar
        """
        # return {}, tx_values
        # return values, tx_values
        self.ensure_one()
        tx_values = dict(values)
        if (
                not self.todopago_client_id or
                not self.todopago_secret_key
        ):
            raise ValidationError(_(
                'YOU MUST COMPLETE acquirer.todopago_client_id and '
                'acquirer.todopago_secret_key'))

        base_url = self.env['ir.config_parameter'].get_param('web.base.url')
        success_url = TodoPagoController._success_url
        failure_url = TodoPagoController._failure_url
        commercial_partner = tx_values['partner'].commercial_partner_id

        # get some values and catch errors
        errors = []
        # mandatorio, ya es mandatorio en ecommerce. Ademas parece ser solo
        # para argentina ya que requiere provincia en codigos argentinos
        country = (
            values['billing_partner_country'] and values[
                'billing_partner_country'].code or
            'AR').encode("utf8")
        if country != 'AR':
            errors.append('Only Argentina Implemented for TODOPAGO')

        # mandatorio y exije que moneda sea ars segun
        # https://github.com/TodoPago/SDK-Python#generalidades
        currency = (tx_values['currency'] and tx_values['currency'].name or '')
        if currency != 'ARS':
            errors.append('Only ARS Currency Implemented for TODOPAGO')

        # usamos estado generico de bs as si no viene definido
        if values['billing_partner_state'] and values[
                'billing_partner_state'].code:
            state = values['billing_partner_state'].code
        else:
            state = 'B'

        # TODOPAGO necesita que el codigo de provincia sea alguno de estos
        todopago_state_codes = [
            'C', 'B', 'K', 'H', 'U', 'X', 'W', 'E', 'P', 'Y', 'L', 'F', 'M',
            'N', 'Q', 'R', 'A', 'J', 'D', 'Z', 'S', 'G', 'V', 'T']
        if state not in todopago_state_codes:
            state = 'B'
        state = state.encode("utf8")

        if errors:
            # if errors, then we dont send todopago_data and button is not
            # display
            _logger.info('Todo pago method not avialble because of %s' % (
                errors))
            return tx_values

        # clean phone, only numbers
        string_all = string.maketrans('', '')
        onlydigits = string_all.translate(string_all, string.digits)
        onlyletters = string_all.translate(string_all, string.letters)
        phone = values["billing_partner_phone"]
        phone = phone or commercial_partner.phone
        phone = str(phone).translate(string_all, onlydigits) or "12345678"
        # todopago no nos acepta mas de 13 caraceteres
        phone = phone[:13]
        amount = "%.2f" % round(tx_values['amount'], 2)
        # parse address
        email = parseaddr(values["partner_email"])[1]
        email = email or commercial_partner.email
        if not email or '@' not in email:
            email = '<EMAIL>'
        email = email.strip().encode("utf8")
        # mandatorio, ya es mandatorio en ecommerce
        city = values["billing_partner_city"]
        city = city or commercial_partner.city or 'DUMMY CITY'
        city = city.encode("utf8")
        street = values["billing_partner_address"]
        street = street or commercial_partner.street or 'DUMMY STREET'
        street = street.encode("utf8")
        postal_code = values["billing_partner_zip"]
        postal_code = (postal_code or commercial_partner.zip or '1000')
        postal_code = postal_code.encode("utf8")
        first_name = values["billing_partner_first_name"]
        last_name = values["billing_partner_last_name"]
        # todopago only accept lettters
        first_name = str(first_name.encode("utf8")).translate(
            string_all, onlyletters)
        last_name = str(last_name.encode("utf8")).translate(
            string_all, onlyletters)
        # TODO tal vez necesitariamos separar primer y segundo nombre
        # en el caso que solo haya una palabra
        if not first_name:
            first_name = last_name
        OPERATIONID = str(tx_values["reference"])
        # cargamos todos los datos obligatorios: facturacion (CSB), envio (CSS)
        # y de los prioductos
        # we use str o encode because not unicode supported
        optionsSAR_operacion = {
            "MERCHANT": str(self.todopago_client_id),
            "OPERATIONID": OPERATIONID,
            "CURRENCYCODE": str("032"),<commit_msg>IMP todopago<commit_after># -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
import logging
import urlparse
from werkzeug import url_encode
from openerp.addons.payment.models.payment_acquirer import ValidationError
from openerp.addons.payment_todopago.controllers.main import (
    TodoPagoController)
from openerp import api, fields, models, _
import string
from ast import literal_eval
from openerp.http import request
from email.utils import parseaddr
from openerp.addons.payment_todopago.todopago import todopagoconnector as tp
_logger = logging.getLogger(__name__)


# configAuthorization.set('PRISMA f3d8b72c94ab4a06be2ef7c95490f7d3')

class AcquirerMercadopago(models.Model):
    _inherit = 'payment.acquirer'

    @api.model
    def _get_providers(self):
        """
        We add todopago on providers selection field
        """
        providers = super(AcquirerMercadopago, self)._get_providers()
        providers.append(['todopago', 'TodoPago'])
        return providers

    todopago_client_id = fields.Char(
        'TodoPago Merchant Id',
        required_if_provider='todopago',
        help='For eg. 11123',
    )
    todopago_secret_key = fields.Char(
        'TodoPago Secret Key',
        help='For eg. TODOPAGO 4C841713E65FBC7719D666CCAC531234',
        required_if_provider='todopago',
    )

    @api.multi
    def get_TodoPagoConnector(self):
        self.ensure_one()
        j_header_http = {"Authorization": self.todopago_secret_key}
        return tp.TodoPagoConnector(j_header_http, self.environment)

    @api.multi
    def todopago_compute_fees(self, amount, currency_id, country_id):
        """ We add [provider]_compute_fees method
            Compute todopago fees.

            :param float amount: the amount to pay
            :param integer country_id: an ID of a res.country, or None. This is
                                       the customer's country, to be compared
                                       to the acquirer company country.
            :return float fees: computed fees
        """
        self.ensure_one()
        if not self.fees_active:
            return 0.0
        country = self.env['res.country'].browse(country_id)
        if country and self.company_id.country_id.id == country.id:
            percentage = self.fees_dom_var
            fixed = self.fees_dom_fixed
        else:
            percentage = self.fees_int_var
            fixed = self.fees_int_fixed
        fees = (percentage / 100.0 * amount + fixed) / (1 - percentage / 100.0)
        return fees

    @api.multi
    def todopago_form_generate_values(self, values):
        """
        Por ahora stamos haciendo que si no vienen datos se usen datos del
        commercial partner, pero esto seguro lo podriamos mejorar
        """
        # return {}, tx_values
        # return values, tx_values
        self.ensure_one()
        tx_values = dict(values)
        if (
                not self.todopago_client_id or
                not self.todopago_secret_key
        ):
            raise ValidationError(_(
                'YOU MUST COMPLETE acquirer.todopago_client_id and '
                'acquirer.todopago_secret_key'))

        base_url = self.env['ir.config_parameter'].get_param('web.base.url')
        success_url = TodoPagoController._success_url
        failure_url = TodoPagoController._failure_url
        commercial_partner = tx_values['partner'].commercial_partner_id

        # get some values and catch errors
        errors = []
        # mandatorio, ya es mandatorio en ecommerce. Ademas parece ser solo
        # para argentina ya que requiere provincia en codigos argentinos
        country = (
            values['billing_partner_country'] and values[
                'billing_partner_country'].code or
            'AR').encode("utf8")
        if country != 'AR':
            errors.append('Only Argentina Implemented for TODOPAGO')

        # mandatorio y exije que moneda sea ars segun
        # https://github.com/TodoPago/SDK-Python#generalidades
        currency = (tx_values['currency'] and tx_values['currency'].name or '')
        if currency != 'ARS':
            errors.append('Only ARS Currency Implemented for TODOPAGO')

        # usamos estado generico de bs as si no viene definido
        if values['billing_partner_state'] and values[
                'billing_partner_state'].code:
            state = values['billing_partner_state'].code
        else:
            state = 'B'

        # TODOPAGO necesita que el codigo de provincia sea alguno de estos
        todopago_state_codes = [
            'C', 'B', 'K', 'H', 'U', 'X', 'W', 'E', 'P', 'Y', 'L', 'F', 'M',
            'N', 'Q', 'R', 'A', 'J', 'D', 'Z', 'S', 'G', 'V', 'T']
        if state not in todopago_state_codes:
            state = 'B'
        state = state.encode("utf8")

        if errors:
            # if errors, then we dont send todopago_data and button is not
            # display
            _logger.info('Todo pago method not avialble because of %s' % (
                errors))
            return tx_values

        # clean phone, only numbers
        # con esto obtenemos listas de reemplazo para lo que queremos limpiar
        string_all = string.maketrans('', '')
        onlydigits = string_all.translate(string_all, string.digits)
        onlyletters = string_all.translate(string_all, string.letters + ' ')
        letters_digits = string_all.translate(
            string_all, string.letters + string.digits + ' ')

        phone = values["billing_partner_phone"]
        phone = phone or commercial_partner.phone
        phone = str(phone).translate(string_all, onlydigits) or "12345678"
        # todopago no nos acepta mas de 13 caraceteres
        phone = phone[:13]

        amount = "%.2f" % round(tx_values['amount'], 2)

        # parse emil address
        email = parseaddr(values["partner_email"])[1]
        email = email or commercial_partner.email
        if not email or '@' not in email:
            email = '<EMAIL>'
        email = email.strip().encode("utf8")
        # no acepta mas de 100
        email = email[:100]

        # mandatorio, ya es mandatorio en ecommerce
        city = values["billing_partner_city"]
        city = city or commercial_partner.city or 'DUMMY CITY'
        city = city.encode("utf8").translate(string_all, letters_digits)
        # no acepta mas de 50
        city = city[:50]

        street = values["billing_partner_address"]
        street = street or commercial_partner.street or 'DUMMY STREET'
        street = street.encode("utf8").translate(string_all, letters_digits)
        # no acepta mas de 60
        street = street[:60]

        postal_code = values["billing_partner_zip"]
        postal_code = (postal_code or commercial_partner.zip or '1000')
        postal_code = postal_code.encode("utf8").translate(
            string_all, letters_digits)
        # no acepta mas de 10
        postal_code = postal_code[:10]

        first_name = values["billing_partner_first_name"]
        last_name = values["billing_partner_last_name"]
        # todopago only accept lettters
        first_name = str(first_name.encode("utf8")).translate(
            string_all, onlyletters)
        last_name = str(last_name.encode("utf8")).translate(
            string_all, onlyletters)
        # no acepta mas de 60
        first_name = first_name[:10]
        last_name = last_name[:10]

        # TODO tal vez necesitariamos separar primer y segundo nombre
        # en el caso que solo haya una palabra
        if not first_name:
            first_name = last_name
        OPERATIONID = str(tx_values["reference"])
        # cargamos todos los datos obligatorios: facturacion (CSB), envio (CSS)
        # y de los prioductos
        # we use str o encode because not unicode supported
        optionsSAR_operacion = {
            "MERCHANT": str(self.todopago_client_id),
            "OPERATIONID": OPERATIONID,
            "CURRENCYCODE": str("032"),
{'fraction_non_alphanumeric': 0.10910017843487127, 'fraction_numerical': 0.01261789446851899, 'mean_word_length': 2.452045754509459, 'pattern_counts': {'":': 8, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4535949', 'n_tokens_mistral': 4799, 'n_tokens_neox': 4582, 'n_words': 1184}