""" 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())