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.
107 lines
4.0 KiB
Python
107 lines
4.0 KiB
Python
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
|