예제 #1
0
파일: forms.py 프로젝트: pavanpawar4591/apr
    def add_new(self, user):
        try:
            client = Client.objects.get(pk=self.cleaned_data['client'])

            if client.phone:
                event_title = "{name} {phone} {id}".format(
                    name=client.get_full_name(),
                    phone=client.phone,
                    id=client.client_id)
            else:
                event_title = "{name} {id}".format(name=client.get_full_name(),
                                                   id=client.client_id)

            event = Event(start=parser.parse(
                self.cleaned_data['start_datetime']),
                          end=parser.parse(self.cleaned_data['end_datetime']),
                          title=event_title,
                          creator=user)
            event.save()
            appointment = Appointment(
                client=client,
                venue=Venue.objects.get(pk=self.cleaned_data['venue_id']),
                event=event,
                creator=user,
                customer=user.userprofile.customer)
            appointment.save()
            return appointment
        except Client.DoesNotExist:
            return False
예제 #2
0
def create(request):
	form = AppointmentForm()
	if request.POST:
		form = AppointmentForm(request.POST)
		if form.is_valid():
			phone_representation = phonenumbers.parse(form.cleaned_data['phone_number'], "US")
			phone_formatted = str(phonenumbers.format_number(phone_representation, phonenumbers.PhoneNumberFormat.E164))
			# get phone owner (or create then)
			patient = Patient.objects.get_or_create(phone_number=phone_formatted)[0]
			
			# make sure appointment date is in the future
			now = datetime.utcnow().replace(tzinfo=utc)
			app_date = form.cleaned_data['date']
			if now < app_date:
				appointment = Appointment(
					owner=patient,
					date = app_date,
					)
				appointment.save()
				patient.send_sms('You added an appointment!')
				return HttpResponseRedirect(reverse(detail, kwargs={
					'appointment_id':appointment.id,
					}))
	return render_to_response('appointments/create.html',{
		'form':form,
		},context_instance=RequestContext(request))
예제 #3
0
파일: forms.py 프로젝트: Avatazjoe/apr
    def add_new(self, user):
        try:
            client = Client.objects.get(pk=self.cleaned_data["client"])

            if client.phone:
                event_title = "{name} {phone} {id}".format(
                    name=client.get_full_name(), phone=client.phone, id=client.client_id
                )
            else:
                event_title = "{name} {id}".format(name=client.get_full_name(), id=client.client_id)

            event = Event(
                start=parser.parse(self.cleaned_data["start_datetime"]),
                end=parser.parse(self.cleaned_data["end_datetime"]),
                title=event_title,
                creator=user,
            )
            event.save()
            appointment = Appointment(
                client=client,
                venue=Venue.objects.get(pk=self.cleaned_data["venue_id"]),
                event=event,
                creator=user,
                customer=user.userprofile.customer,
            )
            appointment.save()
            return appointment
        except Client.DoesNotExist:
            return False
예제 #4
0
    def create(self, validated_data):

        appointment = Appointment(
            donor_id=validated_data['donor_id'],
            clinic_id=validated_data['clinic_id'],
            appointment_time=validated_data['appointment_time'],
            attended=validated_data['attended'])
        appointment.save()
        return appointment
예제 #5
0
파일: forms.py 프로젝트: pavanpawar4591/apr
 def create_generic_event(self, user):
     event = self.create_event(user)
     new_appointment = Appointment(
         client=None,
         venue=Venue.objects.get(pk=self.cleaned_data['venue_id']),
         event=event,
         creator=user,
         customer=user.userprofile.customer)
     new_appointment.save()
     return new_appointment
예제 #6
0
파일: forms.py 프로젝트: pavanpawar4591/apr
 def create_appointment(self, user):
     event = self.create_event(user)
     new_appointment = Appointment(
         client=Client.objects.get(pk=self.cleaned_data['client']),
         venue=self.cleaned_data['venue'],
         event=event,
         creator=user,
         customer=user.userprofile.customer)
     new_appointment.save()
     return new_appointment
예제 #7
0
파일: forms.py 프로젝트: Avatazjoe/apr
 def create_generic_event(self, user):
     event = self.create_event(user)
     new_appointment = Appointment(
         client=None,
         venue=Venue.objects.get(pk=self.cleaned_data["venue_id"]),
         event=event,
         creator=user,
         customer=user.userprofile.customer,
     )
     new_appointment.save()
     return new_appointment
예제 #8
0
파일: forms.py 프로젝트: Avatazjoe/apr
 def create_appointment(self, user):
     event = self.create_event(user)
     new_appointment = Appointment(
         client=Client.objects.get(pk=self.cleaned_data["client"]),
         venue=self.cleaned_data["venue"],
         event=event,
         creator=user,
         customer=user.userprofile.customer,
     )
     new_appointment.save()
     return new_appointment
예제 #9
0
파일: api.py 프로젝트: saihem/Appointments
 def _post(self, kwargs):
     date = kwargs.get("date", None)
     time = kwargs.get("time", None)
     description = kwargs.get("description", None)
     appointment = Appointment()
     appointment.date = date
     appointment.time = time
     appointment.description = description
     appointment.save()
     return appointment
예제 #10
0
    def test_send_invoice_called(self, monkeypatch, billing_detail):
        mock_send = Mock()
        monkeypatch.setattr(Szamlazzhu, "send_invoice", mock_send)

        email = "*****@*****.**"
        full_name = "Test User"
        amount = 100

        appointment = Appointment(email=email, billing_detail=billing_detail)
        seat = Seat(
            full_name=full_name,
            payment=Payment(amount=amount,
                            product_type=ProductType.NORMAL_EXAM),
            appointment=appointment,
        )
        send_seat_invoice(seat)

        item1 = Item(
            name="Laboratóriumi teszt - Alapcsomag (72 óra)",
            quantity=1,
            unit="db",
            net_price=17_000,
            net_unit_price=17_000,
            vat_rate=VATRate.PERCENT_0,
            vat_value=0,
            gross_price=17_000,
        )

        item2 = Item(
            name="Mintavételi csomag",
            quantity=1,
            unit="db",
            net_price=7_600,
            net_unit_price=7_600,
            vat_rate=VATRate.PERCENT_5,
            vat_value=380,
            gross_price=7_980,
        )

        customer = Customer(
            name="Test Company",
            address="Test street 11.",
            post_code="1234",
            city="Budapest",
            tax_number="123456789",
            email=email,
        )
        invoice = Invoice(items=[item1, item2],
                          payment_method=PaymentMethod.CREDIT_CARD,
                          customer=customer)
        mock_send.assert_called_once_with(
            invoice, os.environ["SZAMLAZZHU_INVOICE_PREFIX"])
예제 #11
0
def recv_serial_number(_, up: tg.Update, chat_data):
    serial_number = up.effective_message.text.strip()

    try:
        appliance = Appliance.objects.get(serial_number__iexact=serial_number)

        chat_data["appointment"] = Appointment(
            appliance=appliance,
            user=util.get_user(up),
            tracking_number=Appointment.gen_tracking_number(),
        )
        up.effective_message.reply_text(
            T("Checks out!\n"
              "Next, provide an address for this service appointment.\n\n"
              "You can also share your location, using the attach (📎) button.")
        )

        return recv_location.__name__
    except Appliance.DoesNotExist:
        up.effective_message.reply_text(
            T("You entered an invalid serial number.\n"
              "Please enter a valid serial number."))

        return recv_serial_number.__name__
예제 #12
0
from django.test import TestCase
from django.test import Client
from django.core.urlresolvers import reverse

from appointments.models import Appointment

import datetime

# Create your tests here.

class AppointmentsTest(TestCase):
	fixtures = ['initial_data.json']
	client = Client()
	response = client.get(reverse('home'))
	response.status_code
    response = client.get(reverse('search'))
    response.status_code
    appointment = Appointment(text='Django', date=datetime.datetime.today())
	appointment.save()
예제 #13
0
    def create_appointment(self, request):
        """
        Saves a new Appointment
        :param request: new Appointment that should be saved
        :return: 201 Detailed information for newly created Appointment
        :return: 404 No Treatment for given TreatmentID 
        :return: 409 Appointment Details do not match the requirements
        :return: 500 Connection Error  
        """

        appointment_detail = json.loads(request.get_data())

        if appointment_detail['start_time'] >= appointment_detail['end_time']:
            return 409, "Start time has to be before end time.\n"
        elif appointment_detail['start_time'] < 8 or appointment_detail[
                'start_time'] > 17 or appointment_detail[
                    'end_time'] < 9 or appointment_detail['end_time'] > 18:
            return 409, "Appointments are only available from 8 - 18. Please choose another timeslot.\n"

        try:
            URL = "http://" + config.get(
                'TREATMENTS_SERVICE') + "/treatments/" + str(
                    appointment_detail['treatment_id'])
            t_response = requests.get(url=URL)
            t_response.encoding = 'utf-8'
            treatment_data = literal_eval(t_response.text)
        except SyntaxError:
            return 404, "No Treatment exists for given TreatmentID.\n"
        except requests.exceptions.ConnectionError:
            return 500, "Could not read Treatments.\n"

        if treatment_data['minduration'] > (appointment_detail['end_time'] -
                                            appointment_detail['start_time']):
            return 409, "An appointment for " + treatment_data[
                'name'] + " takes at least " + str(
                    treatment_data['minduration']
                ) + " hour(s). Please choose another timeslot.\n"
        elif treatment_data['maxduration'] < (
                appointment_detail['end_time'] -
                appointment_detail['start_time']):
            return 409, "An appointment for " + treatment_data[
                'name'] + " takes maximum " + str(
                    treatment_data['maxduration']
                ) + " hour(s). Please choose another timeslot.\n"

        try:
            conflicts = 0
            appointments = self.db.session.query(Appointment).all()
            for appointment in appointments:
                if treatment_data['name'] == appointment.treatment_name:
                    if appointment_detail['date'] == appointment.date.strftime(
                            "%Y-%m-%d"):
                        if not (appointment_detail['start_time'] <=
                                appointment.start_time
                                and appointment_detail['end_time'] <=
                                appointment.start_time) and not (
                                    appointment.end_time <=
                                    appointment_detail['end_time']
                                    and appointment.end_time <=
                                    appointment_detail['start_time']):
                            conflicts += 1

            if conflicts == 0:
                newappointment = Appointment(
                    treatment_id=appointment_detail['treatment_id'],
                    treatment_name=treatment_data['name'],
                    customer_name=appointment_detail['customer_name'],
                    date=appointment_detail['date'],
                    start_time=appointment_detail['start_time'],
                    end_time=appointment_detail['end_time'],
                    duration=appointment_detail['end_time'] -
                    appointment_detail['start_time'])

                with self.db.get_session() as session:
                    session.add(newappointment)

                appointment_detail['treatment_name'] = treatment_data['name']
                self.dispatch("booked_appointment", appointment_detail)

                return 201, u"\nAppointment: {}".format(appointment_detail)
            else:
                return 409, "There were " + str(
                    conflicts
                ) + " conflicts with other appointments. Please choose a free timeslot.\n"

        except exc.SQLAlchemyError:
            return 500, "Could not save Appointment.\n"
예제 #14
0
파일: views.py 프로젝트: mxa5473/HealthNet
def edit_appointment(request, appointment_id):
    # this view is used for editing appointments with the appointmentform

    if request.user.is_authenticated():

        title = "Edit Appointment"

        user_id = request.user.id

        isPatient = (Patient.objects.filter(
            profile__user_id=user_id).count() == 1)
        isDoctor = (Doctor.objects.filter(
            profile__user_id=user_id).count() == 1)
        isNurse = (Nurse.objects.filter(profile__user_id=user_id).count() == 1)

        app_instance = Appointment.objects.get(id=appointment_id)

        if isPatient:

            # get the patient instance
            pat = Patient.objects.filter(profile__user_id=request.user.id)[0]

            # tests if the patient is viewing only their appointments
            isValid = (Appointment.objects.filter(id=appointment_id,
                                                  patient=pat))

            # redirect if trying to access others appointments
            if not isValid:
                return redirect('/profile')

            # used to fill form with current values
            initdata = {
                'doctor': app_instance.doctor,
                "date": app_instance.date,
                'time': app_instance.time,
                'reason': app_instance.reason,
                'short_reason': app_instance.short_reason
            }

            # create the form
            form = AppointmentForm(request.POST,
                                   instance=app_instance,
                                   initial=initdata)

            if request.POST:
                """
                modifications to appointments is completed in a bit of a messy way. The issue is that appointments
                should not be able to be edited to be during the same time of another if the doctor is the same.
                This test is done by getting a list of all appointments and checking if any match the current form
                submission. The problem with this is when an appointment is under edit, it already exists, and the
                checker flags the operation as illegal.

                The way around this was to save all the instance's current fields, and delete it. If the form fails,
                a new instance is created with the old forms and the user can try again. If the form is successful
                a new instance is created with the new values and the user is redirected.
                """

                # these are the appointment fields being saved
                pk = Appointment.objects.filter(id=appointment_id)[0].id
                date = Appointment.objects.filter(id=appointment_id)[0].date
                time = Appointment.objects.filter(id=appointment_id)[0].time
                doc = Appointment.objects.filter(id=appointment_id)[0].doctor
                reason = Appointment.objects.filter(
                    id=appointment_id)[0].reason
                s_reason = Appointment.objects.filter(
                    id=appointment_id)[0].short_reason

                # deletes the current appointment instance
                Appointment.objects.filter(id=appointment_id)[0].delete()

                # if the form is valid, log it and save the new data
                if form.is_valid():
                    log = Log(username=pat.profile.user.username,
                              action=" edited an appointment ")
                    log.save()
                    form.save()
                    msg = "Appointment with %s on %s successfully modified" % (
                        doc, date)

                    return account.views.index(request, msg)

                # if the form fails, create a new appointment instance and save it and send a new form
                else:
                    app = Appointment(id=pk,
                                      patient=pat,
                                      date=date,
                                      time=time,
                                      doctor=doc,
                                      reason=reason,
                                      short_reason=s_reason)
                    app.save()

            else:

                form = AppointmentForm(instance=app_instance, initial=initdata)

            return render(request, 'appointments/edit_appointment.html', {
                'form': form,
                'usertype': 'patient'
            })

        elif isDoctor:

            doc = Doctor.objects.filter(profile__user_id=request.user.id)[0]

            # tests if the doctor is viewing only their appointments
            isValid = (Appointment.objects.filter(id=appointment_id,
                                                  doctor=doc))

            if not isValid:
                return redirect('/profile')

            initdata = {
                'patient': app_instance.patient,
                "date": app_instance.date,
                'time': app_instance.time,
                'reason': app_instance.reason,
                'short_reason': app_instance.short_reason
            }

            form = AppointmentFormDoctor(request.POST,
                                         instance=app_instance,
                                         initial=initdata)

            if request.POST:

                date = Appointment.objects.filter(id=appointment_id)[0].date
                time = Appointment.objects.filter(id=appointment_id)[0].time
                pat = Appointment.objects.filter(id=appointment_id)[0].patient
                reason = Appointment.objects.filter(
                    id=appointment_id)[0].reason
                s_reason = Appointment.objects.filter(
                    id=appointment_id)[0].short_reason
                pk = Appointment.objects.filter(id=appointment_id)[0].id

                Appointment.objects.filter(id=appointment_id)[0].delete()

                if form.is_valid():

                    log = Log(username=doc.profile.user.username,
                              action=" edited an appointment ")
                    log.save()
                    form.save()

                    return redirect('/')
                else:

                    app = Appointment(id=pk,
                                      patient=pat,
                                      date=date,
                                      time=time,
                                      doctor=doc,
                                      reason=reason,
                                      short_reason=s_reason)
                    app.save()
            else:
                form = AppointmentFormDoctor(instance=app_instance,
                                             initial=initdata)

            return render(request, 'appointments/edit_appointment.html', {
                'form': form,
                'usertype': 'Doctor'
            })

        elif isNurse:

            nurse = Nurse.objects.filter(profile__user_id=request.user.id)

            initdata = {
                'patient': app_instance.patient,
                "doctor": app_instance.doctor,
                "date": app_instance.date,
                'time': app_instance.time,
                'reason': app_instance.reason,
                'short_reason': app_instance.short_reason
            }

            form = AppointmentFormNurse(request.POST,
                                        instance=app_instance,
                                        initial=initdata)

            if request.POST:
                pk = Appointment.objects.filter(id=appointment_id)[0].id
                date = Appointment.objects.filter(id=appointment_id)[0].date
                time = Appointment.objects.filter(id=appointment_id)[0].time
                pat = Appointment.objects.filter(id=appointment_id)[0].patient
                doc = Appointment.objects.filter(id=appointment_id)[0].doctor
                reason = Appointment.objects.filter(
                    id=appointment_id)[0].reason
                s_reason = Appointment.objects.filter(
                    id=appointment_id)[0].short_reason

                Appointment.objects.filter(id=appointment_id)[0].delete()

                if form.is_valid():
                    form.save()
                    log = Log(username=nurse[0].profile.user.username,
                              action=" edited an appointment ")
                    log.save()
                    return redirect('/')
                else:
                    app = Appointment(id=pk,
                                      patient=pat,
                                      date=date,
                                      time=time,
                                      doctor=doc,
                                      reason=reason,
                                      short_reason=s_reason)
                    app.save()

            else:

                form = AppointmentFormNurse(instance=app_instance,
                                            initial=initdata)

            return render(request, 'appointments/edit_appointment.html', {
                'form': form,
                'usertype': 'Nurse'
            })

    else:
        return redirect('/login')
예제 #15
0
    def post(self, request):
        if request.POST and request.is_ajax:

            currenttime = datetime.datetime.now()
            after10min = currenttime + datetime.timedelta(minutes=10)

            appform = Appointment()
            appform.urgentcare_id = request.POST.get('urgentcare_id')
            appform.urgencare_name = request.POST.get('urgencare_name')
            appform.urgentcare_address = request.POST.get('urgentcare_address')
            appform.name = request.POST.get('name')
            appform.family_name = request.POST.get('family_name')
            appform.phone_number = request.POST.get('phone_number')
            appform.gender = request.POST.get('gender')
            appform.age = request.POST.get('age')
            appform.brief_explanations = request.POST.get('brief_explanations')
            appform.threatening_illnesses = request.POST.get(
                'threatening_illnesses')
            appform.facility_type = request.POST.get('facility_type')
            appform.medical_problem = request.POST.get('medical_problem')
            appform.urgentcare_phone = request.POST.get('urgentcare_phone')
            appform.start_time = currenttime
            appform.end_time = after10min
            appform.save()

            res_data = {}
            res_data['success'] = 'true'
            res_data[
                'message'] = 'Your appointment has been submitted! Thank you.'
            res_data['title'] = 'Appointment Submitted'

            return HttpResponse(json.dumps(res_data),
                                content_type="application/json")
예제 #16
0
    def post(self, request, uuid=None, *args, **kwargs):
        client = get_object_or_404(Client, uuid=uuid)

        if not request.user.has_perm(Client.CAN_VIEW, client):
            raise PermissionDenied

        form = AppointmentForm(request.POST or None)
        qs = User.objects.filter(Q(is_owner=True) | Q(is_team=True))
        form.fields['assigned_to'].choices = [
            (user.username, user.first_name + ' ' + user.last_name)
            for user in qs.all()
        ]
        if form.is_valid():
            appointment = Appointment()
            appointment.client = client
            appointment.appointment_date = form.cleaned_data[
                'appointment_date']
            appointment.appointment_time = form.cleaned_data[
                'appointment_time']
            appointment.appointment_duration = form.cleaned_data[
                'appointment_duration']
            appointment.appointment_reason = form.cleaned_data[
                'appointment_reason']
            appointment.assigned_to = get_object_or_404(
                User, username=form.cleaned_data['assigned_to'])

            appointment.set_aware_appointment_datetime_utc(
                request.user.timezone)

            if form.cleaned_data['send_confirmation_email']:
                emailer.send_appointment_created_email(appointment,
                                                       request.user)
            appointment.save()
            messages.success(request, 'Appointment deleted successfully')
            ActivityStream(
                customer=self.request.user.customer,
                actor=self.request.user.username,
                verb='created_appointment',
                action_object=appointment.get_human_readable_datetime(),
                target=client.__str__()).save()

            return redirect('clients:client-appointments', uuid=client.uuid)
        messages.error(request, 'There was an error Creating appointment')
        context = {'form': form}
        return render(request, self.template_name, context)