wyby sync: cleanup phase - delete wyby users whose codes expired >7 days ago
Verified live: eAccess.deleteUsersAndGroups cascades codes + group relations. Selection only touches wyby label pattern users with at least one code; personal/manual users are never matched.
This commit is contained in:
+70
-2
@@ -26,6 +26,7 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime, time, timedelta
|
||||
|
||||
@@ -34,6 +35,9 @@ from wyby_client import WybyClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# wyby user label: "<last name> <first name> <6-digit transaction>"
|
||||
LABEL_RE = re.compile(r"^.+\s\d{6}$")
|
||||
|
||||
|
||||
def setup_logging() -> None:
|
||||
"""INFO -> stdout, WARNING/ERROR -> stderr (journal priorities)."""
|
||||
@@ -61,14 +65,25 @@ def parse_object_map(raw: str) -> list[tuple[str, str]]:
|
||||
|
||||
|
||||
class Sync:
|
||||
def __init__(self, apply: bool, horizon_days: int, object_map, profile_id: str):
|
||||
def __init__(
|
||||
self,
|
||||
apply: bool,
|
||||
horizon_days: int,
|
||||
object_map,
|
||||
profile_id: str,
|
||||
cleanup_grace_days: int = 7,
|
||||
media_pool_id: str = "1",
|
||||
):
|
||||
self.apply = apply
|
||||
self.horizon_days = horizon_days
|
||||
self.object_map = object_map
|
||||
self.profile_id = profile_id
|
||||
self.cleanup_grace_days = cleanup_grace_days
|
||||
self.media_pool_id = media_pool_id
|
||||
self.planned: list[tuple[str, dict, str]] = [] # (ctx, collection, data)
|
||||
self.skipped: list[str] = []
|
||||
self.failed = 0
|
||||
self.cleanup_ids: list[str] = []
|
||||
|
||||
# --- glutz helpers -------------------------------------------------
|
||||
|
||||
@@ -196,6 +211,30 @@ class Sync:
|
||||
else:
|
||||
self.skipped.append(f"{ctx} - PIN {b.pin} already full-day valid")
|
||||
|
||||
# --- cleanup ---------------------------------------------------------
|
||||
|
||||
def plan_cleanup(self, today):
|
||||
"""Select wyby-pattern users whose codes are ALL expired since more
|
||||
than cleanup_grace_days and delete them (cascades codes+relations)."""
|
||||
cutoff = today - timedelta(days=self.cleanup_grace_days)
|
||||
codes_by_user: dict[str, list] = {}
|
||||
for c in self.codes:
|
||||
codes_by_user.setdefault(str(c.get("userId")), []).append(c)
|
||||
for u in self.users:
|
||||
if u.get("class") != 1 or not LABEL_RE.match(u.get("label") or ""):
|
||||
continue
|
||||
uid = str(u["id"])
|
||||
rows = codes_by_user.get(uid)
|
||||
if not rows:
|
||||
continue # no codes -> cannot judge age, keep
|
||||
latest = max((parse_ts(c.get("validTo")) for c in rows), default=None)
|
||||
if latest is not None and latest.date() < cutoff:
|
||||
self.cleanup_ids.append(uid)
|
||||
self.skipped.append(
|
||||
f"CLEANUP user {uid} ({u['label']}) - last code expired "
|
||||
f"{latest.date()}, older than {self.cleanup_grace_days} days"
|
||||
)
|
||||
|
||||
# --- execution -------------------------------------------------------
|
||||
|
||||
def run(self):
|
||||
@@ -220,6 +259,26 @@ class Sync:
|
||||
else:
|
||||
self.failed += 1
|
||||
logger.error("UNCLEAR %s %s: %r", collection, ctx, res)
|
||||
if self.cleanup_ids:
|
||||
try:
|
||||
res = g.rpc(
|
||||
"eAccess.deleteUsersAndGroups",
|
||||
[self.cleanup_ids, {"mediaPoolId": self.media_pool_id}],
|
||||
)
|
||||
deleted = set(res if isinstance(res, list) else [])
|
||||
missing = [i for i in self.cleanup_ids if i not in deleted]
|
||||
if missing:
|
||||
self.failed += 1
|
||||
logger.error("ERROR cleanup: not deleted: %r", missing)
|
||||
else:
|
||||
logger.info(
|
||||
"OK cleanup: %d user(s) deleted: %r",
|
||||
len(self.cleanup_ids),
|
||||
self.cleanup_ids,
|
||||
)
|
||||
except SystemExit as err:
|
||||
self.failed += 1
|
||||
logger.error("ERROR cleanup: %s", err)
|
||||
logger.info(
|
||||
"%d/%d executed.", len(self.planned) - self.failed, len(self.planned)
|
||||
)
|
||||
@@ -255,6 +314,7 @@ def main() -> None:
|
||||
"--profile-id", default=os.environ.get("WYBY_ACTION_PROFILE_ID", "2")
|
||||
)
|
||||
args = ap.parse_args()
|
||||
grace = int(os.environ.get("WYBY_CLEANUP_GRACE_DAYS", "7"))
|
||||
|
||||
object_map = parse_object_map(os.environ.get("WYBY_OBJECT_MAP", ""))
|
||||
if not object_map:
|
||||
@@ -275,7 +335,14 @@ def main() -> None:
|
||||
bookings = [b for b in bookings if b.pin == args.only_code]
|
||||
logger.info("wyby bookings in horizon: %d", len(bookings))
|
||||
|
||||
sync = Sync(args.apply, args.horizon_days, object_map, args.profile_id)
|
||||
sync = Sync(
|
||||
args.apply,
|
||||
args.horizon_days,
|
||||
object_map,
|
||||
args.profile_id,
|
||||
cleanup_grace_days=grace,
|
||||
media_pool_id=os.environ.get("WYBY_MEDIA_POOL_ID", "1"),
|
||||
)
|
||||
sync._load()
|
||||
groups = {u["label"]: u["id"] for u in sync.users if u.get("class") == 2}
|
||||
|
||||
@@ -298,6 +365,7 @@ def main() -> None:
|
||||
continue
|
||||
sync.plan_booking(b, group_id, today)
|
||||
|
||||
sync.plan_cleanup(today)
|
||||
sync.log_skips()
|
||||
if not sync.planned:
|
||||
logger.info("No changes needed (%d bookings checked).", len(bookings))
|
||||
|
||||
Reference in New Issue
Block a user