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,106 @@
|
||||
from django.contrib import admin
|
||||
from django.utils.html import format_html
|
||||
|
||||
from .models import IdempotencyKey, OutboxMessage, SyncLog, SyncRun
|
||||
|
||||
|
||||
class SyncLogInline(admin.TabularInline):
|
||||
model = SyncLog
|
||||
extra = 0
|
||||
readonly_fields = ("level", "message", "payload", "created_at")
|
||||
can_delete = False
|
||||
|
||||
|
||||
@admin.register(SyncRun)
|
||||
class SyncRunAdmin(admin.ModelAdmin):
|
||||
list_display = (
|
||||
"entity",
|
||||
"direction",
|
||||
"status_badge",
|
||||
"started_at",
|
||||
"finished_at",
|
||||
"duration",
|
||||
)
|
||||
list_filter = ("entity", "direction", "status")
|
||||
readonly_fields = ("started_at", "finished_at", "stats", "error")
|
||||
inlines = [SyncLogInline]
|
||||
actions = ("run_catalog_sync",)
|
||||
|
||||
@admin.display(description="Статус", ordering="status")
|
||||
def status_badge(self, obj):
|
||||
colors = {
|
||||
SyncRun.Status.RUNNING: "#2563eb",
|
||||
SyncRun.Status.SUCCESS: "#16a34a",
|
||||
SyncRun.Status.PARTIAL: "#d97706",
|
||||
SyncRun.Status.FAILED: "#dc2626",
|
||||
}
|
||||
return format_html(
|
||||
'<span style="display:inline-block;padding:2px 8px;border-radius:10px;'
|
||||
'background:{};color:#fff;font-size:12px;">{}</span>',
|
||||
colors.get(obj.status, "#6b7280"),
|
||||
obj.get_status_display(),
|
||||
)
|
||||
|
||||
@admin.display(description="Длительность")
|
||||
def duration(self, obj):
|
||||
if not obj.finished_at:
|
||||
return "—"
|
||||
seconds = int((obj.finished_at - obj.started_at).total_seconds())
|
||||
return f"{seconds} с"
|
||||
|
||||
@admin.action(description="Запустить синхронизацию каталога")
|
||||
def run_catalog_sync(self, request, queryset):
|
||||
from .tasks import sync_catalog_from_1c
|
||||
|
||||
try:
|
||||
task = sync_catalog_from_1c.delay()
|
||||
except Exception as exc: # noqa: BLE001 - show the broker error to the admin
|
||||
self.message_user(
|
||||
request, f"Не удалось поставить задачу: {exc}", level="error"
|
||||
)
|
||||
return
|
||||
self.message_user(request, f"Задача поставлена в очередь: {task.id}")
|
||||
|
||||
|
||||
@admin.register(SyncLog)
|
||||
class SyncLogAdmin(admin.ModelAdmin):
|
||||
list_display = ("run", "level", "message", "created_at")
|
||||
list_filter = ("level",)
|
||||
search_fields = ("message",)
|
||||
|
||||
|
||||
@admin.register(OutboxMessage)
|
||||
class OutboxMessageAdmin(admin.ModelAdmin):
|
||||
list_display = (
|
||||
"topic",
|
||||
"status",
|
||||
"attempts",
|
||||
"next_attempt_at",
|
||||
"sent_at",
|
||||
"created_at",
|
||||
)
|
||||
list_filter = ("status", "topic")
|
||||
search_fields = ("topic", "last_error")
|
||||
readonly_fields = ("created_at", "updated_at")
|
||||
actions = ("retry", "mark_dead")
|
||||
|
||||
@admin.action(description="Повторить отправку")
|
||||
def retry(self, request, queryset):
|
||||
updated = queryset.update(
|
||||
status=OutboxMessage.Status.PENDING,
|
||||
attempts=0,
|
||||
next_attempt_at=None,
|
||||
last_error="",
|
||||
)
|
||||
self.message_user(request, f"Поставлено в очередь: {updated}")
|
||||
|
||||
@admin.action(description="Пометить как dead-letter")
|
||||
def mark_dead(self, request, queryset):
|
||||
updated = queryset.update(status=OutboxMessage.Status.DEAD)
|
||||
self.message_user(request, f"Помечено: {updated}")
|
||||
|
||||
|
||||
@admin.register(IdempotencyKey)
|
||||
class IdempotencyKeyAdmin(admin.ModelAdmin):
|
||||
list_display = ("scope", "key", "status_code", "created_at")
|
||||
search_fields = ("key", "scope")
|
||||
@@ -0,0 +1,7 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class IntegrationConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
name = "apps.integration"
|
||||
verbose_name = "Интеграция с 1С"
|
||||
@@ -0,0 +1,79 @@
|
||||
import logging
|
||||
from urllib.parse import urljoin
|
||||
|
||||
import requests
|
||||
from django.conf import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class OneCClientError(Exception):
|
||||
"""Raised when the 1C HTTP service is unavailable or returns an error."""
|
||||
|
||||
|
||||
class OneCClient:
|
||||
"""Thin HTTP client for the 1C side of the exchange.
|
||||
|
||||
The 1C side is expected to expose an HTTP service (``/hs/homm``) with the
|
||||
endpoints described in ``docs/openapi-1c-outbound.yaml``.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
username: str | None = None,
|
||||
password: str | None = None,
|
||||
timeout: int | None = None,
|
||||
):
|
||||
self.base_url = (base_url or settings.ONEC_BASE_URL or "").rstrip("/")
|
||||
self.username = username if username is not None else settings.ONEC_USERNAME
|
||||
self.password = password if password is not None else settings.ONEC_PASSWORD
|
||||
self.timeout = timeout or settings.ONEC_TIMEOUT
|
||||
self.auth = (
|
||||
(self.username, self.password) if self.username else None
|
||||
)
|
||||
|
||||
def _request(self, method: str, path: str, **kwargs) -> dict:
|
||||
if not self.base_url:
|
||||
raise OneCClientError("ONEC_BASE_URL не настроен")
|
||||
|
||||
url = urljoin(f"{self.base_url}/", path.lstrip("/"))
|
||||
try:
|
||||
response = requests.request(
|
||||
method,
|
||||
url,
|
||||
auth=self.auth,
|
||||
timeout=self.timeout,
|
||||
headers={"Accept": "application/json"},
|
||||
**kwargs,
|
||||
)
|
||||
except requests.RequestException as exc:
|
||||
raise OneCClientError(f"1C недоступна: {exc}") from exc
|
||||
|
||||
if response.status_code >= 400:
|
||||
raise OneCClientError(
|
||||
f"1C вернула {response.status_code}: {response.text[:500]}"
|
||||
)
|
||||
|
||||
if not response.content:
|
||||
return {}
|
||||
try:
|
||||
return response.json()
|
||||
except ValueError as exc:
|
||||
raise OneCClientError("1C вернула не-JSON ответ") from exc
|
||||
|
||||
def fetch_catalog(self, since=None) -> dict:
|
||||
params = {"since": since.isoformat()} if since else {}
|
||||
return self._request("GET", "catalog/changes", params=params)
|
||||
|
||||
def push_order(self, payload: dict) -> dict:
|
||||
return self._request("POST", "orders", json=payload)
|
||||
|
||||
def push_order_status(self, external_id: str, payload: dict) -> dict:
|
||||
return self._request("POST", f"orders/{external_id}/status", json=payload)
|
||||
|
||||
def push_customer(self, payload: dict) -> dict:
|
||||
return self._request("POST", "customers", json=payload)
|
||||
|
||||
def fetch_order_status(self, external_id: str) -> dict:
|
||||
return self._request("GET", f"orders/{external_id}/status")
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,20 @@
|
||||
from django.core.management.base import BaseCommand
|
||||
from django.utils.dateparse import parse_datetime
|
||||
|
||||
from apps.integration.services import pull_catalog_from_1c
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = "Pull catalog changes from 1C and apply them to the store."
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument(
|
||||
"--since",
|
||||
default=None,
|
||||
help="ISO datetime; only changes after this moment are requested.",
|
||||
)
|
||||
|
||||
def handle(self, *args, **options):
|
||||
since = parse_datetime(options["since"]) if options["since"] else None
|
||||
stats = pull_catalog_from_1c(since=since)
|
||||
self.stdout.write(self.style.SUCCESS(f"Catalog synced: {stats}"))
|
||||
@@ -0,0 +1,94 @@
|
||||
# Generated by Django 4.2.16 on 2026-11-06 13:26
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='IdempotencyKey',
|
||||
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)),
|
||||
('key', models.CharField(max_length=128, unique=True)),
|
||||
('scope', models.CharField(max_length=64)),
|
||||
('status_code', models.PositiveSmallIntegerField(default=200)),
|
||||
('response', models.JSONField(blank=True, default=dict)),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'ключ идемпотентности',
|
||||
'verbose_name_plural': 'ключи идемпотентности',
|
||||
'db_table': 'integration_idempotency_key',
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='SyncRun',
|
||||
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)),
|
||||
('direction', models.CharField(choices=[('inbound', '1С → сайт'), ('outbound', 'Сайт → 1С')], max_length=10)),
|
||||
('entity', models.CharField(choices=[('catalog', 'Каталог'), ('orders', 'Заказы'), ('statuses', 'Статусы'), ('customers', 'Клиенты'), ('bonuses', 'Бонусы')], max_length=20)),
|
||||
('status', models.CharField(choices=[('running', 'Выполняется'), ('success', 'Успешно'), ('partial', 'Частично'), ('failed', 'Ошибка')], default='running', max_length=10)),
|
||||
('started_at', models.DateTimeField()),
|
||||
('finished_at', models.DateTimeField(blank=True, null=True)),
|
||||
('stats', models.JSONField(blank=True, default=dict)),
|
||||
('error', models.TextField(blank=True)),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'сеанс обмена',
|
||||
'verbose_name_plural': 'сеансы обмена',
|
||||
'db_table': 'integration_sync_run',
|
||||
'ordering': ['-started_at'],
|
||||
'indexes': [models.Index(fields=['entity', 'started_at'], name='integration_entity_5810cd_idx')],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='SyncLog',
|
||||
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)),
|
||||
('level', models.CharField(choices=[('debug', 'Debug'), ('info', 'Info'), ('warning', 'Warning'), ('error', 'Error')], default='info', max_length=10)),
|
||||
('message', models.TextField()),
|
||||
('payload', models.JSONField(blank=True, default=dict)),
|
||||
('run', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='logs', to='integration.syncrun')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'запись журнала обмена',
|
||||
'verbose_name_plural': 'журнал обмена',
|
||||
'db_table': 'integration_sync_log',
|
||||
'ordering': ['created_at'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='OutboxMessage',
|
||||
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)),
|
||||
('topic', models.CharField(max_length=64)),
|
||||
('payload', models.JSONField(default=dict)),
|
||||
('status', models.CharField(choices=[('pending', 'Ожидает'), ('sent', 'Отправлено'), ('failed', 'Ошибка'), ('dead', 'Исчерпаны попытки')], default='pending', max_length=10)),
|
||||
('attempts', models.PositiveSmallIntegerField(default=0)),
|
||||
('next_attempt_at', models.DateTimeField(blank=True, null=True)),
|
||||
('last_error', models.TextField(blank=True)),
|
||||
('sent_at', models.DateTimeField(blank=True, null=True)),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'сообщение outbox',
|
||||
'verbose_name_plural': 'сообщения outbox',
|
||||
'db_table': 'integration_outbox_message',
|
||||
'ordering': ['created_at'],
|
||||
'indexes': [models.Index(fields=['status', 'next_attempt_at'], name='integration_status_025e86_idx')],
|
||||
},
|
||||
),
|
||||
]
|
||||
Whitespace-only changes.
@@ -0,0 +1,117 @@
|
||||
from django.db import models
|
||||
|
||||
from apps.common.models import TimeStampedModel
|
||||
|
||||
|
||||
class SyncRun(TimeStampedModel):
|
||||
"""One exchange session with 1C (inbound or outbound)."""
|
||||
|
||||
class Direction(models.TextChoices):
|
||||
INBOUND = "inbound", "1С → сайт"
|
||||
OUTBOUND = "outbound", "Сайт → 1С"
|
||||
|
||||
class Entity(models.TextChoices):
|
||||
CATALOG = "catalog", "Каталог"
|
||||
ORDERS = "orders", "Заказы"
|
||||
STATUSES = "statuses", "Статусы"
|
||||
CUSTOMERS = "customers", "Клиенты"
|
||||
BONUSES = "bonuses", "Бонусы"
|
||||
|
||||
class Status(models.TextChoices):
|
||||
RUNNING = "running", "Выполняется"
|
||||
SUCCESS = "success", "Успешно"
|
||||
PARTIAL = "partial", "Частично"
|
||||
FAILED = "failed", "Ошибка"
|
||||
|
||||
direction = models.CharField(max_length=10, choices=Direction.choices)
|
||||
entity = models.CharField(max_length=20, choices=Entity.choices)
|
||||
status = models.CharField(
|
||||
max_length=10, choices=Status.choices, default=Status.RUNNING
|
||||
)
|
||||
started_at = models.DateTimeField()
|
||||
finished_at = models.DateTimeField(null=True, blank=True)
|
||||
stats = models.JSONField(default=dict, blank=True)
|
||||
error = models.TextField(blank=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "integration_sync_run"
|
||||
verbose_name = "сеанс обмена"
|
||||
verbose_name_plural = "сеансы обмена"
|
||||
ordering = ["-started_at"]
|
||||
indexes = [models.Index(fields=["entity", "started_at"])]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.get_entity_display()} ({self.get_status_display()})"
|
||||
|
||||
|
||||
class SyncLog(TimeStampedModel):
|
||||
class Level(models.TextChoices):
|
||||
DEBUG = "debug", "Debug"
|
||||
INFO = "info", "Info"
|
||||
WARNING = "warning", "Warning"
|
||||
ERROR = "error", "Error"
|
||||
|
||||
run = models.ForeignKey(
|
||||
SyncRun, on_delete=models.CASCADE, related_name="logs"
|
||||
)
|
||||
level = models.CharField(
|
||||
max_length=10, choices=Level.choices, default=Level.INFO
|
||||
)
|
||||
message = models.TextField()
|
||||
payload = models.JSONField(default=dict, blank=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "integration_sync_log"
|
||||
verbose_name = "запись журнала обмена"
|
||||
verbose_name_plural = "журнал обмена"
|
||||
ordering = ["created_at"]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"[{self.level}] {self.message[:80]}"
|
||||
|
||||
|
||||
class OutboxMessage(TimeStampedModel):
|
||||
"""Transactional outbox for reliable site → 1C delivery."""
|
||||
|
||||
class Status(models.TextChoices):
|
||||
PENDING = "pending", "Ожидает"
|
||||
SENT = "sent", "Отправлено"
|
||||
FAILED = "failed", "Ошибка"
|
||||
DEAD = "dead", "Исчерпаны попытки"
|
||||
|
||||
topic = models.CharField(max_length=64)
|
||||
payload = models.JSONField(default=dict)
|
||||
status = models.CharField(
|
||||
max_length=10, choices=Status.choices, default=Status.PENDING
|
||||
)
|
||||
attempts = models.PositiveSmallIntegerField(default=0)
|
||||
next_attempt_at = models.DateTimeField(null=True, blank=True)
|
||||
last_error = models.TextField(blank=True)
|
||||
sent_at = models.DateTimeField(null=True, blank=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "integration_outbox_message"
|
||||
verbose_name = "сообщение outbox"
|
||||
verbose_name_plural = "сообщения outbox"
|
||||
ordering = ["created_at"]
|
||||
indexes = [models.Index(fields=["status", "next_attempt_at"])]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.topic} ({self.status})"
|
||||
|
||||
|
||||
class IdempotencyKey(TimeStampedModel):
|
||||
"""Stores responses for repeated inbound requests."""
|
||||
|
||||
key = models.CharField(max_length=128, unique=True)
|
||||
scope = models.CharField(max_length=64)
|
||||
status_code = models.PositiveSmallIntegerField(default=200)
|
||||
response = models.JSONField(default=dict, blank=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "integration_idempotency_key"
|
||||
verbose_name = "ключ идемпотентности"
|
||||
verbose_name_plural = "ключи идемпотентности"
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.scope}:{self.key}"
|
||||
@@ -0,0 +1,10 @@
|
||||
from .models import OutboxMessage
|
||||
|
||||
|
||||
def enqueue(topic: str, payload: dict) -> OutboxMessage:
|
||||
"""Adds a message to the transactional outbox.
|
||||
|
||||
Called inside the same DB transaction as the business change, so an order
|
||||
can never be committed without a corresponding 1C push task.
|
||||
"""
|
||||
return OutboxMessage.objects.create(topic=topic, payload=payload)
|
||||
@@ -0,0 +1,136 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
from apps.catalog.models import Product
|
||||
from apps.orders.models import Order, OrderItem
|
||||
|
||||
|
||||
class CategoryPayloadSerializer(serializers.Serializer):
|
||||
external_id = serializers.CharField(max_length=64)
|
||||
parent_external_id = serializers.CharField(
|
||||
max_length=64, required=False, allow_blank=True, allow_null=True
|
||||
)
|
||||
name = serializers.CharField(max_length=255)
|
||||
slug = serializers.CharField(max_length=255, required=False, allow_blank=True)
|
||||
description = serializers.CharField(required=False, allow_blank=True)
|
||||
image_url = serializers.URLField(required=False, allow_blank=True)
|
||||
is_active = serializers.BooleanField(default=True)
|
||||
sort_order = serializers.IntegerField(default=0)
|
||||
|
||||
|
||||
class ProductImagePayloadSerializer(serializers.Serializer):
|
||||
url = serializers.URLField(max_length=1000)
|
||||
alt = serializers.CharField(max_length=255, required=False, allow_blank=True)
|
||||
sort_order = serializers.IntegerField(default=0)
|
||||
is_main = serializers.BooleanField(default=False)
|
||||
|
||||
|
||||
class ProductPayloadSerializer(serializers.Serializer):
|
||||
external_id = serializers.CharField(max_length=64)
|
||||
sku = serializers.CharField(max_length=64)
|
||||
name = serializers.CharField(max_length=500)
|
||||
slug = serializers.CharField(max_length=500, required=False, allow_blank=True)
|
||||
category_external_id = serializers.CharField(
|
||||
max_length=64, required=False, allow_blank=True, allow_null=True
|
||||
)
|
||||
brand = serializers.CharField(max_length=255, required=False, allow_blank=True)
|
||||
short_description = serializers.CharField(required=False, allow_blank=True)
|
||||
description = serializers.CharField(required=False, allow_blank=True)
|
||||
price = serializers.DecimalField(max_digits=12, decimal_places=2)
|
||||
old_price = serializers.DecimalField(
|
||||
max_digits=12, decimal_places=2, required=False, allow_null=True
|
||||
)
|
||||
stock = serializers.IntegerField(default=0)
|
||||
stock_status = serializers.ChoiceField(
|
||||
choices=Product.StockStatus.choices, required=False
|
||||
)
|
||||
is_hit = serializers.BooleanField(default=False)
|
||||
is_new = serializers.BooleanField(default=False)
|
||||
is_active = serializers.BooleanField(default=True)
|
||||
attributes = serializers.DictField(required=False)
|
||||
images = ProductImagePayloadSerializer(many=True, required=False)
|
||||
external_updated_at = serializers.DateTimeField(required=False, allow_null=True)
|
||||
|
||||
|
||||
class CatalogSyncSerializer(serializers.Serializer):
|
||||
sync_id = serializers.CharField(max_length=64, required=False, allow_blank=True)
|
||||
categories = CategoryPayloadSerializer(many=True, required=False, default=list)
|
||||
products = ProductPayloadSerializer(many=True, required=False, default=list)
|
||||
deleted_product_external_ids = serializers.ListField(
|
||||
child=serializers.CharField(max_length=64), required=False, default=list
|
||||
)
|
||||
deleted_category_external_ids = serializers.ListField(
|
||||
child=serializers.CharField(max_length=64), required=False, default=list
|
||||
)
|
||||
|
||||
|
||||
class OrderStatusPayloadSerializer(serializers.Serializer):
|
||||
status = serializers.CharField(max_length=64)
|
||||
comment = serializers.CharField(required=False, allow_blank=True)
|
||||
changed_at = serializers.DateTimeField(required=False)
|
||||
external_id = serializers.CharField(
|
||||
max_length=64, required=False, allow_blank=True
|
||||
)
|
||||
|
||||
|
||||
class BonusPayloadSerializer(serializers.Serializer):
|
||||
phone = serializers.CharField(max_length=20, required=False, allow_blank=True)
|
||||
external_customer_id = serializers.CharField(
|
||||
max_length=64, required=False, allow_blank=True
|
||||
)
|
||||
amount = serializers.DecimalField(max_digits=12, decimal_places=2)
|
||||
reason = serializers.ChoiceField(
|
||||
choices=["accrual", "spend", "refund", "adjustment"], default="accrual"
|
||||
)
|
||||
comment = serializers.CharField(required=False, allow_blank=True)
|
||||
order_number = serializers.CharField(
|
||||
max_length=32, required=False, allow_blank=True
|
||||
)
|
||||
|
||||
|
||||
class OrderAckSerializer(serializers.Serializer):
|
||||
external_id = serializers.CharField(max_length=64)
|
||||
|
||||
|
||||
class HealthSerializer(serializers.Serializer):
|
||||
status = serializers.CharField()
|
||||
time = serializers.DateTimeField()
|
||||
|
||||
|
||||
class ManualSyncResponseSerializer(serializers.Serializer):
|
||||
status = serializers.CharField()
|
||||
task_id = serializers.CharField()
|
||||
|
||||
|
||||
class PendingOrderItemSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = OrderItem
|
||||
fields = ["sku", "product_external_id", "name", "price", "quantity", "total"]
|
||||
|
||||
|
||||
class PendingOrderSerializer(serializers.ModelSerializer):
|
||||
items = PendingOrderItemSerializer(many=True, read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = Order
|
||||
fields = [
|
||||
"number",
|
||||
"external_id",
|
||||
"status",
|
||||
"payment_status",
|
||||
"customer_name",
|
||||
"phone",
|
||||
"email",
|
||||
"delivery_method",
|
||||
"delivery_address",
|
||||
"delivery_cost",
|
||||
"comment",
|
||||
"subtotal",
|
||||
"discount_total",
|
||||
"bonus_applied",
|
||||
"certificate_applied",
|
||||
"total",
|
||||
"promo_code",
|
||||
"certificate_code",
|
||||
"created_at",
|
||||
"items",
|
||||
]
|
||||
@@ -0,0 +1,378 @@
|
||||
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
|
||||
@@ -0,0 +1,33 @@
|
||||
from apps.orders.models import Order
|
||||
|
||||
# 1C statuses are configurable per configuration (УТ/ERP/УНФ), so the mapping
|
||||
# is intentionally explicit and easy to extend. Keys are normalized to lower
|
||||
# case and stripped before lookup.
|
||||
ONEC_STATUS_MAP: dict[str, str] = {
|
||||
# English codes
|
||||
"new": Order.Status.NEW,
|
||||
"processing": Order.Status.PROCESSING,
|
||||
"delivering": Order.Status.DELIVERING,
|
||||
"completed": Order.Status.COMPLETED,
|
||||
"cancelled": Order.Status.CANCELLED,
|
||||
"canceled": Order.Status.CANCELLED,
|
||||
# Russian names
|
||||
"новый": Order.Status.NEW,
|
||||
"в обработке": Order.Status.PROCESSING,
|
||||
"подтвержден": Order.Status.PROCESSING,
|
||||
"подтверждён": Order.Status.PROCESSING,
|
||||
"собирается": Order.Status.PROCESSING,
|
||||
"передан в доставку": Order.Status.DELIVERING,
|
||||
"доставляется": Order.Status.DELIVERING,
|
||||
"в пути": Order.Status.DELIVERING,
|
||||
"выполнен": Order.Status.COMPLETED,
|
||||
"закрыт": Order.Status.COMPLETED,
|
||||
"отменен": Order.Status.CANCELLED,
|
||||
"отменён": Order.Status.CANCELLED,
|
||||
}
|
||||
|
||||
|
||||
def map_1c_status(raw_status: str | None) -> str | None:
|
||||
if not raw_status:
|
||||
return None
|
||||
return ONEC_STATUS_MAP.get(raw_status.strip().lower())
|
||||
@@ -0,0 +1,31 @@
|
||||
from celery import shared_task
|
||||
|
||||
from apps.orders.models import Order
|
||||
|
||||
from .services import (
|
||||
process_outbox as _process_outbox,
|
||||
pull_catalog_from_1c,
|
||||
pull_order_statuses as _pull_order_statuses,
|
||||
push_order_to_1c,
|
||||
)
|
||||
|
||||
|
||||
@shared_task
|
||||
def sync_catalog_from_1c(since=None):
|
||||
return pull_catalog_from_1c(since=since)
|
||||
|
||||
|
||||
@shared_task
|
||||
def push_order(order_id):
|
||||
order = Order.objects.get(pk=order_id)
|
||||
return push_order_to_1c(order)
|
||||
|
||||
|
||||
@shared_task
|
||||
def process_outbox(limit: int = 100):
|
||||
return _process_outbox(limit=limit)
|
||||
|
||||
|
||||
@shared_task
|
||||
def pull_order_statuses(limit: int = 100):
|
||||
return _pull_order_statuses(limit=limit)
|
||||
@@ -0,0 +1,82 @@
|
||||
from decimal import Decimal
|
||||
|
||||
from django.conf import settings
|
||||
from django.test import TestCase
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from apps.catalog.models import Product
|
||||
from apps.orders.models import Order
|
||||
|
||||
|
||||
class IntegrationApiTests(TestCase):
|
||||
def setUp(self):
|
||||
self.client = APIClient()
|
||||
self.token = settings.INTEGRATION_API_TOKEN
|
||||
|
||||
def test_requires_token(self):
|
||||
response = self.client.get("/api/v1/integration/1c/health/")
|
||||
self.assertEqual(response.status_code, 401)
|
||||
|
||||
def test_catalog_sync(self):
|
||||
payload = {
|
||||
"sync_id": "sync-1",
|
||||
"categories": [{"external_id": "c1", "name": "Кресла"}],
|
||||
"products": [
|
||||
{
|
||||
"external_id": "p1",
|
||||
"sku": "SKU-1",
|
||||
"name": "Кресло Эймс",
|
||||
"price": "1000.00",
|
||||
"stock": 3,
|
||||
"category_external_id": "c1",
|
||||
"images": [
|
||||
{"url": "https://example.com/1.jpg", "is_main": True}
|
||||
],
|
||||
}
|
||||
],
|
||||
}
|
||||
response = self.client.post(
|
||||
"/api/v1/integration/1c/catalog/sync/",
|
||||
payload,
|
||||
format="json",
|
||||
HTTP_X_INTEGRATION_TOKEN=self.token,
|
||||
)
|
||||
self.assertEqual(response.status_code, 200, response.data)
|
||||
self.assertEqual(response.data["stats"]["products_created"], 1)
|
||||
|
||||
product = Product.objects.get(external_id="p1")
|
||||
self.assertEqual(product.price, Decimal("1000.00"))
|
||||
self.assertEqual(product.stock, 3)
|
||||
self.assertEqual(product.images.count(), 1)
|
||||
|
||||
def test_order_status_update(self):
|
||||
order = Order.objects.create(
|
||||
customer_name="Иван",
|
||||
phone="+79991234567",
|
||||
total=Decimal("1000.00"),
|
||||
)
|
||||
response = self.client.post(
|
||||
f"/api/v1/integration/1c/orders/{order.number}/status/",
|
||||
{"status": "Выполнен", "comment": "Выдан клиенту"},
|
||||
format="json",
|
||||
HTTP_X_INTEGRATION_TOKEN=self.token,
|
||||
)
|
||||
self.assertEqual(response.status_code, 200, response.data)
|
||||
order.refresh_from_db()
|
||||
self.assertEqual(order.status, Order.Status.COMPLETED)
|
||||
self.assertEqual(order.status_history.count(), 1)
|
||||
|
||||
def test_unknown_status_is_rejected(self):
|
||||
order = Order.objects.create(
|
||||
customer_name="Иван",
|
||||
phone="+79991234567",
|
||||
total=Decimal("1000.00"),
|
||||
)
|
||||
response = self.client.post(
|
||||
f"/api/v1/integration/1c/orders/{order.number}/status/",
|
||||
{"status": "Неизвестный статус"},
|
||||
format="json",
|
||||
HTTP_X_INTEGRATION_TOKEN=self.token,
|
||||
)
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.data["error"]["code"], "unknown_status")
|
||||
@@ -0,0 +1,29 @@
|
||||
from django.urls import path
|
||||
|
||||
from .views import (
|
||||
BonusView,
|
||||
CatalogSyncView,
|
||||
IntegrationHealthView,
|
||||
ManualSyncView,
|
||||
OrderAckView,
|
||||
OrderStatusView,
|
||||
PendingOrdersView,
|
||||
)
|
||||
|
||||
urlpatterns = [
|
||||
path("health/", IntegrationHealthView.as_view(), name="integration-health"),
|
||||
path("catalog/sync/", CatalogSyncView.as_view(), name="integration-catalog-sync"),
|
||||
path("orders/pending/", PendingOrdersView.as_view(), name="integration-pending-orders"),
|
||||
path(
|
||||
"orders/<str:number>/status/",
|
||||
OrderStatusView.as_view(),
|
||||
name="integration-order-status",
|
||||
),
|
||||
path(
|
||||
"orders/<str:number>/ack/",
|
||||
OrderAckView.as_view(),
|
||||
name="integration-order-ack",
|
||||
),
|
||||
path("customers/bonus/", BonusView.as_view(), name="integration-bonus"),
|
||||
path("sync/run/", ManualSyncView.as_view(), name="integration-manual-sync"),
|
||||
]
|
||||
@@ -0,0 +1,163 @@
|
||||
from django.utils import timezone
|
||||
from rest_framework.permissions import IsAdminUser
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from apps.common.authentication import (
|
||||
IntegrationTokenAuthentication,
|
||||
IsIntegrationClient,
|
||||
)
|
||||
from apps.common.exceptions import IntegrationError
|
||||
from apps.orders.models import Order
|
||||
|
||||
from .models import SyncRun
|
||||
from .serializers import (
|
||||
BonusPayloadSerializer,
|
||||
CatalogSyncSerializer,
|
||||
HealthSerializer,
|
||||
ManualSyncResponseSerializer,
|
||||
OrderAckSerializer,
|
||||
OrderStatusPayloadSerializer,
|
||||
PendingOrderSerializer,
|
||||
)
|
||||
from .services import apply_bonus, apply_order_status, upsert_catalog
|
||||
|
||||
|
||||
class IntegrationBaseView(APIView):
|
||||
authentication_classes = [IntegrationTokenAuthentication]
|
||||
permission_classes = [IsIntegrationClient]
|
||||
|
||||
|
||||
class IntegrationHealthView(IntegrationBaseView):
|
||||
serializer_class = HealthSerializer
|
||||
|
||||
def get(self, request):
|
||||
return Response({"status": "ok", "time": timezone.now().isoformat()})
|
||||
|
||||
|
||||
class CatalogSyncView(IntegrationBaseView):
|
||||
serializer_class = CatalogSyncSerializer
|
||||
|
||||
def post(self, request):
|
||||
serializer = CatalogSyncSerializer(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
run = SyncRun.objects.create(
|
||||
direction=SyncRun.Direction.INBOUND,
|
||||
entity=SyncRun.Entity.CATALOG,
|
||||
status=SyncRun.Status.RUNNING,
|
||||
started_at=timezone.now(),
|
||||
)
|
||||
try:
|
||||
stats = upsert_catalog(serializer.validated_data, run=run)
|
||||
except Exception as exc: # noqa: BLE001 - report the failure to 1C
|
||||
run.status = SyncRun.Status.FAILED
|
||||
run.error = str(exc)
|
||||
run.finished_at = timezone.now()
|
||||
run.save(update_fields=["status", "error", "finished_at", "updated_at"])
|
||||
return Response(
|
||||
{"error": {"code": "catalog_sync_failed", "message": str(exc)}},
|
||||
status=400,
|
||||
)
|
||||
|
||||
run.status = SyncRun.Status.SUCCESS
|
||||
run.stats = stats
|
||||
run.finished_at = timezone.now()
|
||||
run.save(update_fields=["status", "stats", "finished_at", "updated_at"])
|
||||
return Response(
|
||||
{
|
||||
"status": "ok",
|
||||
"sync_id": serializer.validated_data.get("sync_id", ""),
|
||||
"stats": stats,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class OrderStatusView(IntegrationBaseView):
|
||||
serializer_class = OrderStatusPayloadSerializer
|
||||
|
||||
def post(self, request, number: str):
|
||||
serializer = OrderStatusPayloadSerializer(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
try:
|
||||
order = apply_order_status(number, serializer.validated_data)
|
||||
except IntegrationError as exc:
|
||||
status_code = 404 if exc.code == "order_not_found" else 400
|
||||
return Response(
|
||||
{"error": {"code": exc.code, "message": exc.message}},
|
||||
status=status_code,
|
||||
)
|
||||
return Response(
|
||||
{"status": "ok", "order": order.number, "order_status": order.status}
|
||||
)
|
||||
|
||||
|
||||
class BonusView(IntegrationBaseView):
|
||||
serializer_class = BonusPayloadSerializer
|
||||
|
||||
def post(self, request):
|
||||
serializer = BonusPayloadSerializer(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
try:
|
||||
user = apply_bonus(serializer.validated_data)
|
||||
except IntegrationError as exc:
|
||||
status_code = 404 if exc.code == "customer_not_found" else 400
|
||||
return Response(
|
||||
{"error": {"code": exc.code, "message": exc.message}},
|
||||
status=status_code,
|
||||
)
|
||||
return Response({"status": "ok", "phone": user.phone})
|
||||
|
||||
|
||||
class PendingOrdersView(IntegrationBaseView):
|
||||
serializer_class = PendingOrderSerializer
|
||||
|
||||
def get(self, request):
|
||||
orders = (
|
||||
Order.objects.filter(external_id="")
|
||||
.exclude(status=Order.Status.CANCELLED)
|
||||
.prefetch_related("items")
|
||||
.order_by("created_at")[:100]
|
||||
)
|
||||
return Response({"orders": PendingOrderSerializer(orders, many=True).data})
|
||||
|
||||
|
||||
class OrderAckView(IntegrationBaseView):
|
||||
serializer_class = OrderAckSerializer
|
||||
|
||||
def post(self, request, number: str):
|
||||
serializer = OrderAckSerializer(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
order = Order.objects.filter(number=number).first()
|
||||
if order is None:
|
||||
return Response(
|
||||
{
|
||||
"error": {
|
||||
"code": "order_not_found",
|
||||
"message": f"Заказ {number} не найден",
|
||||
}
|
||||
},
|
||||
status=404,
|
||||
)
|
||||
|
||||
order.external_id = serializer.validated_data["external_id"]
|
||||
order.synced_at = timezone.now()
|
||||
order.sync_error = ""
|
||||
order.save(
|
||||
update_fields=["external_id", "synced_at", "sync_error", "updated_at"]
|
||||
)
|
||||
return Response({"status": "ok"})
|
||||
|
||||
|
||||
class ManualSyncView(APIView):
|
||||
"""Admin-triggered catalog sync (JWT + staff)."""
|
||||
|
||||
permission_classes = [IsAdminUser]
|
||||
serializer_class = ManualSyncResponseSerializer
|
||||
|
||||
def post(self, request):
|
||||
from .tasks import sync_catalog_from_1c
|
||||
|
||||
task = sync_catalog_from_1c.delay()
|
||||
return Response({"status": "queued", "task_id": task.id})
|
||||
Reference in new issue
Block a user