Exemplo n.º 1
0
def load_logs(request):
    import slog.models as slog

    result = {"data": []}

    if request.method == "POST":
        check_new = int(request.POST["checknew"])
        states = json.loads(request.POST["searchdata"])
    else:
        check_new = int(request.GET["checknew"])
        states = json.loads(request.GET["searchdata"])

    obj = slog.Log.objects.all()
    if states["user"] > -1:
        obj = obj.filter(user__pk=states["user"])
    if states["user"] == -2:
        obj = obj.filter(user__isnull=True)

    if states["type"] != -1:
        obj = obj.filter(type=states["type"])
    if states["pk"] != "-1":
        obj = obj.filter(key__contains=states["pk"])

    if check_new == 0:
        offset = int(request.POST.get("offset", request.GET.get("offset", 0)))
        size = int(request.POST.get("size", request.GET.get("size", 0)))
        rows = obj.order_by("-pk")[offset:size + offset]
    else:
        pkgt = int(request.POST.get("last_n", request.GET.get("last_n", 0)))
        rows = obj.filter(pk__gt=pkgt).order_by("pk")
    for row in rows:
        tmp_object = {
            "id":
            row.pk,
            "user_fio":
            "Система" if not row.user else
            (row.user.get_fio() + ", " + row.user.user.username),
            "user_pk":
            row.user_id or "",
            "key":
            row.key,
            "body":
            row.body,
            "type":
            row.get_type_display(),
            "time":
            strdatetime(row.time),
        }
        result["data"].append(tmp_object)

    result["s"] = states
    return JsonResponse(result)
Exemplo n.º 2
0
def history(request):
    data = data_parse(request.body, {'offset': int, 'pk': int, 'filterResearches': list}, {'pk': None, 'offset': None, 'filterResearches': None})
    offset: Optional[int] = data[0]
    pk: Optional[int] = data[1]
    filter_researches: Optional[list] = data[2]
    limit = 40
    end = offset + limit if not pk else None
    hospital: Hospitals = request.user.doctorprofile.get_hospital()
    directions = Napravleniya.objects.filter(issledovaniya__research__is_monitoring=True, hospital=hospital).order_by('-data_sozdaniya')
    if pk:
        directions = directions.filter(pk=pk)
    if filter_researches and len(filter_researches) > 0:
        directions = directions.filter(issledovaniya__research_id__in=filter_researches)
    rows = []
    next_offset = None

    directions_chunk = directions[offset:end] if not pk else directions

    d: Napravleniya
    for d in directions_chunk:
        direction_params = DirectionParamsResult.objects.filter(napravleniye=d).order_by('order')

        i: Issledovaniya = d.issledovaniya_set.all()[0]

        rows.append(
            {
                "pk": d.pk,
                "title": i.research.get_title(),
                "lastActionAt": strdatetime(i.time_confirmation or i.time_save or d.data_sozdaniya),
                "isSaved": d.has_save(),
                "isConfirmed": d.is_all_confirm(),
                "author": str(d.doc_who_create or d.doc or ""),
                "params": [
                    {
                        "title": " → ".join([x for x in [x.field.group.title, x.field.title] if x]),
                        "value": x.string_value_normalized,
                    }
                    for x in direction_params
                ],
            }
        )

    total_count = None

    if end:
        total_count = directions.count()
        if total_count > end:
            next_offset = end

    return JsonResponse({"nextOffset": next_offset, "rows": rows, "totalCount": total_count})
Exemplo n.º 3
0
    def handle(self, *args, **kwargs):
        fp = kwargs["path"]

        self.stdout.write("Path: " + fp)
        with open(fp) as json_file:
            data = json.load(json_file)
            dt = utils.current_time()
            d = utils.strdatetime(dt)
            title = f"{d}-{data['title']}"
            r = Researches(title=title,
                           code=data['code'],
                           short_title=data['short_title'])
            r.save()
            for group in data['paraclinic_input_groups']:
                group_current = ParaclinicInputGroups(
                    research=r,
                    title=group["title"],
                    show_title=group["show_title"],
                    order=group["order"],
                    hide=group["hide"])
                group_current.save()
                for f in group['paraclinic_input_field']:
                    field = ParaclinicInputField(
                        group=group_current,
                        title=f['title'],
                        order=f['order'],
                        default_value=f['default_value'],
                        lines=f['lines'],
                        field_type=f['field_type'],
                        for_extract_card=f['for_extract_card'],
                        for_talon=f['for_talon'],
                        helper=f['helper'],
                        input_templates=f['input_templates'],
                        required=f['required'],
                        hide=f['hide'],
                        short_title=f.get('short_title', ''),
                    )
                    field.save()
Exemplo n.º 4
0
def form_02(request_data):
    # Вызов врача
    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=landscape(A4), leftMargin=20 * mm, rightMargin=12 * mm, topMargin=6 * mm, bottomMargin=4 * mm, allowSplitting=1, title="Форма – Вызов врача")

    styleSheet = getSampleStyleSheet()
    style = styleSheet["Normal"]
    style.fontName = "PTAstraSerifReg"
    style.fontSize = 10.5
    style.leading = 12
    style.spaceAfter = 0 * mm
    style.alignment = TA_LEFT
    style.firstLineIndent = 0
    style.spaceAfter = 1.5 * mm

    styleCenterBold = deepcopy(style)
    styleCenterBold.alignment = TA_CENTER
    styleCenterBold.fontSize = 16
    styleCenterBold.leading = 15
    styleCenterBold.face = 'PTAstraSerifBold'

    styleTB = deepcopy(style)
    styleTB.firstLineIndent = 0
    styleTB.alignment = TA_CENTER
    styleTB.fontName = "PTAstraSerifBold"

    styleCenter = deepcopy(style)
    styleCenter.firstLineIndent = 0
    styleCenter.alignment = TA_CENTER

    date = request_data["date"]
    district = int(request_data.get("district", -1) or -1)
    is_canceled = int(request_data["cancel"])
    doc_assigned = int(request_data.get("doc", -1) or -1)
    purpose_id = int(request_data.get("purpose", -1) or -1)
    hospital = int(request_data.get("hospital_pk", -1) or -1)
    cancel = True if is_canceled == 0 else False

    is_external = int(request_data.get("external", 1))
    external = True if is_external == 0 else False
    out_call = ''
    if external:
        out_call = " <u>внешние</u>"

    objs = []
    objs.append(Paragraph(f"Вызова (обращения){out_call} {normalize_dash_date(date)}", styleCenterBold))
    objs.append(Spacer(1, 5 * mm))

    time_start = f'{date} {request_data.get("time_start", "00:00")}'
    time_end = f'{date} {request_data.get("time_end", "23:59")}'
    datetime_start = datetime.datetime.strptime(time_start, '%Y-%m-%d %H:%M')
    datetime_end = datetime.datetime.strptime(time_end, '%Y-%m-%d %H:%M')
    if external:
        doc_call = DoctorCall.objects.filter(
            create_at__range=[datetime_start, datetime_end],
        )
    else:
        doc_call = DoctorCall.objects.filter(create_at__range=[datetime_start, datetime_end])
    doc_call = doc_call.filter(is_external=external, cancel=cancel)

    if hospital > -1:
        doc_call = doc_call.filter(hospital__pk=hospital)
    if doc_assigned > -1:
        doc_call = doc_call.filter(doc_assigned__pk=doc_assigned)
    if district > -1:
        doc_call = doc_call.filter(district_id__pk=district)
    if purpose_id > -1:
        doc_call = doc_call.filter(purpose=purpose_id)

    if external:
        doc_call = doc_call.order_by('hospital', 'pk')
    elif hospital + doc_assigned + district + purpose_id > -4:
        doc_call = doc_call.order_by("pk")
    else:
        doc_call = doc_call.order_by("district__title")

    strike_o = ""
    strike_cl = ""

    if cancel:
        strike_o = "<strike>"
        strike_cl = "</strike>"

    opinion = [
        [
            Paragraph('№ п/п', styleTB),
            Paragraph('Пациент', styleTB),
            Paragraph('Адрес', styleTB),
            Paragraph('Участок', styleTB),
            Paragraph('Телефон', styleTB),
            Paragraph('Услуга', styleTB),
            Paragraph('Примечание', styleTB),
            Paragraph('Врач', styleTB),
            Paragraph('Цель', styleTB),
        ],
    ]

    count = 0
    what_purpose = ''
    who_doc_assigned = ''
    for i in doc_call:
        count += 1
        title = ''
        if i.district:
            title = i.district.title
        if i.doc_assigned:
            who_doc_assigned = i.doc_assigned.get_full_fio()
        if i.purpose:
            what_purpose = i.get_purpose_display()
        org = ""
        if i.hospital:
            org = f"<br/>{i.hospital.short_title or i.title}"

        create_at = strdatetime(i.create_at)

        opinion.append(
            [
                Paragraph(f"{strike_o}{count}{strike_cl}", styleCenter),
                Paragraph(f"{strike_o}{i.client.individual.fio()} ({i.client.number_with_type()}){org}<br/>{create_at}{strike_cl}", styleCenter),
                Paragraph(f"{strike_o}{i.address.replace('<', '&lt;').replace('>', '&gt;')}{strike_cl}", styleCenter),
                Paragraph(f"{strike_o}{title}{strike_cl}", style),
                Paragraph(f"{strike_o}{(i.phone or i.client.phone).replace('<', '&lt;').replace('>', '&gt;')}{strike_cl}", style),
                Paragraph(f"{strike_o}{i.research.title}{strike_cl}", style),
                Paragraph(f"{strike_o}{i.comment.replace('<', '&lt;').replace('>', '&gt;')[:400]}{strike_cl}", style),
                Paragraph(f"{strike_o}{who_doc_assigned}{strike_cl}", style),
                Paragraph(f"{strike_o}{what_purpose}{strike_cl}", style),
            ]
        )

    tbl = Table(opinion, colWidths=(10 * mm, 40 * mm, 35 * mm, 15 * mm, 25 * mm, 40 * mm, 35 * mm, 30 * mm, 25 * mm), splitByRow=1, repeatRows=1)

    tbl.setStyle(
        TableStyle(
            [
                ('GRID', (0, 0), (-1, -1), 1.0, colors.black),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 1.5 * mm),
                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ]
        )
    )

    objs.append(tbl)
    doc.build(objs)
    pdf = buffer.getvalue()
    buffer.close()

    return pdf
Exemplo n.º 5
0
def direction_info(request):
    if request.is_ajax():
        yesno = {True: "да", False: "нет"}
        data = []
        pk = request.GET.get("pk", "-1")

        try:
            pk = int(pk)
        except ValueError:
            pk = -1

        if pk != -1 and Napravleniya.objects.filter(pk=pk).exists():
            dir = Napravleniya.objects.get(pk=pk)
            data.append({
                'type':
                "Направление №%s" % pk,
                'events':
                [[[
                    "title",
                    strdatetime(dir.data_sozdaniya) + " Направление создано"
                ], ["Создатель", get_userdata(dir.doc_who_create)],
                  ["От имени", "" if not dir.doc else get_userdata(dir.doc)],
                  [
                      "Пациент",
                      "%s, %s, Пол: %s" %
                      (dir.client.individual.fio(), dir.client.individual.bd(),
                       dir.client.individual.sex)
                  ],
                  [
                      "Карта",
                      "%s %s" % (dir.client.number, dir.client.base.title)
                  ], ["Архив", yesno[dir.client.is_archive]],
                  [
                      "Источник финансирования",
                      "" if not dir.istochnik_f else dir.istochnik_f.title
                  ], ["Диагноз", dir.diagnos],
                  [
                      "Направление создано на основе направления из РМИС",
                      yesno[dir.imported_from_rmis]
                  ],
                  [
                      "Направивляющая организация из РМИС",
                      "" if not dir.imported_org else dir.imported_org.title
                  ],
                  [
                      "Направление отправлено в РМИС",
                      yesno[dir.imported_directions_rmis_send if dir.
                            imported_from_rmis else dir.rmis_number not in
                            ["", None, "NONERMIS"]]
                  ],
                  [
                      "Номер РМИС направления", dir.rmis_number
                      if dir.rmis_number not in [None, "NONERMIS"] else ""
                  ],
                  [
                      "Направление привязано к случаю РМИС",
                      yesno[dir.rmis_case_id not in ["", None, "NONERMIS"]]
                  ],
                  [
                      "Направление привязано к записи отделения госпитализации РМИС",
                      yesno[dir.rmis_hosp_id not in ["", None, "NONERMIS"]]
                  ],
                  ["Результат отправлен в РМИС", yesno[dir.result_rmis_send]]]]
            })
            if dir.visit_date and dir.visit_who_mark:
                d = {
                    "type":
                    "Посещение по направлению",
                    "events": [[
                        [
                            "title",
                            strdatetime(dir.visit_date) +
                            " Регистрация посещения"
                        ],
                        [
                            "Регистратор", dir.visit_who_mark.fio + ", " +
                            dir.visit_who_mark.podrazdeleniye.title
                        ],
                    ]]
                }
                data.append(d)
            for tube in TubesRegistration.objects.filter(
                    issledovaniya__napravleniye=dir).distinct():
                d = {"type": "Ёмкость №%s" % tube.pk, "events": []}
                if tube.time_get is not None:
                    d["events"].append(
                        [["title",
                          strdatetime(tube.time_get) + " Забор"],
                         ["Заборщик", get_userdata(tube.doc_get)]])
                for l in slog.Log.objects.filter(key=str(tube.pk),
                                                 type__in=(4000, 12,
                                                           11)).distinct():
                    tdata = [["Приёмщик", get_userdata(l.user)],
                             [
                                 "title",
                                 strdatetime(l.time) + " " +
                                 l.get_type_display() + " (#%s)" % l.pk
                             ]]
                    if l.body and l.body != "":
                        tdata.append(["json_data", l.body])
                    d["events"].append(tdata)
                data.append(d)
            for iss in Issledovaniya.objects.filter(napravleniye=dir):
                d = {
                    'type':
                    "Исследование: %s (#%s)" % (iss.research.title, iss.pk),
                    'events': []
                }
                for l in slog.Log.objects.filter(key=str(iss.pk),
                                                 type__in=(13, 14,
                                                           24)).distinct():
                    tdata = [["Исполнитель",
                              get_userdata(l.user)],
                             [
                                 "title",
                                 strdatetime(l.time) + " " +
                                 l.get_type_display() + " (#%s)" % l.pk
                             ]]
                    if l.body and l.body != "" and l.type != 24:
                        tdata.append(["json_data", l.body])
                    d["events"].append(tdata)
                data.append(d)
            slog.Log(key=str(pk),
                     type=5000,
                     body="",
                     user=request.user.doctorprofile).save()
        return JsonResponse(data, safe=False)
    return render(request, 'dashboard/direction_info.html')