def procedural_text_for_result(direction, fwb, napr_child): styleSheet = getSampleStyleSheet() style = styleSheet["Normal"] style.fontName = "FreeSans" style.fontSize = 9 style.alignment = TA_JUSTIFY pdfmetrics.registerFont(TTFont('OpenSans', os.path.join(FONTS_FOLDER, 'OpenSans.ttf'))) pdfmetrics.registerFont(TTFont('OpenSansBold', os.path.join(FONTS_FOLDER, 'OpenSans-Bold.ttf'))) procedurals_diary = ProcedureList.objects.filter(diary=direction) text = '' if not napr_child and procedurals_diary.count() > 0: fwb.append(Paragraph("Назначено:", style)) for p in procedurals_diary: text = f"{text} <font face=\"FreeSansBold\"> {p.drug.mnn} {p.form_release.title} {p.method.title} {p.dosage} {p.units}: </font>" dates = {} for pt in ProcedureListTimes.objects.filter(prescription=p): date_str = strfdatetime(pt.times_medication.astimezone(pytz.timezone(TIME_ZONE)), "%d.%m.%Y") if dates.get(date_str, None) is None: dates[date_str] = '' time_str = strfdatetime(pt.times_medication.astimezone(pytz.timezone(TIME_ZONE)), "%H:%M") temp_time = dates[date_str] if temp_time: temp_time = f"{temp_time}, {time_str}" else: temp_time = f"{time_str}" dates[date_str] = temp_time text = f"{text} <br/>" for k, v in dates.items(): text = f"{text} {k} - {v}; " text = f"{text} <br/>" fwb.append(Paragraph(text, style)) return fwb
def json(self, doc: Optional[DoctorProfile] = None): return { "pk": self.pk, "num": self.num, "card": self.client.number_with_type_and_fio(), "cardPk": self.client_id, "phone": self.phone, "email": self.email, "address": self.address, "purpose": self.get_purpose_display(), "purpose_id": self.purpose, "comment": self.comment, "research": self.research.get_title(), "district": self.district.title if self.district else "", "hospital": self.hospital.safe_short_title if self.hospital else "", "docAssigned": self.doc_assigned.get_fio() if self.doc_assigned else "", "execAt": strfdatetime(self.exec_at, "%d.%m.%Y"), "isCancel": self.cancel, "isExternal": self.is_external, "isMainExternal": self.is_main_external, "needSendToExternal": self.need_send_to_external, "externalNum": self.external_num, "createdAt": strfdatetime(self.create_at, "%d.%m.%Y"), "createdAtTime": strfdatetime(self.create_at, "%X"), "status": self.status, "executor": self.executor_id, "executor_fio": self.executor.get_fio() if self.executor else None, "canEdit": ( not self.need_send_to_external and (not doc or doc.all_hospitals_users_control or not self.hospital or self.hospital == doc.get_hospital()) and not self.is_main_external ), "inLog": DoctorCallLog.objects.filter(call=self).count(), "directionPk": self.direction_id, }
def get_plan_operations_by_params(request): request_data = json.loads(request.body) start_date = datetime.strptime(request_data['start_date'], '%Y-%m-%d') start_date = datetime.combine(start_date, dtime.min) end_date = datetime.strptime(request_data['end_date'], '%Y-%m-%d') end_date = datetime.combine(end_date, dtime.max) doc_operate_pk = request_data.get('doc_operate_pk', -1) doc_anesthetist_pk = request_data.get('doc_anesthetist_pk', -1) department_pk = request_data.get('department_pk', -1) result = get_plans_by_params_sql(start_date, end_date, doc_operate_pk, doc_anesthetist_pk, department_pk) data = [] for i in result: hosp_nums_obj = hosp_get_hosp_direction(i[2]) hosp_first_num = hosp_nums_obj[0].get('direction') primary_reception_data = primary_reception_get_data(hosp_first_num) if primary_reception_data['weight']: weight = f"Вес-{primary_reception_data['weight']}" else: weight = '' fio_patient = f"{i[8]} {i[9][0:1]}.{i[10][0:1]}." date_raw = i[3].split('.') date_raw = f"{date_raw[2]}-{date_raw[1]}-{date_raw[0]}" update_date = Log.objects.filter(key=i[0], type=80002) create_date = Log.objects.filter(key=i[0], type=80001) tooltip_data = [] for c in create_date: doctor = c.user.get_fio() time = strfdatetime(c.time, '%d.%m.%y %H:%M') tooltip_data.append(f'Создал: {doctor} ({time})') for u in update_date: doctor = u.user.get_fio() time = strfdatetime(u.time, '%d.%m.%y %H:%M') tooltip_data.append(f"Обновил: {doctor} ({time})") data.append({ "pk_plan": i[0], "patient_card": i[1], "direction": i[2], "date": i[3], "date_raw": date_raw, "type_operation": i[4], "doc_operate_id": i[5], "doc_anesthetist_id": i[6] or -1, "canceled": i[7], "fio_patient": fio_patient, "birthday": i[11], "weight": weight, "tooltip_data": '\n'.join(tooltip_data), }) return JsonResponse({"result": data})
def to_json(self): return { 'pk': self.pk, 'title': self.title, 'code': self.code, 'hide': self.hide, 'rows': DirectoryRecord.objects.filter(directory=self).count(), 'createdAt': strfdatetime(self.created_at, "%d.%m.%Y %X"), 'updatedAt': strfdatetime(self.updated_at, "%d.%m.%Y %X"), 'editAccess': [str(x) for x in self.edit_access.all()], 'strValueTemplate': self.str_value_template or '{title}', }
def get_plan_hospitalization_by_params(request): request_data = json.loads(request.body) start_date = datetime.strptime(request_data['start_date'], '%Y-%m-%d') start_date = datetime.combine(start_date, dtime.min) end_date = datetime.strptime(request_data['end_date'], '%Y-%m-%d') end_date = datetime.combine(end_date, dtime.max) department_pk = request_data.get('department_pk', -1) result = get_plans_hospitalization_sql(start_date, end_date, department_pk) pk_plans = tuple(set([i.pk_plan for i in result])) data = [] sex_male = 0 sex_female = 0 all_patient = 0 if len(pk_plans) > 0: pk_plans_files = get_plans_hospitalizationfiles(pk_plans) plan_files_data = {} for p in pk_plans_files: if not plan_files_data.get(p.plan_id, None): plan_files_data[p.plan_id] = [{ 'file': f"{MEDIA_URL}{p.uploaded_file}" if p.uploaded_file else None, 'fileName': p.uploaded_file.split("/")[-1] if p.uploaded_file else None }] else: temp_files = plan_files_data.get(p.plan_id, None) temp_files.append({ 'file': f"{MEDIA_URL}{p.uploaded_file}" if p.uploaded_file else None, 'fileName': p.uploaded_file.split("/")[-1] if p.uploaded_file else None }) plan_files_data[p.plan_id] = temp_files.copy() for i in result: last_age_digit = i.ind_age[-1] if int(last_age_digit) in [2, 3, 4]: prefix_age = "года" elif last_age_digit == 1: prefix_age = "год" else: prefix_age = "лет" data_patient = f"{i.fio_patient} {i.ind_age} {prefix_age} ({i.born})" update_date = Log.objects.filter(key=i.pk_plan, type=80008) create_date = Log.objects.filter(key=i.pk_plan, type=80007) tooltip_data = [] patient_created = False for c in create_date: doctor = c.user.get_fio() if c.user else 'Личный кабинет' if not c.user: patient_created = True time = strfdatetime(c.time, '%d.%m.%y %H:%M') tooltip_data.append(f'Создал: {doctor} ({time})') for u in update_date: doctor = u.user.get_fio() if c.user else 'Личный кабинет' time = strfdatetime(u.time, '%d.%m.%y %H:%M') tooltip_data.append(f"Обновил: {doctor} ({time})") if i.date_char: slot_datetime = f'{i.date_char} на {i.hhmm_start}-{i.hhmm_end}' elif i.why_cancel: slot_datetime = i.why_cancel else: slot_datetime = "Ожидает решение" messages_data = Messages.get_messages_by_plan_hosp(i.pk_plan, last=True) data.append({ "pk_plan": i.pk_plan, "date": i.exec_at_char, "patient_card": i.client_id, "fio_patient": data_patient, "phone": i.phone, "research_title": i.research_title, "research_id": i.research_id, "depart_title": i.depart_title, "diagnos": i.diagnos, "tooltip_data": '\n'.join(tooltip_data), "sex": i.sex, "comment": i.comment, "canceled": i.work_status == 2, "status": i.work_status, "slot": slot_datetime, "created_by_patient": patient_created, "uploaded_file": plan_files_data.get(i.pk_plan, ""), "messages": messages_data, }) if i.sex.lower() == "ж": sex_female += 1 else: sex_male += 1 all_patient += 1 return JsonResponse({ "result": data, "sex_female": sex_female, "sex_male": sex_male, "all_patient": all_patient })
def default_title_result_form(direction, doc, date_t, has_paraclinic, individual_birthday, number_poliklinika, logo_col_func, is_extract): styleSheet = getSampleStyleSheet() style = styleSheet["Normal"] style.fontName = "FreeSans" style.fontSize = 9 style.alignment = TA_JUSTIFY style_ml = deepcopy(style) style_ml.leftIndent = 5 * mm styleBold = deepcopy(style) styleBold.fontName = "FreeSansBold" styleTable = deepcopy(style) styleTableMono = deepcopy(styleTable) styleTableMono.fontName = "Consolas" styleTableMono.fontSize = 10 styleAb = deepcopy(styleTable) styleAb.fontSize = 7 styleAb.leading = 7 styleAb.spaceBefore = 0 styleAb.spaceAfter = 0 styleAb.leftIndent = 0 styleAb.rightIndent = 0 styleAb.alignment = TA_CENTER styleTableMonoBold = deepcopy(styleTable) styleTableMonoBold.fontName = "Consolas-Bold" styleTableSm = deepcopy(styleTable) styleTableSm.fontSize = 4 data = [ ["Номер:", str(direction.pk)], ["Пациент:", Paragraph(direction.client.individual.fio(), styleTableMonoBold)], ["Пол:", direction.client.individual.sex], ["Возраст:", "{} {}".format(direction.client.individual.age_s(direction=direction), individual_birthday)], ] if not direction.is_external: data += [["Дата забора:", date_t]] if not has_paraclinic else [["Диагноз:", direction.diagnos]] data += [ [Paragraph(' ', styleTableSm), Paragraph(' ', styleTableSm)], ["РМИС ID:" if direction.client.base.is_rmis else "№ карты:", direction.client.number_with_type() + (" - архив" if direction.client.is_archive else "") + number_poliklinika], ] if direction.is_external and direction.hospital: data.append(["Организация:", direction.hospital.safe_short_title]) if direction.id_in_hospital is not None: data += [["Номер в организации:", direction.id_in_hospital]] else: data += [["", ""]] tube = TubesRegistration.objects.filter(issledovaniya__napravleniye=direction).first() if tube and (tube.time_get or tube.time_recive): data += [["Забор биоматериала:", strfdatetime((tube.time_get or tube.time_recive), "%d.%m.%Y %H:%M")]] elif not direction.imported_from_rmis and not is_extract and direction.doc: data.append(["Врач:", "<font>%s<br/>%s</font>" % (direction.doc.get_fio(), direction.get_doc_podrazdeleniye_title())]) elif direction.imported_org: data.append(["<font>Направляющая<br/>организация:</font>", direction.imported_org.title]) rows = len(data) logo_col = logo_col_func(direction) data = [[Paragraph(y, styleTableMono) if isinstance(y, str) else y for y in data[xi]] + [logo_col[xi]] for xi in range(rows)] if direction.is_external: colWidths = [40 * mm, doc.width - 158 - 40 * mm, 158] else: colWidths = [doc.width * 0.145, doc.width - 158 - doc.width * 0.145, 158] t = Table(data, colWidths=colWidths) t.setStyle( TableStyle( [ ('ALIGN', (-1, 0), (-1, 0), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('VALIGN', (-1, 0), (-1, 0), 'MIDDLE'), ('VALIGN', (-1, 5), (-1, 5), 'TOP'), ('LEFTPADDING', (0, 0), (-1, -1), 0), ('RIGHTPADDING', (0, 0), (-1, -1), 1), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ('TOPPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (-1, 0), (-1, -1), 0), ('TOPPADDING', (-1, 0), (-1, -1), 0), ('TOPPADDING', (-1, 5), (-1, 5), 3), ('TOPPADDING', (-1, 0), (-1, 0), -7 * mm if isinstance(logo_col[0], Paragraph) else 0), ('TOPPADDING', (0, 5), (1, 5), 0), ('TOPPADDING', (0, 6), (1, 6), -6), ('BOTTOMPADDING', (0, 5), (1, 5), 0), ('LEFTPADDING', (0, 5), (1, 5), 0), ('RIGHTPADDING', (0, 5), (1, 5), 0), ('SPAN', (-1, 0), (-1, 4)), ('SPAN', (-1, 5), (-1, -1)), ] ) ) return t
def form_02(request_data): """ Отдельный статталон по отдельному амбулаторному приему. Краткая форма - результата проткола. Учитываются те поля, к-рые имеют признак "для статталона" ------------------------------- Вход: Направление. Выходные: форма в файле .....\Lib\site-packages\anytree\render.py class ContStyle(AbstractStyle): необходимое мотод super сделать так:(изменить символы) super(ContStyle, self).__init__(u'\u2063 ', u'\u2063 ', u'\u2063 ') """ # получить направления ind_dir = json.loads(request_data["napr_id"]) hospital_name = SettingManager.get("org_title") if sys.platform == 'win32': locale.setlocale(locale.LC_ALL, 'rus_rus') else: locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8') pdfmetrics.registerFont( TTFont('PTAstraSerifBold', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf'))) pdfmetrics.registerFont( TTFont('PTAstraSerifReg', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf'))) pdfmetrics.registerFont( TTFont('Symbola', os.path.join(FONTS_FOLDER, 'Symbola.ttf'))) buffer = BytesIO() doc = SimpleDocTemplate(buffer, pagesize=A4, leftMargin=18 * mm, rightMargin=5 * mm, topMargin=6 * mm, bottomMargin=6 * mm, allowSplitting=1, title="Форма {}".format("Статталон пациента")) width, height = portrait(A4) styleSheet = getSampleStyleSheet() style = styleSheet["Normal"] style.fontName = "PTAstraSerifReg" style.fontSize = 10 style.leading = 12 style.spaceAfter = 0.5 * mm styleBold = deepcopy(style) styleBold.fontName = "PTAstraSerifBold" styleCenter = deepcopy(style) styleCenter.alignment = TA_CENTER styleCenter.fontSize = 12 styleCenter.leading = 10 styleCenter.spaceAfter = 1 * mm styleCenterBold = deepcopy(styleBold) styleCenterBold.alignment = TA_CENTER styleCenterBold.fontSize = 12 styleCenterBold.leading = 15 styleCenterBold.face = 'PTAstraSerifBold' styleCenterBold.borderColor = black styleJustified = deepcopy(style) styleJustified.alignment = TA_JUSTIFY styleJustified.spaceAfter = 4.5 * mm styleJustified.fontSize = 12 styleJustified.leading = 4.5 * mm objs = [] styleT = deepcopy(style) styleT.alignment = TA_LEFT styleT.fontSize = 10 styleT.leading = 4.5 * mm styleT.face = 'PTAstraSerifReg' for dir in ind_dir: obj_dir = Napravleniya.objects.get(pk=dir) ind_card = obj_dir.client patient_data = ind_card.get_data_individual() if patient_data['age'] < SettingManager.get( "child_age_before", default='15', default_type='i'): patient_data['serial'] = patient_data['bc_serial'] patient_data['num'] = patient_data['bc_num'] else: patient_data['serial'] = patient_data['passport_serial'] patient_data['num'] = patient_data['passport_num'] card_num_obj = patient_data['card_num'].split(' ') p_card_num = card_num_obj[0] if len(card_num_obj) == 2: p_card_type = '(' + str(card_num_obj[1]) + ')' else: p_card_type = '' space_symbol = ' ' # Добавить сведения о пациента content_title = [ Indenter(left=0 * mm), Spacer(1, 1 * mm), Paragraph('{}'.format(hospital_name), styleCenterBold), Spacer(1, 2 * mm), Paragraph('<u>Статистический талон пациента</u>', styleCenter), Paragraph( '{}<font size=10>Карта № </font><font fontname="PTAstraSerifBold" size=10>{}</font><font size=10> из {}</font>' .format(3 * space_symbol, p_card_num, p_card_type), styleCenter), Spacer(1, 2 * mm), Paragraph('<font size=11>Данные пациента:</font>', styleBold), Paragraph( "1. Фамилия, имя, отчество: <font size=11.7 fontname ='PTAstraSerifBold'> {} </font> " .format(patient_data['fio']), style), Paragraph( '2. Пол: {} {} 3. Дата рождения: {}'.format( patient_data['sex'], 3 * space_symbol, patient_data['born']), style), Paragraph( '4. Место регистрации: {}'.format( patient_data['main_address']), style), Paragraph( '5. Полис ОМС: серия {} №: {} {}' '6. СНИЛС: {}'.format(patient_data['oms']['polis_serial'], patient_data['oms']['polis_num'], 13 * space_symbol, patient_data['snils']), style, ), Paragraph( '7. Наименование страховой медицинской организации: {}'.format( patient_data['oms']['polis_issued']), style), ] objs.extend(content_title) # добавить данные об услуге objs.append(Spacer(1, 3 * mm)) objs.append( Paragraph('<font size=11>Данные об услуге:</font>', styleBold)) objs.append(Spacer(1, 1 * mm)) obj_iss = Issledovaniya.objects.filter(napravleniye=obj_dir, parent_id=None).first() date_proto = utils.strfdatetime(obj_iss.time_confirmation, "%d.%m.%Y") opinion = [ [ Paragraph('Основная услуга', styleT), Paragraph( '<font fontname="PTAstraSerifBold">{}</font> <font face="Symbola">\u2013</font> {}' .format(obj_iss.research.code, obj_iss.research.title), styleT), ], [ Paragraph('Направление №', styleT), Paragraph('{}'.format(dir), styleT) ], [ Paragraph('Дата протокола', styleT), Paragraph('{}'.format(date_proto), styleT) ], ] # Найти и добавить поля у к-рых флаг "for_talon". Отсортировано по 'order' (группа, поле) field_iss = ParaclinicResult.objects.filter( issledovaniye=obj_iss, field__for_talon=True).order_by('field__group__order', 'field__order') for f in field_iss: v = f.value.replace("\n", "<br/>") field_type = f.get_field_type() if field_type == 1: vv = v.split('-') if len(vv) == 3: v = "{}.{}.{}".format(vv[2], vv[1], vv[0]) list_f = [[ Paragraph(f.field.get_title(force_type=field_type), styleT), Paragraph(v, styleT) ]] opinion.extend(list_f) tbl = Table(opinion, colWidths=(60 * mm, 123 * mm)) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 1.0, colors.black), ('BOTTOMPADDING', (0, 0), (-1, -1), 1 * mm), ])) objs.append(tbl) # Заключительные положения objs.append(Spacer(1, 4 * mm)) objs.append( Paragraph('<font size=11>Заключительные положения:</font>', styleBold)) objs.append(Spacer(1, 1 * mm)) empty = '-' purpose = empty if not obj_iss.purpose else obj_iss.purpose outcome_illness = empty if not obj_iss.outcome_illness else obj_iss.outcome_illness result_reception = empty if not obj_iss.result_reception else obj_iss.result_reception diagnos = empty if not obj_iss.diagnos else obj_iss.diagnos opinion = [ [ Paragraph('Цель посещения', styleT), Paragraph('{}'.format(purpose), styleT) ], [ Paragraph('Исход заболевания', styleT), Paragraph('{}'.format(outcome_illness), styleT) ], [ Paragraph('Результат обращения', styleT), Paragraph('{}'.format(result_reception), styleT) ], [ Paragraph('Основной диагноз', styleT), Paragraph('{}'.format(diagnos), styleT) ], ] tbl = Table(opinion, colWidths=(60 * mm, 123 * mm)) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 1.0, colors.black), ('BOTTOMPADDING', (0, 0), (-1, -1), 1 * mm), ])) objs.append(tbl) # Добавить Дополнительные услуги add_research = Issledovaniya.objects.filter( parent_id__napravleniye=obj_dir) if add_research: objs.append(Spacer(1, 3 * mm)) objs.append( Paragraph('<font size=11>Дополнительные услуги:</font>', styleBold)) objs.append(Spacer(1, 1 * mm)) for i in add_research: objs.append( Paragraph( '{} <font face="Symbola">\u2013</font> {}'.format( i.research.code, i.research.title), style)) objs.append(Spacer(1, 5 * mm)) objs.append( HRFlowable(width=185 * mm, thickness=0.7 * mm, spaceAfter=1.3 * mm, spaceBefore=0.5 * mm, color=colors.black, hAlign=TA_LEFT)) objs.append(Paragraph('<font size=11>Лечащий врач:</font>', styleBold)) objs.append(Spacer(1, 1 * mm)) personal_code = '' doc_fio = '' if obj_iss.time_confirmation: personal_code = empty if not obj_iss.doc_confirmation or not obj_iss.doc_confirmation.personal_code else obj_iss.doc_confirmation.personal_code doc_fio = obj_iss.doc_confirmation_fio objs.append( Paragraph( '{} /_____________________/ {} Код врача: {} '.format( doc_fio, 42 * space_symbol, personal_code), style)) objs.append(Spacer(1, 5 * mm)) # Получить структуру Направлений если, направление в Дереве не важно в корне в середине или в начале root_dir = tree_directions.root_direction(dir) num_iss = root_dir[-1][-2] tree_dir = tree_directions.tree_direction(num_iss) final_tree = {} pattern = re.compile('<font face=\"Symbola\" size=10>\u2713</font>') node_dir = Node("Структура направлений") for j in tree_dir: if not Researches.objects.get(pk=j[8]).is_hospital: continue if len(j[9]) > 47: research = j[9][:47] + '...' else: research = j[9] diagnos = ' --' + j[-2] if j[-2] else "" temp_s = f"{j[0]} - {research}. Создано {j[1]} в {j[2]} {diagnos}" if dir == j[0]: temp_s = f"{temp_s} -- <font face=\"Symbola\" size=10>\u2713</font>" if not j[3]: final_tree[j[5]] = Node(temp_s, parent=node_dir) else: final_tree[j[5]] = Node(temp_s, parent=final_tree.get(j[3])) counter = 0 opinion = [] for row in RenderTree(node_dir): counter += 1 result = pattern.search(row.node.name) current_style = styleBold if result else styleT count_space = len(row.pre) // 2 * 2 para = [ Paragraph( '{}{}'.format(space_symbol * count_space, row.node.name), current_style) ] opinion.append(para) tbl = Table(opinion, colWidths=(190 * mm)) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 1.0, colors.white), ('BOTTOMPADDING', (0, 0), (-1, -1), 1 * mm), ])) objs.append(tbl) objs.append(PageBreak()) doc.build(objs) pdf = buffer.getvalue() buffer.close() return pdf
def form(request): request_data = json.loads(request.body) pk = request_data["pk"] iss: Issledovaniya = Issledovaniya.objects.prefetch_related( 'result_set').get(pk=pk) research: Researches = Researches.objects.prefetch_related( Prefetch('fractions_set', queryset=Fractions.objects.all().order_by( "sort_weight", "pk").prefetch_related('references_set'))).get( pk=iss.research_id) data = { "pk": pk, "confirmed": bool(iss.time_confirmation), "saved": bool(iss.time_save), "execData": { "timeSave": strfdatetime(iss.time_save, '%d.%m.%Y %X') or None, "docSave": iss.doc_save.get_fio() if iss.doc_save else None, "timeConfirm": strfdatetime(iss.time_confirmation, '%d.%m.%Y %X') or None, "docConfirmation": iss.doc_confirmation.get_fio() if iss.doc_confirmation else None, "app": iss.api_app.name if iss.api_app else None, }, "allow_reset_confirm": iss.allow_reset_confirm(request.user), "research": { "title": research.title, "can_comment": research.can_lab_result_comment, "no_units_and_ref": research.no_units_and_ref, "co_executor_mode": research.co_executor_mode or 0, "co_executor_title": research.co_executor_2_title, "template": research.template, }, "result": [], "comment": iss.lab_comment or "", "laborants": ([ { "id": -1, "label": 'Не выбрано' }, *[{ "id": x.pk, "label": x.get_full_fio() } for x in DoctorProfile.objects.filter( user__groups__name="Лаборант", podrazdeleniye__p_type=Podrazdeleniya.LABORATORY).order_by( 'fio')], ] if SettingManager.l2('results_laborants') else []), "legalAuthenticators": ([{ "id": x.pk, "label": x.get_full_fio() } for x in DoctorProfile.objects.filter( user__groups__name="Подпись от организации").order_by('fio')] if SettingManager.get('legal_authenticator', default="false", default_type='b') else []), "co_executor": iss.co_executor_id or -1, "co_executor2": iss.co_executor2_id or -1, "legal_authenticator": iss.legal_authenticator_id or SettingManager.get( "preselected_legal_authenticator", default='-1', default_type='i') or -1, } f: Fractions for f in research.fractions_set.all(): r: Optional[Result] = iss.result_set.filter(fraction=f).first() if not r and f.hide: continue ref_m = f.ref_m ref_f = f.ref_f if isinstance(ref_m, str): ref_m = json.loads(ref_m) if isinstance(ref_f, str): ref_f = json.loads(ref_f) av = {} def_ref_pk = -1 if not f.default_ref else f.default_ref_id for avref in f.references_set.all(): av[avref.pk] = { "title": avref.title, "about": avref.about, "m": json.loads(avref.ref_m) if isinstance(avref.ref_m, str) else avref.ref_m, "f": json.loads(avref.ref_f) if isinstance(avref.ref_f, str) else avref.ref_f, } empty_ref = { "m": ref_m, "f": ref_f, } selected_reference = r.selected_reference if r else def_ref_pk current_ref = r.get_ref(full=True) if r else ( empty_ref if def_ref_pk == -1 else av.get(def_ref_pk, {})) av[-1] = { "title": "Основной референс", "about": "", **empty_ref, } if selected_reference == -2: av[-2] = current_ref av[-3] = { "title": "Настраиваемый референс", "about": "", "m": {}, "f": {}, } data["result"].append({ "fraction": { "pk": f.pk, "title": f.title, "units": f.get_unit_str(), "render_type": f.render_type, "options": f.options, "formula": f.formula, "type": f.variants.get_variants() if f.variants else [], "type2": f.variants2.get_variants() if f.variants2 else [], "references": { **empty_ref, "default": def_ref_pk, "available": av, }, }, "ref": current_ref, "selectedReference": selected_reference, "norm": r.get_is_norm(recalc=True)[0] if r else None, "value": str(r.value if r else '').replace('<', '<').replace('>', '>'), }) return JsonResponse({ "data": data, })
def get_procedure_by_dir(request): request_data = json.loads(request.body) dates = set() rows = [] dates_times = {} procedure: ProcedureList for procedure in (ProcedureList.objects.filter( history_id=request_data["direction"], diary__issledovaniya__time_confirmation__isnull=False).order_by( 'pk').prefetch_related( Prefetch( 'procedurelisttimes_set', queryset=ProcedureListTimes.objects.all().order_by( 'times_medication')))): row = { "pk": procedure.pk, "drug": str(procedure.drug), "created_at": strfdatetime(procedure.time_create, "%d.%m.%Y"), "form_release": str(procedure.form_release.title), "method": str(procedure.method.title), "dosage": f"{procedure.dosage} {procedure.units}".strip(), "cancel": bool(procedure.cancel), "who_cancel": None if not procedure.who_cancel else procedure.who_cancel.get_fio(), "comment": procedure.comment or None, "step": procedure.step or 1, "dates": {}, } pt: ProcedureListTimes for pt in procedure.procedurelisttimes_set.all(): date_str = strfdatetime( pt.times_medication.astimezone(pytz.timezone(TIME_ZONE)), "%d.%m.%Y") time_str = strfdatetime( pt.times_medication.astimezone(pytz.timezone(TIME_ZONE)), "%H:%M") if date_str not in dates_times: dates_times[date_str] = [] if time_str not in dates_times[date_str]: dates_times[date_str].append(time_str) dates_times[date_str] = list(sorted(dates_times[date_str])) dates.add( pt.times_medication.astimezone( pytz.timezone(TIME_ZONE)).date()) if date_str not in row["dates"]: row["dates"][date_str] = {} row["dates"][date_str][time_str] = { "datetime": f"{date_str} {time_str}", "pk": pt.pk, "empty": False, "ok": bool(pt.executor), "executor": None if not pt.executor else pt.executor.get_fio(), "cancel": bool(pt.cancel) or row["cancel"], "who_cancel": (None if not pt.who_cancel else pt.who_cancel.get_fio()) or row["who_cancel"], } rows.append(row) dates_all = [] if dates: min_date = min(dates) max_date = max(dates) dates_all = [ strfdatetime(x, "%d.%m.%Y") for x in date_iter_range(min_date, max_date, more_1=True) ] for row in rows: for date in dates_all: if date not in dates_times: continue if date not in row["dates"]: row["dates"][date] = {} for t in dates_times[date]: if t not in row["dates"][date]: row["dates"][date][t] = { "empty": True, "datetime": f"{date} {t}", } return JsonResponse({ "result": rows, "dates": dates_all, "timesInDates": dates_times })