2026-10-22 21:45:29 +02:00
|
|
|
#!/usr/bin/env python3
|
2026-10-23 08:49:49 +02:00
|
|
|
"""Extend wyby booking PINs to full-day validity.
|
2026-10-22 21:45:29 +02:00
|
|
|
|
2026-10-23 08:49:49 +02:00
|
|
|
Problem: the wyby booking interface creates a user and a PIN per booking,
|
|
|
|
|
valid only +/-15 min around the reservation time. But renters book by the
|
|
|
|
|
day and want to enter earlier.
|
2026-10-22 21:45:29 +02:00
|
|
|
|
2026-10-23 08:49:49 +02:00
|
|
|
Solution: find all users matching the wyby label pattern "<name> <6-digit
|
|
|
|
|
transaction>" (e.g. "Graf Markus 225313", see
|
|
|
|
|
../glutz-eaccess-api/wyby-glutz-integration.md) and widen their codes to
|
|
|
|
|
whole days:
|
2026-10-22 21:45:29 +02:00
|
|
|
|
2026-10-23 08:49:49 +02:00
|
|
|
validFrom = start date 00:00:00
|
|
|
|
|
validTo = end date 23:59:59
|
2026-10-22 21:45:29 +02:00
|
|
|
|
2026-10-23 08:49:49 +02:00
|
|
|
Start/end dates are derived from the existing code window, which wyby fills
|
|
|
|
|
with booking time +/- WYBY_BUFFER_MIN (default 15 min).
|
2026-10-22 21:45:29 +02:00
|
|
|
|
2026-10-23 08:49:49 +02:00
|
|
|
Idempotent: already full-day codes, personal codes (no window) and expired
|
|
|
|
|
codes are skipped - so hourly runs are safe. Until the next run, wyby's own
|
|
|
|
|
+/-15 min window covers the start of the booking.
|
2026-10-22 21:45:29 +02:00
|
|
|
|
2026-10-23 08:49:49 +02:00
|
|
|
Usage:
|
|
|
|
|
./extend_pins.py # dry run (read-only)
|
|
|
|
|
./extend_pins.py --apply # write changes
|
|
|
|
|
./extend_pins.py --apply --only-code 123456 # write test on a single code
|
2026-10-22 21:45:29 +02:00
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import argparse
|
2026-10-23 09:01:37 +02:00
|
|
|
import logging
|
2026-10-22 21:45:29 +02:00
|
|
|
import os
|
|
|
|
|
import re
|
|
|
|
|
import sys
|
2026-10-23 08:49:49 +02:00
|
|
|
from datetime import datetime, time, timedelta
|
2026-10-22 21:45:29 +02:00
|
|
|
|
|
|
|
|
import glutz_api as g
|
|
|
|
|
|
2026-10-23 09:01:37 +02:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
2026-10-23 08:49:49 +02:00
|
|
|
# wyby user label: "<last name> <first name> <6-digit transaction>"
|
2026-10-22 21:45:29 +02:00
|
|
|
LABEL_RE = re.compile(r"^.+\s\d{6}$")
|
|
|
|
|
END_OF_DAY = time(23, 59, 59)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def parse_ts(raw: str | None) -> datetime | None:
|
2026-10-23 08:49:49 +02:00
|
|
|
"""Parse a Glutz timestamp (e.g. "2099-02-18T17:45:00.000") into a naive datetime."""
|
2026-10-22 21:45:29 +02:00
|
|
|
if not raw:
|
|
|
|
|
return None
|
|
|
|
|
try:
|
|
|
|
|
return datetime.fromisoformat(str(raw))
|
|
|
|
|
except ValueError:
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def fmt_ts(dt: datetime) -> str:
|
|
|
|
|
return dt.strftime("%Y-%m-%dT%H:%M:%S")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def wyby_users(users: list[dict]) -> dict[str, str]:
|
2026-10-23 08:49:49 +02:00
|
|
|
"""{userId: label} of all users matching the wyby label pattern."""
|
2026-10-22 21:45:29 +02:00
|
|
|
return {
|
|
|
|
|
str(u["id"]): u["label"]
|
|
|
|
|
for u in users
|
|
|
|
|
if u.get("class") == 1 and LABEL_RE.match(u.get("label") or "")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2026-10-23 08:49:49 +02:00
|
|
|
def full_day_window(
|
|
|
|
|
valid_from: datetime, valid_to: datetime, buffer_min: int
|
|
|
|
|
) -> tuple[datetime, datetime]:
|
|
|
|
|
"""Turn a code window (booking +/- buffer) into full-day validity."""
|
2026-10-22 21:45:29 +02:00
|
|
|
start_date = (valid_from + timedelta(minutes=buffer_min)).date()
|
|
|
|
|
end_date = (valid_to - timedelta(minutes=buffer_min)).date()
|
2026-10-23 08:49:49 +02:00
|
|
|
end_date = max(end_date, start_date) # guard against contradictory data
|
2026-10-22 21:45:29 +02:00
|
|
|
return (
|
|
|
|
|
datetime.combine(start_date, time.min),
|
|
|
|
|
datetime.combine(end_date, END_OF_DAY),
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2026-10-23 09:01:37 +02:00
|
|
|
def setup_logging() -> None:
|
|
|
|
|
"""Route INFO to stdout, WARNING/ERROR to stderr.
|
|
|
|
|
|
|
|
|
|
systemd captures stdout at journal priority "info" and stderr at "err",
|
|
|
|
|
so `journalctl -p err -u glutz-maintenances` shows real problems only.
|
|
|
|
|
No timestamps in the format: journald adds them.
|
|
|
|
|
"""
|
|
|
|
|
stdout = logging.StreamHandler(sys.stdout)
|
|
|
|
|
stdout.setLevel(logging.INFO)
|
|
|
|
|
stdout.addFilter(lambda record: record.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, # rebind handlers to the current streams on every call
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2026-10-22 21:45:29 +02:00
|
|
|
def main() -> None:
|
2026-10-23 09:01:37 +02:00
|
|
|
setup_logging()
|
2026-10-22 21:45:29 +02:00
|
|
|
g.load_env()
|
2026-10-23 08:49:49 +02:00
|
|
|
ap = argparse.ArgumentParser(
|
|
|
|
|
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
|
|
|
|
|
)
|
|
|
|
|
ap.add_argument(
|
|
|
|
|
"--apply", action="store_true", help="write changes (without: dry run)"
|
|
|
|
|
)
|
|
|
|
|
ap.add_argument(
|
|
|
|
|
"--only-code",
|
|
|
|
|
metavar="XXXXXX",
|
|
|
|
|
help="only consider this code (for write tests)",
|
|
|
|
|
)
|
|
|
|
|
ap.add_argument(
|
|
|
|
|
"--buffer-min",
|
|
|
|
|
type=int,
|
|
|
|
|
default=int(os.environ.get("WYBY_BUFFER_MIN", "15")),
|
|
|
|
|
help="wyby buffer around booking times (default: 15)",
|
|
|
|
|
)
|
2026-10-22 21:45:29 +02:00
|
|
|
args = ap.parse_args()
|
|
|
|
|
|
|
|
|
|
users = g.rpc("eAccess.getModel", ["UsersGroups", {}, ["id", "label", "class"]])
|
|
|
|
|
if not isinstance(users, list):
|
2026-10-23 08:49:49 +02:00
|
|
|
sys.exit(f"Unexpected response for UsersGroups: {users!r}")
|
2026-10-22 21:45:29 +02:00
|
|
|
targets = wyby_users(users)
|
2026-10-23 09:01:37 +02:00
|
|
|
logger.info("wyby users detected: %d", len(targets))
|
2026-10-22 21:45:29 +02:00
|
|
|
|
2026-10-23 08:49:49 +02:00
|
|
|
codes = g.rpc(
|
|
|
|
|
"eAccess.getModel",
|
|
|
|
|
[
|
|
|
|
|
"Codes",
|
|
|
|
|
{},
|
|
|
|
|
[
|
|
|
|
|
"id",
|
|
|
|
|
"userId",
|
|
|
|
|
"code",
|
|
|
|
|
"description",
|
|
|
|
|
"actionProfileId",
|
|
|
|
|
"validFrom",
|
|
|
|
|
"validTo",
|
|
|
|
|
],
|
|
|
|
|
],
|
|
|
|
|
)
|
2026-10-22 21:45:29 +02:00
|
|
|
if not isinstance(codes, list):
|
2026-10-23 08:49:49 +02:00
|
|
|
sys.exit(f"Unexpected response for Codes: {codes!r}")
|
2026-10-22 21:45:29 +02:00
|
|
|
if args.only_code:
|
|
|
|
|
codes = [c for c in codes if str(c.get("code")) == args.only_code]
|
|
|
|
|
|
|
|
|
|
now = datetime.now()
|
|
|
|
|
planned, skipped, failed = [], [], []
|
|
|
|
|
for c in codes:
|
|
|
|
|
uid = str(c.get("userId"))
|
|
|
|
|
if uid not in targets:
|
|
|
|
|
continue
|
|
|
|
|
ctx = f"user={targets[uid]!r} code={c.get('code')} id={c.get('id')}"
|
|
|
|
|
|
|
|
|
|
vf, vt = parse_ts(c.get("validFrom")), parse_ts(c.get("validTo"))
|
|
|
|
|
if not vf or not vt:
|
2026-10-23 08:49:49 +02:00
|
|
|
skipped.append(f"{ctx} - no validity window (personal code)")
|
2026-10-22 21:45:29 +02:00
|
|
|
continue
|
|
|
|
|
new_vf, new_vt = full_day_window(vf, vt, args.buffer_min)
|
|
|
|
|
if (vf, vt) == (new_vf, new_vt):
|
2026-10-23 08:49:49 +02:00
|
|
|
skipped.append(f"{ctx} - already full-day")
|
2026-10-22 21:45:29 +02:00
|
|
|
continue
|
|
|
|
|
if new_vt < now:
|
2026-10-23 08:49:49 +02:00
|
|
|
skipped.append(f"{ctx} - already expired")
|
2026-10-22 21:45:29 +02:00
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
planned.append((c, new_vf, new_vt))
|
2026-10-23 09:01:37 +02:00
|
|
|
logger.info(
|
|
|
|
|
"PLAN %s: %s -> %s => %s -> %s",
|
|
|
|
|
ctx,
|
|
|
|
|
fmt_ts(vf),
|
|
|
|
|
fmt_ts(vt),
|
|
|
|
|
fmt_ts(new_vf),
|
|
|
|
|
fmt_ts(new_vt),
|
2026-10-23 08:49:49 +02:00
|
|
|
)
|
2026-10-22 21:45:29 +02:00
|
|
|
|
|
|
|
|
for s in skipped:
|
2026-10-23 09:01:37 +02:00
|
|
|
# A wyby user without a validity window hints at an interface problem
|
|
|
|
|
# (see glutz-eaccess-api docs, section 3.1) - surface it as WARNING.
|
|
|
|
|
(logger.warning if "no validity window" in s else logger.info)("SKIP %s", s)
|
2026-10-22 21:45:29 +02:00
|
|
|
|
|
|
|
|
if not planned:
|
2026-10-23 09:01:37 +02:00
|
|
|
logger.info("No changes needed (%d codes checked/skipped).", len(skipped))
|
2026-10-22 21:45:29 +02:00
|
|
|
return
|
|
|
|
|
|
|
|
|
|
if not args.apply:
|
2026-10-23 09:01:37 +02:00
|
|
|
logger.info("DRY-RUN: %d change(s) planned, nothing written.", len(planned))
|
2026-10-22 21:45:29 +02:00
|
|
|
return
|
|
|
|
|
|
|
|
|
|
for c, new_vf, new_vt in planned:
|
2026-10-23 08:49:49 +02:00
|
|
|
# Preserve existing fields, only change validity.
|
2026-10-22 21:45:29 +02:00
|
|
|
data = {
|
|
|
|
|
"userId": str(c["userId"]),
|
|
|
|
|
"code": str(c["code"]),
|
|
|
|
|
"validFrom": fmt_ts(new_vf),
|
|
|
|
|
"validTo": fmt_ts(new_vt),
|
|
|
|
|
}
|
|
|
|
|
if c.get("description"):
|
|
|
|
|
data["description"] = str(c["description"])
|
|
|
|
|
data["actionProfileId"] = str(c.get("actionProfileId") or "1")
|
|
|
|
|
if c.get("id"):
|
2026-10-23 08:49:49 +02:00
|
|
|
data["id"] = str(c["id"]) # update instead of duplicate (mode "id")
|
2026-10-22 21:45:29 +02:00
|
|
|
|
|
|
|
|
ctx = f"user={targets[str(c['userId'])]!r} code={c.get('code')}"
|
|
|
|
|
try:
|
|
|
|
|
res = g.rpc("eAccess.setModel", ["Codes", data])
|
2026-10-23 08:49:49 +02:00
|
|
|
except SystemExit as err: # rpc() reports errors via sys.exit
|
2026-10-22 21:45:29 +02:00
|
|
|
failed.append(ctx)
|
2026-10-23 09:01:37 +02:00
|
|
|
logger.error("ERROR %s: %s", ctx, err)
|
2026-10-22 21:45:29 +02:00
|
|
|
continue
|
|
|
|
|
if res.get("id"):
|
2026-10-23 09:01:37 +02:00
|
|
|
logger.info("OK %s: -> %s ... %s", ctx, fmt_ts(new_vf), fmt_ts(new_vt))
|
2026-10-22 21:45:29 +02:00
|
|
|
else:
|
|
|
|
|
failed.append(ctx)
|
2026-10-23 09:01:37 +02:00
|
|
|
logger.error("UNCLEAR %s: response without id: %r", ctx, res)
|
2026-10-22 21:45:29 +02:00
|
|
|
|
2026-10-23 09:01:37 +02:00
|
|
|
logger.info("%d/%d changed.", len(planned) - len(failed), len(planned))
|
2026-10-22 21:45:29 +02:00
|
|
|
if failed:
|
|
|
|
|
sys.exit(1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
main()
|