Beispiel #1
0
 def get_context_data(self, **kwargs):
     context = super(ProductDetail, self).get_context_data(**kwargs)
     add_member_auto_profiletag(self.request, **kwargs)
     category_slug = kwargs['category_slug']
     product_slug = kwargs['product_slug']
     category = ProductCategory.objects.get(slug=category_slug)
     try:
         current_product = Product.objects.select_related('provider').filter(category=category, slug=product_slug)[0]
     except IndexError:
         raise Http404('No product matches the given query.')
     product = apply_promotion_discount([current_product])[0]
     category = product.category
     context['product'] = product
     product_uri = reverse('shopping:product_detail', args=(category.slug, product.slug))
     product_uri = product_uri.replace(getattr(settings, 'WSGI_SCRIPT_ALIAS', ''), '')
     context['product_uri'] = product_uri
     base_queryset = Product.objects.select_related('provider')\
         .exclude(pk=product.id).filter(visible=True, is_duplicate=False)
     suggestions = base_queryset.filter(category=category, brand=product.brand).order_by('-updated_on')[:6]
     if suggestions.count() < 6:
         additional = 6 - suggestions.count()
         exclude_list = [p.pk for p in suggestions]
         suggestions = list(suggestions)
         suggestions.extend(list(base_queryset.exclude(pk__in=exclude_list).filter(category=product.category)
                                 .order_by('-updated_on')[:additional]))
     suggestions = apply_promotion_discount(list(suggestions))
     context['suggestion_list'] = suggestions
     context['review_count'] = Review.objects.filter(product=product).count()
     context['review_list'] = Review.objects.filter(product=product).order_by('-id')[:50]
     service = get_service_instance()
     banks = []
     for p in OperatorProfile.objects.filter(business_type=OperatorProfile.BANK):
         try:
             banks.append(p.service)
         except:
             continue
     deal_list = []
     for bank in banks:
         try:
             bank_db = bank.database
             add_database(bank_db)
             deal = Deal.objects.using(bank_db)\
                 .filter(product_slug=product.slug, merchant=service, bank=bank).order_by('term_cost')[0]
             deal_list.append(deal)
         except:
             continue
     context['deal_list'] = deal_list
     member = self.request.user
     from daraja.models import Dara
     if member.is_authenticated():
         try:
             Review.objects.get(member=member, product=product)
         except Review.DoesNotExist:
             context['can_review'] = True
         try:
             Dara.objects.get(member=member)
             context['is_dara'] = True
         except Dara.DoesNotExist:
             pass
     return context
Beispiel #2
0
    def get_size_list(self):
        """
        Grabs sizes for product of the same category having the same slug
        """
        size_list = set([
            p.size for p in Product.objects.filter(category=self.category,
                                                   brand=self.brand,
                                                   slug=self.slug,
                                                   stock__gt=0).order_by('id')
            if p.size
        ])
        size_list_obj = []

        from ikwen_kakocase.sales.views import apply_promotion_discount
        for size in size_list:
            try:
                obj = Product.objects.filter(category=self.category,
                                             brand=self.brand,
                                             slug=self.slug,
                                             size=size)[0]
                obj = apply_promotion_discount([obj])[0]

                size_list_obj.append({
                    'id': obj.pk,
                    'label': obj.size,
                    'stock': obj.stock,
                    'retail_price': obj.retail_price,
                    'wholesale_price': obj.wholesale_price,
                    'packing_price': obj.packing_price,
                    'max_price': obj.max_price
                })
            except:
                pass
        return size_list_obj
Beispiel #3
0
    def get_context_data(self, **kwargs):
        context = super(Home, self).get_context_data(**kwargs)

        preview_sections_count = getattr(settings, 'PREVIEW_SECTIONS_COUNT', 7)
        preview_smart_categories = list(SmartCategory.objects
                                        .filter(items_count__gt=0, is_active=True, show_on_home=True)
                                        .order_by('order_of_appearance', 'title', '-updated_on')[:preview_sections_count])
        additional = preview_sections_count - len(preview_smart_categories)
        preview_categories = list(ProductCategory.objects
                                  .filter(items_count__gt=0, is_active=True, show_on_home=True)
                                  .order_by('order_of_appearance', 'name', '-updated_on')[:additional])
        to_be_removed = []
        for item in preview_categories:
            products = item.get_visible_items()
            products_list = apply_promotion_discount(list(products))
            item.as_matrix = as_matrix(products_list, self._get_row_len())
            if not item.as_matrix:
                to_be_removed.append(item)
        for item in to_be_removed:
            preview_categories.remove(item)
        to_be_removed = []
        for item in preview_smart_categories:
            if item.content_type == CATEGORIES:
                item.as_matrix = as_matrix(item.get_category_queryset(), CATEGORIES_PREVIEWS_PER_ROW)
            else:
                products = item.get_product_queryset()
                products_list = []
                if products:
                    products_list = apply_promotion_discount(list(products))
                item.as_matrix = as_matrix(products_list, self._get_row_len())
            if not item.as_matrix:
                to_be_removed.append(item)
        for item in to_be_removed:
            preview_smart_categories.remove(item)

        context['preview_categories'] = preview_categories
        context['preview_smart_categories'] = preview_smart_categories
        context['slideshow'] = Banner.objects.filter(display=SLIDE, is_active=True).order_by('order_of_appearance', '-id')
        context['home_tiles'] = Banner.objects.filter(display=TILES, is_active=True).order_by('order_of_appearance')
        context['popups'] = Banner.objects.filter(display=POPUP, is_active=True)
        fw_section_qs = Banner.objects.filter(display=FULL_WIDTH_SECTION, is_active=True).order_by('-id')
        context['fw_section'] = fw_section_qs[0] if fw_section_qs.count() > 0 else None
        fw_popup_qs = Banner.objects.filter(display=FULL_SCREEN_POPUP, is_active=True).order_by('-id')
        context['fs_popups'] = fw_popup_qs[0] if fw_popup_qs.count() > 0 else None
        return context
Beispiel #4
0
 def get_context_data(self, **kwargs):
     context = super(SingleProduct, self).get_context_data(**kwargs)
     context['template_cache_duration'] = 400
     service = get_service_instance()
     db = service.database
     add_database(db)
     # try:
     #     current_product = Product.objects.select_related('provider').filter(category=category)[0]
     # except IndexError:
     #     raise Http404('No product matches the given query.')
     current_product = Product.objects.using(db).filter(visible=True)[0]
     product = apply_promotion_discount([current_product])[0]
     category = product.category
     context['product'] = product
     context['category'] = category
     return context
Beispiel #5
0
    def render_to_response(self, context, **response_kwargs):
        if self.request.GET.get('format') == 'html_results':
            context['content_type'] = PRODUCTS
            product_queryset = self.get_queryset()
            if self.kwargs.get('category_slug'):
                slug = self.kwargs.get('category_slug')
                category = ProductCategory.objects.get(slug=slug)
                product_queryset = product_queryset.filter(category=category)
            elif self.kwargs.get('smart_category_slug'):
                slug = self.kwargs.get('smart_category_slug')
                try:
                    smart_object = Banner.objects.get(slug=slug)
                except Banner.DoesNotExist:
                    smart_object = SmartCategory.objects.get(slug=slug)
                product_queryset = smart_object.get_product_queryset()
            try:
                min_price = int(self.request.GET.get('min_price'))
                max_price = int(self.request.GET.get('max_price'))
                product_queryset = product_queryset.filter(Q(retail_price__gte=min_price) & Q(retail_price__lte=max_price))
            except:
                pass

            page_size = 9 if self.request.user_agent.is_mobile else 15
            order_by = str(self.request.GET['order_by'])
            product_queryset = self.get_search_results(product_queryset, max_chars=4)
            product_queryset = product_queryset.order_by(order_by)

            product_queryset = apply_promotion_discount(list(product_queryset))
            paginator = Paginator(product_queryset, page_size)
            page = self.request.GET.get('page')
            try:
                products_page = paginator.page(page)
                context['product_list_as_matrix'] = as_matrix(products_page.object_list, self._get_row_len())
            except PageNotAnInteger:
                products_page = paginator.page(1)
                context['product_list_as_matrix'] = as_matrix(products_page.object_list, self._get_row_len())
            except EmptyPage:
                products_page = paginator.page(paginator.num_pages)
                context['product_list_as_matrix'] = as_matrix(products_page.object_list, self._get_row_len())
            context['products_page'] = products_page
            return render(self.request, 'shopping/snippets/product_list_results.html', context)
        else:
            return super(ProductList, self).render_to_response(context, **response_kwargs)
Beispiel #6
0
    def test_apply_promotion_discount_on_product_list(self):
        """
            here we test the complete operation of the promotion management function;
            here for a given promotion, the test will determine if in the end, the promotion will normally apply
            where it is necessary and with the expected values

        """
        # promoted_category = ProductCategory.objects.get(pk='569228a9b37b3301e0706b52')
        # product_in_category = Product.objects.filter(category=promoted_category)
        all_site_product = Product.objects.all()
        specific_promoted_item, item_in_promoted_category, item_in_site = {}, {}, {}
        promotions = Promotion.objects.all()
        for promotion in promotions:
            promotion.is_active = True
            promotion.save()

        final_product_list = apply_promotion_discount(list(all_site_product))
        for product in final_product_list:
            if product.id == '55d1fa8feb60008099bd4152':  #Coca-Cola
                specific_promoted_item = product
            if product.id == '55d1fa8feb60008099bd4153':  #Mutzig
                item_in_promoted_category = product
            if product.id == '55d1fa8feb60008099bd4151':  #Samsung Galaxy S7
                item_in_site = product

        self.assertEqual(specific_promoted_item.name, 'Coca-Cola')
        self.assertEqual(specific_promoted_item.on_sale, True)
        self.assertEqual(specific_promoted_item.previous_price, 450)
        self.assertEqual(specific_promoted_item.retail_price, 405)

        self.assertEqual(item_in_promoted_category.name, 'Mutzig')
        self.assertEqual(item_in_promoted_category.on_sale, True)
        self.assertEqual(item_in_promoted_category.previous_price, 550)
        self.assertEqual(item_in_promoted_category.retail_price, 440)

        self.assertEqual(item_in_site.name, 'Samsung Galaxy S7')
        self.assertEqual(item_in_site.on_sale, True)
        self.assertEqual(item_in_site.previous_price, 480000)
        self.assertEqual(item_in_site.retail_price, 456000)
Beispiel #7
0
    def test_apply_promotion_discount_on_category_only(self):
        """
            here we test the complete operation of the promotion management function;
            here for a given promotion, the test will determine if at the end, the promotion will normally be apply
            on the category "Food" products only

        """
        all_site_product = Product.objects.all()
        specific_promoted_item, item_in_promoted_category, item_in_site = {}, {}, {}
        promotions = Promotion.objects.all()
        for promotion in promotions:
            promotion.is_active = False
            if promotion.category:
                promotion.is_active = True
            promotion.save()

        final_product_list = apply_promotion_discount(list(all_site_product))
        for product in final_product_list:
            if product.id == '55d1fa8feb60008099bd4152':
                specific_promoted_item = product
            if product.id == '55d1fa8feb60008099bd4153':
                item_in_promoted_category = product
            if product.id == '55d1fa8feb60008099bd4151':
                item_in_site = product

        self.assertEqual(specific_promoted_item.name, 'Coca-Cola')
        self.assertEqual(specific_promoted_item.on_sale, False)
        self.assertEqual(specific_promoted_item.retail_price, 450)

        self.assertEqual(item_in_promoted_category.name, 'Mutzig')
        self.assertEqual(item_in_promoted_category.on_sale, False)
        self.assertEqual(item_in_promoted_category.retail_price, 550)

        self.assertEqual(item_in_site.name, 'Samsung Galaxy S7')
        self.assertEqual(item_in_site.on_sale, True)
        self.assertEqual(item_in_site.previous_price, 480000)
        self.assertEqual(item_in_site.retail_price, 456000)
Beispiel #8
0
def parse_order_info(request):
    from ikwen_kakocase.kako.models import Product
    from ikwen_kakocase.shopping.models import Customer, AnonymousBuyer, DeliveryAddress
    from ikwen_kakocase.trade.models import OrderEntry, Order
    from ikwen_kakocase.kakocase.models import DeliveryOption

    entries = request.POST['entries'].split(',')
    delivery_option_id = request.POST['delivery_option_id']
    buy_packing = request.POST.get('buy_packing', False)
    try:
        currency = Currency.objects.get(code=request.session[CURRENCY_SESSION_KEY])
    except KeyError:
        currency = Currency.active.base()
    except Currency.DoesNotExist:
        currency = Currency.objects.all()[0]

    delivery_option = DeliveryOption.objects.get(pk=delivery_option_id)
    seconds = delivery_option.max_delay * 3600
    deadline = timezone.now() + timedelta(seconds=seconds)
    pick_up_in_store = True if delivery_option.type == DeliveryOption.PICK_UP_IN_STORE else False
    order = Order(items_cost=0, items_count=0, total_cost=0, device=request.user_agent.device.family,
                  delivery_option=delivery_option, delivery_expected_on=deadline,
                  delivery_company=delivery_option.company, pick_up_in_store=pick_up_in_store,
                  currency=currency)

    previous_address_index = request.POST.get('previous_address_index')
    if not previous_address_index:
        try:
            country = Country.objects.get(iso2=request.POST.get('country_iso2'))
        except Country.DoesNotExist:
            country = None
        city = request.POST.get('city')
        name = request.POST.get('name')
        email = request.POST['email']
        phone = request.POST['phone']
        postal_code = request.POST.get('postal_code', 'N/A')
        if pick_up_in_store:
            details = delivery_option.name
        else:
            details = request.POST.get('details', '<empty>')
        address = DeliveryAddress(name=name, country=country, city=city,
                                  details=details, postal_code=postal_code, email=email, phone=phone)

    if request.user.is_authenticated():
        try:
            customer = Customer.objects.get(member=request.user)
        except Customer.DoesNotExist:
            customer = Customer.objects.create(member=request.user)
            customer.delivery_addresses.append(address)
        else:
            if not previous_address_index:
                for obj in customer.delivery_addresses:
                    if obj.country == country and obj.city == city and \
                            obj.details == details and obj.phone == phone and obj.email == email:
                        break
                else:
                    customer.delivery_addresses.append(address)
            else:
                address = customer.delivery_addresses[int(previous_address_index)]
        customer.save()
        order.tags = request.user.full_name
    else:
        anonymous_buyer_id = request.POST.get('anonymous_buyer_id')
        name = request.POST.get('name')
        order.tags = name
        if anonymous_buyer_id:
            try:
                anonymous_buyer = AnonymousBuyer.objects.get(pk=anonymous_buyer_id)
            except AnonymousBuyer.DoesNotExist:
                anonymous_buyer = AnonymousBuyer.objects.create(email=email, name=name, phone=phone)
        else:
            anonymous_buyer = AnonymousBuyer.objects.create(email=email, name=name, phone=phone)
        if not previous_address_index:
            try:
                last_address = anonymous_buyer.delivery_addresses[-1]
                if last_address.country != country or last_address.city != city or \
                        last_address.details != details or last_address.phone != phone or last_address.email != email:
                    anonymous_buyer.delivery_addresses.append(address)
            except IndexError:
                anonymous_buyer.delivery_addresses.append(address)
            anonymous_buyer.name = name
            anonymous_buyer.save()
        else:
            address = anonymous_buyer.delivery_addresses[int(previous_address_index)]
        order.anonymous_buyer = anonymous_buyer

    coupon = None
    if request.session.get('promo_code'):
        promo_id = request.session['promo_code_id']
        try:
            now = datetime.now()
            coupon = PromoCode.objects.get(pk=promo_id, start_on__lte=now, end_on__gt=now, is_active=True)
        except PromoCode.DoesNotExist:
            pass

    for entry in entries:
        tokens = entry.split(':')
        product = Product.objects.get(pk=tokens[0])
        product = apply_promotion_discount([product])[0]
        product.units_sold_history = []  # Wipe these unnecessary data for this case
        count = int(tokens[1])

        if not buy_packing:
            product.packing_price = 0  # Cancel packing price if refused to buy packing

        if coupon:
            rate = coupon.rate
            product.retail_price = product.retail_price * (100 - rate) / 100
            # product.packing_price = product.packing_price * (100 - rate) / 100

        order_entry = OrderEntry(product=product, count=count)
        order.entries.append(order_entry)
        order.items_count += count
        order.items_cost += product.retail_price * count
        order.packing_cost += product.packing_price * count
        order.tags += ' ' + product.name

    music_item_list = request.POST.get('music_items')
    album_list = []
    song_list = []
    media_total_cost = 0

    if music_item_list:
        music_item_id_list = music_item_list.split(',')
        for item_id in music_item_id_list:
            try:
                album = Album.objects.get(pk=item_id)
                album_list.append(album)
                media_total_cost += album.cost
            except:
                try:
                    song = Song.objects.get(pk=item_id)
                    song_list.append(song)
                    media_total_cost += song.cost
                except:
                    continue

    media_order = MediaOrder(member_id=request.user.id, album_list=album_list, song_list=song_list,
                             tags=order.id, total_cost=media_total_cost)

    order.coupon = coupon
    if buy_packing:
        order.packing_cost += delivery_option.packing_cost
    order.total_cost = order.items_cost + order.packing_cost + delivery_option.cost
    order.delivery_address = address
    return order, media_order
Beispiel #9
0
    def get_context_data(self, **kwargs):
        context = super(ProductList, self).get_context_data(**kwargs)
        all_smart_categories_level2 = SmartCategory.objects.filter(content_type=CATEGORIES, appear_in_menu=False,
                                                                   is_active=True,
                                                                   items_count__gt=0).order_by('order_of_appearance')
        smart_categories_level1 = list(SmartCategory.objects.filter(
            content_type=PRODUCTS, appear_in_menu=False, is_active=True,
            items_count__gt=0).order_by('order_of_appearance'))
        brands = list(set([p.brand for p in Product.objects.filter(visible=True, is_duplicate=False)
                           if p.brand]))

        smart_categories_level2 = []
        for sc in all_smart_categories_level2:
            show_this = False
            for category in sc.get_category_queryset():
                if category.items_count > 0:
                    show_this = True
                    break
            if show_this:
                smart_categories_level2.append(sc)
        exclude_list_pks = []
        for smart_category in smart_categories_level2:
            exclude_list_pks.extend(list(set([c.pk for c in smart_category.get_category_queryset()])))
        categories = list(ProductCategory.objects.filter(appear_in_menu=False, items_count__gt=0)\
            .exclude(pk__in=exclude_list_pks).order_by('name'))
        top_products = Product.objects.exclude(Q(retail_price__isnull=True) & Q(retail_price=0))\
            .filter(visible=True, is_duplicate=False).order_by('-total_units_sold')
        top_products = apply_promotion_discount(list(top_products))

        page_size = 9 if self.request.user_agent.is_mobile else 15
        q = self.request.GET.get('q')
        category_slug = self.kwargs.get('category_slug')
        smart_category_slug = self.kwargs.get('smart_category_slug')
        banner_slug = self.kwargs.get('banner_slug')
        base_queryset = self.get_queryset()
        if q:
            product_queryset = base_queryset.filter(tags__icontains=q).order_by('name')
            page_title = q
            context['content_type'] = PRODUCTS
        elif category_slug:
            category = get_object_or_404(ProductCategory, slug=category_slug)
            product_queryset = base_queryset.filter(category=category).order_by('order_of_appearance', '-updated_on')
            page_title = category.name
            context['category'] = category
            context['obj_group'] = category
            context['object_id'] = category.id
            context['content_type'] = PRODUCTS
        else:
            if banner_slug:
                smart_object = get_object_or_404(Banner, slug=banner_slug)
            else:
                smart_object = get_object_or_404(SmartCategory, slug=smart_category_slug)
            context['smart_object'] = smart_object
            context['obj_group'] = smart_object
            if smart_object.content_type == CATEGORIES:
                context['category_list_as_matrix'] = as_matrix(list(smart_object.get_category_queryset()), 2)
                product_queryset = None
            else:
                base_queryset = smart_object.get_product_queryset()
                product_queryset = base_queryset

            context['object_id'] = smart_object.id
            context['content_type'] = smart_object.content_type
            page_title = smart_object.title

        context['filter_smart_categories_level2'] = smart_categories_level2
        context['filter_smart_categories_level1'] = smart_categories_level1
        context['category_list'] = categories
        context['show_categories_filter'] = len(smart_categories_level2) + len(smart_categories_level1) + len(categories)
        context['page_title'] = page_title
        context['brands'] = sorted(brands)
        context['top_products'] = top_products[:5]

        if product_queryset:
            product_queryset_lst = apply_promotion_discount(list(product_queryset))
            paginator = Paginator(product_queryset_lst, page_size)
            products_page = paginator.page(1)
            context['products_page'] = products_page
            context['product_list_as_matrix'] = as_matrix(products_page.object_list, self._get_row_len())
            try:
                sorted_by_price = list(base_queryset.order_by('retail_price'))
                context['min_price'] = sorted_by_price[0].retail_price
                context['max_price'] = sorted_by_price[-1].retail_price
            except:
                pass
        return context