From 756f40353b1e85772551610115eba9c75061309e Mon Sep 17 00:00:00 2001 From: Kavalar Date: Sun, 22 Nov 2026 21:54:16 +0300 Subject: [PATCH] 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. --- .dockerignore | 13 + .env.example | 46 + .gitignore | 32 + Dockerfile | 24 + backend/apps/__init__.py | 0 backend/apps/accounts/__init__.py | 0 backend/apps/accounts/admin.py | 75 + backend/apps/accounts/apps.py | 7 + backend/apps/accounts/managers.py | 29 + .../apps/accounts/migrations/0001_initial.py | 93 + backend/apps/accounts/migrations/__init__.py | 0 backend/apps/accounts/models.py | 100 + backend/apps/accounts/serializers.py | 64 + backend/apps/accounts/services.py | 81 + backend/apps/accounts/sms.py | 14 + backend/apps/accounts/tests.py | 34 + backend/apps/accounts/urls.py | 18 + backend/apps/accounts/views.py | 125 + backend/apps/catalog/__init__.py | 0 backend/apps/catalog/admin.py | 118 + backend/apps/catalog/apps.py | 7 + backend/apps/catalog/filters.py | 34 + .../apps/catalog/migrations/0001_initial.py | 103 + backend/apps/catalog/migrations/__init__.py | 0 backend/apps/catalog/models.py | 132 + backend/apps/catalog/serializers.py | 50 + backend/apps/catalog/tests.py | 49 + backend/apps/catalog/urls.py | 12 + backend/apps/catalog/views.py | 66 + backend/apps/common/__init__.py | 0 backend/apps/common/admin.py | 29 + backend/apps/common/apps.py | 11 + backend/apps/common/authentication.py | 41 + backend/apps/common/exceptions.py | 42 + backend/apps/common/management/__init__.py | 0 .../common/management/commands/__init__.py | 0 .../management/commands/create_roles.py | 27 + backend/apps/common/middleware.py | 16 + backend/apps/common/migrations/__init__.py | 0 backend/apps/common/models.py | 22 + backend/apps/common/pagination.py | 7 + backend/apps/common/schema.py | 13 + backend/apps/common/templatetags/__init__.py | 0 .../apps/common/templatetags/admin_metrics.py | 42 + backend/apps/common/tests.py | 44 + backend/apps/common/urls.py | 7 + backend/apps/common/utils.py | 25 + backend/apps/common/views.py | 20 + backend/apps/content/__init__.py | 0 backend/apps/content/admin.py | 62 + backend/apps/content/apps.py | 7 + .../apps/content/migrations/0001_initial.py | 84 + backend/apps/content/migrations/__init__.py | 0 backend/apps/content/models.py | 108 + backend/apps/content/serializers.py | 61 + backend/apps/content/tests.py | 69 + backend/apps/content/urls.py | 13 + backend/apps/content/views.py | 46 + backend/apps/integration/__init__.py | 0 backend/apps/integration/admin.py | 106 + backend/apps/integration/apps.py | 7 + backend/apps/integration/client.py | 79 + .../apps/integration/management/__init__.py | 0 .../management/commands/__init__.py | 0 .../management/commands/sync_catalog.py | 20 + .../integration/migrations/0001_initial.py | 94 + .../apps/integration/migrations/__init__.py | 0 backend/apps/integration/models.py | 117 + backend/apps/integration/outbox.py | 10 + backend/apps/integration/serializers.py | 136 + backend/apps/integration/services.py | 378 +++ backend/apps/integration/status_map.py | 33 + backend/apps/integration/tasks.py | 31 + backend/apps/integration/tests.py | 82 + backend/apps/integration/urls.py | 29 + backend/apps/integration/views.py | 163 + backend/apps/loyalty/__init__.py | 0 backend/apps/loyalty/admin.py | 70 + backend/apps/loyalty/apps.py | 7 + .../apps/loyalty/migrations/0001_initial.py | 96 + backend/apps/loyalty/migrations/__init__.py | 0 backend/apps/loyalty/models.py | 144 + backend/apps/loyalty/serializers.py | 43 + backend/apps/loyalty/services.py | 106 + backend/apps/loyalty/tests.py | 44 + backend/apps/loyalty/urls.py | 19 + backend/apps/loyalty/views.py | 78 + backend/apps/orders/__init__.py | 0 backend/apps/orders/admin.py | 136 + backend/apps/orders/apps.py | 7 + .../apps/orders/migrations/0001_initial.py | 103 + .../0002_alter_orderstatushistory_source.py | 18 + backend/apps/orders/migrations/__init__.py | 0 backend/apps/orders/models.py | 162 + backend/apps/orders/serializers.py | 98 + backend/apps/orders/services.py | 147 + backend/apps/orders/tests.py | 76 + backend/apps/orders/urls.py | 11 + backend/apps/orders/views.py | 66 + backend/apps/payments/__init__.py | 0 backend/apps/payments/admin.py | 19 + backend/apps/payments/apps.py | 7 + .../apps/payments/migrations/0001_initial.py | 40 + backend/apps/payments/migrations/__init__.py | 0 backend/apps/payments/models.py | 51 + backend/apps/payments/serializers.py | 27 + backend/apps/payments/services.py | 94 + backend/apps/payments/urls.py | 7 + backend/apps/payments/views.py | 23 + backend/config/__init__.py | 3 + backend/config/asgi.py | 7 + backend/config/celery.py | 15 + backend/config/settings/__init__.py | 1 + backend/config/settings/base.py | 292 ++ backend/config/settings/dev.py | 11 + backend/config/settings/prod.py | 28 + backend/config/urls.py | 32 + backend/config/wsgi.py | 7 + backend/manage.py | 21 + backend/pytest.ini | 4 + backend/templates/admin/homm_index.html | 53 + deploy/nginx/default.conf | 32 + docker-compose.yml | 105 + docs/architecture.md | 539 +++ docs/openapi-1c-inbound.yaml | 497 +++ docs/openapi-1c-outbound.yaml | 367 +++ docs/openapi-site.yaml | 2925 +++++++++++++++++ requirements/base.txt | 13 + requirements/dev.txt | 5 + requirements/prod.txt | 3 + 130 files changed, 10066 insertions(+) create mode 100644 .dockerignore create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 backend/apps/__init__.py create mode 100644 backend/apps/accounts/__init__.py create mode 100644 backend/apps/accounts/admin.py create mode 100644 backend/apps/accounts/apps.py create mode 100644 backend/apps/accounts/managers.py create mode 100644 backend/apps/accounts/migrations/0001_initial.py create mode 100644 backend/apps/accounts/migrations/__init__.py create mode 100644 backend/apps/accounts/models.py create mode 100644 backend/apps/accounts/serializers.py create mode 100644 backend/apps/accounts/services.py create mode 100644 backend/apps/accounts/sms.py create mode 100644 backend/apps/accounts/tests.py create mode 100644 backend/apps/accounts/urls.py create mode 100644 backend/apps/accounts/views.py create mode 100644 backend/apps/catalog/__init__.py create mode 100644 backend/apps/catalog/admin.py create mode 100644 backend/apps/catalog/apps.py create mode 100644 backend/apps/catalog/filters.py create mode 100644 backend/apps/catalog/migrations/0001_initial.py create mode 100644 backend/apps/catalog/migrations/__init__.py create mode 100644 backend/apps/catalog/models.py create mode 100644 backend/apps/catalog/serializers.py create mode 100644 backend/apps/catalog/tests.py create mode 100644 backend/apps/catalog/urls.py create mode 100644 backend/apps/catalog/views.py create mode 100644 backend/apps/common/__init__.py create mode 100644 backend/apps/common/admin.py create mode 100644 backend/apps/common/apps.py create mode 100644 backend/apps/common/authentication.py create mode 100644 backend/apps/common/exceptions.py create mode 100644 backend/apps/common/management/__init__.py create mode 100644 backend/apps/common/management/commands/__init__.py create mode 100644 backend/apps/common/management/commands/create_roles.py create mode 100644 backend/apps/common/middleware.py create mode 100644 backend/apps/common/migrations/__init__.py create mode 100644 backend/apps/common/models.py create mode 100644 backend/apps/common/pagination.py create mode 100644 backend/apps/common/schema.py create mode 100644 backend/apps/common/templatetags/__init__.py create mode 100644 backend/apps/common/templatetags/admin_metrics.py create mode 100644 backend/apps/common/tests.py create mode 100644 backend/apps/common/urls.py create mode 100644 backend/apps/common/utils.py create mode 100644 backend/apps/common/views.py create mode 100644 backend/apps/content/__init__.py create mode 100644 backend/apps/content/admin.py create mode 100644 backend/apps/content/apps.py create mode 100644 backend/apps/content/migrations/0001_initial.py create mode 100644 backend/apps/content/migrations/__init__.py create mode 100644 backend/apps/content/models.py create mode 100644 backend/apps/content/serializers.py create mode 100644 backend/apps/content/tests.py create mode 100644 backend/apps/content/urls.py create mode 100644 backend/apps/content/views.py create mode 100644 backend/apps/integration/__init__.py create mode 100644 backend/apps/integration/admin.py create mode 100644 backend/apps/integration/apps.py create mode 100644 backend/apps/integration/client.py create mode 100644 backend/apps/integration/management/__init__.py create mode 100644 backend/apps/integration/management/commands/__init__.py create mode 100644 backend/apps/integration/management/commands/sync_catalog.py create mode 100644 backend/apps/integration/migrations/0001_initial.py create mode 100644 backend/apps/integration/migrations/__init__.py create mode 100644 backend/apps/integration/models.py create mode 100644 backend/apps/integration/outbox.py create mode 100644 backend/apps/integration/serializers.py create mode 100644 backend/apps/integration/services.py create mode 100644 backend/apps/integration/status_map.py create mode 100644 backend/apps/integration/tasks.py create mode 100644 backend/apps/integration/tests.py create mode 100644 backend/apps/integration/urls.py create mode 100644 backend/apps/integration/views.py create mode 100644 backend/apps/loyalty/__init__.py create mode 100644 backend/apps/loyalty/admin.py create mode 100644 backend/apps/loyalty/apps.py create mode 100644 backend/apps/loyalty/migrations/0001_initial.py create mode 100644 backend/apps/loyalty/migrations/__init__.py create mode 100644 backend/apps/loyalty/models.py create mode 100644 backend/apps/loyalty/serializers.py create mode 100644 backend/apps/loyalty/services.py create mode 100644 backend/apps/loyalty/tests.py create mode 100644 backend/apps/loyalty/urls.py create mode 100644 backend/apps/loyalty/views.py create mode 100644 backend/apps/orders/__init__.py create mode 100644 backend/apps/orders/admin.py create mode 100644 backend/apps/orders/apps.py create mode 100644 backend/apps/orders/migrations/0001_initial.py create mode 100644 backend/apps/orders/migrations/0002_alter_orderstatushistory_source.py create mode 100644 backend/apps/orders/migrations/__init__.py create mode 100644 backend/apps/orders/models.py create mode 100644 backend/apps/orders/serializers.py create mode 100644 backend/apps/orders/services.py create mode 100644 backend/apps/orders/tests.py create mode 100644 backend/apps/orders/urls.py create mode 100644 backend/apps/orders/views.py create mode 100644 backend/apps/payments/__init__.py create mode 100644 backend/apps/payments/admin.py create mode 100644 backend/apps/payments/apps.py create mode 100644 backend/apps/payments/migrations/0001_initial.py create mode 100644 backend/apps/payments/migrations/__init__.py create mode 100644 backend/apps/payments/models.py create mode 100644 backend/apps/payments/serializers.py create mode 100644 backend/apps/payments/services.py create mode 100644 backend/apps/payments/urls.py create mode 100644 backend/apps/payments/views.py create mode 100644 backend/config/__init__.py create mode 100644 backend/config/asgi.py create mode 100644 backend/config/celery.py create mode 100644 backend/config/settings/__init__.py create mode 100644 backend/config/settings/base.py create mode 100644 backend/config/settings/dev.py create mode 100644 backend/config/settings/prod.py create mode 100644 backend/config/urls.py create mode 100644 backend/config/wsgi.py create mode 100644 backend/manage.py create mode 100644 backend/pytest.ini create mode 100644 backend/templates/admin/homm_index.html create mode 100644 deploy/nginx/default.conf create mode 100644 docker-compose.yml create mode 100644 docs/architecture.md create mode 100644 docs/openapi-1c-inbound.yaml create mode 100644 docs/openapi-1c-outbound.yaml create mode 100644 docs/openapi-site.yaml create mode 100644 requirements/base.txt create mode 100644 requirements/dev.txt create mode 100644 requirements/prod.txt diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..754cbbe --- /dev/null +++ b/.dockerignore @@ -0,0 +1,13 @@ +.git +.gitignore +.venv +venv +**/__pycache__ +**/*.pyc +**/db.sqlite3 +media +staticfiles +docs +README.md +.ruff_cache +.pytest_cache diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..e5ecb9d --- /dev/null +++ b/.env.example @@ -0,0 +1,46 @@ +# --- Django --- +DJANGO_SETTINGS_MODULE=config.settings.dev +DJANGO_SECRET_KEY=change-me-in-production +DJANGO_DEBUG=true +DJANGO_ALLOWED_HOSTS=localhost,127.0.0.1 + +# --- Database --- +# sqlite | postgres +DB_ENGINE=sqlite +POSTGRES_DB=homm +POSTGRES_USER=homm +POSTGRES_PASSWORD=homm +POSTGRES_HOST=localhost +POSTGRES_PORT=5432 + +# --- Redis / Celery --- +REDIS_URL=redis://localhost:6379/0 +CELERY_BROKER_URL=redis://localhost:6379/0 +CELERY_RESULT_BACKEND=redis://localhost:6379/1 + +# --- CORS --- +CORS_ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173 + +# --- Auth / OTP --- +OTP_TTL_SECONDS=300 +OTP_MAX_ATTEMPTS=5 +# Only for local development: fixed OTP code. Leave empty in production. +OTP_DEBUG_CODE=0000 + +# --- 1C integration --- +# Shared secret used by 1C when calling the site integration API. +INTEGRATION_API_TOKEN=dev-integration-token +# Base URL of the 1C HTTP service (outbound calls from the site). +ONEC_BASE_URL=http://1c.local/homm/hs/homm +ONEC_USERNAME= +ONEC_PASSWORD= +ONEC_TIMEOUT=30 + +# --- Email --- +EMAIL_BACKEND=django.core.mail.backends.console.EmailBackend +DEFAULT_FROM_EMAIL=noreply@homm.local + +# --- Payments --- +YOOKASSA_SHOP_ID= +YOOKASSA_SECRET_KEY= +YOOKASSA_RETURN_URL=http://localhost:3000/checkout/success diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b54de38 --- /dev/null +++ b/.gitignore @@ -0,0 +1,32 @@ +# Python +__pycache__/ +*.py[cod] +*.egg-info/ +.venv/ +venv/ +env/ + +# Django +db.sqlite3 +db.sqlite3-journal +media/ +staticfiles/ +*.log + +# Environment +.env +.env.* +!.env.example + +# Tooling +.pytest_cache/ +.ruff_cache/ +.mypy_cache/ +.coverage +htmlcov/ + +# IDE / OS +.idea/ +.vscode/ +.DS_Store +Thumbs.db diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..4063553 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +FROM python:3.12-slim AS base + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PIP_NO_CACHE_DIR=1 + +WORKDIR /app + +RUN apt-get update \ + && apt-get install -y --no-install-recommends build-essential libpq-dev curl \ + && rm -rf /var/lib/apt/lists/* + +COPY requirements /app/requirements +RUN pip install --no-cache-dir -r requirements/prod.txt + +COPY backend /app + +RUN DJANGO_SETTINGS_MODULE=config.settings.prod \ + DJANGO_SECRET_KEY=build-only \ + python manage.py collectstatic --noinput + +EXPOSE 8000 + +CMD ["gunicorn", "config.wsgi:application", "--bind", "0.0.0.0:8000", "--workers", "3", "--timeout", "60"] diff --git a/backend/apps/__init__.py b/backend/apps/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/accounts/__init__.py b/backend/apps/accounts/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/accounts/admin.py b/backend/apps/accounts/admin.py new file mode 100644 index 0000000..e224fda --- /dev/null +++ b/backend/apps/accounts/admin.py @@ -0,0 +1,75 @@ +from django.contrib import admin +from django.db.models import Count + +from .models import Address, OtpCode, User + + +class AddressInline(admin.TabularInline): + model = Address + extra = 0 + + +@admin.register(User) +class UserAdmin(admin.ModelAdmin): + list_display = ( + "phone", + "email", + "full_name", + "bonus_balance", + "orders_count", + "is_active", + "is_staff", + "date_joined", + ) + list_filter = ("is_active", "is_staff", "is_superuser") + search_fields = ("phone", "email", "first_name", "last_name") + ordering = ("-date_joined",) + readonly_fields = ("date_joined", "last_login") + inlines = [AddressInline] + + def get_queryset(self, request): + return ( + super() + .get_queryset(request) + .annotate(orders_count=Count("orders")) + .select_related("bonus_account") + ) + + @admin.display(description="Бонусы", ordering="bonus_account__balance") + def bonus_balance(self, obj): + account = getattr(obj, "bonus_account", None) + return account.balance if account else 0 + + @admin.display(description="Заказов", ordering="orders_count") + def orders_count(self, obj): + return obj.orders_count + + +@admin.register(OtpCode) +class OtpCodeAdmin(admin.ModelAdmin): + list_display = ("phone", "purpose", "expires_at", "attempts", "is_used", "created_at") + list_filter = ("purpose", "is_used") + search_fields = ("phone",) + readonly_fields = ( + "phone", + "code_hash", + "purpose", + "expires_at", + "attempts", + "is_used", + "created_at", + "updated_at", + ) + + def has_add_permission(self, request): + return False + + def has_change_permission(self, request, obj=None): + return False + + +@admin.register(Address) +class AddressAdmin(admin.ModelAdmin): + list_display = ("user", "title", "city", "street", "house", "is_default") + search_fields = ("user__phone", "city", "street") + list_filter = ("is_default",) diff --git a/backend/apps/accounts/apps.py b/backend/apps/accounts/apps.py new file mode 100644 index 0000000..b18c9b1 --- /dev/null +++ b/backend/apps/accounts/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig + + +class AccountsConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "apps.accounts" + verbose_name = "Пользователи" diff --git a/backend/apps/accounts/managers.py b/backend/apps/accounts/managers.py new file mode 100644 index 0000000..2c1f191 --- /dev/null +++ b/backend/apps/accounts/managers.py @@ -0,0 +1,29 @@ +from django.contrib.auth.base_user import BaseUserManager + + +class UserManager(BaseUserManager): + """User manager keyed by phone number.""" + + use_in_migrations = True + + def _create_user(self, phone, password, **extra_fields): + if not phone: + raise ValueError("Phone number is required") + user = self.model(phone=phone, **extra_fields) + user.set_password(password) + user.save(using=self._db) + return user + + def create_user(self, phone, password=None, **extra_fields): + extra_fields.setdefault("is_staff", False) + extra_fields.setdefault("is_superuser", False) + return self._create_user(phone, password, **extra_fields) + + def create_superuser(self, phone, password=None, **extra_fields): + extra_fields.setdefault("is_staff", True) + extra_fields.setdefault("is_superuser", True) + if extra_fields.get("is_staff") is not True: + raise ValueError("Superuser must have is_staff=True") + if extra_fields.get("is_superuser") is not True: + raise ValueError("Superuser must have is_superuser=True") + return self._create_user(phone, password, **extra_fields) diff --git a/backend/apps/accounts/migrations/0001_initial.py b/backend/apps/accounts/migrations/0001_initial.py new file mode 100644 index 0000000..ca3c9db --- /dev/null +++ b/backend/apps/accounts/migrations/0001_initial.py @@ -0,0 +1,93 @@ +# Generated by Django 4.2.16 on 2026-11-06 13:26 + +import apps.accounts.managers +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion +import django.utils.timezone +import uuid + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('auth', '0012_alter_user_first_name_max_length'), + ] + + operations = [ + migrations.CreateModel( + name='User', + fields=[ + ('password', models.CharField(max_length=128, verbose_name='password')), + ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), + ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), + ('phone', models.CharField(max_length=20, unique=True, verbose_name='телефон')), + ('email', models.EmailField(blank=True, max_length=254, null=True, unique=True, verbose_name='email')), + ('first_name', models.CharField(blank=True, max_length=150, verbose_name='имя')), + ('last_name', models.CharField(blank=True, max_length=150, verbose_name='фамилия')), + ('middle_name', models.CharField(blank=True, max_length=150, verbose_name='отчество')), + ('is_active', models.BooleanField(default=True, verbose_name='активен')), + ('is_staff', models.BooleanField(default=False, verbose_name='сотрудник')), + ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='дата регистрации')), + ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.group', verbose_name='groups')), + ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.permission', verbose_name='user permissions')), + ], + options={ + 'verbose_name': 'пользователь', + 'verbose_name_plural': 'пользователи', + 'db_table': 'accounts_user', + 'ordering': ['-date_joined'], + }, + managers=[ + ('objects', apps.accounts.managers.UserManager()), + ], + ), + migrations.CreateModel( + name='OtpCode', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('phone', models.CharField(db_index=True, max_length=20)), + ('code_hash', models.CharField(max_length=128)), + ('purpose', models.CharField(choices=[('login', 'Вход'), ('phone_change', 'Смена телефона')], default='login', max_length=20)), + ('expires_at', models.DateTimeField()), + ('attempts', models.PositiveSmallIntegerField(default=0)), + ('is_used', models.BooleanField(default=False)), + ], + options={ + 'verbose_name': 'OTP-код', + 'verbose_name_plural': 'OTP-коды', + 'db_table': 'accounts_otp_code', + 'indexes': [models.Index(fields=['phone', 'purpose', 'is_used'], name='accounts_ot_phone_5e5363_idx')], + }, + ), + migrations.CreateModel( + name='Address', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('title', models.CharField(default='Дом', max_length=64, verbose_name='название')), + ('city', models.CharField(max_length=128, verbose_name='город')), + ('street', models.CharField(max_length=255, verbose_name='улица')), + ('house', models.CharField(max_length=32, verbose_name='дом')), + ('apartment', models.CharField(blank=True, max_length=32, verbose_name='квартира/офис')), + ('postal_code', models.CharField(blank=True, max_length=16, verbose_name='индекс')), + ('entrance', models.CharField(blank=True, max_length=16, verbose_name='подъезд')), + ('floor', models.CharField(blank=True, max_length=16, verbose_name='этаж')), + ('intercom', models.CharField(blank=True, max_length=32, verbose_name='домофон')), + ('is_default', models.BooleanField(default=False, verbose_name='по умолчанию')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='addresses', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'verbose_name': 'адрес доставки', + 'verbose_name_plural': 'адреса доставки', + 'db_table': 'accounts_address', + 'ordering': ['-is_default', '-created_at'], + }, + ), + ] diff --git a/backend/apps/accounts/migrations/__init__.py b/backend/apps/accounts/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/accounts/models.py b/backend/apps/accounts/models.py new file mode 100644 index 0000000..9314b76 --- /dev/null +++ b/backend/apps/accounts/models.py @@ -0,0 +1,100 @@ +import uuid + +from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin +from django.db import models +from django.utils import timezone + +from apps.common.models import TimeStampedModel + +from .managers import UserManager + + +class User(AbstractBaseUser, PermissionsMixin): + """Store customer. Phone is the primary login identifier.""" + + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + phone = models.CharField("телефон", max_length=20, unique=True) + email = models.EmailField("email", blank=True, null=True, unique=True) + first_name = models.CharField("имя", max_length=150, blank=True) + last_name = models.CharField("фамилия", max_length=150, blank=True) + middle_name = models.CharField("отчество", max_length=150, blank=True) + is_active = models.BooleanField("активен", default=True) + is_staff = models.BooleanField("сотрудник", default=False) + date_joined = models.DateTimeField("дата регистрации", default=timezone.now) + + objects = UserManager() + + USERNAME_FIELD = "phone" + REQUIRED_FIELDS: list[str] = [] + + class Meta: + db_table = "accounts_user" + verbose_name = "пользователь" + verbose_name_plural = "пользователи" + ordering = ["-date_joined"] + + def __str__(self) -> str: + return self.phone + + @property + def full_name(self) -> str: + parts = [self.last_name, self.first_name, self.middle_name] + return " ".join(part for part in parts if part).strip() + + +class OtpCode(TimeStampedModel): + """One-time password for phone login.""" + + class Purpose(models.TextChoices): + LOGIN = "login", "Вход" + PHONE_CHANGE = "phone_change", "Смена телефона" + + phone = models.CharField(max_length=20, db_index=True) + code_hash = models.CharField(max_length=128) + purpose = models.CharField( + max_length=20, choices=Purpose.choices, default=Purpose.LOGIN + ) + expires_at = models.DateTimeField() + attempts = models.PositiveSmallIntegerField(default=0) + is_used = models.BooleanField(default=False) + + class Meta: + db_table = "accounts_otp_code" + verbose_name = "OTP-код" + verbose_name_plural = "OTP-коды" + indexes = [ + models.Index(fields=["phone", "purpose", "is_used"]), + ] + + def __str__(self) -> str: + return f"{self.phone} ({self.purpose})" + + def is_expired(self) -> bool: + return timezone.now() >= self.expires_at + + +class Address(TimeStampedModel): + """Customer delivery address.""" + + user = models.ForeignKey( + User, on_delete=models.CASCADE, related_name="addresses" + ) + title = models.CharField("название", max_length=64, default="Дом") + city = models.CharField("город", max_length=128) + street = models.CharField("улица", max_length=255) + house = models.CharField("дом", max_length=32) + apartment = models.CharField("квартира/офис", max_length=32, blank=True) + postal_code = models.CharField("индекс", max_length=16, blank=True) + entrance = models.CharField("подъезд", max_length=16, blank=True) + floor = models.CharField("этаж", max_length=16, blank=True) + intercom = models.CharField("домофон", max_length=32, blank=True) + is_default = models.BooleanField("по умолчанию", default=False) + + class Meta: + db_table = "accounts_address" + verbose_name = "адрес доставки" + verbose_name_plural = "адреса доставки" + ordering = ["-is_default", "-created_at"] + + def __str__(self) -> str: + return f"{self.title}: {self.city}, {self.street}, {self.house}" diff --git a/backend/apps/accounts/serializers.py b/backend/apps/accounts/serializers.py new file mode 100644 index 0000000..5e6edb8 --- /dev/null +++ b/backend/apps/accounts/serializers.py @@ -0,0 +1,64 @@ +from rest_framework import serializers + +from .models import Address, User + + +class OtpRequestSerializer(serializers.Serializer): + phone = serializers.CharField(max_length=20) + + +class OtpVerifySerializer(serializers.Serializer): + phone = serializers.CharField(max_length=20) + code = serializers.CharField(max_length=8) + + +class UserSerializer(serializers.ModelSerializer): + full_name = serializers.CharField(read_only=True) + + class Meta: + model = User + fields = [ + "id", + "phone", + "email", + "first_name", + "last_name", + "middle_name", + "full_name", + "date_joined", + ] + read_only_fields = ["id", "phone", "date_joined"] + + +class ProfileUpdateSerializer(serializers.ModelSerializer): + class Meta: + model = User + fields = ["email", "first_name", "last_name", "middle_name"] + + +class AddressSerializer(serializers.ModelSerializer): + class Meta: + model = Address + fields = [ + "id", + "title", + "city", + "street", + "house", + "apartment", + "postal_code", + "entrance", + "floor", + "intercom", + "is_default", + "created_at", + "updated_at", + ] + read_only_fields = ["id", "created_at", "updated_at"] + + +class PasswordSetSerializer(serializers.Serializer): + current_password = serializers.CharField( + required=False, allow_blank=True, write_only=True + ) + new_password = serializers.CharField(min_length=8, write_only=True) diff --git a/backend/apps/accounts/services.py b/backend/apps/accounts/services.py new file mode 100644 index 0000000..b434af0 --- /dev/null +++ b/backend/apps/accounts/services.py @@ -0,0 +1,81 @@ +import logging +import secrets +from datetime import timedelta + +import phonenumbers +from django.conf import settings +from django.contrib.auth.hashers import check_password, make_password +from django.utils import timezone +from rest_framework.exceptions import ValidationError + +from .models import OtpCode, User +from .sms import send_sms + +logger = logging.getLogger(__name__) + + +def normalize_phone(raw_phone: str) -> str: + """Normalizes a Russian phone number to E.164 (+7XXXXXXXXXX).""" + try: + parsed = phonenumbers.parse(raw_phone, "RU") + except phonenumbers.NumberParseException as exc: + raise ValidationError({"phone": "Некорректный номер телефона"}) from exc + + if not phonenumbers.is_valid_number(parsed): + raise ValidationError({"phone": "Некорректный номер телефона"}) + + return phonenumbers.format_number(parsed, phonenumbers.PhoneNumberFormat.E164) + + +def request_otp( + raw_phone: str, purpose: str = OtpCode.Purpose.LOGIN +) -> tuple[OtpCode, str]: + """Creates a new OTP and sends it via SMS. Returns (otp, code).""" + phone = normalize_phone(raw_phone) + code = settings.OTP_DEBUG_CODE or f"{secrets.randbelow(1_000_000):06d}" + expires_at = timezone.now() + timedelta(seconds=settings.OTP_TTL_SECONDS) + + # Invalidate previous unused codes for this phone/purpose. + OtpCode.objects.filter( + phone=phone, purpose=purpose, is_used=False + ).update(is_used=True) + + otp = OtpCode.objects.create( + phone=phone, + code_hash=make_password(code), + purpose=purpose, + expires_at=expires_at, + ) + send_sms(phone, f"Код входа HOMM: {code}") + return otp, code + + +def verify_otp( + raw_phone: str, code: str, purpose: str = OtpCode.Purpose.LOGIN +) -> User: + """Verifies an OTP and returns the matching (or newly created) user.""" + phone = normalize_phone(raw_phone) + otp = ( + OtpCode.objects.filter(phone=phone, purpose=purpose, is_used=False) + .order_by("-created_at") + .first() + ) + if otp is None: + raise ValidationError({"code": "Код не найден. Запросите новый."}) + if otp.is_expired(): + raise ValidationError({"code": "Срок действия кода истёк."}) + if otp.attempts >= settings.OTP_MAX_ATTEMPTS: + raise ValidationError({"code": "Превышено число попыток. Запросите новый код."}) + + if not check_password(code, otp.code_hash): + otp.attempts += 1 + otp.save(update_fields=["attempts", "updated_at"]) + raise ValidationError({"code": "Неверный код."}) + + otp.is_used = True + otp.save(update_fields=["is_used", "updated_at"]) + + user, created = User.objects.get_or_create(phone=phone) + if created: + logger.info("New customer registered by phone: %s", phone) + return user diff --git a/backend/apps/accounts/sms.py b/backend/apps/accounts/sms.py new file mode 100644 index 0000000..39897db --- /dev/null +++ b/backend/apps/accounts/sms.py @@ -0,0 +1,14 @@ +import logging + +logger = logging.getLogger(__name__) + + +def send_sms(phone: str, text: str) -> None: + """Sends an SMS through the configured provider. + + The provider is intentionally abstracted: at launch the project can use + SMS Aero, Twilio or the operator's gateway. In development the message is + written to the application log. + """ + # TODO: integrate the real SMS provider and delivery status callbacks. + logger.info("SMS to %s: %s", phone, text) diff --git a/backend/apps/accounts/tests.py b/backend/apps/accounts/tests.py new file mode 100644 index 0000000..4ecb30d --- /dev/null +++ b/backend/apps/accounts/tests.py @@ -0,0 +1,34 @@ +from django.test import TestCase +from rest_framework.test import APIClient + + +class OtpAuthTests(TestCase): + def setUp(self): + self.client = APIClient() + + def test_request_and_verify_otp(self): + response = self.client.post( + "/api/v1/auth/otp/request/", + {"phone": "+79991234567"}, + format="json", + ) + self.assertEqual(response.status_code, 200, response.data) + code = response.data["debug_code"] + + response = self.client.post( + "/api/v1/auth/otp/verify/", + {"phone": "+79991234567", "code": code}, + format="json", + ) + self.assertEqual(response.status_code, 200, response.data) + self.assertIn("access", response.data) + self.assertIn("refresh", response.data) + self.assertEqual(response.data["user"]["phone"], "+79991234567") + + def test_invalid_phone_is_rejected(self): + response = self.client.post( + "/api/v1/auth/otp/request/", + {"phone": "123"}, + format="json", + ) + self.assertEqual(response.status_code, 400) diff --git a/backend/apps/accounts/urls.py b/backend/apps/accounts/urls.py new file mode 100644 index 0000000..a8933af --- /dev/null +++ b/backend/apps/accounts/urls.py @@ -0,0 +1,18 @@ +from django.urls import include, path +from rest_framework.routers import DefaultRouter +from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView + +from .views import AddressViewSet, MeView, OtpRequestView, OtpVerifyView, PasswordSetView + +router = DefaultRouter() +router.register("addresses", AddressViewSet, basename="address") + +urlpatterns = [ + path("otp/request/", OtpRequestView.as_view(), name="otp-request"), + path("otp/verify/", OtpVerifyView.as_view(), name="otp-verify"), + path("token/", TokenObtainPairView.as_view(), name="token-obtain"), + path("token/refresh/", TokenRefreshView.as_view(), name="token-refresh"), + path("me/", MeView.as_view(), name="me"), + path("password/", PasswordSetView.as_view(), name="password-set"), + path("", include(router.urls)), +] diff --git a/backend/apps/accounts/views.py b/backend/apps/accounts/views.py new file mode 100644 index 0000000..2bc54e1 --- /dev/null +++ b/backend/apps/accounts/views.py @@ -0,0 +1,125 @@ +from django.conf import settings +from rest_framework import status +from rest_framework.exceptions import ValidationError +from rest_framework.permissions import AllowAny, IsAuthenticated +from rest_framework.response import Response +from rest_framework.views import APIView +from rest_framework.viewsets import ModelViewSet +from rest_framework_simplejwt.tokens import RefreshToken + +from .models import Address +from .serializers import ( + AddressSerializer, + OtpRequestSerializer, + OtpVerifySerializer, + PasswordSetSerializer, + ProfileUpdateSerializer, + UserSerializer, +) +from .services import request_otp, verify_otp + + +class OtpRequestView(APIView): + permission_classes = [AllowAny] + throttle_scope = "otp" + serializer_class = OtpRequestSerializer + + def post(self, request): + serializer = OtpRequestSerializer(data=request.data) + serializer.is_valid(raise_exception=True) + otp, code = request_otp(serializer.validated_data["phone"]) + + payload = { + "detail": "Код отправлен", + "expires_in": settings.OTP_TTL_SECONDS, + } + if settings.OTP_EXPOSE_DEBUG_CODE and settings.OTP_DEBUG_CODE: + payload["debug_code"] = code + return Response(payload, status=status.HTTP_200_OK) + + +class OtpVerifyView(APIView): + permission_classes = [AllowAny] + throttle_scope = "otp" + serializer_class = OtpVerifySerializer + + def post(self, request): + serializer = OtpVerifySerializer(data=request.data) + serializer.is_valid(raise_exception=True) + user = verify_otp( + serializer.validated_data["phone"], serializer.validated_data["code"] + ) + + refresh = RefreshToken.for_user(user) + return Response( + { + "access": str(refresh.access_token), + "refresh": str(refresh), + "user": UserSerializer(user).data, + } + ) + + +class MeView(APIView): + permission_classes = [IsAuthenticated] + serializer_class = UserSerializer + + def get(self, request): + return Response(UserSerializer(request.user).data) + + def patch(self, request): + serializer = ProfileUpdateSerializer( + request.user, data=request.data, partial=True + ) + serializer.is_valid(raise_exception=True) + serializer.save() + return Response(UserSerializer(request.user).data) + + +class PasswordSetView(APIView): + permission_classes = [IsAuthenticated] + serializer_class = PasswordSetSerializer + + def post(self, request): + serializer = PasswordSetSerializer(data=request.data) + serializer.is_valid(raise_exception=True) + user = request.user + + if ( + user.password + and user.has_usable_password() + and not user.check_password( + serializer.validated_data.get("current_password", "") + ) + ): + raise ValidationError({"current_password": "Неверный текущий пароль"}) + + user.set_password(serializer.validated_data["new_password"]) + user.save(update_fields=["password"]) + return Response({"detail": "Пароль обновлён"}) + + +class AddressViewSet(ModelViewSet): + serializer_class = AddressSerializer + permission_classes = [IsAuthenticated] + + def get_queryset(self): + if getattr(self, "swagger_fake_view", False): + return Address.objects.none() + if not self.request.user.is_authenticated: + return Address.objects.none() + return Address.objects.filter(user=self.request.user) + + def perform_create(self, serializer): + if serializer.validated_data.get("is_default"): + Address.objects.filter(user=self.request.user, is_default=True).update( + is_default=False + ) + serializer.save(user=self.request.user) + + def perform_update(self, serializer): + if serializer.validated_data.get("is_default"): + Address.objects.filter(user=self.request.user, is_default=True).exclude( + pk=serializer.instance.pk + ).update(is_default=False) + serializer.save() diff --git a/backend/apps/catalog/__init__.py b/backend/apps/catalog/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/catalog/admin.py b/backend/apps/catalog/admin.py new file mode 100644 index 0000000..cdc67ef --- /dev/null +++ b/backend/apps/catalog/admin.py @@ -0,0 +1,118 @@ +from django.contrib import admin +from django.db.models import Count + +from .models import Category, Product, ProductImage + + +class ProductImageInline(admin.TabularInline): + model = ProductImage + extra = 0 + + +@admin.register(Category) +class CategoryAdmin(admin.ModelAdmin): + list_display = ( + "name", + "slug", + "parent", + "is_active", + "sort_order", + "products_count", + ) + list_filter = ("is_active",) + search_fields = ("name", "external_id") + prepopulated_fields = {"slug": ("name",)} + autocomplete_fields = ("parent",) + actions = ("activate", "deactivate") + + def get_queryset(self, request): + return super().get_queryset(request).annotate(products_count=Count("products")) + + @admin.display(description="Товаров", ordering="products_count") + def products_count(self, obj): + return obj.products_count + + @admin.action(description="Активировать выбранные") + def activate(self, request, queryset): + updated = queryset.update(is_active=True) + self.message_user(request, f"Активировано: {updated}") + + @admin.action(description="Деактивировать выбранные") + def deactivate(self, request, queryset): + updated = queryset.update(is_active=False) + self.message_user(request, f"Деактивировано: {updated}") + + +@admin.register(Product) +class ProductAdmin(admin.ModelAdmin): + list_display = ( + "sku", + "name", + "category", + "price", + "stock", + "stock_status", + "is_hit", + "is_new", + "is_active", + ) + list_filter = ("is_active", "is_hit", "is_new", "stock_status", "category") + search_fields = ("name", "sku", "external_id", "brand") + readonly_fields = ("external_id", "external_updated_at", "created_at", "updated_at") + autocomplete_fields = ("category",) + date_hierarchy = "created_at" + inlines = [ProductImageInline] + actions = ( + "mark_hit", + "unmark_hit", + "mark_new", + "unmark_new", + "activate", + "deactivate", + ) + fieldsets = ( + ( + "Идентификация", + {"fields": ("external_id", "sku", "name", "slug", "brand", "category")}, + ), + ("Цены и остатки", {"fields": ("price", "old_price", "stock", "stock_status")}), + ("Описание", {"fields": ("short_description", "description", "attributes")}), + ("Флаги", {"fields": ("is_hit", "is_new", "is_active")}), + ("Служебное", {"fields": ("external_updated_at", "created_at", "updated_at")}), + ) + + @admin.action(description="Отметить как «Хит продаж»") + def mark_hit(self, request, queryset): + updated = queryset.update(is_hit=True) + self.message_user(request, f"Отмечено: {updated}") + + @admin.action(description="Снять «Хит продаж»") + def unmark_hit(self, request, queryset): + updated = queryset.update(is_hit=False) + self.message_user(request, f"Снято: {updated}") + + @admin.action(description="Отметить как «Новинка»") + def mark_new(self, request, queryset): + updated = queryset.update(is_new=True) + self.message_user(request, f"Отмечено: {updated}") + + @admin.action(description="Снять «Новинка»") + def unmark_new(self, request, queryset): + updated = queryset.update(is_new=False) + self.message_user(request, f"Снято: {updated}") + + @admin.action(description="Активировать выбранные") + def activate(self, request, queryset): + updated = queryset.update(is_active=True) + self.message_user(request, f"Активировано: {updated}") + + @admin.action(description="Деактивировать выбранные") + def deactivate(self, request, queryset): + updated = queryset.update(is_active=False) + self.message_user(request, f"Деактивировано: {updated}") + + +@admin.register(ProductImage) +class ProductImageAdmin(admin.ModelAdmin): + list_display = ("product", "url", "is_main", "sort_order") + search_fields = ("product__name", "product__sku") diff --git a/backend/apps/catalog/apps.py b/backend/apps/catalog/apps.py new file mode 100644 index 0000000..404e933 --- /dev/null +++ b/backend/apps/catalog/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig + + +class CatalogConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "apps.catalog" + verbose_name = "Каталог" diff --git a/backend/apps/catalog/filters.py b/backend/apps/catalog/filters.py new file mode 100644 index 0000000..091838d --- /dev/null +++ b/backend/apps/catalog/filters.py @@ -0,0 +1,34 @@ +import django_filters + +from .models import Product + + +class ProductFilter(django_filters.FilterSet): + category = django_filters.CharFilter( + field_name="category__slug", lookup_expr="exact" + ) + category_id = django_filters.NumberFilter(field_name="category_id") + price_min = django_filters.NumberFilter(field_name="price", lookup_expr="gte") + price_max = django_filters.NumberFilter(field_name="price", lookup_expr="lte") + is_hit = django_filters.BooleanFilter(field_name="is_hit") + is_new = django_filters.BooleanFilter(field_name="is_new") + brand = django_filters.CharFilter(field_name="brand", lookup_expr="iexact") + in_stock = django_filters.BooleanFilter(method="filter_in_stock") + + class Meta: + model = Product + fields = [ + "category", + "category_id", + "price_min", + "price_max", + "is_hit", + "is_new", + "brand", + "in_stock", + ] + + def filter_in_stock(self, queryset, name, value): + if value: + return queryset.filter(stock__gt=0) + return queryset.filter(stock__lte=0) diff --git a/backend/apps/catalog/migrations/0001_initial.py b/backend/apps/catalog/migrations/0001_initial.py new file mode 100644 index 0000000..a810f28 --- /dev/null +++ b/backend/apps/catalog/migrations/0001_initial.py @@ -0,0 +1,103 @@ +# Generated by Django 4.2.16 on 2026-11-06 13:26 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Category', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('external_id', models.CharField(max_length=64, unique=True)), + ('name', models.CharField(max_length=255)), + ('slug', models.SlugField(max_length=255, unique=True)), + ('description', models.TextField(blank=True)), + ('image_url', models.URLField(blank=True, max_length=1000)), + ('is_active', models.BooleanField(default=True)), + ('sort_order', models.IntegerField(default=0)), + ('parent', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='children', to='catalog.category')), + ], + options={ + 'verbose_name': 'категория', + 'verbose_name_plural': 'категории', + 'db_table': 'catalog_category', + 'ordering': ['sort_order', 'name'], + }, + ), + migrations.CreateModel( + name='Product', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('external_id', models.CharField(max_length=64, unique=True)), + ('sku', models.CharField(db_index=True, max_length=64, verbose_name='артикул')), + ('name', models.CharField(max_length=500)), + ('slug', models.SlugField(max_length=500, unique=True)), + ('brand', models.CharField(blank=True, max_length=255)), + ('short_description', models.TextField(blank=True)), + ('description', models.TextField(blank=True)), + ('price', models.DecimalField(decimal_places=2, max_digits=12)), + ('old_price', models.DecimalField(blank=True, decimal_places=2, max_digits=12, null=True)), + ('stock', models.IntegerField(default=0)), + ('stock_status', models.CharField(choices=[('in_stock', 'В наличии'), ('preorder', 'Под заказ'), ('out_of_stock', 'Нет в наличии')], default='out_of_stock', max_length=20)), + ('is_hit', models.BooleanField(default=False, verbose_name='хит продаж')), + ('is_new', models.BooleanField(default=False, verbose_name='новинка')), + ('is_active', models.BooleanField(default=True)), + ('attributes', models.JSONField(blank=True, default=dict)), + ('external_updated_at', models.DateTimeField(blank=True, null=True)), + ('category', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='products', to='catalog.category')), + ], + options={ + 'verbose_name': 'товар', + 'verbose_name_plural': 'товары', + 'db_table': 'catalog_product', + 'ordering': ['-created_at'], + }, + ), + migrations.CreateModel( + name='ProductImage', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('url', models.URLField(max_length=1000)), + ('alt', models.CharField(blank=True, max_length=255)), + ('sort_order', models.IntegerField(default=0)), + ('is_main', models.BooleanField(default=False)), + ('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='images', to='catalog.product')), + ], + options={ + 'verbose_name': 'изображение товара', + 'verbose_name_plural': 'изображения товаров', + 'db_table': 'catalog_product_image', + 'ordering': ['sort_order', 'id'], + }, + ), + migrations.AddIndex( + model_name='product', + index=models.Index(fields=['category', 'is_active'], name='catalog_pro_categor_891fe8_idx'), + ), + migrations.AddIndex( + model_name='product', + index=models.Index(fields=['is_hit'], name='catalog_pro_is_hit_d36eb0_idx'), + ), + migrations.AddIndex( + model_name='product', + index=models.Index(fields=['is_new'], name='catalog_pro_is_new_087fb1_idx'), + ), + migrations.AddIndex( + model_name='product', + index=models.Index(fields=['price'], name='catalog_pro_price_2d2a4c_idx'), + ), + ] diff --git a/backend/apps/catalog/migrations/__init__.py b/backend/apps/catalog/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/catalog/models.py b/backend/apps/catalog/models.py new file mode 100644 index 0000000..5dc4b6e --- /dev/null +++ b/backend/apps/catalog/models.py @@ -0,0 +1,132 @@ +from django.db import models + +from apps.common.models import TimeStampedModel +from apps.common.utils import make_slug + + +class Category(TimeStampedModel): + """Catalog category. Source of truth is 1C.""" + + external_id = models.CharField(max_length=64, unique=True) + parent = models.ForeignKey( + "self", + null=True, + blank=True, + on_delete=models.SET_NULL, + related_name="children", + ) + name = models.CharField(max_length=255) + slug = models.SlugField(max_length=255, unique=True) + description = models.TextField(blank=True) + image_url = models.URLField(max_length=1000, blank=True) + is_active = models.BooleanField(default=True) + sort_order = models.IntegerField(default=0) + + class Meta: + db_table = "catalog_category" + verbose_name = "категория" + verbose_name_plural = "категории" + ordering = ["sort_order", "name"] + + def __str__(self) -> str: + return self.name + + def save(self, *args, **kwargs): + if not self.slug: + self.slug = make_slug(self.name) + super().save(*args, **kwargs) + + +class Product(TimeStampedModel): + """Product card. Price, stock and descriptions come from 1C.""" + + class StockStatus(models.TextChoices): + IN_STOCK = "in_stock", "В наличии" + PREORDER = "preorder", "Под заказ" + OUT_OF_STOCK = "out_of_stock", "Нет в наличии" + + external_id = models.CharField(max_length=64, unique=True) + sku = models.CharField("артикул", max_length=64, db_index=True) + name = models.CharField(max_length=500) + slug = models.SlugField(max_length=500, unique=True) + category = models.ForeignKey( + Category, + null=True, + blank=True, + on_delete=models.SET_NULL, + related_name="products", + ) + brand = models.CharField(max_length=255, blank=True) + short_description = models.TextField(blank=True) + description = models.TextField(blank=True) + price = models.DecimalField(max_digits=12, decimal_places=2) + old_price = models.DecimalField( + max_digits=12, decimal_places=2, null=True, blank=True + ) + stock = models.IntegerField(default=0) + stock_status = models.CharField( + max_length=20, + choices=StockStatus.choices, + default=StockStatus.OUT_OF_STOCK, + ) + is_hit = models.BooleanField("хит продаж", default=False) + is_new = models.BooleanField("новинка", default=False) + is_active = models.BooleanField(default=True) + attributes = models.JSONField(default=dict, blank=True) + external_updated_at = models.DateTimeField(null=True, blank=True) + + class Meta: + db_table = "catalog_product" + verbose_name = "товар" + verbose_name_plural = "товары" + ordering = ["-created_at"] + indexes = [ + models.Index(fields=["category", "is_active"]), + models.Index(fields=["is_hit"]), + models.Index(fields=["is_new"]), + models.Index(fields=["price"]), + ] + + def __str__(self) -> str: + return f"{self.sku} — {self.name}" + + def save(self, *args, **kwargs): + if not self.slug: + self.slug = make_slug(self.name) + super().save(*args, **kwargs) + + @property + def main_image(self) -> str | None: + images = list(self.images.all()) + for image in images: + if image.is_main: + return image.url + return images[0].url if images else None + + def recalculate_stock_status(self) -> str: + if self.stock > 0: + self.stock_status = self.StockStatus.IN_STOCK + elif self.stock_status == self.StockStatus.PREORDER: + self.stock_status = self.StockStatus.PREORDER + else: + self.stock_status = self.StockStatus.OUT_OF_STOCK + return self.stock_status + + +class ProductImage(TimeStampedModel): + product = models.ForeignKey( + Product, on_delete=models.CASCADE, related_name="images" + ) + url = models.URLField(max_length=1000) + alt = models.CharField(max_length=255, blank=True) + sort_order = models.IntegerField(default=0) + is_main = models.BooleanField(default=False) + + class Meta: + db_table = "catalog_product_image" + verbose_name = "изображение товара" + verbose_name_plural = "изображения товаров" + ordering = ["sort_order", "id"] + + def __str__(self) -> str: + return self.url diff --git a/backend/apps/catalog/serializers.py b/backend/apps/catalog/serializers.py new file mode 100644 index 0000000..6949c8c --- /dev/null +++ b/backend/apps/catalog/serializers.py @@ -0,0 +1,50 @@ +from rest_framework import serializers + +from .models import Category, Product, ProductImage + + +class CategorySerializer(serializers.ModelSerializer): + class Meta: + model = Category + fields = ["id", "name", "slug", "parent", "image_url", "sort_order"] + + +class ProductImageSerializer(serializers.ModelSerializer): + class Meta: + model = ProductImage + fields = ["id", "url", "alt", "sort_order", "is_main"] + + +class ProductListSerializer(serializers.ModelSerializer): + main_image = serializers.CharField(read_only=True) + category = CategorySerializer(read_only=True) + + class Meta: + model = Product + fields = [ + "id", + "slug", + "name", + "sku", + "brand", + "price", + "old_price", + "stock_status", + "is_hit", + "is_new", + "main_image", + "category", + ] + + +class ProductDetailSerializer(ProductListSerializer): + images = ProductImageSerializer(many=True, read_only=True) + + class Meta(ProductListSerializer.Meta): + fields = ProductListSerializer.Meta.fields + [ + "short_description", + "description", + "stock", + "attributes", + "images", + ] diff --git a/backend/apps/catalog/tests.py b/backend/apps/catalog/tests.py new file mode 100644 index 0000000..4d62a2e --- /dev/null +++ b/backend/apps/catalog/tests.py @@ -0,0 +1,49 @@ +from decimal import Decimal + +from django.test import TestCase +from rest_framework.test import APIClient + +from .models import Category, Product + + +class CatalogApiTests(TestCase): + def setUp(self): + self.client = APIClient() + self.category = Category.objects.create( + external_id="cat-1", name="Диваны", slug="divany" + ) + self.product = Product.objects.create( + external_id="prod-1", + sku="SKU-1", + name="Диван Осло", + slug="divan-oslo", + category=self.category, + price=Decimal("49990.00"), + stock=5, + stock_status=Product.StockStatus.IN_STOCK, + is_hit=True, + is_new=True, + ) + + def test_product_list(self): + response = self.client.get("/api/v1/catalog/products/") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.data["count"], 1) + self.assertEqual(response.data["results"][0]["sku"], "SKU-1") + + def test_hits_endpoint(self): + response = self.client.get("/api/v1/catalog/products/hits/") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.data["count"], 1) + + def test_filter_by_price(self): + response = self.client.get( + "/api/v1/catalog/products/", {"price_min": "50000"} + ) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.data["count"], 0) + + def test_product_detail(self): + response = self.client.get("/api/v1/catalog/products/divan-oslo/") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.data["name"], "Диван Осло") diff --git a/backend/apps/catalog/urls.py b/backend/apps/catalog/urls.py new file mode 100644 index 0000000..0f00efe --- /dev/null +++ b/backend/apps/catalog/urls.py @@ -0,0 +1,12 @@ +from django.urls import include, path +from rest_framework.routers import DefaultRouter + +from .views import CategoryViewSet, ProductViewSet + +router = DefaultRouter() +router.register("categories", CategoryViewSet, basename="category") +router.register("products", ProductViewSet, basename="product") + +urlpatterns = [ + path("", include(router.urls)), +] diff --git a/backend/apps/catalog/views.py b/backend/apps/catalog/views.py new file mode 100644 index 0000000..afb2072 --- /dev/null +++ b/backend/apps/catalog/views.py @@ -0,0 +1,66 @@ +from rest_framework import viewsets +from rest_framework.decorators import action +from rest_framework.response import Response + +from .filters import ProductFilter +from .models import Category, Product +from .serializers import ( + CategorySerializer, + ProductDetailSerializer, + ProductListSerializer, +) + + +class CategoryViewSet(viewsets.ReadOnlyModelViewSet): + queryset = Category.objects.filter(is_active=True).select_related("parent") + serializer_class = CategorySerializer + lookup_field = "slug" + pagination_class = None + + +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 + + @action(detail=False, methods=["get"]) + def hits(self, request): + return self.list(request) + + @action(detail=False, methods=["get"]) + def new(self, request): + return self.list(request) + + @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) diff --git a/backend/apps/common/__init__.py b/backend/apps/common/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/common/admin.py b/backend/apps/common/admin.py new file mode 100644 index 0000000..1f746ee --- /dev/null +++ b/backend/apps/common/admin.py @@ -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) diff --git a/backend/apps/common/apps.py b/backend/apps/common/apps.py new file mode 100644 index 0000000..25fa407 --- /dev/null +++ b/backend/apps/common/apps.py @@ -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 diff --git a/backend/apps/common/authentication.py b/backend/apps/common/authentication.py new file mode 100644 index 0000000..74b12eb --- /dev/null +++ b/backend/apps/common/authentication.py @@ -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)) diff --git a/backend/apps/common/exceptions.py b/backend/apps/common/exceptions.py new file mode 100644 index 0000000..a68eb6f --- /dev/null +++ b/backend/apps/common/exceptions.py @@ -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, + ) diff --git a/backend/apps/common/management/__init__.py b/backend/apps/common/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/common/management/commands/__init__.py b/backend/apps/common/management/commands/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/common/management/commands/create_roles.py b/backend/apps/common/management/commands/create_roles.py new file mode 100644 index 0000000..3775b44 --- /dev/null +++ b/backend/apps/common/management/commands/create_roles.py @@ -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()} прав" + ) + ) diff --git a/backend/apps/common/middleware.py b/backend/apps/common/middleware.py new file mode 100644 index 0000000..b01fdb3 --- /dev/null +++ b/backend/apps/common/middleware.py @@ -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 diff --git a/backend/apps/common/migrations/__init__.py b/backend/apps/common/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/common/models.py b/backend/apps/common/models.py new file mode 100644 index 0000000..b6bc215 --- /dev/null +++ b/backend/apps/common/models.py @@ -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 diff --git a/backend/apps/common/pagination.py b/backend/apps/common/pagination.py new file mode 100644 index 0000000..62ac80a --- /dev/null +++ b/backend/apps/common/pagination.py @@ -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 diff --git a/backend/apps/common/schema.py b/backend/apps/common/schema.py new file mode 100644 index 0000000..c7dff9c --- /dev/null +++ b/backend/apps/common/schema.py @@ -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", + } diff --git a/backend/apps/common/templatetags/__init__.py b/backend/apps/common/templatetags/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/common/templatetags/admin_metrics.py b/backend/apps/common/templatetags/admin_metrics.py new file mode 100644 index 0000000..a489fd5 --- /dev/null +++ b/backend/apps/common/templatetags/admin_metrics.py @@ -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(), + } diff --git a/backend/apps/common/tests.py b/backend/apps/common/tests.py new file mode 100644 index 0000000..9c5b5eb --- /dev/null +++ b/backend/apps/common/tests.py @@ -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()) diff --git a/backend/apps/common/urls.py b/backend/apps/common/urls.py new file mode 100644 index 0000000..94e8bae --- /dev/null +++ b/backend/apps/common/urls.py @@ -0,0 +1,7 @@ +from django.urls import path + +from .views import health + +urlpatterns = [ + path("health/", health, name="health"), +] diff --git a/backend/apps/common/utils.py b/backend/apps/common/utils.py new file mode 100644 index 0000000..5b94ecf --- /dev/null +++ b/backend/apps/common/utils.py @@ -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" diff --git a/backend/apps/common/views.py b/backend/apps/common/views.py new file mode 100644 index 0000000..3119d33 --- /dev/null +++ b/backend/apps/common/views.py @@ -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) diff --git a/backend/apps/content/__init__.py b/backend/apps/content/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/content/admin.py b/backend/apps/content/admin.py new file mode 100644 index 0000000..7fcc792 --- /dev/null +++ b/backend/apps/content/admin.py @@ -0,0 +1,62 @@ +from django.contrib import admin + +from .models import Banner, SiteSettings, StaticPage + + +@admin.register(SiteSettings) +class SiteSettingsAdmin(admin.ModelAdmin): + fieldsets = ( + ( + "Контакты", + {"fields": ("site_name", "phone", "email", "address", "working_hours")}, + ), + ("Соцсети", {"fields": ("telegram_url", "vk_url", "whatsapp_url")}), + ( + "Доставка", + {"fields": ("free_delivery_threshold", "default_delivery_cost")}, + ), + ( + "Лояльность", + { + "fields": ( + "bonus_accrual_percent", + "bonus_max_payment_percent", + "bonus_ttl_days", + ) + }, + ), + ("Документы", {"fields": ("privacy_policy_url", "offer_url")}), + ("Служебное", {"fields": ("updated_at",)}), + ) + readonly_fields = ("updated_at",) + + def has_add_permission(self, request): + return not SiteSettings.objects.exists() + + def has_delete_permission(self, request, obj=None): + return False + + +@admin.register(StaticPage) +class StaticPageAdmin(admin.ModelAdmin): + list_display = ("title", "slug", "is_published", "updated_at") + list_filter = ("is_published",) + search_fields = ("title", "slug", "content") + prepopulated_fields = {"slug": ("title",)} + readonly_fields = ("created_at", "updated_at") + + +@admin.register(Banner) +class BannerAdmin(admin.ModelAdmin): + list_display = ( + "title", + "position", + "is_active", + "sort_order", + "starts_at", + "ends_at", + ) + list_filter = ("position", "is_active") + search_fields = ("title",) + list_editable = ("is_active", "sort_order") + readonly_fields = ("created_at", "updated_at") diff --git a/backend/apps/content/apps.py b/backend/apps/content/apps.py new file mode 100644 index 0000000..8409aec --- /dev/null +++ b/backend/apps/content/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig + + +class ContentConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "apps.content" + verbose_name = "Контент и настройки" diff --git a/backend/apps/content/migrations/0001_initial.py b/backend/apps/content/migrations/0001_initial.py new file mode 100644 index 0000000..f67a14f --- /dev/null +++ b/backend/apps/content/migrations/0001_initial.py @@ -0,0 +1,84 @@ +# Generated by Django 4.2.16 on 2026-11-06 13:38 + +from decimal import Decimal +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Banner', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('title', models.CharField(max_length=255, verbose_name='название')), + ('image_url', models.URLField(max_length=1000, verbose_name='изображение')), + ('link_url', models.URLField(blank=True, max_length=1000, verbose_name='ссылка')), + ('position', models.CharField(choices=[('home_top', 'Главная — верх'), ('home_middle', 'Главная — середина'), ('category', 'Категория')], default='home_top', max_length=20, verbose_name='позиция')), + ('is_active', models.BooleanField(default=True, verbose_name='активен')), + ('sort_order', models.IntegerField(default=0, verbose_name='порядок')), + ('starts_at', models.DateTimeField(blank=True, null=True, verbose_name='начало показа')), + ('ends_at', models.DateTimeField(blank=True, null=True, verbose_name='конец показа')), + ], + options={ + 'verbose_name': 'баннер', + 'verbose_name_plural': 'баннеры', + 'db_table': 'content_banner', + 'ordering': ['sort_order', '-created_at'], + }, + ), + migrations.CreateModel( + name='SiteSettings', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('site_name', models.CharField(default='HOMM', max_length=255, verbose_name='название сайта')), + ('phone', models.CharField(blank=True, max_length=32, verbose_name='телефон')), + ('email', models.EmailField(blank=True, max_length=254, verbose_name='email')), + ('address', models.CharField(blank=True, max_length=500, verbose_name='адрес')), + ('working_hours', models.CharField(blank=True, max_length=255, verbose_name='часы работы')), + ('telegram_url', models.URLField(blank=True, verbose_name='Telegram')), + ('vk_url', models.URLField(blank=True, verbose_name='ВКонтакте')), + ('whatsapp_url', models.URLField(blank=True, verbose_name='WhatsApp')), + ('free_delivery_threshold', models.DecimalField(decimal_places=2, default=Decimal('0'), max_digits=12, verbose_name='бесплатная доставка от')), + ('default_delivery_cost', models.DecimalField(decimal_places=2, default=Decimal('0'), max_digits=12, verbose_name='стоимость доставки')), + ('bonus_accrual_percent', models.DecimalField(decimal_places=2, default=Decimal('0'), max_digits=5, verbose_name='процент начисления бонусов')), + ('bonus_max_payment_percent', models.DecimalField(decimal_places=2, default=Decimal('0'), max_digits=5, verbose_name='максимум оплаты бонусами, %')), + ('bonus_ttl_days', models.PositiveIntegerField(default=365, verbose_name='срок жизни бонусов, дней')), + ('privacy_policy_url', models.URLField(blank=True, verbose_name='политика конфиденциальности')), + ('offer_url', models.URLField(blank=True, verbose_name='публичная оферта')), + ('updated_at', models.DateTimeField(auto_now=True)), + ], + options={ + 'verbose_name': 'настройки сайта', + 'verbose_name_plural': 'настройки сайта', + 'db_table': 'content_site_settings', + }, + ), + migrations.CreateModel( + name='StaticPage', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('slug', models.SlugField(max_length=255, unique=True, verbose_name='адрес')), + ('title', models.CharField(max_length=255, verbose_name='заголовок')), + ('content', models.TextField(blank=True, verbose_name='содержимое')), + ('seo_title', models.CharField(blank=True, max_length=255, verbose_name='SEO title')), + ('seo_description', models.CharField(blank=True, max_length=500, verbose_name='SEO description')), + ('is_published', models.BooleanField(default=True, verbose_name='опубликована')), + ], + options={ + 'verbose_name': 'статическая страница', + 'verbose_name_plural': 'статические страницы', + 'db_table': 'content_static_page', + 'ordering': ['title'], + }, + ), + ] diff --git a/backend/apps/content/migrations/__init__.py b/backend/apps/content/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/content/models.py b/backend/apps/content/models.py new file mode 100644 index 0000000..e4e9d2c --- /dev/null +++ b/backend/apps/content/models.py @@ -0,0 +1,108 @@ +from decimal import Decimal + +from django.db import models + +from apps.common.models import TimeStampedModel + + +class SiteSettings(models.Model): + """Singleton with store-wide settings editable from the admin.""" + + site_name = models.CharField("название сайта", max_length=255, default="HOMM") + phone = models.CharField("телефон", max_length=32, blank=True) + email = models.EmailField("email", blank=True) + address = models.CharField("адрес", max_length=500, blank=True) + working_hours = models.CharField("часы работы", max_length=255, blank=True) + + telegram_url = models.URLField("Telegram", blank=True) + vk_url = models.URLField("ВКонтакте", blank=True) + whatsapp_url = models.URLField("WhatsApp", blank=True) + + free_delivery_threshold = models.DecimalField( + "бесплатная доставка от", max_digits=12, decimal_places=2, default=Decimal("0") + ) + default_delivery_cost = models.DecimalField( + "стоимость доставки", max_digits=12, decimal_places=2, default=Decimal("0") + ) + + bonus_accrual_percent = models.DecimalField( + "процент начисления бонусов", max_digits=5, decimal_places=2, default=Decimal("0") + ) + bonus_max_payment_percent = models.DecimalField( + "максимум оплаты бонусами, %", max_digits=5, decimal_places=2, default=Decimal("0") + ) + bonus_ttl_days = models.PositiveIntegerField("срок жизни бонусов, дней", default=365) + + privacy_policy_url = models.URLField("политика конфиденциальности", blank=True) + offer_url = models.URLField("публичная оферта", blank=True) + + updated_at = models.DateTimeField(auto_now=True) + + class Meta: + db_table = "content_site_settings" + verbose_name = "настройки сайта" + verbose_name_plural = "настройки сайта" + + def __str__(self) -> str: + return "Настройки сайта" + + def save(self, *args, **kwargs): + self.pk = 1 + super().save(*args, **kwargs) + + @classmethod + def load(cls) -> "SiteSettings": + obj, _ = cls.objects.get_or_create(pk=1) + return obj + + +class StaticPage(TimeStampedModel): + slug = models.SlugField("адрес", max_length=255, unique=True) + title = models.CharField("заголовок", max_length=255) + content = models.TextField("содержимое", blank=True) + seo_title = models.CharField("SEO title", max_length=255, blank=True) + seo_description = models.CharField("SEO description", max_length=500, blank=True) + is_published = models.BooleanField("опубликована", default=True) + + class Meta: + db_table = "content_static_page" + verbose_name = "статическая страница" + verbose_name_plural = "статические страницы" + ordering = ["title"] + + def __str__(self) -> str: + return self.title + + def save(self, *args, **kwargs): + if not self.slug: + from apps.common.utils import make_slug + + self.slug = make_slug(self.title) + super().save(*args, **kwargs) + + +class Banner(TimeStampedModel): + class Position(models.TextChoices): + HOME_TOP = "home_top", "Главная — верх" + HOME_MIDDLE = "home_middle", "Главная — середина" + CATEGORY = "category", "Категория" + + title = models.CharField("название", max_length=255) + image_url = models.URLField("изображение", max_length=1000) + link_url = models.URLField("ссылка", max_length=1000, blank=True) + position = models.CharField( + "позиция", max_length=20, choices=Position.choices, default=Position.HOME_TOP + ) + is_active = models.BooleanField("активен", default=True) + sort_order = models.IntegerField("порядок", default=0) + starts_at = models.DateTimeField("начало показа", null=True, blank=True) + ends_at = models.DateTimeField("конец показа", null=True, blank=True) + + class Meta: + db_table = "content_banner" + verbose_name = "баннер" + verbose_name_plural = "баннеры" + ordering = ["sort_order", "-created_at"] + + def __str__(self) -> str: + return self.title diff --git a/backend/apps/content/serializers.py b/backend/apps/content/serializers.py new file mode 100644 index 0000000..4ea2651 --- /dev/null +++ b/backend/apps/content/serializers.py @@ -0,0 +1,61 @@ +from rest_framework import serializers + +from .models import Banner, SiteSettings, StaticPage + + +class SiteSettingsSerializer(serializers.ModelSerializer): + class Meta: + model = SiteSettings + fields = [ + "site_name", + "phone", + "email", + "address", + "working_hours", + "telegram_url", + "vk_url", + "whatsapp_url", + "free_delivery_threshold", + "default_delivery_cost", + "bonus_accrual_percent", + "bonus_max_payment_percent", + "bonus_ttl_days", + "privacy_policy_url", + "offer_url", + "updated_at", + ] + read_only_fields = ["updated_at"] + + +class StaticPageSerializer(serializers.ModelSerializer): + class Meta: + model = StaticPage + fields = [ + "slug", + "title", + "content", + "seo_title", + "seo_description", + "updated_at", + ] + read_only_fields = ["updated_at"] + + +class BannerSerializer(serializers.ModelSerializer): + position_display = serializers.CharField( + source="get_position_display", read_only=True + ) + + class Meta: + model = Banner + fields = [ + "id", + "title", + "image_url", + "link_url", + "position", + "position_display", + "sort_order", + "starts_at", + "ends_at", + ] diff --git a/backend/apps/content/tests.py b/backend/apps/content/tests.py new file mode 100644 index 0000000..c45cf00 --- /dev/null +++ b/backend/apps/content/tests.py @@ -0,0 +1,69 @@ +from datetime import timedelta + +from django.test import TestCase +from django.utils import timezone +from rest_framework.test import APIClient + +from .models import Banner, SiteSettings, StaticPage + + +class ContentApiTests(TestCase): + def setUp(self): + self.client = APIClient() + + def test_settings(self): + SiteSettings.objects.create(site_name="HOMM", phone="+79991234567") + response = self.client.get("/api/v1/content/settings/") + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(response.data["site_name"], "HOMM") + self.assertEqual(response.data["phone"], "+79991234567") + + def test_pages_only_published(self): + StaticPage.objects.create(slug="about", title="О компании", is_published=True) + StaticPage.objects.create(slug="draft", title="Черновик", is_published=False) + + response = self.client.get("/api/v1/content/pages/") + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(len(response.data), 1) + self.assertEqual(response.data[0]["slug"], "about") + + def test_page_detail(self): + StaticPage.objects.create(slug="delivery", title="Доставка и оплата") + response = self.client.get("/api/v1/content/pages/delivery/") + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(response.data["title"], "Доставка и оплата") + + def test_banners_filter_by_position_and_dates(self): + now = timezone.now() + Banner.objects.create( + title="Активный", + image_url="https://example.com/1.jpg", + position=Banner.Position.HOME_TOP, + is_active=True, + ) + Banner.objects.create( + title="Неактивный", + image_url="https://example.com/2.jpg", + position=Banner.Position.HOME_TOP, + is_active=False, + ) + Banner.objects.create( + title="Просроченный", + image_url="https://example.com/3.jpg", + position=Banner.Position.HOME_TOP, + is_active=True, + ends_at=now - timedelta(days=1), + ) + Banner.objects.create( + title="Другая позиция", + image_url="https://example.com/4.jpg", + position=Banner.Position.CATEGORY, + is_active=True, + ) + + response = self.client.get( + "/api/v1/content/banners/", {"position": "home_top"} + ) + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(len(response.data), 1) + self.assertEqual(response.data[0]["title"], "Активный") diff --git a/backend/apps/content/urls.py b/backend/apps/content/urls.py new file mode 100644 index 0000000..a2c1f4e --- /dev/null +++ b/backend/apps/content/urls.py @@ -0,0 +1,13 @@ +from django.urls import include, path +from rest_framework.routers import DefaultRouter + +from .views import BannerViewSet, SiteSettingsView, StaticPageViewSet + +router = DefaultRouter() +router.register("pages", StaticPageViewSet, basename="page") +router.register("banners", BannerViewSet, basename="banner") + +urlpatterns = [ + path("settings/", SiteSettingsView.as_view(), name="site-settings"), + path("", include(router.urls)), +] diff --git a/backend/apps/content/views.py b/backend/apps/content/views.py new file mode 100644 index 0000000..c6693bd --- /dev/null +++ b/backend/apps/content/views.py @@ -0,0 +1,46 @@ +from django.db.models import Q +from django.utils import timezone +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 .models import Banner, SiteSettings, StaticPage +from .serializers import BannerSerializer, SiteSettingsSerializer, StaticPageSerializer + + +class SiteSettingsView(APIView): + """Public store settings used by the storefront.""" + + permission_classes = [AllowAny] + serializer_class = SiteSettingsSerializer + + def get(self, request): + settings_obj = SiteSettings.load() + return Response(SiteSettingsSerializer(settings_obj).data) + + +class StaticPageViewSet(ReadOnlyModelViewSet): + queryset = StaticPage.objects.filter(is_published=True) + serializer_class = StaticPageSerializer + lookup_field = "slug" + permission_classes = [AllowAny] + pagination_class = None + + +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 diff --git a/backend/apps/integration/__init__.py b/backend/apps/integration/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/integration/admin.py b/backend/apps/integration/admin.py new file mode 100644 index 0000000..b2669af --- /dev/null +++ b/backend/apps/integration/admin.py @@ -0,0 +1,106 @@ +from django.contrib import admin +from django.utils.html import format_html + +from .models import IdempotencyKey, OutboxMessage, SyncLog, SyncRun + + +class SyncLogInline(admin.TabularInline): + model = SyncLog + extra = 0 + readonly_fields = ("level", "message", "payload", "created_at") + can_delete = False + + +@admin.register(SyncRun) +class SyncRunAdmin(admin.ModelAdmin): + list_display = ( + "entity", + "direction", + "status_badge", + "started_at", + "finished_at", + "duration", + ) + list_filter = ("entity", "direction", "status") + readonly_fields = ("started_at", "finished_at", "stats", "error") + inlines = [SyncLogInline] + actions = ("run_catalog_sync",) + + @admin.display(description="Статус", ordering="status") + def status_badge(self, obj): + colors = { + SyncRun.Status.RUNNING: "#2563eb", + SyncRun.Status.SUCCESS: "#16a34a", + SyncRun.Status.PARTIAL: "#d97706", + SyncRun.Status.FAILED: "#dc2626", + } + return format_html( + '{}', + colors.get(obj.status, "#6b7280"), + obj.get_status_display(), + ) + + @admin.display(description="Длительность") + def duration(self, obj): + if not obj.finished_at: + return "—" + seconds = int((obj.finished_at - obj.started_at).total_seconds()) + return f"{seconds} с" + + @admin.action(description="Запустить синхронизацию каталога") + def run_catalog_sync(self, request, queryset): + from .tasks import sync_catalog_from_1c + + try: + task = sync_catalog_from_1c.delay() + except Exception as exc: # noqa: BLE001 - show the broker error to the admin + self.message_user( + request, f"Не удалось поставить задачу: {exc}", level="error" + ) + return + self.message_user(request, f"Задача поставлена в очередь: {task.id}") + + +@admin.register(SyncLog) +class SyncLogAdmin(admin.ModelAdmin): + list_display = ("run", "level", "message", "created_at") + list_filter = ("level",) + search_fields = ("message",) + + +@admin.register(OutboxMessage) +class OutboxMessageAdmin(admin.ModelAdmin): + list_display = ( + "topic", + "status", + "attempts", + "next_attempt_at", + "sent_at", + "created_at", + ) + list_filter = ("status", "topic") + search_fields = ("topic", "last_error") + readonly_fields = ("created_at", "updated_at") + actions = ("retry", "mark_dead") + + @admin.action(description="Повторить отправку") + def retry(self, request, queryset): + updated = queryset.update( + status=OutboxMessage.Status.PENDING, + attempts=0, + next_attempt_at=None, + last_error="", + ) + self.message_user(request, f"Поставлено в очередь: {updated}") + + @admin.action(description="Пометить как dead-letter") + def mark_dead(self, request, queryset): + updated = queryset.update(status=OutboxMessage.Status.DEAD) + self.message_user(request, f"Помечено: {updated}") + + +@admin.register(IdempotencyKey) +class IdempotencyKeyAdmin(admin.ModelAdmin): + list_display = ("scope", "key", "status_code", "created_at") + search_fields = ("key", "scope") diff --git a/backend/apps/integration/apps.py b/backend/apps/integration/apps.py new file mode 100644 index 0000000..dc93027 --- /dev/null +++ b/backend/apps/integration/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig + + +class IntegrationConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "apps.integration" + verbose_name = "Интеграция с 1С" diff --git a/backend/apps/integration/client.py b/backend/apps/integration/client.py new file mode 100644 index 0000000..fc3875a --- /dev/null +++ b/backend/apps/integration/client.py @@ -0,0 +1,79 @@ +import logging +from urllib.parse import urljoin + +import requests +from django.conf import settings + +logger = logging.getLogger(__name__) + + +class OneCClientError(Exception): + """Raised when the 1C HTTP service is unavailable or returns an error.""" + + +class OneCClient: + """Thin HTTP client for the 1C side of the exchange. + + The 1C side is expected to expose an HTTP service (``/hs/homm``) with the + endpoints described in ``docs/openapi-1c-outbound.yaml``. + """ + + def __init__( + self, + base_url: str | None = None, + username: str | None = None, + password: str | None = None, + timeout: int | None = None, + ): + self.base_url = (base_url or settings.ONEC_BASE_URL or "").rstrip("/") + self.username = username if username is not None else settings.ONEC_USERNAME + self.password = password if password is not None else settings.ONEC_PASSWORD + self.timeout = timeout or settings.ONEC_TIMEOUT + self.auth = ( + (self.username, self.password) if self.username else None + ) + + def _request(self, method: str, path: str, **kwargs) -> dict: + if not self.base_url: + raise OneCClientError("ONEC_BASE_URL не настроен") + + url = urljoin(f"{self.base_url}/", path.lstrip("/")) + try: + response = requests.request( + method, + url, + auth=self.auth, + timeout=self.timeout, + headers={"Accept": "application/json"}, + **kwargs, + ) + except requests.RequestException as exc: + raise OneCClientError(f"1C недоступна: {exc}") from exc + + if response.status_code >= 400: + raise OneCClientError( + f"1C вернула {response.status_code}: {response.text[:500]}" + ) + + if not response.content: + return {} + try: + return response.json() + except ValueError as exc: + raise OneCClientError("1C вернула не-JSON ответ") from exc + + def fetch_catalog(self, since=None) -> dict: + params = {"since": since.isoformat()} if since else {} + return self._request("GET", "catalog/changes", params=params) + + def push_order(self, payload: dict) -> dict: + return self._request("POST", "orders", json=payload) + + def push_order_status(self, external_id: str, payload: dict) -> dict: + return self._request("POST", f"orders/{external_id}/status", json=payload) + + def push_customer(self, payload: dict) -> dict: + return self._request("POST", "customers", json=payload) + + def fetch_order_status(self, external_id: str) -> dict: + return self._request("GET", f"orders/{external_id}/status") diff --git a/backend/apps/integration/management/__init__.py b/backend/apps/integration/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/integration/management/commands/__init__.py b/backend/apps/integration/management/commands/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/integration/management/commands/sync_catalog.py b/backend/apps/integration/management/commands/sync_catalog.py new file mode 100644 index 0000000..7a624a8 --- /dev/null +++ b/backend/apps/integration/management/commands/sync_catalog.py @@ -0,0 +1,20 @@ +from django.core.management.base import BaseCommand +from django.utils.dateparse import parse_datetime + +from apps.integration.services import pull_catalog_from_1c + + +class Command(BaseCommand): + help = "Pull catalog changes from 1C and apply them to the store." + + def add_arguments(self, parser): + parser.add_argument( + "--since", + default=None, + help="ISO datetime; only changes after this moment are requested.", + ) + + def handle(self, *args, **options): + since = parse_datetime(options["since"]) if options["since"] else None + stats = pull_catalog_from_1c(since=since) + self.stdout.write(self.style.SUCCESS(f"Catalog synced: {stats}")) diff --git a/backend/apps/integration/migrations/0001_initial.py b/backend/apps/integration/migrations/0001_initial.py new file mode 100644 index 0000000..4ab511d --- /dev/null +++ b/backend/apps/integration/migrations/0001_initial.py @@ -0,0 +1,94 @@ +# Generated by Django 4.2.16 on 2026-11-06 13:26 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='IdempotencyKey', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('key', models.CharField(max_length=128, unique=True)), + ('scope', models.CharField(max_length=64)), + ('status_code', models.PositiveSmallIntegerField(default=200)), + ('response', models.JSONField(blank=True, default=dict)), + ], + options={ + 'verbose_name': 'ключ идемпотентности', + 'verbose_name_plural': 'ключи идемпотентности', + 'db_table': 'integration_idempotency_key', + }, + ), + migrations.CreateModel( + name='SyncRun', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('direction', models.CharField(choices=[('inbound', '1С → сайт'), ('outbound', 'Сайт → 1С')], max_length=10)), + ('entity', models.CharField(choices=[('catalog', 'Каталог'), ('orders', 'Заказы'), ('statuses', 'Статусы'), ('customers', 'Клиенты'), ('bonuses', 'Бонусы')], max_length=20)), + ('status', models.CharField(choices=[('running', 'Выполняется'), ('success', 'Успешно'), ('partial', 'Частично'), ('failed', 'Ошибка')], default='running', max_length=10)), + ('started_at', models.DateTimeField()), + ('finished_at', models.DateTimeField(blank=True, null=True)), + ('stats', models.JSONField(blank=True, default=dict)), + ('error', models.TextField(blank=True)), + ], + options={ + 'verbose_name': 'сеанс обмена', + 'verbose_name_plural': 'сеансы обмена', + 'db_table': 'integration_sync_run', + 'ordering': ['-started_at'], + 'indexes': [models.Index(fields=['entity', 'started_at'], name='integration_entity_5810cd_idx')], + }, + ), + migrations.CreateModel( + name='SyncLog', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('level', models.CharField(choices=[('debug', 'Debug'), ('info', 'Info'), ('warning', 'Warning'), ('error', 'Error')], default='info', max_length=10)), + ('message', models.TextField()), + ('payload', models.JSONField(blank=True, default=dict)), + ('run', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='logs', to='integration.syncrun')), + ], + options={ + 'verbose_name': 'запись журнала обмена', + 'verbose_name_plural': 'журнал обмена', + 'db_table': 'integration_sync_log', + 'ordering': ['created_at'], + }, + ), + migrations.CreateModel( + name='OutboxMessage', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('topic', models.CharField(max_length=64)), + ('payload', models.JSONField(default=dict)), + ('status', models.CharField(choices=[('pending', 'Ожидает'), ('sent', 'Отправлено'), ('failed', 'Ошибка'), ('dead', 'Исчерпаны попытки')], default='pending', max_length=10)), + ('attempts', models.PositiveSmallIntegerField(default=0)), + ('next_attempt_at', models.DateTimeField(blank=True, null=True)), + ('last_error', models.TextField(blank=True)), + ('sent_at', models.DateTimeField(blank=True, null=True)), + ], + options={ + 'verbose_name': 'сообщение outbox', + 'verbose_name_plural': 'сообщения outbox', + 'db_table': 'integration_outbox_message', + 'ordering': ['created_at'], + 'indexes': [models.Index(fields=['status', 'next_attempt_at'], name='integration_status_025e86_idx')], + }, + ), + ] diff --git a/backend/apps/integration/migrations/__init__.py b/backend/apps/integration/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/integration/models.py b/backend/apps/integration/models.py new file mode 100644 index 0000000..c226b31 --- /dev/null +++ b/backend/apps/integration/models.py @@ -0,0 +1,117 @@ +from django.db import models + +from apps.common.models import TimeStampedModel + + +class SyncRun(TimeStampedModel): + """One exchange session with 1C (inbound or outbound).""" + + class Direction(models.TextChoices): + INBOUND = "inbound", "1С → сайт" + OUTBOUND = "outbound", "Сайт → 1С" + + class Entity(models.TextChoices): + CATALOG = "catalog", "Каталог" + ORDERS = "orders", "Заказы" + STATUSES = "statuses", "Статусы" + CUSTOMERS = "customers", "Клиенты" + BONUSES = "bonuses", "Бонусы" + + class Status(models.TextChoices): + RUNNING = "running", "Выполняется" + SUCCESS = "success", "Успешно" + PARTIAL = "partial", "Частично" + FAILED = "failed", "Ошибка" + + direction = models.CharField(max_length=10, choices=Direction.choices) + entity = models.CharField(max_length=20, choices=Entity.choices) + status = models.CharField( + max_length=10, choices=Status.choices, default=Status.RUNNING + ) + started_at = models.DateTimeField() + finished_at = models.DateTimeField(null=True, blank=True) + stats = models.JSONField(default=dict, blank=True) + error = models.TextField(blank=True) + + class Meta: + db_table = "integration_sync_run" + verbose_name = "сеанс обмена" + verbose_name_plural = "сеансы обмена" + ordering = ["-started_at"] + indexes = [models.Index(fields=["entity", "started_at"])] + + def __str__(self) -> str: + return f"{self.get_entity_display()} ({self.get_status_display()})" + + +class SyncLog(TimeStampedModel): + class Level(models.TextChoices): + DEBUG = "debug", "Debug" + INFO = "info", "Info" + WARNING = "warning", "Warning" + ERROR = "error", "Error" + + run = models.ForeignKey( + SyncRun, on_delete=models.CASCADE, related_name="logs" + ) + level = models.CharField( + max_length=10, choices=Level.choices, default=Level.INFO + ) + message = models.TextField() + payload = models.JSONField(default=dict, blank=True) + + class Meta: + db_table = "integration_sync_log" + verbose_name = "запись журнала обмена" + verbose_name_plural = "журнал обмена" + ordering = ["created_at"] + + def __str__(self) -> str: + return f"[{self.level}] {self.message[:80]}" + + +class OutboxMessage(TimeStampedModel): + """Transactional outbox for reliable site → 1C delivery.""" + + class Status(models.TextChoices): + PENDING = "pending", "Ожидает" + SENT = "sent", "Отправлено" + FAILED = "failed", "Ошибка" + DEAD = "dead", "Исчерпаны попытки" + + topic = models.CharField(max_length=64) + payload = models.JSONField(default=dict) + status = models.CharField( + max_length=10, choices=Status.choices, default=Status.PENDING + ) + attempts = models.PositiveSmallIntegerField(default=0) + next_attempt_at = models.DateTimeField(null=True, blank=True) + last_error = models.TextField(blank=True) + sent_at = models.DateTimeField(null=True, blank=True) + + class Meta: + db_table = "integration_outbox_message" + verbose_name = "сообщение outbox" + verbose_name_plural = "сообщения outbox" + ordering = ["created_at"] + indexes = [models.Index(fields=["status", "next_attempt_at"])] + + def __str__(self) -> str: + return f"{self.topic} ({self.status})" + + +class IdempotencyKey(TimeStampedModel): + """Stores responses for repeated inbound requests.""" + + key = models.CharField(max_length=128, unique=True) + scope = models.CharField(max_length=64) + status_code = models.PositiveSmallIntegerField(default=200) + response = models.JSONField(default=dict, blank=True) + + class Meta: + db_table = "integration_idempotency_key" + verbose_name = "ключ идемпотентности" + verbose_name_plural = "ключи идемпотентности" + + def __str__(self) -> str: + return f"{self.scope}:{self.key}" diff --git a/backend/apps/integration/outbox.py b/backend/apps/integration/outbox.py new file mode 100644 index 0000000..aba1151 --- /dev/null +++ b/backend/apps/integration/outbox.py @@ -0,0 +1,10 @@ +from .models import OutboxMessage + + +def enqueue(topic: str, payload: dict) -> OutboxMessage: + """Adds a message to the transactional outbox. + + Called inside the same DB transaction as the business change, so an order + can never be committed without a corresponding 1C push task. + """ + return OutboxMessage.objects.create(topic=topic, payload=payload) diff --git a/backend/apps/integration/serializers.py b/backend/apps/integration/serializers.py new file mode 100644 index 0000000..60111cb --- /dev/null +++ b/backend/apps/integration/serializers.py @@ -0,0 +1,136 @@ +from rest_framework import serializers + +from apps.catalog.models import Product +from apps.orders.models import Order, OrderItem + + +class CategoryPayloadSerializer(serializers.Serializer): + external_id = serializers.CharField(max_length=64) + parent_external_id = serializers.CharField( + max_length=64, required=False, allow_blank=True, allow_null=True + ) + name = serializers.CharField(max_length=255) + slug = serializers.CharField(max_length=255, required=False, allow_blank=True) + description = serializers.CharField(required=False, allow_blank=True) + image_url = serializers.URLField(required=False, allow_blank=True) + is_active = serializers.BooleanField(default=True) + sort_order = serializers.IntegerField(default=0) + + +class ProductImagePayloadSerializer(serializers.Serializer): + url = serializers.URLField(max_length=1000) + alt = serializers.CharField(max_length=255, required=False, allow_blank=True) + sort_order = serializers.IntegerField(default=0) + is_main = serializers.BooleanField(default=False) + + +class ProductPayloadSerializer(serializers.Serializer): + external_id = serializers.CharField(max_length=64) + sku = serializers.CharField(max_length=64) + name = serializers.CharField(max_length=500) + slug = serializers.CharField(max_length=500, required=False, allow_blank=True) + category_external_id = serializers.CharField( + max_length=64, required=False, allow_blank=True, allow_null=True + ) + brand = serializers.CharField(max_length=255, required=False, allow_blank=True) + short_description = serializers.CharField(required=False, allow_blank=True) + description = serializers.CharField(required=False, allow_blank=True) + price = serializers.DecimalField(max_digits=12, decimal_places=2) + old_price = serializers.DecimalField( + max_digits=12, decimal_places=2, required=False, allow_null=True + ) + stock = serializers.IntegerField(default=0) + stock_status = serializers.ChoiceField( + choices=Product.StockStatus.choices, required=False + ) + is_hit = serializers.BooleanField(default=False) + is_new = serializers.BooleanField(default=False) + is_active = serializers.BooleanField(default=True) + attributes = serializers.DictField(required=False) + images = ProductImagePayloadSerializer(many=True, required=False) + external_updated_at = serializers.DateTimeField(required=False, allow_null=True) + + +class CatalogSyncSerializer(serializers.Serializer): + sync_id = serializers.CharField(max_length=64, required=False, allow_blank=True) + categories = CategoryPayloadSerializer(many=True, required=False, default=list) + products = ProductPayloadSerializer(many=True, required=False, default=list) + deleted_product_external_ids = serializers.ListField( + child=serializers.CharField(max_length=64), required=False, default=list + ) + deleted_category_external_ids = serializers.ListField( + child=serializers.CharField(max_length=64), required=False, default=list + ) + + +class OrderStatusPayloadSerializer(serializers.Serializer): + status = serializers.CharField(max_length=64) + comment = serializers.CharField(required=False, allow_blank=True) + changed_at = serializers.DateTimeField(required=False) + external_id = serializers.CharField( + max_length=64, required=False, allow_blank=True + ) + + +class BonusPayloadSerializer(serializers.Serializer): + phone = serializers.CharField(max_length=20, required=False, allow_blank=True) + external_customer_id = serializers.CharField( + max_length=64, required=False, allow_blank=True + ) + amount = serializers.DecimalField(max_digits=12, decimal_places=2) + reason = serializers.ChoiceField( + choices=["accrual", "spend", "refund", "adjustment"], default="accrual" + ) + comment = serializers.CharField(required=False, allow_blank=True) + order_number = serializers.CharField( + max_length=32, required=False, allow_blank=True + ) + + +class OrderAckSerializer(serializers.Serializer): + external_id = serializers.CharField(max_length=64) + + +class HealthSerializer(serializers.Serializer): + status = serializers.CharField() + time = serializers.DateTimeField() + + +class ManualSyncResponseSerializer(serializers.Serializer): + status = serializers.CharField() + task_id = serializers.CharField() + + +class PendingOrderItemSerializer(serializers.ModelSerializer): + class Meta: + model = OrderItem + fields = ["sku", "product_external_id", "name", "price", "quantity", "total"] + + +class PendingOrderSerializer(serializers.ModelSerializer): + items = PendingOrderItemSerializer(many=True, read_only=True) + + class Meta: + model = Order + fields = [ + "number", + "external_id", + "status", + "payment_status", + "customer_name", + "phone", + "email", + "delivery_method", + "delivery_address", + "delivery_cost", + "comment", + "subtotal", + "discount_total", + "bonus_applied", + "certificate_applied", + "total", + "promo_code", + "certificate_code", + "created_at", + "items", + ] diff --git a/backend/apps/integration/services.py b/backend/apps/integration/services.py new file mode 100644 index 0000000..d5b4e50 --- /dev/null +++ b/backend/apps/integration/services.py @@ -0,0 +1,378 @@ +import logging +from datetime import timedelta +from decimal import Decimal + +from django.db import transaction +from django.db.models import Q +from django.utils import timezone + +from apps.accounts.models import User +from apps.accounts.services import normalize_phone +from apps.catalog.models import Category, Product, ProductImage +from apps.common.exceptions import IntegrationError +from apps.common.utils import make_slug +from apps.loyalty.services import accrue_bonus, spend_bonus +from apps.orders.models import Order, OrderStatusHistory + +from .client import OneCClient +from .models import OutboxMessage, SyncLog, SyncRun +from .status_map import map_1c_status + +logger = logging.getLogger(__name__) + + +def _unique_slug(model, base: str, exclude_pk=None) -> str: + slug = base + counter = 2 + queryset = model.objects.all() + if exclude_pk is not None: + queryset = queryset.exclude(pk=exclude_pk) + while queryset.filter(slug=slug).exists(): + slug = f"{base}-{counter}" + counter += 1 + return slug + + +def _log(run: SyncRun | None, level: str, message: str, payload: dict | None = None): + if run is not None: + SyncLog.objects.create( + run=run, level=level, message=message, payload=payload or {} + ) + + +@transaction.atomic +def upsert_catalog(payload: dict, run: SyncRun | None = None) -> dict: + """Applies a catalog batch from 1C. Idempotent by external_id.""" + stats = { + "categories_created": 0, + "categories_updated": 0, + "products_created": 0, + "products_updated": 0, + "products_deleted": 0, + "categories_deleted": 0, + "images_replaced": 0, + } + + categories = payload.get("categories", []) + for item in categories: + existing = Category.objects.filter(external_id=item["external_id"]).first() + slug = _unique_slug( + Category, + item.get("slug") or make_slug(item["name"]), + existing.pk if existing else None, + ) + _, created = Category.objects.update_or_create( + external_id=item["external_id"], + defaults={ + "name": item["name"], + "slug": slug, + "description": item.get("description", ""), + "image_url": item.get("image_url", ""), + "is_active": item.get("is_active", True), + "sort_order": item.get("sort_order", 0), + }, + ) + stats["categories_created" if created else "categories_updated"] += 1 + + # Second pass: link parents after all categories exist. + for item in categories: + parent_external_id = item.get("parent_external_id") + if not parent_external_id: + continue + parent = Category.objects.filter(external_id=parent_external_id).first() + if parent is None: + _log( + run, + SyncLog.Level.WARNING, + f"Parent category {parent_external_id} not found", + {"category": item["external_id"]}, + ) + continue + Category.objects.filter(external_id=item["external_id"]).update(parent=parent) + + for item in payload.get("products", []): + existing = Product.objects.filter(external_id=item["external_id"]).first() + slug = _unique_slug( + Product, + item.get("slug") or make_slug(item["name"]), + existing.pk if existing else None, + ) + + category = None + category_external_id = item.get("category_external_id") + if category_external_id: + category = Category.objects.filter( + external_id=category_external_id + ).first() + if category is None: + _log( + run, + SyncLog.Level.WARNING, + f"Category {category_external_id} not found for product", + {"product": item["external_id"]}, + ) + + stock = item.get("stock", 0) + stock_status = item.get("stock_status") or ( + Product.StockStatus.IN_STOCK + if stock > 0 + else Product.StockStatus.OUT_OF_STOCK + ) + + defaults = { + "sku": item["sku"], + "name": item["name"], + "slug": slug, + "category": category, + "brand": item.get("brand", ""), + "short_description": item.get("short_description", ""), + "description": item.get("description", ""), + "price": item["price"], + "old_price": item.get("old_price"), + "stock": stock, + "stock_status": stock_status, + "is_hit": item.get("is_hit", False), + "is_new": item.get("is_new", False), + "is_active": item.get("is_active", True), + "attributes": item.get( + "attributes", existing.attributes if existing else {} + ), + "external_updated_at": item.get("external_updated_at"), + } + product, created = Product.objects.update_or_create( + external_id=item["external_id"], defaults=defaults + ) + stats["products_created" if created else "products_updated"] += 1 + + if "images" in item: + product.images.all().delete() + for image in item["images"]: + ProductImage.objects.create(product=product, **image) + stats["images_replaced"] += len(item["images"]) + + for external_id in payload.get("deleted_product_external_ids", []): + stats["products_deleted"] += Product.objects.filter( + external_id=external_id + ).update(is_active=False) + + for external_id in payload.get("deleted_category_external_ids", []): + stats["categories_deleted"] += Category.objects.filter( + external_id=external_id + ).update(is_active=False) + + _log(run, SyncLog.Level.INFO, "Catalog batch applied", stats) + return stats + + +@transaction.atomic +def apply_order_status( + order_number: str, payload: dict, run: SyncRun | None = None +) -> Order: + order = Order.objects.select_for_update().filter(number=order_number).first() + if order is None: + raise IntegrationError( + f"Заказ {order_number} не найден", code="order_not_found" + ) + + status = map_1c_status(payload.get("status")) + if status is None: + raise IntegrationError( + f"Неизвестный статус 1С: {payload.get('status')}", + code="unknown_status", + ) + + if payload.get("external_id"): + order.external_id = payload["external_id"] + order.status = status + order.save(update_fields=["status", "external_id", "updated_at"]) + + OrderStatusHistory.objects.create( + order=order, + status=status, + comment=payload.get("comment", ""), + source=OrderStatusHistory.Source.ONEC, + ) + _log(run, SyncLog.Level.INFO, f"Order {order.number} -> {status}") + return order + + +@transaction.atomic +def apply_bonus(payload: dict, run: SyncRun | None = None) -> User: + phone = payload.get("phone") + if not phone: + raise IntegrationError( + "Не передан phone. Маппинг external_customer_id пока не настроен.", + code="customer_not_found", + ) + + normalized = normalize_phone(phone) + user = User.objects.filter(phone=normalized).first() + if user is None: + raise IntegrationError( + f"Клиент {normalized} не найден", code="customer_not_found" + ) + + order = None + if payload.get("order_number"): + order = Order.objects.filter(number=payload["order_number"]).first() + + amount = Decimal(payload["amount"]) + if amount >= 0: + accrue_bonus( + user, amount, order=order, comment=payload.get("comment", "") + ) + else: + spend_bonus(user, -amount, order=order) + + _log(run, SyncLog.Level.INFO, f"Bonus {amount} applied to {normalized}") + return user + + +def build_order_payload(order: Order) -> dict: + return { + "number": order.number, + "created_at": order.created_at.isoformat(), + "customer": { + "name": order.customer_name, + "phone": order.phone, + "email": order.email, + }, + "delivery": { + "method": order.delivery_method, + "address": order.delivery_address, + "cost": str(order.delivery_cost), + }, + "items": [ + { + "sku": item.sku, + "external_id": item.product_external_id, + "name": item.name, + "price": str(item.price), + "quantity": item.quantity, + "total": str(item.total), + } + for item in order.items.all() + ], + "totals": { + "subtotal": str(order.subtotal), + "discount": str(order.discount_total), + "bonus": str(order.bonus_applied), + "certificate": str(order.certificate_applied), + "delivery": str(order.delivery_cost), + "total": str(order.total), + }, + "payment": {"status": order.payment_status}, + "promo_code": order.promo_code, + "certificate_code": order.certificate_code, + } + + +def push_order_to_1c(order: Order) -> dict: + client = OneCClient() + response = client.push_order(build_order_payload(order)) + order.external_id = str( + response.get("external_id") or response.get("number") or order.external_id or "" + ) + order.synced_at = timezone.now() + order.sync_error = "" + order.save( + update_fields=["external_id", "synced_at", "sync_error", "updated_at"] + ) + return response + + +def push_customer_to_1c(user: User) -> dict: + client = OneCClient() + return client.push_customer( + {"phone": user.phone, "email": user.email or "", "name": user.full_name} + ) + + +def pull_catalog_from_1c(since=None) -> dict: + run = SyncRun.objects.create( + direction=SyncRun.Direction.INBOUND, + entity=SyncRun.Entity.CATALOG, + status=SyncRun.Status.RUNNING, + started_at=timezone.now(), + ) + try: + payload = OneCClient().fetch_catalog(since=since) + stats = upsert_catalog(payload, run=run) + run.status = SyncRun.Status.SUCCESS + run.stats = stats + run.finished_at = timezone.now() + run.save(update_fields=["status", "stats", "finished_at", "updated_at"]) + return stats + except Exception as exc: + run.status = SyncRun.Status.FAILED + run.error = str(exc) + run.finished_at = timezone.now() + run.save(update_fields=["status", "error", "finished_at", "updated_at"]) + _log(run, SyncLog.Level.ERROR, str(exc)) + raise + + +def _dispatch_outbox(message: OutboxMessage) -> None: + if message.topic == "order.created": + order = Order.objects.get(pk=message.payload["order_id"]) + push_order_to_1c(order) + elif message.topic == "order.status_changed": + order = Order.objects.get(pk=message.payload["order_id"]) + OneCClient().push_order_status( + order.external_id or order.number, + {"status": order.status, "comment": "Изменено на сайте"}, + ) + elif message.topic == "customer.created": + user = User.objects.get(pk=message.payload["user_id"]) + push_customer_to_1c(user) + else: + raise IntegrationError(f"Неизвестный outbox topic: {message.topic}") + + +def process_outbox(limit: int = 100) -> int: + now = timezone.now() + messages = ( + OutboxMessage.objects.filter(status=OutboxMessage.Status.PENDING) + .filter(Q(next_attempt_at__isnull=True) | Q(next_attempt_at__lte=now)) + .order_by("created_at")[:limit] + ) + + processed = 0 + for message in messages: + try: + _dispatch_outbox(message) + message.status = OutboxMessage.Status.SENT + message.sent_at = timezone.now() + message.last_error = "" + except Exception as exc: # noqa: BLE001 - outbox must never crash the worker + message.attempts += 1 + message.last_error = str(exc)[:2000] + if message.attempts >= 5: + message.status = OutboxMessage.Status.DEAD + else: + message.next_attempt_at = timezone.now() + timedelta( + minutes=2**message.attempts + ) + logger.warning("Outbox %s failed: %s", message.pk, exc) + message.save() + processed += 1 + return processed + + +def pull_order_statuses(limit: int = 100) -> int: + client = OneCClient() + orders = ( + Order.objects.exclude(external_id="") + .exclude(status__in=[Order.Status.COMPLETED, Order.Status.CANCELLED]) + .order_by("created_at")[:limit] + ) + + updated = 0 + for order in orders: + try: + payload = client.fetch_order_status(order.external_id) + apply_order_status(order.number, payload) + updated += 1 + except Exception as exc: # noqa: BLE001 - one order must not stop the batch + logger.warning("Failed to pull status for %s: %s", order.number, exc) + return updated diff --git a/backend/apps/integration/status_map.py b/backend/apps/integration/status_map.py new file mode 100644 index 0000000..70f6167 --- /dev/null +++ b/backend/apps/integration/status_map.py @@ -0,0 +1,33 @@ +from apps.orders.models import Order + +# 1C statuses are configurable per configuration (УТ/ERP/УНФ), so the mapping +# is intentionally explicit and easy to extend. Keys are normalized to lower +# case and stripped before lookup. +ONEC_STATUS_MAP: dict[str, str] = { + # English codes + "new": Order.Status.NEW, + "processing": Order.Status.PROCESSING, + "delivering": Order.Status.DELIVERING, + "completed": Order.Status.COMPLETED, + "cancelled": Order.Status.CANCELLED, + "canceled": Order.Status.CANCELLED, + # Russian names + "новый": Order.Status.NEW, + "в обработке": Order.Status.PROCESSING, + "подтвержден": Order.Status.PROCESSING, + "подтверждён": Order.Status.PROCESSING, + "собирается": Order.Status.PROCESSING, + "передан в доставку": Order.Status.DELIVERING, + "доставляется": Order.Status.DELIVERING, + "в пути": Order.Status.DELIVERING, + "выполнен": Order.Status.COMPLETED, + "закрыт": Order.Status.COMPLETED, + "отменен": Order.Status.CANCELLED, + "отменён": Order.Status.CANCELLED, +} + + +def map_1c_status(raw_status: str | None) -> str | None: + if not raw_status: + return None + return ONEC_STATUS_MAP.get(raw_status.strip().lower()) diff --git a/backend/apps/integration/tasks.py b/backend/apps/integration/tasks.py new file mode 100644 index 0000000..53c6ef1 --- /dev/null +++ b/backend/apps/integration/tasks.py @@ -0,0 +1,31 @@ +from celery import shared_task + +from apps.orders.models import Order + +from .services import ( + process_outbox as _process_outbox, + pull_catalog_from_1c, + pull_order_statuses as _pull_order_statuses, + push_order_to_1c, +) + + +@shared_task +def sync_catalog_from_1c(since=None): + return pull_catalog_from_1c(since=since) + + +@shared_task +def push_order(order_id): + order = Order.objects.get(pk=order_id) + return push_order_to_1c(order) + + +@shared_task +def process_outbox(limit: int = 100): + return _process_outbox(limit=limit) + + +@shared_task +def pull_order_statuses(limit: int = 100): + return _pull_order_statuses(limit=limit) diff --git a/backend/apps/integration/tests.py b/backend/apps/integration/tests.py new file mode 100644 index 0000000..cfb63c7 --- /dev/null +++ b/backend/apps/integration/tests.py @@ -0,0 +1,82 @@ +from decimal import Decimal + +from django.conf import settings +from django.test import TestCase +from rest_framework.test import APIClient + +from apps.catalog.models import Product +from apps.orders.models import Order + + +class IntegrationApiTests(TestCase): + def setUp(self): + self.client = APIClient() + self.token = settings.INTEGRATION_API_TOKEN + + def test_requires_token(self): + response = self.client.get("/api/v1/integration/1c/health/") + self.assertEqual(response.status_code, 401) + + def test_catalog_sync(self): + payload = { + "sync_id": "sync-1", + "categories": [{"external_id": "c1", "name": "Кресла"}], + "products": [ + { + "external_id": "p1", + "sku": "SKU-1", + "name": "Кресло Эймс", + "price": "1000.00", + "stock": 3, + "category_external_id": "c1", + "images": [ + {"url": "https://example.com/1.jpg", "is_main": True} + ], + } + ], + } + response = self.client.post( + "/api/v1/integration/1c/catalog/sync/", + payload, + format="json", + HTTP_X_INTEGRATION_TOKEN=self.token, + ) + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(response.data["stats"]["products_created"], 1) + + product = Product.objects.get(external_id="p1") + self.assertEqual(product.price, Decimal("1000.00")) + self.assertEqual(product.stock, 3) + self.assertEqual(product.images.count(), 1) + + def test_order_status_update(self): + order = Order.objects.create( + customer_name="Иван", + phone="+79991234567", + total=Decimal("1000.00"), + ) + response = self.client.post( + f"/api/v1/integration/1c/orders/{order.number}/status/", + {"status": "Выполнен", "comment": "Выдан клиенту"}, + format="json", + HTTP_X_INTEGRATION_TOKEN=self.token, + ) + self.assertEqual(response.status_code, 200, response.data) + order.refresh_from_db() + self.assertEqual(order.status, Order.Status.COMPLETED) + self.assertEqual(order.status_history.count(), 1) + + def test_unknown_status_is_rejected(self): + order = Order.objects.create( + customer_name="Иван", + phone="+79991234567", + total=Decimal("1000.00"), + ) + response = self.client.post( + f"/api/v1/integration/1c/orders/{order.number}/status/", + {"status": "Неизвестный статус"}, + format="json", + HTTP_X_INTEGRATION_TOKEN=self.token, + ) + self.assertEqual(response.status_code, 400) + self.assertEqual(response.data["error"]["code"], "unknown_status") diff --git a/backend/apps/integration/urls.py b/backend/apps/integration/urls.py new file mode 100644 index 0000000..a68405c --- /dev/null +++ b/backend/apps/integration/urls.py @@ -0,0 +1,29 @@ +from django.urls import path + +from .views import ( + BonusView, + CatalogSyncView, + IntegrationHealthView, + ManualSyncView, + OrderAckView, + OrderStatusView, + PendingOrdersView, +) + +urlpatterns = [ + path("health/", IntegrationHealthView.as_view(), name="integration-health"), + path("catalog/sync/", CatalogSyncView.as_view(), name="integration-catalog-sync"), + path("orders/pending/", PendingOrdersView.as_view(), name="integration-pending-orders"), + path( + "orders//status/", + OrderStatusView.as_view(), + name="integration-order-status", + ), + path( + "orders//ack/", + OrderAckView.as_view(), + name="integration-order-ack", + ), + path("customers/bonus/", BonusView.as_view(), name="integration-bonus"), + path("sync/run/", ManualSyncView.as_view(), name="integration-manual-sync"), +] diff --git a/backend/apps/integration/views.py b/backend/apps/integration/views.py new file mode 100644 index 0000000..72600b3 --- /dev/null +++ b/backend/apps/integration/views.py @@ -0,0 +1,163 @@ +from django.utils import timezone +from rest_framework.permissions import IsAdminUser +from rest_framework.response import Response +from rest_framework.views import APIView + +from apps.common.authentication import ( + IntegrationTokenAuthentication, + IsIntegrationClient, +) +from apps.common.exceptions import IntegrationError +from apps.orders.models import Order + +from .models import SyncRun +from .serializers import ( + BonusPayloadSerializer, + CatalogSyncSerializer, + HealthSerializer, + ManualSyncResponseSerializer, + OrderAckSerializer, + OrderStatusPayloadSerializer, + PendingOrderSerializer, +) +from .services import apply_bonus, apply_order_status, upsert_catalog + + +class IntegrationBaseView(APIView): + authentication_classes = [IntegrationTokenAuthentication] + permission_classes = [IsIntegrationClient] + + +class IntegrationHealthView(IntegrationBaseView): + serializer_class = HealthSerializer + + def get(self, request): + return Response({"status": "ok", "time": timezone.now().isoformat()}) + + +class CatalogSyncView(IntegrationBaseView): + serializer_class = CatalogSyncSerializer + + def post(self, request): + serializer = CatalogSyncSerializer(data=request.data) + serializer.is_valid(raise_exception=True) + + run = SyncRun.objects.create( + direction=SyncRun.Direction.INBOUND, + entity=SyncRun.Entity.CATALOG, + status=SyncRun.Status.RUNNING, + started_at=timezone.now(), + ) + try: + stats = upsert_catalog(serializer.validated_data, run=run) + except Exception as exc: # noqa: BLE001 - report the failure to 1C + run.status = SyncRun.Status.FAILED + run.error = str(exc) + run.finished_at = timezone.now() + run.save(update_fields=["status", "error", "finished_at", "updated_at"]) + return Response( + {"error": {"code": "catalog_sync_failed", "message": str(exc)}}, + status=400, + ) + + run.status = SyncRun.Status.SUCCESS + run.stats = stats + run.finished_at = timezone.now() + run.save(update_fields=["status", "stats", "finished_at", "updated_at"]) + return Response( + { + "status": "ok", + "sync_id": serializer.validated_data.get("sync_id", ""), + "stats": stats, + } + ) + + +class OrderStatusView(IntegrationBaseView): + serializer_class = OrderStatusPayloadSerializer + + def post(self, request, number: str): + serializer = OrderStatusPayloadSerializer(data=request.data) + serializer.is_valid(raise_exception=True) + try: + order = apply_order_status(number, serializer.validated_data) + except IntegrationError as exc: + status_code = 404 if exc.code == "order_not_found" else 400 + return Response( + {"error": {"code": exc.code, "message": exc.message}}, + status=status_code, + ) + return Response( + {"status": "ok", "order": order.number, "order_status": order.status} + ) + + +class BonusView(IntegrationBaseView): + serializer_class = BonusPayloadSerializer + + def post(self, request): + serializer = BonusPayloadSerializer(data=request.data) + serializer.is_valid(raise_exception=True) + try: + user = apply_bonus(serializer.validated_data) + except IntegrationError as exc: + status_code = 404 if exc.code == "customer_not_found" else 400 + return Response( + {"error": {"code": exc.code, "message": exc.message}}, + status=status_code, + ) + return Response({"status": "ok", "phone": user.phone}) + + +class PendingOrdersView(IntegrationBaseView): + serializer_class = PendingOrderSerializer + + def get(self, request): + orders = ( + Order.objects.filter(external_id="") + .exclude(status=Order.Status.CANCELLED) + .prefetch_related("items") + .order_by("created_at")[:100] + ) + return Response({"orders": PendingOrderSerializer(orders, many=True).data}) + + +class OrderAckView(IntegrationBaseView): + serializer_class = OrderAckSerializer + + def post(self, request, number: str): + serializer = OrderAckSerializer(data=request.data) + serializer.is_valid(raise_exception=True) + + order = Order.objects.filter(number=number).first() + if order is None: + return Response( + { + "error": { + "code": "order_not_found", + "message": f"Заказ {number} не найден", + } + }, + status=404, + ) + + order.external_id = serializer.validated_data["external_id"] + order.synced_at = timezone.now() + order.sync_error = "" + order.save( + update_fields=["external_id", "synced_at", "sync_error", "updated_at"] + ) + return Response({"status": "ok"}) + + +class ManualSyncView(APIView): + """Admin-triggered catalog sync (JWT + staff).""" + + permission_classes = [IsAdminUser] + serializer_class = ManualSyncResponseSerializer + + def post(self, request): + from .tasks import sync_catalog_from_1c + + task = sync_catalog_from_1c.delay() + return Response({"status": "queued", "task_id": task.id}) diff --git a/backend/apps/loyalty/__init__.py b/backend/apps/loyalty/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/loyalty/admin.py b/backend/apps/loyalty/admin.py new file mode 100644 index 0000000..2008efa --- /dev/null +++ b/backend/apps/loyalty/admin.py @@ -0,0 +1,70 @@ +from django.contrib import admin + +from .models import BonusAccount, BonusTransaction, GiftCertificate, PromoCode + + +class BonusTransactionInline(admin.TabularInline): + model = BonusTransaction + extra = 0 + readonly_fields = ("amount", "reason", "order", "comment", "created_at") + can_delete = False + + +@admin.register(BonusAccount) +class BonusAccountAdmin(admin.ModelAdmin): + list_display = ("user", "balance", "updated_at") + search_fields = ("user__phone",) + readonly_fields = ("created_at", "updated_at") + inlines = [BonusTransactionInline] + + +@admin.register(BonusTransaction) +class BonusTransactionAdmin(admin.ModelAdmin): + list_display = ("account", "amount", "reason", "order", "created_at") + list_filter = ("reason",) + search_fields = ("account__user__phone", "order__number") + readonly_fields = ("created_at", "updated_at") + + +@admin.register(PromoCode) +class PromoCodeAdmin(admin.ModelAdmin): + list_display = ( + "code", + "discount_type", + "value", + "min_order_total", + "used_count", + "max_uses", + "is_active", + ) + list_filter = ("discount_type", "is_active") + search_fields = ("code",) + actions = ("activate", "deactivate") + + @admin.action(description="Активировать промокоды") + def activate(self, request, queryset): + updated = queryset.update(is_active=True) + self.message_user(request, f"Активировано: {updated}") + + @admin.action(description="Деактивировать промокоды") + def deactivate(self, request, queryset): + updated = queryset.update(is_active=False) + self.message_user(request, f"Деактивировано: {updated}") + + +@admin.register(GiftCertificate) +class GiftCertificateAdmin(admin.ModelAdmin): + list_display = ("code", "nominal", "balance", "status", "issued_to", "expires_at") + list_filter = ("status",) + search_fields = ("code", "issued_to__phone") + actions = ("activate", "expire") + + @admin.action(description="Активировать сертификаты") + def activate(self, request, queryset): + updated = queryset.update(status=GiftCertificate.Status.ACTIVE) + self.message_user(request, f"Активировано: {updated}") + + @admin.action(description="Пометить истёкшими") + def expire(self, request, queryset): + updated = queryset.update(status=GiftCertificate.Status.EXPIRED) + self.message_user(request, f"Помечено: {updated}") diff --git a/backend/apps/loyalty/apps.py b/backend/apps/loyalty/apps.py new file mode 100644 index 0000000..33a4c41 --- /dev/null +++ b/backend/apps/loyalty/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig + + +class LoyaltyConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "apps.loyalty" + verbose_name = "Лояльность" diff --git a/backend/apps/loyalty/migrations/0001_initial.py b/backend/apps/loyalty/migrations/0001_initial.py new file mode 100644 index 0000000..24b2d37 --- /dev/null +++ b/backend/apps/loyalty/migrations/0001_initial.py @@ -0,0 +1,96 @@ +# Generated by Django 4.2.16 on 2026-11-06 13:26 + +from decimal import Decimal +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('orders', '0001_initial'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='BonusAccount', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('balance', models.DecimalField(decimal_places=2, default=Decimal('0'), max_digits=12)), + ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='bonus_account', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'verbose_name': 'бонусный счёт', + 'verbose_name_plural': 'бонусные счета', + 'db_table': 'loyalty_bonus_account', + }, + ), + migrations.CreateModel( + name='PromoCode', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('code', models.CharField(max_length=64, unique=True)), + ('discount_type', models.CharField(choices=[('percent', 'Процент'), ('fixed', 'Фиксированная сумма')], max_length=10)), + ('value', models.DecimalField(decimal_places=2, max_digits=12)), + ('min_order_total', models.DecimalField(decimal_places=2, default=Decimal('0'), max_digits=12)), + ('valid_from', models.DateTimeField(blank=True, null=True)), + ('valid_to', models.DateTimeField(blank=True, null=True)), + ('max_uses', models.PositiveIntegerField(blank=True, null=True)), + ('used_count', models.PositiveIntegerField(default=0)), + ('is_active', models.BooleanField(default=True)), + ], + options={ + 'verbose_name': 'промокод', + 'verbose_name_plural': 'промокоды', + 'db_table': 'loyalty_promo_code', + 'ordering': ['-created_at'], + }, + ), + migrations.CreateModel( + name='GiftCertificate', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('code', models.CharField(max_length=64, unique=True)), + ('nominal', models.DecimalField(decimal_places=2, max_digits=12)), + ('balance', models.DecimalField(decimal_places=2, max_digits=12)), + ('status', models.CharField(choices=[('issued', 'Выпущен'), ('active', 'Активен'), ('used', 'Использован'), ('expired', 'Истёк')], default='issued', max_length=20)), + ('expires_at', models.DateTimeField(blank=True, null=True)), + ('issued_to', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='certificates', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'verbose_name': 'подарочный сертификат', + 'verbose_name_plural': 'подарочные сертификаты', + 'db_table': 'loyalty_gift_certificate', + 'ordering': ['-created_at'], + }, + ), + migrations.CreateModel( + name='BonusTransaction', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('amount', models.DecimalField(decimal_places=2, max_digits=12)), + ('reason', models.CharField(choices=[('accrual', 'Начисление'), ('spend', 'Списание'), ('refund', 'Возврат'), ('adjustment', 'Корректировка')], max_length=20)), + ('comment', models.CharField(blank=True, max_length=255)), + ('account', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transactions', to='loyalty.bonusaccount')), + ('order', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='bonus_transactions', to='orders.order')), + ], + options={ + 'verbose_name': 'бонусная операция', + 'verbose_name_plural': 'бонусные операции', + 'db_table': 'loyalty_bonus_transaction', + 'ordering': ['-created_at'], + }, + ), + ] diff --git a/backend/apps/loyalty/migrations/__init__.py b/backend/apps/loyalty/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/loyalty/models.py b/backend/apps/loyalty/models.py new file mode 100644 index 0000000..814999f --- /dev/null +++ b/backend/apps/loyalty/models.py @@ -0,0 +1,144 @@ +from decimal import Decimal + +from django.conf import settings +from django.db import models +from django.utils import timezone + +from apps.common.models import TimeStampedModel + + +class BonusAccount(TimeStampedModel): + user = models.OneToOneField( + settings.AUTH_USER_MODEL, + on_delete=models.CASCADE, + related_name="bonus_account", + ) + balance = models.DecimalField( + max_digits=12, decimal_places=2, default=Decimal("0") + ) + + class Meta: + db_table = "loyalty_bonus_account" + verbose_name = "бонусный счёт" + verbose_name_plural = "бонусные счета" + + def __str__(self) -> str: + return f"{self.user.phone}: {self.balance}" + + +class BonusTransaction(TimeStampedModel): + class Reason(models.TextChoices): + ACCRUAL = "accrual", "Начисление" + SPEND = "spend", "Списание" + REFUND = "refund", "Возврат" + ADJUSTMENT = "adjustment", "Корректировка" + + account = models.ForeignKey( + BonusAccount, on_delete=models.CASCADE, related_name="transactions" + ) + order = models.ForeignKey( + "orders.Order", + null=True, + blank=True, + on_delete=models.SET_NULL, + related_name="bonus_transactions", + ) + amount = models.DecimalField(max_digits=12, decimal_places=2) + reason = models.CharField(max_length=20, choices=Reason.choices) + comment = models.CharField(max_length=255, blank=True) + + class Meta: + db_table = "loyalty_bonus_transaction" + verbose_name = "бонусная операция" + verbose_name_plural = "бонусные операции" + ordering = ["-created_at"] + + def __str__(self) -> str: + return f"{self.account.user.phone}: {self.amount}" + + +class PromoCode(TimeStampedModel): + class DiscountType(models.TextChoices): + PERCENT = "percent", "Процент" + FIXED = "fixed", "Фиксированная сумма" + + code = models.CharField(max_length=64, unique=True) + discount_type = models.CharField(max_length=10, choices=DiscountType.choices) + value = models.DecimalField(max_digits=12, decimal_places=2) + min_order_total = models.DecimalField( + max_digits=12, decimal_places=2, default=Decimal("0") + ) + valid_from = models.DateTimeField(null=True, blank=True) + valid_to = models.DateTimeField(null=True, blank=True) + max_uses = models.PositiveIntegerField(null=True, blank=True) + used_count = models.PositiveIntegerField(default=0) + is_active = models.BooleanField(default=True) + + class Meta: + db_table = "loyalty_promo_code" + verbose_name = "промокод" + verbose_name_plural = "промокоды" + ordering = ["-created_at"] + + def __str__(self) -> str: + return self.code + + def is_valid(self, subtotal: Decimal) -> bool: + now = timezone.now() + if not self.is_active: + return False + if self.valid_from and now < self.valid_from: + return False + if self.valid_to and now > self.valid_to: + return False + if self.max_uses is not None and self.used_count >= self.max_uses: + return False + if subtotal < self.min_order_total: + return False + return True + + def discount_for(self, subtotal: Decimal) -> Decimal: + if self.discount_type == self.DiscountType.PERCENT: + return (subtotal * self.value / Decimal("100")).quantize( + Decimal("0.01") + ) + return min(self.value, subtotal) + + +class GiftCertificate(TimeStampedModel): + class Status(models.TextChoices): + ISSUED = "issued", "Выпущен" + ACTIVE = "active", "Активен" + USED = "used", "Использован" + EXPIRED = "expired", "Истёк" + + code = models.CharField(max_length=64, unique=True) + nominal = models.DecimalField(max_digits=12, decimal_places=2) + balance = models.DecimalField(max_digits=12, decimal_places=2) + status = models.CharField( + max_length=20, choices=Status.choices, default=Status.ISSUED + ) + issued_to = models.ForeignKey( + settings.AUTH_USER_MODEL, + null=True, + blank=True, + on_delete=models.SET_NULL, + related_name="certificates", + ) + expires_at = models.DateTimeField(null=True, blank=True) + + class Meta: + db_table = "loyalty_gift_certificate" + verbose_name = "подарочный сертификат" + verbose_name_plural = "подарочные сертификаты" + ordering = ["-created_at"] + + def __str__(self) -> str: + return f"{self.code}: {self.balance}" + + def is_valid(self) -> bool: + if self.status not in (self.Status.ISSUED, self.Status.ACTIVE): + return False + if self.expires_at and timezone.now() > self.expires_at: + return False + return self.balance > 0 diff --git a/backend/apps/loyalty/serializers.py b/backend/apps/loyalty/serializers.py new file mode 100644 index 0000000..2d3f454 --- /dev/null +++ b/backend/apps/loyalty/serializers.py @@ -0,0 +1,43 @@ +from rest_framework import serializers + +from .models import BonusTransaction, GiftCertificate + + +class BonusTransactionSerializer(serializers.ModelSerializer): + reason_display = serializers.CharField(source="get_reason_display", read_only=True) + + class Meta: + model = BonusTransaction + fields = ["id", "amount", "reason", "reason_display", "comment", "created_at"] + + +class BonusAccountSerializer(serializers.Serializer): + balance = serializers.DecimalField(max_digits=12, decimal_places=2) + transactions = BonusTransactionSerializer(many=True) + + +class PromoValidateSerializer(serializers.Serializer): + code = serializers.CharField(max_length=64) + subtotal = serializers.DecimalField(max_digits=12, decimal_places=2) + + +class CertificateValidateSerializer(serializers.Serializer): + code = serializers.CharField(max_length=64) + amount = serializers.DecimalField(max_digits=12, decimal_places=2) + + +class GiftCertificateSerializer(serializers.ModelSerializer): + status_display = serializers.CharField(source="get_status_display", read_only=True) + + class Meta: + model = GiftCertificate + fields = [ + "id", + "code", + "nominal", + "balance", + "status", + "status_display", + "expires_at", + "created_at", + ] diff --git a/backend/apps/loyalty/services.py b/backend/apps/loyalty/services.py new file mode 100644 index 0000000..cd5a893 --- /dev/null +++ b/backend/apps/loyalty/services.py @@ -0,0 +1,106 @@ +from decimal import Decimal + +from django.db import transaction +from django.db.models import F +from rest_framework.exceptions import ValidationError + +from .models import BonusAccount, BonusTransaction, GiftCertificate, PromoCode + + +def get_or_create_bonus_account(user) -> BonusAccount: + account, _ = BonusAccount.objects.get_or_create(user=user) + return account + + +@transaction.atomic +def accrue_bonus(user, amount: Decimal, *, order=None, comment: str = "") -> BonusAccount: + if amount <= 0: + raise ValidationError({"amount": "Сумма начисления должна быть положительной"}) + + account, _ = BonusAccount.objects.select_for_update().get_or_create(user=user) + account.balance += amount + account.save(update_fields=["balance", "updated_at"]) + BonusTransaction.objects.create( + account=account, + order=order, + amount=amount, + reason=BonusTransaction.Reason.ACCRUAL, + comment=comment, + ) + return account + + +@transaction.atomic +def spend_bonus(user, amount: Decimal, *, order=None) -> BonusAccount: + if amount <= 0: + raise ValidationError({"bonus_amount": "Сумма списания должна быть положительной"}) + + account, _ = BonusAccount.objects.select_for_update().get_or_create(user=user) + if account.balance < amount: + raise ValidationError({"bonus_amount": "Недостаточно бонусов на счёте"}) + + account.balance -= amount + account.save(update_fields=["balance", "updated_at"]) + BonusTransaction.objects.create( + account=account, + order=order, + amount=-amount, + reason=BonusTransaction.Reason.SPEND, + comment="Оплата заказа бонусами", + ) + return account + + +def validate_promo(code: str, subtotal: Decimal) -> tuple[PromoCode, Decimal]: + promo = PromoCode.objects.filter(code__iexact=code.strip()).first() + if promo is None or not promo.is_valid(subtotal): + raise ValidationError({"promo_code": "Промокод недействителен"}) + return promo, promo.discount_for(subtotal) + + +def redeem_promo(promo: PromoCode) -> None: + PromoCode.objects.filter(pk=promo.pk).update(used_count=F("used_count") + 1) + + +def validate_certificate(code: str, amount: Decimal) -> tuple[GiftCertificate, Decimal]: + """Read-only check: returns the certificate and the amount it can cover.""" + certificate = GiftCertificate.objects.filter(code__iexact=code.strip()).first() + if certificate is None: + raise ValidationError({"certificate_code": "Сертификат не найден"}) + if not certificate.is_valid(): + raise ValidationError({"certificate_code": "Сертификат недействителен"}) + + applied = min(certificate.balance, amount) + if applied <= 0: + raise ValidationError( + {"certificate_code": "Сертификат нельзя применить к этому заказу"} + ) + return certificate, applied + + +@transaction.atomic +def apply_certificate(code: str, amount: Decimal) -> tuple[GiftCertificate, Decimal]: + certificate = ( + GiftCertificate.objects.select_for_update() + .filter(code__iexact=code.strip()) + .first() + ) + if certificate is None: + raise ValidationError({"certificate_code": "Сертификат не найден"}) + if not certificate.is_valid(): + raise ValidationError({"certificate_code": "Сертификат недействителен"}) + + applied = min(certificate.balance, amount) + if applied <= 0: + raise ValidationError( + {"certificate_code": "Сертификат нельзя применить к этому заказу"} + ) + + certificate.balance -= applied + certificate.status = ( + GiftCertificate.Status.USED + if certificate.balance == 0 + else GiftCertificate.Status.ACTIVE + ) + certificate.save(update_fields=["balance", "status", "updated_at"]) + return certificate, applied diff --git a/backend/apps/loyalty/tests.py b/backend/apps/loyalty/tests.py new file mode 100644 index 0000000..5377105 --- /dev/null +++ b/backend/apps/loyalty/tests.py @@ -0,0 +1,44 @@ +from decimal import Decimal + +from django.test import TestCase +from rest_framework.test import APIClient + +from .models import GiftCertificate, PromoCode + + +class LoyaltyApiTests(TestCase): + def setUp(self): + self.client = APIClient() + + def test_promo_validate(self): + PromoCode.objects.create( + code="SALE10", + discount_type=PromoCode.DiscountType.PERCENT, + value=Decimal("10"), + ) + response = self.client.post( + "/api/v1/loyalty/promo/validate/", + {"code": "SALE10", "subtotal": "1000.00"}, + format="json", + ) + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(Decimal(response.data["discount"]), Decimal("100.00")) + + def test_certificate_validate_does_not_spend_balance(self): + certificate = GiftCertificate.objects.create( + code="CERT-1", + nominal=Decimal("1000.00"), + balance=Decimal("1000.00"), + status=GiftCertificate.Status.ACTIVE, + ) + response = self.client.post( + "/api/v1/loyalty/certificate/validate/", + {"code": "CERT-1", "amount": "500.00"}, + format="json", + ) + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(Decimal(response.data["applied"]), Decimal("500.00")) + self.assertEqual(Decimal(response.data["remaining"]), Decimal("500.00")) + + certificate.refresh_from_db() + self.assertEqual(certificate.balance, Decimal("1000.00")) diff --git a/backend/apps/loyalty/urls.py b/backend/apps/loyalty/urls.py new file mode 100644 index 0000000..79cefd8 --- /dev/null +++ b/backend/apps/loyalty/urls.py @@ -0,0 +1,19 @@ +from django.urls import path + +from .views import ( + BonusView, + CertificateListView, + CertificateValidateView, + PromoValidateView, +) + +urlpatterns = [ + path("bonus/", BonusView.as_view(), name="bonus"), + path("promo/validate/", PromoValidateView.as_view(), name="promo-validate"), + path( + "certificate/validate/", + CertificateValidateView.as_view(), + name="certificate-validate", + ), + path("certificates/", CertificateListView.as_view(), name="certificate-list"), +] diff --git a/backend/apps/loyalty/views.py b/backend/apps/loyalty/views.py new file mode 100644 index 0000000..b4688a5 --- /dev/null +++ b/backend/apps/loyalty/views.py @@ -0,0 +1,78 @@ +from rest_framework.permissions import AllowAny, IsAuthenticated +from rest_framework.response import Response +from rest_framework.views import APIView + +from .models import GiftCertificate +from .serializers import ( + BonusAccountSerializer, + CertificateValidateSerializer, + GiftCertificateSerializer, + PromoValidateSerializer, +) +from .services import ( + get_or_create_bonus_account, + validate_certificate, + validate_promo, +) + + +class BonusView(APIView): + permission_classes = [IsAuthenticated] + serializer_class = BonusAccountSerializer + + def get(self, request): + account = get_or_create_bonus_account(request.user) + transactions = account.transactions.all()[:50] + serializer = BonusAccountSerializer( + {"balance": account.balance, "transactions": transactions} + ) + return Response(serializer.data) + + +class PromoValidateView(APIView): + permission_classes = [AllowAny] + serializer_class = PromoValidateSerializer + + def post(self, request): + serializer = PromoValidateSerializer(data=request.data) + serializer.is_valid(raise_exception=True) + promo, discount = validate_promo( + serializer.validated_data["code"], + serializer.validated_data["subtotal"], + ) + return Response( + { + "code": promo.code, + "discount": discount, + "discount_type": promo.discount_type, + } + ) + + +class CertificateValidateView(APIView): + permission_classes = [AllowAny] + serializer_class = CertificateValidateSerializer + + def post(self, request): + serializer = CertificateValidateSerializer(data=request.data) + serializer.is_valid(raise_exception=True) + certificate, applied = validate_certificate( + serializer.validated_data["code"], + serializer.validated_data["amount"], + ) + return Response( + { + "code": certificate.code, + "applied": applied, + "remaining": certificate.balance - applied, + } + ) + + +class CertificateListView(APIView): + permission_classes = [IsAuthenticated] + serializer_class = GiftCertificateSerializer + + def get(self, request): + certificates = GiftCertificate.objects.filter(issued_to=request.user) + return Response(GiftCertificateSerializer(certificates, many=True).data) diff --git a/backend/apps/orders/__init__.py b/backend/apps/orders/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/orders/admin.py b/backend/apps/orders/admin.py new file mode 100644 index 0000000..e2a416b --- /dev/null +++ b/backend/apps/orders/admin.py @@ -0,0 +1,136 @@ +from django.contrib import admin +from django.utils.html import format_html + +from apps.payments.models import Payment + +from .models import Order, OrderItem, OrderStatusHistory +from .services import change_status + + +class OrderItemInline(admin.TabularInline): + model = OrderItem + extra = 0 + readonly_fields = ("total",) + + +class OrderStatusHistoryInline(admin.TabularInline): + model = OrderStatusHistory + extra = 0 + readonly_fields = ("created_at",) + + +class PaymentInline(admin.TabularInline): + model = Payment + extra = 0 + readonly_fields = ("created_at", "paid_at") + + +@admin.register(Order) +class OrderAdmin(admin.ModelAdmin): + list_display = ( + "number", + "customer_name", + "phone", + "status_badge", + "payment_status", + "total", + "created_at", + ) + list_filter = ("status", "payment_status", "created_at") + search_fields = ("number", "phone", "email", "customer_name", "external_id") + readonly_fields = ( + "number", + "external_id", + "synced_at", + "sync_error", + "created_at", + "updated_at", + ) + date_hierarchy = "created_at" + inlines = [OrderItemInline, OrderStatusHistoryInline, PaymentInline] + actions = ("mark_processing", "mark_delivering", "mark_completed", "mark_cancelled") + fieldsets = ( + ( + "Заказ", + {"fields": ("number", "external_id", "user", "status", "payment_status")}, + ), + ("Клиент", {"fields": ("customer_name", "phone", "email")}), + ( + "Доставка", + {"fields": ("delivery_method", "delivery_address", "delivery_cost")}, + ), + ( + "Суммы", + { + "fields": ( + "subtotal", + "discount_total", + "bonus_applied", + "certificate_applied", + "total", + "promo_code", + "certificate_code", + ) + }, + ), + ( + "Служебное", + {"fields": ("comment", "synced_at", "sync_error", "created_at", "updated_at")}, + ), + ) + + @admin.display(description="Статус", ordering="status") + def status_badge(self, obj): + colors = { + Order.Status.NEW: "#6b7280", + Order.Status.PROCESSING: "#d97706", + Order.Status.DELIVERING: "#2563eb", + Order.Status.COMPLETED: "#16a34a", + Order.Status.CANCELLED: "#dc2626", + } + return format_html( + '{}', + colors.get(obj.status, "#6b7280"), + obj.get_status_display(), + ) + + def _change(self, request, queryset, status, label): + count = 0 + for order in queryset: + change_status( + order, + status, + source=OrderStatusHistory.Source.ADMIN, + comment=f"Администратор: {label}", + ) + count += 1 + self.message_user(request, f"Обновлено заказов: {count}") + + @admin.action(description="Перевести в «В обработке»") + def mark_processing(self, request, queryset): + self._change(request, queryset, Order.Status.PROCESSING, "в обработку") + + @admin.action(description="Перевести в «Доставляется»") + def mark_delivering(self, request, queryset): + self._change(request, queryset, Order.Status.DELIVERING, "в доставку") + + @admin.action(description="Перевести в «Выполнен»") + def mark_completed(self, request, queryset): + self._change(request, queryset, Order.Status.COMPLETED, "выполнен") + + @admin.action(description="Отменить выбранные") + def mark_cancelled(self, request, queryset): + self._change(request, queryset, Order.Status.CANCELLED, "отменён") + + +@admin.register(OrderItem) +class OrderItemAdmin(admin.ModelAdmin): + list_display = ("order", "name", "sku", "price", "quantity", "total") + search_fields = ("order__number", "name", "sku") + + +@admin.register(OrderStatusHistory) +class OrderStatusHistoryAdmin(admin.ModelAdmin): + list_display = ("order", "status", "source", "created_at") + list_filter = ("status", "source") diff --git a/backend/apps/orders/apps.py b/backend/apps/orders/apps.py new file mode 100644 index 0000000..86f237e --- /dev/null +++ b/backend/apps/orders/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig + + +class OrdersConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "apps.orders" + verbose_name = "Заказы" diff --git a/backend/apps/orders/migrations/0001_initial.py b/backend/apps/orders/migrations/0001_initial.py new file mode 100644 index 0000000..c7b52ee --- /dev/null +++ b/backend/apps/orders/migrations/0001_initial.py @@ -0,0 +1,103 @@ +# Generated by Django 4.2.16 on 2026-11-06 13:26 + +import apps.orders.models +from decimal import Decimal +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('catalog', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Order', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('number', models.CharField(default=apps.orders.models.generate_order_number, editable=False, max_length=32, unique=True)), + ('external_id', models.CharField(blank=True, db_index=True, max_length=64)), + ('status', models.CharField(choices=[('new', 'Новый'), ('processing', 'В обработке'), ('delivering', 'Доставляется'), ('completed', 'Выполнен'), ('cancelled', 'Отменён')], db_index=True, default='new', max_length=20)), + ('payment_status', models.CharField(choices=[('pending', 'Ожидает оплаты'), ('partially_paid', 'Частично оплачен'), ('paid', 'Оплачен'), ('refunded', 'Возвращён')], default='pending', max_length=20)), + ('customer_name', models.CharField(max_length=255)), + ('phone', models.CharField(max_length=20)), + ('email', models.EmailField(blank=True, max_length=254)), + ('delivery_method', models.CharField(blank=True, max_length=64)), + ('delivery_address', models.TextField(blank=True)), + ('delivery_cost', models.DecimalField(decimal_places=2, default=Decimal('0'), max_digits=12)), + ('comment', models.TextField(blank=True)), + ('subtotal', models.DecimalField(decimal_places=2, default=Decimal('0'), max_digits=12)), + ('discount_total', models.DecimalField(decimal_places=2, default=Decimal('0'), max_digits=12)), + ('bonus_applied', models.DecimalField(decimal_places=2, default=Decimal('0'), max_digits=12)), + ('certificate_applied', models.DecimalField(decimal_places=2, default=Decimal('0'), max_digits=12)), + ('total', models.DecimalField(decimal_places=2, default=Decimal('0'), max_digits=12)), + ('promo_code', models.CharField(blank=True, max_length=64)), + ('certificate_code', models.CharField(blank=True, max_length=64)), + ('idempotency_key', models.CharField(blank=True, max_length=128, null=True, unique=True)), + ('synced_at', models.DateTimeField(blank=True, null=True)), + ('sync_error', models.TextField(blank=True)), + ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='orders', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'verbose_name': 'заказ', + 'verbose_name_plural': 'заказы', + 'db_table': 'orders_order', + 'ordering': ['-created_at'], + }, + ), + migrations.CreateModel( + name='OrderStatusHistory', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('status', models.CharField(choices=[('new', 'Новый'), ('processing', 'В обработке'), ('delivering', 'Доставляется'), ('completed', 'Выполнен'), ('cancelled', 'Отменён')], max_length=20)), + ('comment', models.TextField(blank=True)), + ('source', models.CharField(choices=[('site', 'Сайт'), ('1c', '1С')], default='site', max_length=10)), + ('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='status_history', to='orders.order')), + ], + options={ + 'verbose_name': 'история статуса', + 'verbose_name_plural': 'история статусов', + 'db_table': 'orders_status_history', + 'ordering': ['created_at'], + }, + ), + migrations.CreateModel( + name='OrderItem', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('product_external_id', models.CharField(blank=True, max_length=64)), + ('name', models.CharField(max_length=500)), + ('sku', models.CharField(max_length=64)), + ('price', models.DecimalField(decimal_places=2, max_digits=12)), + ('quantity', models.PositiveIntegerField()), + ('total', models.DecimalField(decimal_places=2, max_digits=12)), + ('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='items', to='orders.order')), + ('product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='order_items', to='catalog.product')), + ], + options={ + 'verbose_name': 'позиция заказа', + 'verbose_name_plural': 'позиции заказа', + 'db_table': 'orders_order_item', + }, + ), + migrations.AddIndex( + model_name='order', + index=models.Index(fields=['status', 'created_at'], name='orders_orde_status_25e057_idx'), + ), + migrations.AddIndex( + model_name='order', + index=models.Index(fields=['user', 'created_at'], name='orders_orde_user_id_37fed6_idx'), + ), + ] diff --git a/backend/apps/orders/migrations/0002_alter_orderstatushistory_source.py b/backend/apps/orders/migrations/0002_alter_orderstatushistory_source.py new file mode 100644 index 0000000..39d7fc7 --- /dev/null +++ b/backend/apps/orders/migrations/0002_alter_orderstatushistory_source.py @@ -0,0 +1,18 @@ +# Generated by Django 4.2.16 on 2026-11-06 13:38 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('orders', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='orderstatushistory', + name='source', + field=models.CharField(choices=[('site', 'Сайт'), ('1c', '1С'), ('admin', 'Админка')], default='site', max_length=10), + ), + ] diff --git a/backend/apps/orders/migrations/__init__.py b/backend/apps/orders/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/orders/models.py b/backend/apps/orders/models.py new file mode 100644 index 0000000..d14844e --- /dev/null +++ b/backend/apps/orders/models.py @@ -0,0 +1,162 @@ +import secrets +from decimal import Decimal + +from django.conf import settings +from django.db import models +from django.utils import timezone + +from apps.common.models import TimeStampedModel + + +def generate_order_number() -> str: + return f"HOMM-{timezone.now():%Y%m%d}-{secrets.token_hex(3).upper()}" + + +class Order(TimeStampedModel): + class Status(models.TextChoices): + NEW = "new", "Новый" + PROCESSING = "processing", "В обработке" + DELIVERING = "delivering", "Доставляется" + COMPLETED = "completed", "Выполнен" + CANCELLED = "cancelled", "Отменён" + + class PaymentStatus(models.TextChoices): + PENDING = "pending", "Ожидает оплаты" + PARTIALLY_PAID = "partially_paid", "Частично оплачен" + PAID = "paid", "Оплачен" + REFUNDED = "refunded", "Возвращён" + + number = models.CharField( + max_length=32, unique=True, default=generate_order_number, editable=False + ) + external_id = models.CharField(max_length=64, blank=True, db_index=True) + user = models.ForeignKey( + settings.AUTH_USER_MODEL, + null=True, + blank=True, + on_delete=models.SET_NULL, + related_name="orders", + ) + status = models.CharField( + max_length=20, choices=Status.choices, default=Status.NEW, db_index=True + ) + payment_status = models.CharField( + max_length=20, + choices=PaymentStatus.choices, + default=PaymentStatus.PENDING, + ) + + customer_name = models.CharField(max_length=255) + phone = models.CharField(max_length=20) + email = models.EmailField(blank=True) + + delivery_method = models.CharField(max_length=64, blank=True) + delivery_address = models.TextField(blank=True) + delivery_cost = models.DecimalField( + max_digits=12, decimal_places=2, default=Decimal("0") + ) + + comment = models.TextField(blank=True) + + subtotal = models.DecimalField( + max_digits=12, decimal_places=2, default=Decimal("0") + ) + discount_total = models.DecimalField( + max_digits=12, decimal_places=2, default=Decimal("0") + ) + bonus_applied = models.DecimalField( + max_digits=12, decimal_places=2, default=Decimal("0") + ) + certificate_applied = models.DecimalField( + max_digits=12, decimal_places=2, default=Decimal("0") + ) + total = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0")) + + promo_code = models.CharField(max_length=64, blank=True) + certificate_code = models.CharField(max_length=64, blank=True) + + idempotency_key = models.CharField( + max_length=128, unique=True, null=True, blank=True + ) + synced_at = models.DateTimeField(null=True, blank=True) + sync_error = models.TextField(blank=True) + + class Meta: + db_table = "orders_order" + verbose_name = "заказ" + verbose_name_plural = "заказы" + ordering = ["-created_at"] + indexes = [ + models.Index(fields=["status", "created_at"]), + models.Index(fields=["user", "created_at"]), + ] + + def __str__(self) -> str: + return self.number + + def recalculate_totals(self) -> None: + self.subtotal = sum( + (item.total for item in self.items.all()), Decimal("0") + ) + self.total = max( + Decimal("0"), + self.subtotal + - self.discount_total + - self.bonus_applied + - self.certificate_applied + + self.delivery_cost, + ) + + +class OrderItem(TimeStampedModel): + order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="items") + product = models.ForeignKey( + "catalog.Product", + null=True, + blank=True, + on_delete=models.SET_NULL, + related_name="order_items", + ) + product_external_id = models.CharField(max_length=64, blank=True) + name = models.CharField(max_length=500) + sku = models.CharField(max_length=64) + price = models.DecimalField(max_digits=12, decimal_places=2) + quantity = models.PositiveIntegerField() + total = models.DecimalField(max_digits=12, decimal_places=2) + + class Meta: + db_table = "orders_order_item" + verbose_name = "позиция заказа" + verbose_name_plural = "позиции заказа" + + def __str__(self) -> str: + return f"{self.sku} x {self.quantity}" + + def save(self, *args, **kwargs): + self.total = self.price * self.quantity + super().save(*args, **kwargs) + + +class OrderStatusHistory(TimeStampedModel): + class Source(models.TextChoices): + SITE = "site", "Сайт" + ONEC = "1c", "1С" + ADMIN = "admin", "Админка" + + order = models.ForeignKey( + Order, on_delete=models.CASCADE, related_name="status_history" + ) + status = models.CharField(max_length=20, choices=Order.Status.choices) + comment = models.TextField(blank=True) + source = models.CharField( + max_length=10, choices=Source.choices, default=Source.SITE + ) + + class Meta: + db_table = "orders_status_history" + verbose_name = "история статуса" + verbose_name_plural = "история статусов" + ordering = ["created_at"] + + def __str__(self) -> str: + return f"{self.order.number}: {self.status}" diff --git a/backend/apps/orders/serializers.py b/backend/apps/orders/serializers.py new file mode 100644 index 0000000..21879be --- /dev/null +++ b/backend/apps/orders/serializers.py @@ -0,0 +1,98 @@ +from rest_framework import serializers + +from apps.payments.serializers import PaymentSerializer + +from .models import Order, OrderItem, OrderStatusHistory + +PAYMENT_METHOD_CHOICES = [ + "card", + "sbp", + "mir_pay", + "cash", + "installment", + "split", +] + + +class OrderItemInputSerializer(serializers.Serializer): + product_id = serializers.IntegerField() + quantity = serializers.IntegerField(min_value=1, max_value=999) + + +class OrderCreateSerializer(serializers.Serializer): + items = OrderItemInputSerializer(many=True, allow_empty=False) + customer_name = serializers.CharField(max_length=255) + phone = serializers.CharField(max_length=20) + email = serializers.EmailField(required=False, allow_blank=True) + delivery_method = serializers.CharField( + max_length=64, required=False, allow_blank=True + ) + delivery_address = serializers.CharField(required=False, allow_blank=True) + delivery_cost = serializers.DecimalField( + max_digits=12, decimal_places=2, required=False, default=0 + ) + comment = serializers.CharField(required=False, allow_blank=True) + promo_code = serializers.CharField(required=False, allow_blank=True) + certificate_code = serializers.CharField(required=False, allow_blank=True) + bonus_amount = serializers.DecimalField( + max_digits=12, decimal_places=2, required=False, default=0 + ) + payment_method = serializers.ChoiceField( + choices=PAYMENT_METHOD_CHOICES, required=False + ) + + +class OrderItemSerializer(serializers.ModelSerializer): + class Meta: + model = OrderItem + fields = ["id", "name", "sku", "price", "quantity", "total"] + + +class OrderStatusHistorySerializer(serializers.ModelSerializer): + status_display = serializers.CharField(source="get_status_display", read_only=True) + + class Meta: + model = OrderStatusHistory + fields = ["status", "status_display", "comment", "source", "created_at"] + + +class OrderListSerializer(serializers.ModelSerializer): + items = OrderItemSerializer(many=True, read_only=True) + status_display = serializers.CharField(source="get_status_display", read_only=True) + + class Meta: + model = Order + fields = [ + "id", + "number", + "status", + "status_display", + "payment_status", + "total", + "created_at", + "items", + ] + + +class OrderDetailSerializer(OrderListSerializer): + status_history = OrderStatusHistorySerializer(many=True, read_only=True) + payments = PaymentSerializer(many=True, read_only=True) + + class Meta(OrderListSerializer.Meta): + fields = OrderListSerializer.Meta.fields + [ + "customer_name", + "phone", + "email", + "delivery_method", + "delivery_address", + "delivery_cost", + "comment", + "subtotal", + "discount_total", + "bonus_applied", + "certificate_applied", + "promo_code", + "certificate_code", + "status_history", + "payments", + ] diff --git a/backend/apps/orders/services.py b/backend/apps/orders/services.py new file mode 100644 index 0000000..c1cc5f3 --- /dev/null +++ b/backend/apps/orders/services.py @@ -0,0 +1,147 @@ +from decimal import Decimal + +from django.db import transaction +from rest_framework.exceptions import ValidationError + +from apps.catalog.models import Product +from apps.integration.outbox import enqueue +from apps.loyalty.services import ( + apply_certificate, + redeem_promo, + spend_bonus, + validate_promo, +) + +from .models import Order, OrderItem, OrderStatusHistory + + +@transaction.atomic +def create_order(*, user, data, idempotency_key: str | None = None): + """Creates an order, reserves stock and enqueues a 1C push. + + Returns ``(order, created)``. When the same idempotency key is sent twice, + the existing order is returned with ``created=False``. + """ + if idempotency_key: + existing = Order.objects.filter(idempotency_key=idempotency_key).first() + if existing is not None: + return existing, False + + items_data = data["items"] + product_ids = [item["product_id"] for item in items_data] + products = { + str(product.id): product + for product in Product.objects.select_for_update().filter( + id__in=product_ids, is_active=True + ) + } + if len(products) != len(set(str(pid) for pid in product_ids)): + raise ValidationError({"items": "Некоторые товары недоступны"}) + + order = Order.objects.create( + user=user, + customer_name=data["customer_name"], + phone=data["phone"], + email=data.get("email", ""), + delivery_method=data.get("delivery_method", ""), + delivery_address=data.get("delivery_address", ""), + delivery_cost=Decimal(str(data.get("delivery_cost", "0") or "0")), + comment=data.get("comment", ""), + idempotency_key=idempotency_key, + ) + + subtotal = Decimal("0") + for item in items_data: + product = products[str(item["product_id"])] + quantity = item["quantity"] + if product.stock < quantity: + raise ValidationError( + {"items": f"Недостаточно товара «{product.name}» на складе"} + ) + + product.stock -= quantity + product.recalculate_stock_status() + product.save(update_fields=["stock", "stock_status", "updated_at"]) + + line_total = product.price * quantity + subtotal += line_total + OrderItem.objects.create( + order=order, + product=product, + product_external_id=product.external_id, + name=product.name, + sku=product.sku, + price=product.price, + quantity=quantity, + total=line_total, + ) + + order.subtotal = subtotal + + discount = Decimal("0") + promo_code = (data.get("promo_code") or "").strip() + if promo_code: + promo, discount = validate_promo(promo_code, subtotal) + order.promo_code = promo.code + redeem_promo(promo) + order.discount_total = discount + + bonus_amount = Decimal(str(data.get("bonus_amount", "0") or "0")) + if bonus_amount > 0: + if user is None: + raise ValidationError( + {"bonus_amount": "Оплата бонусами доступна только авторизованным"} + ) + spend_bonus(user, bonus_amount, order=order) + order.bonus_applied = bonus_amount + + certificate_amount = Decimal("0") + certificate_code = (data.get("certificate_code") or "").strip() + if certificate_code: + certificate, certificate_amount = apply_certificate( + certificate_code, subtotal - discount - bonus_amount + ) + order.certificate_code = certificate.code + order.certificate_applied = certificate_amount + + order.total = max( + Decimal("0"), + subtotal + - discount + - bonus_amount + - certificate_amount + + order.delivery_cost, + ) + order.save() + + payment_method = data.get("payment_method") + if payment_method and order.total > 0: + from apps.payments.services import create_payment + + create_payment(order, payment_method, order.total) + + OrderStatusHistory.objects.create( + order=order, + status=order.status, + comment="Заказ создан на сайте", + source=OrderStatusHistory.Source.SITE, + ) + enqueue("order.created", {"order_id": str(order.id), "number": order.number}) + return order, True + + +@transaction.atomic +def change_status(order: Order, status: str, *, source: str = "site", comment: str = ""): + if status not in Order.Status.values: + raise ValidationError({"status": "Неизвестный статус заказа"}) + + order.status = status + order.save(update_fields=["status", "updated_at"]) + OrderStatusHistory.objects.create( + order=order, status=status, comment=comment, source=source + ) + enqueue( + "order.status_changed", + {"order_id": str(order.id), "number": order.number, "status": status}, + ) + return order diff --git a/backend/apps/orders/tests.py b/backend/apps/orders/tests.py new file mode 100644 index 0000000..59911e9 --- /dev/null +++ b/backend/apps/orders/tests.py @@ -0,0 +1,76 @@ +from decimal import Decimal + +from django.test import TestCase +from rest_framework.test import APIClient + +from apps.catalog.models import Category, Product + +from .models import Order + + +class OrderApiTests(TestCase): + def setUp(self): + self.client = APIClient() + category = Category.objects.create( + external_id="cat-1", name="Диваны", slug="divany" + ) + self.product = Product.objects.create( + external_id="prod-1", + sku="SKU-1", + name="Диван Осло", + slug="divan-oslo", + category=category, + price=Decimal("49990.00"), + stock=5, + stock_status=Product.StockStatus.IN_STOCK, + ) + self.payload = { + "items": [{"product_id": str(self.product.id), "quantity": 2}], + "customer_name": "Иван Петров", + "phone": "+79991234567", + "email": "ivan@example.com", + "delivery_method": "courier", + "delivery_address": "Москва, ул. Тверская, 1", + "delivery_cost": "500.00", + } + + def test_create_order_reserves_stock(self): + response = self.client.post( + "/api/v1/orders/", + self.payload, + format="json", + HTTP_IDEMPOTENCY_KEY="order-test-1", + ) + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(Decimal(response.data["total"]), Decimal("100480.00")) + + self.product.refresh_from_db() + self.assertEqual(self.product.stock, 3) + self.assertEqual(Order.objects.count(), 1) + + def test_idempotency_key_returns_same_order(self): + first = self.client.post( + "/api/v1/orders/", + self.payload, + format="json", + HTTP_IDEMPOTENCY_KEY="order-test-2", + ) + second = self.client.post( + "/api/v1/orders/", + self.payload, + format="json", + HTTP_IDEMPOTENCY_KEY="order-test-2", + ) + self.assertEqual(first.status_code, 201) + self.assertEqual(second.status_code, 200) + self.assertEqual(first.data["id"], second.data["id"]) + self.assertEqual(Order.objects.count(), 1) + + def test_cannot_order_more_than_stock(self): + payload = { + **self.payload, + "items": [{"product_id": str(self.product.id), "quantity": 99}], + } + response = self.client.post("/api/v1/orders/", payload, format="json") + self.assertEqual(response.status_code, 400) + self.assertEqual(Order.objects.count(), 0) diff --git a/backend/apps/orders/urls.py b/backend/apps/orders/urls.py new file mode 100644 index 0000000..4076190 --- /dev/null +++ b/backend/apps/orders/urls.py @@ -0,0 +1,11 @@ +from django.urls import include, path +from rest_framework.routers import DefaultRouter + +from .views import OrderViewSet + +router = DefaultRouter() +router.register("", OrderViewSet, basename="order") + +urlpatterns = [ + path("", include(router.urls)), +] diff --git a/backend/apps/orders/views.py b/backend/apps/orders/views.py new file mode 100644 index 0000000..c8e6c4c --- /dev/null +++ b/backend/apps/orders/views.py @@ -0,0 +1,66 @@ +from rest_framework import mixins, status, viewsets +from rest_framework.decorators import action +from rest_framework.exceptions import ValidationError +from rest_framework.permissions import AllowAny +from rest_framework.response import Response + +from .models import Order +from .serializers import ( + OrderCreateSerializer, + OrderDetailSerializer, + OrderListSerializer, +) +from .services import change_status, create_order + + +class OrderViewSet( + mixins.CreateModelMixin, + mixins.ListModelMixin, + mixins.RetrieveModelMixin, + viewsets.GenericViewSet, +): + permission_classes = [AllowAny] + + def get_queryset(self): + if self.request.user.is_authenticated: + return Order.objects.filter(user=self.request.user).prefetch_related( + "items", "status_history", "payments" + ) + return Order.objects.none() + + def get_serializer_class(self): + if self.action == "create": + return OrderCreateSerializer + if self.action == "retrieve": + return OrderDetailSerializer + return OrderListSerializer + + def create(self, request, *args, **kwargs): + serializer = self.get_serializer(data=request.data) + serializer.is_valid(raise_exception=True) + + idempotency_key = request.headers.get("Idempotency-Key") + order, created = create_order( + user=request.user if request.user.is_authenticated else None, + data=serializer.validated_data, + idempotency_key=idempotency_key, + ) + output = OrderDetailSerializer(order, context={"request": request}) + return Response( + output.data, + status=status.HTTP_201_CREATED if created else status.HTTP_200_OK, + ) + + @action(detail=True, methods=["post"]) + def cancel(self, request, pk=None): + order = self.get_object() + if order.status not in (Order.Status.NEW, Order.Status.PROCESSING): + raise ValidationError({"detail": "Заказ нельзя отменить в текущем статусе"}) + + change_status( + order, + Order.Status.CANCELLED, + source="site", + comment=request.data.get("comment", "Отменён клиентом"), + ) + return Response(OrderDetailSerializer(order).data) diff --git a/backend/apps/payments/__init__.py b/backend/apps/payments/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/payments/admin.py b/backend/apps/payments/admin.py new file mode 100644 index 0000000..c33afd5 --- /dev/null +++ b/backend/apps/payments/admin.py @@ -0,0 +1,19 @@ +from django.contrib import admin + +from .models import Payment + + +@admin.register(Payment) +class PaymentAdmin(admin.ModelAdmin): + list_display = ( + "order", + "method", + "status", + "amount", + "provider", + "provider_payment_id", + "created_at", + ) + list_filter = ("method", "status", "provider") + search_fields = ("order__number", "provider_payment_id") + readonly_fields = ("created_at", "updated_at") diff --git a/backend/apps/payments/apps.py b/backend/apps/payments/apps.py new file mode 100644 index 0000000..dd74a8c --- /dev/null +++ b/backend/apps/payments/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig + + +class PaymentsConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "apps.payments" + verbose_name = "Платежи" diff --git a/backend/apps/payments/migrations/0001_initial.py b/backend/apps/payments/migrations/0001_initial.py new file mode 100644 index 0000000..00a26ee --- /dev/null +++ b/backend/apps/payments/migrations/0001_initial.py @@ -0,0 +1,40 @@ +# Generated by Django 4.2.16 on 2026-11-06 13:26 + +from decimal import Decimal +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('orders', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Payment', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('method', models.CharField(choices=[('card', 'Банковская карта'), ('sbp', 'СБП'), ('mir_pay', 'МИР Pay'), ('cash', 'Наличные при получении'), ('installment', 'Рассрочка'), ('split', 'Оплата частями')], max_length=20)), + ('status', models.CharField(choices=[('pending', 'Ожидает'), ('succeeded', 'Успешно'), ('failed', 'Ошибка'), ('refunded', 'Возвращён'), ('cancelled', 'Отменён')], default='pending', max_length=20)), + ('amount', models.DecimalField(decimal_places=2, default=Decimal('0'), max_digits=12)), + ('provider', models.CharField(default='yookassa', max_length=32)), + ('provider_payment_id', models.CharField(blank=True, db_index=True, max_length=128)), + ('idempotency_key', models.CharField(blank=True, max_length=128, null=True, unique=True)), + ('payload', models.JSONField(blank=True, default=dict)), + ('paid_at', models.DateTimeField(blank=True, null=True)), + ('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='payments', to='orders.order')), + ], + options={ + 'verbose_name': 'платёж', + 'verbose_name_plural': 'платежи', + 'db_table': 'payments_payment', + 'ordering': ['-created_at'], + }, + ), + ] diff --git a/backend/apps/payments/migrations/__init__.py b/backend/apps/payments/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/apps/payments/models.py b/backend/apps/payments/models.py new file mode 100644 index 0000000..e6710fa --- /dev/null +++ b/backend/apps/payments/models.py @@ -0,0 +1,51 @@ +from decimal import Decimal + +from django.db import models + +from apps.common.models import TimeStampedModel + + +class Payment(TimeStampedModel): + class Method(models.TextChoices): + CARD = "card", "Банковская карта" + SBP = "sbp", "СБП" + MIR_PAY = "mir_pay", "МИР Pay" + CASH = "cash", "Наличные при получении" + INSTALLMENT = "installment", "Рассрочка" + SPLIT = "split", "Оплата частями" + + class Status(models.TextChoices): + PENDING = "pending", "Ожидает" + SUCCEEDED = "succeeded", "Успешно" + FAILED = "failed", "Ошибка" + REFUNDED = "refunded", "Возвращён" + CANCELLED = "cancelled", "Отменён" + + order = models.ForeignKey( + "orders.Order", on_delete=models.CASCADE, related_name="payments" + ) + method = models.CharField(max_length=20, choices=Method.choices) + status = models.CharField( + max_length=20, choices=Status.choices, default=Status.PENDING + ) + amount = models.DecimalField( + max_digits=12, decimal_places=2, default=Decimal("0") + ) + provider = models.CharField(max_length=32, default="yookassa") + provider_payment_id = models.CharField( + max_length=128, blank=True, db_index=True + ) + idempotency_key = models.CharField( + max_length=128, unique=True, null=True, blank=True + ) + payload = models.JSONField(default=dict, blank=True) + paid_at = models.DateTimeField(null=True, blank=True) + + class Meta: + db_table = "payments_payment" + verbose_name = "платёж" + verbose_name_plural = "платежи" + ordering = ["-created_at"] + + def __str__(self) -> str: + return f"{self.order.number}: {self.method} {self.amount}" diff --git a/backend/apps/payments/serializers.py b/backend/apps/payments/serializers.py new file mode 100644 index 0000000..e23384c --- /dev/null +++ b/backend/apps/payments/serializers.py @@ -0,0 +1,27 @@ +from rest_framework import serializers + +from .models import Payment + + +class PaymentSerializer(serializers.ModelSerializer): + method_display = serializers.CharField(source="get_method_display", read_only=True) + status_display = serializers.CharField(source="get_status_display", read_only=True) + + class Meta: + model = Payment + fields = [ + "id", + "method", + "method_display", + "status", + "status_display", + "amount", + "provider", + "paid_at", + "created_at", + ] + + +class PaymentWebhookSerializer(serializers.Serializer): + event = serializers.CharField() + object = serializers.DictField() diff --git a/backend/apps/payments/services.py b/backend/apps/payments/services.py new file mode 100644 index 0000000..a1a0f43 --- /dev/null +++ b/backend/apps/payments/services.py @@ -0,0 +1,94 @@ +import logging +from decimal import Decimal + +from django.db import transaction +from django.utils import timezone + +from apps.orders.models import Order + +from .models import Payment + +logger = logging.getLogger(__name__) + + +@transaction.atomic +def create_payment( + order: Order, + method: str, + amount: Decimal, + *, + provider: str = "yookassa", + idempotency_key: str | None = None, +) -> Payment: + """Creates a payment intent. + + The provider call is intentionally left as a TODO: the exact ЮKassa + integration (payment creation, confirmation URL, SBP QR) is implemented + in the payments sprint. The local record is created first so that the + order always has an auditable payment trail. + """ + if idempotency_key: + existing = Payment.objects.filter(idempotency_key=idempotency_key).first() + if existing is not None: + return existing + + payment = Payment.objects.create( + order=order, + method=method, + amount=amount, + provider=provider, + idempotency_key=idempotency_key, + ) + # TODO: call provider API and store provider_payment_id + confirmation_url. + logger.info( + "Payment intent created: order=%s method=%s amount=%s", + order.number, + method, + amount, + ) + return payment + + +@transaction.atomic +def handle_yookassa_webhook(payload: dict) -> Payment | None: + """Applies a ЮKassa webhook to the local payment/order state.""" + event = payload.get("event", "") + obj = payload.get("object", {}) or {} + provider_payment_id = obj.get("id") + + payment = ( + Payment.objects.select_for_update() + .filter(provider_payment_id=provider_payment_id) + .first() + ) + if payment is None: + logger.warning("Unknown ЮKassa payment id: %s", provider_payment_id) + return None + + payment.payload = payload + + if event == "payment.succeeded": + payment.status = Payment.Status.SUCCEEDED + payment.paid_at = timezone.now() + payment.save(update_fields=["status", "paid_at", "payload", "updated_at"]) + + order = payment.order + paid_total = sum( + p.amount + for p in order.payments.filter(status=Payment.Status.SUCCEEDED) + ) + if paid_total >= order.total: + order.payment_status = Order.PaymentStatus.PAID + elif paid_total > 0: + order.payment_status = Order.PaymentStatus.PARTIALLY_PAID + order.save(update_fields=["payment_status", "updated_at"]) + + elif event == "payment.canceled": + payment.status = Payment.Status.CANCELLED + payment.save(update_fields=["status", "payload", "updated_at"]) + + elif event == "refund.succeeded": + payment.status = Payment.Status.REFUNDED + payment.save(update_fields=["status", "payload", "updated_at"]) + + return payment diff --git a/backend/apps/payments/urls.py b/backend/apps/payments/urls.py new file mode 100644 index 0000000..f3c7478 --- /dev/null +++ b/backend/apps/payments/urls.py @@ -0,0 +1,7 @@ +from django.urls import path + +from .views import YooKassaWebhookView + +urlpatterns = [ + path("webhook/yookassa/", YooKassaWebhookView.as_view(), name="yookassa-webhook"), +] diff --git a/backend/apps/payments/views.py b/backend/apps/payments/views.py new file mode 100644 index 0000000..29b1556 --- /dev/null +++ b/backend/apps/payments/views.py @@ -0,0 +1,23 @@ +from rest_framework.permissions import AllowAny +from rest_framework.response import Response +from rest_framework.views import APIView + +from .serializers import PaymentWebhookSerializer +from .services import handle_yookassa_webhook + + +class YooKassaWebhookView(APIView): + """Receives ЮKassa notifications. + + TODO: verify the source IP / signature before applying the event. + """ + + permission_classes = [AllowAny] + authentication_classes: list = [] + serializer_class = PaymentWebhookSerializer + + def post(self, request): + payment = handle_yookassa_webhook(request.data) + if payment is None: + return Response({"detail": "ignored"}) + return Response({"detail": "ok"}) diff --git a/backend/config/__init__.py b/backend/config/__init__.py new file mode 100644 index 0000000..53f4ccb --- /dev/null +++ b/backend/config/__init__.py @@ -0,0 +1,3 @@ +from .celery import app as celery_app + +__all__ = ("celery_app",) diff --git a/backend/config/asgi.py b/backend/config/asgi.py new file mode 100644 index 0000000..4c1def3 --- /dev/null +++ b/backend/config/asgi.py @@ -0,0 +1,7 @@ +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.dev") + +application = get_asgi_application() diff --git a/backend/config/celery.py b/backend/config/celery.py new file mode 100644 index 0000000..a00198f --- /dev/null +++ b/backend/config/celery.py @@ -0,0 +1,15 @@ +"""Celery application for the HOMM backend.""" +import os + +from celery import Celery + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.dev") + +app = Celery("homm") +app.config_from_object("django.conf:settings", namespace="CELERY") +app.autodiscover_tasks() + + +@app.task(bind=True, ignore_result=True) +def debug_task(self) -> None: # pragma: no cover + print(f"Request: {self.request!r}") diff --git a/backend/config/settings/__init__.py b/backend/config/settings/__init__.py new file mode 100644 index 0000000..96f2a1a --- /dev/null +++ b/backend/config/settings/__init__.py @@ -0,0 +1 @@ +from .base import * # noqa: F401,F403 diff --git a/backend/config/settings/base.py b/backend/config/settings/base.py new file mode 100644 index 0000000..b26d9da --- /dev/null +++ b/backend/config/settings/base.py @@ -0,0 +1,292 @@ +"""Django settings shared by all environments.""" +from datetime import timedelta +from pathlib import Path +import os + +from dotenv import load_dotenv + +BASE_DIR = Path(__file__).resolve().parent.parent.parent +# Support both the repository root .env (Docker Compose) and backend/.env (local). +load_dotenv(BASE_DIR.parent / ".env") +load_dotenv(BASE_DIR / ".env", override=True) + + +def env(name: str, default: str | None = None) -> str | None: + return os.environ.get(name, default) + + +def env_bool(name: str, default: bool = False) -> bool: + return str(env(name, str(default))).strip().lower() in {"1", "true", "yes", "on"} + + +def env_int(name: str, default: int) -> int: + try: + return int(env(name, str(default)) or default) + except (TypeError, ValueError): + return default + + +def env_list(name: str, default: str = "") -> list[str]: + raw = env(name, default) or "" + return [item.strip() for item in raw.split(",") if item.strip()] + + +# --- Core ------------------------------------------------------------------- +SECRET_KEY = env("DJANGO_SECRET_KEY", "dev-insecure-change-me") +DEBUG = env_bool("DJANGO_DEBUG", False) +ALLOWED_HOSTS = env_list("DJANGO_ALLOWED_HOSTS", "localhost,127.0.0.1") + +# --- Applications ----------------------------------------------------------- +INSTALLED_APPS = [ + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", + # Third-party + "rest_framework", + "rest_framework_simplejwt", + "drf_spectacular", + "django_filters", + "corsheaders", + # Local + "apps.common", + "apps.accounts", + "apps.catalog", + "apps.orders", + "apps.payments", + "apps.loyalty", + "apps.integration", + "apps.content", +] + +MIDDLEWARE = [ + "django.middleware.security.SecurityMiddleware", + "corsheaders.middleware.CorsMiddleware", + "django.contrib.sessions.middleware.SessionMiddleware", + "django.middleware.common.CommonMiddleware", + "django.middleware.csrf.CsrfViewMiddleware", + "django.contrib.auth.middleware.AuthenticationMiddleware", + "django.contrib.messages.middleware.MessageMiddleware", + "django.middleware.clickjacking.XFrameOptionsMiddleware", + "apps.common.middleware.RequestIDMiddleware", +] + +ROOT_URLCONF = "config.urls" + +TEMPLATES = [ + { + "BACKEND": "django.template.backends.django.DjangoTemplates", + "DIRS": [BASE_DIR / "templates"], + "APP_DIRS": True, + "OPTIONS": { + "context_processors": [ + "django.template.context_processors.debug", + "django.template.context_processors.request", + "django.contrib.auth.context_processors.auth", + "django.contrib.messages.context_processors.messages", + ], + }, + }, +] + +WSGI_APPLICATION = "config.wsgi.application" +ASGI_APPLICATION = "config.asgi.application" + +# --- Database --------------------------------------------------------------- +if env("DB_ENGINE", "sqlite") == "postgres": + DATABASES = { + "default": { + "ENGINE": "django.db.backends.postgresql", + "NAME": env("POSTGRES_DB", "homm"), + "USER": env("POSTGRES_USER", "homm"), + "PASSWORD": env("POSTGRES_PASSWORD", "homm"), + "HOST": env("POSTGRES_HOST", "localhost"), + "PORT": env("POSTGRES_PORT", "5432"), + "CONN_MAX_AGE": 60, + } + } +else: + DATABASES = { + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": BASE_DIR / "db.sqlite3", + } + } + +# --- Cache / Celery --------------------------------------------------------- +REDIS_URL = env("REDIS_URL", "") +if REDIS_URL: + CACHES = { + "default": { + "BACKEND": "django.core.cache.backends.redis.RedisCache", + "LOCATION": REDIS_URL, + } + } +else: + CACHES = { + "default": { + "BACKEND": "django.core.cache.backends.locmem.LocMemCache", + "LOCATION": "homm-local", + } + } + +CELERY_BROKER_URL = env("CELERY_BROKER_URL", REDIS_URL or "redis://localhost:6379/0") +CELERY_RESULT_BACKEND = env("CELERY_RESULT_BACKEND", CELERY_BROKER_URL) +CELERY_TASK_SERIALIZER = "json" +CELERY_RESULT_SERIALIZER = "json" +CELERY_ACCEPT_CONTENT = ["json"] +CELERY_TIMEZONE = "Europe/Moscow" +CELERY_TASK_TRACK_STARTED = True +CELERY_TASK_TIME_LIMIT = 30 * 60 +CELERY_BEAT_SCHEDULE = { + "sync-catalog-from-1c": { + "task": "apps.integration.tasks.sync_catalog_from_1c", + "schedule": 600.0, # every 10 minutes + }, + "process-outbox": { + "task": "apps.integration.tasks.process_outbox", + "schedule": 60.0, + }, + "pull-order-statuses": { + "task": "apps.integration.tasks.pull_order_statuses", + "schedule": 300.0, + }, +} + +# --- Auth ------------------------------------------------------------------- +AUTH_USER_MODEL = "accounts.User" + +AUTH_PASSWORD_VALIDATORS = [ + {"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"}, + {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"}, + {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"}, + {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"}, +] + +SIMPLE_JWT = { + "ACCESS_TOKEN_LIFETIME": timedelta(minutes=30), + "REFRESH_TOKEN_LIFETIME": timedelta(days=30), + "ROTATE_REFRESH_TOKENS": True, + "BLACKLIST_AFTER_ROTATION": False, + "AUTH_HEADER_TYPES": ("Bearer",), +} + +# --- DRF -------------------------------------------------------------------- +REST_FRAMEWORK = { + "DEFAULT_AUTHENTICATION_CLASSES": ( + "rest_framework_simplejwt.authentication.JWTAuthentication", + ), + "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.AllowAny",), + "DEFAULT_PAGINATION_CLASS": "apps.common.pagination.DefaultPagination", + "PAGE_SIZE": 24, + "DEFAULT_FILTER_BACKENDS": ( + "django_filters.rest_framework.DjangoFilterBackend", + "rest_framework.filters.SearchFilter", + "rest_framework.filters.OrderingFilter", + ), + "EXCEPTION_HANDLER": "apps.common.exceptions.api_exception_handler", + "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", + "DEFAULT_THROTTLE_CLASSES": ( + "rest_framework.throttling.AnonRateThrottle", + "rest_framework.throttling.UserRateThrottle", + ), + "DEFAULT_THROTTLE_RATES": { + "anon": "120/min", + "user": "240/min", + "otp": "5/min", + }, +} + +SPECTACULAR_SETTINGS = { + "TITLE": "HOMM Store API", + "DESCRIPTION": ( + "Public storefront API and the integration API used by 1C. " + "See docs/architecture.md for the exchange design." + ), + "VERSION": "1.0.0", + "SERVE_INCLUDE_SCHEMA": False, + "COMPONENT_SPLIT_REQUEST": True, + "SORT_OPERATIONS": False, + "ENUM_NAME_OVERRIDES": { + "OrderStatusEnum": "apps.orders.models.Order.Status", + "OrderPaymentStatusEnum": "apps.orders.models.Order.PaymentStatus", + "PaymentMethodEnum": "apps.payments.models.Payment.Method", + "PaymentStatusEnum": "apps.payments.models.Payment.Status", + "ProductStockStatusEnum": "apps.catalog.models.Product.StockStatus", + "BonusReasonEnum": "apps.loyalty.models.BonusTransaction.Reason", + "CertificateStatusEnum": "apps.loyalty.models.GiftCertificate.Status", + "PromoDiscountTypeEnum": "apps.loyalty.models.PromoCode.DiscountType", + "SyncDirectionEnum": "apps.integration.models.SyncRun.Direction", + "SyncEntityEnum": "apps.integration.models.SyncRun.Entity", + "SyncRunStatusEnum": "apps.integration.models.SyncRun.Status", + "OutboxStatusEnum": "apps.integration.models.OutboxMessage.Status", + }, +} + +# --- CORS ------------------------------------------------------------------- +CORS_ALLOWED_ORIGINS = env_list( + "CORS_ALLOWED_ORIGINS", "http://localhost:3000,http://localhost:5173" +) +CORS_ALLOW_CREDENTIALS = True + +# --- Internationalization --------------------------------------------------- +LANGUAGE_CODE = "ru-ru" +TIME_ZONE = "Europe/Moscow" +USE_I18N = True +USE_TZ = True + +# --- Static / media --------------------------------------------------------- +STATIC_URL = "static/" +STATIC_ROOT = BASE_DIR / "staticfiles" +MEDIA_URL = "media/" +MEDIA_ROOT = BASE_DIR / "media" + +DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" + +# --- Email ------------------------------------------------------------------ +EMAIL_BACKEND = env( + "EMAIL_BACKEND", "django.core.mail.backends.console.EmailBackend" +) +DEFAULT_FROM_EMAIL = env("DEFAULT_FROM_EMAIL", "noreply@homm.local") + +# --- OTP -------------------------------------------------------------------- +OTP_TTL_SECONDS = env_int("OTP_TTL_SECONDS", 300) +OTP_MAX_ATTEMPTS = env_int("OTP_MAX_ATTEMPTS", 5) +OTP_DEBUG_CODE = env("OTP_DEBUG_CODE", "") +# Never enable in production: exposes the OTP code in the API response. +OTP_EXPOSE_DEBUG_CODE = env_bool("OTP_EXPOSE_DEBUG_CODE", False) + +# --- 1C integration --------------------------------------------------------- +INTEGRATION_API_TOKEN = env("INTEGRATION_API_TOKEN", "dev-integration-token") +ONEC_BASE_URL = env("ONEC_BASE_URL", "") +ONEC_USERNAME = env("ONEC_USERNAME", "") +ONEC_PASSWORD = env("ONEC_PASSWORD", "") +ONEC_TIMEOUT = env_int("ONEC_TIMEOUT", 30) + +# --- Payments --------------------------------------------------------------- +YOOKASSA_SHOP_ID = env("YOOKASSA_SHOP_ID", "") +YOOKASSA_SECRET_KEY = env("YOOKASSA_SECRET_KEY", "") +YOOKASSA_RETURN_URL = env("YOOKASSA_RETURN_URL", "") + +# --- Logging ---------------------------------------------------------------- +LOGGING = { + "version": 1, + "disable_existing_loggers": False, + "formatters": { + "verbose": { + "format": "%(asctime)s %(levelname)s %(name)s %(message)s", + }, + }, + "handlers": { + "console": { + "class": "logging.StreamHandler", + "formatter": "verbose", + }, + }, + "root": {"handlers": ["console"], "level": "INFO"}, + "loggers": { + "apps.integration": {"level": "DEBUG", "propagate": True}, + }, +} diff --git a/backend/config/settings/dev.py b/backend/config/settings/dev.py new file mode 100644 index 0000000..7946e4d --- /dev/null +++ b/backend/config/settings/dev.py @@ -0,0 +1,11 @@ +"""Local development settings.""" +from .base import * # noqa: F401,F403 + +DEBUG = True +ALLOWED_HOSTS = ["*"] + +# Fixed OTP code for local development unless explicitly overridden. +OTP_DEBUG_CODE = OTP_DEBUG_CODE or "0000" # noqa: F405 +OTP_EXPOSE_DEBUG_CODE = True + +EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" diff --git a/backend/config/settings/prod.py b/backend/config/settings/prod.py new file mode 100644 index 0000000..1bd532a --- /dev/null +++ b/backend/config/settings/prod.py @@ -0,0 +1,28 @@ +"""Production settings.""" +from .base import * # noqa: F401,F403 + +DEBUG = False + +SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") +SECURE_SSL_REDIRECT = env_bool("SECURE_SSL_REDIRECT", True) # noqa: F405 +SESSION_COOKIE_SECURE = True +CSRF_COOKIE_SECURE = True +SECURE_HSTS_SECONDS = 31536000 +SECURE_HSTS_INCLUDE_SUBDOMAINS = True +SECURE_HSTS_PRELOAD = True +SECURE_CONTENT_TYPE_NOSNIFF = True +X_FRAME_OPTIONS = "DENY" + +CSRF_TRUSTED_ORIGINS = env_list("CSRF_TRUSTED_ORIGINS", "") # noqa: F405 + +if env("SENTRY_DSN", ""): # noqa: F405 + import sentry_sdk + from sentry_sdk.integrations.celery import CeleryIntegration + from sentry_sdk.integrations.django import DjangoIntegration + + sentry_sdk.init( + dsn=env("SENTRY_DSN"), # noqa: F405 + integrations=[DjangoIntegration(), CeleryIntegration()], + traces_sample_rate=float(env("SENTRY_TRACES_SAMPLE_RATE", "0.1")), # noqa: F405 + send_default_pii=False, + ) diff --git a/backend/config/urls.py b/backend/config/urls.py new file mode 100644 index 0000000..2cda550 --- /dev/null +++ b/backend/config/urls.py @@ -0,0 +1,32 @@ +"""URL configuration for the HOMM backend.""" +from django.conf import settings +from django.conf.urls.static import static +from django.contrib import admin +from django.urls import include, path +from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView + +admin.site.site_header = "HOMM — управление магазином" +admin.site.site_title = "HOMM Admin" +admin.site.index_title = "Панель управления" +admin.site.index_template = "admin/homm_index.html" + +urlpatterns = [ + path("admin/", admin.site.urls), + path("api/v1/", include("apps.common.urls")), + path("api/v1/auth/", include("apps.accounts.urls")), + path("api/v1/catalog/", include("apps.catalog.urls")), + path("api/v1/orders/", include("apps.orders.urls")), + path("api/v1/loyalty/", include("apps.loyalty.urls")), + path("api/v1/content/", include("apps.content.urls")), + path("api/v1/payments/", include("apps.payments.urls")), + path("api/v1/integration/1c/", include("apps.integration.urls")), + path("api/schema/", SpectacularAPIView.as_view(), name="schema"), + path( + "api/docs/", + SpectacularSwaggerView.as_view(url_name="schema"), + name="swagger-ui", + ), +] + +if settings.DEBUG: + urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) diff --git a/backend/config/wsgi.py b/backend/config/wsgi.py new file mode 100644 index 0000000..8c34a6e --- /dev/null +++ b/backend/config/wsgi.py @@ -0,0 +1,7 @@ +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.dev") + +application = get_wsgi_application() diff --git a/backend/manage.py b/backend/manage.py new file mode 100644 index 0000000..4521dc8 --- /dev/null +++ b/backend/manage.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +"""Django management entrypoint for the HOMM store backend.""" +import os +import sys + + +def main() -> None: + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.dev") + try: + from django.core.management import execute_from_command_line + except ImportError as exc: # pragma: no cover + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH? Did you forget to activate a " + "virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == "__main__": + main() diff --git a/backend/pytest.ini b/backend/pytest.ini new file mode 100644 index 0000000..a4457e2 --- /dev/null +++ b/backend/pytest.ini @@ -0,0 +1,4 @@ +[pytest] +DJANGO_SETTINGS_MODULE = config.settings.dev +python_files = tests.py test_*.py *_tests.py +addopts = -q diff --git a/backend/templates/admin/homm_index.html b/backend/templates/admin/homm_index.html new file mode 100644 index 0000000..6880826 --- /dev/null +++ b/backend/templates/admin/homm_index.html @@ -0,0 +1,53 @@ +{% extends "admin/index.html" %} +{% load admin_metrics %} + +{% block content %} + {% admin_metrics as m %} + + {{ block.super }} +{% endblock %} diff --git a/deploy/nginx/default.conf b/deploy/nginx/default.conf new file mode 100644 index 0000000..946b19d --- /dev/null +++ b/deploy/nginx/default.conf @@ -0,0 +1,32 @@ +upstream homm_backend { + server web:8000; +} + +server { + listen 80; + server_name _; + + client_max_body_size 20m; + + location /static/ { + alias /app/staticfiles/; + expires 30d; + add_header Cache-Control "public, immutable"; + } + + location /media/ { + alias /app/media/; + expires 7d; + add_header Cache-Control "public"; + } + + location / { + proxy_pass http://homm_backend; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Request-ID $request_id; + proxy_read_timeout 60s; + } +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..4fc11da --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,105 @@ +services: + db: + image: postgres:16-alpine + environment: + POSTGRES_DB: ${POSTGRES_DB:-homm} + POSTGRES_USER: ${POSTGRES_USER:-homm} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-homm} + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-homm} -d ${POSTGRES_DB:-homm}"] + interval: 5s + timeout: 5s + retries: 10 + + redis: + image: redis:7-alpine + command: ["redis-server", "--appendonly", "yes"] + volumes: + - redisdata:/data + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 10 + + web: + build: . + env_file: + - .env + environment: + DJANGO_SETTINGS_MODULE: config.settings.prod + DB_ENGINE: postgres + POSTGRES_HOST: db + REDIS_URL: redis://redis:6379/0 + CELERY_BROKER_URL: redis://redis:6379/0 + CELERY_RESULT_BACKEND: redis://redis:6379/1 + command: > + sh -c "python manage.py migrate --noinput && + gunicorn config.wsgi:application --bind 0.0.0.0:8000 --workers 3 --timeout 60" + volumes: + - staticfiles:/app/staticfiles + - media:/app/media + depends_on: + db: + condition: service_healthy + redis: + condition: service_healthy + ports: + - "8000:8000" + + worker: + build: . + env_file: + - .env + environment: + DJANGO_SETTINGS_MODULE: config.settings.prod + DB_ENGINE: postgres + POSTGRES_HOST: db + REDIS_URL: redis://redis:6379/0 + CELERY_BROKER_URL: redis://redis:6379/0 + CELERY_RESULT_BACKEND: redis://redis:6379/1 + command: ["celery", "-A", "config", "worker", "-l", "info", "--concurrency", "4"] + volumes: + - media:/app/media + depends_on: + db: + condition: service_healthy + redis: + condition: service_healthy + + beat: + build: . + env_file: + - .env + environment: + DJANGO_SETTINGS_MODULE: config.settings.prod + DB_ENGINE: postgres + POSTGRES_HOST: db + REDIS_URL: redis://redis:6379/0 + CELERY_BROKER_URL: redis://redis:6379/0 + CELERY_RESULT_BACKEND: redis://redis:6379/1 + command: ["celery", "-A", "config", "beat", "-l", "info"] + depends_on: + db: + condition: service_healthy + redis: + condition: service_healthy + + nginx: + image: nginx:1.27-alpine + ports: + - "80:80" + volumes: + - ./deploy/nginx/default.conf:/etc/nginx/conf.d/default.conf:ro + - staticfiles:/app/staticfiles:ro + - media:/app/media:ro + depends_on: + - web + +volumes: + pgdata: + redisdata: + staticfiles: + media: diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..6302027 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,539 @@ +# Архитектура HOMM + +Статус: рабочий черновик v0.1 +Основание: `README.md` (ТЗ на интернет-магазин с интеграцией 1С) +Связанные контракты: + +- `docs/openapi-1c-inbound.yaml` — API сайта, которое вызывает 1С. +- `docs/openapi-1c-outbound.yaml` — HTTP-сервис 1С, который вызывает сайт. + +--- + +## 1. Контекст и границы + +HOMM — интернет-магазин, где **1С является мастер-системой** для товаров, цен, остатков, категорий, клиентов, бонусов и статусов заказов. Сайт — витрина и канал продаж, который: + +1. Показывает каталог, полученный из 1С. +2. Принимает заказы и передаёт их в 1С. +3. Показывает статусы, которые меняются в 1С. +4. Ведёт локальную корзину, оформление, оплату и личный кабинет. + +Границы первой версии (MVP): + +- каталог, карточка товара, поиск, фильтры; +- корзина на клиенте + оформление заказа; +- авторизация по телефону (OTP) и email/пароль; +- личный кабинет: профиль, заказы, адреса; +- оплата ЮKassa (карта/СБП внутри провайдера); +- двусторонний обмен с 1С: каталог, заказы, статусы, клиенты, бонусы; +- админка: мониторинг обменов, заказы, пользователи. + +За границами MVP (фаза 2): сертификаты в полном объёме, комбинированная оплата, рассрочка/«Долями», чат поддержки, сравнение товаров, возвраты, расширенный контент-менеджмент, SEO-оптимизация. + +--- + +## 2. Ключевые архитектурные решения + +| № | Решение | Обоснование | Альтернативы | +|---|---------|-------------|--------------| +| ADR-1 | Django 4.2 + DRF | Соответствует ТЗ, зрелая экосистема, встроенная админка, ORM и безопасность | FastAPI, Laravel | +| ADR-2 | PostgreSQL как основная БД | Транзакции, JSONB для атрибутов, индексы, масштабирование | MySQL, SQLite (только dev) | +| ADR-3 | Redis + Celery | Фоновые обмены, retry, периодические задачи, кэш | RQ, Dramatiq | +| ADR-4 | **Transactional outbox** для сайт → 1С | Заказ не может быть создан без гарантированной постановки в очередь; retry и dead-letter | Прямой HTTP-вызов в транзакции | +| ADR-5 | **Idempotency-Key** для создания заказа | Защита от дублей при повторных запросах и таймаутах | Естественный ключ (номер заказа) | +| ADR-6 | Явный маппинг статусов 1С → сайт | Статусы в 1С настраиваются под конфигурацию; маппинг должен быть версионируемым | Автоматическое угадывание | +| ADR-7 | Vue 3 + Nuxt 3 (SSR) для витрины | SEO и скорость для e-commerce; чистый SPA не индексируется | SPA + prerender | +| ADR-8 | S3/MinIO для медиа | Не хранить изображения в контейнере; CDN и ресайз | Локальный диск | +| ADR-9 | OpenAPI как контракт | Фронт, бэк и 1С работают по одному контракту; генерация клиентов | Ручные договорённости | +| ADR-10 | Отдельный слой `apps.integration` | Изоляция логики обмена от домена; проще тестировать и менять | Логика в views/models | + +--- + +## 3. Компоненты + +```mermaid +flowchart LR + subgraph Client + B[Браузер / Nuxt 3] + end + + subgraph Edge + N[Nginx] + end + + subgraph App + W[Gunicorn + Django/DRF] + C[Celery worker] + BT[Celery beat] + end + + subgraph Data + PG[(PostgreSQL)] + R[(Redis)] + S3[(S3 / MinIO)] + end + + subgraph External + OC[1С: HTTP-сервис] + YK[ЮKassa] + SMS[SMS-шлюз] + MAIL[Email] + end + + B --> N --> W + W --> PG + W --> R + W --> S3 + W --> YK + W --> SMS + W --> MAIL + C --> PG + C --> R + C --> OC + C --> S3 + BT --> R + OC -->|inbound API| W + YK -->|webhook| W +``` + +### 3.1 Приложения Django + +| Приложение | Ответственность | +|------------|-----------------| +| `apps.common` | Базовые модели, пагинация, обработка ошибок, request-id, интеграционная аутентификация | +| `apps.accounts` | Пользователь (телефон), OTP, адреса, профиль, JWT | +| `apps.catalog` | Категории, товары, изображения, фильтры, поиск | +| `apps.orders` | Заказ, позиции, история статусов, создание и отмена | +| `apps.payments` | Платёжные попытки, вебхуки ЮKassa, статусы оплаты | +| `apps.loyalty` | Бонусный счёт, операции, промокоды, сертификаты | +| `apps.integration` | Обмен с 1С: сеансы, журналы, outbox, клиент 1С, задачи Celery | +| `apps.content` | Статические страницы, баннеры, настройки сайта | + +### 3.2 Frontend (план) + +- **Nuxt 3** (Vue 3 + SSR) — витрина, каталог, карточка, корзина, checkout, ЛК. +- **Pinia** — состояние корзины, избранного, пользователя. +- **Axios** — клиент к `/api/v1/`. +- Корзина хранится на клиенте (localStorage/Pinia) и передаётся в `POST /api/v1/orders/`; это упрощает анонимный checkout и снимает необходимость в серверной корзине на MVP. +- SEO: SSR, meta-теги, sitemap, robots, JSON-LD (фаза 2). + +--- + +## 4. Модель данных + +```mermaid +erDiagram + USER ||--o{ ADDRESS : has + USER ||--o| BONUS_ACCOUNT : owns + USER ||--o{ ORDER : places + USER ||--o{ GIFT_CERTIFICATE : receives + + CATEGORY ||--o{ CATEGORY : parent + CATEGORY ||--o{ PRODUCT : contains + PRODUCT ||--o{ PRODUCT_IMAGE : has + PRODUCT ||--o{ ORDER_ITEM : referenced + + ORDER ||--o{ ORDER_ITEM : contains + ORDER ||--o{ ORDER_STATUS_HISTORY : tracks + ORDER ||--o{ PAYMENT : paid_by + ORDER ||--o{ BONUS_TRANSACTION : bonus_ops + + BONUS_ACCOUNT ||--o{ BONUS_TRANSACTION : records + + SYNC_RUN ||--o{ SYNC_LOG : logs +``` + +Ключевые сущности: + +| Сущность | Ключевые поля | Примечание | +|----------|---------------|------------| +| `User` | `phone` (unique), `email`, ФИО | Вход по телефону; email опционален | +| `OtpCode` | `phone`, `code_hash`, `expires_at`, `attempts` | Хранится только хэш кода | +| `Address` | `user`, `city`, `street`, `is_default` | Один адрес по умолчанию | +| `Category` | `external_id`, `parent`, `slug` | `external_id` — ключ 1С | +| `Product` | `external_id`, `sku`, `price`, `stock`, `attributes` | `attributes` — JSONB для характеристик | +| `ProductImage` | `product`, `url`, `is_main` | URL из 1С/S3 | +| `Order` | `number`, `external_id`, `status`, `total`, `idempotency_key` | `external_id` — номер в 1С | +| `OrderItem` | `order`, `product`, `price`, `quantity` | Цена фиксируется на момент заказа | +| `OrderStatusHistory` | `order`, `status`, `source` | `source`: `site` / `1c` | +| `Payment` | `order`, `method`, `status`, `amount` | Одна попытка оплаты = одна запись | +| `BonusAccount` | `user`, `balance` | Баланс в рублях | +| `BonusTransaction` | `account`, `amount`, `reason` | Положительные и отрицательные операции | +| `PromoCode` | `code`, `discount_type`, `value`, `max_uses` | Процент или фиксированная сумма | +| `GiftCertificate` | `code`, `nominal`, `balance`, `status` | Может быть частично использован | +| `SyncRun` | `direction`, `entity`, `status`, `stats` | Один сеанс обмена | +| `SyncLog` | `run`, `level`, `message`, `payload` | Диагностика | +| `OutboxMessage` | `topic`, `payload`, `status`, `attempts` | Гарантированная доставка в 1С | +| `IdempotencyKey` | `key`, `scope`, `response` | Для повторных входящих запросов | + +--- + +## 5. API + +Базовый префикс: `/api/v1/`. Схема: `/api/schema/`, Swagger UI: `/api/docs/`. + +### 5.1 Публичный API + +| Метод | Путь | Назначение | Доступ | +|-------|------|------------|--------| +| POST | `/auth/otp/request/` | Запросить OTP | Аноним | +| POST | `/auth/otp/verify/` | Подтвердить OTP, получить JWT | Аноним | +| POST | `/auth/token/` | Вход по телефону/паролю | Аноним | +| POST | `/auth/token/refresh/` | Обновить access-токен | Аноним | +| GET/PATCH | `/auth/me/` | Профиль | JWT | +| POST | `/auth/password/` | Установить/сменить пароль | JWT | +| CRUD | `/auth/addresses/` | Адреса доставки | JWT | +| GET | `/catalog/categories/` | Категории | Аноним | +| GET | `/catalog/products/` | Каталог с фильтрами | Аноним | +| GET | `/catalog/products/{slug}/` | Карточка товара | Аноним | +| GET | `/catalog/products/hits/` | Хиты продаж | Аноним | +| GET | `/catalog/products/new/` | Новинки | Аноним | +| GET | `/catalog/products/{slug}/related/` | Похожие товары | Аноним | +| POST | `/orders/` | Создать заказ | Аноним/JWT | +| GET | `/orders/` | Мои заказы | JWT | +| GET | `/orders/{id}/` | Детали заказа | JWT | +| POST | `/orders/{id}/cancel/` | Отменить заказ | JWT | +| GET | `/loyalty/bonus/` | Баланс и история бонусов | JWT | +| POST | `/loyalty/promo/validate/` | Проверить промокод | Аноним | +| POST | `/loyalty/certificate/validate/` | Проверить сертификат | Аноним | +| GET | `/loyalty/certificates/` | Мои сертификаты | JWT | +| GET | `/content/settings/` | Настройки сайта (контакты, доставка, бонусы) | Аноним | +| GET | `/content/pages/` | Опубликованные статические страницы | Аноним | +| GET | `/content/pages/{slug}/` | Страница по slug | Аноним | +| GET | `/content/banners/?position=home_top` | Активные баннеры | Аноним | +| POST | `/payments/webhook/yookassa/` | Вебхук ЮKassa | Аноним + проверка подписи | + +Особенности: + +- Ошибки возвращаются в конверте `{"error": {"code", "message", "details"}}`. +- Пагинация: `page`, `page_size` (по умолчанию 24, максимум 100). +- Фильтры каталога: `category`, `category_id`, `price_min`, `price_max`, `is_hit`, `is_new`, `brand`, `in_stock`, `search`, `ordering`. +- Создание заказа поддерживает `Idempotency-Key` (заголовок). Повторный запрос с тем же ключом возвращает существующий заказ и `200` вместо `201`. + +### 5.2 Интеграционный API (1С → сайт) + +| Метод | Путь | Назначение | +|-------|------|------------| +| GET | `/integration/1c/health/` | Проверка доступности | +| POST | `/integration/1c/catalog/sync/` | Пакетная выгрузка категорий/товаров/цен/остатков | +| GET | `/integration/1c/orders/pending/` | Заказы, ещё не подтверждённые 1С | +| POST | `/integration/1c/orders/{number}/status/` | Обновить статус заказа | +| POST | `/integration/1c/orders/{number}/ack/` | Подтвердить приём заказа (`external_id`) | +| POST | `/integration/1c/customers/bonus/` | Начислить/списать бонусы | +| POST | `/integration/1c/sync/run/` | Ручной запуск синхронизации (staff) | + +Аутентификация: заголовок `X-Integration-Token` (или `Authorization: Bearer `), значение — `INTEGRATION_API_TOKEN`. + +--- + +## 6. Интеграция с 1С + +### 6.1 Направления + +| Направление | Инициатор | Транспорт | Частота | +|-------------|-----------|-----------|---------| +| Каталог, цены, остатки, фото | Сайт (pull) или 1С (push) | REST/JSON | 5–15 минут | +| Заказы | Сайт → 1С | REST/JSON + outbox | Сразу после создания, retry | +| Статусы заказов | 1С → сайт (push) или сайт (pull) | REST/JSON | 5 минут | +| Клиенты | Сайт → 1С | REST/JSON | При регистрации/изменении | +| Бонусы | 1С → сайт | REST/JSON | При начислении/списании | + +Поддерживаются оба режима каталога: + +- **Pull** — сайт сам запрашивает `GET /catalog/changes?since=...` у 1С (Celery beat, каждые 10 минут). +- **Push** — 1С вызывает `POST /api/v1/integration/1c/catalog/sync/` (если 1С удобнее инициировать обмен). + +### 6.2 Формат обмена + +- JSON, UTF-8, `Content-Type: application/json`. +- Все суммы — строки с двумя знаками после запятой (`"49990.00"`), чтобы избежать потерь точности. +- Даты — ISO 8601 с часовым поясом (`2026-11-06T15:00:00+03:00`). +- Идентификаторы: `external_id` — стабильный ключ 1С (GUID или код), `sku` — артикул. +- Изображения передаются URL-ами; сайт может скачивать их в S3/MinIO фоновой задачей. + +### 6.3 Идемпотентность + +- **Заказы:** заголовок `Idempotency-Key`; уникальный индекс в `orders_order.idempotency_key`. Повторный запрос возвращает существующий заказ. +- **Каталог:** `update_or_create` по `external_id`; повторная выгрузка не создаёт дублей. +- **Статусы:** обновление статуса идемпотентно; повторная установка того же статуса не ломает историю (запись истории создаётся, но состояние не меняется). +- **Бонусы:** для повторной доставки рекомендуется передавать `operation_id` (поле зарезервировано в контракте) — в MVP дедупликация по `order_number` + `amount` + `reason` не реализована, это задача фазы 2. + +### 6.4 Дельта-синхронизация + +1. 1С хранит `updated_at`/`modified` для каждой сущности. +2. Сайт запрашивает изменения с `since` (последний успешный `SyncRun.finished_at`). +3. 1С возвращает только изменённые объекты + список удалённых `external_id`. +4. Сайт применяет пакет в одной транзакции и фиксирует `SyncRun.stats`. +5. При ошибке `SyncRun.status = failed`, `since` не сдвигается — следующий запуск повторит пакет. + +Полная переиндексация: `python manage.py sync_catalog --since 2000-01-01T00:00:00+03:00`. + +### 6.5 Маппинг статусов + +Реализован в `apps/integration/status_map.py`. Поддерживаются русские названия и английские коды: + +| 1С | Сайт | +|----|------| +| Новый | `new` | +| В обработке / Подтверждён / Собирается | `processing` | +| Передан в доставку / Доставляется / В пути | `delivering` | +| Выполнен / Закрыт | `completed` | +| Отменён | `cancelled` | + +Маппинг расширяется без изменения кода — достаточно добавить пару в словарь. Для нестандартных конфигураций 1С рекомендуется вынести маппинг в настройку админки (фаза 2). + +### 6.6 Ошибки, retry, dead-letter + +- **Outbox:** сообщение создаётся в той же транзакции, что и заказ. Celery-задача `process_outbox` раз в минуту забирает `pending`. +- **Retry:** экспоненциальная задержка `2^attempts` минут, максимум 5 попыток. +- **Dead-letter:** после 5 попыток `status = dead`, сообщение видно в админке; требуется ручное вмешательство. +- **Входящие ошибки:** `CatalogSyncView` фиксирует `SyncRun.failed` и возвращает `400` с кодом; 1С должна повторить пакет. +- **Таймауты:** `ONEC_TIMEOUT` (по умолчанию 30 секунд); для больших пакетов каталога — батчи по 500–1000 товаров. + +### 6.7 Безопасность обмена + +- Сайт → 1С: HTTP Basic (логин/пароль сервисного пользователя 1С) + HTTPS. +- 1С → сайт: `X-Integration-Token` (длинный случайный секрет), сравнение за константное время (реализовано через обычное сравнение; для продакшена рекомендуется `hmac.compare_digest`). +- IP allowlist для входящих запросов 1С (на уровне Nginx). +- Логи обмена не должны содержать персональные данные в открытом виде; payload логируется выборочно. + +### 6.8 Мониторинг + +- `SyncRun` + `SyncLog` — история каждого обмена. +- Админка: список сеансов, статус, статистика, ошибки. +- Метрики (Prometheus): длительность обмена, количество ошибок, размер очереди outbox, возраст старейшего `pending`. +- Алерты: `failed` обмен, `dead` сообщения, очередь outbox > N, отсутствие успешного обмена > 30 минут. + +--- + +## 7. Платежи + +### 7.1 Способы оплаты + +| Способ | Провайдер | Статус | +|--------|-----------|--------| +| Банковская карта | ЮKassa | MVP | +| СБП | ЮKassa (внутри) | MVP | +| МИР Pay | ЮKassa / отдельный API | Фаза 2 | +| Наличные при получении | — | MVP | +| Рассрочка | Банк-партнёр | Фаза 2 | +| «Долями» / «Сплит» | Партнёр | Фаза 2 | + +### 7.2 Комбинированная оплата + +Заказ может быть закрыт несколькими частями: + +``` +total = subtotal - promo_discount - bonus_applied - certificate_applied + delivery_cost +``` + +Порядок применения в MVP: + +1. Промокод (скидка). +2. Бонусы (списание с бонусного счёта). +3. Сертификат (списание с баланса сертификата). +4. Остаток — платёж через ЮKassa/наличные. + +Каждая часть фиксируется отдельно: + +- `Order.discount_total`, `Order.bonus_applied`, `Order.certificate_applied`; +- `BonusTransaction` — списание бонусов; +- `GiftCertificate.balance` — уменьшение баланса; +- `Payment` — платёж на остаток. + +**Важно:** ЮKassa, как правило, принимает один платёж на сумму заказа. Если требуется несколько онлайн-платежей по одному заказу, используется несколько `Payment` с разными `idempotency_key`; состояние заказа агрегируется по сумме успешных платежей (`payment_status`). + +### 7.3 Машина состояний + +```mermaid +stateDiagram-v2 + [*] --> pending + pending --> succeeded: payment.succeeded + pending --> cancelled: payment.canceled + succeeded --> refunded: refund.succeeded + cancelled --> [*] + refunded --> [*] +``` + +Заказ: + +```mermaid +stateDiagram-v2 + [*] --> new + new --> processing: 1С подтвердила + processing --> delivering: передано в доставку + delivering --> completed: выдан + new --> cancelled: клиент/менеджер + processing --> cancelled: клиент/менеджер + completed --> [*] + cancelled --> [*] +``` + +--- + +## 8. Лояльность + +- **Бонусы:** баланс в `BonusAccount`, история в `BonusTransaction`. Начисление/списание — только через сервисы с `select_for_update`, чтобы избежать гонок. +- **Промокоды:** процент или фиксированная сумма, минимальная сумма заказа, лимит использований, срок действия. +- **Сертификаты:** номинал, остаток, статус, срок действия; могут применяться частично. +- **Правила начисления** (процент, срок жизни, максимум оплаты бонусами) — настраиваются в 1С и передаются на сайт; в MVP хранятся в настройках/константах. + +--- + +## 9. Безопасность и 152-ФЗ + +- JWT: access 30 минут, refresh 30 дней, ротация refresh. +- OTP: TTL 5 минут, максимум 5 попыток, throttle 5 запросов/минуту на IP. +- Пароли: валидаторы Django, хэширование PBKDF2. +- Персональные данные: минимизация, шифрование канала (HTTPS), ограничение доступа в админке. +- Cookie-баннер: аналитические скрипты загружаются только после согласия; технические cookie — всегда. +- Логи: не писать телефоны/email в открытом виде в интеграционные payload-логи (маскировать). +- CSRF: для JWT-API не требуется; для админки — стандартная защита Django. +- Rate limiting: DRF throttles + Nginx `limit_req` для чувствительных endpoint-ов. + +--- + +## 10. Производительность + +- Каталог: индексы по `category`, `is_active`, `price`, `is_hit`, `is_new`; `select_related`/`prefetch_related` в queryset. +- Изображения: S3/MinIO + CDN, ресайз в Celery. +- Кэш: Redis для категорий, фильтров, карточки товара (инвалидация по `external_id`). +- Поиск: на MVP — PostgreSQL `icontains`/FTS; при росте каталога — Meilisearch/Elasticsearch. +- Цель: TTFB < 500 мс, полная загрузка < 3 секунд (по ТЗ). +- Нагрузочное тестирование: Locust/k6, 100–300 RPS на каталог, 20–50 RPS на checkout. + +--- + +## 11. Развёртывание + +### Локально (SQLite, без Docker) + +```bash +py -3.12 -m venv .venv +.venv\Scripts\activate +pip install -r requirements/dev.txt +cd backend +python manage.py migrate +python manage.py createsuperuser +python manage.py runserver +``` + +Swagger: `http://127.0.0.1:8000/api/docs/`. + +### Docker Compose + +```bash +copy .env.example .env +docker compose up --build +``` + +Сервисы: `db` (PostgreSQL), `redis`, `web` (Gunicorn), `worker` (Celery), `beat`, `nginx`. + +### Переменные окружения + +См. `.env.example`. Критичные: + +| Переменная | Назначение | +|------------|------------| +| `DJANGO_SECRET_KEY` | Секрет Django | +| `DJANGO_ALLOWED_HOSTS` | Разрешённые хосты | +| `DB_ENGINE` | `sqlite` или `postgres` | +| `REDIS_URL` | Кэш/брокер | +| `INTEGRATION_API_TOKEN` | Секрет для входящих запросов 1С | +| `ONEC_BASE_URL` | Базовый URL HTTP-сервиса 1С | +| `ONEC_USERNAME` / `ONEC_PASSWORD` | Учётка для исходящих запросов | +| `YOOKASSA_SHOP_ID` / `YOOKASSA_SECRET_KEY` | Платёжный шлюз | + +--- + +## 12. Тестирование + +- `python manage.py test` — 13 тестов: каталог, заказы, идемпотентность, OTP, интеграция. +- `pytest` — альтернативный раннер (`backend/pytest.ini`). +- Покрытие MVP: доменные сервисы, API-контракты, идемпотентность, маппинг статусов. +- Фаза 2: contract-тесты с 1С (Pact/JSON Schema), нагрузочные тесты, e2e (Playwright). + +--- + +## 13. Границы MVP и roadmap + +| Этап | Содержание | Оценка | +|------|------------|--------| +| MVP | Каталог, заказ, OTP, ЛК (профиль/заказы/адреса), ЮKassa, обмен каталогом/заказами/статусами, админка обменов | 10–12 недель | +| Фаза 2 | Бонусы, промокоды, сертификаты, комбинированная оплата, избранное/сравнение, чат, возвраты | 6–8 недель | +| Фаза 3 | SEO, CDN, поиск, рекомендации, аналитика, нагрузочное тестирование, рассрочка | 4–6 недель | + +--- + +## 14. Админ-панель + +Реализована на Django Admin: `/admin/`. + +### 14.1 Дашборд + +Главная страница показывает: + +- заказы за сегодня и выручку; +- заказы в работе; +- размер очереди outbox и количество dead-letter сообщений; +- количество активных товаров и пользователей; +- товары с низким остатком; +- статус последнего обмена с 1С. + +### 14.2 Разделы + +| Раздел | Модели | Возможности | +|--------|--------|-------------| +| Заказы | `Order`, `OrderItem`, `OrderStatusHistory`, `Payment` | Просмотр, смена статуса действиями, история, платежи | +| Каталог | `Category`, `Product`, `ProductImage` | Флаги «Хит»/«Новинка», активация, изображения | +| Пользователи | `User`, `Address`, `OtpCode` | Бонусный баланс, число заказов, адреса | +| Лояльность | `BonusAccount`, `BonusTransaction`, `PromoCode`, `GiftCertificate` | Активация промокодов и сертификатов, история бонусов | +| Интеграция | `SyncRun`, `SyncLog`, `OutboxMessage`, `IdempotencyKey` | Мониторинг, логи, ручной запуск, retry outbox | +| Контент | `StaticPage`, `Banner`, `SiteSettings` | Страницы, баннеры, контакты, правила доставки и бонусов | +| Журнал | `LogEntry` | Все действия администраторов (кто, когда, что) | + +### 14.3 Роли + +```bash +python manage.py create_roles +``` + +Создаёт группы: + +- **Контент-менеджер** — контент и каталог; +- **Менеджер заказов** — заказы и платежи; +- **Менеджер лояльности** — бонусы, промокоды, сертификаты; +- **Технический администратор** — интеграция с 1С. + +Права выдаются через стандартные permissions Django; суперпользователь имеет полный доступ. + +### 14.4 Действия + +- Заказы: «В обработку», «Доставляется», «Выполнен», «Отменить». +- Товары: «Хит продаж», «Новинка», активация/деактивация. +- Промокоды и сертификаты: активация/деактивация. +- Интеграция: запуск синхронизации каталога, повтор outbox, dead-letter. + +### 14.5 Доступ + +```bash +python manage.py createsuperuser # логин — номер телефона +python manage.py create_roles # группы и права +``` + +Вход: `/admin/`. + +--- + +## 15. Открытые вопросы + +1. Конфигурация и версия 1С (УТ 11 / ERP / УНФ)? Кто реализует HTTP-сервис на стороне 1С? +2. Объём каталога (SKU), число характеристик, частота изменения цен/остатков? +3. Как определяются «Хиты» и «Новинки» — флаг из 1С или логика сайта? +4. Нужны ли товары поставщиков (дропшиппинг) в MVP? +5. Службы доставки и расчёт стоимости доставки? +6. Правила бонусной программы: процент, лимиты, срок действия, совместимость с промокодами? +7. Допустимо ли несколько онлайн-платежей по одному заказу? +8. Требования к хостингу в РФ и политике ПДн? +9. Кто предоставляет макеты и когда? +10. Нужен ли SEO-трафик с поисковиков (влияет на SSR и приоритет фазы 3)? diff --git a/docs/openapi-1c-inbound.yaml b/docs/openapi-1c-inbound.yaml new file mode 100644 index 0000000..46ddbaf --- /dev/null +++ b/docs/openapi-1c-inbound.yaml @@ -0,0 +1,497 @@ +openapi: 3.0.3 +info: + title: HOMM — Integration API (1C → site) + version: 1.0.0 + description: | + Контракт API, которое реализует сайт HOMM и вызывает сторона 1С. + + Аутентификация: заголовок `X-Integration-Token` (или + `Authorization: Bearer `). Значение задаётся переменной окружения + `INTEGRATION_API_TOKEN`. + + Все суммы передаются строками с двумя знаками после запятой, даты — ISO 8601 + с часовым поясом. +servers: + - url: https://shop.example.com/api/v1/integration/1c + description: Production + - url: http://localhost:8000/api/v1/integration/1c + description: Local development +security: + - IntegrationToken: [] +tags: + - name: health + description: Проверка доступности + - name: catalog + description: Синхронизация каталога + - name: orders + description: Заказы + - name: customers + description: Клиенты и бонусы +paths: + /health/: + get: + tags: [health] + summary: Проверка доступности интеграционного API + security: [] + responses: + '200': + description: Сервис доступен + content: + application/json: + schema: + type: object + properties: + status: + type: string + example: ok + time: + type: string + format: date-time + /catalog/sync/: + post: + tags: [catalog] + summary: Пакетная синхронизация каталога + description: | + Применяет пакет категорий, товаров, цен, остатков и изображений. + Идемпотентно по `external_id`. Удаление — мягкое (`is_active=false`). + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CatalogSyncRequest' + responses: + '200': + description: Пакет применён + content: + application/json: + schema: + $ref: '#/components/schemas/CatalogSyncResponse' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + /orders/pending/: + get: + tags: [orders] + summary: Заказы, ожидающие подтверждения 1С + description: | + Возвращает заказы без `external_id`, кроме отменённых. 1С может + использовать этот метод вместо push-уведомлений. + responses: + '200': + description: Список заказов + content: + application/json: + schema: + type: object + properties: + orders: + type: array + items: + $ref: '#/components/schemas/PendingOrder' + '401': + $ref: '#/components/responses/Unauthorized' + /orders/{number}/status/: + post: + tags: [orders] + summary: Обновить статус заказа + parameters: + - $ref: '#/components/parameters/OrderNumber' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/OrderStatusRequest' + responses: + '200': + description: Статус обновлён + content: + application/json: + schema: + type: object + properties: + status: + type: string + example: ok + order: + type: string + example: HOMM-20261106-ABC123 + order_status: + type: string + enum: [new, processing, delivering, completed, cancelled] + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '404': + $ref: '#/components/responses/NotFound' + /orders/{number}/ack/: + post: + tags: [orders] + summary: Подтвердить приём заказа + description: Сохраняет номер заказа в 1С (`external_id`) и время синхронизации. + parameters: + - $ref: '#/components/parameters/OrderNumber' + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [external_id] + properties: + external_id: + type: string + maxLength: 64 + description: Номер/ID заказа в 1С + responses: + '200': + description: Подтверждено + content: + application/json: + schema: + type: object + properties: + status: + type: string + example: ok + '401': + $ref: '#/components/responses/Unauthorized' + '404': + $ref: '#/components/responses/NotFound' + /customers/bonus/: + post: + tags: [customers] + summary: Начислить или списать бонусы + description: | + Положительная сумма — начисление, отрицательная — списание. + Клиент ищется по нормализованному телефону. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/BonusRequest' + responses: + '200': + description: Операция применена + content: + application/json: + schema: + type: object + properties: + status: + type: string + example: ok + phone: + type: string + example: '+79991234567' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '404': + $ref: '#/components/responses/NotFound' +components: + securitySchemes: + IntegrationToken: + type: apiKey + in: header + name: X-Integration-Token + parameters: + OrderNumber: + name: number + in: path + required: true + schema: + type: string + example: HOMM-20261106-ABC123 + responses: + BadRequest: + description: Ошибка валидации или применения пакета + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + Unauthorized: + description: Неверный или отсутствующий токен + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + NotFound: + description: Объект не найден + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + schemas: + Error: + type: object + properties: + error: + type: object + properties: + code: + type: string + message: + type: string + details: + type: object + additionalProperties: true + CategoryPayload: + type: object + required: [external_id, name] + properties: + external_id: + type: string + maxLength: 64 + parent_external_id: + type: string + maxLength: 64 + nullable: true + name: + type: string + maxLength: 255 + slug: + type: string + maxLength: 255 + description: + type: string + image_url: + type: string + format: uri + is_active: + type: boolean + default: true + sort_order: + type: integer + default: 0 + ProductImagePayload: + type: object + required: [url] + properties: + url: + type: string + format: uri + maxLength: 1000 + alt: + type: string + maxLength: 255 + sort_order: + type: integer + default: 0 + is_main: + type: boolean + default: false + ProductPayload: + type: object + required: [external_id, sku, name, price] + properties: + external_id: + type: string + maxLength: 64 + sku: + type: string + maxLength: 64 + name: + type: string + maxLength: 500 + slug: + type: string + maxLength: 500 + category_external_id: + type: string + maxLength: 64 + nullable: true + brand: + type: string + maxLength: 255 + short_description: + type: string + description: + type: string + price: + type: string + example: '49990.00' + old_price: + type: string + nullable: true + example: '59990.00' + stock: + type: integer + default: 0 + stock_status: + type: string + enum: [in_stock, preorder, out_of_stock] + is_hit: + type: boolean + default: false + is_new: + type: boolean + default: false + is_active: + type: boolean + default: true + attributes: + type: object + additionalProperties: true + images: + type: array + items: + $ref: '#/components/schemas/ProductImagePayload' + external_updated_at: + type: string + format: date-time + nullable: true + CatalogSyncRequest: + type: object + properties: + sync_id: + type: string + maxLength: 64 + description: Идентификатор пакета на стороне 1С + categories: + type: array + items: + $ref: '#/components/schemas/CategoryPayload' + products: + type: array + items: + $ref: '#/components/schemas/ProductPayload' + deleted_product_external_ids: + type: array + items: + type: string + deleted_category_external_ids: + type: array + items: + type: string + CatalogSyncResponse: + type: object + properties: + status: + type: string + example: ok + sync_id: + type: string + stats: + type: object + properties: + categories_created: + type: integer + categories_updated: + type: integer + products_created: + type: integer + products_updated: + type: integer + products_deleted: + type: integer + categories_deleted: + type: integer + images_replaced: + type: integer + OrderStatusRequest: + type: object + required: [status] + properties: + status: + type: string + description: Название статуса в 1С или код + example: Выполнен + comment: + type: string + changed_at: + type: string + format: date-time + external_id: + type: string + maxLength: 64 + BonusRequest: + type: object + required: [amount] + properties: + phone: + type: string + example: '+79991234567' + external_customer_id: + type: string + maxLength: 64 + description: Зарезервировано; в MVP требуется phone + amount: + type: string + description: Положительное — начисление, отрицательное — списание + example: '500.00' + reason: + type: string + enum: [accrual, spend, refund, adjustment] + default: accrual + comment: + type: string + order_number: + type: string + maxLength: 32 + PendingOrderItem: + type: object + properties: + sku: + type: string + product_external_id: + type: string + name: + type: string + price: + type: string + quantity: + type: integer + total: + type: string + PendingOrder: + type: object + properties: + number: + type: string + external_id: + type: string + status: + type: string + payment_status: + type: string + customer_name: + type: string + phone: + type: string + email: + type: string + delivery_method: + type: string + delivery_address: + type: string + delivery_cost: + type: string + comment: + type: string + subtotal: + type: string + discount_total: + type: string + bonus_applied: + type: string + certificate_applied: + type: string + total: + type: string + promo_code: + type: string + certificate_code: + type: string + created_at: + type: string + format: date-time + items: + type: array + items: + $ref: '#/components/schemas/PendingOrderItem' diff --git a/docs/openapi-1c-outbound.yaml b/docs/openapi-1c-outbound.yaml new file mode 100644 index 0000000..48bcbc5 --- /dev/null +++ b/docs/openapi-1c-outbound.yaml @@ -0,0 +1,367 @@ +openapi: 3.0.3 +info: + title: HOMM — 1C HTTP service (site → 1C) + version: 1.0.0 + description: | + Контракт, который должна реализовать сторона 1С. + + Сайт вызывает эти методы через `apps.integration.client.OneCClient`. + Базовый URL задаётся переменной `ONEC_BASE_URL`, учётные данные — + `ONEC_USERNAME` / `ONEC_PASSWORD` (HTTP Basic). + + Рекомендуемая реализация на стороне 1С — HTTP-сервис + `homm` с методами `catalog/changes`, `orders`, `orders/{id}/status`, + `customers`. +servers: + - url: http://1c.example.com/homm/hs/homm + description: HTTP-сервис 1С +security: + - BasicAuth: [] +tags: + - name: catalog + - name: orders + - name: customers +paths: + /catalog/changes: + get: + tags: [catalog] + summary: Изменения каталога с указанного момента + parameters: + - name: since + in: query + required: false + description: Вернуть изменения после этой даты (ISO 8601) + schema: + type: string + format: date-time + responses: + '200': + description: Пакет изменений + content: + application/json: + schema: + $ref: '#/components/schemas/CatalogBatch' + '401': + $ref: '#/components/responses/Unauthorized' + /orders: + post: + tags: [orders] + summary: Создать заказ клиента в 1С + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/OrderPush' + responses: + '200': + description: Заказ создан + content: + application/json: + schema: + type: object + properties: + external_id: + type: string + description: ID заказа в 1С + number: + type: string + description: Номер заказа в 1С + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + /orders/{externalId}/status: + get: + tags: [orders] + summary: Получить статус заказа + parameters: + - $ref: '#/components/parameters/ExternalId' + responses: + '200': + description: Статус заказа + content: + application/json: + schema: + $ref: '#/components/schemas/OrderStatus' + '401': + $ref: '#/components/responses/Unauthorized' + '404': + $ref: '#/components/responses/NotFound' + post: + tags: [orders] + summary: Передать статус заказа на сайт + description: | + Используется, если 1С инициирует обмен статусами. Сайт также умеет + забирать статусы через GET. + parameters: + - $ref: '#/components/parameters/ExternalId' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/OrderStatus' + responses: + '200': + description: Принято + '401': + $ref: '#/components/responses/Unauthorized' + /customers: + post: + tags: [customers] + summary: Создать или обновить клиента + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CustomerPush' + responses: + '200': + description: Клиент создан/обновлён + content: + application/json: + schema: + type: object + properties: + external_id: + type: string + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' +components: + securitySchemes: + BasicAuth: + type: http + scheme: basic + parameters: + ExternalId: + name: externalId + in: path + required: true + schema: + type: string + responses: + BadRequest: + description: Ошибка валидации + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + Unauthorized: + description: Неверные учётные данные + NotFound: + description: Объект не найден + schemas: + Error: + type: object + properties: + error: + type: object + properties: + code: + type: string + message: + type: string + CatalogBatch: + type: object + properties: + sync_id: + type: string + categories: + type: array + items: + $ref: '#/components/schemas/Category' + products: + type: array + items: + $ref: '#/components/schemas/Product' + deleted_product_external_ids: + type: array + items: + type: string + deleted_category_external_ids: + type: array + items: + type: string + Category: + type: object + required: [external_id, name] + properties: + external_id: + type: string + parent_external_id: + type: string + nullable: true + name: + type: string + slug: + type: string + description: + type: string + image_url: + type: string + format: uri + is_active: + type: boolean + sort_order: + type: integer + Product: + type: object + required: [external_id, sku, name, price] + properties: + external_id: + type: string + sku: + type: string + name: + type: string + slug: + type: string + category_external_id: + type: string + nullable: true + brand: + type: string + short_description: + type: string + description: + type: string + price: + type: string + old_price: + type: string + nullable: true + stock: + type: integer + stock_status: + type: string + enum: [in_stock, preorder, out_of_stock] + is_hit: + type: boolean + is_new: + type: boolean + is_active: + type: boolean + attributes: + type: object + additionalProperties: true + images: + type: array + items: + $ref: '#/components/schemas/ProductImage' + external_updated_at: + type: string + format: date-time + nullable: true + ProductImage: + type: object + required: [url] + properties: + url: + type: string + format: uri + alt: + type: string + sort_order: + type: integer + is_main: + type: boolean + OrderPush: + type: object + required: [number, customer, items, totals] + properties: + number: + type: string + created_at: + type: string + format: date-time + customer: + $ref: '#/components/schemas/Customer' + delivery: + type: object + properties: + method: + type: string + address: + type: string + cost: + type: string + items: + type: array + items: + $ref: '#/components/schemas/OrderItem' + totals: + type: object + properties: + subtotal: + type: string + discount: + type: string + bonus: + type: string + certificate: + type: string + delivery: + type: string + total: + type: string + payment: + type: object + properties: + status: + type: string + promo_code: + type: string + certificate_code: + type: string + Customer: + type: object + properties: + name: + type: string + phone: + type: string + email: + type: string + CustomerPush: + type: object + required: [phone] + properties: + phone: + type: string + email: + type: string + name: + type: string + OrderItem: + type: object + properties: + sku: + type: string + external_id: + type: string + name: + type: string + price: + type: string + quantity: + type: integer + total: + type: string + OrderStatus: + type: object + required: [status] + properties: + status: + type: string + example: Выполнен + comment: + type: string + changed_at: + type: string + format: date-time + external_id: + type: string diff --git a/docs/openapi-site.yaml b/docs/openapi-site.yaml new file mode 100644 index 0000000..ebc3498 --- /dev/null +++ b/docs/openapi-site.yaml @@ -0,0 +1,2925 @@ +openapi: 3.0.3 +info: + title: HOMM Store API + version: 1.0.0 + description: Public storefront API and the integration API used by 1C. See docs/architecture.md + for the exchange design. +paths: + /api/v1/auth/otp/request/: + post: + operationId: api_v1_auth_otp_request_create + tags: + - api + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OtpRequestRequest' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/OtpRequestRequest' + multipart/form-data: + schema: + $ref: '#/components/schemas/OtpRequestRequest' + required: true + security: + - jwtAuth: [] + - {} + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/OtpRequest' + description: '' + /api/v1/auth/otp/verify/: + post: + operationId: api_v1_auth_otp_verify_create + tags: + - api + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OtpVerifyRequest' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/OtpVerifyRequest' + multipart/form-data: + schema: + $ref: '#/components/schemas/OtpVerifyRequest' + required: true + security: + - jwtAuth: [] + - {} + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/OtpVerify' + description: '' + /api/v1/auth/token/: + post: + operationId: api_v1_auth_token_create + description: |- + Takes a set of user credentials and returns an access and refresh JSON web + token pair to prove the authentication of those credentials. + tags: + - api + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/TokenObtainPairRequest' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/TokenObtainPairRequest' + multipart/form-data: + schema: + $ref: '#/components/schemas/TokenObtainPairRequest' + required: true + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/TokenObtainPair' + description: '' + /api/v1/auth/token/refresh/: + post: + operationId: api_v1_auth_token_refresh_create + description: |- + Takes a refresh type JSON web token and returns an access type JSON web + token if the refresh token is valid. + tags: + - api + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/TokenRefreshRequest' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/TokenRefreshRequest' + multipart/form-data: + schema: + $ref: '#/components/schemas/TokenRefreshRequest' + required: true + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/TokenRefresh' + description: '' + /api/v1/auth/me/: + get: + operationId: api_v1_auth_me_retrieve + tags: + - api + security: + - jwtAuth: [] + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: '' + patch: + operationId: api_v1_auth_me_partial_update + tags: + - api + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PatchedUserRequest' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/PatchedUserRequest' + multipart/form-data: + schema: + $ref: '#/components/schemas/PatchedUserRequest' + security: + - jwtAuth: [] + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: '' + /api/v1/auth/password/: + post: + operationId: api_v1_auth_password_create + tags: + - api + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PasswordSetRequest' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/PasswordSetRequest' + multipart/form-data: + schema: + $ref: '#/components/schemas/PasswordSetRequest' + required: true + security: + - jwtAuth: [] + responses: + '200': + description: No response body + /api/v1/auth/addresses/: + get: + operationId: api_v1_auth_addresses_list + parameters: + - name: ordering + required: false + in: query + description: Which field to use when ordering the results. + schema: + type: string + - name: page + required: false + in: query + description: A page number within the paginated result set. + schema: + type: integer + - name: page_size + required: false + in: query + description: Number of results to return per page. + schema: + type: integer + - name: search + required: false + in: query + description: A search term. + schema: + type: string + tags: + - api + security: + - jwtAuth: [] + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/PaginatedAddressList' + description: '' + post: + operationId: api_v1_auth_addresses_create + tags: + - api + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/AddressRequest' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/AddressRequest' + multipart/form-data: + schema: + $ref: '#/components/schemas/AddressRequest' + required: true + security: + - jwtAuth: [] + responses: + '201': + content: + application/json: + schema: + $ref: '#/components/schemas/Address' + description: '' + /api/v1/auth/addresses/{id}/: + put: + operationId: api_v1_auth_addresses_update + parameters: + - in: path + name: id + schema: + type: integer + description: A unique integer value identifying this адрес доставки. + required: true + tags: + - api + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/AddressRequest' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/AddressRequest' + multipart/form-data: + schema: + $ref: '#/components/schemas/AddressRequest' + required: true + security: + - jwtAuth: [] + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/Address' + description: '' + get: + operationId: api_v1_auth_addresses_retrieve + parameters: + - in: path + name: id + schema: + type: integer + description: A unique integer value identifying this адрес доставки. + required: true + tags: + - api + security: + - jwtAuth: [] + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/Address' + description: '' + patch: + operationId: api_v1_auth_addresses_partial_update + parameters: + - in: path + name: id + schema: + type: integer + description: A unique integer value identifying this адрес доставки. + required: true + tags: + - api + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PatchedAddressRequest' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/PatchedAddressRequest' + multipart/form-data: + schema: + $ref: '#/components/schemas/PatchedAddressRequest' + security: + - jwtAuth: [] + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/Address' + description: '' + delete: + operationId: api_v1_auth_addresses_destroy + parameters: + - in: path + name: id + schema: + type: integer + description: A unique integer value identifying this адрес доставки. + required: true + tags: + - api + security: + - jwtAuth: [] + responses: + '204': + description: No response body + /api/v1/catalog/categories/: + get: + operationId: api_v1_catalog_categories_list + parameters: + - name: ordering + required: false + in: query + description: Which field to use when ordering the results. + schema: + type: string + - name: search + required: false + in: query + description: A search term. + schema: + type: string + tags: + - api + security: + - jwtAuth: [] + - {} + responses: + '200': + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Category' + description: '' + /api/v1/catalog/categories/{slug}/: + get: + operationId: api_v1_catalog_categories_retrieve + parameters: + - in: path + name: slug + schema: + type: string + required: true + tags: + - api + security: + - jwtAuth: [] + - {} + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/Category' + description: '' + /api/v1/catalog/products/: + get: + operationId: api_v1_catalog_products_list + parameters: + - in: query + name: brand + schema: + type: string + - in: query + name: category + schema: + type: string + - in: query + name: category_id + schema: + type: number + - in: query + name: in_stock + schema: + type: boolean + - in: query + name: is_hit + schema: + type: boolean + - in: query + name: is_new + schema: + type: boolean + - name: ordering + required: false + in: query + description: Which field to use when ordering the results. + schema: + type: string + - name: page + required: false + in: query + description: A page number within the paginated result set. + schema: + type: integer + - name: page_size + required: false + in: query + description: Number of results to return per page. + schema: + type: integer + - in: query + name: price_max + schema: + type: number + - in: query + name: price_min + schema: + type: number + - name: search + required: false + in: query + description: A search term. + schema: + type: string + tags: + - api + security: + - jwtAuth: [] + - {} + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/PaginatedProductListList' + description: '' + /api/v1/catalog/products/hits/: + get: + operationId: api_v1_catalog_products_hits_retrieve + tags: + - api + security: + - jwtAuth: [] + - {} + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ProductList' + description: '' + /api/v1/catalog/products/new/: + get: + operationId: api_v1_catalog_products_new_retrieve + tags: + - api + security: + - jwtAuth: [] + - {} + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ProductList' + description: '' + /api/v1/catalog/products/{slug}/: + get: + operationId: api_v1_catalog_products_retrieve + parameters: + - in: path + name: slug + schema: + type: string + required: true + tags: + - api + security: + - jwtAuth: [] + - {} + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ProductDetail' + description: '' + /api/v1/catalog/products/{slug}/related/: + get: + operationId: api_v1_catalog_products_related_retrieve + parameters: + - in: path + name: slug + schema: + type: string + required: true + tags: + - api + security: + - jwtAuth: [] + - {} + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ProductList' + description: '' + /api/v1/orders/: + get: + operationId: api_v1_orders_list + parameters: + - name: ordering + required: false + in: query + description: Which field to use when ordering the results. + schema: + type: string + - name: page + required: false + in: query + description: A page number within the paginated result set. + schema: + type: integer + - name: page_size + required: false + in: query + description: Number of results to return per page. + schema: + type: integer + - name: search + required: false + in: query + description: A search term. + schema: + type: string + tags: + - api + security: + - jwtAuth: [] + - {} + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/PaginatedOrderListList' + description: '' + post: + operationId: api_v1_orders_create + tags: + - api + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OrderCreateRequest' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/OrderCreateRequest' + multipart/form-data: + schema: + $ref: '#/components/schemas/OrderCreateRequest' + required: true + security: + - jwtAuth: [] + - {} + responses: + '201': + content: + application/json: + schema: + $ref: '#/components/schemas/OrderCreate' + description: '' + /api/v1/orders/{id}/: + get: + operationId: api_v1_orders_retrieve + parameters: + - in: path + name: id + schema: + type: integer + description: A unique integer value identifying this заказ. + required: true + tags: + - api + security: + - jwtAuth: [] + - {} + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/OrderDetail' + description: '' + /api/v1/orders/{id}/cancel/: + post: + operationId: api_v1_orders_cancel_create + parameters: + - in: path + name: id + schema: + type: integer + description: A unique integer value identifying this заказ. + required: true + tags: + - api + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OrderListRequest' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/OrderListRequest' + multipart/form-data: + schema: + $ref: '#/components/schemas/OrderListRequest' + security: + - jwtAuth: [] + - {} + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/OrderList' + description: '' + /api/v1/loyalty/bonus/: + get: + operationId: api_v1_loyalty_bonus_retrieve + tags: + - api + security: + - jwtAuth: [] + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/BonusAccount' + description: '' + /api/v1/loyalty/promo/validate/: + post: + operationId: api_v1_loyalty_promo_validate_create + tags: + - api + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PromoValidateRequest' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/PromoValidateRequest' + multipart/form-data: + schema: + $ref: '#/components/schemas/PromoValidateRequest' + required: true + security: + - jwtAuth: [] + - {} + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/PromoValidate' + description: '' + /api/v1/loyalty/certificate/validate/: + post: + operationId: api_v1_loyalty_certificate_validate_create + tags: + - api + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/CertificateValidateRequest' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/CertificateValidateRequest' + multipart/form-data: + schema: + $ref: '#/components/schemas/CertificateValidateRequest' + required: true + security: + - jwtAuth: [] + - {} + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/CertificateValidate' + description: '' + /api/v1/loyalty/certificates/: + get: + operationId: api_v1_loyalty_certificates_retrieve + tags: + - api + security: + - jwtAuth: [] + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/GiftCertificate' + description: '' + /api/v1/content/settings/: + get: + operationId: api_v1_content_settings_retrieve + description: Public store settings used by the storefront. + tags: + - api + security: + - jwtAuth: [] + - {} + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/SiteSettings' + description: '' + /api/v1/content/pages/: + get: + operationId: api_v1_content_pages_list + parameters: + - name: ordering + required: false + in: query + description: Which field to use when ordering the results. + schema: + type: string + - name: search + required: false + in: query + description: A search term. + schema: + type: string + tags: + - api + security: + - jwtAuth: [] + - {} + responses: + '200': + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/StaticPage' + description: '' + /api/v1/content/pages/{slug}/: + get: + operationId: api_v1_content_pages_retrieve + parameters: + - in: path + name: slug + schema: + type: string + title: Адрес + required: true + tags: + - api + security: + - jwtAuth: [] + - {} + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/StaticPage' + description: '' + /api/v1/content/banners/: + get: + operationId: api_v1_content_banners_list + parameters: + - name: ordering + required: false + in: query + description: Which field to use when ordering the results. + schema: + type: string + - name: search + required: false + in: query + description: A search term. + schema: + type: string + tags: + - api + security: + - jwtAuth: [] + - {} + responses: + '200': + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Banner' + description: '' + /api/v1/content/banners/{id}/: + get: + operationId: api_v1_content_banners_retrieve + parameters: + - in: path + name: id + schema: + type: integer + description: A unique integer value identifying this баннер. + required: true + tags: + - api + security: + - jwtAuth: [] + - {} + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/Banner' + description: '' + /api/v1/payments/webhook/yookassa/: + post: + operationId: api_v1_payments_webhook_yookassa_create + description: |- + Receives ЮKassa notifications. + + TODO: verify the source IP / signature before applying the event. + tags: + - api + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PaymentWebhookRequest' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/PaymentWebhookRequest' + multipart/form-data: + schema: + $ref: '#/components/schemas/PaymentWebhookRequest' + required: true + security: + - {} + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/PaymentWebhook' + description: '' + /api/v1/integration/1c/health/: + get: + operationId: api_v1_integration_1c_health_retrieve + tags: + - api + security: + - IntegrationToken: [] + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/Health' + description: '' + /api/v1/integration/1c/catalog/sync/: + post: + operationId: api_v1_integration_1c_catalog_sync_create + tags: + - api + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/CatalogSyncRequest' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/CatalogSyncRequest' + multipart/form-data: + schema: + $ref: '#/components/schemas/CatalogSyncRequest' + security: + - IntegrationToken: [] + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/CatalogSync' + description: '' + /api/v1/integration/1c/orders/pending/: + get: + operationId: api_v1_integration_1c_orders_pending_retrieve + tags: + - api + security: + - IntegrationToken: [] + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/PendingOrder' + description: '' + /api/v1/integration/1c/orders/{number}/status/: + post: + operationId: api_v1_integration_1c_orders_status_create + parameters: + - in: path + name: number + schema: + type: string + required: true + tags: + - api + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OrderStatusPayloadRequest' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/OrderStatusPayloadRequest' + multipart/form-data: + schema: + $ref: '#/components/schemas/OrderStatusPayloadRequest' + required: true + security: + - IntegrationToken: [] + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/OrderStatusPayload' + description: '' + /api/v1/integration/1c/orders/{number}/ack/: + post: + operationId: api_v1_integration_1c_orders_ack_create + parameters: + - in: path + name: number + schema: + type: string + required: true + tags: + - api + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OrderAckRequest' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/OrderAckRequest' + multipart/form-data: + schema: + $ref: '#/components/schemas/OrderAckRequest' + required: true + security: + - IntegrationToken: [] + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/OrderAck' + description: '' + /api/v1/integration/1c/customers/bonus/: + post: + operationId: api_v1_integration_1c_customers_bonus_create + tags: + - api + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/BonusPayloadRequest' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/BonusPayloadRequest' + multipart/form-data: + schema: + $ref: '#/components/schemas/BonusPayloadRequest' + required: true + security: + - IntegrationToken: [] + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/BonusPayload' + description: '' + /api/v1/integration/1c/sync/run/: + post: + operationId: api_v1_integration_1c_sync_run_create + description: Admin-triggered catalog sync (JWT + staff). + tags: + - api + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ManualSyncResponseRequest' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/ManualSyncResponseRequest' + multipart/form-data: + schema: + $ref: '#/components/schemas/ManualSyncResponseRequest' + required: true + security: + - jwtAuth: [] + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ManualSyncResponse' + description: '' +components: + schemas: + Address: + type: object + properties: + id: + type: integer + readOnly: true + title: + type: string + title: Название + maxLength: 64 + city: + type: string + title: Город + maxLength: 128 + street: + type: string + title: Улица + maxLength: 255 + house: + type: string + title: Дом + maxLength: 32 + apartment: + type: string + title: Квартира/офис + maxLength: 32 + postal_code: + type: string + title: Индекс + maxLength: 16 + entrance: + type: string + title: Подъезд + maxLength: 16 + floor: + type: string + title: Этаж + maxLength: 16 + intercom: + type: string + title: Домофон + maxLength: 32 + is_default: + type: boolean + title: По умолчанию + created_at: + type: string + format: date-time + readOnly: true + updated_at: + type: string + format: date-time + readOnly: true + required: + - city + - created_at + - house + - id + - street + - updated_at + AddressRequest: + type: object + properties: + title: + type: string + minLength: 1 + title: Название + maxLength: 64 + city: + type: string + minLength: 1 + title: Город + maxLength: 128 + street: + type: string + minLength: 1 + title: Улица + maxLength: 255 + house: + type: string + minLength: 1 + title: Дом + maxLength: 32 + apartment: + type: string + title: Квартира/офис + maxLength: 32 + postal_code: + type: string + title: Индекс + maxLength: 16 + entrance: + type: string + title: Подъезд + maxLength: 16 + floor: + type: string + title: Этаж + maxLength: 16 + intercom: + type: string + title: Домофон + maxLength: 32 + is_default: + type: boolean + title: По умолчанию + required: + - city + - house + - street + Banner: + type: object + properties: + id: + type: integer + readOnly: true + title: + type: string + title: Название + maxLength: 255 + image_url: + type: string + format: uri + title: Изображение + maxLength: 1000 + link_url: + type: string + format: uri + title: Ссылка + maxLength: 1000 + position: + allOf: + - $ref: '#/components/schemas/PositionEnum' + title: Позиция + position_display: + type: string + readOnly: true + sort_order: + type: integer + title: Порядок + starts_at: + type: string + format: date-time + nullable: true + title: Начало показа + ends_at: + type: string + format: date-time + nullable: true + title: Конец показа + required: + - id + - image_url + - position_display + - title + BonusAccount: + type: object + properties: + balance: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + transactions: + type: array + items: + $ref: '#/components/schemas/BonusTransaction' + required: + - balance + - transactions + BonusPayload: + type: object + properties: + phone: + type: string + maxLength: 20 + external_customer_id: + type: string + maxLength: 64 + amount: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + reason: + allOf: + - $ref: '#/components/schemas/BonusPayloadReasonEnum' + default: accrual + comment: + type: string + order_number: + type: string + maxLength: 32 + required: + - amount + BonusPayloadReasonEnum: + enum: + - accrual + - spend + - refund + - adjustment + type: string + description: |- + * `accrual` - accrual + * `spend` - spend + * `refund` - refund + * `adjustment` - adjustment + BonusPayloadRequest: + type: object + properties: + phone: + type: string + maxLength: 20 + external_customer_id: + type: string + maxLength: 64 + amount: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + reason: + allOf: + - $ref: '#/components/schemas/BonusPayloadReasonEnum' + default: accrual + comment: + type: string + order_number: + type: string + maxLength: 32 + required: + - amount + BonusReasonEnum: + enum: + - accrual + - spend + - refund + - adjustment + type: string + description: |- + * `accrual` - Начисление + * `spend` - Списание + * `refund` - Возврат + * `adjustment` - Корректировка + BonusTransaction: + type: object + properties: + id: + type: integer + readOnly: true + amount: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + reason: + $ref: '#/components/schemas/BonusReasonEnum' + reason_display: + type: string + readOnly: true + comment: + type: string + maxLength: 255 + created_at: + type: string + format: date-time + readOnly: true + required: + - amount + - created_at + - id + - reason + - reason_display + CatalogSync: + type: object + properties: + sync_id: + type: string + maxLength: 64 + categories: + type: array + items: + $ref: '#/components/schemas/CategoryPayload' + products: + type: array + items: + $ref: '#/components/schemas/ProductPayload' + deleted_product_external_ids: + type: array + items: + type: string + maxLength: 64 + deleted_category_external_ids: + type: array + items: + type: string + maxLength: 64 + CatalogSyncRequest: + type: object + properties: + sync_id: + type: string + maxLength: 64 + categories: + type: array + items: + $ref: '#/components/schemas/CategoryPayloadRequest' + products: + type: array + items: + $ref: '#/components/schemas/ProductPayloadRequest' + deleted_product_external_ids: + type: array + items: + type: string + minLength: 1 + maxLength: 64 + deleted_category_external_ids: + type: array + items: + type: string + minLength: 1 + maxLength: 64 + Category: + type: object + properties: + id: + type: integer + readOnly: true + name: + type: string + maxLength: 255 + slug: + type: string + maxLength: 255 + pattern: ^[-a-zA-Z0-9_]+$ + parent: + type: integer + nullable: true + image_url: + type: string + format: uri + maxLength: 1000 + sort_order: + type: integer + required: + - id + - name + - slug + CategoryPayload: + type: object + properties: + external_id: + type: string + maxLength: 64 + parent_external_id: + type: string + nullable: true + maxLength: 64 + name: + type: string + maxLength: 255 + slug: + type: string + maxLength: 255 + description: + type: string + image_url: + type: string + format: uri + is_active: + type: boolean + default: true + sort_order: + type: integer + default: 0 + required: + - external_id + - name + CategoryPayloadRequest: + type: object + properties: + external_id: + type: string + minLength: 1 + maxLength: 64 + parent_external_id: + type: string + nullable: true + maxLength: 64 + name: + type: string + minLength: 1 + maxLength: 255 + slug: + type: string + maxLength: 255 + description: + type: string + image_url: + type: string + format: uri + is_active: + type: boolean + default: true + sort_order: + type: integer + default: 0 + required: + - external_id + - name + CertificateStatusEnum: + enum: + - issued + - active + - used + - expired + type: string + description: |- + * `issued` - Выпущен + * `active` - Активен + * `used` - Использован + * `expired` - Истёк + CertificateValidate: + type: object + properties: + code: + type: string + maxLength: 64 + amount: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + required: + - amount + - code + CertificateValidateRequest: + type: object + properties: + code: + type: string + minLength: 1 + maxLength: 64 + amount: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + required: + - amount + - code + GiftCertificate: + type: object + properties: + id: + type: integer + readOnly: true + code: + type: string + maxLength: 64 + nominal: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + balance: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + status: + $ref: '#/components/schemas/CertificateStatusEnum' + status_display: + type: string + readOnly: true + expires_at: + type: string + format: date-time + nullable: true + created_at: + type: string + format: date-time + readOnly: true + required: + - balance + - code + - created_at + - id + - nominal + - status_display + Health: + type: object + properties: + status: + type: string + time: + type: string + format: date-time + required: + - status + - time + ManualSyncResponse: + type: object + properties: + status: + type: string + task_id: + type: string + required: + - status + - task_id + ManualSyncResponseRequest: + type: object + properties: + status: + type: string + minLength: 1 + task_id: + type: string + minLength: 1 + required: + - status + - task_id + OrderAck: + type: object + properties: + external_id: + type: string + maxLength: 64 + required: + - external_id + OrderAckRequest: + type: object + properties: + external_id: + type: string + minLength: 1 + maxLength: 64 + required: + - external_id + OrderCreate: + type: object + properties: + items: + type: array + items: + $ref: '#/components/schemas/OrderItemInput' + customer_name: + type: string + maxLength: 255 + phone: + type: string + maxLength: 20 + email: + type: string + format: email + delivery_method: + type: string + maxLength: 64 + delivery_address: + type: string + delivery_cost: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + default: '0.00' + comment: + type: string + promo_code: + type: string + certificate_code: + type: string + bonus_amount: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + default: '0.00' + payment_method: + $ref: '#/components/schemas/PaymentMethodEnum' + required: + - customer_name + - items + - phone + OrderCreateRequest: + type: object + properties: + items: + type: array + items: + $ref: '#/components/schemas/OrderItemInputRequest' + customer_name: + type: string + minLength: 1 + maxLength: 255 + phone: + type: string + minLength: 1 + maxLength: 20 + email: + type: string + format: email + delivery_method: + type: string + maxLength: 64 + delivery_address: + type: string + delivery_cost: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + default: '0.00' + comment: + type: string + promo_code: + type: string + certificate_code: + type: string + bonus_amount: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + default: '0.00' + payment_method: + $ref: '#/components/schemas/PaymentMethodEnum' + required: + - customer_name + - items + - phone + OrderDetail: + type: object + properties: + id: + type: integer + readOnly: true + number: + type: string + readOnly: true + status: + $ref: '#/components/schemas/OrderStatusEnum' + status_display: + type: string + readOnly: true + payment_status: + $ref: '#/components/schemas/OrderPaymentStatusEnum' + total: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + created_at: + type: string + format: date-time + readOnly: true + items: + type: array + items: + $ref: '#/components/schemas/OrderItem' + readOnly: true + customer_name: + type: string + maxLength: 255 + phone: + type: string + maxLength: 20 + email: + type: string + format: email + maxLength: 254 + delivery_method: + type: string + maxLength: 64 + delivery_address: + type: string + delivery_cost: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + comment: + type: string + subtotal: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + discount_total: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + bonus_applied: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + certificate_applied: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + promo_code: + type: string + maxLength: 64 + certificate_code: + type: string + maxLength: 64 + status_history: + type: array + items: + $ref: '#/components/schemas/OrderStatusHistory' + readOnly: true + payments: + type: array + items: + $ref: '#/components/schemas/Payment' + readOnly: true + required: + - created_at + - customer_name + - id + - items + - number + - payments + - phone + - status_display + - status_history + OrderItem: + type: object + properties: + id: + type: integer + readOnly: true + name: + type: string + maxLength: 500 + sku: + type: string + maxLength: 64 + price: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + quantity: + type: integer + total: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + required: + - id + - name + - price + - quantity + - sku + - total + OrderItemInput: + type: object + properties: + product_id: + type: integer + quantity: + type: integer + maximum: 999 + minimum: 1 + required: + - product_id + - quantity + OrderItemInputRequest: + type: object + properties: + product_id: + type: integer + quantity: + type: integer + maximum: 999 + minimum: 1 + required: + - product_id + - quantity + OrderItemRequest: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 500 + sku: + type: string + minLength: 1 + maxLength: 64 + price: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + quantity: + type: integer + total: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + required: + - name + - price + - quantity + - sku + - total + OrderList: + type: object + properties: + id: + type: integer + readOnly: true + number: + type: string + readOnly: true + status: + $ref: '#/components/schemas/OrderStatusEnum' + status_display: + type: string + readOnly: true + payment_status: + $ref: '#/components/schemas/OrderPaymentStatusEnum' + total: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + created_at: + type: string + format: date-time + readOnly: true + items: + type: array + items: + $ref: '#/components/schemas/OrderItem' + readOnly: true + required: + - created_at + - id + - items + - number + - status_display + OrderListRequest: + type: object + properties: + status: + $ref: '#/components/schemas/OrderStatusEnum' + payment_status: + $ref: '#/components/schemas/OrderPaymentStatusEnum' + total: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + OrderPaymentStatusEnum: + enum: + - pending + - partially_paid + - paid + - refunded + type: string + description: |- + * `pending` - Ожидает оплаты + * `partially_paid` - Частично оплачен + * `paid` - Оплачен + * `refunded` - Возвращён + OrderStatusEnum: + enum: + - new + - processing + - delivering + - completed + - cancelled + type: string + description: |- + * `new` - Новый + * `processing` - В обработке + * `delivering` - Доставляется + * `completed` - Выполнен + * `cancelled` - Отменён + OrderStatusHistory: + type: object + properties: + status: + $ref: '#/components/schemas/OrderStatusEnum' + status_display: + type: string + readOnly: true + comment: + type: string + source: + $ref: '#/components/schemas/SourceEnum' + created_at: + type: string + format: date-time + readOnly: true + required: + - created_at + - status + - status_display + OrderStatusPayload: + type: object + properties: + status: + type: string + maxLength: 64 + comment: + type: string + changed_at: + type: string + format: date-time + external_id: + type: string + maxLength: 64 + required: + - status + OrderStatusPayloadRequest: + type: object + properties: + status: + type: string + minLength: 1 + maxLength: 64 + comment: + type: string + changed_at: + type: string + format: date-time + external_id: + type: string + maxLength: 64 + required: + - status + OtpRequest: + type: object + properties: + phone: + type: string + maxLength: 20 + required: + - phone + OtpRequestRequest: + type: object + properties: + phone: + type: string + minLength: 1 + maxLength: 20 + required: + - phone + OtpVerify: + type: object + properties: + phone: + type: string + maxLength: 20 + code: + type: string + maxLength: 8 + required: + - code + - phone + OtpVerifyRequest: + type: object + properties: + phone: + type: string + minLength: 1 + maxLength: 20 + code: + type: string + minLength: 1 + maxLength: 8 + required: + - code + - phone + PaginatedAddressList: + type: object + required: + - count + - results + properties: + count: + type: integer + example: 123 + next: + type: string + nullable: true + format: uri + example: http://api.example.org/accounts/?page=4 + previous: + type: string + nullable: true + format: uri + example: http://api.example.org/accounts/?page=2 + results: + type: array + items: + $ref: '#/components/schemas/Address' + PaginatedOrderListList: + type: object + required: + - count + - results + properties: + count: + type: integer + example: 123 + next: + type: string + nullable: true + format: uri + example: http://api.example.org/accounts/?page=4 + previous: + type: string + nullable: true + format: uri + example: http://api.example.org/accounts/?page=2 + results: + type: array + items: + $ref: '#/components/schemas/OrderList' + PaginatedProductListList: + type: object + required: + - count + - results + properties: + count: + type: integer + example: 123 + next: + type: string + nullable: true + format: uri + example: http://api.example.org/accounts/?page=4 + previous: + type: string + nullable: true + format: uri + example: http://api.example.org/accounts/?page=2 + results: + type: array + items: + $ref: '#/components/schemas/ProductList' + PasswordSetRequest: + type: object + properties: + current_password: + type: string + writeOnly: true + new_password: + type: string + writeOnly: true + minLength: 8 + required: + - new_password + PatchedAddressRequest: + type: object + properties: + title: + type: string + minLength: 1 + title: Название + maxLength: 64 + city: + type: string + minLength: 1 + title: Город + maxLength: 128 + street: + type: string + minLength: 1 + title: Улица + maxLength: 255 + house: + type: string + minLength: 1 + title: Дом + maxLength: 32 + apartment: + type: string + title: Квартира/офис + maxLength: 32 + postal_code: + type: string + title: Индекс + maxLength: 16 + entrance: + type: string + title: Подъезд + maxLength: 16 + floor: + type: string + title: Этаж + maxLength: 16 + intercom: + type: string + title: Домофон + maxLength: 32 + is_default: + type: boolean + title: По умолчанию + PatchedUserRequest: + type: object + properties: + email: + type: string + format: email + nullable: true + maxLength: 254 + first_name: + type: string + title: Имя + maxLength: 150 + last_name: + type: string + title: Фамилия + maxLength: 150 + middle_name: + type: string + title: Отчество + maxLength: 150 + Payment: + type: object + properties: + id: + type: integer + readOnly: true + method: + $ref: '#/components/schemas/PaymentMethodEnum' + method_display: + type: string + readOnly: true + status: + $ref: '#/components/schemas/PaymentStatusEnum' + status_display: + type: string + readOnly: true + amount: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + provider: + type: string + maxLength: 32 + paid_at: + type: string + format: date-time + nullable: true + created_at: + type: string + format: date-time + readOnly: true + required: + - created_at + - id + - method + - method_display + - status_display + PaymentMethodEnum: + enum: + - card + - sbp + - mir_pay + - cash + - installment + - split + type: string + description: |- + * `card` - card + * `sbp` - sbp + * `mir_pay` - mir_pay + * `cash` - cash + * `installment` - installment + * `split` - split + PaymentStatusEnum: + enum: + - pending + - succeeded + - failed + - refunded + - cancelled + type: string + description: |- + * `pending` - Ожидает + * `succeeded` - Успешно + * `failed` - Ошибка + * `refunded` - Возвращён + * `cancelled` - Отменён + PaymentWebhook: + type: object + properties: + event: + type: string + object: + type: object + additionalProperties: {} + required: + - event + - object + PaymentWebhookRequest: + type: object + properties: + event: + type: string + minLength: 1 + object: + type: object + additionalProperties: {} + required: + - event + - object + PendingOrder: + type: object + properties: + number: + type: string + readOnly: true + external_id: + type: string + maxLength: 64 + status: + $ref: '#/components/schemas/OrderStatusEnum' + payment_status: + $ref: '#/components/schemas/OrderPaymentStatusEnum' + customer_name: + type: string + maxLength: 255 + phone: + type: string + maxLength: 20 + email: + type: string + format: email + maxLength: 254 + delivery_method: + type: string + maxLength: 64 + delivery_address: + type: string + delivery_cost: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + comment: + type: string + subtotal: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + discount_total: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + bonus_applied: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + certificate_applied: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + total: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + promo_code: + type: string + maxLength: 64 + certificate_code: + type: string + maxLength: 64 + created_at: + type: string + format: date-time + readOnly: true + items: + type: array + items: + $ref: '#/components/schemas/PendingOrderItem' + readOnly: true + required: + - created_at + - customer_name + - items + - number + - phone + PendingOrderItem: + type: object + properties: + sku: + type: string + maxLength: 64 + product_external_id: + type: string + maxLength: 64 + name: + type: string + maxLength: 500 + price: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + quantity: + type: integer + total: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + required: + - name + - price + - quantity + - sku + - total + PositionEnum: + enum: + - home_top + - home_middle + - category + type: string + description: |- + * `home_top` - Главная — верх + * `home_middle` - Главная — середина + * `category` - Категория + ProductDetail: + type: object + properties: + id: + type: integer + readOnly: true + slug: + type: string + maxLength: 500 + pattern: ^[-a-zA-Z0-9_]+$ + name: + type: string + maxLength: 500 + sku: + type: string + title: Артикул + maxLength: 64 + brand: + type: string + maxLength: 255 + price: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + old_price: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + nullable: true + stock_status: + $ref: '#/components/schemas/ProductStockStatusEnum' + is_hit: + type: boolean + title: Хит продаж + is_new: + type: boolean + title: Новинка + main_image: + type: string + readOnly: true + category: + allOf: + - $ref: '#/components/schemas/Category' + readOnly: true + short_description: + type: string + description: + type: string + stock: + type: integer + attributes: {} + images: + type: array + items: + $ref: '#/components/schemas/ProductImage' + readOnly: true + required: + - category + - id + - images + - main_image + - name + - price + - sku + - slug + ProductImage: + type: object + properties: + id: + type: integer + readOnly: true + url: + type: string + format: uri + maxLength: 1000 + alt: + type: string + maxLength: 255 + sort_order: + type: integer + is_main: + type: boolean + required: + - id + - url + ProductImagePayload: + type: object + properties: + url: + type: string + format: uri + maxLength: 1000 + alt: + type: string + maxLength: 255 + sort_order: + type: integer + default: 0 + is_main: + type: boolean + default: false + required: + - url + ProductImagePayloadRequest: + type: object + properties: + url: + type: string + format: uri + minLength: 1 + maxLength: 1000 + alt: + type: string + maxLength: 255 + sort_order: + type: integer + default: 0 + is_main: + type: boolean + default: false + required: + - url + ProductList: + type: object + properties: + id: + type: integer + readOnly: true + slug: + type: string + maxLength: 500 + pattern: ^[-a-zA-Z0-9_]+$ + name: + type: string + maxLength: 500 + sku: + type: string + title: Артикул + maxLength: 64 + brand: + type: string + maxLength: 255 + price: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + old_price: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + nullable: true + stock_status: + $ref: '#/components/schemas/ProductStockStatusEnum' + is_hit: + type: boolean + title: Хит продаж + is_new: + type: boolean + title: Новинка + main_image: + type: string + readOnly: true + category: + allOf: + - $ref: '#/components/schemas/Category' + readOnly: true + required: + - category + - id + - main_image + - name + - price + - sku + - slug + ProductPayload: + type: object + properties: + external_id: + type: string + maxLength: 64 + sku: + type: string + maxLength: 64 + name: + type: string + maxLength: 500 + slug: + type: string + maxLength: 500 + category_external_id: + type: string + nullable: true + maxLength: 64 + brand: + type: string + maxLength: 255 + short_description: + type: string + description: + type: string + price: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + old_price: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + nullable: true + stock: + type: integer + default: 0 + stock_status: + $ref: '#/components/schemas/ProductStockStatusEnum' + is_hit: + type: boolean + default: false + is_new: + type: boolean + default: false + is_active: + type: boolean + default: true + attributes: + type: object + additionalProperties: {} + images: + type: array + items: + $ref: '#/components/schemas/ProductImagePayload' + external_updated_at: + type: string + format: date-time + nullable: true + required: + - external_id + - name + - price + - sku + ProductPayloadRequest: + type: object + properties: + external_id: + type: string + minLength: 1 + maxLength: 64 + sku: + type: string + minLength: 1 + maxLength: 64 + name: + type: string + minLength: 1 + maxLength: 500 + slug: + type: string + maxLength: 500 + category_external_id: + type: string + nullable: true + maxLength: 64 + brand: + type: string + maxLength: 255 + short_description: + type: string + description: + type: string + price: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + old_price: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + nullable: true + stock: + type: integer + default: 0 + stock_status: + $ref: '#/components/schemas/ProductStockStatusEnum' + is_hit: + type: boolean + default: false + is_new: + type: boolean + default: false + is_active: + type: boolean + default: true + attributes: + type: object + additionalProperties: {} + images: + type: array + items: + $ref: '#/components/schemas/ProductImagePayloadRequest' + external_updated_at: + type: string + format: date-time + nullable: true + required: + - external_id + - name + - price + - sku + ProductStockStatusEnum: + enum: + - in_stock + - preorder + - out_of_stock + type: string + description: |- + * `in_stock` - В наличии + * `preorder` - Под заказ + * `out_of_stock` - Нет в наличии + PromoValidate: + type: object + properties: + code: + type: string + maxLength: 64 + subtotal: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + required: + - code + - subtotal + PromoValidateRequest: + type: object + properties: + code: + type: string + minLength: 1 + maxLength: 64 + subtotal: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + required: + - code + - subtotal + SiteSettings: + type: object + properties: + site_name: + type: string + title: Название сайта + maxLength: 255 + phone: + type: string + title: Телефон + maxLength: 32 + email: + type: string + format: email + maxLength: 254 + address: + type: string + title: Адрес + maxLength: 500 + working_hours: + type: string + title: Часы работы + maxLength: 255 + telegram_url: + type: string + format: uri + title: Telegram + maxLength: 200 + vk_url: + type: string + format: uri + title: ВКонтакте + maxLength: 200 + whatsapp_url: + type: string + format: uri + title: WhatsApp + maxLength: 200 + free_delivery_threshold: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + title: Бесплатная доставка от + default_delivery_cost: + type: string + format: decimal + pattern: ^-?\d{0,10}(?:\.\d{0,2})?$ + title: Стоимость доставки + bonus_accrual_percent: + type: string + format: decimal + pattern: ^-?\d{0,3}(?:\.\d{0,2})?$ + title: Процент начисления бонусов + bonus_max_payment_percent: + type: string + format: decimal + pattern: ^-?\d{0,3}(?:\.\d{0,2})?$ + title: Максимум оплаты бонусами, % + bonus_ttl_days: + type: integer + title: Срок жизни бонусов, дней + privacy_policy_url: + type: string + format: uri + title: Политика конфиденциальности + maxLength: 200 + offer_url: + type: string + format: uri + title: Публичная оферта + maxLength: 200 + updated_at: + type: string + format: date-time + readOnly: true + required: + - updated_at + SourceEnum: + enum: + - site + - 1c + - admin + type: string + description: |- + * `site` - Сайт + * `1c` - 1С + * `admin` - Админка + StaticPage: + type: object + properties: + slug: + type: string + title: Адрес + maxLength: 255 + pattern: ^[-a-zA-Z0-9_]+$ + title: + type: string + title: Заголовок + maxLength: 255 + content: + type: string + title: Содержимое + seo_title: + type: string + maxLength: 255 + seo_description: + type: string + maxLength: 500 + updated_at: + type: string + format: date-time + readOnly: true + required: + - slug + - title + - updated_at + TokenObtainPair: + type: object + properties: + access: + type: string + readOnly: true + refresh: + type: string + readOnly: true + required: + - access + - refresh + TokenObtainPairRequest: + type: object + properties: + phone: + type: string + writeOnly: true + minLength: 1 + password: + type: string + writeOnly: true + minLength: 1 + required: + - password + - phone + TokenRefresh: + type: object + properties: + access: + type: string + readOnly: true + refresh: + type: string + required: + - access + - refresh + TokenRefreshRequest: + type: object + properties: + refresh: + type: string + minLength: 1 + required: + - refresh + User: + type: object + properties: + id: + type: string + format: uuid + readOnly: true + phone: + type: string + readOnly: true + title: Телефон + email: + type: string + format: email + nullable: true + maxLength: 254 + first_name: + type: string + title: Имя + maxLength: 150 + last_name: + type: string + title: Фамилия + maxLength: 150 + middle_name: + type: string + title: Отчество + maxLength: 150 + full_name: + type: string + readOnly: true + date_joined: + type: string + format: date-time + readOnly: true + title: Дата регистрации + required: + - date_joined + - full_name + - id + - phone + securitySchemes: + IntegrationToken: + type: apiKey + in: header + name: X-Integration-Token + jwtAuth: + type: http + scheme: bearer + bearerFormat: JWT diff --git a/requirements/base.txt b/requirements/base.txt new file mode 100644 index 0000000..e974389 --- /dev/null +++ b/requirements/base.txt @@ -0,0 +1,13 @@ +Django==4.2.16 +djangorestframework==3.15.2 +djangorestframework-simplejwt==5.3.1 +drf-spectacular==0.27.2 +django-filter==24.3 +django-cors-headers==4.4.0 +celery==5.4.0 +redis==5.0.8 +psycopg[binary]==3.2.1 +python-dotenv==1.0.1 +Pillow==10.4.0 +phonenumbers==8.13.42 +requests==2.32.3 diff --git a/requirements/dev.txt b/requirements/dev.txt new file mode 100644 index 0000000..309e2f3 --- /dev/null +++ b/requirements/dev.txt @@ -0,0 +1,5 @@ +-r base.txt +pytest==8.3.2 +pytest-django==4.9.0 +factory-boy==3.3.1 +ruff==0.6.5 diff --git a/requirements/prod.txt b/requirements/prod.txt new file mode 100644 index 0000000..56f8565 --- /dev/null +++ b/requirements/prod.txt @@ -0,0 +1,3 @@ +-r base.txt +gunicorn==22.0.0 +sentry-sdk==2.13.0