Add Django backend, 1C integration, deploy config and API docs

Backend (Django 4.2 + DRF):
- accounts: phone OTP login, JWT, profile, addresses
- catalog: categories, products, images, filters, search, hits/new/related
- orders: creation with Idempotency-Key, stock reservation, status history, cancel
- loyalty: bonus accounts, promo codes, gift certificates
- payments: payment records and YooKassa webhook handling
- content: static pages, banners, site settings
- integration: 1C exchange (catalog sync, order push via outbox, statuses, bonuses)
- common: error envelope, pagination, request-id, integration auth, admin dashboard

Infrastructure: Dockerfile, docker-compose (Postgres, Redis, Celery worker/beat, Nginx),
requirements split by environment, OpenAPI contracts for site and 1C, architecture doc.

Tests: 22 pytest cases covering catalog, orders, idempotency, OTP, integration.
This commit is contained in:
apuc committed 2026-11-22 21:54:16 +03:00
1 parent 5f8d37357d
commit 756f40353b
130 files changed
+10066

No files matched your search

View File
Whitespace-only changes.
+29
View File
@@ -0,0 +1,29 @@
from django.contrib import admin
from django.contrib.admin.models import LogEntry
class LogEntryAdmin(admin.ModelAdmin):
list_display = (
"action_time",
"user",
"content_type",
"object_repr",
"action_flag",
"change_message",
)
list_filter = ("action_flag", "content_type", "user")
search_fields = ("object_repr", "change_message")
readonly_fields = [field.name for field in LogEntry._meta.fields]
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
if not admin.site.is_registered(LogEntry):
admin.site.register(LogEntry, LogEntryAdmin)
+11
View File
@@ -0,0 +1,11 @@
from django.apps import AppConfig
class CommonConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "apps.common"
verbose_name = "Общие компоненты"
def ready(self):
# Registers the OpenAPI security scheme for the 1C integration token.
from . import schema # noqa: F401
+41
View File
@@ -0,0 +1,41 @@
import hmac
from django.conf import settings
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.permissions import BasePermission
class IntegrationTokenAuthentication(BaseAuthentication):
"""Authenticates 1C using a shared secret.
The token is accepted either as ``X-Integration-Token`` or as a
``Bearer`` token in the ``Authorization`` header.
"""
def authenticate(self, request):
token = request.headers.get("X-Integration-Token")
if not token:
header = request.headers.get("Authorization", "")
if header.startswith("Bearer "):
token = header[7:].strip()
if not token:
return None
expected = getattr(settings, "INTEGRATION_API_TOKEN", "")
if not expected or not hmac.compare_digest(token, expected):
raise AuthenticationFailed("Invalid integration token")
request.integration_authenticated = True
return (None, None)
def authenticate_header(self, request):
return "Bearer"
class IsIntegrationClient(BasePermission):
"""Allows access only to requests authenticated with the integration token."""
def has_permission(self, request, view):
return bool(getattr(request, "integration_authenticated", False))
+42
View File
@@ -0,0 +1,42 @@
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import exception_handler
def api_exception_handler(exc, context):
"""Wraps DRF errors into a stable envelope: {"error": {...}}."""
response = exception_handler(exc, context)
if response is None:
return None
detail = response.data
message = "Ошибка запроса"
if isinstance(detail, dict) and "detail" in detail:
message = str(detail["detail"])
elif isinstance(detail, list) and detail:
message = str(detail[0])
response.data = {
"error": {
"code": response.status_code,
"message": message,
"details": detail,
}
}
return response
class IntegrationError(Exception):
"""Raised when an inbound 1C payload cannot be applied."""
def __init__(self, message: str, *, code: str = "integration_error"):
super().__init__(message)
self.code = code
self.message = message
def error_response(message: str, *, code: str = "bad_request", status_code: int = status.HTTP_400_BAD_REQUEST):
return Response(
{"error": {"code": code, "message": message}},
status=status_code,
)
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,27 @@
from django.contrib.auth.models import Group, Permission
from django.core.management.base import BaseCommand
ROLES = {
"Контент-менеджер": ["content", "catalog"],
"Менеджер заказов": ["orders", "payments"],
"Менеджер лояльности": ["loyalty"],
"Технический администратор": ["integration"],
}
class Command(BaseCommand):
help = "Creates the default admin roles (groups) and assigns app permissions."
def handle(self, *args, **options):
for role, app_labels in ROLES.items():
group, created = Group.objects.get_or_create(name=role)
permissions = Permission.objects.filter(
content_type__app_label__in=app_labels
)
group.permissions.set(permissions)
state = "создана" if created else "обновлена"
self.stdout.write(
self.style.SUCCESS(
f"Роль «{role}» {state}: {permissions.count()} прав"
)
)
+16
View File
@@ -0,0 +1,16 @@
import uuid
class RequestIDMiddleware:
"""Propagates X-Request-ID for tracing across logs and 1C calls."""
header_name = "X-Request-ID"
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
request.request_id = request.headers.get(self.header_name) or str(uuid.uuid4())
response = self.get_response(request)
response[self.header_name] = request.request_id
return response
Whitespace-only changes.
+22
View File
@@ -0,0 +1,22 @@
import uuid
from django.db import models
class TimeStampedModel(models.Model):
"""Adds created_at / updated_at to a model."""
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class UUIDModel(models.Model):
"""Uses a UUID primary key."""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
class Meta:
abstract = True
+7
View File
@@ -0,0 +1,7 @@
from rest_framework.pagination import PageNumberPagination
class DefaultPagination(PageNumberPagination):
page_size = 24
page_size_query_param = "page_size"
max_page_size = 100
+13
View File
@@ -0,0 +1,13 @@
from drf_spectacular.extensions import OpenApiAuthenticationExtension
class IntegrationTokenAuthenticationScheme(OpenApiAuthenticationExtension):
target_class = "apps.common.authentication.IntegrationTokenAuthentication"
name = "IntegrationToken"
def get_security_definition(self, auto_schema):
return {
"type": "apiKey",
"in": "header",
"name": "X-Integration-Token",
}
Whitespace-only changes.
@@ -0,0 +1,42 @@
from django import template
from django.db.models import Sum
from django.utils import timezone
from apps.accounts.models import User
from apps.catalog.models import Product
from apps.integration.models import OutboxMessage, SyncRun
from apps.orders.models import Order
register = template.Library()
@register.simple_tag
def admin_metrics():
"""Aggregates the numbers shown on the admin dashboard."""
today = timezone.localdate()
orders_today = Order.objects.filter(created_at__date=today)
revenue_today = (
orders_today.exclude(status=Order.Status.CANCELLED).aggregate(
total=Sum("total")
)["total"]
or 0
)
last_sync = SyncRun.objects.order_by("-started_at").first()
return {
"orders_today": orders_today.count(),
"revenue_today": revenue_today,
"orders_pending": Order.objects.filter(
status__in=[Order.Status.NEW, Order.Status.PROCESSING]
).count(),
"outbox_pending": OutboxMessage.objects.filter(
status=OutboxMessage.Status.PENDING
).count(),
"outbox_dead": OutboxMessage.objects.filter(
status=OutboxMessage.Status.DEAD
).count(),
"last_sync": last_sync,
"products_count": Product.objects.filter(is_active=True).count(),
"users_count": User.objects.filter(is_active=True).count(),
"low_stock": Product.objects.filter(is_active=True, stock__lte=3).count(),
}
+44
View File
@@ -0,0 +1,44 @@
from django.contrib.auth.models import Group
from django.core.management import call_command
from django.test import TestCase
from apps.accounts.models import User
class AdminSmokeTests(TestCase):
def setUp(self):
self.admin = User.objects.create_superuser(
phone="+79990000000", password="admin12345"
)
self.client.force_login(self.admin)
def test_admin_index_renders_dashboard(self):
response = self.client.get("/admin/")
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Сводка")
def test_admin_changelists(self):
urls = [
"/admin/orders/order/",
"/admin/catalog/product/",
"/admin/accounts/user/",
"/admin/loyalty/promocode/",
"/admin/integration/syncrun/",
"/admin/integration/outboxmessage/",
"/admin/content/sitesettings/",
"/admin/content/staticpage/",
"/admin/content/banner/",
"/admin/admin/logentry/",
]
for url in urls:
with self.subTest(url=url):
self.assertEqual(self.client.get(url).status_code, 200)
class RolesCommandTests(TestCase):
def test_create_roles(self):
call_command("create_roles")
self.assertTrue(Group.objects.filter(name="Контент-менеджер").exists())
self.assertTrue(Group.objects.filter(name="Менеджер заказов").exists())
self.assertTrue(Group.objects.filter(name="Менеджер лояльности").exists())
self.assertTrue(Group.objects.filter(name="Технический администратор").exists())
+7
View File
@@ -0,0 +1,7 @@
from django.urls import path
from .views import health
urlpatterns = [
path("health/", health, name="health"),
]
+25
View File
@@ -0,0 +1,25 @@
import re
from django.utils.text import slugify
_TRANSLIT = {
"а": "a", "б": "b", "в": "v", "г": "g", "д": "d", "е": "e", "ё": "e",
"ж": "zh", "з": "z", "и": "i", "й": "y", "к": "k", "л": "l", "м": "m",
"н": "n", "о": "o", "п": "p", "р": "r", "с": "s", "т": "t", "у": "u",
"ф": "f", "х": "h", "ц": "ts", "ч": "ch", "ш": "sh", "щ": "sch",
"ъ": "", "ы": "y", "ь": "", "э": "e", "ю": "yu", "я": "ya",
}
def transliterate(text: str) -> str:
result = []
for char in text.lower():
result.append(_TRANSLIT.get(char, char))
return "".join(result)
def make_slug(text: str, max_length: int = 200) -> str:
"""Builds a URL-safe slug that supports Cyrillic source strings."""
value = slugify(transliterate(text))
value = re.sub(r"-{2,}", "-", value).strip("-")
return value[:max_length] or "item"
+20
View File
@@ -0,0 +1,20 @@
from django.db import connection
from django.http import JsonResponse
from django.utils import timezone
def health(request):
"""Liveness/readiness probe used by Docker and monitoring."""
database_ok = True
try:
with connection.cursor() as cursor:
cursor.execute("SELECT 1")
except Exception: # pragma: no cover - depends on runtime environment
database_ok = False
payload = {
"status": "ok" if database_ok else "degraded",
"database": database_ok,
"time": timezone.now().isoformat(),
}
return JsonResponse(payload, status=200 if database_ok else 503)