- wyby_client.py: headless login to admin.wyby.ch (OIDC auth-code flow with PKCE, cookie session) + booking extraction from the scheduler API (GetWallpaperData); PIN = last 6 digits of transaction Number; rental days derived from RentingStartDate / AllotmentRentingEndDate (exclusive midnight) - wyby_sync.py: for every upcoming booking ensure Glutz user, group membership and PIN with full-day validity; idempotent, self-healing against wyby's own late interface runs; dry-run default - deploy: wyby-sync.service + 15-min timer (24/7); extend_pins stays hourly as safety net - 39 tests; requests added via uv (available system-wide for the oneshot)
293 lines
9.8 KiB
Python
Executable File
293 lines
9.8 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 sys
|
|
from datetime import datetime, time, timedelta
|
|
|
|
import glutz_api as g
|
|
from wyby_client import WybyClient
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
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):
|
|
self.apply = apply
|
|
self.horizon_days = horizon_days
|
|
self.object_map = object_map
|
|
self.profile_id = profile_id
|
|
self.planned: list[tuple[str, dict, str]] = [] # (ctx, collection, data)
|
|
self.skipped: list[str] = []
|
|
self.failed = 0
|
|
|
|
# --- 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
|
|
|
|
# --- planning -------------------------------------------------------
|
|
|
|
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:
|
|
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 = (
|
|
g_extend_parse(row.get("validFrom")),
|
|
g_extend_parse(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")
|
|
|
|
# --- 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)
|
|
logger.info(
|
|
"%d/%d executed.", len(self.planned) - self.failed, len(self.planned)
|
|
)
|
|
return self.failed == 0
|
|
|
|
|
|
def g_extend_parse(raw):
|
|
from extend_pins import parse_ts
|
|
|
|
return parse_ts(raw)
|
|
|
|
|
|
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()
|
|
|
|
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)
|
|
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)
|
|
|
|
for s in sync.skipped:
|
|
logger.info("SKIP %s", s)
|
|
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()
|