Files
bellsystems-cp/backend/scripts/sync_device_users_mirror.py
T
bonaminandClaude Opus 5.5 2a6f9697b8 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>
2026-11-07 10:37:21 +02:00

97 lines
3.8 KiB
Python

"""
Make every device's `device_users` sub-collection mirror its `user_list`.
`user_list` is the source of truth for device assignments. The Console keeps
`device_users` ({role, user_reference}) only as a write-only mirror in case the
phone app still reads it. Before 2026-11 the Console read `device_users` first
and never wrote it, so the two drifted. This script lists the drift and, with
--apply, fixes the mirror:
- users in user_list with no device_users doc -> doc added (role "admin")
- device_users docs for users NOT in user_list -> doc deleted
It never changes `user_list` or `device_serials`. Check the dry-run output
first: if a user only appears in device_users and should keep the device,
assign them in the Console (Manage tab) before running --apply, or they will be
dropped from the mirror. Running it twice is a no-op the second time.
Run from backend/ (locally or inside the backend container):
python scripts/sync_device_users_mirror.py # dry run
python scripts/sync_device_users_mirror.py --apply # write changes
"""
import argparse
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from shared.firebase import init_firebase, get_db # noqa: E402
from devices.service import ( # noqa: E402
DEFAULT_DEVICE_USER_ROLE, DEVICE_USERS_SUBCOLLECTION, device_users_by_user, user_list_entry_id,
)
BATCH_SIZE = 400 # Firestore batch limit is 500 writes
def _label(db, uid: str) -> str:
snap = db.collection("users").document(uid).get()
if not snap.exists:
return f"{uid} (no user doc)"
data = snap.to_dict() or {}
return f"{uid} ({data.get('display_name') or data.get('email') or '?'})"
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--apply", action="store_true", help="write changes (default: dry run)")
args = parser.parse_args()
init_firebase()
db = get_db()
if db is None:
print("[ERROR] Firebase not initialized — check FIREBASE_SERVICE_ACCOUNT_PATH")
return 1
print(f"=== sync device_users mirror — {'APPLY' if args.apply else 'DRY RUN'} ===")
writes = [] # (op, ref, data)
for dev in db.collection("devices").stream():
data = dev.to_dict() or {}
wanted = {user_list_entry_id(e) for e in data.get("user_list") or []} - {""}
mirror = device_users_by_user(dev.reference)
to_add = sorted(u for u in wanted - mirror.keys()
if db.collection("users").document(u).get().exists)
to_del = sorted(mirror.keys() - wanted)
if not to_add and not to_del:
continue
serial = data.get("serial_number") or data.get("device_id") or "?"
print(f"\n{dev.id} {serial} {data.get('device_name') or ''}")
for u in to_add:
print(f" + add mirror {_label(db, u)}")
writes.append(("set", dev.reference.collection(DEVICE_USERS_SUBCOLLECTION).document(), {
"role": DEFAULT_DEVICE_USER_ROLE,
"user_reference": db.collection("users").document(u),
}))
for u in to_del:
print(f" - remove mirror {_label(db, u)} <- only in device_users, not in user_list")
writes.extend(("delete", snap.reference, None) for snap in mirror[u])
print(f"\n{len(writes)} write(s) needed.")
if not args.apply or not writes:
if writes:
print("Dry run — nothing written. Re-run with --apply to write.")
return 0
for i in range(0, len(writes), BATCH_SIZE):
batch = db.batch()
for op, ref, payload in writes[i:i + BATCH_SIZE]:
batch.set(ref, payload) if op == "set" else batch.delete(ref)
batch.commit()
print("Done.")
return 0
if __name__ == "__main__":
sys.exit(main())