303 lines
8.7 KiB
Go
303 lines
8.7 KiB
Go
package handlers
|
|
|
|
import (
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"vlog/internal/auth"
|
|
"vlog/internal/models"
|
|
"vlog/internal/storage"
|
|
)
|
|
|
|
// ListCars returns the current user's garage.
|
|
func (h *Handlers) ListCars(w http.ResponseWriter, r *http.Request) {
|
|
userID, _ := auth.UserIDFromContext(r.Context())
|
|
|
|
cars := []models.Car{} // not "var" — an empty result must encode as [], not null
|
|
err := h.dbSelect(r.Context(), &cars, `
|
|
SELECT * FROM cars WHERE user_id = ? ORDER BY created_at DESC
|
|
`, userID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to list cars")
|
|
return
|
|
}
|
|
for i := range cars {
|
|
cars[i].HasPhoto = cars[i].PhotoS3Key != nil
|
|
}
|
|
writeJSON(w, http.StatusOK, cars)
|
|
}
|
|
|
|
// CreateCar creates a new car in the current user's garage.
|
|
func (h *Handlers) CreateCar(w http.ResponseWriter, r *http.Request) {
|
|
userID, _ := auth.UserIDFromContext(r.Context())
|
|
|
|
var in models.CarInput
|
|
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid request body")
|
|
return
|
|
}
|
|
if in.Rego == "" {
|
|
writeError(w, http.StatusBadRequest, "rego is required")
|
|
return
|
|
}
|
|
|
|
regoExpiry, err := parseOptionalDate(in.RegoExpiry)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid regoExpiry")
|
|
return
|
|
}
|
|
wofExpiry, err := parseOptionalDate(in.WofExpiry)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid wofExpiry")
|
|
return
|
|
}
|
|
|
|
var car models.Car
|
|
err = h.dbGet(r.Context(), &car, `
|
|
INSERT INTO cars (id, user_id, rego, make, model, year, color, odometer, rego_expiry, wof_expiry, service_interval_km, service_interval_months)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
RETURNING *
|
|
`, uuid.New().String(), userID, in.Rego, in.Make, in.Model, in.Year, in.Color, in.Odometer, regoExpiry, wofExpiry, in.ServiceIntervalKM, in.ServiceIntervalMonths)
|
|
if err != nil {
|
|
if isUniqueConstraintErr(err) {
|
|
writeError(w, http.StatusConflict, "could not create car (rego may already exist in your garage)")
|
|
} else {
|
|
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to create car: %v", err))
|
|
}
|
|
return
|
|
}
|
|
|
|
writeJSON(w, http.StatusCreated, car)
|
|
}
|
|
|
|
// GetCar returns a single car owned by the current user.
|
|
func (h *Handlers) GetCar(w http.ResponseWriter, r *http.Request) {
|
|
car, ok := h.loadOwnedCar(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
car.HasPhoto = car.PhotoS3Key != nil
|
|
writeJSON(w, http.StatusOK, car)
|
|
}
|
|
|
|
// UpdateCar edits an existing car.
|
|
func (h *Handlers) UpdateCar(w http.ResponseWriter, r *http.Request) {
|
|
car, ok := h.loadOwnedCar(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
var in models.CarInput
|
|
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid request body")
|
|
return
|
|
}
|
|
if in.Rego == "" {
|
|
writeError(w, http.StatusBadRequest, "rego is required")
|
|
return
|
|
}
|
|
|
|
regoExpiry, err := parseOptionalDate(in.RegoExpiry)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid regoExpiry")
|
|
return
|
|
}
|
|
wofExpiry, err := parseOptionalDate(in.WofExpiry)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid wofExpiry")
|
|
return
|
|
}
|
|
|
|
var updated models.Car
|
|
err = h.dbGet(r.Context(), &updated, `
|
|
UPDATE cars
|
|
SET rego = ?, make = ?, model = ?, year = ?, color = ?,
|
|
odometer = ?, rego_expiry = ?, wof_expiry = ?,
|
|
service_interval_km = ?, service_interval_months = ?, updated_at = CURRENT_TIMESTAMP
|
|
WHERE id = ?
|
|
RETURNING *
|
|
`, in.Rego, in.Make, in.Model, in.Year, in.Color, in.Odometer, regoExpiry, wofExpiry,
|
|
in.ServiceIntervalKM, in.ServiceIntervalMonths, car.ID)
|
|
if err != nil {
|
|
if isUniqueConstraintErr(err) {
|
|
writeError(w, http.StatusConflict, "could not update car (rego may already exist in your garage)")
|
|
} else {
|
|
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to update car: %v", err))
|
|
}
|
|
return
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, updated)
|
|
}
|
|
|
|
// DeleteCar removes a car (cascades to service entries, files, reminders in
|
|
// the DB; best-effort cleans up its photo in storage).
|
|
func (h *Handlers) DeleteCar(w http.ResponseWriter, r *http.Request) {
|
|
car, ok := h.loadOwnedCar(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
if _, err := h.dbExec(r.Context(), `DELETE FROM cars WHERE id = ?`, car.ID); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to delete car")
|
|
return
|
|
}
|
|
|
|
if car.PhotoS3Key != nil {
|
|
_ = h.Storage.Delete(r.Context(), *car.PhotoS3Key)
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
// UploadCarPhoto accepts a multipart PNG/JPEG upload and replaces the car's photo.
|
|
func (h *Handlers) UploadCarPhoto(w http.ResponseWriter, r *http.Request) {
|
|
car, ok := h.loadOwnedCar(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
file, contentType, ok := parseUploadedFile(w, r, 10<<20, storage.AllowedPhotoTypes)
|
|
if !ok {
|
|
return
|
|
}
|
|
defer file.Close()
|
|
|
|
oldKey := car.PhotoS3Key
|
|
key := fmt.Sprintf("users/%s/cars/%s/photo.%s", car.UserID, car.ID, extensionForContentType(contentType))
|
|
|
|
if err := h.Storage.Upload(r.Context(), key, contentType, file); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to upload photo")
|
|
return
|
|
}
|
|
|
|
if _, err := h.dbExec(r.Context(), `
|
|
UPDATE cars SET photo_s3_key = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?
|
|
`, key, car.ID); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to save photo reference")
|
|
return
|
|
}
|
|
|
|
if oldKey != nil && *oldKey != key {
|
|
_ = h.Storage.Delete(r.Context(), *oldKey)
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
// GetCarPhoto streams the car's photo from storage.
|
|
func (h *Handlers) GetCarPhoto(w http.ResponseWriter, r *http.Request) {
|
|
car, ok := h.loadOwnedCar(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
if car.PhotoS3Key == nil {
|
|
writeError(w, http.StatusNotFound, "no photo set")
|
|
return
|
|
}
|
|
|
|
body, err := h.Storage.Get(r.Context(), *car.PhotoS3Key)
|
|
if err != nil {
|
|
writeError(w, http.StatusNotFound, "photo not found")
|
|
return
|
|
}
|
|
defer body.Close()
|
|
|
|
w.Header().Set("Content-Type", contentTypeForExtension(*car.PhotoS3Key))
|
|
w.Header().Set("Cache-Control", "private, max-age=60")
|
|
io.Copy(w, body)
|
|
}
|
|
|
|
// UpdateOdometer is a lightweight endpoint for just bumping the odometer
|
|
// reading — quicker than resending the whole car record via UpdateCar.
|
|
func (h *Handlers) UpdateOdometer(w http.ResponseWriter, r *http.Request) {
|
|
car, ok := h.loadOwnedCar(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
var body struct {
|
|
Odometer int `json:"odometer"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid request body")
|
|
return
|
|
}
|
|
if body.Odometer < 0 {
|
|
writeError(w, http.StatusBadRequest, "odometer must be positive")
|
|
return
|
|
}
|
|
|
|
var updated models.Car
|
|
err := h.dbGet(r.Context(), &updated, `
|
|
UPDATE cars SET odometer = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? RETURNING *
|
|
`, body.Odometer, car.ID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to update odometer")
|
|
return
|
|
}
|
|
updated.HasPhoto = updated.PhotoS3Key != nil
|
|
writeJSON(w, http.StatusOK, updated)
|
|
}
|
|
|
|
// GenerateShareLink turns on (or regenerates, invalidating the previous
|
|
// link/QR code) public read-only sharing for a car.
|
|
func (h *Handlers) GenerateShareLink(w http.ResponseWriter, r *http.Request) {
|
|
car, ok := h.loadOwnedCar(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
token := randomID() + randomID() // 64 hex chars of entropy — not guessable
|
|
var updated models.Car
|
|
err := h.dbGet(r.Context(), &updated, `
|
|
UPDATE cars SET share_token = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? RETURNING *
|
|
`, token, car.ID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to generate share link")
|
|
return
|
|
}
|
|
updated.HasPhoto = updated.PhotoS3Key != nil
|
|
writeJSON(w, http.StatusOK, updated)
|
|
}
|
|
|
|
// RevokeShareLink turns off public sharing for a car.
|
|
func (h *Handlers) RevokeShareLink(w http.ResponseWriter, r *http.Request) {
|
|
car, ok := h.loadOwnedCar(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
if _, err := h.dbExec(r.Context(), `
|
|
UPDATE cars SET share_token = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?
|
|
`, car.ID); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to revoke share link")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
func (h *Handlers) loadOwnedCar(w http.ResponseWriter, r *http.Request) (*models.Car, bool) {
|
|
userID, _ := auth.UserIDFromContext(r.Context())
|
|
carID := r.PathValue("carId")
|
|
|
|
var car models.Car
|
|
err := h.dbGet(r.Context(), &car, `
|
|
SELECT * FROM cars WHERE id = ? AND user_id = ?
|
|
`, carID, userID)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
writeError(w, http.StatusNotFound, "car not found")
|
|
return nil, false
|
|
}
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to load car: %v", err))
|
|
return nil, false
|
|
}
|
|
return &car, true
|
|
}
|