예제 #1
0
class BaseDeliveryItem(with_metaclass(deferred.ForeignKeyBuilder, models.Model)):
    """
    Abstract base class to keep track on the delivered quantity for each ordered item. Since the
    quantity can be any numerical value, it has to be defined by the class implementing this model.
    """
    delivery = deferred.ForeignKey(BaseDelivery, verbose_name=_("Delivery"),
        help_text=_("Refer to the shipping provider used to ship this item"))
    item = deferred.ForeignKey(BaseOrderItem, verbose_name=_("Ordered item"))

    class Meta:
        abstract = True
        verbose_name = _("Deliver item")
        verbose_name_plural = _("Deliver items")

    @classmethod
    def perform_model_checks(cls):
        try:
            order_field = [f for f in OrderItemModel._meta.fields if f.attname == 'quantity'][0]
            deliver_field = [f for f in cls._meta.fields if f.attname == 'quantity'][0]
            if order_field.get_internal_type() != deliver_field.get_internal_type():
                msg = "Field `{}.quantity` must be of one same type `{}.quantity`."
                raise ImproperlyConfigured(msg.format(cls.__name__, OrderItemModel.__name__))
        except IndexError:
            msg = "Class `{}` must implement a field named `quantity`."
            raise ImproperlyConfigured(msg.format(cls.__name__))
예제 #2
0
class Cart(BaseCart):
    """
    Default materialized model for BaseCart containing common fields
    """
    shipping_address = deferred.ForeignKey(
        BaseShippingAddress,
        on_delete=SET_DEFAULT,
        null=True,
        default=None,
        related_name='+',
    )

    billing_address = deferred.ForeignKey(
        BaseBillingAddress,
        on_delete=SET_DEFAULT,
        null=True,
        default=None,
        related_name='+',
    )

    @property
    def total_weight(self):
        """
        Returns the total weight of all items in the cart (for Shipping Services).
        """
        rez = 0
        for item in self.items.all():
            try:
                rez += float(item.product.weight) * item.quantity
            except:
                pass
        return float("{0:.2f}".format(rez))
예제 #3
0
class BaseCartItem(with_metaclass(deferred.ForeignKeyBuilder, models.Model)):
    """
    This is a holder for the quantity of items in the cart and, obviously, a
    pointer to the actual Product being purchased
    """
    cart = deferred.ForeignKey('BaseCart', related_name='items')
    product = deferred.ForeignKey(BaseProduct)
    extra = JSONField(
        verbose_name=_("Arbitrary information for this cart item"))

    objects = CartItemManager()

    class Meta:
        abstract = True
        verbose_name = _("Cart item")
        verbose_name_plural = _("Cart items")

    @classmethod
    def perform_model_checks(cls):
        try:
            allowed_types = ('IntegerField', 'DecimalField', 'FloatField')
            field = [f for f in cls._meta.fields if f.attname == 'quantity'][0]
            if not field.get_internal_type() in allowed_types:
                msg = "Field `{}.quantity` must be of one of the types: {}."
                raise ImproperlyConfigured(
                    msg.format(cls.__name__, allowed_types))
        except IndexError:
            msg = "Class `{}` must implement a field named `quantity`."
            raise ImproperlyConfigured(msg.format(cls.__name__))

    def __init__(self, *args, **kwargs):
        # reduce the given fields to what the model actually can consume
        all_field_names = [
            field.name for field in self._meta.get_fields(include_parents=True)
        ]
        model_kwargs = {
            k: v
            for k, v in kwargs.items() if k in all_field_names
        }
        super(BaseCartItem, self).__init__(*args, **model_kwargs)
        self.extra_rows = OrderedDict()
        self._dirty = True

    def save(self, *args, **kwargs):
        super(BaseCartItem, self).save(*args, **kwargs)
        self._dirty = True
        self.cart._dirty = True

    def update(self, request):
        """
        Loop over all registered cart modifier, change the price per cart item and optionally add
        some extra rows.
        """
        if not self._dirty:
            return
        self.extra_rows = OrderedDict()  # reset the dictionary
        for modifier in cart_modifiers_pool.get_all_modifiers():
            modifier.process_cart_item(self, request)
        self._dirty = False
예제 #4
0
파일: cart.py 프로젝트: zanjs/django-shop
class Cart(BaseCart):
    """
    Default materialized model for BaseCart containing common fields
    """
    shipping_address = deferred.ForeignKey(BaseShippingAddress,
                                           null=True,
                                           default=None,
                                           related_name='+')
    billing_address = deferred.ForeignKey(BaseBillingAddress,
                                          null=True,
                                          default=None,
                                          related_name='+')
예제 #5
0
class BaseAddress(models.Model):
    customer = deferred.ForeignKey(
        'BaseCustomer',
        on_delete=models.CASCADE,
    )

    priority = models.SmallIntegerField(
        default=0,
        db_index=True,
        help_text=_("Priority for using this address"),
    )

    class Meta:
        abstract = True

    objects = AddressManager()

    def as_text(self):
        """
        Return the address as plain text to be used for printing, etc.
        """
        template_names = [
            '{}/{}-address.txt'.format(app_settings.APP_LABEL,
                                       self.address_type),
            '{}/address.txt'.format(app_settings.APP_LABEL),
            'shop/address.txt',
        ]
        template = select_template(template_names)
        return template.render({'address': self})
예제 #6
0
class OrderPayment(with_metaclass(deferred.ForeignKeyBuilder, models.Model)):
    """
    A model to hold received payments for a given order.
    """
    order = deferred.ForeignKey(
        BaseOrder,
        verbose_name=_("Order"),
    )

    amount = MoneyField(
        _("Amount paid"),
        help_text=_("How much was paid with this particular transfer."),
    )

    transaction_id = models.CharField(
        _("Transaction ID"),
        max_length=255,
        help_text=_("The transaction processor's reference"),
    )

    created_at = models.DateTimeField(
        _("Received at"),
        auto_now_add=True,
    )

    payment_method = models.CharField(
        _("Payment method"),
        max_length=50,
        help_text=_("The payment backend used to process the purchase"),
    )

    class Meta:
        verbose_name = pgettext_lazy('order_models', "Order payment")
        verbose_name_plural = pgettext_lazy('order_models', "Order payments")
예제 #7
0
class BaseDeliveryItem(models.Model, metaclass=deferred.ForeignKeyBuilder):
    """
    Abstract base class to keep track on the delivered quantity for each ordered item. Since the
    quantity can be any numerical value, it has to be defined by the class implementing this model.
    """
    delivery = deferred.ForeignKey(
        BaseDelivery,
        verbose_name=_("Delivery"),
        on_delete=models.CASCADE,
        related_name='items',
        help_text=_("Refer to the shipping provider used to ship this item"),
    )

    item = deferred.ForeignKey(
        BaseOrderItem,
        on_delete=models.CASCADE,
        related_name='deliver_item',
        verbose_name=_("Ordered item"),
    )

    class Meta:
        abstract = True
        verbose_name = _("Deliver item")
        verbose_name_plural = _("Deliver items")

    @classmethod
    def check(cls, **kwargs):
        errors = super().check(**kwargs)
        for order_field in OrderItemModel._meta.fields:
            if order_field.attname == 'quantity':
                break
        else:
            msg = "Class `{}` must implement a field named `quantity`."
            errors.append(checks.Error(msg.format(OrderItemModel.__name__)))
        for deliver_field in OrderItemModel._meta.fields:
            if deliver_field.attname == 'quantity':
                break
        else:
            msg = "Class `{}` must implement a field named `quantity`."
            errors.append(checks.Error(msg.format(cls.__name__)))
        if order_field.get_internal_type() != deliver_field.get_internal_type(
        ):
            msg = "Field `{}.quantity` must be of one same type `{}.quantity`."
            errors.append(
                checks.Error(msg.format(cls.__name__,
                                        OrderItemModel.__name__)))
        return errors
예제 #8
0
class BaseProductImage(with_metaclass(deferred.ForeignKeyBuilder,
                                      models.Model)):
    """
    ManyToMany relation from the polymorphic Product to a set of images.
    """
    image = image.FilerImageField()
    product = deferred.ForeignKey(BaseProduct)
    order = models.SmallIntegerField(default=0, blank=False, null=False)

    class Meta:
        abstract = True
        verbose_name = ugettext_lazy("Product Image")
        verbose_name_plural = ugettext_lazy("Product Images")
        ordering = ('order', )
예제 #9
0
class BaseProductPage(with_metaclass(deferred.ForeignKeyBuilder,
                                     models.Model)):
    """
    ManyToMany relation from the polymorphic Product to the CMS Page.
    This in practice is the category.
    """
    page = models.ForeignKey(Page)
    product = deferred.ForeignKey(BaseProduct)

    class Meta:
        abstract = True
        unique_together = ['page', 'product']
        verbose_name = _("Category")
        verbose_name_plural = _("Categories")
예제 #10
0
class BaseDelivery(with_metaclass(deferred.ForeignKeyBuilder, models.Model)):
    """
    Shipping provider to keep track on each delivery.
    """
    order = deferred.ForeignKey(BaseOrder)

    shipping_id = models.CharField(
        _("Shipping ID"),
        max_length=255,
        null=True,
        blank=True,
        help_text=_("The transaction processor's reference"),
    )

    fulfilled_at = models.DateTimeField(
        _("Fulfilled at"),
        null=True,
        blank=True,
    )

    shipped_at = models.DateTimeField(
        _("Shipped at"),
        null=True,
        blank=True,
    )

    shipping_method = models.CharField(
        _("Shipping method"),
        max_length=50,
        help_text=_(
            "The shipping backend used to deliver the items for this order"),
    )

    class Meta:
        abstract = True
        verbose_name = _("Delivery")
        verbose_name_plural = _("Deliveries")

    @classmethod
    def perform_model_checks(cls):
        canceled_field = [
            f for f in OrderItemModel._meta.fields if f.attname == 'canceled'
        ]
        if not canceled_field or canceled_field[0].get_internal_type(
        ) != 'BooleanField':
            msg = "Class `{}` must implement a `BooleanField` named `canceled`, if used in combination with a Delivery model."
            raise ImproperlyConfigured(msg.format(OrderItemModel.__name__))
예제 #11
0
    def test_extend_deferred_model_allowed(self):
        """
        Extending a deferred model is allowed,
        but deferred relations will still reference the (first) deferred model.
        """
        create_deferred_class('Customer', DeferredCustomer)

        OrderBase = create_deferred_base_class(
            'OrderBase', {
                'customer':
                deferred.ForeignKey(DeferredBaseCustomer,
                                    on_delete=models.PROTECT),
            })
        Order = create_deferred_class('Order', OrderBase)

        self._test_foreign_key(DeferredOrder, DeferredCustomer, 'customer')
        self._test_foreign_key(Order, DeferredCustomer, 'customer')
예제 #12
0
    def test_extend_non_abstract_deferred_base_model_allowed(self):
        """
        Extending a non abstract deferred model is allowed,
        but deferred relations will still reference the (first) deferred model.
        """
        create_deferred_class('OrderPaymentSubclass', OrderPayment)

        BaseOrderPaymentLog = create_deferred_base_class(
            'BaseOrderPaymentLog', {
                'order_payment':
                deferred.ForeignKey(OrderPayment, on_delete=models.CASCADE),
            })
        OrderPaymentLog = create_deferred_class('OrderPaymentLog',
                                                BaseOrderPaymentLog)

        self._test_foreign_key(DeferredOrderPaymentLog, OrderPayment,
                               'order_payment')
        self._test_foreign_key(OrderPaymentLog, OrderPayment, 'order_payment')
예제 #13
0
class BaseProductImage(models.Model, metaclass=deferred.ForeignKeyBuilder):
    """
    ManyToMany relation from the polymorphic Product to a set of images.
    """
    image = image.FilerImageField(on_delete=models.CASCADE)

    product = deferred.ForeignKey(
        BaseProduct,
        on_delete=models.CASCADE,
    )

    order = models.SmallIntegerField(default=0)

    class Meta:
        abstract = True
        verbose_name = _("Product Image")
        verbose_name_plural = _("Product Images")
        ordering = ['order']
예제 #14
0
    def test_check_for_pending_mappings(self):
        deferred.ForeignKeyBuilder.check_for_pending_mappings()

        PendingMappingBaseCustomer = create_deferred_base_class(
            'PendingMappingBaseCustomer')
        PendingMappingBaseOrder = create_deferred_base_class(
            'PendingMappingBaseOrder', {
                'customer':
                deferred.ForeignKey(PendingMappingBaseCustomer,
                                    on_delete=models.PROTECT),
            })

        deferred.ForeignKeyBuilder.check_for_pending_mappings()

        create_deferred_class('PendingMappingOrder', PendingMappingBaseOrder)

        with self.assertRaisesRegexp(
                ImproperlyConfigured,
                "Deferred foreign key 'PendingMappingOrder.customer' has not been mapped"
        ):
            deferred.ForeignKeyBuilder.check_for_pending_mappings()
예제 #15
0
class BaseAddress(models.Model):
    customer = deferred.ForeignKey('BaseCustomer')
    priority = models.SmallIntegerField(
        help_text=_("Priority for using this address"))

    class Meta:
        abstract = True

    objects = AddressManager()

    def as_text(self):
        """
        Return the address as plain text to be used for printing, etc.
        """
        template_names = [
            '{}/{}.txt'.format(shop_settings.APP_LABEL, self.address_type),
            '{}/address.txt'.format(shop_settings.APP_LABEL),
            'shop/address.txt',
        ]
        template = select_template(template_names)
        context = Context({'address': self})
        return template.render(context)

    as_text.short_description = _("Address")
예제 #16
0
class BaseDelivery(with_metaclass(deferred.ForeignKeyBuilder, models.Model)):
    """
    Shipping provider to keep track on each delivery.
    """
    order = deferred.ForeignKey(
        BaseOrder,
        on_delete=models.CASCADE,
    )

    shipping_id = models.CharField(
        _("Shipping ID"),
        max_length=255,
        null=True,
        blank=True,
        help_text=_("The transaction processor's reference"),
    )

    fulfilled_at = models.DateTimeField(
        _("Fulfilled at"),
        null=True,
        blank=True,
        help_text=_("Timestamp of delivery fulfillment"),
    )

    shipped_at = models.DateTimeField(
        _("Shipped at"),
        null=True,
        blank=True,
        help_text=_("Timestamp of delivery shipment"),
    )

    shipping_method = models.CharField(
        _("Shipping method"),
        max_length=50,
        help_text=_("The shipping backend used to deliver items of this order"),
    )

    class Meta:
        abstract = True
        unique_together = ['shipping_method', 'shipping_id']
        get_latest_by = 'shipped_at'

    def __str__(self):
        return _("Delivery ID: {}").format(self.id)

    @classmethod
    def check(cls, **kwargs):
        errors = super(BaseDelivery, cls).check(**kwargs)
        for field in OrderItemModel._meta.fields:
            if field.attname == 'canceled' and field.get_internal_type() == 'BooleanField':
                break
        else:
             msg = "Class `{}` must implement a `BooleanField` named `canceled`, if used in combination with a Delivery model."
             errors.append(checks.Error(msg.format(OrderItemModel.__name__)))
        return errors

    def clean(self):
        if self.order._fsm_requested_transition == ('status', 'ship_goods') and not self.shipped_at:
            shipping_modifier = cart_modifiers_pool.get_active_shipping_modifier(self.shipping_method)
            shipping_modifier.ship_the_goods(self)

    def get_number(self):
        """
        Hook to get the delivery number.
        A class inheriting from Order may transform this into a string which is better readable.
        """
        if self.order.allow_partial_delivery:
            for part, delivery in enumerate(self.order.delivery_set.all(), 1):
                if delivery.pk == self.pk:
                    return "{} / {}".format(self.order.get_number(), part)
        return self.order.get_number()
예제 #17
0
DeferredUser = create_deferred_class('DeferredUser', DeferredBaseUser)

RegularCustomer = create_regular_class(
    'RegularCustomer', {
        'user':
        models.OneToOneField(RegularUser, on_delete=models.PROTECT),
        'advertised_by':
        models.ForeignKey(
            'self', null=True, blank=True, on_delete=models.SET_NULL),
    })
DeferredBaseCustomer = create_deferred_base_class(
    'DeferredBaseCustomer', {
        'user':
        deferred.OneToOneField(DeferredBaseUser, on_delete=models.PROTECT),
        'advertised_by':
        deferred.ForeignKey(
            'self', null=True, blank=True, on_delete=models.SET_NULL),
    })
DeferredCustomer = create_deferred_class('DeferredCustomer',
                                         DeferredBaseCustomer)

RegularProduct = create_regular_class('RegularProduct')
DeferredBaseProduct = create_deferred_base_class('DeferredBaseProduct')
DeferredProduct = create_deferred_class('DeferredProduct', DeferredBaseProduct)

# Order is important, it must be declared before DeferredOrder, so that fulfillment tests make sense
DeferredBaseOrderItemBeforeOrder = create_deferred_base_class(
    'DeferredBaseOrderItemBeforeOrder', {
        'order':
        deferred.ForeignKey('DeferredBaseOrder', on_delete=models.CASCADE),
        'product':
        deferred.ForeignKey(DeferredBaseProduct, on_delete=models.PROTECT),
예제 #18
0
class BaseOrderItem(with_metaclass(deferred.ForeignKeyBuilder, models.Model)):
    """
    An item for an order.
    """
    order = deferred.ForeignKey(BaseOrder,
                                related_name='items',
                                verbose_name=_("Order"))
    product_name = models.CharField(
        _("Product name"),
        max_length=255,
        null=True,
        blank=True,
        help_text=_("Product name at the moment of purchase."))
    product_code = models.CharField(
        _("Product code"),
        max_length=255,
        null=True,
        blank=True,
        help_text=_("Product code at the moment of purchase."))
    product = deferred.ForeignKey(BaseProduct,
                                  null=True,
                                  blank=True,
                                  on_delete=models.SET_NULL,
                                  verbose_name=_("Product"))
    _unit_price = models.DecimalField(
        _("Unit price"),
        null=True,  # may be NaN
        help_text=_("Products unit price at the moment of purchase."),
        **BaseOrder.decimalfield_kwargs)
    _line_total = models.DecimalField(
        _("Line Total"),
        null=True,  # may be NaN
        help_text=_("Line total on the invoice at the moment of purchase."),
        **BaseOrder.decimalfield_kwargs)
    extra = JSONField(verbose_name=_("Extra fields"),
                      help_text=_("Arbitrary information for this order item"))

    class Meta:
        abstract = True
        verbose_name = _("Order item")
        verbose_name_plural = _("Order items")

    def __str__(self):
        return self.product_name

    @classmethod
    def perform_model_checks(cls):
        try:
            cart_field = [
                f for f in CartItemModel._meta.fields
                if f.attname == 'quantity'
            ][0]
            order_field = [
                f for f in cls._meta.fields if f.attname == 'quantity'
            ][0]
            if order_field.get_internal_type() != cart_field.get_internal_type(
            ):
                msg = "Field `{}.quantity` must be of one same type `{}.quantity`."
                raise ImproperlyConfigured(
                    msg.format(cls.__name__, CartItemModel.__name__))
        except IndexError:
            msg = "Class `{}` must implement a field named `quantity`."
            raise ImproperlyConfigured(msg.format(cls.__name__))

    @cached_property
    def unit_price(self):
        return MoneyMaker(self.order.currency)(self._unit_price)

    @cached_property
    def line_total(self):
        return MoneyMaker(self.order.currency)(self._line_total)

    def populate_from_cart_item(self, cart_item, request):
        """
        From a given cart item, populate the current order item.
        If the operation was successful, the given item shall be removed from the cart.
        If a CartItem.DoesNotExist exception is raised, discard the order item.
        """
        if cart_item.quantity == 0:
            raise CartItemModel.DoesNotExist("Cart Item is on the Wish List")
        self.product = cart_item.product
        # for historical integrity, store the product's name and price at the moment of purchase
        self.product_name = cart_item.product.product_name
        self.product_code = cart_item.product_code
        self._unit_price = Decimal(cart_item.product.get_price(request))
        self._line_total = Decimal(cart_item.line_total)
        self.quantity = cart_item.quantity
        self.extra = dict(cart_item.extra)
        extra_rows = [(modifier, extra_row.data)
                      for modifier, extra_row in cart_item.extra_rows.items()]
        self.extra.update(rows=extra_rows)

    def save(self, *args, **kwargs):
        """
        Before saving the OrderItem object to the database, round the amounts to the given decimal places
        """
        self._unit_price = BaseOrder.round_amount(self._unit_price)
        self._line_total = BaseOrder.round_amount(self._line_total)
        super(BaseOrderItem, self).save(*args, **kwargs)
예제 #19
0
class BaseOrder(with_metaclass(WorkflowMixinMetaclass, models.Model)):
    """
    An Order is the "in process" counterpart of the shopping cart, which freezes the state of the
    cart on the moment of purchase. It also holds stuff like the shipping and billing addresses,
    and keeps all the additional entities, as determined by the cart modifiers.
    """
    TRANSITION_TARGETS = {
        'new': _("New order without content"),
        'created': _("Order freshly created"),
        'payment_confirmed': _("Payment confirmed"),
    }
    decimalfield_kwargs = {
        'max_digits': 30,
        'decimal_places': 2,
    }
    decimal_exp = Decimal('.' + '0' * decimalfield_kwargs['decimal_places'])

    customer = deferred.ForeignKey('BaseCustomer',
                                   verbose_name=_("Customer"),
                                   related_name='orders')
    status = FSMField(default='new', protected=True, verbose_name=_("Status"))
    currency = models.CharField(
        max_length=7,
        editable=False,
        help_text=_("Currency in which this order was concluded"))
    _subtotal = models.DecimalField(_("Subtotal"), **decimalfield_kwargs)
    _total = models.DecimalField(_("Total"), **decimalfield_kwargs)
    created_at = models.DateTimeField(_("Created at"), auto_now_add=True)
    updated_at = models.DateTimeField(_("Updated at"), auto_now=True)
    extra = JSONField(
        verbose_name=_("Extra fields"),
        help_text=
        _("Arbitrary information for this order object on the moment of purchase."
          ))
    stored_request = JSONField(
        help_text=_("Parts of the Request objects on the moment of purchase."))

    objects = OrderManager()

    class Meta:
        abstract = True

    def __str__(self):
        return self.get_number()

    def __repr__(self):
        return "<{}(pk={})>".format(self.__class__.__name__, self.pk)

    def get_or_assign_number(self):
        """
        Hook to get or to assign the order number. It shall be invoked, every time an Order
        object is created. If you prefer to use an order number which differs from the primary
        key, then override this method.
        """
        return self.get_number()

    def get_number(self):
        """
        Hook to get the order number.
        A class inheriting from Order may transform this into a string which is better readable.
        """
        return str(self.pk)

    @classmethod
    def resolve_number(cls, number):
        """
        Return a lookup pair used to filter down a queryset.
        It should revert the effect from the above method `get_number`.
        """
        return dict(pk=number)

    @cached_property
    def subtotal(self):
        """
        The summed up amount for all ordered items excluding extra order lines.
        """
        return MoneyMaker(self.currency)(self._subtotal)

    @cached_property
    def total(self):
        """
        The final total to charge for this order.
        """
        return MoneyMaker(self.currency)(self._total)

    @classmethod
    def round_amount(cls, amount):
        if amount.is_finite():
            return Decimal(amount).quantize(cls.decimal_exp)

    def get_absolute_url(self):
        """
        Returns the URL for the detail view of this order
        """
        return urljoin(OrderModel.objects.get_summary_url(), self.get_number())

    @transition(field=status, source='new', target='created')
    def populate_from_cart(self, cart, request):
        """
        Populate the order object with the fields from the given cart. Override this method,
        in case a customized cart has some fields which have to be transfered to the cart.
        """
        self._subtotal = Decimal(cart.subtotal)
        self._total = Decimal(cart.total)
        self.extra = dict(cart.extra)
        self.extra.update(
            rows=[(modifier, extra_row.data)
                  for modifier, extra_row in cart.extra_rows.items()])

    @transaction.atomic
    def readd_to_cart(self, cart):
        """
        Re-add the items of this order back to the cart.
        """
        for order_item in self.items.all():
            extra = dict(order_item.extra)
            extra.pop('rows', None)
            cart_item = order_item.product.is_in_cart(cart, **extra)
            if cart_item:
                cart_item.quantity = max(cart_item.quantity,
                                         order_item.quantity)
            else:
                cart_item = CartItemModel(cart=cart,
                                          product=order_item.product,
                                          quantity=order_item.quantity,
                                          extra=extra)
            cart_item.save()

    def save(self, **kwargs):
        """
        The status of an Order object my change, if auto transistions are specified.
        """
        auto_transition = self._auto_transitions.get(self.status)
        if callable(auto_transition):
            auto_transition(self)

        # round the total to the given decimal_places
        self._subtotal = BaseOrder.round_amount(self._subtotal)
        self._total = BaseOrder.round_amount(self._total)
        super(BaseOrder, self).save(**kwargs)

    @cached_property
    def amount_paid(self):
        """
        The amount paid is the sum of related orderpayments
        """
        amount = self.orderpayment_set.aggregate(
            amount=Sum('amount'))['amount']
        if amount is None:
            amount = MoneyMaker(self.currency)()
        return amount

    @property
    def outstanding_amount(self):
        """
        Return the outstanding amount paid for this order
        """
        return self.total - self.amount_paid

    def is_fully_paid(self):
        return self.amount_paid >= self.total

    @transition(field='status',
                source='*',
                target='payment_confirmed',
                conditions=[is_fully_paid])
    def acknowledge_payment(self, by=None):
        """
        Change status to `payment_confirmed`. This status code is known globally and can be used
        by all external plugins to check, if an Order object has been fully paid.
        """

    @classmethod
    def get_transition_name(cls, target):
        """Return the human readable name for a given transition target"""
        return cls._transition_targets.get(target, target)

    def status_name(self):
        """Return the human readable name for the current transition state"""
        return self._transition_targets.get(self.status, self.status)

    status_name.short_description = pgettext_lazy('order_models', "State")
예제 #20
0
class BaseCartItem(models.Model, metaclass=deferred.ForeignKeyBuilder):
    """
    This is a holder for the quantity of items in the cart and, obviously, a
    pointer to the actual Product being purchased
    """
    cart = deferred.ForeignKey(
        'BaseCart',
        on_delete=models.CASCADE,
        related_name='items',
    )

    product = deferred.ForeignKey(
        BaseProduct,
        on_delete=models.CASCADE,
    )

    product_code = models.CharField(
        _("Product code"),
        max_length=255,
        null=True,
        blank=True,
        help_text=_("Product code of added item."),
    )

    updated_at = models.DateTimeField(
        _("Updated at"),
        auto_now=True,
    )

    extra = JSONField(
        verbose_name=_("Arbitrary information for this cart item"))

    objects = CartItemManager()

    class Meta:
        abstract = True
        verbose_name = _("Cart item")
        verbose_name_plural = _("Cart items")

    @classmethod
    def check(cls, **kwargs):
        errors = super().check(**kwargs)
        allowed_types = [
            'IntegerField', 'SmallIntegerField', 'PositiveIntegerField',
            'PositiveSmallIntegerField', 'DecimalField', 'FloatField'
        ]
        for field in cls._meta.fields:
            if field.attname == 'quantity':
                if field.get_internal_type() not in allowed_types:
                    msg = "Class `{}.quantity` must be of one of the types: {}."
                    errors.append(
                        checks.Error(msg.format(cls.__name__, allowed_types)))
                break
        else:
            msg = "Class `{}` must implement a field named `quantity`."
            errors.append(checks.Error(msg.format(cls.__name__)))
        return errors

    def __init__(self, *args, **kwargs):
        # reduce the given fields to what the model actually can consume
        all_field_names = [
            field.name for field in self._meta.get_fields(include_parents=True)
        ]
        model_kwargs = {
            k: v
            for k, v in kwargs.items() if k in all_field_names
        }
        super().__init__(*args, **model_kwargs)
        self.extra_rows = OrderedDict()
        self._dirty = True

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        self.cart.save(update_fields=['updated_at'])
        self._dirty = True

    def update(self, request):
        """
        Loop over all registered cart modifier, change the price per cart item and optionally add
        some extra rows.
        """
        if not self._dirty:
            return
        self.refresh_from_db()
        self.extra_rows = OrderedDict()  # reset the dictionary
        for modifier in cart_modifiers_pool.get_all_modifiers():
            modifier.process_cart_item(self, request)
        self._dirty = False
예제 #21
0
class BaseOrderItem(models.Model, metaclass=deferred.ForeignKeyBuilder):
    """
    An item for an order.
    """
    order = deferred.ForeignKey(
        BaseOrder,
        on_delete=models.CASCADE,
        related_name='items',
        verbose_name=_("Order"),
    )

    product_name = models.CharField(
        _("Product name"),
        max_length=255,
        null=True,
        blank=True,
        help_text=_("Product name at the moment of purchase."),
    )

    product_code = models.CharField(
        _("Product code"),
        max_length=255,
        null=True,
        blank=True,
        help_text=_("Product code at the moment of purchase."),
    )

    product = deferred.ForeignKey(
        BaseProduct,
        on_delete=models.SET_NULL,
        verbose_name=_("Product"),
        null=True,
        blank=True,
    )

    _unit_price = models.DecimalField(
        _("Unit price"),
        null=True,  # may be NaN
        help_text=_("Products unit price at the moment of purchase."),
        **BaseOrder.decimalfield_kwargs)

    _line_total = models.DecimalField(
        _("Line Total"),
        null=True,  # may be NaN
        help_text=_("Line total on the invoice at the moment of purchase."),
        **BaseOrder.decimalfield_kwargs)

    extra = JSONField(
        verbose_name=_("Extra fields"),
        help_text=_("Arbitrary information for this order item"),
    )

    class Meta:
        abstract = True
        verbose_name = pgettext_lazy('order_models', "Ordered Item")
        verbose_name_plural = pgettext_lazy('order_models', "Ordered Items")

    def __str__(self):
        return self.product_name

    @classmethod
    def check(cls, **kwargs):
        errors = super().check(**kwargs)
        for cart_field in CartItemModel._meta.fields:
            if cart_field.attname == 'quantity':
                break
        else:
            msg = "Class `{}` must implement a field named `quantity`."
            errors.append(checks.Error(msg.format(CartItemModel.__name__)))
        for field in cls._meta.fields:
            if field.attname == 'quantity':
                if field.get_internal_type() != cart_field.get_internal_type():
                    msg = "Field `{}.quantity` must be of same type as `{}.quantity`."
                    errors.append(
                        checks.Error(
                            msg.format(cls.__name__, CartItemModel.__name__)))
                break
        else:
            msg = "Class `{}` must implement a field named `quantity`."
            errors.append(checks.Error(msg.format(cls.__name__)))
        return errors

    @property
    def unit_price(self):
        return MoneyMaker(self.order.currency)(self._unit_price)

    @property
    def line_total(self):
        return MoneyMaker(self.order.currency)(self._line_total)

    def populate_from_cart_item(self, cart_item, request):
        """
        From a given cart item, populate the current order item.
        If the operation was successful, the given item shall be removed from the cart.
        If an exception of type :class:`CartItem.DoesNotExist` is raised, discard the order item.
        """
        if cart_item.quantity == 0:
            raise CartItemModel.DoesNotExist("Cart Item is on the Wish List")
        kwargs = {'product_code': cart_item.product_code}
        kwargs.update(cart_item.extra)
        cart_item.product.deduct_from_stock(cart_item.quantity, **kwargs)
        self.product = cart_item.product
        # for historical integrity, store the product's name and price at the moment of purchase
        self.product_name = cart_item.product.product_name
        self.product_code = cart_item.product_code
        self._unit_price = Decimal(cart_item.unit_price)
        self._line_total = Decimal(cart_item.line_total)
        self.quantity = cart_item.quantity
        self.extra = dict(cart_item.extra)
        extra_rows = [(modifier, extra_row.data)
                      for modifier, extra_row in cart_item.extra_rows.items()]
        self.extra.update(rows=extra_rows)

    def save(self, *args, **kwargs):
        """
        Before saving the OrderItem object to the database, round the amounts to the given decimal places
        """
        self._unit_price = BaseOrder.round_amount(self._unit_price)
        self._line_total = BaseOrder.round_amount(self._line_total)
        super().save(*args, **kwargs)
예제 #22
0
class BaseOrder(models.Model, metaclass=WorkflowMixinMetaclass):
    """
    An Order is the "in process" counterpart of the shopping cart, which freezes the state of the
    cart on the moment of purchase. It also holds stuff like the shipping and billing addresses,
    and keeps all the additional entities, as determined by the cart modifiers.
    """
    TRANSITION_TARGETS = {
        'new': _("New order without content"),
        'created': _("Order freshly created"),
        'payment_confirmed': _("Payment confirmed"),
        'payment_declined': _("Payment declined"),
    }
    decimalfield_kwargs = {
        'max_digits': 30,
        'decimal_places': 2,
    }
    decimal_exp = Decimal('.' + '0' * decimalfield_kwargs['decimal_places'])

    customer = deferred.ForeignKey(
        'BaseCustomer',
        on_delete=models.PROTECT,
        verbose_name=_("Customer"),
        related_name='orders',
    )

    status = FSMField(
        default='new',
        protected=True,
        verbose_name=_("Status"),
    )

    currency = models.CharField(
        max_length=7,
        editable=False,
        help_text=_("Currency in which this order was concluded"),
    )

    _subtotal = models.DecimalField(_("Subtotal"), **decimalfield_kwargs)

    _total = models.DecimalField(_("Total"), **decimalfield_kwargs)

    created_at = models.DateTimeField(
        _("Created at"),
        auto_now_add=True,
    )

    updated_at = models.DateTimeField(
        _("Updated at"),
        auto_now=True,
    )

    extra = JSONField(
        verbose_name=_("Extra fields"),
        help_text=
        _("Arbitrary information for this order object on the moment of purchase."
          ),
    )

    stored_request = JSONField(help_text=_(
        "Parts of the Request objects on the moment of purchase."), )

    objects = OrderManager()

    class Meta:
        abstract = True

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.logger = logging.getLogger('shop.order')

    def __str__(self):
        return self.get_number()

    def __repr__(self):
        return "<{}(pk={})>".format(self.__class__.__name__, self.pk)

    def get_or_assign_number(self):
        """
        Hook to get or to assign the order number. It shall be invoked, every time an Order
        object is created. If you prefer to use an order number which differs from the primary
        key, then override this method.
        """
        return self.get_number()

    def get_number(self):
        """
        Hook to get the order number.
        A class inheriting from Order may transform this into a string which is better readable.
        """
        return str(self.pk)

    def assign_secret(self):
        """
        Hook to assign a secret to authorize access on this Order object without authentication.
        """

    @property
    def secret(self):
        """
        Hook to return a secret if available.
        """

    @classmethod
    def resolve_number(cls, number):
        """
        Return a lookup pair used to filter down a queryset.
        It should revert the effect from the above method `get_number`.
        """
        return dict(pk=number)

    @property
    def subtotal(self):
        """
        The summed up amount for all ordered items excluding extra order lines.
        """
        return MoneyMaker(self.currency)(self._subtotal)

    @property
    def total(self):
        """
        The final total to charge for this order.
        """
        return MoneyMaker(self.currency)(self._total)

    @classmethod
    def round_amount(cls, amount):
        if amount.is_finite():
            return Decimal(amount).quantize(cls.decimal_exp)

    def get_absolute_url(self):
        """
        Returns the URL for the detail view of this order.
        """
        return urljoin(OrderModel.objects.get_summary_url(), self.get_number())

    @transaction.atomic
    @transition(field=status, source='new', target='created')
    def populate_from_cart(self, cart, request):
        """
        Populate the order object with the fields from the given cart.
        For each cart item a corresponding order item is created populating its fields and removing
        that cart item.

        Override this method, in case a customized cart has some fields which have to be transferred
        to the cart.
        """
        assert hasattr(cart, 'subtotal') and hasattr(cart, 'total'), \
            "Did you forget to invoke 'cart.update(request)' before populating from cart?"
        for cart_item in cart.items.all():
            cart_item.update(request)
            order_item = OrderItemModel(order=self)
            try:
                order_item.populate_from_cart_item(cart_item, request)
                order_item.save()
                cart_item.delete()
            except CartItemModel.DoesNotExist:
                pass
        self._subtotal = Decimal(cart.subtotal)
        self._total = Decimal(cart.total)
        self.extra = dict(cart.extra)
        self.extra.update(
            rows=[(modifier, extra_row.data)
                  for modifier, extra_row in cart.extra_rows.items()])
        self.save()

    @transaction.atomic
    def readd_to_cart(self, cart):
        """
        Re-add the items of this order back to the cart.
        """
        for order_item in self.items.all():
            extra = dict(order_item.extra)
            extra.pop('rows', None)
            extra.update(product_code=order_item.product_code)
            cart_item = order_item.product.is_in_cart(cart, **extra)
            if cart_item:
                cart_item.quantity = max(cart_item.quantity,
                                         order_item.quantity)
            else:
                cart_item = CartItemModel(cart=cart,
                                          product=order_item.product,
                                          product_code=order_item.product_code,
                                          quantity=order_item.quantity,
                                          extra=extra)
            cart_item.save()

    def save(self, with_notification=False, **kwargs):
        """
        :param with_notification: If ``True``, all notifications for the state of this Order object
        are executed.
        """
        from shop.transition import transition_change_notification

        auto_transition = self._auto_transitions.get(self.status)
        if callable(auto_transition):
            auto_transition(self)

        # round the total to the given decimal_places
        self._subtotal = BaseOrder.round_amount(self._subtotal)
        self._total = BaseOrder.round_amount(self._total)
        super().save(**kwargs)
        if with_notification:
            transition_change_notification(self)

    @cached_property
    def amount_paid(self):
        """
        The amount paid is the sum of related orderpayments
        """
        amount = self.orderpayment_set.aggregate(
            amount=Sum('amount'))['amount']
        if amount is None:
            amount = MoneyMaker(self.currency)()
        return amount

    @property
    def outstanding_amount(self):
        """
        Return the outstanding amount paid for this order
        """
        return self.total - self.amount_paid

    def is_fully_paid(self):
        return self.amount_paid >= self.total

    @transition(field='status',
                source='*',
                target='payment_confirmed',
                conditions=[is_fully_paid])
    def acknowledge_payment(self, by=None):
        """
        Change status to ``payment_confirmed``. This status code is known globally and can be used
        by all external plugins to check, if an Order object has been fully paid.
        """
        self.logger.info("Acknowledge payment by user %s", by)

    def cancelable(self):
        """
        A hook method to be overridden by mixin classes managing Order cancellations.

        :returns: ``True`` if the current Order is cancelable.
        """
        return False

    def refund_payment(self):
        """
        Hook to handle payment refunds.
        """

    def withdraw_from_delivery(self):
        """
        Hook to withdraw shipping order.
        """

    @classmethod
    def get_all_transitions(cls):
        """
        :returns: A generator over all transition objects for this Order model.
        """
        return cls.status.field.get_all_transitions(OrderModel)

    @classmethod
    def get_transition_name(cls, target):
        """
        :returns: The verbose name for a given transition target.
        """
        return cls._transition_targets.get(target, target)

    def status_name(self):
        """
        :returns: The verbose name for the current transition state.
        """
        return self._transition_targets.get(self.status, self.status)

    status_name.short_description = pgettext_lazy('order_models', "State")