From 8ec03f1d96c699035a8f81624e80ac33efc53eac Mon Sep 17 00:00:00 2001 From: Ian Gulliver Date: Mon, 16 Feb 2026 09:50:19 -0800 Subject: [PATCH] Add role-based trip views and keep expandos open after adding items --- main.go | 185 +++++++++++++++++++++++++++++++++++++++++++---- static/admin.js | 10 ++- static/trip.html | 50 +++++++------ static/trip.js | 112 ++++++++++++++++++++++++++-- 4 files changed, 314 insertions(+), 43 deletions(-) diff --git a/main.go b/main.go index c38b5e2..5f58ac6 100644 --- a/main.go +++ b/main.go @@ -19,7 +19,7 @@ import ( "strings" texttemplate "text/template" - _ "github.com/lib/pq" + "github.com/lib/pq" "google.golang.org/api/idtoken" ) @@ -69,6 +69,7 @@ func main() { 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}/me", handleTripMe(db)) http.HandleFunc("GET /api/trips/{tripID}", handleGetTrip(db)) http.HandleFunc("PATCH /api/trips/{tripID}", handleUpdateTrip(db)) http.HandleFunc("GET /api/trips/{tripID}/students", handleListStudents(db)) @@ -223,6 +224,57 @@ func requireTripAdmin(db *sql.DB, w http.ResponseWriter, r *http.Request) (strin return email, tripID, true } +func tripRole(db *sql.DB, email string, tripID int64) (string, []int64) { + if isAdmin(email) || isTripAdmin(db, email, tripID) { + return "admin", nil + } + var studentIDs []int64 + rows, _ := db.Query("SELECT id FROM students WHERE trip_id = $1 AND email = $2", tripID, email) + if rows != nil { + defer rows.Close() + for rows.Next() { + var id int64 + rows.Scan(&id) + studentIDs = append(studentIDs, id) + } + } + if len(studentIDs) > 0 { + return "student", studentIDs + } + rows2, _ := db.Query("SELECT s.id FROM parents p JOIN students s ON s.id = p.student_id WHERE s.trip_id = $1 AND p.email = $2", tripID, email) + if rows2 != nil { + defer rows2.Close() + for rows2.Next() { + var id int64 + rows2.Scan(&id) + studentIDs = append(studentIDs, id) + } + } + if len(studentIDs) > 0 { + return "parent", studentIDs + } + return "", nil +} + +func requireTripMember(db *sql.DB, w http.ResponseWriter, r *http.Request) (string, int64, string, []int64, bool) { + email, ok := authorize(r) + if !ok { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return "", 0, "", nil, false + } + tripID, err := strconv.ParseInt(r.PathValue("tripID"), 10, 64) + if err != nil { + http.Error(w, "invalid trip ID", http.StatusBadRequest) + return "", 0, "", nil, false + } + role, studentIDs := tripRole(db, email, tripID) + if role == "" { + http.Error(w, "forbidden", http.StatusForbidden) + return "", 0, "", nil, false + } + return email, tripID, role, studentIDs, true +} + func handleAdminCheck(w http.ResponseWriter, r *http.Request) { email, ok := authorize(r) if !ok { @@ -382,9 +434,34 @@ func handleRemoveTripAdmin(db *sql.DB) http.HandlerFunc { } } +func handleTripMe(db *sql.DB) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + _, tripID, role, studentIDs, ok := requireTripMember(db, w, r) + if !ok { + return + } + type studentInfo struct { + ID int64 `json:"id"` + Name string `json:"name"` + } + var students []studentInfo + for _, sid := range studentIDs { + var name string + if err := db.QueryRow("SELECT name FROM students WHERE id = $1 AND trip_id = $2", sid, tripID).Scan(&name); err == nil { + students = append(students, studentInfo{ID: sid, Name: name}) + } + } + if students == nil { + students = []studentInfo{} + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]any{"role": role, "students": students}) + } +} + func handleGetTrip(db *sql.DB) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - _, tripID, ok := requireTripAdmin(db, w, r) + _, tripID, _, _, ok := requireTripMember(db, w, r) if !ok { return } @@ -402,10 +479,39 @@ func handleGetTrip(db *sql.DB) http.HandlerFunc { func handleListStudents(db *sql.DB) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - _, tripID, ok := requireTripAdmin(db, w, r) + _, tripID, role, _, ok := requireTripMember(db, w, r) if !ok { return } + + if role != "admin" { + rows, err := db.Query("SELECT id, name FROM students WHERE trip_id = $1 ORDER BY name", tripID) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + defer rows.Close() + type studentBasic struct { + ID int64 `json:"id"` + Name string `json:"name"` + } + var students []studentBasic + for rows.Next() { + var s studentBasic + if err := rows.Scan(&s.ID, &s.Name); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + students = append(students, s) + } + if students == nil { + students = []studentBasic{} + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(students) + 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), @@ -612,17 +718,39 @@ func handleUpdateTrip(db *sql.DB) http.HandlerFunc { func handleListConstraints(db *sql.DB) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - _, tripID, ok := requireTripAdmin(db, w, r) + _, tripID, role, myStudentIDs, ok := requireTripMember(db, w, r) if !ok { return } - rows, err := db.Query(` - SELECT rc.id, rc.student_a_id, sa.name, rc.student_b_id, sb.name, rc.kind::text, rc.level::text - FROM roommate_constraints rc - JOIN students sa ON sa.id = rc.student_a_id - JOIN students sb ON sb.id = rc.student_b_id - WHERE sa.trip_id = $1 - ORDER BY rc.id`, tripID) + var query string + var args []any + switch role { + case "admin": + query = `SELECT rc.id, rc.student_a_id, sa.name, rc.student_b_id, sb.name, rc.kind::text, rc.level::text + FROM roommate_constraints rc + JOIN students sa ON sa.id = rc.student_a_id + JOIN students sb ON sb.id = rc.student_b_id + WHERE sa.trip_id = $1 + ORDER BY rc.id` + args = []any{tripID} + case "student": + query = `SELECT rc.id, rc.student_a_id, sa.name, rc.student_b_id, sb.name, rc.kind::text, rc.level::text + FROM roommate_constraints rc + JOIN students sa ON sa.id = rc.student_a_id + JOIN students sb ON sb.id = rc.student_b_id + WHERE sa.trip_id = $1 AND rc.level = 'student' AND rc.student_a_id = ANY($2) + ORDER BY rc.id` + args = []any{tripID, pq.Array(myStudentIDs)} + case "parent": + query = `SELECT rc.id, rc.student_a_id, sa.name, rc.student_b_id, sb.name, rc.kind::text, rc.level::text + FROM roommate_constraints rc + JOIN students sa ON sa.id = rc.student_a_id + JOIN students sb ON sb.id = rc.student_b_id + WHERE sa.trip_id = $1 AND rc.level = 'parent' AND rc.student_a_id = ANY($2) + ORDER BY rc.id` + args = []any{tripID, pq.Array(myStudentIDs)} + } + rows, err := db.Query(query, args...) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return @@ -658,7 +786,7 @@ func handleListConstraints(db *sql.DB) http.HandlerFunc { func handleCreateConstraint(db *sql.DB) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - _, tripID, ok := requireTripAdmin(db, w, r) + _, tripID, role, myStudentIDs, ok := requireTripMember(db, w, r) if !ok { return } @@ -692,6 +820,23 @@ func handleCreateConstraint(db *sql.DB) http.HandlerFunc { http.Error(w, "invalid level", http.StatusBadRequest) return } + if role != "admin" { + if body.Level != role { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + owns := false + for _, sid := range myStudentIDs { + if sid == body.StudentAID { + owns = true + break + } + } + if !owns { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + } var id int64 err := db.QueryRow(` INSERT INTO roommate_constraints (student_a_id, student_b_id, kind, level) @@ -712,7 +857,7 @@ func handleCreateConstraint(db *sql.DB) http.HandlerFunc { func handleDeleteConstraint(db *sql.DB) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - _, tripID, ok := requireTripAdmin(db, w, r) + _, tripID, role, myStudentIDs, ok := requireTripMember(db, w, r) if !ok { return } @@ -721,8 +866,18 @@ func handleDeleteConstraint(db *sql.DB) http.HandlerFunc { http.Error(w, "invalid constraint ID", http.StatusBadRequest) return } - result, err := db.Exec(`DELETE FROM roommate_constraints WHERE id = $1 - AND student_a_id IN (SELECT id FROM students WHERE trip_id = $2)`, constraintID, tripID) + var query string + var args []any + if role == "admin" { + query = `DELETE FROM roommate_constraints WHERE id = $1 + AND student_a_id IN (SELECT id FROM students WHERE trip_id = $2)` + args = []any{constraintID, tripID} + } else { + query = `DELETE FROM roommate_constraints WHERE id = $1 + AND student_a_id = ANY($2) AND level = $3::constraint_level` + args = []any{constraintID, pq.Array(myStudentIDs), role} + } + result, err := db.Exec(query, args...) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return diff --git a/static/admin.js b/static/admin.js index 59be8e6..41c6a62 100644 --- a/static/admin.js +++ b/static/admin.js @@ -24,6 +24,7 @@ async function loadTrips() { container.innerHTML = ''; for (const trip of trips) { const card = document.createElement('wa-card'); + card.dataset.tripId = trip.id; const nameRow = document.createElement('div'); nameRow.style.display = 'flex'; @@ -77,7 +78,14 @@ async function loadTrips() { const email = input.value.trim(); if (!email) return; await api('POST', '/api/trips/' + trip.id + '/admins', { email }); - loadTrips(); + await loadTrips(); + const card = container.querySelector('[data-trip-id="' + trip.id + '"]'); + if (card) { + const det = card.querySelector('wa-details'); + if (det) det.open = true; + const inp = card.querySelector('wa-input'); + if (inp) inp.focus(); + } }; addBtn.addEventListener('click', doAdd); input.addEventListener('keydown', (e) => { if (e.key === 'Enter') doAdd(); }); diff --git a/static/trip.html b/static/trip.html index 1e1cd42..754a105 100644 --- a/static/trip.html +++ b/static/trip.html @@ -73,6 +73,9 @@ .room-label { font-weight: bold; font-size: 0.8rem; margin-bottom: 0.2rem; } .solver-score { font-size: 0.8rem; margin-top: 0.3rem; color: var(--wa-color-neutral-500); } .divider { border: none; border-top: 1px solid #909090; margin: 0.75rem 0; } + .pref-row { display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.4rem; } + .pref-row .pref-name { flex: 1; font-size: 0.85rem; } + .pref-row wa-select { width: 14rem; } @@ -85,28 +88,33 @@ Switch User

-
- - - -
-
-
-
-
-
- Solve Rooms -
-
-
-
- -
- - - Add Student + +
diff --git a/static/trip.js b/static/trip.js index d48fed5..21bbb18 100644 --- a/static/trip.js +++ b/static/trip.js @@ -5,9 +5,12 @@ const tripID = location.pathname.split('/').pop(); const profile = await init(); -let trip; +let trip, me; try { - trip = await api('GET', '/api/trips/' + tripID); + [trip, me] = await Promise.all([ + api('GET', '/api/trips/' + tripID), + api('GET', '/api/trips/' + tripID + '/me') + ]); } catch (e) { document.body.style.opacity = 1; document.body.textContent = 'Access denied.'; @@ -15,11 +18,21 @@ try { } document.getElementById('trip-name').textContent = trip.name; +document.getElementById('main').style.display = 'block'; +document.getElementById('logout-btn').addEventListener('click', logout); + +if (me.role !== 'admin') { + document.getElementById('member-view').style.display = 'block'; + await renderMemberView(me); + await customElements.whenDefined('wa-button'); + document.body.style.opacity = 1; +} else { +await (async () => { + +document.getElementById('admin-view').style.display = 'block'; document.getElementById('room-size').value = trip.room_size; document.getElementById('pn-multiple').value = trip.prefer_not_multiple; document.getElementById('np-cost').value = trip.no_prefer_cost; -document.getElementById('main').style.display = 'block'; -document.getElementById('logout-btn').addEventListener('click', logout); document.getElementById('room-size').addEventListener('change', async () => { const size = parseInt(document.getElementById('room-size').value); if (size >= 1) await api('PATCH', '/api/trips/' + tripID, { room_size: size }); @@ -334,10 +347,17 @@ async function loadStudents() { addBtn.className = 'input-action'; addBtn.textContent = '+'; const doAdd = async () => { - const email = input.value.trim(); + const email = (input.value || '').trim(); if (!email) return; await api('POST', '/api/trips/' + tripID + '/students/' + student.id + '/parents', { email }); - loadStudents(); + await loadStudents(); + const reCard = container.querySelector('[data-student-id="' + student.id + '"]'); + if (reCard) { + const det = reCard.querySelector('wa-details'); + if (det) det.open = true; + const inp = reCard.querySelector('wa-input'); + if (inp) inp.focus(); + } }; addBtn.addEventListener('click', doAdd); input.addEventListener('keydown', (e) => { if (e.key === 'Enter') doAdd(); }); @@ -605,3 +625,83 @@ if (DOMAIN) { if (parts.length >= 2) emailInput.value = parts.join('.') + '@' + DOMAIN; }); } + +})(); +} + +async function renderMemberView(me) { + const [students, constraints] = await Promise.all([ + api('GET', '/api/trips/' + tripID + '/students'), + api('GET', '/api/trips/' + tripID + '/constraints') + ]); + + const myStudentIDs = new Set(me.students.map(s => s.id)); + const container = document.getElementById('member-students'); + + const kindLabels = me.role === 'student' + ? { '': 'OK to room with', prefer: 'Would like to room with', prefer_not: 'Would prefer not to room with' } + : { '': 'OK to room with', must_not: 'Not OK to room with' }; + + const kindOptions = me.role === 'student' + ? ['', 'prefer', 'prefer_not'] + : ['', 'must_not']; + + for (const myStudent of me.students) { + const card = document.createElement('wa-card'); + const label = document.createElement('span'); + label.className = 'student-name'; + label.textContent = myStudent.name; + card.appendChild(label); + + const myConstraints = {}; + for (const c of constraints) { + if (c.student_a_id === myStudent.id) { + myConstraints[c.student_b_id] = c; + } + } + + for (const other of students) { + if (myStudentIDs.has(other.id)) continue; + const row = document.createElement('div'); + row.className = 'pref-row'; + const name = document.createElement('span'); + name.className = 'pref-name'; + name.textContent = other.name; + row.appendChild(name); + + const select = document.createElement('wa-select'); + select.size = 'small'; + for (const kind of kindOptions) { + const opt = document.createElement('wa-option'); + opt.value = kind; + opt.textContent = kindLabels[kind]; + select.appendChild(opt); + } + const existing = myConstraints[other.id]; + const initVal = existing ? existing.kind : ''; + select.updateComplete.then(() => { select.value = initVal; }); + + select.addEventListener('change', async (e) => { + const val = e.target.value; + if (val === '') { + const c = myConstraints[other.id]; + if (c) { + await api('DELETE', '/api/trips/' + tripID + '/constraints/' + c.id); + delete myConstraints[other.id]; + } + } else { + const result = await api('POST', '/api/trips/' + tripID + '/constraints', { + student_a_id: myStudent.id, + student_b_id: other.id, + kind: val, + level: me.role + }); + myConstraints[other.id] = { id: result.id, kind: val, student_a_id: myStudent.id, student_b_id: other.id }; + } + }); + row.appendChild(select); + card.appendChild(row); + } + container.appendChild(card); + } +}