Files
gurix 7ae1de3407 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.
2026-11-13 13:33:41 +01:00

384 lines
13 KiB
Python
Executable File

#!/usr/bin/env python3
"""Proactively set wyby booking PINs in Glutz with full-day validity.
Why: the wyby interface only creates users/PINs shortly before the booking
starts (sometimes), leaving renters without valid PINs earlier in the day.
This sync pulls upcoming bookings from the wyby admin portal and makes sure
every future booking already has its Glutz user, group membership and PIN
with full-day validity (start date 00:00:00 - end date 23:59:59). wyby's own
late interface run may re-narrow the code afterwards; the next sync run
widens it again (idempotent, self-healing).
PIN: last 6 digits of the wyby transaction Number (what renters get shown).
User label: "<last name> <first name> <pin>" (same pattern as the wyby
interface, so both mechanisms converge on the same Glutz user).
Reads bookings read-only from wyby; writes only to Glutz.
Usage:
./wyby_sync.py # dry run
./wyby_sync.py --apply # write changes
./wyby_sync.py --apply --only-code 237251 # test a single booking PIN
"""
from __future__ import annotations
import argparse
import logging
import os
import re
import sys
from datetime import datetime, time, timedelta
import glutz_api as g
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)."""
stdout = logging.StreamHandler(sys.stdout)
stdout.setLevel(logging.INFO)
stdout.addFilter(lambda r: r.levelno < logging.WARNING)
stderr = logging.StreamHandler(sys.stderr)
stderr.setLevel(logging.WARNING)
logging.basicConfig(
level=logging.INFO,
format="%(levelname)s: %(message)s",
handlers=[stdout, stderr],
force=True,
)
def parse_object_map(raw: str) -> list[tuple[str, str]]:
"""'34a24dc9=Gr. Hueb,8b1f91ff=Gr. Langäri' -> [(prefix, group label)]."""
pairs = []
for part in filter(None, raw.split(",")):
prefix, _, group = part.partition("=")
if prefix and group:
pairs.append((prefix.strip(), group.strip()))
return pairs
class Sync:
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 -------------------------------------------------
def _load(self):
self.users = g.rpc(
"eAccess.getModel", ["UsersGroups", {}, ["id", "label", "class"]]
)
self.codes = g.rpc(
"eAccess.getModel",
[
"Codes",
{},
[
"id",
"userId",
"code",
"description",
"actionProfileId",
"validFrom",
"validTo",
],
],
)
self.relations = g.rpc(
"eAccess.getModel",
["UserGroupRelations", {}, ["id", "parentId", "childId"]],
)
if not all(
isinstance(x, list) for x in (self.users, self.codes, self.relations)
):
sys.exit("Unexpected Glutz API response")
def _user_by_label(self, label):
for u in self.users:
if u.get("class") == 1 and u.get("label") == label:
return u
return None
def _relation(self, group_id, user_id):
return any(
r.get("parentId") == group_id and r.get("childId") == user_id
for r in self.relations
)
def _code_row(self, user_id, pin):
for c in self.codes:
if str(c.get("userId")) == str(user_id) and str(c.get("code")) == str(pin):
return c
return None
def _pin_owner(self, pin):
"""Any code row with this PIN value (codes are globally unique in Glutz)."""
for c in self.codes:
if str(c.get("code")) == str(pin):
return c
return None
# --- planning -------------------------------------------------------
def log_skips(self):
for s in self.skipped:
# PIN collisions need manual attention -> surface in the error filter
(logger.warning if "resolve manually" in s else logger.info)("SKIP %s", s)
def plan_booking(self, b, group_id, today):
ctx = f"wyby {b.number} ({b.customer}, {b.object_name})"
if b.end_date < today:
self.skipped.append(f"{ctx} - already expired")
return
user = self._user_by_label(b.label)
uid = str(user["id"]) if user else None
if uid is None:
self.planned.append((ctx, "UsersGroups", {"label": b.label, "class": "1"}))
self.skipped.append(
f"{ctx} - user '{b.label}' will be created; "
"run again (or next run) for group+code"
)
return
if not self._relation(group_id, uid):
self.planned.append(
(ctx, "UserGroupRelations", {"parentId": group_id, "childId": uid})
)
desired_from = datetime.combine(b.start_date, time.min)
desired_to = datetime.combine(b.end_date, time(23, 59, 59))
row = self._code_row(uid, b.pin)
if row is None:
other = self._pin_owner(b.pin)
if other is not None:
self.skipped.append(
f"{ctx} - PIN {b.pin} already exists for Glutz user id "
f"{other['userId']} ({other.get('description') or 'no description'}) "
"-> resolve manually, not touching foreign code"
)
return
self.planned.append(
(
ctx,
"Codes",
{
"userId": uid,
"code": b.pin,
"description": f"wyby {b.number}",
"actionProfileId": self.profile_id,
"validFrom": desired_from.strftime("%Y-%m-%dT%H:%M:%S"),
"validTo": desired_to.strftime("%Y-%m-%dT%H:%M:%S"),
},
)
)
return
current = (
parse_ts(row.get("validFrom")),
parse_ts(row.get("validTo")),
)
if current != (desired_from, desired_to):
data = {
"id": str(row["id"]),
"userId": uid,
"code": b.pin,
"validFrom": desired_from.strftime("%Y-%m-%dT%H:%M:%S"),
"validTo": desired_to.strftime("%Y-%m-%dT%H:%M:%S"),
}
if row.get("actionProfileId"):
data["actionProfileId"] = str(row["actionProfileId"])
self.planned.append((ctx, "Codes", data))
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):
for ctx, collection, data in self.planned:
try:
res = g.rpc("eAccess.setModel", [collection, data])
except SystemExit as err:
self.failed += 1
logger.error("ERROR %s %s: %s", collection, ctx, err)
continue
if res.get("id"):
logger.info(
"OK %s %s: %s",
collection,
ctx,
{
k: v
for k, v in data.items()
if k in ("label", "code", "parentId", "validFrom", "validTo")
},
)
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)
)
return self.failed == 0
def parse_ts(raw):
"""Glutz timestamp (e.g. "2026-11-12T00:00:00.000") -> naive datetime."""
if not raw:
return None
try:
return datetime.fromisoformat(str(raw))
except ValueError:
return None
def main() -> None:
setup_logging()
g.load_env()
ap = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
ap.add_argument(
"--apply", action="store_true", help="write changes (default: dry run)"
)
ap.add_argument("--only-code", metavar="XXXXXX", help="only this booking PIN")
ap.add_argument(
"--horizon-days",
type=int,
default=int(os.environ.get("WYBY_HORIZON_DAYS", "90")),
)
ap.add_argument(
"--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:
sys.exit("WYBY_OBJECT_MAP not set (wyby object id prefix = Glutz group label)")
wyby = WybyClient(
user=os.environ.get("WYBY_USER", ""),
password=os.environ.get("WYBY_PASS", ""),
status_ids=tuple(filter(None, os.environ.get("WYBY_STATUS_IDS", "").split(",")))
or None,
)
wyby.login()
today = datetime.now().date()
bookings = wyby.wallpaper(
today.isoformat(), (today + timedelta(days=args.horizon_days)).isoformat()
)
if args.only_code:
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,
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}
for b in bookings:
group_id = next(
(
gid
for prefix, gid_label in object_map
if (gid := groups.get(gid_label))
and str(b.object_id).startswith(prefix)
),
None,
)
if group_id is None:
sync.skipped.append(
f"wyby {b.number} - no Glutz group mapped for "
f"object '{b.object_name}' ({b.object_id[:8]}), "
"extend WYBY_OBJECT_MAP"
)
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))
return
if not args.apply:
logger.info(
"DRY-RUN: %d change(s) planned, nothing written.", len(sync.planned)
)
return
if not sync.run():
sys.exit(1)
if __name__ == "__main__":
main()