Example #1
0
 def get_visit_date(self):
     if not self.time_confirmation:
         return ""
     if not self.napravleniye.visit_date or not self.napravleniye.visit_who_mark:
         self.napravleniye.visit_date = timezone.now()
         self.napravleniye.visit_who_mark = self.doc_confirmation
         self.napravleniye.save()
     return strdate(self.napravleniye.visit_date)
Example #2
0
def gen_band_pdf(request):
    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')))

    napr_id = json.loads(request.GET["napr_id"])
    direction = Napravleniya.objects.filter(pk=napr_id[0]).first()
    dir_create = strdate(direction.data_sozdaniya)
    iss = Issledovaniya.objects.values('research__title').filter(napravleniye=direction).first()
    individual_birthday = strdate(direction.client.individual.birthday)
    individual_fio = direction.client.individual.fio()

    buffer = BytesIO()
    c = canvas.Canvas(buffer, pagesize=(152 * mm, 25 * mm))
    c.setFont('PTAstraSerifBold', 12)
    c.drawString(3.5 * mm, 18 * mm, '{}, {}'.format(individual_fio, individual_birthday))
    c.setFont('PTAstraSerifBold', 13)
    c.drawString(50 * mm, 12 * mm, '№: {}'.format(napr_id[0]))
    c.setFont('PTAstraSerifReg', 11)
    c.drawString(50 * mm, 8 * mm, '{}'.format(iss['research__title']))
    c.drawString(50 * mm, 4 * mm, 'поступил: {}'.format(dir_create))

    barcodeEAN = eanbc.Ean13BarcodeWidget(napr_id[0] + 460000000000, humanReadable=0, barHeight=11 * mm, barWidth=1.25)
    d = Drawing()
    d.add(barcodeEAN)
    renderPDF.draw(d, c, 0 * mm, 4 * mm)

    c.showPage()
    c.save()
    pdf = buffer.getvalue()
    buffer.close()

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="band.pdf"'
    response.write(pdf)

    return response
Example #3
0
def get_plan_operations_by_patient(request):
    request_data = json.loads(request.body)
    start_date = datetime.combine(current_time(), dtime.min)
    patient_card = Card.objects.filter(pk=request_data['card_pk'])[0]
    result = PlanOperations.objects.filter(
        patient_card=patient_card, date__gte=start_date).order_by('date')
    data = [{
        'direction': i.direction,
        'hirurg': i.doc_operate.get_fio(),
        'hirurg_pk': i.doc_operate.pk,
        'date': strdate(i.date),
        'type_operation': i.type_operation,
        'pk_plan': i.pk,
        'cancel': i.canceled,
    } for i in result]

    return JsonResponse({"data": data})
Example #4
0
def save(request):
    request_data = json.loads(request.body)
    pk = int(request_data.get("pk", -1))
    value = str(request_data.get("value", '')).strip()
    with_confirm = bool(request_data.get("withConfirm", True))

    direction = Napravleniya.objects.filter(pk=pk).first()

    if not direction:
        return JsonResponse({'ok': False, 'message': 'Документ не найден'})

    if not value and with_confirm:
        return JsonResponse({'ok': False, 'message': 'Некорректное значение'})

    iss = Issledovaniya.objects.filter(
        napravleniye=direction, time_confirmation__isnull=True
    ).filter(
        Q(research__podrazdeleniye=request.user.doctorprofile.podrazdeleniye)
        | Q(research__is_doc_refferal=True)
        | Q(research__is_treatment=True)
        | Q(research__is_gistology=True)
        | Q(research__is_stom=True)
        | Q(research__is_gistology=True)
        | Q(research__is_form=True))

    confirmed_at = None
    ok = False
    message = 'Неизвестная ошибка'
    with transaction.atomic():
        for i in iss:
            ParaclinicResult.objects.filter(issledovaniye=i).delete()

            for g in ParaclinicInputGroups.objects.filter(research=i.research):
                for f in ParaclinicInputField.objects.filter(group=g):
                    f_result = ParaclinicResult(issledovaniye=i,
                                                field=f,
                                                value="")
                    f_result.value = value
                    f_result.field_type = f.field_type
                    f_result.save()

            i.doc_save = request.user.doctorprofile
            i.time_save = timezone.now()

            if with_confirm:
                i.doc_confirmation = request.user.doctorprofile
                i.time_confirmation = timezone.now()

            if i.napravleniye:
                i.napravleniye.qr_check_token = None
                i.napravleniye.save(update_fields=['qr_check_token'])
            i.save()
            i.napravleniye.sync_confirmed_fields()
            confirmed_at = strdate(i.time_confirmation)
            ok = True
            message = None

    return JsonResponse({
        'ok': ok,
        'message': message,
        'value': value,
        'slaveConfirm': confirmed_at,
    })
Example #5
0
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]
Example #6
0
def add_template(iss: Issledovaniya, direction, offset=0):
    pdfmetrics.registerFont(
        TTFont('PTAstraSerifBold',
               os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf')))
    pdfmetrics.registerFont(
        TTFont('PTAstraSerifReg',
               os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf')))
    styleSheet = getSampleStyleSheet()
    style = styleSheet["Normal"]
    style.fontName = "PTAstraSerifReg"
    style.fontSize = 12
    style.alignment = TA_JUSTIFY

    style_ml = deepcopy(style)
    style_ml.leftIndent = 5 * mm
    style_ml.spaceAfter = 0.5 * mm

    styleBold = deepcopy(style)
    styleBold.fontName = "PTAstraSerifBold"

    hospital_full_name = SettingManager.get("rmis_orgname")
    hospital_short_name = SettingManager.get("org_title")
    hospital_doc_confirm = iss.doc_confirmation.hospital

    styleT = deepcopy(style)
    styleT.alignment = TA_LEFT
    styleT.fontSize = 10
    styleT.leading = 4.5 * mm

    text = (
        f'<font size=10>{hospital_full_name}<br/>{hospital_short_name}<br/>Адрес: {hospital_doc_confirm.address}'
        f'{hospital_doc_confirm.phones}<br/>Лицензия на осуществление медицинской деятельности <br/> {hospital_doc_confirm.license_data}<br/>'
        f'</font>')

    styleCenterBold = deepcopy(style)
    styleCenterBold.alignment = TA_CENTER
    styleCenterBold.fontSize = 12
    styleCenterBold.leading = 15
    styleCenterBold.fontName = 'PTAstraSerifBold'

    styleCenter = deepcopy(styleCenterBold)
    styleCenter.fontName = 'PTAstraSerifReg'
    obj = []
    obj.append(
        FrameData(0, (-15 - offset) * mm, 120, 28, text=text, style=style))
    obj.append(
        FrameData(0, (-20 - offset) * mm,
                  180,
                  5,
                  text='Медицинская справка',
                  style=styleCenterBold))
    obj.append(
        FrameData(0, (-23 - offset) * mm,
                  180,
                  5,
                  text=f'№ {direction.pk}',
                  style=styleCenter))
    obj.append(
        FrameData(
            0,
            (-32 - offset) * mm,
            180,
            15,
            text=
            'по результатам обследования водителя<br/>транспартнго средства (кандидата в водители траспортного средства)<br/><u>врачом-психиатром</u>',
            style=styleCenter,
        ))
    result = protocol_fields_result(iss)
    main_address, identified_final = '', ''
    for i in result:
        if i["title"] == "Медицинское заключение":
            identified_final = i["value"].replace('<',
                                                  '&lt;').replace('>', '&gt;')
        elif i["title"] == "Место регистрации":
            main_address = i["value"]

    text = (
        f'1. Фамилия, имя, отчество (при наличии): {direction.client.individual.fio()}<br/>'
        f'2. Дата рождения: {direction.client.individual.bd()}<br/>'
        f'3. Место регистрации: {main_address}<br/>'
        f'4. Медицинское заключение: {identified_final}')
    obj.append(
        FrameData(0, (-60 - offset) * mm, 180, 40, text=text, style=style))

    date_confirm = strdate(iss.time_confirmation)
    opinion = [
        [
            Paragraph(f'<u>{date_confirm}</u>', styleCenter),
            Paragraph(
                f'<u>врач-психиатр, {iss.doc_confirmation.get_full_fio()}</u>',
                styleCenter),
        ],
        [
            Paragraph('(Дата)', styleCenter),
            Paragraph('Должность (ФИО)', styleCenter),
        ],
    ]
    tbl = Table(opinion, colWidths=(90 * mm, 90 * mm))

    tbl.setStyle(
        TableStyle([
            ('GRID', (0, 0), (-1, -1), 1.0, colors.white),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 0.5 * mm),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    obj.append(
        FrameData(0, (-75 - offset) * mm,
                  180,
                  20,
                  text=text,
                  style=style,
                  tbl=tbl))

    return obj
Example #7
0
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 = '&nbsp;'
    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. Фамилия, имя, отчество:&nbsp;  <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
Example #8
0
def receive_one_by_one(request):
    request_data = json.loads(request.body)
    lab_pk = request_data["currentLaboratory"]

    if lab_pk >= 0:
        lab = Podrazdeleniya.objects.get(pk=lab_pk)
    else:
        lab = {"title": "Все лаборатории", "pk": lab_pk}

    pk = request_data['q']
    direction = request_data["workMode"] == "direction"
    if not direction:
        pks = [pk]
    else:
        tubes(request, direction_implict_id=pk)
        pks = [
            x.pk for x in (TubesRegistration.objects.filter(
                issledovaniya__napravleniye__pk=pk).filter(
                    Q(issledovaniya__napravleniye__hospital=request.user.
                      doctorprofile.hospital)
                    | Q(issledovaniya__napravleniye__hospital__isnull=True)).
                           distinct())
        ]
    ok_objects = []
    ok_researches = []
    invalid_objects = []
    last_n = None
    for p in pks:
        if TubesRegistration.objects.filter(
                pk=p).exists() and Issledovaniya.objects.filter(
                    tubes__id=p).exists():
            tube = TubesRegistration.objects.get(pk=p)
            podrs = sorted(
                list(
                    set([
                        x.research.podrazdeleniye.get_title()
                        for x in tube.issledovaniya_set.all()
                    ])))
            if lab_pk < 0 or tube.issledovaniya_set.first(
            ).research.get_podrazdeleniye() == lab:
                tube.clear_notice(request.user.doctorprofile)
                status = tube.day_num(request.user.doctorprofile,
                                      request_data["nextN"])
                if status["new"]:
                    last_n = status["n"]

                ok_objects.append({
                    "pk": p,
                    "new": status["new"],
                    "labs": podrs,
                    "receivedate": strdate(tube.time_recive),
                })

                ok_researches.extend([
                    x.research.title
                    for x in Issledovaniya.objects.filter(tubes__id=p)
                ])
            else:
                invalid_objects.append(
                    f"Пробирка {p} для другой лаборатории: {', '.join(podrs)}")
        else:
            invalid_objects.append(f"Пробирка {p} не найдена")
    if direction and Napravleniya.objects.filter(pk=pk).exists():
        d = Napravleniya.objects.get(pk=pk)
        if Issledovaniya.objects.filter(napravleniye_id=pk,
                                        research__is_gistology=True).exists():
            is_new = False
            if not d.time_gistology_receive:
                d.time_gistology_receive = timezone.now()
                d.doc_gistology_receive = request.user.doctorprofile
                d.save()
                Log.log(
                    d.pk,
                    122000,
                    request.user.doctorprofile,
                    {
                        'gistology_receive_time':
                        strdate(d.time_gistology_receive),
                    },
                )
                is_new = True
            ok_objects.append({
                "pk": pk,
                "new": is_new,
                "labs": ['Гистология'],
                "receivedate": strdate(d.time_gistology_receive),
            })
            ok_researches.extend([
                x.research.get_title() for x in Issledovaniya.objects.filter(
                    napravleniye_id=pk, research__is_gistology=True)
            ])
    if not ok_objects and not invalid_objects:
        invalid_objects.append(f"Ёмкости по запросу {pk} не найдены")
    return JsonResponse({
        "ok": ok_objects,
        "researches": sorted(list(set(ok_researches))),
        "invalid": invalid_objects,
        "lastN": last_n,
    })
Example #9
0
def receive_obo(request):
    lpk = int(
        request.GET.get("lab_pk", -2) if request.method ==
        "GET" else request.POST.get("lab_pk", -2))
    if lpk >= 0:
        lab = Podrazdeleniya.objects.get(pk=lpk)
    else:
        lab = {"title": "Все лаборатории", "pk": lpk}
    if request.method == "GET":
        labs = Podrazdeleniya.objects.filter(
            p_type=Podrazdeleniya.LABORATORY).exclude(
                title="Внешние организации").order_by("title")
        if lpk >= 0 and lab.p_type != Podrazdeleniya.LABORATORY:
            lab = labs[0]
        return render(request, 'dashboard/receive_one-by-one.html', {
            "labs": labs,
            "lab": lab
        })
    ret = []
    if request.POST["pk"].isdigit():
        pk = int(request.POST["pk"])
        direction = request.POST.get("direction", "0") == "1"
        if not direction:
            pks = [pk]
            ret = []
        else:
            tubes(request, direction_implict_id=pk)
            pks = [
                x.pk for x in TubesRegistration.objects.filter(
                    issledovaniya__napravleniye__pk=pk).distinct()
            ]
        for p in pks:
            if TubesRegistration.objects.filter(
                    pk=p).exists() and Issledovaniya.objects.filter(
                        tubes__id=p).exists():
                tube = TubesRegistration.objects.get(pk=p)
                if tube.getstatus(one_by_one=True):
                    podrs = sorted(
                        list(
                            set([
                                x.research.podrazdeleniye.get_title()
                                for x in tube.issledovaniya_set.all()
                            ])))
                    if lpk < 0 or tube.issledovaniya_set.first(
                    ).research.get_podrazdeleniye() == lab:
                        tube.clear_notice(request.user.doctorprofile)
                        status = tube.day_num(request.user.doctorprofile,
                                              int(request.POST["num"]))
                        result = {
                            "pk":
                            p,
                            "r":
                            1,
                            "n":
                            status["n"],
                            "new":
                            status["new"],
                            "labs":
                            podrs,
                            "receivedate":
                            strdate(tube.time_recive),
                            "researches": [
                                x.research.title
                                for x in Issledovaniya.objects.filter(
                                    tubes__id=p)
                            ]
                        }
                    else:
                        result = {"pk": p, "r": 2, "labs": podrs}
                else:
                    n = tube.issledovaniya_set.first().napravleniye
                    dw = n.doc or n.doc_who_create
                    if dw:
                        otd = dw.podrazdeleniye
                        if n.doc_who_create:
                            otd = n.doc_who_create.podrazdeleniye
                    else:
                        otd = ''
                    result = {
                        "pk": p,
                        "r": 4,
                        "otd": str(otd),
                        "direction":
                        tube.issledovaniya_set.first().napravleniye.pk
                    }
            else:
                result = {"pk": p, "r": 3}
            ret.append(result)
        if not direction:
            ret = {"r": 3} if len(ret) == 0 else ret[0]
    return JsonResponse(ret, safe=False)
Example #10
0
def print_direction(c: Canvas, n, dir: Napravleniya, format_a6: bool = False):
    xn, yn = 0, 0
    if not format_a6:
        if n % 2 != 0:
            xn = 1
        if n > 2:
            yn = 1

    barcode = eanbc.Ean13BarcodeWidget(dir.pk + 460000000000,
                                       humanReadable=0,
                                       barHeight=17)
    bounds = barcode.getBounds()
    width = bounds[2] - bounds[0]
    height = bounds[3] - bounds[1]
    d = Drawing(width, height)
    d.add(barcode)
    paddingx = 15
    ac = dir.is_all_confirm()
    canc = dir.cancel
    visit = dir.visit_date is not None
    if ac or canc or visit:
        c.saveState()
        c.setFillColorRGB(0, 0, 0, 0.2)
        c.rotate(45)
        if xn == 0 and yn == 1:
            ox = w / 2 + 40 * mm
            oy = h / 2 - 30 * mm
        elif xn == 0 and yn == 0:
            ox = w / 2 - 65 * mm
            oy = 13.5 * mm
        elif xn == 1 and yn == 0:
            ox = w - 95.75 * mm
            oy = 13.5 * mm - h / 4
        else:
            ox = w + 9.25 * mm
            oy = h / 2 - 30 * mm - h / 4
        c.setFont('OpenSansBold', 50)
        s = 'ОТМЕНЕНО'
        if ac:
            s = 'ИСПОЛНЕНО'
        elif visit:
            s = 'ПОСЕЩЕНО'
        c.drawString(ox, oy, s)
        c.restoreState()

    c.setFont('OpenSans', 10)
    c.drawCentredString(w / 2 - w / 4 + (w / 2 * xn),
                        (h / 2 - height - 5) + (h / 2) * yn,
                        dir.hospital_short_title)

    c.setFont('OpenSans', 8)
    c.drawCentredString(
        w / 2 - w / 4 + (w / 2 * xn), (h / 2 - height - 15) + (h / 2) * yn,
        "(%s. %s)" % (dir.hospital_address, dir.hospital_phones))

    c.setFont('OpenSans', 14)
    c.drawCentredString(
        w / 2 - w / 4 + (w / 2 * xn), (h / 2 - height - 30) + (h / 2) * yn,
        "Направление" + ("" if not dir.imported_from_rmis else " из РМИС"))

    renderPDF.draw(d, c, w / 2 - width + (w / 2 * xn) - paddingx / 3 - 5 * mm,
                   (h / 2 - height - 57) + (h / 2) * yn)

    c.setFont('OpenSans', 20)
    c.drawString(paddingx + (w / 2 * xn), (h / 2 - height) + (h / 2) * yn - 57,
                 "№ " + str(dir.pk))  # Номер направления

    c.setFont('OpenSans', 9)
    c.drawString(
        paddingx + (w / 2 * xn), (h / 2 - height - 70) + (h / 2) * yn,
        "Создано: " + strdate(dir.data_sozdaniya) + " " +
        strtime(dir.data_sozdaniya)[:5])
    history_num = dir.history_num
    additional_num = dir.additional_num
    if history_num and len(history_num) > 0:
        c.drawRightString(w / 2 * (xn + 1) - paddingx,
                          (h / 2 - height - 70) + (h / 2) * yn,
                          "№ истории: " + history_num)
    elif additional_num and len(additional_num) > 0:
        c.drawRightString(w / 2 * (xn + 1) - paddingx,
                          (h / 2 - height - 70) + (h / 2) * yn,
                          f"({str(additional_num).strip()})")
    elif dir.client.number_poliklinika and len(
            dir.client.number_poliklinika) > 0:
        c.drawRightString(w / 2 * (xn + 1) - paddingx,
                          (h / 2 - height - 70) + (h / 2) * yn,
                          f"({str(dir.client.number_poliklinika).strip()})")

    if dir.history_num and len(dir.history_num) > 0:
        c.drawRightString(w / 2 * (xn + 1) - paddingx,
                          (h / 2 - height - 70) + (h / 2) * yn,
                          "№ истории: " + dir.history_num)

    c.drawString(paddingx + (w / 2 * xn), (h / 2 - height - 80) + (h / 2) * yn,
                 "ФИО: " + dir.client.individual.fio())

    c.drawRightString(w / 2 * (xn + 1) - paddingx,
                      (h / 2 - height - 80) + (h / 2) * yn,
                      "Пол: " + dir.client.individual.sex)

    c.drawRightString(
        w / 2 * (xn + 1) - paddingx, (h / 2 - height - 90) + (h / 2) * yn,
        "Д/р: {} ({})".format(dir.client.individual.bd(),
                              dir.client.individual.age_s(direction=dir)))

    c.drawString(
        paddingx + (w / 2 * xn), (h / 2 - height - 90) + (h / 2) * yn,
        "{}: {}".format("ID" if dir.client.base.is_rmis else "Номер карты",
                        dir.client.number_with_type()))
    diagnosis = dir.diagnos.strip()[:35]
    if not dir.imported_from_rmis:
        if diagnosis != "":
            c.drawString(
                paddingx + (w / 2 * xn),
                (h / 2 - height - 100) + (h / 2) * yn,
                ("" if dir.vich_code == "" else
                 ("Код: " + dir.vich_code + "  ")) + "Диагноз (МКБ 10): " +
                ("не указан" if diagnosis == "-" else diagnosis),
            )
        elif dir.vich_code != "":
            c.drawString(paddingx + (w / 2 * xn),
                         (h / 2 - height - 100) + (h / 2) * yn,
                         "Код: " + dir.vich_code)
        if dir.istochnik_f:
            c.drawString(
                paddingx + (w / 2 * xn), (h / 2 - height - 110) + (h / 2) * yn,
                "Источник финансирования: " + dir.client.base.title + " - " +
                dir.istochnik_f.title)
        else:
            c.drawString(paddingx + (w / 2 * xn),
                         (h / 2 - height - 110) + (h / 2) * yn,
                         "Источник финансирования: ")
    else:
        nds = 0
        if diagnosis != "":
            c.drawString(paddingx + (w / 2 * xn),
                         (h / 2 - height - 100) + (h / 2) * yn,
                         "Диагноз (МКБ 10): " + diagnosis)
            nds = 5
        if dir.imported_org:
            c.drawString(paddingx + (w / 2 * xn),
                         (h / 2 - height - 105 - nds) + (h / 2) * yn,
                         "Организация: " + dir.imported_org.title)

    issledovaniya = dir.issledovaniya_set.all()

    vid = []
    has_descriptive = False
    has_doc_refferal = False
    need_qr_code = False
    for i in issledovaniya:
        rtp = i.research.reversed_type
        if rtp < -1:
            has_doc_refferal = True
            rt = {
                -2: 'Консультации',
                -3: 'Лечение',
                -4: 'Стоматология',
                -5: 'Стационар',
                -6: 'Микробиология',
                -9998: 'Морфология',
                -9: 'Формы',
                -11: 'Заявления',
                -12: 'Мониторинги',
            }[rtp]
            # if rtp == -6:
            #     has_micro = True
        else:
            rt = i.research.podrazdeleniye.get_title()
        if rt not in vid:
            vid.append(rt)
            if i.research.podrazdeleniye and i.research.podrazdeleniye.p_type == Podrazdeleniya.PARACLINIC:
                has_descriptive = True
                if i.research.podrazdeleniye.can_has_pacs:
                    need_qr_code = True

    c.drawString(paddingx + (w / 2 * xn),
                 (h / 2 - height - 120) + (h / 2) * yn,
                 "Вид: " + ", ".join(vid))

    if dir.purpose:
        c.drawRightString(w / 2 * (xn + 1) - paddingx,
                          (h / 2 - height - 120) + (h / 2) * yn,
                          "Цель: " + dir.get_purpose_display())

    if dir.external_organization:
        c.drawRightString(w / 2 * (xn + 1) - paddingx,
                          (h / 2 - height - 134) + (h / 2) * yn,
                          dir.external_organization.title)

    if dir.parent and dir.parent.research.is_hospital:
        c.setFont('OpenSansBold', 8)
        c.drawRightString(w / 2 * (xn + 1) - paddingx,
                          (h / 2 - height - 129) + (h / 2) * yn,
                          ("Стационар-" + str(dir.parent.napravleniye_id)))
    c.setFont('OpenSans', 9)

    styleSheet = getSampleStyleSheet()

    all_iss = issledovaniya.count()
    max_f = 9
    min_f = 7
    max_res = 36

    max_off = max_f - min_f
    font_size = max_f - (max_off * (all_iss / max_res))

    styleSheet["BodyText"].leading = font_size + 0.5
    data = []

    values = []

    service_locations = {}

    n = 0
    for v in issledovaniya:
        n += 1
        service_location_title = "" if not v.service_location else v.service_location.title
        if service_location_title:
            if service_location_title not in service_locations:
                service_locations[service_location_title] = []
            service_locations[service_location_title].append(n)
        values.append({
            "title":
            v.research.get_title(),
            "full_title":
            v.research.title,
            "sw":
            v.research.sort_weight,
            "count":
            v.how_many,
            "comment":
            v.localization.title if v.localization else v.comment,
            "n":
            n,
            "g":
            -1 if not v.research.fractions_set.exists() else
            v.research.fractions_set.first().relation_id,
            "info":
            v.research.paraclinic_info,
            "hospital_department_replaced_title":
            v.hospital_department_replaced_title,
        })

    one_sl = len(service_locations) <= 1

    tw = w / 2 - paddingx * 2
    m = 0
    ns = {}
    if has_descriptive or has_doc_refferal:
        tmp = [
            Paragraph(
                '<font face="OpenSansBold" size="8">%s</font>' %
                ("Исследование" if not has_doc_refferal else "Назначение"),
                styleSheet["BodyText"]),
            Paragraph('<font face="OpenSansBold" size="8">Информация</font>',
                      styleSheet["BodyText"]),
        ]
        data.append(tmp)
        colWidths = [int(tw * 0.5), int(tw * 0.5)]
        values.sort(key=lambda l: l["full_title"])

        for v in values:
            ns[v["n"]] = v["n"]
            tmp = [
                Paragraph(
                    '<font face="OpenSans" size="8">' +
                    ("" if one_sl else "№{}: ".format(v["n"])) +
                    xh.fix(v["full_title"]) +
                    ("" if not v["comment"] else
                     " <font face=\"OpenSans\" size=\"" +
                     str(font_size * 0.8) +
                     "\">[{}]</font>".format(v["comment"])) +
                    ("" if not v["hospital_department_replaced_title"] else
                     f"<br/>Направлен в: {v['hospital_department_replaced_title']}"
                     ) + "</font>",
                    styleSheet["BodyText"],
                ),
                Paragraph(
                    '<font face="OpenSans" size="8">' + xh.fix(v["info"]) +
                    "</font>", styleSheet["BodyText"]),
            ]
            data.append(tmp)
        m = 8
    else:
        colWidths = [int(tw / 2), int(tw / 2)]
        c.drawString(paddingx + (w / 2 * xn),
                     (h / 2 - height - 134) + (h / 2) * yn, "Назначения: ")
        c.setStrokeColorRGB(0, 0, 0)
        c.setLineWidth(1)
        values.sort(key=lambda l: (l["g"], l["sw"]))

        n_rows = int(len(values) / 2)

        normvars = []
        c_cnt = nc_cnt = 0
        for i in range(0, len(values) + 1):
            if (i + 1) % 2 == 0:
                nc_cnt += 1
                if nc_cnt + n_rows < len(values):
                    normvars.append(values[nc_cnt + n_rows])
            else:
                normvars.append(values[c_cnt])
                c_cnt += 1

        p = Paginator(normvars, 2)
        n = 1
        for pg_num in p.page_range:
            pg = p.page(pg_num)
            tmp = []
            for obj in pg.object_list:
                ns[obj["n"]] = n
                tmp.append(
                    Paragraph(
                        '<font face="OpenSans" size="' + str(font_size) +
                        '">' + ("" if one_sl else "№{}: ".format(n)) +
                        obj["title"] +
                        ("" if not obj["count"] or obj["count"] == 1 else
                         " ({}шт.)".format(str(obj["count"]))) +
                        ("" if not obj["comment"] else
                         " <font face=\"OpenSans\" size=\"" +
                         str(font_size * 0.8) +
                         "\">[{}]</font>".format(obj["comment"])) + "</font>",
                        styleSheet["BodyText"],
                    ))
                n += 1
            if len(pg.object_list) < 2:
                tmp.append(
                    Paragraph(
                        '<font face="OpenSans" size="' + str(font_size) +
                        '"></font>', styleSheet["BodyText"]))
            data.append(tmp)

    t = Table(data, colWidths=colWidths)
    t.setStyle(
        TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('TEXTCOLOR', (0, -1), (-1, -1), colors.black),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('LEFTPADDING', (0, 0), (-1, -1), 4),
            ('TOPPADDING', (0, 0), (-1, -1), 0.5),
            ('RIGHTPADDING', (0, 0), (-1, -1), 2),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 2),
        ]))
    t.canv = c
    wt, ht = t.wrap(0, 0)
    t.drawOn(c, paddingx + (w / 2 * xn),
             ((h / 2 - height - 138 + m) + (h / 2) * yn - ht))

    c.setFont('OpenSans', 8)
    if not has_descriptive and not has_doc_refferal:
        c.drawString(paddingx + (w / 2 * xn),
                     (h / 2 - height - 138 + m) + (h / 2) * yn - ht - 10,
                     "Всего назначено: " + str(len(issledovaniya)))

    if service_locations:
        n = 0 if has_descriptive or has_doc_refferal else 1
        if one_sl:
            c.drawString(paddingx + (w / 2 * xn), (h / 2 - height - 138 + m) +
                         (h / 2) * yn - ht - 14 - n * 10,
                         "Место: " + list(service_locations)[0])
        else:
            c.drawString(paddingx + (w / 2 * xn), (h / 2 - height - 138 + m) +
                         (h / 2) * yn - ht - 14 - n * 10,
                         "Места оказания услуг:")
            for title in service_locations:
                n += 1
                c.drawString(
                    paddingx + (w / 2 * xn),
                    (h / 2 - height - 138 + m) + (h / 2) * yn - ht - 14 -
                    n * 10,
                    title + " – услуги " + ', '.join(
                        map(lambda x: "№{}".format(ns[x]),
                            service_locations[title])),
                )

    if need_qr_code:
        qr_value = translit(dir.client.individual.fio(), 'ru', reversed=True)
        qr_code = qr.QrCodeWidget(qr_value)
        qr_code.barWidth = 70
        qr_code.barHeight = 70
        qr_code.qrVersion = 1
        d = Drawing()
        d.add(qr_code)
        renderPDF.draw(d, c, paddingx + (w / 2 * xn) + 200, 32 + (h / 2) * yn)

    nn = 0
    if not dir.imported_from_rmis:
        if dir.doc_who_create and dir.doc_who_create != dir.doc:
            nn = 9
            c.drawString(
                paddingx + (w / 2 * xn), 13 + (h / 2) * yn,
                Truncator("Выписал: %s, %s" %
                          (dir.doc_who_create.get_fio(),
                           dir.doc_who_create.podrazdeleniye.title)).chars(63))

        if dir.doc:
            c.drawString(
                paddingx + (w / 2 * xn), 22 + (h / 2) * yn + nn,
                "Отделение: " +
                Truncator(dir.get_doc_podrazdeleniye_title()).chars(50))
            c.drawString(paddingx + (w / 2 * xn), 13 + (h / 2) * yn + nn,
                         "Л/врач: " + dir.doc.get_fio())
    else:
        c.drawString(paddingx + (w / 2 * xn), 31 + (h / 2) * yn + nn,
                     "РМИС#" + dir.rmis_number)
        c.drawString(paddingx + (w / 2 * xn), 22 + (h / 2) * yn + nn,
                     "Создал направление: " + dir.doc_who_create.get_fio())
        c.drawString(paddingx + (w / 2 * xn), 13 + (h / 2) * yn + nn,
                     dir.doc_who_create.podrazdeleniye.title)

    c.setFont('OpenSans', 7)
    c.setLineWidth(0.25)