Пример #1
0
def register(request):
    if request.session.get('patient_mode'):
        return redirect('kiosk')
    # If there's a user logged in, require them to log out
    if request.user.is_authenticated():
        return redirect('manual_logout')
    # If it's post, the user has sent us their info and we need to try to set them up
    if request.method == 'POST':
        success = False
        user_form = UserForm(data=request.POST)
        if user_form.is_valid():
            # Save the user and associate it with a new Doctor
            user = user_form.save()
            user.set_password(user.password)
            user.save()

            doctor = Doctor()
            doctor.user = user
            doctor.save()
            success = True

        # Registration done, let's get out of here.
        # (note: I'm not actually sure whether it'd be more appropriate to
        # have a new view for the result and redirect to it. That sort of thing
        # seems common, but this seems simpler)
        return render(request, 'registration_report.html', {
            'success': success,
            'user_form': user_form
        })

    # Otherwise we diplay the form for them to fill out and post to us
    else:
        return render(request, 'register.html', {'user_form': UserForm()})
Пример #2
0
def signup(request):
    """
    Sign Up Page, uses built in Sign-Up
    """
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            name = form.cleaned_data.get('name')
            category = form.cleaned_data.get('category')
            user = authenticate(username=username, password=raw_password)
            if category == "doctor":
                doctor = Doctor(user=user, name=name)
                doctor.save()
            if category == "pharmacist":
                pharmacist = Pharmacist(user=user, name=name)
                pharmacist.save()
            if category == "patient":
                patient = Patient(user=user, name=name)
                patient.save()
            login(request, user)
            return redirect('/pharm/profile')
    else:
        form = SignUpForm()
    return render(request, 'pharmeasyflow/signup.html', {'form': form})
def register(request):
    # If there's a user logged in, require them to log out
    if request.user.is_authenticated():
        return redirect('manual_logout')
    # If it's post, the user has sent us their info and we need to try to set them up
    if request.method == 'POST':
        success = False
        user_form = UserForm(data=request.POST)
        if user_form.is_valid():
            # Save the user and associate it with a new Doctor
            user = user_form.save()
            user.set_password(user.password)
            user.save()

            doctor = Doctor()
            doctor.user = user
            doctor.save()
            success = True
            
        # Registration done, let's get out of here.
        # (note: I'm not actually sure whether it'd be more appropriate to
        # have a new view for the result and redirect to it. That sort of thing
        # seems common, but this seems simpler)
        return render(request, 'registration_report.html', {'success': success, 'user_form': user_form})

    # Otherwise we diplay the form for them to fill out and post to us
    else:
        return render(request, 'register.html', {'user_form': UserForm()}) 
 def post(self):
     response = Doctor.objects.filter(
         email=request.form['email']).count()
     if response == 0:
         doctor = Doctor()
         for key in request.form:
             doctor[str(key)] = request.form[str(key)]
         print doctor.first_name
         body = {}
         if request.form.has_key('email'):
             body['email'] = request.form['email']
         if request.form.has_key('area'):
             body['area'] = request.form['area']
         if request.form.has_key('city'):
             body['city'] = request.form['city']
         if request.form.has_key('specialization'):
             doctor.specialization = []
             doctor.specialization.append(
                 request.form['specialization'])
             body['specialization'] = request.form['specialization']
         if request.form.has_key('education'):
             doctor.education = []
             doctor.education.append(request.form['education'])
         doctor.save()
         es.create(
             index='test', doc_type='doctor', id=doctor.id, body=body)
         return jsonify(status=True)
     return jsonify(status=False)
Пример #5
0
    def get(self):
        id = self.request.get('id')
        jsArray = [];

        if not id:
            docList = Doctor.all()
            for one in docList:
                jsObj = {
                        one.docCode: one.docName
                }
                jsArray.append( jsObj )
        
        else:
            jsArray.append( { "id": id } ) 
            doc = Doctor.all().filter('docCode =', id).get()
            if doc:
                jsArray.append( {"name": doc.docName } )

                # searching for the clinic info:
                depts = []
                times = []
                deptCodes = [] 
                clinics = Clinic.all().filter( 'doctor =', doc.key() ).order('date')
                for one in clinics:
                    times.append( one.date )
                    if one.dept.dptCode not in deptCodes:    # making sure that dept will not be repeated
                        deptCodes.append( one.dept.dptCode )
                        depts.append( { one.dept.dptCode : one.dept.dptName } )
                
                jsArray.append( { "dept": depts } )
                jsArray.append( { "time": times } )

        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write( simplejson.dumps(jsArray) )
Пример #6
0
    def get_doctor(self, columns):
        try:
            doctor = Doctor()
            last_name = columns[self.column_dict['Last Name']].strip()
            if last_name != '':
                doctor.last_name = last_name

            first_name = columns[self.column_dict['First Name']].strip()
            if first_name != '':
                 doctor.first_name = first_name

            address1 = columns[self.column_dict['Line 1 Street Address']].strip()
            if address1 != '':
                 doctor.address_line1 = address1

            zipcode = columns[self.column_dict['Zip Code']].strip()
            if zipcode != '':
                doctor.zipcode = zipcode

            return doctor 

        except (TypeError, ValueError):
            print ("Error with positioning of values in datafile. Line '{}'".format(line))
            exit(os.EX_DATAERR)
        except Exception as e:
            print(str(e))
            exit(os.EX_SOFTWARE)       
Пример #7
0
    def _parse_doctors(self, records):
        if not isinstance(records, list):
            doctor_id, surname, name, patronymic, doctor_spec = records
            return Doctor(doctor_id, surname, name, patronymic, doctor_spec)

        for i in range(len(records)):
            doctor_id, surname, name, patronymic, doctor_spec = records[i]
            records[i] = Doctor(doctor_id, surname, name, patronymic,
                                doctor_spec)
        return records
Пример #8
0
    def doctors_save(self, request):
        d = Doctor(full_name=request.full_name, specialities=request.specialities, email=request.email, invited_by=request.invited_by)
        d.user = d.email.split('@')[0]

        capitalized_name =  ''

        for name in d.full_name.split(' '):
            capitalized_name = capitalized_name + name.capitalize() + ' '

        d.full_name = capitalized_name

        d.put()

        return DoctorMessage(full_name=d.full_name, specialities=d.specialities, email=d.email)
Пример #9
0
def register_doc(request, doc_id):
    filter = {'id': doc_id}
    data = data_from_url(request, 'https://drchrono.com/api/doctors',
                         filter)[0]
    doc = Doctor()
    doc.first_name = data['first_name']
    doc.last_name = data['last_name']
    doc.doctor_id = doc_id
    doc.total_wait_time = 0
    doc.total_patients = 0
    doc.save()
Пример #10
0
def save_user(doctor_data):
    user = User.objects.create_user(
        id=doctor_data['id'],
        username=doctor_data['username'],
    )
    doctor = Doctor(
        first_name=doctor_data['first_name'],
        last_name=doctor_data['last_name'],
        user=user,
    )
    if Doctor.objects.filter(pk=user).exists():
        doctor.save(update_fields=['first_name', 'last_name'])
    else:
        doctor.save()

    return user
Пример #11
0
    def poll_opened(self, request):

        doctor = Doctor.all().filter("user =", request.email)[0]
        doctor.poll_open = True
        doctor.put()

        return message_types.VoidMessage()
Пример #12
0
def new_doctor():
    name = request.json.get('name')
    surname = request.json.get('surname')
    patronymic = request.json.get('patronymic')
    specialty = request.json.get('specialty')
    phone = request.json.get('phone')
    monday = request.json.get('monday')
    tuesday = request.json.get('tuesday')
    wednesday = request.json.get('wednesday')
    thursday = request.json.get('thursday')
    friday = request.json.get('friday')
    saturday = request.json.get('saturday')

    try:
        doctor = Doctor.from_json({ 'name': name,
                                    'surname': surname,
                                    'patronymic': patronymic,
                                    'specialty':specialty,
                                    'phone': phone,
                                    'monday': monday,
                                    'tuesday': tuesday,
                                    'wednesday': wednesday,
                                    'thursday': thursday,
                                    'friday': friday,
                                    'saturday': saturday})
        db.session.add(doctor)
        db.session.commit()
        return jsonify({'doctor_id': doctor.to_json().get('doctor_id')}), 201
    except:
        return '', 500
Пример #13
0
def create_doctor():
    if not request.is_json or 'name' not in request.get_json():
        return bad_request('Missing required data.')
    doctor = Doctor(request.get_json()['name'])
    db.session.add(doctor)
    db.session.commit()
    return jsonify({'doctor': doctor.serialize}), 201
Пример #14
0
    def get(self):
        code = int(self.request.get('code', '0'))
        q = Department.gql('WHERE dptCode >= :1 ORDER BY dptCode', code)
        dpts = q.fetch(limit=2)
        nowDpt  = dpts[0]
        
        soup = BeautifulSoup( urllib2.urlopen( nowDpt.dptLink ) )
        trlist = soup.table.findAll('tr', align='left')
        for tr in trlist:
            tdlist = tr.findAll('td')
            
            column = 0;
            for td in tdlist:
                if column == 0:
                    dateStr = td.text.split('(')[1].split(')')[0]
                    month   = dateStr.split('/')[0]
                    day     = dateStr.split('/')[1]
                    year    = str(datetime.datetime.now().year)
                else:
                    if column == 1:
                        timeStr = 'A'
                    elif column == 2:
                        timeStr = 'B'
                    else:
                        timeStr = 'C'
 
                    alist = td.findAll(lambda tag: tag.name == 'a' and len(tag.attrs) == 2)
                    for a in alist:
                        text = a.text
                        name = re.split('[0-9]', text)[0]
                        doc  = Doctor.all().filter('docName = ', name).get()
                        if doc:
                            clinic = Clinic()
                            link = a['href']
                            code = link.split('data=')[1].split('&sLoc')[0]
                            clinic.link = tzuPrifix + link
                            clinic.code = code
                            clinic.doctor = doc.key()
                            clinic.dept   = nowDpt.key()
                            clinic.date   = year + '-' + month + '-' + day + '-' + timeStr
                            clinic.put()

                column = column + 1
        
        if( len(dpts) > 1):
            nextDpt = dpts[1]
            nextUrl  = '/parse/clinic?code=%d' %  nextDpt.dptCode 
            nextName = nextDpt.dptName
        else:
            nextUrl  = '/'
            nextName = 'END OF PARSING'

        context = { 
            'type'    : 'Clinic',
            'nextUrl' : nextUrl,
            'nextName': nextName,
        }
        path = os.path.join( os.path.dirname('__file__'), 'templates', 'parser.html')
        self.response.out.write( template.render( path, context) )
Пример #15
0
def doctor_add():
    form = DoctorForm()
    if request.method == 'POST' and form.validate_on_submit():
        doctor = Doctor(name=form.name.data, age=form.age.data, gender=form.gender.data, hospital=current_user.hospital)
        db.session.add(doctor)
        db.session.commit()
        flash('Doctor Data is added', 'success')
    return render_template('doctor_add.html', form=form)
Пример #16
0
def get_doctors():
    query = Doctor.query.all()
    doctors = [Doctor.format() for doctor in query]
    result = {
        "success": True,
        "doctors": doctors
    }
    return jsonify(result), 200
Пример #17
0
def create_doctor():
    doctor_data = json.loads(request.data)
    doctor = Doctor(name=doctor_data["name"],
                    address=doctor_data["address"],
                    salary=doctor_data["salary"],
                    email=doctor_data["email"])
    try:
        doctor.insert()
    except IntegrityError:
        return jsonify({
            "success": False,
            "description": "there is doctor with the same email"
        })
    except Exception as err:
        return jsonify({"success": False, "error": str(err)}), 500

    return jsonify({"success": True, "doctor": doctor.format()}), 200
Пример #18
0
def docLogin():
    form = LoginForm()
    if form.validate_on_submit():
        user = Doctor.get_by_username(form.username.data)
        if user is not None and user.check_password(form.password.data):
            login_user(user, form.remember_me.data)
            flash("logged in successfully as {}".format(user.username))
            return redirect(url_for('docHome', id=user.id))
            flash("Incorrect username or password")
    return render_template("doclogin.html", form=form)
Пример #19
0
def get_doctor_info_ajax():
    human = Human(tc=request.form.get('doctor_tc')).get_object()
    doctor = Doctor(human=human).get_object()
    day_list = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    workdays_ = doctor.workdays
    workdays = list()
    for i, workday_ in enumerate(workdays_):
        if int(workday_) == i + 1:
            workdays.append(day_list[i + 1])
    return render_template('sub_templates/doctor_info.html', doctor=doctor, workdays=workdays)
Пример #20
0
 def test_doctor_model(self):
     """Does basic model work?"""
     d = Doctor(first_name="John",
                last_name="Fulcan",
                office_phone="555-5555")
     db.session.add(d)
     db.session.commit()
     """Doctor should have no patients & no medications"""
     self.assertEqual(len(d.medications), 0)
     self.assertEqual(len(d.medications_given), 0)
Пример #21
0
    def setUp(self):
        """Create test client, add sample data."""
        db.drop_all()
        db.create_all()

        d1 = Doctor(first_name="John", last_name="Fulcan")
        d2 = Doctor(first_name="Mike", last_name="NightRider")

        db.session.add(d1)
        db.session.add(d2)

        p1 = Patient(first_name="Blub",
                     last_name="Booper",
                     date_of_birth=datetime.date(1999, 1, 19))
        p2 = Patient(first_name="Jak",
                     last_name="Alomaty",
                     date_of_birth=datetime.date(2001, 3, 21))

        db.session.add(p1)
        db.session.add(p2)

        n1 = Nurse(first_name='Marko', last_name="jamie")
        n2 = Nurse(first_name='Jimbo', last_name="Kilayin")

        db.session.add(n1)
        db.session.add(n2)

        db.session.commit()

        d1 = Doctor.query.get(1)
        d2 = Doctor.query.get(2)
        p1 = Patient.query.get(1)
        p2 = Patient.query.get(2)

        self.d1 = d1
        self.d2 = d2
        self.p1 = p1
        self.p2 = p2
        self.n1 = n1
        self.n2 = n2

        self.client = app.test_client()
Пример #22
0
def addUser():
    form = AddUserForm()
    if form.validate_on_submit():
        new = Doctor(username=form.username.data,
                     email=form.email.data,
                     password_hash=form.password.data)
        db.session.add(new)
        db.session.commit()
        flash('New {} added!!'.format(new.username))
        return redirect(url_for('dashboard'))
    return render_template('addUser.html', form=form)
Пример #23
0
    def post(self):
        okey = False
        errorMessage = ''
        docData   = self.request.get('doctor')
        deptData  = self.request.get('dept')
        timeData  = self.request.get('time')  
        idData    = self.request.get('id')
        firstData = self.request.get('first')
        phoneData = self.request.get('phone')
        
        if len(phoneData) == 0 and bool(firstData.lower() == 'true'):
            jsDic = { "status" : "2",  
                      "message": [{"phone":"Phone Number"}],
                    }       
            self.response.headers['Content-Type'] = 'application/json'
            self.response.out.write( simplejson.dumps(jsDic) )
            return 

        # Check for rest values:
        doc  = Doctor.all().filter('docCode =', docData ).get()
        dept = Department.all().filter('dptCode =', int(deptData) ).get()
        if not doc:
            errorMessage = 'BadDoctorId'
        elif not dept:
            errorMessage = 'BadDeptId'
        elif not timeData:
            errorMessage = 'MissingTimeInfo'
        else:
            clinic = Clinic.all().filter('doctor =', doc).filter('dept =', dept).filter('date =', timeData).get()
            if not clinic:
                errorMessage = 'WrongInfo'
            else:
                okey = True 
       
         
        if okey:
            # Save the info to the db:
            reg = Register()
            reg.doc = doc
            reg.dept = dept
            reg.link = clinic.link
            reg.theId = idData
            reg.isFirst = bool(firstData.lower() == 'true')
            reg.phone = phoneData
            reg.put()
            self.redirect('/tools/register?key=%s' % str(reg.key()) )
        
        else:
            jsDic = { "status":"1",
                      "message": errorMessage,
                    }
            self.response.headers['Content-Type'] = 'application/json'
            self.response.out.write( simplejson.dumps(jsDic) )
Пример #24
0
    def get(self):
        code = int(self.request.get('code', '0'))
        q = Department.gql('WHERE dptCode >= :1 ORDER BY dptCode', code)
        dpts = q.fetch(limit=2)
        nowDpt  = dpts[0]
        
        soup = BeautifulSoup( urllib2.urlopen( nowDpt.dptLink ) )
        list = soup.table.findAll('a')
        for one in list:
            text = one.text;
            name = re.split('[0-9]', text)[0]
            code = text[ len(name):].split(' ')[0].split('(')[0]  # Dealing w/ the special cases
            doc  = Doctor.all().filter('docCode =', code).get()
            if not doc and len(code) != 0:
                doc = Doctor()
                doc.docName = name
                doc.docCode = code
                doc.put()
        
        if( len(dpts) > 1):
            nextDpt  = dpts[1] 
            nextUrl  = '/parse/doctor?code=%d' %  nextDpt.dptCode 
            nextName = nextDpt.dptName
        else:
            nextUrl  = '/'
            nextName = 'END OF PARSING'

        context = { 
            'type'    : 'Doctor',
            'nextUrl' : nextUrl,
            'nextName': nextName,
        }
        path = os.path.join( os.path.dirname('__file__'), 'templates', 'parser.html')
        self.response.out.write( template.render( path, context) )
Пример #25
0
def add_human():
    name = request.form.get("doctor_name")
    surname = request.form.get("doctor_surname")
    tc = request.form.get("doctor_tc")
    password = request.form.get("doctor_password")
    email = request.form.get("doctor_email")
    authorize = request.form.get("authorize_select")
    city = request.form.get("city_select_add")
    district = request.form.get("district_select_add")
    address = Place(city=city, district=district).get_objects()[0]

    human = Human(tc=tc).get_object()
    if human is None:
        human = Human(tc=tc, password=password, authorize=authorize, name=name, surname=surname, mail=email,
                      address=address)
        human.save()

    if authorize == 'doctor':
        workdays = str()
        day_list = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
        for i, day in enumerate(day_list):
            if request.form.get(day) == "on":
                workdays += str(i + 1)
        expertise = request.form.get("doctor_expertise")
        hospital_id = request.form.get("hospital_select_add")
        hospital = Hospital(id=hospital_id).get_object()

        doctor = Doctor(human=human).get_object()
        if doctor is None:
            doctor = Doctor(human=human, workdays=workdays, expertise=expertise, hospital=hospital)
            doctor.save()
        #  else doctor is already created

    return redirect(url_for(views.admin_humans_page.__name__))
Пример #26
0
def create_doctor(user_data):
    user = Doctor(
            government_id = user_data["government_id"],
            first_name = user_data["first_name"],
            last_name = user_data["last_name"],
            email = user_data["email"],
            phone_number = user_data["phone_number"],
            password_hash = create_password_hash( user_data["password"] ),
            verified = False
        )
    add_doctor_degrees( user, user_data.getlist("degree") )

    return user
Пример #27
0
def add_history():
    patient = Human(tc=session['user_tc']).get_object()
    doctor_tc = request.form.get('doctor_select')
    doctor = Doctor(human=Human(tc=doctor_tc).get_object()).get_object()
    hospital_id = request.form.get('hospital_select')
    hospital = Hospital(id=hospital_id).get_object()
    sickness = request.form.get('sickness')
    date = request.form.get('date')
    time = request.form.get('time')
    date_time = date + " " + time

    History(date=date_time, patient=patient, doctor=doctor, hospital=hospital, sickness=sickness).save()
    return redirect(url_for(views.home_page.__name__))
Пример #28
0
def add_user_doctors():

    request_body = json.loads(request.data)

    if request_body["name"] == None and request_body[
            "last_name"] == None and request_body["Especialidad"] == None:
        return "Datos incompletos"
    else:

        user = Doctor(name=request_body["name"],
                      last_name=request_body["last_name"],
                      Especialidad=request_body["Especialidad"])
        db.session.add(user)
        db.session.commit()
        return "Posteo exitoso"
Пример #29
0
    def doctors_list(self, request):
        doctors = Doctor.all()

        doctors_message = []

        for d in doctors:
            doctors_message.append(DoctorMessage(full_name=d.full_name,
                                                 sent = d.sent,
                                                 email = d.email,
                                                 specialities = d.specialities,
                                                 poll_open = d.poll_open,
                                                 invited_by = d.invited_by
                                                 ))


        return DoctorsCollection(doctors=doctors_message)
Пример #30
0
    def doctor_save(self, doctor_msg):

        doctor = Doctor(email=doctor_msg.email)
        doctor.from_message(doctor_msg)
        doctor.user = users.User(doctor_msg.email)

        doctor.put()

        doctor_msg.registered_at = doctor.registered_at
        doctor_msg.key = doctor.key.urlsafe()

        return doctor_msg
Пример #31
0
    def send_email(self, request):

        to_email = request.email

        doctor = Doctor.all().filter("email =",to_email)[0]

        if (mail.is_email_valid(to_email) and doctor):

            from_email = "Carlos Pinelly <*****@*****.**>"
            subject = u"Apoyo para trabajo de investigación"
            body = email_body % (doctor.full_name)

            mail.send_mail(from_email, to_email, subject, body)

            doctor.sent = True
            doctor.put()

        return message_types.VoidMessage()
Пример #32
0
def seeder():

    print('#### Check Database seed ####')
    all_hospitals = db.session.execute(db.select(Hospital)).all()
    all_hospitals = [id for id, in all_hospitals]

    if (len(all_hospitals) <= 0):
        print('#### Tables are empty ####')
        print('#### Adding some entries... ####')
        with open('flaskr/seeders/seeders.json') as f:
            print('#### Adding some entries... ---####')
            data = json.load(f)

        for hospital in data['hospitals']:
            new_hospital = Hospital(hospital['id'], hospital['name'], hospital['city'])
            db.session.add(new_hospital)

        patients = {}
        for patient in data['patients']:
            new_patient = Patient(patient['id'], patient['name'], patient['surname'], patient['dni'], patient['hospital_id'])
            patients[patient['id']] = new_patient
            db.session.add(new_patient)

        for doctor in data['doctors']:
            new_doctor = Doctor(doctor['id'], doctor['name'], doctor['surname'], doctor['speciality'])
            if (new_doctor.id == '014bd297-0a3d-4a17-b207-cff187690045'):
                new_doctor.patients.append(patients['3a268172-6c5c-4d9b-8964-8b9a1e531af5'])
            if (new_doctor.id == 'a0f54d52-5ccb-4e50-adca-5ea0064262fd'):
                new_doctor.patients.append(patients['088d58e2-7691-47b6-a322-eeffcadc9054'])
            if (new_doctor.id == '1497d1be-577a-41ad-b129-45271e113cc0'):
                new_doctor.patients.append(patients['8ec8c43b-f7e1-43e4-b70f-6d5a9799a86a'])
            if (new_doctor.id == '9bb2e300-fa15-4063-a291-13f7199ddb52'):
                new_doctor.patients.append(patients['923ec756-87b7-4743-808b-795a04b6dd21'])
                new_doctor.patients.append(patients['3a268172-6c5c-4d9b-8964-8b9a1e531af5'])
            db.session.add(new_doctor)

        print(patients)
    
        db.session.commit()
        print('#### Finished! ####')
    else:
        print('#### Database already seed ####')
Пример #33
0
    def get(self, *args):


        user = users.get_current_user()

        if user:

            if users.is_current_user_admin():
                self.redirect('/amministratore')
                return

            if Doctor.by_email(user.email()):
                self.redirect('/manager')
                return

        template = JE.get_template('index.html')
        login_url = users.create_login_url('/manager')
        self.response.out.write(template.render({
                                                 'login_url':  login_url
                                                 }))
Пример #34
0
    def get(self, *args):
        template = JE.get_template('manager.html')

        user = users.get_current_user()

        doctor = None

        if user:
            doctor = Doctor.by_email(user.email())

            if not doctor:
                if users.is_current_user_admin():
                    self.redirect('/amministratore')
                else:
                    self.redirect('/')
                    return

        logout_url = users.create_logout_url('/')
        self.response.out.write(template.render({
                                                 'logout_url': logout_url,
                                                 'doctor': doctor
                                                 }))
Пример #35
0
def add_doctors():
    name = input("Insira o nome do médico: ")
    cpf = input("Insira o CPF do médico: ")
    crm = input("Insira a CRM do médico: ")

    while True:
        try:
            genre = input(
                "Insira o sexo do médico (F - Feminino ou M - Masculino): ")

            if genre.upper() != Genre.FEMALE and genre.upper() != Genre.MALE:
                raise Exception(
                    "Insira um sexo válido (F - Feminino ou M - Masculino) ")
        except Exception as e:
            print(e)
        else:
            break

    while True:
        try:
            status = int(
                input(
                    "Insira o Status do cliente (1 - Ativo ou 2 - Inativo): "))

            if status != Status.ACTIVE and status != Status.INACTIVE:
                raise Exception(
                    "Insira um status válido(1 - Ativo ou 2 - Inativo)")
        except Exception as e:
            print(e)
        else:
            break

    doctor_class = Doctor(name, cpf, crm, genre.upper(), status)

    try:
        create_doctor(doctor_class)
    except Exception as e:
        print(e)
Пример #36
0
def save_user(doctor, access_token):
    """

    :param doctor:
    :param access_token:
    :return: saved user and doctor objects which can be used for performing operations
    """
    user = User.objects.create_user(
        id=doctor['id'],
        username=doctor['username'],
    )
    doctor = Doctor(
        first_name=doctor['first_name'],
        last_name=doctor['last_name'],
        user=user,
        token=access_token,
    )
    if Doctor.objects.filter(pk=user).exists():
        doctor.save(update_fields=['first_name', 'last_name'])
    else:
        doctor.save()

    return doctor, user
Пример #37
0
def screen():

    print("from screen")
    print(request.method)

    if request.method == 'POST':

        name_of_test = request.form['name_of_test']
        if name_of_test not in [
                'fsmc', 'hads', 'memory_test', 'sf-36', '25_foot', '9_hpt',
                'pasat_3', 'neurostatus_scoring'
        ]:
            print('error')

        print("Here")

        birth_day = int(request.form['birth_day'])
        birth_month = int(request.form['birth_month'])
        birth_year = int(request.form['birth_year'])

        birth_date = datetime(birth_year, birth_month, birth_day)
        print(birth_date)

        patient = Patient.query.filter_by(fname=request.form['fname'].lower(),
                                          sname=request.form['sname'].lower(),
                                          lname=request.form['lname'].lower(),
                                          birth_date=birth_date).first()

        if not patient:

            patient = Patient(
                fname=request.form['fname'].lower(),
                sname=request.form['sname'].lower(),
                lname=request.form['lname'].lower(),
                birth_date=birth_date,
                sex=True if request.form['sex'] == "male" else False,
            )

            db.session.add(patient)
            db.session.commit()
            print("Patient Created")
        else:
            print("Patient Existed")

        doctor = Doctor.query.filter_by(
            fname=request.form['spec_fname'].lower(),
            sname=request.form['spec_sname'].lower(),
            lname=request.form['spec_lname'].lower(),
            clinic=request.form['clinic'].lower()).first()

        if not doctor:

            doctor = Doctor(fname=request.form['spec_fname'].lower(),
                            sname=request.form['spec_sname'].lower(),
                            lname=request.form['spec_lname'].lower(),
                            clinic=request.form['clinic'].lower())

            db.session.add(doctor)
            db.session.commit()
            print("Doctor Created")
        else:
            print("Doctor Existed")

        visit_day = int(request.form['visit_day'])
        visit_month = int(request.form['visit_month'])
        visit_year = int(request.form['visit_year'])

        visit_date = datetime(visit_year, visit_month, visit_day)
        print(visit_date)

        visit = Visit.query.filter_by(patient_id=patient.id,
                                      doctor_id=doctor.id,
                                      visit_date=visit_date).first()

        if not visit:

            visit = Visit(patient_id=patient.id,
                          doctor_id=doctor.id,
                          visit_date=visit_date)

            db.session.add(visit)
            db.session.commit()
            print("Visit Created")
        else:
            print("Visit Existed")

        screen_name = '_'.join([str(visit.id), name_of_test]) + '.png'
        screen_name = os.path.join(UPLOAD_FOLDER, screen_name)

        screenshot = request.form['screen'].split(',')[1]
        screenshot = base64.b64decode(screenshot)

        with open(screen_name, 'wb') as file:
            file.write(screenshot)

        print(name_of_test)

        test_summary = None
        if name_of_test == 'neurostatus_scoring':

            test_summary = EDSS(
                visit_id=visit.id,
                screenshot_path=screen_name,
                visual=float(request.form['visual']),
                brainstem=float(request.form['brainstem']),
                pyramidal=float(request.form['pyramidal']),
                cerebellar=float(request.form['cerebellar']),
                sensory=float(request.form['sensory']),
                bowel_bladder=float(request.form['bowel_bladder']),
                cerebral=float(request.form['cerebral']),
                ambulation_score=float(request.form['ambulation_score']),
                edss_step=float(request.form['edss_step']),
            )

        if name_of_test == 'fsmc':

            test_summary = FSMC(visit_id=visit.id,
                                screenshot_path=screen_name,
                                kog=int(request.form['kog']),
                                mot=int(request.form['mot']),
                                total=int(request.form['total']))

        if name_of_test == '25_foot':

            test_summary = Foot25(
                visit_id=visit.id,
                screenshot_path=screen_name,
                foot25_try1=float(request.form['foot25_try1']),
                foot25_try2=float(request.form['foot25_try2']),
                foot25_tools=request.form['foot25_tools'],
                foot25_addition=request.form['foot25_addition'])

        if name_of_test == 'hads':

            test_summary = HADS(visit_id=visit.id,
                                screenshot_path=screen_name,
                                anxiety=int(request.form['hads_anx']),
                                depression=int(request.form['hads_dep']))

        if name_of_test == 'memory_test':

            test_summary = MemoryTest(
                visit_id=visit.id,
                screenshot_path=screen_name,
                memtest_all=int(request.form['memtest_all']),
                memtest_correct=int(request.form['memtest_correct']),
                memtest_wrong=int(request.form['memtest_wrong']))

        if name_of_test == 'sf-36':

            test_summary = SF36(visit_id=visit.id,
                                screenshot_path=screen_name,
                                PHC=float(request.form['PHC']),
                                MHC=float(request.form['MHC']))

        if name_of_test == 'pasat_3':

            test_summary = PASAT3(visit_id=visit.id,
                                  screenshot_path=screen_name,
                                  form_type=request.form['pasat_form_type'],
                                  correct=int(request.form['pasat_correct']),
                                  procent=float(request.form['pasat_procent']))

        if name_of_test == '9_hpt':

            test_summary = HPT9(
                visit_id=visit.id,
                screenshot_path=screen_name,
                main_hand=request.form['hpt9_hand'],
                attempt_main_hand_1=float(request.form['hpt9_main_hand_1']),
                attempt_main_hand_2=float(request.form['hpt9_main_hand_2']),
                note_main=request.form['hpt9_note_main'],
                attempt_sec_hand_1=float(request.form['hpt9_sec_hand_1']),
                attempt_sec_hand_2=float(request.form['hpt9_sec_hand_1']),
                note_sec=request.form['hpt9_note_sec'])

        try:
            assert test_summary
            db.session.add(test_summary)
            db.session.commit()
        except AssertionError:
            print('No information about test results')

        print(test_summary)

    return redirect(url_for('index'))
Пример #38
0
def get_doctors_ajax():
    hospital = Hospital(id=request.form.get('hospital_id')).get_object()
    doctors = Doctor(hospital=hospital).get_objects()
    response = " ".join(
        ['<option value="{}">{}</option>'.format(doctor.human.tc, doctor.human.name + " " + doctor.human.surname) for doctor in doctors])
    return response
Пример #39
0
def register_doctor():
    f_name = input('enter first name: ')
    l_name = input('enter last name: ')
    print('the doctor is added!!!')
    d = Doctor(f_name, l_name)
    doctors.append(d)
Пример #40
0
def delete_doctor():
    tc = request.form.get("doctor_tc")
    human_for_check = Human(tc=tc).get_object()
    if human_for_check is not None:
        Doctor(human=human_for_check).delete()
    return redirect(url_for('admin_humans_page'))
Пример #41
0
"""SEED FOR CAPSTONE"""
from models import db, connect_db, Medication, Doctor, Patient, Nurse, Medication_Given
from app import app
import datetime

# Create Tables
db.drop_all()
db.create_all()

d1 = Doctor(first_name="mikey", last_name="jamie", office_phone="555-5555")
d2 = Doctor(first_name="Jun", last_name="Folkan", office_phone="555-5555")
d3 = Doctor(first_name="Moke", last_name="NightRyder", office_phone="555-5555")
d4 = Doctor(first_name="Miguel", last_name="Sabado", office_phone="555-5555")

db.session.add(d1)
db.session.add(d2)
db.session.add(d3)
db.session.add(d4)
#  datetime.date(yr, month, day)
p1 = Patient(first_name="koopa",
             last_name="posha",
             date_of_birth=datetime.date(1999, 1, 19))
p2 = Patient(first_name="musha",
             last_name="shqarm",
             date_of_birth=datetime.date(2001, 4, 21))
p3 = Patient(first_name="Gibber",
             last_name="Nimmerman",
             date_of_birth=datetime.date(1973, 1, 9))
p4 = Patient(first_name="Andy",
             last_name="Rudoph",
             date_of_birth=datetime.date(1973, 1, 9))
Пример #42
0
 def get(self):
     doctors = Doctor.all()
     for one in doctors:
         one.delete()
     self.response.out.write('Delete all doctor data ...')
Пример #43
0
    def post(self):
        docData  = self.request.get('doctor')
        deptData = self.request.get('dept')
        timeData = self.request.get('time') 

        doc  = Doctor.all().filter('docCode =', docData ).get()
        dept = Department.all().filter('dptCode =', int(deptData) ).get()
        
        # Check for post data:
        errorMessage = None
        if not doc:
            errorMessage = 'BadDoctorId'
        elif not dept:
            errorMessage = 'BadDeptId'
        elif not timeData:
            errorMessage = 'MissingTimeInfo'
        else:
            clinic = Clinic.all().filter('doctor =', doc).filter('dept =', dept).filter('date =', timeData).get()
            if not clinic:
                errorMessage = 'WrongInfo'
 
        if errorMessage:
            jsDic = { "status":"1",
                      "message": errorMessage,
                    }
            self.response.headers['Content-Type'] = 'application/json'
            self.response.out.write( simplejson.dumps(jsDic) )
            return
       
        vals = {}
        vals['RadioButtonList1'] = '花蓮'
        vals['txtMRNo'] = 'A123123123'
        vals['btnQry'] = '查詢'
        vals['__EVENTARGUEMENT'] = ''
        vals['__EVENTTARGET'] = ''
        vals['__VIEWSTATE'] = ''

        cookie = cookielib.CookieJar()
        opener = urllib2.build_opener( urllib2.HTTPCookieProcessor(cookie))
      
        #Operation: GET ----------------------'
        req = urllib2.Request(cancelUrl)
        rsp = opener.open(req)
        soup = BeautifulSoup(rsp)

        qText = soup.find(id='lblQuestion').text
        if len(qText.split('+')) == 2:
            A = qText.split('+')[0]
            B = qText.split('+')[1].split('=')[0]
            C = int(A) + int(B)

        elif len(qText.split('-')) == 2:
            A = qText.split('-')[0]
            B = qText.split('-')[1].split('=')[0]
            C = int(A) - int(B)

        vals['txtAnswer'] = str(C)
        vals['__EVENTVALIDATION'] = soup.find(id='__EVENTVALIDATION')['value']
        vals['__VIEWSTATE'] = soup.form.find(id='__VIEWSTATE')['value']

        #Operation: POST --------------------'
        req = urllib2.Request(cancelUrl, urllib.urlencode(vals) )
        rsp = opener.open(req)

        soup = BeautifulSoup(rsp)
        error = soup.find(id='Label5')
        if error: # No Registeration
            jsDic = { "status":"1",
                      "message": error.text,
                    }
            self.response.headers['Content-Type'] = 'application/json'
            self.response.out.write( simplejson.dumps(jsDic) )
            return

        rTable = soup.find(id='dgList')
        results = rTable.findAll('tr')
        row = 0
        target = None
        for one in results:
            if row != 0:
                tds = one.findAll('td')
                col = 0
                for td in tds:
                    if col == 0:
                        script = td.find('a')['href']
                    elif col == 1:
                        date = td.text
                    elif col == 2:
                        time = td.text
                    elif col == 4:
                        docInfo = td.text
                    col = col + 1
            
                year  = str(int(date[:3]) + 1911)
                month = date[3:5]
                day   = date[5:]

                if time == u'早上':
                    time = 'A'
                elif time == u'下午':
                    time = 'B'
                elif time == u'晚上':
                    time = 'C'
            
                datetime = year + '-' + month + '-' + day + '-' + time
                docCode  = docInfo.split('(')[1].split(')')[0].split(' ')[0]

                if doc.docCode == docCode and clinic.date == datetime:
                    target = script.split('\'')[1].split('\'')[0]
                    break

            row = row + 1

        if target:
            vals['__EVENTTARGET'] = target
            vals['__EVENTVALIDATION'] = soup.find(id='__EVENTVALIDATION')['value']
            vals['__VIEWSTATE'] = soup.form.find(id='__VIEWSTATE')['value'] 
            del vals['btnQry']

            req = urllib2.Request(cancelUrl, urllib.urlencode(vals) )
            rsp = opener.open(req)
            jsDic = { "status": "0" }
        
        else: 
            jsDic = { "status":"1",
                      "message": "RecordNotFound",
                    }

        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write( simplejson.dumps(jsDic) )