Cars: arrange the garage, and choose what a car's page shows
Three things you can now set up rather than live with.
The garage takes a drag: cards reorder as you drag across them and the
arrangement saves on drop — or on dragend, since a card released in the
gap between cards never produces a drop and would otherwise revert on
the next load. It is a per-user list of car ids on the profile, so it
covers cars shared with you and never reorders anybody else's garage;
the API returns /api/cars in that order, so a client only sends the new
one back. Pointer-only: touch browsers don't fire the native drag
events, and this is not worth a dependency.
A car's page is now configurable from the gear in its header: which tabs
it shows, and which of the 14 Information rows. Both belong to the car,
so everyone it is shared with sees the same page — Fuel off on an EV
stays off for all of them — and setting them needs write access. Stored
as the hidden sets, so anything added in a later release is on by
default. PUT /api/cars/{id}/view is its own endpoint precisely so an
ordinary save of the car form, which sends every other field, can never
reveal something that was deliberately switched off. Information itself
can't be hidden: a page with no tabs left would be a dead end.
The connected-service cards fold away, remembered per device, so a
provider that reports eight sections can be trimmed to the two worth
watching. A failed section keeps a short badge in its collapsed header
and puts the provider's own message — a few hundred characters of JSON,
which used to stretch the page sideways — inside the body with
everything else.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
e373497958
commit
049da69c83
@@ -147,7 +147,8 @@ GET /api/auth/validate
|
||||
GET /api/auth/me
|
||||
GET /api/identity
|
||||
|
||||
# current user (profile / appearance / avatar / data / account lifecycle)
|
||||
# current user (profile / appearance / garage order / avatar / data /
|
||||
# account lifecycle)
|
||||
GET /api/me PATCH /api/me DELETE /api/me
|
||||
POST /api/me/password
|
||||
POST /api/me/avatar GET /api/me/avatar DELETE /api/me/avatar
|
||||
@@ -186,9 +187,11 @@ GET /api/vehicle-providers
|
||||
GET /api/vehicle-providers/{provider}/vehicles
|
||||
POST /api/vehicle-providers/{provider}/import
|
||||
|
||||
# cars + sharing
|
||||
# cars + sharing (GET /api/cars returns the garage in the user's saved order,
|
||||
# which PATCH /api/me {carOrder} sets)
|
||||
GET /api/cars POST /api/cars
|
||||
GET /api/cars/{id} PATCH /api/cars/{id} DELETE /api/cars/{id}
|
||||
PUT /api/cars/{id}/view # which tabs + Information rows this car shows
|
||||
GET /api/cars/{id}/provider POST /api/cars/{id}/provider
|
||||
POST /api/cars/{id}/provider/sync
|
||||
GET /api/cars/{id}/service-records GET /api/cars/{id}/technical-checks
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"drivervault/apiserver/internal/models"
|
||||
)
|
||||
|
||||
// The garage arrangement is a per-user list of car ids, so it has to cope with
|
||||
// lists that no longer line up with the cars the user actually has: a car sold
|
||||
// since the last drag leaves a stale id, a car added or shared since leaves an
|
||||
// id missing. These cover both directions plus the input cleaning.
|
||||
|
||||
func ids(cars []models.Car) []string {
|
||||
out := make([]string, len(cars))
|
||||
for i, c := range cars {
|
||||
out[i] = c.ID
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func carsWithIDs(list ...string) []models.Car {
|
||||
out := make([]models.Car, len(list))
|
||||
for i, id := range list {
|
||||
out[i] = models.Car{ID: id}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestApplyCarOrder(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
cars []string
|
||||
order []string
|
||||
want []string
|
||||
}{
|
||||
{"arranged", []string{"a", "b", "c"}, []string{"c", "a", "b"}, []string{"c", "a", "b"}},
|
||||
{"no arrangement keeps default order", []string{"a", "b", "c"}, nil, []string{"a", "b", "c"}},
|
||||
{
|
||||
// A car added or shared since the last drag isn't in the list; it
|
||||
// belongs at the end rather than jumping into the middle.
|
||||
"unarranged cars go last in their existing order",
|
||||
[]string{"a", "b", "new1", "new2"}, []string{"b", "a"},
|
||||
[]string{"b", "a", "new1", "new2"},
|
||||
},
|
||||
{
|
||||
// A car that was sold since the last drag just drops out.
|
||||
"stale ids are ignored",
|
||||
[]string{"a", "b"}, []string{"gone", "b", "a"},
|
||||
[]string{"b", "a"},
|
||||
},
|
||||
{"single car is untouched", []string{"a"}, []string{"b", "a"}, []string{"a"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cars := carsWithIDs(tc.cars...)
|
||||
applyCarOrder(cars, tc.order)
|
||||
got := ids(cars)
|
||||
if len(got) != len(tc.want) {
|
||||
t.Fatalf("order = %v, want %v", got, tc.want)
|
||||
}
|
||||
for i := range got {
|
||||
if got[i] != tc.want[i] {
|
||||
t.Fatalf("order = %v, want %v", got, tc.want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCarOrder(t *testing.T) {
|
||||
got, err := normalizeCarOrder([]string{" a ", "", "b", "a", " ", "c"})
|
||||
if err != nil {
|
||||
t.Fatalf("normalizeCarOrder: %v", err)
|
||||
}
|
||||
want := []string{"a", "b", "c"} // trimmed, blanks dropped, first "a" wins
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("normalized = %v, want %v", got, want)
|
||||
}
|
||||
for i := range got {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("normalized = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
tooLong := make([]string, maxCarOrder+1)
|
||||
for i := range tooLong {
|
||||
tooLong[i] = "c"
|
||||
}
|
||||
if _, err := normalizeCarOrder(tooLong); err == nil {
|
||||
t.Error("normalizeCarOrder accepted a list over the cap, want an error")
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"drivervault/apiserver/internal/models"
|
||||
)
|
||||
@@ -136,9 +138,41 @@ func (s *Server) listCars(w http.ResponseWriter, r *http.Request) {
|
||||
out = append(out, m)
|
||||
}
|
||||
|
||||
// Hand the garage back in the order the user arranged it. Best effort: if the
|
||||
// profile can't be read, the default order (owned by name, then shared) still
|
||||
// renders a usable garage.
|
||||
if rec, err := s.fetchUser(r, me); err == nil {
|
||||
applyCarOrder(out, rec.carOrder())
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// applyCarOrder sorts cars into the user's arranged order, in place. Cars the
|
||||
// arrangement doesn't mention — a car added or shared since the last drag — keep
|
||||
// their relative order and follow the arranged ones, so a new car shows up at
|
||||
// the end rather than jumping into the middle.
|
||||
func applyCarOrder(cars []models.Car, order []string) {
|
||||
if len(order) == 0 || len(cars) < 2 {
|
||||
return
|
||||
}
|
||||
rank := make(map[string]int, len(order))
|
||||
for i, id := range order {
|
||||
rank[id] = i
|
||||
}
|
||||
sort.SliceStable(cars, func(i, j int) bool {
|
||||
ri, oki := rank[cars[i].ID]
|
||||
rj, okj := rank[cars[j].ID]
|
||||
if oki != okj {
|
||||
return oki // an arranged car sorts before an unarranged one
|
||||
}
|
||||
if !oki {
|
||||
return false // both unarranged: leave them as they are
|
||||
}
|
||||
return ri < rj
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) getCar(w http.ResponseWriter, r *http.Request) {
|
||||
level, rec, err := s.carAccessLevel(r.Context(), s.currentUserID(r), r.PathValue("id"))
|
||||
if err != nil {
|
||||
@@ -206,6 +240,103 @@ func (s *Server) updateCar(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, m)
|
||||
}
|
||||
|
||||
// hideableCarTabs are the car-detail tabs that can be switched off. "info" is
|
||||
// deliberately absent: it is the car itself, and a page with no tabs left would
|
||||
// be a dead end.
|
||||
var hideableCarTabs = map[string]bool{
|
||||
"provider": true, "services": true, "technical": true, "maintenance": true,
|
||||
"fuel": true, "documents": true, "parts": true, "reminders": true,
|
||||
}
|
||||
|
||||
// hideableCarFields are the Information rows that can be switched off — every
|
||||
// one of them, since unlike the tabs there is no row the page needs to keep.
|
||||
// Mirrors the car.info.* labels the web app renders.
|
||||
var hideableCarFields = map[string]bool{
|
||||
"oilSpec": true, "transmissionOil": true, "differentialOil": true,
|
||||
"brakeFluid": true, "coolant": true, "odometer": true, "serviceInterval": true,
|
||||
"nextDue": true, "registrationPlate": true, "registrationCountry": true,
|
||||
"vin": true, "fuelType": true, "buildDate": true, "firstRegistration": true,
|
||||
}
|
||||
|
||||
// normalizeHidden validates a switched-off set against the keys that exist.
|
||||
// Unknown keys are rejected rather than ignored: they can only come from a stale
|
||||
// or wrong client, and dropping them silently would hide the mistake while the
|
||||
// tab or field stayed visible.
|
||||
func normalizeHidden(in []string, allowed map[string]bool, what string) ([]string, error) {
|
||||
out := make([]string, 0, len(in))
|
||||
seen := make(map[string]bool, len(in))
|
||||
for _, key := range in {
|
||||
key = strings.TrimSpace(key)
|
||||
if key == "" || seen[key] {
|
||||
continue
|
||||
}
|
||||
if !allowed[key] {
|
||||
return nil, fmt.Errorf("%q is not a car %s that can be hidden", key, what)
|
||||
}
|
||||
seen[key] = true
|
||||
out = append(out, key)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// PUT /api/cars/{id}/view — choose what this car's page shows: which tabs, and
|
||||
// which rows of the Information tab. Body: {hiddenTabs?: [...], hiddenFields?:
|
||||
// [...]}; only the sets present are written, so a client can update one without
|
||||
// knowing the other. Its own endpoint rather than fields on the car edit, so an
|
||||
// ordinary save of the car form — which sends every other field — can never
|
||||
// reveal something somebody deliberately switched off. Needs write access: the
|
||||
// choice belongs to the car, so it is the same permission as editing it.
|
||||
func (s *Server) updateCarView(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
HiddenTabs *[]string `json:"hiddenTabs"`
|
||||
HiddenFields *[]string `json:"hiddenFields"`
|
||||
}
|
||||
if err := decodeJSON(r, &in); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
level, _, err := s.carAccessLevel(r.Context(), s.currentUserID(r), r.PathValue("id"))
|
||||
if err != nil {
|
||||
writePBError(w, err)
|
||||
return
|
||||
}
|
||||
if !canWrite(level) {
|
||||
writeError(w, http.StatusForbidden, "you cannot edit this car")
|
||||
return
|
||||
}
|
||||
|
||||
payload := map[string]any{}
|
||||
if in.HiddenTabs != nil {
|
||||
tabs, err := normalizeHidden(*in.HiddenTabs, hideableCarTabs, "tab")
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
payload["hidden_tabs"] = tabs
|
||||
}
|
||||
if in.HiddenFields != nil {
|
||||
fields, err := normalizeHidden(*in.HiddenFields, hideableCarFields, "field")
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
payload["hidden_fields"] = fields
|
||||
}
|
||||
if len(payload) == 0 {
|
||||
writeError(w, http.StatusBadRequest, "no changes provided")
|
||||
return
|
||||
}
|
||||
|
||||
var rec carRecord
|
||||
if err := s.pb.Update(r.Context(), colCars, r.PathValue("id"), payload, &rec); err != nil {
|
||||
writePBError(w, err)
|
||||
return
|
||||
}
|
||||
m := rec.toModel()
|
||||
m.Access = level
|
||||
writeJSON(w, http.StatusOK, m)
|
||||
}
|
||||
|
||||
func (s *Server) deleteCar(w http.ResponseWriter, r *http.Request) {
|
||||
level, _, err := s.carAccessLevel(r.Context(), s.currentUserID(r), r.PathValue("id"))
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package api
|
||||
|
||||
import "testing"
|
||||
|
||||
// What a car's page shows — which tabs, and which rows of the Information tab —
|
||||
// is stored on the car as the hidden sets, so the validation has to keep those
|
||||
// sets to keys the page actually renders. Information itself stays out of the
|
||||
// hideable tabs: a car with no tabs left would be a dead end.
|
||||
|
||||
func TestNormalizeHiddenTabs(t *testing.T) {
|
||||
got, err := normalizeHidden([]string{" fuel ", "parts", "fuel", ""}, hideableCarTabs, "tab")
|
||||
if err != nil {
|
||||
t.Fatalf("normalizeHidden: %v", err)
|
||||
}
|
||||
want := []string{"fuel", "parts"} // trimmed, blanks dropped, deduped
|
||||
assertKeys(t, got, want)
|
||||
|
||||
// Clearing the list is how a car goes back to showing everything.
|
||||
if empty, err := normalizeHidden(nil, hideableCarTabs, "tab"); err != nil || len(empty) != 0 {
|
||||
t.Errorf("normalizeHidden(nil) = %v, %v; want empty and no error", empty, err)
|
||||
}
|
||||
|
||||
// Information is the car itself; hiding it would leave a page with no tabs.
|
||||
if _, err := normalizeHidden([]string{"info"}, hideableCarTabs, "tab"); err == nil {
|
||||
t.Error("normalizeHidden allowed hiding the info tab, want an error")
|
||||
}
|
||||
// A key from a stale or wrong client is an error, not something to drop
|
||||
// quietly while the tab stays visible.
|
||||
if _, err := normalizeHidden([]string{"fuel", "nonsense"}, hideableCarTabs, "tab"); err == nil {
|
||||
t.Error("normalizeHidden accepted an unknown tab, want an error")
|
||||
}
|
||||
|
||||
// The hideable set is the contract the web app's HIDEABLE_TABS mirrors:
|
||||
// every tab the car page renders beside Information.
|
||||
for _, key := range []string{"provider", "services", "technical", "maintenance", "fuel", "documents", "parts", "reminders"} {
|
||||
if !hideableCarTabs[key] {
|
||||
t.Errorf("tab %q should be hideable", key)
|
||||
}
|
||||
}
|
||||
if len(hideableCarTabs) != 8 {
|
||||
t.Errorf("hideableCarTabs has %d entries, want the 8 tabs beside Information", len(hideableCarTabs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeHiddenFields(t *testing.T) {
|
||||
got, err := normalizeHidden([]string{"vin", " differentialOil ", "vin"}, hideableCarFields, "field")
|
||||
if err != nil {
|
||||
t.Fatalf("normalizeHidden: %v", err)
|
||||
}
|
||||
assertKeys(t, got, []string{"vin", "differentialOil"})
|
||||
|
||||
if _, err := normalizeHidden([]string{"oilSpec", "nonsense"}, hideableCarFields, "field"); err == nil {
|
||||
t.Error("normalizeHidden accepted an unknown field, want an error")
|
||||
}
|
||||
// A tab key is not a field key — the two sets are validated separately.
|
||||
if _, err := normalizeHidden([]string{"fuel"}, hideableCarFields, "field"); err == nil {
|
||||
t.Error("normalizeHidden accepted a tab key as a field, want an error")
|
||||
}
|
||||
|
||||
// Every Information row the web app renders must be hideable; unlike the
|
||||
// tabs there is no row the page has to keep.
|
||||
for _, key := range []string{
|
||||
"oilSpec", "transmissionOil", "differentialOil", "brakeFluid", "coolant",
|
||||
"odometer", "serviceInterval", "nextDue", "registrationPlate",
|
||||
"registrationCountry", "vin", "fuelType", "buildDate", "firstRegistration",
|
||||
} {
|
||||
if !hideableCarFields[key] {
|
||||
t.Errorf("field %q should be hideable", key)
|
||||
}
|
||||
}
|
||||
if len(hideableCarFields) != 14 {
|
||||
t.Errorf("hideableCarFields has %d entries, want the 14 Information rows", len(hideableCarFields))
|
||||
}
|
||||
}
|
||||
|
||||
func assertKeys(t *testing.T, got, want []string) {
|
||||
t.Helper()
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("keys = %v, want %v", got, want)
|
||||
}
|
||||
for i := range got {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("keys = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,28 @@ type userRecord struct {
|
||||
Role string `json:"role"`
|
||||
Organization string `json:"organization"`
|
||||
Created string `json:"created"`
|
||||
|
||||
// Garage arrangement. Raw because PocketBase hands back whatever a json field
|
||||
// holds — null on a record that has never been arranged, and "" on one
|
||||
// PocketBase stored as an empty value — neither of which is a []string.
|
||||
CarOrder json.RawMessage `json:"car_order"`
|
||||
}
|
||||
|
||||
// carOrder decodes the stored garage arrangement, treating anything unexpected
|
||||
// as "not arranged yet" rather than failing the whole profile read.
|
||||
func (rec userRecord) carOrder() []string { return decodeStringList(rec.CarOrder) }
|
||||
|
||||
// decodeStringList reads a PocketBase json field that holds a list of strings,
|
||||
// treating anything unexpected as empty rather than failing the whole read.
|
||||
func decodeStringList(raw json.RawMessage) []string {
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
var out []string
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (rec userRecord) toModel() models.User {
|
||||
@@ -54,6 +76,7 @@ func (rec userRecord) toModel() models.User {
|
||||
Created: rec.Created,
|
||||
|
||||
Organization: rec.Organization,
|
||||
CarOrder: rec.carOrder(),
|
||||
}
|
||||
if t := parsePBDate(rec.DeletionRequestedAt); !t.IsZero() {
|
||||
u.DeletionRequestedAt = &t
|
||||
@@ -102,13 +125,41 @@ func (s *Server) handleGetMe(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
type updateMeRequest struct {
|
||||
Name *string `json:"name"`
|
||||
Bio *string `json:"bio"`
|
||||
Theme *string `json:"theme"`
|
||||
Locale *string `json:"locale"`
|
||||
DateFormat *string `json:"dateFormat"`
|
||||
Currency *string `json:"currency"`
|
||||
FontSize *string `json:"fontSize"`
|
||||
Name *string `json:"name"`
|
||||
Bio *string `json:"bio"`
|
||||
Theme *string `json:"theme"`
|
||||
Locale *string `json:"locale"`
|
||||
DateFormat *string `json:"dateFormat"`
|
||||
Currency *string `json:"currency"`
|
||||
FontSize *string `json:"fontSize"`
|
||||
CarOrder *[]string `json:"carOrder"`
|
||||
}
|
||||
|
||||
// maxCarOrder bounds the stored arrangement. listCars fetches at most 200 owned
|
||||
// plus 200 shared cars, so this leaves room without letting a client park an
|
||||
// unbounded blob on the record.
|
||||
const maxCarOrder = 500
|
||||
|
||||
// normalizeCarOrder cleans a client-supplied garage arrangement: blanks out,
|
||||
// duplicates dropped (first position wins), length capped. The ids are not
|
||||
// checked against real cars — that would cost a lookup per entry, and an id for
|
||||
// a car the user no longer has is harmless: listCars ignores what it can't
|
||||
// match, and the next drag rewrites the list anyway.
|
||||
func normalizeCarOrder(in []string) ([]string, error) {
|
||||
if len(in) > maxCarOrder {
|
||||
return nil, fmt.Errorf("carOrder is too long (max %d)", maxCarOrder)
|
||||
}
|
||||
out := make([]string, 0, len(in))
|
||||
seen := make(map[string]bool, len(in))
|
||||
for _, id := range in {
|
||||
id = strings.TrimSpace(id)
|
||||
if id == "" || seen[id] {
|
||||
continue
|
||||
}
|
||||
seen[id] = true
|
||||
out = append(out, id)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
var validThemes = map[string]bool{"light": true, "dark": true, "system": true}
|
||||
@@ -189,6 +240,14 @@ func (s *Server) handleUpdateMe(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
payload["font_size"] = *in.FontSize
|
||||
}
|
||||
if in.CarOrder != nil {
|
||||
ids, err := normalizeCarOrder(*in.CarOrder)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
payload["car_order"] = ids
|
||||
}
|
||||
|
||||
var rec userRecord
|
||||
if err := s.pb.Update(r.Context(), s.usersCollection(), claims.ID, payload, &rec); err != nil {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -66,6 +67,12 @@ type carRecord struct {
|
||||
Owner string `json:"owner"`
|
||||
Created string `json:"created"`
|
||||
Updated string `json:"updated"`
|
||||
|
||||
// Switched-off tabs and Information fields. Raw because PocketBase hands back
|
||||
// whatever a json field holds — null on a car nobody has configured — which
|
||||
// is not a []string.
|
||||
HiddenTabs json.RawMessage `json:"hidden_tabs"`
|
||||
HiddenFields json.RawMessage `json:"hidden_fields"`
|
||||
}
|
||||
|
||||
func (rec carRecord) toModel() models.Car {
|
||||
@@ -92,6 +99,8 @@ func (rec carRecord) toModel() models.Car {
|
||||
FirstRegistrationDate: rec.FirstRegistrationDate,
|
||||
Provider: rec.Provider,
|
||||
ProviderVehicleID: rec.ProviderVehicleID,
|
||||
HiddenTabs: decodeStringList(rec.HiddenTabs),
|
||||
HiddenFields: decodeStringList(rec.HiddenFields),
|
||||
Owner: rec.Owner,
|
||||
Created: rec.Created,
|
||||
Updated: rec.Updated,
|
||||
|
||||
@@ -59,6 +59,7 @@
|
||||
// # cars, service records, parts, shares
|
||||
// GET /api/cars POST /api/cars
|
||||
// GET /api/cars/{id} PATCH /api/cars/{id} DELETE /api/cars/{id}
|
||||
// PUT /api/cars/{id}/view
|
||||
// GET /api/cars/{id}/provider POST /api/cars/{id}/provider
|
||||
// POST /api/cars/{id}/provider/sync
|
||||
// GET /api/cars/{id}/service-records
|
||||
@@ -352,6 +353,7 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("POST /api/cars", s.createCar)
|
||||
mux.HandleFunc("GET /api/cars/{id}", s.getCar)
|
||||
mux.HandleFunc("PATCH /api/cars/{id}", s.updateCar)
|
||||
mux.HandleFunc("PUT /api/cars/{id}/view", s.updateCarView)
|
||||
mux.HandleFunc("DELETE /api/cars/{id}", s.deleteCar)
|
||||
mux.HandleFunc("GET /api/cars/{id}/service-records", s.listCarServiceRecords)
|
||||
mux.HandleFunc("GET /api/cars/{id}/technical-checks", s.listCarTechnicalChecks)
|
||||
|
||||
@@ -39,6 +39,13 @@ var collectionsSchema = map[string][]fieldDef{
|
||||
// internal/api/vehicleproviders.go. Blank for a hand-entered car.
|
||||
fText("provider", false),
|
||||
fText("provider_vehicle_id", false),
|
||||
// What this car's page shows: the tabs switched off (["fuel"] on an EV)
|
||||
// and the Information fields switched off (["differentialOil"] on a car
|
||||
// without one). Properties of the car, so everyone it is shared with sees
|
||||
// the same page. Stored as the hidden sets, so anything added in a later
|
||||
// release is on by default. Keys are validated in internal/api/cars.go.
|
||||
fJSON("hidden_tabs", 2000),
|
||||
fJSON("hidden_fields", 2000),
|
||||
// Owner of this car. Non-cascading: deleting a user must not wipe their cars.
|
||||
fRelation("owner", "users", false, false),
|
||||
},
|
||||
@@ -172,6 +179,10 @@ var collectionsSchema = map[string][]fieldDef{
|
||||
fRelation("organization", "organizations", false, false),
|
||||
// Per-user plugin/integration config (bottom layer of the cascade).
|
||||
fJSON("pluginSettings", 100000),
|
||||
// The garage order: car ids in the order this user arranged them. Per
|
||||
// user rather than per car, so it also covers cars shared with them and
|
||||
// never reorders somebody else's garage.
|
||||
fJSON("car_order", 20000),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -66,6 +66,15 @@ type Car struct {
|
||||
Provider string `json:"provider,omitempty"`
|
||||
ProviderVehicleID string `json:"providerVehicleId,omitempty"`
|
||||
|
||||
// HiddenTabs and HiddenFields are what this car's page does not show: tabs
|
||||
// (["fuel"] on an EV) and Information fields (["differentialOil"] on a car
|
||||
// without one). Properties of the car, so everyone it is shared with sees the
|
||||
// same page. The hidden sets, not the visible ones, so anything added in a
|
||||
// later release is on by default. Set through the view endpoint only, never by
|
||||
// an ordinary car edit, so saving the form cannot silently reveal them again.
|
||||
HiddenTabs []string `json:"hiddenTabs"`
|
||||
HiddenFields []string `json:"hiddenFields"`
|
||||
|
||||
// Owner is the user id that owns this car. Access is the requesting user's
|
||||
// permission on it — "owner", "write", or "read" — computed by the API at
|
||||
// read time and never persisted (omitempty; not part of the write payload).
|
||||
@@ -340,6 +349,11 @@ type User struct {
|
||||
Organization string `json:"organization"`
|
||||
OrganizationName string `json:"organizationName,omitempty"`
|
||||
|
||||
// CarOrder is the garage arrangement: car ids in the order this user dragged
|
||||
// them into. The car list is already returned in this order, so a client only
|
||||
// needs it to send an updated arrangement back.
|
||||
CarOrder []string `json:"carOrder"`
|
||||
|
||||
// Non-empty while an account-deletion request is pending its cooldown.
|
||||
DeletionRequestedAt *time.Time `json:"deletionRequestedAt,omitempty"`
|
||||
|
||||
|
||||
@@ -272,6 +272,13 @@ const DESIRED = {
|
||||
// or linked to a connected account; blank for a hand-entered car.
|
||||
F.text("provider"),
|
||||
F.text("provider_vehicle_id"),
|
||||
// What this car's page shows: the tabs switched off (["fuel"] on an EV) and
|
||||
// the Information rows switched off (["differentialOil"]). Properties of the
|
||||
// car, so everyone it is shared with sees the same page. The hidden sets,
|
||||
// not the visible ones, so anything added in a later release is on by
|
||||
// default. Keys are validated in internal/api/cars.go.
|
||||
F.json("hidden_tabs", 2000),
|
||||
F.json("hidden_fields", 2000),
|
||||
// Owner of this car. Non-cascading on purpose: deleting a user must not
|
||||
// wipe their cars (account deletion in me.go intentionally leaves cars).
|
||||
// required:false at the DB level — the API always sets owner on create and
|
||||
@@ -444,6 +451,10 @@ const DESIRED = {
|
||||
// { "<plugin>": { "config": {…}, "enabled": bool } }
|
||||
// The `enabled` flag is the personal opt-in; see internal/api/integrations.go.
|
||||
F.json("pluginSettings"),
|
||||
// The garage order: car ids as this user dragged them, e.g. ["c2","c1"].
|
||||
// Per user rather than per car, so it also covers cars shared with them and
|
||||
// never reorders somebody else's garage. See internal/api/cars.go.
|
||||
F.json("car_order", 20000),
|
||||
],
|
||||
};
|
||||
|
||||
|
||||
+17
-4
@@ -88,7 +88,18 @@ Config (`server/.env`, copy from `.env.example`):
|
||||
car by hand, or **import from service** — pick a vehicle off a connected
|
||||
manufacturer account and have its details filled in (the button appears only
|
||||
once an account is connected). Shared cars are labelled and gated by your access
|
||||
level.
|
||||
level. **Drag a card** to rearrange the garage: the order is saved per user (so
|
||||
it covers shared cars and never reorders anybody else's garage) and applied by
|
||||
the API on every list. Pointer-only — the native drag events it uses don't fire
|
||||
on touch.
|
||||
- **What a car shows** — the gear button in a car's header picks both the
|
||||
sections that car's page shows (connected service, service history, technical
|
||||
checks, maintenance, fuel, documents, parts, reminders — Fuel off on an EV,
|
||||
say) and which of the 14 Information rows it lists (no Differential oil on a
|
||||
car without one). It belongs to the car, so everyone it is shared with sees
|
||||
the same page; setting it needs write access. Stored as the *hidden* sets, so
|
||||
anything added in a later release is on by default, and the Information tab
|
||||
itself can't be switched off.
|
||||
- **Car detail** — all car spec fields (engine / transmission / differential oil,
|
||||
brake fluid, coolant, VIN, fuel type, …) plus tabbed histories, each with an
|
||||
optional file attachment and add/edit/delete gated by your access level:
|
||||
@@ -96,9 +107,11 @@ Config (`server/.env`, copy from `.env.example`):
|
||||
car linked to a manufacturer account: live readings (odometer, fuel, battery,
|
||||
range, position), the vehicle record, and every section the plugin can fetch
|
||||
with its raw response. Offers the provider's odometer when it is ahead of the
|
||||
stored one. On an unlinked car the tab instead offers to connect it to a
|
||||
vehicle on your account. Read under *your* account, so a car shared from
|
||||
someone else shows data only if that vehicle is on your account too.
|
||||
stored one. Every card below the live readings — the vehicle record and each
|
||||
provider section — folds away, and which ones you folded is remembered per
|
||||
device in localStorage. On an unlinked car the tab instead offers to connect
|
||||
it to a vehicle on your account. Read under *your* account, so a car shared
|
||||
from someone else shows data only if that vehicle is on your account too.
|
||||
- **Service history** — date, km, computed next date/km, and changed-parts flags.
|
||||
- **Technical checks** — roadworthiness inspections; result, cost, station and
|
||||
the certificate's valid-until, which drives the next-due date.
|
||||
|
||||
@@ -119,6 +119,12 @@ export const api = {
|
||||
getCar: (id) => request(`/cars/${id}`),
|
||||
createCar: (body) => request("/cars", { method: "POST", body: JSON.stringify(body) }),
|
||||
updateCar: (id, body) => request(`/cars/${id}`, { method: "PATCH", body: JSON.stringify(body) }),
|
||||
// What this car's page shows — {hiddenTabs?, hiddenFields?}, as hidden sets.
|
||||
// Its own endpoint so an ordinary car edit — which sends every other field —
|
||||
// can never reveal something switched off. Needs write access, like editing
|
||||
// the car. Only the sets passed are written.
|
||||
updateCarView: (id, patch) =>
|
||||
request(`/cars/${id}/view`, { method: "PUT", body: JSON.stringify(patch) }),
|
||||
deleteCar: (id) => request(`/cars/${id}`, { method: "DELETE" }),
|
||||
|
||||
// Sharing (owner-only). A share grants another user read or write access.
|
||||
|
||||
@@ -143,6 +143,42 @@ async function applyOdometer() {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Collapsing the cards ---
|
||||
//
|
||||
// Every card below the headline readings folds away, so a long provider dump
|
||||
// (Toyota reports eight sections) can be trimmed to the two or three worth
|
||||
// watching. Which ones are folded is remembered in localStorage rather than on
|
||||
// the profile: it is a per-device reading habit, not an account setting, and it
|
||||
// should survive leaving the tab without a round trip. Keyed by section id, so
|
||||
// collapsing "Notifications" keeps it collapsed on every car.
|
||||
const COLLAPSED_KEY = "cc_provider_collapsed";
|
||||
|
||||
const collapsed = ref(readCollapsed());
|
||||
|
||||
function readCollapsed() {
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(COLLAPSED_KEY) || "[]");
|
||||
return Array.isArray(raw) ? raw.filter((id) => typeof id === "string") : [];
|
||||
} catch {
|
||||
return []; // unreadable (hand-edited, or written by an older version)
|
||||
}
|
||||
}
|
||||
|
||||
function isOpen(id) {
|
||||
return !collapsed.value.includes(id);
|
||||
}
|
||||
|
||||
function toggleCard(id) {
|
||||
collapsed.value = isOpen(id)
|
||||
? [...collapsed.value, id]
|
||||
: collapsed.value.filter((k) => k !== id);
|
||||
try {
|
||||
localStorage.setItem(COLLAPSED_KEY, JSON.stringify(collapsed.value));
|
||||
} catch {
|
||||
// A full or blocked store just means the choice lasts this visit only.
|
||||
}
|
||||
}
|
||||
|
||||
function metricLabel(key) {
|
||||
return t(`car.provider.metrics.${key}`);
|
||||
}
|
||||
@@ -225,9 +261,22 @@ onMounted(async () => {
|
||||
|
||||
<!-- The vehicle record itself -->
|
||||
<div v-if="snap.vehicle" class="dh-card mb-4 p-6">
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center justify-between gap-3 text-left"
|
||||
:aria-expanded="isOpen('vehicle')"
|
||||
@click="toggleCard('vehicle')"
|
||||
>
|
||||
<p class="eyebrow">{{ t("car.provider.vehicle") }}</p>
|
||||
<svg
|
||||
viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
|
||||
class="h-4 w-4 shrink-0 text-muted transition-transform" :class="isOpen('vehicle') ? '' : '-rotate-90'"
|
||||
><path stroke-linecap="round" stroke-linejoin="round" d="m6 9 6 6 6-6" /></svg>
|
||||
</button>
|
||||
|
||||
<div v-show="isOpen('vehicle')">
|
||||
<div class="flex flex-wrap items-start justify-between gap-4">
|
||||
<div>
|
||||
<p class="eyebrow">{{ t("car.provider.vehicle") }}</p>
|
||||
<p class="mt-0.5 font-bold text-strong">{{ snap.vehicle.name }}</p>
|
||||
<p class="text-sm text-muted">
|
||||
{{ [snap.vehicle.make, snap.vehicle.model, snap.vehicle.year || ''].filter(Boolean).join(' ') }}
|
||||
@@ -252,17 +301,41 @@ onMounted(async () => {
|
||||
</div>
|
||||
</dl>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- One card per capability the plugin exposes -->
|
||||
<div class="space-y-4">
|
||||
<div v-for="sec in sections" :key="sec.id" class="dh-card p-6">
|
||||
<div class="mb-3 flex items-center justify-between gap-3">
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center justify-between gap-3 text-left"
|
||||
:aria-expanded="isOpen(sec.id)"
|
||||
@click="toggleCard(sec.id)"
|
||||
>
|
||||
<h3 class="font-semibold text-strong">{{ sectionLabel(sec.id) }}</h3>
|
||||
<span v-if="sec.status === 'error'" class="dh-badge dh-badge-warning">{{ sec.error }}</span>
|
||||
</div>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<!-- A failed section says so in the collapsed header, but only
|
||||
as a badge: the provider's own message can run to hundreds
|
||||
of characters, which belongs in the body with the rest of
|
||||
the detail rather than stretching the card. -->
|
||||
<span v-if="sec.status === 'error'" class="dh-badge dh-badge-warning">
|
||||
{{ t("car.provider.sectionFailed") }}
|
||||
</span>
|
||||
<svg
|
||||
viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
|
||||
class="h-4 w-4 shrink-0 text-muted transition-transform" :class="isOpen(sec.id) ? '' : '-rotate-90'"
|
||||
><path stroke-linecap="round" stroke-linejoin="round" d="m6 9 6 6 6-6" /></svg>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<p v-if="sec.status === 'empty'" class="text-sm text-muted">{{ t("car.provider.sectionEmpty") }}</p>
|
||||
<div v-show="isOpen(sec.id)" class="mt-3">
|
||||
<p
|
||||
v-if="sec.status === 'error'"
|
||||
class="overflow-x-auto whitespace-pre-wrap break-words rounded-control bg-warning-soft px-3 py-2 text-sm text-warning"
|
||||
>{{ sec.error }}</p>
|
||||
|
||||
<p v-else-if="sec.status === 'empty'" class="text-sm text-muted">{{ t("car.provider.sectionEmpty") }}</p>
|
||||
|
||||
<template v-else-if="sec.status === 'ok'">
|
||||
<dl class="divide-y divide-subtle text-sm">
|
||||
@@ -281,6 +354,7 @@ onMounted(async () => {
|
||||
<pre class="mt-2 max-h-96 overflow-auto rounded-control bg-sunken p-3 text-xs text-body">{{ prettyJSON(sec.raw) }}</pre>
|
||||
</details>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -88,6 +88,7 @@
|
||||
"subtitle": "Serviceoverblik og servicehistorik.",
|
||||
"addCar": "Tilføj bil",
|
||||
"importCar": "Importér fra tjeneste",
|
||||
"dragHint": "Træk for at ændre rækkefølgen i din garage.",
|
||||
"empty": "Ingen biler endnu. Klik på {action} for at komme i gang.",
|
||||
"shared": "Delt",
|
||||
"sharedReadOnly": "Delt · skrivebeskyttet",
|
||||
@@ -190,6 +191,7 @@
|
||||
"fontLarge": "stor"
|
||||
},
|
||||
|
||||
|
||||
"profile": {
|
||||
"title": "Profil",
|
||||
"avatarAlt": "Profilbillede",
|
||||
@@ -273,6 +275,15 @@
|
||||
"reminders": "Påmindelser"
|
||||
},
|
||||
|
||||
"viewPicker": {
|
||||
"open": "Hvad denne bils side viser",
|
||||
"title": "Hvad denne bil viser",
|
||||
"subtitle": "Vælg hvilke afsnit og oplysninger denne bils side viser. Det gælder alle, bilen er delt med.",
|
||||
"tabsHeading": "Faner",
|
||||
"fieldsHeading": "Oplysninger",
|
||||
"alwaysOn": "{tab} er altid tilgængelig."
|
||||
},
|
||||
|
||||
"provider": {
|
||||
"subtitle": "Live-data fra din {label}-konto.",
|
||||
"refresh": "Opdater",
|
||||
@@ -285,6 +296,7 @@
|
||||
"allFields": "Alle oplyste felter",
|
||||
"truncated": "Kun de første {n} felter er vist — resten findes i det rå svar nedenfor.",
|
||||
"sectionEmpty": "Intet oplyst.",
|
||||
"sectionFailed": "Kunne ikke hentes",
|
||||
"own": "Kun din egen konto bruges, så loginoplysninger deles aldrig sammen med en bil.",
|
||||
"odometerSuggest": "{label} oplyser {km}, altså mere end bilens gemte kilometerstand.",
|
||||
"updateOdometer": "Opdater kilometerstand",
|
||||
@@ -318,6 +330,7 @@
|
||||
},
|
||||
|
||||
"info": {
|
||||
"allHidden": "Alle felter er slået fra for denne bil.",
|
||||
"oilSpec": "Motorolie-specifikation",
|
||||
"transmissionOil": "Gearolie",
|
||||
"differentialOil": "Differentialeolie",
|
||||
|
||||
@@ -106,6 +106,7 @@
|
||||
"subtitle": "Maintenance overview and service history.",
|
||||
"addCar": "Add car",
|
||||
"importCar": "Import from service",
|
||||
"dragHint": "Drag to rearrange your garage.",
|
||||
"empty": "No cars yet. Click {action} to get started.",
|
||||
"shared": "Shared",
|
||||
"sharedReadOnly": "Shared · read-only",
|
||||
@@ -208,6 +209,7 @@
|
||||
"fontLarge": "large"
|
||||
},
|
||||
|
||||
|
||||
"profile": {
|
||||
"title": "Profile",
|
||||
"avatarAlt": "Avatar",
|
||||
@@ -348,6 +350,15 @@
|
||||
"reminders": "Reminders"
|
||||
},
|
||||
|
||||
"viewPicker": {
|
||||
"open": "What this car's page shows",
|
||||
"title": "What this car shows",
|
||||
"subtitle": "Pick the sections and details this car's page shows. It applies to everyone the car is shared with.",
|
||||
"tabsHeading": "Tabs",
|
||||
"fieldsHeading": "Information fields",
|
||||
"alwaysOn": "{tab} is always available."
|
||||
},
|
||||
|
||||
"provider": {
|
||||
"subtitle": "Live data from your {label} account.",
|
||||
"refresh": "Refresh",
|
||||
@@ -360,6 +371,7 @@
|
||||
"allFields": "All reported fields",
|
||||
"truncated": "Only the first {n} fields are listed — the raw response below has the rest.",
|
||||
"sectionEmpty": "Nothing reported.",
|
||||
"sectionFailed": "Couldn't be fetched",
|
||||
"own": "Only your own account is used, so credentials are never shared with a car.",
|
||||
"odometerSuggest": "{label} reports {km}, ahead of this car's stored reading.",
|
||||
"updateOdometer": "Update odometer",
|
||||
@@ -393,6 +405,7 @@
|
||||
},
|
||||
|
||||
"info": {
|
||||
"allHidden": "Every field is switched off for this car.",
|
||||
"oilSpec": "Engine oil spec",
|
||||
"transmissionOil": "Transmission oil",
|
||||
"differentialOil": "Differential oil",
|
||||
|
||||
@@ -90,6 +90,7 @@
|
||||
"subtitle": "Przegląd serwisowy i historia napraw.",
|
||||
"addCar": "Dodaj samochód",
|
||||
"importCar": "Importuj z serwisu",
|
||||
"dragHint": "Przeciągnij, aby zmienić kolejność w garażu.",
|
||||
"empty": "Nie masz jeszcze samochodów. Kliknij {action}, aby zacząć.",
|
||||
"shared": "Udostępniony",
|
||||
"sharedReadOnly": "Udostępniony · tylko do odczytu",
|
||||
@@ -194,6 +195,7 @@
|
||||
"fontLarge": "duża"
|
||||
},
|
||||
|
||||
|
||||
"profile": {
|
||||
"title": "Profil",
|
||||
"avatarAlt": "Awatar",
|
||||
@@ -277,6 +279,15 @@
|
||||
"reminders": "Przypomnienia"
|
||||
},
|
||||
|
||||
"viewPicker": {
|
||||
"open": "Co pokazuje strona tego samochodu",
|
||||
"title": "Co pokazuje ten samochód",
|
||||
"subtitle": "Wybierz sekcje i szczegóły widoczne na stronie tego samochodu. Dotyczy wszystkich, którym go udostępniono.",
|
||||
"tabsHeading": "Zakładki",
|
||||
"fieldsHeading": "Pola informacji",
|
||||
"alwaysOn": "Zakładka {tab} jest zawsze dostępna."
|
||||
},
|
||||
|
||||
"provider": {
|
||||
"subtitle": "Dane na żywo z Twojego konta {label}.",
|
||||
"refresh": "Odśwież",
|
||||
@@ -289,6 +300,7 @@
|
||||
"allFields": "Wszystkie zgłoszone pola",
|
||||
"truncated": "Wypisano tylko pierwsze {n} pól — pozostałe znajdziesz w surowej odpowiedzi poniżej.",
|
||||
"sectionEmpty": "Brak danych.",
|
||||
"sectionFailed": "Nie udało się pobrać",
|
||||
"own": "Używane jest wyłącznie Twoje własne konto, więc dane logowania nigdy nie są udostępniane wraz z samochodem.",
|
||||
"odometerSuggest": "{label} podaje {km}, czyli więcej niż zapisany przebieg tego samochodu.",
|
||||
"updateOdometer": "Zaktualizuj przebieg",
|
||||
@@ -322,6 +334,7 @@
|
||||
},
|
||||
|
||||
"info": {
|
||||
"allHidden": "Wszystkie pola są wyłączone dla tego samochodu.",
|
||||
"oilSpec": "Specyfikacja oleju silnikowego",
|
||||
"transmissionOil": "Olej przekładniowy",
|
||||
"differentialOil": "Olej mostu napędowego",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup>
|
||||
import { ref, onMounted, computed } from "vue";
|
||||
import { ref, onMounted, computed, watch } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
import { api } from "../api";
|
||||
import {
|
||||
@@ -24,6 +24,7 @@ import DocumentFormModal from "../components/DocumentFormModal.vue";
|
||||
import ReminderFormModal from "../components/ReminderFormModal.vue";
|
||||
import ShareModal from "../components/ShareModal.vue";
|
||||
import ProviderPanel from "../components/ProviderPanel.vue";
|
||||
import Modal from "../components/Modal.vue";
|
||||
|
||||
const props = defineProps({ id: { type: String, required: true } });
|
||||
const router = useRouter();
|
||||
@@ -102,17 +103,139 @@ const dueReminders = computed(
|
||||
|
||||
// Computed, not a plain array: t() reads the reactive locale, so the tab labels
|
||||
// have to re-evaluate when the language changes.
|
||||
const TABS = computed(() => [
|
||||
...(showProviderTab.value ? [{ key: "provider", label: providerLabel.value }] : []),
|
||||
{ key: "info", label: t("car.tabs.info") },
|
||||
{ key: "services", label: t("car.tabs.services") },
|
||||
{ key: "technical", label: t("car.tabs.technical") },
|
||||
{ key: "maintenance", label: t("car.tabs.maintenance") },
|
||||
{ key: "fuel", label: t("car.tabs.fuel") },
|
||||
{ key: "documents", label: t("car.tabs.documents") },
|
||||
{ key: "parts", label: t("car.tabs.parts") },
|
||||
{ key: "reminders", label: t("car.tabs.reminders") },
|
||||
]);
|
||||
//
|
||||
// Tabs switched off for this car are dropped here. It is a property of the car,
|
||||
// so everyone it is shared with sees the same page — an EV with Fuel off has no
|
||||
// Fuel tab for anybody. Information always stays: it is the car itself, and a
|
||||
// page with no tabs left would be a dead end. The panels below are keyed off
|
||||
// activeTab, so a hidden tab's content is unreachable rather than unlabelled.
|
||||
const hiddenTabs = computed(() => car.value?.hiddenTabs || []);
|
||||
const hiddenFields = computed(() => car.value?.hiddenFields || []);
|
||||
const TABS = computed(() =>
|
||||
[
|
||||
...(showProviderTab.value ? [{ key: "provider", label: providerLabel.value }] : []),
|
||||
{ key: "info", label: t("car.tabs.info") },
|
||||
{ key: "services", label: t("car.tabs.services") },
|
||||
{ key: "technical", label: t("car.tabs.technical") },
|
||||
{ key: "maintenance", label: t("car.tabs.maintenance") },
|
||||
{ key: "fuel", label: t("car.tabs.fuel") },
|
||||
{ key: "documents", label: t("car.tabs.documents") },
|
||||
{ key: "parts", label: t("car.tabs.parts") },
|
||||
{ key: "reminders", label: t("car.tabs.reminders") },
|
||||
].filter((tab) => !hiddenTabs.value.includes(tab.key))
|
||||
);
|
||||
|
||||
// Switching a tab off while standing on it (or landing on a car whose provider
|
||||
// tab doesn't apply) would otherwise leave the page on a tab that no longer has
|
||||
// a button.
|
||||
watch(TABS, (tabs) => {
|
||||
if (tabs.length && !tabs.some((tab) => tab.key === activeTab.value)) {
|
||||
activeTab.value = tabs[0].key;
|
||||
}
|
||||
});
|
||||
|
||||
// --- What this car's page shows (write access; owner or write-shared) ---
|
||||
//
|
||||
// Two hidden sets, both properties of the car: the tabs, and the rows of the
|
||||
// Information tab. Edited as a draft in one modal and saved together, rather
|
||||
// than saving on every checkbox: switching several off one at a time would make
|
||||
// the page rearrange under the pointer between clicks.
|
||||
const showViewPicker = ref(false);
|
||||
const HIDEABLE_TABS = [
|
||||
"provider", "services", "technical", "maintenance", "fuel", "documents", "parts", "reminders",
|
||||
];
|
||||
// The Information rows, in the order they are laid out. Keys mirror
|
||||
// hideableCarFields in the API's cars.go — the server rejects anything else.
|
||||
const INFO_FIELD_KEYS = [
|
||||
"oilSpec", "transmissionOil", "differentialOil", "brakeFluid", "coolant",
|
||||
"odometer", "serviceInterval", "nextDue", "registrationPlate",
|
||||
"registrationCountry", "vin", "fuelType", "buildDate", "firstRegistration",
|
||||
];
|
||||
const tabDraft = ref([]); // tab keys that stay visible
|
||||
const fieldDraft = ref([]); // Information keys that stay visible
|
||||
const viewSaving = ref(false);
|
||||
const viewError = ref("");
|
||||
|
||||
function openViewPicker() {
|
||||
tabDraft.value = HIDEABLE_TABS.filter((key) => !hiddenTabs.value.includes(key));
|
||||
fieldDraft.value = INFO_FIELD_KEYS.filter((key) => !hiddenFields.value.includes(key));
|
||||
viewError.value = "";
|
||||
showViewPicker.value = true;
|
||||
}
|
||||
|
||||
// One handler per draft rather than passing the ref in from the template: Vue
|
||||
// unwraps refs in the render context, so a shared handler would be handed the
|
||||
// plain array and its writes would go nowhere.
|
||||
function toggleTabDraft(key, on) {
|
||||
tabDraft.value = on ? [...tabDraft.value, key] : tabDraft.value.filter((k) => k !== key);
|
||||
}
|
||||
function toggleFieldDraft(key, on) {
|
||||
fieldDraft.value = on ? [...fieldDraft.value, key] : fieldDraft.value.filter((k) => k !== key);
|
||||
}
|
||||
|
||||
async function saveView() {
|
||||
viewSaving.value = true;
|
||||
viewError.value = "";
|
||||
try {
|
||||
const updated = await api.updateCarView(props.id, {
|
||||
hiddenTabs: HIDEABLE_TABS.filter((key) => !tabDraft.value.includes(key)),
|
||||
hiddenFields: INFO_FIELD_KEYS.filter((key) => !fieldDraft.value.includes(key)),
|
||||
});
|
||||
car.value = { ...updated, access: car.value.access };
|
||||
showViewPicker.value = false;
|
||||
} catch (e) {
|
||||
viewError.value = e.message;
|
||||
} finally {
|
||||
viewSaving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// The connected-service tab is only offered when this car could show one at all
|
||||
// — hiding a tab nobody can see would just be confusing.
|
||||
const tabPickerKeys = computed(() =>
|
||||
HIDEABLE_TABS.filter((key) => key !== "provider" || showProviderTab.value)
|
||||
);
|
||||
function tabPickerLabel(key) {
|
||||
return key === "provider" ? providerLabel.value : t(`car.tabs.${key}`);
|
||||
}
|
||||
function infoFieldLabel(key) {
|
||||
return t(`car.info.${key}`);
|
||||
}
|
||||
|
||||
// The Information rows as data, so the same list drives both the grid and the
|
||||
// picker and the two can't drift apart. `mono` marks the values that read as
|
||||
// figures rather than prose.
|
||||
const infoFields = computed(() => {
|
||||
const c = car.value;
|
||||
if (!c) return [];
|
||||
const values = {
|
||||
oilSpec: { text: c.oilSpec || t("common.empty") },
|
||||
transmissionOil: { text: c.transmissionOilSpec || t("common.empty") },
|
||||
differentialOil: { text: c.differentialOilSpec || t("common.empty") },
|
||||
brakeFluid: { text: c.brakeFluidSpec || t("common.empty") },
|
||||
coolant: { text: c.coolantSpec || t("common.empty") },
|
||||
odometer: { text: formatKm(c.currentKm), mono: true },
|
||||
serviceInterval: { text: `${c.serviceIntervalDays}d · ${formatKm(c.serviceIntervalKm)}`, mono: true },
|
||||
nextDue: {
|
||||
text: `${formatDate(latest.value?.nextServiceDate)} · ${formatKm(latest.value?.nextServiceKm)}`,
|
||||
mono: true,
|
||||
},
|
||||
registrationPlate: { text: c.registration || t("common.empty"), mono: true },
|
||||
registrationCountry: { text: c.registrationCountry || t("common.empty") },
|
||||
vin: { text: c.vin || t("common.empty"), mono: true },
|
||||
fuelType: { text: fuelLabel(c.fuelType) },
|
||||
buildDate: { text: c.buildDate ? formatDate(c.buildDate) : t("common.empty"), mono: true },
|
||||
firstRegistration: {
|
||||
text: c.firstRegistrationDate ? formatDate(c.firstRegistrationDate) : t("common.empty"),
|
||||
mono: true,
|
||||
},
|
||||
};
|
||||
return INFO_FIELD_KEYS.filter((key) => !hiddenFields.value.includes(key)).map((key) => ({
|
||||
key,
|
||||
label: infoFieldLabel(key),
|
||||
...values[key],
|
||||
}));
|
||||
});
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
@@ -478,6 +601,16 @@ onMounted(load);
|
||||
{{ isReadOnly ? t("car.sharedReadOnly") : t("car.shared") }}
|
||||
</span>
|
||||
<span :class="status.classes">{{ status.label }}</span>
|
||||
<!-- Which tabs this car's page shows. -->
|
||||
<button
|
||||
v-if="canWrite"
|
||||
class="dh-btn dh-btn-ghost !px-2 !py-1.5"
|
||||
:title="t('car.viewPicker.open')"
|
||||
:aria-label="t('car.viewPicker.open')"
|
||||
@click="openViewPicker"
|
||||
>
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" class="h-4 w-4"><path stroke-linecap="round" stroke-linejoin="round" d="M9.6 3.6 9 6a7.5 7.5 0 0 0-1.7 1L5 6.3l-2 3.4 2 1.5a7.6 7.6 0 0 0 0 2l-2 1.5 2 3.4 2.3-.7c.5.4 1.1.8 1.7 1l.6 2.4h4l.6-2.4c.6-.2 1.2-.6 1.7-1l2.3.7 2-3.4-2-1.5a7.6 7.6 0 0 0 0-2l2-1.5-2-3.4-2.3.7A7.5 7.5 0 0 0 15 6l-.6-2.4z"/><circle cx="12" cy="12" r="2.6"/></svg>
|
||||
</button>
|
||||
<button v-if="isOwner" class="dh-btn dh-btn-ghost !px-3 !py-1.5" @click="showShare = true">{{ t("car.share") }}</button>
|
||||
<button v-if="canWrite" class="dh-btn dh-btn-ghost !px-3 !py-1.5" @click="showCarEdit = true">{{ t("common.edit") }}</button>
|
||||
<button v-if="isOwner" class="dh-btn !px-3 !py-1.5 border border-danger/30 text-danger hover:bg-danger-soft" @click="openDeleteCar">{{ t("common.delete") }}</button>
|
||||
@@ -517,21 +650,12 @@ onMounted(load);
|
||||
<!-- Information -->
|
||||
<section v-else-if="activeTab === 'info'">
|
||||
<div class="dh-card p-6">
|
||||
<dl class="grid grid-cols-2 gap-4 text-sm sm:grid-cols-4">
|
||||
<div><dt class="eyebrow">{{ t("car.info.oilSpec") }}</dt><dd class="mt-0.5 font-medium text-strong">{{ car.oilSpec || t("common.empty") }}</dd></div>
|
||||
<div><dt class="eyebrow">{{ t("car.info.transmissionOil") }}</dt><dd class="mt-0.5 font-medium text-strong">{{ car.transmissionOilSpec || t("common.empty") }}</dd></div>
|
||||
<div><dt class="eyebrow">{{ t("car.info.differentialOil") }}</dt><dd class="mt-0.5 font-medium text-strong">{{ car.differentialOilSpec || t("common.empty") }}</dd></div>
|
||||
<div><dt class="eyebrow">{{ t("car.info.brakeFluid") }}</dt><dd class="mt-0.5 font-medium text-strong">{{ car.brakeFluidSpec || t("common.empty") }}</dd></div>
|
||||
<div><dt class="eyebrow">{{ t("car.info.coolant") }}</dt><dd class="mt-0.5 font-medium text-strong">{{ car.coolantSpec || t("common.empty") }}</dd></div>
|
||||
<div><dt class="eyebrow">{{ t("car.info.odometer") }}</dt><dd class="mt-0.5 data font-medium text-strong">{{ formatKm(car.currentKm) }}</dd></div>
|
||||
<div><dt class="eyebrow">{{ t("car.info.serviceInterval") }}</dt><dd class="mt-0.5 data font-medium text-strong">{{ car.serviceIntervalDays }}d · {{ formatKm(car.serviceIntervalKm) }}</dd></div>
|
||||
<div><dt class="eyebrow">{{ t("car.info.nextDue") }}</dt><dd class="mt-0.5 data font-medium text-strong">{{ formatDate(latest?.nextServiceDate) }} · {{ formatKm(latest?.nextServiceKm) }}</dd></div>
|
||||
<div><dt class="eyebrow">{{ t("car.info.registrationPlate") }}</dt><dd class="mt-0.5 data font-medium text-strong">{{ car.registration || t("common.empty") }}</dd></div>
|
||||
<div><dt class="eyebrow">{{ t("car.info.registrationCountry") }}</dt><dd class="mt-0.5 font-medium text-strong">{{ car.registrationCountry || t("common.empty") }}</dd></div>
|
||||
<div><dt class="eyebrow">{{ t("car.info.vin") }}</dt><dd class="mt-0.5 data font-medium text-strong">{{ car.vin || t("common.empty") }}</dd></div>
|
||||
<div><dt class="eyebrow">{{ t("car.info.fuelType") }}</dt><dd class="mt-0.5 font-medium text-strong">{{ fuelLabel(car.fuelType) }}</dd></div>
|
||||
<div><dt class="eyebrow">{{ t("car.info.buildDate") }}</dt><dd class="mt-0.5 data font-medium text-strong">{{ car.buildDate ? formatDate(car.buildDate) : t("common.empty") }}</dd></div>
|
||||
<div><dt class="eyebrow">{{ t("car.info.firstRegistration") }}</dt><dd class="mt-0.5 data font-medium text-strong">{{ car.firstRegistrationDate ? formatDate(car.firstRegistrationDate) : t("common.empty") }}</dd></div>
|
||||
<p v-if="infoFields.length === 0" class="text-sm text-muted">{{ t("car.info.allHidden") }}</p>
|
||||
<dl v-else class="grid grid-cols-2 gap-4 text-sm sm:grid-cols-4">
|
||||
<div v-for="f in infoFields" :key="f.key">
|
||||
<dt class="eyebrow">{{ f.label }}</dt>
|
||||
<dd class="mt-0.5 font-medium text-strong" :class="f.mono ? 'data' : ''">{{ f.text }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
</section>
|
||||
@@ -1055,6 +1179,55 @@ onMounted(load);
|
||||
/>
|
||||
<ShareModal v-if="showShare && car" :car="car" @close="showShare = false" />
|
||||
|
||||
<!-- What this car's page shows: tabs, and the Information rows -->
|
||||
<Modal v-if="showViewPicker" :title="t('car.viewPicker.title')" @close="showViewPicker = false">
|
||||
<p class="mb-4 text-sm text-muted">{{ t("car.viewPicker.subtitle") }}</p>
|
||||
|
||||
<p class="eyebrow mb-2">{{ t("car.viewPicker.tabsHeading") }}</p>
|
||||
<div class="grid gap-2 sm:grid-cols-2">
|
||||
<label
|
||||
v-for="key in tabPickerKeys"
|
||||
:key="key"
|
||||
class="flex items-center gap-2 text-sm font-medium text-body"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
class="h-4 w-4 rounded border-subtle text-accent focus:ring-accent"
|
||||
:checked="tabDraft.includes(key)"
|
||||
@change="toggleTabDraft(key, $event.target.checked)"
|
||||
/>
|
||||
<span>{{ tabPickerLabel(key) }}</span>
|
||||
</label>
|
||||
</div>
|
||||
<p class="mt-2 text-xs text-muted">{{ t("car.viewPicker.alwaysOn", { tab: t("car.tabs.info") }) }}</p>
|
||||
|
||||
<p class="eyebrow mb-2 mt-5">{{ t("car.viewPicker.fieldsHeading") }}</p>
|
||||
<div class="grid gap-2 sm:grid-cols-2">
|
||||
<label
|
||||
v-for="key in INFO_FIELD_KEYS"
|
||||
:key="key"
|
||||
class="flex items-center gap-2 text-sm font-medium text-body"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
class="h-4 w-4 rounded border-subtle text-accent focus:ring-accent"
|
||||
:checked="fieldDraft.includes(key)"
|
||||
@change="toggleFieldDraft(key, $event.target.checked)"
|
||||
/>
|
||||
<span>{{ infoFieldLabel(key) }}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<p v-if="viewError" class="mt-3 text-sm text-danger">{{ viewError }}</p>
|
||||
|
||||
<div class="mt-5 flex justify-end gap-2">
|
||||
<button class="dh-btn dh-btn-ghost" @click="showViewPicker = false">{{ t("common.cancel") }}</button>
|
||||
<button class="dh-btn dh-btn-primary" :disabled="viewSaving" @click="saveView">
|
||||
{{ viewSaving ? t("common.saving") : t("common.save") }}
|
||||
</button>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
<!-- Delete-car confirmation (type-to-confirm; cascade removes all data) -->
|
||||
<div v-if="showDeleteCar && car" class="fixed inset-0 z-30 grid place-items-center bg-brand-900/40 p-4 backdrop-blur-sm" @click.self="showDeleteCar = false">
|
||||
<div class="dh-card w-full max-w-md p-6 shadow-pop">
|
||||
|
||||
@@ -38,6 +38,65 @@ async function load() {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Drag to rearrange the garage ---
|
||||
//
|
||||
// The order is a per-user list of car ids on the profile, so it also covers
|
||||
// cars shared with you and never reorders anybody else's garage. The API
|
||||
// already returns the list in that order; a drop just sends the new one back.
|
||||
// Hand-rolled on the native HTML5 drag events rather than pulling in a drag
|
||||
// library for one screen — which does mean it is pointer-only, as touch
|
||||
// browsers don't fire these.
|
||||
const dragId = ref(""); // card being dragged
|
||||
const dropId = ref(""); // card it is currently hovering over
|
||||
const orderError = ref("");
|
||||
let moved = false; // the grid changed during this drag and isn't saved yet
|
||||
|
||||
function onDragStart(car, e) {
|
||||
dragId.value = car.id;
|
||||
moved = false;
|
||||
e.dataTransfer.effectAllowed = "move";
|
||||
// Firefox only starts a drag once something is on the transfer.
|
||||
e.dataTransfer.setData("text/plain", car.id);
|
||||
}
|
||||
|
||||
// Reorder live as the pointer crosses cards, so the grid shows the arrangement
|
||||
// you are about to get instead of only settling after the drop. dragenter fires
|
||||
// again for every child element the pointer touches inside the same card, so
|
||||
// the card being hovered is remembered and only a genuinely new one moves
|
||||
// anything — otherwise a slow drag across one card would shuffle it repeatedly.
|
||||
function onDragEnter(car) {
|
||||
if (!dragId.value || car.id === dragId.value || dropId.value === car.id) return;
|
||||
dropId.value = car.id;
|
||||
const list = cars.value;
|
||||
const from = list.findIndex((c) => c.id === dragId.value);
|
||||
const to = list.findIndex((c) => c.id === car.id);
|
||||
if (from < 0 || to < 0) return;
|
||||
// `to` is the target's index before the removal, which lands the card in the
|
||||
// target's slot when dragging backwards and just past it when dragging
|
||||
// forwards — in both cases where it was dropped.
|
||||
list.splice(to, 0, ...list.splice(from, 1));
|
||||
moved = true;
|
||||
}
|
||||
|
||||
// Save whatever the grid now shows. Called from both drop and dragend: a card
|
||||
// released over a gap between cards never produces a drop, and leaving that
|
||||
// arrangement unsaved would quietly undo itself on the next load.
|
||||
async function commitOrder() {
|
||||
dragId.value = "";
|
||||
dropId.value = "";
|
||||
if (!moved) return;
|
||||
moved = false;
|
||||
orderError.value = "";
|
||||
try {
|
||||
await api.updateMe({ carOrder: cars.value.map((c) => c.id) });
|
||||
} catch (e) {
|
||||
// The arrangement didn't stick; say so and reload the stored one rather
|
||||
// than leaving the screen showing an order the server doesn't have.
|
||||
orderError.value = e.message;
|
||||
await load();
|
||||
}
|
||||
}
|
||||
|
||||
function onSaved(car) {
|
||||
showAdd.value = false;
|
||||
router.push({ name: "car", params: { id: car.id } });
|
||||
@@ -101,6 +160,7 @@ onMounted(() => {
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="mb-4 rounded-control bg-danger-soft px-4 py-3 text-sm font-medium text-danger">{{ error }}</p>
|
||||
<p v-if="orderError" class="mb-4 rounded-control bg-danger-soft px-4 py-3 text-sm font-medium text-danger">{{ orderError }}</p>
|
||||
<p v-if="loading" class="text-muted">{{ t("common.loading") }}</p>
|
||||
|
||||
<div v-else-if="cars.length === 0" class="rounded-card border border-dashed border-default p-12 text-center text-muted">
|
||||
@@ -113,7 +173,18 @@ onMounted(() => {
|
||||
v-for="car in cars"
|
||||
:key="car.id"
|
||||
:to="{ name: 'car', params: { id: car.id } }"
|
||||
class="dh-card group block p-5 transition-shadow duration-150 hover:shadow-pop"
|
||||
:draggable="cars.length > 1"
|
||||
:title="cars.length > 1 ? t('dashboard.dragHint') : ''"
|
||||
class="dh-card group block cursor-grab p-5 transition-shadow duration-150 hover:shadow-pop active:cursor-grabbing"
|
||||
:class="[
|
||||
dragId === car.id ? 'opacity-50' : '',
|
||||
dropId === car.id ? 'ring-2 ring-accent' : '',
|
||||
]"
|
||||
@dragstart="onDragStart(car, $event)"
|
||||
@dragenter.prevent="onDragEnter(car)"
|
||||
@dragover.prevent
|
||||
@drop.prevent="commitOrder"
|
||||
@dragend="commitOrder"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
|
||||
Reference in New Issue
Block a user