feat: import mostovik exchange sections
All checks were successful
CI/CD Pipeline / Run Tests (push) Successful in 6m12s
CI/CD Pipeline / Code Quality Checks (push) Successful in 6m19s
CI/CD Pipeline / Build Docker Images (push) Successful in 2m21s
CI/CD Pipeline / Push to Gitea Registry (push) Successful in 1s
CI/CD Pipeline / Deploy to Server (push) Successful in 1s
All checks were successful
CI/CD Pipeline / Run Tests (push) Successful in 6m12s
CI/CD Pipeline / Code Quality Checks (push) Successful in 6m19s
CI/CD Pipeline / Build Docker Images (push) Successful in 2m21s
CI/CD Pipeline / Push to Gitea Registry (push) Successful in 1s
CI/CD Pipeline / Deploy to Server (push) Successful in 1s
This commit is contained in:
@@ -1,18 +1,13 @@
|
||||
"""
|
||||
Сервисы для работы с организациями.
|
||||
"""Services for organization lookup and read-side helpers."""
|
||||
|
||||
Содержит:
|
||||
- OrganizationService - CRUD операции и бизнес-логика
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from apps.core.services import BaseService
|
||||
from apps.organization.models import Organization
|
||||
from django.db import transaction
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class OrganizationNotFoundError(ValueError):
|
||||
"""Raised when a non-Mostovik import references an unknown organization."""
|
||||
|
||||
|
||||
class OrganizationService(BaseService[Organization]):
|
||||
@@ -20,7 +15,7 @@ class OrganizationService(BaseService[Organization]):
|
||||
Сервис для работы с организациями.
|
||||
|
||||
Методы:
|
||||
get_or_create_by_inn: Получить или создать организацию по ИНН
|
||||
get_or_create_by_inn: Legacy lookup API. Creation is intentionally disabled.
|
||||
update_organization: Обновить данные организации
|
||||
search_by_name: Поиск по наименованию
|
||||
"""
|
||||
@@ -28,53 +23,35 @@ class OrganizationService(BaseService[Organization]):
|
||||
model = Organization
|
||||
|
||||
@classmethod
|
||||
@transaction.atomic
|
||||
def get_or_create_by_inn(
|
||||
cls,
|
||||
inn: str,
|
||||
defaults: dict[str, Any] | None = None,
|
||||
) -> tuple[Organization, bool]:
|
||||
"""
|
||||
Получить или создать организацию по ИНН.
|
||||
Получить организацию по ИНН без создания новой записи.
|
||||
|
||||
Args:
|
||||
inn: ИНН организации
|
||||
defaults: Значения по умолчанию для создания
|
||||
|
||||
Returns:
|
||||
(Organization, created) - организация и флаг создания
|
||||
Организации создаются только из Mostovik exchange-пакетов. Метод сохраняет
|
||||
старую сигнатуру для существующих импортов форм, но при отсутствии ИНН
|
||||
выбрасывает ошибку вместо создания справочника из вторичных источников.
|
||||
"""
|
||||
defaults = defaults or {}
|
||||
_ = defaults
|
||||
return cls.get_required_by_inn(inn), False
|
||||
|
||||
org, created = cls.model.objects.get_or_create(
|
||||
inn=inn,
|
||||
defaults=defaults,
|
||||
)
|
||||
@classmethod
|
||||
def get_required_by_inn(cls, inn: str) -> Organization:
|
||||
"""Return organization by INN or fail explicitly."""
|
||||
normalized_inn = cls._clean_digits(inn)
|
||||
if not normalized_inn:
|
||||
raise OrganizationNotFoundError("ИНН организации не указан")
|
||||
|
||||
if created:
|
||||
logger.info(
|
||||
f"Создана организация: {org.name} (ИНН: {inn})",
|
||||
extra={"inn": inn, "org_id": str(org.id)},
|
||||
organization = cls.get_by_inn(normalized_inn)
|
||||
if organization is None:
|
||||
raise OrganizationNotFoundError(
|
||||
f"Организация с ИНН {normalized_inn} не найдена. "
|
||||
"Сначала загрузите организацию из Mostovik exchange-пакета."
|
||||
)
|
||||
else:
|
||||
# Обновляем данные если переданы новые
|
||||
updated_fields = []
|
||||
for field, value in defaults.items():
|
||||
if value and getattr(org, field, None) != value:
|
||||
# Обновляем только пустые поля или если значение изменилось
|
||||
current = getattr(org, field, None)
|
||||
if not current:
|
||||
setattr(org, field, value)
|
||||
updated_fields.append(field)
|
||||
|
||||
if updated_fields:
|
||||
org.save(update_fields=updated_fields + ["updated_at"])
|
||||
logger.info(
|
||||
f"Обновлена организация: {org.name} (ИНН: {inn}), поля: {updated_fields}",
|
||||
extra={"inn": inn, "org_id": str(org.id), "fields": updated_fields},
|
||||
)
|
||||
|
||||
return org, created
|
||||
return organization
|
||||
|
||||
@classmethod
|
||||
def search_by_name(cls, query: str, limit: int = 20):
|
||||
@@ -101,7 +78,16 @@ class OrganizationService(BaseService[Organization]):
|
||||
Returns:
|
||||
Organization или None
|
||||
"""
|
||||
normalized_inn = cls._clean_digits(inn)
|
||||
if not normalized_inn:
|
||||
return None
|
||||
try:
|
||||
return cls.model.objects.get(inn=inn)
|
||||
return cls.model.objects.get(inn=normalized_inn)
|
||||
except cls.model.DoesNotExist:
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _clean_digits(value: Any) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
return "".join(char for char in str(value).strip() if char.isdigit())
|
||||
|
||||
Reference in New Issue
Block a user