From 98e2da8348d3ba923a6702dfdcf487fa202bffad Mon Sep 17 00:00:00 2001 From: Sergei Kasianenko Date: Thu, 19 Oct 2023 07:59:33 +0800 Subject: [PATCH 1/4] get refbook --- directory/sql_func.py | 33 ++++++++++++++++++++ integration_framework/urls.py | 1 + integration_framework/views.py | 55 ++++++++++++++++++++++++++++++++++ pyproject.toml | 2 +- 4 files changed, 90 insertions(+), 1 deletion(-) diff --git a/directory/sql_func.py b/directory/sql_func.py index e141ab34fb..2b36524b12 100644 --- a/directory/sql_func.py +++ b/directory/sql_func.py @@ -35,3 +35,36 @@ def is_lab_filter_research(reserches_id): ) rows = namedtuplefetchall(cursor) return rows + + +def get_lab_research_reference_books(): + with connection.cursor() as cursor: + cursor.execute( + """ + SELECT + directory_fractions.id as fraction_id, + directory_fractions.title as fraction_title, + directory_fractions.fsli as fraction_fsli, + directory_fractions.ref_m as fraction_ref_m, + directory_fractions.ref_f as fraction_ref_f, + + du.title as unit_title, + du.code as unit_code, + du.ucum as unit_ucum, + + dr.id as research_id, + dr.title as research_title, + dr.internal_code as research_internal_code, + dr.code as research_nmu_code + + FROM directory_fractions + LEFT JOIN directory_researches dr on dr.id = directory_fractions.research_id + LEFT JOIN directory_unit du on du.id = directory_fractions.unit_id + LEFT JOIN podrazdeleniya_podrazdeleniya pp on dr.podrazdeleniye_id = pp.id + WHERE pp.p_type = 2 + order by dr.id + """, + params={}, + ) + rows = namedtuplefetchall(cursor) + return rows diff --git a/integration_framework/urls.py b/integration_framework/urls.py index 9fe8300feb..0e5a82cc2a 100644 --- a/integration_framework/urls.py +++ b/integration_framework/urls.py @@ -58,4 +58,5 @@ path('get-value-field', views.get_value_field), path('get-price-data', views.get_price_data), path('get-prices-by-date', views.get_prices_by_date), + path('get-reference-books', views.get_reference_books), ] diff --git a/integration_framework/views.py b/integration_framework/views.py index 5c1bd0c983..1c7ada8e26 100644 --- a/integration_framework/views.py +++ b/integration_framework/views.py @@ -93,6 +93,7 @@ from laboratory.settings import COVID_RESEARCHES_PK from .utils import get_json_protocol_data, get_json_labortory_data, check_type_file, legal_auth_get, author_doctor from django.contrib.auth.models import User +from directory.sql_func import get_lab_research_reference_books logger = logging.getLogger("IF") @@ -3088,3 +3089,57 @@ def get_prices_by_date(request): } for i in prices] return Response({"data": result}) + + +@api_view(['POST']) +def get_reference_books(request): + request_data = json.loads(request.body) + token = request.headers.get("Authorization").split(" ")[1] + token_obj = Application.objects.filter(key=token).first() + mode = request_data.get('mode') + is_lab = request_data.get('isLab', mode == 'laboratory') + if not token_obj.unlimited_access: + return Response({"ok": False, 'message': 'Некорректный auth токен'}) + result = [] + if is_lab: + lab_data = get_lab_research_reference_books() + service_result = { + "serviceId": "", + "serviceTitle": "", + "serviceInternalCode": "", + "serviceNMUCode": "", + "fractions": [] + } + + last_research_id = -1 + step = 0 + tmp_result = service_result.copy() + fractions = [] + for i in lab_data: + if i.research_id != last_research_id: + if step != 0: + result.append(tmp_result.copy()) + fractions = [] + tmp_result = service_result.copy() + tmp_result["serviceId"] = i.research_id + tmp_result["serviceTitle"] = i.research_title + tmp_result["serviceInternalCode"] = i.research_internal_code + tmp_result["serviceNMUCode"] = i.research_nmu_code + tmp_result["fractions"] = fractions + + fractions.append({ + "id": i.fraction_id, + "title": i.fraction_title, + "fsli": i.fraction_fsli, + "ref_m": json.loads(i.fraction_ref_m), + "ref_f": json.loads(i.fraction_ref_f), + "unitTitle": i.unit_title, + "unitCode": i.unit_code, + "unitUcum": i.unit_ucum + }) + + last_research_id = i.research_id + step += 1 + tmp_result["fractions"] = fractions + result.append(tmp_result.copy()) + return JsonResponse({"result": result}) diff --git a/pyproject.toml b/pyproject.toml index c0e6794a6d..f1f63f5fbc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -72,7 +72,7 @@ beren = "0.7.1" transliterate = "1.10.2" imgkit = "1.2.3" astm = {git = "https://github.com/moodpulse/python-astm.git", rev = "v0.6"} -psycopg2-binary = "^2.9.4" +#psycopg2-binary = "^2.9.4" boto3 = "^1.28.64" prompt-toolkit = "^3.0.36" pdf2docx = "^0.5.6" From d8b5e507ae02aaeb8416295127df68350fd8e522 Mon Sep 17 00:00:00 2001 From: Sergei Kasianenko Date: Thu, 19 Oct 2023 07:59:42 +0800 Subject: [PATCH 2/4] get refbook --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index f1f63f5fbc..c0e6794a6d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -72,7 +72,7 @@ beren = "0.7.1" transliterate = "1.10.2" imgkit = "1.2.3" astm = {git = "https://github.com/moodpulse/python-astm.git", rev = "v0.6"} -#psycopg2-binary = "^2.9.4" +psycopg2-binary = "^2.9.4" boto3 = "^1.28.64" prompt-toolkit = "^3.0.36" pdf2docx = "^0.5.6" From 695bec9c7de49c3fb6393997635145298b85bb30 Mon Sep 17 00:00:00 2001 From: Sergei Kasianenko Date: Thu, 19 Oct 2023 08:02:44 +0800 Subject: [PATCH 3/4] black --- integration_framework/views.py | 1362 ++++++++++++++++---------------- pyproject.toml | 2 +- 2 files changed, 681 insertions(+), 683 deletions(-) diff --git a/integration_framework/views.py b/integration_framework/views.py index 1c7ada8e26..3e5f7f629a 100644 --- a/integration_framework/views.py +++ b/integration_framework/views.py @@ -103,26 +103,26 @@ def next_result_direction(request): from_pk = request.GET.get("fromPk") after_date = request.GET.get("afterDate") only_signed = request.GET.get("onlySigned") - if after_date == '0': + if after_date == "0": after_date = AFTER_DATE next_n = int(request.GET.get("nextN", 1)) - type_researches = request.GET.get("research", '*') - d_start = f'{after_date}' + type_researches = request.GET.get("research", "*") + d_start = f"{after_date}" is_research = 1 researches = [-999] - if type_researches == 'lab': + if type_researches == "lab": researches = [x.pk for x in Researches.objects.filter(podrazdeleniye__p_type=Podrazdeleniya.LABORATORY)] - elif type_researches == 'gistology': + elif type_researches == "gistology": researches = [x.pk for x in Researches.objects.filter(is_gistology=True)] - elif type_researches == 'paraclinic': + elif type_researches == "paraclinic": researches = [x.pk for x in Researches.objects.filter(is_paraclinic=True)] - elif type_researches != '*': - researches = [int(i) for i in type_researches.split(',')] + elif type_researches != "*": + researches = [int(i) for i in type_researches.split(",")] else: is_research = -1 dirs, dirs_eds = None, None - if only_signed == '1': + if only_signed == "1": # TODO: вернуть только подписанные и как дату next_time использовать дату подписания, а не подтверждения # признак – eds_total_signed=True, датавремя полного подписания eds_total_signed_at dirs_eds = sql_if.direction_collect_date_signed(d_start, researches, is_research, next_n) or [] @@ -188,14 +188,14 @@ def resend_dir_crie(request): def result_amd_send(request): result = json.loads(request.GET.get("result")) resp = {"ok": False} - if result['error']: - for i in result['error']: - dir_pk = int(i.split(':')[0]) + if result["error"]: + for i in result["error"]: + dir_pk = int(i.split(":")[0]) directions.Napravleniya.objects.filter(pk=dir_pk).update(need_resend_amd=False, error_amd=True) resp = {"ok": True} - if result['send']: - for i in result['send']: - data_amd = i.split(':') + if result["send"]: + for i in result["send"]: + data_amd = i.split(":") dir_pk = int(data_amd[0]) amd_num = data_amd[1] directions.Napravleniya.objects.filter(pk=dir_pk).update(need_resend_amd=False, amd_number=amd_num, error_amd=False) @@ -206,15 +206,15 @@ def result_amd_send(request): @api_view() def direction_data(request): pk = request.GET.get("pk") - research_pks = request.GET.get("research", '*') + research_pks = request.GET.get("research", "*") only_cda = request.GET.get("onlyCDA", False) - direction: directions.Napravleniya = directions.Napravleniya.objects.select_related('istochnik_f', 'client', 'client__individual', 'client__base').get(pk=pk) + direction: directions.Napravleniya = directions.Napravleniya.objects.select_related("istochnik_f", "client", "client__individual", "client__base").get(pk=pk) card = direction.client individual = card.individual - iss = directions.Issledovaniya.objects.filter(napravleniye=direction, time_confirmation__isnull=False).select_related('research', 'doc_confirmation') - if research_pks != '*': - iss = iss.filter(research__pk__in=research_pks.split(',')) + iss = directions.Issledovaniya.objects.filter(napravleniye=direction, time_confirmation__isnull=False).select_related("research", "doc_confirmation") + if research_pks != "*": + iss = iss.filter(research__pk__in=research_pks.split(",")) for i in iss: if len(REMD_ONLY_RESEARCH) > 0 and i.research.pk not in REMD_ONLY_RESEARCH: return Response({"ok": False}) @@ -234,18 +234,18 @@ def direction_data(request): if only_cda and d.file_type.upper() != "CDA": continue document = { - 'type': d.file_type.upper(), - 'content': base64.b64encode(d.file.read()).decode('utf-8'), - 'signatures': [], + "type": d.file_type.upper(), + "content": base64.b64encode(d.file.read()).decode("utf-8"), + "signatures": [], } for s in DocumentSign.objects.filter(document=d): - document['signatures'].append( + document["signatures"].append( { - "content": s.sign_value.replace('\n', ''), + "content": s.sign_value.replace("\n", ""), "type": s.sign_type, "executor": s.executor.uploading_data, - "crc32": zlib.crc32(base64.b64decode(s.sign_value.replace('\n', '').encode())), + "crc32": zlib.crc32(base64.b64decode(s.sign_value.replace("\n", "").encode())), } ) @@ -265,7 +265,7 @@ def direction_data(request): "birthday": individual.birthday, "docs": card.get_n3_documents(), "sex": individual.sex, - 'gender': individual.sex.lower(), + "gender": individual.sex.lower(), "card": { "base": {"pk": card.base_id, "title": card.base.title, "short_title": card.base.short_title}, "pk": card.pk, @@ -282,14 +282,14 @@ def direction_data(request): "department_oid": iss[iss_index].doc_confirmation.podrazdeleniye.oid if iss[iss_index].doc_confirmation else None, "department_name": iss[iss_index].doc_confirmation.podrazdeleniye.nsi_title if iss[iss_index].doc_confirmation else None, "kind": iss[iss_index].research.oid_kind if iss[iss_index].doc_confirmation else None, - "finSourceTitle": direction.istochnik_f.title if direction.istochnik_f else 'другое', - "finSourceCode": direction.istochnik_f.get_n3_code() if direction.istochnik_f else '6', - "finSourceEcpCode": direction.istochnik_f.get_ecp_code() if direction.istochnik_f else '380101000000023', + "finSourceTitle": direction.istochnik_f.title if direction.istochnik_f else "другое", + "finSourceCode": direction.istochnik_f.get_n3_code() if direction.istochnik_f else "6", + "finSourceEcpCode": direction.istochnik_f.get_ecp_code() if direction.istochnik_f else "380101000000023", "oldPk": direction.core_id, "isExternal": direction.is_external, "titleInitiator": direction.get_title_org_initiator(), "ogrnInitiator": direction.get_ogrn_org_initiator(), - "titleLaboratory": direction.hospital_title.replace("\"", " "), + "titleLaboratory": direction.hospital_title.replace('"', " "), "ogrnLaboratory": direction.hospital_ogrn, "hospitalN3Id": direction.hospital_n3id, "departmentN3Id": direction.department_n3id, @@ -318,10 +318,10 @@ def format_time_if_is_not_none(t): @api_view() def issledovaniye_data(request): pk = request.GET.get("pk") - ignore_sample = request.GET.get("ignoreSample") == 'true' + ignore_sample = request.GET.get("ignoreSample") == "true" i = directions.Issledovaniya.objects.get(pk=pk) sample = directions.TubesRegistration.objects.filter(issledovaniya=i, time_get__isnull=False).first() - results = directions.Result.objects.filter(issledovaniye=i).exclude(fraction__fsli__isnull=True).exclude(fraction__fsli='').exclude(fraction__not_send_odli=True) + results = directions.Result.objects.filter(issledovaniye=i).exclude(fraction__fsli__isnull=True).exclude(fraction__fsli="").exclude(fraction__not_send_odli=True) if ( (not ignore_sample and not sample) or (not results.exists() and not i.research.is_gistology and not i.research.is_paraclinic and not i.research.is_slave_hospital) @@ -343,31 +343,31 @@ def issledovaniye_data(request): refs = [refs.const_orig] else: refs_list = [str(refs.range.val_from.value), str(refs.range.val_to.value)] - if refs_list[0] == '-inf': - refs = [f'до {refs_list[1]}'] - elif refs_list[1] == 'inf': - refs = [f'от {refs_list[0]}'] + if refs_list[0] == "-inf": + refs = [f"до {refs_list[1]}"] + elif refs_list[1] == "inf": + refs = [f"от {refs_list[0]}"] elif refs_list[0] == refs_list[1]: refs = [refs.const_orig] else: refs = refs_list else: - refs = [r.calc_normal(only_ref=True) or ''] + refs = [r.calc_normal(only_ref=True) or ""] norm = r.calc_normal() u = r.fraction.get_unit() if not REFERENCE_ODLI: - refs = [''] + refs = [""] results_data.append( { "pk": r.pk, "fsli": r.fraction.get_fsli_code(), - "value": r.value.replace(',', '.'), + "value": r.value.replace(",", "."), "units": r.get_units(), "unitCode": u.code if u else None, "ref": refs, - "interpretation": 'N' if norm and norm[0] == ResultRight.RESULT_MODE_NORMAL else 'A', + "interpretation": "N" if norm and norm[0] == ResultRight.RESULT_MODE_NORMAL else "A", } ) @@ -389,7 +389,7 @@ def issledovaniye_data(request): "docConfirm": i.doc_confirmation_fio, "doctorData": doctor_data, "results": results_data, - "code": i.research.code.upper().replace('А', 'A').replace('В', 'B').replace('С', 'C').strip(), + "code": i.research.code.upper().replace("А", "A").replace("В", "B").replace("С", "C").strip(), "research": i.research.get_title(), "comments": i.lab_comment, "isGistology": i.research.is_gistology, @@ -457,9 +457,9 @@ def issledovaniye_data_simple(request): "date": i.time_confirmation_local, "docConfirm": i.doc_confirmation_fio, "doctorData": doctor_data, - "outcome": (i.outcome_illness.n3_id if i.outcome_illness else None) or '3', - "visitPlace": (i.place.n3_id if i.place else None) or '1', - "visitPurpose": (i.purpose.n3_id if i.purpose else None) or '2', + "outcome": (i.outcome_illness.n3_id if i.outcome_illness else None) or "3", + "visitPlace": (i.place.n3_id if i.place else None) or "1", + "visitPurpose": (i.purpose.n3_id if i.purpose else None) or "2", "typeFlags": i.research.get_flag_types_n3(), "typeResInstr": type_res_instr_iemk, "activityCodeResearch": i.research.code, @@ -472,12 +472,12 @@ def issledovaniye_data_simple(request): @api_view() def issledovaniye_data_multi(request): pks = request.GET["pks"].split(",") - ignore_sample = request.GET.get("ignoreSample") == 'true' + ignore_sample = request.GET.get("ignoreSample") == "true" iss = ( directions.Issledovaniya.objects.filter(pk__in=pks) - .select_related('doc_confirmation', 'research') - .prefetch_related(Prefetch('result_set', queryset=(directions.Result.objects.filter(fraction__fsli__isnull=False).select_related('fraction')))) - .prefetch_related(Prefetch('tubes', queryset=(directions.TubesRegistration.objects.filter(time_get__isnull=False)))) + .select_related("doc_confirmation", "research") + .prefetch_related(Prefetch("result_set", queryset=(directions.Result.objects.filter(fraction__fsli__isnull=False).select_related("fraction")))) + .prefetch_related(Prefetch("tubes", queryset=(directions.TubesRegistration.objects.filter(time_get__isnull=False)))) ) result = [] @@ -500,14 +500,14 @@ def issledovaniye_data_multi(request): refs = [refs.const] else: refs = [str(refs.range.val_from.value), str(refs.range.val_to.value)] - if refs[0] == '-inf': - refs = [f'до {refs[1]}'] - elif refs[1] == 'inf': - refs = [f'от {refs[0]}'] + if refs[0] == "-inf": + refs = [f"до {refs[1]}"] + elif refs[1] == "inf": + refs = [f"от {refs[0]}"] elif refs[0] == refs[1]: refs = [refs[0]] else: - refs = [r.calc_normal(only_ref=True) or ''] + refs = [r.calc_normal(only_ref=True) or ""] results_data.append( { @@ -515,7 +515,7 @@ def issledovaniye_data_multi(request): "issTitle": i.research.title, "title": r.fraction.title, "fsli": r.fraction.get_fsli_code(), - "value": r.value.replace(',', '.'), + "value": r.value.replace(",", "."), "units": r.get_units(), "ref": refs, "confirmed": i.time_confirmation, @@ -547,7 +547,7 @@ def issledovaniye_data_multi(request): ) -@api_view(['GET', 'POST']) +@api_view(["GET", "POST"]) def make_log(request): key = request.GET.get("key") keys = request.GET.get("keys", key).split(",") @@ -594,10 +594,10 @@ def make_log(request): for k in pks_to_set_odli_id: Log.log(key=k, type=t, body=body.get(k, {})) - if str(k) in body and isinstance(body[k], dict) and body[str(k)]['id']: + if str(k) in body and isinstance(body[k], dict) and body[str(k)]["id"]: d = directions.Napravleniya.objects.get(pk=k) - d.n3_odli_id = body[str(k)]['id'] - d.save(update_fields=['n3_odli_id']) + d.n3_odli_id = body[str(k)]["id"] + d.save(update_fields=["n3_odli_id"]) for k in pks_to_set_vi_fail: Log.log(key=k, type=t, body=body.get(k, {})) @@ -605,10 +605,10 @@ def make_log(request): for k in pks_to_set_vi: Log.log(key=k, type=t, body=body.get(k, {})) - if str(k) in body and isinstance(body[k], dict) and body[str(k)]['id']: + if str(k) in body and isinstance(body[k], dict) and body[str(k)]["id"]: d = directions.Napravleniya.objects.get(pk=k) - d.vi_id = body[str(k)]['id'] - d.save(update_fields=['vi_id']) + d.vi_id = body[str(k)]["id"] + d.save(update_fields=["vi_id"]) for k in pks_to_set_iemk_fail: Log.log(key=k, type=t, body=body.get(k, {})) @@ -618,7 +618,7 @@ def make_log(request): d = directions.Napravleniya.objects.get(pk=k) d.n3_iemk_ok = True - d.save(update_fields=['n3_iemk_ok']) + d.save(update_fields=["n3_iemk_ok"]) for k in pks_to_set_onkor_fail: Log.log(key=k, type=t, body=body.get(k, {})) @@ -627,8 +627,8 @@ def make_log(request): Log.log(key=k, type=t, body=body.get(k, {})) d = directions.Napravleniya.objects.get(pk=k) - d.onkor_message_id = body[str(k)]['messageId'] - d.save(update_fields=['onkor_message_id']) + d.onkor_message_id = body[str(k)]["messageId"] + d.save(update_fields=["onkor_message_id"]) for k in pks_to_set_emdr_fail: Log.log(key=k, type=t, body=body.get(k, {})) @@ -644,74 +644,74 @@ def make_log(request): d = directions.Napravleniya.objects.get(pk=k) d.ecp_ok = True - d.save(update_fields=['ecp_ok']) + d.save(update_fields=["ecp_ok"]) iss: Issledovaniya for iss in Issledovaniya.objects.filter(napravleniye_id=k): if str(iss.pk) in body.get(k, {}): - if 'ecpServiceId' in body[k][str(iss.pk)]: - iss.ecp_evn_id = str(body[k][str(iss.pk)]['ecpServiceId'] or '') or None - iss.save(update_fields=['ecp_evn_id']) + if "ecpServiceId" in body[k][str(iss.pk)]: + iss.ecp_evn_id = str(body[k][str(iss.pk)]["ecpServiceId"] or "") or None + iss.save(update_fields=["ecp_evn_id"]) return Response({"ok": True}) -@api_view(['GET']) +@api_view(["GET"]) def crie_status(request): pk = request.GET.get("direction") system_id = request.GET.get("system_id") - status = request.GET.get("status") or 'null' - error = request.GET.get("error") or '' + status = request.GET.get("status") or "null" + error = request.GET.get("error") or "" direction = directions.Napravleniya.objects.filter(pk=pk).first() if direction: if direction.need_resend_crie: direction.need_resend_crie = False - direction.save(update_fields=['need_resend_crie']) + direction.save(update_fields=["need_resend_crie"]) order = CrieOrder.objects.filter(local_direction=direction).first() if not order: order = CrieOrder.objects.create(local_direction=direction, system_id=system_id, status=status, error=error) - updated = ['system_id', 'status', 'error', 'local_direction'] + updated = ["system_id", "status", "error", "local_direction"] else: updated = [] if order.system_id != system_id: order.system_id = system_id - updated.append('system_id') + updated.append("system_id") if order.status != status: order.status = status - updated.append('status') + updated.append("status") if order.error != error: order.error = error - updated.append('error') + updated.append("error") if updated: order.save(update_fields=updated) if updated: - Log.log(key=pk, type=60006, body={'updated': updated, 'order_id': order.pk}) + Log.log(key=pk, type=60006, body={"updated": updated, "order_id": order.pk}) return Response({"ok": True, "order": order.pk}) return Response({"ok": False}) -@api_view(['POST']) +@api_view(["POST"]) def check_enp(request): enp, family, name, patronymic, bd, enp_mode, snils = data_parse( request.body, - {'enp': str, 'family': str, 'name': str, 'patronymic': str, 'bd': str, 'check_mode': str, 'snils': str}, - {'check_mode': 'tfoms', 'bd': None, 'name': None, 'patronymic': None, 'family': None, 'enp': None, 'ud': None, 'snils': None}, + {"enp": str, "family": str, "name": str, "patronymic": str, "bd": str, "check_mode": str, "snils": str}, + {"check_mode": "tfoms", "bd": None, "name": None, "patronymic": None, "family": None, "enp": None, "ud": None, "snils": None}, ) if not enp: enp = "" - enp = enp.replace(' ', '') + enp = enp.replace(" ", "") - logger.exception(f'enp_mode: {enp_mode}') + logger.exception(f"enp_mode: {enp_mode}") - if enp_mode == 'l2-enp': + if enp_mode == "l2-enp": tfoms_data = match_enp(enp) if tfoms_data: - return Response({"ok": True, 'patient_data': tfoms_data}) + return Response({"ok": True, "patient_data": tfoms_data}) else: params = json.dumps( { @@ -728,20 +728,20 @@ def check_enp(request): request_obj._body = params request_obj.user = request.user data = patients_search_card(request_obj) - results_json = json.loads(data.content.decode('utf-8')) - if len(results_json['results']) > 0: - data_patient = results_json['results'][0] - docs_patinet = data_patient['docs'] + results_json = json.loads(data.content.decode("utf-8")) + if len(results_json["results"]) > 0: + data_patient = results_json["results"][0] + docs_patinet = data_patient["docs"] snils = "" for d in docs_patinet: - if d['type_title'] == 'СНИЛС': - snils = d['number'] + if d["type_title"] == "СНИЛС": + snils = d["number"] patient_data = { - "family": data_patient['family'], - "given": data_patient['name'], - "patronymic": data_patient['twoname'], - "gender": data_patient['sex'], - "birthdate": normalize_dots_date(data_patient['birthday']), + "family": data_patient["family"], + "given": data_patient["name"], + "patronymic": data_patient["twoname"], + "gender": data_patient["sex"], + "birthdate": normalize_dots_date(data_patient["birthday"]), "enp": enp, "birthyear": f"{normalize_dots_date(data_patient['birthday']).split('-')[0]}", "country": "RUS", @@ -770,19 +770,19 @@ def check_enp(request): "idt": "", "insurer_full_code": "", } - return Response({"ok": True, 'patient_data': patient_data, '1': results_json['results']}) - elif enp_mode == 'l2-enp-ud': + return Response({"ok": True, "patient_data": patient_data, "1": results_json["results"]}) + elif enp_mode == "l2-enp-ud": tfoms_data = get_ud_info_by_enp(enp) if tfoms_data: - return Response({"ok": True, 'patient_data': tfoms_data}) - elif enp_mode == 'l2-enp-dn': + return Response({"ok": True, "patient_data": tfoms_data}) + elif enp_mode == "l2-enp-dn": tfoms_data = get_dn_info_by_enp(enp) if tfoms_data: - return Response({"ok": True, 'patient_data': tfoms_data}) - elif enp_mode == 'l2-snils': + return Response({"ok": True, "patient_data": tfoms_data}) + elif enp_mode == "l2-snils": tfoms_data = match_patient_by_snils(snils) if tfoms_data: - return Response({"ok": True, 'patient_data': tfoms_data}) + return Response({"ok": True, "patient_data": tfoms_data}) else: params = json.dumps( { @@ -799,21 +799,21 @@ def check_enp(request): request_obj._body = params request_obj.user = request.user data = patients_search_card(request_obj) - results_json = json.loads(data.content.decode('utf-8')) - if len(results_json['results']) > 0: - data_patient = results_json['results'][0] - docs_patinet = data_patient['docs'] + results_json = json.loads(data.content.decode("utf-8")) + if len(results_json["results"]) > 0: + data_patient = results_json["results"][0] + docs_patinet = data_patient["docs"] snils = "" for d in docs_patinet: - if d['type_title'] == 'СНИЛС': - snils = d['number'] + if d["type_title"] == "СНИЛС": + snils = d["number"] patient_data = { "card": data_patient["pk"], - "family": data_patient['family'], - "given": data_patient['name'], - "patronymic": data_patient['twoname'], - "gender": data_patient['sex'], - "birthdate": normalize_dots_date(data_patient['birthday']), + "family": data_patient["family"], + "given": data_patient["name"], + "patronymic": data_patient["twoname"], + "gender": data_patient["sex"], + "birthdate": normalize_dots_date(data_patient["birthday"]), "enp": enp, "birthyear": f"{normalize_dots_date(data_patient['birthday']).split('-')[0]}", "country": "RUS", @@ -842,88 +842,88 @@ def check_enp(request): "idt": "", "insurer_full_code": "", } - return Response({"ok": True, 'patient_data': patient_data}) - elif enp_mode == 'l2-enp-full': - patronymic = patronymic if patronymic != 'None' else None - logger.exception(f'data: {(family, name, patronymic, bd)}') + return Response({"ok": True, "patient_data": patient_data}) + elif enp_mode == "l2-enp-full": + patronymic = patronymic if patronymic != "None" else None + logger.exception(f"data: {(family, name, patronymic, bd)}") tfoms_data = match_patient(family, name, patronymic, bd) if tfoms_data: - return Response({"ok": True, 'list': tfoms_data}) - elif enp_mode == 'tfoms': + return Response({"ok": True, "list": tfoms_data}) + elif enp_mode == "tfoms": tfoms_data = match_enp(enp) - logger.exception(f'tfoms data: {json.dumps(tfoms_data)}') + logger.exception(f"tfoms data: {json.dumps(tfoms_data)}") if tfoms_data: - bdate = tfoms_data.get('birthdate', '').split(' ')[0] + bdate = tfoms_data.get("birthdate", "").split(" ")[0] if normalize_date(bd) == normalize_date(bdate): - return Response({"ok": True, 'patient_data': tfoms_data}) - elif enp_mode == 'rmis': - logger.exception(f'enp: {enp}') - c = Client(modules=['patients']) + return Response({"ok": True, "patient_data": tfoms_data}) + elif enp_mode == "rmis": + logger.exception(f"enp: {enp}") + c = Client(modules=["patients"]) card = c.patients.get_l2_card_by_enp(enp) if card: - logger.exception(f'card: {card}') + logger.exception(f"card: {card}") i: Individual = card.individual bd_orig = f"{i.birthday:%Y-%m-%d}" - logger.exception(f'{bd_orig} == {bd}') + logger.exception(f"{bd_orig} == {bd}") if bd_orig == bd: return Response( { "ok": True, - 'patient_data': { + "patient_data": { "rmis_id": card.individual.get_rmis_uid_fast(), }, } ) - elif enp_mode == 'local': - logger.exception(f'enp: {enp}') - card = Card.objects.filter(base__internal_type=True, is_archive=False, carddocusage__document__number=enp, carddocusage__document__document_type__title='Полис ОМС').first() + elif enp_mode == "local": + logger.exception(f"enp: {enp}") + card = Card.objects.filter(base__internal_type=True, is_archive=False, carddocusage__document__number=enp, carddocusage__document__document_type__title="Полис ОМС").first() if card: - logger.exception(f'card: {card}') + logger.exception(f"card: {card}") i: Individual = card.individual bd_orig = f"{i.birthday:%Y-%m-%d}" - logger.exception(f'{bd_orig} == {bd}') + logger.exception(f"{bd_orig} == {bd}") if bd_orig == bd: return Response( { "ok": True, - 'patient_data': { + "patient_data": { "rmis_id": card.individual.get_rmis_uid_fast(), }, } ) - return Response({"ok": False, 'message': 'Неверные данные или нет прикрепления к поликлинике'}) + return Response({"ok": False, "message": "Неверные данные или нет прикрепления к поликлинике"}) -@api_view(['POST']) +@api_view(["POST"]) def patient_results_covid19(request): return Response({"ok": False}) days = 15 results = [] - p_enp = data_parse(request.body, {'enp': str}, {'enp': ''})[0] + p_enp = data_parse(request.body, {"enp": str}, {"enp": ""})[0] if p_enp: - logger.exception(f'patient_results_covid19 by enp: {p_enp}') + logger.exception(f"patient_results_covid19 by enp: {p_enp}") card = Card.objects.filter( - base__internal_type=True, is_archive=False, carddocusage__document__number=str(p_enp).replace(' ', ''), carddocusage__document__document_type__title='Полис ОМС' + base__internal_type=True, is_archive=False, carddocusage__document__number=str(p_enp).replace(" ", ""), carddocusage__document__document_type__title="Полис ОМС" ).first() - logger.exception(f'patient_results_covid19 by enp [CARD]: {card}') + logger.exception(f"patient_results_covid19 by enp [CARD]: {card}") if card: date_end = current_time() date_start = date_end + relativedelta(days=-days) date_end = date_end + relativedelta(days=1) results_covid = last_results_researches_by_time_ago(card.pk, COVID_RESEARCHES_PK, date_start, date_end) - logger.exception(f'patient_results_covid19 by enp params: {(card.pk, COVID_RESEARCHES_PK, date_start, date_end)}') - logger.exception(f'patient_results_covid19 by enp results count: {len(results_covid)}') + logger.exception(f"patient_results_covid19 by enp params: {(card.pk, COVID_RESEARCHES_PK, date_start, date_end)}") + logger.exception(f"patient_results_covid19 by enp results count: {len(results_covid)}") for i in results_covid: - results.append({'date': i.confirm, 'result': i.value}) + results.append({"date": i.confirm, "result": i.value}) if len(results) > 0: - return Response({"ok": True, 'results': results}) + return Response({"ok": True, "results": results}) - rmis_id = data_parse(request.body, {'rmis_id': str}, {'rmis_id': ''})[0] + rmis_id = data_parse(request.body, {"rmis_id": str}, {"rmis_id": ""})[0] results = [] @@ -931,14 +931,14 @@ def patient_results_covid19(request): for i in range(3): results = [] - logger.exception(f'patient_results_covid19 by rmis id, try {i + 1}/3: {rmis_id}') + logger.exception(f"patient_results_covid19 by rmis id, try {i + 1}/3: {rmis_id}") try: - c = Client(modules=['directions', 'rendered_services']) + c = Client(modules=["directions", "rendered_services"]) now = current_time().date() - variants = ['РНК вируса SARS-CоV2 не обнаружена', 'РНК вируса SARS-CоV2 обнаружена'] + variants = ["РНК вируса SARS-CоV2 не обнаружена", "РНК вируса SARS-CоV2 обнаружена"] for i in range(days): date = now - datetime.timedelta(days=i) @@ -947,44 +947,44 @@ def patient_results_covid19(request): protocol = c.directions.get_protocol(rs) for v in variants: if v in protocol: - results.append({'date': date.strftime('%d.%m.%Y'), 'result': v}) + results.append({"date": date.strftime("%d.%m.%Y"), "result": v}) break break except Exception as e: logger.exception(e) time.sleep(2) - return Response({"ok": True, 'results': results}) + return Response({"ok": True, "results": results}) -@api_view(['POST']) +@api_view(["POST"]) def external_doc_call_create(request): data = json.loads(request.body) - org_id = data.get('org_id') - patient_data = data.get('patient_data') - form = data.get('form') - idp = patient_data.get('idp') - enp = patient_data.get('enp') - comment = form.get('comment') - purpose = form.get('purpose') - email = form.get('email') - external_num = form.get('external_num') - is_main_external = form.get('is_main_external') - - if email == 'undefined': + org_id = data.get("org_id") + patient_data = data.get("patient_data") + form = data.get("form") + idp = patient_data.get("idp") + enp = patient_data.get("enp") + comment = form.get("comment") + purpose = form.get("purpose") + email = form.get("email") + external_num = form.get("external_num") + is_main_external = form.get("is_main_external") + + if email == "undefined": email = None - logger.exception(f'external_doc_call_create: {org_id} {json.dumps(patient_data)} {json.dumps(form)} {idp} {enp} {comment} {purpose} {email} {external_num}') + logger.exception(f"external_doc_call_create: {org_id} {json.dumps(patient_data)} {json.dumps(form)} {idp} {enp} {comment} {purpose} {email} {external_num}") Individual.import_from_tfoms(patient_data) - individuals = Individual.objects.filter(Q(tfoms_enp=enp or '###$fakeenp$###') | Q(tfoms_idp=idp or '###$fakeidp$###')) + individuals = Individual.objects.filter(Q(tfoms_enp=enp or "###$fakeenp$###") | Q(tfoms_idp=idp or "###$fakeidp$###")) individual_obj = individuals.first() if not individual_obj: return JsonResponse({"ok": False, "number": None}) card = Card.objects.filter(individual=individual_obj, base__internal_type=True).first() - research = Researches.objects.filter(title='Обращение пациента').first() + research = Researches.objects.filter(title="Обращение пациента").first() hospital = Hospitals.objects.filter(code_tfoms=org_id).first() if not card or not research or not hospital: @@ -994,42 +994,42 @@ def external_doc_call_create(request): count = DoctorCall.objects.filter(client=card, is_external=True, exec_at__date=date.date()).count() if count >= MAX_DOC_CALL_EXTERNAL_REQUESTS_PER_DAY: - logger.exception(f'TOO MANY REQUESTS PER DAY: already have {count} calls at {date:%d.%m.%Y}') + logger.exception(f"TOO MANY REQUESTS PER DAY: already have {count} calls at {date:%d.%m.%Y}") return JsonResponse({"ok": False, "number": None, "tooManyRequests": True}) research_pk = research.pk doc_call = DoctorCall.doctor_call_save( { - 'card': card, - 'research': research_pk, - 'address': card.main_address, - 'district': -1, - 'date': date, - 'comment': comment, - 'phone': form.get('phone'), - 'doc': -1, - 'purpose': int(purpose), - 'hospital': hospital.pk, - 'external': True, - 'email': email, - 'external_num': external_num, - 'is_main_external': bool(is_main_external), + "card": card, + "research": research_pk, + "address": card.main_address, + "district": -1, + "date": date, + "comment": comment, + "phone": form.get("phone"), + "doc": -1, + "purpose": int(purpose), + "hospital": hospital.pk, + "external": True, + "email": email, + "external_num": external_num, + "is_main_external": bool(is_main_external), } ) if is_main_external: doc_call.external_num = doc_call.num - elif SettingManager.l2('send_doc_calls'): + elif SettingManager.l2("send_doc_calls"): doc_call.external_num = f"{org_id}{doc_call.pk}" doc_call.save() return Response({"ok": True, "number": doc_call.external_num}) -@api_view(['POST']) +@api_view(["POST"]) def external_doc_call_update_status(request): - if not hasattr(request.user, 'hospitals'): - return Response({"ok": False, 'message': 'Некорректный auth токен'}) + if not hasattr(request.user, "hospitals"): + return Response({"ok": False, "message": "Некорректный auth токен"}) body = json.loads(request.body) @@ -1040,13 +1040,13 @@ def external_doc_call_update_status(request): oid_org = org.get("oid") if not external_num: - return Response({"ok": False, 'message': 'externalNum не указан'}) + return Response({"ok": False, "message": "externalNum не указан"}) if not status: - return Response({"ok": False, 'message': 'status не указан'}) + return Response({"ok": False, "message": "status не указан"}) if not code_tfoms and not oid_org: - return Response({"ok": False, 'message': 'Должно быть указано хотя бы одно значение из org.codeTFOMS или org.oid'}) + return Response({"ok": False, "message": "Должно быть указано хотя бы одно значение из org.codeTFOMS или org.oid"}) if code_tfoms: hospital = Hospitals.objects.filter(code_tfoms=code_tfoms).first() @@ -1054,69 +1054,69 @@ def external_doc_call_update_status(request): hospital = Hospitals.objects.filter(oid=oid_org).first() if not hospital: - return Response({"ok": False, 'message': 'Организация не найдена'}) + return Response({"ok": False, "message": "Организация не найдена"}) if not request.user.hospitals.filter(pk=hospital.pk).exists(): - return Response({"ok": False, 'message': 'Нет доступа в переданную организацию'}) + return Response({"ok": False, "message": "Нет доступа в переданную организацию"}) if not hospital: - return Response({"ok": False, 'message': 'Организация не найдена'}) + return Response({"ok": False, "message": "Организация не найдена"}) status = str(status) if not status.isdigit(): - return Response({"ok": False, 'message': 'Некорректный status'}) + return Response({"ok": False, "message": "Некорректный status"}) status = int(status) if status not in [x[0] for x in DoctorCall.STATUS]: - return Response({"ok": False, 'message': 'Некорректный status'}) + return Response({"ok": False, "message": "Некорректный status"}) num = str(external_num) - if not num.startswith('XR'): - return Response({"ok": False, 'message': 'Некорректный externalNum'}) + if not num.startswith("XR"): + return Response({"ok": False, "message": "Некорректный externalNum"}) - num = num.replace('XR', '') + num = num.replace("XR", "") if not num.isdigit(): - return Response({"ok": False, 'message': 'Некорректный externalNum'}) + return Response({"ok": False, "message": "Некорректный externalNum"}) call: DoctorCall = DoctorCall.objects.filter(pk=num).first() if not call: - return Response({"ok": False, 'message': f'Заявка с номером {num} не найдена'}) + return Response({"ok": False, "message": f"Заявка с номером {num} не найдена"}) call.status = status - call.save(update_fields=['status']) + call.save(update_fields=["status"]) return Response({"ok": True}) -@api_view(['POST']) +@api_view(["POST"]) def external_doc_call_send(request): data = json.loads(request.body) - patient_data = data.get('patient_data') - form = data.get('form') - enp = patient_data.get('enp') - address = patient_data.get('address') - comment = form.get('comment') - purpose = form.get('purpose_id') - email = form.get('email') - external_num = form.get('num') + patient_data = data.get("patient_data") + form = data.get("form") + enp = patient_data.get("enp") + address = patient_data.get("address") + comment = form.get("comment") + purpose = form.get("purpose_id") + email = form.get("email") + external_num = form.get("num") - logger.exception(f'external_doc_call_send: {json.dumps(patient_data)} {json.dumps(form)} {enp} {comment} {purpose} {email} {external_num}') + logger.exception(f"external_doc_call_send: {json.dumps(patient_data)} {json.dumps(form)} {enp} {comment} {purpose} {email} {external_num}") individuals = Individual.objects.filter(tfoms_enp=enp) if not individuals.exists(): - individuals = Individual.objects.filter(document__number=enp).filter(Q(document__document_type__title='Полис ОМС') | Q(document__document_type__title='ЕНП')) + individuals = Individual.objects.filter(document__number=enp).filter(Q(document__document_type__title="Полис ОМС") | Q(document__document_type__title="ЕНП")) if not individuals.exists(): tfoms_data = match_enp(enp) if not tfoms_data: - return Response({"ok": False, 'message': 'Неверные данные полиса, в базе ТФОМС нет такого пациента'}) + return Response({"ok": False, "message": "Неверные данные полиса, в базе ТФОМС нет такого пациента"}) Individual.import_from_tfoms(tfoms_data) individuals = Individual.objects.filter(tfoms_enp=enp) individual = individuals if isinstance(individuals, Individual) else individuals.first() if not individual: - return Response({"ok": False, 'message': 'Физлицо не найдено'}) + return Response({"ok": False, "message": "Физлицо не найдено"}) card = Card.objects.filter(individual=individual, base__internal_type=True).first() - research = Researches.objects.filter(title='Обращение пациента').first() + research = Researches.objects.filter(title="Обращение пациента").first() hospital = Hospitals.get_default_hospital() if not card or not research or not hospital: @@ -1126,34 +1126,34 @@ def external_doc_call_send(request): doc_call = DoctorCall.doctor_call_save( { - 'card': card, - 'research': research_pk, - 'address': address, - 'district': -1, - 'date': current_time(), - 'comment': comment, - 'phone': form.get('phone'), - 'doc': -1, - 'purpose': int(purpose), - 'hospital': hospital.pk, - 'external': True, - 'email': email, - 'external_num': external_num, - 'is_main_external': False, + "card": card, + "research": research_pk, + "address": address, + "district": -1, + "date": current_time(), + "comment": comment, + "phone": form.get("phone"), + "doc": -1, + "purpose": int(purpose), + "hospital": hospital.pk, + "external": True, + "email": email, + "external_num": external_num, + "is_main_external": False, } ) return Response({"ok": True, "number": doc_call.num}) -@api_view(['POST']) +@api_view(["POST"]) def set_core_id(request): data = json.loads(request.body) - pk = data.get('pk') - core_id = data.get('coreId') + pk = data.get("pk") + core_id = data.get("coreId") n = directions.Napravleniya.objects.get(pk=pk) n.core_id = core_id - n.save(update_fields=['core_id']) + n.save(update_fields=["core_id"]) return Response({"ok": True}) @@ -1165,10 +1165,10 @@ def limit_str(s: str, limit=500): return str(s)[:limit] -@api_view(['POST']) +@api_view(["POST"]) def external_research_create(request): - if not hasattr(request.user, 'hospitals'): - return Response({"ok": False, 'message': 'Некорректный auth токен'}) + if not hasattr(request.user, "hospitals"): + return Response({"ok": False, "message": "Некорректный auth токен"}) body = json.loads(request.body) @@ -1178,7 +1178,7 @@ def external_research_create(request): oid_org = org.get("oid") if not code_tfoms and not oid_org: - return Response({"ok": False, 'message': 'Должно быть указано хотя бы одно значение из org.codeTFOMS или org.oid'}) + return Response({"ok": False, "message": "Должно быть указано хотя бы одно значение из org.codeTFOMS или org.oid"}) if code_tfoms: hospital = Hospitals.objects.filter(code_tfoms=code_tfoms).first() @@ -1186,17 +1186,17 @@ def external_research_create(request): hospital = Hospitals.objects.filter(oid=oid_org).first() if not hospital: - return Response({"ok": False, 'message': 'Организация не найдена'}) + return Response({"ok": False, "message": "Организация не найдена"}) if not request.user.hospitals.filter(pk=hospital.pk).exists(): - return Response({"ok": False, 'message': 'Нет доступа в переданную организацию'}) + return Response({"ok": False, "message": "Нет доступа в переданную организацию"}) - initiator = org.get('initiator') or {} - title_org_initiator = initiator.get('title') + initiator = org.get("initiator") or {} + title_org_initiator = initiator.get("title") if title_org_initiator is not None: title_org_initiator = str(title_org_initiator)[:254] - ogrn_org_initiator = initiator.get('ogrn') + ogrn_org_initiator = initiator.get("ogrn") if ogrn_org_initiator is not None: ogrn_org_initiator = str(ogrn_org_initiator) @@ -1207,84 +1207,84 @@ def external_research_create(request): ogrn_org_initiator = None if not title_org_initiator and ogrn_org_initiator: - return Response({"ok": False, 'message': 'org.initiator: при передаче ogrn поле title обязательно'}) + return Response({"ok": False, "message": "org.initiator: при передаче ogrn поле title обязательно"}) if title_org_initiator and not ogrn_org_initiator: - return Response({"ok": False, 'message': 'org.initiator: при передаче title поле ogrn обязательно'}) + return Response({"ok": False, "message": "org.initiator: при передаче title поле ogrn обязательно"}) if ogrn_org_initiator and not ogrn_org_initiator.isdigit(): - return Response({"ok": False, 'message': 'org.initiator.ogrn: в значении возможны только числа'}) + return Response({"ok": False, "message": "org.initiator.ogrn: в значении возможны только числа"}) if ogrn_org_initiator and len(ogrn_org_initiator) != 13: - return Response({"ok": False, 'message': 'org.initiator.ogrn: длина должна быть 13'}) + return Response({"ok": False, "message": "org.initiator.ogrn: длина должна быть 13"}) if ogrn_org_initiator and not petrovna.validate_ogrn(ogrn_org_initiator): - return Response({"ok": False, 'message': 'org.initiator.ogrn: не прошёл валидацию'}) + return Response({"ok": False, "message": "org.initiator.ogrn: не прошёл валидацию"}) patient = body.get("patient", {}) - enp = (patient.get("enp") or '').replace(' ', '') + enp = (patient.get("enp") or "").replace(" ", "") if enp and (len(enp) != 16 or not enp.isdigit()): - return Response({"ok": False, 'message': 'Неверные данные полиса, должно быть 16 чисел'}) + return Response({"ok": False, "message": "Неверные данные полиса, должно быть 16 чисел"}) - passport_serial = (patient.get("passportSerial") or '').replace(' ', '') - passport_number = (patient.get("passportNumber") or '').replace(' ', '') + passport_serial = (patient.get("passportSerial") or "").replace(" ", "") + passport_number = (patient.get("passportNumber") or "").replace(" ", "") - snils = (patient.get("snils") or '').replace(' ', '').replace('-', '') + snils = (patient.get("snils") or "").replace(" ", "").replace("-", "") if not enp and (not passport_serial or not passport_number) and not snils: - return Response({"ok": False, 'message': 'При пустом patient.enp должно быть передано patient.snils или patient.passportSerial+patient.passportNumber'}) + return Response({"ok": False, "message": "При пустом patient.enp должно быть передано patient.snils или patient.passportSerial+patient.passportNumber"}) if passport_serial and len(passport_serial) != 4: - return Response({"ok": False, 'message': 'Длина patient.passportSerial должна быть 4'}) + return Response({"ok": False, "message": "Длина patient.passportSerial должна быть 4"}) if passport_serial and not passport_serial.isdigit(): - return Response({"ok": False, 'message': 'patient.passportSerial должен содержать только числа'}) + return Response({"ok": False, "message": "patient.passportSerial должен содержать только числа"}) if passport_number and len(passport_number) != 6: - return Response({"ok": False, 'message': 'Длина patient.passportNumber должна быть 6'}) + return Response({"ok": False, "message": "Длина patient.passportNumber должна быть 6"}) if passport_number and not passport_number.isdigit(): - return Response({"ok": False, 'message': 'patient.passportNumber должен содержать только числа'}) + return Response({"ok": False, "message": "patient.passportNumber должен содержать только числа"}) if snils and not petrovna.validate_snils(snils): - return Response({"ok": False, 'message': 'patient.snils: не прошёл валидацию'}) + return Response({"ok": False, "message": "patient.snils: не прошёл валидацию"}) individual_data = patient.get("individual") or {} if not enp and not individual_data: - return Response({"ok": False, 'message': 'При пустом patient.enp должно быть передано поле patient.individual'}) + return Response({"ok": False, "message": "При пустом patient.enp должно быть передано поле patient.individual"}) - lastname = str(individual_data.get("lastname") or '') - firstname = str(individual_data.get('firstname') or '') - patronymic = str(individual_data.get('patronymic') or '') - birthdate = str(individual_data.get('birthdate') or '') - sex = str(individual_data.get('sex') or '').lower() + lastname = str(individual_data.get("lastname") or "") + firstname = str(individual_data.get("firstname") or "") + patronymic = str(individual_data.get("patronymic") or "") + birthdate = str(individual_data.get("birthdate") or "") + sex = str(individual_data.get("sex") or "").lower() individual = None if lastname and not firstname: - return Response({"ok": False, 'message': 'При передаче lastname должен быть передан и firstname'}) + return Response({"ok": False, "message": "При передаче lastname должен быть передан и firstname"}) if firstname and not lastname: - return Response({"ok": False, 'message': 'При передаче firstname должен быть передан и lastname'}) + return Response({"ok": False, "message": "При передаче firstname должен быть передан и lastname"}) if firstname and lastname and not birthdate: - return Response({"ok": False, 'message': 'При передаче firstname и lastname должно быть передано поле birthdate'}) + return Response({"ok": False, "message": "При передаче firstname и lastname должно быть передано поле birthdate"}) - if birthdate and (not re.fullmatch(r'\d{4}-\d\d-\d\d', birthdate) or birthdate[0] not in ['1', '2']): - return Response({"ok": False, 'message': 'birthdate должно соответствовать формату YYYY-MM-DD'}) + if birthdate and (not re.fullmatch(r"\d{4}-\d\d-\d\d", birthdate) or birthdate[0] not in ["1", "2"]): + return Response({"ok": False, "message": "birthdate должно соответствовать формату YYYY-MM-DD"}) - if birthdate and sex not in ['м', 'ж']: - return Response({"ok": False, 'message': 'individual.sex должно быть "м" или "ж"'}) + if birthdate and sex not in ["м", "ж"]: + return Response({"ok": False, "message": 'individual.sex должно быть "м" или "ж"'}) individual_status = "unknown" if enp: individuals = Individual.objects.filter(tfoms_enp=enp) if not individuals.exists(): - individuals = Individual.objects.filter(document__number=enp).filter(Q(document__document_type__title='Полис ОМС') | Q(document__document_type__title='ЕНП')) + individuals = Individual.objects.filter(document__number=enp).filter(Q(document__document_type__title="Полис ОМС") | Q(document__document_type__title="ЕНП")) individual = individuals.first() individual_status = "local_enp" if not individual: @@ -1302,12 +1302,12 @@ def external_research_create(request): individual = Individual.import_from_tfoms(tfoms_data, need_return_individual=True) if not individual and passport_serial: - individuals = Individual.objects.filter(document__serial=passport_serial, document__number=passport_number, document__document_type__title='Паспорт гражданина РФ') + individuals = Individual.objects.filter(document__serial=passport_serial, document__number=passport_number, document__document_type__title="Паспорт гражданина РФ") individual = individuals.first() individual_status = "passport" if not individual and snils: - individuals = Individual.objects.filter(document__number=snils, document__document_type__title='СНИЛС') + individuals = Individual.objects.filter(document__number=snils, document__document_type__title="СНИЛС") individual = individuals.first() individual_status = "snils" @@ -1329,31 +1329,31 @@ def external_research_create(request): individual_status = "new_local" if not individual: - return Response({"ok": False, 'message': 'Физлицо не найдено'}) + return Response({"ok": False, "message": "Физлицо не найдено"}) card = Card.objects.filter(individual=individual, base__internal_type=True).first() if not card: card = Card.add_l2_card(individual) if not card: - return Response({"ok": False, 'message': 'Карта не найдена'}) + return Response({"ok": False, "message": "Карта не найдена"}) - financing_source_title = body.get("financingSource", '') + financing_source_title = body.get("financingSource", "") financing_source = directions.IstochnikiFinansirovaniya.objects.filter(title__iexact=financing_source_title, base__internal_type=True).first() if not financing_source: - return Response({"ok": False, 'message': 'Некорректный источник финансирования'}) + return Response({"ok": False, "message": "Некорректный источник финансирования"}) results = body.get("results") if not results or not isinstance(results, list): - return Response({"ok": False, 'message': 'Некорректное значение results'}) + return Response({"ok": False, "message": "Некорректное значение results"}) results = results[:40] message = None - id_in_hospital = body.get("internalId", '') + id_in_hospital = body.get("internalId", "") if id_in_hospital is not None: id_in_hospital = limit_str(id_in_hospital, 15) @@ -1390,28 +1390,28 @@ def external_research_create(request): code_research = r.get("codeResearch", "unknown") research = Researches.objects.filter(code=code_research).first() if not research: - raise InvalidData(f'Исследование с кодом {code_research} не найдено') + raise InvalidData(f"Исследование с кодом {code_research} не найдено") if research_to_filter[code_research]: - raise InvalidData(f'Исследование с кодом {code_research} отправлено повторно в одном направлении') + raise InvalidData(f"Исследование с кодом {code_research} отправлено повторно в одном направлении") tests = r.get("tests") if not tests or not isinstance(tests, list): - raise InvalidData(f'Исследование {code_research} содержит некорректное поле tests') + raise InvalidData(f"Исследование {code_research} содержит некорректное поле tests") comments = str(r.get("comments", "") or "") or None time_confirmation = r.get("dateTimeConfirm") if not time_confirmation or not valid_date(time_confirmation): - raise InvalidData(f'{code_research}: содержит некорректное поле dateTimeConfirm. Оно должно быть заполнено и соответствовать шаблону YYYY-MM-DD HH:MM') + raise InvalidData(f"{code_research}: содержит некорректное поле dateTimeConfirm. Оно должно быть заполнено и соответствовать шаблону YYYY-MM-DD HH:MM") time_get = str(r.get("dateTimeGet", "") or "") or None if time_get and not valid_date(time_confirmation): - raise InvalidData(f'{code_research}: содержит некорректное поле dateTimeGet. Оно должно быть пустым или соответствовать шаблону YYYY-MM-DD HH:MM') + raise InvalidData(f"{code_research}: содержит некорректное поле dateTimeGet. Оно должно быть пустым или соответствовать шаблону YYYY-MM-DD HH:MM") time_receive = str(r.get("dateTimeReceive", "") or "") or None if time_receive and not valid_date(time_confirmation): - raise InvalidData(f'{code_research}: содержит некорректное поле dateTimeReceive. Оно должно быть пустым или соответствовать шаблону YYYY-MM-DD HH:MM') + raise InvalidData(f"{code_research}: содержит некорректное поле dateTimeReceive. Оно должно быть пустым или соответствовать шаблону YYYY-MM-DD HH:MM") doc_confirm = str(r.get("docConfirm", "") or "") or None @@ -1424,11 +1424,11 @@ def external_research_create(request): lab_comment=comments, time_confirmation=time_confirmation, time_save=timezone.now(), - doc_confirmation_string=doc_confirm or f'Врач {hospital.short_title or hospital.title}', + doc_confirmation_string=doc_confirm or f"Врач {hospital.short_title or hospital.title}", ) - tube = Tubes.objects.filter(title='Универсальная пробирка').first() + tube = Tubes.objects.filter(title="Универсальная пробирка").first() if not tube: - tube = Tubes.objects.create(title='Универсальная пробирка', color='#049372') + tube = Tubes.objects.create(title="Универсальная пробирка", color="#049372") ft = ReleationsFT.objects.filter(tube=tube).first() if not ft: @@ -1446,7 +1446,7 @@ def external_research_create(request): tr = iss.tubes.create(type=ft, number=number) tr.time_get = time_get tr.time_recive = time_receive - tr.save(update_fields=['time_get', 'time_recive']) + tr.save(update_fields=["time_get", "time_recive"]) tests_to_filter = defaultdict(lambda: False) @@ -1454,10 +1454,10 @@ def external_research_create(request): fsli_code = t.get("idFsli", "unknown") fraction = Fractions.objects.filter(fsli=fsli_code).first() if not fraction: - raise InvalidData(f'В исследовании {code_research} не найден тест {fsli_code}') + raise InvalidData(f"В исследовании {code_research} не найден тест {fsli_code}") if tests_to_filter[code_research]: - raise InvalidData(f'Тест с кодом {fsli_code} отправлен повторно в одном направлении в {code_research}') + raise InvalidData(f"Тест с кодом {fsli_code} отправлен повторно в одном направлении в {code_research}") value = limit_str(t.get("valueString", "") or "", 500) units = limit_str(str(t.get("units", "") or ""), 50) @@ -1466,12 +1466,12 @@ def external_research_create(request): reference_range = t.get("referenceRange") or None if reference_value and not isinstance(reference_value, str): - raise InvalidData(f'{code_research} -> {fsli_code}: поле referenceValue должно быть строкой или null') + raise InvalidData(f"{code_research} -> {fsli_code}: поле referenceValue должно быть строкой или null") if reference_range and not isinstance(reference_range, dict): - raise InvalidData(f'{code_research} -> {fsli_code}: поле referenceRange должно быть объектом {{low, high}} или null') + raise InvalidData(f"{code_research} -> {fsli_code}: поле referenceRange должно быть объектом {{low, high}} или null") - if reference_range and ('low' not in reference_range or 'high' not in reference_range): - raise InvalidData(f'{code_research} -> {fsli_code}: поле referenceRange должно быть объектом с полями {{low, high}} или null') + if reference_range and ("low" not in reference_range or "high" not in reference_range): + raise InvalidData(f"{code_research} -> {fsli_code}: поле referenceRange должно быть объектом с полями {{low, high}} или null") ref_str = reference_value @@ -1479,7 +1479,7 @@ def external_research_create(request): ref_str = f"{reference_range['low']} – {reference_range['high']}" if ref_str: - ref_str = limit_str(ref_str.replace("\"", "'"), 120) + ref_str = limit_str(ref_str.replace('"', "'"), 120) ref_str = f'{{"Все": "{ref_str}"}}' directions.Result( @@ -1505,22 +1505,22 @@ def external_research_create(request): ) except Exception as e: logger.exception(e) - return Response({"ok": True, 'id': str(direction.pk)}) + return Response({"ok": True, "id": str(direction.pk)}) except InvalidData as e: logger.exception(e) message = str(e) except Exception as e: logger.exception(e) - message = 'Серверная ошибка' + message = "Серверная ошибка" - return Response({"ok": False, 'message': message}) + return Response({"ok": False, "message": message}) -@api_view(['POST']) +@api_view(["POST"]) def external_direction_create(request): - if not hasattr(request.user, 'hospitals'): - return Response({"ok": False, 'message': 'Некорректный auth токен'}) + if not hasattr(request.user, "hospitals"): + return Response({"ok": False, "message": "Некорректный auth токен"}) body = json.loads(request.body) @@ -1529,7 +1529,7 @@ def external_direction_create(request): oid_org = org.get("oid") if not code_tfoms and not oid_org: - return Response({"ok": False, 'message': 'Должно быть указано хотя бы одно значение из org.codeTFOMS или org.oid'}) + return Response({"ok": False, "message": "Должно быть указано хотя бы одно значение из org.codeTFOMS или org.oid"}) if code_tfoms: hospital = Hospitals.objects.filter(code_tfoms=code_tfoms).first() @@ -1537,10 +1537,10 @@ def external_direction_create(request): hospital = Hospitals.objects.filter(oid=oid_org).first() if not hospital: - return Response({"ok": False, 'message': 'Организация не найдена'}) + return Response({"ok": False, "message": "Организация не найдена"}) if not request.user.hospitals.filter(pk=hospital.pk).exists(): - return Response({"ok": False, 'message': 'Нет доступа в переданную организацию'}) + return Response({"ok": False, "message": "Нет доступа в переданную организацию"}) is_exclude_contorl_documnets = False if hospital.pk in HOSPITAL_PKS_NOT_CONTROL_DOCUMENT_EXTERNAL_CREATE_DIRECTION: @@ -1548,52 +1548,52 @@ def external_direction_create(request): patient = body.get("patient", {}) - enp = (patient.get("enp") or '').replace(' ', '') + enp = (patient.get("enp") or "").replace(" ", "") if enp and (len(enp) != 16 or not enp.isdigit()): - return Response({"ok": False, 'message': 'Неверные данные полиса, должно быть 16 чисел'}) + return Response({"ok": False, "message": "Неверные данные полиса, должно быть 16 чисел"}) - snils = (patient.get("snils") or '').replace(' ', '').replace('-', '') + snils = (patient.get("snils") or "").replace(" ", "").replace("-", "") if not enp and not snils and not is_exclude_contorl_documnets: - return Response({"ok": False, 'message': 'При пустом patient.enp должно быть передано patient.snils или patient.passportSerial+patient.passportNumber'}) + return Response({"ok": False, "message": "При пустом patient.enp должно быть передано patient.snils или patient.passportSerial+patient.passportNumber"}) if snils and not petrovna.validate_snils(snils): - return Response({"ok": False, 'message': 'patient.snils: не прошёл валидацию'}) + return Response({"ok": False, "message": "patient.snils: не прошёл валидацию"}) - lastname = str(patient.get("lastName") or '') - firstname = str(patient.get('firstName') or '') - patronymic = str(patient.get('patronymicName') or '') - birthdate = str(patient.get('birthDate') or '') - sex = patient.get('sex') or '' + lastname = str(patient.get("lastName") or "") + firstname = str(patient.get("firstName") or "") + patronymic = str(patient.get("patronymicName") or "") + birthdate = str(patient.get("birthDate") or "") + sex = patient.get("sex") or "" if sex == 1: sex = "м" else: sex = "ж" if not enp and not (lastname and firstname and birthdate and birthdate): - return Response({"ok": False, 'message': 'При пустом patient.enp должно быть передано поле patient.individual'}) + return Response({"ok": False, "message": "При пустом patient.enp должно быть передано поле patient.individual"}) if lastname and not firstname: - return Response({"ok": False, 'message': 'При передаче lastname должен быть передан и firstname'}) + return Response({"ok": False, "message": "При передаче lastname должен быть передан и firstname"}) if firstname and not lastname: - return Response({"ok": False, 'message': 'При передаче firstname должен быть передан и lastname'}) + return Response({"ok": False, "message": "При передаче firstname должен быть передан и lastname"}) if firstname and lastname and not birthdate: - return Response({"ok": False, 'message': 'При передаче firstname и lastname должно быть передано поле birthdate'}) + return Response({"ok": False, "message": "При передаче firstname и lastname должно быть передано поле birthdate"}) - if birthdate and (not re.fullmatch(r'\d{4}-\d\d-\d\d', birthdate) or birthdate[0] not in ['1', '2']): - return Response({"ok": False, 'message': 'birthdate должно соответствовать формату YYYY-MM-DD'}) + if birthdate and (not re.fullmatch(r"\d{4}-\d\d-\d\d", birthdate) or birthdate[0] not in ["1", "2"]): + return Response({"ok": False, "message": "birthdate должно соответствовать формату YYYY-MM-DD"}) - if birthdate and sex not in ['м', 'ж']: - return Response({"ok": False, 'message': 'individual.sex должно быть "м" или "ж"'}) + if birthdate and sex not in ["м", "ж"]: + return Response({"ok": False, "message": 'individual.sex должно быть "м" или "ж"'}) individual = None if enp: individuals = Individual.objects.filter(tfoms_enp=enp) if not individuals.exists(): - individuals = Individual.objects.filter(document__number=enp).filter(Q(document__document_type__title='Полис ОМС') | Q(document__document_type__title='ЕНП')) + individuals = Individual.objects.filter(document__number=enp).filter(Q(document__document_type__title="Полис ОМС") | Q(document__document_type__title="ЕНП")) individual = individuals.first() if not individual: tfoms_data = match_enp(enp) @@ -1608,7 +1608,7 @@ def external_direction_create(request): individual = Individual.import_from_tfoms(tfoms_data, need_return_individual=True) if not individual and snils: - individuals = Individual.objects.filter(document__number=snils, document__document_type__title='СНИЛС') + individuals = Individual.objects.filter(document__number=snils, document__document_type__title="СНИЛС") individual = individuals.first() if not individual and lastname: @@ -1626,43 +1626,43 @@ def external_direction_create(request): ) if not individual: - return Response({"ok": False, 'message': 'Физлицо не найдено'}) + return Response({"ok": False, "message": "Физлицо не найдено"}) card = Card.objects.filter(individual=individual, base__internal_type=True).first() if not card: card = Card.add_l2_card(individual) if not card: - return Response({"ok": False, 'message': 'Карта не найдена'}) + return Response({"ok": False, "message": "Карта не найдена"}) - financing_source_title = body.get("financingSource", '') + financing_source_title = body.get("financingSource", "") if financing_source_title.lower() not in ["омс", "бюджет", "платно"]: - return Response({"ok": False, 'message': 'Некорректный источник финансирования'}) + return Response({"ok": False, "message": "Некорректный источник финансирования"}) financing_source = directions.IstochnikiFinansirovaniya.objects.filter(title__iexact=financing_source_title, base__internal_type=True).first() - financing_category_code = body.get("financingCategory", '') + financing_category_code = body.get("financingCategory", "") price_category = PriceCategory.objects.filter(title__startswith=financing_category_code).first() if not financing_source: - return Response({"ok": False, 'message': 'Некорректный источник финансирования'}) + return Response({"ok": False, "message": "Некорректный источник финансирования"}) message = None - id_in_hospital = body.get("internalId", '') + id_in_hospital = body.get("internalId", "") if id_in_hospital is not None: id_in_hospital = limit_str(id_in_hospital, 15) - department = body.get("department", '') - additiona_info = body.get("additionalInfo", '') - last_result_data = body.get("lastResultData", '') + department = body.get("department", "") + additiona_info = body.get("additionalInfo", "") + last_result_data = body.get("lastResultData", "") - diag_text = body.get("diagText", '') # обязательно + diag_text = body.get("diagText", "") # обязательно if not diag_text: - return Response({"ok": False, 'message': 'Диагноз описание не заполнено'}) + return Response({"ok": False, "message": "Диагноз описание не заполнено"}) - diag_mkb10 = body.get("diagMKB10", '') # обязательно + diag_mkb10 = body.get("diagMKB10", "") # обязательно if not diag_mkb10: - return Response({"ok": False, 'message': 'Диагноз по МКБ10 не заполнен (не верно)'}) + return Response({"ok": False, "message": "Диагноз по МКБ10 не заполнен (не верно)"}) open_skob = "{" close_skob = "}" @@ -1677,34 +1677,34 @@ def external_direction_create(request): 6: "операционный материал—6", 7: "самопроизвольно отделившиеся фрагменты тканей—7", } - method_obtain_material = body.get("methodObtainMaterial", '') # обязательно code из НСИ 1.2.643.5.1.13.13.99.2.33" + method_obtain_material = body.get("methodObtainMaterial", "") # обязательно code из НСИ 1.2.643.5.1.13.13.99.2.33" if not method_obtain_material or method_obtain_material not in [1, 2, 3, 4, 5, 6, 7]: - return Response({"ok": False, 'message': 'Способо забора не верно заполнено'}) + return Response({"ok": False, "message": "Способо забора не верно заполнено"}) - resident_code = patient.get("residentCode", '') # обязательно code из НСИ 1.2.643.5.1.13.13.11.1042" + resident_code = patient.get("residentCode", "") # обязательно code из НСИ 1.2.643.5.1.13.13.11.1042" if not resident_code or resident_code not in [1, 2]: - return Response({"ok": False, 'message': 'Не указан вид жительства'}) + return Response({"ok": False, "message": "Не указан вид жительства"}) if resident_code == 1: resident_data = f'{open_skob}"code": "1", "title": "Город"{close_skob}' else: resident_data = f'{open_skob}"code": "2", "title": "Село"{close_skob}' - solution10 = body.get("solution10", '') # обязательно + solution10 = body.get("solution10", "") # обязательно if not solution10 or solution10 not in ["true", "false"]: - return Response({"ok": False, 'message': 'Не указано помещен в 10% раствор'}) + return Response({"ok": False, "message": "Не указано помещен в 10% раствор"}) - doctor_fio = body.get("doctorFio", '') # обязательно + doctor_fio = body.get("doctorFio", "") # обязательно if not doctor_fio: - return Response({"ok": False, 'message': 'Не указан врач производивший забор материала'}) - material_mark = body.get("materialMark", '') + return Response({"ok": False, "message": "Не указан врач производивший забор материала"}) + material_mark = body.get("materialMark", "") numbers_vial = [] for k in material_mark: result_check = check_valid_material_mark(k, numbers_vial) if not result_check: - return Response({"ok": False, 'message': 'Не верная маркировка материала'}) + return Response({"ok": False, "message": "Не верная маркировка материала"}) numbers_vial = result_check if len(numbers_vial) != sorted(numbers_vial)[-1]: - return Response({"ok": False, 'message': 'Не верная маркировка флаконов (порядок 1,2,3,4...)'}) + return Response({"ok": False, "message": "Не верная маркировка флаконов (порядок 1,2,3,4...)"}) try: with transaction.atomic(): @@ -1721,7 +1721,7 @@ def external_direction_create(request): time_get = str(body.get("dateTimeGet", "") or "") or None if time_get and not valid_date(time_get) or not time_get: - raise InvalidData('Содержит некорректное поле dateTimeGet. Оно должно соответствовать шаблону YYYY-MM-DD HH:MM') + raise InvalidData("Содержит некорректное поле dateTimeGet. Оно должно соответствовать шаблону YYYY-MM-DD HH:MM") directions.Issledovaniya.objects.create( napravleniye=direction, @@ -1771,99 +1771,99 @@ def external_direction_create(request): ) except Exception as e: logger.exception(e) - return Response({"ok": True, 'id': str(direction.pk)}) + return Response({"ok": True, "id": str(direction.pk)}) except InvalidData as e: logger.exception(e) message = str(e) except Exception as e: logger.exception(e) - message = 'Серверная ошибка' + message = "Серверная ошибка" - return Response({"ok": False, 'message': message}) + return Response({"ok": False, "message": message}) -@api_view(['POST']) +@api_view(["POST"]) def get_directions(request): - if not hasattr(request.user, 'hospitals'): - return Response({"ok": False, 'message': 'Некорректный auth токен'}) + if not hasattr(request.user, "hospitals"): + return Response({"ok": False, "message": "Некорректный auth токен"}) body = json.loads(request.body) - oid_org = body.get(("oid") or '') + oid_org = body.get(("oid") or "") check_result = check_correct_hosp(request, oid_org) if not check_result["OK"]: - return Response({"ok": False, 'message': check_result["message"]}) + return Response({"ok": False, "message": check_result["message"]}) else: hospital = check_result["hospital"] - create_from = body.get(("createFrom") or '') - create_to = body.get(('createTo') or '') - directions_data = Napravleniya.objects.values_list('pk', flat=True).filter(hospital=hospital, data_sozdaniya__gte=create_from, data_sozdaniya__lte=create_to) - return Response({"ok": True, 'data': directions_data}) + create_from = body.get(("createFrom") or "") + create_to = body.get(("createTo") or "") + directions_data = Napravleniya.objects.values_list("pk", flat=True).filter(hospital=hospital, data_sozdaniya__gte=create_from, data_sozdaniya__lte=create_to) + return Response({"ok": True, "data": directions_data}) -@api_view(['POST']) +@api_view(["POST"]) def get_direction_data_by_num(request): - if not hasattr(request.user, 'hospitals'): - return Response({"ok": False, 'message': 'Некорректный auth токен'}) + if not hasattr(request.user, "hospitals"): + return Response({"ok": False, "message": "Некорректный auth токен"}) body = json.loads(request.body) - oid_org = body.get(("oid") or '') + oid_org = body.get(("oid") or "") check_result = check_correct_hosp(request, oid_org) if not check_result["OK"]: - return Response({"ok": False, 'message': check_result["message"]}) + return Response({"ok": False, "message": check_result["message"]}) - pk = int(body.get(("directionNum") or '')) + pk = int(body.get(("directionNum") or "")) data_result = get_data_direction_with_param(pk) if not data_result: return Response({"ok": False}) - return Response({"ok": True, 'data': data_result}) + return Response({"ok": True, "data": data_result}) -@api_view(['POST']) +@api_view(["POST"]) def get_direction_data_by_period(request): - if not hasattr(request.user, 'hospitals'): - return Response({"ok": False, 'message': 'Некорректный auth токен'}) + if not hasattr(request.user, "hospitals"): + return Response({"ok": False, "message": "Некорректный auth токен"}) body = json.loads(request.body) - oid_org = body.get(("oid") or '') + oid_org = body.get(("oid") or "") check_result = check_correct_hosp(request, oid_org) if not check_result["OK"]: - return Response({"ok": False, 'message': check_result["message"]}) + return Response({"ok": False, "message": check_result["message"]}) hospital = check_result["hospital"] - create_from = body.get(("createFrom") or '') - create_to = body.get(('createTo') or '') + create_from = body.get(("createFrom") or "") + create_to = body.get(("createTo") or "") dot_format_create_from = normalize_date(create_from.split(" ")[0]) dot_format_create_to = normalize_date(create_to.split(" ")[0]) date_start, date_end = try_parse_range(dot_format_create_from, dot_format_create_to) if date_start and date_end: delta = date_end - date_start if abs(delta.days) > 2: - return Response({"ok": False, 'message': 'Период между датами не более 48 часов'}) + return Response({"ok": False, "message": "Период между датами не более 48 часов"}) - directions_data = Napravleniya.objects.values_list('pk', flat=True).filter(hospital=hospital, data_sozdaniya__gte=create_from, data_sozdaniya__lte=create_to) + directions_data = Napravleniya.objects.values_list("pk", flat=True).filter(hospital=hospital, data_sozdaniya__gte=create_from, data_sozdaniya__lte=create_to) result = [] for direction_number in directions_data: data_result = get_data_direction_with_param(direction_number) if not data_result: continue result.append(data_result) - return Response({"ok": True, 'data': result}) + return Response({"ok": True, "data": result}) -@api_view(['POST']) +@api_view(["POST"]) def external_get_pdf_result(request): - if not hasattr(request.user, 'hospitals'): - return Response({"ok": False, 'message': 'Некорректный auth токен'}) + if not hasattr(request.user, "hospitals"): + return Response({"ok": False, "message": "Некорректный auth токен"}) body = json.loads(request.body) - oid_org = body.get(("oid") or '') + oid_org = body.get(("oid") or "") check_result = check_correct_hosp(request, oid_org) if not check_result["OK"]: - return Response({"ok": False, 'message': check_result["message"]}) + return Response({"ok": False, "message": check_result["message"]}) hospital = check_result["hospital"] - pk = int(body.get(("directionNum") or '')) + pk = int(body.get(("directionNum") or "")) direction = directions.Napravleniya.objects.filter(hospital=hospital, pk=pk).first() if not direction: - return Response({"ok": False, 'message': 'Номер направления не принадлежит организации'}) + return Response({"ok": False, "message": "Номер направления не принадлежит организации"}) pdf_data = direction_pdf_result(direction.pk) return JsonResponse({"result": pdf_data}) @@ -1887,12 +1887,12 @@ def check_valid_material_mark(current_material_data, current_numbers_vial): return current_numbers_vial -@api_view(['POST']) +@api_view(["POST"]) @authentication_classes([]) @permission_classes([]) def eds_get_user_data(request): - token = request.META.get('HTTP_AUTHORIZATION') - token = token.replace('Bearer ', '') + token = request.META.get("HTTP_AUTHORIZATION") + token = token.replace("Bearer ", "") if not token or not DoctorProfile.objects.filter(eds_token=token).exists(): return Response({"ok": False}) @@ -1923,18 +1923,18 @@ def get_cda_data(pk): else: data = {} data_individual = card.get_data_individual() - p_enp_re = re.compile(r'^[0-9]{16}$') - p_enp = bool(re.search(p_enp_re, card.get_data_individual()['oms']['polis_num'])) - insurer_full_code = card.get_data_individual()['insurer_full_code'] + p_enp_re = re.compile(r"^[0-9]{16}$") + p_enp = bool(re.search(p_enp_re, card.get_data_individual()["oms"]["polis_num"])) + insurer_full_code = card.get_data_individual()["insurer_full_code"] if not insurer_full_code: card.individual.sync_with_tfoms() - insurer_full_code = card.get_data_individual()['insurer_full_code'] + insurer_full_code = card.get_data_individual()["insurer_full_code"] smo_title = "" smo_id = "" if insurer_full_code: - smo = NSI.get("1.2.643.5.1.13.13.99.2.183_smo_code", {}).get('values', {}) + smo = NSI.get("1.2.643.5.1.13.13.99.2.183_smo_code", {}).get("values", {}) smo_title = smo.get(insurer_full_code, "") - smo_ids = NSI.get("1.2.643.5.1.13.13.99.2.183_smo_id", {}).get('values', {}) + smo_ids = NSI.get("1.2.643.5.1.13.13.99.2.183_smo_id", {}).get("values", {}) smo_id = smo_ids.get(insurer_full_code, "") if p_enp: return { @@ -1945,12 +1945,12 @@ def get_cda_data(pk): "oidMo": data["oidMo"], "document": data, "patient": { - 'id': card.pk, - 'snils': data_individual["snils"], - 'name': {'family': ind.family, 'name': ind.name, 'patronymic': ind.patronymic}, - 'gender': ind.sex.lower(), - 'birthdate': ind.birthday.strftime("%Y%m%d"), - 'oms': {'number': card.get_data_individual()['oms']['polis_num'], 'issueOrgName': smo_title, 'issueOrgCode': insurer_full_code, 'smoId': smo_id}, + "id": card.pk, + "snils": data_individual["snils"], + "name": {"family": ind.family, "name": ind.name, "patronymic": ind.patronymic}, + "gender": ind.sex.lower(), + "birthdate": ind.birthday.strftime("%Y%m%d"), + "oms": {"number": card.get_data_individual()["oms"]["polis_num"], "issueOrgName": smo_title, "issueOrgCode": insurer_full_code, "smoId": smo_id}, }, "organization": data["organization"], }, @@ -1958,12 +1958,12 @@ def get_cda_data(pk): return {} -@api_view(['POST']) +@api_view(["POST"]) @authentication_classes([]) @permission_classes([]) def eds_get_cda_data(request): - token = request.META.get('HTTP_AUTHORIZATION') - token = token.replace('Bearer ', '') + token = request.META.get("HTTP_AUTHORIZATION") + token = token.replace("Bearer ", "") if not token or not DoctorProfile.objects.filter(eds_token=token).exists(): return Response({"ok": False}) @@ -1974,12 +1974,12 @@ def eds_get_cda_data(request): return Response(get_cda_data(pk)) -@api_view(['POST']) +@api_view(["POST"]) @authentication_classes([]) @permission_classes([]) def external_check_result(request): - token = request.META.get('HTTP_AUTHORIZATION') - token = token.replace('Bearer ', '') + token = request.META.get("HTTP_AUTHORIZATION") + token = token.replace("Bearer ", "") external_service = ExternalService.objects.filter(token=token).first() if not token or not external_service: @@ -2001,7 +2001,7 @@ def external_check_result(request): status=403, ) - if 'qr_check_result' not in external_service.rights: + if "qr_check_result" not in external_service.rights: return Response( { "ok": False, @@ -2082,7 +2082,7 @@ def external_check_result(request): ) -@api_view(['POST']) +@api_view(["POST"]) def get_protocol_result(request): body = json.loads(request.body) pk = body.get("pk") @@ -2099,11 +2099,11 @@ def get_protocol_result(request): "oidMo": data["oidMo"], "document": data, "patient": { - 'id': card.number, - 'snils': card.get_data_individual()["snils"], - 'name': {'family': ind.family, 'name': ind.name, 'patronymic': ind.patronymic}, - 'gender': ind.sex.lower(), - 'birthdate': ind.birthday.strftime("%Y%m%d"), + "id": card.number, + "snils": card.get_data_individual()["snils"], + "name": {"family": ind.family, "name": ind.name, "patronymic": ind.patronymic}, + "gender": ind.sex.lower(), + "birthdate": ind.birthday.strftime("%Y%m%d"), }, "organization": data["organization"], }, @@ -2118,11 +2118,11 @@ def get_protocol_result(request): "oidMo": data["oidMo"], "document": data, "patient": { - 'id': card.number, - 'snils': card.get_data_individual()["snils"], - 'name': {'family': ind.family, 'name': ind.name, 'patronymic': ind.patronymic}, - 'gender': ind.sex.lower(), - 'birthdate': ind.birthday.strftime("%Y%m%d"), + "id": card.number, + "snils": card.get_data_individual()["snils"], + "name": {"family": ind.family, "name": ind.name, "patronymic": ind.patronymic}, + "gender": ind.sex.lower(), + "birthdate": ind.birthday.strftime("%Y%m%d"), }, "organization": data["organization"], }, @@ -2138,11 +2138,11 @@ def get_protocol_result(request): "oidMo": data["oidMo"], "document": data, "patient": { - 'id': card.number, - 'snils': card.get_data_individual()["snils"], - 'name': {'family': ind.family, 'name': ind.name, 'patronymic': ind.patronymic}, - 'gender': ind.sex.lower(), - 'birthdate': ind.birthday.strftime("%Y%m%d"), + "id": card.number, + "snils": card.get_data_individual()["snils"], + "name": {"family": ind.family, "name": ind.name, "patronymic": ind.patronymic}, + "gender": ind.sex.lower(), + "birthdate": ind.birthday.strftime("%Y%m%d"), }, "organization": data["organization"], }, @@ -2152,7 +2152,7 @@ def get_protocol_result(request): return Response({}) -@api_view(['POST', 'GET']) +@api_view(["POST", "GET"]) def get_hosp_services(request): services = [] r: Researches @@ -2166,48 +2166,48 @@ def get_hosp_services(request): return Response({"services": services}) -@api_view(['GET']) +@api_view(["GET"]) def mkb10(request): return Response({"rows": mkb10_dict(request, True)}) -@api_view(['POST', 'PUT']) +@api_view(["POST", "PUT"]) @parser_classes([MultiPartParser, FormParser, JSONParser]) @can_use_schedule_only def hosp_record(request): files = [] - if request.method == 'PUT': + if request.method == "PUT": for kf in request.data: - if kf != 'document': + if kf != "document": files.append(request.data[kf]) - form = request.data['document'] + form = request.data["document"] else: form = request.body data = data_parse( form, { - 'snils': 'str_strip', - 'enp': 'str_strip', - 'family': 'str_strip', - 'name': 'str_strip', - 'patronymic': 'str_strip', - 'sex': 'str_strip', - 'birthdate': 'str_strip', - 'comment': 'str_strip', - 'date': 'str_strip', - 'service': int, - 'phone': 'str_strip', - 'diagnosis': 'str_strip', + "snils": "str_strip", + "enp": "str_strip", + "family": "str_strip", + "name": "str_strip", + "patronymic": "str_strip", + "sex": "str_strip", + "birthdate": "str_strip", + "comment": "str_strip", + "date": "str_strip", + "service": int, + "phone": "str_strip", + "diagnosis": "str_strip", }, ) if len(files) > LK_FILE_COUNT: - return Response({"ok": False, 'message': 'Слишком много файлов'}) + return Response({"ok": False, "message": "Слишком много файлов"}) for f in files: if f.size > LK_FILE_SIZE_BYTES: - return Response({"ok": False, 'message': 'Файл слишком большой'}) + return Response({"ok": False, "message": "Файл слишком большой"}) if not check_type_file(file_in_memory=f): return JsonResponse( { @@ -2229,13 +2229,13 @@ def hosp_record(request): phone: str = data[10] diagnosis: str = data[11] - if sex == 'm': - sex = 'м' + if sex == "m": + sex = "м" - if sex == 'f': - sex = 'ж' + if sex == "f": + sex = "ж" - snils = ''.join(ch for ch in snils if ch.isdigit()) + snils = "".join(ch for ch in snils if ch.isdigit()) individual = None if enp: @@ -2243,7 +2243,7 @@ def hosp_record(request): individual = individuals.first() if not individual and snils: - individuals = Individual.objects.filter(document__number=snils, document__document_type__title='СНИЛС') + individuals = Individual.objects.filter(document__number=snils, document__document_type__title="СНИЛС") individual = individuals.first() if not individual and family and name: @@ -2260,24 +2260,24 @@ def hosp_record(request): need_return_individual=True, ) if not individual: - return Response({"ok": False, 'message': 'Физлицо не найдено'}) + return Response({"ok": False, "message": "Физлицо не найдено"}) card = Card.objects.filter(individual=individual, base__internal_type=True).first() if not card: card = Card.add_l2_card(individual) if not card: - return Response({"ok": False, 'message': 'Карта не найдена'}) + return Response({"ok": False, "message": "Карта не найдена"}) if SCHEDULE_AGE_LIMIT_LTE: age = card.individual.age() if age > SCHEDULE_AGE_LIMIT_LTE: - return Response({"ok": False, 'message': f'Пациент должен быть не старше {SCHEDULE_AGE_LIMIT_LTE} лет'}) + return Response({"ok": False, "message": f"Пациент должен быть не старше {SCHEDULE_AGE_LIMIT_LTE} лет"}) hospital_research: Researches = Researches.objects.filter(pk=service, is_hospital=True).first() if not hospital_research: - return Response({"ok": False, 'message': 'Услуга не найдена'}) + return Response({"ok": False, "message": "Услуга не найдена"}) has_free_slots = check_available_hospital_slot_before_save(hospital_research.pk, None, date) if not has_free_slots: @@ -2287,15 +2287,15 @@ def hosp_record(request): with transaction.atomic(): plan_pk = PlanHospitalization.plan_hospitalization_save( { - 'card': card, - 'research': hospital_research.pk, - 'date': date, - 'comment': comment[:256], - 'phone': phone, - 'action': 0, - 'hospital_department_id': hosp_department_id, - 'diagnos': diagnosis, - 'files': files, + "card": card, + "research": hospital_research.pk, + "date": date, + "comment": comment[:256], + "phone": phone, + "action": 0, + "hospital_department_id": hosp_department_id, + "diagnos": diagnosis, + "files": files, }, None, ) @@ -2304,24 +2304,24 @@ def hosp_record(request): plan_files.uploaded_file = f plan_files.save() - y, m, d = date.split('-') + y, m, d = date.split("-") return Response({"ok": True, "message": f"Запись создана — {hospital_research.get_title()} {d}.{m}.{y}"}) -@api_view(['POST']) +@api_view(["POST"]) @can_use_schedule_only def hosp_record_list(request): data = data_parse( request.body, { - 'snils': 'str_strip', - 'enp': 'str_strip', + "snils": "str_strip", + "enp": "str_strip", }, ) snils: str = data[0] enp: str = data[1] - snils = ''.join(ch for ch in snils if ch.isdigit()) + snils = "".join(ch for ch in snils if ch.isdigit()) individual = None if enp: @@ -2329,34 +2329,34 @@ def hosp_record_list(request): individual = individuals.first() if not individual and snils: - individuals = Individual.objects.filter(document__number=snils, document__document_type__title='СНИЛС') + individuals = Individual.objects.filter(document__number=snils, document__document_type__title="СНИЛС") individual = individuals.first() if not individual: - return Response({"rows": [], 'message': 'Физлицо не найдено'}) + return Response({"rows": [], "message": "Физлицо не найдено"}) card = Card.objects.filter(individual=individual, base__internal_type=True).first() if not card: - return Response({"rows": [], 'message': 'Карта не найдена'}) + return Response({"rows": [], "message": "Карта не найдена"}) rows = [] plan: PlanHospitalization - for plan in PlanHospitalization.objects.filter(client=card, research__isnull=False, action=0).order_by('-exec_at'): + for plan in PlanHospitalization.objects.filter(client=card, research__isnull=False, action=0).order_by("-exec_at"): status_description = "" if plan.work_status == 2: status_description = plan.why_cancel if plan.work_status == 3: slot_plan = plan.slot_fact.plan - status_description = slot_plan.datetime.astimezone(pytz.timezone(settings.TIME_ZONE)).strftime('%d.%m.%Y %H:%M') + status_description = slot_plan.datetime.astimezone(pytz.timezone(settings.TIME_ZONE)).strftime("%d.%m.%Y %H:%M") rows_files = [] row_file: PlanHospitalizationFiles - for row_file in PlanHospitalizationFiles.objects.filter(plan=plan).order_by('-created_at'): + for row_file in PlanHospitalizationFiles.objects.filter(plan=plan).order_by("-created_at"): rows_files.append( { - 'pk': row_file.pk, - 'fileName': os.path.basename(row_file.uploaded_file.name) if row_file.uploaded_file else None, + "pk": row_file.pk, + "fileName": os.path.basename(row_file.uploaded_file.name) if row_file.uploaded_file else None, } ) messages_data = Messages.get_messages_by_plan_hosp(plan.pk, last=True) @@ -2364,7 +2364,7 @@ def hosp_record_list(request): { "pk": plan.pk, "service": plan.research.get_title(), - "date": plan.exec_at.strftime('%d.%m.%Y'), + "date": plan.exec_at.strftime("%d.%m.%Y"), "phone": plan.phone, "diagnosis": plan.diagnos, "comment": plan.comment, @@ -2378,19 +2378,19 @@ def hosp_record_list(request): return Response({"rows": rows}) -@api_view(['POST']) +@api_view(["POST"]) def get_all_messages_by_plan_id(request): - data = data_parse(request.body, {'pk': int}) + data = data_parse(request.body, {"pk": int}) pk: int = data[0] messages = Messages.get_messages_by_plan_hosp(pk, last=False) return Response({"rows": messages}) -@api_view(['POST']) +@api_view(["POST"]) def direction_records(request): data = data_parse( request.body, - {'snils': 'str_strip', 'enp': 'str_strip', 'date_year': int}, + {"snils": "str_strip", "enp": "str_strip", "date_year": int}, ) snils: str = data[0] enp: str = data[1] @@ -2398,9 +2398,9 @@ def direction_records(request): card: Card = find_patient(snils, enp) if not card: - return Response({"rows": [], 'message': 'Карта не найдена'}) - d1 = try_strptime(f"{date_year}-01-01", formats=('%Y-%m-%d',)) - d2 = try_strptime(f"{date_year}-12-31", formats=('%Y-%m-%d',)) + return Response({"rows": [], "message": "Карта не найдена"}) + d1 = try_strptime(f"{date_year}-01-01", formats=("%Y-%m-%d",)) + d2 = try_strptime(f"{date_year}-12-31", formats=("%Y-%m-%d",)) start_date = datetime.datetime.combine(d1, datetime.time.min) end_date = datetime.datetime.combine(d2, datetime.time.max) rows = {} @@ -2444,24 +2444,24 @@ def direction_records(request): return Response({"rows": rows, "count_paraclinic": count_paraclinic, "count_doc_refferal": count_doc_refferal, "count_laboratory": count_laboratory}) -@api_view(['POST']) +@api_view(["POST"]) def directions_by_category_result_year(request): request_data = json.loads(request.body) - mode = request_data.get('mode') - is_lab = request_data.get('isLab', mode == 'laboratory') - is_paraclinic = request_data.get('isParaclinic', mode == 'paraclinic') - is_doc_refferal = request_data.get('isDocReferral', mode == 'docReferral') - is_extract = request_data.get('isExtract', mode == 'extract') - is_user_forms = request_data.get('isUserForms', mode == 'forms') - year = request_data['year'] - - card: Card = find_patient(request_data.get('snils'), request_data.get('enp')) + mode = request_data.get("mode") + is_lab = request_data.get("isLab", mode == "laboratory") + is_paraclinic = request_data.get("isParaclinic", mode == "paraclinic") + is_doc_refferal = request_data.get("isDocReferral", mode == "docReferral") + is_extract = request_data.get("isExtract", mode == "extract") + is_user_forms = request_data.get("isUserForms", mode == "forms") + year = request_data["year"] + + card: Card = find_patient(request_data.get("snils"), request_data.get("enp")) if not card: - return Response({"results": [], 'message': 'Карта не найдена'}) + return Response({"results": [], "message": "Карта не найдена"}) - d1 = datetime.datetime.strptime(f'{LK_DAY_MONTH_START_SHOW_RESULT}{year}', '%d.%m.%Y') + d1 = datetime.datetime.strptime(f"{LK_DAY_MONTH_START_SHOW_RESULT}{year}", "%d.%m.%Y") start_date = datetime.datetime.combine(d1, datetime.time.min) - d2 = datetime.datetime.strptime(f'31.12.{year}', '%d.%m.%Y') + d2 = datetime.datetime.strptime(f"31.12.{year}", "%d.%m.%Y") end_date = datetime.datetime.combine(d2, datetime.time.max) if not is_lab and not is_doc_refferal and not is_paraclinic and not is_extract and not is_user_forms: @@ -2475,7 +2475,7 @@ def directions_by_category_result_year(request): confirmed_directions = None if is_extract: - extract_research_pks = tuple(HospitalService.objects.values_list('slave_research__id', flat=True).filter(site_type=7)) + extract_research_pks = tuple(HospitalService.objects.values_list("slave_research__id", flat=True).filter(site_type=7)) if extract_research_pks: confirmed_directions = get_confirm_direction_patient_year_is_extract(start_date, end_date, card.pk, extract_research_pks) @@ -2491,39 +2491,39 @@ def directions_by_category_result_year(request): if d.direction not in directions: dicom_server_url = None if d.study_instance_uid_tag: - data = {'Level': 'Study', 'Query': {"StudyInstanceUID": d.study_instance_uid_tag}, "Expand": True} + data = {"Level": "Study", "Query": {"StudyInstanceUID": d.study_instance_uid_tag}, "Expand": True} if len(DICOM_SERVERS) > 1: is_dicom_study = check_dicom_study(DICOM_SERVERS, data) if is_dicom_study.get("server"): dicom_server_url = is_dicom_study.get("server") else: dicom_server_url = DICOM_SERVER - directions[d.direction] = {'pk': d.direction, 'confirmedAt': d.ch_time_confirmation, 'services': [], 'study': d.study_instance_uid_tag, "server": dicom_server_url} - directions[d.direction]['services'].append(d.research_title) + directions[d.direction] = {"pk": d.direction, "confirmedAt": d.ch_time_confirmation, "services": [], "study": d.study_instance_uid_tag, "server": dicom_server_url} + directions[d.direction]["services"].append(d.research_title) return JsonResponse({"results": list(directions.values())}) -@api_view(['POST']) +@api_view(["POST"]) def results_by_direction(request): request_data = json.loads(request.body) token = request.headers.get("Authorization").split(" ")[1] token_obj = Application.objects.filter(key=token).first() - if not hasattr(request.user, 'hospitals'): - return Response({"ok": False, 'message': 'Некорректный auth токен'}) - oid_org = request_data.get(("oid") or '') + if not hasattr(request.user, "hospitals"): + return Response({"ok": False, "message": "Некорректный auth токен"}) + oid_org = request_data.get(("oid") or "") check_result = check_correct_hosp(request, oid_org) if not check_result["OK"]: - return Response({"ok": False, 'message': check_result["message"]}) + return Response({"ok": False, "message": check_result["message"]}) hospital = check_result["hospital"] - mode = request_data.get('mode') - is_lab = request_data.get('isLab', mode == 'laboratory') - is_paraclinic = request_data.get('isParaclinic', mode == 'paraclinic') - is_doc_refferal = request_data.get('isDocReferral', mode == 'docReferral') - is_user_forms = request_data.get('isUserFroms', mode == 'forms') - direction = request_data.get('pk') - external_add_order = request_data.get('externalOrder') - directions_data = request_data.get('directions') + mode = request_data.get("mode") + is_lab = request_data.get("isLab", mode == "laboratory") + is_paraclinic = request_data.get("isParaclinic", mode == "paraclinic") + is_doc_refferal = request_data.get("isDocReferral", mode == "docReferral") + is_user_forms = request_data.get("isUserFroms", mode == "forms") + direction = request_data.get("pk") + external_add_order = request_data.get("externalOrder") + directions_data = request_data.get("directions") if is_lab and not directions_data: if external_add_order: ext_add_order_obj = directions.ExternalAdditionalOrder.objects.filter(external_add_order=external_add_order).first() @@ -2536,60 +2536,60 @@ def results_by_direction(request): for d in directions_data: direction_obj = Napravleniya.objects.filter(hospital=hospital, pk=d).first() if not direction_obj: - return Response({"ok": False, 'message': 'Номер направления не принадлежит организации'}) + return Response({"ok": False, "message": "Номер направления не принадлежит организации"}) objs_result = {} if is_lab: direction_result = get_laboratory_results_by_directions(tuple(directions_data)) for r in direction_result: if r.direction not in objs_result: - objs_result[r.direction] = {'pk': r.direction, 'confirmedAt': r.date_confirm, 'services': {}} - - if r.iss_id not in objs_result[r.direction]['services']: - objs_result[r.direction]['services'][r.iss_id] = { - 'title': r.research_title, - 'internalCode': r.research_internal_code, - 'fio': short_fio_dots(r.fio) if r.fio else r.doc_confirmation_string, - 'confirmedAt': r.date_confirm, - 'fractions': [], + objs_result[r.direction] = {"pk": r.direction, "confirmedAt": r.date_confirm, "services": {}} + + if r.iss_id not in objs_result[r.direction]["services"]: + objs_result[r.direction]["services"][r.iss_id] = { + "title": r.research_title, + "internalCode": r.research_internal_code, + "fio": short_fio_dots(r.fio) if r.fio else r.doc_confirmation_string, + "confirmedAt": r.date_confirm, + "fractions": [], } - objs_result[r.direction]['services'][r.iss_id]['fractions'].append( + objs_result[r.direction]["services"][r.iss_id]["fractions"].append( { - 'title': r.fraction_title, - 'value': r.value, - 'units': r.units, - 'fsli': r.fraction_fsli, - 'ref_m': r.ref_m, - 'ref_f': r.ref_f, + "title": r.fraction_title, + "value": r.value, + "units": r.units, + "fsli": r.fraction_fsli, + "ref_m": r.ref_m, + "ref_f": r.ref_f, } ) if is_paraclinic or is_doc_refferal or is_user_forms: results = desc_to_data(directions_data, force_all_fields=True) for i in results: - direction_data = i['result'][0]["date"].split(' ') + direction_data = i["result"][0]["date"].split(" ") if direction_data[1] not in objs_result: - objs_result[direction_data[1]] = {'pk': direction_data[1], 'confirmedAt': direction_data[0], 'services': {}} - if i['result'][0]["iss_id"] not in objs_result[direction_data[1]]['services']: - objs_result[direction_data[1]]['services'][i['result'][0]["iss_id"]] = { - 'title': i['title_research'], - 'fio': short_fio_dots(i['result'][0]["docConfirm"]), - 'confirmedAt': direction_data[0], - 'fractions': [], + objs_result[direction_data[1]] = {"pk": direction_data[1], "confirmedAt": direction_data[0], "services": {}} + if i["result"][0]["iss_id"] not in objs_result[direction_data[1]]["services"]: + objs_result[direction_data[1]]["services"][i["result"][0]["iss_id"]] = { + "title": i["title_research"], + "fio": short_fio_dots(i["result"][0]["docConfirm"]), + "confirmedAt": direction_data[0], + "fractions": [], } - values = values_as_structure_data(i['result'][0]["data"]) - objs_result[direction_data[1]]['services'][i['result'][0]["iss_id"]]["fractions"].extend(values) + values = values_as_structure_data(i["result"][0]["data"]) + objs_result[direction_data[1]]["services"][i["result"][0]["iss_id"]]["fractions"].extend(values) return JsonResponse({"results": list(objs_result.values())}) -@api_view(['POST']) +@api_view(["POST"]) @can_use_schedule_only def check_employee(request): data = json.loads(request.body) - snils = data.get('snils') + snils = data.get("snils") date_now = current_time(only_date=True) doctor_profile = DoctorProfile.objects.filter(snils=snils, external_access=True, date_stop_external_access__gte=date_now).first() if doctor_profile: @@ -2597,90 +2597,90 @@ def check_employee(request): return Response({"ok": False}) -@api_view(['GET']) +@api_view(["GET"]) @can_use_schedule_only def hospitalization_plan_research(request): return Response({"services": get_hospital_resource()}) -@api_view(['POST']) +@api_view(["POST"]) @can_use_schedule_only def available_hospitalization_plan(request): data = json.loads(request.body) - research_pk = data.get('research_pk') - resource_id = data.get('resource_id') - date_start = data.get('date_start') - date_end = data.get('date_end') + research_pk = data.get("research_pk") + resource_id = data.get("resource_id") + date_start = data.get("date_start") + date_end = data.get("date_end") result, _ = get_available_hospital_plans(research_pk, resource_id, date_start, date_end) return Response({"data": result}) -@api_view(['POST']) +@api_view(["POST"]) @can_use_schedule_only def check_hosp_slot_before_save(request): data = json.loads(request.body) - research_pk = data.get('research_pk') - resource_id = data.get('resource_id') - date = data.get('date') + research_pk = data.get("research_pk") + resource_id = data.get("resource_id") + date = data.get("date") result = check_available_hospital_slot_before_save(research_pk, resource_id, date) return JsonResponse({"result": result}) -@api_view(['POST']) +@api_view(["POST"]) @can_use_schedule_only def get_pdf_result(request): data = json.loads(request.body) - pk = data.get('pk') + pk = data.get("pk") pdf_content = direction_pdf_result(pk) return JsonResponse({"result": pdf_content}) -@api_view(['POST']) +@api_view(["POST"]) @can_use_schedule_only def get_pdf_direction(request): data = json.loads(request.body) - pk = data.get('pk') + pk = data.get("pk") localclient = TC(enforce_csrf_checks=False) addr = "/directions/pdf" - params = {"napr_id": json.dumps([pk]), 'token': "8d63a9d6-c977-4c7b-a27c-64f9ba8086a7"} + params = {"napr_id": json.dumps([pk]), "token": "8d63a9d6-c977-4c7b-a27c-64f9ba8086a7"} result = localclient.get(addr, params).content - pdf_content = base64.b64encode(result).decode('utf-8') + pdf_content = base64.b64encode(result).decode("utf-8") return JsonResponse({"result": pdf_content}) -@api_view(['POST']) +@api_view(["POST"]) @can_use_schedule_only def documents_lk(request): return Response({"documents": get_can_created_patient()}) -@api_view(['POST']) +@api_view(["POST"]) @can_use_schedule_only def details_document_lk(request): data = data_parse( request.body, - {'pk': int}, + {"pk": int}, ) pk: int = data[0] response = get_researches_details(pk) return Response(response) -@api_view(['POST']) +@api_view(["POST"]) @can_use_schedule_only def forms_lk(request): response = {"forms": LK_FORMS} return Response(response) -@api_view(['POST']) +@api_view(["POST"]) @can_use_schedule_only def pdf_form_lk(request): data = data_parse( request.body, - {'type_form': str, 'snils': str, 'enp': str, 'agent': {'snils': str, 'enp': str}}, + {"type_form": str, "snils": str, "enp": str, "agent": {"snils": str, "enp": str}}, ) type_form: str = data[0] snils: str = data[1] @@ -2688,9 +2688,9 @@ def pdf_form_lk(request): card: Card = find_patient(snils, enp) if not card: - return Response({"results": [], 'message': 'Карта не найдена'}) + return Response({"results": [], "message": "Карта не найдена"}) - f = import_string('forms.forms' + type_form[0:3] + '.form_' + type_form[4:6]) + f = import_string("forms.forms" + type_form[0:3] + ".form_" + type_form[4:6]) user = User.objects.get(pk=LK_USER) result = f( request_data={ @@ -2699,16 +2699,16 @@ def pdf_form_lk(request): "hospital": user.doctorprofile.get_hospital(), } ) - pdf_content = base64.b64encode(result).decode('utf-8') + pdf_content = base64.b64encode(result).decode("utf-8") return Response({"result": pdf_content}) -@api_view(['POST', 'PUT']) +@api_view(["POST", "PUT"]) @parser_classes([MultiPartParser, FormParser, JSONParser]) @can_use_schedule_only def add_file_hospital_plan(request): - file = request.data.get('file-add') - data = data_parse(request.data.get('document'), {'pk': int}) + file = request.data.get("file-add") + data = data_parse(request.data.get("document"), {"pk": int}) pk: int = data[0] with transaction.atomic(): @@ -2751,13 +2751,13 @@ def add_file_hospital_plan(request): ) -@api_view(['POST']) +@api_view(["POST"]) @can_use_schedule_only def get_limit_download_files(request): return Response({"lk_file_count": LK_FILE_COUNT, "lk_file_size_bytes": LK_FILE_SIZE_BYTES}) -@api_view(['POST']) +@api_view(["POST"]) @can_use_schedule_only def document_lk_save(request): form = request.body @@ -2765,19 +2765,19 @@ def document_lk_save(request): data = data_parse( form, { - 'snils': 'str_strip', - 'enp': 'str_strip', - 'family': 'str_strip', - 'name': 'str_strip', - 'patronymic': 'str_strip', - 'sex': 'str_strip', - 'birthdate': 'str_strip', - 'service': int, - 'groups': list, - 'phone': 'str_strip', + "snils": "str_strip", + "enp": "str_strip", + "family": "str_strip", + "name": "str_strip", + "patronymic": "str_strip", + "sex": "str_strip", + "birthdate": "str_strip", + "service": int, + "groups": list, + "phone": "str_strip", }, { - 'phone': '', + "phone": "", }, ) @@ -2792,13 +2792,13 @@ def document_lk_save(request): groups: dict = data[8] phone: str = data[9] - if sex == 'm': - sex = 'м' + if sex == "m": + sex = "м" - if sex == 'f': - sex = 'ж' + if sex == "f": + sex = "ж" - snils = ''.join(ch for ch in snils if ch.isdigit()) + snils = "".join(ch for ch in snils if ch.isdigit()) individual = None if enp: @@ -2806,7 +2806,7 @@ def document_lk_save(request): individual = individuals.first() if not individual and snils: - individuals = Individual.objects.filter(document__number=snils, document__document_type__title='СНИЛС') + individuals = Individual.objects.filter(document__number=snils, document__document_type__title="СНИЛС") individual = individuals.first() if not individual and family and name: @@ -2823,24 +2823,24 @@ def document_lk_save(request): need_return_individual=True, ) if not individual: - return Response({"ok": False, 'message': 'Физлицо не найдено'}) + return Response({"ok": False, "message": "Физлицо не найдено"}) card = Card.objects.filter(individual=individual, base__internal_type=True).first() if not card: card = Card.add_l2_card(individual) if not card: - return Response({"ok": False, 'message': 'Карта не найдена'}) + return Response({"ok": False, "message": "Карта не найдена"}) if SCHEDULE_AGE_LIMIT_LTE: age = card.individual.age() if age > SCHEDULE_AGE_LIMIT_LTE: - return Response({"ok": False, 'message': f'Пациент должен быть не старше {SCHEDULE_AGE_LIMIT_LTE} лет'}) + return Response({"ok": False, "message": f"Пациент должен быть не старше {SCHEDULE_AGE_LIMIT_LTE} лет"}) service: Researches = Researches.objects.filter(pk=service, can_created_patient=True).first() if not service: - return Response({"ok": False, 'message': 'Услуга не найдена'}) + return Response({"ok": False, "message": "Услуга не найдена"}) date = timezone.now() date_start = date_at_bound(date) @@ -2848,7 +2848,7 @@ def document_lk_save(request): user = User.objects.get(pk=LK_USER).doctorprofile if Napravleniya.objects.filter(client=card, issledovaniya__research=service, data_sozdaniya__gte=date_start).count() > 1: - return Response({"ok": False, 'message': 'Вы сегодня уже заполняли эту форму два раза!\nПопробуйте позднее.'}) + return Response({"ok": False, "message": "Вы сегодня уже заполняли эту форму два раза!\nПопробуйте позднее."}) with transaction.atomic(): result = Napravleniya.gen_napravleniya_by_issledovaniya( @@ -2888,14 +2888,14 @@ def document_lk_save(request): comment_lines = [] for g in groups[:50]: - if g['title'] and g['show_title']: + if g["title"] and g["show_title"]: comment_lines.append(f"{g['title']}:") - for f in g['fields'][:50]: - if not f['new_value']: + for f in g["fields"][:50]: + if not f["new_value"]: continue fields_count += 1 - f_result = directions.ParaclinicResult(issledovaniye=iss, field_id=f['pk'], field_type=f['field_type'], value=html.escape(f['new_value'][:400])) + f_result = directions.ParaclinicResult(issledovaniye=iss, field_id=f["pk"], field_type=f["field_type"], value=html.escape(f["new_value"][:400])) f_result.save() @@ -2914,49 +2914,49 @@ def document_lk_save(request): hospital = Hospitals.get_default_hospital() DoctorCall.doctor_call_save( { - 'card': card, - 'research': service.pk, - 'address': card.main_address, - 'district': -1, - 'date': current_time(), - 'comment': '\n'.join(comment_lines), - 'phone': phone, - 'doc': -1, - 'purpose': 24, - 'hospital': hospital.pk, - 'external': True, - 'external_num': str(direction), - 'is_main_external': False, - 'direction': direction, + "card": card, + "research": service.pk, + "address": card.main_address, + "district": -1, + "date": current_time(), + "comment": "\n".join(comment_lines), + "phone": phone, + "doc": -1, + "purpose": 24, + "hospital": hospital.pk, + "external": True, + "external_num": str(direction), + "is_main_external": False, + "direction": direction, } ) return Response({"ok": True, "message": f"Заявка {direction} зарегистрирована"}) - return Response({"ok": True, "message": f"Форма \"{service.get_title()}\" ({direction}) сохранена"}) + return Response({"ok": True, "message": f'Форма "{service.get_title()}" ({direction}) сохранена'}) -@api_view(['POST']) +@api_view(["POST"]) def amd_save(request): data = json.loads(request.body) - local_uid = data.get('localUid') - direction_pk = data.get('pk') - status = data.get('status') - message_id = data.get('messageId') - message = data.get('message') - kind = data.get('kind') - organization_oid = data.get('organizationOid') + local_uid = data.get("localUid") + direction_pk = data.get("pk") + status = data.get("status") + message_id = data.get("messageId") + message = data.get("message") + kind = data.get("kind") + organization_oid = data.get("organizationOid") hospital = Hospitals.objects.filter(oid=organization_oid).first() - emdr_id = data.get('emdrId') - registration_date = data.get('registrationDate') + emdr_id = data.get("emdrId") + registration_date = data.get("registrationDate") if registration_date: - registration_date = datetime.datetime.strptime(registration_date, '%Y-%m-%d %H:%M:%S') + registration_date = datetime.datetime.strptime(registration_date, "%Y-%m-%d %H:%M:%S") - type = data.get('type') + type = data.get("type") if type and type == "registerDocument": - time_exec = data.get('timeExec') - time_exec = datetime.datetime.strptime(time_exec, '%Y-%m-%d %H:%M:%S') - department_oid = data.get('departmentOid') + time_exec = data.get("timeExec") + time_exec = datetime.datetime.strptime(time_exec, "%Y-%m-%d %H:%M:%S") + department_oid = data.get("departmentOid") podrazdeleniye = Podrazdeleniya.objects.filter(oid=department_oid).first() amd = ArchiveMedicalDocuments( local_uid=local_uid, @@ -2979,62 +2979,62 @@ def amd_save(request): amd = ArchiveMedicalDocuments.objects.get(message_id=message_id) amd.emdr_id = emdr_id amd.registration_date = registration_date - code = data.get('code') + code = data.get("code") amd.message = f"{code}@{message}" amd.save() return Response({"ok": True}) -@api_view(['POST']) +@api_view(["POST"]) def register_emdr_id(request): data = json.loads(request.body) - emdr_id = data.get('localUid') - direction_pk = data.get('pk') + emdr_id = data.get("localUid") + direction_pk = data.get("pk") direction = Napravleniya.objects.get(pk=direction_pk) direction.emdr_id = emdr_id - direction.save(update_fields=['emdr_id']) + direction.save(update_fields=["emdr_id"]) return Response({"ok": True}) -@api_view(['POST']) +@api_view(["POST"]) def get_direction_pk_by_emdr_id(request): data = json.loads(request.body) - emdr_id = data.get('emdrId') + emdr_id = data.get("emdrId") direction = Napravleniya.objects.get(emdr_id=emdr_id) return Response({"pk": direction.pk}) -@api_view(['POST']) +@api_view(["POST"]) def get_value_field(request): data = json.loads(request.body) - research_id = data.get('researchId') - field_id = data.get('fieldId') - date = data.get('date') - type_period = data.get('typePeriod') + research_id = data.get("researchId") + field_id = data.get("fieldId") + date = data.get("date") + type_period = data.get("typePeriod") research_obj = Researches.objects.filter(pk=research_id).first() data = [] if research_obj and research_obj.is_monitoring: query_data = directions.MonitoringResult.objects.filter(type_period=type_period, period_date=date, field_id=int(field_id), research_id=research_id) data = [ { - 'hospitalTitle': i.hospital.title, - 'hospitalOid': i.hospital.oid, - 'valueAggregate': i.value_aggregate, - 'valueText': i.value_text, - 'period_param_hour': i.period_param_hour, - 'period_param_day': i.period_param_day, - 'period_param_week_description': i.period_param_week_description, - 'period_param_week_date_start': i.period_param_week_date_start, - 'period_param_week_date_end': i.period_param_week_date_end, - 'period_param_month': i.period_param_month, - 'period_param_year': i.period_param_year, + "hospitalTitle": i.hospital.title, + "hospitalOid": i.hospital.oid, + "valueAggregate": i.value_aggregate, + "valueText": i.value_text, + "period_param_hour": i.period_param_hour, + "period_param_day": i.period_param_day, + "period_param_week_description": i.period_param_week_description, + "period_param_week_date_start": i.period_param_week_date_start, + "period_param_week_date_end": i.period_param_week_date_end, + "period_param_month": i.period_param_month, + "period_param_year": i.period_param_year, } for i in query_data ] return Response({"data": data}) -@api_view(['POST']) +@api_view(["POST"]) def get_price_data(request): request_data = json.loads(request.body) price_code = request_data.get("priceCode") @@ -3045,10 +3045,10 @@ def get_price_data(request): result = [] if not token_obj.unlimited_access: if not price_code and not price_id: - return {"OK": False, "message": 'priceCode или priceId должны быть переданы'} + return {"OK": False, "message": "priceCode или priceId должны быть переданы"} check_permissions_price = check_correct_hospital_company_for_price(request, price_code, price_id) if not check_permissions_price["OK"]: - return Response({"ok": False, 'message': check_permissions_price["message"]}) + return Response({"ok": False, "message": check_permissions_price["message"]}) price = check_permissions_price["price"] else: price = PriceName.get_price_by_id_symbol_code(price_code, price_id) @@ -3058,17 +3058,17 @@ def get_price_data(request): return Response({"data": result}) -@api_view(['POST']) +@api_view(["POST"]) def get_prices_by_date(request): request_data = json.loads(request.body) token = request.headers.get("Authorization").split(" ")[1] token_obj = Application.objects.filter(key=token).first() - ogrn = request_data.get("ogrn" or '') - date = request_data.get("date" or '') + ogrn = request_data.get("ogrn" or "") + date = request_data.get("date" or "") if not token_obj.unlimited_access: check_permissions = check_correct_hospital_company(request, ogrn) if not check_permissions["OK"]: - return Response({"ok": False, 'message': check_permissions["message"]}) + return Response({"ok": False, "message": check_permissions["message"]}) hospital = check_permissions["hospital"] company = check_permissions["company"] is_company = check_permissions["is_company"] @@ -3086,30 +3086,26 @@ def get_prices_by_date(request): "title": i.title, "dateStart": i.date_start, "dateEnd": i.date_end, - } for i in prices] + } + for i in prices + ] return Response({"data": result}) -@api_view(['POST']) +@api_view(["POST"]) def get_reference_books(request): request_data = json.loads(request.body) token = request.headers.get("Authorization").split(" ")[1] token_obj = Application.objects.filter(key=token).first() - mode = request_data.get('mode') - is_lab = request_data.get('isLab', mode == 'laboratory') + mode = request_data.get("mode") + is_lab = request_data.get("isLab", mode == "laboratory") if not token_obj.unlimited_access: - return Response({"ok": False, 'message': 'Некорректный auth токен'}) + return Response({"ok": False, "message": "Некорректный auth токен"}) result = [] if is_lab: lab_data = get_lab_research_reference_books() - service_result = { - "serviceId": "", - "serviceTitle": "", - "serviceInternalCode": "", - "serviceNMUCode": "", - "fractions": [] - } + service_result = {"serviceId": "", "serviceTitle": "", "serviceInternalCode": "", "serviceNMUCode": "", "fractions": []} last_research_id = -1 step = 0 @@ -3127,16 +3123,18 @@ def get_reference_books(request): tmp_result["serviceNMUCode"] = i.research_nmu_code tmp_result["fractions"] = fractions - fractions.append({ - "id": i.fraction_id, - "title": i.fraction_title, - "fsli": i.fraction_fsli, - "ref_m": json.loads(i.fraction_ref_m), - "ref_f": json.loads(i.fraction_ref_f), - "unitTitle": i.unit_title, - "unitCode": i.unit_code, - "unitUcum": i.unit_ucum - }) + fractions.append( + { + "id": i.fraction_id, + "title": i.fraction_title, + "fsli": i.fraction_fsli, + "ref_m": json.loads(i.fraction_ref_m), + "ref_f": json.loads(i.fraction_ref_f), + "unitTitle": i.unit_title, + "unitCode": i.unit_code, + "unitUcum": i.unit_ucum, + } + ) last_research_id = i.research_id step += 1 diff --git a/pyproject.toml b/pyproject.toml index c0e6794a6d..f1f63f5fbc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -72,7 +72,7 @@ beren = "0.7.1" transliterate = "1.10.2" imgkit = "1.2.3" astm = {git = "https://github.com/moodpulse/python-astm.git", rev = "v0.6"} -psycopg2-binary = "^2.9.4" +#psycopg2-binary = "^2.9.4" boto3 = "^1.28.64" prompt-toolkit = "^3.0.36" pdf2docx = "^0.5.6" From c17181e7b70df65fc6bdd0f5de6b87f1aad2288e Mon Sep 17 00:00:00 2001 From: Sergei Kasianenko Date: Thu, 19 Oct 2023 08:10:21 +0800 Subject: [PATCH 4/4] psycopg2 --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index f1f63f5fbc..c0e6794a6d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -72,7 +72,7 @@ beren = "0.7.1" transliterate = "1.10.2" imgkit = "1.2.3" astm = {git = "https://github.com/moodpulse/python-astm.git", rev = "v0.6"} -#psycopg2-binary = "^2.9.4" +psycopg2-binary = "^2.9.4" boto3 = "^1.28.64" prompt-toolkit = "^3.0.36" pdf2docx = "^0.5.6"