96 lines
2.8 KiB
Python
96 lines
2.8 KiB
Python
"""Helpers for corporation scope derivation from active registries."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from collections.abc import Iterable
|
|
|
|
from django.db.models import Q, QuerySet
|
|
|
|
SCOPE_KEYWORDS: dict[str, tuple[str, ...]] = {
|
|
"rosatom": ("Росатом",),
|
|
"roscosmos": ("Роскосмос",),
|
|
"opk": ("ОПК",),
|
|
}
|
|
|
|
SCOPE_LABELS: dict[str, str] = {
|
|
"rosatom": "Госкорпорация «Росатом»",
|
|
"roscosmos": "Госкорпорация «Роскосмос»",
|
|
"opk": "Организации ОПК",
|
|
"other": "Иная корпорация",
|
|
}
|
|
|
|
SCOPE_SHORT_NAMES: dict[str, str] = {
|
|
"rosatom": "Росатом",
|
|
"roscosmos": "Роскосмос",
|
|
"opk": "ОПК",
|
|
"other": "Иная",
|
|
}
|
|
|
|
SCOPE_SORT_ORDER: dict[str, int] = {
|
|
"rosatom": 10,
|
|
"roscosmos": 20,
|
|
"opk": 30,
|
|
"other": 90,
|
|
}
|
|
|
|
|
|
def scopes_from_registry_names(registry_names: Iterable[str]) -> list[str]:
|
|
normalized_names = [registry_name.casefold() for registry_name in registry_names]
|
|
scopes: list[str] = []
|
|
|
|
for scope, keywords in SCOPE_KEYWORDS.items():
|
|
if any(
|
|
keyword.casefold() in registry_name
|
|
for registry_name in normalized_names
|
|
for keyword in keywords
|
|
):
|
|
scopes.append(scope)
|
|
|
|
return scopes
|
|
|
|
|
|
def scope_labels(scope_codes: Iterable[str]) -> list[str]:
|
|
return [SCOPE_LABELS[code] for code in scope_codes if code in SCOPE_LABELS]
|
|
|
|
|
|
def get_corporation_scope_dictionary() -> list[dict[str, str | int]]:
|
|
"""Возвращает справочник корпусов для API-словаря."""
|
|
items: list[dict[str, str | int]] = []
|
|
for code, sort_order in sorted(
|
|
SCOPE_SORT_ORDER.items(), key=lambda item: item[1]
|
|
):
|
|
label = SCOPE_LABELS.get(code)
|
|
short_name = SCOPE_SHORT_NAMES.get(code)
|
|
if not label or not short_name:
|
|
continue
|
|
items.append(
|
|
{
|
|
"code": code,
|
|
"name": label,
|
|
"short_name": short_name,
|
|
"sort_order": sort_order,
|
|
}
|
|
)
|
|
return items
|
|
|
|
|
|
def build_scope_query(scope_codes: Iterable[str]) -> Q:
|
|
query = Q()
|
|
for scope_code in scope_codes:
|
|
keywords = SCOPE_KEYWORDS.get(scope_code, ())
|
|
for keyword in keywords:
|
|
query |= Q(
|
|
membership_periods__registry__name__contains=keyword,
|
|
membership_periods__ended_at__isnull=True,
|
|
)
|
|
return query
|
|
|
|
|
|
def filter_queryset_by_scopes(
|
|
queryset: QuerySet, scope_codes: Iterable[str]
|
|
) -> QuerySet:
|
|
scope_codes = [code for code in scope_codes if code in SCOPE_KEYWORDS]
|
|
if not scope_codes:
|
|
return queryset.none()
|
|
return queryset.filter(build_scope_query(scope_codes)).distinct()
|