<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#  licence AGPL version 3 or later
#  see licence in __openerp__.py or http://www.gnu.org/licenses/agpl-3.0.txt
#  Copyright (C) 2014 Akretion (http://www.akretion.com).
#  @author <NAME> <<EMAIL>>
#          <NAME>
##############################################################################

from openerp.osv import orm, fields
from openerp.tools.config import config
from openerp.tools.translate import _
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
from laposte_api.colissimo_and_so import (
    ColiPoste,
    InvalidDataForMako,
    InvalidWebServiceRequest)

from laposte_api.exception_helper import (
    InvalidWeight,
    InvalidSize,
    InvalidMissingField,
    InvalidCode,
    InvalidCountry,
    InvalidZipCode,
    InvalidSequence,
    InvalidKeyInTemplate,
    InvalidType)

from datetime import datetime

EXCEPT_TITLE = "'Colissimo and So' library Exception"
LABEL_TYPE = 'zpl2'


def raise_exception(orm, message):
    raise orm.except_orm(EXCEPT_TITLE, map_except_message(message))


def map_except_message(message):
    """Allows to map vocabulary from external library
    to Odoo vocabulary in Exception message
    """
    webservice_mapping = {
        'line2': 'line2 (rue du partner du bon de livraison)',
        '\\xe8': 'e',
        '\\xe9': 'e',
        '\\xe0': 'a',
    }
    model_mapping = {
        'sender': 'company and \ncarrier configuration',
        'delivery': 'delivery order',
        'address': 'customer/partner'}
    for key, val in model_mapping.items():
        message = message.replace('(model: ' + key, '\n(check model: ' + val)
    for key, val in webservice_mapping.items():
        message = message.replace(key, val)
    if 'commercial afin de reinitialiser votre compte client' in message:
        message += ("\n\nEn gros à ce stade, "
                    "si vous avez saisi correctement votre identifiant"
                    "et mot de passe transmis par votre commercial"
                    "\nil est probable que ce dernier"
                    "n'a pas terminé le boulot jusqu'au bout"
                    "\nVraisemblablement, vous allez passez encore beaucoup"
                    "de temps à faire la balle de ping pong entre les"
                    "services: commercial, ADV et Support Intégration Clients."
                    "\nCe dernier est probablement votre meilleur chance."
                    "\nun homme averti en vaut deux"
                    "\nBougez avec la poste"
                    "\nBonne chance\n\n(the developer team)")
    return message


def move_label_content(content, tag, value, axis='y'):
    """ move label content
        :param content: unicode: whole text to parse
        :param tag: str: string to search in content for replacement purpose
        :param value: integer: define position x or y in the label
        :param axis: char: direction x or y
    """
    cpn = tag.split(',')
    if axis == 'y':
        position = str(int(cpn[1]) + value)
        new_tag = '%s,%s' % (cpn[0], position)
    else:
        extract_pos = int(cpn[0][3:])
        position = extract_pos + value
        new_tag = '%s%s,%s' % (cpn[0][:3], position, cpn[1])
    return content.replace(tag, new_tag)


def modify_label_content(content):
    """ International web service label is too long
        to be printed correctly
    """
    tags = ['^FO270,920', '^FO30,920', '^FO670,920', '^FO290,970',
            '^FO27,995', '^FO170,1194', '^FO27,988']
    for tag in tags:
        content = move_label_content(content, tag, -30)
    return content


class StockPicking(orm.Model):
    _inherit = 'stock.picking'

    def send_douane_doc(self, cr, uid, ids, field_n, arg, context=None):
        result = {}
        for elm in self.browse(cr, uid, ids):
            res = False
            if elm.state == 'done' and elm.carrier_type == 'colissimo':
                eu_country = False
                if elm.partner_id.country_id \
                        and elm.partner_id.country_id.intrastat:
                    # intrastat field identify european countries
                    eu_country = True
                if elm.carrier_code in ['8Q', '7Q']:
                    res = True
                if elm.carrier_code in ['EI', 'AI', 'SO'] and not eu_country:
                    res = True
                elif elm.carrier_code in ['9V', '9L'] \
                        and elm.partner_id.country_id \
                        and elm.partner_id.country_id.code == 'AD':
                    res = True
            result[elm.id] = res
        return result

    _columns = {
        'colipostefr_prise_en_charge': fields.char(
            '||| || |||| pch',
            size=64,
            help="""Code barre de prise en charge :
            cf documentation coliposte pour plus de détails
    - code étiquette sur 2 alfa.
    - coliss_order : valeur 1 ou 2 (selon la méthode de livraison)
    - code postal (5 alfa) ou   prefix pays (étranger)
      + 3 premiers caractères CP
    - N° du compte client fourni par le partner 'La Poste'
    - poids du colis sur 4 numeriques
    - 00 : assurance+recommandation (non implémenté à ce jour)
    - option 'non mécanisable' : valeur 1 ou 0
    - combinaison d'options : FTD+AR+CRBT (valeur de 0 à 7)
    - clé de liaison du code barre précédent sur 1 numérique
      (issu de l'avant dernier caractère)
    - clé de contrôle du code barre actuel sur 1 numérique
    """),
        'colipostefr_insur_recomm': fields.selection([
            ('01', '150 €'), ('02', '300 €'), ('03', '450 €'),
            ('04', '600 €'), ('05', '750 €'), ('06', '900 €'),
            ('07', '1050 €'), ('08', '1200 €'),
            ('09', '1350 €'), ('10', '1500 €'),
            # TODO Recommandation level
            #('21', 'R1'), ('22', 'R2'), ('23', 'R3'),
        ],
            'Insurance',
            help="Insurance amount in € (add valorem)"),
        'colipostefr_send_douane_doc': fields.function(
            send_douane_doc,
            string='Send douane document',
            type='boolean',
            store=False,
            help="Define if document CN23 et CN11 should be "
                 "printed/sent with the parcel"),
    }

    def _prepare_address_postefr(self, cr, uid, pick, context=None):
        address = {}
        for elm in ['name', 'city', 'zip', 'phone', 'mobile']:
            address[elm] = pick.partner_id[elm]
        # 3 is the number of fields street
        # 38 is the field street max length
        res = self.pool['res.partner']._get_split_address(
            cr, uid, pick.partner_id, 3, 38, context=context)
        address['street'], address['street2'], address['street3'] = res
        if pick.partner_id.country_id.code and pick.partner_id.country_id.code:
            address['countryCode'] = pick.partner_id.country_id.code
        return address

    def _prepare_option_postefr(self, cr, uid, pick, context=None):
        option = {}
        if pick.option_ids:
            for opt in pick.option_ids:
                opt_key = str(opt.tmpl_option_id['code'].lower())
                option[opt_key] = True
        if pick.colipostefr_insur_recomm:
            # TODO improve this mechanism option
            option['insurance'] = pick.colipostefr_insur_recomm
        return option

    def _prepare_sender_postefr(self, cr, uid, pick, context=None):
        partner = self.pool['stock.picking']._get_label_sender_address(
            cr, uid, pick, context=context)
        sender = {'support_city': pick.company_id.colipostefr_support_city,
                  'password': pick.company_id.colipostefr_password}
        if partner.country_id:
            sender['country'] = partner.country_id.name
        fields = ['name', 'street', 'zip', 'city',
                  'phone', 'mobile', 'email']
        for elm in fields:
            sender[elm] = partner[elm]
        if pick.carrier_code == '6J':
            sender['chargeur'] = pick.company_id.colipostefr_account_chargeur
        return sender

    def _get_account(self, cr, uid, pick, france, context=None):
        account = pick.company_id.colipostefr_account
        if not france:
            return pick.company_id.colipostefr_world_account or account<commit_msg>[FIX] compatbility with signature new api<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#  licence AGPL version 3 or later
#  see licence in __openerp__.py or http://www.gnu.org/licenses/agpl-3.0.txt
#  Copyright (C) 2014 Akretion (http://www.akretion.com).
#  @author <NAME> <<EMAIL>>
#          <NAME>
##############################################################################

from openerp.osv import orm, fields
from openerp.tools.config import config
from openerp.tools.translate import _
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
from laposte_api.colissimo_and_so import (
    ColiPoste,
    InvalidDataForMako,
    InvalidWebServiceRequest)

from laposte_api.exception_helper import (
    InvalidWeight,
    InvalidSize,
    InvalidMissingField,
    InvalidCode,
    InvalidCountry,
    InvalidZipCode,
    InvalidSequence,
    InvalidKeyInTemplate,
    InvalidType)

from datetime import datetime

EXCEPT_TITLE = "'Colissimo and So' library Exception"
LABEL_TYPE = 'zpl2'


def raise_exception(orm, message):
    raise orm.except_orm(EXCEPT_TITLE, map_except_message(message))


def map_except_message(message):
    """Allows to map vocabulary from external library
    to Odoo vocabulary in Exception message
    """
    webservice_mapping = {
        'line2': 'line2 (rue du partner du bon de livraison)',
        '\\xe8': 'e',
        '\\xe9': 'e',
        '\\xe0': 'a',
    }
    model_mapping = {
        'sender': 'company and \ncarrier configuration',
        'delivery': 'delivery order',
        'address': 'customer/partner'}
    for key, val in model_mapping.items():
        message = message.replace('(model: ' + key, '\n(check model: ' + val)
    for key, val in webservice_mapping.items():
        message = message.replace(key, val)
    if 'commercial afin de reinitialiser votre compte client' in message:
        message += ("\n\nEn gros à ce stade, "
                    "si vous avez saisi correctement votre identifiant"
                    "et mot de passe transmis par votre commercial"
                    "\nil est probable que ce dernier"
                    "n'a pas terminé le boulot jusqu'au bout"
                    "\nVraisemblablement, vous allez passez encore beaucoup"
                    "de temps à faire la balle de ping pong entre les"
                    "services: commercial, ADV et Support Intégration Clients."
                    "\nCe dernier est probablement votre meilleur chance."
                    "\nun homme averti en vaut deux"
                    "\nBougez avec la poste"
                    "\n<NAME>\n\n(the developer team)")
    return message


def move_label_content(content, tag, value, axis='y'):
    """ move label content
        :param content: unicode: whole text to parse
        :param tag: str: string to search in content for replacement purpose
        :param value: integer: define position x or y in the label
        :param axis: char: direction x or y
    """
    cpn = tag.split(',')
    if axis == 'y':
        position = str(int(cpn[1]) + value)
        new_tag = '%s,%s' % (cpn[0], position)
    else:
        extract_pos = int(cpn[0][3:])
        position = extract_pos + value
        new_tag = '%s%s,%s' % (cpn[0][:3], position, cpn[1])
    return content.replace(tag, new_tag)


def modify_label_content(content):
    """ International web service label is too long
        to be printed correctly
    """
    tags = ['^FO270,920', '^FO30,920', '^FO670,920', '^FO290,970',
            '^FO27,995', '^FO170,1194', '^FO27,988']
    for tag in tags:
        content = move_label_content(content, tag, -30)
    return content


class StockPicking(orm.Model):
    _inherit = 'stock.picking'

    def send_douane_doc(self, cr, uid, ids, field_n, arg, context=None):
        result = {}
        for elm in self.browse(cr, uid, ids):
            res = False
            if elm.state == 'done' and elm.carrier_type == 'colissimo':
                eu_country = False
                if elm.partner_id.country_id \
                        and elm.partner_id.country_id.intrastat:
                    # intrastat field identify european countries
                    eu_country = True
                if elm.carrier_code in ['8Q', '7Q']:
                    res = True
                if elm.carrier_code in ['EI', 'AI', 'SO'] and not eu_country:
                    res = True
                elif elm.carrier_code in ['9V', '9L'] \
                        and elm.partner_id.country_id \
                        and elm.partner_id.country_id.code == 'AD':
                    res = True
            result[elm.id] = res
        return result

    _columns = {
        'colipostefr_prise_en_charge': fields.char(
            '||| || |||| pch',
            size=64,
            help="""Code barre de prise en charge :
            cf documentation coliposte pour plus de détails
    - code étiquette sur 2 alfa.
    - coliss_order : valeur 1 ou 2 (selon la méthode de livraison)
    - code postal (5 alfa) ou   prefix pays (étranger)
      + 3 premiers caractères CP
    - N° du compte client fourni par le partner 'La Poste'
    - poids du colis sur 4 numeriques
    - 00 : assurance+recommandation (non implémenté à ce jour)
    - option 'non mécanisable' : valeur 1 ou 0
    - combinaison d'options : FTD+AR+CRBT (valeur de 0 à 7)
    - clé de liaison du code barre précédent sur 1 numérique
      (issu de l'avant dernier caractère)
    - clé de contrôle du code barre actuel sur 1 numérique
    """),
        'colipostefr_insur_recomm': fields.selection([
            ('01', '150 €'), ('02', '300 €'), ('03', '450 €'),
            ('04', '600 €'), ('05', '750 €'), ('06', '900 €'),
            ('07', '1050 €'), ('08', '1200 €'),
            ('09', '1350 €'), ('10', '1500 €'),
            # TODO Recommandation level
            #('21', 'R1'), ('22', 'R2'), ('23', 'R3'),
        ],
            'Insurance',
            help="Insurance amount in € (add valorem)"),
        'colipostefr_send_douane_doc': fields.function(
            send_douane_doc,
            string='Send douane document',
            type='boolean',
            store=False,
            help="Define if document CN23 et CN11 should be "
                 "printed/sent with the parcel"),
    }

    def _prepare_address_postefr(self, cr, uid, pick, context=None):
        address = {}
        for elm in ['name', 'city', 'zip', 'phone', 'mobile']:
            address[elm] = pick.partner_id[elm]
        # 3 is the number of fields street
        # 38 is the field street max length
        res = self.pool['res.partner']._get_split_address(
            cr, uid, pick.partner_id, 3, 38, context=context)
        address['street'], address['street2'], address['street3'] = res
        if pick.partner_id.country_id.code and pick.partner_id.country_id.code:
            address['countryCode'] = pick.partner_id.country_id.code
        return address

    def _prepare_option_postefr(self, cr, uid, pick, context=None):
        option = {}
        if pick.option_ids:
            for opt in pick.option_ids:
                opt_key = str(opt.tmpl_option_id['code'].lower())
                option[opt_key] = True
        if pick.colipostefr_insur_recomm:
            # TODO improve this mechanism option
            option['insurance'] = pick.colipostefr_insur_recomm
        return option

    def _prepare_sender_postefr(self, cr, uid, pick, context=None):
        partner = self.pool['stock.picking']._get_label_sender_address(
            cr, uid, pick.id, context=context)
        sender = {'support_city': pick.company_id.colipostefr_support_city,
                  'password': <PASSWORD>.company_<PASSWORD>fr_password}
        if partner.country_id:
            sender['country'] = partner.country_id.name
        fields = ['name', 'street', 'zip', 'city',
                  'phone', 'mobile', 'email']
        for elm in fields:
            sender[elm] = partner[elm]
        if pick.carrier_code == '6J':
            sender['chargeur'] = pick.company_id.colipostefr_account_chargeur
        return sender

    def _get_account(self, cr, uid, pick, france, context=None):
        account = pick.company_id.colipostefr_account
        if not france:
            return pick.company_id.colipostefr_world_account or account
{'fraction_non_alphanumeric': 0.13067671872195297, 'fraction_numerical': 0.01902710464907557, 'mean_word_length': 2.2753282382912015, 'pattern_counts': {'":': 0, '<': 14, '<?xml version=': 0, '>': 14, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, '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': '5655079', 'n_tokens_mistral': 5327, 'n_tokens_neox': 4985, 'n_words': 1435}