<commit_before># -*- coding: utf-8 -*-
import six
from decimal import Decimal
from django.core.urlresolvers import reverse
from django.contrib.auth.models import AnonymousUser
from django.db import models, transaction
from django.db.models.aggregates import Sum
from django.utils.translation import ugettext_lazy as _
from jsonfield.fields import JSONField
from shop.util.fields import CurrencyField
from shop.order_signals import processing
from .user import USER_MODEL
from .cart import BaseCartItem
from . import deferred


class OrderManager(models.Manager):
    def get_latest_for_user(self, user):
        """
        Returns the last Order (from a time perspective) a given user has
        placed.
        """
        if user and not isinstance(user, AnonymousUser):
            return self.filter(user=user).order_by('-modified')[0]
        else:
            return None

    def get_unconfirmed_for_cart(self, cart):
        return self.filter(cart_pk=cart.pk, status__lt=self.model.CONFIRMED)

    def remove_old_orders(self, cart):
        """
        Removes all old unconfirmed order objects.
        """
        old_orders = self.get_unconfirmed_for_cart(cart)
        old_orders.delete()

    def create_order_object(self, cart, request):
        """
        Create an empty order object and fill it with the given cart data.
        """
        order = self.model()
        order.cart_pk = cart.pk
        order.user = cart.user
        order.status = self.model.PROCESSING  # Processing
        order.order_subtotal = cart.subtotal_price
        order.order_total = cart.total_price
        return order

    @transaction.commit_on_success
    def create_from_cart(self, cart, request):
        """
        This creates a new Order object (and all the rest) from a passed Cart
        object.

        Specifically, it creates an Order with corresponding OrderItems and
        eventually corresponding ExtraPriceFields

        This will only actually commit the transaction once the function exits
        to minimize useless database access.

        The `state` parameter is further passed to process_cart_item,
        process_cart, and post_process_cart, so it can be used as a way to
        store per-request arbitrary information.

        Emits the ``processing`` signal.
        """
        CartItem = getattr(BaseCartItem, 'materialized_model')
        OrderItem = getattr(BaseOrderItem, 'materialized_model')

        # First, let's remove old orders
        self.remove_old_orders(cart)

        # Create an empty order object
        order = self.create_order_object(cart, request)
        order.save()

        # Let's serialize all the extra price arguments in DB
        for field in cart.extra_price_fields:
            eoi = ExtraOrderPriceField()
            eoi.order = order
            eoi.label = unicode(field[0])
            eoi.value = field[1]
            if len(field) == 3:<commit_msg>Fixed circular dependency<commit_after># -*- coding: utf-8 -*-
import six
from decimal import Decimal
from django.core.urlresolvers import reverse
from django.contrib.auth.models import AnonymousUser
from django.db import models, transaction
from django.db.models.aggregates import Sum
from django.utils.translation import ugettext_lazy as _
from jsonfield.fields import JSONField
from shop.util.fields import CurrencyField
from shop.order_signals import processing
from .user import USER_MODEL
from . import deferred


class OrderManager(models.Manager):
    def get_latest_for_user(self, user):
        """
        Returns the last Order (from a time perspective) a given user has
        placed.
        """
        if user and not isinstance(user, AnonymousUser):
            return self.filter(user=user).order_by('-modified')[0]
        else:
            return None

    def get_unconfirmed_for_cart(self, cart):
        return self.filter(cart_pk=cart.pk, status__lt=self.model.CONFIRMED)

    def remove_old_orders(self, cart):
        """
        Removes all old unconfirmed order objects.
        """
        old_orders = self.get_unconfirmed_for_cart(cart)
        old_orders.delete()

    def create_order_object(self, cart, request):
        """
        Create an empty order object and fill it with the given cart data.
        """
        order = self.model()
        order.cart_pk = cart.pk
        order.user = cart.user
        order.status = self.model.PROCESSING  # Processing
        order.order_subtotal = cart.subtotal_price
        order.order_total = cart.total_price
        return order

    @transaction.commit_on_success
    def create_from_cart(self, cart, request):
        """
        This creates a new Order object (and all the rest) from a passed Cart
        object.

        Specifically, it creates an Order with corresponding OrderItems and
        eventually corresponding ExtraPriceFields

        This will only actually commit the transaction once the function exits
        to minimize useless database access.

        The `state` parameter is further passed to process_cart_item,
        process_cart, and post_process_cart, so it can be used as a way to
        store per-request arbitrary information.

        Emits the ``processing`` signal.
        """
        from .cart import BaseCartItem
        CartItem = getattr(BaseCartItem, 'materialized_model')
        OrderItem = getattr(BaseOrderItem, 'materialized_model')

        # First, let's remove old orders
        self.remove_old_orders(cart)

        # Create an empty order object
        order = self.create_order_object(cart, request)
        order.save()

        # Let's serialize all the extra price arguments in DB
        for field in cart.extra_price_fields:
            eoi = ExtraOrderPriceField()
            eoi.order = order
            eoi.label = unicode(field[0])
            eoi.value = field[1]
            if len(field) == 3:
{'fraction_non_alphanumeric': 0.07133152173913043, 'fraction_numerical': 0.0016983695652173913, 'mean_word_length': 2.6062461726883037, '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': '6919249', 'n_tokens_mistral': 1586, 'n_tokens_neox': 1535, 'n_words': 509}