def get_context_data(self, **kwargs): kwargs = super(DoctorWelcome, self).get_context_data(**kwargs) access_token = get_token() dt_api = DoctorEndpoint(access_token) ap_api = AppointmentEndpoint(access_token) pt_api = PatientSummaryEndpoint(access_token) doctor = next(dt_api.list()) appointments = list(ap_api.list(date=dt.date.today())) app_list = [] for a in appointments: patient_info = pt_api.fetch(id=a["patient"]) a["patient_info"] = patient_info a['start_time'] = dt.datetime.strptime(a["scheduled_time"], "%Y-%m-%dT%H:%M:%S") a['end_time'] = a["start_time"]\ + dt.timedelta(minutes=int(a["duration"])) updated_at = dt.datetime.strptime(a['updated_at'], "%Y-%m-%dT%H:%M:%S") wait_time = dt.datetime.now() - updated_at a["wait_time"] = round(wait_time.total_seconds() / 60) app_list.append(a) confirmed = filter(lambda x: x["status"] == "", app_list) current = filter(lambda x: x["status"] == "In Session", app_list) arrived = filter(lambda x: x["status"] == "Arrived", app_list) complete = filter(lambda x: x["status"] == "Complete", app_list) kwargs['doctor'] = doctor kwargs['confirmed'] = confirmed kwargs['current'] = current kwargs['arrived'] = arrived kwargs['complete'] = complete return kwargs
def make_api_request(self): """ Use the token we have stored in the DB to make an API request and get doctor details. If this succeeds, we've proved that the OAuth setup is working """ # We can create an instance of an endpoint resource class, and use it to fetch details access_token = self.get_token() self.request.session['access_token'] = access_token doctor_api = DoctorEndpoint(access_token) patient_api = PatientEndpoint(access_token) apppointment_api = AppointmentEndpoint(access_token) # Grab the first doctor from the list; normally this would be the whole # practice group, but your hackathon account probably only has one doctor in it. doctor = doctor_api.get_and_store_data() self.request.session['doctor'] = doctor.id # Get patients and appointments for the doctor and store it in the local DB patient_api.get_and_store_data(doctor=doctor) date = datetime.now( tz=pytz.timezone(doctor.timezone)).strftime('%Y-%m-%d') apppointment_api.get_and_store_data(doctor=doctor, date=date) return doctor
def list(self, request): oauth_provider = UserSocialAuth.objects.get(provider='drchrono') access_token = oauth_provider.extra_data['access_token'] api = DoctorEndpoint(access_token) doctor = next(api.list()) request.session['doctor'] = doctor['id'] today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) # today = datetime.strptime("2019-12-16", "%Y-%m-%d") tomorrow = today + timedelta(days=1) queryset = Appointment.objects.filter( scheduled_time__gte=today, scheduled_time__lte=tomorrow, doctor=doctor['id'] ).order_by('scheduled_time') serializer = retrieveAppointmentSerializer(queryset, many=True) avg_wait_time = Appointment.objects.filter( scheduled_time__gte=today, scheduled_time__lte=tomorrow, doctor=doctor['id'], waiting_time__isnull=False ).aggregate(models.Avg('waiting_time'))['waiting_time__avg'] if avg_wait_time: avg_wait_time = round(avg_wait_time, 2) return Response({'appointments': serializer.data, 'avg_wait_time' : avg_wait_time, 'current_time':now()}, template_name='index.html')
def get_doctor(self, doctor_id): """ :param doctor_id: doctor id :return: doctor info """ api = DoctorEndpoint(self.access_token) return api.fetch(doctor_id)
def make_doctor_api_request(request, access_token): doctor_api = DoctorEndpoint(access_token) detail = next(doctor_api.list()) doctor, _ = Doctor.objects.get_or_create( id=detail["id"], user=request.user, first_name=detail["first_name"], last_name=detail["last_name"], office_phone=detail["office_phone"]) return DoctorSerializer(instance=doctor).data
def make_api_request(self): """ Use the token we have stored in the DB to make an API request and get doctor details. If this succeeds, we've proved that the OAuth setup is working """ # We can create an instance of an endpoint resource class, and use it to fetch details access_token = self.get_token() api = DoctorEndpoint(access_token) self.request.session["access_token"] = access_token return api.save_doctor()
def doc_db_save(self, token): """ Save doctor info to doctor table """ doc_api = DoctorEndpoint(token) for p in doc_api.list(): doctor = models.Doctor(doctor_id=p[u'id'], first_name=p[u'first_name'], last_name=p[u'last_name'], \ specialty=p[u'specialty'], cell_phone=p[u'cell_phone'], email=p[u'email']) doctor.save() return
def get_doctor(self): """ Use the token we have stored in the DB to make an API request and get doctor details. If this succeeds, we've proved that the OAuth setup is working """ # We can create an instance of an endpoint resource class, and use it to fetch details api = DoctorEndpoint(self.access_token) # Grab the first doctor from the list; normally this would be the whole practice group, but your hackathon # account probably only has one doctor in it. return next(api.list())
def get_doctors(self): """ Get all doctors (without pagenating), should only contain 1, for developer API Using ID as key """ access_token = self.get_token() api = DoctorEndpoint(access_token) for doctor in list(api.list()): self.doctors[doctor['id']] = doctor return self.doctors
def manage_doctor(request): if request.method == 'POST': oauth_provider = UserSocialAuth.objects.get(provider='drchrono') access_token = oauth_provider.extra_data['access_token'] api = DoctorEndpoint(access_token) for p in api.list(): doctor = models.Doctor(doctor_id=p[u'id'], first_name=p[u'first_name'], last_name=p[u'last_name'], \ specialty=p[u'specialty'], cell_phone=p[u'cell_phone'], email=p[u'email']) doctor.save() else: pass doctor_db = models.Doctor.objects.all() return render(request, 'patient_checkin.html', {})
def make_api_request(self): """ Use the token we have stored in the DB to make an API request and get doctor details. If this succeeds, we've proved that the OAuth setup is working """ # We can create an instance of an endpoint resource class, and use it to fetch details access_token = utility.get_token() api = DoctorEndpoint(access_token) # Grab the first doctor from the list; normally this would be the whole practice group, but your hackathon # account probably only has one doctor in it. # u'date_of_last_appointment': u'2020-02-14' gives todays appnt return next(api.list())
def make_api_request(self): """ Use the token we have stored in the DB to make an API request and get doctor details. If this succeeds, we've proved that the OAuth setup is working """ # We can create an instance of an endpoint resource class, and use it to fetch details access_token = self.get_token() self.request.session['access_token'] = access_token doctor = DoctorEndpoint(access_token).get_doctor() self.request.session['doctor'] = doctor # Grab the first doctor from the list; normally this would be the whole practice group, but your hackathon # account probably only has one doctor in it. #doctor = DoctorEndpoint(access_token).get_doctor() #self.request.session['doctor'] = doctor.id # I don't think I want to get patient info here. patient_details = PatientEndpoint(access_token).get_patients( doctor['id']) patient_details = CreatePatientIdTable(patient_details) appts = AppointmentEndpoint(access_token).get_appoinments( doctor['id'], datetime.now()) # Get patients and appointments for the doctor and store it in the local DB CreateTemplateIdTable(appts, patient_details) appts = GetTemplateIdTable() return doctor
def get_context_data(self, **kwargs): token = get_token() #kwargs = super(DoctorWelcome, self).get_context_data(**kwargs) # Hit the API using one of the endpoints just to prove that we can # If this works, then your oAuth setup is working correctly. self.apt_db_save(get_token()) doctor_details = DoctorEndpoint(token) kwargs['doctor'] = doctor_details return kwargs
def get_current_doctor(self, user): """ Use the token we have stored in the DB to make an API request and get doctor details. If this succeeds, we've proved that the OAuth setup is working """ access_token = self.get_token() api = DoctorEndpoint(access_token) doctor_data = next(api.list()) Doctor.objects.update_or_create(defaults={ 'user': user, 'first_name': doctor_data['first_name'], 'last_name': doctor_data['last_name'], 'office_phone': doctor_data['office_phone'] }, id=doctor_data['id']) return doctor_data
def save_doctor(token, doctor_id): """ This function fetches the doctor object using the id proved and saves it in the db. :param token: Access token :param doctor_id: Unique id of a doctor :return: """ doctor = DoctorEndpoint(access_token=token).fetch(doctor_id) Doctor.objects.get_or_create(id=doctor["id"], first_name=doctor["first_name"], last_name=doctor["last_name"], doctor_photo=doctor["profile_picture"])
def make_api_request(self): """ Use the token we have stored in the DB to make an API request and get doctor details. If this succeeds, we've proved that the OAuth setup is working """ # We can create an instance of an endpoint resource class, and use it to fetch details access_token = self.get_token() try: doctor = next(DoctorEndpoint(access_token).list()) except APIException: return None return doctor
def setUp(self): self.doctor_endpoint = DoctorEndpoint() self.doctor_welcome = DoctorWelcome() self.user_model = get_user_model() self.user = self.user_model.objects.create_user( username='******', email='*****@*****.**') self.access_token = "secret" self.usa = UserSocialAuth.objects.create( user=self.user, provider='drchrono', uid='1234', extra_data={ "access_token": self.access_token, "expires_in": 172800, "refresh_token": "wWdSgnBSwLZs1XEwxxG0CE8JRFNAjm", "auth_time": 1575496917})
def make_api_request(self): """ Use the token we have stored in the DB to make an API request and get doctor details. If this succeeds, we've proved that the OAuth setup is working """ # We can create an instance of an endpoint resource class, and use it to fetch details access_token = self.get_token() self.request.session['access_token'] = access_token # Grab the first doctor from the list; normally this would be the whole # practice group, but your hackathon account probably only has one doctor in it. doctor = DoctorEndpoint(access_token).get_doctor() #self.request.session['doctor'] = doctor.id patient = PatientEndpoint(access_token).get_patients(doctor) appt = AppointmentEndpoint(access_token).get_appoinments(doctor, None) # Get patients and appointments for the doctor and store it in the local DB return doctor
def make_api_requests(self): """ Use the token we have stored in the DB to make an API request and get doctor details. If this succeeds, we've proved that the OAuth setup is working. Populate Doctor, Patient, and Appointment tables. """ access_token = self.get_token() doctor_endpoint = DoctorEndpoint(access_token) utils.populate_doctors(doctor_endpoint) doctor = Doctor.objects.first() self.request.session['doctor_id'] = doctor.id self.request.session['access_token'] = access_token # Populate patient and appointment tables with patients and appointments for the given doctor. patient_endpoint = PatientEndpoint(access_token) utils.populate_patients(patient_endpoint, doctor) appointment_endpoint = AppointmentEndpoint(access_token) utils.populate_appointments(appointment_endpoint, doctor) return doctor
def post(self, request, *args, **kwargs): # create a form instance and populate it with data from the request: form = CheckInForm(request.POST) # we need to get the list of pacents on the appointment to check if they are checking in or if its a walk-in data = request.POST.copy() ssn = data.get('ssn') access_token = get_token() appointment_api = AppointmentEndpoint(access_token) if form.is_valid() and check_ssn_format(ssn): first_name, last_name, date_of_birth = form.cleaned_data.get('first_name'), \ form.cleaned_data.get('last_name'), \ form.cleaned_data.get('date').strftime('%Y-%m-%d') # here we get data from App and Pa django objects instead p = Patient.objects.get(first_name=first_name, last_name=last_name, date_of_birth=date_of_birth, social_security_number=ssn) try: p = Patient.objects.get(first_name=first_name, last_name=last_name, date_of_birth=date_of_birth, social_security_number=ssn) except Patient.DoesNotExist: p = None if not p: return HttpResponseRedirect('/patient_new/') wi = form.cleaned_data.get('walk_in') if wi: doctor = next(DoctorEndpoint(get_token()).list()) create_appointment = { 'status': 'Arrived', 'duration': 30, 'date': timezone.now(), 'doctor': doctor.get('id'), 'patient': p.patient_id, 'scheduled_time': timezone.now(), 'exam_room': 0, 'office': 276816, # hardcoded for now 'notes': 'Walk-In' } created_appointment = appointment_api.create( create_appointment) appointment, created = Appointment.objects.get_or_create( appointment_id=created_appointment.get('id'), patient_id=p.patient_id, scheduled_time=created_appointment.get('scheduled_time'), notes=created_appointment.get('notes')) else: today = timezone.now() try: appointment = Appointment.objects.get( patient_id=p.patient_id, scheduled_time__year=today.year, scheduled_time__month=today.month, scheduled_time__day=today.day) except Appointment.DoesNotExist: form.add_error( 'first_name', "We are sorry, but we could not find you on todays list, is this a walk-in?" ) return render(request, 'patient_check_in.html', {'form': form}) appointment_api.update(appointment.appointment_id, {'status': 'Arrived'}) if (appointment.status == 'Arrived'): # Here we return that they have already checked in return redirect('patient_demographic_information', patient_id=p.patient_id) appointment.arrival_time = timezone.now() appointment.status = 'Arrived' appointment.save() # redirect to demographic information page return redirect('patient_demographic_information', patient_id=p.patient_id) form.add_error('ssn', "Please Enter a Valid SSN in format 123-44-1234") return render(request, 'patient_check_in.html', {'form': form})
def get(self, request, *args, **kwargs): # GET send a blank form for the patient template = 'patient_new.html' doctor = next(DoctorEndpoint(get_token()).list()) return render(request, template, {'doctor': doctor})
def list(self, request): doctors = list(DoctorEndpoint(self.get_token()).list()) return Response(doctors)
def doctor_details(self): access_token = self.get_token() api = DoctorEndpoint(access_token) return next(api.list())
def retrieve(self, request, pk=None): doctor = DoctorEndpoint(self.get_token()).fetch(pk) return Response(doctor)
def get_context_data(self, **kwargs): """ :param kwargs: :return: """ kwargs = super(DoctorWelcome, self).get_context_data(**kwargs) # look for oauth user, so we can use it's access_token oauth_provider = get_object_or_404(UserSocialAuth, provider='drchrono') # check if token is about to expire, and refresh it if so if self.is_access_token_expired( oauth_provider.extra_data['access_token']): oauth_provider.refresh_token(load_strategy()) access_token = oauth_provider.extra_data['access_token'] patient_client = PatientEndpoint(access_token) appointments_client = AppointmentEndpoint(access_token) # information about the doctor kwargs['doctor'] = next(DoctorEndpoint(access_token).list()) # list of patients patients = list(patient_client.list()) # list of today's appointments today_str = timezone.now().strftime('%m-%d-%y') todays_appointments = list( appointments_client.list({}, start=today_str, end=today_str)) for appointment in todays_appointments: patient = [ patient for patient in patients if patient.get('id') == appointment.get('patient') ][0] appointment['first_name'] = patient.get('first_name') appointment['last_name'] = patient.get('last_name') kwargs['appointments'] = todays_appointments # fetch information about patients who have checked in visits = Visit.objects.filter(status='Arrived', arrival_time__isnull=False, start_time__isnull=True).all() for visit in visits: visit.wait_since_arrived = visit.get_wait_duration().seconds patient = [ patient for patient in patients if patient.get('id') == visit.patient_id ][0] visit.first_name = patient.get('first_name') visit.last_name = patient.get('last_name') kwargs['arrived'] = visits # fetch information about our current appointment current_appointment = Visit.objects.filter( status='In Session', arrival_time__isnull=False, start_time__isnull=False).first() if current_appointment: kwargs['current_appointment'] = current_appointment current_appointment.visit_duration = current_appointment.get_visit_duration( ).seconds patient = [ patient for patient in patients if patient.get('id') == current_appointment.patient_id ][0] current_appointment.first_name = patient.get('first_name') current_appointment.last_name = patient.get('last_name') current_appointment.date_of_birth = patient.get('date_of_birth') current_appointment.date_of_last_appointment = patient.get( 'date_of_last_appointment') current_appointment.race = patient.get('race') current_appointment.gender = patient.get('gender') current_appointment.ethnicity = patient.get('ethnicity') # create list of past visit, and use it to generate average wait and visit duration past_visits = Visit.objects.filter(status="Finished", arrival_time__isnull=False, start_time__isnull=False).all() if len(past_visits) > 0: avg_wait_time = sum( [(visit.start_time - visit.arrival_time).seconds for visit in past_visits]) / len(past_visits) kwargs['avg_wait_duration'] = math.ceil(avg_wait_time) avg_visit_duration = sum( [(visit.end_time - visit.start_time).seconds for visit in past_visits]) / len(past_visits) kwargs['avg_visit_duration'] = math.ceil(avg_visit_duration) kwargs['avg_wait_duration'] = "You have no arrivals! - 0" kwargs['avg_visit_duration'] = "You have no visits! - 0" else: kwargs['avg_wait_duration'] = "You have no arrivals! - 0" kwargs['avg_visit_duration'] = "You have no visits! - 0" # creating altair visualization # create a df with list of times and durations visit_data = [{ 'start_time': visit.arrival_time, 'arrival_time': visit.start_time, 'wait_duration': visit.get_visit_duration().seconds, 'visit_duration': visit.get_wait_duration().seconds, } for visit in past_visits] visit_data_df = pd.DataFrame(visit_data) # https://altair-viz.github.io/user_guide/interactions.html#selections-building-blocks-of-interactions brush = alt.selection_interval(encodings=['x']) chart = alt.Chart(visit_data_df).mark_bar().properties( width=300, height=150).add_selection(brush) # combine two charts one with wait duration and one with visit duration kwargs['chart'] = alt.hconcat( chart.encode(x=alt.X( 'start_time:T', axis=alt.Axis(title='Time the visit started')), y=alt.Y('wait_duration:Q', axis=alt.Axis(title='Wait Duration')), color=alt.condition(brush, alt.value('black'), alt.value('lightgray'))), chart.encode( x=alt.X('start_time:T', axis=alt.Axis(title='Time the visit started')), y=alt.Y('visit_duration:Q', axis=alt.Axis(title='Visit Duration')), color=alt.condition( brush, alt.value('black'), alt.value('lightgray')))).resolve_scale(y='shared') return kwargs