コード例 #1
0
    def get_appointments(self, doctor):
        """
        Return all appointments for today

        TODO: Performing local db sync on page load slows performance, even if by a non-negligible amount
              Write cron/celery task to periodically sync so we can remove the API call from here
        """
        access_token = self.get_token()
        api = AppointmentEndpoint(access_token)
        apts_api = api.list(params={"verbose": True, "doctor": doctor['id']}, date=self.today_date)
        for apt in apts_api:
            try:
                #  TODO: Update status locally if value from API result differs
                apt_db = Appointment.objects.get(id=apt['id'])
                #  Check if status has changed and update if needed
                # if apt_db.status != apt['status']:
                #     apt_db.status = apt['status']
                #     apt_db.save()
            except Appointment.DoesNotExist:
                Appointment.create_from_api(apt, access_token)

        # Sort appointments by status, in order of time_spent_waiting
        yesterday = datetime.today() - timedelta(days=1)
        apts_db = Appointment.objects\
            .filter(scheduled_time__gt=yesterday)\
            .exclude(status=Appointment.IN_SESSION)\
            .order_by(Appointment.ORDER_HIERARCHY)
        return apts_db
コード例 #2
0
ファイル: views.py プロジェクト: clllyw/Project
def addapp(request):
    fff = True
    teacherlist = Teacher.objects.all()   
    c = Context({"teacherlist":teacherlist})
    u=User.objects.all()
    for mu in u:
        mu1=mu
    if "seleted_teacher" in request.POST:
        tea=Teacher.objects.get(id=request.POST["seleted_teacher"])
        apps = Appointment.objects.filter(tea_name = tea.Username)
        for t in apps:
            if t.app_time == request.POST["requestdate"]:
                fff = False
        if fff == True:
            new_appointment = Appointment( 
            stu_name =  mu1.Username,
            tea_name = tea.Username,
            app_time = request.POST["requestdate"],
            flag = "no")       
            new_appointment.save()
            u=User.objects.all()
            for mu in u:
                mu1=mu
            applist=Appointment.objects.filter(stu_name=mu1.Username)
            c = Context({"applist":applist,})
            return render_to_response("requestm.html",c)
        else:
            return HttpResponse("Time interrupt!")
    
    else:
        return render_to_response("request.html",c)
コード例 #3
0
 def load_appointments(self, doctor_timezone):
     """
     Load all of today's appointments for the logged in doctor
     """
     access_token = self.get_token()
     api = AppointmentEndpoint(access_token)
     today = datetime.datetime.now()
     today = today.strftime('%Y-%m-%d')
     appointments = api.list(date=today)
     for a in appointments:
         patient = self.get_patient(a['patient'])
         patient_name = patient['first_name'] + ' ' + patient['last_name']
         check_in_time = None
         seen_time = None
         print(a['status'])
         if a['status'] in ['In Session', 'Complete']:
             seen_time = datetime.datetime.now()
         elif a['status'] in ['Arrived', 'Checked In', 'In Room']:
             check_in_time = datetime.datetime.now()
             print('CHECKED IN')
         appointment = Appointment(
             drchrono_id=a['id'],
             doctor=a['doctor'],
             patient_name=patient_name,
             patient_id=a['patient'],
             scheduled_time=datetime.datetime.strptime(
                 a['scheduled_time'], '%Y-%m-%dT%H:%M:%S'),
             duration=a['duration'],
             status=a['status'],
             check_in_time=check_in_time,
             seen_time=seen_time)
         appointment.save()
コード例 #4
0
ファイル: appointment.py プロジェクト: yb7984/Capstone1
    def insert(username):
        """New Appointment"""
        form = AppointmentForm(obj=request.json, prefix="appointment")

        if form.validate():
            event_id = ''
            service_id = form.service_id.data
            provider_username = form.provider_username.data
            customer_username = login_username()
            service_date = form.service_date.data
            times = form.times.data
            note = form.note.data

            if provider_username == customer_username:
                return {
                    "error":
                    "You are not supposed to book the service from yourself!"
                }

            if len(times) == 0:
                form.times.errors.append("Must select an appointment time!")

            [start, end] = times.split("-")

            item = Appointment(event_id='',
                               service_id=service_id,
                               provider_username=provider_username,
                               customer_username=customer_username,
                               start=datetime.datetime.combine(
                                   service_date,
                                   datetime.time.fromisoformat(start)),
                               end=datetime.datetime.combine(
                                   service_date,
                                   datetime.time.fromisoformat(end)),
                               note=note)

            if not item.available:
                # time conflict return error
                return {
                    "error":
                    "Selected appointment time is not available now. Please choose another time frame!"
                }

            if len(form.errors) == 0:

                db.session.add(item)
                db.session.commit()

                # set the google calendar event
                AppointmentHandler.set_google_calendar(item)

                # todo email to the provider and the customer
                AppointmentHandler.email(item)

                return {"item": item.serialize()}
        return {"errors": form.errors}
コード例 #5
0
def new_appointment(app_id, fname, lname):
    appointment = Appointment()
    now = datetime.now()
    appointment.app_id = app_id
    appointment.time_of_arrival = now
    appointment.first_name = fname
    appointment.last_name = lname
    appointment.save()
コード例 #6
0
def populate_database(num_patients, min_checkins, max_checkins):
    """
    Generates a number of Patients and a number of CheckIns per patient and
    stores them in the database.

    Arguments
    num_patients    -- the number of patients to generate
    min_checkins -- the minimum number of CheckIns to generate per Patient
    max_checkins -- the maximum number of CheckIns to generate per Patient

    """
    departments = [
        Department(department_name="Cardiology"),
        Department(department_name="Emergency"),
        Department(department_name="Gynecology"),
        Department(department_name="Pediatrics"),
        Department(department_name="Obstetrics"),
        Department(department_name="Oncology"),
        Department(department_name="Orthopedics"),
        Department(department_name="Neurology")
    ]

    for i in xrange(num_patients):
        patient = Patient(**generate_patient())
        patient.departments.append(choice(departments))
        db.add(patient)

        for j in xrange(randrange(min_checkins, max_checkins)):
            checkin = CheckIn(**generate_checkin())
            checkin.patient_nhi = patient.nhi

            lci = patient.latest_checkin_time
            vid = checkin.checkin_time

            lci = vid if lci is None or vid > lci else lci
            patient.latest_checkin_time = lci

            db.add(checkin)

        for k in xrange(randrange(0, 3)):
            appointment = Appointment(**generate_appointment())
            appointment.patient_nhi = patient.nhi

            db.add(appointment)

    db.commit()
コード例 #7
0
ファイル: utils.py プロジェクト: brianthf/Appointa-Backend
def map_json_to_appointment(data: dict) -> Appointment:
    type = data.get('type', None)
    client_id = data.get('clientId', None)
    address_id = data.get('addressId', None)
    description = data.get('description', None)
    date = data.get('date', None)
    time = data.get('time', None)

    return Appointment(type, client_id, address_id, description, date, time)
コード例 #8
0
ファイル: tapin.py プロジェクト: hugarsthealth/tapin-portal
def patient_appointments(nhi):
    if request.method == "GET":
        offset = int(request.args.get('offset', 0))
        limit = int(request.args.get('limit', 100))

        return make_response((json.dumps([
            a.serialize() for a in Appointment.query
            .filter_by(patient_nhi=nhi)
            .order_by(desc(Appointment.time))
            .offset(offset)
            .limit(limit)
        ]), 200, {"Content-Type": "application/json"}))

    elif request.method == "POST":
        appointment = Appointment(**json.loads(request.data))
        db.commit()

        return jsonify(appointment.serialize())
コード例 #9
0
    def create_appointment(payload):
        # Get values from the request
        body = request.get_json()
        artist_id = body.get('artist', None)
        client_id = body.get('client', None)
        appt_date = body.get('appointment_date', None)

        # Appointment will not be created if it does not
        # include an appointment date
        if appt_date is None:
            abort(422)

        appointment_date = format_datetime(appt_date)

        new_appt = Appointment(client=client_id,
                               artist=artist_id,
                               appointment_date=appointment_date)
        # Insert the new appointment into the database
        try:
            new_appt.insert()
        except:
            return abort(422)

        # Get the appointment in the database by matching the artist
        # and appointment time
        posted_appt = Appointment.query.filter(
            Appointment.artist == new_appt.artist).filter(
                Appointment.appointment_date ==
                new_appt.appointment_date).order_by(Appointment.id).all()[-1]

        formatted_appt = posted_appt.format()

        # Return an array containing all upcoming appointments
        now = datetime.now()
        upcoming_appointments = Appointment.query.filter(
            Appointment.appointment_date > now).all()
        return jsonify({
            'success':
            True,
            'appointment':
            formatted_appt,
            'total_upcoming_appointments':
            len(upcoming_appointments)
        })
コード例 #10
0
ファイル: user_service.py プロジェクト: pabvald/chatbot2
    def make_appointment(self, t_date, t_time, topic):
        """ Makes an appointment for the user. """
        try:
            appointment = Appointment(t_date, t_time, topic, self.user_id)
            db.session.add(appointment)
            db.session.commit()

        except Exception as e:
            app.logger.error(str(e))
            raise
コード例 #11
0
def process_iden_conversation(msg, created=True, conv=None):
    resp = VoiceResponse()
    app.logger.info('customer is registered')
    conversation = new_conversation()
    if created:
        input_msg=''
    else:
        input_msg=request.form['SpeechResult'] if 'SpeechResult' in request.form else 'donno'
    app.logger.info('input_message [%s] created [%s]', input_msg, created)
    #conv.log_json()
    watson_response = new_conversation_msg(conversation, context=conv.context, input_msg=input_msg, first=False)
    conv.store_context()
    # check if watson identified the customer
    twilio_resp, watson_dialog = create_response(watson_response, conv, twilio_voice=resp)
    app.logger.info('output_message [%s] ', watson_dialog)
    if 'action' in conv.context:
        if conv.context['action'] == 'register_customer':
            cust=Customer.create(
                name=str(conv.context['name']).lower(),
                business=conv.business,
                phone=conv.call_number
            )
            conv.customer = cust
        elif conv.context['action'] == 'create_app':
            app_date = conv.context['app_date']
            app_time = conv.context['app_time']
            start = datetime.strptime(f"{app_date} {app_time}", '%Y-%m-%d %H:%M:%S')
            end = start+timedelta(hours=float(conv.context['app_duration']))
            appoint = Appointment(
                customer=conv.customer,
                note='tutoring',
                start=start,
                end=end
            )
            app.logger.info(f"created a new appointment {start} to {end}")
            appoint.save()
            conv.context['success'] = 'true'
        elif conv.context['action'] == 'end':
            twilio_resp.hangup()
        conv.context.pop('action', None)
    conv.save()
    return str(resp)
コード例 #12
0
def save_appointments(appointments):
    """

    :param appointments:
    Saves Appointment
    """
    for appt in appointments:
        appointment = Appointment(
            id=appt['id'],
            duration=appt['duration'],
            doctor=Doctor.objects.get(pk=appt['doctor']),
            patient=Patient.objects.get(pk=appt['patient']),
            office=Office.objects.get(pk=appt['office']),
            exam_room=appt['exam_room'],
            reason=appt['reason'],
            status=appt['status'],
            deleted_flag=appt['deleted_flag'],
            scheduled_time=appt['scheduled_time'],
            in_room_time=appt['scheduled_time'],
        )
        print appointment
        appointment.save()
コード例 #13
0
def add_appointment():
    date = input('Insira a data da consulta (dd/MM/YYYY): ')

    while True:
        try:
            crm = input('Insira o crm do médico: ')
            _doctor = get_doctor_by_crm(crm)

            if not _doctor:
                raise Exception("Nenhum médico encontrado!")
        except Exception as e:
            print(e)
        else:
            break

    while True:
        try:
            cpf = input('Insira o CPF do paciente: ')
            _patient = get_patient_by_cpf(cpf)

            if not _patient:
                raise Exception("Nenhum paciente foi encontrado!")
        except Exception as e:
            print(e)
        else:
            break

    while True:
        try:
            appointment_type = int(
                input(
                    "Insira o tipo da consulta (1 - Primeira consulta ou 2 - Consulta de retorno): "
                ))

            if appointment_type != AppointmentType.FIRST_APPOINTMENT and appointment_type != AppointmentType.RETURN_APPOINTMENT:
                raise Exception(
                    "Insira um tipo válido (1 - Primeira consulta ou 2 - Consulta de retorno)"
                )

        except Exception as e:
            print(e)
        else:
            break

    try:
        _appointment = Appointment(date, _doctor[0], _patient[0],
                                   appointment_type, Status.ACTIVE)
        create_appointment(_appointment)
    except Exception as e:
        print(e)
コード例 #14
0
ファイル: util.py プロジェクト: prajask/find-your-doctor
def book_appointment(doctor_id, appointment_information):
    date = appointment_information["date"].split('-')

    appointment = Appointment(patient=session["user"]["id"],
                              doctor=doctor_id,
                              time=datetime(
                                  int(date[0]), int(date[1]), int(date[2]),
                                  int(appointment_information["time"]), 0),
                              status="pending",
                              has_report=True)

    database.session.add(appointment)

    database.session.commit()
コード例 #15
0
ファイル: salon.py プロジェクト: Skwanch/Salon
def schedule_appt(date, time, username, stylist):
    if g.patron:
        if g.patron.username == username:

            stylist = Stylist.query.filter_by(username=stylist).first()
            date = datetime.strptime(date, '%Y-%m-%d')
            time = datetime.strptime(time, '%H:%M:%S').time()
            datetime_obj = dt.datetime.combine(date, time)

            appt = Appointment(datetime_obj)#, get_stylist_id(stylist), g.patron.patron_id)
            appt.patron_id = g.patron.patron_id
            appt.stylist_id = stylist.stylist_id

            g.patron.appointments.append(appt)
            stylist.appointments.append(appt)
            db.session.add(appt)
            db.session.commit()
            flash('Appointment scheduled')
            return redirect(url_for('patron_profile', username = g.patron.username))
    if g.stylist:
        abort(401)
    if g.owner:
        abort(401)
コード例 #16
0
ファイル: flask_s1.py プロジェクト: gordy2015/flask_s1
def add_appointment():
    if request.method == 'POST':
        ret = {'status': True, 'info': 'None', 'data': None}
        try:
            u = request.form.get('user')
            p = request.form.get('phone')
            a = request.form.get('address')
            n = request.form.get('note')
            s = request.form.getlist('service_type')
            ad = request.form.get('appointment_date')
            t = request.form.get('time')
            if u and p and a and s:
                logging.info(u, p, a, n, s, ad, t)
                inp = "user={u},phone={p},address={a},note={n},pt_id={t}".format(u=u,p=p,a=a,n=n,t=t)
                l = ad.replace("-","")
                curr_date = datetime.date.today().strftime("%Y-%m-%d")
                if int(l) < int(curr_date.replace("-","")):
                    ret['status'] = False
                    ret['info'] = '选择的日期最早是今天{date}'.format(date=curr_date)
                    # q = Appointment.query.filter(Appointment.user == u, Appointment.phone == p,Appointment.address==a,
                    #                                    Appointment.note==n, Appointment.pt_id==t).all()
                    # if q:
                    #     ret['status'] = False
                    #     ret['info'] = '您已预约过了'
                else:
                    r_num = randomnum()
                    ins = Appointment(user=u,phone=p,address=a,note=n,pt_id=t, appoint_num=r_num, appoint_date=ad)
                    db.session.add(ins)
                    db.session.commit()
                    q = Appointment.query.filter(Appointment.user == u, Appointment.phone == p,Appointment.address==a,
                                                   Appointment.note==n, Appointment.pt_id==t).all()
                    for i in q:
                        aid = i.id
                    for i in s:
                        w = Appoint_ser(st_id=i,appoint_id=aid,appoint_num=r_num)
                        db.session.add(w)
                        db.session.commit()
                    ret['status'] = True
                    ret['info'] = '预约成功,您的预约号为{r_num}'.format(r_num=r_num)

            else:
                ret['status'] = False
                ret['info'] = '输入内容不能为空'
            logging.debug(ret)
        except Exception as e:
            logging.error(e)
            ret['status'] = False
            ret['info'] = 'request error'
        return json.dumps(ret)
コード例 #17
0
def import_csv():
    filename = os.path.join(SITE_ROOT, 'appointments.csv')
    with open(filename, 'r') as csvfile:
        csvreader = csv.reader(csvfile)
        csvlist = list(csvreader)
        try:
            for row in csvlist:
                datetime_string = row[1] + ' ' + row[2]
                appointment_datetime = datetime.strptime(datetime_string, '%d-%m-%Y %H:%M')
                appointment = Appointment(row[0], row[3], appointment_datetime)
                db.session.add(appointment)
                db.session.commit()
        except Exception as e:
            db.session.rollback()
            print(e)
コード例 #18
0
ファイル: tapin.py プロジェクト: hugarsthealth/tapin-portal
def patient_appointment(nhi, appointment_id):
    appointment = Appointment.query.filter_by(
        patient_nhi=nhi, appointment_id=appointment_id).first()

    if not appointment:
        return make_response("No appointment for patient {} with id {}".format(nhi, appointment_id))

    elif request.method == "GET":
        return jsonify(appointment.serialize())

    elif request.method == "POST":
        appointment_data = json.loads(request.data)
        appointment = Appointment(**appointment_data)
        appointment.appointment_id = appointment_id
        appointment = db.merge(appointment)
        db.commit()

        return jsonify(appointment.serialize())

    elif request.method == "DELETE":
        db.delete(appointment)
        db.commit()

        return make_response("Deleted appointment: {} from patient: {}".format(appointment_id, nhi), 200)
コード例 #19
0
def createAppointment():
    token = request.headers.get('Authorization')
    account = getCurrentUser(token)
    appointmentData = request.get_json()
    newAppointment = Appointment(date=appointmentData['date'],
                                 time=appointmentData['time'],
                                 centreId=appointmentData['centreId'],
                                 userId=appointmentData['userId'])
    if account['id'] == int(
            appointmentData['userId']) or account['userType'] == 'a':
        try:
            db.session.add(newAppointment)
            db.session.commit()
        except IntegrityError:
            db.session.rollback()
            return "Appointment already created.", 400
        return "Appointment created successfully.", 200
    return "Not authorized to access this page.", 401
コード例 #20
0
def appointment_create():
    """
    Provide HTML form to create a new appointment.
    """
    form = AppointmentForm(request.form)
    if request.method == 'POST' and form.validate():

        appt = Appointment(user_id=current_user.id)
        if appt.user_id != current_user.id:
            abort(403)

        form.populate_obj(appt)
        print("Start: {}".format(appt.start))

        db.session.add(appt)
        db.session.commit()
        # Success. Send user back to full appointment list.
        return redirect(url_for('appointment_list'))
    # Either first load or validation error at this point.
    return render_template('appointment/edit.html', form=form)
コード例 #21
0
    def get_appoinments(self, doctor, date):

        #check if a specific doctor was passed
        if not doctor:
            doctor = Doctor.objects.first()
            d = {}
        else:
            d = {'doctor': doctor.id}
        #check if a specific date was passed
        #if no date passed, get all appointments for next 30 days
        if not date:
            date = datetime.now()
            month_later = date + timedelta(days=30)
            date = date.strftime('%Y-%m-%d')
            month_later = month_later.strftime('%Y-%m-%d')
            appointments = self.list(params=d, start=date, end=month_later)
        else:
            appointments = self.list(params=d, date=date)

        for appt in appointments:
            status = appt['status']
            if not status:
                status = ""
            checked_in = Appointment.patient_checked_in(status)
            try:
                patient = Patient.objects.get(id=appt['patient'])
            except Patient.DoesNotExist:
                patient = None
            appt_fields = {
                'patient': patient,
                'doctor': doctor,
                'exam_room': appt['exam_room'],
                'duration': appt['duration'],
                'appt_time': appt['scheduled_time'],
                'status': status,
                'checked_in': checked_in,
                'reason': appt['reason']
            }
            updated_appt, created = Appointment.objects.update_or_create(
                defaults=appt_fields, pk=appt['id'])
コード例 #22
0
ファイル: schedule.py プロジェクト: yb7984/Capstone1
    def get_available_times(username, date, appointment_id=0):
        """Return the list of available times for a provider"""

        schedule = ScheduleHandler.get(username, date.isoformat())
        if schedule is None or schedule.is_active == False:
            # no specific date, check for the weekly schedule
            weekday = date.isoweekday()
            if weekday == 7:
                weekday = 0
            schedule = ScheduleHandler.get(username, str(weekday))

        if schedule is None or schedule.is_active == False or len(schedule.schedules) == 0:
            # no defined schedule
            return []

        times = json.loads(schedule.schedules)

        return [time for time in times if Appointment.check_available(
            username,
            start=datetime.datetime.combine(date , datetime.time.fromisoformat(time["start"])),
            end=datetime.datetime.combine(date , datetime.time.fromisoformat(time["end"])),
            appointment_id=appointment_id)]
コード例 #23
0
def add_stylist():
    if not session.get('logged_in'):
        abort(401)
    if not session.get('username') == 'owner':
        abort(401)
    new = Stylist(request.form['name'], request.form['password'])

    day = date.today().weekday()
    today = date.today()
    for i in range(7):
        if 1 <= day + i <= 6:
            for t in range(11):
                add = t + 8
                dt = datetime.combine(today, time(0, 0)) + timedelta(days=i, hours=(add + 2))
                a = Appointment(dt, new.id, -1)
                new.appointments.append(a)
                db.session.add(new)
                db.session.add(a)
                db.session.commit()

    flash('New entry was successfully posted')
    return redirect(url_for('owner_page'))
コード例 #24
0
def appoint(username=None, date=None, time=None):
    if "username" in session:
        stylist = Stylist.query.filter_by(username=session["username"]).first()
        owner = Owner.query.filter_by(username=session["username"]).first()
        if stylist is not None:
            abort(403)
        elif owner is not None:
            abort(403)
        if username == None or date == None or time == None:
            return redirect(url_for("pat"))

        db.session.add(Appointment(username, session["username"], date, time))
        appointments = OpenAppointment.query.filter_by(time=time).all()
        for x in appointments:
            if x.stylist_username == username and date == x.date:
                db.session.delete(x)

        db.session.commit()
        flash('appointment created')
        return redirect(url_for("pat"))

    abort(403)
コード例 #25
0
ファイル: views.py プロジェクト: ash-kai/api-example-django
def updateDemographic(request):
	if request.method=='POST':
		token = Token.objects.get(pk = request.session['user'])
		data = {
		"address" : request.POST['address'],
		"cell_phone" : request.POST['phone'],
		"zip_code" : request.POST['zipCode'],
		}
		patientId = request.POST['patientId']
		response = auth.updatePatientDemographicInfo(token, patientId, data)
		if response.status_code==400 or response.status_code==403 or response.status_code==409:
			messages.error(request, "Demographic data not updated.")
		else:
			messages.success(request, "Demographic data updated.")
		appointmentId = request.POST['appointmentId']
		status = "Arrived"
		update = auth.updatePatientAppointmentData(token, appointmentId, status)
		Appointment(appointmentId=appointmentId, checkIn = datetime.datetime.now()).save()
		if update.status_code==400 or update.status_code==403 or update.status_code==409:
			messages.error(request, "The status was not modified. Please try again")
		else:
			messages.success(request, "Check In successful")
		return redirect('home')
コード例 #26
0
def appointment(id=None):
    if request.method == 'GET':
        if id is not None:
            appoint = Appointment.query.get(id)
            if appoint:
                return jsonify(appoint.serialize()), 200
            else:
                return jsonify({"msg": "Appointment not found"}), 404
        else:
            appoints = Appointment.query.all()
            appoints = list(map(lambda appoint: appoint.serialize(), appoints))
            return jsonify(appoints), 200

    if request.method == 'POST':
        if not request.is_json:
            return jsonify({"msg": "Incorrect format"}), 400

        app_name = request.json.get('app_name', None)
        app_lastname = request.json.get('app_lastname', None)
        app_email = request.json.get('app_email', None)
        app_phone = request.json.get('app_phone', None)
        app_time = request.json.get('app_time', None)
        app_message = request.json.get('app_message', None)

        if not app_name or app_name == '':
            return jsonify({"msg": "Please enter Name"}), 400
        if not app_lastname or app_lastname == '':
            return jsonify({"msg": "Please enter Last name"}), 400
        if not app_email or app_email == '':
            return jsonify({"msg": "Please enter email"}), 400
        if not app_time or app_time == '':
            return jsonify({"msg": "Please enter date"}), 400
        if not app_phone or app_phone == '':
            return jsonify({"msg": "Please enter a phone number"}), 400
        if not app_message or app_message == '':
            return jsonify({"msg": "Please enter a message"}), 400

        appoints = Appointment()
        appoints.app_name = app_name
        appoints.app_lastname = app_lastname
        appoints.app_email = app_email
        appoints.app_time = app_time
        appoints.app_phone = app_phone
        appoints.app_message = app_message

        db.session.add(appoints)
        db.session.commit()

        appoints = Appointment.query.all()
        appoints = list(map(lambda appoint: appoint.serialize(), appoints))
        return jsonify(appoints), 201

    if request.method == 'PUT':
        if not request.is_json:
            return jsonify({"msg": "Ingresar formato correcto"}), 400

        app_name = request.json.get('app_name', None)
        app_lastname = request.json.get('app_lastname', None)
        app_email = request.json.get('app_email', None)
        app_phone = request.json.get('app_phone', None)
        app_time = request.json.get('app_time', None)
        app_message = request.json.get('app_message', None)
        app_status = request.json.get('app_status', None)

        # if not app_status or app_status == '':
        #     return jsonify({"msg": "Por favor cambiar status"}), 400

        setappoints = Appointment.query.get(id)  #busca por el id

        if not setappoints:
            return jsonify({"msg": "Not Found"
                            }), 404  # para no actualizar algo q no existe

        setappoints.app_status = app_status
        setappoints.app_name = app_name
        setappoints.app_lastname = app_lastname
        setappoints.app_email = app_email
        setappoints.app_time = app_time
        setappoints.app_phone = app_phone
        setappoints.app_message = app_message

        db.session.commit()

        setappoints = Appointment.query.all()
        setappoints = list(
            map(lambda setappoint: setappoint.serialize(), setappoints))
        return jsonify(setappoints), 201
コード例 #27
0
def handle_json():
    apps = Appointment.get_all_json()
    emit('events', apps)
コード例 #28
0
def on_save_handler(model_class, instance, created):
    apps = Appointment.get_all_json()
    app.logger.info('new instance was just edited or saved')
    app.logger.info(apps)
    socketio.emit('events', apps, broadcast=True)
コード例 #29
0
def get_models(row):
    """
    """
    judge_row = Judge(
        **{
            slug_col: clean_data(slug_col, row[col])
            for col, slug_col in column_name_maps.demographic_col_map.items()
        })

    # A judge can have multiple appointments. There are a lot of columns associated with an appointment
    # and they are in the data as "<Column Description (N)>", go through and link all of these
    # together. There is no way of knowning how many (N) a judge may have and it's not sufficient to
    # just look for one column that has data, so loop through and look if _any_ of the appointment
    # pattern columns have data up to the MAX_DUP_COLS appointment.
    for i in range(1, MAX_DUP_COLS):
        appointment_dict = {}
        for col, slug_col in column_name_maps.appt_col_map.items():
            appt_row_val = row.get(_get_column_pattern(col, i))
            if appt_row_val:
                appointment_dict[slug_col] = clean_data(slug_col, appt_row_val)
        if len(appointment_dict) == 0:
            continue

        # In case there are multiple start dates due to bad data, assume the earliest
        appointment_dict['start_date'] = min(
            appointment_dict[date_col]
            for date_col in column_name_maps.START_DATE_COLUMNS_TO_PARSE
            if appointment_dict.get(date_col))

        appointment_dict['start_year'] = datetime.strptime(
            appointment_dict['start_date'], DATE_FORMAT).year

        # Multiple columns indicate a judgeship ending, take the min of them if duplicates.
        potential_end_dates = [
            appointment_dict[date_col]
            for date_col in column_name_maps.END_DATE_COLUMNS_TO_PARSE
            if appointment_dict.get(date_col)
        ]

        # Empty list means still in job
        if not potential_end_dates:
            appointment_dict['end_date'] = None
        else:
            appointment_dict['end_date'] = min(potential_end_dates)

        if appointment_dict['end_date']:
            appointment_dict['end_year'] = datetime.strptime(
                appointment_dict['end_date'], DATE_FORMAT).year
        else:
            appointment_dict['end_year'] = None

        if appointment_dict.get('confirmation_date') and appointment_dict.get(
                'nomination_date'):
            timedelta_to_confirm = (
                datetime.strptime(appointment_dict['confirmation_date'],
                                  DATE_FORMAT) -
                datetime.strptime(appointment_dict['nomination_date'],
                                  DATE_FORMAT))
            appointment_dict['days_to_confirm'] = timedelta_to_confirm.days
        else:
            appointment_dict['days_to_confirm'] = None

        judge_row.appointments.append(Appointment(**appointment_dict))

    education_dict = defaultdict(dict)
    for i in range(1, MAX_DUP_COLS):
        for col, slug_col in column_name_maps.edu_col_map.items():
            edu_row_val = row.get(_get_column_pattern(col, i))
            if edu_row_val:
                education_dict[i][slug_col] = clean_data(slug_col, edu_row_val)
        if len(education_dict[i]) == 0:
            education_dict.pop(i)
            continue
        judge_row.educations.append(Education(**education_dict[i]))

    return judge_row
コード例 #30
0
ファイル: views.py プロジェクト: joyoon/api-example-django
    def get_context_data(self, **kwargs):
        kwargs = super(Appointments, 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.
        appointments = self.getAppointments()

        # appointment dictionary
        # key: hour interval, value: appointment
        appointmentLookup = {}

        # populate dictionary
        for a in appointments:
            if a['status'] != 'Cancelled':
                scheduledTime = datetime.strptime(a['scheduled_time'],
                                                  '%Y-%m-%dT%H:%M:%S')
                key = str(scheduledTime.hour) + ":" + str(scheduledTime.minute)
                appointmentLookup[key] = Appointment(a['patient'],
                                                     a['duration'],
                                                     a['exam_room'],
                                                     scheduledTime,
                                                     a['status'])

        appointmentsViewModel = None
        scheduleData = []
        date = datetime.strptime(self.request.GET.get('date'), '%Y-%m-%d')
        appointmentDate = datetime(date.year, date.month, date.day)
        hourIntervals = self.getHourIntervals(appointmentDate)

        for i in range(0, len(hourIntervals)):
            intervalData = None
            interval = hourIntervals[i]
            key = str(interval.hour) + ":" + str(interval.minute)

            # check if there is an appointment at the scheduled time
            if key not in appointmentLookup:
                # check previous interval
                if i - 1 >= 0:
                    prevInterval = scheduleData[i - 1]

                    if prevInterval.appointment and\
                        prevInterval.appointment.scheduledtime + timedelta(minutes=prevInterval.appointment.duration)\
                            > interval:
                        key = str(
                            prevInterval.appointment.scheduledtime.hour
                        ) + ":" + str(
                            prevInterval.appointment.scheduledtime.minute)
                        intervalData = AppointmentViewModel(
                            interval, appointmentLookup[key])

                    else:
                        intervalData = AppointmentViewModel(interval, None)

                else:
                    intervalData = AppointmentViewModel(interval, None)

            else:
                intervalData = AppointmentViewModel(interval,
                                                    appointmentLookup[key])

            scheduleData.append(intervalData)

        appointmentsViewModel = AppointmentsViewModel(scheduleData)

        kwargs['scheduledata'] = scheduleData
        kwargs['appointmentlookup'] = appointmentLookup
        kwargs['model'] = appointmentsViewModel
        return kwargs
コード例 #31
0
def create_appt(request):
    u = request.user
    if request.POST:
        d = request.POST['id']
        t = date.today() + timedelta(days=1)
        doc = Usr.objects.filter(user_id=d, user_type='doctor')
        ptnt = Usr.objects.filter(user_id=u, user_type='patient')
        #Only 10 appointments can be made for a doctor in a day
        tx = date.today() + timedelta(days=3)
        x = Appointment.objects.filter(doctor=d,
                                       user_id=u,
                                       time__gte=date.today(),
                                       time__lte=tx,
                                       active=True)
        y = Appointment.objects.filter(time=t, doctor=d)
        t2 = date.today() + timedelta(days=2)
        y2 = Appointment.objects.filter(time=t2, doctor=d)
        t3 = date.today() + timedelta(days=3)
        y3 = Appointment.objects.filter(time=t3, doctor=d)
        if len(x) > 0:
            return render_to_response('appt_user_failure.html')
        else:
            if len(y) < 10:
                a = Appointment(a_id=uuid.uuid4(),
                                user_id=u,
                                patient_name=ptnt[0].name,
                                doctor=d,
                                doc_name=doc[0].name,
                                dept=doc[0].extra,
                                time=t,
                                active=True,
                                token=len(y) + 1)
                a.save()
                return render_to_response('appt_success.html', {
                    'date': t,
                    'token': len(y) + 1
                })
            elif len(y2) < 10:
                a = Appointment(a_id=uuid.uuid4(),
                                user_id=u,
                                patient_name=ptnt[0].name,
                                doctor=d,
                                doc_name=doc[0].name,
                                dept=doc[0].extra,
                                time=t2,
                                active=True,
                                token=len(y2) + 1)
                a.save()
                return render_to_response('appt_success.html', {
                    'date': t2,
                    'token': len(y2) + 1
                })
            elif len(y3) < 10:
                a = Appointment(a_id=uuid.uuid4(),
                                user_id=u,
                                patient_name=ptnt[0].name,
                                doctor=d,
                                doc_name=doc[0].name,
                                dept=doc[0].extra,
                                time=t3,
                                active=True,
                                token=len(y3) + 1)
                a.save()
                return render_to_response('appt_success.html', {
                    'date': t3,
                    'token': len(y3) + 1
                })
            else:
                return render_to_response('appt_failure.html')