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:
@@ -20,3 +20,7 @@ WYBY_STATUS_IDS=a198f429-6e7d-4a46-b94f-08164c47e1a0
|
|||||||
WYBY_ACTION_PROFILE_ID=2
|
WYBY_ACTION_PROFILE_ID=2
|
||||||
# Wie weit in die Zukunft Buchungen geholt werden (Tage)
|
# Wie weit in die Zukunft Buchungen geholt werden (Tage)
|
||||||
WYBY_HORIZON_DAYS=90
|
WYBY_HORIZON_DAYS=90
|
||||||
|
# Cleanup: wyby-Benutzer loeschen, deren Codes seit mehr als X Tagen abgelaufen
|
||||||
|
# sind (0 = aus). Kaskadiert Codes + Gruppenzuordnungen.
|
||||||
|
WYBY_CLEANUP_GRACE_DAYS=7
|
||||||
|
WYBY_MEDIA_POOL_ID=1
|
||||||
|
|||||||
+75
-1
@@ -1,6 +1,6 @@
|
|||||||
"""Tests for wyby_sync: planning logic with mocked Glutz API + WybyClient."""
|
"""Tests for wyby_sync: planning logic with mocked Glutz API + WybyClient."""
|
||||||
|
|
||||||
from datetime import date
|
from datetime import date, timedelta
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from conftest import USERS, code_row
|
from conftest import USERS, code_row
|
||||||
@@ -181,3 +181,77 @@ class TestLogRouting:
|
|||||||
captured = capsys.readouterr()
|
captured = capsys.readouterr()
|
||||||
assert "resolve manually" in captured.err
|
assert "resolve manually" in captured.err
|
||||||
assert "resolve manually" not in captured.out
|
assert "resolve manually" not in captured.out
|
||||||
|
|
||||||
|
|
||||||
|
class TestCleanup:
|
||||||
|
def test_old_wyby_user_selected(self, sync):
|
||||||
|
old = date(2026, 11, 4) # >7 days before "today" (2026-11-12)
|
||||||
|
sync.users = sync.users + [{"id": 70, "label": "Alt Kunde 111111", "class": 1}]
|
||||||
|
sync.codes = [
|
||||||
|
code_row(
|
||||||
|
id=80,
|
||||||
|
userId=70,
|
||||||
|
code="111111",
|
||||||
|
validFrom=f"{old}T00:00:00.000",
|
||||||
|
validTo=f"{old + timedelta(days=1)}T23:59:59.000",
|
||||||
|
)
|
||||||
|
]
|
||||||
|
sync.plan_cleanup(date.today())
|
||||||
|
assert sync.cleanup_ids == ["70"]
|
||||||
|
assert any("CLEANUP" in s for s in sync.skipped)
|
||||||
|
|
||||||
|
def test_future_and_recent_users_kept(self, sync):
|
||||||
|
today = date.today()
|
||||||
|
sync.users = sync.users + [
|
||||||
|
{"id": 71, "label": "Aktiv Kunde 222222", "class": 1},
|
||||||
|
{"id": 72, "label": "Frisch Kunde 333333", "class": 1},
|
||||||
|
{"id": 73, "label": "Manuell ohne Ziffern", "class": 1},
|
||||||
|
{"id": 74, "label": "Kein Code 444444", "class": 1},
|
||||||
|
]
|
||||||
|
sync.codes = [
|
||||||
|
code_row(
|
||||||
|
id=81,
|
||||||
|
userId=71,
|
||||||
|
code="222222",
|
||||||
|
validFrom=f"{today}T00:00:00.000",
|
||||||
|
validTo=f"{today}T23:59:59.000",
|
||||||
|
),
|
||||||
|
code_row(
|
||||||
|
id=82,
|
||||||
|
userId=72,
|
||||||
|
code="333333",
|
||||||
|
validFrom=f"{today - timedelta(days=3)}T00:00:00.000",
|
||||||
|
validTo=f"{today - timedelta(days=2)}T23:59:59.000",
|
||||||
|
),
|
||||||
|
code_row(
|
||||||
|
id=83,
|
||||||
|
userId=73,
|
||||||
|
code="555555",
|
||||||
|
validFrom="2020-01-01T00:00:00.000",
|
||||||
|
validTo="2020-01-02T00:00:00.000",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
sync.plan_cleanup(today)
|
||||||
|
assert sync.cleanup_ids == []
|
||||||
|
|
||||||
|
def test_run_deletes_with_media_pool(self, sync, monkeypatch):
|
||||||
|
import glutz_api
|
||||||
|
|
||||||
|
calls = []
|
||||||
|
monkeypatch.setattr(
|
||||||
|
glutz_api, "rpc", lambda m, p: calls.append((m, p)) or ["70"]
|
||||||
|
)
|
||||||
|
sync.users = sync.users + [{"id": 70, "label": "Alt Kunde 111111", "class": 1}]
|
||||||
|
sync.codes = [
|
||||||
|
code_row(
|
||||||
|
id=80,
|
||||||
|
userId=70,
|
||||||
|
code="111111",
|
||||||
|
validFrom="2026-01-01T00:00:00.000",
|
||||||
|
validTo="2026-01-02T00:00:00.000",
|
||||||
|
)
|
||||||
|
]
|
||||||
|
sync.plan_cleanup(date.today())
|
||||||
|
sync.planned = []
|
||||||
|
assert sync.run() is True
|
||||||
|
assert ("eAccess.deleteUsersAndGroups", [["70"], {"mediaPoolId": "1"}]) in calls
|
||||||
|
|||||||
+70
-2
@@ -26,6 +26,7 @@ from __future__ import annotations
|
|||||||
import argparse
|
import argparse
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
import sys
|
import sys
|
||||||
from datetime import datetime, time, timedelta
|
from datetime import datetime, time, timedelta
|
||||||
|
|
||||||
@@ -34,6 +35,9 @@ from wyby_client import WybyClient
|
|||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
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:
|
def setup_logging() -> None:
|
||||||
"""INFO -> stdout, WARNING/ERROR -> stderr (journal priorities)."""
|
"""INFO -> stdout, WARNING/ERROR -> stderr (journal priorities)."""
|
||||||
@@ -61,14 +65,25 @@ def parse_object_map(raw: str) -> list[tuple[str, str]]:
|
|||||||
|
|
||||||
|
|
||||||
class Sync:
|
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.apply = apply
|
||||||
self.horizon_days = horizon_days
|
self.horizon_days = horizon_days
|
||||||
self.object_map = object_map
|
self.object_map = object_map
|
||||||
self.profile_id = profile_id
|
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.planned: list[tuple[str, dict, str]] = [] # (ctx, collection, data)
|
||||||
self.skipped: list[str] = []
|
self.skipped: list[str] = []
|
||||||
self.failed = 0
|
self.failed = 0
|
||||||
|
self.cleanup_ids: list[str] = []
|
||||||
|
|
||||||
# --- glutz helpers -------------------------------------------------
|
# --- glutz helpers -------------------------------------------------
|
||||||
|
|
||||||
@@ -196,6 +211,30 @@ class Sync:
|
|||||||
else:
|
else:
|
||||||
self.skipped.append(f"{ctx} - PIN {b.pin} already full-day valid")
|
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 -------------------------------------------------------
|
# --- execution -------------------------------------------------------
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
@@ -220,6 +259,26 @@ class Sync:
|
|||||||
else:
|
else:
|
||||||
self.failed += 1
|
self.failed += 1
|
||||||
logger.error("UNCLEAR %s %s: %r", collection, ctx, res)
|
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(
|
logger.info(
|
||||||
"%d/%d executed.", len(self.planned) - self.failed, len(self.planned)
|
"%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")
|
"--profile-id", default=os.environ.get("WYBY_ACTION_PROFILE_ID", "2")
|
||||||
)
|
)
|
||||||
args = ap.parse_args()
|
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", ""))
|
object_map = parse_object_map(os.environ.get("WYBY_OBJECT_MAP", ""))
|
||||||
if not 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]
|
bookings = [b for b in bookings if b.pin == args.only_code]
|
||||||
logger.info("wyby bookings in horizon: %d", len(bookings))
|
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()
|
sync._load()
|
||||||
groups = {u["label"]: u["id"] for u in sync.users if u.get("class") == 2}
|
groups = {u["label"]: u["id"] for u in sync.users if u.get("class") == 2}
|
||||||
|
|
||||||
@@ -298,6 +365,7 @@ def main() -> None:
|
|||||||
continue
|
continue
|
||||||
sync.plan_booking(b, group_id, today)
|
sync.plan_booking(b, group_id, today)
|
||||||
|
|
||||||
|
sync.plan_cleanup(today)
|
||||||
sync.log_skips()
|
sync.log_skips()
|
||||||
if not sync.planned:
|
if not sync.planned:
|
||||||
logger.info("No changes needed (%d bookings checked).", len(bookings))
|
logger.info("No changes needed (%d bookings checked).", len(bookings))
|
||||||
|
|||||||
Reference in New Issue
Block a user