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>
179 lines
6.9 KiB
Python
179 lines
6.9 KiB
Python
"""
|
|
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"
|