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.
163 lines
5.3 KiB
Python
163 lines
5.3 KiB
Python
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}"
|