Skip to content

Commit

Permalink
Validate that corrent number of species submitted before saving to da…
Browse files Browse the repository at this point in the history
…tabase
  • Loading branch information
mikkohei13 committed Sep 4, 2024
1 parent 311c441 commit 09edc12
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 16 deletions.
7 changes: 4 additions & 3 deletions app/controllers/challenge.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,14 +131,15 @@ def main(challenge_id_untrusted):
raise ValueError

challenge_data = common_helpers.get_challenge(challenge_id)
# If challenge not found, quietly redirect to homepage
if not challenge_data:
# flash("Tätä haastetta ei löydy.", "info")
return {"redirect": True, "url": "/"}

# If challenge is still a draft, redirect to homepage
# If challenge is still a draft, quietly redirect to homepage
if challenge_data["status"] == "draft":
# flash("Tämä haaste ei ole juuri nyt avoinna.", "info")
return {"redirect": True, "url": "/"}

# TODO: If challenge is not open anymore

# Participation data
# Logged in user
Expand Down
28 changes: 19 additions & 9 deletions app/controllers/participation.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,10 @@ def validate_participation_data(form_data):
else:
form_data["place"] = ""

# 0) Add trashed if not present
if "trashed" not in form_data:
form_data["trashed"] = False

# Handle taxon data
# 1) Extract taxon data from form data
taxa_data = taxa_to_dict(form_data)
Expand All @@ -261,13 +265,23 @@ def validate_participation_data(form_data):
if not common_helpers.is_yyyy_mm_dd(value):
del taxa_data[key]

# 4) Add trashed if not present
if "trashed" not in form_data:
form_data["trashed"] = False

# 5) Calculate number of species
# 4) Calculate number of species
form_data["taxa_count"] = len(taxa_data)

# 5) Compare to date_fields_count, to see if all fields were received from the browser
# Do this only if user is not trashing / has not trashed the participation
if form_data["trashed"] == True or form_data["trashed"] == 1 or form_data["trashed"] == "1":
print("Trashed, skipping date_fields_count check.")
else:
if "date_fields_count" in form_data:
# print("Taxa count: ", form_data["taxa_count"])
# print("Date field count: ", form_data["date_fields_count"])

if form_data["taxa_count"] != int(form_data["date_fields_count"]):
raise Exception(f"Received incomplete data from browser (expected { form_data['date_fields_count'] } taxa, received { form_data['taxa_count'] }).")
else:
raise Exception("Received incomplete data from browser (date_fields_count missing).")

# 6) Convert to JSON string (for database JSON field) where dates are YYYY-MM-DD
# Note: form_data still has the original taxon data
form_data["taxa_json"] = json.dumps(taxa_data)
Expand Down Expand Up @@ -383,10 +397,6 @@ def main(challenge_id_untrusted, participation_id_untrusted, form_data = None):
# Todo: Maybe instead remove only empty taxon fields here?
form_data = {key: value for key, value in form_data.items(multi=True) if value}

# First check that form is fully received by checking that field form_completed has value "ready"
if "form_completed" not in form_data or form_data["form_completed"] != "ready":
raise Exception("Received incomplete data from browser.")

errors, form_data = validate_participation_data(form_data)

# Case C1: Errors found. Show the form again with error messages.
Expand Down
30 changes: 26 additions & 4 deletions app/templates/form_challenge100.html
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,28 @@
.then(data => speciesData = data);

document.addEventListener('DOMContentLoaded', function() {

// Count filled in date field before submission
// Todo: Change form name to participation. Side-effects?
document.getElementById('challenge').addEventListener('submit', function(event) {

// Select all date inputs with the class 'species_date'
var dateFields = document.querySelectorAll('#challenge input[type="date"]');
var filledCount = 0;

// Loop through each date field to check if it's filled
dateFields.forEach(function(field) {
if (field.value) { // If the field is not empty (i.e., has a value)
filledCount++;
}
});

// Set the count in the hidden input field
document.getElementById('date_fields_count').value = filledCount;
console.log("Number of filled date fields: " + filledCount);
});

// Autocmplete logic
const input = document.getElementById('autocomplete-input');
const resultsContainer = document.getElementById('autocomplete-results');

Expand Down Expand Up @@ -215,7 +237,7 @@
}, 300); // Wait 300 ms before processing the input
});
});

</script>

{% endblock %}
Expand Down Expand Up @@ -276,6 +298,9 @@ <h1>Osallistuminen: {{ html['challenge']['title'] }}</h1>
>
</p>

<!-- Hidden input field to store the count of filled date fields -->
<input type="hidden" id="date_fields_count" name="date_fields_count">

<p id="submit_container">
<button type="submit" id="submit_button">Tallenna osallistuminen</button>
</p>
Expand Down Expand Up @@ -316,9 +341,6 @@ <h3 id="taxon_count_heading">{{ html['data_fields']['taxa_count'] }} lajia</h3>
{{ html['taxa']|safe }}
</fieldset>

<!-- Hidden form field -->
<input type="hidden" name="form_completed" value="ready">

</form>

{% endblock %}
1 change: 1 addition & 0 deletions tests-playwright/test_login.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ def test_add_edit_participation(browser):
assert page.input_value("#MX_71663") == ""

# Trash the participation
page.fill("#MX_71822", "2024-01-01") # Add one more taxon to test trashing with changed taxon count
page.click("#trash_button")
page.click("#confirm_button")

Expand Down

0 comments on commit 09edc12

Please sign in to comment.