Ejemplo n.º 1
0
    def plan_hosp_get(data):
        if data.get('d1', None):
            d1 = datetime.strptime(data.get('d1'), '%d.%m.%Y')
        else:
            d1 = current_time()
        if data.get('d2', None):
            d2 = datetime.strptime(data.get('d2'), '%d.%m.%Y')
        else:
            d2 = current_time()

        start_date = datetime.combine(d1, datetime.time.min)
        end_date = datetime.combine(d2, datetime.time.max)
        if data.get('research', None):
            result = PlanHospitalization.objects.filter(
                research_id=data.get('research'),
                exec_at__range=(start_date, end_date)).order_by("exec_at")
        elif data.get('patient_pk', None):
            result = PlanHospitalization.objects.filter(
                client__pk=data.get('patient_pk')).order_by("exec_at")
        else:
            result = PlanHospitalization.objects.filter(
                exec_at__range=(start_date,
                                end_date)).order_by("pk", "exec_at",
                                                    "research")

        return result
Ejemplo n.º 2
0
def get_hospital_resource():
    hospital_resource = get_resource_by_research_hospital()
    hospital_resource_pk = [i.scheduleresource_id for i in hospital_resource]
    resource_researches = {}
    for i in hospital_resource:
        if not resource_researches.get(i.scheduleresource_id, None):
            resource_researches[i.scheduleresource_id] = {
                "researches_id": i.researches_id,
                "title": i.schedule_title or i.title,
                "short_title": i.short_title
            }

    d1 = current_time(only_date=True)
    d2 = d1 + relativedelta(days=FORWARD_DAYS_SCHEDULE)
    date_start = datetime.datetime.combine(d1, datetime.time.min)
    date_end = datetime.datetime.combine(d2, datetime.time.max)
    slot_plan_for_hospital = get_slot_plan_by_hosp_resource(
        date_start, date_end, tuple(hospital_resource_pk))
    resource_has_slot = set([sl.resource_id for sl in slot_plan_for_hospital])
    final_hosp_researches_has_slot = []
    for rslot in resource_has_slot:
        if resource_researches.get(rslot):
            temp_data = resource_researches.get(rslot)
            temp_data["resource_id"] = rslot
            final_hosp_researches_has_slot.append(temp_data.copy())

    return final_hosp_researches_has_slot
Ejemplo n.º 3
0
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
Ejemplo n.º 4
0
    def limit_plan_hosp_get(research_pk):
        start_date = current_time()
        end_date = start_date + relativedelta(days=30)
        result = LimitDatePlanHospitalization.objects.filter(
            exec_at__range=(start_date, end_date),
            research_pk=research_pk).order_by("date")

        return result
Ejemplo n.º 5
0
    def doctor_call_get(data):
        if data.get('d1', None):
            d1 = datetime.datetime.strptime(data.get('d1'), '%d.%m.%Y')
        else:
            d1 = current_time()
        if data.get('d2', None):
            d2 = datetime.datetime.strptime(data.get('d2'), '%d.%m.%Y')
        else:
            d2 = current_time()

        start_date = datetime.datetime.combine(d1, datetime.time.min)
        end_date = datetime.datetime.combine(d2, datetime.time.max)
        if data.get('district', None):
            district_obj = District.objects.filter(pk__in=data.get('district'))
            result = DoctorCall.objects.filter(district__in=district_obj, exec_at__range=(start_date, end_date)).order_by("district")
        elif data.get('patient_pk', None):
            result = DoctorCall.objects.filter(client__pk=data.get('patient_pk')).order_by("exec_at")
        else:
            result = DoctorCall.objects.filter(exec_at__range=(start_date, end_date)).order_by("exec_at, district")

        return result
Ejemplo n.º 6
0
    def list_wait_get(data):
        if data.get('d1', None):
            d1 = datetime.datetime.strptime(data.get('d1'), '%d.%m.%Y')
        else:
            d1 = current_time()
        if data.get('d2', None):
            d2 = datetime.datetime.strptime(data.get('d2'), '%d.%m.%Y')
        else:
            d2 = current_time()

        start_date = datetime.datetime.combine(d1, datetime.time.min)
        end_date = datetime.datetime.combine(d2, datetime.time.max)
        if data.get('research', None):
            research_obj = Researches.objects.filter(pk=data.get('research'))
            result = ListWait.objects.filter(research=research_obj, exec_at__range=(start_date, end_date)).order_by("exec_at")
        elif data.get('patient_pk', None):
            result = ListWait.objects.filter(client__pk=data.get('patient_pk')).order_by("exec_at")
        else:
            result = ListWait.objects.filter(exec_at__range=(start_date, end_date)).order_by("pk", "exec_at", "research")

        return result
Ejemplo n.º 7
0
def get_available_slots_of_dates(research_pk,
                                 date_start,
                                 date_end,
                                 allow_cito=False):
    d1 = try_strptime(f"{date_start}", formats=('%Y-%m-%d', ))
    d2 = try_strptime(f"{date_end}", formats=('%Y-%m-%d', ))
    current_date = try_strptime(current_time().strftime("%Y-%m-%d"),
                                formats=('%Y-%m-%d', ))
    start_date = datetime.datetime.combine(d1, datetime.time.min)
    end_date = datetime.datetime.combine(d2, datetime.time.max)

    if end_date < datetime.datetime.combine(current_date, datetime.time.max):
        return {}

    if start_date < datetime.datetime.combine(current_date, datetime.time.min):
        start_date = datetime.datetime.combine(
            current_date, datetime.time.min) + datetime.timedelta(days=1)

    if allow_cito:
        data = {}
        date_i = start_date - datetime.timedelta(
            days=1)  # ЦИТО можно записать на сегодня
        while date_i < end_date:
            date_s = date_i.strftime("%Y-%m-%d")
            data[date_s] = True
            date_i += datetime.timedelta(days=1)
        return data

    resource_hosp = get_hospital_resource_by_research(research_pk)
    structure_resource = {
        rh.scheduleresource_id: rh.resource_title
        for rh in resource_hosp
    }

    resource_tuple = tuple(structure_resource.keys())
    slot_plans = get_date_slots_for_many_resource(start_date, end_date,
                                                  resource_tuple)
    slot_plan_pks = tuple([slplan.slot_id for slplan in slot_plans])
    slot_plan_busy_slot_fact = get_slot_fact(slot_plan_pks)
    slot_plan_busy_slot_fact = [i.plan_id for i in slot_plan_busy_slot_fact]
    data = {}

    for slotplan in slot_plans:
        if slotplan.slot_id in slot_plan_busy_slot_fact or slotplan.date_char in data:
            continue
        data[slotplan.date_char] = True

    return data
Ejemplo n.º 8
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})
Ejemplo n.º 9
0
def actual_rows(request):
    data = data_parse(request.body, {'card_pk': int})
    card_pk: int = data[0]

    date_from = datetime.datetime.combine(current_time(), datetime.time.min)

    rows = list(
        ListWait.objects.filter(client_id=card_pk,
                                exec_at__gte=date_from).order_by(
                                    'exec_at',
                                    'pk').values('pk', 'exec_at',
                                                 'research__title', 'comment',
                                                 'work_status', 'phone'))
    p: PlanHospitalization
    for p in PlanHospitalization.objects.filter(client_id=card_pk,
                                                exec_at__gte=date_from,
                                                action=0).order_by(
                                                    'exec_at', 'pk'):
        if p.slot_fact:
            slot_datetime = f"{datetime.datetime.strftime(localtime(p.slot_fact.plan.datetime), '%d.%m.%Y %H:%M')}, {p.slot_fact.plan.duration_minutes} мин."
        elif p.why_cancel:
            slot_datetime = p.why_cancel
        else:
            slot_datetime = "Ожидает решение"
        rows.append({
            "pk": p.pk,
            "pk_plan": p.pk,
            "exec_at": p.exec_at,
            "date": p.exec_at,
            "research_id": p.research_id,
            "research__title": p.research.title,
            "research_title": p.research.title,
            "comment": p.comment,
            "work_status": p.work_status,
            "phone": p.phone,
            "diagnos": p.diagnos,
            "hospital_department__title": p.hospital_department.title,
            "slot": slot_datetime,
            "patient_card": card_pk,
            "fio_patient": p.client.individual.fio(),
            "canceled": p.work_status == 2,
        })

    return JsonResponse(rows, safe=False)
Ejemplo n.º 10
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()
Ejemplo n.º 11
0
def create_contract(ind_dir, card_pk):
    ind_card = Card.objects.get(pk=card_pk)
    # exec_person = request_data['user'].doctorprofile.get_full_fio()

    patient_data = ind_card.get_data_individual()
    p_agent = None
    if ind_card.who_is_agent:
        p_agent = getattr(ind_card, ind_card.who_is_agent)

    p_payer = None
    if ind_card.payer:
        p_payer = ind_card.payer

    # Получить все источники, у которых title-ПЛАТНО
    ist_f = list(IstochnikiFinansirovaniya.objects.values_list('id').filter(title__exact='Платно'))
    ist_f_list = [int(x[0]) for x in ist_f]

    napr = Napravleniya.objects.filter(pk__in=ind_dir)
    dir_temp = []

    # Проверить, что все направления принадлежат к одной карте и имеют ист. финансирования "Платно"
    num_contract_set = set()
    for n in napr:
        if n.istochnik_f_id in ist_f_list and n.client == ind_card:
            num_contract_set.add(n.num_contract)
            dir_temp.append(n.pk)

    if not dir_temp:
        return False

    # получить УСЛУГИ по направлениям(отфильтрованы по "платно" и нет сохраненных исследований) в Issledovaniya
    research_direction = get_research_by_dir(dir_temp)

    if not research_direction:
        return False

    # получить по направлению-услугам цену из Issledovaniya
    research_price = get_coast_from_issledovanie(research_direction)

    # Получить Итоговую стр-ру данных
    result_data = get_final_data(research_price)

    sum_research = result_data[1]

    # Контрольная сумма расчет: послдеовательность направлений+Итоговая сумма (стоимость денежная)
    qr_napr = ','.join([str(elem) for elem in result_data[3]])
    protect_val = sum_research.replace(' ', '')
    bstr = (qr_napr + protect_val).encode()
    protect_code = str(zlib.crc32(bstr))

    today = utils.current_time()
    date_now1 = datetime.datetime.strftime(today, '%y%m%d%H%M%S%f')[:-3]
    date_now_str = str(ind_card.pk) + str(date_now1)

    # Проверить записан ли номер контракта в направлениях, и контрольная сумма
    # ПереЗаписать номер контракта Если в наборе направлений значение None, или в направлениях разные контракты,
    # а также разные контрольные суммы, все перезаписать.
    num_contract_set = set()
    protect_code_set = set()
    napr_end = Napravleniya.objects.filter(id__in=result_data[3])
    for n in napr_end:
        num_contract_set.add(n.num_contract)
        protect_code_set.add(n.protect_code)

    if len(num_contract_set) == 1 and None in num_contract_set or None in protect_code_set:
        PersonContract.person_contract_save(date_now_str, protect_code, qr_napr, sum_research, patient_data['fio'], ind_card, p_payer, p_agent)
        Napravleniya.objects.filter(id__in=result_data[3]).update(num_contract=date_now_str, protect_code=protect_code)

    return PersonContract.pk
Ejemplo n.º 12
0
def get_available_hospital_plans(research_pk,
                                 resource_id=None,
                                 date_start=None,
                                 date_end=None):
    if date_start and date_end:
        d1 = try_strptime(f"{date_start}", formats=('%Y-%m-%d', ))
        d2 = try_strptime(f"{date_end}", formats=('%Y-%m-%d', ))
    else:
        d1 = current_time(only_date=True) + relativedelta(days=1)
        d2 = d1 + relativedelta(days=FORWARD_DAYS_SCHEDULE)

    if resource_id is None:
        resource_id = tuple(
            ScheduleResource.objects.filter(
                service__in=[research_pk]).values_list('pk', flat=True))
    elif isinstance(resource_id, tuple):
        resource_id = resource_id
    elif isinstance(resource_id, list):
        resource_id = tuple(resource_id)
    else:
        resource_id = tuple([resource_id])

    if not resource_id:
        return {}, {}

    counts = {}

    start_date = datetime.datetime.combine(d1, datetime.time.min)
    end_date = datetime.datetime.combine(d2, datetime.time.max)
    result_slot = get_slot_plan_by_hosp_resource(start_date, end_date,
                                                 resource_id)
    date_slots = {}
    for rslots in result_slot:
        if not date_slots.get(rslots.date_char, None):
            date_slots[rslots.date_char] = [rslots.datetime]
        else:
            temp_date_slots = date_slots.get(rslots.date_char, None)
            temp_date_slots.append(rslots.datetime)
            date_slots[rslots.date_char] = temp_date_slots.copy()
    date_available_status = {}

    date_i = start_date - datetime.timedelta(
        days=1)  # ЦИТО можно записать на сегодня
    while date_i < end_date:
        date_s = date_i.strftime("%Y-%m-%d")
        date_available_status[date_s] = False
        date_i += datetime.timedelta(days=1)

    for current_date, slots_in_date in date_slots.items():
        d1 = try_strptime(current_date, formats=('%Y-%m-%d', ))
        start_date = datetime.datetime.combine(d1, datetime.time.min)
        end_date = datetime.datetime.combine(d1, datetime.time.max)
        current_plan_count = (PlanHospitalization.objects.filter(
            exec_at__range=(start_date, end_date),
            work_status__in=[0, 1, 3],
            action=0,
            research_id=research_pk).order_by("exec_at").count())
        counts[current_date] = {
            "available": len(slots_in_date),
            "used": current_plan_count,
        }
        date_available_status[current_date] = counts[current_date][
            "available"] > counts[current_date]["used"]

    return date_available_status, counts
Ejemplo n.º 13
0
def get_available_hospital_resource_slot(research_pk,
                                         date_start,
                                         date_end,
                                         allow_cito=False):
    d1 = try_strptime(f"{date_start}", formats=('%Y-%m-%d', ))
    d2 = try_strptime(f"{date_end}", formats=('%Y-%m-%d', ))
    start_date = datetime.datetime.combine(d1, datetime.time.min)
    end_date = datetime.datetime.combine(d2, datetime.time.max)
    result = {"dates": {}}

    if end_date < datetime.datetime.combine(
            try_strptime(current_time().strftime("%Y-%m-%d"),
                         formats=('%Y-%m-%d', )), datetime.time.max):
        return result

    resource_hosp = get_hospital_resource_by_research(research_pk)
    structure_resource = {
        rh.scheduleresource_id: rh.resource_title
        for rh in resource_hosp
    }

    resource_tuple = tuple(structure_resource.keys())
    slot_plans = get_date_slots_for_many_resource(start_date, end_date,
                                                  resource_tuple)
    slot_plan_pks = tuple([slplan.slot_id for slplan in slot_plans])
    slot_plan_busy_slot_fact = get_slot_fact(slot_plan_pks)
    slot_plan_busy_slot_fact = [i.plan_id for i in slot_plan_busy_slot_fact]
    data = result["dates"]
    dates = set([slotplan.date_char for slotplan in slot_plans])
    for d in dates:
        data[d] = []

    temp_data_slot_resource = {}
    for slotplan in slot_plans:
        if slotplan.slot_id in slot_plan_busy_slot_fact:
            continue
        if not temp_data_slot_resource.get(slotplan.resource_id):
            temp_data_slot_resource[slotplan.resource_id] = {
                slotplan.date_char: [{
                    "pk":
                    slotplan.slot_id,
                    "title":
                    f"{slotplan.start_slot} - {slotplan.end_slot}"
                }]
            }
        else:
            temp_slot_resource_date = temp_data_slot_resource.get(
                slotplan.resource_id, None)
            if not temp_slot_resource_date.get(slotplan.date_char):
                temp_slot_resource_date[slotplan.date_char] = [{
                    "pk":
                    slotplan.slot_id,
                    "title":
                    f"{slotplan.start_slot} - {slotplan.end_slot}"
                }]
            else:
                temp_slot_resource_data = temp_slot_resource_date.get(
                    slotplan.date_char)
                temp_slot_resource_data.append({
                    "pk":
                    slotplan.slot_id,
                    "title":
                    f"{slotplan.start_slot} - {slotplan.end_slot}"
                })
                temp_slot_resource_date[
                    slotplan.date_char] = temp_slot_resource_data.copy()
            temp_data_slot_resource[
                slotplan.resource_id] = temp_slot_resource_date.copy()

    for k, v in temp_data_slot_resource.items():
        for date, slots in v.items():
            temp_data = data.get(date)
            temp_data.append({
                "resourcePk": k,
                "resourceTitle": structure_resource.get(k, ""),
                "slots": slots
            })
            data[date] = temp_data.copy()

    if allow_cito:
        dates = []
        date_i = start_date
        while date_i < end_date:
            date = date_i.strftime("%Y-%m-%d")
            if date not in data:
                data[date] = []
            has_resources = {x['resourcePk']: x for x in data[date]}
            for rpk in resource_tuple:
                if rpk in has_resources:
                    has_resources[rpk]['slots'].append({
                        "pk": -10,
                        "title": "CITO"
                    })
                    continue
                temp_data = {
                    "resourcePk": rpk,
                    "resourceTitle": structure_resource.get(rpk, ""),
                    "slots": [{
                        "pk": -10,
                        "title": "CITO"
                    }]
                }
                data[date].append(temp_data)

            date_i += datetime.timedelta(days=1)
    return result
Ejemplo n.º 14
0
def dashboard_charts(request):
    request_data = json.loads(request.body)
    dashboard_pk = request_data.get("dashboard", -1)

    end_period_type = request_data.get("end_type", None)
    end_period_duration = request_data.get("end_duration", 0)

    start_period_type = request_data.get("start_type", None)
    start_period_duration = request_data.get("start_duration", 0)

    date_end = request_data.get("date_end", None)
    date_start = request_data.get("date_start", None)

    date_period_start = request_data.get("dateStart", None)
    date_period_end = request_data.get("dateEnd", None)

    if date_end and date_start:
        try:
            date_end = str_date(date_end)
        except Exception as e:
            logger.exception(e)
            date_end = None
        try:
            date_start = str_date(date_start, indicator="min")
        except Exception as e:
            logger.exception(e)
            date_start = None

    elif start_period_type and start_period_duration:
        start_periods_data = define_period(start_period_type,
                                           start_period_duration)
        date_end = current_time()

        if end_period_type and end_period_duration:
            end_periods_data = define_period(end_period_type,
                                             end_period_duration)
            date_end = date_end + relativedelta(
                years=end_periods_data["years"],
                months=end_periods_data["months"],
                weeks=end_periods_data["weeks"],
                days=end_periods_data["days"])

        date_start = date_end + relativedelta(
            years=start_periods_data["years"],
            months=start_periods_data["months"],
            weeks=start_periods_data["weeks"],
            days=start_periods_data["days"])

    if date_end and date_start:
        d = date_end - date_start
        if d.days > DASH_REPORT_LIMIT_DURATION_DAYS[
                "max_delta_days"] or d.days < 0:
            date_end = None
            date_start = None
    try:
        result = exec_query(
            dashboard_pk, {
                "date_start": date_period_start or date_start,
                "date_end": date_period_end or date_end
            })
    except Exception as e:
        logger.exception(e)
        return JsonResponse({"ok": False})

    dash = Dashboard.objects.get(pk=dashboard_pk)
    return JsonResponse({
        'rows': result["result"],
        "ok": True,
        "intervalReloadSeconds": dash.interval_reload_seconds,
        "showDatesParam": result["show_dates_param"],
        "datesParam": result["dates_param"]
    })