Exemple #1
0
def event_details(id):
    """Render a page that allows the user to enter more details
    about the event.
    """
    details_form = EventDetailsForm()
    upload_image_form = UploadImageForm()
    remove_image_form = RemoveImageForm()
    details_form.submit.label.text = "Submit"
    event = Event.query.get_or_404(id)

    if not current_user.is_organizer(
            event) and not current_user.is_administrator():
        return redirect(url_for("main.index"))

    if details_form.validate_on_submit():
        event.description = details_form.description.data
        event.pitch = details_form.pitch.data
        db.session.commit()
        flash("Update successful.", "success")
        return redirect(url_for("events.event_details", id=event.id))
    # pre-fill fields
    details_form.description.data = event.description
    details_form.pitch.data = event.pitch
    return render_template(
        "events/event_details.html",
        details_form=details_form,
        upload_image_form=upload_image_form,
        remove_image_form=remove_image_form,
        main_image_path=event.main_image(),
        event=event,
    )
Exemple #2
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     self.team.choices = [(0, '')] + \
                         [(t.team_id, t) for t in Team.query.filter(Team.name == TEAM_ORGANIZATION).all()] + \
                         [(t.team_id, t) for t in Team.query.filter(Team.name == TEAM_SUPER_VOLUNTEER).all()] + \
                         [(t.team_id, t) for t in Team.query.filter(Team.name != TEAM_SUPER_VOLUNTEER).all()
                          if t.is_active()]
     self.volunteer.choices = [
         (0, 'Please select a volunteer to assign to this shift.')
     ]
     if current_user.is_organizer():
         super_volunteers = User.query.filter(
             User.volunteer_id.isnot(None)).all()
         contestants = Contestant.query.join(StatusInfo).filter(
             StatusInfo.status == CONFIRMED).all()
         volunteers = sorted(super_volunteers +
                             [c.user for c in contestants],
                             key=lambda x: x.get_full_name())
         self.volunteer.choices.extend([(u.user_id, f"{u.get_full_name()}")
                                        for u in volunteers])
     elif current_user.is_tc():
         volunteers = Contestant.query.join(StatusInfo, ContestantInfo)\
             .filter(ContestantInfo.team == current_user.team, StatusInfo.status == CONFIRMED)\
             .order_by(Contestant.first_name).all()
         self.volunteer.choices.extend([
             (v.user.user_id, v.user.get_full_name()) for v in volunteers
         ])
Exemple #3
0
def media(id):
    """Return a page that allows the user do at various forms of
    media to their event page."""
    event = Event.query.get_or_404(id)
    if not current_user.is_organizer(
            event) and not current_user.is_administrator():
        return redirect(url_for("main.index"))

    # Instantiate forms
    upload_video_form = UploadVideoForm()
    remove_video_form = RemoveVideoForm()
    image_form = MultipleImageForm()
    remove_image_form = RemoveImageForm()

    # Get data from user session
    upload_video_form.video_url.errors = session.pop(
        "upload_video_form_errors", [])
    upload_video_form.video_url.data = session.pop("video_url", "")
    image_form.images.errors = session.pop("image_form_errors", [])

    return render_template(
        "events/media.html",
        upload_video_form=upload_video_form,
        remove_video_form=remove_video_form,
        image_form=image_form,
        remove_image_form=remove_image_form,
        video=event.video,
        misc_image_paths=event.misc_images(),
        event=event,
    )
Exemple #4
0
def register():
    form = SuperVolunteerForm()
    if g.ts.super_volunteer_registration_open or current_user.is_organizer():
        if request.method == 'POST':
            form.custom_validate()
            all_users = User.query.all()
            emails = [u.email.lower() for u in all_users if u.email is not None]
            form_email = form.email.data
            if form_email.lower() in emails and form_email is not None:
                flash(f'There is already a dancer registered with the e-mail address {form.email.data}.<br/>'
                      f'You cannot register as both a dancer in the tournament, and a Super Volunteer.<br/>'
                      f'If you are already registered as a dancer, and wish to be a Super Volunteer instead, '
                      f'please contact your teamcaptain to completely remove your registration as a dancer '
                      f'from the tournament first. Afterwards, you can register as a Super Volunteer.',
                      "alert-danger")
            else:
                if form.validate_on_submit():
                    if 'privacy_checkbox' in request.values:
                        super_volunteer = SuperVolunteer()
                        super_volunteer.update_data(form)
                        db.session.add(super_volunteer)
                        db.session.commit()
                        flash(f'<b>Registration complete:</b> {super_volunteer.get_full_name()}, '
                              f'you have been successfully registered as a Super Volunteer.', 'alert-success')
                        # noinspection PyTypeChecker
                        create_super_volunteer_user_account(form, super_volunteer)
                        return redirect(url_for('main.index'))
                    else:
                        flash('You can not register without accepting the privacy statement.', 'alert-danger')
    return render_template('volunteering/register_volunteer.html', form=form)
Exemple #5
0
def edit_package(event_id, package_id):
    """View function to add a package to an event in the database."""
    form = EventPackagesForm()
    event = Event.query.get_or_404(event_id)
    package = event.packages.filter(Package.id == package_id).first_or_404()
    if not current_user.is_organizer(
            event) and not current_user.is_administrator():
        return redirect(url_for("main.index"))
    if form.validate_on_submit():
        form_data = form.data
        form_data["audience"] = EventPackagesForm.convert_choice_to_value(
            form.audience.data, "PEOPLE_RANGES")
        form_data["package_type"] = EventPackagesForm.convert_choice_to_value(
            form.package_type.data, "PACKAGE_TYPES")
        package.update(**form_data)
        db.session.commit()
        flash("Package details were successfully updated.", "success")
        return redirect(url_for("events.packages", id=event_id))
    packages = event.packages.all()
    package_data = package.to_dict()
    package_data["audience"] = EventPackagesForm.convert_choice_to_id(
        package.audience, "PEOPLE_RANGES")
    package_data["package_type"] = EventPackagesForm.convert_choice_to_id(
        package.package_type, "PACKAGE_TYPES")
    form.populate(**package_data)
    return render_template("events/packages.html",
                           form=form,
                           event=event,
                           packages=packages)
Exemple #6
0
def demographics(id):
    """Return a page that allows the user to give details
    about who is attending the event.
    """
    form = DemographicsForm()
    event = Event.query.get_or_404(id)
    if not current_user.is_organizer(
            event) and not current_user.is_administrator():
        return redirect(url_for("main.index"))
    if form.validate_on_submit():
        event.attendees = DemographicsForm.convert_choice_to_value(
            form.attendees.data, "PEOPLE_RANGES")
        event.male_to_female = str(form.males.data) + "-" + str(
            form.females.data)
        db.session.commit()
        flash("Your information has been successfilly uploaded.", "success")
        return redirect(url_for("events.demographics", id=id))
    if event.attendees:
        form.attendees.data = DemographicsForm.convert_choice_to_id(
            event.attendees, "PEOPLE_RANGES")
    else:
        form.attendees.data = 1
    if event.male_to_female:
        distribution = event.male_to_female.split("-")
        form.males.data = distribution[0]
        form.females.data = distribution[1]
    else:
        form.males.data = 0
        form.females.data = 0
    return render_template("events/demographics.html", form=form, event=event)
Exemple #7
0
def external_adjudicator_register():
    form = SuperVolunteerForm()
    if g.ts.external_adjudicator_registration_open:
        if request.method == 'POST':
            if not current_user.is_organizer():
                form.custom_validate()
                all_users = User.query.all()
                emails = [u.email.lower() for u in all_users if u.email is not None]
                form_email = form.email.data
                if form_email.lower() in emails and form_email is not None:
                    flash(f'There is already someone registered with the e-mail address {form.email.data}.',
                          "alert-warning")
                else:
                    form.emergency_response_officer.data = NO
                    form.first_aid.data = NO
                    if form.validate_on_submit():
                        if 'privacy_checkbox' in request.values:
                            super_volunteer = SuperVolunteer()
                            super_volunteer.update_data(form)
                            db.session.add(super_volunteer)
                            db.session.commit()
                            flash(f'<b>Registration complete:</b> {super_volunteer.get_full_name()}, '
                                  f'you have been successfully registered as an external Adjudicator.', 'alert-success')
                            # noinspection PyTypeChecker
                            create_super_volunteer_user_account(form, super_volunteer, external_adjudicator=True)
                            return redirect(url_for('main.index'))
                        else:
                            flash('You can not register without accepting the privacy statement.', 'alert-danger')
            else:
                flash('You can not register as an external Adjudicator while logged in to the organizer account.',
                      'alert-warning')
    return render_template('volunteering/register_external_adjudicator.html', form=form)
Exemple #8
0
def delete_event(id):
    """View function to delete an event."""
    event = Event.query.get(id)
    if not current_user.is_organizer(
            event) and not current_user.is_administrator():
        return redirect(url_for("main.index"))
    db.session.delete(event)
    db.session.commit()
    return jsonify({"message": "Your event has been successfully deleted."})
Exemple #9
0
def delete_video(event_id, video_id):
    """View function to delete a video."""
    event = Event.query.get_or_404(event_id)
    if not current_user.is_organizer(
            event) and not current_user.is_administrator():
        return redirect(url_for("main.index"))
    video = Video.query.get_or_404(video_id)
    db.session.delete(video)
    db.session.commit()
    flash("Your video has been deleted.", "success")
    return redirect(url_for("events.media", id=event_id))
Exemple #10
0
def shifts():
    if current_user.is_tc() and not g.ts.volunteering_system_open:
        flash("This page is not accessible yet.")
        return redirect(url_for('main.dashboard'))
    all_tasks = ShiftInfo.query.order_by(ShiftInfo.name).all()
    if current_user.is_organizer():
        shift_list = Shift.query.order_by(Shift.start_time).all()
    else:
        shift_list = Shift.query.join(ShiftSlot)\
            .filter(or_(ShiftSlot.team == current_user.team,
                        and_(ShiftSlot.team_id.is_(None), ShiftSlot.mandatory.is_(False)),
                        and_(ShiftSlot.user_id.isnot(None), ShiftSlot.mandatory.is_(True))),
                    Shift.published.is_(True))\
            .order_by(Shift.start_time).all()
        shift_list = [s for s in shift_list if s.has_slots_available(current_user.team)]
    task_list = {task: [shift for shift in shift_list if shift.info == task] for task in all_tasks}
    if current_user.is_organizer():
        filled_list = {task: sum([shift.filled_slots() for shift in shift_list if shift.info == task])
                       for task in all_tasks}
        slots_list = {task: sum([len(shift.slots) for shift in shift_list if shift.info == task])
                      for task in all_tasks}
        return render_template('volunteering/shifts.html', shifts=shift_list, task_list=task_list,
                               filled_list=filled_list, slots_list=slots_list)
    else:
        task_list = {task: task_list[task] for task in task_list if len(task_list[task]) > 0}
        all_volunteers = Contestant.query.join(ContestantInfo, StatusInfo)\
            .filter(ContestantInfo.team == current_user.team, StatusInfo.status == CONFIRMED)\
            .order_by(Contestant.first_name).all()
        days = sorted(set([s.start_time.date() for s in shift_list]))
        sorted_shifts = {day: [s for s in shift_list if s.start_time.date() == day] for day in days}
        team_slots = ShiftSlot.query.filter(ShiftSlot.team == current_user.team).all()
        team_slots = [s for s in team_slots if s.shift.published]
        organization_slots = ShiftSlot.query.filter(ShiftSlot.mandatory.is_(True), ShiftSlot.user_id.isnot(None),
                                                    ShiftSlot.team_id.is_(None)).all()
        organization_slots = [s for s in organization_slots if s.user.team == current_user.team and s.shift.published]
        hours = {'total': hours_delta(sum([s.duration() for s in team_slots], timedelta(0, 0))),
                 'filled': hours_delta(sum([s.duration() for s in team_slots if s.user is not None], timedelta(0, 0))),
                 'freelance': hours_delta(sum([s.duration() for s in organization_slots], timedelta(0, 0)))
                 }
        return render_template('volunteering/shifts.html', shifts=shift_list, task_list=task_list,
                               all_volunteers=all_volunteers, sorted_shifts=sorted_shifts, hours=hours)
Exemple #11
0
def delete_image(filename):
    """View function to delete an event image."""
    referrer = request.referrer
    path = "/Users/ericmontague/sponsormatch/app/static/images/" + filename
    image = Image.query.filter_by(path=path).first_or_404()
    event = Event.query.get_or_404(image.event_id)
    if not current_user.is_organizer(
            event) and not current_user.is_administrator():
        return redirect(url_for("main.index"))
    db.session.delete(image)
    db.session.commit()
    flash("Your event image was successfully deleted.", "success")
    return redirect(referrer)
Exemple #12
0
def add_event_image(id):
    """view function to add an image to the database."""
    form = UploadImageForm()
    event = Event.query.get_or_404(id)
    if not current_user.is_organizer(
            event) and not current_user.is_administrator():
        return redirect(url_for("main.index"))
    if form.validate_on_submit():
        services.save_event_main_image(form.image.data, event, images,
                                       db.session)
        db.session.commit()
        flash("Your image was successfully uploaded.", "success")
        return redirect(url_for("events.event_details", id=id))
    return redirect(url_for("events.event_details", id=event.id))
Exemple #13
0
def configuration():
    form = RaffleConfigurationForm()
    if request.method == 'GET':
        form.populate()
    if request.method == 'POST':
        form.custom_validate()
    if form.validate_on_submit():
        form.save_settings()
        flash("Configuration saved.", "alert-success")
        if current_user.is_organizer():
            g.ts.raffle_system_configured = True
        db.session.commit()
        return redirect(url_for('main.dashboard'))
    return render_template('raffle/configuration.html', form=form)
Exemple #14
0
def edit_basic_info(id):
    """Return the view that allows a user to edit an event's basic info."""
    form = CreateEventForm()
    form.submit.label.text = "Update Event"
    event = Event.query.get_or_404(id)
    if not current_user.is_organizer(
            event) and not current_user.is_administrator():
        return redirect(url_for("main.index"))
    if form.validate_on_submit():
        services.update_models_from_create_event_form(form, event.venue, event)
        db.session.commit()
        flash("Your changes were saved.", "success")
        return redirect(url_for("events.edit_basic_info", id=id))
    services.populate_create_event_form(form, event.venue, event)
    return render_template("events/basic_info.html", form=form, event=event)
Exemple #15
0
def add_misc_images(id):
    """Add multiple images to the database for an event."""
    event = Event.query.get_or_404(id)
    if not current_user.is_organizer(
            event) and not current_user.is_administrator():
        return redirect(url_for("main.index"))
    image_form = MultipleImageForm()
    if image_form.validate_on_submit():
        services.save_misc_images(image_form.images.data, event, images,
                                  db.session)
        db.session.commit()
        flash("Your upload was successful.", "success")
        return redirect(url_for("events.media", id=id))
    else:
        session["image_form_errors"] = image_form.images.errors
    return redirect(url_for("events.media", id=event.id))
Exemple #16
0
def delete_package(event_id, package_id):
    """View function to be executed when a user wants to remove
    a sponsorship package from their event.
    """
    event = Event.query.get_or_404(event_id)
    if not current_user.is_organizer(
            event) and not current_user.is_administrator():
        return redirect(url_for("main.index"))

    package = event.packages.filter(Package.id == package_id).first_or_404()
    if package.was_purchased():
        flash("A package that was purchased cannot be deleted", "danger")
    else:
        db.session.delete(package)
        db.session.commit()
        flash(f"Package named {package.name} was successfully deleted",
              "success")
    return jsonify({"url": url_for("events.packages", id=event.id)})
Exemple #17
0
def dashboard():
    if current_user.is_treasurer():
        if g.ts.main_raffle_result_visible:
            return redirect(url_for('teamcaptains.edit_finances'))
        else:
            return redirect(url_for('teamcaptains.treasurer_inaccessible'))
    if current_user.is_organizer():
        if g.sc.finalize_merchandise() and g.ts.system_configured:
            flash(
                "Please check the merchandise tab. The last date for ordering merchandise has passed."
            )
    if current_user.is_bda():
        return redirect(url_for('adjudication_system.available_couples'))
    if current_user.is_floor_manager():
        return redirect(
            url_for('adjudication_system.floor_manager_start_page'))
    if current_user.is_presenter():
        return redirect(url_for('presenter.dashboard'))
    return render_template('dashboard.html')
Exemple #18
0
def add_video(id):
    """Add a video to the database for an event."""
    event = Event.query.get_or_404(id)
    if not current_user.is_organizer(
            event) and not current_user.is_administrator():
        return redirect(url_for("main.index"))
    upload_video_form = UploadVideoForm()
    if upload_video_form.validate_on_submit():
        video = Video(url=UploadVideoForm.parse_url(
            upload_video_form.video_url.data),
                      event=event)
        db.session.add(video)
        db.session.commit()
        flash("Your upload was successful.", "success")
        return redirect(url_for("events.media", id=id))
    else:
        session[
            "upload_video_form_errors"] = upload_video_form.video_url.errors
        session["video_url"] = upload_video_form.video_url.data
    return redirect(url_for("events.media", id=event.id))
Exemple #19
0
def create_super_volunteer_user_account(form, super_volunteer, external_adjudicator=False):
    super_volunteer_account = User()
    super_volunteer_account.username = form.email.data
    super_volunteer_account.email = form.email.data
    super_volunteer_account_password = random_password()
    super_volunteer_account.set_password(super_volunteer_account_password)
    super_volunteer_account.access = ACCESS[SUPER_VOLUNTEER]
    super_volunteer_account.is_active = True
    super_volunteer_account.send_new_messages_email = True
    super_volunteer_account.super_volunteer = super_volunteer
    if current_user.is_organizer():
        super_volunteer_account.team = Team.query.filter(Team.name == TEAM_ORGANIZATION).first()
    elif external_adjudicator:
        super_volunteer_account.team = Team.query.filter(Team.name == TEAM_ADJUDICATOR).first()
    else:
        super_volunteer_account.team = Team.query.filter(Team.name == TEAM_SUPER_VOLUNTEER).first()
    db.session.add(super_volunteer_account)
    db.session.commit()
    send_super_volunteer_user_account_email(super_volunteer_account, super_volunteer.get_full_name(),
                                            super_volunteer_account_password)
Exemple #20
0
def create_tournament():
    if not current_user.is_organizer():
        return abort(404)
    form = CreateTournamentForm()
    if form.validate_on_submit():
        tournament = Tournament()
        tournament.name = form.name.data
        tournament.category = form.category.data
        tournament.signups_open = form.signups_open.data
        tournament.signups_close = form.signups_close.data
        tournament.start_date = form.start_date.data
        tournament.end_date = form.end_date.data
        tournament.visible = form.visible.data
        db.session.add(tournament)
        db.session.commit()
        flash("%s has been created." % tournament.name)
        return redirect(url_for("tournaments"))
    return render_template("create_tournament.html",
                           title="Create Tournament",
                           form=form)
Exemple #21
0
def publish(id):
    """View function that is called when a user wants to publish their
    event.
    """
    event = Event.query.get_or_404(id)
    if (not current_user.is_organizer(event)
            and not current_user.is_administrator()) or event.has_ended():
        return redirect(url_for("main.index"))
    if event.description is None or event.pitch is None:
        flash(
            "You cannot publish an event without adding a description or pitch.",
            "danger")
        return redirect(url_for("events.event_details", id=event.id))
    if event.packages.count() == 0:
        flash("You cannot publish an event without adding any packages.",
              "danger")
        return redirect(url_for("events.packages", id=event.id))
    event.published = True
    db.session.commit()
    flash("Your event has been published.", "success")
    return redirect(url_for("main.index"))
Exemple #22
0
def packages(id):
    """Render a page that allows the user to select the sponsorship
    packages that will go along with theri event.
    """
    form = EventPackagesForm()
    event = Event.query.get_or_404(id)
    packages = event.packages.all()
    if not current_user.is_organizer(
            event) and not current_user.is_administrator():
        return redirect(url_for("main.index"))
    if form.validate_on_submit():
        form_data = form.data
        form_data["event"] = event
        form_data["audience"] = EventPackagesForm.convert_choice_to_value(
            form.audience.data, "PEOPLE_RANGES")
        form_data["package_type"] = EventPackagesForm.convert_choice_to_value(
            form.package_type.data, "PACKAGE_TYPES")
        package = Package.create(**form_data)
        db.session.commit()
        return redirect(url_for("events.packages", id=id))
    return render_template("events/packages.html",
                           form=form,
                           event=event,
                           packages=packages)
Exemple #23
0
def shift_slot(slot_id):
    slot = ShiftSlot.query.get(slot_id)
    form = ShiftSlotForm()
    task_id = request.args.get("task_id", default=None)
    if current_user.is_tc():
        if not slot.is_editable(current_user.team):
            flash("You cannot edit this shift, it is not part of your team!", "alert-warning")
            return redirect(url_for('volunteering.shifts',
                                    task_id=task_id if task_id is not None else slot.shift.info.shift_info_id))
        form.submit.label.text = 'Assign dancer'
        form.volunteer.description = 'Assigning a dancer to this shift wil automatically claim the shift for your team.'
        form.mandatory.validators = []
        form.mandatory.data = str(False)
    if request.method == 'POST':
        if form.submit.name in request.form:
            if form.validate_on_submit():
                volunteer = User.query.get(form.volunteer.data) if form.volunteer.data > 0 else None
                team = Team.query.get(form.team.data) if form.team.data > 0 else None
                if current_user.is_organizer():
                    if not slot.user_assigned_to_shift(volunteer):
                        if volunteer is not None:
                            test_shifts = Shift.query.join(ShiftSlot).filter(ShiftSlot.user == volunteer).all()
                            test_shifts = [s for s in test_shifts if not (slot.shift.stop_time <= s.start_time or
                                                                          slot.shift.start_time >= s.stop_time)]
                            if len(test_shifts) > 0:
                                flash(f"Added {volunteer} to {slot.shift}.<br/>{volunteer} is already assigned "
                                      f"to {test_shifts[0]} at the same time, so make sure that this is is "
                                      f"possible!", "alert-warning")
                        slot.user = volunteer
                        slot.team = team
                        if volunteer is not None and team is not None:
                            if team != volunteer.team:
                                slot.user = None
                                flash(f'Did not add {volunteer} to slot, he/she is not part of team {team}',
                                      'alert-warning')
                        slot.mandatory = str2bool(form.mandatory.data)
                        db.session.commit()
                        flash('Changes saved.')
                        return redirect(url_for('volunteering.single_shift', shift_id=slot.shift.shift_id))
                    else:
                        flash(f'Cannot assign {volunteer}, he/she is already assigned to a slot in this shift.',
                              'alert-warning')
                else:
                    slot.team = current_user.team
                    if volunteer is not None:
                        test_shifts = Shift.query.join(ShiftSlot).filter(ShiftSlot.user == volunteer).all()
                        test_shifts = [s for s in test_shifts if not (slot.shift.stop_time <= s.start_time or
                                                                      slot.shift.start_time >= s.stop_time)]
                        if len(test_shifts) > 0:
                            flash(f"Cannot add {volunteer} to {slot.shift}.<br/>{volunteer} is already assigned "
                                  f"to {test_shifts[0]}.", "alert-danger")
                            return redirect(url_for('volunteering.shift_slot', slot_id=slot.slot_id))
                        if not slot.user_assigned_to_shift(volunteer):
                            slot.user = volunteer
                            db.session.commit()
                            flash(f'Assigned {volunteer} to shift {slot.shift}.')
                            return redirect(url_for('volunteering.shifts',
                                                    task_id=task_id if task_id is not None
                                                    else slot.shift.info.shift_info_id))
                        else:
                            flash(f'Cannot assign {volunteer}, he/she is already assigned to a slot in this shift.',
                                  'alert-warning')
                    else:
                        flash(f'Cleared slot of shift {slot.shift}.')
                        slot.user = None
                        db.session.commit()
                        return redirect(url_for('volunteering.shifts',
                                                task_id=task_id if task_id is not None
                                                else slot.shift.info.shift_info_id))
        if current_user.is_tc():
            if 'claim' in request.form:
                slot.team = current_user.team
                db.session.commit()
                flash(f'Claimed slot in shift {slot.shift}.')
                return redirect(url_for('volunteering.shifts',
                                        task_id=task_id if task_id is not None else slot.shift.info.shift_info_id))
            if 'release' in request.form:
                slot.user = None
                slot.team = None
                db.session.commit()
                flash(f'Released slot in shift {slot.shift}.')
                return redirect(url_for('volunteering.shifts',
                                        task_id=task_id if task_id is not None else slot.shift.info.shift_info_id))
    form.populate(slot)
    return render_template('volunteering/slot.html', slot=slot, form=form)
Exemple #24
0
def system_configuration():
    form = SystemSetupForm()
    if request.method == 'GET':
        form.tournament.data = g.sc.tournament
        form.year.data = g.sc.year
        form.city.data = g.sc.city
        tsd = datetime.datetime.utcfromtimestamp(
            g.sc.tournament_starting_date).replace(
                tzinfo=datetime.timezone.utc)
        form.tournament_starting_date.data = datetime.date(
            tsd.year, tsd.month, tsd.day)

        form.main_page_link.data = g.sc.main_page_link
        form.terms_and_conditions_link.data = g.sc.terms_and_conditions_link
        form.merchandise_link.data = g.sc.merchandise_link

        form.number_of_teamcaptains.data = g.sc.number_of_teamcaptains
        form.additional_teamcaptain_large_teams.data = str(
            g.sc.additional_teamcaptain_large_teams)
        form.additional_teamcaptain_large_teams_cutoff.data = g.sc.additional_teamcaptain_large_teams_cutoff

        form.beginners_level.data = str(g.sc.beginners_level)
        form.closed_level.data = str(g.sc.closed_level)
        form.breitensport_obliged_blind_date.data = str(
            g.sc.breitensport_obliged_blind_date)
        form.salsa_competition.data = str(g.sc.salsa_competition)
        form.polka_competition.data = str(g.sc.polka_competition)

        form.student_price.data = g.sc.student_price
        form.non_student_price.data = g.sc.non_student_price
        form.phd_student_category.data = str(g.sc.phd_student_category)
        form.phd_student_price.data = g.sc.phd_student_price

        form.finances_refund.data = str(g.sc.finances_refund)
        form.finances_refund_percentage.data = g.sc.finances_refund_percentage
        frd = datetime.datetime.utcfromtimestamp(
            g.sc.finances_refund_date).replace(tzinfo=datetime.timezone.utc)
        frd += datetime.timedelta(days=-1)
        form.finances_refund_date.data = datetime.date(frd.year, frd.month,
                                                       frd.day)

        form.first_time_ask.data = str(g.sc.first_time_ask)
        form.ask_adult.data = str(g.sc.ask_adult)
        form.ask_diet_allergies.data = str(g.sc.ask_diet_allergies)
        form.ask_volunteer.data = str(g.sc.ask_volunteer)
        form.ask_first_aid.data = str(g.sc.ask_first_aid)
        form.ask_emergency_response_officer.data = str(
            g.sc.ask_emergency_response_officer)
        form.ask_adjudicator_highest_achieved_level.data = str(
            g.sc.ask_adjudicator_highest_achieved_level)
        form.ask_adjudicator_certification.data = str(
            g.sc.ask_adjudicator_certification)
    if request.method == 'POST':
        if current_user.is_organizer():
            form.tournament.data = g.sc.tournament
            form.year.data = g.sc.year
            form.city.data = g.sc.city
            tsd = datetime.datetime.utcfromtimestamp(
                g.sc.tournament_starting_date)
            form.tournament_starting_date.data = datetime.date(
                tsd.year, tsd.month, tsd.day)
            if g.ts.main_raffle_result_visible:
                form.number_of_teamcaptains.data = g.sc.number_of_teamcaptains
                form.additional_teamcaptain_large_teams.data = str(
                    g.sc.additional_teamcaptain_large_teams)
                form.additional_teamcaptain_large_teams_cutoff.data = g.sc.additional_teamcaptain_large_teams_cutoff
            if g.ts.registration_period_started:
                form.beginners_level.data = str(g.sc.beginners_level)
                form.closed_level.data = str(g.sc.closed_level)
                form.breitensport_obliged_blind_date.data = str(
                    g.sc.breitensport_obliged_blind_date)
        if form.number_of_teamcaptains.data == 2:
            form.additional_teamcaptain_large_teams.data = str(
                g.sc.additional_teamcaptain_large_teams)
            form.additional_teamcaptain_large_teams_cutoff.data = g.sc.additional_teamcaptain_large_teams_cutoff
        if not str2bool(form.finances_refund.data):
            form.finances_refund_date.data = datetime.date.today()
        if form.validate_on_submit():
            g.sc.tournament = form.tournament.data
            g.sc.year = form.year.data
            g.sc.city = form.city.data
            tsd = datetime.datetime(form.tournament_starting_date.data.year,
                                    form.tournament_starting_date.data.month,
                                    form.tournament_starting_date.data.day, 3,
                                    0, 0, 0)
            g.sc.tournament_starting_date = tsd.replace(
                tzinfo=datetime.timezone.utc).timestamp()

            g.sc.main_page_link = form.main_page_link.data
            g.sc.terms_and_conditions_link = form.terms_and_conditions_link.data
            g.sc.merchandise_link = form.merchandise_link.data

            g.sc.number_of_teamcaptains = form.number_of_teamcaptains.data
            g.sc.additional_teamcaptain_large_teams = str2bool(
                form.additional_teamcaptain_large_teams.data)
            g.sc.additional_teamcaptain_large_teams_cutoff = form.additional_teamcaptain_large_teams_cutoff.data

            g.sc.beginners_level = str2bool(form.beginners_level.data)
            g.sc.closed_level = str2bool(form.closed_level.data)
            g.sc.breitensport_obliged_blind_date = str2bool(
                form.breitensport_obliged_blind_date.data)
            g.sc.salsa_competition = str2bool(form.salsa_competition.data)
            g.sc.polka_competition = str2bool(form.polka_competition.data)

            g.sc.student_price = form.student_price.data
            g.sc.non_student_price = form.non_student_price.data
            g.sc.phd_student_category = str2bool(
                form.phd_student_category.data)
            g.sc.phd_student_price = form.phd_student_price.data

            g.sc.finances_refund = str2bool(form.finances_refund.data)
            g.sc.finances_refund_percentage = form.finances_refund_percentage.data
            frd = datetime.datetime(form.finances_refund_date.data.year,
                                    form.finances_refund_date.data.month,
                                    form.finances_refund_date.data.day, 3, 0,
                                    0, 0) + datetime.timedelta(days=1)
            g.sc.finances_refund_date = frd.replace(
                tzinfo=datetime.timezone.utc).timestamp()

            g.sc.first_time_ask = str2bool(form.first_time_ask.data)
            g.sc.ask_adult = str2bool(form.ask_adult.data)
            g.sc.ask_diet_allergies = str2bool(form.ask_diet_allergies.data)
            g.sc.ask_volunteer = str2bool(form.ask_volunteer.data)
            g.sc.ask_first_aid = str2bool(form.ask_first_aid.data)
            g.sc.ask_emergency_response_officer = str2bool(
                form.ask_emergency_response_officer.data)
            g.sc.ask_adjudicator_highest_achieved_level = str2bool(
                form.ask_adjudicator_highest_achieved_level.data)
            g.sc.ask_adjudicator_certification = str2bool(
                form.ask_adjudicator_certification.data)

            db.session.commit()
            flash("Configuration saved.", "alert-success")
            db.session.commit()
            if current_user.is_organizer():
                g.ts.system_configured = True
                return redirect(url_for('main.dashboard'))
            return redirect(url_for('self_admin.system_configuration'))
    return render_template('admin/system_configuration.html', form=form)