Skip to content

Commit

Permalink
Merge branch 'develop' into import-tubes
Browse files Browse the repository at this point in the history
  • Loading branch information
Wellheor1 committed Dec 27, 2023
2 parents 0bc8c0b + 56ba593 commit 82ad4c3
Show file tree
Hide file tree
Showing 14 changed files with 191 additions and 12 deletions.
18 changes: 14 additions & 4 deletions api/directions/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from cda.integration import cdator_gen_xml, render_cda
from contracts.models import PriceCategory, PriceCoast, PriceName, Company
from ecp_integration.integration import get_ecp_time_table_list_patient, get_ecp_evn_direction, fill_slot_ecp_free_nearest
from external_system.models import ProfessionsWorkersPositionsRefbook
from integration_framework.common_func import directions_pdf_result
from l2vi.integration import gen_cda_xml, send_cda_xml
import collections
Expand Down Expand Up @@ -84,7 +85,7 @@
from utils.dates import normalize_date, date_iter_range, try_strptime
from utils.dates import try_parse_range
from utils.xh import check_float_is_valid, short_fio_dots
from xml_generate.views import gen_resul_cpp_file
from xml_generate.views import gen_resul_cpp_file, gen_result_cda_files
from .sql_func import (
get_history_dir,
get_confirm_direction,
Expand Down Expand Up @@ -2816,6 +2817,13 @@ def last_field_result(request):
if len(work_data) >= 1:
work_position = work_data[0]
result = {"value": work_position.strip()}
elif request_data["fieldPk"].find('%work_code_position') != -1:
work_position = ""
work_data = c.work_position.split(';')
if len(work_data) >= 1:
work_position = work_data[0]
nsi_position = ProfessionsWorkersPositionsRefbook.objects.values_list("code", flat=True).filter(title=work_position).first()
result = {"value": nsi_position.strip()}
elif request_data["fieldPk"].find('%work_department') != -1:
work_department = ""
work_data = c.work_position.split(';')
Expand Down Expand Up @@ -3854,7 +3862,6 @@ def eds_documents(request):
DirectionDocument.objects.create(direction=direction, last_confirmed_at=last_time_confirm, file_type=t.lower())

DirectionDocument.objects.filter(direction=direction, is_archive=False).exclude(last_confirmed_at=last_time_confirm).update(is_archive=True)

cda_eds_data = get_cda_data(pk)

for d in DirectionDocument.objects.filter(direction=direction, last_confirmed_at=last_time_confirm):
Expand Down Expand Up @@ -3900,8 +3907,11 @@ def eds_documents(request):
cda_data = gen_cda_xml(pk=pk)
cda_xml = cda_data.get('result', {}).get('content')
elif SettingManager.l2('cdator'):
cda_data = cdator_gen_xml(cda_eds_data["generatorName"], direction_data=cda_eds_data["data"])
cda_xml = cda_data.get('result', {}).get('content')
if not iss_obj.research.cda_template_file:
cda_data = cdator_gen_xml(cda_eds_data["generatorName"], direction_data=cda_eds_data["data"])
cda_xml = cda_data.get('result', {}).get('content')
else:
cda_xml = gen_result_cda_files(iss_obj.research.cda_template_file, cda_eds_data["data"])
else:
cda_xml = render_cda(service=cda_eds_data['title'], direction_data=cda_eds_data)
filename = f"{pk}{last_time_confirm}.cda.xml"
Expand Down
8 changes: 7 additions & 1 deletion api/patients/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,12 @@ def patients_get_card_data(request, card_id):
]
rc = Card.objects.filter(base__is_rmis=True, individual=card.individual)
d = District.objects.all().order_by('-sort_weight', '-id')

age = card.individual.age()
if age < 14:
doc_types = [{"pk": x.pk, "title": x.title} for x in DocumentType.objects.all().exclude(title__startswith="Паспорт гражданина РФ")]
else:
doc_types = [{"pk": x.pk, "title": x.title} for x in DocumentType.objects.all()]
return JsonResponse(
{
**i,
Expand Down Expand Up @@ -543,7 +549,7 @@ def patients_get_card_data(request, card_id):
"payer": None if not card.payer else card.payer.get_fio_w_card(),
"payer_pk": card.payer_id,
"rmis_uid": rc[0].number if rc.exists() else None,
"doc_types": [{"pk": x.pk, "title": x.title} for x in DocumentType.objects.all()],
"doc_types": doc_types,
"number_poli": card.number_poliklinika,
"harmful": card.harmful_factor,
"medbookPrefix": card.medbook_prefix,
Expand Down
42 changes: 42 additions & 0 deletions clients/management/commands/import_nsi_harmfull_factors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from django.core.management.base import BaseCommand
from openpyxl import load_workbook

from clients.models import HarmfulFactor


class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('path', type=str)

def handle(self, *args, **kwargs):
"""
:param path - xlsx файл со столбцами:
Идентификатор
Код
Наименование
"""

fp = kwargs["path"]
self.stdout.write("Path: " + fp)
wb = load_workbook(filename=fp)
ws = wb[wb.sheetnames[0]]
starts = False
harmfull_title, description = '', ''
for row in ws.rows:
cells = [str(x.value) for x in row]
if not starts:
if "ИД" in cells:
nsi_id = cells.index("ИД")
description = cells.index("Описание")
harmfull_title = cells.index("Номер")
starts = True
else:
harmful_factor = HarmfulFactor.objects.filter(title=cells[harmfull_title]).first()
if harmful_factor:
harmful_factor.nsi_id = cells[nsi_id]
harmful_factor.save()
self.stdout.write(f'Фактор {harmful_factor.title} обновлён, nsi_id={harmful_factor.nsi_id}')
else:
new_harmful_factor = HarmfulFactor(title=cells[harmfull_title], description=cells[description], nsi_id=cells[nsi_id])
new_harmful_factor.save()
self.stdout.write(f'Фактор {cells[harmfull_title]} добавлен')
1 change: 1 addition & 0 deletions clients/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1065,6 +1065,7 @@ class HarmfulFactor(models.Model):
description = models.CharField(max_length=1024, help_text='Описание', blank=True, default=None, null=True)
template = models.ForeignKey(AssignmentTemplates, db_index=True, null=True, blank=True, default=None, on_delete=models.CASCADE)
cpp_key = models.UUIDField(null=True, blank=True, editable=False, help_text="UUID, с справочника", db_index=True)
nsi_id = models.CharField(max_length=128, db_index=True, blank=True, default=None, null=True)

class Meta:
verbose_name = 'Фактор вредности'
Expand Down
2 changes: 2 additions & 0 deletions directory/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,8 @@ class Researches(models.Model):
plan_external_performing_organization = models.ForeignKey('hospitals.Hospitals', blank=True, null=True, default=None, db_index=True, on_delete=models.SET_NULL)
actual_period_result = models.SmallIntegerField(default=0, blank=True, help_text="Актуальность услуги в днях (для запрета)")
cpp_template_files = models.TextField(max_length=500, default=None, null=True, blank=True, help_text="{1: 'название шаблона',2: 'название шаблона', 3: 'название шаблона'}")
cda_template_file = models.CharField(max_length=50, db_index=True, blank=True, default="", null=True, help_text="название шаблона cda-шаблона")
n3_id_med_document_type = models.SmallIntegerField(default=0, blank=True, help_text="N3 id_med_document_type")

@staticmethod
def save_plan_performer(tb_data):
Expand Down
11 changes: 10 additions & 1 deletion external_system/admin.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from django.contrib import admin
from .models import FsliRefbookTest, InstrumentalResearchRefbook, BodySiteRefbook, ArchiveMedicalDocuments, TypesMedicalDocuments, CdaFields
from .models import FsliRefbookTest, InstrumentalResearchRefbook, BodySiteRefbook, ArchiveMedicalDocuments, TypesMedicalDocuments, CdaFields, ProfessionsWorkersPositionsRefbook


class ResArchiveMedicalDocuments(admin.ModelAdmin):
Expand Down Expand Up @@ -36,9 +36,18 @@ class ResCdaFields(admin.ModelAdmin):
)


class ResProfessionsWorkersPositionsRefbook(admin.ModelAdmin):
list_display = (
'code',
'title',
)
search_fields = ('title',)


admin.site.register(FsliRefbookTest)
admin.site.register(InstrumentalResearchRefbook)
admin.site.register(BodySiteRefbook)
admin.site.register(ArchiveMedicalDocuments, ResArchiveMedicalDocuments)
admin.site.register(TypesMedicalDocuments)
admin.site.register(CdaFields, ResCdaFields)
admin.site.register(ProfessionsWorkersPositionsRefbook, ResProfessionsWorkersPositionsRefbook)
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from django.core.management.base import BaseCommand
from openpyxl import load_workbook

from external_system.models import ProfessionsWorkersPositionsRefbook


class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('path', type=str)

def handle(self, *args, **kwargs):
"""
:param path - xlsx файл с ФСЛИ со столбцами:
ID,
NAME
"""
fp = kwargs["path"]
self.stdout.write("Path: " + fp)
wb = load_workbook(filename=fp)
ws = wb[wb.sheetnames[0]]
starts = False

id_position, name_position = '', ''
for row in ws.rows:
cells = [str(x.value) for x in row]
if not starts:
if "ID" in cells:
id_position = cells.index("ID")
name_position = cells.index("NAME")
starts = True
else:
r = ProfessionsWorkersPositionsRefbook.objects.filter(code=cells[id_position])
if not r.exists():
ProfessionsWorkersPositionsRefbook(code=cells[id_position], title=cells[name_position]).save()
self.stdout.write('сохранено', cells[name_position])
elif r.exists():
r = r[0]
updated = []
if r.title != cells[name_position]:
r.title = cells[name_position]
updated.append('title')
if updated:
r.save(update_fields=updated)
self.stdout.write('обновлено', cells[name_position])
16 changes: 16 additions & 0 deletions external_system/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,19 @@ def get_cda_params(is_doc_refferal, is_treatment, is_form, is_extract):
result = [{"id": -1, "label": "Пусто"}, *[{"id": x.pk, "label": f"{x.title} - {x.code}"} for x in CdaFields.objects.filter(is_extract=True).order_by("title")]]

return result


class ProfessionsWorkersPositionsRefbook(models.Model):
"""
Профессии рабочих и должностей служащих: 1.2.643.5.1.13.13.99.2.855
"""

code = models.CharField(max_length=20, db_index=True, help_text='Код')
title = models.CharField(max_length=1000, db_index=True, help_text='Полное наименование')

def __str__(self):
return f"{self.code}{self.title}"

class Meta:
verbose_name = "Профессия рабочих и должностей служащих"
verbose_name_plural = "Профессии рабочих и должностей служащих"
9 changes: 7 additions & 2 deletions forms/forms112.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ def form_02(request_data):

if additional_data_from_file:
with open(additional_data_from_file) as json_file:
data = json.loads(json_file)
data = json.loads(json_file.read())
appendix_paragraphs = data.get('appendix_paragraphs', None)
appendix_route_list = data.get('appendix_route_list', None)
appendix_direction_list = data.get('appendix_direction_list', None)
Expand Down Expand Up @@ -479,7 +479,7 @@ def add_route_list(objs, appendix_route_list, patient_data, styles_obj, addition

def add_appendix_direction_list(appendix_direction_list, dir_temp):
direction_data = []
types_direction = {"islab": set(), "isDocrefferal": set(), "isParaclinic": set(), "isGistology": set(), "isHospital": set()}
types_direction = {"islab": set(), "isDocrefferal": set(), "isParaclinic": set(), "isGistology": set(), "isHospital": set(), "isForm": set()}
for d in dir_temp:
iss_obj = Issledovaniya.objects.filter(napravleniye_id=d).first()
if iss_obj.research.is_doc_refferal:
Expand All @@ -490,6 +490,8 @@ def add_appendix_direction_list(appendix_direction_list, dir_temp):
types_direction["isGistology"].add(d)
elif iss_obj.research.is_hospital:
types_direction["isHospital"].add(d)
elif iss_obj.research.is_form:
types_direction["isForm"].add(d)
elif (
not iss_obj.research.is_form
and not iss_obj.research.is_citology
Expand All @@ -511,6 +513,9 @@ def add_appendix_direction_list(appendix_direction_list, dir_temp):
direction_data.extend(list(types_direction["isParaclinic"]))
elif section.get('isHospital'):
direction_data.extend(list(types_direction["isHospital"]))
elif section.get('isForm'):
direction_data.extend(list(types_direction["isForm"]))

return direction_data


Expand Down
27 changes: 27 additions & 0 deletions integration_framework/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import pytz_deprecation_shim as pytz

from appconf.manager import SettingManager
from clients.models import HarmfulFactor
from external_system.models import InstrumentalResearchRefbook
from laboratory import settings
import simplejson as json
Expand Down Expand Up @@ -125,6 +126,28 @@ def get_json_protocol_data(pk, is_paraclinic=False):
data["Состояние код"] = "1"
data["Состояние наименование"] = "Удовлетворительное"

try:
val = data.get("Вредные факторы", None)
if not val:
pass
else:
harm_full_factors = val.split(";")
harm_full_factors = [h.strip() for h in harm_full_factors]
harm_full_factors_object = [{"nsi_id": hf.nsi_id, "nsi_title": hf.description, "code": hf.title} for hf in HarmfulFactor.objects.filter(title__in=harm_full_factors)]
data["Вредные факторы"] = harm_full_factors_object
except Exception:
pass

try:
val = data.get("Группа здоровья", None)
if not val or not isinstance(val, dict):
pass
else:
data["Группа здоровья код"] = val["code"]
data["Группа здоровья наименование"] = val["title"]
except Exception:
pass

for i in REMD_FIELDS_BY_TYPE_DOCUMENT.get(iss.research.generator_name, []):
data[i] = "-"
for r in result_protocol:
Expand All @@ -140,7 +163,11 @@ def get_json_protocol_data(pk, is_paraclinic=False):
data["Состояние наименование"] = "Удовлетворительное"
if not data.get("Дата осмотра"):
data["Дата осмотра"] = iss.medical_examination.strftime("%Y-%m-%d")
if data.get("Дата заключения"):
val = data.get("Дата заключения")
data["Дата заключения"] = normalize_dots_date(val).replace("-", "")
data = add_absent_field(data, iss.research)

direction_params_obj = directions.DirectionParamsResult.objects.filter(napravleniye_id=pk)
direction_params = {}
for dp in direction_params_obj:
Expand Down
11 changes: 8 additions & 3 deletions integration_framework/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,8 @@ def issledovaniye_data_simple(request):
id_med_document_type = ID_MED_DOCUMENT_TYPE_IEMK_N3.get("is_doc_refferal")
if i.research.is_extract:
id_med_document_type = ID_MED_DOCUMENT_TYPE_IEMK_N3.get("is_extract")

if i.research.is_form:
id_med_document_type = i.research.n3_id_med_document_type
return Response(
{
"ok": True,
Expand Down Expand Up @@ -1983,7 +1984,10 @@ def get_cda_data(pk):
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_id = smo_ids.get(insurer_full_code, "")
if p_enp:

if SettingManager.get("eds_control_enp", default='true', default_type='b') and not p_enp:
return {}
else:
return {
"title": n.get_eds_title(),
"generatorName": n.get_eds_generator(),
Expand All @@ -1996,14 +2000,15 @@ def get_cda_data(pk):
"snils": data_individual["snils"],
"name": {"family": ind.family, "name": ind.name, "patronymic": ind.patronymic},
"gender": ind.sex.lower(),
"gender_code": 2 if ind.sex.lower() == "ж" else 1,
"gender_title": "Женский" if ind.sex.lower() == "ж" else "Мужской",
"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},
"address": data_individual['main_address'],
},
"organization": data["organization"],
},
}
return {}


@api_view(["POST"])
Expand Down
1 change: 1 addition & 0 deletions laboratory/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,7 @@ def __getitem__(self, item):
TYPE_COMPANY_SET_DIRECTION_PDF = ""
CPP_SEND_PROTOCOL_ID = -1
CPP_TEMPLATE_XML_DIRECTORY = ""
CDA_TEMPLATE_XML_DIRECTORY = ""

try:
from laboratory.local_settings import * # noqa: F403,F401
Expand Down
4 changes: 4 additions & 0 deletions utils/nsi_directories.py
Original file line number Diff line number Diff line change
Expand Up @@ -966,4 +966,8 @@
'Выдана справка о необходимости дополнительного медицинского обследования': '20487f06-1140-4659-aa61-7fa8a93eeaa7',
},
},
'1.2.643.5.1.13.13.99.2.725': {
'title': 'Результат медицинского осмотра (НСИ)',
'values': {'32': 'Медицинские противопоказания к работе не выявлены', '31': 'Медицинские противопоказания к работе выявлены'},
},
}
9 changes: 8 additions & 1 deletion xml_generate/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from clients.models import HarmfulFactor
from directions.models import Issledovaniya, DirectionDocument
from laboratory.settings import BASE_DIR, CPP_TEMPLATE_XML_DIRECTORY, MEDIA_ROOT
from laboratory.settings import BASE_DIR, CPP_TEMPLATE_XML_DIRECTORY, MEDIA_ROOT, CDA_TEMPLATE_XML_DIRECTORY
import shutil
from datetime import datetime

Expand Down Expand Up @@ -91,3 +91,10 @@ def normilize_result_data(results):
dict_result["Вредные факторы"] = [str(i.cpp_key) for i in hf]
dict_result["uuid"] = str(uuid.uuid4())
return dict_result


def gen_result_cda_files(template_file_name, data):
file_loader = FileSystemLoader(os.path.join(BASE_DIR, 'xml_generate', CDA_TEMPLATE_XML_DIRECTORY))
env = Environment(loader=file_loader, trim_blocks=True, lstrip_blocks=True)
tm = env.get_template(template_file_name)
return tm.render(data)

0 comments on commit 82ad4c3

Please sign in to comment.