Skip to content

Commit

Permalink
Merge pull request #3239 from mikhailprivalov/jsonForZip_pc
Browse files Browse the repository at this point in the history
Json for zip pc
  • Loading branch information
urchinpro authored Dec 8, 2023
2 parents af92213 + bbda8c0 commit 1de0ae7
Show file tree
Hide file tree
Showing 26 changed files with 1,121 additions and 445 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -242,3 +242,4 @@ external_system/settings/phones_org.json
!/forms/additional_pages/default.json
/ftp_orders/hl7_rule
!/ftp_orders/hl7_rule/default.json
/xml_generate/templates/
33 changes: 31 additions & 2 deletions api/directions/views.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import base64
import math
import os
import uuid
from typing import Optional

from django.core.paginator import Paginator
from cda.integration import cdator_gen_xml, render_cda
from contracts.models import PriceCategory, PriceCoast
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 integration_framework.common_func import directions_pdf_result
from l2vi.integration import gen_cda_xml, send_cda_xml
import collections

from integration_framework.views import get_cda_data
from results.prepare_data import fields_result_only_title_fields
from utils.response import status_response
from hospitals.models import Hospitals, HospitalParams
import operator
Expand Down Expand Up @@ -82,6 +84,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 .sql_func import (
get_history_dir,
get_confirm_direction,
Expand Down Expand Up @@ -1536,7 +1539,6 @@ def directions_paraclinic_form(request):
card_documents = d.client.get_card_documents(check_has_type=['СНИЛС'])

has_snils = bool(card_documents)

response["patient"] = {
"fio_age": d.client.individual.fio(full=True),
"fio": d.client.individual.fio(),
Expand Down Expand Up @@ -2406,6 +2408,33 @@ def directions_paraclinic_result(request):
if child_direction.parent:
Napravleniya.objects.filter(pk=child_iss[0]).update(parent=parent_iss, cancel=False)

if iss.research.cpp_template_files:
patient = iss.napravleniye.client.get_data_individual()
company = iss.napravleniye.client.work_place_db
price = PriceName.get_company_price_by_date(company.pk, current_time(only_date=True), current_time(only_date=True))
patient['uuid'] = str(uuid.uuid4())

data = {
"company": Company.as_json(company),
"contract": PriceName.as_json(price),
"patient": patient
}
field_titles = [
"СНИЛС",
"Дата осмотра",
"Результат медицинского осмотра",
"Группы риска",
"Группы риска по SCORE",
"Дата присвоения группы здоровья",
"Вредные факторы",
"Группа здоровья",
"Номер справки",
"Дата выдачи справки",
]
result_protocol = fields_result_only_title_fields(iss, field_titles)
data["result"] = result_protocol
gen_resul_cpp_file(iss, iss.research.cpp_template_files, data)

Log(key=pk, type=14, body="", user=request.user.doctorprofile).save()
forbidden_edit = forbidden_edit_dir(iss.napravleniye_id)
response["forbidden_edit"] = forbidden_edit or more_forbidden
Expand Down
Empty file added api/statistic/__init__.py
Empty file.
4 changes: 3 additions & 1 deletion api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2204,6 +2204,7 @@ def organization_data_update(request):
"resultPullFtpServerUrl": None,
"hl7SenderApplication": None,
"hl7ReceiverAapplication": None,
"isAutotransfer": False,
},
)

Expand All @@ -2227,7 +2228,7 @@ def organization_data_update(request):
result_pull_by_numbers: Optional[str] = data[17] or None
hl7_sender_application: Optional[str] = data[18] or None
hl7_receiver_appplication: Optional[str] = data[19] or None
is_auto_transfer = data[20]
is_auto_transfer = data[20] if data[20] else False

if not title:
return status_response(False, "Название не может быть пустым")
Expand Down Expand Up @@ -2955,6 +2956,7 @@ def update_company(request):
company_data.kpp = request_data["kpp"]
company_data.bik = request_data["bik"]
company_data.contract_id = request_data.get("contractId") or None
company_data.cpp_send = request_data.get("cppSend", False)
company_data.save()
new_company_data = Company.as_json(company_data)
Log.log(
Expand Down
30 changes: 17 additions & 13 deletions contracts/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ def as_json(price):
"end": price.date_end,
"company": company_id,
"companyTitle": company_title,
"symbolCode": price.symbol_code,
"uuid": str(price.uuid),
}
return json_data
Expand Down Expand Up @@ -161,6 +162,7 @@ class Company(models.Model):
contract = models.ForeignKey(Contract, blank=True, null=True, db_index=True, on_delete=models.CASCADE)
email = models.CharField(max_length=128, blank=True, default="", help_text="email")
uuid = models.UUIDField(default=uuid.uuid4, editable=False, help_text="UUID, генерируется автоматически", db_index=True)
cpp_send = models.BooleanField(default=False, help_text='отправлять в ЦПП', db_index=True)

def __str__(self):
return "{}".format(self.title)
Expand Down Expand Up @@ -201,7 +203,8 @@ def as_json(company):
"kpp": company.kpp,
"bik": company.bik,
"contractId": company.contract_id,
"uuid": company.uuid,
"uuid": str(company.uuid),
"cppSend": company.cpp_send,
}
return json_data

Expand All @@ -210,6 +213,7 @@ class CompanyDepartment(models.Model):
title = models.CharField(max_length=511, help_text="Наименование отдела", db_index=True)
hide = models.BooleanField(default=False, help_text="Скрыть", db_index=True)
company = models.ForeignKey(Company, blank=True, null=True, db_index=True, on_delete=models.CASCADE)
uuid = models.UUIDField(default=uuid.uuid4, editable=False, help_text="UUID, генерируется автоматически", db_index=True)

def __str__(self):
return "{}".format(self.title)
Expand Down Expand Up @@ -246,7 +250,6 @@ def get_by_date(date: str, company_id: int, month: bool = False) -> list[dict]:
else:
date_start = date
date_end = date
result = []
last_date_year = f"{current_year()}-12-31"
examination_data = get_examination_data(company_id, date_start, date_end, last_date_year)
male = CONTROL_AGE_MEDEXAM.get("м")
Expand Down Expand Up @@ -287,17 +290,18 @@ def get_by_date(date: str, company_id: int, month: bool = False) -> list[dict]:
tmp_patient["research_titles"].append(f"{i.research_title}; ")
patient_result[i.card_id] = tmp_patient.copy()

result = [
{
"card_id": k,
"fio": v["fio"],
"harmful_factors": list(set(v["harmful_factors"])),
"research_id": list(set(v["research_id"])),
"research_titles": list(set(v["research_titles"])),
"date": v["date"],
}
for k, v in patient_result.items()
]
result = [
{
"card_id": k,
"fio": v["fio"],
"harmful_factors": list(set(v["harmful_factors"])),
"research_id": list(set(v["research_id"])),
"research_titles": list(set(v["research_titles"])),
"date": v["date"],
"cppSendStatus": "",
}
for k, v in patient_result.items()
]

if month:
result = sorted(result, key=lambda d: d["date"])
Expand Down
4 changes: 4 additions & 0 deletions directions/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -557,6 +557,8 @@ class Napravleniya(models.Model):
)
time_send_hl7 = models.DateTimeField(help_text='Дата и время отправки заказа', db_index=True, blank=True, default=None, null=True)
price_name = models.ForeignKey(contracts.PriceName, default=None, blank=True, null=True, on_delete=models.PROTECT, help_text='Прайс для направления')
cpp_upload_id = models.CharField(max_length=128, default=None, blank=True, null=True, db_index=True, help_text='Id-загрузки ЦПП')
need_resend_cpp = models.BooleanField(default=False, blank=True, help_text='Требуется отправка в ЦПП')

def sync_confirmed_fields(self):
has_confirmed_iss = Issledovaniya.objects.filter(napravleniye=self, time_confirmation__isnull=False).exists()
Expand Down Expand Up @@ -2029,9 +2031,11 @@ def get_direction_file_path(instance: 'DirectionDocument', filename):
class DirectionDocument(models.Model):
PDF = 'pdf'
CDA = 'cda'
CPP = 'cpp'
FILE_TYPES = (
(PDF, PDF),
(CDA, CDA),
(CPP, CPP),
)

direction = models.ForeignKey(Napravleniya, on_delete=models.CASCADE, db_index=True, verbose_name="Направление")
Expand Down
1 change: 1 addition & 0 deletions directory/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,7 @@ class Researches(models.Model):
auto_register_on_rmis_location = models.CharField(max_length=128, db_index=True, blank=True, default="", null=True, help_text="Автозапись пациента на ближайший свободный слот")
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: 'название шаблона'}")

@staticmethod
def save_plan_performer(tb_data):
Expand Down
2 changes: 1 addition & 1 deletion 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.load(json_file)
data = json.loads(json_file)
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
4 changes: 4 additions & 0 deletions forms/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,3 +246,7 @@ def get_epid_data(directions, with_confirm):
temp_data['master_field_results'].append({'master_field_title': i.master_field_title, 'master_value': master_value})

return data


def generate_xml(request):
return
Empty file.
Empty file.
23 changes: 23 additions & 0 deletions integration_framework/researches/sql_func.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from django.db import connection
from laboratory.settings import TIME_ZONE
from utils.db import namedtuplefetchall


def get_confirm_research(research_id, date_start, date_end):
with connection.cursor() as cursor:
cursor.execute(
"""
SELECT research_id, doc_confirmation_id,
hh.title as title_mo,
hh.oid as oid_mo
FROM directions_issledovaniya
INNER JOIN users_doctorprofile doctor
ON directions_issledovaniya.doc_confirmation_id = doctor.id
LEFT JOIN hospitals_hospitals hh on doctor.hospital_id = hh.id
WHERE time_confirmation AT TIME ZONE %(tz)s BETWEEN %(date_start)s and %(date_end)s and research_id=%(research_id)s
""",
params={"research_id": research_id, "date_start": date_start, "date_end": date_end, 'tz': TIME_ZONE},
)
rows = namedtuplefetchall(cursor)
return rows
6 changes: 6 additions & 0 deletions integration_framework/researches/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.urls import path
from . import views

urlpatterns = [
path('get-confirm-sign-research', views.get_confirm_sign_research),
]
26 changes: 26 additions & 0 deletions integration_framework/researches/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import simplejson as json
from rest_framework.response import Response
from integration_framework.researches.sql_func import get_confirm_research
from laboratory.utils import current_time
from rest_framework.decorators import api_view


@api_view()
def get_confirm_sign_research(request):
if not hasattr(request.user, "hospitals"):
return Response({"ok": False, "message": "Некорректный auth токен"})

body = json.loads(request.body)
research_id = body.get("researchId")
date_start = body.get("dateStart", current_time(only_date=True))
date_start = f"{date_start} 00:00:01"
date_end = body.get("dateEnd", current_time(only_date=True))
date_end = f"{date_end} 23:59:59"
result = get_confirm_research(research_id, date_start, date_end)
count_mo = {}
for i in result:
if not count_mo.get(i.title_mo):
count_mo[i.title_mo] = 1
else:
count_mo[i.title_mo] += 1
return Response(count_mo)
21 changes: 21 additions & 0 deletions integration_framework/sql_if.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.db import connection
from utils.db import namedtuplefetchall

from laboratory.settings import TIME_ZONE

Expand Down Expand Up @@ -98,6 +99,26 @@ def direction_resend_amd(limit):
return row


def direction_resend_cpp(limit):
"""
Вернуть:
Направления, в к-рых все исследования подтверждены, и подтверждены после определенной даты
в SQL:
"""

with connection.cursor() as cursor:
cursor.execute(
"""
SELECT id FROM public.directions_napravleniya
WHERE need_resend_cpp = True
ORDER BY id DESC LIMIT %(limit)s """,
params={'limit': limit},
)

rows = namedtuplefetchall(cursor)
return rows


def direction_resend_n3(limit):
"""
Вернуть:
Expand Down
2 changes: 2 additions & 0 deletions integration_framework/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
urlpatterns = [
path('result/next', views.next_result_direction),
path('result/amd', views.get_dir_amd),
path('result/cpp', views.get_dir_cpp),
path('result/n3', views.get_dir_n3),
path('result/resend-l2', views.resend_dir_l2),
path('result/resend-crie', views.resend_dir_crie),
path('result/sendamd', views.result_amd_send),
path('result/sendcpp', views.result_cpp_send),
path('result/pdf', views.get_pdf_result),
path('external-result/pdf', views.external_get_pdf_result),
path('direction/pdf', views.get_pdf_direction),
Expand Down
43 changes: 43 additions & 0 deletions integration_framework/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import base64
import hashlib
import os
import html
import zlib
Expand Down Expand Up @@ -154,6 +155,34 @@ def get_dir_amd(request):
return Response(result)


@api_view()
def get_dir_cpp(request):
next_n = int(request.GET.get("nextN", 5))
direction_pk = request.GET.get("idDirection", None)
dirs = None
if not direction_pk:
dirs = sql_if.direction_resend_cpp(next_n)
result = {"ok": False, "next": []}
data_direction = []
if dirs:
result = {"ok": True}
dirs_data = [i.id for i in dirs]
else:
dirs_data = [i for i in json.loads(direction_pk)]
direction_document = DirectionDocument.objects.filter(direction__in=dirs_data, file_type="cpp")
for d in direction_document:
with open(d.file.name, "rb") as f:
digest = hashlib.file_digest(f, "md5")
md5_file = digest.hexdigest()
f.close()
zip_file = d.file.open(mode='rb')
bs64_zip = base64.b64encode(zip_file.read())
md5_checksum_file = base64.b64encode(md5_file.encode('utf-8'))
data_direction.append({"directionNumbrer": d.direction_id, "bs64Zip": bs64_zip, "md5file": md5_checksum_file})
result["next"] = data_direction
return Response(result)


@api_view()
def get_dir_n3(request):
next_n = int(request.GET.get("nextN", 5))
Expand Down Expand Up @@ -206,6 +235,20 @@ def result_amd_send(request):
return Response(resp)


@api_view()
def result_cpp_send(request):
result = json.loads(request.GET.get("result"))
resp = {"ok": False}
if result["send"]:
for i in result["send"]:
data_amd = i.split(":")
dir_pk = int(data_amd[0])
cpp_upload_id = data_amd[1]
directions.Napravleniya.objects.filter(pk=dir_pk).update(need_resend_cpp=False, cpp_upload_id=cpp_upload_id)
resp = {"ok": True}
return Response(resp)


@api_view()
def direction_data(request):
pk = request.GET.get("pk")
Expand Down
Loading

0 comments on commit 1de0ae7

Please sign in to comment.