diff --git a/API Server/internal/api/integrations.go b/API Server/internal/api/integrations.go index 9caabb7..8132473 100644 --- a/API Server/internal/api/integrations.go +++ b/API Server/internal/api/integrations.go @@ -6,6 +6,8 @@ import ( "net/http" "net/url" "strings" + + "drivervault/apiserver/internal/plugins/builtin/toyota" ) // Integrations exposes the Toyota Connected Europe plugin to end users under a @@ -13,14 +15,20 @@ import ( // account, while a superadmin (and, in an organization, an org admin) can impose // settings from above. // +// The one connector serves three brands — Toyota, Lexus and Subaru — and each is +// a plugin of its own to the user (toyota.Brands): its own panel entry, its own +// settings card, its own credentials and enable flag under its own +// pluginSettings key, and its own /api/integrations/{brand} routes. Everything +// below is written once and parameterized by the brand. +// // Resolution is a cascade: the top layer wins, and a lower layer only fills a // field the layers above left blank. // // - global (L1): pluginSettings on the app_settings singleton, set in the API // Server panel by a superadmin. This is the top of the cascade for everyone. -// - org (L2): pluginSettings.toyota on the caller's organization record, +// - org (L2): pluginSettings.{brand} on the caller's organization record, // editable by an org admin. Present only for users who belong to an org. -// - user (L3): pluginSettings.toyota on the caller's own user record. +// - user (L3): pluginSettings.{brand} on the caller's own user record. // // So the effective cascade is: // - org user: global → org → user @@ -28,7 +36,7 @@ import ( // // The MyToyota username + password resolve together as a *pair* from the highest // layer that supplies a username, so credential halves are never mixed across -// layers. The brand resolves on its own. Enablement is strictly per-user (L3), +// layers. Enablement is strictly per-user (L3), // gated by the global master switch (the plugin being enabled in the panel) and, // for org users, by the org gate. // @@ -36,19 +44,34 @@ import ( // client: the effective config is resolved server-side and only masked values // leave the API. The live probe runs server-side against the resolved config. -const ( - toyotaPlugin = "toyota" - toyotaSecretMask = "••••••••" -) +const toyotaSecretMask = "••••••••" -// toyotaConfig is one layer's Toyota settings. +// vehicleBrand is one face of the Toyota Connected Europe connector. +type vehicleBrand = toyota.Brand + +// toyotaBrand is the MyToyota face, the one that predates the split. +var toyotaBrand = toyota.Brands[0] + +// brandByName finds a registered brand by its plugin name. +func brandByName(name string) (vehicleBrand, bool) { + for _, b := range toyota.Brands { + if b.Name == name { + return b, true + } + } + return vehicleBrand{}, false +} + +// toyotaConfig is one layer's settings for one brand. type toyotaConfig struct { Username string `json:"username"` Password string `json:"password"` - Brand string `json:"brand"` + // Brand is read only from settings saved before the brands were split, to + // move them onto their own key (see splitLegacyBrand); nothing writes it. + Brand string `json:"brand,omitempty"` } -// toyotaStored is what we persist per user/org under pluginSettings.toyota. +// toyotaStored is what we persist per user/org under pluginSettings.{brand}. type toyotaStored struct { Config toyotaConfig `json:"config"` // Enabled is the personal per-user opt-in (user layer). Default false. @@ -58,9 +81,62 @@ type toyotaStored struct { Disabled bool `json:"disabled,omitempty"` } -// toyotaSettingsDoc is the pluginSettings JSON shape (only toyota today). -type toyotaSettingsDoc struct { - Toyota toyotaStored `json:"toyota"` +// decodePluginSettings reads a pluginSettings blob into its per-plugin entries, +// with any pre-split brand entry already moved onto its own key. Never nil. +func decodePluginSettings(raw json.RawMessage) map[string]json.RawMessage { + doc := map[string]json.RawMessage{} + if len(raw) > 0 { + _ = json.Unmarshal(raw, &doc) + } + if doc == nil { + doc = map[string]json.RawMessage{} // raw was JSON null + } + splitLegacyBrand(doc) + return doc +} + +// splitLegacyBrand moves a pre-split entry onto its brand. Before Lexus and +// Subaru were plugins of their own, all three brands lived under +// pluginSettings.toyota with a brand field picking the login; an entry there +// that names L or S is that brand's account, so it belongs under that brand's +// key — left under toyota it would show a Lexus login on the Toyota card. The +// move happens on every read, so it needs no migration step, and is written +// back the first time the record is saved for any brand. +func splitLegacyBrand(doc map[string]json.RawMessage) { + raw, ok := doc[toyotaBrand.Name] + if !ok { + return + } + var ts toyotaStored + if json.Unmarshal(raw, &ts) != nil { + return + } + code := strings.ToUpper(strings.TrimSpace(ts.Config.Brand)) + var target vehicleBrand + for _, b := range toyota.Brands { + if b.Code == code && b.Name != toyotaBrand.Name { + target = b + } + } + if target.Name == "" { + return // a Toyota entry, or one from before the brand field existed + } + if _, taken := doc[target.Name]; !taken { + ts.Config.Brand = "" + moved, _ := json.Marshal(ts) + doc[target.Name] = moved + } + delete(doc, toyotaBrand.Name) +} + +// storedFor is one brand's entry in a pluginSettings blob. +func storedFor(raw json.RawMessage, b vehicleBrand) toyotaStored { + var ts toyotaStored + if entry, ok := decodePluginSettings(raw)[b.Name]; ok { + _ = json.Unmarshal(entry, &ts) + } + ts.Config.Brand = "" + return ts } // toyotaFieldView is one field's resolved state for the UI. @@ -71,7 +147,7 @@ type toyotaFieldView struct { Locked bool `json:"locked"` // set above the caller's editable layer } -// toyotaResolution is the fully-resolved Toyota state for one caller. It captures +// toyotaResolution is the fully-resolved state of one brand for one caller. It captures // the effective cascade plus both editable layers (personal + organization), so // an org admin can manage each independently. type toyotaResolution struct { @@ -89,24 +165,19 @@ type toyotaResolution struct { // toyotaLayerRank orders the cascade layers; a higher number is lower priority. var toyotaLayerRank = map[string]int{"global": 1, "org": 2, "user": 3} -// resolveToyota computes the cascade for a caller. userRaw is the caller's -// pluginSettings blob (read from their user record). -func (s *Server) resolveToyota(ctx context.Context, who *callerIdentity, userRaw json.RawMessage) toyotaResolution { - g, masterEnabled, _ := s.plugins.RawConfig(toyotaPlugin) - gc := toyotaConfig{Username: g["username"], Password: g["password"], Brand: g["brand"]} +// resolveToyota computes one brand's cascade for a caller. userRaw is the +// caller's pluginSettings blob (read from their user record). +func (s *Server) resolveToyota(ctx context.Context, who *callerIdentity, userRaw json.RawMessage, b vehicleBrand) toyotaResolution { + g, masterEnabled, _ := s.plugins.RawConfig(b.Name) + gc := toyotaConfig{Username: g["username"], Password: g["password"]} var oStored toyotaStored if who.OrgID != "" { - oStored, _ = s.orgToyota(ctx, who.OrgID) + oStored, _ = s.orgToyota(ctx, who.OrgID, b) } oc := oStored.Config - var uStored toyotaStored - if len(userRaw) > 0 { - var d toyotaSettingsDoc - _ = json.Unmarshal(userRaw, &d) - uStored = d.Toyota - } + uStored := storedFor(userRaw, b) uc := uStored.Config res := toyotaResolution{ @@ -133,15 +204,6 @@ func (s *Server) resolveToyota(ctx context.Context, who *callerIdentity, userRaw } layers = append(layers, layer{"user", uc}) - // Brand resolves independently: the highest layer that sets it wins. - res.source["brand"] = "unset" - for _, l := range layers { - if v := strings.TrimSpace(l.c.Brand); v != "" { - res.eff.Brand, res.source["brand"] = v, l.name - break - } - } - // Credentials resolve as a pair from the highest layer with a username, so // the username and password never come from different layers. credSrc := "unset" @@ -177,10 +239,11 @@ func toyotaMaskPresent(v string) string { return "" } -// orgToyota reads an organization's stored Toyota settings (config + the org -// gate) and its raw pluginSettings blob via the service account. Best effort: -// zero values on any miss so callers proceed as if the org layer were empty. -func (s *Server) orgToyota(ctx context.Context, orgID string) (toyotaStored, json.RawMessage) { +// orgToyota reads an organization's stored settings for one brand (config + the +// org gate) and its raw pluginSettings blob via the service account. Best +// effort: zero values on any miss so callers proceed as if the org layer were +// empty. +func (s *Server) orgToyota(ctx context.Context, orgID string, b vehicleBrand) (toyotaStored, json.RawMessage) { if orgID == "" || !s.pb.Configured() { return toyotaStored{}, nil } @@ -193,11 +256,7 @@ func (s *Server) orgToyota(ctx context.Context, orgID string) (toyotaStored, jso PluginSettings json.RawMessage `json:"pluginSettings"` } _ = json.Unmarshal(data, &rec) - var doc toyotaSettingsDoc - if len(rec.PluginSettings) > 0 { - _ = json.Unmarshal(rec.PluginSettings, &doc) - } - return doc.Toyota, rec.PluginSettings + return storedFor(rec.PluginSettings, b), rec.PluginSettings } // userPluginSettings reads a user's raw pluginSettings blob via the service @@ -215,23 +274,19 @@ func (s *Server) userPluginSettings(ctx context.Context, id string) json.RawMess return rec.PluginSettings } -// mergeToyota applies a mutation to the toyota entry of a pluginSettings blob, -// preserving any other plugin keys, and returns the new blob. -func mergeToyota(existing json.RawMessage, apply func(*toyotaStored)) json.RawMessage { - doc := map[string]json.RawMessage{} - if len(existing) > 0 { - _ = json.Unmarshal(existing, &doc) - } - if doc == nil { - doc = map[string]json.RawMessage{} // existing was JSON null - } +// mergeToyota applies a mutation to one brand's entry of a pluginSettings blob, +// preserving any other plugin keys, and returns the new blob. A pre-split entry +// is moved onto its brand on the way through, so the save also migrates it. +func mergeToyota(existing json.RawMessage, b vehicleBrand, apply func(*toyotaStored)) json.RawMessage { + doc := decodePluginSettings(existing) var ts toyotaStored - if raw, ok := doc["toyota"]; ok { + if raw, ok := doc[b.Name]; ok { _ = json.Unmarshal(raw, &ts) } apply(&ts) - b, _ := json.Marshal(ts) - doc["toyota"] = b + ts.Config.Brand = "" + entry, _ := json.Marshal(ts) + doc[b.Name] = entry out, _ := json.Marshal(doc) return out } @@ -265,7 +320,6 @@ func (s *Server) toyotaScopeView(res toyotaResolution, editable string) map[stri "fields": map[string]toyotaFieldView{ "username": field("username", res.eff.Username, own.Username, false), "password": field("password", res.eff.Password, own.Password, true), - "brand": field("brand", res.eff.Brand, own.Brand, false), }, } } @@ -273,8 +327,11 @@ func (s *Server) toyotaScopeView(res toyotaResolution, editable string) map[stri // toyotaView builds the masked, client-safe response body from a resolution. It // exposes a "user" scope for everyone plus, for org admins, an "org" scope — each // with its own locked-field state — so the UI can present the two independently. -func (s *Server) toyotaView(who *callerIdentity, res toyotaResolution) map[string]any { +func (s *Server) toyotaView(who *callerIdentity, res toyotaResolution, b vehicleBrand) map[string]any { out := map[string]any{ + "brand": b.Name, + "make": b.Make, + "app": b.App, "available": res.available, "orgEnabled": res.orgEnabled, "enabled": res.enabled, @@ -297,28 +354,52 @@ func (s *Server) toyotaView(who *callerIdentity, res toyotaResolution) map[strin return out } -// GET /api/integrations/toyota — resolved Toyota view for the caller. +// integrationBrand reads the brand segment of /api/integrations/{brand}. The +// routes are registered once per brand, so a miss is a wiring mistake; it still +// answers 404 rather than falling back to Toyota. +func integrationBrand(w http.ResponseWriter, r *http.Request) (vehicleBrand, bool) { + name := strings.TrimPrefix(r.URL.Path, "/api/integrations/") + if i := strings.IndexByte(name, '/'); i >= 0 { + name = name[:i] + } + b, ok := brandByName(name) + if !ok { + writeError(w, http.StatusNotFound, "unknown integration") + } + return b, ok +} + +// GET /api/integrations/{toyota|lexus|subaru} — resolved view of one brand for +// the caller. func (s *Server) handleGetToyota(w http.ResponseWriter, r *http.Request) { who := caller(r) if who == nil { writeError(w, http.StatusUnauthorized, "not authenticated") return } + b, ok := integrationBrand(w, r) + if !ok { + return + } userRaw := s.userPluginSettings(r.Context(), who.ID) - res := s.resolveToyota(r.Context(), who, userRaw) - writeJSON(w, http.StatusOK, s.toyotaView(who, res)) + res := s.resolveToyota(r.Context(), who, userRaw, b) + writeJSON(w, http.StatusOK, s.toyotaView(who, res, b)) } -// PUT /api/integrations/toyota — save the caller's editable layer. Body: -// {enabled?: bool, scope?: "user"|"org", config?: {username, password, brand}}. -// Fields locked above the caller are ignored; a password left at the mask is -// preserved. +// PUT /api/integrations/{toyota|lexus|subaru} — save the caller's editable layer +// of one brand. Body: {enabled?: bool, scope?: "user"|"org", config?: {username, +// password}}. Fields locked above the caller are ignored; a password left at the +// mask is preserved. func (s *Server) handlePutToyota(w http.ResponseWriter, r *http.Request) { who := caller(r) if who == nil { writeError(w, http.StatusUnauthorized, "not authenticated") return } + b, ok := integrationBrand(w, r) + if !ok { + return + } if !s.pb.Configured() { writeError(w, http.StatusServiceUnavailable, "integration settings not configured on the server") return @@ -334,7 +415,7 @@ func (s *Server) handlePutToyota(w http.ResponseWriter, r *http.Request) { } userRaw := s.userPluginSettings(r.Context(), who.ID) - res := s.resolveToyota(r.Context(), who, userRaw) + res := s.resolveToyota(r.Context(), who, userRaw, b) // Resolve which layer this write targets. Everyone edits their own personal // (user) layer by default; an org admin may target the organization layer by @@ -370,12 +451,11 @@ func (s *Server) handlePutToyota(w http.ResponseWriter, r *http.Request) { } applyField("username", func(c *toyotaConfig, v string) { c.Username = v }) applyField("password", func(c *toyotaConfig, v string) { c.Password = v }) - applyField("brand", func(c *toyotaConfig, v string) { c.Brand = v }) // Persist the organization layer (admins) via the service account. if editable == "org" { - _, orgRaw := s.orgToyota(r.Context(), who.OrgID) - newDoc := mergeToyota(orgRaw, func(ts *toyotaStored) { + _, orgRaw := s.orgToyota(r.Context(), who.OrgID, b) + newDoc := mergeToyota(orgRaw, b, func(ts *toyotaStored) { ts.Config = newOwn // In the org scope the enable flag is the org master switch, stored // inverted (disabled) so absent means enabled. @@ -401,7 +481,7 @@ func (s *Server) handlePutToyota(w http.ResponseWriter, r *http.Request) { // so does the personal config layer when this write targets the user scope. personalEnable := body.Enabled != nil && editable != "org" if personalEnable || editable == "user" { - newDoc := mergeToyota(userRaw, func(ts *toyotaStored) { + newDoc := mergeToyota(userRaw, b, func(ts *toyotaStored) { if personalEnable { ts.Enabled = *body.Enabled } @@ -418,42 +498,45 @@ func (s *Server) handlePutToyota(w http.ResponseWriter, r *http.Request) { // Re-resolve and return the fresh view. fresh := s.userPluginSettings(r.Context(), who.ID) - res2 := s.resolveToyota(r.Context(), who, fresh) - writeJSON(w, http.StatusOK, s.toyotaView(who, res2)) + res2 := s.resolveToyota(r.Context(), who, fresh, b) + writeJSON(w, http.StatusOK, s.toyotaView(who, res2, b)) } -// POST /api/integrations/toyota/health — live probe using the caller's resolved -// config. Never returns secrets. +// POST /api/integrations/{toyota|lexus|subaru}/health — live probe using the +// caller's resolved config for that brand. Never returns secrets. func (s *Server) handleToyotaHealth(w http.ResponseWriter, r *http.Request) { who := caller(r) if who == nil { writeError(w, http.StatusUnauthorized, "not authenticated") return } + b, ok := integrationBrand(w, r) + if !ok { + return + } userRaw := s.userPluginSettings(r.Context(), who.ID) - res := s.resolveToyota(r.Context(), who, userRaw) + res := s.resolveToyota(r.Context(), who, userRaw, b) down := func(detail string) { writeJSON(w, http.StatusOK, map[string]any{"health": map[string]any{"status": "down", "detail": detail}}) } switch { case !res.available: - down("The Toyota integration is disabled by the administrator") + down("The " + b.Make + " integration is disabled by the administrator") return case !res.orgEnabled: - down("The Toyota integration is disabled for your organization") + down("The " + b.Make + " integration is disabled for your organization") return case strings.TrimSpace(res.eff.Username) == "" || strings.TrimSpace(res.eff.Password) == "": - down("Enter your MyToyota email and password to connect") + down("Enter your " + b.App + " email and password to connect") return } cfg := map[string]string{ "username": res.eff.Username, "password": res.eff.Password, - "brand": res.eff.Brand, } - h, err := s.plugins.HealthCheckWith(r.Context(), toyotaPlugin, cfg) + h, err := s.plugins.HealthCheckWith(r.Context(), b.Name, cfg) if err != nil { writeJSON(w, http.StatusBadGateway, map[string]any{"error": err.Error()}) return @@ -461,7 +544,8 @@ func (s *Server) handleToyotaHealth(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"health": h}) } -// GET /api/integrations/toyota/vehicles — the caller's Toyota vehicles as the +// GET /api/integrations/{toyota|lexus|subaru}/vehicles — the caller's vehicles +// on that brand's account as the // upstream returned them, fetched server-side under their resolved credentials. // Gated by the same switches as the settings view (global master, org gate, // personal opt-in, credentials present); when any gate is off it returns 200 with @@ -477,14 +561,18 @@ func (s *Server) handleToyotaVehicles(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusUnauthorized, "not authenticated") return } + b, found := integrationBrand(w, r) + if !found { + return + } userRaw := s.userPluginSettings(r.Context(), who.ID) - cfg, ok, detail := toyotaSource{}.gate(r.Context(), s, who, userRaw) + cfg, ok, detail := toyotaSource{b}.gate(r.Context(), s, who, userRaw) if !ok { writeJSON(w, http.StatusOK, map[string]any{"vehicles": []any{}, "unavailable": true, "detail": detail}) return } - raw, err := s.plugins.InvokeWith(r.Context(), toyotaPlugin, cfg, "vehicles", nil) + raw, err := s.plugins.InvokeWith(r.Context(), b.Name, cfg, "vehicles", nil) if err != nil { writeJSON(w, http.StatusBadGateway, map[string]any{"error": err.Error()}) return diff --git a/API Server/internal/api/integrations_brands_test.go b/API Server/internal/api/integrations_brands_test.go new file mode 100644 index 0000000..2414a54 --- /dev/null +++ b/API Server/internal/api/integrations_brands_test.go @@ -0,0 +1,131 @@ +package api + +import ( + "encoding/json" + "net/http" + "strings" + "testing" +) + +// Toyota, Lexus and Subaru are one connector shown as three integrations, so +// each brand must be a vehicle provider of its own, labelled with its app. +func TestEveryBrandIsAVehicleProvider(t *testing.T) { + want := map[string]string{"toyota": "MyToyota", "lexus": "Lexus Link+", "subaru": "MySubaru"} + for id, label := range want { + src, ok := vehicleSourceByID(id) + if !ok { + t.Errorf("%q is not a vehicle provider", id) + continue + } + if src.label() != label { + t.Errorf("%q label = %q, want %q", id, src.label(), label) + } + } + if n := len(vehicleSources()); n != len(want) { + t.Errorf("vehicle providers = %d, want %d", n, len(want)) + } +} + +// Before the split every brand lived under pluginSettings.toyota with a brand +// field. A Lexus or Subaru entry there belongs to that brand now, and must leave +// the Toyota card empty rather than show the other brand's login. +func TestLegacyBrandEntryMovesToItsBrand(t *testing.T) { + lexus, _ := brandByName("lexus") + subaru, _ := brandByName("subaru") + raw := json.RawMessage(`{"toyota":{"config":{"username":"me@x","password":"pw","brand":"L"},"enabled":true},"anker-solix":{"enabled":true}}`) + + if got := storedFor(raw, lexus); got.Config.Username != "me@x" || got.Config.Password != "pw" || !got.Enabled { + t.Errorf("lexus entry = %+v, want the legacy login, enabled", got) + } + if got := storedFor(raw, toyotaBrand); got.Config.Username != "" || got.Enabled { + t.Errorf("toyota entry = %+v, want empty — the legacy login was a Lexus one", got) + } + if got := storedFor(raw, subaru); got.Config.Username != "" { + t.Errorf("subaru entry = %+v, want empty", got) + } + + // Saving any brand writes the move back and keeps unrelated plugins. + out := mergeToyota(raw, toyotaBrand, func(ts *toyotaStored) { ts.Config.Username = "t@x" }) + var doc map[string]map[string]any + _ = json.Unmarshal(out, &doc) + if doc["lexus"] == nil || doc["anker-solix"] == nil { + t.Fatalf("merged doc lost an entry: %s", out) + } + if cfg, _ := doc["toyota"]["config"].(map[string]any); cfg["username"] != "t@x" || cfg["brand"] != nil { + t.Errorf("toyota entry after save = %v", doc["toyota"]) + } + + // A plain Toyota entry, with or without the old field, stays where it is. + for _, plain := range []string{ + `{"toyota":{"config":{"username":"t@x","brand":"T"}}}`, + `{"toyota":{"config":{"username":"t@x"}}}`, + } { + if got := storedFor(json.RawMessage(plain), toyotaBrand); got.Config.Username != "t@x" { + t.Errorf("%s: toyota entry = %+v", plain, got) + } + } + + // A brand that already has its own entry keeps it; the legacy one is dropped. + both := json.RawMessage(`{"toyota":{"config":{"username":"old","brand":"S"}},"subaru":{"config":{"username":"new"}}}`) + if got := storedFor(both, subaru); got.Config.Username != "new" { + t.Errorf("subaru entry = %+v, want its own", got) + } +} + +// A car linked before the split says provider "toyota" whatever its make; it +// must read through its own brand's account. +func TestLegacyCarLinkFollowsItsMake(t *testing.T) { + cases := []struct{ provider, make, want string }{ + {"toyota", "Lexus", "lexus"}, + {"toyota", "SUBARU", "subaru"}, + {"toyota", "Toyota", "toyota"}, + {"toyota", "", "toyota"}, + {"lexus", "Lexus", "lexus"}, + } + for _, c := range cases { + src, ok := carVehicleSource(c.provider, c.make) + if !ok || src.id() != c.want { + t.Errorf("carVehicleSource(%q, %q) = %v, want %q", c.provider, c.make, src, c.want) + } + } +} + +// Each brand answers on its own route with its own identity, and the provider +// listing offers all three — the server end of "three plugins in the apps". +func TestEveryBrandHasItsOwnIntegrationRoutes(t *testing.T) { + srv := newProviderTestServer(t, &fakeProviderPB{}) + + for _, c := range []struct{ brand, make, app string }{ + {"toyota", "Toyota", "MyToyota"}, + {"lexus", "Lexus", "Lexus Link+"}, + {"subaru", "Subaru", "MySubaru"}, + } { + status, body := call(t, srv, http.MethodGet, "/api/integrations/"+c.brand, "") + if status != http.StatusOK { + t.Errorf("GET %s: status %d", c.brand, status) + continue + } + if body["brand"] != c.brand || body["make"] != c.make || body["app"] != c.app { + t.Errorf("GET %s: identity = %v/%v/%v", c.brand, body["brand"], body["make"], body["app"]) + } + scopes, _ := body["scopes"].(map[string]any) + user, _ := scopes["user"].(map[string]any) + fields, _ := user["fields"].(map[string]any) + if _, hasBrand := fields["brand"]; hasBrand || fields["username"] == nil { + t.Errorf("GET %s: fields = %v, want username/password and no brand picker", c.brand, fields) + } + + // Plugin not enabled for lexus/subaru in this store: the probe says so, + // naming the brand rather than Toyota. + status, body = call(t, srv, http.MethodPost, "/api/integrations/"+c.brand+"/health", "") + h, _ := body["health"].(map[string]any) + if status != http.StatusOK || h["status"] != "down" || !strings.Contains(h["detail"].(string), c.make) { + t.Errorf("POST %s/health: %d %v", c.brand, status, body) + } + } + + _, body := call(t, srv, http.MethodGet, "/api/vehicle-providers", "") + if list, _ := body["providers"].([]any); len(list) != 3 { + t.Errorf("providers = %v, want three", body["providers"]) + } +} diff --git a/API Server/internal/api/server.go b/API Server/internal/api/server.go index 154fcd7..757c061 100644 --- a/API Server/internal/api/server.go +++ b/API Server/internal/api/server.go @@ -45,9 +45,9 @@ // DELETE /api/admin/plugins/{name} POST /api/admin/plugins/{name}/health // // # integrations (per-user plugin settings; superadmin → org admin → user cascade) -// GET /api/integrations/toyota PUT /api/integrations/toyota -// POST /api/integrations/toyota/health -// GET /api/integrations/toyota/vehicles +// GET /api/integrations/{toyota|lexus|subaru} PUT (same) +// POST /api/integrations/{toyota|lexus|subaru}/health +// GET /api/integrations/{toyota|lexus|subaru}/vehicles // GET /api/integrations/anker-solix PUT /api/integrations/anker-solix // POST /api/integrations/anker-solix/health // GET /api/integrations/anker-solix/chargers @@ -142,6 +142,7 @@ import ( "drivervault/apiserver/internal/ocpp" "drivervault/apiserver/internal/pb" "drivervault/apiserver/internal/plugins" + "drivervault/apiserver/internal/plugins/builtin/toyota" _ "drivervault/apiserver/internal/plugins/builtin" // register built-in plugins ) @@ -444,10 +445,15 @@ func (s *Server) Handler() http.Handler { // Integrations — per-user plugin settings under the superadmin → org admin → // user cascade (see integrations.go). Any authenticated user manages their // own layer; an org admin may also target their organization's layer. - mux.HandleFunc("GET /api/integrations/toyota", s.handleGetToyota) - mux.HandleFunc("PUT /api/integrations/toyota", s.handlePutToyota) - mux.HandleFunc("POST /api/integrations/toyota/health", s.handleToyotaHealth) - mux.HandleFunc("GET /api/integrations/toyota/vehicles", s.handleToyotaVehicles) + // Toyota, Lexus and Subaru are one connector registered once per brand; each + // gets its own routes, so the apps can show them as three integrations. + for _, b := range toyota.Brands { + base := "/api/integrations/" + b.Name + mux.HandleFunc("GET "+base, s.handleGetToyota) + mux.HandleFunc("PUT "+base, s.handlePutToyota) + mux.HandleFunc("POST "+base+"/health", s.handleToyotaHealth) + mux.HandleFunc("GET "+base+"/vehicles", s.handleToyotaVehicles) + } mux.HandleFunc("GET /api/integrations/anker-solix", s.handleGetAnker) mux.HandleFunc("PUT /api/integrations/anker-solix", s.handlePutAnker) mux.HandleFunc("POST /api/integrations/anker-solix/health", s.handleAnkerHealth) diff --git a/API Server/internal/api/vehicleproviders.go b/API Server/internal/api/vehicleproviders.go index c22a914..49a35fc 100644 --- a/API Server/internal/api/vehicleproviders.go +++ b/API Server/internal/api/vehicleproviders.go @@ -49,6 +49,7 @@ import ( "drivervault/apiserver/internal/models" "drivervault/apiserver/internal/plugins" + "drivervault/apiserver/internal/plugins/builtin/toyota" ) // vehicleSource adapts one plugin that can enumerate the caller's vehicles and @@ -73,9 +74,30 @@ type vehicleSource interface { sections() []providerSection } -// vehicleSources are the registered providers, in menu order. +// vehicleSources are the registered providers, in menu order: one per brand of +// the Toyota Connected Europe connector. func vehicleSources() []vehicleSource { - return []vehicleSource{toyotaSource{}} + out := make([]vehicleSource, 0, len(toyota.Brands)) + for _, b := range toyota.Brands { + out = append(out, toyotaSource{b}) + } + return out +} + +// carVehicleSource is the provider a linked car reads from. A Lexus or a Subaru +// linked before the brands were split carries provider "toyota" — there was only +// the one — so its make picks the brand it now belongs to; reading it through +// the Toyota account would log in to the wrong app. +func carVehicleSource(provider, carMake string) (vehicleSource, bool) { + if provider == toyotaBrand.Name && strings.TrimSpace(carMake) != "" { + mk := toyotaMake(carMake) + for _, b := range toyota.Brands { + if b.Make == mk { + return toyotaSource{b}, true + } + } + } + return vehicleSourceByID(provider) } func vehicleSourceByID(id string) (vehicleSource, bool) { @@ -282,8 +304,13 @@ func (s *Server) linkedVehicles(ctx context.Context, userID, provider string) ma if userID == "" || provider == "" { return out } + filter := fmt.Sprintf("provider='%s'", provider) + if b, ok := brandByName(provider); ok && b.Name != toyotaBrand.Name { + // Cars of this brand linked before the split are under "toyota". + filter = fmt.Sprintf("(%s || (provider='%s' && make='%s'))", filter, toyotaBrand.Name, b.Make) + } res, err := s.pb.List(ctx, colCars, url.Values{ - "filter": {fmt.Sprintf("owner='%s' && provider='%s'", userID, provider)}, + "filter": {fmt.Sprintf("owner='%s' && %s", userID, filter)}, "perPage": {"200"}, }) if err != nil { @@ -531,7 +558,7 @@ func (s *Server) handleCarProvider(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusNotFound, "this car is not linked to a connected service") return } - src, found := vehicleSourceByID(rec.Provider) + src, found := carVehicleSource(rec.Provider, rec.Make) if !found { writeError(w, http.StatusNotFound, "unknown vehicle provider") return @@ -822,7 +849,7 @@ func (s *Server) handleSyncCarProvider(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusBadRequest, "this car is not linked to a connected service") return } - src, found := vehicleSourceByID(rec.Provider) + src, found := carVehicleSource(rec.Provider, rec.Make) if !found { writeError(w, http.StatusNotFound, "unknown vehicle provider") return diff --git a/API Server/internal/api/vehicleproviders_toyota.go b/API Server/internal/api/vehicleproviders_toyota.go index 9912596..58a6efc 100644 --- a/API Server/internal/api/vehicleproviders_toyota.go +++ b/API Server/internal/api/vehicleproviders_toyota.go @@ -1,7 +1,9 @@ package api // toyotaSource is the first vehicleSource: Toyota Connected Europe, the backend -// behind the MyToyota app (see internal/plugins/builtin/toyota). It contributes +// behind the MyToyota app (see internal/plugins/builtin/toyota), and behind the +// Lexus and Subaru apps too. There is one source per brand, so each shows up as +// a provider of its own, labelled with the app its owner knows. It contributes // nothing but wiring — credentials come from the cascade already in // integrations.go, and the payload walking lives in vehicleproviders.go — which // is the shape the next manufacturer's adapter should copy. @@ -12,14 +14,13 @@ import ( "strings" ) -// toyotaLabel is what the user sees: the app they know the account by, not the -// corporate service name behind it. It titles the car's provider tab. -const toyotaLabel = "MyToyota" +// toyotaSource serves one brand. Its label is what the user sees: the app they +// know the account by ("MyToyota", "Lexus Link+"), not the corporate service +// name behind it. It titles the car's provider tab. +type toyotaSource struct{ brand vehicleBrand } -type toyotaSource struct{} - -func (toyotaSource) id() string { return toyotaPlugin } -func (toyotaSource) label() string { return toyotaLabel } +func (t toyotaSource) id() string { return t.brand.Name } +func (t toyotaSource) label() string { return t.brand.App } func (toyotaSource) service() string { return "Toyota Connected Europe" } func (toyotaSource) listAction() string { return "vehicles" } @@ -40,25 +41,25 @@ func (toyotaSource) sections() []providerSection { } } -// gate resolves the caller's MyToyota credentials through the global → org → user -// cascade and reports what is missing when they cannot be used. It is the single -// place those messages are written: handleToyotaVehicles calls it too. -func (toyotaSource) gate(ctx context.Context, s *Server, who *callerIdentity, userRaw json.RawMessage) (map[string]string, bool, string) { - res := s.resolveToyota(ctx, who, userRaw) +// gate resolves the caller's credentials for this brand through the global → org +// → user cascade and reports what is missing when they cannot be used. It is the +// single place those messages are written: handleToyotaVehicles calls it too. +func (t toyotaSource) gate(ctx context.Context, s *Server, who *callerIdentity, userRaw json.RawMessage) (map[string]string, bool, string) { + b := t.brand + res := s.resolveToyota(ctx, who, userRaw, b) switch { case !res.available: - return nil, false, "The Toyota integration is disabled by the administrator" + return nil, false, "The " + b.Make + " integration is disabled by the administrator" case !res.orgEnabled: - return nil, false, "The Toyota integration is disabled for your organization" + return nil, false, "The " + b.Make + " integration is disabled for your organization" case !res.enabled: - return nil, false, "Enable the Toyota integration in Settings to load your vehicles" + return nil, false, "Enable the " + b.Make + " integration in Settings to load your vehicles" case strings.TrimSpace(res.eff.Username) == "" || strings.TrimSpace(res.eff.Password) == "": - return nil, false, "Enter your MyToyota email and password to connect" + return nil, false, "Enter your " + b.App + " email and password to connect" } return map[string]string{ "username": res.eff.Username, "password": res.eff.Password, - "brand": res.eff.Brand, }, true, "" } diff --git a/API Server/internal/plugins/README.md b/API Server/internal/plugins/README.md index 7ae24c3..f2622c4 100644 --- a/API Server/internal/plugins/README.md +++ b/API Server/internal/plugins/README.md @@ -177,7 +177,8 @@ Restart the server. The plugin appears in the panel's **Plugins** card, **disabled** by default. > DriverVault ships four built-in connectors today — `toyota` (Toyota Connected / -> MyToyota, read-only vehicle data), `anker-solix` (Anker Solix V1 EV charger), +> MyToyota, read-only vehicle data; registered three times, as `toyota`, `lexus` +> and `subaru`, so each brand shows up as a plugin of its own), `anker-solix` (Anker Solix V1 EV charger), > `greencell` (Greencell HabuDen EV charger, read over the owner's MQTT broker > rather than a cloud API) and `apprise` (notifications, through an apprise-api > gateway the operator runs) — all blank-imported from `builtin/builtin.go`. The diff --git a/API Server/internal/plugins/builtin/builtin_test.go b/API Server/internal/plugins/builtin/builtin_test.go index 867a125..ac0a21c 100644 --- a/API Server/internal/plugins/builtin/builtin_test.go +++ b/API Server/internal/plugins/builtin/builtin_test.go @@ -24,6 +24,9 @@ func TestEveryBuiltinIsRegistered(t *testing.T) { "apprise": plugins.CategoryNotifications, "greencell": plugins.CategoryChargers, "toyota": plugins.CategoryVehicles, + // One connector, three registrations: see toyota.Brands. + "lexus": plugins.CategoryVehicles, + "subaru": plugins.CategoryVehicles, } for name, category := range want { v, ok := seen[name] diff --git a/API Server/internal/plugins/builtin/toyota/toyota.go b/API Server/internal/plugins/builtin/toyota/toyota.go index 4f83d9b..22dc5f8 100644 --- a/API Server/internal/plugins/builtin/toyota/toyota.go +++ b/API Server/internal/plugins/builtin/toyota/toyota.go @@ -138,8 +138,41 @@ const ( // never fires with a token that expires mid-flight. const tokenExpiryMargin = 30 * time.Second +// Brand is one of the three makes this connector serves. The apps show each as +// a plugin of its own — its own panel entry, its own settings card, its own +// credentials — because an owner thinks of "my Lexus account", not of the +// Toyota Connected Europe backend the three happen to share. The code is one +// connector; only the login realm and a few headers differ (see authFor). +type Brand struct { + Name string // plugin name, also the key under pluginSettings: "toyota" + Code string // the one-letter code the API uses on the wire: "T" + Make string // "Toyota" + App string // the app the owner knows the account by: "MyToyota" + Provider string // the panel's provider line +} + +// Brands are the registered makes, in menu order. +var Brands = []Brand{ + {Name: "toyota", Code: "T", Make: "Toyota", App: "MyToyota", Provider: "Toyota Connected Europe"}, + {Name: "lexus", Code: "L", Make: "Lexus", App: "Lexus Link+", Provider: "Lexus (Toyota Connected Europe)"}, + {Name: "subaru", Code: "S", Make: "Subaru", App: "MySubaru", Provider: "Subaru (Toyota Connected Europe)"}, +} + +// brandByCode finds a brand by its wire code; Toyota for anything unknown. +func brandByCode(code string) Brand { + for _, b := range Brands { + if b.Code == code { + return b + } + } + return Brands[0] +} + func init() { - plugins.Register("toyota", func() plugins.Plugin { return &Plugin{} }) + for _, b := range Brands { + code := b.Code + plugins.Register(b.Name, func() plugins.Plugin { return &Plugin{fixedBrand: code} }) + } } // tokenInfo holds the currently-held OAuth tokens and the derived account UUID. @@ -154,8 +187,11 @@ type tokenInfo struct { type Plugin struct { username string password string - brand string // "T" (Toyota), "L" (Lexus) or "S" (Subaru) - auth brandAuth // the OAuth client for brand, fixed at Init + // fixedBrand is the brand this registration serves, set by its factory. A + // bare &Plugin{} (tests) has none and takes the brand from config instead. + fixedBrand string + brand string // "T" (Toyota), "L" (Lexus) or "S" (Subaru) + auth brandAuth // the OAuth client for brand, fixed at Init mu sync.Mutex // guards tok and the login flow tok *tokenInfo @@ -169,9 +205,10 @@ type Plugin struct { // Descriptor returns the plugin's static metadata for the admin panel. func (p *Plugin) Descriptor() plugins.Descriptor { + b := brandByCode(p.fixedBrand) return plugins.Descriptor{ - Name: "toyota", - Provider: "Toyota Connected Europe", + Name: b.Name, + Provider: b.Provider, Version: "0.4.0", Kind: plugins.KindBuiltin, Category: plugins.CategoryVehicles, @@ -190,21 +227,15 @@ func (p *Plugin) Descriptor() plugins.Descriptor { }, ConfigFields: []plugins.ConfigField{ // Credentials are intentionally NOT required at the global (panel) layer: - // this connector runs under each user's own MyToyota account, supplied in - // the Web App's per-user integration settings. A superadmin/org admin may + // this connector runs under each user's own account, supplied in the + // Web App's per-user integration settings. A superadmin/org admin may // still set a shared (e.g. fleet) account here that users inherit. See the - // cascade in internal/api/integrations.go. - {Key: "username", Label: "MyToyota email", Type: "text", - Help: "The email address for your MyToyota (Toyota Connected Europe) account."}, - {Key: "password", Label: "MyToyota password", Type: "password", Secret: true, - Help: "Your MyToyota account password. Stored locally, sent only to Toyota's login endpoint."}, - {Key: "brand", Label: "Brand", Type: "select", Default: "T", - Help: "Vehicle brand tied to the account. Subaru accounts (Solterra) log in through their own realm on the same service.", - Options: []plugins.SelectOption{ - {Value: "T", Label: "Toyota"}, - {Value: "L", Label: "Lexus"}, - {Value: "S", Label: "Subaru"}, - }}, + // cascade in internal/api/integrations.go. There is no brand field: each + // brand is its own registration. + {Key: "username", Label: b.App + " email", Type: "text", + Help: "The email address for your " + b.App + " account."}, + {Key: "password", Label: b.App + " password", Type: "password", Secret: true, + Help: "Your " + b.App + " account password. Stored locally, sent only to the " + b.Make + " login endpoint."}, }, } } @@ -217,7 +248,10 @@ func (p *Plugin) Init(_ context.Context, config map[string]string) error { p.username = strings.TrimSpace(config["username"]) p.password = config["password"] - p.brand = strings.TrimSpace(config["brand"]) + p.brand = p.fixedBrand + if p.brand == "" { + p.brand = strings.TrimSpace(config["brand"]) + } if p.brand == "" { p.brand = "T" } diff --git a/API Server/internal/plugins/builtin/toyota/toyota_test.go b/API Server/internal/plugins/builtin/toyota/toyota_test.go index 91fc562..6a93574 100644 --- a/API Server/internal/plugins/builtin/toyota/toyota_test.go +++ b/API Server/internal/plugins/builtin/toyota/toyota_test.go @@ -22,34 +22,58 @@ func TestDescriptor(t *testing.T) { if len(d.Capabilities) == 0 { t.Fatal("expected capabilities") } - // The credential + brand fields must be advertised. They are intentionally - // NOT required at the global layer — credentials come from the per-user - // cascade — and the password field must be marked secret. + // The credential fields must be advertised. They are intentionally NOT + // required at the global layer — credentials come from the per-user cascade — + // and the password field must be marked secret. There is no brand field: each + // brand is a registration of its own. fields := map[string]plugins.ConfigField{} for _, f := range d.ConfigFields { fields[f.Key] = f } - for _, k := range []string{"username", "password", "brand"} { + for _, k := range []string{"username", "password"} { if _, ok := fields[k]; !ok { t.Errorf("config field %q should be present", k) } } + if _, ok := fields["brand"]; ok { + t.Error("the brand is fixed per registration and must not be a config field") + } if fields["username"].Required || fields["password"].Required { t.Error("credentials must not be required at the global layer (per-user cascade)") } if !fields["password"].Secret { t.Error("password field must be marked secret") } - // The three brands that share the backend must all be offered: a value the - // select does not list cannot be chosen from the panel. - brands := map[string]bool{} - for _, o := range fields["brand"].Options { - brands[o.Value] = true +} + +// TestBrandRegistrations pins the three faces of the one connector: each brand +// is its own plugin name with its brand fixed, so the panel and the apps list +// Toyota, Lexus and Subaru separately, and a config cannot move one onto +// another's login. +func TestBrandRegistrations(t *testing.T) { + want := map[string]string{"toyota": "T", "lexus": "L", "subaru": "S"} + if len(Brands) != len(want) { + t.Fatalf("Brands = %d entries, want %d", len(Brands), len(want)) } - for _, b := range []string{"T", "L", "S"} { - if !brands[b] { - t.Errorf("brand option %q should be offered", b) + for _, b := range Brands { + code, ok := want[b.Name] + if !ok || code != b.Code { + t.Errorf("brand %q has code %q, want %q", b.Name, b.Code, code) } + p := &Plugin{fixedBrand: b.Code} + if d := p.Descriptor(); d.Name != b.Name || d.Category != plugins.CategoryVehicles { + t.Errorf("brand %q: descriptor name %q category %q", b.Name, d.Name, d.Category) + } + // A stray brand in config (a pre-split setting) must not win. + _ = p.Init(context.Background(), map[string]string{"username": "u", "password": "p", "brand": "T"}) + if p.brand != b.Code { + t.Errorf("brand %q: Init with brand=T gave %q", b.Name, p.brand) + } + } + s := &Plugin{fixedBrand: "S"} + _ = s.Init(context.Background(), map[string]string{"username": "u", "password": "p"}) + if s.auth.clientID != subaruAuth.clientID { + t.Errorf("subaru registration logs in as %q", s.auth.clientID) } } diff --git a/API Server/panel/src/App.vue b/API Server/panel/src/App.vue index 9bcd65f..01309bd 100644 --- a/API Server/panel/src/App.vue +++ b/API Server/panel/src/App.vue @@ -192,10 +192,10 @@ const providersApi = [ ]; const integrationsApi = [ - { method: "GET", path: "/api/integrations/toyota", desc: "Resolved Toyota Connected settings (secrets masked)" }, - { method: "PUT", path: "/api/integrations/toyota", desc: "Save the caller's own layer (user or org scope)" }, - { method: "POST", path: "/api/integrations/toyota/health", desc: "Live probe with the resolved credentials" }, - { method: "GET", path: "/api/integrations/toyota/vehicles", desc: "Raw MyToyota vehicle payload" }, + { method: "GET", path: "/api/integrations/{toyota|lexus|subaru}", desc: "Resolved settings for one brand of Toyota Connected (secrets masked)" }, + { method: "PUT", path: "/api/integrations/{toyota|lexus|subaru}", desc: "Save the caller's own layer (user or org scope)" }, + { method: "POST", path: "/api/integrations/{toyota|lexus|subaru}/health", desc: "Live probe with the resolved credentials" }, + { method: "GET", path: "/api/integrations/{toyota|lexus|subaru}/vehicles", desc: "Raw vehicle payload from that brand's account" }, { method: "GET", path: "/api/integrations/anker-solix", desc: "Resolved Anker Solix settings (secrets masked)" }, { method: "PUT", path: "/api/integrations/anker-solix", desc: "Save the caller's own layer (user or org scope)" }, { method: "POST", path: "/api/integrations/anker-solix/health", desc: "Live probe with the resolved credentials" }, diff --git a/Phone App/assets/i18n/da.json b/Phone App/assets/i18n/da.json index a730d98..d59f88a 100644 --- a/Phone App/assets/i18n/da.json +++ b/Phone App/assets/i18n/da.json @@ -631,6 +631,10 @@ "title": "Integrationer", "subtitle": "Forbind eksterne tjenester til din konto.", "toyotaDesc": "Log ind med din MyToyota-konto for at hente køretøjsdata fra Toyota Connected Europe. Kun Europa.", + "lexus": "Lexus (Lexus Link+)", + "lexusDesc": "Log ind med din Lexus Link+-konto for at hente køretøjsdata fra Toyota Connected Europe. Kun Europa.", + "subaru": "Subaru (MySubaru)", + "subaruDesc": "Log ind med din MySubaru-konto for at hente Solterra-data fra Toyota Connected Europe. Kun Europa.", "enable": "Aktivér for min konto", "enableOrg": "Aktivér for organisationen", "unavailable": "Denne integration er slået fra af administratoren.", @@ -639,9 +643,8 @@ "scopeOrg": "Organisation", "scopeHint": "Organisationens indstillinger gælder for alle i din organisation, der lader et felt stå tomt.", "readOnly": "Denne integrations fælles indstillinger administreres i API-serverens panel; her er de skrivebeskyttede.", - "email": "MyToyota-e-mail", - "password": "MyToyota-adgangskode", - "brand": "Mærke", + "email": "{app}-e-mail", + "password": "{app}-adgangskode", "inherited": "Sat på et højere niveau", "inheritedFrom": "Nedarvet fra {source}", "sourceGlobal": "administratoren", @@ -733,9 +736,6 @@ "greencellCommandTopic": "Emne for QUERY-kommandoen", "greencellCommandTopicHint": "Valgfrit. Greencell beskriver en QUERY-kommando, der får laderen til at publicere med det samme, men ikke det emne, den lytter på. Finder du dit, så skriv det her, og læsninger behøver ikke vente på laderens egen kadence. Brug {sn} for serienummeret.", "toyota": "Toyota Connected (MyToyota)", - "brandToyota": "Toyota", - "brandLexus": "Lexus", - "brandSubaru": "Subaru", "ankerSolix": "Anker Solix (V1 Smart EV Charger)", "categories": { "vehicles": "Bilproducenter", diff --git a/Phone App/assets/i18n/en.json b/Phone App/assets/i18n/en.json index fffa887..65d1d17 100644 --- a/Phone App/assets/i18n/en.json +++ b/Phone App/assets/i18n/en.json @@ -498,6 +498,10 @@ "subtitle": "Connect external services to your account.", "toyota": "Toyota Connected (MyToyota)", "toyotaDesc": "Sign in with your MyToyota account to pull vehicle data from Toyota Connected Europe. Europe only.", + "lexus": "Lexus (Lexus Link+)", + "lexusDesc": "Sign in with your Lexus Link+ account to pull vehicle data from Toyota Connected Europe. Europe only.", + "subaru": "Subaru (MySubaru)", + "subaruDesc": "Sign in with your MySubaru account to pull Solterra vehicle data from Toyota Connected Europe. Europe only.", "enable": "Enable for my account", "enableOrg": "Enable for the organization", "unavailable": "This integration is turned off by the administrator.", @@ -506,12 +510,8 @@ "scopeOrg": "Organization", "scopeHint": "Organization settings apply to everyone in your organization who leaves a field blank.", "readOnly": "You manage this integration's shared settings in the API Server panel; here it is read-only.", - "email": "MyToyota email", - "password": "MyToyota password", - "brand": "Brand", - "brandToyota": "Toyota", - "brandLexus": "Lexus", - "brandSubaru": "Subaru", + "email": "{app} email", + "password": "{app} password", "inherited": "Set above your level", "inheritedFrom": "Inherited from {source}", "sourceGlobal": "the administrator", diff --git a/Phone App/assets/i18n/pl.json b/Phone App/assets/i18n/pl.json index 09f4968..b67df35 100644 --- a/Phone App/assets/i18n/pl.json +++ b/Phone App/assets/i18n/pl.json @@ -639,6 +639,10 @@ "title": "Integracje", "subtitle": "Połącz zewnętrzne usługi ze swoim kontem.", "toyotaDesc": "Zaloguj się kontem MyToyota, aby pobierać dane pojazdu z Toyota Connected Europe. Tylko Europa.", + "lexus": "Lexus (Lexus Link+)", + "lexusDesc": "Zaloguj się kontem Lexus Link+, aby pobierać dane pojazdu z Toyota Connected Europe. Tylko Europa.", + "subaru": "Subaru (MySubaru)", + "subaruDesc": "Zaloguj się kontem MySubaru, aby pobierać dane Solterry z Toyota Connected Europe. Tylko Europa.", "enable": "Włącz dla mojego konta", "enableOrg": "Włącz dla organizacji", "unavailable": "Ta integracja została wyłączona przez administratora.", @@ -647,9 +651,8 @@ "scopeOrg": "Organizacja", "scopeHint": "Ustawienia organizacji obowiązują każdego w Twojej organizacji, kto pozostawi pole puste.", "readOnly": "Wspólnymi ustawieniami tej integracji zarządzasz w panelu API Servera; tutaj są tylko do odczytu.", - "email": "E-mail MyToyota", - "password": "Hasło MyToyota", - "brand": "Marka", + "email": "E-mail {app}", + "password": "Hasło {app}", "inherited": "Ustawione na wyższym poziomie", "inheritedFrom": "Odziedziczone od: {source}", "sourceGlobal": "administratora", @@ -741,9 +744,6 @@ "greencellCommandTopic": "Temat polecenia QUERY", "greencellCommandTopicHint": "Opcjonalne. Greencell opisuje polecenie QUERY, które każe ładowarce natychmiast opublikować dane, ale nie podaje tematu, na którym ona nasłuchuje. Jeśli poznasz swój, wpisz go tutaj, a odczyty przestaną czekać na własny rytm ładowarki. Użyj {sn} zamiast numeru seryjnego.", "toyota": "Toyota Connected (MyToyota)", - "brandToyota": "Toyota", - "brandLexus": "Lexus", - "brandSubaru": "Subaru", "ankerSolix": "Anker Solix (V1 Smart EV Charger)", "categories": { "vehicles": "Producenci samochodów", diff --git a/Phone App/lib/api.dart b/Phone App/lib/api.dart index c623822..a2e19e6 100644 --- a/Phone App/lib/api.dart +++ b/Phone App/lib/api.dart @@ -600,18 +600,21 @@ class ApiClient { // (effective/own/locked per field, secrets and inherited values masked); save… // writes the caller's editable layer (scope "user" by default, "org" for org // admins); test… runs a live probe under the resolved config. - Future getToyota() async { - final data = await _send("GET", "/integrations/toyota"); + // + // brand is "toyota", "lexus" or "subaru": one connector on the server, but + // three integrations with their own accounts. + Future getToyota([String brand = "toyota"]) async { + final data = await _send("GET", "/integrations/$brand"); return IntegrationView.fromJson(Map.from(data)); } - Future saveToyota(Map body) async { - final data = await _send("PUT", "/integrations/toyota", body: body); + Future saveToyota(Map body, [String brand = "toyota"]) async { + final data = await _send("PUT", "/integrations/$brand", body: body); return IntegrationView.fromJson(Map.from(data)); } - Future testToyota() async { - final data = await _send("POST", "/integrations/toyota/health"); + Future testToyota([String brand = "toyota"]) async { + final data = await _send("POST", "/integrations/$brand/health"); final h = (data is Map ? data["health"] : null) ?? {}; return IntegrationHealth.fromJson(Map.from(h)); } diff --git a/Phone App/lib/screens/settings_screen.dart b/Phone App/lib/screens/settings_screen.dart index 1f6d94d..44f77c6 100644 --- a/Phone App/lib/screens/settings_screen.dart +++ b/Phone App/lib/screens/settings_screen.dart @@ -1540,7 +1540,7 @@ class _DangerSectionState extends State<_DangerSection> { // --- Integrations tab ------------------------------------------------------ // -// Three foldable connector cards (Toyota, Anker Solix, Greencell) over a +// Foldable connector cards (Toyota, Lexus, Subaru, Anker Solix, Greencell) over a // superadmin → org admin → user cascade. Each card resolves, per field, the effective value // (secrets/inherited values masked), the caller's own-layer value, its source // layer, and whether it's locked (set above the caller). Org admins get a @@ -1609,6 +1609,9 @@ class _IntegrationConfig { final Future Function(Map) save; final Future Function() test; + /// Filled into every field label — the app name in "{app} email". + final Map labelParams; + const _IntegrationConfig({ required this.nameKey, required this.descKey, @@ -1617,6 +1620,7 @@ class _IntegrationConfig { required this.load, required this.save, required this.test, + this.labelParams = const {}, }); } @@ -1634,29 +1638,26 @@ class _IntegrationsTabState extends State<_IntegrationsTab> { @override Widget build(BuildContext context) { - final toyota = _IntegrationConfig( - nameKey: "settings.integrations.toyota", - descKey: "settings.integrations.toyotaDesc", - anker: false, - load: apiClient.getToyota, - save: apiClient.saveToyota, - test: apiClient.testToyota, - fields: const [ - _FieldSpec(key: "username", labelKey: "settings.integrations.email"), - _FieldSpec(key: "password", labelKey: "settings.integrations.password", type: _FieldType.password), - _FieldSpec( - key: "brand", - labelKey: "settings.integrations.brand", - type: _FieldType.select, - options: [ - ("", "common.empty"), - ("T", "settings.integrations.brandToyota"), - ("L", "settings.integrations.brandLexus"), - ("S", "settings.integrations.brandSubaru"), + // Toyota, Lexus and Subaru are one connector on the server, but each is an + // integration of its own here: its own account, switch and card. + _IntegrationConfig toyotaBrand(String brand, String app) => _IntegrationConfig( + nameKey: "settings.integrations.$brand", + descKey: "settings.integrations.${brand}Desc", + anker: false, + load: () => apiClient.getToyota(brand), + save: (body) => apiClient.saveToyota(body, brand), + test: () => apiClient.testToyota(brand), + labelParams: {"app": app}, + fields: const [ + _FieldSpec(key: "username", labelKey: "settings.integrations.email"), + _FieldSpec(key: "password", labelKey: "settings.integrations.password", type: _FieldType.password), ], - ), - ], - ); + ); + final toyotaBrands = [ + toyotaBrand("toyota", "MyToyota"), + toyotaBrand("lexus", "Lexus Link+"), + toyotaBrand("subaru", "MySubaru"), + ]; final anker = _IntegrationConfig( nameKey: "settings.integrations.ankerSolix", @@ -1786,7 +1787,7 @@ class _IntegrationsTabState extends State<_IntegrationsTab> { // exactly these cards a line below it, so saying how many would be saying it // twice. final groups = [ - [toyota], + toyotaBrands, [anker, greencell], ]; final index = _group.clamp(0, groups.length - 1); @@ -1814,7 +1815,9 @@ class _IntegrationsTabState extends State<_IntegrationsTab> { for (final config in groups[index]) Padding( padding: const EdgeInsets.only(bottom: 12), - child: _IntegrationCard(config: config), + // Keyed, so switching category never hands one card's state + // (its loaded view, its typed password) to another. + child: _IntegrationCard(key: ValueKey(config.nameKey), config: config), ), ], ), @@ -1826,7 +1829,7 @@ class _IntegrationsTabState extends State<_IntegrationsTab> { class _IntegrationCard extends StatefulWidget { final _IntegrationConfig config; - const _IntegrationCard({required this.config}); + const _IntegrationCard({super.key, required this.config}); @override State<_IntegrationCard> createState() => _IntegrationCardState(); } @@ -2333,7 +2336,7 @@ class _IntegrationCardState extends State<_IntegrationCard> { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(t(f.labelKey), style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), + Text(t(f.labelKey, params: _c.labelParams), style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), const SizedBox(height: 4), input, if (hint != null) diff --git a/Web App/web/src/api.js b/Web App/web/src/api.js index ae5f2ed..ca40a6c 100644 --- a/Web App/web/src/api.js +++ b/Web App/web/src/api.js @@ -260,9 +260,13 @@ export const api = { // field, with secrets and inherited usernames masked); saveToyota writes the // caller's editable layer (scope "user" by default, "org" for org admins); // testToyota runs a live login probe under the resolved credentials. - getToyota: () => request("/integrations/toyota"), - saveToyota: (body) => request("/integrations/toyota", { method: "PUT", body: JSON.stringify(body) }), - testToyota: () => request("/integrations/toyota/health", { method: "POST" }), + // + // brand is "toyota", "lexus" or "subaru": one connector on the server, but + // three integrations with their own accounts (see TOYOTA_BRANDS). + getToyota: (brand = "toyota") => request(`/integrations/${brand}`), + saveToyota: (body, brand = "toyota") => + request(`/integrations/${brand}`, { method: "PUT", body: JSON.stringify(body) }), + testToyota: (brand = "toyota") => request(`/integrations/${brand}/health`, { method: "POST" }), // Vehicle providers — manufacturer services a car can be created from, and the // data feed behind a car's provider tab. Every call runs server-side under the diff --git a/Web App/web/src/components/ToyotaBrandIntegration.vue b/Web App/web/src/components/ToyotaBrandIntegration.vue new file mode 100644 index 0000000..d950ddf --- /dev/null +++ b/Web App/web/src/components/ToyotaBrandIntegration.vue @@ -0,0 +1,258 @@ + + + diff --git a/Web App/web/src/i18n/da.json b/Web App/web/src/i18n/da.json index 514ff2f..cbc270e 100644 --- a/Web App/web/src/i18n/da.json +++ b/Web App/web/src/i18n/da.json @@ -593,6 +593,10 @@ "subtitle": "Forbind eksterne tjenester til din konto.", "toyota": "Toyota Connected (MyToyota)", "toyotaDesc": "Log ind med din MyToyota-konto for at hente køretøjsdata fra Toyota Connected Europe. Kun Europa.", + "lexus": "Lexus (Lexus Link+)", + "lexusDesc": "Log ind med din Lexus Link+-konto for at hente køretøjsdata fra Toyota Connected Europe. Kun Europa.", + "subaru": "Subaru (MySubaru)", + "subaruDesc": "Log ind med din MySubaru-konto for at hente Solterra-data fra Toyota Connected Europe. Kun Europa.", "enable": "Aktivér for min konto", "enableOrg": "Aktivér for organisationen", "unavailable": "Denne integration er slået fra af administratoren.", @@ -601,12 +605,8 @@ "scopeOrg": "Organisation", "scopeHint": "Organisationens indstillinger gælder for alle i din organisation, der lader et felt stå tomt.", "readOnly": "Denne integrations fælles indstillinger administreres i API-serverens panel; her er de skrivebeskyttede.", - "email": "MyToyota-e-mail", - "password": "MyToyota-adgangskode", - "brand": "Mærke", - "brandToyota": "Toyota", - "brandLexus": "Lexus", - "brandSubaru": "Subaru", + "email": "{app}-e-mail", + "password": "{app}-adgangskode", "inherited": "Sat på et højere niveau", "inheritedFrom": "Nedarvet fra {source}", "sourceGlobal": "administratoren", diff --git a/Web App/web/src/i18n/en.json b/Web App/web/src/i18n/en.json index cef4fcd..ac14b72 100644 --- a/Web App/web/src/i18n/en.json +++ b/Web App/web/src/i18n/en.json @@ -592,6 +592,10 @@ "subtitle": "Connect external services to your account.", "toyota": "Toyota Connected (MyToyota)", "toyotaDesc": "Sign in with your MyToyota account to pull vehicle data from Toyota Connected Europe. Europe only.", + "lexus": "Lexus (Lexus Link+)", + "lexusDesc": "Sign in with your Lexus Link+ account to pull vehicle data from Toyota Connected Europe. Europe only.", + "subaru": "Subaru (MySubaru)", + "subaruDesc": "Sign in with your MySubaru account to pull Solterra vehicle data from Toyota Connected Europe. Europe only.", "enable": "Enable for my account", "enableOrg": "Enable for the organization", "unavailable": "This integration is turned off by the administrator.", @@ -600,12 +604,8 @@ "scopeOrg": "Organization", "scopeHint": "Organization settings apply to everyone in your organization who leaves a field blank.", "readOnly": "You manage this integration's shared settings in the API Server panel; here it is read-only.", - "email": "MyToyota email", - "password": "MyToyota password", - "brand": "Brand", - "brandToyota": "Toyota", - "brandLexus": "Lexus", - "brandSubaru": "Subaru", + "email": "{app} email", + "password": "{app} password", "inherited": "Set above your level", "inheritedFrom": "Inherited from {source}", "sourceGlobal": "the administrator", diff --git a/Web App/web/src/i18n/pl.json b/Web App/web/src/i18n/pl.json index 7eef65d..a98db06 100644 --- a/Web App/web/src/i18n/pl.json +++ b/Web App/web/src/i18n/pl.json @@ -599,6 +599,10 @@ "subtitle": "Połącz zewnętrzne usługi ze swoim kontem.", "toyota": "Toyota Connected (MyToyota)", "toyotaDesc": "Zaloguj się kontem MyToyota, aby pobierać dane pojazdu z Toyota Connected Europe. Tylko Europa.", + "lexus": "Lexus (Lexus Link+)", + "lexusDesc": "Zaloguj się kontem Lexus Link+, aby pobierać dane pojazdu z Toyota Connected Europe. Tylko Europa.", + "subaru": "Subaru (MySubaru)", + "subaruDesc": "Zaloguj się kontem MySubaru, aby pobierać dane Solterry z Toyota Connected Europe. Tylko Europa.", "enable": "Włącz dla mojego konta", "enableOrg": "Włącz dla organizacji", "unavailable": "Ta integracja została wyłączona przez administratora.", @@ -607,12 +611,8 @@ "scopeOrg": "Organizacja", "scopeHint": "Ustawienia organizacji obowiązują każdego w Twojej organizacji, kto pozostawi pole puste.", "readOnly": "Wspólnymi ustawieniami tej integracji zarządzasz w panelu API Servera; tutaj są tylko do odczytu.", - "email": "E-mail MyToyota", - "password": "Hasło MyToyota", - "brand": "Marka", - "brandToyota": "Toyota", - "brandLexus": "Lexus", - "brandSubaru": "Subaru", + "email": "E-mail {app}", + "password": "Hasło {app}", "inherited": "Ustawione na wyższym poziomie", "inheritedFrom": "Odziedziczone od: {source}", "sourceGlobal": "administratora", diff --git a/Web App/web/src/views/Settings.vue b/Web App/web/src/views/Settings.vue index b5cf84f..4cf0aba 100644 --- a/Web App/web/src/views/Settings.vue +++ b/Web App/web/src/views/Settings.vue @@ -11,6 +11,7 @@ import { TAB_SURFACES, SETTINGS_TABS, defaultTabFor } from "../lib/tabs.js"; import { askConfirm } from "../lib/confirm.js"; import OrgManager from "../components/OrgManager.vue"; import AdminUsers from "../components/AdminUsers.vue"; +import ToyotaBrandIntegration from "../components/ToyotaBrandIntegration.vue"; const router = useRouter(); const route = useRoute(); @@ -53,7 +54,6 @@ function selectTab(tab) { // Each integration card folds open/closed, like the plugin rows in the API // Server panel. Collapsed by default so the Integrations tab reads as a compact // list of connectors you expand to configure. -const toyotaOpen = ref(false); const ankerOpen = ref(false); const greencellOpen = ref(false); @@ -355,129 +355,32 @@ function inheritedPlaceholder(field, example = "") { return field.locked ? field.effective || "" : example; } -// --- Integrations: Toyota Connected (per-user, cascading settings) --- +// --- Integrations: Toyota Connected (Toyota, Lexus, Subaru) --- // -// The server resolves a superadmin → org admin → user cascade and returns, per -// field, the effective value (secrets/inherited usernames masked), the caller's -// own-layer value, its source layer, and whether it's locked (set above us). -// An org admin gets a second "org" scope to edit organization-wide defaults. - -const toyota = ref(null); // resolved view from the server -const toyotaScope = ref("user"); // "user" | "org" (org admins only) -const toyotaForm = ref({ username: "", password: "", brand: "" }); -const toyotaSaving = ref(false); -const toyotaSaved = ref(false); -const toyotaError = ref(""); -const toyotaTesting = ref(false); -const toyotaHealth = ref(null); // { status, detail } from the last test - -// Superadmins manage the shared (global) layer in the API Server panel; here the -// credential fields are read-only (they may still toggle their own opt-in). -const toyotaReadOnly = computed(() => !!toyota.value?.isSuperadmin); -const toyotaScopeKey = computed(() => (toyota.value?.isSuperadmin ? "user" : toyotaScope.value)); -const toyotaScopeData = computed( - () => toyota.value?.scopes?.[toyotaScopeKey.value] || { editableLayer: "user", fields: {} } -); -const toyotaEditingOrg = computed(() => toyotaScopeKey.value === "org"); - -function toyotaField(k) { - return toyotaScopeData.value.fields?.[k] || { effective: "", own: "", source: "unset", locked: false }; -} -// A field is locked when it's set above the caller's editable layer, or the -// whole scope is read-only (superadmin). -function toyotaLocked(k) { - return toyotaReadOnly.value || toyotaField(k).locked; -} -// The toggle reflects the personal opt-in normally, or the org gate in org scope. -const toyotaEnabled = computed(() => - toyotaEditingOrg.value ? toyota.value?.orgEnabled : toyota.value?.enabled -); -// A friendly "inherited from …" note for a locked field. -function toyotaSourceLabel(k) { - const map = { global: "sourceGlobal", org: "sourceOrg", user: "sourceUser" }; - const key = map[toyotaField(k).source] || "sourceGlobal"; - return t("settings.integrations.inheritedFrom", { source: t("settings.integrations." + key) }); -} - -// Load the editable inputs from the current scope's own-layer values. Locked -// fields and the secret password are never prefilled. -function fillToyotaForm() { - const f = toyotaScopeData.value.fields || {}; - toyotaForm.value = { - username: f.username?.locked ? "" : f.username?.own || "", - password: "", - brand: f.brand?.locked ? "" : f.brand?.own || "", - }; -} - -function applyToyotaView(body) { - toyota.value = body; - // Keep the selected scope valid (fall back to personal when org isn't offered). - if (toyotaScope.value === "org" && !body.canEditOrg) toyotaScope.value = "user"; - fillToyotaForm(); -} +// One connector on the server, three integrations here: each brand has its own +// account, enable switch and card (see components/ToyotaBrandIntegration.vue). +// The views are loaded here so the category tabs know which cards exist; a +// brand the server does not know (an older API Server) simply has no card. +const TOYOTA_BRANDS = ["toyota", "lexus", "subaru"]; +const toyotaViews = ref({}); // brand -> resolved view from the server async function loadToyota() { - try { - applyToyotaView(await api.getToyota()); - } catch (e) { - toyotaError.value = e.message; - } + await Promise.all( + TOYOTA_BRANDS.map(async (brand) => { + try { + toyotaViews.value = { ...toyotaViews.value, [brand]: await api.getToyota(brand) }; + } catch { + // Not offered by this server; leave the card out. + } + }) + ); } -// Refill the form when an admin flips between personal and organization scope. -watch(toyotaScope, () => { - toyotaError.value = ""; - toyotaSaved.value = false; - toyotaHealth.value = null; - fillToyotaForm(); -}); - -async function toggleToyota(v) { - toyotaError.value = ""; - const org = toyotaEditingOrg.value; - try { - applyToyotaView(await api.saveToyota(org ? { scope: "org", enabled: v } : { scope: "user", enabled: v })); - } catch (e) { - toyotaError.value = e.message; - } +function setToyotaView(brand, body) { + toyotaViews.value = { ...toyotaViews.value, [brand]: body }; } -async function saveToyotaSettings() { - toyotaError.value = ""; - toyotaSaving.value = true; - toyotaSaved.value = false; - const config = {}; - for (const k of ["username", "password", "brand"]) { - if (toyotaLocked(k)) continue; - // Only send the password when the user actually typed a new one. - if (k === "password" && !toyotaForm.value.password) continue; - config[k] = toyotaForm.value[k]; - } - try { - applyToyotaView(await api.saveToyota({ scope: toyotaScopeKey.value, config })); - toyotaSaved.value = true; - setTimeout(() => (toyotaSaved.value = false), 2000); - } catch (e) { - toyotaError.value = e.message; - } finally { - toyotaSaving.value = false; - } -} - -async function testToyotaConnection() { - toyotaError.value = ""; - toyotaHealth.value = null; - toyotaTesting.value = true; - try { - const { health } = await api.testToyota(); - toyotaHealth.value = health; - } catch (e) { - toyotaError.value = e.message; - } finally { - toyotaTesting.value = false; - } -} +const toyotaBrandsLoaded = computed(() => TOYOTA_BRANDS.filter((b) => toyotaViews.value[b])); // --- Integrations: category tabs --- // @@ -491,7 +394,7 @@ async function testToyotaConnection() { const INTEGRATION_CATEGORIES = ["vehicles", "chargers"]; const integrationsByCategory = computed(() => ({ - vehicles: [toyota.value && "toyota"].filter(Boolean), + vehicles: toyotaBrandsLoaded.value, chargers: [anker.value && "anker", greencell.value && "greencell"].filter(Boolean), })); @@ -1394,7 +1297,7 @@ onBeforeUnmount(() => {
-
+

{{ t("settings.integrations.title") }}

{{ t("settings.integrations.subtitle") }}

@@ -1414,135 +1317,15 @@ onBeforeUnmount(() => {
-
- - -
- -

{{ t("settings.integrations.unavailable") }}

-

- {{ t("settings.integrations.orgDisabled") }} -

- - - -

{{ toyotaError }}

-
-
+ +