diff --git a/public/api/contributions.php b/public/api/contributions.php index 7e23ebb..076bac2 100644 --- a/public/api/contributions.php +++ b/public/api/contributions.php @@ -303,24 +303,51 @@ function handle_vote($input) { // Prepared SQL Statement try { + // Checks if Voter already voted on this Contribution $stmt = $pdo->prepare(" - INSERT INTO votes (contribution_id, voter_name, vote_type) - VALUES (:cid, :voter, :vtype) + SELECT vote_id, vote_type FROM votes + WHERE contribution_id = :cid AND voter_name = :voter "); + $stmt->execute([':cid' => $input['contribution_id'], ':voter' => $input['voter_name']]); + $existing = $stmt->fetch(); - $stmt->execute([ - ':cid' => $input['contribution_id'], - ':voter' => $input['voter_name'], - ':vtype' => $input['vote_type'] - ]); + if ($existing) { + if ($existing['vote_type'] === $input['vote_type']) { + // Same Vote Type — Removes Vote + $stmt = $pdo->prepare("DELETE FROM votes WHERE vote_id = :vid"); + $stmt->execute([':vid' => $existing['vote_id']]); + json_response(['message' => 'Vote removed.', 'action' => 'removed']); + } else { + // Different Vote Type — Switches Vote + $stmt = $pdo->prepare("DELETE FROM votes WHERE vote_id = :vid"); + $stmt->execute([':vid' => $existing['vote_id']]); - json_response(['message' => 'Vote recorded successfully.'], 201); + $stmt = $pdo->prepare(" + INSERT INTO votes (contribution_id, voter_name, vote_type) + VALUES (:cid, :voter, :vtype) + "); + $stmt->execute([ + ':cid' => $input['contribution_id'], + ':voter' => $input['voter_name'], + ':vtype' => $input['vote_type'] + ]); + json_response(['message' => 'Vote changed.', 'action' => 'changed'], 200); + } + } else { + // No existing Vote — Inserts Vote + $stmt = $pdo->prepare(" + INSERT INTO votes (contribution_id, voter_name, vote_type) + VALUES (:cid, :voter, :vtype) + "); + $stmt->execute([ + ':cid' => $input['contribution_id'], + ':voter' => $input['voter_name'], + ':vtype' => $input['vote_type'] + ]); + json_response(['message' => 'Vote recorded.', 'action' => 'created'], 201); + } } catch (PDOException $e) { - // UNIQUE Constraint Violation - Voter already voted on this Contribution - if ($e->getCode() == '23505') { - error_response('You have already voted on this Contribution.', 409); - } error_response('Database Error: ' . $e->getMessage(), 500); } } \ No newline at end of file diff --git a/public/js/app.js b/public/js/app.js index 14a30bc..4b26310 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -572,6 +572,13 @@ function voteContribution(contributionId, voteType) { return; } + // Show Feedback based on Vote Action + if (response.action === 'removed') { + Swal.fire({ title: 'Bewertung zurückgenommen', icon: 'info', timer: 1500, showConfirmButton: false }); + } else if (response.action === 'changed') { + Swal.fire({ title: 'Bewertung verändert', icon: 'success', timer: 1500, showConfirmButton: false }); + } + // Updates Vote Counts in the Popup without reloading everything loadContributions(); });