Add student and parent management for trip admins
This commit is contained in:
204
main.go
204
main.go
@@ -65,6 +65,14 @@ func main() {
|
||||
http.HandleFunc("DELETE /api/trips/{tripID}", handleDeleteTrip(db))
|
||||
http.HandleFunc("POST /api/trips/{tripID}/admins", handleAddTripAdmin(db))
|
||||
http.HandleFunc("DELETE /api/trips/{tripID}/admins/{adminID}", handleRemoveTripAdmin(db))
|
||||
http.HandleFunc("GET /trip/{tripID}", serveHTML("trip.html"))
|
||||
http.HandleFunc("GET /trip.js", serveJS("trip.js"))
|
||||
http.HandleFunc("GET /api/trips/{tripID}", handleGetTrip(db))
|
||||
http.HandleFunc("GET /api/trips/{tripID}/students", handleListStudents(db))
|
||||
http.HandleFunc("POST /api/trips/{tripID}/students", handleCreateStudent(db))
|
||||
http.HandleFunc("DELETE /api/trips/{tripID}/students/{studentID}", handleDeleteStudent(db))
|
||||
http.HandleFunc("POST /api/trips/{tripID}/students/{studentID}/parents", handleAddParent(db))
|
||||
http.HandleFunc("DELETE /api/trips/{tripID}/students/{studentID}/parents/{parentID}", handleRemoveParent(db))
|
||||
http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := db.Ping(); err != nil {
|
||||
http.Error(w, "db unhealthy", http.StatusServiceUnavailable)
|
||||
@@ -184,6 +192,30 @@ func requireAdmin(w http.ResponseWriter, r *http.Request) (string, bool) {
|
||||
return email, true
|
||||
}
|
||||
|
||||
func isTripAdmin(db *sql.DB, email string, tripID int64) bool {
|
||||
var exists bool
|
||||
db.QueryRow("SELECT EXISTS(SELECT 1 FROM trip_admins WHERE trip_id = $1 AND email = $2)", tripID, email).Scan(&exists)
|
||||
return exists
|
||||
}
|
||||
|
||||
func requireTripAdmin(db *sql.DB, w http.ResponseWriter, r *http.Request) (string, int64, bool) {
|
||||
email, ok := authorize(r)
|
||||
if !ok {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return "", 0, false
|
||||
}
|
||||
tripID, err := strconv.ParseInt(r.PathValue("tripID"), 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid trip ID", http.StatusBadRequest)
|
||||
return "", 0, false
|
||||
}
|
||||
if !isAdmin(email) && !isTripAdmin(db, email, tripID) {
|
||||
http.Error(w, "forbidden", http.StatusForbidden)
|
||||
return "", 0, false
|
||||
}
|
||||
return email, tripID, true
|
||||
}
|
||||
|
||||
func handleAdminCheck(w http.ResponseWriter, r *http.Request) {
|
||||
email, ok := authorize(r)
|
||||
if !ok {
|
||||
@@ -339,3 +371,175 @@ func handleRemoveTripAdmin(db *sql.DB) http.HandlerFunc {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func handleGetTrip(db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
_, tripID, ok := requireTripAdmin(db, w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var name string
|
||||
err := db.QueryRow("SELECT name FROM trips WHERE id = $1", tripID).Scan(&name)
|
||||
if err != nil {
|
||||
http.Error(w, "trip not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]any{"id": tripID, "name": name})
|
||||
}
|
||||
}
|
||||
|
||||
func handleListStudents(db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
_, tripID, ok := requireTripAdmin(db, w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
rows, err := db.Query(`
|
||||
SELECT s.id, s.name, s.email, COALESCE(
|
||||
json_agg(json_build_object('id', p.id, 'email', p.email)) FILTER (WHERE p.id IS NOT NULL),
|
||||
'[]'
|
||||
)
|
||||
FROM students s
|
||||
LEFT JOIN parents p ON p.student_id = s.id
|
||||
WHERE s.trip_id = $1
|
||||
GROUP BY s.id, s.name, s.email
|
||||
ORDER BY s.name`, tripID)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
type parent struct {
|
||||
ID int64 `json:"id"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
type student struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Parents []parent `json:"parents"`
|
||||
}
|
||||
|
||||
var students []student
|
||||
for rows.Next() {
|
||||
var s student
|
||||
var parentsJSON string
|
||||
if err := rows.Scan(&s.ID, &s.Name, &s.Email, &parentsJSON); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
json.Unmarshal([]byte(parentsJSON), &s.Parents)
|
||||
students = append(students, s)
|
||||
}
|
||||
if students == nil {
|
||||
students = []student{}
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(students)
|
||||
}
|
||||
}
|
||||
|
||||
func handleCreateStudent(db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
_, tripID, ok := requireTripAdmin(db, w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.Name == "" || body.Email == "" {
|
||||
http.Error(w, "name and email are required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var id int64
|
||||
err := db.QueryRow("INSERT INTO students (trip_id, name, email) VALUES ($1, $2, $3) RETURNING id", tripID, body.Name, body.Email).Scan(&id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]any{"id": id, "name": body.Name, "email": body.Email})
|
||||
}
|
||||
}
|
||||
|
||||
func handleDeleteStudent(db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
_, tripID, ok := requireTripAdmin(db, w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
studentID, err := strconv.ParseInt(r.PathValue("studentID"), 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid student ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
result, err := db.Exec("DELETE FROM students WHERE id = $1 AND trip_id = $2", studentID, tripID)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if n, _ := result.RowsAffected(); n == 0 {
|
||||
http.Error(w, "student not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func handleAddParent(db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
_, tripID, ok := requireTripAdmin(db, w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
studentID, err := strconv.ParseInt(r.PathValue("studentID"), 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid student ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Email string `json:"email"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.Email == "" {
|
||||
http.Error(w, "email is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var id int64
|
||||
err = db.QueryRow("INSERT INTO parents (student_id, email) VALUES ((SELECT id FROM students WHERE id = $1 AND trip_id = $2), $3) RETURNING id",
|
||||
studentID, tripID, body.Email).Scan(&id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]any{"id": id, "email": body.Email})
|
||||
}
|
||||
}
|
||||
|
||||
func handleRemoveParent(db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
_, tripID, ok := requireTripAdmin(db, w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
parentID, err := strconv.ParseInt(r.PathValue("parentID"), 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid parent ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
result, err := db.Exec(`DELETE FROM parents WHERE id = $1 AND student_id IN (SELECT id FROM students WHERE trip_id = $2)`, parentID, tripID)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if n, _ := result.RowsAffected(); n == 0 {
|
||||
http.Error(w, "parent not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,10 @@ async function loadTrips() {
|
||||
const header = document.createElement('div');
|
||||
header.className = 'trip-header';
|
||||
const h3 = document.createElement('h3');
|
||||
h3.textContent = trip.name;
|
||||
const tripLink = document.createElement('a');
|
||||
tripLink.href = '/trip/' + trip.id;
|
||||
tripLink.textContent = trip.name;
|
||||
h3.appendChild(tripLink);
|
||||
const deleteBtn = document.createElement('wa-button');
|
||||
deleteBtn.variant = 'danger';
|
||||
deleteBtn.size = 'small';
|
||||
|
||||
81
static/trip.html
Normal file
81
static/trip.html
Normal file
@@ -0,0 +1,81 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Trip - Rooms</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: var(--wa-font-sans);
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
padding: 1rem;
|
||||
opacity: 0;
|
||||
}
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
.header img {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
}
|
||||
.header .spacer { flex: 1; }
|
||||
wa-card {
|
||||
margin-bottom: 1rem;
|
||||
display: block;
|
||||
}
|
||||
wa-card h3 { margin: 0 0 0.5rem 0; }
|
||||
.parent-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.25rem;
|
||||
margin-left: 1rem;
|
||||
}
|
||||
.add-parent-row {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
margin-top: 0.5rem;
|
||||
margin-left: 1rem;
|
||||
}
|
||||
.add-parent-row wa-input { flex: 1; }
|
||||
.add-student {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
.add-student wa-input { flex: 1; }
|
||||
.student-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.student-header h3 { flex: 1; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="signin" style="display: none; align-items: center; justify-content: center; height: 100vh;"></div>
|
||||
<div id="main" style="display: none;">
|
||||
<div class="header">
|
||||
<img data-bind="picture" alt="Profile">
|
||||
<span data-bind="name"></span>
|
||||
<span class="spacer"></span>
|
||||
<wa-button variant="neutral" size="small" id="logout-btn">Switch User</wa-button>
|
||||
</div>
|
||||
<h2 id="trip-name"></h2>
|
||||
<h3>Add Student</h3>
|
||||
<div class="add-student">
|
||||
<wa-input id="new-student-name" placeholder="Student name"></wa-input>
|
||||
<wa-input id="new-student-email" placeholder="Student email"></wa-input>
|
||||
<wa-button variant="brand" id="add-student-btn">Add</wa-button>
|
||||
</div>
|
||||
<h3>Students</h3>
|
||||
<div id="students"></div>
|
||||
</div>
|
||||
<script type="module" src="/trip.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
101
static/trip.js
Normal file
101
static/trip.js
Normal file
@@ -0,0 +1,101 @@
|
||||
import { init, logout, api } from '/app.js';
|
||||
|
||||
const tripID = location.pathname.split('/').pop();
|
||||
|
||||
const profile = await init();
|
||||
|
||||
let trip;
|
||||
try {
|
||||
trip = await api('GET', '/api/trips/' + tripID);
|
||||
} catch (e) {
|
||||
document.body.style.opacity = 1;
|
||||
document.body.textContent = 'Access denied.';
|
||||
throw e;
|
||||
}
|
||||
|
||||
document.getElementById('trip-name').textContent = trip.name;
|
||||
document.getElementById('main').style.display = 'block';
|
||||
document.getElementById('logout-btn').addEventListener('click', logout);
|
||||
|
||||
async function loadStudents() {
|
||||
const students = await api('GET', '/api/trips/' + tripID + '/students');
|
||||
const container = document.getElementById('students');
|
||||
container.innerHTML = '';
|
||||
for (const student of students) {
|
||||
const card = document.createElement('wa-card');
|
||||
const header = document.createElement('div');
|
||||
header.className = 'student-header';
|
||||
const h3 = document.createElement('h3');
|
||||
h3.textContent = student.name + ' (' + student.email + ')';
|
||||
const deleteBtn = document.createElement('wa-button');
|
||||
deleteBtn.variant = 'danger';
|
||||
deleteBtn.size = 'small';
|
||||
deleteBtn.textContent = 'Remove';
|
||||
deleteBtn.addEventListener('click', async () => {
|
||||
if (!confirm('Remove student "' + student.name + '"?')) return;
|
||||
await api('DELETE', '/api/trips/' + tripID + '/students/' + student.id);
|
||||
loadStudents();
|
||||
});
|
||||
header.appendChild(h3);
|
||||
header.appendChild(deleteBtn);
|
||||
card.appendChild(header);
|
||||
|
||||
const parentLabel = document.createElement('strong');
|
||||
parentLabel.textContent = 'Parents:';
|
||||
card.appendChild(parentLabel);
|
||||
|
||||
for (const parent of student.parents) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'parent-row';
|
||||
const span = document.createElement('span');
|
||||
span.textContent = parent.email;
|
||||
const removeBtn = document.createElement('wa-button');
|
||||
removeBtn.variant = 'danger';
|
||||
removeBtn.size = 'small';
|
||||
removeBtn.textContent = 'Remove';
|
||||
removeBtn.addEventListener('click', async () => {
|
||||
await api('DELETE', '/api/trips/' + tripID + '/students/' + student.id + '/parents/' + parent.id);
|
||||
loadStudents();
|
||||
});
|
||||
row.appendChild(span);
|
||||
row.appendChild(removeBtn);
|
||||
card.appendChild(row);
|
||||
}
|
||||
|
||||
const addRow = document.createElement('div');
|
||||
addRow.className = 'add-parent-row';
|
||||
const input = document.createElement('wa-input');
|
||||
input.placeholder = 'Parent email';
|
||||
const addBtn = document.createElement('wa-button');
|
||||
addBtn.variant = 'neutral';
|
||||
addBtn.size = 'small';
|
||||
addBtn.textContent = 'Add Parent';
|
||||
addBtn.addEventListener('click', async () => {
|
||||
const email = input.value.trim();
|
||||
if (!email) return;
|
||||
await api('POST', '/api/trips/' + tripID + '/students/' + student.id + '/parents', { email });
|
||||
loadStudents();
|
||||
});
|
||||
addRow.appendChild(input);
|
||||
addRow.appendChild(addBtn);
|
||||
card.appendChild(addRow);
|
||||
|
||||
container.appendChild(card);
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('add-student-btn').addEventListener('click', async () => {
|
||||
const nameInput = document.getElementById('new-student-name');
|
||||
const emailInput = document.getElementById('new-student-email');
|
||||
const name = nameInput.value.trim();
|
||||
const email = emailInput.value.trim();
|
||||
if (!name || !email) return;
|
||||
await api('POST', '/api/trips/' + tripID + '/students', { name, email });
|
||||
nameInput.value = '';
|
||||
emailInput.value = '';
|
||||
loadStudents();
|
||||
});
|
||||
|
||||
await loadStudents();
|
||||
await customElements.whenDefined('wa-button');
|
||||
document.body.style.opacity = 1;
|
||||
Reference in New Issue
Block a user