Expand tracker analytics and dashboard UX
This commit is contained in:
+201
-15
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from "vue";
|
||||
import { computed, nextTick, onMounted, reactive, ref, watch } from "vue";
|
||||
import { useRoute } from "vue-router";
|
||||
import { api, type Device } from "../api";
|
||||
import { api, type AdminGoal, type Device, type NotificationSettings, type Report } from "../api";
|
||||
import CodeBlock from "../components/CodeBlock.vue";
|
||||
import Collector from "../components/Collector.vue";
|
||||
import KeyBox from "../components/KeyBox.vue";
|
||||
@@ -14,6 +14,17 @@ const loaded = ref(false);
|
||||
const status = ref<{ msg: string; cls?: string }>({ msg: "" });
|
||||
const active = computed(() => devices.value.filter(d => !d.revoked_at));
|
||||
const revoked = computed(() => devices.value.filter(d => d.revoked_at));
|
||||
const goals = ref<AdminGoal[]>([]);
|
||||
const goalLoaded = ref(false);
|
||||
const goalForm = reactive({ kind: "tab_focus", label: "", op: ">=", target: "30m" });
|
||||
const editingGoal = ref<number | null>(null);
|
||||
const goalBusy = ref(false);
|
||||
const pendingRevoke = ref<Device | null>(null);
|
||||
const revokeCancel = ref<HTMLButtonElement>();
|
||||
const reports = ref<Report[]>([]);
|
||||
const notifications = reactive<NotificationSettings>({ ntfy_server: "https://ntfy.sh", ntfy_topic: "", enabled: false, retention_days: 0 });
|
||||
const purgeBefore = ref(new Date(Date.now() - 90 * 86400000).toISOString().slice(0, 10));
|
||||
const privacyBusy = ref(false);
|
||||
|
||||
// Which collector sections are open: the browser's by default, and the one a
|
||||
// #section in the URL names.
|
||||
@@ -45,6 +56,24 @@ function ago(t?: string | null) {
|
||||
return new Date(t).toLocaleDateString([], { day: "numeric", month: "short", year: "numeric" });
|
||||
}
|
||||
|
||||
function deviceStatus(d: Device) {
|
||||
if (d.revoked_at) return { label: "Revoked", cls: "bad" };
|
||||
if (!d.last_seen_at) return { label: "Never seen", cls: "warn" };
|
||||
const age = Date.now() - +new Date(d.last_seen_at);
|
||||
return age < 2 * 86400000 ? { label: "Healthy", cls: "good" } : { label: "Stale", cls: "warn" };
|
||||
}
|
||||
|
||||
function parseDuration(value: string) {
|
||||
const m = value.trim().match(/^(?:(\d+(?:\.\d+)?)h)?\s*(?:(\d+(?:\.\d+)?)m)?\s*(?:(\d+(?:\.\d+)?)s)?$/i);
|
||||
if (!m || !m[1] && !m[2] && !m[3]) return 0;
|
||||
return Math.round((Number(m[1] || 0) * 3600) + (Number(m[2] || 0) * 60) + Number(m[3] || 0));
|
||||
}
|
||||
|
||||
function formatDuration(s: number) {
|
||||
const h = Math.floor(s / 3600), m = Math.floor(s % 3600 / 60), sec = s % 60;
|
||||
return h ? `${h}h${m ? ` ${m}m` : ""}` : m ? `${m}m${sec ? ` ${sec}s` : ""}` : `${sec}s`;
|
||||
}
|
||||
|
||||
async function loadDevices() {
|
||||
try {
|
||||
({ devices: devices.value } = await api<{ devices: Device[] }>("GET", "devices"));
|
||||
@@ -53,7 +82,26 @@ async function loadDevices() {
|
||||
status.value = { msg: (e as Error).message, cls: "err" };
|
||||
}
|
||||
}
|
||||
onMounted(loadDevices);
|
||||
async function loadGoals() {
|
||||
try {
|
||||
const out = await api<{ goals: AdminGoal[] }>("GET", "goals");
|
||||
goals.value = out.goals;
|
||||
goalLoaded.value = true;
|
||||
} catch (e) {
|
||||
status.value = { msg: (e as Error).message, cls: "err" };
|
||||
}
|
||||
}
|
||||
async function loadAdminData() {
|
||||
try {
|
||||
const [notification, reportList] = await Promise.all([
|
||||
api<{ settings: NotificationSettings }>("GET", "notifications/status"),
|
||||
api<{ reports: Report[] }>("GET", "reports"),
|
||||
]);
|
||||
Object.assign(notifications, notification.settings);
|
||||
reports.value = reportList.reports;
|
||||
} catch (e) { status.value = { msg: (e as Error).message, cls: "err" }; }
|
||||
}
|
||||
onMounted(() => { loadDevices(); loadGoals(); loadAdminData(); });
|
||||
|
||||
// A readable name that isn't taken yet (names stay taken after revoking).
|
||||
function suggestName(kind: string) {
|
||||
@@ -93,36 +141,124 @@ async function create() {
|
||||
}
|
||||
|
||||
async function revoke(name: string) {
|
||||
if (!confirm(`Revoke ${name}? Its collector will stop being able to upload.`)) return;
|
||||
pendingRevoke.value = devices.value.find(d => d.name === name) || null;
|
||||
}
|
||||
|
||||
watch(pendingRevoke, value => { if (value) nextTick(() => revokeCancel.value?.focus()); });
|
||||
|
||||
async function confirmRevoke() {
|
||||
const device = pendingRevoke.value;
|
||||
if (!device) return;
|
||||
try {
|
||||
await api("DELETE", "devices/" + encodeURIComponent(name));
|
||||
status.value = { msg: `Revoked ${name}.`, cls: "ok" };
|
||||
await api("DELETE", "devices/" + encodeURIComponent(device.name));
|
||||
status.value = { msg: `Revoked ${device.name}.`, cls: "ok" };
|
||||
pendingRevoke.value = null;
|
||||
loadDevices();
|
||||
} catch (e) {
|
||||
status.value = { msg: (e as Error).message, cls: "err" };
|
||||
}
|
||||
}
|
||||
|
||||
async function addGoal() {
|
||||
const target_s = parseDuration(goalForm.target);
|
||||
if (!goalForm.kind.trim() || target_s <= 0) { status.value = { msg: "Enter a kind and a duration such as 30m or 1h.", cls: "err" }; return; }
|
||||
goalBusy.value = true;
|
||||
try {
|
||||
const body = { kind: goalForm.kind.trim(), label: goalForm.label.trim(), op: goalForm.op, target_s };
|
||||
if (editingGoal.value === null) {
|
||||
const out = await api<AdminGoal>("POST", "goals", body);
|
||||
goals.value.push(out);
|
||||
status.value = { msg: "Goal added.", cls: "ok" };
|
||||
} else {
|
||||
const out = await api<AdminGoal>("PUT", "goals/" + encodeURIComponent(String(editingGoal.value)), body);
|
||||
goals.value = goals.value.map(g => g.id === editingGoal.value ? out : g);
|
||||
status.value = { msg: "Goal updated.", cls: "ok" };
|
||||
}
|
||||
resetGoalForm();
|
||||
} catch (e) { status.value = { msg: (e as Error).message, cls: "err" }; }
|
||||
finally { goalBusy.value = false; }
|
||||
}
|
||||
|
||||
function editGoal(goal: AdminGoal) {
|
||||
editingGoal.value = goal.id;
|
||||
goalForm.kind = goal.kind;
|
||||
goalForm.label = goal.label;
|
||||
goalForm.op = goal.op;
|
||||
goalForm.target = formatDuration(goal.target_s).replace(" ", "");
|
||||
}
|
||||
|
||||
function resetGoalForm() {
|
||||
editingGoal.value = null;
|
||||
goalForm.kind = "tab_focus";
|
||||
goalForm.label = "";
|
||||
goalForm.op = ">=";
|
||||
goalForm.target = "30m";
|
||||
}
|
||||
|
||||
async function removeGoal(goal: AdminGoal) {
|
||||
try {
|
||||
await api("DELETE", "goals/" + encodeURIComponent(String(goal.id)));
|
||||
goals.value = goals.value.filter(g => g.id !== goal.id);
|
||||
status.value = { msg: "Goal removed.", cls: "ok" };
|
||||
} catch (e) { status.value = { msg: (e as Error).message, cls: "err" }; }
|
||||
}
|
||||
|
||||
async function saveNotifications() {
|
||||
privacyBusy.value = true;
|
||||
try {
|
||||
Object.assign(notifications, await api<NotificationSettings>("PUT", "notifications/config", notifications));
|
||||
status.value = { msg: "Notification and retention settings saved.", cls: "ok" };
|
||||
} catch (e) { status.value = { msg: (e as Error).message, cls: "err" }; }
|
||||
finally { privacyBusy.value = false; }
|
||||
}
|
||||
|
||||
async function purgeData() {
|
||||
if (!purgeBefore.value) return;
|
||||
privacyBusy.value = true;
|
||||
try {
|
||||
const before = new Date(purgeBefore.value + "T00:00:00").toISOString();
|
||||
const out = await api<{ deleted: number }>("POST", "privacy/purge?before=" + encodeURIComponent(before));
|
||||
status.value = { msg: `Deleted ${out.deleted} records before ${purgeBefore.value}.`, cls: "ok" };
|
||||
} catch (e) { status.value = { msg: (e as Error).message, cls: "err" }; }
|
||||
finally { privacyBusy.value = false; }
|
||||
}
|
||||
|
||||
const setupProgress = computed(() => {
|
||||
const done = [active.value.length > 0, goals.value.length > 0, active.value.some(d => d.last_seen_at)].filter(Boolean).length;
|
||||
return { done, total: 3 };
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<h1>Setup</h1>
|
||||
<p class="muted">Each collector uploads to <code>{{ base }}</code> with its own API key. Open a collector below and click <b>Generate key</b>; the key is filled into its steps. A key is shown only once.</p>
|
||||
|
||||
<section class="card" aria-labelledby="progress-title">
|
||||
<div class="row spread"><h2 id="progress-title">Getting started</h2><span class="badge">{{ setupProgress.done }}/{{ setupProgress.total }} complete</span></div>
|
||||
<ol class="setup-progress">
|
||||
<li :class="{ ok: active.length }"><b>{{ active.length ? "Device created" : "Create a device key" }}</b><span class="muted"> Generate a key below, then follow that collector's instructions.</span></li>
|
||||
<li :class="{ ok: goals.length }"><b>{{ goals.length ? "Goals configured" : "Add a daily goal" }}</b><span class="muted"> Optional targets are managed here and appear on the dashboard.</span></li>
|
||||
<li :class="{ ok: active.some(d => d.last_seen_at) }"><b>{{ active.some(d => d.last_seen_at) ? "First upload received" : "Check device health" }}</b><span class="muted"> A healthy device has uploaded in the last two days.</span></li>
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="row spread"><h2>Devices</h2></div>
|
||||
<div class="tablewrap"><table>
|
||||
<tr v-if="!loaded"><td class="muted">Loading…</td></tr>
|
||||
<template v-else>
|
||||
<tr><th>Name</th><th>Kind</th><th>Last upload</th><th></th></tr>
|
||||
<caption class="sr-only">Collector devices and upload health</caption>
|
||||
<thead><tr><th scope="col">Name</th><th scope="col">Kind</th><th scope="col">Health</th><th scope="col">Last upload</th><th scope="col"><span class="sr-only">Actions</span></th></tr></thead>
|
||||
<tbody v-if="!loaded"><tr><td colspan="5" class="muted">Loading…</td></tr></tbody>
|
||||
<tbody v-else>
|
||||
<tr v-for="d in active" :key="d.name">
|
||||
<td class="label">{{ d.name }}</td>
|
||||
<td><span class="badge">{{ d.kind }}</span></td>
|
||||
<td><span class="status-dot" :class="deviceStatus(d).cls"></span>{{ deviceStatus(d).label }}</td>
|
||||
<td class="time">{{ ago(d.last_seen_at) }}</td>
|
||||
<td class="num"><button class="small" @click="revoke(d.name)">Revoke</button></td>
|
||||
</tr>
|
||||
<tr v-if="!active.length"><td colspan="4" class="muted">No devices yet.</td></tr>
|
||||
<tr v-if="revoked.length"><td colspan="4" class="muted small-text">{{ revoked.length }} revoked: {{ revoked.map(d => d.name).join(", ") }}</td></tr>
|
||||
</template>
|
||||
<tr v-if="!active.length"><td colspan="5" class="muted">No devices yet.</td></tr>
|
||||
<tr v-if="revoked.length"><td colspan="5" class="muted small-text">{{ revoked.length }} revoked: {{ revoked.map(d => d.name).join(", ") }}</td></tr>
|
||||
</tbody>
|
||||
</table></div>
|
||||
<form class="row" style="margin-top:12px" @submit.prevent="create">
|
||||
<select v-model="kindSel" aria-label="Kind">
|
||||
@@ -137,6 +273,11 @@ async function revoke(name: string) {
|
||||
</form>
|
||||
<KeyBox v-if="issued?.slot === 'create'" :key="issued.key" :device="issued.device" :api-key="issued.key" />
|
||||
<p class="small-text" :class="status.cls">{{ status.msg }}</p>
|
||||
<div v-if="pendingRevoke" class="confirm" role="alertdialog" aria-modal="true" aria-labelledby="revoke-title" aria-describedby="revoke-copy" @keydown.esc="pendingRevoke = null">
|
||||
<h3 id="revoke-title">Revoke {{ pendingRevoke.name }}?</h3>
|
||||
<p id="revoke-copy">This stops the collector from uploading. Existing data is not deleted, but the key cannot be used again.</p>
|
||||
<div class="row"><button ref="revokeCancel" class="small" @click="pendingRevoke = null">Keep device</button><button class="small danger" @click="confirmRevoke">Revoke device</button></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<Collector id="browser" title="Browser" hint="Violentmonkey userscript · time per site" v-model:open="open.browser">
|
||||
@@ -144,7 +285,7 @@ async function revoke(name: string) {
|
||||
<button class="primary" :disabled="busy === 'browser'" @click="generate('browser', '', 'browser')">Generate key for this browser</button>
|
||||
<KeyBox v-if="issued?.slot === 'browser'" :key="issued.key" :device="issued.device" :api-key="issued.key" />
|
||||
<ol>
|
||||
<li>Install Violentmonkey: <a href="https://addons.mozilla.org/firefox/addon/violentmonkey/" target="_blank" rel="noopener">Firefox</a> · <a href="https://chromewebstore.google.com/detail/violentmonkey/jinjaccalgkegednnccohejagnlnfdag" target="_blank" rel="noopener">Chrome / Chromium</a></li>
|
||||
<li>Install Violentmonkey: <a href="https://addons.mozilla.org/firefox/addon/violentmonkey/" target="_blank" rel="noopener">Firefox <span class="sr-only">(opens in a new tab)</span></a> · <a href="https://chromewebstore.google.com/detail/violentmonkey/jinjaccalgkegednnccohejagnlnfdag" target="_blank" rel="noopener">Chrome / Chromium <span class="sr-only">(opens in a new tab)</span></a></li>
|
||||
<li>Open <a :href="base + '/tracker.user.js'">{{ base }}/tracker.user.js</a> and click <b>Install</b>. Violentmonkey checks this URL for updates.</li>
|
||||
<li>Click the Violentmonkey toolbar icon, then <b>Activity Tracker → Set server and API key</b>. Enter the server and key:
|
||||
<CodeBlock>{{ base }}</CodeBlock>
|
||||
@@ -223,10 +364,55 @@ listener {
|
||||
</Collector>
|
||||
|
||||
<Collector id="goals" title="Goals" hint="daily targets on the dashboard" v-model:open="open.goals">
|
||||
<p>Managed on the server. An empty label matches every label of that kind.</p>
|
||||
<p>Daily targets are managed here. An empty label matches every label of that kind. Durations accept values such as <code>30m</code>, <code>1h</code>, or <code>1h 30m</code>.</p>
|
||||
<form class="goal-form" @submit.prevent="addGoal">
|
||||
<label>Kind<input v-model="goalForm.kind" required placeholder="tab_focus"></label>
|
||||
<label>Label <span class="muted">(optional)</span><input v-model="goalForm.label" placeholder="youtube.com"></label>
|
||||
<label>Rule<select v-model="goalForm.op"><option value=">=">At least</option><option value="<=">At most</option></select></label>
|
||||
<label>Target per day<input v-model="goalForm.target" required placeholder="30m"></label>
|
||||
<div class="row"><button class="primary" :disabled="goalBusy">{{ goalBusy ? "Saving…" : editingGoal === null ? "Add goal" : "Save goal" }}</button><button v-if="editingGoal !== null" type="button" class="small" @click="resetGoalForm">Cancel</button></div>
|
||||
</form>
|
||||
<div class="tablewrap" v-if="goalLoaded || goals.length">
|
||||
<table>
|
||||
<caption class="sr-only">Configured daily goals</caption>
|
||||
<thead><tr><th scope="col">Kind</th><th scope="col">Label</th><th scope="col">Rule</th><th scope="col">Target</th><th scope="col"><span class="sr-only">Actions</span></th></tr></thead>
|
||||
<tbody><tr v-for="goal in goals" :key="goal.id"><td>{{ goal.kind }}</td><td>{{ goal.label || "Any label" }}</td><td>{{ goal.op === ">=" ? "At least" : "At most" }}</td><td>{{ formatDuration(goal.target_s) }}</td><td class="num"><button class="small" @click="editGoal(goal)">Edit</button> <button class="small" @click="removeGoal(goal)">Remove</button></td></tr><tr v-if="!goals.length"><td colspan="5" class="muted">No goals configured.</td></tr></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<CodeBlock>docker exec activity-tracker tracker goal add --kind tab_focus --label youtube.com --op '<=' --target 1h
|
||||
docker exec activity-tracker tracker goal add --kind walk --op '>=' --target 30m
|
||||
docker exec activity-tracker tracker goal list
|
||||
docker exec activity-tracker tracker goal rm --id 2</CodeBlock>
|
||||
docker exec activity-tracker tracker goal rm --id 2</CodeBlock>
|
||||
</Collector>
|
||||
|
||||
<section class="card" aria-labelledby="data-title">
|
||||
<div class="row spread"><h2 id="data-title">Data and notifications</h2><span class="badge">Admin only</span></div>
|
||||
<p class="muted small-text">Export your activity data, configure optional goal nudges, and control how long records are retained.</p>
|
||||
<div class="row data-actions">
|
||||
<a class="button-like" :href="base + '/api/v1/activities/export?format=csv'" download>Export activity CSV</a>
|
||||
<a class="button-like" :href="base + '/api/v1/activities/export?format=json'" download>Export activity JSON</a>
|
||||
</div>
|
||||
<form class="settings-form" @submit.prevent="saveNotifications">
|
||||
<label>ntfy server<input v-model="notifications.ntfy_server" placeholder="https://ntfy.sh"></label>
|
||||
<label>Topic<input v-model="notifications.ntfy_topic" placeholder="private-topic"></label>
|
||||
<label class="check"><input v-model="notifications.enabled" type="checkbox"> Enable goal nudges</label>
|
||||
<label>Retention days <span class="muted">(0 = keep forever)</span><input v-model.number="notifications.retention_days" type="number" min="0"></label>
|
||||
<button class="primary" :disabled="privacyBusy">Save settings</button>
|
||||
</form>
|
||||
<div class="privacy-tools">
|
||||
<h3>Delete old records</h3>
|
||||
<p class="muted small-text">This permanently deletes activities, samples, and reports before the selected date.</p>
|
||||
<form class="row" @submit.prevent="purgeData">
|
||||
<label>Delete before <input v-model="purgeBefore" type="date" required></label>
|
||||
<button class="danger" :disabled="privacyBusy">Delete records</button>
|
||||
</form>
|
||||
</div>
|
||||
<div v-if="reports.length" class="report-list">
|
||||
<h3>Saved insights</h3>
|
||||
<article v-for="report in reports.slice(0, 5)" :key="report.id" class="report">
|
||||
<div class="row spread"><b>{{ report.model }}</b><span class="muted small-text">{{ new Date(report.period_start).toLocaleDateString() }}–{{ new Date(report.period_end).toLocaleDateString() }}</span></div>
|
||||
<p>{{ report.body }}</p>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
Reference in New Issue
Block a user