- Add OpenAPI tags for the seven API groups and a full description (auth, error envelope, pagination, idempotency) in SPECTACULAR_SETTINGS - Annotate every endpoint with @extend_schema: summary, description, query parameters, request/response examples and error responses - Add shared schema helpers in apps/common/schema.py: ErrorEnvelope, error_responses(), pagination and catalog filter parameters - Document JWT login and token refresh that simplejwt ships without docs - Add ReDoc at /api/redoc/ next to Swagger UI at /api/docs/ - Add export_api_docs management command rendering the schema into a standalone HTML reference (no CDN) and commit docs/api-reference.html - Describe the documentation entry points in docs/architecture.md Schema validates cleanly: 41 operations, 0 warnings.
169 lines
6.7 KiB
Python
169 lines
6.7 KiB
Python
from drf_spectacular.utils import OpenApiExample, extend_schema, extend_schema_view
|
|
from rest_framework import viewsets
|
|
from rest_framework.decorators import action
|
|
from rest_framework.response import Response
|
|
|
|
from apps.common.schema import CATALOG_FILTER_PARAMS, PAGINATION_PARAMS, error_responses
|
|
|
|
from .filters import ProductFilter
|
|
from .models import Category, Product
|
|
from .serializers import (
|
|
CategorySerializer,
|
|
ProductDetailSerializer,
|
|
ProductListSerializer,
|
|
)
|
|
|
|
TAGS = ["Каталог"]
|
|
|
|
|
|
@extend_schema_view(
|
|
list=extend_schema(
|
|
tags=TAGS,
|
|
summary="Категории",
|
|
description=(
|
|
"Плоский список активных категорий. Иерархия задаётся полем `parent` "
|
|
"(ID родительской категории), поэтому дерево собирается на клиенте без "
|
|
"дополнительных запросов. Данные приходят из 1С."
|
|
),
|
|
responses={200: CategorySerializer(many=True)},
|
|
),
|
|
retrieve=extend_schema(
|
|
tags=TAGS,
|
|
summary="Категория по slug",
|
|
description="Карточка категории: название, родитель, изображение и порядок сортировки.",
|
|
responses={200: CategorySerializer, **error_responses(404)},
|
|
),
|
|
)
|
|
class CategoryViewSet(viewsets.ReadOnlyModelViewSet):
|
|
queryset = Category.objects.filter(is_active=True).select_related("parent")
|
|
serializer_class = CategorySerializer
|
|
lookup_field = "slug"
|
|
pagination_class = None
|
|
|
|
|
|
@extend_schema_view(
|
|
list=extend_schema(
|
|
tags=TAGS,
|
|
summary="Список товаров",
|
|
description=(
|
|
"Витрина каталога: только активные товары, постранично.\n\n"
|
|
"Поддерживает фильтры по категории, цене, бренду и наличию, поиск по "
|
|
"названию/артикулу/бренду/описанию и сортировку. Все параметры "
|
|
"необязательны и комбинируются между собой."
|
|
),
|
|
parameters=[*CATALOG_FILTER_PARAMS, *PAGINATION_PARAMS],
|
|
responses={200: ProductListSerializer(many=True), **error_responses(400)},
|
|
examples=[
|
|
OpenApiExample(
|
|
"Товар в списке",
|
|
value={
|
|
"id": 42,
|
|
"slug": "kurtka-homm-softshell",
|
|
"name": "Куртка HOMM Softshell",
|
|
"sku": "HM-1042",
|
|
"brand": "HOMM",
|
|
"price": "12990.00",
|
|
"old_price": "14990.00",
|
|
"stock_status": "in_stock",
|
|
"is_hit": True,
|
|
"is_new": False,
|
|
"main_image": "https://cdn.example.com/products/hm-1042/main.jpg",
|
|
"category": {
|
|
"id": 7,
|
|
"name": "Верхняя одежда",
|
|
"slug": "verhnyaya-odezhda",
|
|
"parent": 1,
|
|
"image_url": "",
|
|
"sort_order": 10,
|
|
},
|
|
},
|
|
response_only=True,
|
|
),
|
|
],
|
|
),
|
|
retrieve=extend_schema(
|
|
tags=TAGS,
|
|
summary="Карточка товара",
|
|
description=(
|
|
"Полные данные товара: описание, характеристики (объект «ключ-значение»), "
|
|
"остаток и галерея изображений. Изображения отдаются ссылками."
|
|
),
|
|
responses={200: ProductDetailSerializer, **error_responses(404)},
|
|
),
|
|
)
|
|
class ProductViewSet(viewsets.ReadOnlyModelViewSet):
|
|
queryset = (
|
|
Product.objects.filter(is_active=True)
|
|
.select_related("category")
|
|
.prefetch_related("images")
|
|
)
|
|
serializer_class = ProductListSerializer
|
|
lookup_field = "slug"
|
|
filterset_class = ProductFilter
|
|
search_fields = ["name", "sku", "brand", "description"]
|
|
ordering_fields = ["price", "created_at", "name"]
|
|
ordering = ["-created_at"]
|
|
|
|
def get_serializer_class(self):
|
|
if self.action == "retrieve":
|
|
return ProductDetailSerializer
|
|
return ProductListSerializer
|
|
|
|
def get_queryset(self):
|
|
queryset = super().get_queryset()
|
|
if self.action == "hits":
|
|
queryset = queryset.filter(is_hit=True)
|
|
elif self.action == "new":
|
|
queryset = queryset.filter(is_new=True)
|
|
return queryset
|
|
|
|
@extend_schema(
|
|
tags=TAGS,
|
|
summary="Хиты продаж",
|
|
description=(
|
|
"Товары с флагом «Хит». Флаг приходит из 1С и не вычисляется на сайте. "
|
|
"Поддерживает те же фильтры и сортировку, что и общий список."
|
|
),
|
|
parameters=[*CATALOG_FILTER_PARAMS, *PAGINATION_PARAMS],
|
|
responses={200: ProductListSerializer(many=True), **error_responses(400)},
|
|
)
|
|
@action(detail=False, methods=["get"])
|
|
def hits(self, request):
|
|
return self.list(request)
|
|
|
|
@extend_schema(
|
|
tags=TAGS,
|
|
summary="Новинки",
|
|
description=(
|
|
"Товары с флагом «Новинка». Поддерживает те же фильтры и сортировку, "
|
|
"что и общий список."
|
|
),
|
|
parameters=[*CATALOG_FILTER_PARAMS, *PAGINATION_PARAMS],
|
|
responses={200: ProductListSerializer(many=True), **error_responses(400)},
|
|
)
|
|
@action(detail=False, methods=["get"])
|
|
def new(self, request):
|
|
return self.list(request)
|
|
|
|
@extend_schema(
|
|
tags=TAGS,
|
|
summary="Похожие товары",
|
|
description=(
|
|
"До 8 активных товаров из той же категории, кроме самого товара. "
|
|
"Без пагинации."
|
|
),
|
|
responses={200: ProductListSerializer(many=True), **error_responses(404)},
|
|
)
|
|
@action(detail=True, methods=["get"])
|
|
def related(self, request, slug=None):
|
|
product = self.get_object()
|
|
queryset = (
|
|
Product.objects.filter(is_active=True, category=product.category)
|
|
.exclude(pk=product.pk)
|
|
.prefetch_related("images")[:8]
|
|
)
|
|
serializer = ProductListSerializer(
|
|
queryset, many=True, context={"request": request}
|
|
)
|
|
return Response(serializer.data)
|