fix(devices): read device users from user_list, mirror writes to device_users

The Manage tab and Onboarding page list users via GET /devices/{id}/users,
which read the device_users sub-collection first and only fell back to
user_list when it was empty. Every write (add/remove on those pages, the
Users page, PUT with user_list) went to user_list only, so on any device
that had a device_users doc the list showed stale data: users added in the
Console never appeared and removed users never went away. A production
survey found 6 device_users docs (all role "admin") on 6 devices; 2 of them
disagree with user_list.

user_list is now the single source of truth:
- get_device_users reads only user_list; role comes from the mirror if any.
- Every user_list write also adds/removes the device_users mirror doc
  ({role: "admin", user_reference}) in the same atomic batch, in case the
  phone app still reads the sub-collection. It is meant to go away later.
- users.service.assign_device and PUT /devices/{id} now store
  DocumentReferences (the app's format) instead of "users/{id}" strings.

scripts/sync_device_users_mirror.py (dry run by default) reports and fixes
pre-existing drift between the two. Not run yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-07 10:37:21 +02:00
co-authored by Claude Opus 5.5
parent fba5110cc0
commit 2a6f9697b8
7 changed files with 330 additions and 142 deletions
+92 -87
View File
@@ -235,22 +235,35 @@ def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
doc_ref.update(update_data)
else:
# 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
old_ids = {_user_list_entry_id(e) for e in (existing.get("user_list") or [])} - {""}
new_ids = {_user_list_entry_id(e) for e in update_data["user_list"]} - {""}
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 ^ 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_doc = user_ref.get()
if not user_doc.exists:
continue # dangling reference — nothing to sync
users_service.stage_device_serial_link(batch, user_ref, serial, linked=user_id in new_ids)
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:
@@ -260,7 +273,7 @@ def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
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."""
if isinstance(entry, DocumentReference):
return entry.id
@@ -269,11 +282,53 @@ def _user_list_entry_id(entry) -> str:
return ""
def get_device_users(device_doc_id: str) -> list[dict]:
"""Get users assigned to a device from the device_users sub-collection.
# ─── 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.
Falls back to the user_list field on the device document if the
sub-collection is empty.
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)
@@ -281,83 +336,33 @@ def get_device_users(device_doc_id: str) -> list[dict]:
if not doc.exists:
raise NotFoundError("Device")
# Try sub-collection first
sub_docs = list(doc_ref.collection("device_users").stream())
roles = {
uid: (snaps[0].to_dict() or {}).get("role", "")
for uid, snaps in device_users_by_user(doc_ref).items()
}
users = []
if sub_docs:
for sub_doc in sub_docs:
sub_data = sub_doc.to_dict()
role = sub_data.get("role", "")
user_ref = sub_data.get("user_reference")
# Resolve user reference
user_id = ""
display_name = ""
email = ""
photo_url = ""
if isinstance(user_ref, DocumentReference):
try:
user_doc = user_ref.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:
print(f"[devices] Error resolving user reference: {e}")
continue
elif isinstance(user_ref, str):
# 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
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({
"user_id": user_doc.id,
"display_name": user_data.get("display_name", ""),
"email": user_data.get("email", ""),
"role": "",
"photo_url": user_data.get("photo_url", ""),
})
except Exception as e:
print(f"[devices] Error resolving user_list entry: {e}")
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