Files
bonaminandClaude Opus 5.5 2e3d7ba062 refactor(devices): store hardware identity as hw_family / hw_revision
The firmware moved its NVS identity keys from hw_type / hw_version to
hw_family / hw_revision (NvsMigration.cpp), and the NVS generator, cloudflash
and the device models already used the new names. Firestore device docs and
the manufacturing code still wrote and read hw_type / hw_version, so the
device API's hw_family / hw_revision were always "" (0 of 14 docs had them)
and the console used two names for one value.

Device docs now use the firmware's names (schema v1.1.0, decision D2 in the
bellsystems-schema repo). The apps don't read these fields, so no app change.

- Manufacturing batch-create writes hw_family / hw_revision; the inventory
  API exposes hw_family / hw_revision (filters: ?hw_family= / ?hw_families=).
  Reads fall back to hw_type / hw_version so docs not yet migrated still work.
- devices/firestore_v1.py renames hw_type / hw_version on read and write and
  rejects a hw_family that isn't a code (e.g. "Bell Plus"): when the console
  generates NVS from it, the firmware builds its OTA URL from that value.
- Inventory, provisioning, onboarding and overview pages use the new names.

Unchanged on purpose: the firmware catalog and flash assets
(/api/firmware/{hw_type}/..., hw_type_override) — a separate store and the
URL devices call; same values, only the variable name differs. The public
cloudflash response keeps its hw_type field (public contract).

Data migration (rename + fix 3 display-label values) runs from the
bellsystems-schema repo AFTER this is deployed: the currently deployed
console still reads hw_type.

Verified: 118 backend tests pass; frontend builds; ESLint errors in
ProvisioningWizard.jsx (7) are pre-existing and unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 21:02:20 +02:00

191 lines
7.4 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_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"