Source

django-lfs / lfs / core / templatetags / lfs_tags.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
# python imports
import math
import locale

# django imports
from django import template
from django.conf import settings
from django.core.cache import cache
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.template import Node, TemplateSyntaxError
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _

# lfs imports
import lfs.catalog.utils
import lfs.core.utils
import lfs.utils.misc
import logging
from lfs.caching.utils import lfs_get_object_or_404
from lfs.catalog.models import Category
from lfs.catalog.settings import CONFIGURABLE_PRODUCT
from lfs.catalog.settings import CATEGORY_VARIANT_CHEAPEST_PRICES
from lfs.catalog.settings import PRODUCT_WITH_VARIANTS
from lfs.catalog.settings import STANDARD_PRODUCT
from lfs.catalog.models import Product
from lfs.catalog.models import PropertyOption
from lfs.catalog.settings import PRODUCT_TYPE_LOOKUP
from lfs.core.models import Action
from lfs.page.models import Page
from lfs.shipping import utils as shipping_utils


logger = logging.getLogger("default")
register = template.Library()


@register.inclusion_tag('lfs/portlets/category_children.html', takes_context=True)
def category_children(context, categories):
    """
    """
    return {"categories": categories}


@register.inclusion_tag('lfs/shop/google_analytics_tracking.html', takes_context=True)
def google_analytics_tracking(context):
    """Returns google analytics tracking code which has been entered to the
    shop.
    """
    shop = lfs.core.utils.get_default_shop(context.get("request"))
    return {
        "ga_site_tracking": shop.ga_site_tracking,
        "google_analytics_id": shop.google_analytics_id,
    }


@register.inclusion_tag('lfs/shop/google_analytics_ecommerce.html', takes_context=True)
def google_analytics_ecommerce(context, clear_session=True):
    """Returns google analytics e-commerce tracking code. This should be
    displayed on the thank-you page.
    """
    request = context.get("request")
    order = request.session.get("order")
    shop = lfs.core.utils.get_default_shop(request)

    # The order is removed from the session. It has been added after the order
    # has been payed within the checkout process. See order.utils for more.
    if clear_session and "order" in request.session:
        del request.session["order"]

    if "voucher" in request.session:
        del request.session["voucher"]

    return {
        "order": order,
        "ga_ecommerce_tracking": shop.ga_ecommerce_tracking,
        "google_analytics_id": shop.google_analytics_id,
    }


def _get_shipping(context, product):
    request = context.get("request")
    if product.is_deliverable() == False:
        return {
            "deliverable": False,
            "delivery_time": shipping_utils.get_product_delivery_time(request, product)
        }
    else:
        return {
            "deliverable": True,
            "delivery_time": shipping_utils.get_product_delivery_time(request, product)
        }


@register.inclusion_tag('lfs/shipping/shipping_tag.html', takes_context=True)
def shipping(context, variant):
    return _get_shipping(context, variant)


@register.inclusion_tag('lfs/catalog/sorting.html', takes_context=True)
def sorting(context):
    """
    """
    request = context.get("request")
    return {"current": request.session.get("sorting")}


@register.inclusion_tag('lfs/catalog/breadcrumbs.html', takes_context=True)
def breadcrumbs(context, obj):
    """
    """
    if isinstance(obj, Category):
        cache_key = "%s-category-breadcrumbs-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, obj.slug)
        objects = cache.get(cache_key)
        if objects is not None:
            return objects

        objects = []
        while obj is not None:
            objects.insert(0, {
                "name": obj.name,
                "url": obj.get_absolute_url(),
            })
            obj = obj.parent

        result = {
            "objects": objects,
            "STATIC_URL": context.get("STATIC_URL"),
        }
        cache.set(cache_key, result)

    elif isinstance(obj, Product):
        try:
            if obj.is_variant():
                parent_product = obj.parent
            else:
                parent_product = obj
        except ObjectDoesNotExist:
            return []
        else:
            request = context.get("request")
            category = obj.get_current_category(request)
            if category is None:
                return []
            else:
                objects = [{
                    "name": obj.get_name(),
                    "url": obj.get_absolute_url(),
                }]
                while category is not None:
                    objects.insert(0, {
                        "name": category.name,
                        "url": category.get_absolute_url(),
                    })
                    category = category.parent

        result = {
            "objects": objects,
            "STATIC_URL": context.get("STATIC_URL"),
        }

    elif isinstance(obj, Page):
        objects = []
        objects.append({
            "name": _(u"Information"),
            "url": reverse("lfs_pages")})
        objects.append({"name": obj.title})

        result = {
            "objects": objects,
            "STATIC_URL": context.get("STATIC_URL"),
        }
    else:
        result = {
            "objects": ({"name": obj},),
            "STATIC_URL": context.get("STATIC_URL"),
        }

    return result


@register.inclusion_tag('lfs/catalog/product_navigation.html', takes_context=True)
def product_navigation(context, product):
    """Provides previous and next product links.
    """
    request = context.get("request")
    sorting = request.session.get("sorting", "price")
    if sorting == "":
        sorting = "price"

    slug = product.slug

    cache_key = "%s-product-navigation-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, slug)
    temp = None  # cache.get(cache_key)

    if temp is not None:
        try:
            return temp[sorting]
        except KeyError:
            pass
    else:
        temp = dict()

    # To calculate the position we take only STANDARD_PRODUCT into account.
    # That means if the current product is a VARIANT we switch to its parent
    # product.
    if product.is_variant():
        product = product.parent
        slug = product.slug

    category = product.get_current_category(request)
    if category is None:
        return {"display": False}
    else:
        # First we collect all sub categories. This and using the in operator makes
        # batching more easier
        categories = [category]

        if category.show_all_products:
            categories.extend(category.get_all_children())

        # This is necessary as we display non active products to superusers.
        # So we have to take care for the product navigation too.
        if request.user.is_superuser:
            products = Product.objects.filter(
                categories__in=categories,
                sub_type__in=(STANDARD_PRODUCT, PRODUCT_WITH_VARIANTS, CONFIGURABLE_PRODUCT),
            ).distinct().order_by(sorting)
        else:
            products = Product.objects.filter(
                categories__in=categories,
                sub_type__in=(STANDARD_PRODUCT, PRODUCT_WITH_VARIANTS, CONFIGURABLE_PRODUCT),
                active=True,
            ).distinct().order_by(sorting)

        product_slugs = [p.slug for p in products]
        product_index = product_slugs.index(slug)

        if product_index > 0:
            previous = product_slugs[product_index - 1]
        else:
            previous = None

        total = len(product_slugs)
        if product_index < total - 1:
            next = product_slugs[product_index + 1]
        else:
            next = None

        result = {
            "display": True,
            "previous": previous,
            "next": next,
            "current": product_index + 1,
            "total": total,
            "STATIC_URL": context.get("STATIC_URL"),
        }

        temp[sorting] = result
        cache.set(cache_key, temp)

        return result


class ActionsNode(Node):
    """
    Node for do_actions.
    """
    def __init__(self, group_name):
        self.group_name = group_name

    def render(self, context):
        request = context.get("request")
        context["actions"] = Action.objects.filter(active=True, group__name=self.group_name)
        return ''


def do_actions(parser, token):
    """
    Returns the actions for the group with the given id.
    """
    bits = token.contents.split()
    len_bits = len(bits)
    if len_bits != 2:
        raise TemplateSyntaxError(_('%s tag needs group id as argument') % bits[0])
    return ActionsNode(bits[1])
register.tag('actions', do_actions)


class CheapestVariantNode(Node):
    """
    Node for do_cheapest_variant.
    """
    def __init__(self, product_id):
        self.product_id = template.Variable(product_id)

    def render(self, context):
        product_id = self.product_id.resolve(context)
        request = context.get("request")
        cheapest_variant = None
        min_price = None
        for variant in Product.objects.filter(parent__id=product_id):
            price = variant.get_price_gross(request)
            if price == 0:
                continue
            if (min_price is None) or (price < min_price):
                cheapest_variant = variant
                min_price = price

        context["cheapest_variant"] = cheapest_variant
        return ""


def do_cheapest_variant(parser, token):
    """
    Returns the cheapest variant for the product with given id.
    """
    bits = token.contents.split()
    len_bits = len(bits)
    if len_bits != 2:
        raise TemplateSyntaxError('%s tag needs product id as argument' % bits[0])
    return CheapestVariantNode(bits[1])
register.tag('cheapest_variant', do_cheapest_variant)


@register.inclusion_tag('lfs/shop/tabs.html', takes_context=True)
def tabs(context, obj=None):
    """
    """
    if obj is None:
        obj = context.get("product") or context.get("category")

    request = context.get("request")
    tabs = Action.objects.filter(active=True, group=1)
    if isinstance(obj, (Product, Category)):
        top_category = lfs.catalog.utils.get_current_top_category(request, obj)
        if top_category:
            for tab in tabs:
                if top_category.get_absolute_url().find(tab.link) != -1:
                    tab.selected = True
                    break
    else:
        for tab in tabs:
            if request.path.find(tab.link) != -1:
                tab.selected = True
                break

    return {
        "tabs": tabs,
        "STATIC_URL": context.get("STATIC_URL"),
    }


@register.inclusion_tag('lfs/catalog/top_level_categories.html', takes_context=True)
def top_level_categories(context):
    """Displays the top level categories.
    """
    request = context.get("request")
    obj = context.get("product") or context.get("category")

    categories = []
    top_category = lfs.catalog.utils.get_current_top_category(request, obj)

    for category in Category.objects.filter(parent=None)[:4]:

        if top_category:
            current = top_category.id == category.id
        else:
            current = False

        categories.append({
            "url": category.get_absolute_url(),
            "name": category.name,
            "current": current,
        })

    return {
        "categories": categories,
    }


class TopLevelCategory(Node):
    """Calculates the current top level category.
    """
    def render(self, context):
        request = context.get("request")
        obj = context.get("product") or context.get("category")

        top_level_category = lfs.catalog.utils.get_current_top_category(request, obj)
        context["top_level_category"] = top_level_category.name
        return ''


def do_top_level_category(parser, token):
    """Calculates the current top level category.
    """
    bits = token.contents.split()
    len_bits = len(bits)
    if len_bits != 1:
        raise TemplateSyntaxError(_('%s tag needs no argument') % bits[0])

    return TopLevelCategory()
register.tag('top_level_category', do_top_level_category)


class CartInformationNode(Node):
    """
    """
    def render(self, context):
        request = context.get("request")
        cart = lfs.cart.utils.get_cart(request)
        if cart is None:
            amount_of_items = 0
            price = 0.0
        else:
            amount_of_items = cart.get_amount_of_items()
            price = cart.get_price_gross(request, total=True)

        context["cart_amount_of_items"] = amount_of_items
        context["cart_price"] = price
        return ''


def do_cart_information(parser, token):
    """Calculates cart informations.
    """
    bits = token.contents.split()
    len_bits = len(bits)
    if len_bits != 1:
        raise TemplateSyntaxError(_('%s tag needs no argument') % bits[0])

    return CartInformationNode()
register.tag('cart_information', do_cart_information)


class CurrentCategoryNode(Node):
    """
    """
    def render(self, context):
        request = context.get("request")
        product = context.get("product")

        context["current_category"] = \
            product.get_current_category(request)
        return ''


def do_current_category(parser, token):
    """Calculates current category.
    """
    bits = token.contents.split()
    len_bits = len(bits)
    if len_bits != 2:
        raise TemplateSyntaxError(_('%s tag needs product as argument') % bits[0])

    return CurrentCategoryNode()
register.tag('current_category', do_current_category)


# TODO: Move this to shop utils or similar
def get_slug_from_request(request):
    """Returns the slug of the currently displayed category.
    """
    slug = request.path.split("/")[-1]
    try:
        int(slug)
    except ValueError:
        pass
    else:
        slug = request.path.split("/")[-2]

    return slug


@register.filter
def currency(value, request=None, grouping=True):
    """
    Returns the currency based on the given locale within settings.LFS_LOCALE

    e.g.

    import locale
    locale.setlocale(locale.LC_ALL, 'de_CH.UTF-8')
    currency(123456.789)  # Fr. 123'456.79
    currency(-123456.789) # <span class="negative">Fr. -123'456.79</span>
    """
    if not value:
        value = 0.0

    shop = lfs.core.utils.get_default_shop(request)
    try:
        result = locale.currency(value, grouping=grouping, international=shop.use_international_currency_code)
    except ValueError, e:
        result = value
        logger.error("currency filter: %s" % e)

    # add css class if value is negative
    if value < 0:
        # replace the minus symbol if needed
        if result[-1] == '-':
            length = len(locale.nl_langinfo(locale.CRNCYSTR))
            result = '%s-%s' % (result[0:length], result[length:-1])
        return mark_safe('<span class="negative">%s</span>' % result)
    return result


@register.filter
def decimal_l10n(value, digits=2):
    """Returns the decimal value of value based on current locale.
    """
    try:
        value = float(value)
    except ValueError:
        return value

    format_str = "%%.%sf" % digits
    return locale.format_string(format_str, value)


@register.filter
def quantity(quantity):
    """Removes the decimal places when they are zero.

    Means "1.0" is transformed to "1", whereas "1.1" is not transformed at all.
    """
    if str(quantity).find(".0") == -1:
        return quantity
    else:
        return int(float(quantity))


@register.filter
def sub_type_name(sub_type, arg=None):
    """Returns the sub type name for the sub type with passed sub_type id.
    """
    try:
        return PRODUCT_TYPE_LOOKUP[sub_type]
    except KeyError:
        return ""


@register.filter
def multiply(score, pixel):
    """Returns the result of score * pixel
    """
    return score * pixel


@register.filter
def option_name(option_id):
    """Returns the option name for option with passed id.
    """
    try:
        option_id = int(float(option_id))
    except ValueError:
        pass

    try:
        option = PropertyOption.objects.get(pk=option_id)
    except (PropertyOption.DoesNotExist, ValueError):
        return option_id
    else:
        return option.name


@register.filter
def option_name_for_property_value(property_value):
    """Returns the value or the option name for passed property_value
    """
    if property_value.property.is_select_field:
        try:
            option_id = int(float(property_value.value))
        except ValueError:
            return property_value.value

        try:
            option = PropertyOption.objects.get(pk=option_id)
        except (PropertyOption.DoesNotExist, ValueError):
            return option_id
        else:
            return option.name

    return property_value.value


@register.filter
def packages(cart_item):
    """Returns the packages based on product's package unit and cart items
    amount.
    """
    if cart_item.product.packing_unit:
        return int(math.ceil(float(cart_item.amount) / cart_item.product.packing_unit))
    return 0


class CategoryProductPricesGrossNode(Node):
    """
    Node to calculate needed gross prices of a product for the category view.
    """
    def __init__(self, product_id):
        self.product_id = template.Variable(product_id)

    def render(self, context):
        request = context.get("request")

        product_id = self.product_id.resolve(context)
        product = Product.objects.get(pk=product_id)

        if product.is_variant():
            parent = product.parent
        else:
            parent = product

        if parent.category_variant == CATEGORY_VARIANT_CHEAPEST_PRICES:
            if product.get_for_sale():
                info = parent.get_cheapest_standard_price_gross(request)
                context["standard_price"] = info["price"]
                context["standard_price_starting_from"] = info["starting_from"]

            info = parent.get_cheapest_price_gross(request)
            context["price"] = info["price"]
            context["price_starting_from"] = info["starting_from"]

            info = parent.get_cheapest_base_price_gross(request)
            context["base_price"] = info["price"]
            context["base_price_starting_from"] = info["starting_from"]
        else:
            if product.get_for_sale():
                context["standard_price"] = product.get_standard_price(request)
            context["price"] = product.get_price_gross(request)
            context["price_starting_from"] = False

            context["base_price"] = product.get_base_price_gross(request)
            context["base_price_starting_from"] = False

        if product.get_active_packing_unit():
            context["base_packing_price"] = product.get_base_packing_price_gross(request)

        return ""


def do_category_product_prices_gross(parser, token):
    """
    Calculates needed gross price of a product for the category view.
    """
    bits = token.contents.split()
    if len(bits) != 2:
        raise TemplateSyntaxError('%s tag needs product id as argument' % bits[0])
    return CategoryProductPricesGrossNode(bits[1])
register.tag('category_product_prices_gross', do_category_product_prices_gross)


@register.filter(name='get_price')
def get_price_net(product, request):
    return product.get_price(request)


@register.filter(name='get_price_net')
def get_price_net(product, request):
    return product.get_price_net(request)


@register.filter(name='get_price_gross')
def get_price_gross(product, request):
    return product.get_price_gross(request)


@register.filter(name='get_standard_price')
def get_standard_price(product, request):
    return product.get_standard_price(request)


@register.filter(name='get_standard_price_net')
def get_standard_price_net(product, request):
    return product.get_standard_price_net(request)


@register.filter(name='get_standard_price_gross')
def get_standard_price_gross(product, request):
    return product.get_standard_price_gross(request)


@register.filter(name='get_for_sale_price')
def get_for_sale_price(product, request):
    return product.get_for_sale_price(request)


@register.filter(name='get_for_sale_price_net')
def get_for_sale_price_net(product, request):
    return product.get_for_sale_price_net(request)


@register.filter(name='get_for_sale_price_gross')
def get_for_sale_price_gross(product, request):
    return product.get_for_sale_price_gross(request)


@register.filter(name='get_base_price')
def get_base_price(product, request):
    return product.get_base_price(request)


@register.filter(name='get_base_price_net')
def get_base_price_net(product, request):
    return product.get_base_price_net(request)


@register.filter(name='get_base_price_gross')
def get_base_price_gross(product, request):
    return product.get_base_price_gross(request)


@register.filter(name='get_base_packing_price')
def get_base_packing_price(product, request):
    return product.get_base_packing_price(request)


@register.filter(name='get_base_packing_price_net')
def get_base_packing_price_net(product, request):
    return product.get_base_packing_price_net(request)


@register.filter(name='get_base_packing_price_gross')
def get_base_packing_price_gross(product, request):
    return product.get_base_packing_price_gross(request)