Add Django backend, 1C integration, deploy config and API docs
Backend (Django 4.2 + DRF): - accounts: phone OTP login, JWT, profile, addresses - catalog: categories, products, images, filters, search, hits/new/related - orders: creation with Idempotency-Key, stock reservation, status history, cancel - loyalty: bonus accounts, promo codes, gift certificates - payments: payment records and YooKassa webhook handling - content: static pages, banners, site settings - integration: 1C exchange (catalog sync, order push via outbox, statuses, bonuses) - common: error envelope, pagination, request-id, integration auth, admin dashboard Infrastructure: Dockerfile, docker-compose (Postgres, Redis, Celery worker/beat, Nginx), requirements split by environment, OpenAPI contracts for site and 1C, architecture doc. Tests: 22 pytest cases covering catalog, orders, idempotency, OTP, integration.
This commit is contained in:
1 parent
5f8d37357d
commit
756f40353b
130 files changed
+10066
No files matched your search
@@ -0,0 +1,3 @@
|
||||
from .celery import app as celery_app
|
||||
|
||||
__all__ = ("celery_app",)
|
||||
@@ -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()
|
||||
@@ -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}")
|
||||
@@ -0,0 +1 @@
|
||||
from .base import * # noqa: F401,F403
|
||||
@@ -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},
|
||||
},
|
||||
}
|
||||
@@ -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"
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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)
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user