Bells, Clock and General tabs ran a silent "reconcile" on mount that read the device config and wrote any drift straight to Firestore, with no user action. Combined with oldest-first ack matching (backend health-check pongs and other tabs' replies resolved bells.get_config), this wrote 16-item bellOutputs on load and emptied them on tab switch. - Remove the auto-write reconciles from Bells/Clock/General tabs - useDeviceCommand: match acks to commands by payload.type (ping->pong, playback.* -> playback), ignore health-check pongs, drop late replies, register pending entries before the POST - update_device: write nested maps as dotted field paths so only the sent leaves are touched, never the whole parent map - Clock modals: stop re-sending the whole clockSettings copy Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
330 lines
12 KiB
Python
330 lines
12 KiB
Python
import secrets
|
|
import string
|
|
|
|
from google.cloud.firestore_v1 import DocumentReference
|
|
from google.cloud.firestore_v1.field_path import FieldPath
|
|
|
|
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"
|
|
|
|
# Serial number format: BS-XXXX-XXXX (uppercase alphanumeric)
|
|
SN_CHARS = string.ascii_uppercase + string.digits
|
|
SN_SEGMENT_LEN = 4
|
|
|
|
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))
|
|
seg2 = "".join(secrets.choice(SN_CHARS) for _ in range(SN_SEGMENT_LEN))
|
|
return f"BS-{seg1}-{seg2}"
|
|
|
|
|
|
def _ensure_unique_serial(db) -> str:
|
|
"""Generate a serial number and verify it doesn't already exist in Firestore."""
|
|
existing_sns = set()
|
|
for doc in db.collection(COLLECTION).select(["serial_number"]).stream():
|
|
data = doc.to_dict()
|
|
sn = data.get("serial_number") or data.get("device_id")
|
|
if sn:
|
|
existing_sns.add(sn)
|
|
|
|
for _ in range(100): # safety limit
|
|
sn = _generate_serial_number()
|
|
if sn not in existing_sns:
|
|
return sn
|
|
|
|
raise RuntimeError("Could not generate a unique serial number after 100 attempts")
|
|
|
|
|
|
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."""
|
|
current_status = data.get("mfg_status", "")
|
|
if current_status in ("claimed", "decommissioned"):
|
|
return data
|
|
user_list = data.get("user_list", []) or []
|
|
if user_list:
|
|
doc_ref.update({"mfg_status": "claimed"})
|
|
data = dict(data)
|
|
data["mfg_status"] = "claimed"
|
|
return data
|
|
|
|
|
|
def _doc_to_device(doc) -> DeviceInDB:
|
|
"""Convert a Firestore document snapshot to a DeviceInDB model.
|
|
|
|
Also auto-upgrades mfg_status to 'claimed' if user_list is non-empty.
|
|
"""
|
|
raw = doc.to_dict()
|
|
raw = _auto_upgrade_claimed(doc.reference, raw)
|
|
data = firestore_v1.to_api(raw)
|
|
return DeviceInDB(id=doc.id, **data)
|
|
|
|
|
|
FLEET_STATUSES = {"sold", "claimed"}
|
|
|
|
|
|
def list_devices(
|
|
search: str | None = None,
|
|
online_only: bool | None = None,
|
|
subscription_tier: str | None = None,
|
|
) -> list[DeviceInDB]:
|
|
"""List fleet devices (sold + claimed only) with optional filters."""
|
|
db = get_db()
|
|
ref = db.collection(COLLECTION)
|
|
query = ref
|
|
|
|
if subscription_tier:
|
|
query = query.where("device_subscription.subscrTier", "==", subscription_tier)
|
|
|
|
docs = query.stream()
|
|
results = []
|
|
|
|
for doc in docs:
|
|
raw = doc.to_dict() or {}
|
|
|
|
# Only include sold/claimed devices in the fleet view.
|
|
# Legacy devices without mfg_status are included to avoid breaking old data.
|
|
mfg_status = raw.get("mfg_status")
|
|
if mfg_status and mfg_status not in FLEET_STATUSES:
|
|
continue
|
|
|
|
device = _doc_to_device(doc)
|
|
|
|
# Client-side filters
|
|
if online_only is not None and device.is_Online != online_only:
|
|
continue
|
|
|
|
if search:
|
|
search_lower = search.lower()
|
|
name_match = search_lower in (device.device_name or "").lower()
|
|
console_name_match = search_lower in (device.console_name or "").lower()
|
|
location_match = search_lower in (device.device_location or "").lower()
|
|
sn_match = search_lower in (device.serial_number or "").lower()
|
|
if not (name_match or console_name_match or location_match or sn_match):
|
|
continue
|
|
|
|
results.append(device)
|
|
|
|
return results
|
|
|
|
|
|
def get_device(device_doc_id: str) -> DeviceInDB:
|
|
"""Get a single device by Firestore document ID."""
|
|
db = get_db()
|
|
doc = db.collection(COLLECTION).document(device_doc_id).get()
|
|
if not doc.exists:
|
|
raise NotFoundError("Device")
|
|
return _doc_to_device(doc)
|
|
|
|
|
|
def create_device(data: DeviceCreate) -> DeviceInDB:
|
|
"""Create a new device document in Firestore with auto-generated serial number."""
|
|
db = get_db()
|
|
|
|
# Generate unique serial number
|
|
serial_number = _ensure_unique_serial(db)
|
|
|
|
doc_data = data.model_dump()
|
|
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 _doc_to_device(doc_ref.get())
|
|
|
|
|
|
def _leaf_field_paths(value: dict, prefix: tuple = ()) -> dict:
|
|
"""Flatten a nested map into {firestore field path: leaf value}.
|
|
|
|
Lists and scalars are leaves; a non-empty map is descended into, so writing
|
|
{"device_attributes": {"hasBells": True}} touches ONLY
|
|
device_attributes.hasBells — never the sibling fields of the parent map.
|
|
An empty map is kept as a leaf (it explicitly sets that map to {}).
|
|
"""
|
|
out: dict = {}
|
|
for k, v in value.items():
|
|
path = prefix + (k,)
|
|
if isinstance(v, dict) and v:
|
|
out.update(_leaf_field_paths(v, path))
|
|
else:
|
|
out[FieldPath(*path).to_api_repr()] = v
|
|
return out
|
|
|
|
|
|
def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
|
|
"""Update an existing device document. Only provided fields are updated."""
|
|
db = get_db()
|
|
doc_ref = db.collection(COLLECTION).document(device_doc_id)
|
|
doc = doc_ref.get()
|
|
if not doc.exists:
|
|
raise NotFoundError("Device")
|
|
|
|
# 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)
|
|
|
|
# Nested structs are written field-by-field (dotted paths), so only the
|
|
# exact leaves the caller sent are touched. Rewriting the whole parent map
|
|
# (the old read-merge-write) clobbered sibling fields whenever two writes
|
|
# raced, or the FlutterFlow apps wrote in between our read and our write.
|
|
existing = doc.to_dict()
|
|
nested_keys = (
|
|
"device_attributes", "device_subscription", "device_stats", "device_health_settings",
|
|
)
|
|
for key in nested_keys:
|
|
if isinstance(update_data.get(key), dict) and update_data[key]:
|
|
update_data.update(_leaf_field_paths(update_data.pop(key), (key,)))
|
|
|
|
if "user_list" not in update_data:
|
|
doc_ref.update(update_data)
|
|
else:
|
|
# A user_list change must also update each affected user's
|
|
# device_serials (MQTT ACL) and the device_users mirror, in the
|
|
# same atomic batch.
|
|
from users import service as users_service
|
|
|
|
new_ids = []
|
|
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)
|
|
mirror = device_users_by_user(doc_ref)
|
|
|
|
batch = db.batch()
|
|
batch.update(doc_ref, update_data)
|
|
touched = []
|
|
for user_id in (old_ids ^ set(new_ids)):
|
|
linked = user_id in new_ids
|
|
user_ref = db.collection("users").document(user_id)
|
|
user_doc = user_ref.get()
|
|
if not user_doc.exists:
|
|
if not linked:
|
|
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())
|
|
batch.commit()
|
|
for user_data in touched:
|
|
users_service.invalidate_mqtt_acl_cache(user_data)
|
|
|
|
updated_doc = doc_ref.get()
|
|
return _doc_to_device(updated_doc)
|
|
|
|
|
|
def user_list_entry_id(entry) -> str:
|
|
"""user_list entries are DocumentReferences, "users/{id}" paths or raw doc IDs."""
|
|
if isinstance(entry, DocumentReference):
|
|
return entry.id
|
|
if isinstance(entry, str):
|
|
return entry.strip().split("/")[-1]
|
|
return ""
|
|
|
|
|
|
# ─── device_users sub-collection mirror ──────────────────────────────────────
|
|
# 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.
|
|
|
|
DEVICE_USERS_SUBCOLLECTION = "device_users"
|
|
# 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()
|
|
doc_ref = db.collection(COLLECTION).document(device_doc_id)
|
|
doc = doc_ref.get()
|
|
if not doc.exists:
|
|
raise NotFoundError("Device")
|
|
|
|
roles = {
|
|
uid: (snaps[0].to_dict() or {}).get("role", "")
|
|
for uid, snaps in device_users_by_user(doc_ref).items()
|
|
}
|
|
|
|
users = []
|
|
seen = set()
|
|
for entry in (doc.to_dict() or {}).get("user_list") or []:
|
|
uid = user_list_entry_id(entry)
|
|
if not uid or uid in seen:
|
|
continue
|
|
seen.add(uid)
|
|
try:
|
|
user_doc = db.collection("users").document(uid).get()
|
|
except Exception as e:
|
|
print(f"[devices] Error resolving user_list entry {uid}: {e}")
|
|
continue
|
|
if not user_doc.exists:
|
|
continue
|
|
user_data = user_doc.to_dict() or {}
|
|
users.append({
|
|
"user_id": user_doc.id,
|
|
"display_name": user_data.get("display_name", ""),
|
|
"email": user_data.get("email", ""),
|
|
"role": roles.get(uid, ""),
|
|
"photo_url": user_data.get("photo_url", ""),
|
|
})
|
|
|
|
return users
|
|
|
|
|
|
def delete_device(device_doc_id: str) -> None:
|
|
"""Delete a device document from Firestore."""
|
|
db = get_db()
|
|
doc_ref = db.collection(COLLECTION).document(device_doc_id)
|
|
doc = doc_ref.get()
|
|
if not doc.exists:
|
|
raise NotFoundError("Device")
|
|
|
|
doc_ref.delete()
|