Beispiel #1
0
def register(user_type):

    if current_user.is_authenticated:
        return redirect(url_for('deliveries', username=current_user.username))

    form = RecipientRegistrationForm(
    ) if user_type == 'recipient' else VolunteerRegistrationForm()
    header = f'{user_type.capitalize()} Registration'

    if form.validate_on_submit():
        if user_type == 'volunteer':
            user = Volunteer(name=form.name.data,
                             username=form.username.data,
                             email=form.email.data,
                             phone=form.phone.data)
        elif user_type == 'recipient':
            user = Recipient(name=form.name.data,
                             username=form.username.data,
                             email=form.email.data,
                             phone=form.phone.data,
                             address=form.address.data,
                             address_notes=form.address_notes.data)

        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('Thank you for registering for Hanover Helpers!')
        login_user(user)
        return redirect(url_for('deliveries', username=current_user.username))

    return render_template('standard_form.html', header=header, form=form)
def generate_fakes():
	Author.generate_fake()
	BookDetails.generate_fake()
	BookInventory.generate_fake()
	Client.generate_fake()
	Person.generate_fake()
	Volunteer.generate_fake()
	Donor.generate_fake()
Beispiel #3
0
def set_volunteer_details(
    request: schemas.UpdateVolunteerInfoRequest,
    db: Session = Depends(get_db),
    volunteer: models.Volunteer = Depends(get_current_active_volunteer)):
    if volunteer.email != request.new_email:
        if db.query(models.Volunteer).filter(
                models.Volunteer.email == request.new_email).first():
            raise HTTPException(
                status.HTTP_409_CONFLICT,
                detail="Volunteer already exists with the provided email")
        volunteer.email = request.new_email
    volunteer.address_lat = request.new_address.address_lat
    volunteer.address_lng = request.new_address.address_lng
    volunteer.address_str = request.new_address.address_str
    db.commit()
Beispiel #4
0
def get_volunteer_mission(
    uuid: pydantic.UUID4,
    db: Session = Depends(get_db),
    volunteer: models.Volunteer = Depends(get_current_active_volunteer)):
    mission = crud.get_mission_by_uuid(db, uuid)
    if not mission:
        raise HTTPException(status.HTTP_404_NOT_FOUND,
                            detail="No such mission")

    volunteer_mission_statuses = crud.get_all_volunteer_mission_statuses(
        db, mission)
    if any(s == models.VolunteerMissionState.accepted
           for s in volunteer_mission_statuses):
        check_volunteer_mission(db,
                                mission,
                                volunteer,
                                in_state=models.VolunteerMissionState.accepted)
    else:
        check_volunteer_mission(db, mission, volunteer)

    if mission.state.name == models.MissionState.approved.name:
        return schemas.SlimMissionResponse(
            **mission.__dict__,
            distance=utils.distance_to_string(
                volunteer.calculate_distance_from(mission.elder_address)))
    elif mission.state.name in {
            models.MissionState.acquired.name, models.MissionState.started.name
    }:
        return schemas.VolunteerMission(**mission.to_dict())
    else:
        raise HTTPException(status.HTTP_403_FORBIDDEN,
                            detail="Mission is not longer required volunteer")
Beispiel #5
0
 def test_delete_user(self):
     v = Volunteer(username='******')
     db.session.add(v)
     db.session.commit()
     self.assertIn(v, Volunteer.query.all())
     db.session.delete(v)
     db.session.commit()
     self.assertNotIn(v, Volunteer.query.all())
     all_userdir_ids = [u.id for u in UserDirectory.query.all()]
     self.assertNotIn(v.userdir_id, all_userdir_ids)
 def post(self):
     data = request.get_json()
     try:
         volunteer = Volunteer(tournament_id=data.get("tournament_id"), \
                             user_id=Security.get_current_user().id)
         db.session.add(volunteer)
         db.session.commit()
     except IntegrityError:
         db.session.rollback()
         return "You've already signed up for this event"
     return None, 201
Beispiel #7
0
def new_volunteer():
    form = VolunteerForm(request.form)
    if request.method == 'POST' and form.validate():

        new_volunteer = Volunteer(name=form.name.data,
                                  email=form.email.data,
                                  role=form.role.data)

        db.session.add(new_volunteer)
        db.session.commit()

        flash('Volunteer ' + new_volunteer.name + ' added!', 'success')

        return redirect(url_for('index'))
    return render_template('volunteer_form.html', form=form)
Beispiel #8
0
def create_volunteer_post():
    form = VolunteerForm()
    if form.validate_on_submit():
        postImage = ""
        if form.postImage.data:
            postImage = save_post_image(form.postImage.data)
        post = Volunteer(Title=form.title.data,
                         Content=form.content.data,
                         ImageFile=postImage)
        db.session.add(post)
        db.session.commit()
        flash("Succesfully Posted!", category='success')
        return redirect(url_for('main.volunteer'))

    return render_template('volunteer/create-volunteer-post.html',
                           form=form,
                           title="Make a story")
Beispiel #9
0
 def test_transaction_assign_recipient_volunteer(self):
     t = Transaction()
     r = Recipient(username='******')
     v = Volunteer(username='******')
     db.session.add_all([t, r, v])
     db.session.commit()
     t.assign_recipient(r)
     self.assertEqual(t.recipient, r)
     self.assertEqual(t.recipient_id, r.id)
     self.assertFalse(t.claimed)
     self.assertEqual(r.transactions[0], t)
     t.assign_volunteer(v)
     db.session.add(t)
     db.session.commit()
     self.assertEqual(t.volunteer, v)
     self.assertEqual(t.volunteer_id, v.id)
     self.assertTrue(t.claimed)
     self.assertEqual(v.transactions[0], t)
Beispiel #10
0
def notify_volunteer_new_mission(db: Session, volunteer: models.Volunteer,
                                 mission: models.Mission):
    volunteer_distance_from_mission = utils.calculate_distance(
        coord1=volunteer.address_coords, coord2=mission.elder_address)
    utils.notifications_handler.send_new_assistance_request(
        volunteer_name=volunteer.first_name_capitalized,
        volunteer_phone=volunteer.phone_number,
        distance=volunteer_distance_from_mission,
        elder_name=mission.elder_first_name_capitalized,
        mission_url=config.MISSON_FOR_VOLUNTEER_URL.format(
            mission_id=mission.uuid))
    volunteer.last_whatsapp_mission_at = models.get_utc_now()
    if mission not in volunteer.missions:
        volunteer.missions.append(mission)
    else:
        logger.info(
            f"Mission {mission.uuid} already exists for volunteer {volunteer.uuid}"
        )
Beispiel #11
0
def decline_mission(
    uuid: pydantic.UUID4,
    decline_request: schemas.DeclineMissionRequest,
    background_tasks: BackgroundTasks,
    db: Session = Depends(get_db),
    volunteer: models.Volunteer = Depends(get_current_active_volunteer)):
    mission: models.Mission = crud.get_mission_by_uuid(db, uuid)
    if not mission:
        raise HTTPException(status.HTTP_404_NOT_FOUND,
                            detail="No such mission")

    crud.handle_decline_mission(db, mission.uuid, volunteer.id,
                                decline_request.reason, background_tasks)

    return schemas.SlimMissionResponse(**mission.to_dict(),
                                       distance=utils.distance_to_string(
                                           volunteer.calculate_distance_from(
                                               mission.elder_address)))
Beispiel #12
0
def new_volunteer():
    form = VolunteerForm(request.form)
    if request.method == 'POST' and form.validate():
        new_volunteer = Volunteer(name=form.name.data,
                                  email=form.email.data,
                                  role=form.role.data,
                                  active=True)

        db.session.add(new_volunteer)
        db.session.commit()
        # try:
        #     db.session.add(new_volunteer)
        #     db.session.commit()
        # except exc.SQLAlchemyError:
        #     return '<h1>NOPE</h1>'

        flash('Volunteer %s added!' % new_volunteer.name, 'success')

        return redirect(url_for('volunteers.index'))
    return render_template('volunteer_form.html', form=form)
Beispiel #13
0
def get_volunteer_home_page(
        db: Session = Depends(get_db),
        volunteer: models.Volunteer = Depends(get_current_active_volunteer)):
    last_mission_completed_date = volunteer.last_completed_mission.state_changed_at.date(
    ) if volunteer.last_completed_mission else 0
    last_mission_elder_first_name = volunteer.missions[
        -1].elder_first_name if len(volunteer.missions) > 0 else ""
    last_mission_elder_address = volunteer.missions[
        -1].elder_address_str if len(volunteer.missions) > 0 else ""

    return schemas.GetHomePageResponse(
        volunteer=dict(volunteer.__dict__,
                       age=volunteer.age,
                       address=volunteer.__dict__),
        is_subscribed=volunteer.is_subscribed,
        volunteers_count=8266,
        elders_count=2729,
        # volunteers_count=crud.get_volunteers_count(db),
        # elders_count=volunteer.count_elders(),
        last_mission_elder_first_name=last_mission_elder_first_name,
        last_mission_elder_address=last_mission_elder_address,
        last_mission_completed_date=last_mission_completed_date,
        missions_amount=volunteer.completed_mission_count())
Beispiel #14
0
def add_volunteer(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('index')) # Logged in users shouldn't be able to sign up
    else:
        if request.method == "POST":
            profile_form = UserForm(request.POST)
            if profile_form.is_valid():
                user = Volunteer()
                user.first_name = profile_form.cleaned_data.get("first_name")
                user.last_name = profile_form.cleaned_data.get("last_name")
                user.email = profile_form.cleaned_data.get("email")
                user.phone = profile_form.cleaned_data.get("phone")
                user.address = profile_form.cleaned_data.get("address")

                user.save()
                
                user_resources = profile_form.cleaned_data.get("has_resources")
                
                user_resource_objects = [Resource.objects.filter(name=r).first() for r in user_resources]

                for r in user_resource_objects:
                    user.has_resources.add(r)
                
                user.save()
                
                    

        
                # Grab email set dependent on language value (may need to change values)
                if request.LANGUAGE_CODE == 'es':
                    from email_texts import spanish_version_emails as emails
                else:
                    from email_texts import english_version_emails as emails
                    
                # Find some nearby locations that need the things the volunteer has
                coords = find_search_coordinates(user.address)
                
                within_radius = []
                
                if len(user_resource_objects) == 0:
                    #do not include anything about local orgs if the user specified no resources
                    pass
                elif not coords:
                    #do not include local orgs if the coordinates weren't found
                    pass
                elif len(user_resource_objects) == 1 and user_resource_objects[0].name.lower() == "other":
                    #do not include local orgs if the only resource is "other"
                    pass
                else:
                    locations = Location.objects.select_related('provider').exclude(provider__approved=False)
                    locations = locations.filter(resources_needed__in=user_resource_objects)
                    locations = set(locations)
                    
                    for location in locations:
                        dist = vincenty(
                            (location.latitude, location.longitude), 
                            (coords['latitude'], coords['longitude'])
                            ).miles
                    
                        if dist <= RADIUS_DISTANCE:
                            within_radius.append((location,round(dist,1)))
                        
                    
                    within_radius.sort(key=lambda tup: tup[1])
                    
                    within_radius = within_radius[0:3] #only display the 3 nearest locations in email
                
                vol_conf_texts = emails['volunteer_signup']['confirmation']
                if len(within_radius) > 0:
                    getting_started = vol_conf_texts["here_are_some_orgs"].decode('utf-8')
                    for location_tuple in within_radius:
                        location = location_tuple[0]
                        dist = location_tuple[1]
                        
                        location_resources = []
                        for r in location.resources_needed.all():
                            if r.name in emails['resource_translation']:
                                location_resources.append(emails['resource_translation'][r.name])

                        location_info = [location.provider.name.decode('utf-8'),
                                        location.address,location.phone.decode('utf-8'),
                                        location.provider.URL.decode('utf-8'),
                                        "{0} {1}".format(dist,vol_conf_texts["miles_from_you"].decode('utf-8')),
                                        "{0} {1}".format(vol_conf_texts["resources_needed"].decode('utf-8'),', '.join(location_resources)),
                                        '\n\n']
                        getting_started = getting_started.decode('utf-8')
                        getting_started += '\n'.join(location_info)
                    getting_started += vol_conf_texts["find_some_more_orgs"].decode('utf-8')
                else:
                    getting_started = vol_conf_texts["find_some_orgs"].decode('utf-8')
                    
                getting_started += " http://www.buscandomaryland.com/resources/volunteer"
                    
                # Grab admin email list (if not already grabbed or stored somewhere else)
                admin_email_list = [admin_email_address]
                
                vol_resources = []
                for r in user_resources:
                    if r in emails['resource_translation']:
                        vol_resources.append(emails['resource_translation'][r.lower()])
                
                if len(vol_resources) > 0:
                    vol_resources = ','.join(vol_resources)
                else:
                    vol_resources = "None"
        
                # Build confirmation email
                email = emails['volunteer_signup']['confirmation']
                volunteer_email_body = email['body'].format(firstname=user.first_name,
                    vol_username=user.email,
                    vol_location=user.address,
                    resources_available=vol_resources,
                    getting_started = getting_started)
                confirmation_email = (email['subject'], volunteer_email_body, email['from'], [user.email])
        
                # Build admin notification email
                email = emails['volunteer_signup']['admin']
                admin_email_body = email['body'].format(vol_username=user.email)
                admin_email = (email['subject'], admin_email_body, email['from'], admin_email_list)
        
                # Send Them
                try:
                    send_mass_mail((admin_email, confirmation_email), fail_silently=False)
                except:
                    pass
                #end of code for confirmation e-mail
                
                
                # Still need to check for saving of skills they have here
                return HttpResponseRedirect(reverse('resources'))
        else:
            profile_form = UserForm()
        return render(request, "volunteer/new.html", { 'profile_form': profile_form})
Beispiel #15
0
 def test_register_volunteer(self):
     v = Volunteer(username='******')
     db.session.add(v)
     db.session.commit()
     self.assertEqual(Volunteer.query.first(), v)
     self.assertEqual(UserDirectory.query.first().id, v.userdir_id)
    def generate_fake(count=100, **kwargs):
        """Generate a number of fake users for testing."""
        from sqlalchemy.exc import IntegrityError
        from random import seed, choice
        import random
        import enum
        import datetime
        from faker import Faker
        from app.models import Volunteer, Status

        fake = Faker()
        roles = Role.query.all()
        now = datetime.datetime.now()
        seed()

        for i in range(count):
            fake_first_name = fake.first_name()
            fake_last_name = fake.last_name()
            fake_email = fake.email()
            fake_phone_number = fake.phone_number().replace('-', '')
            fake_street = fake.street_address()
            fake_city = fake.city()
            fake_state = fake.state_abbr(include_territories=True)
            fake_zip_code = fake.zipcode()
            fake_organization = fake.company()
            fake_clearance_exp = fake.date(pattern='%Y-%m-%d',
                                           end_datetime=None)
            fake_residency = random.choice(["Yes", "No"])
            user_role = choice(roles)

            u = User(first_name=fake_first_name,
                     last_name=fake_last_name,
                     email=fake_email,
                     phone_number=fake_phone_number,
                     street=fake_street,
                     city=fake_city,
                     state=fake_state,
                     zip_code=fake_zip_code,
                     organization_corporation=fake_organization,
                     pa_residency=fake_residency,
                     password='******',
                     confirmed=True,
                     role=user_role,
                     **kwargs)

            # User is only assigned as a volunteer if its user_role is 'Volunteer'
            if (user_role.name == 'Volunteer'):
                if (i < 5):
                    v = Volunteer(first_name=fake_first_name,
                                  last_name=fake_last_name,
                                  email=fake_email,
                                  phone_number=fake_phone_number,
                                  address_street=fake_street,
                                  address_city=fake_city,
                                  address_state=fake_state,
                                  address_zip_code=fake_zip_code,
                                  organization=fake_organization,
                                  year_pa=fake_residency,
                                  clearance_expiration=fake_clearance_exp,
                                  status1=Status.CLEARED,
                                  comment1=fake.text(max_nb_chars=100,
                                                     ext_word_list=None),
                                  link1=fake.uri(),
                                  status2=Status.CLEARED,
                                  comment2=fake.text(max_nb_chars=100,
                                                     ext_word_list=None),
                                  link2=fake.uri(),
                                  status3=Status.CLEARED,
                                  comment3=fake.text(max_nb_chars=100,
                                                     ext_word_list=None),
                                  link3=fake.uri(),
                                  status4=Status.CLEARED,
                                  comment4=fake.text(max_nb_chars=100,
                                                     ext_word_list=None),
                                  link4=fake.uri(),
                                  **kwargs)
                else:
                    v = Volunteer(first_name=fake_first_name,
                                  last_name=fake_last_name,
                                  email=fake_email,
                                  phone_number=fake_phone_number,
                                  address_street=fake_street,
                                  address_city=fake_city,
                                  address_state=fake_state,
                                  address_zip_code=fake_zip_code,
                                  organization=fake_organization,
                                  year_pa=fake_residency,
                                  clearance_expiration=fake_clearance_exp,
                                  status1=random.choice(list(Status)),
                                  comment1=fake.text(max_nb_chars=100,
                                                     ext_word_list=None),
                                  link1=fake.uri(),
                                  status2=random.choice(list(Status)),
                                  comment2=fake.text(max_nb_chars=100,
                                                     ext_word_list=None),
                                  link2=fake.uri(),
                                  status3=random.choice(list(Status)),
                                  comment3=fake.text(max_nb_chars=100,
                                                     ext_word_list=None),
                                  link3=fake.uri(),
                                  status4=random.choice(list(Status)),
                                  comment4=fake.text(max_nb_chars=100,
                                                     ext_word_list=None),
                                  link4=fake.uri(),
                                  **kwargs)

            db.session.add(u)
            # User is only assigned as a volunteer if its user_role is 'Volunteer'
            if (user_role.name == 'Volunteer'):
                db.session.add(v)

            try:
                db.session.commit()
            except IntegrityError:
                db.session.rollback()
 def make_volunteer(self, data, **kwargs):
     return Volunteer(**data)
Beispiel #18
0
def view_clearances():
    """View all volunteer clearances."""
    volunteers = Volunteer.query.all()
    now = datetime.now()
    exp_arr = []
    for v in volunteers:
        if v.clearance_expiration:
            split_arr = v.clearance_expiration.split('-')
            if len(split_arr) != 3:
                exp_arr.append("NA")
            else:
                exp = datetime(int(split_arr[0]), int(split_arr[1]),
                               int(split_arr[2]))
                delta = now - exp
                if delta.days > -60:
                    exp_arr.append("Yes")
                else:
                    exp_arr.append("No")
        else:
            exp_arr.append("NA")
    """Download CSV with all volunteer information"""
    download_csv_form = DownloadCSVForm()
    upload_csv_form = UploadCSVForm()

    if request.method == 'POST':
        if request.form.get('download_csv'):

            csv_file = io.StringIO()
            csv_writer = csv.writer(csv_file)
            filename = 'volunteers' + datetime.now().strftime(
                "%Y%m%d-%H%M%S") + '.csv'

            csv_writer.writerow([
                'First Name', 'Last Name', 'Email', 'Phone Number',
                'Address Street', 'City', 'State', 'Zip Code', 'Organization',
                'Over 10 years in PA', 'Clearance Expiration Date',
                'PA State Police Check Status', 'Comment 1',
                '(Link) PA State Police Check', 'PA Childlink', 'Comment 2',
                '(Link) PA Childlink', 'FBI Clearance', 'Comment 3',
                '(Link) FBI Clearance', 'Conflict of Interest', 'Comment 4',
                '(Link) Conflict of Interest'
            ])

            for v in volunteers:
                csv_writer.writerow([
                    v.first_name,
                    v.last_name,
                    v.email,
                    v.phone_number,
                    v.address_street,
                    v.address_city,
                    v.address_state,
                    v.address_zip_code,
                    v.organization,
                    v.year_pa,
                    v.clearance_expiration,
                    str(v.status1),
                    v.comment1,
                    v.link1,
                    str(v.status2),
                    v.comment2,
                    v.link2,
                    str(v.status3),
                    v.comment3,
                    v.link3,
                    str(v.status4),
                    v.comment4,
                    v.link4,
                ])

            csv_bytes = io.BytesIO()
            csv_bytes.write(csv_file.getvalue().encode('utf-8'))
            csv_bytes.seek(0)

            # Send file for download.
            return send_file(csv_bytes,
                             as_attachment=True,
                             attachment_filename=filename,
                             mimetype='text/csv')

        else:
            f = request.files['volunteer-file']
            name = f.filename
            stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None)
            csv_input = csv.reader(stream)
            header_row = True

            for row in csv_input:
                if header_row:
                    header_row = False
                    continue

                u = User(first_name=row[0],
                         last_name=row[1],
                         email=row[2],
                         phone_number=row[3],
                         street=row[4],
                         city=row[5],
                         state=row[6],
                         zip_code=row[7],
                         organization_corporation=row[8],
                         pa_residency=row[9],
                         password='******',
                         confirmed=True,
                         role_id=1)

                db.session.add(u)

                if 'Y' in row[9]:
                    status3 = Status.NOT_NEEDED
                else:
                    status3 = Status.NOT_SUBMITTED

                v = Volunteer(first_name=row[0],
                              last_name=row[1],
                              email=row[2],
                              phone_number=row[3],
                              address_street=row[4],
                              address_city=row[5],
                              address_state=row[6],
                              address_zip_code=row[7],
                              organization=row[8],
                              year_pa=row[9],
                              clearance_expiration=row[10],
                              status1=Status.NOT_SUBMITTED,
                              comment1='',
                              link1='',
                              status2=Status.NOT_SUBMITTED,
                              comment2='',
                              link2='',
                              status3=status3,
                              comment3='',
                              link3='',
                              status4=Status.CLEARED,
                              comment4='',
                              link4='')

                db.session.add(v)

                try:
                    db.session.commit()
                except IntegrityError:
                    db.session.rollback()

    return render_template('admin/view_clearances.html',
                           volunteers=volunteers,
                           download_csv_form=download_csv_form,
                           upload_csv_form=upload_csv_form,
                           exp_arr=exp_arr)
Beispiel #19
0
def new_volunteer():
    """Create a new volunteer."""
    form = NewVolunteerForm()
    if form.is_submitted():
        print("submitted")

    if form.validate_on_submit():
        print("valid")

    print(form.errors)
    if form.validate_on_submit():
        user = User(
            role_id=1,
            first_name=form.first_name.data,
            last_name=form.last_name.data,
            email=form.email.data,
            password=form.password.data,
            phone_number=form.phone_number.data,
            street=form.street.data,
            city=form.city.data,
            state=form.state.data,
            zip_code=form.zip_code.data,
            organization_corporation=form.organization_corporation.data,
            pa_residency=form.pa_residency.data,
            confirmed=True)
        db.session.add(user)
        if form.pa_residency.data == "Yes":
            volunteer = Volunteer(
                first_name=form.first_name.data,
                last_name=form.last_name.data,
                email=form.email.data,
                phone_number=form.phone_number.data,
                address_street=form.street.data,
                address_city=form.city.data,
                address_state=form.state.data,
                address_zip_code=form.zip_code.data,
                organization=form.organization_corporation.data,
                year_pa=form.pa_residency.data,
                status1=Status.NOT_SUBMITTED,
                status2=Status.NOT_SUBMITTED,
                status3=Status.NOT_NEEDED,
                status4=Status.NOT_SUBMITTED)
        if form.pa_residency.data == "No":
            volunteer = Volunteer(
                first_name=form.first_name.data,
                last_name=form.last_name.data,
                email=form.email.data,
                phone_number=form.phone_number.data,
                address_street=form.street.data,
                address_city=form.city.data,
                address_state=form.state.data,
                address_zip_code=form.zip_code.data,
                organization=form.organization_corporation.data,
                year_pa=form.pa_residency.data,
                status1=Status.NOT_SUBMITTED,
                status2=Status.NOT_SUBMITTED,
                status3=Status.NOT_SUBMITTED,
                status4=Status.NOT_SUBMITTED)
        db.session.add(volunteer)
        db.session.commit()
        flash('Volunteer {} successfully created'.format(user.full_name()),
              'form-success')
        return redirect(url_for('main.index'))
    return render_template('admin/new_volunteer.html',
                           form=form,
                           is_volunteer=True)
def init_persons():
	Person.generate_fake(100)
	Donor.generate_fake()
	Volunteer.generate_fake()
Beispiel #21
0
def add_volunteers(json_path):
    volunteers = read_json(json_path)
    for id, data in volunteers.items():
        volunteer = Volunteer(id=id, name=data['name'], userpic=data['userpic'], phone=data['phone'])
        db.session.add(volunteer)
    db.session.commit()
Beispiel #22
0
def register():
    """Register a new user, and send them a confirmation email."""
    form = RegistrationForm()
    if form.is_submitted():
        print("submitted")

    if form.validate_on_submit():
        print("valid")

    print(form.errors)
    if form.validate_on_submit():
        user = User(
            first_name=form.first_name.data,
            last_name=form.last_name.data,
            email=form.email.data,
            password=form.password.data,
            phone_number=form.phone_number.data,
            street=form.street.data,
            city=form.city.data,
            state=form.state.data,
            zip_code = form.zip_code.data,
            organization_corporation=form.organization_corporation.data,
            pa_residency =form.pa_residency.data,
            confirmed=False,
            role_id=1)
        db.session.add(user)
        if form.pa_residency.data == "Yes":
            volunteer = Volunteer(
                first_name=form.first_name.data,
                last_name=form.last_name.data,
                email=form.email.data,
                phone_number=form.phone_number.data,
                address_street=form.street.data,
                address_city=form.city.data,
                address_state=form.state.data,
                address_zip_code = form.zip_code.data,
                organization = form.organization_corporation.data,
                year_pa = form.pa_residency.data,
                status1=Status.NOT_SUBMITTED,
                status2=Status.NOT_SUBMITTED,
                status3=Status.NOT_NEEDED,
                status4=Status.NOT_SUBMITTED
            )
        if form.pa_residency.data == "No":
            volunteer = Volunteer(
                first_name=form.first_name.data,
                last_name=form.last_name.data,
                email=form.email.data,
                phone_number=form.phone_number.data,
                address_street=form.street.data,
                address_city=form.city.data,
                address_state=form.state.data,
                address_zip_code = form.zip_code.data,
                organization = form.organization_corporation.data,
                year_pa = form.pa_residency.data,
                status1=Status.NOT_SUBMITTED,
                status2=Status.NOT_SUBMITTED,
                status3=Status.NOT_SUBMITTED,
                status4=Status.NOT_SUBMITTED
            )
        db.session.add(volunteer)
        # db.session.query(user)
        db.session.commit()

        token = user.generate_confirmation_token()
        confirm_link = url_for('account.confirm', token=token, _external=True)
        get_queue().enqueue(
            send_email,
            recipient=user.email,
            subject='Confirm Your Account',
            template='account/email/confirm',
            user=user,
            confirm_link=confirm_link)
        flash('A confirmation link has been sent to {}.'.format(user.email),
              'warning')
        return redirect(url_for('main.index'))
    return render_template('account/register.html', form=form)