feat(booking): add service eligibility based on age and patch tests

- Add eligibility filtering to /api/services: exclude services below
  user's
  age, gray out services requiring patch tests that are missing/expired
- Add new endpoint /api/services/eligible-for/{user_id} for admin
  booking
  flows to check eligibility for a specific user
- Add image metadata stripping: uploads now strip all EXIF/GPS data
  via imaging library (security improvement)
- Update ServiceCard frontend: show grayed-out state for ineligible
  services with "contact us" link (public) or just warning (admin)
- Add 2 patch test services to seed data: Gel Polish Full Set,
  Luxury Gel Manicure (48h each)
- Remove deprecated local-dev.sh script
This commit is contained in:
2026-02-20 18:46:38 +00:00
parent eb1a719fc3
commit 41dc839830
13 changed files with 385 additions and 1647 deletions
+272 -5
View File
@@ -1,14 +1,17 @@
package services
import (
"crussell/auth"
"crussell/db"
"crussell/mw"
"database/sql"
"encoding/json"
"net/http"
"strings"
"time"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
)
// Service represents a service in the system
@@ -33,6 +36,8 @@ type ServiceResponse struct {
DurationMinutes int `json:"duration_minutes"`
PatchTestDurationHours int `json:"patch_test_duration_hours"`
MinimumAgeRequired int `json:"minimum_age_required"`
// Patch test status for non-admin users
PatchTestStatus *string `json:"patch_test_status,omitempty"` // nil = not checked, "ok" = valid, "required" = no record, "expired" = record too old
}
// CreateServiceRequest represents the request payload for creating a new service
@@ -205,8 +210,102 @@ func DeleteServiceHandler(w http.ResponseWriter, r *http.Request) {
}
// ServicesHandler returns all services from the database
// For non-admin logged-in users, filters based on age and patch test eligibility
func ServicesHandler(w http.ResponseWriter, r *http.Request) {
// Query all active services
// Check if user is authenticated - try context first, then optional token
userID, hasUser := r.Context().Value(mw.UserIDKey).(string)
role, _ := r.Context().Value(mw.UserRoleKey).(string)
// If no user in context, try to parse token from header
if !hasUser || userID == "" {
authHeader := r.Header.Get("Authorization")
if strings.HasPrefix(authHeader, "Bearer ") {
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
var err error
userID, role, err = auth.VerifyToken(tokenString, r.Context())
if err != nil {
// Invalid token - treat as unauthenticated
userID = ""
role = ""
}
hasUser = userID != ""
}
}
// If not logged in or admin, return all services (current behavior)
if !hasUser || userID == "" || role == "admin" {
query := `
SELECT id, name, description, price, duration_minutes,
patch_test_duration_hours, minimum_age_required
FROM services
WHERE is_active = TRUE
ORDER BY name
`
rows, err := db.DB.Query(r.Context(), query)
if err != nil {
http.Error(w, "Failed to fetch services: "+err.Error(), http.StatusInternalServerError)
return
}
defer rows.Close()
var services []ServiceResponse
for rows.Next() {
var service ServiceResponse
err := rows.Scan(
&service.ID,
&service.Name,
&service.Description,
&service.Price,
&service.DurationMinutes,
&service.PatchTestDurationHours,
&service.MinimumAgeRequired,
)
if err != nil {
http.Error(w, "Failed to read service data: "+err.Error(), http.StatusInternalServerError)
return
}
services = append(services, service)
}
if err = rows.Err(); err != nil {
http.Error(w, "Error iterating over services: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if services == nil {
services = []ServiceResponse{}
}
if err := json.NewEncoder(w).Encode(services); err != nil {
http.Error(w, "Failed to encode response: "+err.Error(), http.StatusInternalServerError)
}
return
}
// User is logged in and not admin - check eligibility
// Get user's date of birth
var dob time.Time
err := db.DB.QueryRow(r.Context(), `SELECT date_of_birth FROM users WHERE id = $1`, userID).Scan(&dob)
if err != nil {
http.Error(w, "Failed to get user data: "+err.Error(), http.StatusInternalServerError)
return
}
// Calculate age
now := time.Now()
age := now.Year() - dob.Year()
if now.YearDay() < dob.YearDay() {
age--
}
// Get all active services
query := `
SELECT id, name, description, price, duration_minutes,
patch_test_duration_hours, minimum_age_required
@@ -223,6 +322,7 @@ func ServicesHandler(w http.ResponseWriter, r *http.Request) {
defer rows.Close()
var services []ServiceResponse
var ineligibleServices []ServiceResponse
for rows.Next() {
var service ServiceResponse
@@ -241,7 +341,47 @@ func ServicesHandler(w http.ResponseWriter, r *http.Request) {
return
}
services = append(services, service)
// Check age eligibility - EXCLUDE if user is too young (can't be fixed by user)
if age < service.MinimumAgeRequired {
continue
}
// Check patch test if required - GRAY OUT if not valid
if service.PatchTestDurationHours > 0 {
var lastTime time.Time
err := db.DB.QueryRow(r.Context(),
`SELECT last_time FROM user_service_patch_tests WHERE user_id = $1 AND service_id = $2`,
userID, service.ID).Scan(&lastTime)
if err == sql.ErrNoRows || err == pgx.ErrNoRows {
// No patch test record
status := "required"
service.PatchTestStatus = &status
ineligibleServices = append(ineligibleServices, service)
continue
} else if err != nil {
http.Error(w, "Failed to check patch test: "+err.Error(), http.StatusInternalServerError)
return
}
// Check if patch test is still valid
requiredSince := lastTime.Add(time.Duration(service.PatchTestDurationHours) * time.Hour)
if now.After(requiredSince) {
// Patch test expired - gray out
status := "expired"
service.PatchTestStatus = &status
ineligibleServices = append(ineligibleServices, service)
continue
}
// Patch test is valid - include normally
status := "ok"
service.PatchTestStatus = &status
services = append(services, service)
} else {
// No patch test required - include normally
services = append(services, service)
}
}
if err = rows.Err(); err != nil {
@@ -249,20 +389,147 @@ func ServicesHandler(w http.ResponseWriter, r *http.Request) {
return
}
// Set response headers
// Sort: eligible first (by name), then ineligible (by name)
// Combine: eligible + ineligible
services = append(services, ineligibleServices...)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
// Return empty array instead of null if no services found
if services == nil {
services = []ServiceResponse{}
}
// Encode response
if err := json.NewEncoder(w).Encode(services); err != nil {
http.Error(w, "Failed to encode response: "+err.Error(), http.StatusInternalServerError)
}
}
// ServicesEligibleForUserHandler returns services with eligibility calculated for a specific user
// Used by admin booking flows when booking on behalf of a user
func ServicesEligibleForUserHandler(w http.ResponseWriter, r *http.Request) {
userID := chi.URLParam(r, "user_id")
if userID == "" {
http.Error(w, "User ID required", http.StatusBadRequest)
return
}
// Get user's date of birth
var dob time.Time
err := db.DB.QueryRow(r.Context(), `SELECT date_of_birth FROM users WHERE id = $1`, userID).Scan(&dob)
if err == sql.ErrNoRows {
http.Error(w, "User not found", http.StatusNotFound)
return
}
if err != nil {
http.Error(w, "Failed to get user data: "+err.Error(), http.StatusInternalServerError)
return
}
// Calculate age
now := time.Now()
age := now.Year() - dob.Year()
if now.YearDay() < dob.YearDay() {
age--
}
// Get all active services
query := `
SELECT id, name, description, price, duration_minutes,
patch_test_duration_hours, minimum_age_required
FROM services
WHERE is_active = TRUE
ORDER BY name
`
rows, err := db.DB.Query(r.Context(), query)
if err != nil {
http.Error(w, "Failed to fetch services: "+err.Error(), http.StatusInternalServerError)
return
}
defer rows.Close()
var services []ServiceResponse
var grayedOutServices []ServiceResponse
for rows.Next() {
var service ServiceResponse
err := rows.Scan(
&service.ID,
&service.Name,
&service.Description,
&service.Price,
&service.DurationMinutes,
&service.PatchTestDurationHours,
&service.MinimumAgeRequired,
)
if err != nil {
http.Error(w, "Failed to read service data: "+err.Error(), http.StatusInternalServerError)
return
}
// Check age eligibility - EXCLUDE if user is too young
if age < service.MinimumAgeRequired {
continue
}
// Check patch test if required
if service.PatchTestDurationHours > 0 {
var lastTime time.Time
err := db.DB.QueryRow(r.Context(),
`SELECT last_time FROM user_service_patch_tests WHERE user_id = $1 AND service_id = $2`,
userID, service.ID).Scan(&lastTime)
if err == sql.ErrNoRows || err == pgx.ErrNoRows {
// No patch test record - gray out
status := "required"
service.PatchTestStatus = &status
grayedOutServices = append(grayedOutServices, service)
continue
} else if err != nil {
http.Error(w, "Failed to check patch test: "+err.Error(), http.StatusInternalServerError)
return
}
// Check if patch test is still valid
requiredSince := lastTime.Add(time.Duration(service.PatchTestDurationHours) * time.Hour)
if now.After(requiredSince) {
// Patch test expired - gray out
status := "expired"
service.PatchTestStatus = &status
grayedOutServices = append(grayedOutServices, service)
continue
}
// Patch test is valid
status := "ok"
service.PatchTestStatus = &status
services = append(services, service)
} else {
// No patch test required
services = append(services, service)
}
}
if err = rows.Err(); err != nil {
http.Error(w, "Error iterating over services: "+err.Error(), http.StatusInternalServerError)
return
}
// Sort and combine: valid first, then grayed out
services = append(services, grayedOutServices...)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if services == nil {
services = []ServiceResponse{}
}
if err := json.NewEncoder(w).Encode(services); err != nil {
http.Error(w, "Failed to encode response: "+err.Error(), http.StatusInternalServerError)
}
}
// AllServicesHandler returns all services including inactive ones (useful for admin)
+2 -1
View File
@@ -81,10 +81,11 @@ func main() {
// All API routes grouped under /api for clarity
r.Route("/api", func(r chi.Router) {
// Public read-only
// Public read-only (but check auth context if present for eligibility)
r.Group(func(r chi.Router) {
r.Use(mw.RateLimit(120, time.Minute))
r.Get("/services", services.ServicesHandler)
r.Get("/services/eligible-for/{user_id}", services.ServicesEligibleForUserHandler)
})
// Registration: 10/min to prevent spam