|
1
|
|
|
# -*- coding: utf-8 -*- |
|
2
|
|
|
import six |
|
3
|
|
|
from django.db.models import Q |
|
4
|
|
|
from django.utils.translation import ugettext_lazy as _ |
|
5
|
|
|
|
|
6
|
|
|
from shoop.core.models import ShopProduct |
|
7
|
|
|
from shoop.core.pricing import PriceInfo, PricingContext, PricingModule |
|
8
|
|
|
|
|
9
|
|
|
from .models import ReservableProductPrice |
|
10
|
|
|
|
|
11
|
|
|
|
|
12
|
|
|
class ReservablePricingContext(PricingContext): |
|
13
|
|
|
REQUIRED_VALUES = ("customer_group_ids", "shop") |
|
14
|
|
|
customer_group_ids = () |
|
15
|
|
|
shop = None |
|
16
|
|
|
|
|
17
|
|
|
|
|
18
|
|
|
class ReservablePricingModule(PricingModule): |
|
19
|
|
|
identifier = "reservable_pricing" |
|
20
|
|
|
name = _("Reservable Pricing") |
|
21
|
|
|
|
|
22
|
|
|
pricing_context_class = ReservablePricingContext |
|
23
|
|
|
|
|
24
|
|
|
def get_context_from_request(self, request): |
|
25
|
|
|
customer = getattr(request, "customer", None) |
|
26
|
|
|
|
|
27
|
|
|
if not customer or customer.is_anonymous: |
|
28
|
|
|
customer_group_ids = [] |
|
29
|
|
|
else: |
|
30
|
|
|
customer_group_ids = sorted(customer.groups.all().values_list("id", flat=True)) |
|
31
|
|
|
|
|
32
|
|
|
return self.pricing_context_class( |
|
33
|
|
|
shop=request.shop, |
|
34
|
|
|
customer_group_ids=customer_group_ids |
|
35
|
|
|
) |
|
36
|
|
|
|
|
37
|
|
|
def get_price_info(self, context, product, quantity=1): |
|
38
|
|
|
shop = context.shop |
|
39
|
|
|
|
|
40
|
|
|
if isinstance(product, six.integer_types): |
|
41
|
|
|
product_id = product |
|
42
|
|
|
shop_product = ShopProduct.objects.get(product_id=product_id, shop=shop) |
|
43
|
|
|
else: |
|
44
|
|
|
shop_product = product.get_shop_instance(shop) |
|
45
|
|
|
product_id = product.pk |
|
46
|
|
|
|
|
47
|
|
|
default_price = (shop_product.default_price_value or 0) |
|
48
|
|
|
|
|
49
|
|
|
if context.customer_group_ids: |
|
50
|
|
|
filter = Q( |
|
|
|
|
|
|
51
|
|
|
price_value__gt=0, product=product_id, shop=shop, |
|
52
|
|
|
group__in=context.customer_group_ids) |
|
53
|
|
|
result = ( |
|
54
|
|
|
ReservableProductPrice.objects.filter(filter) |
|
|
|
|
|
|
55
|
|
|
.order_by("price_value")[:1] |
|
56
|
|
|
.values_list("price_value", flat=True) |
|
57
|
|
|
) |
|
58
|
|
|
else: |
|
59
|
|
|
result = None |
|
60
|
|
|
|
|
61
|
|
|
if result: |
|
62
|
|
|
price = result[0] |
|
63
|
|
|
if default_price > 0: |
|
64
|
|
|
price = min([default_price, price]) |
|
65
|
|
|
else: |
|
66
|
|
|
price = default_price |
|
67
|
|
|
|
|
68
|
|
|
return PriceInfo( |
|
69
|
|
|
price=shop.create_price(price * quantity), |
|
70
|
|
|
base_price=shop.create_price(price * quantity), |
|
71
|
|
|
quantity=quantity, |
|
72
|
|
|
) |
|
73
|
|
|
|
It is generally discouraged to redefine built-ins as this makes code very hard to read.