Files
jobboard/app/web/static/app.js
T
WolfandClaude Opus 5.5 7a63311714 Rename the package roledesk to app
The boilerplate's rule: the deploy kit's Dockerfile, the APP_CONFIG,
APP_PASSWORD and APP_DATA variables and its commands all assume a package
called app, so a project renames its display title and nothing else. The
console script is `app`, and the launch entry runs `uv run app serve --port
8790`. The domain noun stays `role`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 12:30:10 +02:00

445 lines
15 KiB
JavaScript

// roledesk's page: the filter bar, the role list, the tracker, the search
// agents, and the tab switch between them. The template renders an empty shell (see index.html);
// everything on screen comes from the API, and every action — Save, an
// affinity click, a status change — is a fetch from here, not a form post.
"use strict";
const ROLES_URL = "/api/roles";
/** @type {Map<string, object>} company_key -> company row from /api/companies */
let companies = new Map();
/** @type {Map<string, object>} role_uid -> application row, for roles that are already tracked */
let trackedByRole = new Map();
/** @type {object[]} the last /api/roles response, already muted-filtered by the server */
let roles = [];
/** @type {object[]} every search agent, from /api/agents */
let agents = [];
const $ = (sel, root = document) => root.querySelector(sel);
const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));
function debounce(fn, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
async function api(path, options) {
const res = await fetch(path, options);
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.detail || `${path}: ${res.status}`);
}
return res.status === 204 ? null : res.json();
}
// ------------------------------------------------------------------ tabs
function initTabs() {
$$(".tab").forEach((tab) => {
tab.addEventListener("click", () => {
$$(".tab").forEach((t) => t.setAttribute("aria-pressed", String(t === tab)));
const name = tab.dataset.tab;
$("#roles-view").hidden = name !== "roles";
$("#applications-view").hidden = name !== "applications";
$("#agents-view").hidden = name !== "agents";
if (name === "applications") loadApplications();
if (name === "agents") loadAgents();
});
});
}
// ----------------------------------------------------------------- roles
function filterParams() {
const params = new URLSearchParams();
const q = $("#f-q").value.trim();
const company = $("#f-company").value.trim();
const place = $("#f-place").value.trim();
const fn = $("#f-function").value;
const remote = $("#f-remote").value;
const days = $("#f-days").value;
if (q) params.set("q", q);
if (company) params.set("company", company);
if (place) params.set("place", place);
if (fn) params.set("function", fn);
if (remote) params.set("remote", remote);
if (days) params.set("days", days);
if ($("#f-show-muted").checked) params.set("show_muted", "true");
const agent = $("#f-agent").value;
if (agent) {
params.set("agent", agent);
if ($("#f-gated").checked) params.set("gated", "1");
}
return params;
}
async function loadRoles() {
const params = filterParams();
roles = await api(`${ROLES_URL}?${params.toString()}`);
renderRoles();
}
function relativeAge(iso) {
const then = new Date(iso);
const minutes = Math.max(0, Math.floor((Date.now() - then.getTime()) / 60000));
if (minutes < 60) return `${minutes} min ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours} h ago`;
const days = Math.floor(hours / 24);
return `${days} d ago`;
}
function renderRoles() {
const list = $("#roles-list");
const template = $("#role-row");
list.replaceChildren();
for (const role of roles) {
const node = template.content.cloneNode(true);
const li = node.querySelector(".role");
const company = companies.get(role.company_key);
if (company && company.affinity === -1) li.classList.add("muted");
const titleLink = node.querySelector(".role-title");
titleLink.textContent = role.title || "(untitled)";
titleLink.href = role.original_url || "#";
node.querySelector(".role-company").textContent = role.company || "";
node.querySelector(".role-place").textContent = role.place || "";
node.querySelector(".role-remote").textContent = role.remote || "";
node.querySelector(".role-function").textContent = role.function || "";
node.querySelector(".role-age").textContent = relativeAge(role.first_seen);
if (role.score !== null && role.score !== undefined) {
const badge = node.querySelector(".role-score");
badge.textContent = role.gated_reason ? "gated" : role.score.toFixed(2);
badge.title = "Score for the selected agent";
node.querySelector(".role-gated").textContent = role.gated_reason || "";
if (role.gated_reason) li.classList.add("gated");
}
node.querySelector(".affinity").replaceWith(
affinityControl(role.company_key, company ? company.affinity : 0));
const saveButton = node.querySelector(".save");
setSaveButton(saveButton, role.uid);
saveButton.addEventListener("click", () => saveRole(role.uid, saveButton));
list.appendChild(node);
}
$("#roles-count").textContent = `${roles.length} role${roles.length === 1 ? "" : "s"}`;
}
function setSaveButton(button, uid) {
const saved = trackedByRole.has(uid);
button.textContent = saved ? "Saved" : "Save";
button.disabled = saved;
}
async function saveRole(uid, button) {
button.disabled = true;
button.textContent = "Saving…";
try {
const application = await api("/api/applications", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ role_uid: uid, status: "saved" }),
});
trackedByRole.set(uid, application);
setSaveButton(button, uid);
} catch (err) {
button.disabled = false;
button.textContent = "Save";
console.error(err);
}
}
// -------------------------------------------------------------- affinity
const AFFINITY_LEVELS = [
{ value: -1, label: "Mute" },
{ value: 0, label: "Neutral" },
{ value: 1, label: "Like" },
{ value: 2, label: "Favourite" },
];
function affinityControl(companyKey, current) {
const span = document.createElement("span");
span.className = "affinity";
span.setAttribute("role", "group");
span.setAttribute("aria-label", "Company affinity");
for (const level of AFFINITY_LEVELS) {
const button = document.createElement("button");
button.type = "button";
button.dataset.value = String(level.value);
button.textContent = level.label[0];
button.title = level.label;
button.setAttribute("aria-label", level.label);
button.setAttribute("aria-pressed", String(level.value === current));
button.addEventListener("click", () => setAffinity(companyKey, level.value));
span.appendChild(button);
}
return span;
}
async function setAffinity(companyKey, affinity) {
if (!companyKey) return;
try {
const updated = await api(`/api/companies/${encodeURIComponent(companyKey)}/affinity`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ affinity }),
});
const company = companies.get(companyKey);
if (company) company.affinity = updated.affinity;
// Muting or unmuting changes which roles the server hands back, so the
// list is refetched rather than just re-rendered from what is on hand.
await loadRoles();
} catch (err) {
console.error(err);
}
}
// ------------------------------------------------------------ applications
// `ROLEDESK_STATUSES` is set by index.html from the same `STATUSES` tuple
// the store validates against, so this list can never drift from what a
// `POST .../status` will actually accept.
function statusSelect(current) {
const select = document.createElement("select");
for (const status of window.ROLEDESK_STATUSES) {
const option = document.createElement("option");
option.value = status;
option.textContent = status[0].toUpperCase() + status.slice(1);
option.selected = status === current;
select.appendChild(option);
}
return select;
}
async function loadApplications() {
const applications = await api("/api/applications");
trackedByRole = new Map(applications.filter((a) => a.role_uid).map((a) => [a.role_uid, a]));
renderApplications(applications);
}
function renderApplications(applications) {
const body = $("#applications-list");
body.replaceChildren();
for (const application of applications) {
const tr = document.createElement("tr");
const roleTd = document.createElement("td");
roleTd.dataset.label = "Role";
roleTd.textContent = application.role_title || "(untitled)";
tr.appendChild(roleTd);
const companyTd = document.createElement("td");
companyTd.dataset.label = "Company";
const company = companies.get(application.company_key);
companyTd.textContent = company ? company.name : application.company_key;
tr.appendChild(companyTd);
const statusTd = document.createElement("td");
statusTd.dataset.label = "Status";
const select = statusSelect(application.status);
select.addEventListener("change", () => setStatus(application.id, select.value));
statusTd.appendChild(select);
tr.appendChild(statusTd);
const nextTd = document.createElement("td");
nextTd.dataset.label = "Next";
nextTd.textContent = [application.next_action, application.next_date]
.filter(Boolean).join(" · ");
tr.appendChild(nextTd);
body.appendChild(tr);
}
$("#applications-count").textContent =
`${applications.length} tracked application${applications.length === 1 ? "" : "s"}`;
}
async function setStatus(id, status) {
try {
await api(`/api/applications/${encodeURIComponent(id)}/status`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ status }),
});
await loadApplications();
} catch (err) {
console.error(err);
}
}
// ---------------------------------------------------------------- agents
async function loadAgents() {
agents = await api("/api/agents");
renderAgentSelect();
renderAgents();
}
// The filter bar's order: "Newest", or one agent's score. Keeps the current
// choice when the list is refreshed, unless that agent is gone.
function renderAgentSelect() {
const select = $("#f-agent");
const current = select.value;
select.replaceChildren(new Option("Newest", ""));
for (const agent of agents) {
const label = agent.enabled ? agent.name : `${agent.name} (off)`;
select.appendChild(new Option(label, String(agent.id)));
}
select.value = agents.some((a) => String(a.id) === current) ? current : "";
$("#show-gated").hidden = !select.value;
}
function renderAgents() {
const list = $("#agents-list");
list.replaceChildren();
for (const agent of agents) {
const li = document.createElement("li");
li.className = "agent";
const name = document.createElement("strong");
name.textContent = agent.name;
const meta = document.createElement("span");
meta.className = "agent-meta";
const gates = agent.gates.map((g) => `${g.mode} ${g.field}`).join(", ") || "no gates";
meta.textContent = `${agent.enabled ? "" : "off · "}${gates}`;
const edit = document.createElement("button");
edit.type = "button";
edit.textContent = "Edit";
edit.addEventListener("click", () => fillAgentForm(agent));
li.append(name, meta, edit);
list.appendChild(li);
}
$("#agents-count").textContent = `${agents.length} agent${agents.length === 1 ? "" : "s"}`;
}
function fillAgentForm(agent) {
$("#agent-form-title").textContent = agent ? `Edit ${agent.name}` : "New agent";
$("#a-id").value = agent ? String(agent.id) : "";
$("#a-name").value = agent ? agent.name : "";
$("#a-intent").value = agent ? agent.intent : "";
$("#a-gates").value = JSON.stringify(agent ? agent.gates : [], null, 2);
const weights = agent ? agent.weights : { fit: 0.6, recency: 0.2, affinity: 0.2 };
$("#a-fit").value = weights.fit;
$("#a-recency").value = weights.recency;
$("#a-affinity").value = weights.affinity;
$("#a-enabled").checked = agent ? agent.enabled : true;
$("#a-delete").hidden = !agent;
$("#agent-status").textContent = "";
}
async function saveAgent(event) {
event.preventDefault();
const status = $("#agent-status");
let gates;
try {
gates = JSON.parse($("#a-gates").value || "[]");
} catch (err) {
status.textContent = `Gates are not valid JSON: ${err.message}`;
return;
}
const id = $("#a-id").value;
const body = {
name: $("#a-name").value.trim(),
intent: $("#a-intent").value,
gates,
weights: {
fit: Number($("#a-fit").value),
recency: Number($("#a-recency").value),
affinity: Number($("#a-affinity").value),
},
enabled: $("#a-enabled").checked,
};
if (id) body.id = Number(id);
try {
const saved = await api("/api/agents", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
await loadAgents();
fillAgentForm(saved);
await rescore(status);
} catch (err) {
status.textContent = err.message;
}
}
async function deleteAgent() {
const id = $("#a-id").value;
if (!id || !confirm("Delete this agent and its scores?")) return;
try {
await api(`/api/agents/${encodeURIComponent(id)}`, { method: "DELETE" });
fillAgentForm(null);
await loadAgents();
await loadRoles();
} catch (err) {
$("#agent-status").textContent = err.message;
}
}
// Start the `score` job and refetch the roles once it has finished, so the
// order on the Roles tab is the saved agent's.
async function rescore(status) {
status.textContent = "Saved. Scoring…";
const job = await api("/api/jobs", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ kind: "score", payload: {} }),
});
for (let i = 0; i < 300; i += 1) {
await new Promise((resolve) => setTimeout(resolve, 1000));
const snapshot = await api("/api/jobs");
const busy = [...snapshot.running, ...snapshot.queued].some((j) => j.id === job.id);
if (!busy) {
const done = snapshot.recent.find((j) => j.id === job.id);
status.textContent = done && done.state !== "done"
? `Scoring ${done.state}: ${done.error || ""}`
: "Saved and scored.";
await loadRoles();
return;
}
}
status.textContent = "Saved. Scoring is still running; see Jobs below.";
}
// -------------------------------------------------------------------- init
async function loadCompanies() {
const rows = await api("/api/companies");
companies = new Map(rows.map((c) => [c.key, c]));
}
async function init() {
initTabs();
await Promise.all([loadCompanies(), loadApplications(), loadAgents()]);
await loadRoles();
const refetch = debounce(loadRoles, 300);
$("#f-q").addEventListener("input", refetch);
$("#f-company").addEventListener("input", refetch);
$("#f-place").addEventListener("input", refetch);
$("#f-function").addEventListener("change", loadRoles);
$("#f-remote").addEventListener("change", loadRoles);
$("#f-days").addEventListener("change", loadRoles);
$("#f-show-muted").addEventListener("change", loadRoles);
$("#f-agent").addEventListener("change", () => {
$("#show-gated").hidden = !$("#f-agent").value;
loadRoles();
});
$("#f-gated").addEventListener("change", loadRoles);
$("#agent-form").addEventListener("submit", saveAgent);
$("#a-new").addEventListener("click", () => fillAgentForm(null));
$("#a-delete").addEventListener("click", deleteAgent);
$("#filters").addEventListener("submit", (e) => e.preventDefault());
}
document.addEventListener("DOMContentLoaded", init);