Exemple #1
0
def ready(request):
    request_data = json.loads(request.body)
    dates = request_data['date_range']
    laboratory_pk = request_data['laboratory']
    result = {"tubes": [], "directions": []}

    date_start, date_end = try_parse_range(*dates)
    dates_cache = {}
    tubes = set()
    dirs = set()

    tlist = TubesRegistration.objects.filter(
        doc_recive__isnull=False,
        time_recive__range=(date_start, date_end),
        issledovaniya__time_confirmation__isnull=True,
        issledovaniya__research__podrazdeleniye_id=laboratory_pk,
        issledovaniya__isnull=False,
    ).filter(
        Q(issledovaniya__napravleniye__hospital_id=request.user.doctorprofile.
          hospital_id) | Q(issledovaniya__napravleniye__hospital__isnull=True))

    for tube in tlist.distinct().prefetch_related(
            'issledovaniya_set__napravleniye').select_related(
                'type', 'type__tube'):
        direction = None
        if tube.pk not in tubes:
            if not direction:
                direction = tube.issledovaniya_set.first().napravleniye
            if tube.time_recive.date() not in dates_cache:
                dates_cache[tube.time_recive.date()] = dateformat.format(
                    tube.time_recive, 'd.m.y')
            tubes.add(tube.pk)
            dicttube = {
                "pk": tube.pk,
                "direction": direction.pk,
                "date": dates_cache[tube.time_recive.date()],
                "tube": {
                    "title": tube.type.tube.title,
                    "color": tube.type.tube.color
                },
            }
            result["tubes"].append(dicttube)

        if tube.issledovaniya_set.first().napravleniye_id not in dirs:
            if not direction:
                direction = tube.issledovaniya_set.first().napravleniye
            if direction.data_sozdaniya.date() not in dates_cache:
                dates_cache[
                    direction.data_sozdaniya.date()] = dateformat.format(
                        direction.data_sozdaniya, 'd.m.y')
            dirs.add(direction.pk)
            dictdir = {
                "pk": direction.pk,
                "date": dates_cache[direction.data_sozdaniya.date()]
            }
            result["directions"].append(dictdir)

    result["tubes"].sort(key=lambda k: k['pk'])
    result["directions"].sort(key=lambda k: k['pk'])
    return JsonResponse(result)
Exemple #2
0
def dashboard_from(request):
    """Получение отделений и кол-ва пробирок"""
    date_start = request.GET["datestart"]
    date_end = request.GET["dateend"]
    filter_type = request.GET.get("type", "wait")
    result = {}
    try:
        date_start, date_end = try_parse_range(date_start, date_end)
        if request.GET.get("get_labs", "false") == "true":
            for lab in (Podrazdeleniya.objects.filter(
                    p_type=Podrazdeleniya.LABORATORY).filter(
                        Q(hospital=request.user.doctorprofile.hospital)
                        | Q(hospital__isnull=True)).exclude(
                            title="Внешние организации")):
                tubes_list = TubesRegistration.objects.filter(
                    doc_get__podrazdeleniye__p_type=Podrazdeleniya.DEPARTMENT,
                    time_get__range=(date_start, date_end),
                    issledovaniya__research__podrazdeleniye=lab).filter(
                        Q(issledovaniya__napravleniye__hospital=request.user.
                          doctorprofile.hospital)
                        | Q(issledovaniya__napravleniye__hospital__isnull=True)
                    )
                if filter_type == "not_received":
                    tubes_list = tubes_list.filter(
                        doc_recive__isnull=True).exclude(notice="")
                elif filter_type == "received":
                    tubes_list = tubes_list.filter(doc_recive__isnull=False)
                else:
                    tubes_list = tubes_list.filter(notice="",
                                                   doc_recive__isnull=True)
                tubes = tubes_list.distinct().count()
                result[lab.pk] = tubes
            return JsonResponse(result)
        podrazdeleniya = Podrazdeleniya.objects.filter(
            p_type=Podrazdeleniya.DEPARTMENT).filter(
                Q(hospital=request.user.doctorprofile.hospital)
                | Q(hospital__isnull=True)).order_by("title")
        lab = Podrazdeleniya.objects.get(pk=request.GET["lab"])
        i = 0
        for podrazledeniye in podrazdeleniya:
            i += 1
            tubes_list = get_tubes_list_in_receive_ui(
                date_end, date_start, filter_type, lab, podrazledeniye,
                request.user.doctorprofile)
            result[i] = {
                "tubes": tubes_list.distinct().count(),
                "title": podrazledeniye.title,
                "pk": podrazledeniye.pk
            }
    except ValueError:
        pass

    return JsonResponse(result)
Exemple #3
0
def tubes_get(request):
    """Получение списка не принятых пробирок"""
    result = []
    k = set()
    if (request.method == "GET" and "lab" in request.GET
            and request.GET["lab"].isdigit() and "from" in request.GET
            and request.GET["from"].isdigit() and "datestart" in request.GET
            and "dateend" in request.GET):
        filter_type = request.GET.get("type", "wait")
        lab = Podrazdeleniya.objects.get(pk=request.GET["lab"])
        podrazledeniye = Podrazdeleniya.objects.get(pk=request.GET["from"])
        date_start = request.GET["datestart"]
        date_end = request.GET["dateend"]
        date_start, date_end = try_parse_range(date_start, date_end)
        from mainmenu.views import get_tubes_list_in_receive_ui

        tubes_list = get_tubes_list_in_receive_ui(date_end, date_start,
                                                  filter_type, lab,
                                                  podrazledeniye,
                                                  request.user.doctorprofile)

        for tube in tubes_list:
            if tube.getbc() in k or (tube.rstatus()
                                     and filter_type != "received"):
                continue
            issledovaniya_tmp = []
            for iss in Issledovaniya.objects.filter(
                    tubes__id=tube.id,
                    research__podrazdeleniye=lab,
                    tubes__time_get__range=(date_start, date_end)):
                issledovaniya_tmp.append(iss.research.title)
            if len(issledovaniya_tmp) > 0:
                k.add(tube.getbc())
                result.append({
                    "researches": ' | '.join(issledovaniya_tmp),
                    "direction":
                    tube.issledovaniya_set.first().napravleniye_id,
                    "tube": {
                        "type": tube.type.tube.title,
                        "id": tube.getbc(),
                        "status": tube.rstatus(),
                        "color": tube.type.tube.color,
                        "notice": tube.notice
                    },
                })

    return JsonResponse(list(result), safe=False)
Exemple #4
0
def form_03(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="Форма {}".format("План операций")
    )

    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

    dates = request_data["date"].split(",")
    date_start, date_end = try_parse_range(dates[0], dates[1])

    objs = []
    objs.append(Paragraph(f"Лист ожидани: {dates[0]} - {dates[1]}", styleCenterBold))
    objs.append(Spacer(1, 5 * mm))

    research_pk = int(request_data["research_pk"])
    if research_pk > -1:
        list_wait = ListWait.objects.filter(
            exec_at__range=(
                date_start,
                date_end,
            ),
            research_id__pk=research_pk,
        ).order_by("exec_at")
    else:
        list_wait = ListWait.objects.filter(
            exec_at__range=(
                date_start,
                date_end,
            )
        ).order_by("exec_at")

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

    count = 0
    for i in list_wait:
        count += 1
        opinion.append(
            [
                Paragraph(f"{count}", styleCenter),
                Paragraph(f"{i.client.individual.fio()} ({i.client.number_with_type()})", styleCenter),
                Paragraph(f"{i.client.phone}", styleCenter),
                Paragraph(f"{i.research.title}", style),
                Paragraph(f"{i.get_work_status_display()}", style),
                Paragraph(f"{i.comment}", style),
            ]
        )

    tbl = Table(opinion, colWidths=(10 * mm, 80 * mm, 30 * mm, 50 * mm, 30 * mm, 40 * 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
Exemple #5
0
def discharge_search(request):
    r = {"rows": []}
    if request.method == "GET":
        import discharge.models as discharge
        date_start = request.GET["date_start"]
        date_end = request.GET["date_end"]
        date_start, date_end = try_parse_range(date_start, date_end)
        query = request.GET.get("q", "")
        otd_pk = int(request.GET.get("otd", "-1"))
        doc_fio = request.GET.get("doc_fio", "")

        slog.Log(key=query,
                 type=1001,
                 body=json.dumps({
                     "date_start": request.GET["date_start"],
                     "date_end": request.GET["date_end"],
                     "otd_pk": otd_pk,
                     "doc_fio": doc_fio
                 }),
                 user=request.user.doctorprofile).save()

        filter_type = "any"
        family = ""
        name = ""
        twoname = ""
        bdate = ""

        if query.isdigit():
            filter_type = "card_number"
        elif bool(
                re.compile(
                    r'^([a-zA-Zа-яА-Я]+)( [a-zA-Zа-яА-Я]+)?( [a-zA-Zа-яА-Я]+)?( \d{2}\.\d{2}\.\d{4})?$'
                ).match(query)):
            filter_type = "fio"
            split = query.split()
            if len(split) > 0:
                family = split[0]
            if len(split) > 1:
                name = split[1]
            if len(split) > 2:
                twoname = split[2]
            if len(split) > 2:
                twoname = split[2]
            if len(split) > 3:
                spq = split[3]
                bdate = "%s-%s-%s" % (spq[4:8], spq[2:4], spq[0:2])

        rows = discharge.Discharge.objects.filter(created_at__range=(
            date_start,
            date_end,
        ),
                                                  doc_fio__icontains=doc_fio)

        if otd_pk > -1:
            rows = rows.filter(otd__pk=otd_pk)

        if filter_type == "fio":
            rows = rows.filter(client_surname__contains=family,
                               client_name__contains=name,
                               client_patronymic__contains=twoname)
            if bdate != "":
                rows = rows.filter(client_birthday=bdate)

        if filter_type == "card_number":
            rows = rows.filter(client_cardnum=int(query))
        import os
        for row in rows.order_by("-created_at"):
            r["rows"].append({
                "date":
                str(
                    dateformat.format(row.created_at.date(),
                                      settings.DATE_FORMAT)),
                "client": {
                    "surname": row.client_surname,
                    "name": row.client_name,
                    "patronymic": row.client_patronymic,
                    "sex": row.client_sex,
                    "birthday": row.client_birthday
                },
                "otd":
                row.otd.title,
                "doc_fio":
                row.doc_fio,
                "filename":
                os.path.basename(row.file.name),
                "fileurl":
                row.file.url
            })

    return JsonResponse(r)
Exemple #6
0
def gen_pdf_execlist(request):
    """
    Лист исполнения
    :param request:
    :return:
    """
    type = int(request.GET["type"])
    date_start = request.GET["datestart"]
    date_end = request.GET["dateend"]
    if type != 2:
        date_start, date_end = try_parse_range(date_start, date_end)

    researches = json.loads(request.GET["researches"])
    xsize = 8
    ysize = 8
    from reportlab.lib.pagesizes import landscape

    lw, lh = landscape(A4)
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="execlist.pdf"'
    buffer = BytesIO()
    doc = SimpleDocTemplate(buffer,
                            pagesize=A4,
                            rightMargin=10,
                            leftMargin=80,
                            topMargin=10,
                            bottomMargin=0)
    doc.pagesize = landscape(A4)

    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    import os.path
    from django.utils.text import Truncator

    pdfmetrics.registerFont(
        TTFont('OpenSans', os.path.join(FONTS_FOLDER, 'OpenSans.ttf')))
    elements = []
    for res in directory.Researches.objects.filter(pk__in=researches):
        if type != 2:
            iss_list = Issledovaniya.objects.filter(
                tubes__doc_recive_id__isnull=False,
                tubes__time_recive__range=(date_start, date_end),
                time_confirmation__isnull=True,
                research__pk=res.pk,
                deferred=False).order_by('tubes__time_recive')
        else:
            iss_list = Issledovaniya.objects.filter(
                research__pk=res.pk,
                deferred=True,
                time_confirmation__isnull=True,
                tubes__doc_recive__isnull=False).order_by('tubes__time_recive')

        if iss_list.count() == 0:
            # if not hb:
            #    elements.append(PageBreak())
            continue
        pn = 0
        tubes = []
        for iss in iss_list:
            for tube in iss.tubes.all():
                # if not tube.doc_recive:
                #    pass
                # else:
                tubes.append(tube)
        if len(tubes) == 0:
            continue
        pn += 1
        p = Paginator(tubes, xsize * (ysize - 1))

        for pg_num in p.page_range:
            pg = p.page(pg_num)
            data = [[]]
            for j in range(0, xsize):
                data[-1].append("<br/><br/><br/><br/><br/>")
            inpg = Paginator(pg.object_list, xsize)
            for inpg_num in inpg.page_range:
                inpg_o = inpg.page(inpg_num)
                data.append([])
                for inobj in inpg_o.object_list:
                    data[-1].append(
                        inobj.issledovaniya_set.first().napravleniye.client.
                        individual.fio(short=True, dots=True) + ", " +
                        inobj.issledovaniya_set.first().napravleniye.client.
                        individual.age_s(iss=inobj.issledovaniya_set.first()) +
                        "<br/>№ напр.: " +
                        str(inobj.issledovaniya_set.first().napravleniye_id) +
                        "<br/>" + "№ ёмкости: " + str(inobj.pk) + "<br/>" +
                        Truncator(inobj.issledovaniya_set.first().napravleniye.
                                  doc.podrazdeleniye.title).chars(19) +
                        "<br/><br/>")
            if len(data) < ysize:
                for i in range(len(data), ysize):
                    data.append([])
            for y in range(0, ysize):
                if len(data[y]) < xsize:
                    for i in range(len(data[y]), xsize):
                        data[y].append("<br/><br/><br/><br/><br/>")
            style = TableStyle([
                ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                ('INNERGRID', (0, 0), (-1, -1), 0.3, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.3, colors.black),
            ])

            s = getSampleStyleSheet()
            s = s["BodyText"]
            s.wordWrap = 'LTR'
            data = transpose(data)
            data2 = [[
                Paragraph('<font face="OpenSans" size="7">' + cell + "</font>",
                          s) for cell in row
            ] for row in data]
            tw = lw - 90
            t = Table(data2,
                      colWidths=[
                          int(tw / 8),
                          int(tw / 8),
                          int(tw / 8),
                          int(tw / 8),
                          int(tw / 8),
                          int(tw / 8),
                          int(tw / 8),
                          int(tw / 8)
                      ])
            t.setStyle(style)
            st = ""
            if type == 2:
                st = ", отложенные"
            elements.append(
                Paragraph(
                    '<font face="OpenSans" size="10">' + res.title + st +
                    ", " + str(pg_num) + " стр<br/><br/></font>", s))
            elements.append(t)
            elements.append(PageBreak())

    doc.build(elements)
    pdf = buffer.getvalue()  # Получение данных из буфера
    buffer.close()  # Закрытие буфера
    response.write(pdf)  # Запись PDF в ответ
    return response