def get_appointments_for_staff_and_status_filter_by_date_time(
            staff_id, status, start_time, end_time):
        try:
            client = MongoClient(Constant.DB_CONNECTION_URL)
            document = client[Constant.DB_NAME][AppointmentDB.COLLECTION_NAME]

            appointments = document.find({
                'staffId': staff_id,
                'status': status,
                'dateTime': {
                    '$gte': start_time,
                    '$lte': end_time
                }
            })

            appointments_for_staff = []

            for appointment in appointments:
                a = Appointment(str(appointment['_id']), staff_id,
                                appointment['visitorId'],
                                appointment['subject'],
                                appointment['dateTime'], appointment['status'])

                visitor = VisitorDB.get_visitor_by_id(appointment['visitorId'])
                a.set_visitor(visitor)

                appointments_for_staff.append(a)

            client.close()
            return appointments_for_staff

        except Exception as e:
            print('unable to get appointments for staff')
            raise Exception('Could not get appointments for staff')
Ejemplo n.º 2
0
def initialize():
    DATABASE.create_tables([User, Saloon, Appointment], safe=True)
    try:
        User.create(first_name="Felicia",
                    last_name="Mueni",
                    email="*****@*****.**")
    except IntegrityError:
        pass

    try:
        Saloon.create(name="Mrembo",
                      business_number="9897",
                      opening_time="10:00 am",
                      closing_time="5:00 pm",
                      description="Urembo services",
                      services="Manicure, Pedicure, Haircare",
                      user_id=1,
                      location="George Padimore Lane")
    except IntegrityError:
        pass
    try:
        no_appointments = Appointment.select().count()
        if no_appointments < 1:
            Appointment.create(user_id=1,
                               saloon_id=1,
                               services="Manicure, Pedicure",
                               time_appointment=datetime.datetime.now())

    except IntegrityError:
        pass
    def get_appointments_for_staff_in(staff_id, appointment_ids):
        try:
            client = MongoClient(Constant.DB_CONNECTION_URL)
            document = client[Constant.DB_NAME][AppointmentDB.COLLECTION_NAME]

            appointment_ids_obj = [ObjectId(item) for item in appointment_ids]

            appointments = document.find({
                '_id': {
                    '$in': appointment_ids_obj
                },
                'staffId': staff_id
            })

            appointments_for_staff = []

            for appointment in appointments:
                a = Appointment(str(appointment['_id']), staff_id,
                                appointment['visitorId'],
                                appointment['subject'],
                                appointment['dateTime'], appointment['status'])

                visitor = VisitorDB.get_visitor_by_id(appointment['visitorId'])
                a.set_visitor(visitor)

                appointments_for_staff.append(a)

            client.close()
            return appointments_for_staff

        except Exception as e:
            print('unable to get appointments for staff - ' + str(e))
            raise Exception('Could not get appointments for staff')
Ejemplo n.º 4
0
def make_appointment():
    appointment_data = dict(request.form.items())
    time_appointment_raw = appointment_data.get('time_appointment')
    time_appointment_processed = datetime.strptime(time_appointment_raw,
                                                   "%d %b %Y %H:%M")
    Appointment.create(user_id=appointment_data.get('user_id'),
                       saloon_id=appointment_data.get('saloon_id'),
                       services=appointment_data.get('services'),
                       time_appointment=time_appointment_processed)
    result = {"status": "Success", "message": "Appointment set"}
    return jsonify(result)
Ejemplo n.º 5
0
    def _set_new_appointment(self):
        subject = input("Enter subject:")
        duration = input("Enter duration:")
        start_time = input("Enter start time:")
        client_name = input("Enter client name:")
        counselor_id = self.counselor.id

        appointment = Appointment(subject, duration, start_time, client_name,
                                  counselor_id)
        appointment.save_to_db()

        print("Appointment has been set successfully!")
Ejemplo n.º 6
0
def _found_slots(start_date, end_date, professional_id):
    start_date = start_date + datetime.timedelta(
        minutes=(30 - start_date.minute % 30) % 30)
    slots = []
    half_hour = datetime.timedelta(minutes=30)
    professional = Professional.find_by_id(professional_id)
    appointments = Appointment.find_by_professional(professional)
    while start_date + half_hour <= end_date:
        occupied = False
        for appointment in appointments:
            schedule_start_date = dateparser.parse(appointment.start_date)
            schedule_end_date = dateparser.parse(appointment.end_date)
            if not (start_date <= schedule_start_date
                    and start_date + half_hour <= schedule_start_date
                    or start_date >= schedule_end_date
                    and start_date + half_hour >= schedule_end_date):
                occupied = True
                break
        if not occupied:
            slots.append({
                'id':
                hashlib.md5(str(start_date) + professional_id).hexdigest(),
                'start_date':
                start_date.isoformat(),
            })
        start_date += half_hour
    return slots
Ejemplo n.º 7
0
def search():
    id = request.args.get("appointment_id")
    appointment = Appointment.get_or_none(Appointment.id == id)
    if appointment:
        if appointment.zoom_url:
            zoom_link = a.zoom_url
        else:
            zoom_link = None
        return jsonify({
            "appointment_id":
            appointment.id,
            "doctor_name":
            appointment.doctor.name,
            "patient_name":
            appointment.patient.name,
            "doctor_ic":
            appointment.doctor.ic_number,
            "patient_ic":
            appointment.patient.ic_number,
            "appointment_start":
            appointment.start_datetime.strftime("%Y-%m-%d %H:%M:%S"),
            "appointment_end":
            appointment.end_datetime.strftime("%Y-%m-%d %H:%M:%S"),
            "zoom_link":
            zoom_link
        })
    else:
        return jsonify({"message": "Appointment not found.", "status": "fail"})
Ejemplo n.º 8
0
def destroy():
    online_user = get_jwt_identity()
    user = User.get_or_none(User.id == online_user['id'])

    if "admin" not in user.role:
        return jsonify({
            "message": "401 Unauthorized (Only admin is allowed)",
            "status": "fail"
        })

    id = request.json.get("appointment_id")
    appointment = Appointment.get_or_none(Appointment.id == id)
    if appointment:
        if appointment.record:
            return jsonify({
                "message": "An appointment with record is not deleteable.",
                "status": "fail"
            })
        else:
            if appointment.delete_instance():
                return jsonify({
                    "message": "Successfully deleted appointment.",
                    "status": "success"
                })
            else:
                return jsonify({
                    "message": "Couldn't delete appointment.",
                    "status": "fail"
                })
    else:
        return jsonify({
            "message": "No such appointment exists.",
            "status": "fail"
        })
Ejemplo n.º 9
0
 def past_appointment(self):
     from models.appointment import Appointment
     past_appointment = Appointment.select().where((
         Appointment.doctor == self) | (Appointment.patient == self))
     past_appointment_list = []
     for a in past_appointment:
         if a.end_datetime < datetime.now():
             if a.zoom_url:
                 link = a.zoom_url
             else:
                 link = None
             past_appointment_list.append({
                 "appointment_id":
                 a.id,
                 "doctor_name":
                 a.doctor.name,
                 "doctor_ic":
                 a.doctor.ic_number,
                 "patient_name":
                 a.patient.name,
                 "patient_ic":
                 a.patient.ic_number,
                 "start_time":
                 a.start_datetime.strftime("%Y-%m-%d %H:%M:%S"),
                 "end_time":
                 a.end_datetime.strftime("%Y-%m-%d %H:%M:%S"),
                 "zoom_url":
                 link
             })
     return past_appointment_list
Ejemplo n.º 10
0
def get_zoom_url():
    import json
    from zoomus import ZoomClient
    from zoomus.components import meeting
    from app import app

    client = ZoomClient(app.config.get('ZOOM_API_KEY'),
                        app.config.get('ZOOM_API_SECRET'))

    user_list_response = client.user.list()
    user_list = json.loads(user_list_response.content)

    for user in user_list['users']:
        user_id = user['id']
        print(json.loads(client.meeting.list(user_id=user_id).content))

    new_meeting = client.meeting.create(user_id=user_id).json()
    join_url = new_meeting['join_url']

    id = request.args.get('appointment_id')
    appointment = Appointment.get_or_none(Appointment.id == id)

    appointment.zoom_url = join_url
    appointment.start_datetime = appointment.start_datetime.strftime(
        "%Y-%m-%d %H:%M:%S")
    appointment.end_datetime = appointment.end_datetime.strftime(
        "%Y-%m-%d %H:%M:%S")
    if appointment.save():
        return join_url
    else:
        return "fail"
Ejemplo n.º 11
0
def create_appointment():
    """Creates an appointment
    :return: a success message
    """
    details = json.loads(request.data)

    appointment = Appointment(consultation_type=details["consultation_type"],
                              resolution=details["resolution"],
                              status=details["status"],
                              slot_id=details["slot_id"],
                              venue=details["venue"],
                              patient_id=details["patient_id"],
                              doctor_id=details["doctor_id"])

    appointment.save()
    return make_response(
        jsonify({"message": "appointment created_successfully"}), 201)
Ejemplo n.º 12
0
def initialize():
    DATABASE.create_tables(
        [User, Saloon, Appointment, Register, Service, Saloonservices],
        safe=True)
    try:
        User.create(
            user_name="feliciah",
            service="haircare",
            password="******",
        )
    except IntegrityError:
        pass

    try:
        Service.create(service="manicure", price=1000)
    except IntegrityError:
        pass
    try:
        Saloon.create(name="mrembo",
                      business_number="9887",
                      opening_time="10:00am",
                      closing_time="5:00pm",
                      description="urembo services",
                      services="manicure,pedicure,haircare",
                      user_id=1,
                      location='location')
    except IntegrityError:
        pass

    try:
        Register.create(user_name="feliciah",
                        email="*****@*****.**",
                        phone_number="0712343647",
                        service="manicure",
                        password="******",
                        confirm_password="******")
    except IntegrityError:
        pass
    try:
        Appointment.create(user_id=1,
                           salon_id=1,
                           services="haircare,manicure,facial",
                           time_appointment=datetime.datetime.now())
    except IntegrityError:
        pass
    DATABASE.close()
    def post(self):
        form = NewAppointmentForm(request.form)

        if form.validate():
            from tasks import send_sms_reminder

            appt = Appointment(**form.data)
            appt.time = arrow.get(appt.time, appt.timezone).to('utc').naive

            reminders.db.session.add(appt)
            reminders.db.session.commit()
            send_sms_reminder.apply_async(
                args=[appt.id], eta=appt.notification_time())

            return redirect(url_for('appointment.index'), code=303)
        else:
            return render_template('appointments/new.html', form=form), 400
Ejemplo n.º 14
0
    def post(self):
        form = NewAppointmentForm(request.form)

        if form.validate():
            from tasks import send_sms_reminder

            appt = Appointment(**form.data)
            appt.time = arrow.get(appt.time, appt.timezone).to('utc').naive

            reminders.db.session.add(appt)
            reminders.db.session.commit()
            send_sms_reminder.apply_async(args=[appt.id],
                                          eta=appt.get_notification_time())

            return redirect(url_for('appointment.index'), code=303)
        else:
            return render_template('appointments/new.html', form=form), 400
Ejemplo n.º 15
0
    def get(self):
        # Clear data
        db.delete(CoachAvailability.all())
        db.delete(Appointment.all())

        # Create availability for the next couple months
        morning = datetime.time(9, 0, 0)
        afternoon = datetime.time(13, 0, 0)
        today = datetime.date.today()

        for x in range(0, 60):
            date = today + datetime.timedelta(days=x)
            # Morning availability
            if random.random() > 0.2:
                slot = CoachAvailability(date=date, start_time=morning, duration_minutes=180)
                slot.put()
                for hour in range(9, 12):
                    if random.random() > 0.5:
                        appt = Appointment(
                            date=date, start_time=datetime.time(hour, 0, 0), duration_minutes=60, client_id=SOMEONE_ELSE
                        )
                        appt.put()
            # Afternoon availability
            if random.random() > 0.2:
                duration_minutes = 90 + int(random.random() * 10) * 30
                slot = CoachAvailability(date=date, start_time=afternoon, duration_minutes=duration_minutes)
                slot.put()
                for hour in range(13, 13 + duration_minutes / 60):
                    if random.random() > 0.5:
                        appt = Appointment(
                            date=date, start_time=datetime.time(hour, 0, 0), duration_minutes=60, client_id=SOMEONE_ELSE
                        )
                        appt.put()
        self.response.write("Done")
def create_appointment():
    start_time = request.form["start_time"]
    end_time = request.form["end_time"]
    appointment_date = request.form["appointment_date"]
    animal = animal_repository.select(request.form["animal_id"])
    new_appointment = Appointment(start_time, end_time, appointment_date,
                                  animal)
    appointment_repository.save(new_appointment)
    return redirect("/appointments")
def update_appointment(id):
    start_time = request.form["start_time"]
    end_time = request.form["end_time"]
    appointment_date = request.form["appointment_date"]
    animal = request.form["animal_id"]
    appointment = Appointment(start_time, end_time, appointment_date, animal,
                              id)
    appointment_repository.update(appointment)
    return redirect("/appointments")
def add_new_appointment():
    date = request.form["date"]
    time = request.form["time"]
    notes = request.form["notes"]
    vet = vet_repository.select_vet(request.form["vet_id"])
    animal = animal_repository.select_animal(request.form["animal_id"])
    appointment = Appointment(date, time, vet, animal, notes)
    appointment_repository.save_new_appointment(appointment)
    return redirect('/appointments')
Ejemplo n.º 19
0
def select_appointment(id):
    sql = "SELECT * FROM appointments WHERE id=%s"
    value = [id]
    result = run_sql(sql, value)[0]
    if result is not None:
        vet = vet_repository.select_vet(result["vet_id"])
        animal = animal_repository.select_animal(result["animal_id"])
        appointment = Appointment(result["date"], result["time"], vet, animal,
                                  result["additional_notes"], result["id"])
        return appointment
Ejemplo n.º 20
0
def get_appointment_patient_id(patient_id):
    try:
        patient = Patient.find_by_id(patient_id)
        appointments = [
            appointment.to_dict()
            for appointment in Appointment.find_by_patient(patient)
        ]
    except:
        abort(500)
    return json.dumps(appointments)
Ejemplo n.º 21
0
def get_appointment_professional_id(professional_id):
    try:
        professional = Professional.find_by_id(professional_id)
        appointments = [
            appointment.to_dict()
            for appointment in Appointment.find_by_professional(professional)
        ]
    except:
        abort(500)
    return json.dumps(appointments)
Ejemplo n.º 22
0
 def test_instance(self):
     params = {
         'name': 'Mr Praline',
         'phone_number': '+12025550170',
         'delta': '15',
         'time': datetime.datetime(2015, 7, 28, 12, 24),
         'timezone': 'US/Pacific'
     }
     appt = Appointment(**params)
     self.assertEqual(repr(appt), "<Appointment 'Mr Praline'>")
Ejemplo n.º 23
0
def create():
    online_user = get_jwt_identity()
    user = User.get_or_none(User.id == online_user['id'])

    if "admin" not in user.role:
        return jsonify({
            "message": "401 Unauthorized (Only admin is allowed)",
            "status": "fail"
        })

    params = request.json
    doctor_ic = params.get("doctor_ic")
    patient_ic = params.get("patient_ic")
    start_datetime = params.get("start_datetime")
    end_datetime = params.get("end_datetime")

    doctor = User.get_or_none(User.ic_number == doctor_ic)
    patient = User.get_or_none(User.ic_number == patient_ic)
    if doctor and patient:
        new_appointment = Appointment(doctor_id=doctor.id,
                                      patient_id=patient.id,
                                      start_datetime=start_datetime,
                                      end_datetime=end_datetime)
        if new_appointment.save():
            response = {
                "message": "Successfully created an appointment",
                "status ": "success",
                "doctor_name": new_appointment.doctor.name,
                "doctor_ic": new_appointment.doctor.ic_number,
                "patient_name": new_appointment.patient.name,
                "patient_ic": new_appointment.patient.ic_number,
                "start_datetime": new_appointment.start_datetime,
                "end_datetime": new_appointment.end_datetime
            }
        else:
            response = new_appointment.error()
        return jsonify(response)
    else:
        return jsonify({
            "message": "Can't find doctor or patient",
            "status ": "fail",
        })
Ejemplo n.º 24
0
def list_appointments():
    appointments = Appointment.select()
    results = []
    for appointment in appointments:
        results.append({
            'user_id': appointment.user_id,
            'time_appointment': appointment.time_appointment,
            'saloon_id': appointment.saloon_id,
            'services': appointment.services
        })
    return jsonify(results)
Ejemplo n.º 25
0
def select_all_appointments():
    sql = "SELECT * FROM appointments"
    results = run_sql(sql)
    appointments = []
    for result in results:
        animal = animal_repository.select_animal(result["animal_id"])
        vet = vet_repository.select_vet(result["vet_id"])
        appointment = Appointment(result["date"], result["time"], vet, animal,
                                  result["additional_notes"], result["id"])
        appointments.append(appointment)
    return appointments
Ejemplo n.º 26
0
def edit():
    online_user = get_jwt_identity()
    user = User.get_or_none(User.id == online_user['id'])

    if "admin" not in user.role:
        return jsonify({
            "message": "401 Unauthorized (Only admin is allowed)",
            "status": "fail"
        })

    id = request.json.get("appointment_id")
    start_datetime = request.json.get("start_datetime")
    end_datetime = request.json.get("end_datetime")
    doctor_ic = request.json.get("doctor_ic")
    patient_ic = request.json.get("patient_ic")

    appointment = Appointment.get_or_none(Appointment.id == id)
    if appointment:
        start_datetime = request.json.get("start_datetime")
        end_datetime = request.json.get("end_datetime")
        doctor_ic = request.json.get("doctor_ic")
        patient_ic = request.json.get("patient_ic")

        doctor = User.get_or_none(User.ic_number == doctor_ic)
        patient = User.get_or_none(User.ic_number == patient_ic)

        if doctor == None or patient == None:
            return jsonify({
                "message": "Patient or doctor not found",
                "status": "fail"
            })

        appointment.doctor = doctor
        appointment.patient = patient
        appointment.start_datetime = start_datetime
        appointment.end_datetime = end_datetime

        if appointment.save():
            response = {
                "message": "successfully changed appointment's info!",
                "status": "success",
                "patient_name": appointment.patient.name,
                "doctor_name": appointment.doctor.name,
                "patient_ic": appointment.patient.ic_number,
                "doctor_ic": appointment.doctor.ic_number,
                "start_datetime": appointment.start_datetime,
                "end_datetime": appointment.end_datetime
            }
        else:
            response = appointment.error()
    else:
        response = {"message": "Appointment not found.", "status": "fail"}
    return jsonify(response)
Ejemplo n.º 27
0
def get_slots(professional_id):
    try:
        professional = Professional.find_by_id(professional_id)
        appointments = Appointment.find_by_professional(professional)
        start_date = dateparser.parse(request.args['start_date'])
        end_date = dateparser.parse(request.args['end_date'])
        slots = _found_slots(start_date, end_date, professional_id)
        for slot in slots:
            print slot["start_date"]
    except:
        abort(500)
    return json.dumps(slots)
    def get_appointments_for_status(status):
        try:
            client = MongoClient(Constant.DB_CONNECTION_URL)
            document = client[Constant.DB_NAME][AppointmentDB.COLLECTION_NAME]

            appointments = document.find({'status': status})

            appointments_for_status = []

            for appointment in appointments:
                a = Appointment(str(appointment['_id']),
                                appointment['staffId'],
                                appointment['visitorId'],
                                appointment['subject'],
                                appointment['dateTime'], status)

                visitor = VisitorDB.get_visitor_by_id(appointment['visitorId'])
                a.set_visitor(visitor)

                staff = StaffDB.get_staff_by_id(appointment['staffId'])
                a.set_staff(staff.serialize)

                appointments_for_status.append(a)

            client.close()
            return appointments_for_status

        except Exception as e:
            print('unable to get appointments for staff')
            raise Exception('Could not get appointments for staff')
    def search_all_appointments_visitors_name(visitor_name_keyword):
        try:
            client = MongoClient(Constant.DB_CONNECTION_URL)
            document = client[Constant.DB_NAME][AppointmentDB.COLLECTION_NAME]

            appointments = document.find({})

            appointments_for_staff = []

            for appointment in appointments:
                a = Appointment(str(appointment['_id']),
                                appointment['staffId'],
                                appointment['visitorId'],
                                appointment['subject'],
                                appointment['dateTime'], appointment['status'])

                visitor = VisitorDB.get_visitor_by_id(appointment['visitorId'])
                if visitor_name_keyword.lower() not in visitor.name.lower():
                    continue

                a.set_visitor(visitor)

                staff = StaffDB.get_staff_by_id(appointment['staffId'])
                a.set_staff(staff.serialize)

                appointments_for_staff.append(a)

            client.close()
            return appointments_for_staff

        except Exception as e:
            print('unable to get appointments')
            raise Exception('Could not get appointments')
Ejemplo n.º 30
0
def create_appointment():
    if not request.form:
        abort(400)
    try:
        params = request.form
        professional = Professional.find_by_id(params['professional_id'])
        appointments = Appointment.find_by_professional(professional)
        start_date = dateparser.parse(params['start_date'])
        end_date = dateparser.parse(params['end_date'])
        for appointment in appointments:
            schedule_start_date = dateparser.parse(appointment.start_date)
            schedule_end_date = dateparser.parse(appointment.end_date)
            if not (start_date <= schedule_start_date
                    and end_date <= schedule_start_date
                    or start_date >= schedule_end_date
                    and end_date >= schedule_end_date):
                abort(404)

        appointment = Appointment(
            professional=professional,
            patient=Patient.find_by_id(params['patient_id']),
            start_date=params['start_date'],
            end_date=params['end_date'],
        )

        appointment.save()
    except:
        abort(500)
    return jsonify(appointment.to_dict())
Ejemplo n.º 31
0
    def post(self):
        # Parse date
        date = self.request.get('date')
        dateParts = date.split('/')
        year = int(dateParts[0])
        month = int(dateParts[1])
        day = int(dateParts[2])
        date = datetime.date(year, month, day)

        # Parse time
        hour = int(self.request.get('hour'))
        minute = int(self.request.get('minute'))
        ampm = self.request.get('ampm')
        if ampm == 'pm':
            hour += 12
        time = datetime.time(hour, minute, 0)

        # Insert to database
        appt = Appointment(date = date, start_time = time, duration_minutes = 60, client_id = 1)
        appt.put()

        self.response.write('OK')
Ejemplo n.º 32
0
def select(id):
    sql = "SELECT * FROM appointments WHERE id = %s"
    vaules = [id]
    result = run_sql(sql, vaules)[0]
    animal = animal_repository.select(result["animal_id"])
        
    if result is not None:
        appointment = Appointment(
        result["start_time"], 
        result["end_time"],
        result["appointment_date"], 
        animal, 
        result["id"]) 
    return appointment
Ejemplo n.º 33
0
def save_from_pet(id):
    # Grab request data
    date = request.form['appointment_date']
    note = request.form['appointment_note']
    vet_id = request.form['appointment_vet']

    # Grab needed objects
    vet = VR.select(vet_id)
    pet = PR.select(id)

    # Create object for saving
    appointment = Appointment(date, note, vet, pet, pet)
    AR.save(appointment)

    # Redirect
    return redirect('/pets/' + id)