<commit_before>import collections
import time
from operator import itemgetter

import simplejson as json
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import JsonResponse
from django.utils import dateformat, timezone

from api.dicom import search_dicom_study
from api.sql_func import get_fraction_result, get_field_result
from api.views import get_reset_time_vars
from appconf.manager import SettingManager
from clients.models import Card, Individual, DispensaryReg, BenefitReg
from directions.models import Napravleniya, Issledovaniya, Result, ParaclinicResult, Recipe, MethodsOfTaking
from directory.models import Fractions, ParaclinicInputGroups, ParaclinicTemplateName, ParaclinicInputField
from laboratory import settings
from laboratory.decorators import group_required
from laboratory.utils import strdatetime, strdate, tsdatetime, localtime, start_end_year
from results.views import result_normal
from rmis_integration.client import Client, get_direction_full_data_cache
from slog.models import Log
from statistics_tickets.models import VisitPurpose, ResultOfTreatment, Outcomes
from utils.dates import try_parse_range
from api import sql_func


@login_required
@group_required("Лечащий врач", "Оператор лечащего врача")
def directions_generate(request):
    result = {"ok": False, "directions": [], "message": ""}
    if request.method == "POST":
        p = json.loads(request.body)
        type_card = Card.objects.get(pk=p.get("card_pk"))
        if type_card.base.forbidden_create_napr:
            result["message"] = "Для данного типа карт нельзя создать направления"
            return JsonResponse(result)
        rc = Napravleniya.gen_napravleniya_by_issledovaniya(p.get("card_pk"),
                                                            p.get("diagnos"),
                                                            p.get("fin_source"),
                                                            p.get("history_num"),
                                                            p.get("ofname_pk"),
                                                            request.user.doctorprofile,
                                                            p.get("researches"),
                                                            p.get("comments"),
                                                            p.get("for_rmis"),
                                                            p.get("rmis_data", {}),
                                                            vich_code=p.get("vich_code", ""),
                                                            count=p.get("count", 1),
                                                            discount=p.get("discount", 0),
                                                            parent_iss=p.get("parent_iss", None),
                                                            counts=p.get("counts", {}),
                                                            localizations=p.get("localizations", {}),
                                                            service_locations=p.get("service_locations", {}))
        result["ok"] = rc["r"]
        result["directions"] = rc["list_id"]
        if "message" in rc:
            result["message"] = rc["message"]
    return JsonResponse(result)


@login_required
def directions_history(request):
    res = {"directions": []}
    request_data = json.loads(request.body)

    pk = request_data.get("patient", -1)
    req_status = request_data.get("type", 4)
    iss_pk = request_data.get("iss_pk", None)
    services = request_data.get("services", [])
    services = list(map(int, services or []))

    date_start, date_end = try_parse_range(request_data["date_from"], request_data["date_to"])
    try:
        if pk >= 0 or req_status == 4 or iss_pk:
            if iss_pk:
                rows = Napravleniya.objects.filter(parent_id=iss_pk).order_by("data_sozdaniya").prefetch_related()
            elif req_status != 4:
                rows = Napravleniya.objects.filter(data_sozdaniya__range=(date_start, date_end),
                                                   client__pk=pk).order_by(
                    "-data_sozdaniya").prefetch_related()
            else:
                rows = Napravleniya.objects.filter(Q(data_sozdaniya__range=(date_start, date_end),
                                                     doc_who_create=request.user.doctorprofile)
                                                   | Q(data_sozdaniya__range=(date_start, date_end),
                                                       doc=request.user.doctorprofile)).order_by(
                    "-data_sozdaniya")

            if services:
                rows = rows.filter(issledovaniya__research__pk__in=services)

            for napr in rows.values("pk", "data_sozdaniya", "cancel"):
                iss_list = Issledovaniya.objects.filter(napravleniye__pk=napr["pk"]).prefetch_related(
                    "tubes", "research", "research__podrazdeleniye")
                if not iss_list.exists():
                    continue
                status = 2  # 0 - выписано. 1 - Материал получен лабораторией. 2 - результат подтвержден. -1 - отменено
                has_conf = False
                researches_list = []
                researches_pks = []
                has_descriptive = False
                has_hosp = False
                for v in iss_list:
                    if not has_descriptive and v.research.desc:
                        has_descriptive = True
                    if not has_hosp and v.research.is_hospital:
                        has_hosp = True
                    researches_list.append(v.research.title)
                    researches_pks.append(v.research_id)
                    iss_status = 1
                    if not v.doc_confirmation and not v.doc_save and not v.deferred:
                        iss_status = 1
                        if v.tubes.count() == 0:
                            iss_status = 0
                        else:
                            for t in v.tubes.all():
                                if not t.time_recive:
                                    iss_status = 0
                    elif v.doc_confirmation or v.deferred:
                        iss_status = 2
                    if v.doc_confirmation and not has_conf:
                        has_conf = True
                    status = min(iss_status, status)
                if status == 2 and not has_conf:
                    status = 1
                if req_status in [3, 4] or req_status == status or iss_pk:
                    res["directions"].append(
                        {"pk": napr["pk"], "status": -1 if status == 0 and napr["cancel"] else status,
                         "researches": ' | '.join(researches_list),
                         "researches_pks": researches_pks,
                         "date": str(<commit_msg>Exclude naprs from history api.direction when research has attrs 'is_slave_hospital'<commit_after>import collections
import time
from operator import itemgetter

import simplejson as json
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import JsonResponse
from django.utils import dateformat, timezone

from api.dicom import search_dicom_study
from api.sql_func import get_fraction_result, get_field_result
from api.views import get_reset_time_vars
from appconf.manager import SettingManager
from clients.models import Card, Individual, DispensaryReg, BenefitReg
from directions.models import Napravleniya, Issledovaniya, Result, ParaclinicResult, Recipe, MethodsOfTaking
from directory.models import Fractions, ParaclinicInputGroups, ParaclinicTemplateName, ParaclinicInputField
from laboratory import settings
from laboratory.decorators import group_required
from laboratory.utils import strdatetime, strdate, tsdatetime, localtime, start_end_year
from results.views import result_normal
from rmis_integration.client import Client, get_direction_full_data_cache
from slog.models import Log
from statistics_tickets.models import VisitPurpose, ResultOfTreatment, Outcomes
from utils.dates import try_parse_range
from api import sql_func


@login_required
@group_required("Лечащий врач", "Оператор лечащего врача")
def directions_generate(request):
    result = {"ok": False, "directions": [], "message": ""}
    if request.method == "POST":
        p = json.loads(request.body)
        type_card = Card.objects.get(pk=p.get("card_pk"))
        if type_card.base.forbidden_create_napr:
            result["message"] = "Для данного типа карт нельзя создать направления"
            return JsonResponse(result)
        rc = Napravleniya.gen_napravleniya_by_issledovaniya(p.get("card_pk"),
                                                            p.get("diagnos"),
                                                            p.get("fin_source"),
                                                            p.get("history_num"),
                                                            p.get("ofname_pk"),
                                                            request.user.doctorprofile,
                                                            p.get("researches"),
                                                            p.get("comments"),
                                                            p.get("for_rmis"),
                                                            p.get("rmis_data", {}),
                                                            vich_code=p.get("vich_code", ""),
                                                            count=p.get("count", 1),
                                                            discount=p.get("discount", 0),
                                                            parent_iss=p.get("parent_iss", None),
                                                            counts=p.get("counts", {}),
                                                            localizations=p.get("localizations", {}),
                                                            service_locations=p.get("service_locations", {}))
        result["ok"] = rc["r"]
        result["directions"] = rc["list_id"]
        if "message" in rc:
            result["message"] = rc["message"]
    return JsonResponse(result)


@login_required
def directions_history(request):
    res = {"directions": []}
    request_data = json.loads(request.body)

    pk = request_data.get("patient", -1)
    req_status = request_data.get("type", 4)
    iss_pk = request_data.get("iss_pk", None)
    services = request_data.get("services", [])
    services = list(map(int, services or []))

    date_start, date_end = try_parse_range(request_data["date_from"], request_data["date_to"])
    try:
        if pk >= 0 or req_status == 4 or iss_pk:
            if iss_pk:
                rows = Napravleniya.objects.filter(parent_id=iss_pk).order_by("data_sozdaniya").prefetch_related()
            elif req_status != 4:
                rows = Napravleniya.objects.filter(data_sozdaniya__range=(date_start, date_end),
                                                   client__pk=pk).order_by(
                    "-data_sozdaniya").prefetch_related()
            else:
                rows = Napravleniya.objects.filter(Q(data_sozdaniya__range=(date_start, date_end),
                                                     doc_who_create=request.user.doctorprofile)
                                                   | Q(data_sozdaniya__range=(date_start, date_end),
                                                       doc=request.user.doctorprofile)).order_by(
                    "-data_sozdaniya")

            if services:
                rows = rows.filter(issledovaniya__research__pk__in=services)

            for napr in rows.values("pk", "data_sozdaniya", "cancel"):
                iss_list = Issledovaniya.objects.filter(napravleniye__pk=napr["pk"]).prefetch_related(
                    "tubes", "research", "research__podrazdeleniye")
                if not iss_list.exists():
                    continue
                status = 2  # 0 - выписано. 1 - Материал получен лабораторией. 2 - результат подтвержден. -1 - отменено
                has_conf = False
                researches_list = []
                researches_pks = []
                has_descriptive = False
                has_hosp = False
                has_slave_hospital = False
                for v in iss_list:
                    if v.research.is_slave_hospital:
                        has_slave_hospital = True
                        break

                    if not has_descriptive and v.research.desc:
                        has_descriptive = True
                    if not has_hosp and v.research.is_hospital:
                        has_hosp = True
                    researches_list.append(v.research.title)
                    researches_pks.append(v.research_id)
                    iss_status = 1
                    if not v.doc_confirmation and not v.doc_save and not v.deferred:
                        iss_status = 1
                        if v.tubes.count() == 0:
                            iss_status = 0
                        else:
                            for t in v.tubes.all():
                                if not t.time_recive:
                                    iss_status = 0
                    elif v.doc_confirmation or v.deferred:
                        iss_status = 2
                    if v.doc_confirmation and not has_conf:
                        has_conf = True
                    status = min(iss_status, status)
                if has_slave_hospital:
                    continue
                if status == 2 and not has_conf:
                    status = 1
                if req_status in [3, 4] or req_status == status or iss_pk:
                    res["directions"].append(
                        {"pk": napr["pk"], "status": -1 if status == 0 and napr["cancel"] else status,
                         "researches": ' | '.join(researches_list),
                         "researches_pks": researches_pks,
                         "date": str(
{'fraction_non_alphanumeric': 0.08230250210851842, 'fraction_numerical': 0.0033736294630306437, 'mean_word_length': 1.4207213337870024, 'pattern_counts': {'":': 20, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 84, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4702967', 'n_tokens_mistral': 3645, 'n_tokens_neox': 3461, 'n_words': 764}