diff --git a/backend/secfit/workouts/serializers.py b/backend/secfit/workouts/serializers.py index 42c344044b722c6553b1a0a46442dfcf936e0064..4e3267ead3aa6f129a6245b202963d9b2f5cba51 100644 --- a/backend/secfit/workouts/serializers.py +++ b/backend/secfit/workouts/serializers.py @@ -98,7 +98,9 @@ class WorkoutSerializer(serializers.HyperlinkedModelSerializer): if "files" in validated_data: files_data = validated_data.pop("files") + print(validated_data) workout = Workout.objects.create(**validated_data) + print(workout) for exercise_instance_data in exercise_instances_data: ExerciseInstance.objects.create(workout=workout, **exercise_instance_data) @@ -127,6 +129,7 @@ class WorkoutSerializer(serializers.HyperlinkedModelSerializer): instance.name = validated_data.get("name", instance.name) instance.notes = validated_data.get("notes", instance.notes) + instance.owner = validated_data.get("owner", instance.owner) instance.visibility = validated_data.get("visibility", instance.visibility) instance.date = validated_data.get("date", instance.date) instance.save() diff --git a/backend/secfit/workouts/views.py b/backend/secfit/workouts/views.py index efddf40454376b23d233f9fe2cecaf9da43fddb8..13dd9720dd96242d205084f286669925825f9004 100644 --- a/backend/secfit/workouts/views.py +++ b/backend/secfit/workouts/views.py @@ -26,6 +26,7 @@ from workouts.models import Workout, Exercise, ExerciseInstance, WorkoutFile from workouts.serializers import WorkoutSerializer, ExerciseSerializer from workouts.serializers import RememberMeSerializer from workouts.serializers import ExerciseInstanceSerializer, WorkoutFileSerializer +from django.contrib.auth import get_user_model from django.core.exceptions import PermissionDenied from rest_framework_simplejwt.tokens import RefreshToken from rest_framework.response import Response @@ -128,7 +129,10 @@ class WorkoutList( return self.create(request, *args, **kwargs) def perform_create(self, serializer): - serializer.save(owner=self.request.user) + owner = self.request.POST.get("owner") + User = get_user_model() + user = User.objects.get(username=owner) + serializer.save(owner=user) def get_queryset(self): qs = Workout.objects.none() diff --git a/frontend/www/scripts/workout.js b/frontend/www/scripts/workout.js index 94eddb777de4dba4cc24b4ef447430a989b0c935..bc95851bb273e4b8332432a2c0fd701febe8c9b0 100644 --- a/frontend/www/scripts/workout.js +++ b/frontend/www/scripts/workout.js @@ -4,350 +4,458 @@ let deleteWorkoutButton; let editWorkoutButton; let postCommentButton; -async function retrieveWorkout(id) { - let workoutData = null; - let response = await sendRequest("GET", `${HOST}/api/workouts/${id}/`); - if (!response.ok) { - let data = await response.json(); - let alert = createAlert("Could not retrieve workout data!", data); - document.body.prepend(alert); - } else { - workoutData = await response.json(); - let form = document.querySelector("#form-workout"); - let formData = new FormData(form); - - for (let key of formData.keys()) { - let selector = `input[name="${key}"], textarea[name="${key}"]`; - let input = form.querySelector(selector); - let newVal = workoutData[key]; - if (key == "date") { - // Creating a valid datetime-local string with the correct local time - let date = new Date(newVal); - date = new Date(date.getTime() - (date.getTimezoneOffset() * 60 * 1000)).toISOString(); // get ISO format for local time - newVal = date.substring(0, newVal.length - 1); // remove Z (since this is a local time, not UTC) - } - if (key != "files") { - input.value = newVal; - } - } +async function retrieveWorkout(id) { + let workoutData = null; + let response = await sendRequest("GET", `${HOST}/api/workouts/${id}/`); + if (!response.ok) { + let data = await response.json(); + let alert = createAlert("Could not retrieve workout data!", data); + document.body.prepend(alert); + } else { + workoutData = await response.json(); + let form = document.querySelector("#form-workout"); + let formData = new FormData(form); - let input = form.querySelector("select:disabled"); - input.value = workoutData["visibility"]; - // files - let filesDiv = document.querySelector("#uploaded-files"); - for (let file of workoutData.files) { - let a = document.createElement("a"); - a.href = file.file; - let pathArray = file.file.split("/"); - a.text = pathArray[pathArray.length - 1]; - a.className = "me-2"; - filesDiv.appendChild(a); - } + for (let key of formData.keys()) { + let selector = `input[name="${key}"], textarea[name="${key}"]`; + let input = form.querySelector(selector); + let newVal = workoutData[key]; + if (key == "date") { + // Creating a valid datetime-local string with the correct local time + let date = new Date(newVal); + date = new Date( + date.getTime() - date.getTimezoneOffset() * 60 * 1000 + ).toISOString(); // get ISO format for local time + newVal = date.substring(0, newVal.length - 1); // remove Z (since this is a local time, not UTC) + } + if (key != "files") { + input.value = newVal; + } + } + + let input = form.querySelector("select:disabled"); + document.getElementById("divAthlete").style.display = "none"; + input.value = workoutData["visibility"]; + // files + let filesDiv = document.querySelector("#uploaded-files"); + for (let file of workoutData.files) { + let a = document.createElement("a"); + a.href = file.file; + let pathArray = file.file.split("/"); + a.text = pathArray[pathArray.length - 1]; + a.className = "me-2"; + filesDiv.appendChild(a); + } + + // create exercises - // create exercises - - // fetch exercise types - let exerciseTypeResponse = await sendRequest("GET", `${HOST}/api/exercises/`); - let exerciseTypes = await exerciseTypeResponse.json(); - - //TODO: This should be in its own method. - for (let i = 0; i < workoutData.exercise_instances.length; i++) { - let templateExercise = document.querySelector("#template-exercise"); - let divExerciseContainer = templateExercise.content.firstElementChild.cloneNode(true); - - let exerciseTypeLabel = divExerciseContainer.querySelector('.exercise-type'); - exerciseTypeLabel.for = `inputExerciseType${i}`; - - let exerciseTypeSelect = divExerciseContainer.querySelector("select"); - exerciseTypeSelect.id = `inputExerciseType${i}`; - exerciseTypeSelect.disabled = true; - - let splitUrl = workoutData.exercise_instances[i].exercise.split("/"); - let currentExerciseTypeId = splitUrl[splitUrl.length - 2]; - let currentExerciseType = ""; - - for (let j = 0; j < exerciseTypes.count; j++) { - let option = document.createElement("option"); - option.value = exerciseTypes.results[j].id; - if (currentExerciseTypeId == exerciseTypes.results[j].id) { - currentExerciseType = exerciseTypes.results[j]; - } - option.innerText = exerciseTypes.results[j].name; - exerciseTypeSelect.append(option); - } - - exerciseTypeSelect.value = currentExerciseType.id; - - let exerciseSetLabel = divExerciseContainer.querySelector('.exercise-sets'); - exerciseSetLabel.for = `inputSets${i}`; - - let exerciseSetInput = divExerciseContainer.querySelector("input[name='sets']"); - exerciseSetInput.id = `inputSets${i}`; - exerciseSetInput.value = workoutData.exercise_instances[i].sets; - exerciseSetInput.readOnly = true; - - let exerciseNumberLabel = divExerciseContainer.querySelector('.exercise-number'); - exerciseNumberLabel.for = "for", `inputNumber${i}`; - exerciseNumberLabel.innerText = currentExerciseType.unit; - - let exerciseNumberInput = divExerciseContainer.querySelector("input[name='number']"); - exerciseNumberInput.id = `inputNumber${i}`; - exerciseNumberInput.value = workoutData.exercise_instances[i].number; - exerciseNumberInput.readOnly = true; - - let exercisesDiv = document.querySelector("#div-exercises"); - exercisesDiv.appendChild(divExerciseContainer); + // fetch exercise types + let exerciseTypeResponse = await sendRequest( + "GET", + `${HOST}/api/exercises/` + ); + let exerciseTypes = await exerciseTypeResponse.json(); + + //TODO: This should be in its own method. + for (let i = 0; i < workoutData.exercise_instances.length; i++) { + let templateExercise = document.querySelector("#template-exercise"); + let divExerciseContainer = templateExercise.content.firstElementChild.cloneNode( + true + ); + + let exerciseTypeLabel = divExerciseContainer.querySelector( + ".exercise-type" + ); + exerciseTypeLabel.for = `inputExerciseType${i}`; + + let exerciseTypeSelect = divExerciseContainer.querySelector("select"); + exerciseTypeSelect.id = `inputExerciseType${i}`; + exerciseTypeSelect.disabled = true; + + let splitUrl = workoutData.exercise_instances[i].exercise.split("/"); + let currentExerciseTypeId = splitUrl[splitUrl.length - 2]; + let currentExerciseType = ""; + + for (let j = 0; j < exerciseTypes.count; j++) { + let option = document.createElement("option"); + option.value = exerciseTypes.results[j].id; + if (currentExerciseTypeId == exerciseTypes.results[j].id) { + currentExerciseType = exerciseTypes.results[j]; } + option.innerText = exerciseTypes.results[j].name; + exerciseTypeSelect.append(option); + } + + exerciseTypeSelect.value = currentExerciseType.id; + + let exerciseSetLabel = divExerciseContainer.querySelector( + ".exercise-sets" + ); + exerciseSetLabel.for = `inputSets${i}`; + + let exerciseSetInput = divExerciseContainer.querySelector( + "input[name='sets']" + ); + exerciseSetInput.id = `inputSets${i}`; + exerciseSetInput.value = workoutData.exercise_instances[i].sets; + exerciseSetInput.readOnly = true; + + let exerciseNumberLabel = divExerciseContainer.querySelector( + ".exercise-number" + ); + (exerciseNumberLabel.for = "for"), `inputNumber${i}`; + exerciseNumberLabel.innerText = currentExerciseType.unit; + + let exerciseNumberInput = divExerciseContainer.querySelector( + "input[name='number']" + ); + + exerciseNumberInput.id = `inputNumber${i}`; + exerciseNumberInput.value = workoutData.exercise_instances[i].number; + exerciseNumberInput.readOnly = true; + + let exercisesDiv = document.querySelector("#div-exercises"); + exercisesDiv.appendChild(divExerciseContainer); } - return workoutData; + } + return workoutData; } function handleCancelDuringWorkoutEdit() { - location.reload(); + location.reload(); } -function handleEditWorkoutButtonClick() { - let addExerciseButton = document.querySelector("#btn-add-exercise"); - let removeExerciseButton = document.querySelector("#btn-remove-exercise"); - - setReadOnly(false, "#form-workout"); - document.querySelector("#inputOwner").readOnly = true; // owner field should still be readonly - - editWorkoutButton.className += " hide"; - okWorkoutButton.className = okWorkoutButton.className.replace(" hide", ""); - cancelWorkoutButton.className = cancelWorkoutButton.className.replace(" hide", ""); - deleteWorkoutButton.className = deleteWorkoutButton.className.replace(" hide", ""); - addExerciseButton.className = addExerciseButton.className.replace(" hide", ""); - removeExerciseButton.className = removeExerciseButton.className.replace(" hide", ""); +function athleteChecked() { + let checkBox = document.getElementById("forAthlete"); + let athletes = document.getElementById("athletes"); + let myself = document.getElementById("inputOwner"); + if (checkBox.checked == true) { + athletes.style.display = "block"; + myself.style.display = "none"; + } else { + athletes.style.display = "none"; + myself.style.display = "block"; + } +} - cancelWorkoutButton.addEventListener("click", handleCancelDuringWorkoutEdit); +async function athletesInDropdown() { + let ath = document.getElementById("athletes"); + let currentUser = await getCurrentUser(); + for (let athleteUrl of currentUser.athletes) { + let newElement = document.createElement("option"); + let response = await sendRequest("GET", athleteUrl); + let athlete = await response.json(); + newElement.text = athlete.username; + ath.add(newElement); + } + click = true; +} +function handleEditWorkoutButtonClick() { + let addExerciseButton = document.querySelector("#btn-add-exercise"); + let removeExerciseButton = document.querySelector("#btn-remove-exercise"); + + setReadOnly(false, "#form-workout"); + + document.querySelector("#inputOwner").readOnly = true; // owner field should still be readonly + + editWorkoutButton.className += " hide"; + okWorkoutButton.className = okWorkoutButton.className.replace(" hide", ""); + cancelWorkoutButton.className = cancelWorkoutButton.className.replace( + " hide", + "" + ); + deleteWorkoutButton.className = deleteWorkoutButton.className.replace( + " hide", + "" + ); + addExerciseButton.className = addExerciseButton.className.replace( + " hide", + "" + ); + removeExerciseButton.className = removeExerciseButton.className.replace( + " hide", + "" + ); + + cancelWorkoutButton.addEventListener("click", handleCancelDuringWorkoutEdit); } async function deleteWorkout(id) { - let response = await sendRequest("DELETE", `${HOST}/api/workouts/${id}/`); - if (!response.ok) { - let data = await response.json(); - let alert = createAlert(`Could not delete workout ${id}!`, data); - document.body.prepend(alert); - } else { - window.location.replace("workouts.html"); - } + let response = await sendRequest("DELETE", `${HOST}/api/workouts/${id}/`); + if (!response.ok) { + let data = await response.json(); + let alert = createAlert(`Could not delete workout ${id}!`, data); + document.body.prepend(alert); + } else { + window.location.replace("workouts.html"); + } } async function updateWorkout(id) { - let submitForm = generateWorkoutForm(); - - let response = await sendRequest("PUT", `${HOST}/api/workouts/${id}/`, submitForm, ""); - if (!response.ok) { - let data = await response.json(); - let alert = createAlert("Could not update workout!", data); - document.body.prepend(alert); - } else { - location.reload(); - } + let submitForm = generateWorkoutForm(); + + let response = await sendRequest( + "PUT", + `${HOST}/api/workouts/${id}/`, + submitForm, + "" + ); + if (!response.ok) { + let data = await response.json(); + let alert = createAlert("Could not update workout!", data); + document.body.prepend(alert); + } else { + location.reload(); + } +} +function getOwnerID(username) { + return username.url; } function generateWorkoutForm() { - let form = document.querySelector("#form-workout"); - - let formData = new FormData(form); - let submitForm = new FormData(); - - submitForm.append("name", formData.get('name')); - let date = new Date(formData.get('date')).toISOString(); - submitForm.append("date", date); - submitForm.append("notes", formData.get("notes")); - submitForm.append("visibility", formData.get("visibility")); - - // adding exercise instances - let exerciseInstances = []; - let exerciseInstancesTypes = formData.getAll("type"); - let exerciseInstancesSets = formData.getAll("sets"); - let exerciseInstancesNumbers = formData.getAll("number"); - for (let i = 0; i < exerciseInstancesTypes.length; i++) { - exerciseInstances.push({ - exercise: `${HOST}/api/exercises/${exerciseInstancesTypes[i]}/`, - number: exerciseInstancesNumbers[i], - sets: exerciseInstancesSets[i] - }); - } - - submitForm.append("exercise_instances", JSON.stringify(exerciseInstances)); - // adding files - for (let file of formData.getAll("files")) { - submitForm.append("files", file); - } - return submitForm; + let form = document.querySelector("#form-workout"); + + let formData = new FormData(form); + let submitForm = new FormData(); + + submitForm.append("name", formData.get("name")); + let date = new Date(formData.get("date")).toISOString(); + submitForm.append("date", date); + submitForm.append("owner", formData.get("owner_username")); + submitForm.append("notes", formData.get("notes")); + submitForm.append("visibility", formData.get("visibility")); + + // adding exercise instances + let exerciseInstances = []; + let exerciseInstancesTypes = formData.getAll("type"); + let exerciseInstancesSets = formData.getAll("sets"); + let exerciseInstancesNumbers = formData.getAll("number"); + for (let i = 0; i < exerciseInstancesTypes.length; i++) { + exerciseInstances.push({ + exercise: `${HOST}/api/exercises/${exerciseInstancesTypes[i]}/`, + number: exerciseInstancesNumbers[i], + sets: exerciseInstancesSets[i] + }); + } + + submitForm.append("exercise_instances", JSON.stringify(exerciseInstances)); + // adding files + for (let file of formData.getAll("files")) { + submitForm.append("files", file); + } + return submitForm; } async function createWorkout() { - let submitForm = generateWorkoutForm(); + let submitForm = generateWorkoutForm(); + console.log(submitForm); - let response = await sendRequest("POST", `${HOST}/api/workouts/`, submitForm, ""); + let response = await sendRequest( + "POST", + `${HOST}/api/workouts/`, + submitForm, + "" + ); - if (response.ok) { - window.location.replace("workouts.html"); - } else { - let data = await response.json(); - let alert = createAlert("Could not create new workout!", data); - document.body.prepend(alert); - } + if (response.ok) { + window.location.replace("workouts.html"); + } else { + let data = await response.json(); + let alert = createAlert("Could not create new workout!", data); + document.body.prepend(alert); + } } function handleCancelDuringWorkoutCreate() { - window.location.replace("workouts.html"); + window.location.replace("workouts.html"); } async function createBlankExercise() { - let form = document.querySelector("#form-workout"); + let form = document.querySelector("#form-workout"); - let exerciseTypeResponse = await sendRequest("GET", `${HOST}/api/exercises/`); - let exerciseTypes = await exerciseTypeResponse.json(); + let exerciseTypeResponse = await sendRequest("GET", `${HOST}/api/exercises/`); + let exerciseTypes = await exerciseTypeResponse.json(); - let exerciseTemplate = document.querySelector("#template-exercise"); - let divExerciseContainer = exerciseTemplate.content.firstElementChild.cloneNode(true); - let exerciseTypeSelect = divExerciseContainer.querySelector("select"); - - for (let i = 0; i < exerciseTypes.count; i++) { - let option = document.createElement("option"); - option.value = exerciseTypes.results[i].id; - option.innerText = exerciseTypes.results[i].name; - exerciseTypeSelect.append(option); - } + let exerciseTemplate = document.querySelector("#template-exercise"); + let divExerciseContainer = exerciseTemplate.content.firstElementChild.cloneNode( + true + ); + let exerciseTypeSelect = divExerciseContainer.querySelector("select"); - let currentExerciseType = exerciseTypes.results[0]; - exerciseTypeSelect.value = currentExerciseType.name; - - let divExercises = document.querySelector("#div-exercises"); - divExercises.appendChild(divExerciseContainer); + for (let i = 0; i < exerciseTypes.count; i++) { + let option = document.createElement("option"); + option.value = exerciseTypes.results[i].id; + option.innerText = exerciseTypes.results[i].name; + exerciseTypeSelect.append(option); + } + + let currentExerciseType = exerciseTypes.results[0]; + exerciseTypeSelect.value = currentExerciseType.name; + + let divExercises = document.querySelector("#div-exercises"); + divExercises.appendChild(divExerciseContainer); } function removeExercise(event) { - let divExerciseContainers = document.querySelectorAll(".div-exercise-container"); - if (divExerciseContainers && divExerciseContainers.length > 0) { - divExerciseContainers[divExerciseContainers.length - 1].remove(); - } + let divExerciseContainers = document.querySelectorAll( + ".div-exercise-container" + ); + if (divExerciseContainers && divExerciseContainers.length > 0) { + divExerciseContainers[divExerciseContainers.length - 1].remove(); + } } function addComment(author, text, date, append) { - /* Taken from https://www.bootdey.com/snippets/view/Simple-Comment-panel#css*/ - let commentList = document.querySelector("#comment-list"); - let listElement = document.createElement("li"); - listElement.className = "media"; - let commentBody = document.createElement("div"); - commentBody.className = "media-body"; - let dateSpan = document.createElement("span"); - dateSpan.className = "text-muted pull-right me-1"; - let smallText = document.createElement("small"); - smallText.className = "text-muted"; - - if (date != "Now") { - let localDate = new Date(date); - smallText.innerText = localDate.toLocaleString(); - } else { - smallText.innerText = date; - } - - dateSpan.appendChild(smallText); - commentBody.appendChild(dateSpan); - - let strong = document.createElement("strong"); - strong.className = "text-success"; - strong.innerText = author; - commentBody.appendChild(strong); - let p = document.createElement("p"); - p.innerHTML = text; - - commentBody.appendChild(strong); - commentBody.appendChild(p); - listElement.appendChild(commentBody); - - if (append) { - commentList.append(listElement); - } else { - commentList.prepend(listElement); - } - + /* Taken from https://www.bootdey.com/snippets/view/Simple-Comment-panel#css*/ + let commentList = document.querySelector("#comment-list"); + let listElement = document.createElement("li"); + listElement.className = "media"; + let commentBody = document.createElement("div"); + commentBody.className = "media-body"; + let dateSpan = document.createElement("span"); + dateSpan.className = "text-muted pull-right me-1"; + let smallText = document.createElement("small"); + smallText.className = "text-muted"; + + if (date != "Now") { + let localDate = new Date(date); + smallText.innerText = localDate.toLocaleString(); + } else { + smallText.innerText = date; + } + + dateSpan.appendChild(smallText); + commentBody.appendChild(dateSpan); + + let strong = document.createElement("strong"); + strong.className = "text-success"; + strong.innerText = author; + commentBody.appendChild(strong); + let p = document.createElement("p"); + p.innerHTML = text; + + commentBody.appendChild(strong); + commentBody.appendChild(p); + listElement.appendChild(commentBody); + + if (append) { + commentList.append(listElement); + } else { + commentList.prepend(listElement); + } } async function createComment(workoutid) { - let commentArea = document.querySelector("#comment-area"); - let content = commentArea.value; - let body = {workout: `${HOST}/api/workouts/${workoutid}/`, content: content}; - - let response = await sendRequest("POST", `${HOST}/api/comments/`, body); - if (response.ok) { - addComment(sessionStorage.getItem("username"), content, "Now", false); - } else { - let data = await response.json(); - let alert = createAlert("Failed to create comment!", data); - document.body.prepend(alert); - } + let commentArea = document.querySelector("#comment-area"); + let content = commentArea.value; + let body = { + workout: `${HOST}/api/workouts/${workoutid}/`, + content: content + }; + + let response = await sendRequest("POST", `${HOST}/api/comments/`, body); + if (response.ok) { + addComment(sessionStorage.getItem("username"), content, "Now", false); + } else { + let data = await response.json(); + let alert = createAlert("Failed to create comment!", data); + document.body.prepend(alert); + } } async function retrieveComments(workoutid) { - let response = await sendRequest("GET", `${HOST}/api/comments/`); - if (!response.ok) { - let data = await response.json(); - let alert = createAlert("Could not retrieve comments!", data); - document.body.prepend(alert); - } else { - let data = await response.json(); - let comments = data.results; - for (let comment of comments) { - let splitArray = comment.workout.split("/"); - if (splitArray[splitArray.length - 2] == workoutid) { - addComment(comment.owner, comment.content, comment.timestamp, true); - } - } + let response = await sendRequest("GET", `${HOST}/api/comments/`); + if (!response.ok) { + let data = await response.json(); + let alert = createAlert("Could not retrieve comments!", data); + document.body.prepend(alert); + } else { + let data = await response.json(); + let comments = data.results; + for (let comment of comments) { + let splitArray = comment.workout.split("/"); + if (splitArray[splitArray.length - 2] == workoutid) { + addComment(comment.owner, comment.content, comment.timestamp, true); + } } + } } window.addEventListener("DOMContentLoaded", async () => { - cancelWorkoutButton = document.querySelector("#btn-cancel-workout"); - okWorkoutButton = document.querySelector("#btn-ok-workout"); - deleteWorkoutButton = document.querySelector("#btn-delete-workout"); - editWorkoutButton = document.querySelector("#btn-edit-workout"); - let postCommentButton = document.querySelector("#post-comment"); - let divCommentRow = document.querySelector("#div-comment-row"); - let buttonAddExercise = document.querySelector("#btn-add-exercise"); - let buttonRemoveExercise = document.querySelector("#btn-remove-exercise"); - - buttonAddExercise.addEventListener("click", createBlankExercise); - buttonRemoveExercise.addEventListener("click", removeExercise); - - const urlParams = new URLSearchParams(window.location.search); - let currentUser = await getCurrentUser(); - - if (urlParams.has('id')) { - const id = urlParams.get('id'); - let workoutData = await retrieveWorkout(id); - await retrieveComments(id); - - if (workoutData["owner"] == currentUser.url) { - editWorkoutButton.classList.remove("hide"); - editWorkoutButton.addEventListener("click", handleEditWorkoutButtonClick); - deleteWorkoutButton.addEventListener("click", (async (id) => await deleteWorkout(id)).bind(undefined, id)); - okWorkoutButton.addEventListener("click", (async (id) => await updateWorkout(id)).bind(undefined, id)); - postCommentButton.addEventListener("click", (async (id) => await createComment(id)).bind(undefined, id)); - divCommentRow.className = divCommentRow.className.replace(" hide", ""); - } - } else { - await createBlankExercise(); - let ownerInput = document.querySelector("#inputOwner"); - ownerInput.value = currentUser.username; - setReadOnly(false, "#form-workout"); - ownerInput.readOnly = !ownerInput.readOnly; - - okWorkoutButton.className = okWorkoutButton.className.replace(" hide", ""); - cancelWorkoutButton.className = cancelWorkoutButton.className.replace(" hide", ""); - buttonAddExercise.className = buttonAddExercise.className.replace(" hide", ""); - buttonRemoveExercise.className = buttonRemoveExercise.className.replace(" hide", ""); - - okWorkoutButton.addEventListener("click", async () => await createWorkout()); - cancelWorkoutButton.addEventListener("click", handleCancelDuringWorkoutCreate); - divCommentRow.className += " hide"; + cancelWorkoutButton = document.querySelector("#btn-cancel-workout"); + okWorkoutButton = document.querySelector("#btn-ok-workout"); + deleteWorkoutButton = document.querySelector("#btn-delete-workout"); + editWorkoutButton = document.querySelector("#btn-edit-workout"); + let postCommentButton = document.querySelector("#post-comment"); + let divCommentRow = document.querySelector("#div-comment-row"); + let buttonAddExercise = document.querySelector("#btn-add-exercise"); + let buttonRemoveExercise = document.querySelector("#btn-remove-exercise"); + + buttonAddExercise.addEventListener("click", createBlankExercise); + buttonRemoveExercise.addEventListener("click", removeExercise); + + const urlParams = new URLSearchParams(window.location.search); + let currentUser = await getCurrentUser(); + + if (urlParams.has("id")) { + const id = urlParams.get("id"); + let workoutData = await retrieveWorkout(id); + await retrieveComments(id); + console.log(currentUser.url); + + if (workoutData["owner"] == currentUser.url) { + editWorkoutButton.classList.remove("hide"); + editWorkoutButton.addEventListener("click", handleEditWorkoutButtonClick); + deleteWorkoutButton.addEventListener( + "click", + (async id => await deleteWorkout(id)).bind(undefined, id) + ); + okWorkoutButton.addEventListener( + "click", + (async id => await updateWorkout(id)).bind(undefined, id) + ); + postCommentButton.addEventListener( + "click", + (async id => await createComment(id)).bind(undefined, id) + ); + divCommentRow.className = divCommentRow.className.replace(" hide", ""); } + } else { + await createBlankExercise(); + + let query = "#inputOwner"; + let ownerInput = document.querySelector(query); + let check = document.querySelector("#forAthlete"); + console.log(check); + ownerInput.value = currentUser.username; -}); \ No newline at end of file + console.log(ownerInput.value); + setReadOnly(false, "#form-workout"); + ownerInput.readOnly = !ownerInput.readOnly; + + okWorkoutButton.className = okWorkoutButton.className.replace(" hide", ""); + cancelWorkoutButton.className = cancelWorkoutButton.className.replace( + " hide", + "" + ); + buttonAddExercise.className = buttonAddExercise.className.replace( + " hide", + "" + ); + buttonRemoveExercise.className = buttonRemoveExercise.className.replace( + " hide", + "" + ); + + okWorkoutButton.addEventListener( + "click", + async () => await createWorkout() + ); + cancelWorkoutButton.addEventListener( + "click", + handleCancelDuringWorkoutCreate + ); + divCommentRow.className += " hide"; + } +}); diff --git a/frontend/www/statistics.html b/frontend/www/statistics.html index c44d81ffc96960ff065882f4f057794ca0ac46f2..f00349f925e80cd3635fe62f1526e08d2571171b 100644 --- a/frontend/www/statistics.html +++ b/frontend/www/statistics.html @@ -33,15 +33,15 @@ <div class="centering"> <div class="list-group list-group-horizontal d-inline-flex mt-2"> <div class="number"> - <h1 id="week">Last seven days</h1> + <h1 id="week">0</h1> <p>Last seven days</p> </div> <div class="number"> - <h1 id="month">Last thirty days</h1> + <h1 id="month">0</h1> <p>Last 30 days</p> </div> <div class="number"> - <h1 id="year">Last 365 days</h1> + <h1 id="year">0</h1> <p>Last 365 days</p> </div> </div> diff --git a/frontend/www/workout.html b/frontend/www/workout.html index b3f6bbc7a1bb957d7b3cba58a683b9e4d4033345..25af4423a4d864af19ba2aae179fab3af8a088fb 100644 --- a/frontend/www/workout.html +++ b/frontend/www/workout.html @@ -11,6 +11,14 @@ integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous" /> + <script src="scripts/defaults.js"></script> + <script src="scripts/scripts.js"></script> + <script type="text/javascript" src="scripts/workout.js"></script> + <script + src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" + integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" + crossorigin="anonymous" + ></script> <script src="https://kit.fontawesome.com/0ce6c392ca.js" @@ -52,15 +60,34 @@ </div> <div class="col-lg-6"></div> <div class="col-lg-6"> - <label for="inputOwner" class="form-label">Owner</label> - <input - type="text" - class="form-control" - id="inputOwner" - name="owner_username" - readonly - /> + <div id="divAthlete"> + <label for="forAthlete">Create workout for athlete</label> + <input id="forAthlete" type="checkbox" onclick="athleteChecked()" /> + </div> + <div class="col-lg-6"></div> + <p>Owner</p> + + <div> + <select + id="athletes" + class="form-select" + name="owner_username" + style="display:none" + onclick="athletesInDropdown(); this.onclick=null;" + > + </select> + + <input + type="text" + class="form-control" + id="inputOwner" + name="owner_username" + style="display:block" + readonly + /> + </div> </div> + <div class="col-lg-6"></div> <div class="col-lg-6"> <label for="inputVisibility" class="form-label">Visibility</label> <select @@ -74,6 +101,7 @@ <option value="PR">Private</option> </select> </div> + <div class="col-lg-6"></div> <div class="col-lg-6"> <label for="inputNotes" class="form-label">Notes</label> <textarea @@ -197,14 +225,5 @@ <div class="col-lg-6"></div> </div> </template> - - <script src="scripts/defaults.js"></script> - <script src="scripts/scripts.js"></script> - <script src="scripts/workout.js"></script> - <script - src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" - integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" - crossorigin="anonymous" - ></script> </body> </html>