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