Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9deff308b6 | ||
|
|
2e3d7ba062 | ||
|
|
5ab87fa9f0 | ||
|
|
62be80c9d8 | ||
|
|
2a6f9697b8 |
@@ -375,6 +375,27 @@ lose (or keep) access to the wrong devices.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Firestore Schema v1 (devices)
|
||||||
|
|
||||||
|
The tablet and phone apps (FlutterFlow) and this console share Firestore. The contract
|
||||||
|
is the `bellsystems-schema` repo (`C:\development\bellsystems-schema`, `v1/firestore.schema.json`).
|
||||||
|
One wrongly typed field makes the apps **silently drop the whole device** from the user's list.
|
||||||
|
|
||||||
|
- Every device write goes through `backend/devices/firestore_v1.py` (`to_firestore`), every
|
||||||
|
read through `to_api`. Never write a device dict to Firestore any other way.
|
||||||
|
- Timestamps: ISO 8601 strings in the API, Firestore Timestamps in the DB. Unset = `null`, never `""`.
|
||||||
|
- IP addresses: dotted strings (`"10.0.0.5"`), never octet arrays. The firmware's
|
||||||
|
`network.set_config` MQTT command has its own names (`useStaticIP`, `ip`) — that's the
|
||||||
|
MQTT protocol, not Firestore.
|
||||||
|
- Key spelling is the apps': `bellguardSafetyOn`, `usesStaticIP`, `maintainancePeriod`.
|
||||||
|
- `device_id` and `serial_number` are always equal (decision D1); `serial_number` is canonical.
|
||||||
|
- Hardware identity is `hw_family` / `hw_revision` — the firmware's NVS names (decision D2).
|
||||||
|
`hw_family` is a code (`vesper_plus`), never a label (`"Bell Plus"`). The firmware *catalog*
|
||||||
|
(`/api/firmware/{hw_type}/…`, flash assets) keeps `hw_type` as its variable name — same values.
|
||||||
|
- Check live data with `node tools/audit.js <service-account.json>` in the schema repo.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## API Client
|
## API Client
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@@ -39,6 +39,20 @@ bellsystems-admin/
|
|||||||
└── .env
|
└── .env
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Shared data contract (Firestore schema v1)
|
||||||
|
|
||||||
|
Firestore is shared with the BellSystems tablet and phone apps (FlutterFlow). Device
|
||||||
|
documents must follow the schema in the **bellsystems-schema** repo
|
||||||
|
(`v1/firestore.schema.json`) — one wrongly typed field makes the apps silently hide the
|
||||||
|
device from its users.
|
||||||
|
|
||||||
|
- All device writes go through `backend/devices/firestore_v1.py`.
|
||||||
|
- Adding or changing a shared field: update the schema repo first, then every app and this
|
||||||
|
console in the same release.
|
||||||
|
- Check production data: `node tools/audit.js <service-account.json>` in the schema repo.
|
||||||
|
|
||||||
|
Details: the "Firestore Schema v1" section of `CLAUDE.md`.
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
See `BellSystems_AdminPanel_Strategy.md` for the full architecture and build plan.
|
See `BellSystems_AdminPanel_Strategy.md` for the full architecture and build plan.
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
"""Device documents <-> Firestore schema v1.
|
||||||
|
|
||||||
|
The contract lives in the bellsystems-schema repo (v1/firestore.schema.json). v1 is
|
||||||
|
the shape the shipped tablet and phone apps read. FlutterFlow parses each document
|
||||||
|
inside safeGet: ONE field of the wrong type makes the app silently drop the whole
|
||||||
|
device from the user's list. So every console write to a device goes through
|
||||||
|
`to_firestore`, and every read goes through `to_api`.
|
||||||
|
|
||||||
|
Rules enforced here (README "rules every writer must follow"):
|
||||||
|
- Timestamps are Firestore Timestamps (datetime). Unset = None, never "".
|
||||||
|
- IP addresses are dotted strings ("10.0.0.5"), never octet arrays.
|
||||||
|
- Exact v1 key spelling: bellguardSafetyOn, usesStaticIP. The misspellings
|
||||||
|
bellGuardSafetyOn / useStaticIP / users_list are converted or dropped.
|
||||||
|
- device_id and serial_number are equal (decision D1); serial_number is canonical.
|
||||||
|
- device_melodies_all items use the MelodyMainItem shape (mainInformation, ...).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from google.cloud.firestore_v1 import DocumentReference, GeoPoint
|
||||||
|
|
||||||
|
from shared.exceptions import ValidationError
|
||||||
|
|
||||||
|
# Keys inside device_attributes (and its nested maps) that hold Timestamps.
|
||||||
|
TIMESTAMP_KEYS = {
|
||||||
|
"towerClockTime",
|
||||||
|
"daySilenceFrom", "daySilenceTo",
|
||||||
|
"nightSilenceFrom", "nightSilenceTo",
|
||||||
|
"backlightTurnOnTime", "backlightTurnOffTime",
|
||||||
|
"subscrStart",
|
||||||
|
"warrantyStart", "maintainedOn",
|
||||||
|
}
|
||||||
|
|
||||||
|
IP_KEYS = {"ipAddress", "gateway", "subnet", "dns1", "dns2"}
|
||||||
|
|
||||||
|
# Misspelled key -> v1 key, per nested map. A value of None means "drop".
|
||||||
|
LEGACY_KEYS: dict[str, dict[str, str | None]] = {
|
||||||
|
# hw_type / hw_version: pre-2026-11-08 names; the firmware NVS uses hw_family / hw_revision.
|
||||||
|
"": {"users_list": None, "hw_type": "hw_family", "hw_version": "hw_revision"},
|
||||||
|
"device_attributes": {"bellGuardSafetyOn": "bellguardSafetyOn"},
|
||||||
|
"device_attributes.networkSettings": {"useStaticIP": "usesStaticIP"},
|
||||||
|
}
|
||||||
|
|
||||||
|
# Shape of a melody stored inside a device (MelodyMainItem) vs. a melodies/{id} doc.
|
||||||
|
_MELODY_ITEM_FORBIDDEN = {"information", "default_settings", "url"}
|
||||||
|
|
||||||
|
# Format the console API used to serve before ISO 8601 ("15 January 2026 at 22:01:00 UTC+0000").
|
||||||
|
# Still accepted on write so a browser tab opened before the deploy can't corrupt data.
|
||||||
|
_LEGACY_DISPLAY_FMT = "%d %B %Y at %H:%M:%S UTC%z"
|
||||||
|
|
||||||
|
# Board family code: a BoardType value ("vesper_plus") or a bespoke UID. Never a display
|
||||||
|
# label like "Bell Plus" — the firmware builds its OTA URL from this value.
|
||||||
|
_HW_FAMILY = re.compile(r"^[a-z0-9][a-z0-9_-]*$")
|
||||||
|
|
||||||
|
_IPV4 = re.compile(r"^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- write side
|
||||||
|
|
||||||
|
|
||||||
|
def to_timestamp(value: Any, field: str) -> datetime | None:
|
||||||
|
"""Coerce an API value into a Firestore Timestamp (tz-aware datetime) or None."""
|
||||||
|
if value is None or value == "":
|
||||||
|
return None
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
|
||||||
|
if isinstance(value, str):
|
||||||
|
s = value.strip()
|
||||||
|
try:
|
||||||
|
dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
|
||||||
|
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
return datetime.strptime(s, _LEGACY_DISPLAY_FMT)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
raise ValidationError(f"{field}: expected an ISO 8601 timestamp or null, got {value!r}")
|
||||||
|
|
||||||
|
|
||||||
|
def to_ipv4(value: Any, field: str) -> str:
|
||||||
|
"""Coerce an API value into a dotted IPv4 string. "" means not set."""
|
||||||
|
if value is None:
|
||||||
|
return ""
|
||||||
|
if isinstance(value, (list, tuple)):
|
||||||
|
parts = [str(p).strip() for p in value if str(p).strip() != ""]
|
||||||
|
if not parts:
|
||||||
|
return ""
|
||||||
|
value = ".".join(parts)
|
||||||
|
if isinstance(value, str):
|
||||||
|
s = value.strip()
|
||||||
|
if s == "" or _IPV4.match(s):
|
||||||
|
return s
|
||||||
|
raise ValidationError(f"{field}: expected a dotted IPv4 address like \"10.0.0.5\", got {value!r}")
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_map(data: dict, path: str) -> dict:
|
||||||
|
"""Recursively apply key renames, timestamp and IP coercion to one map."""
|
||||||
|
renames = LEGACY_KEYS.get(path, {})
|
||||||
|
out: dict = {}
|
||||||
|
# v1 keys first, so a legacy duplicate never overwrites a correct value
|
||||||
|
# that is also present in the same map.
|
||||||
|
for key in sorted(data, key=lambda k: k in renames):
|
||||||
|
value = data[key]
|
||||||
|
if key in renames:
|
||||||
|
target = renames[key]
|
||||||
|
if target is None or target in out or target in data:
|
||||||
|
continue # drop the legacy key (v1 key present, or field is retired)
|
||||||
|
key = target
|
||||||
|
child = f"{path}.{key}" if path else key
|
||||||
|
if isinstance(value, dict):
|
||||||
|
value = _normalize_map(value, child)
|
||||||
|
elif key in TIMESTAMP_KEYS and path:
|
||||||
|
value = to_timestamp(value, child)
|
||||||
|
elif key in IP_KEYS and path.endswith("networkSettings"):
|
||||||
|
value = to_ipv4(value, child)
|
||||||
|
out[key] = value
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _user_ref(db, entry) -> DocumentReference:
|
||||||
|
if isinstance(entry, DocumentReference):
|
||||||
|
return entry
|
||||||
|
uid = str(entry).strip().split("/")[-1]
|
||||||
|
if not uid:
|
||||||
|
raise ValidationError(f"user_list: empty entry {entry!r}")
|
||||||
|
return db.collection("users").document(uid)
|
||||||
|
|
||||||
|
|
||||||
|
def _check_melodies(items: Any, db) -> list:
|
||||||
|
if items is None:
|
||||||
|
return []
|
||||||
|
if not isinstance(items, list):
|
||||||
|
raise ValidationError("device_melodies_all: expected a list")
|
||||||
|
out = []
|
||||||
|
for i, item in enumerate(items):
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
raise ValidationError(f"device_melodies_all[{i}]: expected an object")
|
||||||
|
bad = _MELODY_ITEM_FORBIDDEN & item.keys()
|
||||||
|
if bad:
|
||||||
|
raise ValidationError(
|
||||||
|
f"device_melodies_all[{i}]: uses melodies-collection keys {sorted(bad)}; "
|
||||||
|
"device melodies must use mainInformation / defaultSettings / settings / binaryUrl"
|
||||||
|
)
|
||||||
|
ref = item.get("melodyReference")
|
||||||
|
if isinstance(ref, str) and db is not None:
|
||||||
|
item = {**item, "melodyReference": db.collection("melodies").document(ref.split("/")[-1]) if ref else None}
|
||||||
|
out.append(item)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def to_firestore(data: dict, db=None) -> dict:
|
||||||
|
"""Normalize a (partial) device document for writing to Firestore under v1.
|
||||||
|
|
||||||
|
Raises ValidationError (422) for values that cannot be represented in v1, instead
|
||||||
|
of writing something the apps would choke on.
|
||||||
|
"""
|
||||||
|
out = _normalize_map(data, "")
|
||||||
|
|
||||||
|
# D1: device_id mirrors serial_number. Whichever one is being written, write both.
|
||||||
|
sn, did = out.get("serial_number"), out.get("device_id")
|
||||||
|
if sn and did and sn != did:
|
||||||
|
raise ValidationError(f"device_id ({did}) must equal serial_number ({sn})")
|
||||||
|
if sn or did:
|
||||||
|
out["serial_number"] = out["device_id"] = sn or did
|
||||||
|
|
||||||
|
fam = out.get("hw_family")
|
||||||
|
if fam not in (None, "") and not (isinstance(fam, str) and _HW_FAMILY.match(fam)):
|
||||||
|
raise ValidationError(f"hw_family: expected a board family code like \"vesper_plus\", got {fam!r}")
|
||||||
|
|
||||||
|
if "user_list" in out and db is not None:
|
||||||
|
refs, seen = [], set()
|
||||||
|
for e in out["user_list"] or []:
|
||||||
|
ref = _user_ref(db, e)
|
||||||
|
if ref.id not in seen:
|
||||||
|
seen.add(ref.id)
|
||||||
|
refs.append(ref)
|
||||||
|
out["user_list"] = refs
|
||||||
|
|
||||||
|
if "device_melodies_all" in out:
|
||||||
|
out["device_melodies_all"] = _check_melodies(out["device_melodies_all"], db)
|
||||||
|
|
||||||
|
coords = out.get("device_location_coordinates")
|
||||||
|
if isinstance(coords, dict) and "lat" in coords and "lng" in coords:
|
||||||
|
out["device_location_coordinates"] = GeoPoint(coords["lat"], coords["lng"])
|
||||||
|
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------- read side
|
||||||
|
|
||||||
|
|
||||||
|
def _api_value(v):
|
||||||
|
if isinstance(v, datetime):
|
||||||
|
dt = v if v.tzinfo else v.replace(tzinfo=timezone.utc)
|
||||||
|
return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||||
|
if isinstance(v, GeoPoint):
|
||||||
|
return {"lat": v.latitude, "lng": v.longitude}
|
||||||
|
if isinstance(v, DocumentReference):
|
||||||
|
return v.path
|
||||||
|
if isinstance(v, dict):
|
||||||
|
return {k: _api_value(x) for k, x in v.items()}
|
||||||
|
if isinstance(v, list):
|
||||||
|
return [_api_value(x) for x in v]
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
def to_api(raw: dict) -> dict:
|
||||||
|
"""Firestore device doc -> JSON for the console frontend.
|
||||||
|
|
||||||
|
Timestamps become ISO 8601 UTC strings (round-trip safe with to_timestamp),
|
||||||
|
references become paths, GeoPoints become {lat, lng}. Legacy misspelled keys
|
||||||
|
are folded into their v1 names so the frontend only ever sees v1 names.
|
||||||
|
"""
|
||||||
|
return _api_value(_normalize_read(raw, ""))
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_read(data: dict, path: str) -> dict:
|
||||||
|
renames = LEGACY_KEYS.get(path, {})
|
||||||
|
out = {}
|
||||||
|
for key in sorted(data, key=lambda k: k in renames):
|
||||||
|
value = data[key]
|
||||||
|
if key in renames:
|
||||||
|
target = renames[key]
|
||||||
|
if target is None or target in data:
|
||||||
|
continue
|
||||||
|
key = target
|
||||||
|
child = f"{path}.{key}" if path else key
|
||||||
|
if isinstance(value, dict):
|
||||||
|
value = _normalize_read(value, child)
|
||||||
|
elif key in TIMESTAMP_KEYS and path and value == "":
|
||||||
|
value = None # stored "" (pre-v1 bug) reads as unset
|
||||||
|
elif key in IP_KEYS and path.endswith("networkSettings") and isinstance(value, list):
|
||||||
|
parts = [str(p) for p in value if str(p) != ""]
|
||||||
|
value = ".".join(parts) if parts else ""
|
||||||
|
out[key] = value
|
||||||
|
return out
|
||||||
+41
-25
@@ -1,7 +1,12 @@
|
|||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
|
||||||
|
# Field names and types follow Firestore schema v1 (bellsystems-schema repo,
|
||||||
|
# v1/firestore.schema.json) — the shape the shipped tablet/phone apps read.
|
||||||
|
# Timestamps travel through the API as ISO 8601 strings and are unset as None
|
||||||
|
# (never ""); devices/firestore_v1.py converts to/from Firestore.
|
||||||
|
|
||||||
|
|
||||||
# --- Enums ---
|
# --- Enums ---
|
||||||
|
|
||||||
@@ -30,12 +35,14 @@ class DeviceTiers(str, Enum):
|
|||||||
|
|
||||||
class DeviceNetworkSettings(BaseModel):
|
class DeviceNetworkSettings(BaseModel):
|
||||||
hostname: str = ""
|
hostname: str = ""
|
||||||
useStaticIP: bool = False
|
usesStaticIP: bool = False
|
||||||
ipAddress: Any = []
|
# Dotted strings ("10.0.0.5"); "" = not set. The firmware's network.set_config
|
||||||
gateway: Any = []
|
# MQTT command uses its own names (useStaticIP / ip) — convert at that boundary.
|
||||||
subnet: Any = []
|
ipAddress: str = ""
|
||||||
dns1: Any = []
|
gateway: str = ""
|
||||||
dns2: Any = []
|
subnet: str = ""
|
||||||
|
dns1: str = ""
|
||||||
|
dns2: str = ""
|
||||||
|
|
||||||
|
|
||||||
class DeviceClockSettings(BaseModel):
|
class DeviceClockSettings(BaseModel):
|
||||||
@@ -49,12 +56,13 @@ class DeviceClockSettings(BaseModel):
|
|||||||
quarterAlertsBell: int = 0
|
quarterAlertsBell: int = 0
|
||||||
isDaySilenceOn: bool = False
|
isDaySilenceOn: bool = False
|
||||||
isNightSilenceOn: bool = False
|
isNightSilenceOn: bool = False
|
||||||
daySilenceFrom: str = ""
|
# Time of day carried in a Timestamp (v1 quirk); only the UTC time part matters.
|
||||||
daySilenceTo: str = ""
|
daySilenceFrom: Optional[str] = None
|
||||||
nightSilenceFrom: str = ""
|
daySilenceTo: Optional[str] = None
|
||||||
nightSilenceTo: str = ""
|
nightSilenceFrom: Optional[str] = None
|
||||||
backlightTurnOnTime: str = ""
|
nightSilenceTo: Optional[str] = None
|
||||||
backlightTurnOffTime: str = ""
|
backlightTurnOnTime: Optional[str] = None
|
||||||
|
backlightTurnOffTime: Optional[str] = None
|
||||||
isBacklightAutomationOn: bool = False
|
isBacklightAutomationOn: bool = False
|
||||||
backlightOutput: int = 0
|
backlightOutput: int = 0
|
||||||
# Firmware 3.2.0+ face sync policy (clock.set_config face_sync_mode / smart_max_wait_min)
|
# Firmware 3.2.0+ face sync policy (clock.set_config face_sync_mode / smart_max_wait_min)
|
||||||
@@ -70,9 +78,9 @@ class DeviceAttributes(BaseModel):
|
|||||||
bellOutputs: List[int] = []
|
bellOutputs: List[int] = []
|
||||||
hammerTimings: List[int] = []
|
hammerTimings: List[int] = []
|
||||||
bellGuardOn: bool = False
|
bellGuardOn: bool = False
|
||||||
bellGuardSafetyOn: bool = False
|
bellguardSafetyOn: bool = False # lower-case g: the exact key the apps read
|
||||||
warningsOn: bool = False
|
warningsOn: bool = False
|
||||||
towerClockTime: str = ""
|
towerClockTime: Optional[str] = None
|
||||||
clockSettings: DeviceClockSettings = DeviceClockSettings()
|
clockSettings: DeviceClockSettings = DeviceClockSettings()
|
||||||
deviceLocale: HelperMelodyTypes = HelperMelodyTypes.all
|
deviceLocale: HelperMelodyTypes = HelperMelodyTypes.all
|
||||||
networkSettings: DeviceNetworkSettings = DeviceNetworkSettings()
|
networkSettings: DeviceNetworkSettings = DeviceNetworkSettings()
|
||||||
@@ -83,7 +91,7 @@ class DeviceAttributes(BaseModel):
|
|||||||
|
|
||||||
class DeviceSubInformation(BaseModel):
|
class DeviceSubInformation(BaseModel):
|
||||||
subscrTier: DeviceTiers = DeviceTiers.basic
|
subscrTier: DeviceTiers = DeviceTiers.basic
|
||||||
subscrStart: str = ""
|
subscrStart: Optional[str] = None
|
||||||
subscrDuration: int = 0
|
subscrDuration: int = 0
|
||||||
maxUsers: int = 0
|
maxUsers: int = 0
|
||||||
maxOutputs: int = 0
|
maxOutputs: int = 0
|
||||||
@@ -95,10 +103,10 @@ class DeviceStatistics(BaseModel):
|
|||||||
perBellStrikes: List[int] = []
|
perBellStrikes: List[int] = []
|
||||||
totalWarningsGiven: int = 0
|
totalWarningsGiven: int = 0
|
||||||
warrantyActive: bool = False
|
warrantyActive: bool = False
|
||||||
warrantyStart: str = ""
|
warrantyStart: Optional[str] = None
|
||||||
warrantyPeriod: int = 0
|
warrantyPeriod: int = 0
|
||||||
maintainedOn: str = ""
|
maintainedOn: Optional[str] = None
|
||||||
maintainancePeriod: int = 0
|
maintainancePeriod: int = 0 # misspelled in v1 on purpose: the apps read this key
|
||||||
|
|
||||||
|
|
||||||
class HealthThresholdTier(BaseModel):
|
class HealthThresholdTier(BaseModel):
|
||||||
@@ -131,13 +139,21 @@ class DeviceHealthSettings(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class MelodyMainItem(BaseModel):
|
class MelodyMainItem(BaseModel):
|
||||||
"""Mirrors the Melody schema used in the melodies collection."""
|
"""One melody as stored inside devices.device_melodies_all (v1 MelodyMainItem).
|
||||||
information: dict = {}
|
|
||||||
default_settings: dict = {}
|
NOT the melodies/{id} document shape: the apps read camelCase keys here
|
||||||
type: str = ""
|
(mainInformation / defaultSettings / settings / binaryUrl / melodyReference).
|
||||||
url: str = ""
|
Extra keys are kept so a read-modify-write never drops data.
|
||||||
|
"""
|
||||||
|
model_config = ConfigDict(extra="allow")
|
||||||
|
|
||||||
|
melodyReference: Optional[str] = None # path "melodies/{id}" in the API
|
||||||
uid: str = ""
|
uid: str = ""
|
||||||
pid: str = ""
|
pid: str = ""
|
||||||
|
mainInformation: Dict[str, Any] = {}
|
||||||
|
defaultSettings: Dict[str, Any] = {}
|
||||||
|
settings: Dict[str, Any] = {}
|
||||||
|
binaryUrl: str = ""
|
||||||
|
|
||||||
|
|
||||||
# --- Request / Response schemas ---
|
# --- Request / Response schemas ---
|
||||||
@@ -218,7 +234,7 @@ class DeviceNoteUpdate(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class DeviceUserInfo(BaseModel):
|
class DeviceUserInfo(BaseModel):
|
||||||
"""User info resolved from device_users sub-collection or user_list."""
|
"""User info resolved from the device's user_list (role from the device_users mirror)."""
|
||||||
user_id: str = ""
|
user_id: str = ""
|
||||||
display_name: str = ""
|
display_name: str = ""
|
||||||
email: str = ""
|
email: str = ""
|
||||||
|
|||||||
@@ -462,13 +462,15 @@ async def add_user_to_device(
|
|||||||
elif isinstance(entry, str):
|
elif isinstance(entry, str):
|
||||||
existing_ids.add(entry.split("/")[-1])
|
existing_ids.add(entry.split("/")[-1])
|
||||||
|
|
||||||
# user_list and the user's device_serials (MQTT ACL lookup) commit together.
|
# user_list, the user's device_serials (MQTT ACL lookup) and the
|
||||||
|
# device_users mirror commit together.
|
||||||
user_ref = fs.collection("users").document(body.user_id)
|
user_ref = fs.collection("users").document(body.user_id)
|
||||||
batch = fs.batch()
|
batch = fs.batch()
|
||||||
if body.user_id not in existing_ids:
|
if body.user_id not in existing_ids:
|
||||||
user_list.append(user_ref)
|
user_list.append(user_ref)
|
||||||
batch.update(device_ref, {"user_list": user_list})
|
batch.update(device_ref, {"user_list": user_list})
|
||||||
users_service.stage_device_serial_link(batch, user_ref, users_service.device_serial_of(data), linked=True)
|
users_service.stage_device_serial_link(batch, user_ref, users_service.device_serial_of(data), linked=True)
|
||||||
|
service.stage_device_users_mirror(batch, device_ref, user_ref, linked=True)
|
||||||
batch.commit()
|
batch.commit()
|
||||||
users_service.invalidate_mqtt_acl_cache(user_doc.to_dict())
|
users_service.invalidate_mqtt_acl_cache(user_doc.to_dict())
|
||||||
|
|
||||||
@@ -512,6 +514,7 @@ async def remove_user_from_device(
|
|||||||
user_doc = user_ref.get()
|
user_doc = user_ref.get()
|
||||||
if user_doc.exists:
|
if user_doc.exists:
|
||||||
users_service.stage_device_serial_link(batch, user_ref, users_service.device_serial_of(data), linked=False)
|
users_service.stage_device_serial_link(batch, user_ref, users_service.device_serial_of(data), linked=False)
|
||||||
|
service.stage_device_users_mirror(batch, device_ref, user_ref, linked=False)
|
||||||
batch.commit()
|
batch.commit()
|
||||||
if user_doc.exists:
|
if user_doc.exists:
|
||||||
users_service.invalidate_mqtt_acl_cache(user_doc.to_dict())
|
users_service.invalidate_mqtt_acl_cache(user_doc.to_dict())
|
||||||
|
|||||||
+99
-151
@@ -1,11 +1,11 @@
|
|||||||
import secrets
|
import secrets
|
||||||
import string
|
import string
|
||||||
|
|
||||||
from datetime import datetime
|
from google.cloud.firestore_v1 import DocumentReference
|
||||||
from google.cloud.firestore_v1 import GeoPoint, DocumentReference
|
|
||||||
|
|
||||||
from shared.firebase import get_db
|
from shared.firebase import get_db
|
||||||
from shared.exceptions import NotFoundError
|
from shared.exceptions import NotFoundError
|
||||||
|
from devices import firestore_v1
|
||||||
from devices.models import DeviceCreate, DeviceUpdate, DeviceInDB
|
from devices.models import DeviceCreate, DeviceUpdate, DeviceInDB
|
||||||
|
|
||||||
COLLECTION = "devices"
|
COLLECTION = "devices"
|
||||||
@@ -14,35 +14,6 @@ COLLECTION = "devices"
|
|||||||
SN_CHARS = string.ascii_uppercase + string.digits
|
SN_CHARS = string.ascii_uppercase + string.digits
|
||||||
SN_SEGMENT_LEN = 4
|
SN_SEGMENT_LEN = 4
|
||||||
|
|
||||||
# Clock/silence/backlight fields stored as Firestore Timestamps (written as datetime)
|
|
||||||
_TIMESTAMP_FIELD_NAMES = {
|
|
||||||
"daySilenceFrom", "daySilenceTo",
|
|
||||||
"nightSilenceFrom", "nightSilenceTo",
|
|
||||||
"backlightTurnOnTime", "backlightTurnOffTime",
|
|
||||||
"subscrStart", "warrantyStart", "maintainedOn",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _restore_timestamps(d: dict) -> dict:
|
|
||||||
"""Recursively convert ISO 8601 strings for known timestamp fields to datetime objects.
|
|
||||||
|
|
||||||
Firestore stores Python datetime objects as native Timestamps, which Flutter
|
|
||||||
reads as DateTime. Plain strings would break the Flutter app.
|
|
||||||
"""
|
|
||||||
result = {}
|
|
||||||
for k, v in d.items():
|
|
||||||
if isinstance(v, dict):
|
|
||||||
result[k] = _restore_timestamps(v)
|
|
||||||
elif isinstance(v, str) and k in _TIMESTAMP_FIELD_NAMES:
|
|
||||||
try:
|
|
||||||
result[k] = datetime.fromisoformat(v.replace("Z", "+00:00"))
|
|
||||||
except ValueError:
|
|
||||||
result[k] = v
|
|
||||||
else:
|
|
||||||
result[k] = v
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def _generate_serial_number() -> str:
|
def _generate_serial_number() -> str:
|
||||||
"""Generate a unique serial number in the format BS-XXXX-XXXX."""
|
"""Generate a unique serial number in the format BS-XXXX-XXXX."""
|
||||||
seg1 = "".join(secrets.choice(SN_CHARS) for _ in range(SN_SEGMENT_LEN))
|
seg1 = "".join(secrets.choice(SN_CHARS) for _ in range(SN_SEGMENT_LEN))
|
||||||
@@ -67,36 +38,6 @@ def _ensure_unique_serial(db) -> str:
|
|||||||
raise RuntimeError("Could not generate a unique serial number after 100 attempts")
|
raise RuntimeError("Could not generate a unique serial number after 100 attempts")
|
||||||
|
|
||||||
|
|
||||||
def _convert_firestore_value(val):
|
|
||||||
"""Convert Firestore-specific types (Timestamp, GeoPoint, DocumentReference) to strings."""
|
|
||||||
if isinstance(val, datetime):
|
|
||||||
# Firestore DatetimeWithNanoseconds is a datetime subclass
|
|
||||||
return val.strftime("%d %B %Y at %H:%M:%S UTC%z")
|
|
||||||
if isinstance(val, GeoPoint):
|
|
||||||
return {"lat": val.latitude, "lng": val.longitude}
|
|
||||||
if isinstance(val, DocumentReference):
|
|
||||||
# Store the document path (e.g. "users/abc123")
|
|
||||||
return val.path
|
|
||||||
return val
|
|
||||||
|
|
||||||
|
|
||||||
def _sanitize_dict(d: dict) -> dict:
|
|
||||||
"""Recursively convert Firestore-native types in a dict to plain strings."""
|
|
||||||
result = {}
|
|
||||||
for k, v in d.items():
|
|
||||||
if isinstance(v, dict):
|
|
||||||
result[k] = _sanitize_dict(v)
|
|
||||||
elif isinstance(v, list):
|
|
||||||
result[k] = [
|
|
||||||
_sanitize_dict(item) if isinstance(item, dict)
|
|
||||||
else _convert_firestore_value(item)
|
|
||||||
for item in v
|
|
||||||
]
|
|
||||||
else:
|
|
||||||
result[k] = _convert_firestore_value(v)
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def _auto_upgrade_claimed(doc_ref, data: dict) -> dict:
|
def _auto_upgrade_claimed(doc_ref, data: dict) -> dict:
|
||||||
"""If the device has entries in user_list and isn't already claimed/decommissioned,
|
"""If the device has entries in user_list and isn't already claimed/decommissioned,
|
||||||
upgrade mfg_status to 'claimed' automatically and return the updated data dict."""
|
upgrade mfg_status to 'claimed' automatically and return the updated data dict."""
|
||||||
@@ -118,7 +59,7 @@ def _doc_to_device(doc) -> DeviceInDB:
|
|||||||
"""
|
"""
|
||||||
raw = doc.to_dict()
|
raw = doc.to_dict()
|
||||||
raw = _auto_upgrade_claimed(doc.reference, raw)
|
raw = _auto_upgrade_claimed(doc.reference, raw)
|
||||||
data = _sanitize_dict(raw)
|
data = firestore_v1.to_api(raw)
|
||||||
return DeviceInDB(id=doc.id, **data)
|
return DeviceInDB(id=doc.id, **data)
|
||||||
|
|
||||||
|
|
||||||
@@ -187,11 +128,13 @@ def create_device(data: DeviceCreate) -> DeviceInDB:
|
|||||||
serial_number = _ensure_unique_serial(db)
|
serial_number = _ensure_unique_serial(db)
|
||||||
|
|
||||||
doc_data = data.model_dump()
|
doc_data = data.model_dump()
|
||||||
doc_data["device_id"] = serial_number
|
doc_data["serial_number"] = serial_number # D1: canonical id; to_firestore mirrors it to device_id
|
||||||
|
doc_data.pop("device_id", None)
|
||||||
|
doc_data = firestore_v1.to_firestore(doc_data, db)
|
||||||
|
|
||||||
_, doc_ref = db.collection(COLLECTION).add(doc_data)
|
_, doc_ref = db.collection(COLLECTION).add(doc_data)
|
||||||
|
|
||||||
return DeviceInDB(id=doc_ref.id, **doc_data)
|
return _doc_to_device(doc_ref.get())
|
||||||
|
|
||||||
|
|
||||||
def _deep_merge(base: dict, overrides: dict) -> dict:
|
def _deep_merge(base: dict, overrides: dict) -> dict:
|
||||||
@@ -213,44 +156,57 @@ def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
|
|||||||
if not doc.exists:
|
if not doc.exists:
|
||||||
raise NotFoundError("Device")
|
raise NotFoundError("Device")
|
||||||
|
|
||||||
update_data = data.model_dump(exclude_none=True)
|
# Top-level None still means "not sent" (unchanged API behaviour). Inside the
|
||||||
|
# nested maps an explicit null is kept: it clears that field, e.g. a silence
|
||||||
|
# time being switched off — the v1 way to say "unset" (never "").
|
||||||
|
sent = data.model_dump(exclude_unset=True)
|
||||||
|
update_data = firestore_v1.to_firestore({k: v for k, v in sent.items() if v is not None}, db)
|
||||||
|
|
||||||
# Convert {lat, lng} dict to a Firestore GeoPoint
|
# Deep-merge nested structs so unmentioned sub-fields are preserved, then
|
||||||
coords = update_data.get("device_location_coordinates")
|
# normalize the merged map again: that also repairs pre-v1 junk already
|
||||||
if isinstance(coords, dict) and "lat" in coords and "lng" in coords:
|
# stored in the device (""-timestamps, octet-array IPs, misspelled keys).
|
||||||
update_data["device_location_coordinates"] = GeoPoint(coords["lat"], coords["lng"])
|
|
||||||
|
|
||||||
# Deep-merge nested structs so unmentioned sub-fields are preserved
|
|
||||||
existing = doc.to_dict()
|
existing = doc.to_dict()
|
||||||
nested_keys = (
|
nested_keys = (
|
||||||
"device_attributes", "device_subscription", "device_stats", "device_health_settings",
|
"device_attributes", "device_subscription", "device_stats", "device_health_settings",
|
||||||
)
|
)
|
||||||
for key in nested_keys:
|
for key in nested_keys:
|
||||||
if key in update_data and isinstance(existing.get(key), dict):
|
if key in update_data and isinstance(existing.get(key), dict):
|
||||||
update_data[key] = _deep_merge(existing[key], update_data[key])
|
merged = _deep_merge(existing[key], update_data[key])
|
||||||
|
update_data[key] = firestore_v1.to_firestore({key: merged}, db)[key]
|
||||||
update_data = _restore_timestamps(update_data)
|
|
||||||
|
|
||||||
if "user_list" not in update_data:
|
if "user_list" not in update_data:
|
||||||
doc_ref.update(update_data)
|
doc_ref.update(update_data)
|
||||||
else:
|
else:
|
||||||
# A user_list change must also update each affected user's
|
# A user_list change must also update each affected user's
|
||||||
# device_serials (MQTT ACL), in the same atomic batch.
|
# device_serials (MQTT ACL) and the device_users mirror, in the
|
||||||
|
# same atomic batch.
|
||||||
from users import service as users_service
|
from users import service as users_service
|
||||||
|
|
||||||
old_ids = {_user_list_entry_id(e) for e in (existing.get("user_list") or [])} - {""}
|
new_ids = []
|
||||||
new_ids = {_user_list_entry_id(e) for e in update_data["user_list"]} - {""}
|
for e in update_data["user_list"]:
|
||||||
|
uid = user_list_entry_id(e)
|
||||||
|
if uid and uid not in new_ids:
|
||||||
|
new_ids.append(uid)
|
||||||
|
# Stored as DocumentReferences, the format the FlutterFlow app writes.
|
||||||
|
update_data["user_list"] = [db.collection("users").document(uid) for uid in new_ids]
|
||||||
|
|
||||||
|
old_ids = {user_list_entry_id(e) for e in (existing.get("user_list") or [])} - {""}
|
||||||
serial = users_service.device_serial_of(existing)
|
serial = users_service.device_serial_of(existing)
|
||||||
|
mirror = device_users_by_user(doc_ref)
|
||||||
|
|
||||||
batch = db.batch()
|
batch = db.batch()
|
||||||
batch.update(doc_ref, update_data)
|
batch.update(doc_ref, update_data)
|
||||||
touched = []
|
touched = []
|
||||||
for user_id in (old_ids ^ new_ids):
|
for user_id in (old_ids ^ set(new_ids)):
|
||||||
|
linked = user_id in new_ids
|
||||||
user_ref = db.collection("users").document(user_id)
|
user_ref = db.collection("users").document(user_id)
|
||||||
user_doc = user_ref.get()
|
user_doc = user_ref.get()
|
||||||
if not user_doc.exists:
|
if not user_doc.exists:
|
||||||
continue # dangling reference — nothing to sync
|
if not linked:
|
||||||
users_service.stage_device_serial_link(batch, user_ref, serial, linked=user_id in new_ids)
|
stage_device_users_mirror(batch, doc_ref, user_ref, linked=False, existing=mirror)
|
||||||
|
continue # dangling reference — no user doc to sync
|
||||||
|
users_service.stage_device_serial_link(batch, user_ref, serial, linked=linked)
|
||||||
|
stage_device_users_mirror(batch, doc_ref, user_ref, linked=linked, existing=mirror)
|
||||||
touched.append(user_doc.to_dict())
|
touched.append(user_doc.to_dict())
|
||||||
batch.commit()
|
batch.commit()
|
||||||
for user_data in touched:
|
for user_data in touched:
|
||||||
@@ -260,7 +216,7 @@ def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
|
|||||||
return _doc_to_device(updated_doc)
|
return _doc_to_device(updated_doc)
|
||||||
|
|
||||||
|
|
||||||
def _user_list_entry_id(entry) -> str:
|
def user_list_entry_id(entry) -> str:
|
||||||
"""user_list entries are DocumentReferences, "users/{id}" paths or raw doc IDs."""
|
"""user_list entries are DocumentReferences, "users/{id}" paths or raw doc IDs."""
|
||||||
if isinstance(entry, DocumentReference):
|
if isinstance(entry, DocumentReference):
|
||||||
return entry.id
|
return entry.id
|
||||||
@@ -269,11 +225,53 @@ def _user_list_entry_id(entry) -> str:
|
|||||||
return ""
|
return ""
|
||||||
|
|
||||||
|
|
||||||
def get_device_users(device_doc_id: str) -> list[dict]:
|
# ─── device_users sub-collection mirror ──────────────────────────────────────
|
||||||
"""Get users assigned to a device from the device_users sub-collection.
|
# The device's `user_list` field is the single source of truth for who is
|
||||||
|
# assigned to a device. The older `device_users` sub-collection
|
||||||
|
# ({role, user_reference}) is kept as a write-only mirror in case the phone
|
||||||
|
# app still reads it, and is slated for removal. Never read assignments from it.
|
||||||
|
|
||||||
Falls back to the user_list field on the device document if the
|
DEVICE_USERS_SUBCOLLECTION = "device_users"
|
||||||
sub-collection is empty.
|
# Every existing device_users doc (2026-11) has role "admin".
|
||||||
|
DEFAULT_DEVICE_USER_ROLE = "admin"
|
||||||
|
|
||||||
|
|
||||||
|
def device_users_by_user(device_ref) -> dict[str, list]:
|
||||||
|
"""user doc id -> the device_users snapshots that point at that user."""
|
||||||
|
out: dict[str, list] = {}
|
||||||
|
for snap in device_ref.collection(DEVICE_USERS_SUBCOLLECTION).stream():
|
||||||
|
uid = user_list_entry_id((snap.to_dict() or {}).get("user_reference"))
|
||||||
|
if uid:
|
||||||
|
out.setdefault(uid, []).append(snap)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def stage_device_users_mirror(batch, device_ref, user_ref, linked: bool, existing: dict | None = None) -> None:
|
||||||
|
"""Add (linked=True) or remove the user's device_users mirror doc inside the
|
||||||
|
caller's batch, so it commits together with the `user_list` change.
|
||||||
|
|
||||||
|
`existing` is a pre-fetched device_users_by_user() map, for callers that
|
||||||
|
touch several users of one device.
|
||||||
|
"""
|
||||||
|
if existing is None:
|
||||||
|
existing = device_users_by_user(device_ref)
|
||||||
|
current = existing.get(user_ref.id, [])
|
||||||
|
if linked:
|
||||||
|
if not current:
|
||||||
|
batch.set(device_ref.collection(DEVICE_USERS_SUBCOLLECTION).document(), {
|
||||||
|
"role": DEFAULT_DEVICE_USER_ROLE,
|
||||||
|
"user_reference": user_ref,
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
for snap in current:
|
||||||
|
batch.delete(snap.reference)
|
||||||
|
|
||||||
|
|
||||||
|
def get_device_users(device_doc_id: str) -> list[dict]:
|
||||||
|
"""Users assigned to a device, read from the device's `user_list` field.
|
||||||
|
|
||||||
|
`role` is taken from the device_users mirror when one exists for the user
|
||||||
|
(that's the only place a role is stored); otherwise it is "".
|
||||||
"""
|
"""
|
||||||
db = get_db()
|
db = get_db()
|
||||||
doc_ref = db.collection(COLLECTION).document(device_doc_id)
|
doc_ref = db.collection(COLLECTION).document(device_doc_id)
|
||||||
@@ -281,83 +279,33 @@ def get_device_users(device_doc_id: str) -> list[dict]:
|
|||||||
if not doc.exists:
|
if not doc.exists:
|
||||||
raise NotFoundError("Device")
|
raise NotFoundError("Device")
|
||||||
|
|
||||||
# Try sub-collection first
|
roles = {
|
||||||
sub_docs = list(doc_ref.collection("device_users").stream())
|
uid: (snaps[0].to_dict() or {}).get("role", "")
|
||||||
|
for uid, snaps in device_users_by_user(doc_ref).items()
|
||||||
|
}
|
||||||
|
|
||||||
users = []
|
users = []
|
||||||
|
seen = set()
|
||||||
if sub_docs:
|
for entry in (doc.to_dict() or {}).get("user_list") or []:
|
||||||
for sub_doc in sub_docs:
|
uid = user_list_entry_id(entry)
|
||||||
sub_data = sub_doc.to_dict()
|
if not uid or uid in seen:
|
||||||
role = sub_data.get("role", "")
|
continue
|
||||||
user_ref = sub_data.get("user_reference")
|
seen.add(uid)
|
||||||
|
|
||||||
# Resolve user reference
|
|
||||||
user_id = ""
|
|
||||||
display_name = ""
|
|
||||||
email = ""
|
|
||||||
photo_url = ""
|
|
||||||
|
|
||||||
if isinstance(user_ref, DocumentReference):
|
|
||||||
try:
|
try:
|
||||||
user_doc = user_ref.get()
|
user_doc = db.collection("users").document(uid).get()
|
||||||
if user_doc.exists:
|
|
||||||
user_data = user_doc.to_dict()
|
|
||||||
user_id = user_doc.id
|
|
||||||
display_name = user_data.get("display_name", "")
|
|
||||||
email = user_data.get("email", "")
|
|
||||||
photo_url = user_data.get("photo_url", "")
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[devices] Error resolving user reference: {e}")
|
print(f"[devices] Error resolving user_list entry {uid}: {e}")
|
||||||
continue
|
continue
|
||||||
elif isinstance(user_ref, str):
|
if not user_doc.exists:
|
||||||
# String path like "users/abc123"
|
|
||||||
try:
|
|
||||||
ref_doc = db.document(user_ref).get()
|
|
||||||
if ref_doc.exists:
|
|
||||||
user_data = ref_doc.to_dict()
|
|
||||||
user_id = ref_doc.id
|
|
||||||
display_name = user_data.get("display_name", "")
|
|
||||||
email = user_data.get("email", "")
|
|
||||||
photo_url = user_data.get("photo_url", "")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[devices] Error resolving user path: {e}")
|
|
||||||
continue
|
continue
|
||||||
|
user_data = user_doc.to_dict() or {}
|
||||||
users.append({
|
|
||||||
"user_id": user_id,
|
|
||||||
"display_name": display_name,
|
|
||||||
"email": email,
|
|
||||||
"role": role,
|
|
||||||
"photo_url": photo_url,
|
|
||||||
})
|
|
||||||
else:
|
|
||||||
# Fallback to user_list field
|
|
||||||
device_data = doc.to_dict()
|
|
||||||
user_list = device_data.get("user_list", [])
|
|
||||||
for entry in user_list:
|
|
||||||
try:
|
|
||||||
if isinstance(entry, DocumentReference):
|
|
||||||
user_doc = entry.get()
|
|
||||||
elif isinstance(entry, str) and entry.strip():
|
|
||||||
# Could be a path like "users/abc" or a raw doc ID
|
|
||||||
if "/" in entry:
|
|
||||||
user_doc = db.document(entry).get()
|
|
||||||
else:
|
|
||||||
user_doc = db.collection("users").document(entry).get()
|
|
||||||
else:
|
|
||||||
continue
|
|
||||||
|
|
||||||
if user_doc.exists:
|
|
||||||
user_data = user_doc.to_dict()
|
|
||||||
users.append({
|
users.append({
|
||||||
"user_id": user_doc.id,
|
"user_id": user_doc.id,
|
||||||
"display_name": user_data.get("display_name", ""),
|
"display_name": user_data.get("display_name", ""),
|
||||||
"email": user_data.get("email", ""),
|
"email": user_data.get("email", ""),
|
||||||
"role": "",
|
"role": roles.get(uid, ""),
|
||||||
"photo_url": user_data.get("photo_url", ""),
|
"photo_url": user_data.get("photo_url", ""),
|
||||||
})
|
})
|
||||||
except Exception as e:
|
|
||||||
print(f"[devices] Error resolving user_list entry: {e}")
|
|
||||||
|
|
||||||
return users
|
return users
|
||||||
|
|
||||||
|
|||||||
@@ -89,8 +89,8 @@ class DeviceUserSummary(BaseModel):
|
|||||||
class DeviceInventoryItem(BaseModel):
|
class DeviceInventoryItem(BaseModel):
|
||||||
id: str
|
id: str
|
||||||
serial_number: str
|
serial_number: str
|
||||||
hw_type: str
|
hw_family: str # board family code (BoardType value or bespoke UID) = firmware NVS "hw_family"
|
||||||
hw_version: str
|
hw_revision: str # hardware revision, e.g. "1.0" = firmware NVS "hw_revision"
|
||||||
mfg_status: str
|
mfg_status: str
|
||||||
mfg_batch_id: Optional[str] = None
|
mfg_batch_id: Optional[str] = None
|
||||||
created_at: Optional[str] = None
|
created_at: Optional[str] = None
|
||||||
@@ -134,7 +134,7 @@ class CustomerSearchResult(BaseModel):
|
|||||||
|
|
||||||
class RecentActivityItem(BaseModel):
|
class RecentActivityItem(BaseModel):
|
||||||
serial_number: str
|
serial_number: str
|
||||||
hw_type: str
|
hw_family: str
|
||||||
mfg_status: str
|
mfg_status: str
|
||||||
owner: Optional[str] = None
|
owner: Optional[str] = None
|
||||||
updated_at: Optional[str] = None
|
updated_at: Optional[str] = None
|
||||||
|
|||||||
@@ -71,8 +71,8 @@ async def create_batch(
|
|||||||
@router.get("/devices", response_model=DeviceInventoryListResponse)
|
@router.get("/devices", response_model=DeviceInventoryListResponse)
|
||||||
def list_devices(
|
def list_devices(
|
||||||
status: Optional[str] = Query(None),
|
status: Optional[str] = Query(None),
|
||||||
hw_type: Optional[str] = Query(None),
|
hw_family: Optional[str] = Query(None),
|
||||||
hw_types: Optional[list[str]] = Query(None, description="Multi-select board type filter — repeat param, e.g. ?hw_types=vesper&hw_types=chronos"),
|
hw_families: Optional[list[str]] = Query(None, description="Multi-select board family filter — repeat param, e.g. ?hw_families=vesper&hw_families=chronos"),
|
||||||
has_users: Optional[bool] = Query(None, description="Filter by whether the device has any app users assigned"),
|
has_users: Optional[bool] = Query(None, description="Filter by whether the device has any app users assigned"),
|
||||||
search: Optional[str] = Query(None),
|
search: Optional[str] = Query(None),
|
||||||
limit: int = Query(100, ge=1, le=500),
|
limit: int = Query(100, ge=1, le=500),
|
||||||
@@ -81,8 +81,8 @@ def list_devices(
|
|||||||
):
|
):
|
||||||
items = service.list_devices(
|
items = service.list_devices(
|
||||||
status=status,
|
status=status,
|
||||||
hw_type=hw_type,
|
hw_family=hw_family,
|
||||||
hw_types=hw_types,
|
hw_families=hw_families,
|
||||||
has_users=has_users,
|
has_users=has_users,
|
||||||
search=search,
|
search=search,
|
||||||
limit=limit,
|
limit=limit,
|
||||||
@@ -605,7 +605,7 @@ def download_bootloader(
|
|||||||
):
|
):
|
||||||
"""Return the bootloader.bin for this device's hw_type (flashed at 0x1000)."""
|
"""Return the bootloader.bin for this device's hw_type (flashed at 0x1000)."""
|
||||||
item = service.get_device_by_sn(sn)
|
item = service.get_device_by_sn(sn)
|
||||||
hw_type = hw_type_override or item.hw_type
|
hw_type = hw_type_override or item.hw_family
|
||||||
try:
|
try:
|
||||||
data = service.get_flash_asset(hw_type, "bootloader.bin")
|
data = service.get_flash_asset(hw_type, "bootloader.bin")
|
||||||
except NotFoundError as e:
|
except NotFoundError as e:
|
||||||
@@ -625,7 +625,7 @@ def download_partitions(
|
|||||||
):
|
):
|
||||||
"""Return the partitions.bin for this device's hw_type (flashed at 0x8000)."""
|
"""Return the partitions.bin for this device's hw_type (flashed at 0x8000)."""
|
||||||
item = service.get_device_by_sn(sn)
|
item = service.get_device_by_sn(sn)
|
||||||
hw_type = hw_type_override or item.hw_type
|
hw_type = hw_type_override or item.hw_family
|
||||||
try:
|
try:
|
||||||
data = service.get_flash_asset(hw_type, "partitions.bin")
|
data = service.get_flash_asset(hw_type, "partitions.bin")
|
||||||
except NotFoundError as e:
|
except NotFoundError as e:
|
||||||
|
|||||||
@@ -66,8 +66,9 @@ def _doc_to_inventory_item(doc, customer_names: dict | None = None, user_infos:
|
|||||||
return DeviceInventoryItem(
|
return DeviceInventoryItem(
|
||||||
id=doc.id,
|
id=doc.id,
|
||||||
serial_number=data.get("serial_number", ""),
|
serial_number=data.get("serial_number", ""),
|
||||||
hw_type=data.get("hw_type", ""),
|
# hw_type / hw_version: names used before 2026-11-08 (kept as read fallback)
|
||||||
hw_version=data.get("hw_version", ""),
|
hw_family=data.get("hw_family") or data.get("hw_type", ""),
|
||||||
|
hw_revision=data.get("hw_revision") or data.get("hw_version", ""),
|
||||||
mfg_status=data.get("mfg_status", "manufactured"),
|
mfg_status=data.get("mfg_status", "manufactured"),
|
||||||
mfg_batch_id=data.get("mfg_batch_id"),
|
mfg_batch_id=data.get("mfg_batch_id"),
|
||||||
created_at=created_str,
|
created_at=created_str,
|
||||||
@@ -134,8 +135,11 @@ def create_batch(data: BatchCreate) -> BatchResponse:
|
|||||||
|
|
||||||
db.collection(COLLECTION).add({
|
db.collection(COLLECTION).add({
|
||||||
"serial_number": sn,
|
"serial_number": sn,
|
||||||
"hw_type": data.board_type.value,
|
"device_id": sn, # schema v1 / D1: both apps connect over MQTT with device_id
|
||||||
"hw_version": data.board_version,
|
|
||||||
|
# Same names as the firmware NVS keys.
|
||||||
|
"hw_family": data.board_type.value,
|
||||||
|
"hw_revision": data.board_version,
|
||||||
"mfg_status": "manufactured",
|
"mfg_status": "manufactured",
|
||||||
"mfg_batch_id": batch_id,
|
"mfg_batch_id": batch_id,
|
||||||
"created_at": now,
|
"created_at": now,
|
||||||
@@ -168,8 +172,8 @@ def create_batch(data: BatchCreate) -> BatchResponse:
|
|||||||
|
|
||||||
def list_devices(
|
def list_devices(
|
||||||
status: str | None = None,
|
status: str | None = None,
|
||||||
hw_type: str | None = None,
|
hw_family: str | None = None,
|
||||||
hw_types: list[str] | None = None,
|
hw_families: list[str] | None = None,
|
||||||
has_users: bool | None = None,
|
has_users: bool | None = None,
|
||||||
search: str | None = None,
|
search: str | None = None,
|
||||||
limit: int = 100,
|
limit: int = 100,
|
||||||
@@ -180,15 +184,15 @@ def list_devices(
|
|||||||
|
|
||||||
if status:
|
if status:
|
||||||
query = query.where("mfg_status", "==", status)
|
query = query.where("mfg_status", "==", status)
|
||||||
if hw_type:
|
if hw_family:
|
||||||
query = query.where("hw_type", "==", hw_type)
|
query = query.where("hw_family", "==", hw_family)
|
||||||
|
|
||||||
docs = list(query.stream())
|
docs = list(query.stream())
|
||||||
docs_data = [doc.to_dict() or {} for doc in docs]
|
docs_data = [doc.to_dict() or {} for doc in docs]
|
||||||
|
|
||||||
if hw_types:
|
if hw_families:
|
||||||
hw_type_set = set(hw_types)
|
family_set = set(hw_families)
|
||||||
keep = [i for i, d in enumerate(docs_data) if d.get("hw_type") in hw_type_set]
|
keep = [i for i, d in enumerate(docs_data) if d.get("hw_family") in family_set]
|
||||||
docs = [docs[i] for i in keep]
|
docs = [docs[i] for i in keep]
|
||||||
docs_data = [docs_data[i] for i in keep]
|
docs_data = [docs_data[i] for i in keep]
|
||||||
|
|
||||||
@@ -272,8 +276,8 @@ def get_nvs_binary(sn: str, hw_type_override: str | None = None, hw_revision_ove
|
|||||||
item = get_device_by_sn(sn)
|
item = get_device_by_sn(sn)
|
||||||
return generate_nvs_binary(
|
return generate_nvs_binary(
|
||||||
serial_number=item.serial_number,
|
serial_number=item.serial_number,
|
||||||
hw_family=hw_type_override if hw_type_override else item.hw_type,
|
hw_family=hw_type_override if hw_type_override else item.hw_family,
|
||||||
hw_revision=hw_revision_override if hw_revision_override else item.hw_version,
|
hw_revision=hw_revision_override if hw_revision_override else item.hw_revision,
|
||||||
legacy=legacy,
|
legacy=legacy,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -331,7 +335,7 @@ def assign_device(sn: str, data: DeviceAssign) -> DeviceInventoryItem:
|
|||||||
for item in owned_items
|
for item in owned_items
|
||||||
)
|
)
|
||||||
if not already_assigned:
|
if not already_assigned:
|
||||||
device_name = doc_data.get("device_name") or BOARD_TYPE_LABELS.get(doc_data.get("hw_type", ""), sn)
|
device_name = doc_data.get("device_name") or BOARD_TYPE_LABELS.get(doc_data.get("hw_family") or doc_data.get("hw_type", ""), sn)
|
||||||
owned_items.append({
|
owned_items.append({
|
||||||
"type": "console_device",
|
"type": "console_device",
|
||||||
"console_device": {
|
"console_device": {
|
||||||
@@ -401,7 +405,7 @@ def get_stats() -> ManufacturingStats:
|
|||||||
|
|
||||||
activity_candidates.append(RecentActivityItem(
|
activity_candidates.append(RecentActivityItem(
|
||||||
serial_number=data.get("serial_number", ""),
|
serial_number=data.get("serial_number", ""),
|
||||||
hw_type=data.get("hw_type", ""),
|
hw_family=data.get("hw_family") or data.get("hw_type", ""),
|
||||||
mfg_status=status,
|
mfg_status=status,
|
||||||
owner=data.get("owner"),
|
owner=data.get("owner"),
|
||||||
updated_at=ts_str,
|
updated_at=ts_str,
|
||||||
@@ -561,7 +565,6 @@ def get_firmware_url(sn: str) -> str:
|
|||||||
"""Return the FastAPI download URL for the latest stable firmware for this device's hw_type."""
|
"""Return the FastAPI download URL for the latest stable firmware for this device's hw_type."""
|
||||||
from firmware.service import get_latest
|
from firmware.service import get_latest
|
||||||
item = get_device_by_sn(sn)
|
item = get_device_by_sn(sn)
|
||||||
hw_type = item.hw_type.lower()
|
latest = get_latest(item.hw_family.lower(), "stable")
|
||||||
latest = get_latest(hw_type, "stable")
|
|
||||||
# download_url is a relative path like /api/firmware/vs/stable/1.4.2/firmware.bin
|
# download_url is a relative path like /api/firmware/vs/stable/1.4.2/firmware.bin
|
||||||
return latest.download_url
|
return latest.download_url
|
||||||
|
|||||||
@@ -109,9 +109,9 @@ async def validate_serial(serial_number: str):
|
|||||||
device = get_device_by_sn(sn)
|
device = get_device_by_sn(sn)
|
||||||
return SerialValidationResult(
|
return SerialValidationResult(
|
||||||
valid=True,
|
valid=True,
|
||||||
hw_type=device.hw_type,
|
hw_type=device.hw_family,
|
||||||
hw_type_label=HW_TYPE_LABELS.get(device.hw_type, device.hw_type.replace("_", " ").title()),
|
hw_type_label=HW_TYPE_LABELS.get(device.hw_family, device.hw_family.replace("_", " ").title()),
|
||||||
hw_version=device.hw_version,
|
hw_version=device.hw_revision,
|
||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
return SerialValidationResult(valid=False)
|
return SerialValidationResult(valid=False)
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
"""
|
||||||
|
Make every device's `device_users` sub-collection mirror its `user_list`.
|
||||||
|
|
||||||
|
`user_list` is the source of truth for device assignments. The Console keeps
|
||||||
|
`device_users` ({role, user_reference}) only as a write-only mirror in case the
|
||||||
|
phone app still reads it. Before 2026-11 the Console read `device_users` first
|
||||||
|
and never wrote it, so the two drifted. This script lists the drift and, with
|
||||||
|
--apply, fixes the mirror:
|
||||||
|
|
||||||
|
- users in user_list with no device_users doc -> doc added (role "admin")
|
||||||
|
- device_users docs for users NOT in user_list -> doc deleted
|
||||||
|
|
||||||
|
It never changes `user_list` or `device_serials`. Check the dry-run output
|
||||||
|
first: if a user only appears in device_users and should keep the device,
|
||||||
|
assign them in the Console (Manage tab) before running --apply, or they will be
|
||||||
|
dropped from the mirror. Running it twice is a no-op the second time.
|
||||||
|
|
||||||
|
Run from backend/ (locally or inside the backend container):
|
||||||
|
|
||||||
|
python scripts/sync_device_users_mirror.py # dry run
|
||||||
|
python scripts/sync_device_users_mirror.py --apply # write changes
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
from shared.firebase import init_firebase, get_db # noqa: E402
|
||||||
|
from devices.service import ( # noqa: E402
|
||||||
|
DEFAULT_DEVICE_USER_ROLE, DEVICE_USERS_SUBCOLLECTION, device_users_by_user, user_list_entry_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
BATCH_SIZE = 400 # Firestore batch limit is 500 writes
|
||||||
|
|
||||||
|
|
||||||
|
def _label(db, uid: str) -> str:
|
||||||
|
snap = db.collection("users").document(uid).get()
|
||||||
|
if not snap.exists:
|
||||||
|
return f"{uid} (no user doc)"
|
||||||
|
data = snap.to_dict() or {}
|
||||||
|
return f"{uid} ({data.get('display_name') or data.get('email') or '?'})"
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||||
|
parser.add_argument("--apply", action="store_true", help="write changes (default: dry run)")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
init_firebase()
|
||||||
|
db = get_db()
|
||||||
|
if db is None:
|
||||||
|
print("[ERROR] Firebase not initialized — check FIREBASE_SERVICE_ACCOUNT_PATH")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
print(f"=== sync device_users mirror — {'APPLY' if args.apply else 'DRY RUN'} ===")
|
||||||
|
writes = [] # (op, ref, data)
|
||||||
|
for dev in db.collection("devices").stream():
|
||||||
|
data = dev.to_dict() or {}
|
||||||
|
wanted = {user_list_entry_id(e) for e in data.get("user_list") or []} - {""}
|
||||||
|
mirror = device_users_by_user(dev.reference)
|
||||||
|
to_add = sorted(u for u in wanted - mirror.keys()
|
||||||
|
if db.collection("users").document(u).get().exists)
|
||||||
|
to_del = sorted(mirror.keys() - wanted)
|
||||||
|
if not to_add and not to_del:
|
||||||
|
continue
|
||||||
|
serial = data.get("serial_number") or data.get("device_id") or "?"
|
||||||
|
print(f"\n{dev.id} {serial} {data.get('device_name') or ''}")
|
||||||
|
for u in to_add:
|
||||||
|
print(f" + add mirror {_label(db, u)}")
|
||||||
|
writes.append(("set", dev.reference.collection(DEVICE_USERS_SUBCOLLECTION).document(), {
|
||||||
|
"role": DEFAULT_DEVICE_USER_ROLE,
|
||||||
|
"user_reference": db.collection("users").document(u),
|
||||||
|
}))
|
||||||
|
for u in to_del:
|
||||||
|
print(f" - remove mirror {_label(db, u)} <- only in device_users, not in user_list")
|
||||||
|
writes.extend(("delete", snap.reference, None) for snap in mirror[u])
|
||||||
|
|
||||||
|
print(f"\n{len(writes)} write(s) needed.")
|
||||||
|
if not args.apply or not writes:
|
||||||
|
if writes:
|
||||||
|
print("Dry run — nothing written. Re-run with --apply to write.")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
for i in range(0, len(writes), BATCH_SIZE):
|
||||||
|
batch = db.batch()
|
||||||
|
for op, ref, payload in writes[i:i + BATCH_SIZE]:
|
||||||
|
batch.set(ref, payload) if op == "set" else batch.delete(ref)
|
||||||
|
batch.commit()
|
||||||
|
print("Done.")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -1,16 +1,21 @@
|
|||||||
"""
|
"""
|
||||||
update_device must keep users.device_serials in sync when a PUT changes the
|
Device user assignment: `user_list` is the source of truth. Every write must
|
||||||
device's user_list (the MQTT ACL reads device_serials). Firestore is faked.
|
keep users.device_serials (MQTT ACL) and the device_users sub-collection
|
||||||
|
mirror in sync, and reads must come from user_list only. Firestore is faked.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import itertools
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from google.cloud.firestore_v1 import ArrayRemove, ArrayUnion
|
from google.cloud.firestore_v1 import ArrayRemove, ArrayUnion, DocumentReference
|
||||||
|
|
||||||
from devices import service as devices_service
|
from devices import service as devices_service
|
||||||
from devices.models import DeviceUpdate
|
from devices.models import DeviceUpdate
|
||||||
from mqtt import app_users
|
from mqtt import app_users
|
||||||
|
from users import service as users_service
|
||||||
|
|
||||||
SERIAL = "BSVSPR-26C13X-STD01R-X7KQA"
|
SERIAL = "BSVSPR-26C13X-STD01R-X7KQA"
|
||||||
|
MIRROR = "devices/dev1/device_users"
|
||||||
|
|
||||||
|
|
||||||
class _Snap:
|
class _Snap:
|
||||||
@@ -24,9 +29,16 @@ class _Snap:
|
|||||||
return dict(self._data) if self._data is not None else None
|
return dict(self._data) if self._data is not None else None
|
||||||
|
|
||||||
|
|
||||||
class _Ref:
|
class _Ref(DocumentReference):
|
||||||
def __init__(self, db, collection, doc_id):
|
"""A real DocumentReference subclass, so isinstance checks and .id/.path work."""
|
||||||
self._db, self._col, self.id = db, collection, doc_id
|
|
||||||
|
def __init__(self, db, col_path, doc_id):
|
||||||
|
self._db, self._col = db, col_path
|
||||||
|
self._client = db
|
||||||
|
self._path = tuple(col_path.split("/")) + (doc_id,)
|
||||||
|
|
||||||
|
def collection(self, name):
|
||||||
|
return _Collection(self._db, f"{self._col}/{self.id}/{name}")
|
||||||
|
|
||||||
def get(self):
|
def get(self):
|
||||||
return _Snap(self, self._db.docs[self._col].get(self.id))
|
return _Snap(self, self._db.docs[self._col].get(self.id))
|
||||||
@@ -34,32 +46,48 @@ class _Ref:
|
|||||||
def update(self, data):
|
def update(self, data):
|
||||||
self._db.apply(self._col, self.id, data)
|
self._db.apply(self._col, self.id, data)
|
||||||
|
|
||||||
|
def set(self, data):
|
||||||
|
self._db.docs[self._col][self.id] = dict(data)
|
||||||
|
|
||||||
|
def delete(self):
|
||||||
|
self._db.docs[self._col].pop(self.id, None)
|
||||||
|
|
||||||
|
|
||||||
class _Batch:
|
class _Batch:
|
||||||
def __init__(self, db):
|
def __init__(self, db):
|
||||||
self._db, self.ops = db, []
|
self._db, self.ops = db, []
|
||||||
|
|
||||||
def update(self, ref, data):
|
def update(self, ref, data):
|
||||||
self.ops.append((ref, data))
|
self.ops.append(("update", ref, data))
|
||||||
|
|
||||||
|
def set(self, ref, data):
|
||||||
|
self.ops.append(("set", ref, data))
|
||||||
|
|
||||||
|
def delete(self, ref):
|
||||||
|
self.ops.append(("delete", ref, None))
|
||||||
|
|
||||||
def commit(self):
|
def commit(self):
|
||||||
for ref, data in self.ops:
|
for op, ref, data in self.ops:
|
||||||
ref.update(data)
|
getattr(ref, op)(*([data] if data is not None else []))
|
||||||
self._db.commits += 1
|
self._db.commits += 1
|
||||||
|
|
||||||
|
|
||||||
class _Collection:
|
class _Collection:
|
||||||
def __init__(self, db, name):
|
def __init__(self, db, path):
|
||||||
self._db, self._name = db, name
|
self._db, self._path = db, path
|
||||||
|
|
||||||
def document(self, doc_id):
|
def document(self, doc_id=None):
|
||||||
return _Ref(self._db, self._name, doc_id)
|
return _Ref(self._db, self._path, doc_id or f"auto{next(self._db.ids)}")
|
||||||
|
|
||||||
|
def stream(self):
|
||||||
|
return [_Snap(_Ref(self._db, self._path, k), v) for k, v in list(self._db.docs[self._path].items())]
|
||||||
|
|
||||||
|
|
||||||
class FakeDB:
|
class FakeDB:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.docs = {"devices": {}, "users": {}}
|
self.docs = {"devices": {}, "users": {}, MIRROR: {}}
|
||||||
self.commits = 0
|
self.commits = 0
|
||||||
|
self.ids = itertools.count(1)
|
||||||
|
|
||||||
def collection(self, name):
|
def collection(self, name):
|
||||||
return _Collection(self, name)
|
return _Collection(self, name)
|
||||||
@@ -67,6 +95,10 @@ class FakeDB:
|
|||||||
def batch(self):
|
def batch(self):
|
||||||
return _Batch(self)
|
return _Batch(self)
|
||||||
|
|
||||||
|
def ref(self, path):
|
||||||
|
col, doc_id = path.rsplit("/", 1)
|
||||||
|
return _Ref(self, col, doc_id)
|
||||||
|
|
||||||
def apply(self, col, doc_id, data):
|
def apply(self, col, doc_id, data):
|
||||||
doc = self.docs[col][doc_id]
|
doc = self.docs[col][doc_id]
|
||||||
for key, val in data.items():
|
for key, val in data.items():
|
||||||
@@ -77,38 +109,53 @@ class FakeDB:
|
|||||||
else:
|
else:
|
||||||
doc[key] = val
|
doc[key] = val
|
||||||
|
|
||||||
|
def mirror_user_ids(self):
|
||||||
|
return sorted(d["user_reference"].id for d in self.docs[MIRROR].values())
|
||||||
|
|
||||||
|
def user_list_ids(self, device="dev1"):
|
||||||
|
return [devices_service.user_list_entry_id(e) for e in self.docs["devices"][device]["user_list"]]
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def db(monkeypatch):
|
def db(monkeypatch):
|
||||||
fake = FakeDB()
|
fake = FakeDB()
|
||||||
fake.docs["devices"]["dev1"] = {
|
fake.docs["devices"]["dev1"] = {
|
||||||
"serial_number": SERIAL, "mfg_status": "claimed", "user_list": ["users/alice", "users/bob"],
|
"serial_number": SERIAL, "mfg_status": "claimed",
|
||||||
|
"user_list": [fake.ref("users/alice"), "users/bob"], # both formats seen in the wild
|
||||||
}
|
}
|
||||||
fake.docs["users"]["alice"] = {"uid": "alice", "device_serials": [SERIAL]}
|
fake.docs[MIRROR]["m1"] = {"role": "admin", "user_reference": fake.ref("users/alice")}
|
||||||
fake.docs["users"]["bob"] = {"uid": "bob", "device_serials": [SERIAL, "OTHER"]}
|
fake.docs["users"]["alice"] = {"uid": "alice", "device_serials": [SERIAL], "display_name": "Alice"}
|
||||||
fake.docs["users"]["carol"] = {"uid": "carol"}
|
fake.docs["users"]["bob"] = {"uid": "bob", "device_serials": [SERIAL, "OTHER"], "display_name": "Bob"}
|
||||||
|
fake.docs["users"]["carol"] = {"uid": "carol", "display_name": "Carol"}
|
||||||
monkeypatch.setattr(devices_service, "get_db", lambda: fake)
|
monkeypatch.setattr(devices_service, "get_db", lambda: fake)
|
||||||
|
monkeypatch.setattr(users_service, "get_db", lambda: fake)
|
||||||
|
monkeypatch.setattr(app_users, "invalidate", lambda uid: None)
|
||||||
return fake
|
return fake
|
||||||
|
|
||||||
|
|
||||||
|
# ── PUT /api/devices/{id} with user_list ─────────────────────────────────────
|
||||||
|
|
||||||
def test_put_user_list_syncs_added_and_removed_users(db, monkeypatch):
|
def test_put_user_list_syncs_added_and_removed_users(db, monkeypatch):
|
||||||
invalidated = []
|
invalidated = []
|
||||||
monkeypatch.setattr(app_users, "invalidate", invalidated.append)
|
monkeypatch.setattr(app_users, "invalidate", invalidated.append)
|
||||||
|
|
||||||
devices_service.update_device("dev1", DeviceUpdate(user_list=["users/alice", "users/carol"]))
|
devices_service.update_device("dev1", DeviceUpdate(user_list=["users/alice", "users/carol"]))
|
||||||
|
|
||||||
assert db.docs["devices"]["dev1"]["user_list"] == ["users/alice", "users/carol"]
|
assert db.user_list_ids() == ["alice", "carol"]
|
||||||
|
assert all(isinstance(e, DocumentReference) for e in db.docs["devices"]["dev1"]["user_list"])
|
||||||
assert db.docs["users"]["alice"]["device_serials"] == [SERIAL] # unchanged
|
assert db.docs["users"]["alice"]["device_serials"] == [SERIAL] # unchanged
|
||||||
assert db.docs["users"]["bob"]["device_serials"] == ["OTHER"] # removed
|
assert db.docs["users"]["bob"]["device_serials"] == ["OTHER"] # removed
|
||||||
assert db.docs["users"]["carol"]["device_serials"] == [SERIAL] # added
|
assert db.docs["users"]["carol"]["device_serials"] == [SERIAL] # added
|
||||||
|
assert db.mirror_user_ids() == ["alice", "carol"] # alice's mirror kept, carol's added
|
||||||
assert sorted(invalidated) == ["bob", "carol"]
|
assert sorted(invalidated) == ["bob", "carol"]
|
||||||
assert db.commits == 1 # one atomic batch
|
assert db.commits == 1 # one atomic batch
|
||||||
|
|
||||||
|
|
||||||
def test_put_user_list_ignores_dangling_user_refs(db):
|
def test_put_user_list_ignores_dangling_user_refs(db):
|
||||||
devices_service.update_device("dev1", DeviceUpdate(user_list=["users/alice", "users/bob", "users/ghost"]))
|
devices_service.update_device("dev1", DeviceUpdate(user_list=["users/alice", "users/bob", "users/ghost"]))
|
||||||
assert db.docs["devices"]["dev1"]["user_list"] == ["users/alice", "users/bob", "users/ghost"]
|
assert db.user_list_ids() == ["alice", "bob", "ghost"]
|
||||||
assert "ghost" not in db.docs["users"]
|
assert "ghost" not in db.docs["users"]
|
||||||
|
assert "ghost" not in db.mirror_user_ids()
|
||||||
|
|
||||||
|
|
||||||
def test_put_without_user_list_does_not_touch_users(db):
|
def test_put_without_user_list_does_not_touch_users(db):
|
||||||
@@ -116,3 +163,45 @@ def test_put_without_user_list_does_not_touch_users(db):
|
|||||||
assert db.docs["devices"]["dev1"]["device_name"] == "Church"
|
assert db.docs["devices"]["dev1"]["device_name"] == "Church"
|
||||||
assert db.commits == 0
|
assert db.commits == 0
|
||||||
assert db.docs["users"]["bob"]["device_serials"] == [SERIAL, "OTHER"]
|
assert db.docs["users"]["bob"]["device_serials"] == [SERIAL, "OTHER"]
|
||||||
|
|
||||||
|
|
||||||
|
# ── Reads come from user_list, not the sub-collection ────────────────────────
|
||||||
|
|
||||||
|
def test_get_device_users_reads_user_list_with_mirror_role(db):
|
||||||
|
# A stale mirror doc for someone NOT in user_list must not show up.
|
||||||
|
db.docs[MIRROR]["stale"] = {"role": "admin", "user_reference": db.ref("users/carol")}
|
||||||
|
|
||||||
|
users = devices_service.get_device_users("dev1")
|
||||||
|
|
||||||
|
assert [(u["user_id"], u["display_name"], u["role"]) for u in users] == [
|
||||||
|
("alice", "Alice", "admin"),
|
||||||
|
("bob", "Bob", ""),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_device_users_skips_duplicates_and_missing_users(db):
|
||||||
|
db.docs["devices"]["dev1"]["user_list"] += ["alice", db.ref("users/ghost")]
|
||||||
|
assert [u["user_id"] for u in devices_service.get_device_users("dev1")] == ["alice", "bob"]
|
||||||
|
|
||||||
|
|
||||||
|
# ── Users page: assign / unassign ────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_assign_device_writes_reference_and_mirror(db):
|
||||||
|
users_service.assign_device("carol", "dev1")
|
||||||
|
assert db.user_list_ids() == ["alice", "bob", "carol"]
|
||||||
|
assert isinstance(db.docs["devices"]["dev1"]["user_list"][-1], DocumentReference)
|
||||||
|
assert db.docs["users"]["carol"]["device_serials"] == [SERIAL]
|
||||||
|
assert db.mirror_user_ids() == ["alice", "carol"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_assign_device_twice_does_not_duplicate(db):
|
||||||
|
users_service.assign_device("alice", "dev1")
|
||||||
|
assert db.user_list_ids() == ["alice", "bob"]
|
||||||
|
assert db.mirror_user_ids() == ["alice"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_unassign_device_removes_any_format_and_mirror(db):
|
||||||
|
users_service.unassign_device("alice", "dev1")
|
||||||
|
assert db.user_list_ids() == ["bob"]
|
||||||
|
assert db.docs["users"]["alice"]["device_serials"] == []
|
||||||
|
assert db.mirror_user_ids() == []
|
||||||
|
|||||||
@@ -0,0 +1,190 @@
|
|||||||
|
"""
|
||||||
|
Device writes must match Firestore schema v1 (bellsystems-schema/v1). One wrongly
|
||||||
|
typed field makes the FlutterFlow apps silently drop the whole device, so these
|
||||||
|
cover the exact shapes found corrupting production data on 2026-11-08.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from google.cloud.firestore_v1 import DocumentReference, GeoPoint
|
||||||
|
|
||||||
|
from devices import firestore_v1 as v1
|
||||||
|
from devices.models import DeviceCreate
|
||||||
|
from shared.exceptions import ValidationError
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeDb:
|
||||||
|
"""Just enough of a Firestore client to build DocumentReferences."""
|
||||||
|
|
||||||
|
def collection(self, name):
|
||||||
|
db = self
|
||||||
|
|
||||||
|
class _Col:
|
||||||
|
def document(self, doc_id):
|
||||||
|
return DocumentReference(name, doc_id, client=db)
|
||||||
|
|
||||||
|
return _Col()
|
||||||
|
|
||||||
|
|
||||||
|
DB = _FakeDb()
|
||||||
|
T = datetime(2026, 1, 15, 22, 1, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- timestamps
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("value", ["", None])
|
||||||
|
def test_unset_timestamp_becomes_null_never_empty_string(value):
|
||||||
|
out = v1.to_firestore({"device_attributes": {"towerClockTime": value,
|
||||||
|
"clockSettings": {"daySilenceFrom": value}}})
|
||||||
|
assert out["device_attributes"]["towerClockTime"] is None
|
||||||
|
assert out["device_attributes"]["clockSettings"]["daySilenceFrom"] is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("value", [
|
||||||
|
"2026-01-15T22:01:00Z",
|
||||||
|
"2026-01-15T22:01:00+00:00",
|
||||||
|
"15 January 2026 at 22:01:00 UTC+0000", # the format the API used to serve
|
||||||
|
])
|
||||||
|
def test_timestamp_strings_become_datetimes(value):
|
||||||
|
out = v1.to_firestore({"device_stats": {"maintainedOn": value}})
|
||||||
|
assert out["device_stats"]["maintainedOn"] == T
|
||||||
|
|
||||||
|
|
||||||
|
def test_unparseable_timestamp_is_rejected_not_stored():
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
v1.to_firestore({"device_subscription": {"subscrStart": "next tuesday"}})
|
||||||
|
|
||||||
|
|
||||||
|
def test_timestamp_round_trip_is_lossless():
|
||||||
|
stored = {"device_attributes": {"clockSettings": {"nightSilenceTo": T}}}
|
||||||
|
api = v1.to_api(stored)
|
||||||
|
assert api["device_attributes"]["clockSettings"]["nightSilenceTo"] == "2026-01-15T22:01:00Z"
|
||||||
|
again = v1.to_firestore(api)
|
||||||
|
assert again["device_attributes"]["clockSettings"]["nightSilenceTo"] == T
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- IP addresses
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("value, expected", [
|
||||||
|
(["10", "0", "0", "5"], "10.0.0.5"),
|
||||||
|
([10, 0, 0, 5], "10.0.0.5"),
|
||||||
|
([], ""),
|
||||||
|
("192.168.1.102", "192.168.1.102"),
|
||||||
|
("", ""),
|
||||||
|
])
|
||||||
|
def test_ip_addresses_are_dotted_strings(value, expected):
|
||||||
|
out = v1.to_firestore({"device_attributes": {"networkSettings": {"ipAddress": value}}})
|
||||||
|
assert out["device_attributes"]["networkSettings"]["ipAddress"] == expected
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_ip_is_rejected():
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
v1.to_firestore({"device_attributes": {"networkSettings": {"gateway": "10.0.0"}}})
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- key spelling
|
||||||
|
|
||||||
|
def test_legacy_keys_are_renamed():
|
||||||
|
out = v1.to_firestore({"device_attributes": {
|
||||||
|
"bellGuardSafetyOn": True,
|
||||||
|
"networkSettings": {"useStaticIP": True},
|
||||||
|
}})
|
||||||
|
attrs = out["device_attributes"]
|
||||||
|
assert attrs == {"bellguardSafetyOn": True, "networkSettings": {"usesStaticIP": True}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_v1_key_wins_over_legacy_duplicate():
|
||||||
|
out = v1.to_firestore({"device_attributes": {
|
||||||
|
"bellguardSafetyOn": False, "bellGuardSafetyOn": True,
|
||||||
|
"networkSettings": {"usesStaticIP": True, "useStaticIP": False},
|
||||||
|
}})
|
||||||
|
attrs = out["device_attributes"]
|
||||||
|
assert attrs["bellguardSafetyOn"] is False and "bellGuardSafetyOn" not in attrs
|
||||||
|
assert attrs["networkSettings"] == {"usesStaticIP": True}
|
||||||
|
|
||||||
|
|
||||||
|
def test_legacy_hw_names_become_firmware_names():
|
||||||
|
out = v1.to_firestore({"hw_type": "vesper_plus", "hw_version": "1.0"})
|
||||||
|
assert out == {"hw_family": "vesper_plus", "hw_revision": "1.0"}
|
||||||
|
assert v1.to_api({"hw_type": "agnus", "hw_version": "1.0"}) == {"hw_family": "agnus", "hw_revision": "1.0"}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("label", ["Bell Plus", "Bell Core", "vesper plus"])
|
||||||
|
def test_hw_family_display_labels_are_rejected(label):
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
v1.to_firestore({"hw_family": label})
|
||||||
|
|
||||||
|
|
||||||
|
def test_retired_users_list_is_dropped():
|
||||||
|
assert "users_list" not in v1.to_firestore({"users_list": [], "device_name": "x"})
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_folds_legacy_keys_and_repairs_values():
|
||||||
|
api = v1.to_api({"device_attributes": {
|
||||||
|
"bellGuardSafetyOn": True,
|
||||||
|
"towerClockTime": "",
|
||||||
|
"networkSettings": {"useStaticIP": True, "dns1": ["10", "0", "0", "1"]},
|
||||||
|
}})
|
||||||
|
attrs = api["device_attributes"]
|
||||||
|
assert attrs["bellguardSafetyOn"] is True and "bellGuardSafetyOn" not in attrs
|
||||||
|
assert attrs["towerClockTime"] is None
|
||||||
|
assert attrs["networkSettings"] == {"usesStaticIP": True, "dns1": "10.0.0.1"}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- identifiers (D1)
|
||||||
|
|
||||||
|
def test_serial_number_is_mirrored_to_device_id():
|
||||||
|
out = v1.to_firestore({"serial_number": "BSVSPR-26C20B-STD10R-2KCDPH"})
|
||||||
|
assert out["device_id"] == out["serial_number"] == "BSVSPR-26C20B-STD10R-2KCDPH"
|
||||||
|
|
||||||
|
|
||||||
|
def test_conflicting_ids_are_rejected():
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
v1.to_firestore({"serial_number": "BSVSPR-A", "device_id": "PV25K29BP01R01"})
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- references
|
||||||
|
|
||||||
|
def test_user_list_entries_become_references():
|
||||||
|
out = v1.to_firestore({"user_list": ["users/alice", "bob", "users/alice"]}, DB)
|
||||||
|
assert [r.path for r in out["user_list"]] == ["users/alice", "users/bob"]
|
||||||
|
assert all(isinstance(r, DocumentReference) for r in out["user_list"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_coordinates_become_geopoint():
|
||||||
|
out = v1.to_firestore({"device_location_coordinates": {"lat": 40.6, "lng": 22.9}})
|
||||||
|
assert isinstance(out["device_location_coordinates"], GeoPoint)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- melodies
|
||||||
|
|
||||||
|
def test_device_melody_in_melodies_collection_shape_is_rejected():
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
v1.to_firestore({"device_melodies_all": [{"information": {}, "default_settings": {}, "url": "x"}]})
|
||||||
|
|
||||||
|
|
||||||
|
def test_device_melody_reference_becomes_reference():
|
||||||
|
out = v1.to_firestore({"device_melodies_all": [
|
||||||
|
{"melodyReference": "melodies/m1", "mainInformation": {"name": "x"}},
|
||||||
|
]}, DB)
|
||||||
|
ref = out["device_melodies_all"][0]["melodyReference"]
|
||||||
|
assert isinstance(ref, DocumentReference) and ref.path == "melodies/m1"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- new devices
|
||||||
|
|
||||||
|
def test_new_device_defaults_are_v1_valid():
|
||||||
|
"""create_device writes DeviceCreate() defaults — they must not break the apps."""
|
||||||
|
doc = v1.to_firestore({**DeviceCreate().model_dump(), "serial_number": "BS-AAAA-BBBB"}, DB)
|
||||||
|
attrs = doc["device_attributes"]
|
||||||
|
for key in ("daySilenceFrom", "daySilenceTo", "nightSilenceFrom", "nightSilenceTo",
|
||||||
|
"backlightTurnOnTime", "backlightTurnOffTime"):
|
||||||
|
assert attrs["clockSettings"][key] is None
|
||||||
|
assert attrs["towerClockTime"] is None
|
||||||
|
assert attrs["networkSettings"]["ipAddress"] == ""
|
||||||
|
assert "useStaticIP" not in attrs["networkSettings"] and "usesStaticIP" in attrs["networkSettings"]
|
||||||
|
assert "bellguardSafetyOn" in attrs and "bellGuardSafetyOn" not in attrs
|
||||||
|
assert doc["device_stats"]["maintainedOn"] is None
|
||||||
|
assert doc["device_subscription"]["subscrStart"] is None
|
||||||
|
assert doc["device_id"] == "BS-AAAA-BBBB"
|
||||||
+17
-28
@@ -236,29 +236,23 @@ def assign_device(user_doc_id: str, device_doc_id: str) -> UserInDB:
|
|||||||
if not device_doc.exists:
|
if not device_doc.exists:
|
||||||
raise NotFoundError("Device")
|
raise NotFoundError("Device")
|
||||||
|
|
||||||
# Add user path to device's user_list if not already there
|
from devices import service as devices_service
|
||||||
|
|
||||||
|
# Add a user reference to device's user_list if not already there.
|
||||||
|
# Stored as a DocumentReference, the format the FlutterFlow app writes.
|
||||||
device_data = device_doc.to_dict()
|
device_data = device_doc.to_dict()
|
||||||
user_list = device_data.get("user_list", [])
|
user_list = device_data.get("user_list", []) or []
|
||||||
user_path = f"users/{user_doc_id}"
|
already_assigned = any(devices_service.user_list_entry_id(e) == user_doc_id for e in user_list)
|
||||||
|
|
||||||
# Check if already assigned (handle both string paths and DocumentReferences)
|
# Device user_list, the user's device_serials and the device_users mirror
|
||||||
already_assigned = False
|
# are written in one atomic batch. device_serials and the mirror are
|
||||||
for entry in user_list:
|
# re-synced even when already assigned, to heal drift.
|
||||||
if isinstance(entry, DocumentReference):
|
|
||||||
if entry.path == user_path:
|
|
||||||
already_assigned = True
|
|
||||||
break
|
|
||||||
elif entry == user_path:
|
|
||||||
already_assigned = True
|
|
||||||
break
|
|
||||||
|
|
||||||
# Device user_list and the user's device_serials are written in one atomic batch.
|
|
||||||
# device_serials is re-synced even when already assigned, to heal drift.
|
|
||||||
batch = db.batch()
|
batch = db.batch()
|
||||||
if not already_assigned:
|
if not already_assigned:
|
||||||
user_list.append(user_path)
|
user_list.append(user_ref)
|
||||||
batch.update(device_ref, {"user_list": user_list})
|
batch.update(device_ref, {"user_list": user_list})
|
||||||
stage_device_serial_link(batch, user_ref, device_serial_of(device_data), linked=True)
|
stage_device_serial_link(batch, user_ref, device_serial_of(device_data), linked=True)
|
||||||
|
devices_service.stage_device_users_mirror(batch, device_ref, user_ref, linked=True)
|
||||||
batch.commit()
|
batch.commit()
|
||||||
invalidate_mqtt_acl_cache(user_doc.to_dict())
|
invalidate_mqtt_acl_cache(user_doc.to_dict())
|
||||||
|
|
||||||
@@ -281,22 +275,17 @@ def unassign_device(user_doc_id: str, device_doc_id: str) -> UserInDB:
|
|||||||
if not device_doc.exists:
|
if not device_doc.exists:
|
||||||
raise NotFoundError("Device")
|
raise NotFoundError("Device")
|
||||||
|
|
||||||
# Remove user from device's user_list
|
from devices import service as devices_service
|
||||||
device_data = device_doc.to_dict()
|
|
||||||
user_list = device_data.get("user_list", [])
|
|
||||||
user_path = f"users/{user_doc_id}"
|
|
||||||
|
|
||||||
new_list = []
|
# Remove user from device's user_list (any entry format)
|
||||||
for entry in user_list:
|
device_data = device_doc.to_dict()
|
||||||
if isinstance(entry, DocumentReference):
|
user_list = device_data.get("user_list", []) or []
|
||||||
if entry.path != user_path:
|
new_list = [e for e in user_list if devices_service.user_list_entry_id(e) != user_doc_id]
|
||||||
new_list.append(entry)
|
|
||||||
elif entry != user_path:
|
|
||||||
new_list.append(entry)
|
|
||||||
|
|
||||||
batch = db.batch()
|
batch = db.batch()
|
||||||
batch.update(device_ref, {"user_list": new_list})
|
batch.update(device_ref, {"user_list": new_list})
|
||||||
stage_device_serial_link(batch, user_ref, device_serial_of(device_data), linked=False)
|
stage_device_serial_link(batch, user_ref, device_serial_of(device_data), linked=False)
|
||||||
|
devices_service.stage_device_users_mirror(batch, device_ref, user_ref, linked=False)
|
||||||
batch.commit()
|
batch.commit()
|
||||||
invalidate_mqtt_acl_cache(user_doc.to_dict())
|
invalidate_mqtt_acl_cache(user_doc.to_dict())
|
||||||
|
|
||||||
|
|||||||
@@ -201,11 +201,17 @@ When those lines stop appearing, set `MQTT_ALLOW_LEGACY_PASSWORD=false`.
|
|||||||
Firestore (e.g. a claim flow), it must also update `device_serials` the same way
|
Firestore (e.g. a claim flow), it must also update `device_serials` the same way
|
||||||
(ArrayUnion / ArrayRemove of the serial on the user doc). Otherwise that user
|
(ArrayUnion / ArrayRemove of the serial on the user doc). Otherwise that user
|
||||||
cannot reach the device over MQTT. The app owner will handle this in the app.
|
cannot reach the device over MQTT. The app owner will handle this in the app.
|
||||||
- **The `device_users` subcollection** on devices (older way of recording device users,
|
- **The `device_users` subcollection** on devices (`{role, user_reference}`, the older
|
||||||
read first by `devices.service.get_device_users`) is **intentionally ignored** by
|
way of recording device users) is a **write-only mirror** since 2026-11. `user_list`
|
||||||
the backfill and the MQTT ACL. Left as is by decision.
|
is the only source of truth: the Console reads assignments only from it
|
||||||
- The two Console assignment paths store `user_list` entries in different formats
|
(`devices.service.get_device_users`, which takes just the `role` from the mirror).
|
||||||
(path strings vs DocumentReferences). This predates this work; all readers accept both.
|
Every Console path that edits `user_list` also adds/removes the mirror doc in the
|
||||||
|
same batch (`devices.service.stage_device_users_mirror`). The MQTT ACL and the
|
||||||
|
backfill ignore it. It is kept only in case the phone app still reads it, and is
|
||||||
|
meant to be removed. `scripts/sync_device_users_mirror.py` (dry run by default)
|
||||||
|
fixes drift from before 2026-11.
|
||||||
|
- All Console paths now write `user_list` entries as DocumentReferences (what the app
|
||||||
|
writes). Older data may still hold `"users/{id}"` path strings; all readers accept both.
|
||||||
- ACL denies are logged at INFO, which is not shown by default. Auth denies and
|
- ACL denies are logged at INFO, which is not shown by default. Auth denies and
|
||||||
legacy-password logins are WARNING.
|
legacy-password logins are WARNING.
|
||||||
|
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ function extractTime(tsStr) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function timeToIso(hhmm) {
|
function timeToIso(hhmm) {
|
||||||
if (!hhmm) return ''
|
if (!hhmm) return null
|
||||||
return `2000-01-01T${hhmm}:00Z`
|
return `2000-01-01T${hhmm}:00Z`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -183,11 +183,11 @@ export default function EditAlertsModal({ open, onClose, onSaved, clock, attr, i
|
|||||||
halfhourAlertsBell: Number(halfBell),
|
halfhourAlertsBell: Number(halfBell),
|
||||||
quarterAlertsBell: Number(quarterBell),
|
quarterAlertsBell: Number(quarterBell),
|
||||||
isDaySilenceOn: isDayOn,
|
isDaySilenceOn: isDayOn,
|
||||||
daySilenceFrom: isDayOn && daySilenceFrom ? timeToIso(daySilenceFrom) : (clock?.daySilenceFrom || ''),
|
daySilenceFrom: isDayOn && daySilenceFrom ? timeToIso(daySilenceFrom) : (clock?.daySilenceFrom ?? null),
|
||||||
daySilenceTo: isDayOn && daySilenceTo ? timeToIso(daySilenceTo) : (clock?.daySilenceTo || ''),
|
daySilenceTo: isDayOn && daySilenceTo ? timeToIso(daySilenceTo) : (clock?.daySilenceTo ?? null),
|
||||||
isNightSilenceOn: isNightOn,
|
isNightSilenceOn: isNightOn,
|
||||||
nightSilenceFrom: isNightOn && nightFrom ? timeToIso(nightFrom) : (clock?.nightSilenceFrom || ''),
|
nightSilenceFrom: isNightOn && nightFrom ? timeToIso(nightFrom) : (clock?.nightSilenceFrom ?? null),
|
||||||
nightSilenceTo: isNightOn && nightTo ? timeToIso(nightTo) : (clock?.nightSilenceTo || ''),
|
nightSilenceTo: isNightOn && nightTo ? timeToIso(nightTo) : (clock?.nightSilenceTo ?? null),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ const toBool = (v) => v === 'true' || v === true
|
|||||||
|
|
||||||
export default function EditAttributesModal({ open, onClose, onSaved, attr, id }) {
|
export default function EditAttributesModal({ open, onClose, onSaved, attr, id }) {
|
||||||
const [bellGuardOn, setBellGuardOn] = useState(String(attr?.bellGuardOn ?? false))
|
const [bellGuardOn, setBellGuardOn] = useState(String(attr?.bellGuardOn ?? false))
|
||||||
const [bellGuardSafetyOn, setBellGuardSafetyOn] = useState(String(attr?.bellGuardSafetyOn ?? false))
|
const [bellGuardSafetyOn, setBellGuardSafetyOn] = useState(String(attr?.bellguardSafetyOn ?? false))
|
||||||
const [warningsOn, setWarningsOn] = useState(String(attr?.warningsOn ?? false))
|
const [warningsOn, setWarningsOn] = useState(String(attr?.warningsOn ?? false))
|
||||||
const [saving, setSaving] = useState(false)
|
const [saving, setSaving] = useState(false)
|
||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
@@ -23,7 +23,7 @@ export default function EditAttributesModal({ open, onClose, onSaved, attr, id }
|
|||||||
device_attributes: {
|
device_attributes: {
|
||||||
bellGuardOn: toBool(bellGuardOn),
|
bellGuardOn: toBool(bellGuardOn),
|
||||||
warningsOn: toBool(warningsOn),
|
warningsOn: toBool(warningsOn),
|
||||||
bellGuardSafetyOn: toBool(bellGuardSafetyOn),
|
bellguardSafetyOn: toBool(bellGuardSafetyOn),
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
await onSaved()
|
await onSaved()
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ function extractTime(tsStr) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function timeToIso(hhmm) {
|
function timeToIso(hhmm) {
|
||||||
if (!hhmm) return ''
|
if (!hhmm) return null
|
||||||
return `2000-01-01T${hhmm}:00Z`
|
return `2000-01-01T${hhmm}:00Z`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,8 +62,8 @@ export default function EditBacklightModal({ open, onClose, onSaved, attr, clock
|
|||||||
...clock,
|
...clock,
|
||||||
isBacklightAutomationOn: enabled,
|
isBacklightAutomationOn: enabled,
|
||||||
backlightOutput: Number(output),
|
backlightOutput: Number(output),
|
||||||
backlightTurnOnTime: enabled && onTime ? timeToIso(onTime) : '',
|
backlightTurnOnTime: enabled && onTime ? timeToIso(onTime) : null,
|
||||||
backlightTurnOffTime: enabled && offTime ? timeToIso(offTime) : '',
|
backlightTurnOffTime: enabled && offTime ? timeToIso(offTime) : null,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -91,7 +91,7 @@ function deepMerge(base, overrides) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function timeToIso(hhmm) {
|
function timeToIso(hhmm) {
|
||||||
if (!hhmm) return ''
|
if (!hhmm) return null
|
||||||
return `2000-01-01T${hhmm}:00Z`
|
return `2000-01-01T${hhmm}:00Z`
|
||||||
}
|
}
|
||||||
function extractTime(tsStr) {
|
function extractTime(tsStr) {
|
||||||
@@ -250,8 +250,8 @@ const TABLE_COLUMNS = [
|
|||||||
render: (d) => friendlyName(d) || <span style={{ color: 'var(--color-text-muted)' }}>—</span>,
|
render: (d) => friendlyName(d) || <span style={{ color: 'var(--color-text-muted)' }}>—</span>,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'hw_type', label: 'Board Type', sortable: true,
|
key: 'hw_family', label: 'Board Type', sortable: true,
|
||||||
render: (d) => d.hw_type || <span style={{ color: 'var(--color-text-muted)' }}>—</span>,
|
render: (d) => d.hw_family || <span style={{ color: 'var(--color-text-muted)' }}>—</span>,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'mfg_status', label: 'Status',
|
key: 'mfg_status', label: 'Status',
|
||||||
@@ -301,14 +301,14 @@ function DevicePicker({ onSelect }) {
|
|||||||
}
|
}
|
||||||
if (boardTypes.length > 0) {
|
if (boardTypes.length > 0) {
|
||||||
const boardTypeSet = new Set(boardTypes)
|
const boardTypeSet = new Set(boardTypes)
|
||||||
list = list.filter((d) => boardTypeSet.has(d.hw_type))
|
list = list.filter((d) => boardTypeSet.has(d.hw_family))
|
||||||
}
|
}
|
||||||
const q = search.trim().toLowerCase()
|
const q = search.trim().toLowerCase()
|
||||||
if (q) {
|
if (q) {
|
||||||
list = list.filter((d) => {
|
list = list.filter((d) => {
|
||||||
if ((d.serial_number || '').toLowerCase().includes(q)) return true
|
if ((d.serial_number || '').toLowerCase().includes(q)) return true
|
||||||
if ((friendlyName(d) || '').toLowerCase().includes(q)) return true
|
if ((friendlyName(d) || '').toLowerCase().includes(q)) return true
|
||||||
if ((d.hw_type || '').toLowerCase().includes(q)) return true
|
if ((d.hw_family || '').toLowerCase().includes(q)) return true
|
||||||
if ((d.customer_name || '').toLowerCase().includes(q)) return true
|
if ((d.customer_name || '').toLowerCase().includes(q)) return true
|
||||||
if ((d.users || []).some((u) => (u.display_name || '').toLowerCase().includes(q) || (u.email || '').toLowerCase().includes(q))) return true
|
if ((d.users || []).some((u) => (u.display_name || '').toLowerCase().includes(q) || (u.email || '').toLowerCase().includes(q))) return true
|
||||||
return false
|
return false
|
||||||
@@ -640,7 +640,7 @@ const PlanStep = forwardRef(function PlanStep({ device, onDeviceUpdated }, ref)
|
|||||||
const startIso = startDateStr ? `${startDateStr}T00:00:00Z` : new Date().toISOString()
|
const startIso = startDateStr ? `${startDateStr}T00:00:00Z` : new Date().toISOString()
|
||||||
// PUT /devices/{id} returns the DeviceInDB shape, which doesn't line up
|
// PUT /devices/{id} returns the DeviceInDB shape, which doesn't line up
|
||||||
// field-for-field with the DeviceInventoryItem shape the rest of the wizard
|
// field-for-field with the DeviceInventoryItem shape the rest of the wizard
|
||||||
// uses (e.g. hw_type vs hw_family) — merge in just the two fields Configure
|
// uses — merge in just the two fields Configure
|
||||||
// actually needs rather than replacing the whole device object.
|
// actually needs rather than replacing the whole device object.
|
||||||
const updated = await api.put(`/devices/${device.id}`, {
|
const updated = await api.put(`/devices/${device.id}`, {
|
||||||
device_subscription: {
|
device_subscription: {
|
||||||
@@ -1353,11 +1353,11 @@ function ConfigureStep({ device, onDeviceUpdated, onNext, onBack }) {
|
|||||||
halfhourAlertsBell: Number(alert.halfBell),
|
halfhourAlertsBell: Number(alert.halfBell),
|
||||||
quarterAlertsBell: Number(alert.quarterBell),
|
quarterAlertsBell: Number(alert.quarterBell),
|
||||||
isDaySilenceOn: alert.isDayOn,
|
isDaySilenceOn: alert.isDayOn,
|
||||||
daySilenceFrom: alert.isDayOn && alert.dayFrom ? timeToIso(alert.dayFrom) : (clock.daySilenceFrom || ''),
|
daySilenceFrom: alert.isDayOn && alert.dayFrom ? timeToIso(alert.dayFrom) : (clock.daySilenceFrom ?? null),
|
||||||
daySilenceTo: alert.isDayOn && alert.dayTo ? timeToIso(alert.dayTo) : (clock.daySilenceTo || ''),
|
daySilenceTo: alert.isDayOn && alert.dayTo ? timeToIso(alert.dayTo) : (clock.daySilenceTo ?? null),
|
||||||
isNightSilenceOn: alert.isNightOn,
|
isNightSilenceOn: alert.isNightOn,
|
||||||
nightSilenceFrom: alert.isNightOn && alert.nightFrom ? timeToIso(alert.nightFrom) : (clock.nightSilenceFrom || ''),
|
nightSilenceFrom: alert.isNightOn && alert.nightFrom ? timeToIso(alert.nightFrom) : (clock.nightSilenceFrom ?? null),
|
||||||
nightSilenceTo: alert.isNightOn && alert.nightTo ? timeToIso(alert.nightTo) : (clock.nightSilenceTo || ''),
|
nightSilenceTo: alert.isNightOn && alert.nightTo ? timeToIso(alert.nightTo) : (clock.nightSilenceTo ?? null),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -1377,8 +1377,8 @@ function ConfigureStep({ device, onDeviceUpdated, onNext, onBack }) {
|
|||||||
clockSettings: {
|
clockSettings: {
|
||||||
isBacklightAutomationOn: backlight.enabled,
|
isBacklightAutomationOn: backlight.enabled,
|
||||||
backlightOutput: Number(backlight.output),
|
backlightOutput: Number(backlight.output),
|
||||||
backlightTurnOnTime: backlight.enabled && backlight.onTime ? timeToIso(backlight.onTime) : '',
|
backlightTurnOnTime: backlight.enabled && backlight.onTime ? timeToIso(backlight.onTime) : null,
|
||||||
backlightTurnOffTime: backlight.enabled && backlight.offTime ? timeToIso(backlight.offTime) : '',
|
backlightTurnOffTime: backlight.enabled && backlight.offTime ? timeToIso(backlight.offTime) : null,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -1975,7 +1975,7 @@ function DeviceWorkspace({ device, onDeviceUpdated, onDone, onChangeDevice }) {
|
|||||||
return (
|
return (
|
||||||
<Card
|
<Card
|
||||||
title={device.serial_number}
|
title={device.serial_number}
|
||||||
subtitle={`${friendlyName(device) || device.hw_type || '—'} · ${device.mfg_status}`}
|
subtitle={`${friendlyName(device) || device.hw_family || '—'} · ${device.mfg_status}`}
|
||||||
action={<Button variant="ghost" size="sm" onClick={onChangeDevice}>Change Device</Button>}
|
action={<Button variant="ghost" size="sm" onClick={onChangeDevice}>Change Device</Button>}
|
||||||
>
|
>
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)' }}>
|
||||||
|
|||||||
@@ -388,15 +388,15 @@ export default function ClockTab({
|
|||||||
halfhourAlertsBell: trueHalfBell,
|
halfhourAlertsBell: trueHalfBell,
|
||||||
quarterAlertsBell: trueQuarterBell,
|
quarterAlertsBell: trueQuarterBell,
|
||||||
isDaySilenceOn: !!data.daytime_silence,
|
isDaySilenceOn: !!data.daytime_silence,
|
||||||
daySilenceFrom: data.daytime_on ? `2000-01-01T${data.daytime_on}:00Z` : (clock?.daySilenceFrom || ''),
|
daySilenceFrom: data.daytime_on ? `2000-01-01T${data.daytime_on}:00Z` : (clock?.daySilenceFrom ?? null),
|
||||||
daySilenceTo: data.daytime_off ? `2000-01-01T${data.daytime_off}:00Z` : (clock?.daySilenceTo || ''),
|
daySilenceTo: data.daytime_off ? `2000-01-01T${data.daytime_off}:00Z` : (clock?.daySilenceTo ?? null),
|
||||||
isNightSilenceOn: !!data.night_silence,
|
isNightSilenceOn: !!data.night_silence,
|
||||||
nightSilenceFrom: data.night_on ? `2000-01-01T${data.night_on}:00Z` : (clock?.nightSilenceFrom || ''),
|
nightSilenceFrom: data.night_on ? `2000-01-01T${data.night_on}:00Z` : (clock?.nightSilenceFrom ?? null),
|
||||||
nightSilenceTo: data.night_off ? `2000-01-01T${data.night_off}:00Z` : (clock?.nightSilenceTo || ''),
|
nightSilenceTo: data.night_off ? `2000-01-01T${data.night_off}:00Z` : (clock?.nightSilenceTo ?? null),
|
||||||
isBacklightAutomationOn: !!data.backlight,
|
isBacklightAutomationOn: !!data.backlight,
|
||||||
backlightOutput: trueBacklightOutput,
|
backlightOutput: trueBacklightOutput,
|
||||||
backlightTurnOnTime: data.backlight_on ? `2000-01-01T${data.backlight_on}:00Z` : '',
|
backlightTurnOnTime: data.backlight_on ? `2000-01-01T${data.backlight_on}:00Z` : null,
|
||||||
backlightTurnOffTime: data.backlight_off ? `2000-01-01T${data.backlight_off}:00Z` : '',
|
backlightTurnOffTime: data.backlight_off ? `2000-01-01T${data.backlight_off}:00Z` : null,
|
||||||
faceSyncMode: data.face_sync_mode ?? clock?.faceSyncMode ?? 'force',
|
faceSyncMode: data.face_sync_mode ?? clock?.faceSyncMode ?? 'force',
|
||||||
smartMaxWaitMin: data.smart_max_wait_min ?? clock?.smartMaxWaitMin ?? 61,
|
smartMaxWaitMin: data.smart_max_wait_min ?? clock?.smartMaxWaitMin ?? 61,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1170,7 +1170,7 @@ export default function GeneralTab({
|
|||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)', flex: 1, justifyContent: 'center' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)', flex: 1, justifyContent: 'center' }}>
|
||||||
<SafetyRow label="Bell Guard" description="Automated striking lock" enabled={attr?.bellGuardOn} />
|
<SafetyRow label="Bell Guard" description="Automated striking lock" enabled={attr?.bellGuardOn} />
|
||||||
<SafetyRow label="Warnings" description="Audible system alerts" enabled={attr?.warningsOn} />
|
<SafetyRow label="Warnings" description="Audible system alerts" enabled={attr?.warningsOn} />
|
||||||
<SafetyRow label="Safety" description="Manual override lock" enabled={attr?.bellGuardSafetyOn} />
|
<SafetyRow label="Safety" description="Manual override lock" enabled={attr?.bellguardSafetyOn} />
|
||||||
</div>
|
</div>
|
||||||
</GlassCard>
|
</GlassCard>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -235,7 +235,7 @@ export default function OverviewTab({
|
|||||||
api.get('/crm/products').catch(() => null),
|
api.get('/crm/products').catch(() => null),
|
||||||
]).then(([mfgItem, productsRes]) => {
|
]).then(([mfgItem, productsRes]) => {
|
||||||
if (mfgItem?.revision) setHwRevision(mfgItem.revision)
|
if (mfgItem?.revision) setHwRevision(mfgItem.revision)
|
||||||
const hwType = mfgItem?.hw_type || ''
|
const hwType = mfgItem?.hw_family || ''
|
||||||
if (!hwType) return
|
if (!hwType) return
|
||||||
const products = productsRes?.products || []
|
const products = productsRes?.products || []
|
||||||
const norm = s => (s || '').toLowerCase().replace(/[^a-z0-9]/g, '')
|
const norm = s => (s || '').toLowerCase().replace(/[^a-z0-9]/g, '')
|
||||||
|
|||||||
@@ -154,7 +154,7 @@ export default function DeviceInventory() {
|
|||||||
const params = new URLSearchParams()
|
const params = new URLSearchParams()
|
||||||
if (search) params.set('search', search)
|
if (search) params.set('search', search)
|
||||||
if (statusFilter) params.set('status', statusFilter)
|
if (statusFilter) params.set('status', statusFilter)
|
||||||
if (typeFilter) params.set('hw_type', typeFilter)
|
if (typeFilter) params.set('hw_family', typeFilter)
|
||||||
params.set('limit', '500')
|
params.set('limit', '500')
|
||||||
const data = await api.get(`/manufacturing/devices${params.toString() ? `?${params}` : ''}`)
|
const data = await api.get(`/manufacturing/devices${params.toString() ? `?${params}` : ''}`)
|
||||||
const devs = data.devices || []
|
const devs = data.devices || []
|
||||||
@@ -198,8 +198,8 @@ export default function DeviceInventory() {
|
|||||||
if (!sortKey) return devices
|
if (!sortKey) return devices
|
||||||
return [...devices].sort((a, b) => {
|
return [...devices].sort((a, b) => {
|
||||||
let av, bv
|
let av, bv
|
||||||
if (sortKey === 'type') { av = BOARD_TYPE_LABELS[a.hw_type] || a.hw_type || ''; bv = BOARD_TYPE_LABELS[b.hw_type] || b.hw_type || '' }
|
if (sortKey === 'type') { av = BOARD_TYPE_LABELS[a.hw_family] || a.hw_family || ''; bv = BOARD_TYPE_LABELS[b.hw_family] || b.hw_family || '' }
|
||||||
else if (sortKey === 'version') { av = a.hw_version || ''; bv = b.hw_version || '' }
|
else if (sortKey === 'version') { av = a.hw_revision || ''; bv = b.hw_revision || '' }
|
||||||
else if (sortKey === 'created') { av = a.created_at || ''; bv = b.created_at || '' }
|
else if (sortKey === 'created') { av = a.created_at || ''; bv = b.created_at || '' }
|
||||||
else if (sortKey === 'customer') {
|
else if (sortKey === 'customer') {
|
||||||
const ca = customerMap[a.customer_id]; const cb = customerMap[b.customer_id]
|
const ca = customerMap[a.customer_id]; const cb = customerMap[b.customer_id]
|
||||||
@@ -268,7 +268,7 @@ export default function DeviceInventory() {
|
|||||||
sortable: true,
|
sortable: true,
|
||||||
render: (d) => (
|
render: (d) => (
|
||||||
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>
|
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>
|
||||||
{BOARD_TYPE_LABELS[d.hw_type] || d.hw_type}
|
{BOARD_TYPE_LABELS[d.hw_family] || d.hw_family}
|
||||||
</span>
|
</span>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@@ -278,7 +278,7 @@ export default function DeviceInventory() {
|
|||||||
sortable: true,
|
sortable: true,
|
||||||
render: (d) => (
|
render: (d) => (
|
||||||
<span style={{ fontSize: 'var(--font-size-sm)', fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-muted)' }}>
|
<span style={{ fontSize: 'var(--font-size-sm)', fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-muted)' }}>
|
||||||
{formatHwVersion(d.hw_version)}
|
{formatHwVersion(d.hw_revision)}
|
||||||
</span>
|
</span>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -645,7 +645,7 @@ export default function DeviceInventoryDetail() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const boardLabel = BOARD_TYPE_LABELS[device.hw_type] || device.hw_type
|
const boardLabel = BOARD_TYPE_LABELS[device.hw_family] || device.hw_family
|
||||||
const existingUserIds = deviceUsers.map((u) => u.user_id).filter(Boolean)
|
const existingUserIds = deviceUsers.map((u) => u.user_id).filter(Boolean)
|
||||||
|
|
||||||
const editStepMeta = editModalData ? LIFECYCLE[editModalData.stepIndex] : null
|
const editStepMeta = editModalData ? LIFECYCLE[editModalData.stepIndex] : null
|
||||||
@@ -662,7 +662,7 @@ export default function DeviceInventoryDetail() {
|
|||||||
</StatusBadge>
|
</StatusBadge>
|
||||||
</span>
|
</span>
|
||||||
}
|
}
|
||||||
subtitle={`${device.name || device.device_name || '—'} · ${boardLabel} · ${formatHwVersion(device.hw_version)}`}
|
subtitle={`${device.name || device.device_name || '—'} · ${boardLabel} · ${formatHwVersion(device.hw_revision)}`}
|
||||||
>
|
>
|
||||||
{canEdit && (
|
{canEdit && (
|
||||||
<Button variant="secondary" size="md" onClick={() => navigate(`/manufacturing/provision?sn=${sn}`)}>
|
<Button variant="secondary" size="md" onClick={() => navigate(`/manufacturing/provision?sn=${sn}`)}>
|
||||||
@@ -687,7 +687,7 @@ export default function DeviceInventoryDetail() {
|
|||||||
<Field label="Serial Number" value={device.serial_number} mono />
|
<Field label="Serial Number" value={device.serial_number} mono />
|
||||||
<Field label="Batch ID" value={device.batch_id || device.mfg_batch_id} mono />
|
<Field label="Batch ID" value={device.batch_id || device.mfg_batch_id} mono />
|
||||||
<Field label="Hardware Family" value={boardLabel} />
|
<Field label="Hardware Family" value={boardLabel} />
|
||||||
<Field label="HW Version" value={formatHwVersion(device.hw_version)} mono />
|
<Field label="HW Version" value={formatHwVersion(device.hw_revision)} mono />
|
||||||
<Field label="Created At" value={formatDate(device.created_at)} />
|
<Field label="Created At" value={formatDate(device.created_at)} />
|
||||||
<Field label="Device Name" value={device.name || device.device_name} />
|
<Field label="Device Name" value={device.name || device.device_name} />
|
||||||
<div style={{ gridColumn: '1 / -1' }}>
|
<div style={{ gridColumn: '1 / -1' }}>
|
||||||
|
|||||||
@@ -344,7 +344,7 @@ function BespokePickerModal({ open, onConfirm, onClose }) {
|
|||||||
Hardware Family for NVS
|
Hardware Family for NVS
|
||||||
</label>
|
</label>
|
||||||
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', marginBottom: 'var(--space-2)' }}>
|
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', marginBottom: 'var(--space-2)' }}>
|
||||||
Written to NVS as <span style={{ fontFamily: 'var(--font-family-mono)' }}>hw_type</span>.
|
Written to NVS as <span style={{ fontFamily: 'var(--font-family-mono)' }}>hw_family</span>.
|
||||||
</p>
|
</p>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
@@ -508,7 +508,7 @@ function StepSelectDevice({ mode, preloadSn, onSelected, onCreatedSn }) {
|
|||||||
|
|
||||||
// ── Selected confirmation panel ──
|
// ── Selected confirmation panel ──
|
||||||
if (picked) {
|
if (picked) {
|
||||||
const boardInfo = BOARD_TYPE_MAP[picked.hw_type]
|
const boardInfo = BOARD_TYPE_MAP[picked.hw_family]
|
||||||
const pal = BOARD_FAMILY_COLORS[boardInfo?.family || 'vesper']
|
const pal = BOARD_FAMILY_COLORS[boardInfo?.family || 'vesper']
|
||||||
return (
|
return (
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
|
||||||
@@ -516,8 +516,8 @@ function StepSelectDevice({ mode, preloadSn, onSelected, onCreatedSn }) {
|
|||||||
<p style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: pal.selectedText, textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: 'var(--space-3)' }}>Device Selected</p>
|
<p style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: pal.selectedText, textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: 'var(--space-3)' }}>Device Selected</p>
|
||||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
||||||
<InfoCell label="Serial Number" value={picked.serial_number} mono />
|
<InfoCell label="Serial Number" value={picked.serial_number} mono />
|
||||||
<InfoCell label="Board Type" value={BOARD_TYPE_LABELS[picked.hw_type] || picked.hw_type} />
|
<InfoCell label="Board Type" value={BOARD_TYPE_LABELS[picked.hw_family] || picked.hw_family} />
|
||||||
<InfoCell label="HW Revision" value={formatHwVersion(picked.hw_version)} />
|
<InfoCell label="HW Revision" value={formatHwVersion(picked.hw_revision)} />
|
||||||
<InfoCell label="Status" value={<StatusBadge variant={STATUS_VARIANT[picked.mfg_status] || 'neutral'}>{picked.mfg_status}</StatusBadge>} />
|
<InfoCell label="Status" value={<StatusBadge variant={STATUS_VARIANT[picked.mfg_status] || 'neutral'}>{picked.mfg_status}</StatusBadge>} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -660,8 +660,8 @@ function StepSelectDevice({ mode, preloadSn, onSelected, onCreatedSn }) {
|
|||||||
onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = '' }}
|
onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = '' }}
|
||||||
>
|
>
|
||||||
<td style={{ padding: 'var(--space-3)', fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)' }}>{d.serial_number}</td>
|
<td style={{ padding: 'var(--space-3)', fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)' }}>{d.serial_number}</td>
|
||||||
<td style={{ padding: 'var(--space-3)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>{BOARD_TYPE_LABELS[d.hw_type] || d.hw_type}</td>
|
<td style={{ padding: 'var(--space-3)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>{BOARD_TYPE_LABELS[d.hw_family] || d.hw_family}</td>
|
||||||
<td style={{ padding: 'var(--space-3)', fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>{formatHwVersion(d.hw_version)}</td>
|
<td style={{ padding: 'var(--space-3)', fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>{formatHwVersion(d.hw_revision)}</td>
|
||||||
<td style={{ padding: 'var(--space-3)' }}>
|
<td style={{ padding: 'var(--space-3)' }}>
|
||||||
<StatusBadge variant={STATUS_VARIANT[d.mfg_status] || 'neutral'}>{d.mfg_status}</StatusBadge>
|
<StatusBadge variant={STATUS_VARIANT[d.mfg_status] || 'neutral'}>{d.mfg_status}</StatusBadge>
|
||||||
</td>
|
</td>
|
||||||
@@ -888,7 +888,7 @@ function StepFlash({ device, bespokeOverride, onFlashed, serialConn }) {
|
|||||||
|
|
||||||
const webSerialAvailable = typeof navigator !== 'undefined' && 'serial' in navigator
|
const webSerialAvailable = typeof navigator !== 'undefined' && 'serial' in navigator
|
||||||
const busy = connecting || flashing
|
const busy = connecting || flashing
|
||||||
const boardInfo = BOARD_TYPE_MAP[device.hw_type]
|
const boardInfo = BOARD_TYPE_MAP[device.hw_family]
|
||||||
|
|
||||||
const familyPal = BOARD_FAMILY_COLORS[boardInfo?.family || 'vesper']
|
const familyPal = BOARD_FAMILY_COLORS[boardInfo?.family || 'vesper']
|
||||||
const readyToFlash = portConnected && !flashing && !done && log.length === 0
|
const readyToFlash = portConnected && !flashing && !done && log.length === 0
|
||||||
@@ -934,7 +934,7 @@ function StepFlash({ device, bespokeOverride, onFlashed, serialConn }) {
|
|||||||
{bespokeOverride ? (
|
{bespokeOverride ? (
|
||||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
||||||
<InfoCell label="Serial Number" value={device.serial_number} mono />
|
<InfoCell label="Serial Number" value={device.serial_number} mono />
|
||||||
<InfoCell label="NVS hw_type" value={bespokeOverride.hwFamily} />
|
<InfoCell label="NVS hw_family" value={bespokeOverride.hwFamily} />
|
||||||
<InfoCell label="NVS hw_revision" value="1.0" />
|
<InfoCell label="NVS hw_revision" value="1.0" />
|
||||||
<div>
|
<div>
|
||||||
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', fontWeight: 'var(--font-weight-semibold)', marginBottom: 'var(--space-1)' }}>Firmware</p>
|
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', fontWeight: 'var(--font-weight-semibold)', marginBottom: 'var(--space-1)' }}>Firmware</p>
|
||||||
@@ -956,7 +956,7 @@ function StepFlash({ device, bespokeOverride, onFlashed, serialConn }) {
|
|||||||
Board Type:
|
Board Type:
|
||||||
<span style={{ display: 'inline-block', width: 'var(--space-3)' }} />
|
<span style={{ display: 'inline-block', width: 'var(--space-3)' }} />
|
||||||
<span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-md)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-primary)' }}>
|
<span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-md)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-primary)' }}>
|
||||||
{boardInfo?.uiName || boardInfo?.name || device.hw_type}
|
{boardInfo?.uiName || boardInfo?.name || device.hw_family}
|
||||||
</span>
|
</span>
|
||||||
{boardInfo?.codename && (
|
{boardInfo?.codename && (
|
||||||
<span style={{ fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-muted)', fontSize: 'var(--font-size-xs)', marginLeft: 'var(--space-2)' }}>| {boardInfo.codename}</span>
|
<span style={{ fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-muted)', fontSize: 'var(--font-size-xs)', marginLeft: 'var(--space-2)' }}>| {boardInfo.codename}</span>
|
||||||
@@ -967,7 +967,7 @@ function StepFlash({ device, bespokeOverride, onFlashed, serialConn }) {
|
|||||||
Revision:
|
Revision:
|
||||||
<span style={{ display: 'inline-block', width: 'var(--space-3)' }} />
|
<span style={{ display: 'inline-block', width: 'var(--space-3)' }} />
|
||||||
<span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-md)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-primary)' }}>
|
<span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-md)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-primary)' }}>
|
||||||
{formatHwVersion(device.hw_version)}
|
{formatHwVersion(device.hw_revision)}
|
||||||
</span>
|
</span>
|
||||||
</p>
|
</p>
|
||||||
</>
|
</>
|
||||||
@@ -1453,11 +1453,11 @@ function StepDone({ device, onProvisionNext, serialConn }) {
|
|||||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
|
||||||
<div style={{ padding: 'var(--space-4)', borderRight: '1px solid var(--color-border)' }}>
|
<div style={{ padding: 'var(--space-4)', borderRight: '1px solid var(--color-border)' }}>
|
||||||
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: 'var(--space-1)' }}>Board Type</p>
|
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: 'var(--space-1)' }}>Board Type</p>
|
||||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)' }}>{BOARD_TYPE_LABELS[device?.hw_type] || device?.hw_type}</p>
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)' }}>{BOARD_TYPE_LABELS[device?.hw_family] || device?.hw_family}</p>
|
||||||
</div>
|
</div>
|
||||||
<div style={{ padding: 'var(--space-4)', display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
|
<div style={{ padding: 'var(--space-4)', display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
|
||||||
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: 'var(--space-1)' }}>HW Version</p>
|
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: 'var(--space-1)' }}>HW Version</p>
|
||||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)' }}>{formatHwVersion(device?.hw_version)}</p>
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)' }}>{formatHwVersion(device?.hw_revision)}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Reference in New Issue
Block a user