Files
glutz-maintenances/extend_pins.py
T

200 lines
6.2 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
"""Extend wyby booking PINs to full-day validity.
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.
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:
validFrom = start date 00:00:00
validTo = end date 23:59:59
Start/end dates are derived from the existing code window, which wyby fills
with booking time +/- WYBY_BUFFER_MIN (default 15 min).
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.
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
"""
from __future__ import annotations
import argparse
import os
import re
import sys
from datetime import datetime, time, timedelta
import glutz_api as g
# wyby user label: "<last name> <first name> <6-digit transaction>"
LABEL_RE = re.compile(r"^.+\s\d{6}$")
END_OF_DAY = time(23, 59, 59)
def parse_ts(raw: str | None) -> datetime | None:
"""Parse a Glutz timestamp (e.g. "2099-02-18T17:45:00.000") into a naive datetime."""
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]:
"""{userId: label} of all users matching the wyby label pattern."""
return {
str(u["id"]): u["label"]
for u in users
if u.get("class") == 1 and LABEL_RE.match(u.get("label") or "")
}
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."""
start_date = (valid_from + timedelta(minutes=buffer_min)).date()
end_date = (valid_to - timedelta(minutes=buffer_min)).date()
end_date = max(end_date, start_date) # guard against contradictory data
return (
datetime.combine(start_date, time.min),
datetime.combine(end_date, END_OF_DAY),
)
def main() -> None:
g.load_env()
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)",
)
args = ap.parse_args()
users = g.rpc("eAccess.getModel", ["UsersGroups", {}, ["id", "label", "class"]])
if not isinstance(users, list):
sys.exit(f"Unexpected response for UsersGroups: {users!r}")
targets = wyby_users(users)
print(f"wyby users detected: {len(targets)}")
codes = g.rpc(
"eAccess.getModel",
[
"Codes",
{},
[
"id",
"userId",
"code",
"description",
"actionProfileId",
"validFrom",
"validTo",
],
],
)
if not isinstance(codes, list):
sys.exit(f"Unexpected response for Codes: {codes!r}")
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:
skipped.append(f"{ctx} - no validity window (personal code)")
continue
new_vf, new_vt = full_day_window(vf, vt, args.buffer_min)
if (vf, vt) == (new_vf, new_vt):
skipped.append(f"{ctx} - already full-day")
continue
if new_vt < now:
skipped.append(f"{ctx} - already expired")
continue
planned.append((c, new_vf, new_vt))
print(
f"PLAN {ctx}: {fmt_ts(vf)} -> {fmt_ts(vt)}"
f" => {fmt_ts(new_vf)} -> {fmt_ts(new_vt)}"
)
for s in skipped:
print(f"SKIP {s}")
if not planned:
print(f"No changes needed ({len(skipped)} codes checked/skipped).")
return
if not args.apply:
print(f"\nDRY-RUN: {len(planned)} change(s) planned, nothing written.")
return
print()
for c, new_vf, new_vt in planned:
# Preserve existing fields, only change validity.
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"):
data["id"] = str(c["id"]) # update instead of duplicate (mode "id")
ctx = f"user={targets[str(c['userId'])]!r} code={c.get('code')}"
try:
res = g.rpc("eAccess.setModel", ["Codes", data])
except SystemExit as err: # rpc() reports errors via sys.exit
failed.append(ctx)
print(f"ERROR {ctx}: {err}")
continue
if res.get("id"):
print(f"OK {ctx}: -> {fmt_ts(new_vf)} ... {fmt_ts(new_vt)}")
else:
failed.append(ctx)
print(f"UNCLEAR {ctx}: response without id: {res!r}")
print(f"\n{len(planned) - len(failed)}/{len(planned)} changed.")
if failed:
sys.exit(1)
if __name__ == "__main__":
main()