Skip to content

Commit

Permalink
Merge pull request #4426 from mikhailprivalov/toGetherStatisticPatter…
Browse files Browse the repository at this point in the history
…n_AnyRowsForOneHosp

save statistic-model to xlsx
  • Loading branch information
Wellheor1 authored Oct 28, 2024
2 parents 094c7d3 + 079bc17 commit 3828ef3
Show file tree
Hide file tree
Showing 7 changed files with 177 additions and 92 deletions.
21 changes: 12 additions & 9 deletions api/reports/sql_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,20 +86,23 @@ def get_field_results(directions, input_field, fraction_field):
cursor.execute(
"""
SELECT
dn.id as direction_id,
dn.id as protocol_direction_id,
to_char(directions_issledovaniya.time_confirmation AT TIME ZONE %(tz)s, 'DD.MM.YYYY HH24:MI') AS time_confirm,
dp.value as input_value,
dpif.title as field_title,
dpif.statistic_pattern_param_id as input_static_param,
dpif.statistic_pattern_param_id as input_static_param_id,
dr.value as fraction_value,
df.statistic_pattern_param_id as fraction_static_param,
df.statistic_pattern_param_id as fraction_static_param_id,
dn.parent_id as parrent_iss,
pd.napravleniye_id as hosp_direction,
ci.family,
ci.name,
ci.patronymic,
to_char(ci.birthday, 'DD.MM.YYYY') as born,
to_char(EXTRACT(YEAR from age(directions_issledovaniya.time_confirmation, ci.birthday)), '999') as ind_age
pd.napravleniye_id as hospital_direction,
ci.sex,
ci.family as patient_family,
ci.name as patient_name,
ci.patronymic as patient_patronymic,
to_char(ci.birthday, 'DD.MM.YYYY') as patient_birthday,
to_char(EXTRACT(YEAR from age(directions_issledovaniya.time_confirmation, ci.birthday)), '999') as patient_age,
cc.main_address as patient_main_address,
cc.fact_address as patient_fact_address
FROM directions_issledovaniya
LEFT JOIN directions_napravleniya dn on directions_issledovaniya.napravleniye_id = dn.id
Expand Down
80 changes: 0 additions & 80 deletions api/reports/statistic_model/base_columns.py

This file was deleted.

10 changes: 10 additions & 0 deletions api/reports/statistic_model/save_file_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from statistic.report import base_data
from statistic.statistic_func import initial_work_book, save_file_disk


def data_model_save_to_file(final_result, head_data, sheet_name, permanent_head_data, custom_fields):
wb, ws = initial_work_book(sheet_name)
ws = base_data.fill_default_base(ws, head_data)
ws = base_data.fill_xls_model_statistic_data(ws, final_result, permanent_head_data, custom_fields)
file_dir = save_file_disk(wb)
return file_dir
Empty file.
101 changes: 99 additions & 2 deletions api/reports/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
from api.reports import sql_func
from api.reports import handle_func
from api.reports.sql_func import get_pair_direction_iss, get_simple_directions_for_hosp_stationar, get_field_results
from directory.models import StatisticPatternParamSet, ParaclinicInputField, Fractions
from api.reports.statistic_model.save_file_model import data_model_save_to_file
from directory.models import StatisticPatternParamSet, ParaclinicInputField, Fractions, PatternParam, PatternParamTogether
from laboratory.settings import SEARCH_PAGE_STATISTIC_PARAMS
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
Expand Down Expand Up @@ -91,5 +92,101 @@ def xlsx_model(request):
if len(laboratory_fractions_statistic_param) == 0:
laboratory_fractions_statistic_param = [-1]
result_directions = get_field_results(tuple(res_dir), tuple(input_field_statistic_param), tuple(laboratory_fractions_statistic_param))
pattern_params = PatternParam.objects.filter(id__in=list(statistic_param_data.keys())).order_by("order").values("pk", "title")
order_custom_field = {i.get('pk'): i.get('title') for i in pattern_params}
together_params = PatternParamTogether.get_together_param(list(order_custom_field.keys()))
together_params_by_group = together_params.get("by_group")
together_params_by_params = together_params.get("by_param")
intermediate_structure_result = {}
for i in result_directions:
if not intermediate_structure_result.get(i.hospital_direction):
intermediate_structure_result[i.hospital_direction] = {
"patient_fio": f"{i.patient_family} {i.patient_name} {i.patient_patronymic}",
"sex": i.sex,
"birthday": i.patient_birthday,
"age": i.patient_age,
"address": i.patient_fact_address if i.patient_fact_address else i.patient_main_address,
"protocol_directions": {},
}
if not intermediate_structure_result[i.hospital_direction]["protocol_directions"].get(i.protocol_direction_id):
intermediate_structure_result[i.hospital_direction]["protocol_directions"][i.protocol_direction_id] = []
intermediate_structure_result[i.hospital_direction]["protocol_directions"][i.protocol_direction_id].append(
{
"input_static_param_id": i.input_static_param_id,
"field_title": i.field_title,
"input_value": i.input_value,
"fraction_static_param_id": i.fraction_static_param_id,
"fraction_value": i.fraction_value,
"time_confirm": i.time_confirm,
}
)

return JsonResponse({"results": "file-xls-model", "link": "open-xls", "result": result_directions})
custom_fields = {v: "" for k, v in order_custom_field.items()}

final_result = []
for k, v in intermediate_structure_result.items():
field_data = [custom_fields.copy()]
prev_direction_num = None
for direction_num, data_direction in v.get("protocol_directions").items():
for current_data in data_direction:
group_id_block_param = None
value_field = None
title_field = None
if current_data.get("input_value"):
title_field = order_custom_field.get(current_data["input_static_param_id"])
group_id_block_param = together_params_by_params.get(current_data["input_static_param_id"])
value_field = current_data.get("input_value")
elif current_data.get("fraction_value"):
title_field = order_custom_field.get(current_data["fraction_static_param_id"])
group_id_block_param = together_params_by_params.get(current_data["fraction_static_param_id"])
value_field = current_data.gey("fraction_value")
param_ids_in_group_block = []
if group_id_block_param:
param_ids_in_group_block = together_params_by_group.get(group_id_block_param)
used_block_in_order_custom_field = []
if len(param_ids_in_group_block) > 0:
used_block_in_order_custom_field = [field_v for field_k, field_v in order_custom_field.items() if field_k in param_ids_in_group_block]
# проверить были ли значения полей заполнены уже БЛОКА-ВМЕСТЕ ранее
later_value = []
if len(used_block_in_order_custom_field) > 0 and prev_direction_num != direction_num:
later_value = [used for used in used_block_in_order_custom_field if used in field_data[-1].values()]
if (prev_direction_num != direction_num and len(later_value) > 0) or field_data[-1].get(title_field):
# сделай вторую строку для текущего параметра текущей истории
field_data.append(custom_fields.copy())

field_data[-1][title_field] = value_field
field_data[-1]["proto_direction"] = direction_num
else:
# добавить в начальную строку текущее поле
if len(field_data) == 0:
field_data.append(custom_fields.copy())
field_data[-1][title_field] = value_field
field_data[-1]["proto_direction"] = direction_num
prev_direction_num = direction_num
final_result.append(
{
"Случай": k,
"Пациент": v.get('patient_fio'),
"Пол": v.get("sex"),
"Дата рождения": v.get("birthday"),
"Возраст": v.get("age"),
"Адрес": v.get("address"),
"field_data": field_data.copy(),
}
)

permanent_head_data = [
'Случай',
'Пациент',
'Пол',
'Дата рождения',
'Возраст',
'Адрес',
]
all_head_data = [*permanent_head_data, *custom_fields.keys()]
head_data_dict = {i: i for i in all_head_data}

results = data_model_save_to_file(final_result, head_data_dict, "Гиршпрунга", permanent_head_data, list(custom_fields.keys()))
link = "open-xls"

return JsonResponse({"ok": True, "results": results, "link": link})
38 changes: 37 additions & 1 deletion directory/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1084,7 +1084,7 @@ class Meta:
@staticmethod
def get_pattern_params():
params = PatternParam.objects.all().order_by("title").values("title", "pk")
result = [{"label": p["title"], "id": p["pk"]} for p in params]
result = [{"id": -1, "label": "Пусто"}, *[{"label": p["title"], "id": p["pk"]} for p in params]]
return result


Expand All @@ -1105,6 +1105,42 @@ def get_statistic_param(statistic_pattern_id):
return {p.statistic_param_id: {"title": p.statistic_param.title, "isDynamic": p.statistic_param.is_dynamic_param} for p in params}


class GroupPatternParams(models.Model):
title = models.CharField(max_length=400, unique=True, help_text="Название группы-блока параметра вместе")

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

class Meta:
verbose_name = "Статистическая модель - группа-блок"
verbose_name_plural = "Статистическая модель - группы-блоки"


class PatternParamTogether(models.Model):
statistic_param = models.ForeignKey(PatternParam, default=None, null=True, blank=True, help_text="Параметр статистической модели отчет", on_delete=models.CASCADE)
group_pattern_param = models.ForeignKey(GroupPatternParams, default=None, null=True, blank=True, help_text="Статистическая модель", on_delete=models.CASCADE)

def __str__(self):
return f"{self.statistic_param}-{self.group_pattern_param}"

class Meta:
verbose_name = "Статистическая модель - группа-блок и параметры ВМЕСТЕ"
verbose_name_plural = "Статистическая модель - группы-блоки и параметры ВМЕСТЕ"

@staticmethod
def get_together_param(statistic_pattern_ids):
groups_data = PatternParamTogether.objects.filter(statistic_param_id__in=statistic_pattern_ids)
result_by_group = {}
result_by_param = {g.statistic_param_id: g.group_pattern_param_id for g in groups_data}

for g in groups_data:
if not result_by_group.get(g.group_pattern_param_id):
result_by_group[g.group_pattern_param_id] = []
result_by_group[g.group_pattern_param_id].append(g.statistic_param_id)

return {"by_group": result_by_group, "by_param": result_by_param}


class ParaclinicInputGroups(models.Model):
title = models.CharField(max_length=255, help_text="Название группы")
show_title = models.BooleanField()
Expand Down
19 changes: 19 additions & 0 deletions statistic/report/base_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,22 @@ def fill_xls_check_research_exam_data(ws1, value_data):
column += 1
ws1.cell(row=r, column=column).value = v
return ws1


def fill_xls_model_statistic_data(ws1, final_data, permanent_head_data, custom_fields):
style_border1 = NamedStyle(name="style_border1")
bd = Side(style='thin', color="000000")
style_border1.border = Border(left=bd, top=bd, right=bd, bottom=bd)
style_border1.font = Font(bold=False, size=11)
style_border1.alignment = Alignment(wrap_text=True, horizontal='center', vertical='center')

r = 5
for row_data in final_data:
r += 1
for current_col in range(0, len(permanent_head_data)):
ws1.cell(row=r, column=current_col + 1).value = row_data.get(permanent_head_data[current_col])
for custom_field in row_data.get("field_data"):
for current_col in range(len(permanent_head_data), len(custom_fields) + len(permanent_head_data)):
ws1.cell(row=r, column=current_col + 1).value = custom_field.get(custom_fields[current_col - len(permanent_head_data)])
r += 1
return ws1

0 comments on commit 3828ef3

Please sign in to comment.