Skip to content

Commit

Permalink
Auto create case (#3238)
Browse files Browse the repository at this point in the history
* проверка созданного случая

* автосоздание направлений и случая

* .

* print set document for many people

* print set document for many people

* Update utils/xh.py

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Update utils/xh.py

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Update directions/models.py

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Update directions/models.py

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Update api/views.py

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Update api/sql_func.py

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* print set document for many people

* fix

* Update directions/models.py

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Update api/views.py

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Update api/views.py

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Update api/views.py

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* планируемая дата начала оказания услуг

* планируемая дата -fix

* fix: price_name =None

* hash to file name - store in cashe

* hash to file name - store in cashe

* fix import pep

* Update utils/xh.py

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Update directions/views.py

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Update directions/views.py

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Update directions/views.py

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* fix

* настройки хэш

* pep

* add slot_fact_id

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
  • Loading branch information
urchinpro and github-actions[bot] authored Nov 21, 2023
1 parent 17ad7cf commit 35cfdbe
Show file tree
Hide file tree
Showing 11 changed files with 237 additions and 9 deletions.
1 change: 1 addition & 0 deletions api/directions/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ def directions_generate(request):
price_category=p.get("priceCategory", -1),
case_id=p.get("caseId", -2),
case_by_direction=p.get("caseByDirection", False),
plan_start_date=p.get("planStartDate", None),
slot_fact_id=p.get("slotFactId", None),
)
if type_generate == "calculate-cost":
Expand Down
22 changes: 22 additions & 0 deletions api/sql_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -404,3 +404,25 @@ def search_text_stationar(date_create_start, date_create_end, final_text):

rows = namedtuplefetchall(cursor)
return rows


def search_case_by_card_date(card_id, plan_date_start_case, research_case_id, limit):
with connection.cursor() as cursor:
cursor.execute(
"""
SELECT
directions_napravleniya.id as case_direction_number,
directions_issledovaniya.id as case_issledovaniye_number
FROM directions_issledovaniya
LEFT JOIN directions_napravleniya ON directions_napravleniya.id = directions_issledovaniya.napravleniye_id
WHERE
directions_issledovaniya.research_id = %(research_case_id)s
and directions_issledovaniya.plan_start_date AT TIME ZONE %(tz)s = %(plan_date_start_case)s
and directions_napravleniya.client_id = %(card_id)s
LIMIT %(limit)s
""",
params={'card_id': card_id, 'plan_date_start_case': plan_date_start_case, 'research_case_id': research_case_id, 'tz': TIME_ZONE, 'limit': limit},
)

rows = namedtuplefetchall(cursor)
return rows
38 changes: 36 additions & 2 deletions api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import pytz_deprecation_shim as pytz

from api.models import ManageDoctorProfileAnalyzer, Analyzer
from directions.views import create_case_by_cards
from directory.models import Researches, SetResearch, SetOrderResearch, PatientControlParam
from doctor_schedule.models import ScheduleResource
from ecp_integration.integration import get_reserves_ecp, get_slot_ecp
Expand All @@ -24,6 +25,7 @@
TITLE_REPORT_FILTER_HAS_ALL_FIN_SOURCE,
STATISTIC_TYPE_DEPARTMENT,
USE_TFOMS_DISTRICT,
TYPE_COMPANY_SET_DIRECTION_PDF,
)
from utils.response import status_response

Expand Down Expand Up @@ -76,12 +78,13 @@
from utils.common import non_selected_visible_type
from utils.dates import try_parse_range, try_strptime
from utils.nsi_directories import NSI
from utils.xh import get_all_hospitals
from utils.xh import get_all_hospitals, simple_join_two_pdf_files, simple_save_pdf_file, correspondence_set_file_hash
from .dicom import search_dicom_study
from .directions.sql_func import get_lab_podr
from .sql_func import users_by_group, users_all, get_diagnoses, get_resource_researches, search_data_by_param, search_text_stationar
from laboratory.settings import URL_RMIS_AUTH, URL_ELN_MADE, URL_SCHEDULE
import urllib.parse
from django.utils.module_loading import import_string

logger = logging.getLogger("API")

Expand Down Expand Up @@ -3305,7 +3308,38 @@ def get_examination_list(request):
@login_required
@group_required("Конструктор: Настройка организации")
def print_medical_examination_data(request):
return status_response(True)
request_data = json.loads(request.body)
cards = request_data.get("cards")
card_directions = create_case_by_cards(cards)
files_data = []
if TYPE_COMPANY_SET_DIRECTION_PDF:
additional_page = import_string('forms.forms112.' + TYPE_COMPANY_SET_DIRECTION_PDF.split(".")[0])
for card, directions_data in card_directions.items():
if len(directions_data) > 1:
directions_data = [str(i) for i in directions_data]
napr_id = ", ".join(directions_data)
else:
napr_id = directions_data[0]
napr_id = f"[{napr_id}]"
fc = additional_page(
request_data={
**dict(request.GET.items()),
"user": request.user,
"card_pk": card,
"hospital": request.user.doctorprofile.get_hospital() if hasattr(request.user, "doctorprofile") else Hospitals.get_default_hospital(),
"type_additional_pdf": TYPE_COMPANY_SET_DIRECTION_PDF.split(".")[1],
"fin_title": "профосмотр",
"napr_id": napr_id,
}
)
saved_file_pdf = simple_save_pdf_file(fc)
files_data.append(saved_file_pdf)

buffer = simple_join_two_pdf_files(files_data)

id_file = simple_save_pdf_file(buffer)
hash_file = correspondence_set_file_hash(id_file)
return JsonResponse({"id": hash_file})


@login_required
Expand Down
2 changes: 2 additions & 0 deletions directions/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1298,6 +1298,7 @@ def gen_napravleniya_by_issledovaniya(
price_name=None,
case_id=-2,
case_by_direction=False,
plan_start_date=None,
slot_fact_id=None,
):
result = {"r": False, "list_id": [], "list_stationar_id": [], "messageLimit": ""}
Expand Down Expand Up @@ -2283,6 +2284,7 @@ class Issledovaniya(models.Model):
DoctorProfile, null=True, blank=True, related_name="doc_add_additional", db_index=True, help_text='Профиль-добавил исполнитель дополнительные услуги', on_delete=models.SET_NULL
)
external_add_order = models.ForeignKey(ExternalAdditionalOrder, db_index=True, blank=True, null=True, default=None, help_text="Внешний заказ", on_delete=models.SET_NULL)
plan_start_date = models.DateTimeField(null=True, blank=True, db_index=True, help_text='Планируемое время начала услуги')

@property
def time_save_local(self):
Expand Down
15 changes: 15 additions & 0 deletions directions/sql_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,18 @@ def check_create_direction_patient_by_research(client_id, researches, months_ago
)
rows = namedtuplefetchall(cursor)
return rows


def get_researches_by_number_directions(direction_numbers):
with connection.cursor() as cursor:
cursor.execute(
"""
SELECT
directions_issledovaniya.research_id
FROM directions_issledovaniya
WHERE directions_issledovaniya.napravleniye_id in %(direction_numbers)s
""",
params={'direction_numbers': direction_numbers},
)
rows = namedtuplefetchall(cursor)
return rows
95 changes: 93 additions & 2 deletions directions/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,19 @@
from transliterate import translit

import directory.models as directory
from directions.sql_func import get_researches_by_number_directions
from users.models import DoctorProfile
from api.sql_func import search_case_by_card_date
from hospitals.models import Hospitals
import slog.models as slog
from appconf.manager import SettingManager
from directions.models import Napravleniya, Issledovaniya, TubesRegistration, DirectionParamsResult
from directions.models import Napravleniya, Issledovaniya, TubesRegistration, DirectionParamsResult, IstochnikiFinansirovaniya
from laboratory.decorators import logged_in_or_token
from laboratory.settings import FONTS_FOLDER, PRINT_ADDITIONAL_PAGE_DIRECTION_FIN_SOURCE, PRINT_APPENDIX_PAGE_DIRECTION
from laboratory.utils import strtime, strdate
from podrazdeleniya.models import Podrazdeleniya
from utils import xh
from utils.dates import try_parse_range
from utils.dates import try_parse_range, normalize_dots_date
from django.utils.module_loading import import_string

from utils.matrix import transpose
Expand Down Expand Up @@ -1040,3 +1043,91 @@ def px(x=0.0):
def pxr(x=0.0):
x *= mm
return w - x


def create_case_by_cards(cards):
research_case = directory.Researches.objects.filter(is_case=True, hide=False).first()
doc = DoctorProfile.objects.filter(fio='Системный Пользователь', is_system_user=True).first()
card_directions = {}
number_directons = None
for card in cards:
card_id = card.get("card_id")
researches = card.get("research")
plan_start_date_case = normalize_dots_date(card.get("date"))
plan_start_date_case = f"{plan_start_date_case} 00:00:00"
result_search_case = search_case_by_card_date(card_id, plan_start_date_case, research_case.pk, 1)
case_issledovaniye_number, case_direction_number = None, None
for i in result_search_case:
case_issledovaniye_number = i.case_issledovaniye_number
case_direction_number = i.case_direction_number
break
financing_source = IstochnikiFinansirovaniya.objects.filter(title__in=["Профосмотр", "Юрлицо"]).first()

if case_issledovaniye_number:
number_directons = Napravleniya.objects.values_list("id", flat=True).filter(parent_case_id=case_issledovaniye_number)
researches_sql = get_researches_by_number_directions(tuple(number_directons))
current_researches_case = set([i.research_id for i in researches_sql])
api_researches = set(researches)
api_researches -= current_researches_case
researches = list(api_researches)
result = Napravleniya.gen_napravleniya_by_issledovaniya(
card_id,
"",
financing_source.pk,
"",
None,
doc,
{-1: researches},
{},
False,
{},
vich_code="",
count=1,
discount=0,
rmis_slot=None,
price_name=None,
case_id=case_direction_number,
case_by_direction=True,
plan_start_date=plan_start_date_case,
)
else:
napravleniye_case = Napravleniya.gen_napravleniye(
card_id,
doc,
financing_source,
"",
"",
doc,
-1,
doc,
)

issledovaniye_case = Issledovaniya(napravleniye=napravleniye_case, research=research_case, deferred=False, plan_start_date=plan_start_date_case)
issledovaniye_case.save()
result = Napravleniya.gen_napravleniya_by_issledovaniya(
card_id,
"",
financing_source.pk,
"",
None,
doc,
{-1: researches},
{},
False,
{},
vich_code="",
count=1,
discount=0,
rmis_slot=None,
price_name=None,
case_id=napravleniye_case.pk,
case_by_direction=True,
plan_start_date=plan_start_date_case,
)
if number_directons:
number_directons = [i for i in number_directons]
else:
number_directons = []
number_directons.extend(result.get("list_id"))
card_directions[card_id] = list(set(number_directons))
return card_directions
21 changes: 19 additions & 2 deletions forms/forms112.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@
from directions.models import Napravleniya, Issledovaniya
from hospitals.models import Hospitals
from laboratory.settings import FONTS_FOLDER, BASE_DIR
from utils.xh import save_tmp_file
from utils.xh import save_tmp_file, correspondence_get_file_hash
from directions.views import gen_pdf_dir as f_print_direction
from django.http import HttpRequest
from django.utils.module_loading import import_string
from pdfrw import PdfReader, PdfWriter


def form_01(request_data):
Expand Down Expand Up @@ -342,7 +343,6 @@ def form_02(request_data):


def join_two_pdf_data(func_name, http_params, user_data, buffer, ind_card, type="post"):

if type == "get":
fc = func_name(request_data=http_params)
is_get = False
Expand Down Expand Up @@ -512,3 +512,20 @@ def add_appendix_direction_list(appendix_direction_list, dir_temp):
elif section.get('isHospital'):
direction_data.extend(list(types_direction["isHospital"]))
return direction_data


def form_03(request_data):
id_file = request_data.get("id").replace('"', "")
file_data = correspondence_get_file_hash(id_file)
if file_data:
dir_param = SettingManager.get("dir_param", default='/tmp', default_type='s')
file_dir = os.path.join(dir_param, file_data)
pdf_all = BytesIO()
inputs = [file_dir]
writer = PdfWriter()
for inpfn in inputs:
writer.addpages(PdfReader(inpfn).pages)
writer.write(pdf_all)
pdf_out = pdf_all.getvalue()
os.remove(file_dir)
return pdf_out
7 changes: 6 additions & 1 deletion l2-frontend/src/construct/ConstructCompany.vue
Original file line number Diff line number Diff line change
Expand Up @@ -608,10 +608,15 @@ export default {
const selectCard = this.selectedCards;
return selectCard.includes(card);
}).map((exam) => ({ card_id: exam.card_id, date: exam.date, research: exam.research_id }));
await this.$api('print-medical-examination-data', {
await this.$store.dispatch(actions.INC_LOADING);
const result = await this.$api('print-medical-examination-data', {
cards: printData,
exclude: this.excludedResearches,
});
await this.$store.dispatch(actions.DEC_LOADING);
if (result.id) {
window.open(`/forms/pdf?type=112.03&id=${encodeURIComponent(JSON.stringify(result.id))}`, '_blank');
}
},
},
};
Expand Down
1 change: 1 addition & 0 deletions laboratory/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,7 @@ def __getitem__(self, item):
QR_CODE_ANKETA = ""
RESULT_LABORATORY_FORM = ""
SELF_WATERMARKS = ""
TYPE_COMPANY_SET_DIRECTION_PDF = ""

try:
from laboratory.local_settings import * # noqa: F403,F401
Expand Down
2 changes: 0 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,8 @@ pdf2docx = "^0.5.6"
pyotp = "^2.8.0"
qrcode = "^7.4.2"
hl7apy = "^1.3.4"

[tool.poetry.extras]
caching = ["psycopg2"]

[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
42 changes: 42 additions & 0 deletions utils/xh.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@
from appconf.manager import SettingManager
from laboratory.settings import QRCODE_OFFSET_SIZE, LEFT_QRCODE_OFFSET_SIZE
from utils.flowable import QrCodeSite
import uuid
import os.path
from io import BytesIO
from pdfrw import PdfReader, PdfWriter
from django.core.cache import cache
import hashlib


def fix(s: str):
Expand Down Expand Up @@ -104,3 +110,39 @@ def show_qr_lk_address(fwb, leftnone=False):
def replace_values(key):
replace_data = {"code": "Код МКБ10", "title": "", "id": ""}
return replace_data.get(key, "")


def simple_join_two_pdf_files(inputs):
pdf_all = BytesIO()
writer = PdfWriter()
dir_param = SettingManager.get("dir_param", default='/tmp', default_type='s')
for inpfn in inputs:
writer.addpages(PdfReader(os.path.join(dir_param, inpfn)).pages)
writer.write(pdf_all)
pdf_out = pdf_all.getvalue()
pdf_all.close()

for i in inputs:
os.remove(os.path.join(dir_param, i))
return pdf_out


def simple_save_pdf_file(fc):
fc_buf = BytesIO()
fc_buf.write(fc)
fc_buf.seek(0)
dir_param = SettingManager.get("dir_param", default='/tmp', default_type='s')
name = str(uuid.uuid4()) + '_buffer.pdf'
file_buffer1 = os.path.join(dir_param, name)
save_tmp_file(fc_buf, filename=file_buffer1)
return name


def correspondence_set_file_hash(title_name):
k = hashlib.sha1(title_name.encode('utf-8')).hexdigest()
cache.set(k, title_name, 60 * 1)
return k


def correspondence_get_file_hash(k):
return cache.get(k)

0 comments on commit 35cfdbe

Please sign in to comment.