-
Notifications
You must be signed in to change notification settings - Fork 5
/
catalog.py
320 lines (262 loc) · 10.7 KB
/
catalog.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
import typing
from functools import partial
from django import http
from django.conf import settings
from django.shortcuts import render, get_object_or_404
from django.views.decorators.http import require_POST
from django_user_agents.utils import get_user_agent
from catalog import newcontext
from catalog.views import catalog
from images.models import Image
from pages import views as pages_views
from shopelectro import models
from shopelectro.views.helpers import set_csrf_cookie
PRODUCTS_ON_PAGE_PC = 48
PRODUCTS_ON_PAGE_MOB = 12
def get_products_count(request):
"""Calculate max products list size from request. List size depends on device type."""
mobile_view = get_user_agent(request).is_mobile
return PRODUCTS_ON_PAGE_MOB if mobile_view else PRODUCTS_ON_PAGE_PC
def get_view_type(request):
view_type = request.session.get('view_type', 'tile')
assert view_type in ['list', 'tile']
return view_type
# @todo #683:60m Create context class(es) for catalog page representation.
# Created class(es) will compose the context classes for catalog views.
# Remove get_catalog_context in favor of created class(es).
def get_catalog_context(request, category, raw_tags, page_number, per_page, sorting_index):
all_tags = newcontext.Tags(models.Tag.objects.all())
selected_tags = newcontext.tags.ParsedTags(
tags=all_tags,
raw_tags=raw_tags,
)
if raw_tags:
selected_tags = newcontext.tags.Checked404Tags(selected_tags)
# @todo #683:30m Remove *Tags and *Products suffixes from catalog.newcontext classes.
# Rename Checked404Tags to ExistingOr404.
products = newcontext.products.OrderedProducts(
sorting_index=sorting_index,
products=newcontext.products.TaggedProducts(
tags=selected_tags,
products=newcontext.products.ProductsByCategory(
category=category,
products=newcontext.products.ActiveProducts(
newcontext.Products(
models.Product.objects.all(),
),
),
),
),
)
paginated_products = newcontext.products.PaginatedProducts(
products=products,
url=request.path,
page_number=page_number,
per_page=per_page,
)
images = newcontext.products.ProductImages(paginated_products, Image.objects.all())
brands = newcontext.products.ProductBrands(paginated_products, all_tags)
grouped_tags = newcontext.tags.GroupedTags(all_tags)
contexts = newcontext.Contexts(paginated_products, images, brands, grouped_tags)
# @todo #683:60m Create context class(es).
# Remove optional_context from get_catalog_context and
# patching of page.get_template_render_context in favor of created class(es).
optional_context = {
'skip_canonical': selected_tags.qs().exists(),
'total_products': products.qs().count(),
'selected_tags': selected_tags.qs(),
}
return contexts, optional_context
# CATALOG VIEWS
class CategoryTree(catalog.CategoryTree):
category_model = models.Category
@set_csrf_cookie
class ProductPage(catalog.ProductPage):
pk_url_kwarg = None
slug_url_kwarg = 'product_vendor_code'
slug_field = 'vendor_code'
queryset = (
models.Product.objects.active()
.filter(category__isnull=False)
.prefetch_related('product_feedbacks', 'page__images')
.select_related('page')
)
@property
def product(self):
return self.object
def get(self, request, *args, **kwargs):
try:
self.object = self.get_object()
except http.Http404 as error404:
response_404 = self.render_siblings_on_404(request, **kwargs)
if response_404:
return response_404
else:
raise error404
context = self.get_context_data(object=self.object)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
context_ = super(ProductPage, self).get_context_data(**kwargs)
if not self.product.page.is_active:
# this context required to render 404 page
# with it's own logic
return context_
tile_products = self.product.get_siblings(
offset=settings.PRODUCT_SIBLINGS_COUNT
)
product_images = self.get_images_context_data(tile_products)
return {
**context_,
**product_images,
'price_bounds': settings.PRICE_BOUNDS,
'group_tags_pairs': self.product.get_params(),
'tile_products': tile_products,
}
def get_images_context_data(self, products) -> dict:
"""Return images for given products."""
products_to_filter = [self.product, *products]
return newcontext.products.ProductImages(
newcontext.Products(products_to_filter),
Image.objects.all(),
).context()
def render_siblings_on_404(
self, request, **url_kwargs
) -> typing.Union[http.Http404, None]:
"""Try to render removed product's siblings on it's 404 page."""
inactive_product = models.Product.objects.filter(
**{self.slug_field: url_kwargs['product_vendor_code']},
category__isnull=False,
page__is_active=False
).first()
if inactive_product:
siblings = inactive_product.get_siblings(
offset=settings.PRODUCT_SIBLINGS_COUNT
)
self.object = inactive_product
context_ = self.get_context_data(
object=inactive_product,
tile_products=siblings,
tile_title='Возможно вас заинтересуют похожие товары:',
**url_kwargs,
)
context_.update(self.get_images_context_data(siblings))
return render(request, 'catalog/product_404.html', context_, status=404)
# SHOPELECTRO-SPECIFIC VIEWS
@set_csrf_cookie
class IndexPage(pages_views.CustomPageView):
def get_context_data(self, **kwargs):
"""Extended method. Add product's images to context."""
context_ = super(IndexPage, self).get_context_data(**kwargs)
mobile_view = get_user_agent(self.request).is_mobile
tile_products = []
top_products = (
models.Product.objects.active()
.filter(id__in=settings.TOP_PRODUCTS)
.prefetch_related('category')
.select_related('page')
)
if not mobile_view:
tile_products = top_products
images_ctx = newcontext.products.ProductImages(
newcontext.Products(tile_products),
Image.objects.all(),
).context()
return {
**context_,
**images_ctx,
'tile_title': 'ТОП 10 ТОВАРОВ',
'category_tile': settings.MAIN_PAGE_TILE,
'tile_products': tile_products,
}
@set_csrf_cookie
class CategoryPage(catalog.CategoryPage):
def get_context_data(self, **kwargs):
"""Add sorting options and view_types in context."""
sorting_index = int(self.kwargs.get('sorting', 0))
contexts, optional_context = get_catalog_context(
request=self.request,
category=self.object.model,
raw_tags=self.kwargs.get('tags'),
page_number=int(self.request.GET.get('page', 1)),
per_page=int(self.request.GET.get(
'step', get_products_count(self.request),
)),
sorting_index=sorting_index,
)
selected_tags = optional_context['selected_tags']
if selected_tags:
def template_context(page, tag_titles, tags):
return {
'page': page,
'tag_titles': tag_titles,
'tags': tags,
}
page = self.object
page.get_template_render_context = partial(
template_context, page, selected_tags.as_title(), selected_tags
)
return {
**super().get_context_data(**kwargs),
**contexts.context(),
**optional_context,
'view_type': get_view_type(self.request),
'sorting_options': settings.CATEGORY_SORTING_OPTIONS.values(),
'limits': settings.CATEGORY_STEP_MULTIPLIERS,
'sort': sorting_index,
}
def load_more(request, slug, offset=0, limit=0, sorting=0, tags=None):
"""
Load more products of a given category.
:param sorting: preferred sorting index from CATEGORY_SORTING tuple
:param request: HttpRequest object
:param slug: Slug for a given category
:param offset: used for slicing QuerySet.
:return: products list in html format
"""
products_on_page = limit or get_products_count(request)
offset = int(offset)
if offset < 0:
return http.HttpResponseBadRequest(
'The offset is wrong. An offset should be greater than or equal to 0.'
)
# increment page number because:
# 11 // 12 = 0, 0 // 12 = 0 but it should be the first page
# 12 // 12 = 1, 23 // 12 = 1, but it should be the second page
page_number = (offset // products_on_page) + 1
category = get_object_or_404(models.CategoryPage, slug=slug).model
sorting_index = int(sorting)
contexts, _ = get_catalog_context(
request=request,
category=category,
raw_tags=tags,
page_number=page_number,
per_page=products_on_page,
sorting_index=sorting_index,
)
return render(request, 'catalog/category_products.html', contexts.context())
@require_POST
def save_feedback(request):
def get_keys_from_post(*args):
return {arg: request.POST.get(arg, '') for arg in args}
product_id = request.POST.get('id')
product = models.Product.objects.filter(id=product_id, page__is_active=True).first()
if not (product_id and product):
return http.HttpResponse(status=422)
fields = ['rating', 'name', 'dignities', 'limitations', 'general']
feedback_data = get_keys_from_post(*fields)
models.ProductFeedback.objects.create(product=product, **feedback_data)
return http.HttpResponse('ok')
@require_POST
def delete_feedback(request):
if not request.user.is_authenticated:
return http.HttpResponseForbidden('Not today, sly guy...')
feedback_id = request.POST.get('id')
feedback = models.ProductFeedback.objects.filter(id=feedback_id).first()
if not (feedback_id and feedback):
return http.HttpResponse(status=422)
feedback.delete()
return http.HttpResponse('Feedback with id={} was deleted.'.format(feedback_id))
class ProductsWithoutImages(catalog.ProductsWithoutImages):
model = models.Product
class ProductsWithoutText(catalog.ProductsWithoutText):
model = models.Product