def available_hospitalization_plan(request): data = data_parse( request.body, { 'research_pk': int, 'resource_id': int, 'date_start': str, 'date_end': str }, { 'research_pk': None, 'resource_id': None, 'date_start': None, 'date_end': None, }, ) research_pk = data[0] resource_id = data[1] date_start = data[2] date_end = data[3] is_cito = has_group(request.user, 'Цито-запись в расписании') result, counts = get_available_hospital_plans(research_pk, resource_id, date_start, date_end) return JsonResponse({"data": result, "counts": counts, "cito": is_cito})
def save_resource(request): data = data_parse(request.body, { 'pk': int, 'resource_researches': list, 'res_pk': int, 'res_title': str }) user_pk = data[0] resource_researches = data[1] res_pk = data[2] res_title = data[3] user = User.objects.get(pk=user_pk) executor = DoctorProfile.objects.get(user=user) researches = Researches.objects.filter(pk__in=resource_researches) if res_pk == -1: doc_resource = ScheduleResource(executor=executor, department=executor.podrazdeleniye, speciality=executor.specialities, title=res_title) doc_resource.save() else: doc_resource = ScheduleResource.objects.get(pk=res_pk) doc_resource.title = res_title doc_resource.service.clear() for r in researches: doc_resource.service.add(r) doc_resource.save() return JsonResponse({"message": "Ресурс создан", "ok": True})
def create_slots(request): data = data_parse( request.body, { 'slots': list, 'sources': list, 'duration': int, 'date': str, 'resource': int }) slots: List[str] = data[0] sources: List[str] = data[1] duration: int = data[2] date: str = data[3] resource: int = data[4] date_start = f"{date} 00:00:00" date_end = f"{date} 23:59:59" has_rights = can_edit_resource(request, resource) if not has_rights: return status_response(False, 'У вас недостаточно прав') date_slots = get_date_slots(date_start, date_end, resource) remove_element = [] for s in slots: start_end = s.split(" — ") a1 = try_strptime(f"{date} {start_end[0]}", formats=('%Y-%m-%d %H:%M', )) a2 = try_strptime(f"{date} {start_end[1]}", formats=('%Y-%m-%d %H:%M', )) for ds in date_slots: b1 = try_strptime(f"{date} {ds.start_slot}", formats=('%Y-%m-%d %H:%M', )) b2 = try_strptime(f"{date} {ds.end_slot}", formats=('%Y-%m-%d %H:%M', )) # проерка на не пересечение if not (a1 >= b2 or a2 <= b1): remove_element.append(s) for r in remove_element: slots.remove(r) with transaction.atomic(): for s in slots: time = s.split(' ')[0] datetime_str = f"{date} {time}" dt = try_strptime(datetime_str, formats=('%Y-%m-%d %H:%M', )) end_date = dt + relativedelta(minutes=duration) SlotPlan.objects.create( resource_id=resource, datetime=dt, datetime_end=end_date, duration_minutes=duration, available_systems=sources, ) return status_response(True)
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})
def available_slots(request): data = data_parse(request.body, { 'research_pk': int, 'date_start': str, 'date_end': str }) research_pk: int = data[0] date_start: str = data[1] date_end: str = data[2] result = get_available_hospital_resource_slot( research_pk, date_start, date_end, allow_cito=has_group(request.user, 'Цито-запись в расписании')) return JsonResponse({"result": result})
def available_slots_of_dates(request): data = data_parse(request.body, { 'research_pk': int, 'date_start': str, 'date_end': str }) research_pk = data[0] date_start = data[1] date_end = data[2] result = get_available_slots_of_dates(research_pk, date_start, date_end, allow_cito=has_group( request.user, 'Цито-запись в расписании')) return JsonResponse({"data": result})
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)
def check_hosp_slot_before_save(request): data = data_parse( request.body, { 'research_pk': int, 'resource_id': int, 'date': str }, { 'research_pk': None, 'resource_id': None, 'date': None, }, ) research_pk = data[0] resource_id = data[1] date = data[2] result = check_available_hospital_slot_before_save(research_pk, resource_id, date) return JsonResponse({"result": result})
def schedule_access(request): resource_pk = data_parse(request.body, {'resourcePk': int}, {'resourcePk': None})[0] return status_response(can_edit_resource(request, resource_pk))
def days(request): day, resource_pk, display_days = data_parse(request.body, { 'date': str, 'resource': int, 'displayDays': int }, {'displayDays': 7}) rows = [] start_time = None end_time = None display_days = min(display_days, 21) date_start = datetime.datetime.strptime(day, '%Y-%m-%d') resource = ScheduleResource.objects.filter(pk=resource_pk).first() for i in range(display_days): date = date_start + datetime.timedelta(days=i) date_end = date + datetime.timedelta(days=1) date_s = datetime.datetime.strftime(date, '%Y-%m-%d') date_data = { 'date': date_s, 'weekDay': date.weekday(), 'month': date.month - 1, 'slots': [], } if resource: slots = SlotPlan.objects.filter( resource=resource, datetime__gte=date, datetime__lt=date_end).order_by('datetime') for s in slots: slot_datetime = localtime(s.datetime) duration = s.duration_minutes current_slot_time = timedelta(hours=max(slot_datetime.hour, 0)) hours_duration = int(math.ceil(duration / 60)) current_slot_end_time = timedelta( hours=min(slot_datetime.hour + hours_duration, 24)) if start_time is None or start_time > current_slot_time: start_time = current_slot_time if end_time is None or end_time < current_slot_end_time: end_time = current_slot_end_time slot_fact = SlotFact.objects.filter( plan=s).order_by('-pk').first() status = 'empty' patient = None service = None direction = None is_cito = s.is_cito if slot_fact: status = { 0: 'reserved', 1: 'cancelled', 2: 'success', }[slot_fact.status] if slot_fact.is_cito: is_cito = True if slot_fact.patient: card: Card = slot_fact.patient patient = { 'cardId': card.pk, 'base': card.base_id, 'number': card.number_with_type(), 'fio': card.individual.fio(full=True), 'fioShort': card.individual.fio(dots=True, short=True), 'birthday': card.individual.bd(), } if slot_fact.service: service = { 'id': slot_fact.service_id, 'title': slot_fact.service.get_title(), } if slot_fact.direction: direction = { 'id': slot_fact.direction_id, } date_data['slots'].append({ 'id': s.pk, 'date': datetime.datetime.strftime(slot_datetime, '%Y-%m-%d'), 'time': datetime.datetime.strftime(slot_datetime, '%H:%M'), 'timeEnd': datetime.datetime.strftime( slot_datetime + timedelta(minutes=duration), '%H:%M'), 'hour': delta_to_string(current_slot_time), 'hourValue': slot_datetime.hour, 'minute': slot_datetime.minute, 'duration': duration, 'status': status, 'patient': patient, 'service': service, 'direction': direction, 'cito': is_cito, }) rows.append(date_data) if end_time is not None and end_time >= timedelta(hours=24): end_time = timedelta(hours=23) start_calendar_time = delta_to_string(start_time) end_calendar_time = delta_to_string(end_time) services = [] if resource: services = [{ 'id': x['pk'], 'label': x['short_title'] or x['title'] } for x in resource.service.all().values( 'pk', 'title', 'short_title').order_by('short_title', 'title')] return JsonResponse({ 'days': rows, 'startTime': start_calendar_time, 'endTime': end_calendar_time, 'services': services, })
def save(request): data = data_parse( request.body, { 'id': int, 'cardId': int, 'status': str, 'planId': int, 'serviceId': int, 'date': str, 'resource': str }, { 'planId': None, 'cardId': None, 'serviceId': None, 'status': 'reserved', 'date': None, 'resource': None }, ) pk: int = data[0] card_pk: int = data[1] status: str = data[2] plan_id: int = data[3] service_id: int = data[4] date: str = data[5] resource: int = data[6] if not card_pk: return status_response(False, 'Пациен не выбран') is_cito = False if has_group( request.user, 'Цито-запись в расписании') and pk == -10 and date and resource: d = try_strptime(f"{date}", formats=('%Y-%m-%d', )) start_date = datetime.datetime.combine(d, datetime.time.min) end_date = datetime.datetime.combine(d, datetime.time.max) slots = SlotPlan.objects.filter(datetime__range=(start_date, end_date)) free_slot: SlotPlan = slots.filter( slotfact__isnull=True).order_by('datetime').first() if not free_slot: last_any_slot: SlotPlan = slots.order_by('-datetime').first() if last_any_slot: next_time = last_any_slot.datetime + datetime.timedelta( minutes=last_any_slot.duration_minutes) duration = last_any_slot.duration_minutes else: next_time = try_strptime(f"{date} 08:00", formats=('%Y-%m-%d %H:%M', )) duration = 3 end_time = next_time + datetime.timedelta(minutes=duration) new_slot_plan = SlotPlan.objects.create( resource_id=resource, datetime=next_time, datetime_end=end_time, duration_minutes=duration, available_systems=[SlotPlan.LOCAL], disabled=False, is_cito=True, ) pk = new_slot_plan.pk else: pk = free_slot.pk is_cito = True s: SlotPlan = SlotPlan.objects.filter(pk=pk).first() if s: status = { 'reserved': 0, 'cancelled': 1, 'success': 2, }.get(status, 0) slot_fact: SlotFact = SlotFact.objects.filter( plan=s).order_by('-pk').first() if not slot_fact: slot_fact = SlotFact.objects.create(plan=s, status=status) slot_fact.patient_id = card_pk slot_fact.status = status slot_fact.service_id = service_id slot_fact.is_cito = is_cito slot_fact.save() if plan_id: ph: PlanHospitalization = PlanHospitalization.objects.get( pk=plan_id) ph.slot_fact = slot_fact ph.work_status = 3 ph.exec_at = s.datetime ph.save() return status_response(True) return status_response(False, 'Слот не найден')
def details(request): pk = data_parse(request.body, {'id': int})[0] s: SlotPlan = SlotPlan.objects.filter(pk=pk).first() if s: slot_datetime = localtime(s.datetime) duration = s.duration_minutes current_slot_time = timedelta(hours=max(slot_datetime.hour, 0)) slot_fact = SlotFact.objects.filter(plan=s).order_by('-pk').first() status = 'empty' card_pk = None service = { 'id': None, } direction = None base_pk = CardBase.objects.filter(internal_type=True)[0].pk if slot_fact: status = { 0: 'reserved', 1: 'cancelled', 2: 'success', }[slot_fact.status] if slot_fact.patient: card: Card = slot_fact.patient card_pk = card.pk if slot_fact.service: service = { 'id': slot_fact.service_id, 'title': slot_fact.service.get_title(), } if slot_fact.direction: direction = { 'id': slot_fact.direction_id, } return status_response( True, data={ 'data': { 'id': s.pk, 'date': datetime.datetime.strftime(slot_datetime, '%Y-%m-%d'), 'time': datetime.datetime.strftime(slot_datetime, '%X'), 'hour': delta_to_string(current_slot_time), 'hourValue': slot_datetime.hour, 'minute': slot_datetime.minute, 'duration': duration, 'status': status, 'cardId': card_pk, 'baseId': base_pk, 'service': service, 'direction': direction, }, }, ) return status_response(False)
def create(request): data = data_parse( request.body, { 'card_pk': 'card', 'comment': 'str_strip', 'date': str, 'researches': list, 'phone': 'str_strip', 'hospitalDepartment': int, 'diagnosis': 'str_strip' }, { 'hospitalDepartment': None, 'diagnosis': None }, ) card: Card = data[0] comment: str = data[1] date: str = data[2] researches: List[int] = data[3] phone: str = data[4] hosp_department_id: Optional[int] = data[5] diagnosis: Optional[str] = data[6] if phone != card.phone: card.phone = phone card.save(update_fields=['phone']) hospital_researches = [ r for r in Researches.objects.filter(pk__in=researches) if r.is_hospital ] if len(hospital_researches) > 1: return JsonResponse({ "ok": False, "message": "Выбрано больше одной услуги" }) if len(hospital_researches) == 1: if not hosp_department_id: hosp_department_id = hospital_researches[0].podrazdeleniye.pk has_free_slots = check_available_hospital_slot_before_save( hospital_researches[0].pk, None, date) is_cito = has_group(request.user, 'Цито-запись в расписании') if not has_free_slots and not is_cito: return JsonResponse({ "ok": False, "message": "Нет свободных слотов" }) PlanHospitalization.plan_hospitalization_save( { 'card': card, 'research': hospital_researches[0].pk, 'date': date, 'comment': comment, 'phone': phone, 'action': 0, 'hospital_department_id': hosp_department_id, 'diagnos': diagnosis, }, request.user.doctorprofile, ) else: for research_pk in researches: ListWait.list_wait_save( { 'card': card, 'research': research_pk, 'date': date, 'comment': comment, 'phone': phone, }, request.user.doctorprofile, ) return JsonResponse({"ok": True})