Initial commit
This commit is contained in:
commit
b6014c6ffc
47 files changed
+4329
No files matched your search
@@ -0,0 +1,74 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"vlog/internal/auth"
|
||||
)
|
||||
|
||||
// Login kicks off the OIDC authorization-code flow.
|
||||
func (h *Handlers) Login(w http.ResponseWriter, r *http.Request) {
|
||||
h.Authenticator.BeginLogin(w, r)
|
||||
}
|
||||
|
||||
// Callback completes the OIDC flow: verifies the ID token, JIT-provisions
|
||||
// the user row, mints our own session JWT, and redirects into the app.
|
||||
func (h *Handlers) Callback(w http.ResponseWriter, r *http.Request) {
|
||||
claims, err := h.Authenticator.HandleCallback(r.Context(), w, r)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnauthorized, "login failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
var name *string
|
||||
if claims.Name != "" {
|
||||
name = &claims.Name
|
||||
}
|
||||
|
||||
var userID string
|
||||
err = h.dbGet(r.Context(), &userID, `
|
||||
INSERT INTO users (id, oidc_sub, email, name)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT (oidc_sub) DO UPDATE SET email = excluded.email, name = excluded.name
|
||||
RETURNING id
|
||||
`, uuid.New().String(), claims.Sub, claims.Email, name)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to provision user")
|
||||
return
|
||||
}
|
||||
|
||||
token, err := auth.MintSessionJWT(h.JWTSecret, userID, claims.Email)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to mint session")
|
||||
return
|
||||
}
|
||||
|
||||
auth.SetSessionCookie(w, token, h.SecureCookies)
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
}
|
||||
|
||||
// Logout clears the session cookie.
|
||||
func (h *Handlers) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
auth.ClearSessionCookie(w, h.SecureCookies)
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
// Me returns the current authenticated user.
|
||||
func (h *Handlers) Me(w http.ResponseWriter, r *http.Request) {
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
|
||||
var user struct {
|
||||
ID string `db:"id" json:"id"`
|
||||
Email string `db:"email" json:"email"`
|
||||
Name *string `db:"name" json:"name"`
|
||||
}
|
||||
err := h.dbGet(r.Context(), &user, `SELECT id, email, name FROM users WHERE id = ?`, userID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnauthorized, "user not found")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, user)
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"vlog/internal/auth"
|
||||
"vlog/internal/models"
|
||||
)
|
||||
|
||||
// Dashboard computes the "what's coming up" view for the current user:
|
||||
// open reminders due soon/overdue (real + synthesized rego/WoF/service-due),
|
||||
// across every car. It's computed at request time — no scheduler, no
|
||||
// email, matching the in-app-only reminder decision. Shares its synthesis
|
||||
// logic with the car-scoped ListReminders (see reminder_view.go) so the two
|
||||
// views never disagree about what's due.
|
||||
func (h *Handlers) Dashboard(w http.ResponseWriter, r *http.Request) {
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
todayDate := today()
|
||||
|
||||
var cars []models.Car
|
||||
if err := h.dbSelect(r.Context(), &cars, `SELECT * FROM cars WHERE user_id = ?`, userID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load dashboard")
|
||||
return
|
||||
}
|
||||
|
||||
carByID := make(map[string]models.Car, len(cars))
|
||||
carIDs := make([]string, len(cars))
|
||||
for i, c := range cars {
|
||||
carByID[c.ID] = c
|
||||
carIDs[i] = c.ID
|
||||
}
|
||||
|
||||
items := []models.ReminderView{} // not "var" — an empty result must encode as [], not null
|
||||
|
||||
if len(carIDs) > 0 {
|
||||
query, args, err := sqlx.In(`SELECT * FROM reminders WHERE car_id IN (?) AND completed_at IS NULL`, carIDs)
|
||||
if err == nil {
|
||||
var reminders []models.Reminder
|
||||
if err := h.dbSelect(r.Context(), &reminders, query, args...); err == nil {
|
||||
for _, rem := range reminders {
|
||||
car := carByID[rem.CarID]
|
||||
view := reminderToView(rem, car.Rego, car.Odometer, todayDate)
|
||||
if view.Status == "overdue" || view.Status == "upcoming" {
|
||||
items = append(items, view)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, c := range cars {
|
||||
car := c // local copy — synthesizedReminders takes a pointer
|
||||
for _, view := range synthesizedReminders(r.Context(), h, &car, todayDate) {
|
||||
if view.Status == "overdue" || view.Status == "upcoming" {
|
||||
items = append(items, view)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sortReminderViews(items)
|
||||
writeJSON(w, http.StatusOK, items)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package handlers
|
||||
|
||||
import "time"
|
||||
|
||||
const dateLayout = "2006-01-02"
|
||||
|
||||
// parseOptionalDate parses a "YYYY-MM-DD" string, treating nil/empty as no
|
||||
// value. Used for the optional date fields on car/reminder inputs.
|
||||
func parseOptionalDate(s *string) (*time.Time, error) {
|
||||
if s == nil || *s == "" {
|
||||
return nil, nil
|
||||
}
|
||||
t, err := time.Parse(dateLayout, *s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &t, nil
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"vlog/internal/auth"
|
||||
"vlog/internal/models"
|
||||
"vlog/internal/storage"
|
||||
)
|
||||
|
||||
// parseUploadedFile extracts the "file" multipart field, enforces maxBytes,
|
||||
// and sniffs+validates its real content type against allowed (never trusts
|
||||
// the client-declared type/extension). Returns the file handle reset to the
|
||||
// start, ready to stream to storage — caller must Close it.
|
||||
func parseUploadedFile(w http.ResponseWriter, r *http.Request, maxBytes int64, allowed map[string]bool) (multipart.File, string, bool) {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
|
||||
if err := r.ParseMultipartForm(maxBytes); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "file too large or invalid upload")
|
||||
return nil, "", false
|
||||
}
|
||||
|
||||
file, _, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "missing file")
|
||||
return nil, "", false
|
||||
}
|
||||
|
||||
contentType, err := storage.DetectAndValidate(file, allowed)
|
||||
if err != nil {
|
||||
file.Close()
|
||||
writeError(w, http.StatusUnsupportedMediaType, err.Error())
|
||||
return nil, "", false
|
||||
}
|
||||
|
||||
return file, contentType, true
|
||||
}
|
||||
|
||||
func extensionForContentType(ct string) string {
|
||||
switch ct {
|
||||
case "image/png":
|
||||
return "png"
|
||||
case "image/jpeg":
|
||||
return "jpg"
|
||||
case "application/pdf":
|
||||
return "pdf"
|
||||
default:
|
||||
return "bin"
|
||||
}
|
||||
}
|
||||
|
||||
func contentTypeForExtension(key string) string {
|
||||
switch {
|
||||
case strings.HasSuffix(key, ".png"):
|
||||
return "image/png"
|
||||
case strings.HasSuffix(key, ".jpg"), strings.HasSuffix(key, ".jpeg"):
|
||||
return "image/jpeg"
|
||||
case strings.HasSuffix(key, ".pdf"):
|
||||
return "application/pdf"
|
||||
default:
|
||||
return "application/octet-stream"
|
||||
}
|
||||
}
|
||||
|
||||
func randomID() string {
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// sanitizeFileName strips any path components and whitespace so it's safe
|
||||
// to embed in a storage key and to send back in Content-Disposition.
|
||||
func sanitizeFileName(name string) string {
|
||||
name = filepath.Base(name)
|
||||
name = strings.ReplaceAll(name, " ", "_")
|
||||
if name == "" || name == "." || name == "/" {
|
||||
return "file"
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
// GetFile streams a service-entry attachment after verifying the requesting
|
||||
// user owns the car the entry belongs to.
|
||||
func (h *Handlers) GetFile(w http.ResponseWriter, r *http.Request) {
|
||||
file, ok := h.loadOwnedFile(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
body, err := h.Storage.Get(r.Context(), file.S3Key)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "file not found in storage")
|
||||
return
|
||||
}
|
||||
defer body.Close()
|
||||
|
||||
w.Header().Set("Content-Type", file.ContentType)
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, file.FileName))
|
||||
io.Copy(w, body)
|
||||
}
|
||||
|
||||
// DeleteFile removes a single attachment.
|
||||
func (h *Handlers) DeleteFile(w http.ResponseWriter, r *http.Request) {
|
||||
file, ok := h.loadOwnedFile(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := h.dbExec(r.Context(), `DELETE FROM service_entry_files WHERE id = ?`, file.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to delete file")
|
||||
return
|
||||
}
|
||||
_ = h.Storage.Delete(r.Context(), file.S3Key)
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (h *Handlers) loadOwnedFile(w http.ResponseWriter, r *http.Request) (*models.ServiceEntryFile, bool) {
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
fileID := r.PathValue("fileId")
|
||||
|
||||
var file models.ServiceEntryFile
|
||||
err := h.dbGet(r.Context(), &file, `
|
||||
SELECT sef.*
|
||||
FROM service_entry_files sef
|
||||
JOIN service_entries se ON se.id = sef.service_entry_id
|
||||
JOIN cars c ON c.id = se.car_id
|
||||
WHERE sef.id = ? AND c.user_id = ?
|
||||
`, fileID, userID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "file not found")
|
||||
return nil, false
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load file")
|
||||
return nil, false
|
||||
}
|
||||
return &file, true
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"vlog/internal/auth"
|
||||
"vlog/internal/models"
|
||||
)
|
||||
|
||||
// ListFuelEntries returns one page of a car's fuel-up history, newest
|
||||
// first. Paginated for the same reason as service entries — no unbounded
|
||||
// fetch regardless of how long the car's been tracked.
|
||||
func (h *Handlers) ListFuelEntries(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, offset := parsePagination(r)
|
||||
|
||||
entries := []models.FuelEntry{} // not "var" — empty result must encode as [], not null
|
||||
err := h.dbSelect(r.Context(), &entries, `
|
||||
SELECT * FROM fuel_entries WHERE car_id = ?
|
||||
ORDER BY entry_date DESC, created_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`, car.ID, limit+1, offset)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list fuel entries")
|
||||
return
|
||||
}
|
||||
|
||||
entries, hasMore := paginate(limit, entries)
|
||||
writeJSON(w, http.StatusOK, page[models.FuelEntry]{Items: entries, HasMore: hasMore})
|
||||
}
|
||||
|
||||
// CreateFuelEntry adds a fuel-up to a car.
|
||||
func (h *Handlers) CreateFuelEntry(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
in, entryDate, ok := decodeFuelEntryInput(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var entry models.FuelEntry
|
||||
err := h.dbGet(r.Context(), &entry, `
|
||||
INSERT INTO fuel_entries (id, car_id, entry_date, litres, cost, odometer, location, notes)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
RETURNING *
|
||||
`, uuid.New().String(), car.ID, entryDate, in.Litres, in.Cost, in.Odometer, in.Location, in.Notes)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to create fuel entry")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, entry)
|
||||
}
|
||||
|
||||
// UpdateFuelEntry edits a fuel entry's fields.
|
||||
func (h *Handlers) UpdateFuelEntry(w http.ResponseWriter, r *http.Request) {
|
||||
entry, ok := h.loadOwnedFuelEntry(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
in, entryDate, ok := decodeFuelEntryInput(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var updated models.FuelEntry
|
||||
err := h.dbGet(r.Context(), &updated, `
|
||||
UPDATE fuel_entries
|
||||
SET entry_date = ?, litres = ?, cost = ?, odometer = ?, location = ?, notes = ?
|
||||
WHERE id = ?
|
||||
RETURNING *
|
||||
`, entryDate, in.Litres, in.Cost, in.Odometer, in.Location, in.Notes, entry.ID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to update fuel entry")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, updated)
|
||||
}
|
||||
|
||||
// DeleteFuelEntry removes a fuel entry.
|
||||
func (h *Handlers) DeleteFuelEntry(w http.ResponseWriter, r *http.Request) {
|
||||
entry, ok := h.loadOwnedFuelEntry(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := h.dbExec(r.Context(), `DELETE FROM fuel_entries WHERE id = ?`, entry.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to delete fuel entry")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func decodeFuelEntryInput(w http.ResponseWriter, r *http.Request) (models.FuelEntryInput, time.Time, bool) {
|
||||
var in models.FuelEntryInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return in, time.Time{}, false
|
||||
}
|
||||
if in.Litres <= 0 {
|
||||
writeError(w, http.StatusBadRequest, "litres must be greater than 0")
|
||||
return in, time.Time{}, false
|
||||
}
|
||||
if in.Cost <= 0 {
|
||||
writeError(w, http.StatusBadRequest, "cost must be greater than 0")
|
||||
return in, time.Time{}, false
|
||||
}
|
||||
entryDate, err := time.Parse(dateLayout, in.EntryDate)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid entryDate")
|
||||
return in, time.Time{}, false
|
||||
}
|
||||
return in, entryDate, true
|
||||
}
|
||||
|
||||
func (h *Handlers) loadOwnedFuelEntry(w http.ResponseWriter, r *http.Request) (*models.FuelEntry, bool) {
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
entryID := r.PathValue("entryId")
|
||||
|
||||
var entry models.FuelEntry
|
||||
err := h.dbGet(r.Context(), &entry, `
|
||||
SELECT fe.*
|
||||
FROM fuel_entries fe
|
||||
JOIN cars c ON c.id = fe.car_id
|
||||
WHERE fe.id = ? AND c.user_id = ?
|
||||
`, entryID, userID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "fuel entry not found")
|
||||
return nil, false
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load fuel entry")
|
||||
return nil, false
|
||||
}
|
||||
return &entry, true
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
// Package handlers implements the JSON API. All handlers hang off Handlers,
|
||||
// which carries the shared dependencies (DB, storage, auth) they need.
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"vlog/internal/auth"
|
||||
"vlog/internal/storage"
|
||||
)
|
||||
|
||||
type Handlers struct {
|
||||
DB *sqlx.DB
|
||||
Storage storage.Storage
|
||||
Authenticator *auth.Authenticator
|
||||
JWTSecret string
|
||||
SecureCookies bool
|
||||
}
|
||||
|
||||
func New(db *sqlx.DB, store storage.Storage, authenticator *auth.Authenticator, jwtSecret string, secureCookies bool) *Handlers {
|
||||
return &Handlers{
|
||||
DB: db,
|
||||
Storage: store,
|
||||
Authenticator: authenticator,
|
||||
JWTSecret: jwtSecret,
|
||||
SecureCookies: secureCookies,
|
||||
}
|
||||
}
|
||||
|
||||
// All queries in this package are written with "?" placeholders (SQLite's
|
||||
// native style) and go through these three helpers, which rebind to "$1,
|
||||
// $2, ..." automatically when running against Postgres. This is what lets
|
||||
// the same query strings work against both DB_DRIVER options.
|
||||
|
||||
func (h *Handlers) dbGet(ctx context.Context, dest interface{}, query string, args ...interface{}) error {
|
||||
return h.DB.GetContext(ctx, dest, h.DB.Rebind(query), args...)
|
||||
}
|
||||
|
||||
func (h *Handlers) dbSelect(ctx context.Context, dest interface{}, query string, args ...interface{}) error {
|
||||
return h.DB.SelectContext(ctx, dest, h.DB.Rebind(query), args...)
|
||||
}
|
||||
|
||||
func (h *Handlers) dbExec(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
|
||||
return h.DB.ExecContext(ctx, h.DB.Rebind(query), args...)
|
||||
}
|
||||
|
||||
// writeJSON marshals v as the response body, or 500s if it fails.
|
||||
func writeJSON(w http.ResponseWriter, status int, v interface{}) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
if err := json.NewEncoder(w).Encode(v); err != nil {
|
||||
// Response is already partially written at this point; just log.
|
||||
// (No logger wired up yet — keep it dead simple and let it be silent
|
||||
// in the rare case encoding itself fails.)
|
||||
_ = err
|
||||
}
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, message string) {
|
||||
writeJSON(w, status, map[string]string{"error": message})
|
||||
}
|
||||
|
||||
// isUniqueConstraintErr distinguishes an actual unique-constraint violation
|
||||
// (e.g. duplicate rego) from any other DB error, so a schema/column problem
|
||||
// during development doesn't get mislabeled as "already exists" and hide
|
||||
// the real cause. Postgres and SQLite word this differently, so it's a
|
||||
// substring match on the driver's own error text rather than a typed
|
||||
// sentinel — good enough since the only thing we do with it is pick the
|
||||
// response code/message, not branch on a specific constraint.
|
||||
func isUniqueConstraintErr(err error) bool {
|
||||
msg := strings.ToLower(err.Error())
|
||||
return strings.Contains(msg, "unique constraint") || strings.Contains(msg, "duplicate key")
|
||||
}
|
||||
|
||||
// page is the response shape for every paginated list endpoint — long lists
|
||||
// (service history, knowledgebase) load a page at a time instead of
|
||||
// dumping everything into one response/DOM.
|
||||
type page[T any] struct {
|
||||
Items []T `json:"items"`
|
||||
HasMore bool `json:"hasMore"`
|
||||
}
|
||||
|
||||
const (
|
||||
defaultPageSize = 20
|
||||
maxPageSize = 100
|
||||
)
|
||||
|
||||
// parsePagination reads ?limit=&offset= from the query string, applying
|
||||
// sane defaults/bounds so a bad or missing value can't blow up the page
|
||||
// size or request something nonsensical.
|
||||
func parsePagination(r *http.Request) (limit, offset int) {
|
||||
limit = defaultPageSize
|
||||
if v, err := strconv.Atoi(r.URL.Query().Get("limit")); err == nil && v > 0 {
|
||||
limit = v
|
||||
}
|
||||
if limit > maxPageSize {
|
||||
limit = maxPageSize
|
||||
}
|
||||
offset = 0
|
||||
if v, err := strconv.Atoi(r.URL.Query().Get("offset")); err == nil && v > 0 {
|
||||
offset = v
|
||||
}
|
||||
return limit, offset
|
||||
}
|
||||
|
||||
// paginate expects rows fetched with LIMIT limit+1, so it can tell whether
|
||||
// there's a next page without a separate COUNT(*) query — then trims back
|
||||
// down to limit.
|
||||
func paginate[T any](limit int, rows []T) (trimmed []T, hasMore bool) {
|
||||
hasMore = len(rows) > limit
|
||||
if hasMore {
|
||||
rows = rows[:limit]
|
||||
}
|
||||
return rows, hasMore
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"vlog/internal/auth"
|
||||
"vlog/internal/models"
|
||||
)
|
||||
|
||||
// ListKnowledge returns one page of a car's knowledgebase entries
|
||||
// (procedures, common problems, reference info like coolant type), most
|
||||
// recently updated first. Paginated (?limit=&offset=) for the same reason
|
||||
// as service entries — a big knowledgebase shouldn't mean one giant fetch.
|
||||
func (h *Handlers) ListKnowledge(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, offset := parsePagination(r)
|
||||
|
||||
entries := []models.KnowledgeEntry{} // not "var" — empty result must encode as [], not null
|
||||
err := h.dbSelect(r.Context(), &entries, `
|
||||
SELECT * FROM knowledge_entries WHERE car_id = ?
|
||||
ORDER BY updated_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`, car.ID, limit+1, offset)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list knowledge entries")
|
||||
return
|
||||
}
|
||||
|
||||
entries, hasMore := paginate(limit, entries)
|
||||
writeJSON(w, http.StatusOK, page[models.KnowledgeEntry]{Items: entries, HasMore: hasMore})
|
||||
}
|
||||
|
||||
// CreateKnowledge adds a new knowledgebase entry to a car.
|
||||
func (h *Handlers) CreateKnowledge(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
in, ok := decodeKnowledgeInput(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var entry models.KnowledgeEntry
|
||||
err := h.dbGet(r.Context(), &entry, `
|
||||
INSERT INTO knowledge_entries (id, car_id, title, body)
|
||||
VALUES (?, ?, ?, ?)
|
||||
RETURNING *
|
||||
`, uuid.New().String(), car.ID, in.Title, in.Body)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to create knowledge entry")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, entry)
|
||||
}
|
||||
|
||||
// UpdateKnowledge edits a knowledgebase entry's title/body.
|
||||
func (h *Handlers) UpdateKnowledge(w http.ResponseWriter, r *http.Request) {
|
||||
entry, ok := h.loadOwnedKnowledge(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
in, ok := decodeKnowledgeInput(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var updated models.KnowledgeEntry
|
||||
err := h.dbGet(r.Context(), &updated, `
|
||||
UPDATE knowledge_entries
|
||||
SET title = ?, body = ?, updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
RETURNING *
|
||||
`, in.Title, in.Body, entry.ID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to update knowledge entry")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, updated)
|
||||
}
|
||||
|
||||
// DeleteKnowledge removes a knowledgebase entry.
|
||||
func (h *Handlers) DeleteKnowledge(w http.ResponseWriter, r *http.Request) {
|
||||
entry, ok := h.loadOwnedKnowledge(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := h.dbExec(r.Context(), `DELETE FROM knowledge_entries WHERE id = ?`, entry.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to delete knowledge entry")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func decodeKnowledgeInput(w http.ResponseWriter, r *http.Request) (models.KnowledgeEntryInput, bool) {
|
||||
var in models.KnowledgeEntryInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return in, false
|
||||
}
|
||||
if in.Title == "" {
|
||||
writeError(w, http.StatusBadRequest, "title is required")
|
||||
return in, false
|
||||
}
|
||||
return in, true
|
||||
}
|
||||
|
||||
func (h *Handlers) loadOwnedKnowledge(w http.ResponseWriter, r *http.Request) (*models.KnowledgeEntry, bool) {
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
entryID := r.PathValue("knowledgeId")
|
||||
|
||||
var entry models.KnowledgeEntry
|
||||
err := h.dbGet(r.Context(), &entry, `
|
||||
SELECT k.*
|
||||
FROM knowledge_entries k
|
||||
JOIN cars c ON c.id = k.car_id
|
||||
WHERE k.id = ? AND c.user_id = ?
|
||||
`, entryID, userID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "knowledge entry not found")
|
||||
return nil, false
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load knowledge entry")
|
||||
return nil, false
|
||||
}
|
||||
return &entry, true
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sort"
|
||||
"time"
|
||||
)
|
||||
|
||||
type MileageResponse struct {
|
||||
CurrentOdometer *int `json:"currentOdometer"`
|
||||
KmPerYear *float64 `json:"kmPerYear"`
|
||||
// YearsPer100k/Next100kEta answer "how long does it take to put another
|
||||
// 100,000km on this car at my current rate" — a throughput figure, not
|
||||
// tied to the odometer's current position (68,420km → 100,000km is a
|
||||
// misleadingly small gap; this is always a full 100,000km from today).
|
||||
YearsPer100k *float64 `json:"yearsPer100k"`
|
||||
Next100kEta *string `json:"next100kEta"`
|
||||
}
|
||||
|
||||
// milestoneDistance is the block of driving the "how long" estimate is
|
||||
// measured over — a generic throughput unit, not a specific odometer target.
|
||||
const milestoneDistance = 100_000
|
||||
|
||||
// Mileage reports the car's usage rate: an estimated km/year (derived from
|
||||
// every known odometer+date pair across service and fuel entries, plus the
|
||||
// car's own current reading) and how long, at that rate, it takes to add
|
||||
// another 100,000km from today. Needs at least two data points to estimate
|
||||
// a rate — with fewer, it just reports the current reading.
|
||||
func (h *Handlers) Mileage(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
type odometerPoint struct {
|
||||
EntryDate time.Time `db:"entry_date"`
|
||||
Odometer int `db:"odometer"`
|
||||
}
|
||||
|
||||
var points []odometerPoint
|
||||
_ = h.dbSelect(r.Context(), &points, `
|
||||
SELECT entry_date, odometer FROM service_entries WHERE car_id = ? AND odometer IS NOT NULL
|
||||
UNION ALL
|
||||
SELECT entry_date, odometer FROM fuel_entries WHERE car_id = ? AND odometer IS NOT NULL
|
||||
`, car.ID, car.ID)
|
||||
// best-effort: a query error just means we fall back to "current reading
|
||||
// only" below, rather than failing the whole endpoint.
|
||||
|
||||
if car.Odometer != nil {
|
||||
points = append(points, odometerPoint{EntryDate: today(), Odometer: *car.Odometer})
|
||||
}
|
||||
sort.Slice(points, func(i, j int) bool { return points[i].EntryDate.Before(points[j].EntryDate) })
|
||||
|
||||
resp := MileageResponse{CurrentOdometer: car.Odometer}
|
||||
|
||||
if len(points) >= 2 {
|
||||
first, last := points[0], points[len(points)-1]
|
||||
days := last.EntryDate.Sub(first.EntryDate).Hours() / 24
|
||||
if days > 0 && last.Odometer > first.Odometer {
|
||||
kmPerYear := float64(last.Odometer-first.Odometer) / days * 365
|
||||
resp.KmPerYear = &kmPerYear
|
||||
|
||||
years := milestoneDistance / kmPerYear
|
||||
resp.YearsPer100k = &years
|
||||
|
||||
eta := today().AddDate(0, 0, int(years*365)).Format(dateLayout)
|
||||
resp.Next100kEta = &eta
|
||||
}
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// Public, unauthenticated read-only endpoints for a car whose owner has
|
||||
// turned on sharing (POST /api/cars/{id}/share) — e.g. a QR code stuck in
|
||||
// the glovebox a mechanic can scan, or a link sent to a buyer. Deliberately
|
||||
// a separate, narrow surface (not just "the normal endpoints minus auth")
|
||||
// so there's no risk of it ever exposing more than intended: car identity,
|
||||
// service history, and its attachments — no reminders, no knowledgebase, no
|
||||
// owner info.
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"vlog/internal/models"
|
||||
)
|
||||
|
||||
func (h *Handlers) loadCarByShareToken(w http.ResponseWriter, r *http.Request) (*models.Car, bool) {
|
||||
token := r.PathValue("shareToken")
|
||||
if token == "" {
|
||||
writeError(w, http.StatusNotFound, "not found")
|
||||
return nil, false
|
||||
}
|
||||
|
||||
var car models.Car
|
||||
err := h.dbGet(r.Context(), &car, `SELECT * FROM cars WHERE share_token = ?`, token)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "not found")
|
||||
return nil, false
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load car")
|
||||
return nil, false
|
||||
}
|
||||
return &car, true
|
||||
}
|
||||
|
||||
// PublicCar returns just enough to identify the car — no owner/user info.
|
||||
func (h *Handlers) PublicCar(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadCarByShareToken(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"rego": car.Rego,
|
||||
"make": car.Make,
|
||||
"model": car.Model,
|
||||
"year": car.Year,
|
||||
"color": car.Color,
|
||||
"hasPhoto": car.PhotoS3Key != nil,
|
||||
})
|
||||
}
|
||||
|
||||
// PublicCarPhoto streams the car's photo — helps confirm it's the right car.
|
||||
func (h *Handlers) PublicCarPhoto(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadCarByShareToken(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))
|
||||
io.Copy(w, body)
|
||||
}
|
||||
|
||||
// PublicServiceEntries returns one page of service history, including
|
||||
// attachments — read-only, no edit/delete affordance on this surface.
|
||||
func (h *Handlers) PublicServiceEntries(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadCarByShareToken(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, offset := parsePagination(r)
|
||||
|
||||
var entries []models.ServiceEntry
|
||||
err := h.dbSelect(r.Context(), &entries, `
|
||||
SELECT * FROM service_entries WHERE car_id = ?
|
||||
ORDER BY entry_date DESC, created_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`, car.ID, limit+1, offset)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list service entries")
|
||||
return
|
||||
}
|
||||
|
||||
entries, hasMore := paginate(limit, entries)
|
||||
writeJSON(w, http.StatusOK, page[ServiceEntryWithFiles]{
|
||||
Items: h.attachFiles(r, entries),
|
||||
HasMore: hasMore,
|
||||
})
|
||||
}
|
||||
|
||||
// PublicFile streams a service-entry attachment, verified to belong to a
|
||||
// car reachable via this exact share token (not just "any file the caller
|
||||
// asks for").
|
||||
func (h *Handlers) PublicFile(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadCarByShareToken(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
fileID := r.PathValue("fileId")
|
||||
|
||||
var file models.ServiceEntryFile
|
||||
err := h.dbGet(r.Context(), &file, `
|
||||
SELECT sef.*
|
||||
FROM service_entry_files sef
|
||||
JOIN service_entries se ON se.id = sef.service_entry_id
|
||||
WHERE sef.id = ? AND se.car_id = ?
|
||||
`, fileID, car.ID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "file not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load file")
|
||||
return
|
||||
}
|
||||
|
||||
body, err := h.Storage.Get(r.Context(), file.S3Key)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "file not found in storage")
|
||||
return
|
||||
}
|
||||
defer body.Close()
|
||||
w.Header().Set("Content-Type", file.ContentType)
|
||||
io.Copy(w, body)
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"vlog/internal/models"
|
||||
)
|
||||
|
||||
// reminderWindowDays is how far ahead items are surfaced as "upcoming"
|
||||
// (overdue items always show regardless of age).
|
||||
const reminderWindowDays = 30
|
||||
|
||||
func today() time.Time {
|
||||
now := time.Now().UTC()
|
||||
return time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
// statusFor computes overdue/upcoming/future for a due date and/or due
|
||||
// odometer against today and the car's current odometer reading. Either
|
||||
// dueDate or dueOdometer (or both) may be nil.
|
||||
func statusFor(dueDate *time.Time, dueOdometer, currentOdometer *int, today time.Time) string {
|
||||
overdue, upcoming := false, false
|
||||
if dueDate != nil {
|
||||
if dueDate.Before(today) {
|
||||
overdue = true
|
||||
} else if !dueDate.After(today.AddDate(0, 0, reminderWindowDays)) {
|
||||
upcoming = true
|
||||
}
|
||||
}
|
||||
if dueOdometer != nil && currentOdometer != nil {
|
||||
if *currentOdometer >= *dueOdometer {
|
||||
overdue = true
|
||||
} else if *dueOdometer-*currentOdometer <= 1000 {
|
||||
upcoming = true
|
||||
}
|
||||
}
|
||||
if overdue {
|
||||
return "overdue"
|
||||
}
|
||||
if upcoming {
|
||||
return "upcoming"
|
||||
}
|
||||
return "future"
|
||||
}
|
||||
|
||||
// reminderToView converts a stored Reminder row into the unified view shape.
|
||||
func reminderToView(r models.Reminder, carRego string, currentOdometer *int, todayDate time.Time) models.ReminderView {
|
||||
status := "done"
|
||||
if r.CompletedAt == nil {
|
||||
status = statusFor(r.DueDate, r.DueOdometer, currentOdometer, todayDate)
|
||||
}
|
||||
id := r.ID
|
||||
return models.ReminderView{
|
||||
ID: &id, CarID: r.CarID, CarRego: carRego, ReminderType: r.ReminderType,
|
||||
Label: r.Label, DueDate: r.DueDate, DueOdometer: r.DueOdometer,
|
||||
Notes: r.Notes, CompletedAt: r.CompletedAt, Status: status,
|
||||
}
|
||||
}
|
||||
|
||||
// synthesizedReminders returns the rego/WoF/next-service-due items derived
|
||||
// from a car's own fields — never stored, always computed fresh, so there's
|
||||
// nothing to keep in sync when the car (or its service history) changes.
|
||||
// ID is left nil, which is how the frontend knows these aren't editable
|
||||
// directly — change the car's rego/WoF/service-interval fields instead.
|
||||
func synthesizedReminders(ctx context.Context, h *Handlers, car *models.Car, todayDate time.Time) []models.ReminderView {
|
||||
var views []models.ReminderView
|
||||
|
||||
if car.RegoExpiry != nil {
|
||||
views = append(views, models.ReminderView{
|
||||
CarID: car.ID, CarRego: car.Rego, ReminderType: "rego",
|
||||
DueDate: car.RegoExpiry, Status: statusFor(car.RegoExpiry, nil, nil, todayDate),
|
||||
})
|
||||
}
|
||||
if car.WofExpiry != nil {
|
||||
views = append(views, models.ReminderView{
|
||||
CarID: car.ID, CarRego: car.Rego, ReminderType: "wof",
|
||||
DueDate: car.WofExpiry, Status: statusFor(car.WofExpiry, nil, nil, todayDate),
|
||||
})
|
||||
}
|
||||
|
||||
if car.ServiceIntervalKM != nil || car.ServiceIntervalMonths != nil {
|
||||
var last models.ServiceEntry
|
||||
err := h.dbGet(ctx, &last, `
|
||||
SELECT * FROM service_entries
|
||||
WHERE car_id = ? AND is_service = ?
|
||||
ORDER BY entry_date DESC, created_at DESC
|
||||
LIMIT 1
|
||||
`, car.ID, true)
|
||||
if err == nil {
|
||||
var dueDate *time.Time
|
||||
if car.ServiceIntervalMonths != nil {
|
||||
d := last.EntryDate.AddDate(0, *car.ServiceIntervalMonths, 0)
|
||||
dueDate = &d
|
||||
}
|
||||
var dueOdometer *int
|
||||
if car.ServiceIntervalKM != nil && last.Odometer != nil {
|
||||
o := *last.Odometer + *car.ServiceIntervalKM
|
||||
dueOdometer = &o
|
||||
}
|
||||
if dueDate != nil || dueOdometer != nil {
|
||||
views = append(views, models.ReminderView{
|
||||
CarID: car.ID, CarRego: car.Rego, ReminderType: "service",
|
||||
DueDate: dueDate, DueOdometer: dueOdometer,
|
||||
Status: statusFor(dueDate, dueOdometer, car.Odometer, todayDate),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return views
|
||||
}
|
||||
|
||||
// sortReminderViews orders overdue-first, then by due date (nulls last),
|
||||
// then by due odometer (nulls last), with completed items always last.
|
||||
func sortReminderViews(views []models.ReminderView) {
|
||||
rank := func(v models.ReminderView) int {
|
||||
switch v.Status {
|
||||
case "overdue":
|
||||
return 0
|
||||
case "upcoming":
|
||||
return 1
|
||||
case "future":
|
||||
return 2
|
||||
default: // "done"
|
||||
return 3
|
||||
}
|
||||
}
|
||||
sort.SliceStable(views, func(i, j int) bool {
|
||||
a, b := views[i], views[j]
|
||||
if ra, rb := rank(a), rank(b); ra != rb {
|
||||
return ra < rb
|
||||
}
|
||||
switch {
|
||||
case a.DueDate == nil && b.DueDate != nil:
|
||||
return false
|
||||
case a.DueDate != nil && b.DueDate == nil:
|
||||
return true
|
||||
case a.DueDate != nil && b.DueDate != nil && !a.DueDate.Equal(*b.DueDate):
|
||||
return a.DueDate.Before(*b.DueDate)
|
||||
}
|
||||
switch {
|
||||
case a.DueOdometer == nil && b.DueOdometer != nil:
|
||||
return false
|
||||
case a.DueOdometer != nil && b.DueOdometer == nil:
|
||||
return true
|
||||
case a.DueOdometer != nil && b.DueOdometer != nil:
|
||||
return *a.DueOdometer < *b.DueOdometer
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"vlog/internal/auth"
|
||||
"vlog/internal/models"
|
||||
)
|
||||
|
||||
var validReminderTypes = map[string]bool{
|
||||
"service": true,
|
||||
"wheel_rotation": true,
|
||||
"alignment": true,
|
||||
"custom": true,
|
||||
}
|
||||
|
||||
// ListReminders returns a car's reminders — real ones (service/custom/etc,
|
||||
// completed ones hidden unless ?completed=1) plus rego/WoF/next-service-due
|
||||
// synthesized from the car's own fields, all in one unified list.
|
||||
func (h *Handlers) ListReminders(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
includeCompleted := r.URL.Query().Get("completed") == "1"
|
||||
todayDate := today()
|
||||
|
||||
query := `SELECT * FROM reminders WHERE car_id = ?`
|
||||
if !includeCompleted {
|
||||
query += ` AND completed_at IS NULL`
|
||||
}
|
||||
var reminders []models.Reminder
|
||||
if err := h.dbSelect(r.Context(), &reminders, query, car.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list reminders")
|
||||
return
|
||||
}
|
||||
|
||||
views := make([]models.ReminderView, 0, len(reminders))
|
||||
for _, rem := range reminders {
|
||||
views = append(views, reminderToView(rem, car.Rego, car.Odometer, todayDate))
|
||||
}
|
||||
views = append(views, synthesizedReminders(r.Context(), h, car, todayDate)...)
|
||||
sortReminderViews(views)
|
||||
|
||||
writeJSON(w, http.StatusOK, views)
|
||||
}
|
||||
|
||||
// CreateReminder adds a reminder to a car — either a built-in type (service,
|
||||
// wheel_rotation, alignment) or a fully custom one with its own label.
|
||||
func (h *Handlers) CreateReminder(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
in, ok := h.decodeReminderInput(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
dueDate, err := parseOptionalDate(in.DueDate)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid dueDate")
|
||||
return
|
||||
}
|
||||
|
||||
var reminder models.Reminder
|
||||
err = h.dbGet(r.Context(), &reminder, `
|
||||
INSERT INTO reminders (id, car_id, reminder_type, label, due_date, due_odometer, notes)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
RETURNING *
|
||||
`, uuid.New().String(), car.ID, in.ReminderType, in.Label, dueDate, in.DueOdometer, in.Notes)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to create reminder")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, reminder)
|
||||
}
|
||||
|
||||
// UpdateReminder edits a reminder's fields, or marks/unmarks it complete
|
||||
// (send completed: true/false in the body).
|
||||
func (h *Handlers) UpdateReminder(w http.ResponseWriter, r *http.Request) {
|
||||
reminder, ok := h.loadOwnedReminder(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
models.ReminderInput
|
||||
Completed *bool `json:"completed"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
// Marking complete/incomplete is a lightweight partial update that
|
||||
// doesn't require the other fields to be present.
|
||||
if body.Completed != nil && body.ReminderType == "" {
|
||||
var updated models.Reminder
|
||||
var err error
|
||||
if *body.Completed {
|
||||
err = h.dbGet(r.Context(), &updated, `
|
||||
UPDATE reminders SET completed_at = CURRENT_TIMESTAMP WHERE id = ? RETURNING *
|
||||
`, reminder.ID)
|
||||
} else {
|
||||
err = h.dbGet(r.Context(), &updated, `
|
||||
UPDATE reminders SET completed_at = NULL WHERE id = ? RETURNING *
|
||||
`, reminder.ID)
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to update reminder")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, updated)
|
||||
return
|
||||
}
|
||||
|
||||
if !validateReminderFields(w, body.ReminderInput) {
|
||||
return
|
||||
}
|
||||
dueDate, err := parseOptionalDate(body.DueDate)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid dueDate")
|
||||
return
|
||||
}
|
||||
|
||||
var updated models.Reminder
|
||||
err = h.dbGet(r.Context(), &updated, `
|
||||
UPDATE reminders
|
||||
SET reminder_type = ?, label = ?, due_date = ?, due_odometer = ?, notes = ?
|
||||
WHERE id = ?
|
||||
RETURNING *
|
||||
`, body.ReminderType, body.Label, dueDate, body.DueOdometer, body.Notes, reminder.ID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to update reminder")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, updated)
|
||||
}
|
||||
|
||||
// DeleteReminder removes a reminder.
|
||||
func (h *Handlers) DeleteReminder(w http.ResponseWriter, r *http.Request) {
|
||||
reminder, ok := h.loadOwnedReminder(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := h.dbExec(r.Context(), `DELETE FROM reminders WHERE id = ?`, reminder.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to delete reminder")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (h *Handlers) decodeReminderInput(w http.ResponseWriter, r *http.Request) (models.ReminderInput, bool) {
|
||||
var in models.ReminderInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return in, false
|
||||
}
|
||||
if !validateReminderFields(w, in) {
|
||||
return in, false
|
||||
}
|
||||
return in, true
|
||||
}
|
||||
|
||||
func validateReminderFields(w http.ResponseWriter, in models.ReminderInput) bool {
|
||||
if !validReminderTypes[in.ReminderType] {
|
||||
writeError(w, http.StatusBadRequest, "reminderType must be one of service, wheel_rotation, alignment, custom")
|
||||
return false
|
||||
}
|
||||
if in.ReminderType == "custom" && (in.Label == nil || *in.Label == "") {
|
||||
writeError(w, http.StatusBadRequest, "label is required for custom reminders")
|
||||
return false
|
||||
}
|
||||
if (in.DueDate == nil || *in.DueDate == "") && in.DueOdometer == nil {
|
||||
writeError(w, http.StatusBadRequest, "either dueDate or dueOdometer is required")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *Handlers) loadOwnedReminder(w http.ResponseWriter, r *http.Request) (*models.Reminder, bool) {
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
reminderID := r.PathValue("reminderId")
|
||||
|
||||
var reminder models.Reminder
|
||||
err := h.dbGet(r.Context(), &reminder, `
|
||||
SELECT rm.*
|
||||
FROM reminders rm
|
||||
JOIN cars c ON c.id = rm.car_id
|
||||
WHERE rm.id = ? AND c.user_id = ?
|
||||
`, reminderID, userID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "reminder not found")
|
||||
return nil, false
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load reminder")
|
||||
return nil, false
|
||||
}
|
||||
return &reminder, true
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"vlog/internal/auth"
|
||||
"vlog/internal/models"
|
||||
"vlog/internal/storage"
|
||||
)
|
||||
|
||||
// ServiceEntryWithFiles is the shape returned to the frontend: an entry plus
|
||||
// its attachments, so the timeline can render everything in one fetch.
|
||||
type ServiceEntryWithFiles struct {
|
||||
models.ServiceEntry
|
||||
Files []models.ServiceEntryFile `json:"files"`
|
||||
}
|
||||
|
||||
// ListServiceEntries returns one page of a car's service history, newest
|
||||
// first — the "timeline" is just this list rendered chronologically,
|
||||
// nothing fancier. Paginated (?limit=&offset=) so a long history doesn't
|
||||
// mean dumping thousands of rows into a single response/DOM.
|
||||
func (h *Handlers) ListServiceEntries(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, offset := parsePagination(r)
|
||||
|
||||
var entries []models.ServiceEntry
|
||||
err := h.dbSelect(r.Context(), &entries, `
|
||||
SELECT * FROM service_entries WHERE car_id = ?
|
||||
ORDER BY entry_date DESC, created_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`, car.ID, limit+1, offset)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list service entries")
|
||||
return
|
||||
}
|
||||
|
||||
entries, hasMore := paginate(limit, entries)
|
||||
writeJSON(w, http.StatusOK, page[ServiceEntryWithFiles]{
|
||||
Items: h.attachFiles(r, entries),
|
||||
HasMore: hasMore,
|
||||
})
|
||||
}
|
||||
|
||||
// attachFiles batches a single query for all files belonging to entries,
|
||||
// rather than one query per entry.
|
||||
func (h *Handlers) attachFiles(r *http.Request, entries []models.ServiceEntry) []ServiceEntryWithFiles {
|
||||
result := make([]ServiceEntryWithFiles, len(entries))
|
||||
ids := make([]string, len(entries))
|
||||
for i, e := range entries {
|
||||
result[i] = ServiceEntryWithFiles{ServiceEntry: e, Files: []models.ServiceEntryFile{}}
|
||||
ids[i] = e.ID
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return result
|
||||
}
|
||||
|
||||
// sqlx.In expands the slice into the right number of "?" placeholders;
|
||||
// Rebind then adapts those for whichever driver is actually connected.
|
||||
query, args, err := sqlx.In(`SELECT * FROM service_entry_files WHERE service_entry_id IN (?) ORDER BY created_at`, ids)
|
||||
if err != nil {
|
||||
return result // best-effort: entries without file metadata beats a 500
|
||||
}
|
||||
|
||||
var files []models.ServiceEntryFile
|
||||
if err := h.dbSelect(r.Context(), &files, query, args...); err != nil {
|
||||
return result
|
||||
}
|
||||
|
||||
byEntry := make(map[string][]models.ServiceEntryFile, len(ids))
|
||||
for _, f := range files {
|
||||
byEntry[f.ServiceEntryID] = append(byEntry[f.ServiceEntryID], f)
|
||||
}
|
||||
for i := range result {
|
||||
if fs, ok := byEntry[result[i].ID]; ok {
|
||||
result[i].Files = fs
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// CreateServiceEntry adds a new history entry to a car.
|
||||
func (h *Handlers) CreateServiceEntry(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var in models.ServiceEntryInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if in.EntryType == "" {
|
||||
writeError(w, http.StatusBadRequest, "entryType is required")
|
||||
return
|
||||
}
|
||||
entryDate, err := time.Parse(dateLayout, in.EntryDate)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid entryDate")
|
||||
return
|
||||
}
|
||||
|
||||
var entry models.ServiceEntry
|
||||
err = h.dbGet(r.Context(), &entry, `
|
||||
INSERT INTO service_entries (id, car_id, entry_date, entry_type, description, performed_at, odometer, is_service)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
RETURNING *
|
||||
`, uuid.New().String(), car.ID, entryDate, in.EntryType, in.Description, in.PerformedAt, in.Odometer, in.IsService)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to create service entry")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, ServiceEntryWithFiles{ServiceEntry: entry, Files: []models.ServiceEntryFile{}})
|
||||
}
|
||||
|
||||
// GetServiceEntry returns one entry with its attachments.
|
||||
func (h *Handlers) GetServiceEntry(w http.ResponseWriter, r *http.Request) {
|
||||
entry, ok := h.loadOwnedServiceEntry(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
result := h.attachFiles(r, []models.ServiceEntry{*entry})
|
||||
writeJSON(w, http.StatusOK, result[0])
|
||||
}
|
||||
|
||||
// UpdateServiceEntry edits an entry's fields.
|
||||
func (h *Handlers) UpdateServiceEntry(w http.ResponseWriter, r *http.Request) {
|
||||
entry, ok := h.loadOwnedServiceEntry(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var in models.ServiceEntryInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if in.EntryType == "" {
|
||||
writeError(w, http.StatusBadRequest, "entryType is required")
|
||||
return
|
||||
}
|
||||
entryDate, err := time.Parse(dateLayout, in.EntryDate)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid entryDate")
|
||||
return
|
||||
}
|
||||
|
||||
var updated models.ServiceEntry
|
||||
err = h.dbGet(r.Context(), &updated, `
|
||||
UPDATE service_entries
|
||||
SET entry_date = ?, entry_type = ?, description = ?, performed_at = ?, odometer = ?, is_service = ?
|
||||
WHERE id = ?
|
||||
RETURNING *
|
||||
`, entryDate, in.EntryType, in.Description, in.PerformedAt, in.Odometer, in.IsService, entry.ID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to update service entry")
|
||||
return
|
||||
}
|
||||
|
||||
result := h.attachFiles(r, []models.ServiceEntry{updated})
|
||||
writeJSON(w, http.StatusOK, result[0])
|
||||
}
|
||||
|
||||
// DeleteServiceEntry removes an entry (DB cascades to its files; storage
|
||||
// cleanup of each attached file is best-effort).
|
||||
func (h *Handlers) DeleteServiceEntry(w http.ResponseWriter, r *http.Request) {
|
||||
entry, ok := h.loadOwnedServiceEntry(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var files []models.ServiceEntryFile
|
||||
_ = h.dbSelect(r.Context(), &files, `SELECT * FROM service_entry_files WHERE service_entry_id = ?`, entry.ID)
|
||||
|
||||
if _, err := h.dbExec(r.Context(), `DELETE FROM service_entries WHERE id = ?`, entry.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to delete service entry")
|
||||
return
|
||||
}
|
||||
|
||||
for _, f := range files {
|
||||
_ = h.Storage.Delete(r.Context(), f.S3Key)
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
// UploadServiceEntryFile attaches one PNG/PDF file to an entry. Call once
|
||||
// per file for multi-file uploads.
|
||||
func (h *Handlers) UploadServiceEntryFile(w http.ResponseWriter, r *http.Request) {
|
||||
entry, ok := h.loadOwnedServiceEntry(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
file, contentType, ok := parseUploadedFile(w, r, 15<<20, storage.AllowedAttachmentTypes)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
_, header, _ := r.FormFile("file")
|
||||
originalName := "attachment"
|
||||
if header != nil {
|
||||
originalName = sanitizeFileName(header.Filename)
|
||||
}
|
||||
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
key := fmt.Sprintf("users/%s/cars/%s/service/%s/%s-%s",
|
||||
userID, entry.CarID, entry.ID, randomID(), originalName)
|
||||
|
||||
var sizeBytes int64
|
||||
if header != nil {
|
||||
sizeBytes = header.Size
|
||||
}
|
||||
|
||||
if err := h.Storage.Upload(r.Context(), key, contentType, file); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to upload file")
|
||||
return
|
||||
}
|
||||
|
||||
var saved models.ServiceEntryFile
|
||||
err := h.dbGet(r.Context(), &saved, `
|
||||
INSERT INTO service_entry_files (id, service_entry_id, s3_key, file_name, content_type, size_bytes)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
RETURNING *
|
||||
`, uuid.New().String(), entry.ID, key, originalName, contentType, sizeBytes)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to save file reference")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, saved)
|
||||
}
|
||||
|
||||
func (h *Handlers) loadOwnedServiceEntry(w http.ResponseWriter, r *http.Request) (*models.ServiceEntry, bool) {
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
entryID := r.PathValue("entryId")
|
||||
|
||||
var entry models.ServiceEntry
|
||||
err := h.dbGet(r.Context(), &entry, `
|
||||
SELECT se.*
|
||||
FROM service_entries se
|
||||
JOIN cars c ON c.id = se.car_id
|
||||
WHERE se.id = ? AND c.user_id = ?
|
||||
`, entryID, userID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "service entry not found")
|
||||
return nil, false
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load service entry")
|
||||
return nil, false
|
||||
}
|
||||
return &entry, true
|
||||
}
|
||||
Reference in new issue
Block a user