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.
379 lines
13 KiB
Python
379 lines
13 KiB
Python
import logging
|
|
from datetime import timedelta
|
|
from decimal import Decimal
|
|
|
|
from django.db import transaction
|
|
from django.db.models import Q
|
|
from django.utils import timezone
|
|
|
|
from apps.accounts.models import User
|
|
from apps.accounts.services import normalize_phone
|
|
from apps.catalog.models import Category, Product, ProductImage
|
|
from apps.common.exceptions import IntegrationError
|
|
from apps.common.utils import make_slug
|
|
from apps.loyalty.services import accrue_bonus, spend_bonus
|
|
from apps.orders.models import Order, OrderStatusHistory
|
|
|
|
from .client import OneCClient
|
|
from .models import OutboxMessage, SyncLog, SyncRun
|
|
from .status_map import map_1c_status
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def _unique_slug(model, base: str, exclude_pk=None) -> str:
|
|
slug = base
|
|
counter = 2
|
|
queryset = model.objects.all()
|
|
if exclude_pk is not None:
|
|
queryset = queryset.exclude(pk=exclude_pk)
|
|
while queryset.filter(slug=slug).exists():
|
|
slug = f"{base}-{counter}"
|
|
counter += 1
|
|
return slug
|
|
|
|
|
|
def _log(run: SyncRun | None, level: str, message: str, payload: dict | None = None):
|
|
if run is not None:
|
|
SyncLog.objects.create(
|
|
run=run, level=level, message=message, payload=payload or {}
|
|
)
|
|
|
|
|
|
@transaction.atomic
|
|
def upsert_catalog(payload: dict, run: SyncRun | None = None) -> dict:
|
|
"""Applies a catalog batch from 1C. Idempotent by external_id."""
|
|
stats = {
|
|
"categories_created": 0,
|
|
"categories_updated": 0,
|
|
"products_created": 0,
|
|
"products_updated": 0,
|
|
"products_deleted": 0,
|
|
"categories_deleted": 0,
|
|
"images_replaced": 0,
|
|
}
|
|
|
|
categories = payload.get("categories", [])
|
|
for item in categories:
|
|
existing = Category.objects.filter(external_id=item["external_id"]).first()
|
|
slug = _unique_slug(
|
|
Category,
|
|
item.get("slug") or make_slug(item["name"]),
|
|
existing.pk if existing else None,
|
|
)
|
|
_, created = Category.objects.update_or_create(
|
|
external_id=item["external_id"],
|
|
defaults={
|
|
"name": item["name"],
|
|
"slug": slug,
|
|
"description": item.get("description", ""),
|
|
"image_url": item.get("image_url", ""),
|
|
"is_active": item.get("is_active", True),
|
|
"sort_order": item.get("sort_order", 0),
|
|
},
|
|
)
|
|
stats["categories_created" if created else "categories_updated"] += 1
|
|
|
|
# Second pass: link parents after all categories exist.
|
|
for item in categories:
|
|
parent_external_id = item.get("parent_external_id")
|
|
if not parent_external_id:
|
|
continue
|
|
parent = Category.objects.filter(external_id=parent_external_id).first()
|
|
if parent is None:
|
|
_log(
|
|
run,
|
|
SyncLog.Level.WARNING,
|
|
f"Parent category {parent_external_id} not found",
|
|
{"category": item["external_id"]},
|
|
)
|
|
continue
|
|
Category.objects.filter(external_id=item["external_id"]).update(parent=parent)
|
|
|
|
for item in payload.get("products", []):
|
|
existing = Product.objects.filter(external_id=item["external_id"]).first()
|
|
slug = _unique_slug(
|
|
Product,
|
|
item.get("slug") or make_slug(item["name"]),
|
|
existing.pk if existing else None,
|
|
)
|
|
|
|
category = None
|
|
category_external_id = item.get("category_external_id")
|
|
if category_external_id:
|
|
category = Category.objects.filter(
|
|
external_id=category_external_id
|
|
).first()
|
|
if category is None:
|
|
_log(
|
|
run,
|
|
SyncLog.Level.WARNING,
|
|
f"Category {category_external_id} not found for product",
|
|
{"product": item["external_id"]},
|
|
)
|
|
|
|
stock = item.get("stock", 0)
|
|
stock_status = item.get("stock_status") or (
|
|
Product.StockStatus.IN_STOCK
|
|
if stock > 0
|
|
else Product.StockStatus.OUT_OF_STOCK
|
|
)
|
|
|
|
defaults = {
|
|
"sku": item["sku"],
|
|
"name": item["name"],
|
|
"slug": slug,
|
|
"category": category,
|
|
"brand": item.get("brand", ""),
|
|
"short_description": item.get("short_description", ""),
|
|
"description": item.get("description", ""),
|
|
"price": item["price"],
|
|
"old_price": item.get("old_price"),
|
|
"stock": stock,
|
|
"stock_status": stock_status,
|
|
"is_hit": item.get("is_hit", False),
|
|
"is_new": item.get("is_new", False),
|
|
"is_active": item.get("is_active", True),
|
|
"attributes": item.get(
|
|
"attributes", existing.attributes if existing else {}
|
|
),
|
|
"external_updated_at": item.get("external_updated_at"),
|
|
}
|
|
product, created = Product.objects.update_or_create(
|
|
external_id=item["external_id"], defaults=defaults
|
|
)
|
|
stats["products_created" if created else "products_updated"] += 1
|
|
|
|
if "images" in item:
|
|
product.images.all().delete()
|
|
for image in item["images"]:
|
|
ProductImage.objects.create(product=product, **image)
|
|
stats["images_replaced"] += len(item["images"])
|
|
|
|
for external_id in payload.get("deleted_product_external_ids", []):
|
|
stats["products_deleted"] += Product.objects.filter(
|
|
external_id=external_id
|
|
).update(is_active=False)
|
|
|
|
for external_id in payload.get("deleted_category_external_ids", []):
|
|
stats["categories_deleted"] += Category.objects.filter(
|
|
external_id=external_id
|
|
).update(is_active=False)
|
|
|
|
_log(run, SyncLog.Level.INFO, "Catalog batch applied", stats)
|
|
return stats
|
|
|
|
|
|
@transaction.atomic
|
|
def apply_order_status(
|
|
order_number: str, payload: dict, run: SyncRun | None = None
|
|
) -> Order:
|
|
order = Order.objects.select_for_update().filter(number=order_number).first()
|
|
if order is None:
|
|
raise IntegrationError(
|
|
f"Заказ {order_number} не найден", code="order_not_found"
|
|
)
|
|
|
|
status = map_1c_status(payload.get("status"))
|
|
if status is None:
|
|
raise IntegrationError(
|
|
f"Неизвестный статус 1С: {payload.get('status')}",
|
|
code="unknown_status",
|
|
)
|
|
|
|
if payload.get("external_id"):
|
|
order.external_id = payload["external_id"]
|
|
order.status = status
|
|
order.save(update_fields=["status", "external_id", "updated_at"])
|
|
|
|
OrderStatusHistory.objects.create(
|
|
order=order,
|
|
status=status,
|
|
comment=payload.get("comment", ""),
|
|
source=OrderStatusHistory.Source.ONEC,
|
|
)
|
|
_log(run, SyncLog.Level.INFO, f"Order {order.number} -> {status}")
|
|
return order
|
|
|
|
|
|
@transaction.atomic
|
|
def apply_bonus(payload: dict, run: SyncRun | None = None) -> User:
|
|
phone = payload.get("phone")
|
|
if not phone:
|
|
raise IntegrationError(
|
|
"Не передан phone. Маппинг external_customer_id пока не настроен.",
|
|
code="customer_not_found",
|
|
)
|
|
|
|
normalized = normalize_phone(phone)
|
|
user = User.objects.filter(phone=normalized).first()
|
|
if user is None:
|
|
raise IntegrationError(
|
|
f"Клиент {normalized} не найден", code="customer_not_found"
|
|
)
|
|
|
|
order = None
|
|
if payload.get("order_number"):
|
|
order = Order.objects.filter(number=payload["order_number"]).first()
|
|
|
|
amount = Decimal(payload["amount"])
|
|
if amount >= 0:
|
|
accrue_bonus(
|
|
user, amount, order=order, comment=payload.get("comment", "")
|
|
)
|
|
else:
|
|
spend_bonus(user, -amount, order=order)
|
|
|
|
_log(run, SyncLog.Level.INFO, f"Bonus {amount} applied to {normalized}")
|
|
return user
|
|
|
|
|
|
def build_order_payload(order: Order) -> dict:
|
|
return {
|
|
"number": order.number,
|
|
"created_at": order.created_at.isoformat(),
|
|
"customer": {
|
|
"name": order.customer_name,
|
|
"phone": order.phone,
|
|
"email": order.email,
|
|
},
|
|
"delivery": {
|
|
"method": order.delivery_method,
|
|
"address": order.delivery_address,
|
|
"cost": str(order.delivery_cost),
|
|
},
|
|
"items": [
|
|
{
|
|
"sku": item.sku,
|
|
"external_id": item.product_external_id,
|
|
"name": item.name,
|
|
"price": str(item.price),
|
|
"quantity": item.quantity,
|
|
"total": str(item.total),
|
|
}
|
|
for item in order.items.all()
|
|
],
|
|
"totals": {
|
|
"subtotal": str(order.subtotal),
|
|
"discount": str(order.discount_total),
|
|
"bonus": str(order.bonus_applied),
|
|
"certificate": str(order.certificate_applied),
|
|
"delivery": str(order.delivery_cost),
|
|
"total": str(order.total),
|
|
},
|
|
"payment": {"status": order.payment_status},
|
|
"promo_code": order.promo_code,
|
|
"certificate_code": order.certificate_code,
|
|
}
|
|
|
|
|
|
def push_order_to_1c(order: Order) -> dict:
|
|
client = OneCClient()
|
|
response = client.push_order(build_order_payload(order))
|
|
order.external_id = str(
|
|
response.get("external_id") or response.get("number") or order.external_id or ""
|
|
)
|
|
order.synced_at = timezone.now()
|
|
order.sync_error = ""
|
|
order.save(
|
|
update_fields=["external_id", "synced_at", "sync_error", "updated_at"]
|
|
)
|
|
return response
|
|
|
|
|
|
def push_customer_to_1c(user: User) -> dict:
|
|
client = OneCClient()
|
|
return client.push_customer(
|
|
{"phone": user.phone, "email": user.email or "", "name": user.full_name}
|
|
)
|
|
|
|
|
|
def pull_catalog_from_1c(since=None) -> dict:
|
|
run = SyncRun.objects.create(
|
|
direction=SyncRun.Direction.INBOUND,
|
|
entity=SyncRun.Entity.CATALOG,
|
|
status=SyncRun.Status.RUNNING,
|
|
started_at=timezone.now(),
|
|
)
|
|
try:
|
|
payload = OneCClient().fetch_catalog(since=since)
|
|
stats = upsert_catalog(payload, run=run)
|
|
run.status = SyncRun.Status.SUCCESS
|
|
run.stats = stats
|
|
run.finished_at = timezone.now()
|
|
run.save(update_fields=["status", "stats", "finished_at", "updated_at"])
|
|
return stats
|
|
except Exception as exc:
|
|
run.status = SyncRun.Status.FAILED
|
|
run.error = str(exc)
|
|
run.finished_at = timezone.now()
|
|
run.save(update_fields=["status", "error", "finished_at", "updated_at"])
|
|
_log(run, SyncLog.Level.ERROR, str(exc))
|
|
raise
|
|
|
|
|
|
def _dispatch_outbox(message: OutboxMessage) -> None:
|
|
if message.topic == "order.created":
|
|
order = Order.objects.get(pk=message.payload["order_id"])
|
|
push_order_to_1c(order)
|
|
elif message.topic == "order.status_changed":
|
|
order = Order.objects.get(pk=message.payload["order_id"])
|
|
OneCClient().push_order_status(
|
|
order.external_id or order.number,
|
|
{"status": order.status, "comment": "Изменено на сайте"},
|
|
)
|
|
elif message.topic == "customer.created":
|
|
user = User.objects.get(pk=message.payload["user_id"])
|
|
push_customer_to_1c(user)
|
|
else:
|
|
raise IntegrationError(f"Неизвестный outbox topic: {message.topic}")
|
|
|
|
|
|
def process_outbox(limit: int = 100) -> int:
|
|
now = timezone.now()
|
|
messages = (
|
|
OutboxMessage.objects.filter(status=OutboxMessage.Status.PENDING)
|
|
.filter(Q(next_attempt_at__isnull=True) | Q(next_attempt_at__lte=now))
|
|
.order_by("created_at")[:limit]
|
|
)
|
|
|
|
processed = 0
|
|
for message in messages:
|
|
try:
|
|
_dispatch_outbox(message)
|
|
message.status = OutboxMessage.Status.SENT
|
|
message.sent_at = timezone.now()
|
|
message.last_error = ""
|
|
except Exception as exc: # noqa: BLE001 - outbox must never crash the worker
|
|
message.attempts += 1
|
|
message.last_error = str(exc)[:2000]
|
|
if message.attempts >= 5:
|
|
message.status = OutboxMessage.Status.DEAD
|
|
else:
|
|
message.next_attempt_at = timezone.now() + timedelta(
|
|
minutes=2**message.attempts
|
|
)
|
|
logger.warning("Outbox %s failed: %s", message.pk, exc)
|
|
message.save()
|
|
processed += 1
|
|
return processed
|
|
|
|
|
|
def pull_order_statuses(limit: int = 100) -> int:
|
|
client = OneCClient()
|
|
orders = (
|
|
Order.objects.exclude(external_id="")
|
|
.exclude(status__in=[Order.Status.COMPLETED, Order.Status.CANCELLED])
|
|
.order_by("created_at")[:limit]
|
|
)
|
|
|
|
updated = 0
|
|
for order in orders:
|
|
try:
|
|
payload = client.fetch_order_status(order.external_id)
|
|
apply_order_status(order.number, payload)
|
|
updated += 1
|
|
except Exception as exc: # noqa: BLE001 - one order must not stop the batch
|
|
logger.warning("Failed to pull status for %s: %s", order.number, exc)
|
|
return updated
|