- 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.
141 lines
5.3 KiB
Python
141 lines
5.3 KiB
Python
from django.db.models import Q
|
||
from django.utils import timezone
|
||
from drf_spectacular.utils import (
|
||
OpenApiExample,
|
||
OpenApiParameter,
|
||
extend_schema,
|
||
extend_schema_view,
|
||
)
|
||
from rest_framework.permissions import AllowAny
|
||
from rest_framework.response import Response
|
||
from rest_framework.views import APIView
|
||
from rest_framework.viewsets import ReadOnlyModelViewSet
|
||
|
||
from apps.common.schema import error_responses
|
||
|
||
from .models import Banner, SiteSettings, StaticPage
|
||
from .serializers import BannerSerializer, SiteSettingsSerializer, StaticPageSerializer
|
||
|
||
TAGS = ["Контент"]
|
||
|
||
BANNER_POSITION = OpenApiParameter(
|
||
name="position",
|
||
type=str,
|
||
location=OpenApiParameter.QUERY,
|
||
required=False,
|
||
description=(
|
||
"Позиция баннера, например `home_top` или `home_middle`. "
|
||
"Без параметра возвращаются все активные баннеры."
|
||
),
|
||
)
|
||
|
||
|
||
class SiteSettingsView(APIView):
|
||
"""Public store settings used by the storefront."""
|
||
|
||
permission_classes = [AllowAny]
|
||
serializer_class = SiteSettingsSerializer
|
||
|
||
@extend_schema(
|
||
tags=TAGS,
|
||
summary="Настройки магазина",
|
||
description=(
|
||
"Контакты, режим работы, ссылки на соцсети, стоимость и порог бесплатной "
|
||
"доставки, правила бонусной программы. Одна запись на сайт, меняется "
|
||
"в админке."
|
||
),
|
||
responses={200: SiteSettingsSerializer},
|
||
examples=[
|
||
OpenApiExample(
|
||
"Настройки",
|
||
value={
|
||
"site_name": "HOMM",
|
||
"phone": "+7 (495) 120-33-45",
|
||
"email": "shop@homm.ru",
|
||
"address": "Москва, ул. Тверская, 12",
|
||
"working_hours": "Пн–Вс, 10:00–21:00",
|
||
"telegram_url": "https://t.me/homm",
|
||
"vk_url": "",
|
||
"whatsapp_url": "",
|
||
"free_delivery_threshold": "15000.00",
|
||
"default_delivery_cost": "490.00",
|
||
"bonus_accrual_percent": "5.00",
|
||
"bonus_max_payment_percent": "30.00",
|
||
"bonus_ttl_days": 365,
|
||
"privacy_policy_url": "/pages/privacy",
|
||
"offer_url": "/pages/offer",
|
||
"updated_at": "2026-11-20T10:12:00+03:00",
|
||
},
|
||
response_only=True,
|
||
),
|
||
],
|
||
)
|
||
def get(self, request):
|
||
settings_obj = SiteSettings.load()
|
||
return Response(SiteSettingsSerializer(settings_obj).data)
|
||
|
||
|
||
@extend_schema_view(
|
||
list=extend_schema(
|
||
tags=TAGS,
|
||
summary="Статические страницы",
|
||
description=(
|
||
"Опубликованные страницы: «О компании», «Доставка и оплата», «Контакты», "
|
||
"политика конфиденциальности. Публикуются и редактируются в админке."
|
||
),
|
||
responses={200: StaticPageSerializer(many=True)},
|
||
),
|
||
retrieve=extend_schema(
|
||
tags=TAGS,
|
||
summary="Страница по slug",
|
||
description="Полный текст страницы вместе с SEO-полями.",
|
||
responses={200: StaticPageSerializer, **error_responses(404)},
|
||
),
|
||
)
|
||
class StaticPageViewSet(ReadOnlyModelViewSet):
|
||
queryset = StaticPage.objects.filter(is_published=True)
|
||
serializer_class = StaticPageSerializer
|
||
lookup_field = "slug"
|
||
permission_classes = [AllowAny]
|
||
pagination_class = None
|
||
|
||
|
||
@extend_schema_view(
|
||
list=extend_schema(
|
||
tags=TAGS,
|
||
summary="Баннеры",
|
||
description=(
|
||
"Только активные баннеры, у которых наступила дата начала и не истёк срок "
|
||
"показа. Сортировка задаётся полем `sort_order`. Без пагинации — витрина "
|
||
"забирает все нужные позиции одним запросом."
|
||
),
|
||
parameters=[BANNER_POSITION],
|
||
responses={200: BannerSerializer(many=True)},
|
||
),
|
||
retrieve=extend_schema(
|
||
tags=TAGS,
|
||
summary="Баннер по ID",
|
||
description=(
|
||
"Один баннер: заголовок, ссылка на изображение, ссылка перехода, позиция "
|
||
"и период показа."
|
||
),
|
||
responses={200: BannerSerializer, **error_responses(404)},
|
||
),
|
||
)
|
||
class BannerViewSet(ReadOnlyModelViewSet):
|
||
serializer_class = BannerSerializer
|
||
permission_classes = [AllowAny]
|
||
pagination_class = None
|
||
|
||
def get_queryset(self):
|
||
now = timezone.now()
|
||
queryset = (
|
||
Banner.objects.filter(is_active=True)
|
||
.filter(Q(starts_at__isnull=True) | Q(starts_at__lte=now))
|
||
.filter(Q(ends_at__isnull=True) | Q(ends_at__gte=now))
|
||
)
|
||
position = self.request.query_params.get("position")
|
||
if position:
|
||
queryset = queryset.filter(position=position)
|
||
return queryset
|