Remove extend_pins (superseded by wyby sync)
- wyby sync covers all its cases with better data (actual booking dates instead of +-15 min window derivation) and faster reaction (15 min vs 1 h) - parse_ts moved into wyby_sync; skip logging extracted to Sync.log_skips - deploy installs only wyby-sync units
This commit is contained in:
@@ -8,9 +8,6 @@ GLUTZ_HOST=https://ij32ezn9.eaccess.glutz.com
|
|||||||
GLUTZ_USER=
|
GLUTZ_USER=
|
||||||
GLUTZ_PASS=
|
GLUTZ_PASS=
|
||||||
|
|
||||||
# Optional: Puffer in Minuten, den wyby um Buchungszeiten setzt (Default 15).
|
|
||||||
# Nur ändern, wenn der Anbieter das Fenster der Schnittstelle anpasst.
|
|
||||||
#WYBY_BUFFER_MIN=15
|
|
||||||
|
|
||||||
# wyby admin portal (https://admin.wyby.ch) — Login des Vermieter-Kontos
|
# wyby admin portal (https://admin.wyby.ch) — Login des Vermieter-Kontos
|
||||||
WYBY_USER=
|
WYBY_USER=
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# glutz-maintenances — wyby-PINs auf tageweise Gültigkeit erweitern
|
# glutz-maintenances — wyby-Buchungs-PINs proaktiv tageweise setzen
|
||||||
|
|
||||||
Python-Script (nur Stdlib), das per stündlichem systemd-Lauf die von der
|
Python-Script (nur Stdlib), das per stündlichem systemd-Lauf die von der
|
||||||
**wyby**-Buchungsschnittstelle erzeugten Zutritts-PINs auf der
|
**wyby**-Buchungsschnittstelle erzeugten Zutritts-PINs auf der
|
||||||
@@ -8,23 +8,15 @@ Hintergrund und Schnittstellen-Doku: `../glutz-eaccess-api/wyby-glutz-integratio
|
|||||||
|
|
||||||
## Problem
|
## Problem
|
||||||
|
|
||||||
wyby legt pro Buchung einen Benutzer (`<Name> <6-stellige Transaktion>`, z.B.
|
Die wyby-Schnittstelle legt Benutzer/PINs erst kurz vor Buchungsbeginn an
|
||||||
`Graf Markus 225313`) und einen PIN an, gültig nur ± 15 min um die
|
(«irgendwann davor») und nur ± 15 min um die Reservierungszeit gültig.
|
||||||
Reservierungszeit. Mieter mieten aber tageweise und wollen früher hinein.
|
Mieter mieten aber tageweise und wollen früher hinein.
|
||||||
|
|
||||||
## Lösung
|
## Lösung
|
||||||
|
|
||||||
Bei jedem Lauf (stündlich 5:40–23:40 Uhr):
|
Der wyby-Sync (siehe unten) holt die Buchungen direkt aus dem Vermieterportal
|
||||||
|
und setzt Benutzer, Gruppenzuordnung und PIN mit tageweiser Gültigkeit
|
||||||
1. Benutzer mit wyby-Label-Muster «endet auf 6 Ziffern» suchen.
|
(`Startdatum 00:00:00` → `Enddatum 23:59:59`) proaktiv bei Erfassung.
|
||||||
2. Deren Codes lesen; Start-/Enddatum aus dem vorhandenen Fenster ableiten
|
|
||||||
(Buchungszeit ± Puffer, Default 15 min, konfigurierbar via `WYBY_BUFFER_MIN`).
|
|
||||||
3. Gültigkeit neu setzen: `Startdatum 00:00:00` → `Enddatum 23:59:59`.
|
|
||||||
|
|
||||||
Idempotent — übersprungen werden: bereits tageweise gültige Codes, Codes ohne
|
|
||||||
Fenster (persönliche Codes) und abgelaufene Codes. Deshalb sind stündliche
|
|
||||||
Läufe gefahrlos; bis zum nächsten Lauf deckt wybys eigenes ±15-min-Fenster
|
|
||||||
den Buchungsbeginn ab.
|
|
||||||
|
|
||||||
## Dateien
|
## Dateien
|
||||||
|
|
||||||
@@ -33,7 +25,6 @@ den Buchungsbeginn ab.
|
|||||||
| `glutz_api.py` | JSON-RPC-Client (vendored aus `../glutz-eaccess-api`) |
|
| `glutz_api.py` | JSON-RPC-Client (vendored aus `../glutz-eaccess-api`) |
|
||||||
| `wyby_client.py` | Headless-Client für das wyby-Vermieterportal (nur lesen) |
|
| `wyby_client.py` | Headless-Client für das wyby-Vermieterportal (nur lesen) |
|
||||||
| `wyby_sync.py` | Proaktives PIN-Setzen aus wyby-Buchungen (Dry-Run ist Standard) |
|
| `wyby_sync.py` | Proaktives PIN-Setzen aus wyby-Buchungen (Dry-Run ist Standard) |
|
||||||
| `extend_pins.py` | Sicherheitsnetz: erweitert wyby-gesetzte Codes stündlich |
|
|
||||||
| `deploy/` | systemd Services + Timer + `deploy.sh` |
|
| `deploy/` | systemd Services + Timer + `deploy.sh` |
|
||||||
| `.env` | Zugangsdaten (nicht im Repo, siehe `.env.example`) |
|
| `.env` | Zugangsdaten (nicht im Repo, siehe `.env.example`) |
|
||||||
|
|
||||||
@@ -54,14 +45,12 @@ Enddatum 23:59). PIN = letzte 6 Ziffern der Transaktionsnummer.
|
|||||||
- Timer: alle 15 Minuten, rund um die Uhr (Buchungen können jederzeit
|
- Timer: alle 15 Minuten, rund um die Uhr (Buchungen können jederzeit
|
||||||
erfasst werden).
|
erfasst werden).
|
||||||
|
|
||||||
## extend_pins (Sicherheitsnetz, stündlich 05:40–23:40)
|
|
||||||
|
|
||||||
## Manuell
|
## Manuell
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
./extend_pins.py # Dry-Run: zeigt geplante Änderungen
|
./wyby_sync.py # Dry-Run: zeigt geplante Änderungen
|
||||||
./extend_pins.py --apply # Schreiben
|
./wyby_sync.py --apply # Schreiben
|
||||||
./extend_pins.py --apply --only-code 123456 # Schreibtest auf einzelnen Code
|
./wyby_sync.py --apply --only-code 237251 # Schreibtest auf eine Buchung
|
||||||
```
|
```
|
||||||
|
|
||||||
## Entwicklung
|
## Entwicklung
|
||||||
@@ -111,9 +100,7 @@ Das Journal ist persistent (`/var/log/journal`), überlebt also Reboots.
|
|||||||
## Verifikation (Testbuchung)
|
## Verifikation (Testbuchung)
|
||||||
|
|
||||||
1. Testbuchung im wyby-Portal erfassen → Schnittstelle legt Benutzer + PIN an.
|
1. Testbuchung im wyby-Portal erfassen → Schnittstelle legt Benutzer + PIN an.
|
||||||
2. `./extend_pins.py` (Dry-Run) → PLAN-Zeile mit dem neuen Fenster prüfen.
|
2. `./wyby_sync.py` (Dry-Run) → PLAN-Zeilen mit Benutzer/Code prüfen.
|
||||||
3. `./extend_pins.py --apply --only-code <PIN>` → Schreibpfad prüfen:
|
3. `./wyby_sync.py --apply --only-code <PIN>` → Schreibpfad prüfen:
|
||||||
In der Cloud-UI bzw. per `codes` kontrollieren, dass der Code **aktualiert**
|
Per Cloud-UI bzw. `codes` kontrollieren, dass der Code **aktualisiert**
|
||||||
wurde (kein Duplicate angelegt) und die Gültigkeit tageweise ist.
|
wurde (kein Duplicate angelegt) und die Gültigkeit tageweise ist.
|
||||||
4. Falls die API den Update per `id` nicht akzeptiert: Duplicate-Verhalten
|
|
||||||
prüfen und ggf. Schreibmodus anpassen (siehe `extend_pins.py`).
|
|
||||||
|
|||||||
+1
-3
@@ -21,13 +21,11 @@ fi
|
|||||||
|
|
||||||
# systemd-Units installieren
|
# systemd-Units installieren
|
||||||
sudo install -m 644 \
|
sudo install -m 644 \
|
||||||
"$REPO_DIR/deploy/glutz-maintenances.service" \
|
|
||||||
"$REPO_DIR/deploy/glutz-maintenances.timer" \
|
|
||||||
"$REPO_DIR/deploy/wyby-sync.service" \
|
"$REPO_DIR/deploy/wyby-sync.service" \
|
||||||
"$REPO_DIR/deploy/wyby-sync.timer" \
|
"$REPO_DIR/deploy/wyby-sync.timer" \
|
||||||
/etc/systemd/system/
|
/etc/systemd/system/
|
||||||
sudo systemctl daemon-reload
|
sudo systemctl daemon-reload
|
||||||
sudo systemctl enable --now glutz-maintenances.timer wyby-sync.timer
|
sudo systemctl enable --now wyby-sync.timer
|
||||||
|
|
||||||
echo
|
echo
|
||||||
systemctl list-timers glutz-maintenances.timer --no-pager
|
systemctl list-timers glutz-maintenances.timer --no-pager
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
[Unit]
|
|
||||||
Description=glutz-maintenances — wyby-Buchungs-PINs auf tageweise Gueltigkeit erweitern
|
|
||||||
After=network-online.target
|
|
||||||
Wants=network-online.target
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=oneshot
|
|
||||||
User=apps
|
|
||||||
Group=users
|
|
||||||
WorkingDirectory=/home/apps/glutz-maintenances
|
|
||||||
ExecStart=/usr/bin/python3 /home/apps/glutz-maintenances/extend_pins.py --apply
|
|
||||||
SyslogIdentifier=glutz-maintenances
|
|
||||||
NoNewPrivileges=true
|
|
||||||
ProtectSystem=full
|
|
||||||
ProtectHome=read-only
|
|
||||||
PrivateTmp=true
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
[Unit]
|
|
||||||
Description=Stuendlicher Lauf von glutz-maintenances (05:40 bis 23:40)
|
|
||||||
|
|
||||||
[Timer]
|
|
||||||
OnCalendar=*-*-* 05..23:40:00
|
|
||||||
Persistent=true
|
|
||||||
Unit=glutz-maintenances.service
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=timers.target
|
|
||||||
-228
@@ -1,228 +0,0 @@
|
|||||||
#!/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 logging
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
import sys
|
|
||||||
from datetime import datetime, time, timedelta
|
|
||||||
|
|
||||||
import glutz_api as g
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
# 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 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
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
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 (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)
|
|
||||||
logger.info("wyby users detected: %d", 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))
|
|
||||||
logger.info(
|
|
||||||
"PLAN %s: %s -> %s => %s -> %s",
|
|
||||||
ctx,
|
|
||||||
fmt_ts(vf),
|
|
||||||
fmt_ts(vt),
|
|
||||||
fmt_ts(new_vf),
|
|
||||||
fmt_ts(new_vt),
|
|
||||||
)
|
|
||||||
|
|
||||||
for s in skipped:
|
|
||||||
# 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)
|
|
||||||
|
|
||||||
if not planned:
|
|
||||||
logger.info("No changes needed (%d codes checked/skipped).", len(skipped))
|
|
||||||
return
|
|
||||||
|
|
||||||
if not args.apply:
|
|
||||||
logger.info("DRY-RUN: %d change(s) planned, nothing written.", len(planned))
|
|
||||||
return
|
|
||||||
|
|
||||||
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)
|
|
||||||
logger.error("ERROR %s: %s", ctx, err)
|
|
||||||
continue
|
|
||||||
if res.get("id"):
|
|
||||||
logger.info("OK %s: -> %s ... %s", ctx, fmt_ts(new_vf), fmt_ts(new_vt))
|
|
||||||
else:
|
|
||||||
failed.append(ctx)
|
|
||||||
logger.error("UNCLEAR %s: response without id: %r", ctx, res)
|
|
||||||
|
|
||||||
logger.info("%d/%d changed.", len(planned) - len(failed), len(planned))
|
|
||||||
if failed:
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -1,11 +1,8 @@
|
|||||||
"""Shared fixtures: canned Glutz API data and a fake rpc()."""
|
"""Shared fixtures: canned Glutz API data and a fake rpc()."""
|
||||||
|
|
||||||
import sys
|
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
import glutz_api
|
import glutz_api
|
||||||
from extend_pins import main
|
|
||||||
|
|
||||||
USERS = [
|
USERS = [
|
||||||
{"id": 50, "label": "Graf Markus 225313", "class": 1}, # wyby booking user
|
{"id": 50, "label": "Graf Markus 225313", "class": 1}, # wyby booking user
|
||||||
@@ -53,8 +50,3 @@ def install_rpc(monkeypatch):
|
|||||||
return calls
|
return calls
|
||||||
|
|
||||||
return _install
|
return _install
|
||||||
|
|
||||||
|
|
||||||
def run_main(monkeypatch, *argv):
|
|
||||||
monkeypatch.setattr(sys, "argv", ["extend_pins.py", *argv])
|
|
||||||
main()
|
|
||||||
|
|||||||
@@ -1,220 +0,0 @@
|
|||||||
"""Unit tests for extend_pins.py (helpers and main() flow, rpc mocked)."""
|
|
||||||
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from conftest import USERS, code_row, run_main
|
|
||||||
|
|
||||||
import glutz_api
|
|
||||||
from extend_pins import fmt_ts, full_day_window, parse_ts, wyby_users
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
|
||||||
def no_env(monkeypatch):
|
|
||||||
"""Never touch the real .env / environment from tests."""
|
|
||||||
monkeypatch.setattr(glutz_api, "load_env", lambda *a, **k: None)
|
|
||||||
|
|
||||||
|
|
||||||
# --- helpers ---------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
class TestWybyUsers:
|
|
||||||
def test_detects_label_ending_in_six_digits(self):
|
|
||||||
assert wyby_users(USERS) == {str(u["id"]): u["label"] for u in USERS[:1]}
|
|
||||||
|
|
||||||
def test_ignores_single_digit_labels_and_groups(self):
|
|
||||||
users = [
|
|
||||||
{"id": 1, "label": "Hueb 8a - Gast 1", "class": 1},
|
|
||||||
{"id": 2, "label": "Unused Media", "class": 3},
|
|
||||||
{"id": 3, "label": None, "class": 1},
|
|
||||||
]
|
|
||||||
assert wyby_users(users) == {}
|
|
||||||
|
|
||||||
|
|
||||||
class TestParseTs:
|
|
||||||
def test_parses_milliseconds(self):
|
|
||||||
assert parse_ts("2026-10-24T17:45:00.000") == datetime(2026, 10, 24, 17, 45)
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("raw", [None, "", "not-a-date"])
|
|
||||||
def test_returns_none_for_missing_or_invalid(self, raw):
|
|
||||||
assert parse_ts(raw) is None
|
|
||||||
|
|
||||||
def test_fmt_ts_roundtrip(self):
|
|
||||||
dt = datetime(2099, 2, 18, 0, 0, 0)
|
|
||||||
assert parse_ts(fmt_ts(dt)) == dt
|
|
||||||
|
|
||||||
|
|
||||||
class TestFullDayWindow:
|
|
||||||
def test_single_day_booking(self):
|
|
||||||
vf, vt = (
|
|
||||||
parse_ts("2099-02-18T17:45:00.000"),
|
|
||||||
parse_ts("2099-02-18T22:15:00.000"),
|
|
||||||
)
|
|
||||||
assert full_day_window(vf, vt, 15) == (
|
|
||||||
datetime(2099, 2, 18, 0, 0),
|
|
||||||
datetime(2099, 2, 18, 23, 59, 59),
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_multi_day_booking(self):
|
|
||||||
vf, vt = (
|
|
||||||
parse_ts("2099-02-18T17:45:00.000"),
|
|
||||||
parse_ts("2099-02-20T22:15:00.000"),
|
|
||||||
)
|
|
||||||
assert full_day_window(vf, vt, 15) == (
|
|
||||||
datetime(2099, 2, 18, 0, 0),
|
|
||||||
datetime(2099, 2, 20, 23, 59, 59),
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_start_at_midnight_buffer_crosses_back(self):
|
|
||||||
# Booking starts 00:00 -> wyby window reaches to previous day 23:45.
|
|
||||||
vf, vt = (
|
|
||||||
parse_ts("2099-02-17T23:45:00.000"),
|
|
||||||
parse_ts("2099-02-18T20:15:00.000"),
|
|
||||||
)
|
|
||||||
start, _ = full_day_window(vf, vt, 15)
|
|
||||||
assert start == datetime(2099, 2, 18, 0, 0)
|
|
||||||
|
|
||||||
def test_end_shortly_after_midnight_buffer_crosses_forward(self):
|
|
||||||
# Booking ends 23:50 -> wyby window reaches into next day 00:05.
|
|
||||||
vf, vt = (
|
|
||||||
parse_ts("2099-02-18T16:45:00.000"),
|
|
||||||
parse_ts("2099-02-19T00:05:00.000"),
|
|
||||||
)
|
|
||||||
_, end = full_day_window(vf, vt, 15)
|
|
||||||
assert end == datetime(2099, 2, 18, 23, 59, 59)
|
|
||||||
|
|
||||||
def test_end_before_start_is_clamped(self):
|
|
||||||
vf, vt = parse_ts("2099-02-18T10:00:00"), parse_ts("2099-02-18T10:01:00")
|
|
||||||
start, end = full_day_window(vf, vt, 15)
|
|
||||||
assert (start, end) == (
|
|
||||||
datetime(2099, 2, 18, 0, 0),
|
|
||||||
datetime(2099, 2, 18, 23, 59, 59),
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_zero_buffer_falls_back_to_plain_dates(self):
|
|
||||||
vf, vt = parse_ts("2099-02-18T00:00:00"), parse_ts("2099-02-19T23:59:59")
|
|
||||||
assert full_day_window(vf, vt, 0) == (
|
|
||||||
datetime(2099, 2, 18, 0, 0),
|
|
||||||
datetime(2099, 2, 19, 23, 59, 59),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# --- main() flow -----------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
class TestMainDryRun:
|
|
||||||
def test_plans_but_writes_nothing(self, install_rpc, monkeypatch, capsys):
|
|
||||||
calls = install_rpc(codes=[code_row()])
|
|
||||||
run_main(monkeypatch)
|
|
||||||
|
|
||||||
out = capsys.readouterr().out
|
|
||||||
assert not any(m == "eAccess.setModel" for m, _ in calls)
|
|
||||||
assert "DRY-RUN" in out
|
|
||||||
assert "PLAN" in out
|
|
||||||
assert "2099-02-18T00:00:00" in out
|
|
||||||
assert "2099-02-20T23:59:59" in out
|
|
||||||
|
|
||||||
def test_no_wyby_users_nothing_to_do(self, install_rpc, monkeypatch, capsys):
|
|
||||||
install_rpc(codes=[code_row(userId=42)])
|
|
||||||
run_main(monkeypatch)
|
|
||||||
|
|
||||||
out = capsys.readouterr().out
|
|
||||||
assert "No changes needed" in out
|
|
||||||
assert "PLAN" not in out
|
|
||||||
|
|
||||||
|
|
||||||
class TestMainApply:
|
|
||||||
def test_writes_update_with_preserved_fields(
|
|
||||||
self, install_rpc, monkeypatch, capsys
|
|
||||||
):
|
|
||||||
calls = install_rpc(codes=[code_row()])
|
|
||||||
run_main(monkeypatch, "--apply")
|
|
||||||
|
|
||||||
writes = [p for m, p in calls if m == "eAccess.setModel"]
|
|
||||||
assert len(writes) == 1
|
|
||||||
collection, data = writes[0]
|
|
||||||
assert collection == "Codes"
|
|
||||||
assert data == {
|
|
||||||
"id": "77",
|
|
||||||
"userId": "50",
|
|
||||||
"code": "225313",
|
|
||||||
"description": "reservation",
|
|
||||||
"actionProfileId": "2",
|
|
||||||
"validFrom": "2099-02-18T00:00:00",
|
|
||||||
"validTo": "2099-02-20T23:59:59",
|
|
||||||
}
|
|
||||||
assert "1/1 changed" in capsys.readouterr().out
|
|
||||||
|
|
||||||
def test_action_profile_defaults_to_1_when_missing(self, install_rpc, monkeypatch):
|
|
||||||
calls = install_rpc(codes=[code_row(actionProfileId=None)])
|
|
||||||
run_main(monkeypatch, "--apply")
|
|
||||||
|
|
||||||
_, data = next(p for m, p in calls if m == "eAccess.setModel")
|
|
||||||
assert data["actionProfileId"] == "1"
|
|
||||||
|
|
||||||
def test_skip_reasons(self, install_rpc, monkeypatch, capsys):
|
|
||||||
codes = [
|
|
||||||
code_row(id=1), # planned
|
|
||||||
code_row(id=2, userId=50, code="111111", validFrom=None, validTo=None),
|
|
||||||
code_row(
|
|
||||||
id=3,
|
|
||||||
validFrom="2099-03-01T00:00:00.000",
|
|
||||||
validTo="2099-03-01T23:59:59.000",
|
|
||||||
),
|
|
||||||
code_row(
|
|
||||||
id=4, validFrom="2020-01-01T17:45:00", validTo="2020-01-01T22:15:00"
|
|
||||||
),
|
|
||||||
]
|
|
||||||
calls = install_rpc(codes=codes)
|
|
||||||
run_main(monkeypatch, "--apply")
|
|
||||||
|
|
||||||
captured = capsys.readouterr()
|
|
||||||
writes = [p for m, p in calls if m == "eAccess.setModel"]
|
|
||||||
assert len(writes) == 1
|
|
||||||
assert writes[0][1]["id"] == "1"
|
|
||||||
assert "no validity window" in captured.err # suspicious -> WARNING
|
|
||||||
assert "already full-day" in captured.out
|
|
||||||
assert "already expired" in captured.out
|
|
||||||
|
|
||||||
def test_log_routing_info_stdout_problems_stderr(
|
|
||||||
self, install_rpc, monkeypatch, capsys
|
|
||||||
):
|
|
||||||
codes = [
|
|
||||||
code_row(id=1),
|
|
||||||
code_row(id=2, code="111111", validFrom=None, validTo=None),
|
|
||||||
]
|
|
||||||
install_rpc(codes=codes)
|
|
||||||
run_main(monkeypatch)
|
|
||||||
|
|
||||||
captured = capsys.readouterr()
|
|
||||||
assert "PLAN" in captured.out
|
|
||||||
assert "PLAN" not in captured.err
|
|
||||||
assert "no validity window" in captured.err
|
|
||||||
assert "no validity window" not in captured.out
|
|
||||||
|
|
||||||
def test_only_code_filter(self, install_rpc, monkeypatch, capsys):
|
|
||||||
codes = [code_row(id=1, code="225313"), code_row(id=2, code="999999")]
|
|
||||||
calls = install_rpc(codes=codes)
|
|
||||||
run_main(monkeypatch, "--apply", "--only-code", "999999")
|
|
||||||
|
|
||||||
writes = [p for m, p in calls if m == "eAccess.setModel"]
|
|
||||||
assert len(writes) == 1
|
|
||||||
assert writes[0][1]["code"] == "999999"
|
|
||||||
|
|
||||||
def test_write_result_without_id_counts_as_failure(
|
|
||||||
self, install_rpc, monkeypatch, capsys
|
|
||||||
):
|
|
||||||
install_rpc(codes=[code_row()], write_result={})
|
|
||||||
with pytest.raises(SystemExit) as excinfo:
|
|
||||||
run_main(monkeypatch, "--apply")
|
|
||||||
assert excinfo.value.code == 1
|
|
||||||
assert "UNCLEAR" in capsys.readouterr().err
|
|
||||||
|
|
||||||
def test_rpc_error_during_write_exits_nonzero(
|
|
||||||
self, install_rpc, monkeypatch, capsys
|
|
||||||
):
|
|
||||||
install_rpc(codes=[code_row()], write_error="HTTP 500: boom")
|
|
||||||
with pytest.raises(SystemExit) as excinfo:
|
|
||||||
run_main(monkeypatch, "--apply")
|
|
||||||
assert excinfo.value.code == 1
|
|
||||||
assert "ERROR" in capsys.readouterr().err
|
|
||||||
@@ -169,15 +169,15 @@ class TestPinCollision:
|
|||||||
|
|
||||||
class TestLogRouting:
|
class TestLogRouting:
|
||||||
def test_pin_collision_logged_as_warning(self, sync, capsys):
|
def test_pin_collision_logged_as_warning(self, sync, capsys):
|
||||||
from wyby_sync import logger
|
from wyby_sync import setup_logging
|
||||||
|
|
||||||
|
setup_logging()
|
||||||
sync.relations = [{"parentId": "12", "childId": "55"}]
|
sync.relations = [{"parentId": "12", "childId": "55"}]
|
||||||
sync.codes = [
|
sync.codes = [
|
||||||
code_row(id=66, userId=6, code="237251", description="Bajo Temporär")
|
code_row(id=66, userId=6, code="237251", description="Bajo Temporär")
|
||||||
]
|
]
|
||||||
sync.plan_booking(booking(), "12", date.today())
|
sync.plan_booking(booking(), "12", date.today())
|
||||||
for s in sync.skipped:
|
sync.log_skips()
|
||||||
(logger.warning if "resolve manually" in s else logger.info)("SKIP %s", s)
|
|
||||||
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
|
||||||
|
|||||||
+16
-9
@@ -128,6 +128,11 @@ class Sync:
|
|||||||
|
|
||||||
# --- planning -------------------------------------------------------
|
# --- 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):
|
def plan_booking(self, b, group_id, today):
|
||||||
ctx = f"wyby {b.number} ({b.customer}, {b.object_name})"
|
ctx = f"wyby {b.number} ({b.customer}, {b.object_name})"
|
||||||
if b.end_date < today:
|
if b.end_date < today:
|
||||||
@@ -174,8 +179,8 @@ class Sync:
|
|||||||
)
|
)
|
||||||
return
|
return
|
||||||
current = (
|
current = (
|
||||||
g_extend_parse(row.get("validFrom")),
|
parse_ts(row.get("validFrom")),
|
||||||
g_extend_parse(row.get("validTo")),
|
parse_ts(row.get("validTo")),
|
||||||
)
|
)
|
||||||
if current != (desired_from, desired_to):
|
if current != (desired_from, desired_to):
|
||||||
data = {
|
data = {
|
||||||
@@ -221,10 +226,14 @@ class Sync:
|
|||||||
return self.failed == 0
|
return self.failed == 0
|
||||||
|
|
||||||
|
|
||||||
def g_extend_parse(raw):
|
def parse_ts(raw):
|
||||||
from extend_pins import parse_ts
|
"""Glutz timestamp (e.g. "2026-11-12T00:00:00.000") -> naive datetime."""
|
||||||
|
if not raw:
|
||||||
return parse_ts(raw)
|
return None
|
||||||
|
try:
|
||||||
|
return datetime.fromisoformat(str(raw))
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
@@ -289,9 +298,7 @@ def main() -> None:
|
|||||||
continue
|
continue
|
||||||
sync.plan_booking(b, group_id, today)
|
sync.plan_booking(b, group_id, today)
|
||||||
|
|
||||||
for s in sync.skipped:
|
sync.log_skips()
|
||||||
# PIN collisions need manual attention -> surface in the error filter
|
|
||||||
(logger.warning if "resolve manually" in s else logger.info)("SKIP %s", s)
|
|
||||||
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))
|
||||||
return
|
return
|
||||||
|
|||||||
Reference in New Issue
Block a user