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
Whitespace-only changes.
@@ -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")
|
||||
@@ -0,0 +1,7 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class PaymentsConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
name = "apps.payments"
|
||||
verbose_name = "Платежи"
|
||||
@@ -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'],
|
||||
},
|
||||
),
|
||||
]
|
||||
Whitespace-only changes.
@@ -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}"
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -0,0 +1,7 @@
|
||||
from django.urls import path
|
||||
|
||||
from .views import YooKassaWebhookView
|
||||
|
||||
urlpatterns = [
|
||||
path("webhook/yookassa/", YooKassaWebhookView.as_view(), name="yookassa-webhook"),
|
||||
]
|
||||
@@ -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"})
|
||||
Reference in new issue
Block a user