<commit_before># Copyright 2021 Studio73 - <NAME> <<EMAIL>>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)..

import requests

from odoo import _, fields
from odoo.exceptions import UserError

DHL_PARCEL_DELIVERY_STATES_STATIC = {
    "A": "shipping_recorded_in_carrier",  # Assigned
    "T": "in_transit",  # Transit
    "R": "customer_delivered",  # Received
}

DHL_PARCEL_INCOTERMS_STATIC = [
    ("CPT", "Paid transport"),
    ("EXW", "Owed transport"),
]

DHL_PATH = "https://external.dhl.es/cimapi/api/v1/customer/"


class DhlParcelRequest(object):
    """Interface between DHL Parcel API and Odoo recordset
    Abstract DHL Parcel API Operations to connect them with Odoo
    """

    def __init__(self, carrier):
        self.carrier_id = carrier
        self.token = self._get_new_auth_token(
            username=carrier.dhl_parcel_uid or "",
            password=<PASSWORD> or "",
        )
        self.year = str(fields.Date.today().year)[-1]  # last digit of the year

    def _send_api_request(self, request_type, url, data=None, skip_auth=False):
        if data is None:
            data = {}
        try:
            auth = {}
            if not skip_auth:
                auth = {"Authorization": "Bearer {}".format(self.token)}
            if request_type == "GET":
                res = requests.get(url=url, headers=auth, timeout=60)
            elif request_type == "POST":
                res = requests.post(url=url, json=data, headers=auth, timeout=60)
            else:
                raise UserError(
                    _("Unsupported request type, please only use 'GET' or 'POST'")
                )
            res.raise_for_status()
            dhl_parcel_last_request = ("Request type: {}\nURL: {}\nData: {}").format(
                request_type, url, data
            )
            self.log_xml(dhl_parcel_last_request, "dhl_parcel_last_request")
            self.log_xml(res.text or "", "dhl_parcel_last_response")
        except requests.exceptions.Timeout:
            raise UserError(_("Timeout: the server did not reply within 60s"))
        except (ValueError, requests.exceptions.ConnectionError):
            raise UserError(_("Server not reachable, please try again later"))
        except requests.exceptions.HTTPError as e:
            raise UserError(
                _("{}\n{}".format(e, res.json().get("Message", "") if res.text else ""))
            )
        return res

    def _get_new_auth_token(self, username, password):
        res = self._send_api_request(
            request_type="POST",
            url=DHL_PATH + "authenticate",
            data={"Username": username, "Password": password},
            skip_auth=True,<commit_msg>[FIX] delivery_dhl_parcel: Fix log_xml<commit_after># Copyright 2021 Studio73 - <NAME> <<EMAIL>>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)..

import requests

from odoo import _, fields
from odoo.exceptions import UserError

DHL_PARCEL_DELIVERY_STATES_STATIC = {
    "A": "shipping_recorded_in_carrier",  # Assigned
    "T": "in_transit",  # Transit
    "R": "customer_delivered",  # Received
}

DHL_PARCEL_INCOTERMS_STATIC = [
    ("CPT", "Paid transport"),
    ("EXW", "Owed transport"),
]

DHL_PATH = "https://external.dhl.es/cimapi/api/v1/customer/"


class DhlParcelRequest(object):
    """Interface between DHL Parcel API and Odoo recordset
    Abstract DHL Parcel API Operations to connect them with Odoo
    """

    def __init__(self, carrier):
        self.carrier_id = carrier
        self.token = self._get_new_auth_token(
            username=carrier.dhl_parcel_uid or "",
            password=carrier.dhl_parcel_password or "",
        )
        self.year = str(fields.Date.today().year)[-1]  # last digit of the year

    def _send_api_request(self, request_type, url, data=None, skip_auth=False):
        if data is None:
            data = {}
        try:
            auth = {}
            if not skip_auth:
                auth = {"Authorization": "Bearer {}".format(self.token)}
            if request_type == "GET":
                res = requests.get(url=url, headers=auth, timeout=60)
            elif request_type == "POST":
                res = requests.post(url=url, json=data, headers=auth, timeout=60)
            else:
                raise UserError(
                    _("Unsupported request type, please only use 'GET' or 'POST'")
                )
            res.raise_for_status()
            dhl_parcel_last_request = ("Request type: {}\nURL: {}\nData: {}").format(
                request_type, url, data
            )
            self.carrier_id.log_xml(dhl_parcel_last_request, "dhl_parcel_last_request")
            self.carrier_id.log_xml(res.text or "", "dhl_parcel_last_response")
        except requests.exceptions.Timeout:
            raise UserError(_("Timeout: the server did not reply within 60s"))
        except (ValueError, requests.exceptions.ConnectionError):
            raise UserError(_("Server not reachable, please try again later"))
        except requests.exceptions.HTTPError as e:
            raise UserError(
                _("{}\n{}".format(e, res.json().get("Message", "") if res.text else ""))
            )
        return res

    def _get_new_auth_token(self, username, password):
        res = self._send_api_request(
            request_type="POST",
            url=DHL_PATH + "authenticate",
            data={"Username": username, "Password": password},
            skip_auth=True,
{'fraction_non_alphanumeric': 0.11921254101348888, 'fraction_numerical': 0.005833029529711994, 'mean_word_length': 2.372464658881377, 'pattern_counts': {'":': 16, '<': 10, '<?xml version=': 0, '>': 10, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 5}, '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': '5929021', 'n_tokens_mistral': 1713, 'n_tokens_neox': 1650, 'n_words': 380}