def get_epid_data(directions, with_confirm): result = get_extra_notification_data_for_pdf(directions, EXTRA_MASTER_RESEARCH_PK, EXTRA_SLAVE_RESEARCH_PK, with_confirm) data = {} for i in result: if i.master_field == 1: master_value = normalize_date(i.master_value) else: master_value = i.master_value if data.get(i.slave_dir) is None: data[i.slave_dir] = { 'master_dir': i.master_dir, 'epid_title': i.epid_title, 'epid_value': i.epid_value, 'master_field_results': [{ 'master_field_title': i.master_field_title, 'master_value': master_value }], } else: temp_data = data.get(i.slave_dir) temp_data['master_field_results'].append({ 'master_field_title': i.master_field_title, 'master_value': master_value }) return data
def hosp_get_transfers_data(hosp_nums_obj): titles_field = ['Дата перевода', 'Время перевода'] date_transfer_value, time_transfer_value = '', '' transfers = [] list_values = None for i in range(len(hosp_nums_obj)): if i == 0: continue transfer_research_title = hosp_nums_obj[i].get('research_title') # получить для текущего hosp_dir эпикриз с title - перевод..... from_hosp_dir_transfer = hosp_nums_obj[i - 1].get('direction') epicrisis_data = hosp_get_data_direction(from_hosp_dir_transfer, site_type=6, type_service='None', level=2) if epicrisis_data: result_check = check_transfer_epicrisis(epicrisis_data) if result_check['iss']: iss_transfer, research_id_transfer = result_check['iss'], result_check['research_id'] if titles_field and iss_transfer: list_values = get_result_value_iss(iss_transfer, research_id_transfer, titles_field) else: continue if list_values: for i in list_values: if i[3] == 'Дата перевода': date_transfer_value = normalize_date(i[2]) continue if i[3] == 'Время перевода': time_transfer_value = i[2] continue transfers.append({'transfer_research_title': transfer_research_title, 'date_transfer_value': date_transfer_value, 'time_transfer_value': time_transfer_value}) return transfers
def get_temperature_list(hosp_num_dir): """ :param num_dir: :return: { temperature: {data: [36.6, 36.7, 37.1 итд], xtext: ['21.01.20 13:30', '21.01.20 20:00', '22.01.20 12:10' итд],}, systolic: {data[], xtext :[]}, diastolic: {data[], xtext :[]}, pulse: {data[], xtext :[]} } """ # tl - temperature list tl_objs = hosp_get_data_direction(hosp_num_dir, site_type=9, type_service='None', level=2) tl_iss = [i['iss'] for i in tl_objs] research_id = None for i in tl_objs: research_id = i['research_id'] break if research_id is None: return {} final_data = {} title_list = ['Температура', 'Пульс (уд/с)', 'Дата измерения', 'Время измерения', 'Систолическое давление (мм рт.с)', 'Диастолическое давление (мм рт.с)'] a = get_result_temperature_list(tl_iss, research_id, title_list) data = {} for i in a: value = i[2] field = i[3] if field.lower().find('дата') != -1: value = normalize_date(value) in_data = {field: value} key = i[1] if not data.get(key): data.update({key: {}}) t_data = data.get(key) t_data.update(in_data) data[key] = t_data for k, v in data.items(): date_time = get_date_time_tl(v) for title, value in v.items(): if not value or value == '0': continue if not final_data.get(title): final_data[title] = {'data': [], 'xtext': []} t_final_data = final_data.get(title) t_data = t_final_data['data'] t_data.append(value) t_xtext = t_final_data['xtext'] t_xtext.append(date_time) final_data[title] = {'data': t_data, 'xtext': t_xtext} final_data.pop('Дата измерения', None) final_data.pop('Время измерения', None) for k, v in final_data.items(): if 'температура' in k.lower() or 'давление' in k.lower() or 'пульс' in k.lower(): number_data = list(map(force_to_number, v['data'])) v['data'] = number_data v['min_max'] = [min(number_data), max(number_data)] final_data[k] = v if 'Температура' in final_data: final_data['Температура (°C)'] = final_data.pop('Температура') return final_data
def cast_sql_syntax_dates(params, indicator): date = None if "now" in params.lower(): current_date = current_time() if "+" in params or '-' in params: interval = params.split("now") period = interval[1].replace("'", "").strip() period = period.strip().split(" ") period_duration = int(period[0]) period_type = period[1] years, months, weeks, days = 0, 0, 0, 0 if period_type == "years": years = period_duration elif period_type == "months": months = period_duration elif period_type == "days": days = period_duration elif period_type == "weeks": weeks = period_duration date = current_date + relativedelta( years=years, months=months, weeks=weeks, days=days) else: date = current_date date = date.strftime("%Y-%m-%d %H:%M:%S") else: try: if "-" in params: params = normalize_date(params) date = str_date(params, indicator=indicator).strftime("%Y-%m-%d %H:%M:%S") except Exception: date = None return date
def fields_result(iss, fwb, title_field_result=None): if title_field_result is None: title_field_result = [] styleSheet = getSampleStyleSheet() style = styleSheet["Normal"] style.fontName = "PTAstraSerifReg" style.fontSize = 12 style.alignment = TA_JUSTIFY style_ml = deepcopy(style) style_ml.spaceAfter = 2 * mm styleCenter = deepcopy(style) styleCenter.alignment = TA_CENTER styleBold = deepcopy(style) styleBold.fontName = "PTAstraSerifBold" for group in directory.ParaclinicInputGroups.objects.filter(research=iss.research).order_by("order"): results = ParaclinicResult.objects.filter(issledovaniye=iss, field__group=group).order_by("field__order") fwb.append(Spacer(1, 3 * mm)) if results.exists(): if group.show_title and group.show_title != "": fwb.append(Paragraph(group.title.replace('<', '<').replace('>', '>'), styleBold)) for r in results: field_type = r.get_field_type() if field_type == 15: continue else: v = r.value.replace('<', '<').replace('>', '>').replace("\n", "<br/>") if not v: continue v = v.replace('<sub>', '<sub>') v = v.replace('</sub>', '</sub>') v = v.replace('<sup>', '<sup>') v = v.replace('</sup>', '</sup>') v = text_to_bold(v) if field_type == 16: continue if field_type == 17: continue if field_type == 1: v = normalize_date(v) if field_type in [11, 13]: v = '<font face="PTAstraSerifReg" size="12">{}</font>'.format(v.replace("<br/>", " ")) if r.field.get_title(force_type=field_type) != "" and not r.field.get_title(force_type=field_type) in title_field_result: fwb.append( Paragraph( "<font face=\"PTAstraSerifBold\">{}:</font> {}".format(r.field.get_title(force_type=field_type).replace('<', '<').replace('>', '>'), v), style_ml, ) ) else: if not r.field.get_title(force_type=field_type) in title_field_result: fwb.append(Paragraph(v, style_ml)) return fwb
def closed_bl(hosp_num_dir): """ Подтверждены больничные-протоколы со словом закрытие среди Б/Л? """ result_bl = hosp_get_data_direction(hosp_num_dir, site_type=8, type_service='None', level=-1) num, who_get, who_care, start_date, end_date, start_work = '', '', '', '', '', '' for i in result_bl: if i['date_confirm'] is None: continue if i["research_title"].lower().find('закрыт') != -1: data_closed_bl = ParaclinicResult.objects.filter(issledovaniye=i['iss']) for b in data_closed_bl: if b.field.title == "Лист нетрудоспособности №": num = b.value continue if b.field.title == "Выдан кому": who_get = b.value continue if b.field.title == "по уходу за": who_care = b.value continue if b.field.title == "выдан с": start_date = b.value if start_date.find('-') != -1: start_date = normalize_date(start_date) continue if b.field.title == "по": end_date = b.value if end_date.find('-') != -1: end_date = normalize_date(end_date) continue if b.field.title == "к труду": start_work = b.value if start_work.find('-') != -1: start_work = normalize_date(start_work) continue return {'is_closed': True, 'num': num, 'who_get': who_get, 'who_care': who_care, 'start_date': start_date, 'end_date': end_date, 'start_work': start_work} return {'is_closed': False, 'num': num, 'who_get': who_get, 'who_care': who_care, 'start_date': start_date, 'end_date': end_date, 'start_work': start_work}
def hosp_patient_movement(hosp_nums_obj): titles_field = ['Дата перевода'] patient_movement = [] list_values = None for i in range(len(hosp_nums_obj)): date_out, diagnos_mkb, doc_confirm_code = '', '', '' bed_profile_research_title = hosp_nums_obj[i].get('research_title') hosp_dir = hosp_nums_obj[i].get('direction') primary_reception_data = primary_reception_get_data(hosp_dir) hosp_extract_data = hosp_get_data_direction(hosp_dir, site_type=7, type_service='None', level=2) if hosp_extract_data: extract_data = hosp_extract_get_data(hosp_dir) if extract_data: date_out = extract_data['date_value'] diagnos_mkb = extract_data['final_diagnos_mkb'] doc_confirm_code = ( None if not Issledovaniya.objects.get(pk=extract_data['extract_iss']) else Issledovaniya.objects.get(pk=extract_data['extract_iss']).doc_confirmation.personal_code ) list_values = None epicrisis_data = hosp_get_data_direction(hosp_dir, site_type=6, type_service='None', level=2) if epicrisis_data: result_check = check_transfer_epicrisis(epicrisis_data) if result_check['iss']: iss_transfer, research_id_transfer = result_check['iss'], result_check['research_id'] if titles_field and iss_transfer: list_values = get_result_value_iss(iss_transfer, research_id_transfer, titles_field) if list_values: for i in list_values: if i[3] == 'Дата перевода': date_out = normalize_date(i[2]) if i[3] == 'Клинический диагноз по МКБ': diagnos_mkb = i[2] patient_movement.append( { 'bed_profile_research_title': bed_profile_research_title, 'date_entered_value': primary_reception_data['date_entered_value'], 'date_oute': date_out, 'diagnos_mkb': diagnos_mkb, 'doc_confirm_code': doc_confirm_code, } ) return patient_movement
def hosp_get_clinical_diagnos(hosp_obj): clinic_diagnos = '' tmp_clinic_diagnos = [] for i in hosp_obj: hosp_diagnostic_epicris = hosp_get_data_direction(i['direction'], site_type=6, type_service='None', level=2) day_entries_iss = [] day_entries_research_id = None if hosp_diagnostic_epicris: for i in hosp_diagnostic_epicris: # найти эпикризы диагностические if i.get('research_title').lower().find('диагностич') != -1: day_entries_iss.append(i.get('iss')) if not day_entries_research_id: day_entries_research_id = i.get('research_id') titles_field = ['Диагноз клинический', 'Дата установления диагноза', 'Основной', 'Осложнение', 'Сопутствующий'] list_values = [] if titles_field and day_entries_iss: for i in day_entries_iss: list_values.append(get_result_value_iss(i, day_entries_research_id, titles_field)) if list_values: for fields in list_values: clinical_data = {'clinic_diagnos': '', 'main_diagnos': '', 'other_diagnos': '', 'near_diagnos': '', 'date': ''} for i in fields: if i[3] == 'Дата установления диагноза': clinical_data['date'] = normalize_date(i[2]) continue if i[3] == 'Диагноз клинический': clinical_data['clinic_diagnos'] = i[2] continue if i[3] == 'Основной': clinical_data['main_diagnos'] = f"Основной: {i[2]}" continue if i[3] == 'Осложнение': clinical_data['other_diagnos'] = f"; Осложнение: {i[2]}" continue if i[3] == 'Сопутствующий': clinical_data['near_diagnos'] = f"; Сопутствующий: {i[2]}" continue if clinical_data['date'] and (clinical_data['clinic_diagnos'] or clinical_data['main_diagnos']): tmp_clinic_diagnos.append(clinical_data.copy()) for i in tmp_clinic_diagnos: clinic_diagnos = f"{clinic_diagnos}{i['clinic_diagnos']} <u>{i['main_diagnos']}</u>{i['other_diagnos']}{i['near_diagnos']}; дата: {i['date']}<br/>" return clinic_diagnos
def form_02(direction: Napravleniya, iss: Issledovaniya, fwb, doc, leftnone, user=None): # Направление на ВМП styleSheet = getSampleStyleSheet() style = styleSheet["Normal"] style.fontName = "PTAstraSerifReg" style.fontSize = 12 style.alignment = TA_JUSTIFY style_ml = deepcopy(style) style_ml.spaceAfter = 2 * mm styleCenter = deepcopy(style) styleCenter.alignment = TA_CENTER styleBold = deepcopy(style) styleBold.fontName = "PTAstraSerifBold" styleCenterBold = deepcopy(style) styleCenterBold.alignment = TA_CENTER styleCenterBold.fontSize = 12 styleCenterBold.leading = 15 styleCenterBold.fontName = 'PTAstraSerifBold' hospital_name = direction.hospital.title phones = direction.hospital.phones hospital_address = direction.hospital.address pdfmetrics.registerFont( TTFont('PTAstraSerifBold', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf'))) pdfmetrics.registerFont( TTFont('PTAstraSerifReg', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf'))) fwb.append(Spacer(1, 5 * mm)) open_bold_tag = "<font face =\"PTAstraSerifBold\">" close_tag_bold = "</font>" fwb.append(Spacer(1, 4 * mm)) fwb.append(Paragraph(f'{hospital_name.upper()}', styleCenterBold)) fwb.append(Paragraph(f'{hospital_address} тел: {phones}', styleCenter)) fwb.append( Paragraph(f'{direction.doc.podrazdeleniye.title.upper()}', styleCenter)) fwb.append( HRFlowable(width=190 * mm, spaceAfter=3 * mm, spaceBefore=3 * mm, color=colors.black, thickness=1.5)) fwb.append(Spacer(1, 2 * mm)) title_field_result = ["Руководитель медицинской организации", "Дата"] data_fields_result = fields_result_only_title_fields( iss, title_field_result) main_manager, date_protocol = "", "" for i in data_fields_result: if i["title"] == "Руководитель медицинской организации": main_manager = i["value"] if i["title"] == "Дата": date_protocol = normalize_date(i["value"]) fwb.append( Paragraph( f'Исх.№ <u>{direction.pk}</u> от <u>{date_protocol or str(iss.medical_examination)}</u>', style)) fwb.append(Spacer(1, 2 * mm)) fwb.append(Paragraph('НАПРАВЛЕНИЕ', styleCenterBold)) fwb.append( Paragraph( 'на госпитализацию для оказания высокотехнологичной медицинской помощи', styleCenterBold)) fwb.append(Spacer(1, 4 * mm)) fwb.append( Paragraph( f'{open_bold_tag}ФИО пациента:{close_tag_bold} {direction.client.individual.fio()}', style_ml)) sex = direction.client.individual.sex space_symbol = ' ' fwb.append( Paragraph( f'{open_bold_tag}Дата рождения:{close_tag_bold} {direction.client.individual.bd()} {open_bold_tag} - Пол:{close_tag_bold} {sex}, {space_symbol * 5}', style_ml)) polis_num = '' polis_issue = '' snils = '' ind_data = direction.client.get_data_individual() if ind_data['oms']['polis_num']: polis_num = ind_data['oms']['polis_num'] if ind_data['oms']['polis_issued']: polis_issue = ind_data['oms']['polis_issued'] if ind_data['snils']: snils = ind_data['snils'] fwb.append( Paragraph(f'{open_bold_tag}Полис ОМС:{close_tag_bold} {polis_num}', style_ml)) fwb.append( Paragraph( f'{open_bold_tag}Название страховой медицинской организации:{close_tag_bold} {polis_issue}', style_ml)) fwb.append( Paragraph(f'{open_bold_tag}СНИЛС:{close_tag_bold} {snils}', style_ml)) address = ind_data['main_address'] fwb.append( Paragraph( f'{open_bold_tag}Адрес регистрации:{close_tag_bold} {address}', style_ml)) fwb = fields_result(iss, fwb, title_field_result) fwb.append(Spacer(1, 10 * mm)) styleT = deepcopy(style) styleT.alignment = TA_LEFT styleT.leading = 5 * mm opinion = [ [ Paragraph('Руководитель медицинской организации', styleT), Paragraph('___________________', styleT), Paragraph(f'{main_manager}', styleT), ], [ Paragraph('Лечащий врач', styleT), Paragraph('___________________', styleT), Paragraph(f'{iss.doc_confirmation.get_full_fio()}', styleT), ], ] tbl = Table(opinion, hAlign='LEFT', colWidths=[57 * mm, 45 * mm, 57 * mm], rowHeights=[13 * mm, 13 * mm]) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.white), ('LEFTPADDING', (0, 0), (-1, -1), 0 * mm), ('VALIGN', (0, 0), (-1, -1), 'BOTTOM'), ])) fwb.append(tbl) fwb.append(Spacer(1, 10 * mm)) fwb.append( Paragraph("Печать направляющей медицинской организации", style_ml)) return fwb
def form_01(request_data): d1 = request_data['date1'] d2 = request_data['date2'] company_pk = request_data['company'] date1 = normalize_date(d1) date2 = normalize_date(d2) company_objs = Company.objects.get(pk=company_pk) d1 = datetime.strptime(date1, '%d.%m.%Y') d2 = datetime.strptime(date2, '%d.%m.%Y') start_date = datetime.combine(d1, dtime.min) end_date = datetime.combine(d2, dtime.max) confirm_direction = get_confirm_direction_pathology(start_date, end_date) confirm_direction = [i[0] for i in confirm_direction] dir_obs = Napravleniya.objects.filter( pk__in=confirm_direction, workplace__icontains=company_objs.title) hospital: Hospitals = request_data["hospital"] hospital_name = hospital.safe_short_title hospital_address = hospital.safe_address hospital_kod_ogrn = hospital.safe_ogrn 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'))) buffer = BytesIO() doc = SimpleDocTemplate(buffer, pagesize=A4, leftMargin=25 * mm, rightMargin=5 * mm, topMargin=6 * mm, bottomMargin=6 * mm, allowSplitting=1, title="Форма {}".format("025/у")) width, height = portrait(A4) styleSheet = getSampleStyleSheet() style = styleSheet["Normal"] style.fontName = "PTAstraSerifReg" style.fontSize = 12 style.leading = 15 style.spaceAfter = 0.5 * mm styleBold = deepcopy(style) styleBold.fontName = "PTAstraSerifBold" styleCenter = deepcopy(style) styleCenter.alignment = TA_CENTER styleCenter.fontSize = 12 styleCenter.leading = 7 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 = 11 styleT.leading = 4.5 * mm styleT.face = 'PTAstraSerifReg' styleTCenter = deepcopy(styleT) styleTCenter.alignment = TA_CENTER opinion = [ [ Paragraph( '<font size=11>{}<br/>Адрес: {}<br/></font>'.format( hospital_name, hospital_address), styleT), Paragraph('', styleT), ], ] tbl = Table(opinion, 2 * [90 * mm]) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.white), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) objs.append(tbl) opinion = [[Paragraph('Код ОГРН', styleT)]] opinion[0].extend( [Paragraph(f"{hospital_kod_ogrn[i]}", styleT) for i in range(13)]) col_width = [6 * mm for i in range(13)] col_width.insert(0, 22 * mm) tbl = Table(opinion, hAlign='LEFT', rowHeights=6 * mm, colWidths=tuple(col_width)) tbl.setStyle( TableStyle([ ('GRID', (1, 0), (-1, 0), 0.75, colors.black), ('LINEABOVE', (0, 0), (0, -1), 0.5, colors.white), ('LINEBEFORE', (0, 0), (0, -1), 2.5, colors.white), ('LINEBELOW', (0, 0), (0, -1), 1.5, colors.white), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('BOTTOMPADDING', (0, 0), (-1, -1), 3.5 * mm), ('LEFTPADDING', (1, 0), (-1, -1), 1 * mm), ])) objs.append(Spacer(1, 3 * mm)) objs.append(tbl) space_symbol = ' ' objs.append(Spacer(1, 13 * mm)) objs.append(Paragraph('ЗАКЛЮЧИТЕЛЬНЫЙ АКТ', styleCenterBold)) objs.append( Paragraph( 'по результатам проведенного периодического медицинского осмотра ', styleCenterBold)) objs.append( Paragraph('(обследования) работников за 2020 год. ', styleCenterBold)) objs.append(Spacer(1, 4 * mm)) objs.append(Paragraph(f'{date2}', styleBold)) objs.append(Spacer(1, 2 * mm)) objs.append(Paragraph('Комиссией в составе', style)) objs.append( Paragraph( f'Председатель врачебной комиссии {space_symbol * 10} {hospital_name} Кирилюк К.В.', style)) objs.append(Spacer(1, 3 * mm)) objs.append( Paragraph( f'Врач-терапевт {space_symbol * 10} {hospital_name} Шатурская Л.Е.', style)) bold_open = '<font fontname ="PTAstraSerifBold">' bold_close = '</font>' objs.append(Spacer(1, 3 * mm)) objs.append( Paragraph( f'Составлен настоящий акт по результатам проведенного периодического медицинского осмотра (обследования) работников {bold_open}{company_objs.title}{bold_close} ' f'в период: {bold_open}с {date1} по {date2}.{bold_close}', style, )) objs.append(Spacer(1, 3 * mm)) objs.append( Paragraph('1. Число работников организации (предприятия), цеха:', style)) objs = all_and_women(objs, styleT) objs.append(Spacer(1, 3 * mm)) objs.append( Paragraph( '2. Число работников организации (предприятия), цеха, работающих с вредными и (или) опасными веществами и производственными факторами, а так же на работах*:', style)) objs = all_and_women(objs, styleT) objs.append(Spacer(1, 3 * mm)) objs.append( Paragraph( '3. Число работников, подлежащих периодическому медицинскому осмотру (обследованию), работающих в контакте с вредными и (или) опасными веществами и ' 'производственными факторами, а так же на работах* в данном году:', style, )) objs = all_and_women(objs, styleT) objs.append(Spacer(1, 3 * mm)) people = [] count = 0 for dir in dir_obs: count += 1 iss = Issledovaniya.objects.filter(napravleniye=dir).first() fio = dir.client.individual.fio() patient_data = dir.client.get_data_individual() result = protocol_fields_result(iss) position, identified_final = '', '' for i in result: if i["title"] == "Должность": position = i["value"] elif i["title"] == "Заключение по приказу N302н": identified_final = i["value"] people.append([ Paragraph(f'{count}', styleT), Paragraph(f'{fio}', styleT), Paragraph(f'{patient_data["sex"]}', styleT), Paragraph(f'{patient_data["born"]}', styleT), Paragraph(f'{position}', styleT), Paragraph(f'{identified_final}', styleT), ]) objs.append( Paragraph( '4. Число работников, прошедших периодический медицинский осмотр (обследования):', style)) objs = all_and_women(objs, styleT) objs.append(Spacer(1, 3 * mm)) objs.append( Paragraph( 'Поименный список работников, завершивших периодический медицинский осмотр ', style)) opinion = [ [ Paragraph('№', styleT), Paragraph('Ф.И.О.', styleT), Paragraph('пол', styleT), Paragraph('Дата рождения', styleT), Paragraph('Должность', styleT), Paragraph('Заключение', styleT), ], ] opinion.extend(people) tbl = Table( opinion, colWidths=( 7 * mm, 80 * mm, 10 * mm, 25 * mm, 30 * mm, 25 * mm, ), ) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) objs.append(tbl) objs.append(Spacer(1, 3 * mm)) objs.append( Paragraph('5. % охвата периодическими медицинскими осмотрами:', style)) objs = all_and_women(objs, styleT) objs.append(Spacer(1, 3 * mm)) objs.append( Paragraph( '6. Число работников, не завершивших периодический медицинский осмотр (обследования):', style)) objs = all_and_women(objs, styleT) objs.append(Spacer(1, 3 * mm)) objs.append( Paragraph( 'Поименный список работников, не завершивших периодический медицинский осмотр (обследования):', style)) opinion = [ [ Paragraph('№', styleT), Paragraph('Ф.И.О.', styleT), Paragraph('Подразделение предприятия', styleT), ], [ Paragraph('', styleT), Paragraph('', styleT), Paragraph('', styleT), ], ] tbl = Table( opinion, colWidths=( 7 * mm, 120 * mm, 50 * mm, ), ) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) objs.append(tbl) objs.append(Spacer(1, 3 * mm)) objs.append( Paragraph( '7. Число работников, не прошедших периодический медицинский осмотр (обследование):', style)) opinion = [ [ Paragraph('всего,', styleT), Paragraph(' ', styleT), ], [ Paragraph('в том числе женщин', styleT), Paragraph('-', styleT), ], [ Paragraph( 'в том числе по причине: (медосмотр прошел при переводе, после лечения)', styleT), Paragraph('-', styleT), ], [ Paragraph('больничный лист', styleT), Paragraph('-', styleT), ], [ Paragraph('командировка', styleT), Paragraph('-', styleT), ], [ Paragraph('очередной отпуск', styleT), Paragraph('-', styleT), ], [ Paragraph('увольнение', styleT), Paragraph('-', styleT), ], [ Paragraph('отказ от прохождения', styleT), Paragraph('-', styleT), ], ] tbl = Table(opinion, colWidths=(150 * mm, 20 * mm)) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) objs.append(tbl) objs.append(Spacer(1, 3 * mm)) objs.append( Paragraph( 'Поименный список работников, не прошедших периодический медицинский осмотр (обследование):', style)) opinion = [ [ Paragraph('№', styleT), Paragraph('Ф.И.О.', styleT), Paragraph('Подразделение предприятия', styleT), Paragraph('Причина', styleT), ], [ Paragraph('', styleT), Paragraph('', styleT), Paragraph('', styleT), ], ] tbl = Table( opinion, colWidths=( 7 * mm, 80 * mm, 60 * mm, 30 * mm, ), ) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) objs.append(tbl) objs.append(Spacer(1, 3 * mm)) objs.append( Paragraph( '8. Заключение по результатам данного периодического медицинского осмотра (обследования)', style)) objs.append(Spacer(1, 1 * mm)) objs.append(Paragraph('8.1 Сводная таблица N 1:', style)) opinion = [ [ Paragraph( 'Результаты периодического медицинского осмотра (обследования)', styleT), Paragraph('Всего', styleT), Paragraph('В том числе женщин', styleT), ], [ Paragraph( 'Число лиц, профпригодных к работе с вредными и (или) опасными веществами и производственными факторами, к видам работ*', styleT), Paragraph('-', styleT), Paragraph('-', styleT), ], [ Paragraph( 'Число лиц, временно профнепригодных к работе с вредными и (или) опасными веществами и производственными факторами, к видам работ*', styleT), Paragraph('-', styleT), Paragraph('-', styleT), ], ] tbl = Table( opinion, colWidths=( 120 * mm, 27 * mm, 27 * mm, ), ) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) objs.append(tbl) objs = add_needs_text( objs, 'Число лиц, постоянно профнепригодных к работе с вредными и (или) опасными веществами и производственными факторами, к видам работ*', styleT) objs = add_fio_spec_diagnosis(objs, styleT) objs = add_needs_text( objs, 'Число лиц нуждающихся в дообследовании (заключение не дано)', styleT) objs = add_fio_spec_diagnosis(objs, styleT) objs = add_needs_text( objs, 'Число лиц с подозрением на профессиональное заболевание', styleT) objs = add_fio_spec_diagnosis(objs, styleT) objs = add_needs_text( objs, 'Число лиц, нуждающихся в обследовании в центре профпатологии', styleT) objs = add_fio_spec_diagnosis(objs, styleT) objs = add_needs_text(objs, 'Люди', styleT) objs = add_fio_spec_diagnosis(objs, styleT) objs = add_needs_text( objs, 'Число лиц, нуждающихся в амбулаторном обследовании и лечении', styleT) objs = add_fio_spec_diagnosis(objs, styleT) objs = add_needs_text( objs, 'Число лиц, нуждающихся в стационарном обследовании и лечении: (оперативное лечение)', styleT) objs = add_fio_spec_diagnosis(objs, styleT) objs = add_needs_text( objs, 'Число лиц, нуждающихся в санаторно-курортном лечении', styleT) objs = add_fio_spec_diagnosis(objs, styleT) objs = add_needs_text( objs, 'Число лиц, нуждающихся в лечебно-профилактическом питании', styleT) objs = add_fio_spec_diagnosis(objs, styleT) objs = add_needs_text(objs, 'Число лиц, нуждающихся в диспансерном наблюдении', styleT) objs = add_fio_spec_diagnosis(objs, styleT) objs = add_needs_text( objs, 'Число лиц, нуждающихся в направлении на медико-социальную экспертизу', styleT) objs = add_fio_spec_diagnosis(objs, styleT) objs.append(Spacer(1, 5 * mm)) objs.append( Paragraph( '8.3 Выявлено лиц с подозрением на профессиональное заболевание:', style)) opinion = [ [ Paragraph('Nп/п', styleT), Paragraph('Ф.И.О.', styleT), Paragraph('Подразделение предприятия', styleT), Paragraph('Профессия, должность', styleT), Paragraph( 'Вредные и (или) опасные вещества и производственные факторы', styleT), ], ] tbl = Table( opinion, colWidths=( 10 * mm, 90 * mm, 25 * mm, 25 * mm, 25 * mm, ), ) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) objs.append(tbl) objs.append(Spacer(1, 5 * mm)) objs.append( Paragraph( '8.4 Выявлено впервые в жизни хронических соматических заболеваний:', style)) opinion = [ [ Paragraph('№', styleT), Paragraph('Класс заболевания по МКБ-10', styleT), Paragraph('Количество работников (всего)', styleT), ], ] tbl = Table( opinion, colWidths=( 10 * mm, 130 * mm, 30 * mm, ), ) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) objs.append(tbl) objs.append(Spacer(1, 5 * mm)) objs.append( Paragraph( '8.5 Выявлено впервые в жизни хронических профессиональных заболеваний:', style)) opinion = [ [ Paragraph('№', styleT), Paragraph('Класс заболевания по МКБ-10', styleT), Paragraph('Количество работников (всего)', styleT), ], ] tbl = Table( opinion, colWidths=( 10 * mm, 130 * mm, 30 * mm, ), ) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) objs.append(tbl) objs.append(Spacer(1, 5 * mm)) objs.append( Paragraph( '9. Результаты выполнения рекомендаций предыдущего заключительного акта. по результатам проведенного периодического медицинского осмотра (обследования) работников.', style)) opinion = [ [ Paragraph('Nп/п', styleT), Paragraph('Мероприятия', styleT), Paragraph('Подлежало (чел.)', styleT), Paragraph('абс.', styleT), Paragraph('в %', styleT), ], [ Paragraph('1', styleT), Paragraph('Обследование в центре профпатологии', styleT), Paragraph(' ', styleT), Paragraph(' ', styleT), Paragraph(' ', styleT), ], [ Paragraph('2', styleT), Paragraph('Дообследование', styleT), Paragraph(' ', styleT), Paragraph(' ', styleT), Paragraph(' ', styleT), ], [ Paragraph('3', styleT), Paragraph('Лечение и обследование амбулаторное', styleT), Paragraph(' ', styleT), Paragraph(' ', styleT), Paragraph(' ', styleT), ], [ Paragraph('4', styleT), Paragraph('Лечение и обследование стационарное', styleT), Paragraph(' ', styleT), Paragraph(' ', styleT), Paragraph(' ', styleT), ], [ Paragraph('5', styleT), Paragraph('Санаторно-курортное лечение', styleT), Paragraph(' ', styleT), Paragraph(' ', styleT), Paragraph(' ', styleT), ], [ Paragraph('6', styleT), Paragraph('Диетпитание', styleT), Paragraph(' ', styleT), Paragraph(' ', styleT), Paragraph(' ', styleT), ], [ Paragraph('7', styleT), Paragraph('Взято на диспансерное наблюдение', styleT), Paragraph(' ', styleT), Paragraph(' ', styleT), Paragraph(' ', styleT), ], [ Paragraph('8', styleT), Paragraph('Направлено на медико-социальную экспертизу', styleT), Paragraph(' ', styleT), Paragraph(' ', styleT), Paragraph(' ', styleT), ], ] tbl = Table( opinion, colWidths=( 10 * mm, 90 * mm, 25 * mm, 25 * mm, 25 * mm, ), ) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) objs.append(tbl) objs.append(Spacer(1, 5 * mm)) objs.append( Paragraph( '10. Рекомендации работодателю: санитарно-профилактические и оздоровительные мероприятия и т.п.: Соблюдение режима труда и отдыха; сезонная вакцинация ' '(грипп; клещевой энцефалит); зарядка на рабочем мест; закаливание; обеспечить возможность и оказать содействие работникам, нуждающимся в прохождении ' 'соответствующего обследования и лечения; обеспечить возможность и оказать содействие работникам , нуждающимся в санаторно – курортном лечении, в прохождении ' 'соответствующего СКЛ; обеспечить возможность и оказать содействие работникам, нуждающимся диспансерном наблюдении, в прохождении соответствующего наблюдения, ' 'обеспечить соблюдение санитарно- гигиенических норм условий труда.', style, )) doc.build(objs) pdf = buffer.getvalue() buffer.close() return pdf
def primary_reception_get_data(hosp_first_num): # Получение данных из певичного приема hosp_primary_receptions = hosp_get_data_direction(hosp_first_num, site_type=0, type_service='None', level=2) hosp_primary_iss, primary_research_id = None, None if hosp_primary_receptions: hosp_primary_iss = hosp_primary_receptions[0].get('iss') primary_research_id = hosp_primary_receptions[0].get('research_id') titles_field = [ 'Дата поступления', 'Время поступления', 'Виды транспортировки', 'Побочное действие лекарств (непереносимость)', 'Кем направлен больной', 'Вид госпитализации', 'Время через, которое доставлен после начала заболевания, получения травмы', 'Диагноз направившего учреждения', 'Диагноз при поступлении', 'Госпитализирован по поводу данного заболевания', 'Общее состояние', 'Социальный статус', 'Категория льготности', 'Всего госпитализаций', 'Вид травмы', 'Группа крови', 'Резус принадлежность', 'Вес', ] list_values = None if titles_field and hosp_primary_receptions: list_values = get_result_value_iss(hosp_primary_iss, primary_research_id, titles_field) date_entered_value, time_entered_value, type_transport, medicament_allergy = '', '', '', '' who_directed, plan_hospital, extra_hospital, type_hospital = '', '', '', '' time_start_ill, diagnos_who_directed, diagnos_entered = '', '', '' what_time_hospitalized, state, social_status, category_privilege = '', '', '', '' all_hospitalized, type_trauma, blood_group, resus_factor = '', '', '', '' weight = '' if list_values: for i in list_values: if i[3] == 'Дата поступления': date_entered_value = normalize_date(i[2]) continue if i[3] == 'Время поступления': time_entered_value = i[2] continue if i[3] == 'Виды транспортировки': type_transport = i[2] continue if i[3] == 'Побочное действие лекарств (непереносимость)': medicament_allergy = i[2] continue if i[3] == 'Кем направлен больной': who_directed = i[2] continue if i[3] == 'Вид госпитализации': type_hospital = i[2] if type_hospital.lower() == 'экстренная': time_start_ill_obj = get_result_value_iss(hosp_primary_iss, primary_research_id, ['Время через, которое доставлен после начала заболевания, получения травмы']) if time_start_ill_obj: time_start_ill = time_start_ill_obj[0][2] extra_hospital = "Да" plan_hospital = "Нет" else: plan_hospital = "Да" extra_hospital = "Нет" time_start_ill = '' if i[3] == 'Диагноз направившего учреждения': diagnos_who_directed = i[2] continue if i[3] == 'Диагноз при поступлении': diagnos_entered = i[2] continue if i[3] == 'Госпитализирован по поводу данного заболевания': what_time_hospitalized = i[2] continue if i[3] == 'Общее состояние': state = i[2] continue if i[3] == 'Социальный статус': social_status = i[2] continue if i[3] == 'Категория льготности': category_privilege = i[2] continue if i[3] == 'Всего госпитализаций': all_hospitalized = i[2] continue if i[3] == 'Вид травмы': type_trauma = i[2] continue if i[3] == 'Группа крови': blood_group = i[2] continue if i[3] == 'Резус принадлежность': resus_factor = i[2] continue if i[3] == 'Вес': weight = i[2] continue return { 'date_entered_value': date_entered_value, 'time_entered_value': time_entered_value, 'type_transport': type_transport, 'medicament_allergy': medicament_allergy, 'who_directed': who_directed, 'plan_hospital': plan_hospital, 'extra_hospital': extra_hospital, 'type_hospital': type_hospital, 'time_start_ill': time_start_ill, 'diagnos_who_directed': diagnos_who_directed, 'diagnos_entered': diagnos_entered, 'what_time_hospitalized': what_time_hospitalized, 'state': state, 'social_status': social_status, 'category_privilege': category_privilege, 'all_hospitalized': all_hospitalized, 'type_trauma': type_trauma, 'blood_group': blood_group, 'resus_factor': resus_factor, 'weight': weight, }
def hosp_extract_get_data(hosp_last_num): # Получение данных из выписки hosp_extract = hosp_get_data_direction(hosp_last_num, site_type=7, type_service='None', level=2) if not hosp_extract: return {} hosp_extract_iss, extract_research_id, doc_confirm = None, None, None if hosp_extract: hosp_extract_iss = hosp_extract[0].get('iss') doc_confirm = Issledovaniya.objects.get(pk=hosp_extract_iss).doc_confirmation if not doc_confirm: return {} extract_research_id = hosp_extract[0].get('research_id') titles_field = [ 'Время выписки', 'Дата выписки', 'Основной диагноз (описание)', 'Основной диагноз по МКБ', 'Осложнение основного диагноза (описание)', 'Осложнение основного диагноза по МКБ', 'Сопутствующий диагноз (описание)', 'Сопутствующий диагноз по МКБ', 'Исход госпитализации', 'Результат госпитализации', 'Проведено койко-дней', 'Заведующий отделением', 'Палата №', ] list_values = None if titles_field and hosp_extract: list_values = get_result_value_iss(hosp_extract_iss, extract_research_id, titles_field) date_value, time_value = '', '' final_diagnos, other_diagnos, near_diagnos, outcome, final_diagnos_mkb, other_diagnos_mkb, near_diagnos_mkb = '', '', '', '', '', '', '' days_count, result_hospital, manager_depart, room_num = '', '', '', '' if list_values: for i in list_values: if i[3] == 'Дата выписки': date_value = normalize_date(i[2]) if i[3] == 'Время выписки': time_value = i[2] if i[3] == 'Основной диагноз (описание)': final_diagnos = i[2] if i[3] == 'Осложнение основного диагноза (описание)': other_diagnos = i[2] if i[3] == 'Сопутствующий диагноз (описание)': near_diagnos = i[2] if i[3] == 'Исход госпитализации': outcome = i[2] if i[3] == 'Результат госпитализации': result_hospital = i[2] if i[3] == 'Основной диагноз по МКБ': final_diagnos_mkb = str(i[2]) if i[3] == 'Осложнение основного диагноза по МКБ': other_diagnos_mkb = str(i[2]).split(' ')[0] if i[3] == 'Сопутствующий диагноз по МКБ': near_diagnos_mkb = str(i[2]).split(' ')[0] if i[3] == 'Проведено койко-дней': days_count = str(i[2]) if i[3] == 'Заведующий отделением': manager_depart = str(i[2]) if i[3] == 'Палата №': room_num = str(i[2]) doc_fio = doc_confirm.get_fio() return { 'date_value': date_value, 'time_value': time_value, 'final_diagnos': final_diagnos, 'other_diagnos': other_diagnos, 'near_diagnos': near_diagnos, 'outcome': outcome, 'final_diagnos_mkb': final_diagnos_mkb, 'other_diagnos_mkb': other_diagnos_mkb, 'near_diagnos_mkb': near_diagnos_mkb, 'extract_iss': hosp_extract_iss, 'days_count': days_count, 'result_hospital': result_hospital, 'doc_fio': doc_fio, 'manager_depart': manager_depart, 'room_num': room_num, }
def get_finaldata_talon(doc_result_obj): """ Вход результаты врача за определенную дату Выход: стр-ра данных {'№п.п':'номер', 'ФИО пациента':'Иванов Иван Иванович', '№ карты (тип)':'1212 (L2)', 'Данные полиса':'номер;Компаня', 'цель посещения': '(код)', 'первичны прием':'Нет', 'Диагноз по МКБ': '(код)', 'Впервые':'Да', 'Результат обращения':'код', 'Исход':'Код', 'Д-стоит':'коды', 'Д-взят':'коды', 'Д-снят':'коды' 'причина снятия':'', 'Онкоподозрение':'Да' """ fin_oms = 'омс' fin_dms = 'дмс' fin_pay = 'платно' fin_medexam = MEDEXAM_FIN_SOURCE_TITLE fin_disp = 'диспансеризация' fin_budget = 'бюджет' fin_source = OrderedDict() fin_source[fin_oms] = OrderedDict() fin_source[fin_pay] = OrderedDict() fin_source[fin_dms] = OrderedDict() fin_source[fin_medexam] = OrderedDict() fin_source[fin_disp] = OrderedDict() fin_source[fin_budget] = OrderedDict() fin_source_iss = OrderedDict() fin_source_iss[fin_oms] = OrderedDict() fin_source_iss[fin_pay] = OrderedDict() fin_source_iss[fin_dms] = OrderedDict() fin_source_iss[fin_medexam] = OrderedDict() fin_source_iss[fin_disp] = OrderedDict() fin_source_iss[fin_budget] = OrderedDict() oms_count = 0 dms_count = 0 pay_count = 0 disp_count = 0 medexam_count = 0 budget_count = 0 empty = '-' today = utils.timezone.now().date() for i in doc_result_obj: napr_attr = Napravleniya.get_attr(i.napravleniye) temp_dict = OrderedDict() temp_dict_iss = OrderedDict() dict_fsourcce = '' order = '' if napr_attr['istochnik_f'] in ['омс', '']: oms_count += 1 dict_fsourcce = fin_oms order = oms_count elif napr_attr['istochnik_f'] == 'платно': pay_count += 1 dict_fsourcce = fin_pay order = pay_count elif napr_attr['istochnik_f'] == 'дмс': dms_count += 1 dict_fsourcce = fin_dms order = dms_count elif napr_attr['istochnik_f'] == MEDEXAM_FIN_SOURCE_TITLE: medexam_count += 1 dict_fsourcce = fin_medexam order = medexam_count elif napr_attr['istochnik_f'] == 'диспансеризация': disp_count += 1 dict_fsourcce = fin_disp order = disp_count elif napr_attr['istochnik_f'] == 'бюджет': budget_count += 1 dict_fsourcce = fin_budget order = budget_count else: continue polis_who_giv = empty if not napr_attr['polis_who_give'] else napr_attr['polis_who_give'] polis_num = empty if not napr_attr['polis_n'] else napr_attr['polis_n'] temp_dict['client_fio'] = napr_attr['client_fio'] + ', ' + napr_attr['client_bd'] temp_dict['med_exam'] = strdate(i.medical_examination) + ', ' + str(i.napravleniye_id) num_poliklinika = f'\n({napr_attr["number_poliklinika"]})' if napr_attr['number_poliklinika'] else '' temp_dict['card_num'] = napr_attr['card_num'] + num_poliklinika temp_dict['polis_data'] = '<u>' + polis_num + '</u>' + '<br/>' + polis_who_giv temp_dict_iss = temp_dict.copy() temp_dict_iss['research_code'] = i.research.code temp_dict_iss['research_title'] = i.research.title temp_dict['purpose'] = empty if not i.purpose else i.purpose temp_dict['is_first_reception'] = 'Да' if i.research.is_first_reception else 'Нет' temp_dict['diagnos'] = empty if not i.diagnos else i.diagnos temp_dict['first_time'] = 'Да' if i.first_time else 'Нет' temp_dict['result_reception'] = empty if not i.result_reception else i.result_reception temp_dict['outcome_illness'] = empty if not i.outcome_illness else i.outcome_illness # Данные Д-учета disp = DispensaryReg.objects.filter(Q(card=i.napravleniye.client), (Q(date_end=None) | Q(date_end=today))) d_stand = [] d_take = [] d_stop = [] d_whystop = [] if disp: for d in disp: if d.date_end is None and d.date_start != i.time_confirmation.date(): date_start = strdate(d.date_start, short_year=True) date_start = normalize_date(date_start) d_stand.append(f'{d.diagnos}<br/>{date_start}<br/>') elif d.date_end is None and d.date_start == i.time_confirmation.date(): d_take.append(d.diagnos) elif d.date_end == i.time_confirmation.date(): d_stop.append(d.diagnos) d_whystop.append(d.why_stop) temp_dict['d_stand'] = '' if not d_stand else ''.join(d_stand) temp_dict['d_take'] = '' if not d_take else ', '.join(d_take) temp_dict['d_stop'] = '' if not d_stand else ', '.join(d_stop) temp_dict['d_whystop'] = '' if not d_whystop else ', '.join(d_whystop) temp_dict['maybe_onco'] = 'Да' if i.maybe_onco else '' fin_source[dict_fsourcce].update({order: temp_dict}) fin_source_iss[dict_fsourcce].update({order: temp_dict_iss}) if Issledovaniya.objects.filter(parent=i).exists(): temp_dict_iss_copy = deepcopy(temp_dict_iss) add_iss_dict = OrderedDict() for iss in Issledovaniya.objects.filter(parent=i): temp_dict_iss_copy['research_code'] = iss.research.code temp_dict_iss_copy['research_title'] = iss.research.title order = Decimal(str(order)) + Decimal('0.1') add_iss_dict[order] = deepcopy(temp_dict_iss_copy) fin_source_iss[dict_fsourcce].update(add_iss_dict) return [fin_source, fin_source_iss]
def form_01(direction, iss, fwb, doc, leftnone, user=None): # ПАТОЛОГО-АНАТОМИЧЕСКОЕ заключение styleSheet = getSampleStyleSheet() style = styleSheet["Normal"] style.fontName = "FreeSans" style.fontSize = 10 style.alignment = TA_JUSTIFY style_ml = deepcopy(style) style_ml.leftIndent = 5 * mm style_ml.spaceAfter = 0.5 * mm styleBold = deepcopy(style) styleBold.fontName = "FreeSansBold" hospital_name = SettingManager.get("org_title") hospital_address = SettingManager.get("org_address") hospital_kod_ogrn = SettingManager.get("org_ogrn") styleT = deepcopy(style) styleT.alignment = TA_LEFT styleT.fontSize = 10 styleT.leading = 4.5 * mm opinion = [ [ Paragraph(f'<font size=10>{hospital_name}<br/>Адрес: {hospital_address}<br/>ОГРН: {hospital_kod_ogrn} <br/> </font>', styleT), Paragraph('<font size=9 >Медицинская документация <br/> Учетная форма № 014/1-у<br/>Утверждена приказом Минздрава России<br/>от 24 марта 2016г. № 179н</font>', styleT), ], ] tbl = Table(opinion, 2 * [100 * mm]) tbl.setStyle( TableStyle( [ ('GRID', (0, 0), (-1, -1), 0.75, colors.white), ('LEFTPADDING', (1, 0), (-1, -1), 35 * mm), ('LEFTPADDING', (0, 0), (0, -1), 15 * mm), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ] ) ) fwb.append(tbl) fwb.append(Spacer(1, 5 * mm)) history_num = '' if direction.parent and direction.parent.research.is_hospital: history_num = f"(cтационар-{str(direction.parent.napravleniye_id)})" styleCenterBold = deepcopy(style) styleCenterBold.alignment = TA_CENTER styleCenterBold.fontSize = 11.5 styleCenterBold.leading = 15 styleCenterBold.fontName = 'FreeSansBold' fwb.append(Paragraph(f'ПРОТОКОЛ № {direction.pk} {history_num} ', styleCenterBold)) fwb.append(Paragraph('ПРИЖИЗНЕННОГО ПАТОЛОГО-АНАТОМИЧЕСКОГО<br/> ИССЛЕДОВАНИЯ БИОПСИЙНОГО (ОПЕРАЦИОННОГО) МАТЕРИАЛА', styleCenterBold)) short_title = iss.research.short_title fwb.append(Paragraph(f'{short_title.upper()}', styleCenterBold)) open_bold_tag = "<font face =\"FreeSansBold\">" close_tag_bold = "</font>" fwb.append(Spacer(1, 4 * mm)) fwb.append(Paragraph(f'{open_bold_tag}1. Отделение, направившее биопсийный (операционный) материал:{close_tag_bold}{direction.doc.podrazdeleniye.title}', style_ml)) fwb.append(Paragraph(f'{open_bold_tag}2. Фамилия, имя, отчество (при наличии) пациента:{close_tag_bold} {direction.client.individual.fio()}', style_ml)) sex = direction.client.individual.sex if sex == "м": sex = f'{sex}-1' else: sex = f'{sex}-2' space_symbol = ' ' fwb.append(Paragraph(f'{open_bold_tag}3. Пол:{close_tag_bold} {sex}, {space_symbol * 5} {open_bold_tag}4. Дата рождения:{close_tag_bold} {direction.client.individual.bd()}', style_ml)) polis_num = '' polis_issue = '' snils = '' ind_data = direction.client.get_data_individual() if ind_data['oms']['polis_num']: polis_num = ind_data['oms']['polis_num'] if ind_data['oms']['polis_issued']: polis_issue = ind_data['oms']['polis_issued'] if ind_data['snils']: snils = ind_data['snils'] fwb.append(Paragraph(f'{open_bold_tag}5. Полис ОМС:{close_tag_bold}{polis_num}-{polis_issue} {space_symbol * 4} {open_bold_tag}6. СНИЛС:{close_tag_bold} {snils}', style_ml)) address = ind_data['main_address'] fwb.append(Paragraph(f'{open_bold_tag}7. Место регистрации:{close_tag_bold} {address}', style_ml)) fwb.append(Paragraph(f'{open_bold_tag}8. Местность:{close_tag_bold} городская — 1, сельская — 2.', style_ml)) for group in directory.ParaclinicInputGroups.objects.filter(research=iss.research).order_by("order"): results = ParaclinicResult.objects.filter(issledovaniye=iss, field__group=group).order_by("field__order") group_title = False if results.exists(): fwb.append(Spacer(1, 1 * mm)) if group.show_title and group.show_title != "": fwb.append(Paragraph(group.title.replace('<', '<').replace('>', '>'), styleBold)) fwb.append(Spacer(1, 0.25 * mm)) group_title = True for r in results: field_type = r.get_field_type() if field_type == 15: continue else: v = r.value.replace('<', '<').replace('>', '>').replace("\n", "<br/>") v = v.replace('<sub>', '<sub>') v = v.replace('</sub>', '</sub>') v = v.replace('<sup>', '<sup>') v = v.replace('</sup>', '</sup>') v = text_to_bold(v) if field_type == 16: continue if field_type == 17: continue if field_type == 1: v = normalize_date(v) if field_type in [11, 13]: v = '<font face="FreeSans" size="8">{}</font>'.format(v.replace("<br/>", " ")) if r.field.get_title(force_type=field_type) != "": fwb.append( Paragraph( "<font face=\"FreeSansBold\">{}:</font>{}".format(r.field.get_title(force_type=field_type).replace('<', '<').replace('>', '>'), v), style_ml if group_title else style, ) ) else: fwb.append(Paragraph(v, style)) return fwb
def form_01(direction, iss, fwb, doc, leftnone, user=None): # Форма для печати наркозной карты - течения Анестези при операции 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" styleTC = deepcopy(style) styleTC.fontSize = 8 styleTCBold = deepcopy(style) styleTCBold.fontName = "FreeSansBold" fwb.append( Paragraph( f'№ карты : {direction.client.number_with_type()} Пациент : {direction.client.individual.fio()}', styleTCBold)) txt = '' for group in directory.ParaclinicInputGroups.objects.filter( research=iss.research).order_by("order"): results = ParaclinicResult.objects.filter( issledovaniye=iss, field__group=group).exclude(value="").order_by("field__order") if results.exists(): if group.show_title and group.title != "": txt += "<font face=\"FreeSansBold\">{}:</font> ".format( group.title.replace('<', '<').replace('>', '>')) vals = [] for r in results: field_type = r.get_field_type() v = r.value.replace('<', '<').replace('>', '>').replace( "\n", "<br/>") v = v.replace('<sub>', '<sub>') v = v.replace('</sub>', '</sub>') v = v.replace('<sup>', '<sup>') v = v.replace('</sup>', '</sup>') if field_type == 21: fwb.append(Paragraph(txt, style)) fwb.append(Spacer(1, 4 * mm)) txt = '' query_anesthesia = json.dumps({ "research_data": { "iss_pk": iss.pk, "field_pk": r.field.pk } }) query_obj = HttpRequest() query_obj._body = query_anesthesia query_obj.user = user results = directions_anesthesia_load(query_obj) results_json = json.loads(results.content.decode('utf-8')) count_table = 1 if len(results_json['data'][0]) > 18: count_table = ceil(len(results_json['data'][0]) / 18) slice_count = 19 start = 1 temp_record = [] temp_count_table = 0 for v_table in range(count_table): v_table = [] temp_count_table += 1 end = start + slice_count step = 1 for record in results_json['data']: if step == 1: temp_record = [ Paragraph( '{} {}'.format( el[11:16], normalize_date(el[0:10])[0:5]), styleTCBold) for el in record[start:end] ] else: temp_record = [ Paragraph('{}'.format(el), styleTC) for el in record[start:end] ] temp_record.insert( 0, Paragraph('{}'.format(record[0]), styleTCBold)) v_table.append(temp_record) step += 1 cols_width = [ 12.5 * mm for i in range(len(temp_record)) ] cols_width[0] = 37 * mm if temp_count_table == count_table: cols_width[-1] = 15 * mm tbl = Table(v_table, repeatRows=1, colWidths=cols_width, hAlign='LEFT') tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 1.0, colors.black), ('BOTTOMPADDING', (0, 0), (-1, -1), 1 * mm), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ])) fwb.append(tbl) fwb.append(Spacer(1, 1 * mm)) start = end end += slice_count continue if field_type == 1: vv = v.split('-') if len(vv) == 3: v = "{}.{}.{}".format(vv[2], vv[1], vv[0]) if field_type in [11, 13]: v = '<font face="FreeSans" size="8">{}</font>'.format( v.replace("<br/>", " ")) if r.field.get_title(force_type=field_type) != "": vals.append("{}: {}".format( r.field.get_title().replace('<', '<').replace( '>', '>'), text_to_bold(v))) else: vals.append(text_to_bold(v)) txt += "; ".join(vals) txt = txt.strip() if len(txt) > 0 and txt.strip()[-1] != ".": txt += ". " elif len(txt) > 0: txt += " " fwb.append(Paragraph(txt, style)) return fwb
def hosp_get_operation_data(num_dir): hosp_operation = hosp_get_data_direction(num_dir, site_type=3, type_service='None', level=-1) operation_iss_research = [] if hosp_operation: for i in hosp_operation: # найти протоколы по типу операции if (i.get('research_title').lower().find('операци') != -1 or i.get('research_title').lower().find('манипул') != -1) and i['date_confirm']: operation_iss_research.append({'iss': i['iss'], 'research': i['research_id']}) titles_field = [ 'Название операции', 'Название манипуляции', 'Дата проведения', 'Время начала', 'Время окончания', 'Метод обезболивания', 'Осложнения', 'Код операции', 'Код манипуляции', 'Оперативное вмешательство', 'Описание манипуляции', 'Код анестезиолога', 'Категория сложности', 'Диагноз после оперативного лечения', 'МКБ 10', 'Оперировал', 'Код хирурга', 'Код врача', 'Заключение', ] list_values = [] operation_result = [] if titles_field and operation_iss_research and hosp_operation: for i in operation_iss_research: list_values.append(get_result_value_iss(i['iss'], i['research'], titles_field)) operation_result = [] for fields_operation in list_values: pk_iss_operation = fields_operation[0][1] operation_data = { 'name_operation': '', 'date': '', 'time_start': '', 'time_end': '', 'anesthesia method': '', 'complications': '', 'doc_fio': '', 'code_operation': '', 'code_doc_anesthesia': '', 'plan_operation': '', 'diagnos_after_operation': '', 'mkb10': '', 'category_difficult': '', 'doc_code': '', 'final': '', } iss_obj = Issledovaniya.objects.filter(pk=pk_iss_operation).first() if not iss_obj.time_confirmation: continue operation_data['doc_fio'] = iss_obj.doc_confirmation_fio operation_data['doc_code'] = None if not Issledovaniya.objects.get(pk=pk_iss_operation) else Issledovaniya.objects.get(pk=pk_iss_operation).doc_confirmation.personal_code if operation_data['doc_code'] == 0: operation_data['doc_code'] = '' category_difficult = '' for field in fields_operation: if field[3] == 'Название операции' or field[3] == 'Название манипуляции': operation_data['name_operation'] = field[2] continue if field[3] == 'Дата проведения': operation_data['date'] = normalize_date(field[2]) continue if field[3] == 'Время начала': operation_data['time_start'] = field[2] continue if field[3] == 'Время окончания': operation_data['time_end'] = field[2] continue if field[3] == 'Метод обезболивания': operation_data['anesthesia method'] = field[2] continue if field[3] == 'Осложнения': operation_data['complications'] = field[2] continue if field[3] == 'Код операции': operation_data['code_operation'] = field[2] continue if field[3] == 'Код манипуляции': operation_data['code_operation'] = field[2] continue if field[3] == 'Код анестезиолога': operation_data['code_doc_anesthesia'] = field[2] continue if field[3] == 'Оперативное вмешательство': operation_data['plan_operation'] = field[2] continue if field[3] == 'Категория сложности': operation_data['category_difficult'] = f"Сложность - {field[2]}" continue if field[3] == 'Диагноз после оперативного лечения': operation_data['diagnos_after_operation'] = field[2] continue if field[3] == 'МКБ 10': operation_data['mkb10'] = field[2] continue if field[3] == 'Оперировал': if field[2]: operation_data['doc_fio'] = field[2] continue if field[3] == 'Код хирурга' or field[3] == 'Код врача': if field[2]: operation_data['doc_code'] = field[2] continue if field[3] == 'Заключение': if field[2]: operation_data['final'] = field[2] continue operation_data['name_operation'] = f"{operation_data['name_operation']} {category_difficult}" operation_result.append(operation_data.copy()) return operation_result
def form_04(request_data): """ Форма 030/у - контрольная карта диспансерного учета """ reg_dipensary = DispensaryReg.objects.get(pk=request_data["reg_pk"]) ind_card = reg_dipensary.card patient_data = ind_card.get_data_individual() hospital: Hospitals = request_data["hospital"] hospital_name = hospital.safe_short_title hospital_address = hospital.safe_address hospital_kod_ogrn = hospital.safe_ogrn 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'))) buffer = BytesIO() # doc = SimpleDocTemplate(buffer, pagesize=A4, leftMargin=25 * mm, rightMargin=5 * mm, topMargin=6 * mm, bottomMargin=6 * mm, allowSplitting=1, title="Форма {}".format("025/у")) doc = SimpleDocTemplate(buffer, pagesize=landscape(A5), leftMargin=25 * mm, rightMargin=5 * mm, topMargin=6 * mm, bottomMargin=6 * mm, allowSplitting=1, title="Форма {}".format("030/у")) 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 = 7 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' styleTCenter = deepcopy(styleT) styleTCenter.alignment = TA_CENTER print_district = '' if SettingManager.get("district", default='True', default_type='b'): if ind_card.district is not None: print_district = 'Уч: {}'.format(ind_card.district.title) opinion = [ [ Paragraph( '<font size=11>{}<br/>Адрес: {}<br/>ОГРН: {} <br/><u>{}</u> </font>' .format(hospital_name, hospital_address, hospital_kod_ogrn, print_district), styleT), Paragraph( '<font size=9 >Код формы по ОКУД:<br/>Код организации по ОКПО:<br/>' 'Медицинская документация<br/>Учетная форма N 030/у</font>', styleT), ], ] tbl = Table(opinion, 2 * [90 * mm]) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.white), ('LEFTPADDING', (1, 0), (-1, -1), 80), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) objs.append(tbl) space_symbol = ' ' 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 = '' diagnos = reg_dipensary.diagnos illnes = reg_dipensary.illnes doctor = reg_dipensary.doc_start_reg doc_speciality = "____________________" if doctor.specialities: doc_speciality = f"<u>{doctor.specialities.title}</u>" doc_fio = doctor.get_full_fio() date_start = reg_dipensary.date_start date_start = strdate(date_start, short_year=True) date_start = normalize_date(date_start) date_end = reg_dipensary.date_end if date_end: date_end = strdate(date_end, short_year=True) date_end = normalize_date(date_end) else: date_end = "" why_stop = reg_dipensary.why_stop if reg_dipensary.what_times == 1: what_times = "впервые - 1" elif reg_dipensary.what_times == 2: what_times = "повторно - 2" else: what_times = "впервые - 1, повторно - 2" if reg_dipensary.how_identified == 1: how_identified = "обращении за лечением - 1" elif reg_dipensary.how_identified == 2: how_identified = "профилактическом осмотре - 2" else: how_identified = "обращении за лечением - 1, профилактическом осмотре - 2" content_title = [ Indenter(left=0 * mm), Spacer(1, 1 * mm), Paragraph('КОНТРОЛЬНАЯ КАРТА, ', styleCenter), Paragraph( 'ДИСПАНСЕРНОГО НАБЛЮДЕНИЯ {}<font size=14>№</font><font fontname="PTAstraSerifBold" size=17> <u>{}</u></font><font size=14> {}</font>' .format(3 * space_symbol, p_card_num, p_card_type), styleCenter, ), Spacer(1, 7 * mm), Paragraph( f'1. Диагноз заболевания, по поводу которого пациент подлежит диспансерному наблюдению: <u>{illnes}</u> Код по МКБ-10: <u>{diagnos}</u>', style), Paragraph('2.Дата заполнения медицинской карты: _____________________', style), Paragraph( f'3. Специальность врача: {doc_speciality} {4 * space_symbol} 4.ФИО врача: <u>{doc_fio}</u>', style), Paragraph( f'5. Дата установления диагноза: <u>{date_start}</u> {4 * space_symbol} 6. Диагноз установлен: {what_times}', style), Paragraph(f'7. Заболевание выявлено при: {how_identified}', style), Paragraph( f'8. Дата начала диспансерного наблюдения <u>{date_start}</u> {4 * space_symbol} 9. Дата прекращения диспансерного наблюдения {date_end}', style), Paragraph( f'10. Причины прекращения диспансерного наблюдения: <u>{why_stop}</u>', style), Paragraph( "11. Фамилия, имя, отчество: <font size=11.7 fontname ='PTAstraSerifBold'> {} </font> " .format(patient_data['fio']), style), Paragraph( '12. Пол: {} {} 13. Дата рождения: {}'.format( patient_data['sex'], 3 * space_symbol, patient_data['born']), style), Paragraph( '14. Место регистрации: {}'.format(patient_data['main_address']), style), Paragraph('15. Код категории льготы:__________', style), ] objs.extend(content_title) objs.append(Spacer(1, 5 * mm)) research_need = DispensaryPlan.objects.filter(diagnos=diagnos).order_by( 'research__title', 'speciality__title') researches_list = [] specialities_list = [] visits_result = "" visits_plan = "" visits_research = VisitPurpose.objects.filter( title__icontains="диспансерн") current_year = datetime.datetime.now().year year = request_data.get('year', current_year) for i in research_need: if i.speciality: results = research_last_result_every_month( Researches.objects.filter(speciality=i.speciality), ind_card, year, visits_research) dates_result = "" dates_plan = "" plans = DispensaryRegPlans.objects.filter( card=ind_card, research=None, speciality=i.speciality, date__year=year).order_by('date') for p in plans: dates_plan = f"{dates_plan} {strfdatetime(p.date, '%d.%m')};" for r in range(12): if results[r]: if r < 9: dates_result = f"{dates_result} {results[r]['date']}.0{r + 1};" else: dates_result = f"{dates_result} {results[r]['date']}.{r + 1};" if i.is_visit: visits_result = dates_result visits_plan = dates_plan else: specialities_list.append( f'{i.speciality.title}-{dates_plan}-{dates_result}') if i.research: dates_plan = " " plans = DispensaryRegPlans.objects.filter( card=ind_card, research=None, speciality=i.speciality, date__year=year).order_by('date') for p in plans: dates_plan = f"{dates_plan} {strfdatetime(p.date, '%d.%m')};" results = research_last_result_every_month([i.research], ind_card, year) dates_result = "" for r in range(12): if results[r]: if r < 9: dates_result = f"{dates_result} {results[r]['date']}.0{r + 1};" else: dates_result = f"{dates_result} {results[r]['date']}.{r + 1};" researches_list.append( f'{i.research.title}-{dates_plan}-{dates_result}') researches_list.extend(specialities_list) visits_result = visits_result.split(';')[:-1] visits_plan = visits_plan.split(';')[:-1] visits_plan = [Paragraph(i, styleT) for i in visits_plan] if len(visits_plan) < 7: for i in range(7 - len(visits_plan)): visits_plan.append(Paragraph('', styleT)) visits_plan.insert(0, Paragraph('Назначено явиться', styleT)) visits_result = [Paragraph(i, styleT) for i in visits_result] if len(visits_result) < 7: for i in range(7 - len(visits_result)): visits_result.append(Paragraph('', styleT)) visits_result.insert(0, Paragraph('Явился(лась)', styleT)) opinion = [ [ Paragraph('Даты посещений', styleTCenter), Paragraph('', styleT), Paragraph('', styleT), Paragraph('', styleT), Paragraph('', styleT), Paragraph('', styleT), Paragraph('', styleT), Paragraph('', styleT), ], visits_plan, visits_result, ] tbl = Table(opinion, colWidths=(40 * mm, 20 * mm, 20 * mm, 20 * mm, 20 * mm, 20 * mm, 20 * mm, 20 * mm)) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.black), ('SPAN', (0, 0), (-1, 0)), ])) objs.append(tbl) objs.append(PageBreak()) objs.append(Paragraph('оборотная сторона ф. N 030/у', style)) objs.append(Spacer(1, 5 * mm)) visit_date = [Paragraph('', styleT) for i in range(7)] visit_date.insert(0, Paragraph('Даты посещений', styleTCenter)) visits_plan = [Paragraph('', styleT) for i in range(7)] visits_plan.insert(0, Paragraph('Назначено явиться', styleT)) visits_result = [Paragraph('', styleT) for i in range(7)] visits_result.insert(0, Paragraph('Явился(лась)я', styleT)) opinion = [visit_date, visits_plan, visits_result] tbl = Table(opinion, colWidths=(40 * mm, 20 * mm, 20 * mm, 20 * mm, 20 * mm, 20 * mm, 20 * mm, 20 * mm)) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.black), ('SPAN', (0, 0), (-1, 0)), ])) objs.append(tbl) objs.append(Spacer(1, 5 * mm)) objs.append(Paragraph('17. Сведения об изменении диагноза', style)) objs.append(Spacer(1, 2 * mm)) empty_para = [Paragraph('', styleT) for i in range(4)] opinion = [ [ Paragraph('Дата', styleTCenter), Paragraph('Формулировка диагноза', styleT), Paragraph('Код по МКБ-10', styleT), Paragraph('ФИО врача', styleT), ], empty_para, empty_para, ] tbl = Table(opinion, colWidths=(30 * mm, 85 * mm, 30 * mm, 35 * mm), rowHeights=6 * mm) tbl.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.black), ])) objs.append(tbl) objs.append(Spacer(1, 3 * mm)) objs.append( Paragraph( '18. Сопутствующие заболевания ______________________________________________________________________', style)) objs.append(Spacer(1, 2 * mm)) objs.append( Paragraph( '___________________________________________________________________________________________________', style)) objs.append(Spacer(1, 1 * mm)) objs.append(Paragraph('19. Лечебно-профилактические мероприятия', style)) opinion_title = [ Paragraph('N п/п', styleT), Paragraph('Мероприятия', styleT), Paragraph('Дата<br/> начала', styleT), Paragraph('Дата<br/>окончания', styleT), Paragraph('Отметка о<br/>выполнении', styleT), Paragraph('ФИО врача', styleT), ] opinion = [[ '', Paragraph(f'{i.split("-")[0]}', styleT), '', Paragraph(f'{i.split("-")[2]}', styleT), '' ] for i in researches_list] opinion.insert(0, opinion_title) tbl = Table(opinion, colWidths=(10 * mm, 60 * mm, 25 * mm, 25 * mm, 23 * mm, 35 * mm)) tbl.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.black), ])) objs.append(tbl) def first_pages(canvas, document): canvas.saveState() canvas.restoreState() def later_pages(canvas, document): canvas.saveState() canvas.restoreState() doc.build(objs, onFirstPage=first_pages, onLaterPages=later_pages) pdf = buffer.getvalue() buffer.close() return pdf
def form_03(direction: Napravleniya, iss: Issledovaniya, fwb, doc, leftnone, user=None): # Рапорт ВМП styleSheet = getSampleStyleSheet() style = styleSheet["Normal"] style.fontName = "PTAstraSerifReg" style.fontSize = 12 style.alignment = TA_JUSTIFY style_ml = deepcopy(style) style_ml.spaceAfter = 2 * mm styleCenter = deepcopy(style) styleCenter.alignment = TA_CENTER styleBold = deepcopy(style) styleBold.fontName = "PTAstraSerifBold" styleCenterBold = deepcopy(style) styleCenterBold.alignment = TA_CENTER styleCenterBold.fontSize = 12 styleCenterBold.leading = 15 styleCenterBold.fontName = 'PTAstraSerifBold' styleT = deepcopy(style) styleT.alignment = TA_LEFT styleT.leading = 5 * mm pdfmetrics.registerFont( TTFont('PTAstraSerifBold', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf'))) pdfmetrics.registerFont( TTFont('PTAstraSerifReg', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf'))) fwb.append(Spacer(1, 3 * mm)) title_field_result = ["Кому", "От кого", "Отделение", "Дата"] data_fields_result = fields_result_only_title_fields( iss, title_field_result) main_manager, from_who, departmnet, date_protocol = "", "", "", "" for i in data_fields_result: if i["title"] == "Кому": main_manager = i["value"] if i["title"] == "От кого": from_who = i["value"] if i["title"] == "Отделение": departmnet = i["value"] if i["title"] == "Дата": date_protocol = normalize_date(i["value"]) opinion = [ [ Paragraph(' ', styleT), Paragraph(f'{main_manager}<br/>от<br/>{from_who}', styleT), ], ] tbl = Table(opinion, colWidths=[120 * mm, 60 * mm]) tbl.setStyle( TableStyle([('GRID', (0, 0), (-1, -1), 0.75, colors.white), ('LEFTPADDING', (1, 0), (-1, -1), 2 * mm), ('VALIGN', (0, 0), (-1, -1), 'TOP')])) fwb.append(tbl) fwb.append(Spacer(1, 3 * mm)) open_bold_tag = "<font face =\"PTAstraSerifBold\">" close_tag_bold = "</font>" fwb.append(Spacer(1, 4 * mm)) fwb.append(Paragraph('Рапорт', styleCenterBold)) fwb.append(Spacer(1, 4 * mm)) fwb.append( Paragraph( f'Довожу до Вашего сведения, что в отделение {departmnet} поступил пациент, нуждающийся в оказании ВМП', style_ml)) fwb.append(Spacer(1, 2 * mm)) fwb.append( Paragraph( f'{open_bold_tag}ФИО пациента:{close_tag_bold} {direction.client.individual.fio()}', style_ml)) sex = direction.client.individual.sex space_symbol = ' ' fwb.append( Paragraph( f'{open_bold_tag}Дата рождения:{close_tag_bold} {direction.client.individual.bd()} {open_bold_tag} - Пол:{close_tag_bold} {sex}, {space_symbol * 5}', style_ml)) polis_num = '' polis_issue = '' snils = '' ind_data = direction.client.get_data_individual() if ind_data['oms']['polis_num']: polis_num = ind_data['oms']['polis_num'] if ind_data['oms']['polis_issued']: polis_issue = ind_data['oms']['polis_issued'] if ind_data['snils']: snils = ind_data['snils'] fwb.append( Paragraph(f'{open_bold_tag}Полис ОМС:{close_tag_bold} {polis_num}', style_ml)) fwb.append( Paragraph( f'{open_bold_tag}Название страховой медицинской организации:{close_tag_bold} {polis_issue}', style_ml)) fwb.append( Paragraph(f'{open_bold_tag}СНИЛС:{close_tag_bold} {snils}', style_ml)) address = ind_data['main_address'] fwb.append( Paragraph( f'{open_bold_tag}Адрес регистрации:{close_tag_bold} {address}', style_ml)) fwb = fields_result(iss, fwb, title_field_result) fwb.append(Spacer(1, 7 * mm)) opinion = [ [ Paragraph('Лечащий врач', styleT), Paragraph('___________________', styleT), Paragraph(f'{iss.doc_confirmation.get_full_fio()}', styleT), ], [ Paragraph(f'{date_protocol} ', styleT), Paragraph('', styleT), Paragraph('', styleT), ], ] tbl = Table(opinion, hAlign='LEFT', colWidths=[57 * mm, 45 * mm, 57 * mm], rowHeights=[10 * mm, 10 * mm]) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.white), ('LEFTPADDING', (0, 0), (-1, -1), 2 * mm), ('VALIGN', (0, 0), (-1, -1), 'BOTTOM'), ])) fwb.append(tbl) return fwb
def form_01(direction, iss, fwb, doc, leftnone, user=None): # Форма для печати дневников в 3 колонки 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" date, time = '', '' patient_fio = direction.client.individual.fio() i = 0 title_opinion = [] column_data = [] txt = "" pw = doc.width append_table = False for group in directory.ParaclinicInputGroups.objects.filter( research=iss.research).order_by("order"): i += 1 results = ParaclinicResult.objects.filter( issledovaniye=iss, field__group=group).exclude(value="").order_by("field__order") if i <= 3: if results.exists(): fwb.append(Spacer(1, 1 * mm)) title_opinion.append( Paragraph( group.title.replace('<', '<').replace('>', '>'), styleBold)) column_result = '' for r in results: field_type = r.get_field_type() if field_type == 1 and r.field.get_title( force_type=field_type) == 'Дата осмотра': date = normalize_date(r.value) continue if field_type == 20 and r.field.get_title( force_type=field_type) == 'Время осмотра': time = r.value continue if field_type == 21: continue v = r.value.replace('<', '<').replace('>', '>').replace( "\n", "<br/>") v = text_to_bold(v) column_result = column_result + "<font face=\"FreeSans\">{}:</font>{}".format( r.field.get_title(force_type=field_type).replace( '<', '<').replace('>', '>'), v) + ";" if i == 1: column_result += "<br/>" column_data.append(Paragraph(column_result, style)) if i > 3: if not append_table: column_data += [''] * (3 - len(column_data)) opinion = [title_opinion, column_data] tbl = Table(opinion, colWidths=(33 * mm, 100 * mm, 50 * mm)) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 1.0, colors.white), ('BOTTOMPADDING', (0, 0), (-1, -1), 1.5 * mm), ('RIGHTPADDING', (0, 0), (-1, -1), 5 * mm), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) hosp_dir = hosp_get_curent_hosp_dir(iss.pk) fwb.append(Spacer(1, 2 * mm)) fwb.append( Paragraph( 'Пациент: {}. (№:{})'.format(patient_fio, hosp_dir), style)) fwb.append( Paragraph('Дата-время осмотра: {} в {}'.format(date, time), style)) fwb.append(Spacer(1, 0.5 * mm)) fwb.append(tbl) append_table = True if results.exists(): if group.show_title and group.title != "": txt += "<font face=\"FreeSansBold\">{}:</font> ".format( group.title.replace('<', '<').replace('>', '>')) txt += "<br/>" fwb.append(Spacer(1, 2 * mm)) fwb.append(Paragraph(txt, style)) txt = '' vals = [] for r in results: field_type = r.get_field_type() v = r.value.replace('<', '<').replace('>', '>').replace( "\n", "<br/>") v = v.replace('<sub>', '<sub>') v = v.replace('</sub>', '</sub>') v = v.replace('<sup>', '<sup>') v = v.replace('</sup>', '</sup>') if field_type == 1: vv = v.split('-') if len(vv) == 3: v = "{}.{}.{}".format(vv[2], vv[1], vv[0]) if field_type in [11, 13]: v = '<font face="FreeSans" size="8">{}</font>'.format( v.replace("<br/>", " ")) if field_type == 15: txt += "; ".join(vals) fwb.append(Paragraph(txt, style)) txt = '' vals = [] date_now1 = datetime.datetime.strftime( datetime.datetime.now(), "%y%m%d%H%M%S") dir_param = SettingManager.get("dir_param", default='/tmp', default_type='s') file_tmp = os.path.join( dir_param, f'field_{date_now1}_{r.pk}.png') fwb.append(Spacer(1, 2 * mm)) img = html_to_pdf(file_tmp, r.value, pw, leftnone) fwb.append(img) os.remove(file_tmp) continue if field_type == 16: v = json.loads(v) if not v['directions']: continue txt += "; ".join(vals) fwb.append(Paragraph(txt, style)) txt = '' vals = [] fwb.append(Spacer(1, 2 * mm)) fwb.append(Paragraph(r.field.get_title(), styleBold)) aggr_lab = lab_iss_to_pdf(v) fwb.extend(aggr_lab) continue if field_type == 24: previous_laboratory = previous_laboratory_result(v) if not previous_laboratory: continue fwb.append(Spacer(1, 2 * mm)) fwb.append( Paragraph( "<font face=\"FreeSansBold\">{}</font>".format( r.field.get_title( force_type=field_type).replace( '<', '<').replace('>', '>')), style)) fwb.extend(previous_laboratory) continue if field_type in [26, 25]: if v: fwb.append(Spacer(1, 2 * mm)) fwb.append( Paragraph( "<font face=\"FreeSansBold\">{}</font>". format( r.field.get_title( force_type=field_type).replace( '<', '<').replace('>', '>')), style)) fwb = previous_doc_refferal_result(v, fwb) continue if field_type == 17: if v: v = json.loads(v) if not v['directions']: continue v = text_iss_to_pdf(v, True) v = text_to_bold(v) if r.field.get_title(force_type=field_type) != "": vals.append("{}: {}".format( r.field.get_title().replace('<', '<').replace( '>', '>'), v)) else: vals.append(v) txt += "; ".join(vals) txt = txt.strip() if len(txt) > 0 and txt.strip()[-1] != ".": txt += ". " elif len(txt) > 0: txt += " " fwb.append(Paragraph(txt, style)) txt = '' fwb.append(Spacer(1, 0.5 * mm)) if i <= 3: column_data += [''] * (3 - len(column_data)) opinion = [title_opinion, column_data] tbl = Table(opinion, colWidths=(33 * mm, 100 * mm, 50 * mm)) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 1.0, colors.white), ('BOTTOMPADDING', (0, 0), (-1, -1), 1.5 * mm), ('RIGHTPADDING', (0, 0), (-1, -1), 5 * mm), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) hosp_dir = hosp_get_curent_hosp_dir(iss.pk) fwb.append(Spacer(1, 2 * mm)) fwb.append( Paragraph('Пациент: {}. (№:{})'.format(patient_fio, hosp_dir), style)) fwb.append( Paragraph('Дата-время осмотра: {} в {}'.format(date, time), style)) fwb.append(Spacer(1, 0.5 * mm)) fwb.append(tbl) fwb.append(Spacer(1, 0.5 * mm)) return fwb