def doctor_register(self, request): id = request.POST.get('doctor_id') phone = request.POST.get('phone_number') doctor = Doctor.objects.filter(doctor_id=id) doctor2 = Doctor.objects.filter(phone_number=phone) if doctor.count() == 1: return Response({'status': '用户已经存在'}) elif doctor2.count() == 1: return Response({'status': '此手机号已经注册'}) doctor_serializer = DoctorSerializer(data=request.data) if doctor_serializer.is_valid(): doctor_serializer.save() return Response(status=status.HTTP_200_OK) else: return Response(doctor_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class VisitSerializer(serializers.ModelSerializer): patient = PatientSerializer(many=False, required=False) doctor = DoctorSerializer(many=False) visit_hour = WorkingHourSerializer(many=False, read_only=False) class Meta: model = Visit fields = ('id', 'date', 'visit_hour', 'patient', 'doctor') read_only_fields = ('visit_hour', 'patient', 'doctor') def create(self, validated_data): data = self.context['request'].data user = self.context['request'].user print(data) print(user) if user.role == 'patient': date = data.get('date') hour = WorkingHour.objects.get(pk=data['visit_hour']['id']) doctor = Doctor.objects.get(pk=data['doctor']['id']) if not Visit.objects.filter( Q(date=date) & Q(visit_hour=hour) & Q(doctor=doctor)).exists(): visit = Visit() visit.date = date visit.visit_hour = hour visit.doctor = doctor visit.patient = user.patient_set.first() visit.save() return visit raise PermissionDenied('Оnly patients can create visits')
def doctor_login(self, request): phone = request.POST.get('phone_number') psw = request.POST.get('password') try: result = Doctor.objects.get(phone_number=phone, password=psw) except: return Response({'status': '用户不存在'}) serializer = DoctorSerializer(result, context={'request': request}) return Response(serializer.data)
class AnswerDisplaySerializer(serializers.ModelSerializer): owner = DoctorSerializer() class Meta: model = Answer fields = ('id', 'question', 'owner', 'diagnosis', 'prescription', 'course', 'advice', 'picked', 'upvotes', 'comment_num', 'created') read_only_fields = ('picked', 'upvotes', 'comment_num', 'created')
def reports(request): user = request.user if (not user): return Response(status=status.HTTP_401_UNAUTHORIZED) clinic = Clinic.objects\ .annotate(rating=Avg('ratings__rating')) \ .prefetch_related('doctors') \ .get(id=user.adminAccount.employedAt.id) statsMonthly = (Appointment.objects .annotate(month=TruncMonth('date')) .values('month') .annotate(num=Count('id')) .order_by() ) statsDaily = (Appointment.objects .annotate(day=TruncDay('date')) .values('day') .annotate(num=Count('id')) .order_by() ) statsWeekly = (Appointment.objects .annotate(week=TruncWeek('date')) .values('week') .annotate(num=Count('id')) .order_by() ) clinicSerializer = ClinicSerializer(clinic, many=False) doctorSerializer = DoctorSerializer(clinic.doctors.annotate(rating=Coalesce(Avg('ratings__rating'),0)), many=True) return Response(status=status.HTTP_200_OK, data={ 'clinic': clinicSerializer.data, "doctors": doctorSerializer.data, "monthly" : statsMonthly, "daily": statsDaily, "weekly": statsWeekly })
def appointmentCheck(request): try: date = datetime.datetime.strptime(request.data['data']['appointmentDate'], '%Y-%m-%d') dateDay = date.weekday() appointmentType = request.data['data']['appointmentType'] except: return Response(status=status.HTTP_400_BAD_REQUEST, data={'msg':"Invalid parameters."}) try: schedule = Schedule.objects.filter(employee_id = OuterRef('email'), day=dateDay) appTypes = AppointmentType.objects.filter(clinic = OuterRef('employedAt'), typeName=appointmentType) doctors = Doctor.objects\ .annotate(busyHours = Coalesce(Sum(Case(When(appointments__date=date, then='appointments__typeOf__duration'))), 0), startTime= Subquery(schedule.values('startTime')[:1]), endTime = Subquery(schedule.values('endTime')[:1]), rating = Avg('ratings__rating'), duration = Subquery(appTypes.values('duration')), ) \ .filter(specializations__typeOf__typeName=appointmentType, busyHours__lte=((F('endTime')-F('startTime'))/60000000)-F('duration')).distinct() priceList = PriceList.objects.filter(clinic=OuterRef('id'), appointmentType__typeName=appointmentType) appointments = [] docs_on_holiday = [] for doc in doctors: holiday = Holiday.objects.filter(employee=doc.user, startDate__lte=date, endDate__gte=date, approved=True, resolved=True) if len(holiday) > 0: docs_on_holiday.append(doc.email) doctorElement = {'doctor':doc.email, 'time':[]} time = doc.startTime endTime = doc.endTime appointmentsQS = Appointment.objects.filter(doctor=doc, date=date) duration = doc.duration while(time_add(time, duration) <= endTime): time_advanced = False for app in appointmentsQS: appEndTime = time_add(app.time, app.typeOf.duration) nextEndTime = time_add(time, duration) if (app.time <= time < appEndTime or app.time < nextEndTime <= appEndTime): time = appEndTime time_advanced = True elif(time <= app.time < nextEndTime or time < appEndTime <= nextEndTime ): time = appEndTime time_advanced = True if time_advanced: continue doctorElement['time'].append(time) time = time_add(time, duration) appointments.append(doctorElement) doctors = doctors.exclude(email__in=docs_on_holiday) clinics = Clinic.objects. \ annotate(rating=Avg('ratings__rating'), appointmentPrice=Subquery(priceList.values('price'))). \ filter(doctors__in=doctors).distinct() print(request.data) if request.data['queryParams']['clinicLocation'] != '': clinics = clinics.filter(address=request.data['queryParams']['clinicLocation']) if request.data['queryParams']['clinicMinRating'] != '': clinics = clinics.filter(rating__gte=request.data['queryParams']['clinicMinRating']) if request.data['queryParams']['clinicMaxRating'] != '': clinics = clinics.filter(rating__lte=request.data['queryParams']['clinicMaxRating']) if request.data['queryParams']['doctorName'] != '': doctors = doctors.filter(firstName__startswith=request.data['queryParams']['doctorName']) if request.data['queryParams']['doctorLastName'] != '': doctors = doctors.filter(lastName__startswith=request.data['queryParams']['doctorLastName']) if request.data['queryParams']['doctorMinRating'] != '': doctors = doctors.filter(rating__gte=request.data['queryParams']['doctorMinRating']) if request.data['queryParams']['doctorMaxRating'] != '': doctors = doctors.filter(rating__lte=request.data['queryParams']['doctorMaxRating']) print(doctors, clinics) clinics = clinics.filter(doctors__in=doctors) docSer = DoctorSerializer(doctors, many=True) clinicSer = ClinicSerializer(clinics, many=True) return Response(status=status.HTTP_200_OK, data={"doctors": docSer.data, "clinics": clinicSer.data, "availableTerms":appointments}, content_type='application/json') except Exception as inst: return Response(status=status.HTTP_400_BAD_REQUEST, data={'msg':'Cannot book an appointment.'})