<commit_before># -*- coding: utf-8 -*-
"""
    sale

    Sale

"""
import dateutil.parser
from decimal import Decimal

from trytond.model import fields
from trytond.transaction import Transaction
from trytond.pool import PoolMeta, Pool
from trytond.pyson import Eval


__all__ = ['Sale']
__metaclass__ = PoolMeta


class Sale:
    "Sale"
    __name__ = 'sale.sale'

    amazon_order_id = fields.Char(
        'Amazon Order ID', readonly=True, select=True,
        help="This is global and unique ID given to an order across whole"
        "amazon"
        "Warning: Editing this might result in duplicate orders on next"
        " import",
        states={
            'invisible': ~(Eval('channel_type') == 'amazon_mws')
        }, depends=['channel_type']
    )

    @classmethod
    def __setup__(cls):
        """
        Setup the class before adding to pool
        """
        super(Sale, cls).__setup__()

        cls._sql_constraints += [
            (
                'amazon_id_unique',
                'UNIQUE(amazon_order_id)',
                'Sale with this amazon Order ID already exists'
            )
        ]

    @classmethod
    def find_or_create_using_amazon_id(cls, order_id):
        """
        This method tries to find the sale with the order ID
        first and if not found it will fetch the info from amazon and
        create a new sale with the data from amazon using
        create_using_amazon_data

        :param order_id: Order ID from amazon
        :type order_id: string
        :returns: Active record of sale order created/found
        """
        SaleChannel = Pool().get('sale.channel')

        sales = cls.search([
            ('amazon_order_id', '=', order_id),
        ])
        if sales:
            return sales[0]

        amazon_channel = SaleChannel(
            Transaction().context['current_channel']
        )
        assert amazon_channel.source == 'amazon_mws'

        order_api = amazon_channel.get_amazon_order_api()

        order_data = order_api.get_order([order_id]).parsed

        order_line_data = order_api.list_order_items(
            order_data['Orders']['Order']['AmazonOrderId']['value']
        ).parsed

        return cls.create_using_amazon_data(
            order_data['Orders']['Order'],
            order_line_data['OrderItems']['OrderItem']
        )

    @classmethod
    def create_using_amazon_data(cls, order_data, line_data):
        """
        Create a sale using amazon data

        :param order_data: Order data from amazon
        :return: Active record of record created
        """
        Party = Pool().get('party.party')
        Address = Pool().get('party.address')
        SaleChannel = Pool().get('sale.channel')

        amazon_channel = SaleChannel(
            Transaction().context['current_channel']
        )
        assert amazon_channel.source == 'amazon_mws'

        party_values = {
            'name': order_data['BuyerName']['value'],
            'email': order_data['BuyerEmail']['value'],
        }
        party = Party.find_or_create_using_amazon_data(party_values)

        party.add_phone_using_amazon_data(
            order_data['ShippingAddress']['Phone']['value']
        )
        party_invoice_address = party_shipping_address = \
            Address.find_or_create_for_party_using_amazon_data(
                party, order_data['ShippingAddress']
            )

        sale = cls.get_sale_using_amazon_data(order_data, line_data)
<commit_msg>Add phone no. only if it is available<commit_after># -*- coding: utf-8 -*-
"""
    sale

    Sale

"""
import dateutil.parser
from decimal import Decimal

from trytond.model import fields
from trytond.transaction import Transaction
from trytond.pool import PoolMeta, Pool
from trytond.pyson import Eval


__all__ = ['Sale']
__metaclass__ = PoolMeta


class Sale:
    "Sale"
    __name__ = 'sale.sale'

    amazon_order_id = fields.Char(
        'Amazon Order ID', readonly=True, select=True,
        help="This is global and unique ID given to an order across whole"
        "amazon"
        "Warning: Editing this might result in duplicate orders on next"
        " import",
        states={
            'invisible': ~(Eval('channel_type') == 'amazon_mws')
        }, depends=['channel_type']
    )

    @classmethod
    def __setup__(cls):
        """
        Setup the class before adding to pool
        """
        super(Sale, cls).__setup__()

        cls._sql_constraints += [
            (
                'amazon_id_unique',
                'UNIQUE(amazon_order_id)',
                'Sale with this amazon Order ID already exists'
            )
        ]

    @classmethod
    def find_or_create_using_amazon_id(cls, order_id):
        """
        This method tries to find the sale with the order ID
        first and if not found it will fetch the info from amazon and
        create a new sale with the data from amazon using
        create_using_amazon_data

        :param order_id: Order ID from amazon
        :type order_id: string
        :returns: Active record of sale order created/found
        """
        SaleChannel = Pool().get('sale.channel')

        sales = cls.search([
            ('amazon_order_id', '=', order_id),
        ])
        if sales:
            return sales[0]

        amazon_channel = SaleChannel(
            Transaction().context['current_channel']
        )
        assert amazon_channel.source == 'amazon_mws'

        order_api = amazon_channel.get_amazon_order_api()

        order_data = order_api.get_order([order_id]).parsed

        order_line_data = order_api.list_order_items(
            order_data['Orders']['Order']['AmazonOrderId']['value']
        ).parsed

        return cls.create_using_amazon_data(
            order_data['Orders']['Order'],
            order_line_data['OrderItems']['OrderItem']
        )

    @classmethod
    def create_using_amazon_data(cls, order_data, line_data):
        """
        Create a sale using amazon data

        :param order_data: Order data from amazon
        :return: Active record of record created
        """
        Party = Pool().get('party.party')
        Address = Pool().get('party.address')
        SaleChannel = Pool().get('sale.channel')

        amazon_channel = SaleChannel(
            Transaction().context['current_channel']
        )
        assert amazon_channel.source == 'amazon_mws'

        party_values = {
            'name': order_data['BuyerName']['value'],
            'email': order_data['BuyerEmail']['value'],
        }
        party = Party.find_or_create_using_amazon_data(party_values)

        if 'Phone' in order_data['ShippingAddress']:
            party.add_phone_using_amazon_data(
                order_data['ShippingAddress']['Phone']['value']
            )
        party_invoice_address = party_shipping_address = \
            Address.find_or_create_for_party_using_amazon_data(
                party, order_data['ShippingAddress']
            )

        sale = cls.get_sale_using_amazon_data(order_data, line_data)

{'fraction_non_alphanumeric': 0.09998579747195001, 'fraction_numerical': 0.000568101121999716, 'mean_word_length': 2.2707849512308407, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '2661694', 'n_tokens_mistral': 2020, 'n_tokens_neox': 1962, 'n_words': 473}