Merge pull request #2 from jasonMPM/v3

Add files via upload
This commit was merged in pull request #2.
This commit is contained in:
jasonMPM
2026-03-04 19:53:57 -06:00
committed by GitHub
3 changed files with 389 additions and 345 deletions

162
README.md
View File

@@ -1,19 +1,21 @@
# UniFi Access Badge-In Dashboard (V2) # UniFi Access Badge-In Dashboard (V3)
A Dockerised Flask + SQLite web app that receives UniFi Access `access.door.unlock` webhooks, A Dockerised Flask + SQLite web app that receives UniFi Access `access.door.unlock` webhooks,
resolves UUID actor IDs to real user names via the UniFi Access API, resolves UUIDs to real user names via the UniFi Access API, and displays a modern dark
and displays a modern dark dashboard with on-time / late status per person. attendance dashboard with on-time / late status, first + latest badge times, and a test reset button.
--- ---
## Features ## Features
- Receives `access.door.unlock` webhooks from either the **UniFi Access developer API** or the legacy **Alarm Manager** format. - Receives webhooks from the UniFi Access developer API or legacy Alarm Manager format.
- Resolves blank `user_name` UUIDs to real names by querying the UniFi Access REST API on a schedule (every 6 hours) and caching results in SQLite. - Resolves UUIDs to real names via the UniFi Access REST API (cached in SQLite, refreshed every 6 hrs).
- Manual **Sync Users** button in the UI triggers an immediate cache refresh. - **First badge in** column — never overwritten by subsequent badges.
- Dark theme with gold accents, green ON TIME / red LATE status chips. - **Latest badge in** column — shows the most recent entry that day.
- Date picker + configurable "badged in by" cutoff time. - **Sync Users** button — manually refreshes the user name cache.
- Fully Dockerised — single container, persisted SQLite volume. - **Reset Day** button — confirmation modal deletes all records for the selected date (testing only).
- Green ON TIME / Red LATE status chips based on a configurable cutoff time.
- Fully Dockerised — single container, persistent SQLite volume.
--- ---
@@ -21,50 +23,33 @@ and displays a modern dark dashboard with on-time / late status per person.
``` ```
. .
├── app.py # Flask application ├── app.py
├── requirements.txt ├── requirements.txt
├── Dockerfile ├── Dockerfile
├── docker-compose.yml ├── docker-compose.yml
├── .env.example # Copy to .env and fill in your values ├── .env.example
├── .gitignore ├── .gitignore
└── static/ └── static/
└── index.html # Dashboard UI └── index.html
``` ```
--- ---
## Step 1 — Generate a UniFi Access API token ## Setup
1. Open your **UniFi OS** web interface. ### 1. Generate a UniFi Access API token
2. Navigate to **UniFi Access → Settings → Integrations** (or the **Developer API** section).
3. Create a new **API Key** (Bearer Token). Copy it — you will need it below.
> Use a dedicated read-only admin account to generate the token if possible. 1. Open UniFi OS → UniFi Access → Settings → Integrations / Developer API.
2. Create a new API Key (Bearer Token) and copy it.
--- ### 2. Create your .env file
## Step 2 — Create your .env file
Copy `.env.example` to `.env` and fill in your values:
```bash ```bash
cp .env.example .env cp .env.example .env
# edit .env and fill in UNIFI_HOST and UNIFI_API_TOKEN
``` ```
```dotenv ### 3. Register the webhook with UniFi Access (run once)
UNIFI_HOST=192.168.1.1 # IP of your UniFi OS controller
UNIFI_API_TOKEN=YOUR_TOKEN_HERE
TZ=America/Chicago
DB_PATH=/data/dashboard.db
```
> **Never commit `.env` to git.** It is listed in `.gitignore`.
---
## Step 3 — Register the webhook with UniFi Access
Run this once from any machine on the same LAN as your controller (replace placeholders):
```bash ```bash
curl -k -X POST "https://192.168.1.1:45/api1/webhooks/endpoints" \ curl -k -X POST "https://192.168.1.1:45/api1/webhooks/endpoints" \
@@ -78,97 +63,26 @@ curl -k -X POST "https://192.168.1.1:45/api1/webhooks/endpoints" \
}' }'
``` ```
Verify it was registered: Verify registration:
```bash ```bash
curl -k -X GET "https://192.168.1.1:45/api1/webhooks/endpoints" \ curl -k -X GET "https://192.168.1.1:45/api1/webhooks/endpoints" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" -H "Authorization: Bearer YOUR_TOKEN_HERE"
``` ```
You should see your webhook listed with a unique `id`. ### 4. Deploy on Unraid
> **Note:** The UniFi Access API runs on **port 45** over HTTPS with a self-signed cert.
> Always pass `-k` to curl, or `verify=False` in Python requests.
---
## Step 4 — Deploy on Unraid
### Clone from GitHub and build locally
SSH into your Unraid server:
```bash ```bash
cd /mnt/user/appdata cd /mnt/user/appdata
git clone https://github.com/<your-user>/<your-repo>.git unifi-access-dashboard git clone https://github.com/<your-user>/<your-repo>.git unifi-access-dashboard
cd unifi-access-dashboard cd unifi-access-dashboard
cp .env.example .env cp .env.example .env && nano .env
nano .env # fill in UNIFI_HOST and UNIFI_API_TOKEN
docker compose up -d --build docker compose up -d --build
``` ```
The app is now running on **port 8000**. Open: `http://<UNRAID-IP>:8000/`
### Unraid GUI (Docker tab — Add Container) ### 5. Updating from GitHub
If you prefer using the GUI after pushing an image to Docker Hub:
```bash
# On your workstation:
docker build -t <your-dockerhub-user>/unifi-access-dashboard:latest .
docker push <your-dockerhub-user>/unifi-access-dashboard:latest
```
Then in Unraid → Docker → Add Container:
| Field | Value |
|---|---|
| Name | unifi-access-dashboard |
| Repository | `<your-dockerhub-user>/unifi-access-dashboard:latest` |
| Port | Host `8000` → Container `8000` |
| Path | Host `/mnt/user/appdata/unifi-access-dashboard/data` → Container `/data` |
| Env: UNIFI_HOST | `192.168.1.x` |
| Env: UNIFI_API_TOKEN | `your-token` |
| Env: TZ | `America/Chicago` |
---
## Step 5 — Open the dashboard
Browse to:
```
http://<UNRAID-IP>:8000/
```
- Choose a **date** and set the **"Badged in by"** cutoff time (e.g. `09:00`).
- Click **Refresh** to load the day's first badge-in per person.
- Green chip = on time. Red chip = late.
- Click **Sync Users** to immediately pull the latest user list from your UniFi Access controller.
---
## Keeping the user cache fresh
The app automatically re-syncs users from UniFi Access every **6 hours** in the background.
If you add or rename a badge holder, click **Sync Users** in the dashboard or restart the container.
---
## Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| Names show as `Unknown (UUID…)` | Users not yet cached | Click Sync Users or wait for the 6-hour job |
| Webhook not arriving | Firewall / Docker network | Ensure port 8000 is reachable from the UniFi controller |
| `curl` returns SSL error | Self-signed cert | Add `-k` to bypass; already handled in Python |
| 404 on `/api1/users` | Firmware difference | Try `/api/v1/users`; check your Access app version |
| Duplicate events | Both Alarm Manager and API webhook active | Remove one, or they will both store rows (harmless but duplicates) |
| Container exits | `.env` missing | Ensure `.env` exists and `docker compose up` picks it up |
---
## Updating from GitHub
```bash ```bash
cd /mnt/user/appdata/unifi-access-dashboard cd /mnt/user/appdata/unifi-access-dashboard
@@ -178,9 +92,23 @@ docker compose up -d --build
--- ---
## Security notes ## API endpoints
- The `.env` file is excluded from git via `.gitignore`. | Method | Path | Description |
- The UniFi API token is never exposed to the frontend. |---|---|---|
- Mount `/data` to persistent storage so badge history survives container restarts. | POST | `/api/unifi-access` | Receives webhook from UniFi Access |
- For external access, place a reverse proxy (Nginx/Traefik) with HTTPS in front. | GET | `/api/first-badge-status` | Returns first + latest badge per user for a date |
| GET | `/api/sync-users` | Triggers immediate user cache sync |
| DELETE | `/api/reset-day?date=YYYY-MM-DD` | Deletes all records for the given date |
---
## Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| Names show as `Unknown (UUID…)` | Users not cached yet | Click Sync Users |
| Webhook not arriving | Firewall / port | Ensure port 8000 reachable from controller |
| SSL error on curl | Self-signed cert | Use `-k` flag |
| 404 on `/api1/users` | Firmware path differs | Try `/api/v1/users` |
| Duplicate events | Both Alarm Manager and API webhooks active | Remove one or deduplicate by event ID |

140
app.py
View File

@@ -12,8 +12,8 @@ load_dotenv()
app = Flask(__name__) app = Flask(__name__)
DB_PATH = os.environ.get("DB_PATH", "/data/dashboard.db") DB_PATH = os.environ.get("DB_PATH", "/data/dashboard.db")
UNIFI_HOST = os.environ.get("UNIFI_HOST", "") UNIFI_HOST = os.environ.get("UNIFI_HOST", "")
UNIFI_API_TOKEN = os.environ.get("UNIFI_API_TOKEN", "") UNIFI_API_TOKEN = os.environ.get("UNIFI_API_TOKEN", "")
@@ -30,16 +30,16 @@ def init_db():
conn = get_db() conn = get_db()
conn.executescript(""" conn.executescript("""
CREATE TABLE IF NOT EXISTS unlocks ( CREATE TABLE IF NOT EXISTS unlocks (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
ts TEXT NOT NULL, ts TEXT NOT NULL,
event TEXT NOT NULL DEFAULT 'access.door.unlock', event TEXT NOT NULL DEFAULT 'access.door.unlock',
door_name TEXT, door_name TEXT,
device_name TEXT, device_name TEXT,
actor_id TEXT, actor_id TEXT,
actor_name TEXT, actor_name TEXT,
resolved_name TEXT, resolved_name TEXT,
auth_type TEXT, auth_type TEXT,
result TEXT result TEXT
); );
CREATE TABLE IF NOT EXISTS access_users ( CREATE TABLE IF NOT EXISTS access_users (
@@ -49,11 +49,11 @@ def init_db():
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
); );
""") """)
# migration: add resolved_name if upgrading from V1 for col in ("resolved_name", "device_name"):
try: try:
conn.execute("ALTER TABLE unlocks ADD COLUMN resolved_name TEXT") conn.execute(f"ALTER TABLE unlocks ADD COLUMN {col} TEXT")
except Exception: except Exception:
pass pass
conn.commit() conn.commit()
conn.close() conn.close()
@@ -64,13 +64,13 @@ def sync_unifi_users():
if not UNIFI_HOST or not UNIFI_API_TOKEN: if not UNIFI_HOST or not UNIFI_API_TOKEN:
print("[UniFi Sync] UNIFI_HOST or UNIFI_API_TOKEN not set — skipping.") print("[UniFi Sync] UNIFI_HOST or UNIFI_API_TOKEN not set — skipping.")
return return
url = f"https://{UNIFI_HOST}:45/api1/users" url = f"https://{UNIFI_HOST}:45/api1/users"
headers = {"Authorization": f"Bearer {UNIFI_API_TOKEN}"} headers = {"Authorization": f"Bearer {UNIFI_API_TOKEN}"}
try: try:
resp = requests.get(url, headers=headers, verify=False, timeout=10) resp = requests.get(url, headers=headers, verify=False, timeout=10)
resp.raise_for_status() resp.raise_for_status()
users = resp.json().get("data", []) users = resp.json().get("data", [])
conn = get_db() conn = get_db()
for user in users: for user in users:
conn.execute( conn.execute(
"""INSERT INTO access_users (id, name, email, updated_at) """INSERT INTO access_users (id, name, email, updated_at)
@@ -92,7 +92,7 @@ def resolve_user_name(user_id: str) -> str:
if not user_id: if not user_id:
return "Unknown" return "Unknown"
conn = get_db() conn = get_db()
row = conn.execute( row = conn.execute(
"SELECT name FROM access_users WHERE id = ?", (user_id,) "SELECT name FROM access_users WHERE id = ?", (user_id,)
).fetchone() ).fetchone()
conn.close() conn.close()
@@ -104,36 +104,32 @@ def resolve_user_name(user_id: str) -> str:
@app.post("/api/unifi-access") @app.post("/api/unifi-access")
def unifi_access_webhook(): def unifi_access_webhook():
payload = request.get_json(force=True, silent=True) or {} payload = request.get_json(force=True, silent=True) or {}
ts = dt.datetime.utcnow().isoformat(timespec="seconds") + "Z"
ts = dt.datetime.utcnow().isoformat(timespec="seconds") + "Z"
# ── New developer-API webhook format ──────────────────────────────────────
if payload.get("event") == "access.door.unlock": if payload.get("event") == "access.door.unlock":
data = payload.get("data", {}) data = payload.get("data", {})
actor = data.get("actor", {}) actor = data.get("actor", {})
location = data.get("location", {}) location = data.get("location", {})
device = data.get("device", {}) device = data.get("device", {})
obj = data.get("object", {}) obj = data.get("object", {})
actor_id = actor.get("id", "")
actor_id = actor.get("id", "") actor_name = actor.get("name") or resolve_user_name(actor_id)
actor_name = actor.get("name") or resolve_user_name(actor_id) door_name = location.get("name")
door_name = location.get("name")
device_name = device.get("name") device_name = device.get("name")
auth_type = obj.get("authentication_type") auth_type = obj.get("authentication_type")
result = obj.get("result", "Access Granted") result = obj.get("result", "Access Granted")
# ── Legacy Alarm Manager format ───────────────────────────────────────────
elif "events" in payload: elif "events" in payload:
event = payload["events"][0] event = payload["events"][0]
actor_id = event.get("user", "") actor_id = event.get("user", "")
actor_name = event.get("user_name") or resolve_user_name(actor_id) actor_name = event.get("user_name") or resolve_user_name(actor_id)
door_name = event.get("location_name") or event.get("location", "Unknown Door") door_name = event.get("location_name") or event.get("location", "Unknown Door")
device_name = None device_name = None
auth_type = event.get("unlock_method_text", "Unknown") auth_type = event.get("unlock_method_text", "Unknown")
result = "Access Granted" result = "Access Granted"
else: else:
return "", 204 # unrecognised — silently ignore return "", 204
conn = get_db() conn = get_db()
conn.execute( conn.execute(
@@ -159,7 +155,8 @@ def first_badge_status():
end = f"{date}T23:59:59Z" end = f"{date}T23:59:59Z"
conn = get_db() conn = get_db()
rows = conn.execute( # First badge per person
first_rows = conn.execute(
"""SELECT COALESCE(resolved_name, actor_name, actor_id) AS display_name, """SELECT COALESCE(resolved_name, actor_name, actor_id) AS display_name,
actor_id, actor_id,
MIN(ts) AS first_ts MIN(ts) AS first_ts
@@ -172,29 +169,72 @@ def first_badge_status():
ORDER BY first_ts""", ORDER BY first_ts""",
(start, end), (start, end),
).fetchall() ).fetchall()
# Latest badge per person (may equal first if they only badged once)
latest_rows = conn.execute(
"""SELECT actor_id, MAX(ts) AS latest_ts
FROM unlocks
WHERE event = 'access.door.unlock'
AND result = 'Access Granted'
AND ts BETWEEN ? AND ?
AND actor_id IS NOT NULL
GROUP BY actor_id""",
(start, end),
).fetchall()
conn.close() conn.close()
latest_map = {r["actor_id"]: r["latest_ts"] for r in latest_rows}
result = [] result = []
for r in rows: for r in first_rows:
t = dt.datetime.fromisoformat(r["first_ts"].replace("Z", "+00:00")) t_first = dt.datetime.fromisoformat(r["first_ts"].replace("Z", "+00:00"))
badge_time = t.strftime("%H:%M") first_time = t_first.strftime("%H:%M")
latest_ts = latest_map.get(r["actor_id"], r["first_ts"])
t_latest = dt.datetime.fromisoformat(latest_ts.replace("Z", "+00:00"))
latest_time = t_latest.strftime("%H:%M")
result.append({ result.append({
"actor_name": r["display_name"], "actor_name": r["display_name"],
"actor_id": r["actor_id"], "actor_id": r["actor_id"],
"first_badge": r["first_ts"], "first_badge": r["first_ts"],
"badge_time": badge_time, "badge_time": first_time,
"on_time": badge_time <= cutoff, "latest_badge": latest_ts,
"latest_time": latest_time,
"on_time": first_time <= cutoff,
}) })
return jsonify(result) return jsonify(result)
# ── Sync users ────────────────────────────────────────────────────────────────
@app.get("/api/sync-users") @app.get("/api/sync-users")
def manual_sync(): def manual_sync():
sync_unifi_users() sync_unifi_users()
return jsonify({"status": "ok"}) return jsonify({"status": "ok"})
# ── Reset day (testing only) ──────────────────────────────────────────────────
@app.delete("/api/reset-day")
def reset_day():
"""Delete all unlock records for a given date (defaults to today).
Intended for development/testing only.
"""
date = request.args.get("date") or dt.date.today().isoformat()
start = f"{date}T00:00:00Z"
end = f"{date}T23:59:59Z"
conn = get_db()
res = conn.execute(
"DELETE FROM unlocks WHERE ts BETWEEN ? AND ?", (start, end)
)
conn.commit()
deleted = res.rowcount
conn.close()
return jsonify({"status": "ok", "deleted": deleted, "date": date})
# ── Static files ────────────────────────────────────────────────────────────── # ── Static files ──────────────────────────────────────────────────────────────
@app.get("/") @app.get("/")

View File

@@ -14,6 +14,7 @@
--muted: #888; --muted: #888;
--danger: #ff4d4f; --danger: #ff4d4f;
--success: #2ecc71; --success: #2ecc71;
--warn: #f39c12;
--border: #222; --border: #222;
} }
* { box-sizing: border-box; margin: 0; padding: 0; } * { box-sizing: border-box; margin: 0; padding: 0; }
@@ -27,7 +28,7 @@
padding: 32px 16px; padding: 32px 16px;
} }
.app-shell { .app-shell {
width: 100%; max-width: 1200px; width: 100%; max-width: 1280px;
background: rgba(5,5,8,0.96); background: rgba(5,5,8,0.96);
border-radius: 20px; border-radius: 20px;
border: 1px solid rgba(212,175,55,0.3); border: 1px solid rgba(212,175,55,0.3);
@@ -39,10 +40,7 @@
align-items: center; margin-bottom: 20px; gap: 16px; align-items: center; margin-bottom: 20px; gap: 16px;
} }
.title-block { display: flex; flex-direction: column; gap: 4px; } .title-block { display: flex; flex-direction: column; gap: 4px; }
h1 { h1 { font-size: 1.6rem; letter-spacing: 0.08em; text-transform: uppercase; color: var(--gold); }
font-size: 1.6rem; letter-spacing: 0.08em;
text-transform: uppercase; color: var(--gold);
}
.subtitle { font-size: 0.9rem; color: var(--muted); } .subtitle { font-size: 0.9rem; color: var(--muted); }
.badge { .badge {
border-radius: 999px; border-radius: 999px;
@@ -55,20 +53,17 @@
.controls { .controls {
display: flex; flex-wrap: wrap; gap: 12px; display: flex; flex-wrap: wrap; gap: 12px;
margin-bottom: 18px; align-items: center; margin-bottom: 18px; align-items: center;
justify-content: space-between;
} }
.control-group { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; } .control-group { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }
.spacer { flex: 1; }
label { font-size: 0.8rem; letter-spacing: 0.1em; text-transform: uppercase; color: var(--muted); } label { font-size: 0.8rem; letter-spacing: 0.1em; text-transform: uppercase; color: var(--muted); }
input, select { input {
background: var(--bg-card); border-radius: 999px; background: var(--bg-card); border-radius: 999px;
border: 1px solid var(--border); border: 1px solid var(--border);
padding: 8px 14px; font-size: 0.9rem; color: var(--text); padding: 8px 14px; font-size: 0.9rem; color: var(--text);
outline: none; min-width: 130px; outline: none; min-width: 130px;
} }
input:focus, select:focus { input:focus { border-color: var(--gold-soft); box-shadow: 0 0 0 1px rgba(212,175,55,0.4); }
border-color: var(--gold-soft);
box-shadow: 0 0 0 1px rgba(212,175,55,0.4);
}
button { button {
border-radius: 999px; border-radius: 999px;
border: 1px solid rgba(212,175,55,0.7); border: 1px solid rgba(212,175,55,0.7);
@@ -77,13 +72,19 @@
font-size: 0.85rem; letter-spacing: 0.1em; font-size: 0.85rem; letter-spacing: 0.1em;
text-transform: uppercase; cursor: pointer; text-transform: uppercase; cursor: pointer;
transition: transform 0.08s, box-shadow 0.08s; transition: transform 0.08s, box-shadow 0.08s;
white-space: nowrap;
} }
button:hover { transform: translateY(-1px); box-shadow: 0 8px 24px rgba(0,0,0,0.5); } button:hover { transform: translateY(-1px); box-shadow: 0 8px 24px rgba(0,0,0,0.5); }
button:active { transform: translateY(1px); } button:active { transform: translateY(1px); box-shadow: none; }
button:disabled { opacity: 0.45; cursor: default; transform: none; }
.sync-btn { .sync-btn {
border-color: rgba(100,180,255,0.6); border-color: rgba(100,180,255,0.6);
background: radial-gradient(circle at top,rgba(100,180,255,0.18),rgba(2,2,4,0.95)); background: radial-gradient(circle at top,rgba(100,180,255,0.18),rgba(2,2,4,0.95));
} }
.reset-btn {
border-color: rgba(255,100,100,0.6);
background: radial-gradient(circle at top,rgba(255,80,80,0.18),rgba(2,2,4,0.95));
}
.summary-row { .summary-row {
display: flex; flex-wrap: wrap; gap: 12px; display: flex; flex-wrap: wrap; gap: 12px;
margin-bottom: 16px; font-size: 0.85rem; margin-bottom: 16px; font-size: 0.85rem;
@@ -91,8 +92,7 @@
.summary-pill { .summary-pill {
display: inline-flex; align-items: center; gap: 8px; display: inline-flex; align-items: center; gap: 8px;
background: var(--bg-card); border-radius: 999px; background: var(--bg-card); border-radius: 999px;
padding: 6px 14px; border: 1px solid var(--border); padding: 6px 14px; border: 1px solid var(--border); color: var(--muted);
color: var(--muted);
} }
.dot { width: 9px; height: 9px; border-radius: 50%; } .dot { width: 9px; height: 9px; border-radius: 50%; }
.dot.on { background: var(--success); box-shadow: 0 0 10px rgba(46,204,113,0.7); } .dot.on { background: var(--success); box-shadow: 0 0 10px rgba(46,204,113,0.7); }
@@ -104,216 +104,292 @@
overflow: hidden; overflow: hidden;
} }
table { width: 100%; border-collapse: collapse; font-size: 0.9rem; } table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
thead { thead { background: radial-gradient(circle at top left,rgba(212,175,55,0.22),rgba(10,10,12,0.9)); }
background: radial-gradient(circle at top left,rgba(212,175,55,0.22),rgba(10,10,12,0.9));
}
th, td { th, td {
padding: 10px 16px; text-align: left; padding: 10px 16px; text-align: left;
border-bottom: 1px solid rgba(255,255,255,0.04); border-bottom: 1px solid rgba(255,255,255,0.04);
white-space: nowrap; white-space: nowrap;
} }
th { th { font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.12em; color: var(--muted); }
font-size: 0.78rem; text-transform: uppercase;
letter-spacing: 0.12em; color: var(--muted);
}
tbody tr:last-child td { border-bottom: none; } tbody tr:last-child td { border-bottom: none; }
tbody tr:hover { background: rgba(212,175,55,0.04); } tbody tr:hover { background: rgba(212,175,55,0.04); }
.name-cell { font-weight: 500; color: var(--text); } .name-cell { font-weight: 500; color: var(--text); }
.muted-cell { color: var(--muted); font-size: 0.82rem; } .muted-cell { color: var(--muted); font-size: 0.82rem; }
.align-center { text-align: center; } .align-center { text-align: center; }
.time-first { color: var(--text); font-weight: 500; }
.time-latest { color: var(--muted); font-size: 0.85rem; }
.same-badge { color: #555; font-size: 0.82rem; font-style: italic; }
.status-chip { .status-chip {
display: inline-flex; align-items: center; display: inline-flex; align-items: center; justify-content: center;
justify-content: center; min-width: 88px; min-width: 88px; padding: 5px 12px; border-radius: 999px;
padding: 5px 12px; border-radius: 999px;
font-size: 0.78rem; font-weight: 600; font-size: 0.78rem; font-weight: 600;
text-transform: uppercase; letter-spacing: 0.1em; text-transform: uppercase; letter-spacing: 0.1em;
} }
.status-on { .status-on { background: rgba(46,204,113,0.1); color: #c9f7dc; border: 1px solid rgba(46,204,113,0.65); box-shadow: 0 0 14px rgba(46,204,113,0.2); }
background: rgba(46,204,113,0.1); color: #c9f7dc; .status-off { background: rgba(255,77,79,0.1); color: #ffd6d7; border: 1px solid rgba(255,77,79,0.75); box-shadow: 0 0 14px rgba(255,77,79,0.2); }
border: 1px solid rgba(46,204,113,0.65);
box-shadow: 0 0 14px rgba(46,204,113,0.2);
}
.status-off {
background: rgba(255,77,79,0.1); color: #ffd6d7;
border: 1px solid rgba(255,77,79,0.75);
box-shadow: 0 0 14px rgba(255,77,79,0.2);
}
.chip-dot { width: 7px; height: 7px; border-radius: 50%; margin-right: 6px; background: currentColor; } .chip-dot { width: 7px; height: 7px; border-radius: 50%; margin-right: 6px; background: currentColor; }
.empty-state { .empty-state { padding: 28px 16px; text-align: center; color: var(--muted); font-size: 0.9rem; }
padding: 28px 16px; text-align: center;
color: var(--muted); font-size: 0.9rem;
}
.empty-state span { color: var(--gold-soft); } .empty-state span { color: var(--gold-soft); }
/* Modal */
.modal-overlay {
display: none; position: fixed; inset: 0;
background: rgba(0,0,0,0.75); backdrop-filter: blur(4px);
z-index: 100; align-items: center; justify-content: center;
}
.modal-overlay.open { display: flex; }
.modal {
background: var(--bg-card);
border: 1px solid rgba(255,100,100,0.5);
border-radius: 16px; padding: 28px 32px;
max-width: 400px; width: 90%; text-align: center;
box-shadow: 0 24px 60px rgba(0,0,0,0.8);
}
.modal h2 { color: var(--danger); font-size: 1.1rem; margin-bottom: 10px; text-transform: uppercase; letter-spacing: 0.08em; }
.modal p { color: var(--muted); font-size: 0.9rem; margin-bottom: 22px; line-height: 1.6; }
.modal p strong { color: var(--text); }
.modal-actions { display: flex; gap: 12px; justify-content: center; }
.modal-cancel {
border-color: rgba(255,255,255,0.15);
background: rgba(255,255,255,0.05);
}
.modal-confirm { border-color: rgba(255,100,100,0.6); background: rgba(255,80,80,0.18); }
/* Toast */
.toast { .toast {
position: fixed; bottom: 24px; right: 24px; position: fixed; bottom: 24px; right: 24px;
background: var(--bg-card); border: 1px solid rgba(212,175,55,0.5); background: var(--bg-card); border: 1px solid rgba(212,175,55,0.5);
border-radius: 12px; padding: 12px 18px; font-size: 0.85rem; border-radius: 12px; padding: 12px 18px; font-size: 0.85rem;
color: var(--gold); opacity: 0; transform: translateY(12px); color: var(--gold); opacity: 0; transform: translateY(12px);
transition: opacity 0.25s, transform 0.25s; transition: opacity 0.25s, transform 0.25s;
pointer-events: none; z-index: 99; pointer-events: none; z-index: 200;
} }
.toast.show { opacity: 1; transform: translateY(0); } .toast.show { opacity: 1; transform: translateY(0); }
@media (max-width: 720px) {
@media (max-width: 800px) {
header { flex-direction: column; align-items: flex-start; } header { flex-direction: column; align-items: flex-start; }
.controls { flex-direction: column; align-items: stretch; } .controls { flex-direction: column; align-items: stretch; }
input, select, button { width: 100%; } input, button { width: 100%; }
th:nth-child(3), td:nth-child(3),
th:nth-child(4), td:nth-child(4) { display: none; } th:nth-child(4), td:nth-child(4) { display: none; }
} }
</style> </style>
</head> </head>
<body> <body>
<div class="app-shell"> <div class="app-shell">
<header>
<div class="title-block">
<h1>Building Access</h1>
<div class="subtitle">Daily badge-in attendance — powered by UniFi Access</div>
</div>
<div class="badge">LIVE ATTENDANCE DASHBOARD</div>
</header>
<section class="controls"> <header>
<div class="control-group"> <div class="title-block">
<label for="date">Date</label> <h1>Building Access</h1>
<input type="date" id="date" /> <div class="subtitle">Daily badge-in attendance — powered by UniFi Access</div>
</div> </div>
<div class="control-group"> <div class="badge">LIVE ATTENDANCE DASHBOARD</div>
<label for="cutoff">Badged in by</label> </header>
<input type="time" id="cutoff" value="09:00" />
</div>
<div class="control-group">
<button id="refresh-btn">&#8635; Refresh</button>
<button class="sync-btn" id="sync-btn" title="Sync user list from UniFi Access API">&#8635; Sync Users</button>
</div>
</section>
<section class="summary-row"> <section class="controls">
<div class="summary-pill"><div class="dot on"></div><span id="on-time-count">0 on time</span></div> <div class="control-group">
<div class="summary-pill"><div class="dot off"></div><span id="late-count">0 late</span></div> <label for="date">Date</label>
<div class="summary-pill"><div class="dot all"></div><span id="total-count">0 total</span></div> <input type="date" id="date" />
</section> </div>
<div class="control-group">
<label for="cutoff">Badged in by</label>
<input type="time" id="cutoff" value="09:00" />
</div>
<div class="spacer"></div>
<div class="control-group">
<button id="refresh-btn">&#8635; Refresh</button>
<button class="sync-btn" id="sync-btn">&#8635; Sync Users</button>
<button class="reset-btn" id="reset-btn">&#x2715; Reset Day</button>
</div>
</section>
<section class="table-card"> <section class="summary-row">
<table> <div class="summary-pill"><div class="dot on"></div><span id="on-time-count">0 on time</span></div>
<thead> <div class="summary-pill"><div class="dot off"></div><span id="late-count">0 late</span></div>
<tr> <div class="summary-pill"><div class="dot all"></div><span id="total-count">0 total</span></div>
<th>#</th> </section>
<th>Name</th>
<th>Badge Time</th> <section class="table-card">
<th>Actor ID</th> <table>
<th class="align-center">Status</th> <thead>
</tr> <tr>
</thead> <th>#</th>
<tbody id="table-body"> <th>Name</th>
<tr><td colspan="5" class="empty-state">No data yet. <span>Badge into a door</span> and press Refresh.</td></tr> <th>First Badge In</th>
</tbody> <th>Latest Badge In</th>
</table> <th>Actor ID</th>
</section> <th class="align-center">Status</th>
</tr>
</thead>
<tbody id="table-body">
<tr><td colspan="6" class="empty-state">No data yet. <span>Badge into a door</span> and press Refresh.</td></tr>
</tbody>
</table>
</section>
</div>
<!-- Reset confirmation modal -->
<div class="modal-overlay" id="reset-modal">
<div class="modal">
<h2>&#9888; Reset Day</h2>
<p>This will permanently delete all badge-in records for <strong id="modal-date-label"></strong>.<br/>Use this for testing only.</p>
<div class="modal-actions">
<button class="modal-cancel" id="modal-cancel">Cancel</button>
<button class="modal-confirm" id="modal-confirm">Yes, Reset</button>
</div>
</div> </div>
</div>
<div class="toast" id="toast"></div> <div class="toast" id="toast"></div>
<script> <script>
function isoToday() { function isoToday() {
return new Date().toISOString().slice(0, 10); return new Date().toISOString().slice(0, 10);
}
function showToast(msg, duration = 3000) {
const t = document.getElementById('toast');
t.textContent = msg;
t.classList.add('show');
clearTimeout(t._timer);
t._timer = setTimeout(() => t.classList.remove('show'), duration);
}
async function loadData() {
const date = document.getElementById('date').value || isoToday();
const cutoff = document.getElementById('cutoff').value || '09:00';
const params = new URLSearchParams({ date, cutoff });
let data = [];
try {
const res = await fetch('/api/first-badge-status?' + params.toString());
data = await res.json();
} catch {
showToast('⚠ Could not load data');
return;
} }
function showToast(msg, duration = 2800) { const tbody = document.getElementById('table-body');
const t = document.getElementById('toast'); tbody.innerHTML = '';
t.textContent = msg;
t.classList.add('show');
setTimeout(() => t.classList.remove('show'), duration);
}
async function loadData() { if (!data.length) {
const date = document.getElementById('date').value || isoToday(); tbody.innerHTML = '<tr><td colspan="6" class="empty-state">No badge-in records for this day.</td></tr>';
const cutoff = document.getElementById('cutoff').value || '09:00'; ['on-time-count','late-count','total-count'].forEach(id => {
const params = new URLSearchParams({ date, cutoff }); document.getElementById(id).textContent = id === 'total-count' ? '0 total' : id === 'on-time-count' ? '0 on time' : '0 late';
let data = [];
try {
const res = await fetch('/api/first-badge-status?' + params.toString());
data = await res.json();
} catch (err) {
showToast('⚠ Could not load data');
return;
}
const tbody = document.getElementById('table-body');
tbody.innerHTML = '';
if (!data.length) {
tbody.innerHTML = '<tr><td colspan="5" class="empty-state">No badge-in records for this day.</td></tr>';
document.getElementById('on-time-count').textContent = '0 on time';
document.getElementById('late-count').textContent = '0 late';
document.getElementById('total-count').textContent = '0 total';
return;
}
let onTime = 0, late = 0;
data.forEach((row, i) => {
const tr = document.createElement('tr');
const numTd = document.createElement('td');
numTd.className = 'muted-cell';
numTd.textContent = i + 1;
tr.appendChild(numTd);
const nameTd = document.createElement('td');
nameTd.className = 'name-cell';
nameTd.textContent = row.actor_name || '(Unknown)';
tr.appendChild(nameTd);
const timeTd = document.createElement('td');
timeTd.textContent = row.badge_time || '';
tr.appendChild(timeTd);
const idTd = document.createElement('td');
idTd.className = 'muted-cell';
idTd.textContent = row.actor_id ? row.actor_id.slice(0, 8) + '…' : '';
tr.appendChild(idTd);
const statusTd = document.createElement('td');
statusTd.className = 'align-center';
const chip = document.createElement('div');
chip.className = 'status-chip ' + (row.on_time ? 'status-on' : 'status-off');
chip.innerHTML = '<span class="chip-dot"></span>' + (row.on_time ? 'ON TIME' : 'LATE');
statusTd.appendChild(chip);
tr.appendChild(statusTd);
tbody.appendChild(tr);
row.on_time ? onTime++ : late++;
}); });
return;
document.getElementById('on-time-count').textContent = onTime + ' on time';
document.getElementById('late-count').textContent = late + ' late';
document.getElementById('total-count').textContent = (onTime + late) + ' total';
} }
async function syncUsers() { let onTime = 0, late = 0;
const btn = document.getElementById('sync-btn');
btn.textContent = '⏳ Syncing…'; data.forEach((row, i) => {
btn.disabled = true; const tr = document.createElement('tr');
try {
await fetch('/api/sync-users'); // # column
showToast('✔ User list synced from UniFi Access'); const numTd = document.createElement('td');
await loadData(); numTd.className = 'muted-cell';
} catch { numTd.textContent = i + 1;
showToast('⚠ Sync failed — check server logs'); tr.appendChild(numTd);
} finally {
btn.textContent = '↻ Sync Users'; // Name
btn.disabled = false; const nameTd = document.createElement('td');
nameTd.className = 'name-cell';
nameTd.textContent = row.actor_name || '(Unknown)';
tr.appendChild(nameTd);
// First badge in (always show bold)
const firstTd = document.createElement('td');
firstTd.className = 'time-first';
firstTd.textContent = row.badge_time;
tr.appendChild(firstTd);
// Latest badge in (show dashes if same as first)
const latestTd = document.createElement('td');
if (row.latest_time === row.badge_time) {
latestTd.className = 'same-badge';
latestTd.textContent = '— same';
} else {
latestTd.className = 'time-latest';
latestTd.textContent = row.latest_time;
} }
} tr.appendChild(latestTd);
document.getElementById('refresh-btn').addEventListener('click', loadData); // Actor ID (truncated)
document.getElementById('sync-btn').addEventListener('click', syncUsers); const idTd = document.createElement('td');
idTd.className = 'muted-cell';
idTd.textContent = row.actor_id ? row.actor_id.slice(0, 8) + '…' : '';
tr.appendChild(idTd);
window.addEventListener('load', () => { // Status chip
const dateInput = document.getElementById('date'); const statusTd = document.createElement('td');
if (!dateInput.value) dateInput.value = isoToday(); statusTd.className = 'align-center';
loadData(); const chip = document.createElement('div');
chip.className = 'status-chip ' + (row.on_time ? 'status-on' : 'status-off');
chip.innerHTML = '<span class="chip-dot"></span>' + (row.on_time ? 'ON TIME' : 'LATE');
statusTd.appendChild(chip);
tr.appendChild(statusTd);
tbody.appendChild(tr);
row.on_time ? onTime++ : late++;
}); });
</script>
document.getElementById('on-time-count').textContent = onTime + ' on time';
document.getElementById('late-count').textContent = late + ' late';
document.getElementById('total-count').textContent = (onTime + late) + ' total';
}
async function syncUsers() {
const btn = document.getElementById('sync-btn');
btn.textContent = '⏳ Syncing…'; btn.disabled = true;
try {
await fetch('/api/sync-users');
showToast('✔ User list synced from UniFi Access');
await loadData();
} catch {
showToast('⚠ Sync failed — check server logs');
} finally {
btn.textContent = '↻ Sync Users'; btn.disabled = false;
}
}
// ── Reset day modal ─────────────────────────────────────────────────────────
document.getElementById('reset-btn').addEventListener('click', () => {
const date = document.getElementById('date').value || isoToday();
document.getElementById('modal-date-label').textContent = date;
document.getElementById('reset-modal').classList.add('open');
});
document.getElementById('modal-cancel').addEventListener('click', () => {
document.getElementById('reset-modal').classList.remove('open');
});
document.getElementById('modal-confirm').addEventListener('click', async () => {
document.getElementById('reset-modal').classList.remove('open');
const date = document.getElementById('date').value || isoToday();
try {
const res = await fetch('/api/reset-day?date=' + date, { method: 'DELETE' });
const json = await res.json();
showToast(`✔ Reset complete — ${json.deleted} record(s) deleted for ${date}`);
await loadData();
} catch {
showToast('⚠ Reset failed — check server logs');
}
});
// Close modal on overlay click
document.getElementById('reset-modal').addEventListener('click', e => {
if (e.target === document.getElementById('reset-modal'))
document.getElementById('reset-modal').classList.remove('open');
});
document.getElementById('refresh-btn').addEventListener('click', loadData);
document.getElementById('sync-btn').addEventListener('click', syncUsers);
window.addEventListener('load', () => {
const dateInput = document.getElementById('date');
if (!dateInput.value) dateInput.value = isoToday();
loadData();
});
</script>
</body> </body>
</html> </html>