fix(devices): write devices in Firestore schema v1 so the apps can read them

The FlutterFlow tablet and phone apps parse each device doc inside safeGet:
one wrongly typed field makes them silently drop the whole device from the
user's list. The console was the source of every such field found in
production on 2026-11-08:

- New devices: DeviceCreate defaulted times to "" and IPs to [], and
  create_device wrote them as-is. Every console-created device was invisible
  in the apps from birth. It also set device_id but not serial_number.
- Round trip: reads formatted Timestamps as "15 January 2026 at 22:01:00
  UTC+0000", the frontend echoed that back on save, and _restore_timestamps
  could not parse it (nor ""), so it stored the string. towerClockTime was
  not in its list at all.
- Key spelling: the console wrote bellGuardSafetyOn / useStaticIP; the apps
  read bellguardSafetyOn / usesStaticIP, so console edits never reached them
  and docs ended up with both spellings disagreeing.
- MelodyMainItem used the melodies-collection shape (information, url, ...)
  instead of the device shape the apps read (mainInformation, binaryUrl, ...);
  Pydantic dropped every real key on read.
- Manufacturing batches created devices with serial_number but no device_id,
  which both apps use to connect over MQTT (7 of 14 devices affected).

The contract now lives in the bellsystems-schema repo (v1 = what the shipped
apps read). backend/devices/firestore_v1.py enforces it on every device
write (to_firestore) and read (to_api):
- Timestamps: ISO 8601 in the API, Firestore Timestamps in the DB, null for
  unset. The old display format is still accepted on write so an open
  browser tab can't corrupt data; anything unparseable is a 422.
- IPs: dotted strings; octet arrays are joined; invalid values are a 422.
- Legacy keys are renamed (v1 key wins over a duplicate); users_list dropped.
- device_id mirrors serial_number (decision D1); conflicting values are a 422.
- user_list / melodyReference entries become DocumentReferences.
- update_device re-normalizes the merged nested maps, so saving a device
  also repairs pre-v1 junk already stored in it.

Models and the frontend now use v1 names and send null (not "") for unset
times. The firmware's network.set_config MQTT payload keeps its own names.

Verified: 114 backend tests pass (new tests/test_firestore_v1.py covers the
production failure shapes; test_timezones.py not run locally, needs tzdata).
A read-only dry run of a console save against all 14 production devices
produced v1-valid docs with no fields lost. Frontend builds. Not deployed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-08 20:00:33 +02:00
co-authored by Claude Opus 5.5
parent 2a6f9697b8
commit 62be80c9d8
12 changed files with 511 additions and 122 deletions
+18
View File
@@ -375,6 +375,24 @@ 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.
- Check live data with `node tools/audit.js <service-account.json>` in the schema repo.
---
## API Client
```js
+232
View File
@@ -0,0 +1,232 @@
"""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]] = {
"": {"users_list": None},
"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"
_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
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
+40 -24
View File
@@ -1,7 +1,12 @@
from pydantic import BaseModel, Field
from pydantic import BaseModel, ConfigDict, Field
from typing import Any, Dict, List, Optional
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 ---
@@ -30,12 +35,14 @@ class DeviceTiers(str, Enum):
class DeviceNetworkSettings(BaseModel):
hostname: str = ""
useStaticIP: bool = False
ipAddress: Any = []
gateway: Any = []
subnet: Any = []
dns1: Any = []
dns2: Any = []
usesStaticIP: bool = False
# Dotted strings ("10.0.0.5"); "" = not set. The firmware's network.set_config
# MQTT command uses its own names (useStaticIP / ip) — convert at that boundary.
ipAddress: str = ""
gateway: str = ""
subnet: str = ""
dns1: str = ""
dns2: str = ""
class DeviceClockSettings(BaseModel):
@@ -49,12 +56,13 @@ class DeviceClockSettings(BaseModel):
quarterAlertsBell: int = 0
isDaySilenceOn: bool = False
isNightSilenceOn: bool = False
daySilenceFrom: str = ""
daySilenceTo: str = ""
nightSilenceFrom: str = ""
nightSilenceTo: str = ""
backlightTurnOnTime: str = ""
backlightTurnOffTime: str = ""
# Time of day carried in a Timestamp (v1 quirk); only the UTC time part matters.
daySilenceFrom: Optional[str] = None
daySilenceTo: Optional[str] = None
nightSilenceFrom: Optional[str] = None
nightSilenceTo: Optional[str] = None
backlightTurnOnTime: Optional[str] = None
backlightTurnOffTime: Optional[str] = None
isBacklightAutomationOn: bool = False
backlightOutput: int = 0
# 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] = []
hammerTimings: List[int] = []
bellGuardOn: bool = False
bellGuardSafetyOn: bool = False
bellguardSafetyOn: bool = False # lower-case g: the exact key the apps read
warningsOn: bool = False
towerClockTime: str = ""
towerClockTime: Optional[str] = None
clockSettings: DeviceClockSettings = DeviceClockSettings()
deviceLocale: HelperMelodyTypes = HelperMelodyTypes.all
networkSettings: DeviceNetworkSettings = DeviceNetworkSettings()
@@ -83,7 +91,7 @@ class DeviceAttributes(BaseModel):
class DeviceSubInformation(BaseModel):
subscrTier: DeviceTiers = DeviceTiers.basic
subscrStart: str = ""
subscrStart: Optional[str] = None
subscrDuration: int = 0
maxUsers: int = 0
maxOutputs: int = 0
@@ -95,10 +103,10 @@ class DeviceStatistics(BaseModel):
perBellStrikes: List[int] = []
totalWarningsGiven: int = 0
warrantyActive: bool = False
warrantyStart: str = ""
warrantyStart: Optional[str] = None
warrantyPeriod: int = 0
maintainedOn: str = ""
maintainancePeriod: int = 0
maintainedOn: Optional[str] = None
maintainancePeriod: int = 0 # misspelled in v1 on purpose: the apps read this key
class HealthThresholdTier(BaseModel):
@@ -131,13 +139,21 @@ class DeviceHealthSettings(BaseModel):
class MelodyMainItem(BaseModel):
"""Mirrors the Melody schema used in the melodies collection."""
information: dict = {}
default_settings: dict = {}
type: str = ""
url: str = ""
"""One melody as stored inside devices.device_melodies_all (v1 MelodyMainItem).
NOT the melodies/{id} document shape: the apps read camelCase keys here
(mainInformation / defaultSettings / settings / binaryUrl / melodyReference).
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 = ""
pid: str = ""
mainInformation: Dict[str, Any] = {}
defaultSettings: Dict[str, Any] = {}
settings: Dict[str, Any] = {}
binaryUrl: str = ""
# --- Request / Response schemas ---
+17 -74
View File
@@ -1,11 +1,11 @@
import secrets
import string
from datetime import datetime
from google.cloud.firestore_v1 import GeoPoint, DocumentReference
from google.cloud.firestore_v1 import DocumentReference
from shared.firebase import get_db
from shared.exceptions import NotFoundError
from devices import firestore_v1
from devices.models import DeviceCreate, DeviceUpdate, DeviceInDB
COLLECTION = "devices"
@@ -14,35 +14,6 @@ COLLECTION = "devices"
SN_CHARS = string.ascii_uppercase + string.digits
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:
"""Generate a unique serial number in the format BS-XXXX-XXXX."""
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")
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:
"""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."""
@@ -118,7 +59,7 @@ def _doc_to_device(doc) -> DeviceInDB:
"""
raw = doc.to_dict()
raw = _auto_upgrade_claimed(doc.reference, raw)
data = _sanitize_dict(raw)
data = firestore_v1.to_api(raw)
return DeviceInDB(id=doc.id, **data)
@@ -187,11 +128,13 @@ def create_device(data: DeviceCreate) -> DeviceInDB:
serial_number = _ensure_unique_serial(db)
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)
return DeviceInDB(id=doc_ref.id, **doc_data)
return _doc_to_device(doc_ref.get())
def _deep_merge(base: dict, overrides: dict) -> dict:
@@ -213,23 +156,23 @@ def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
if not doc.exists:
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
coords = update_data.get("device_location_coordinates")
if isinstance(coords, dict) and "lat" in coords and "lng" in coords:
update_data["device_location_coordinates"] = GeoPoint(coords["lat"], coords["lng"])
# Deep-merge nested structs so unmentioned sub-fields are preserved
# Deep-merge nested structs so unmentioned sub-fields are preserved, then
# normalize the merged map again: that also repairs pre-v1 junk already
# stored in the device (""-timestamps, octet-array IPs, misspelled keys).
existing = doc.to_dict()
nested_keys = (
"device_attributes", "device_subscription", "device_stats", "device_health_settings",
)
for key in nested_keys:
if key in update_data and isinstance(existing.get(key), dict):
update_data[key] = _deep_merge(existing[key], update_data[key])
update_data = _restore_timestamps(update_data)
merged = _deep_merge(existing[key], update_data[key])
update_data[key] = firestore_v1.to_firestore({key: merged}, db)[key]
if "user_list" not in update_data:
doc_ref.update(update_data)
+2
View File
@@ -134,6 +134,8 @@ def create_batch(data: BatchCreate) -> BatchResponse:
db.collection(COLLECTION).add({
"serial_number": sn,
"device_id": sn, # schema v1 / D1: both apps connect over MQTT with device_id
"hw_type": data.board_type.value,
"hw_version": data.board_version,
"mfg_status": "manufactured",
+178
View File
@@ -0,0 +1,178 @@
"""
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_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"
@@ -20,7 +20,7 @@ function extractTime(tsStr) {
}
function timeToIso(hhmm) {
if (!hhmm) return ''
if (!hhmm) return null
return `2000-01-01T${hhmm}:00Z`
}
@@ -183,11 +183,11 @@ export default function EditAlertsModal({ open, onClose, onSaved, clock, attr, i
halfhourAlertsBell: Number(halfBell),
quarterAlertsBell: Number(quarterBell),
isDaySilenceOn: isDayOn,
daySilenceFrom: isDayOn && daySilenceFrom ? timeToIso(daySilenceFrom) : (clock?.daySilenceFrom || ''),
daySilenceTo: isDayOn && daySilenceTo ? timeToIso(daySilenceTo) : (clock?.daySilenceTo || ''),
daySilenceFrom: isDayOn && daySilenceFrom ? timeToIso(daySilenceFrom) : (clock?.daySilenceFrom ?? null),
daySilenceTo: isDayOn && daySilenceTo ? timeToIso(daySilenceTo) : (clock?.daySilenceTo ?? null),
isNightSilenceOn: isNightOn,
nightSilenceFrom: isNightOn && nightFrom ? timeToIso(nightFrom) : (clock?.nightSilenceFrom || ''),
nightSilenceTo: isNightOn && nightTo ? timeToIso(nightTo) : (clock?.nightSilenceTo || ''),
nightSilenceFrom: isNightOn && nightFrom ? timeToIso(nightFrom) : (clock?.nightSilenceFrom ?? null),
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 }) {
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 [saving, setSaving] = useState(false)
const [error, setError] = useState('')
@@ -23,7 +23,7 @@ export default function EditAttributesModal({ open, onClose, onSaved, attr, id }
device_attributes: {
bellGuardOn: toBool(bellGuardOn),
warningsOn: toBool(warningsOn),
bellGuardSafetyOn: toBool(bellGuardSafetyOn),
bellguardSafetyOn: toBool(bellGuardSafetyOn),
},
})
await onSaved()
@@ -17,7 +17,7 @@ function extractTime(tsStr) {
}
function timeToIso(hhmm) {
if (!hhmm) return ''
if (!hhmm) return null
return `2000-01-01T${hhmm}:00Z`
}
@@ -62,8 +62,8 @@ export default function EditBacklightModal({ open, onClose, onSaved, attr, clock
...clock,
isBacklightAutomationOn: enabled,
backlightOutput: Number(output),
backlightTurnOnTime: enabled && onTime ? timeToIso(onTime) : '',
backlightTurnOffTime: enabled && offTime ? timeToIso(offTime) : '',
backlightTurnOnTime: enabled && onTime ? timeToIso(onTime) : null,
backlightTurnOffTime: enabled && offTime ? timeToIso(offTime) : null,
},
},
})
@@ -91,7 +91,7 @@ function deepMerge(base, overrides) {
}
function timeToIso(hhmm) {
if (!hhmm) return ''
if (!hhmm) return null
return `2000-01-01T${hhmm}:00Z`
}
function extractTime(tsStr) {
@@ -1353,11 +1353,11 @@ function ConfigureStep({ device, onDeviceUpdated, onNext, onBack }) {
halfhourAlertsBell: Number(alert.halfBell),
quarterAlertsBell: Number(alert.quarterBell),
isDaySilenceOn: alert.isDayOn,
daySilenceFrom: alert.isDayOn && alert.dayFrom ? timeToIso(alert.dayFrom) : (clock.daySilenceFrom || ''),
daySilenceTo: alert.isDayOn && alert.dayTo ? timeToIso(alert.dayTo) : (clock.daySilenceTo || ''),
daySilenceFrom: alert.isDayOn && alert.dayFrom ? timeToIso(alert.dayFrom) : (clock.daySilenceFrom ?? null),
daySilenceTo: alert.isDayOn && alert.dayTo ? timeToIso(alert.dayTo) : (clock.daySilenceTo ?? null),
isNightSilenceOn: alert.isNightOn,
nightSilenceFrom: alert.isNightOn && alert.nightFrom ? timeToIso(alert.nightFrom) : (clock.nightSilenceFrom || ''),
nightSilenceTo: alert.isNightOn && alert.nightTo ? timeToIso(alert.nightTo) : (clock.nightSilenceTo || ''),
nightSilenceFrom: alert.isNightOn && alert.nightFrom ? timeToIso(alert.nightFrom) : (clock.nightSilenceFrom ?? null),
nightSilenceTo: alert.isNightOn && alert.nightTo ? timeToIso(alert.nightTo) : (clock.nightSilenceTo ?? null),
},
},
},
@@ -1377,8 +1377,8 @@ function ConfigureStep({ device, onDeviceUpdated, onNext, onBack }) {
clockSettings: {
isBacklightAutomationOn: backlight.enabled,
backlightOutput: Number(backlight.output),
backlightTurnOnTime: backlight.enabled && backlight.onTime ? timeToIso(backlight.onTime) : '',
backlightTurnOffTime: backlight.enabled && backlight.offTime ? timeToIso(backlight.offTime) : '',
backlightTurnOnTime: backlight.enabled && backlight.onTime ? timeToIso(backlight.onTime) : null,
backlightTurnOffTime: backlight.enabled && backlight.offTime ? timeToIso(backlight.offTime) : null,
},
},
},
@@ -388,15 +388,15 @@ export default function ClockTab({
halfhourAlertsBell: trueHalfBell,
quarterAlertsBell: trueQuarterBell,
isDaySilenceOn: !!data.daytime_silence,
daySilenceFrom: data.daytime_on ? `2000-01-01T${data.daytime_on}:00Z` : (clock?.daySilenceFrom || ''),
daySilenceTo: data.daytime_off ? `2000-01-01T${data.daytime_off}:00Z` : (clock?.daySilenceTo || ''),
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 ?? null),
isNightSilenceOn: !!data.night_silence,
nightSilenceFrom: data.night_on ? `2000-01-01T${data.night_on}:00Z` : (clock?.nightSilenceFrom || ''),
nightSilenceTo: data.night_off ? `2000-01-01T${data.night_off}:00Z` : (clock?.nightSilenceTo || ''),
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 ?? null),
isBacklightAutomationOn: !!data.backlight,
backlightOutput: trueBacklightOutput,
backlightTurnOnTime: data.backlight_on ? `2000-01-01T${data.backlight_on}:00Z` : '',
backlightTurnOffTime: data.backlight_off ? `2000-01-01T${data.backlight_off}:00Z` : '',
backlightTurnOnTime: data.backlight_on ? `2000-01-01T${data.backlight_on}:00Z` : null,
backlightTurnOffTime: data.backlight_off ? `2000-01-01T${data.backlight_off}:00Z` : null,
faceSyncMode: data.face_sync_mode ?? clock?.faceSyncMode ?? 'force',
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' }}>
<SafetyRow label="Bell Guard" description="Automated striking lock" enabled={attr?.bellGuardOn} />
<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>
</GlassCard>
</div>