<commit_before>from collections import defaultdict

import simplejson as json
from django.contrib.auth.decorators import login_required
from django.core.cache import cache
from django.db import transaction
from django.db.models import Q, Prefetch
from django.http import JsonResponse

import users.models as users
from api.directions.views import get_research_for_direction_params
from directory.models import (
    Researches as DResearches,
    ParaclinicInputGroups,
    Fractions,
    ParaclinicTemplateName,
    ParaclinicInputField,
    ParaclinicTemplateField,
    HospitalService,
    DispensaryPlan, Localization, ServiceLocation,
)
from laboratory.decorators import group_required
from podrazdeleniya.models import Podrazdeleniya
from researches.models import Tubes
from rmis_integration.client import get_md5
from slog.models import Log
from users.models import Speciality


@login_required
def get_researches_templates(request):
    templates = []
    for t in (
        users.AssignmentTemplates.objects.filter(global_template=True)
        .filter(Q(doc__isnull=True, podrazdeleniye__isnull=True) | Q(doc=request.user.doctorprofile) | Q(podrazdeleniye=request.user.doctorprofile.podrazdeleniye))
        .prefetch_related('assignmentresearches_set')
    ):
        templates.append(
            {
                "values": [x.research_id for x in t.assignmentresearches_set.all()],
                "pk": t.pk,
                "title": t.title,
                "for_current_user": t.doc_id is not None,
                "for_users_department": t.podrazdeleniye_id is not None,
            }
        )
    result = {"templates": templates}
    if hasattr(request, 'plain_response') and request.plain_response:
        return result
    return JsonResponse(result)


def get_researches(request):
    deps = defaultdict(list)
    doctorprofile = request.user.doctorprofile
    k = f'get_researches:restricted_to_direct:{doctorprofile.pk}'
    restricted_to_direct = cache.get(k)
    if not restricted_to_direct:
        restricted_to_direct = [x['pk'] for x in doctorprofile.restricted_to_direct.all().values('pk')]
        cache.set(k, json.dumps(restricted_to_direct), 30)
    else:
        restricted_to_direct = json.loads(restricted_to_direct)
    mk = f'get_researches:result:{get_md5(";".join(restricted_to_direct))}'
    result = cache.get(mk)
    if not result:
        res = (
            DResearches.objects.filter(hide=False)
            .exclude(pk__in=restricted_to_direct)
            .select_related('podrazdeleniye', 'comment_variants')
            .prefetch_related(
                Prefetch('localization', queryset=Localization.objects.only('pk', 'title'), to_attr='localization_list'),
                Prefetch('service_location', queryset=ServiceLocation.objects.only('pk', 'title'), to_attr='service_location_list'),
                'a',
                'b',
            )
            .distinct('title', 'pk')
            .order_by('title')
            .defer(
                "preparation",
                "paraclinic_info",
                "instructions",
                "internal_code",
                "co_executor_2_title",<commit_msg>Fixes<commit_after>from collections import defaultdict

import simplejson as json
from django.contrib.auth.decorators import login_required
from django.core.cache import cache
from django.db import transaction
from django.db.models import Q, Prefetch
from django.http import JsonResponse

import users.models as users
from api.directions.views import get_research_for_direction_params
from directory.models import (
    Researches as DResearches,
    ParaclinicInputGroups,
    Fractions,
    ParaclinicTemplateName,
    ParaclinicInputField,
    ParaclinicTemplateField,
    HospitalService,
    DispensaryPlan, Localization, ServiceLocation,
)
from laboratory.decorators import group_required
from podrazdeleniya.models import Podrazdeleniya
from researches.models import Tubes
from rmis_integration.client import get_md5
from slog.models import Log
from users.models import Speciality


@login_required
def get_researches_templates(request):
    templates = []
    for t in (
        users.AssignmentTemplates.objects.filter(global_template=True)
        .filter(Q(doc__isnull=True, podrazdeleniye__isnull=True) | Q(doc=request.user.doctorprofile) | Q(podrazdeleniye=request.user.doctorprofile.podrazdeleniye))
        .prefetch_related('assignmentresearches_set')
    ):
        templates.append(
            {
                "values": [x.research_id for x in t.assignmentresearches_set.all()],
                "pk": t.pk,
                "title": t.title,
                "for_current_user": t.doc_id is not None,
                "for_users_department": t.podrazdeleniye_id is not None,
            }
        )
    result = {"templates": templates}
    if hasattr(request, 'plain_response') and request.plain_response:
        return result
    return JsonResponse(result)


def get_researches(request):
    deps = defaultdict(list)
    doctorprofile = request.user.doctorprofile
    k = f'get_researches:restricted_to_direct:{doctorprofile.pk}'
    restricted_to_direct = cache.get(k)
    if not restricted_to_direct:
        restricted_to_direct = [x['pk'] for x in doctorprofile.restricted_to_direct.all().values('pk')]
        cache.set(k, json.dumps(restricted_to_direct), 30)
    else:
        restricted_to_direct = json.loads(restricted_to_direct)
    mk = f'get_researches:result:{get_md5(";".join([str(x) for x in restricted_to_direct]))}'
    result = cache.get(mk)
    if not result:
        res = (
            DResearches.objects.filter(hide=False)
            .exclude(pk__in=restricted_to_direct)
            .select_related('podrazdeleniye', 'comment_variants')
            .prefetch_related(
                Prefetch('localization', queryset=Localization.objects.only('pk', 'title'), to_attr='localization_list'),
                Prefetch('service_location', queryset=ServiceLocation.objects.only('pk', 'title'), to_attr='service_location_list'),
                'a',
                'b',
            )
            .distinct('title', 'pk')
            .order_by('title')
            .defer(
                "preparation",
                "paraclinic_info",
                "instructions",
                "internal_code",
                "co_executor_2_title",
{'fraction_non_alphanumeric': 0.0940547341931425, 'fraction_numerical': 0.0015728216420257944, 'mean_word_length': 3.0374603174603174, 'pattern_counts': {'":': 12, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1841420', 'n_tokens_mistral': 1937, 'n_tokens_neox': 1838, 'n_words': 361}