diff --git a/app/static/app.css b/app/static/app.css index cd38c96..a85cd93 100644 --- a/app/static/app.css +++ b/app/static/app.css @@ -526,13 +526,21 @@ table.applications td[data-label="Saved"] { white-space: nowrap; color: var(--di .role-main .affinity { margin-left: auto; } .affinity button { background: none; border: 1px solid var(--line); border-radius: .3rem; - padding: .1rem .4rem; color: var(--dim); font-size: .85rem; line-height: 1.4; + padding: .1rem .4rem; color: var(--dim); font-size: 1rem; line-height: 1.4; } -.affinity button[aria-pressed="true"] { +/* One colour per stance, filled rather than tinted so "pressed" reads at a + glance (news's own reasoning for its vote buttons, app.css 1906-1930): + gold for favourite, the app's own accent for like, the error red for + hidden, since hiding a company is the one stance that keeps its roles out + of the list entirely. */ +.affinity button[data-value="2"][aria-pressed="true"] { + color: var(--accent-fg); background: var(--warn); border-color: var(--warn); +} +.affinity button[data-value="1"][aria-pressed="true"] { color: var(--accent-fg); background: var(--accent); border-color: var(--accent); } .affinity button[data-value="-1"][aria-pressed="true"] { - background: var(--error); border-color: var(--error); + color: var(--accent-fg); background: var(--error); border-color: var(--error); } /* agents */ @@ -567,14 +575,21 @@ table.applications td[data-label="Saved"] { white-space: nowrap; color: var(--di .agent-form details summary { cursor: pointer; color: var(--dim); font-size: .9rem; } .agent-form details[open] summary { margin-bottom: .5rem; } -/* sources */ +/* ================================================================ */ +/* companies and sources — Settings' Companies and Searches pages, */ +/* static/companies.js and static/sources.js. Package B2's own */ +/* section; the rest of the file is not reflowed for it. */ +/* ================================================================ */ .section { margin: 1.5rem 0 2rem; } .section > h2 { margin-bottom: .25rem; } -.source-form { margin-top: 1rem; } -.form-row { display: flex; gap: .75rem; flex-wrap: wrap; } -.form-row label { flex: 0 1 auto; } -.form-row label.grow { flex: 1 1 14rem; } +.source-form { margin-top: 1rem; max-width: none; } +/* `auto-fit` rather than a fixed count of columns: a row with fewer fields + (Jobindex's Area, say, where Adzuna also needs Country and Place) simply + leaves the boxes it does have at the same width instead of stretching one + to fill the gap, which is what made the boxes disagree with each other's + width before. */ +.form-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr)); gap: .75rem; align-items: start; } .source-form select { background: var(--bg); border: 1px solid var(--line); border-radius: .3rem; padding: .35rem .5rem; @@ -583,8 +598,46 @@ table.applications td[data-label="Saved"] { white-space: nowrap; color: var(--di .sample { margin: 0; padding-left: 1.25rem; font-size: .9rem; } .sample li { margin: .15rem 0; } .mono { font-family: var(--mono); overflow-wrap: anywhere; } -.row-actions { display: inline-flex; gap: .35rem; } -.row-actions button { padding: .25rem .6rem; } + +/* A row of a list that is not a table: Companies and Searches, after news's + `.srow` (app.css 659-665 and 783-787 there). Line one is the name and + whatever switch or controls belong beside it; `.sub`, muted and full width, + wraps onto its own line rather than sharing a column with them, which is + what keeps a long query or board name from crowding the switch at any + width — a table's fixed columns needed a breakpoint to do the same, a grid + with one column spanning the row does not. */ +.srows, .crows { display: flex; flex-direction: column; margin: .5rem 0 1.5rem; } +.srow, .crow { + display: grid; grid-template-columns: 1fr auto auto; + align-items: center; column-gap: .6rem; row-gap: .15rem; + padding: .5rem 0; border-bottom: 1px solid var(--line); +} +.srow .name, .crow .name { + grid-column: 1; display: flex; align-items: center; gap: .4rem; + font-size: .96rem; text-decoration: none; color: inherit; +} +.crow .name { font-weight: 600; } +@media (hover: hover) { + .crow .name:hover { text-decoration: underline; } +} +.srow .sub, .crow .sub { + grid-column: 1 / -1; display: flex; flex-wrap: wrap; align-items: center; + gap: .4rem; font-size: .8rem; color: var(--dim); +} +.srow[data-muted="true"], .crow[data-hidden="true"] { opacity: .6; } + +.linky { + padding: 0; border: 0; background: none; font-size: .8rem; + color: var(--dim); text-decoration: underline; text-underline-offset: 2px; +} +@media (hover: hover) { + .linky:hover { color: var(--fg); background: none; } +} + +/* The prune tool: folded under the list, since switching a board off by + region is an occasional errand and not what the page is for. */ +.prune > summary { cursor: pointer; color: var(--dim); font-weight: 600; } +.prune[open] > summary { margin-bottom: .75rem; } /* applications and companies */ @@ -670,6 +723,6 @@ table.list select { padding: .25rem .4rem; } .top nav a, .subtabs a { display: inline-flex; align-items: center; justify-content: center; } .filters input[type="search"], .filters input[type="text"], .filters select, .agent-form input, .source-form select { min-height: 2.75rem; } - .affinity button { min-width: 2.25rem; } + .affinity button { min-width: 2.75rem; } .check input { width: 1.25rem; height: 1.25rem; } } diff --git a/app/static/app.js b/app/static/app.js index 35d2d3b..b108b69 100644 --- a/app/static/app.js +++ b/app/static/app.js @@ -113,30 +113,36 @@ return companies; } + /* Three icon toggles, not four: there is no button for neutral, since + pressing the one that is already pressed is how a company gets back to + it. "Hidden" is the word for -1 everywhere the UI names it, even though + the code and the API keep `mute`/`hide_muted` — a rename in the store + and CLI is a separate, larger change than this control. */ const AFFINITY_LEVELS = [ - { value: -1, label: "Mute" }, - { value: 0, label: "Neutral" }, - { value: 1, label: "Like" }, - { value: 2, label: "Favourite" }, + { value: 2, icon: "★", label: "Favourite" }, // ★ + { value: 1, icon: "▲", label: "Like" }, // ▲ + { value: -1, icon: "⦸", label: "Hidden" }, // ⊘ ]; - /* The four buttons. `onChange` runs after the server accepted the change, - so each page decides what a change means for it: the role list refetches, - since muting changes which roles come back, and the company table redraws. */ + /* `onChange` runs after the server accepted the change, so each page + decides what a change means for it: the role list refetches, since a + hidden company's roles come out of it, and the company list redraws. */ function affinityControl(companyKey, current, onChange) { 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 pressed = level.value === current; const button = document.createElement("button"); button.type = "button"; button.dataset.value = String(level.value); - button.textContent = level.label[0]; + button.textContent = level.icon; 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, onChange)); + button.setAttribute("aria-pressed", String(pressed)); + button.addEventListener("click", () => + setAffinity(companyKey, pressed ? 0 : level.value, onChange)); span.appendChild(button); } return span; diff --git a/app/static/companies.js b/app/static/companies.js index 1a4b05a..9f7d1a2 100644 --- a/app/static/companies.js +++ b/app/static/companies.js @@ -1,42 +1,181 @@ -/* The Companies page: every company, its open roles, and its affinity. +/* The Companies page: every company, its board, its open roles, its + * affinity, following a new one, and pruning boards with nothing open in a + * region. * - * The list is app.js's shared company list, and the affinity buttons are its - * `affinityControl`, the same ones the Roles tab draws on every row. Filtering - * is done here, over the list already loaded. + * The list is app.js's shared company list (`/api/companies`), already + * joined with each company's board subscription — its id and whether it is + * on — so nothing here fetches `/api/sources` as well. The affinity buttons + * are `affinityControl`, the same ones the Roles tab and the read page draw. */ (function () { "use strict"; - const { count, cell, debounce, companies, loadCompanies, affinityControl } = window; + const { api, count, debounce, companies, loadCompanies, affinityControl } = window; const $ = (sel, root = document) => root.querySelector(sel); + // ---------------------------------------------------------------- the list + + function subLine(company) { + const sub = document.createElement("span"); + sub.className = "sub"; + if (company.board) { + const badge = document.createElement("span"); + badge.className = "badge"; + badge.textContent = company.board; + sub.appendChild(badge); + } else { + sub.append("from searches"); + } + sub.append(` · ${count(company.open_roles, "open role")}`); + return sub; + } + + /** The board switch, or nothing for a company known only from a search: + there is no subscription to switch. */ + function onSwitch(company, rerender) { + if (company.subscription_id == null) return null; + const box = document.createElement("input"); + box.type = "checkbox"; + box.checked = Boolean(company.on); + box.setAttribute("aria-label", `Read ${company.name}'s board`); + box.addEventListener("change", async () => { + box.disabled = true; + try { + const result = await api(`/api/sources/${company.subscription_id}/switch`, + { method: "POST", body: { on: box.checked } }); + company.on = result.source.on; + if (!box.checked && result.closed) { + window.toast.info(`${company.name}: ${count(result.closed, "open role")} closed.`); + } + } catch (err) { + box.checked = !box.checked; + } + box.disabled = false; + rerender(); + }); + return box; + } + + function matchesFilter(company, filter) { + switch (filter) { + case "favourite": return company.affinity === 2; + case "liked": return company.affinity === 1; + case "hidden": return company.affinity === -1; + case "on": return company.on === true; + case "off": return company.on === false; + default: return true; + } + } + function render() { const q = $("#c-q").value.trim().toLowerCase(); - const affinity = $("#c-affinity").value; + const filter = $("#c-filter").value; const rows = [...companies.values()] .filter((c) => !q || c.name.toLowerCase().includes(q) || c.board.includes(q)) - .filter((c) => affinity === "" || String(c.affinity) === affinity) + .filter((c) => matchesFilter(c, filter)) .sort((a, b) => b.open_roles - a.open_roles || a.name.localeCompare(b.name)); const body = $("#companies-list"); body.replaceChildren(); for (const company of rows) { - const tr = document.createElement("tr"); - if (company.affinity === -1) tr.classList.add("muted"); + const row = document.createElement("div"); + row.className = "crow"; + if (company.affinity === -1) row.dataset.hidden = "true"; const link = document.createElement("a"); + link.className = "name"; link.href = `/?company=${encodeURIComponent(company.name)}`; link.title = "This company's open roles"; link.textContent = company.name; - cell(tr, "Company", link); - cell(tr, "Board", company.board || ""); - cell(tr, "Open roles", String(company.open_roles)).className = "num"; - cell(tr, "Affinity", affinityControl(company.key, company.affinity, async () => render())); - body.appendChild(tr); + row.appendChild(link); + const switchBox = onSwitch(company, render); + if (switchBox) row.appendChild(switchBox); + row.appendChild(affinityControl(company.key, company.affinity, async () => render())); + row.appendChild(subLine(company)); + body.appendChild(row); } const open = rows.reduce((sum, c) => sum + c.open_roles, 0); $("#companies-count").textContent = `${count(rows.length, "company", "companies")}, ${count(open, "open role")}`; } + // -------------------------------------------------------------------- follow + + async function addBoard(event) { + event.preventDefault(); + const status = $("#board-status"); + const button = $("#board-form button[type=submit]"); + button.disabled = true; + status.textContent = "Reading the board once before following it…"; + const board = `${$("#b-host").value}:${$("#b-slug").value.trim()}`; + try { + const result = await api("/api/boards", { + method: "POST", + body: { board, name: $("#b-name").value.trim() }, + }); + await loadCompanies(); + render(); + $("#board-form").reset(); + status.textContent = `Following ${result.source.label}: ` + + `${count(result.found, "role")} listed. They arrive with the next pull.`; + } catch (err) { + status.textContent = ""; + } + button.disabled = false; + } + + // -------------------------------------------------------------------- prune + + /** @type {object[]} the boards the last preview named. */ + let pruneBoards = []; + + async function previewPrune(event) { + event.preventDefault(); + const status = $("#prune-status"); + const list = $("#prune-list"); + const region = $("#p-region").value.trim(); + list.replaceChildren(); + $("#p-apply").disabled = true; + $("#p-apply").textContent = "Switch off these boards"; + status.textContent = "Checking every board…"; + try { + const result = await api(`/api/prune?region=${encodeURIComponent(region)}`); + pruneBoards = result.boards; + const roles = pruneBoards.reduce((sum, b) => sum + b.open_roles, 0); + status.textContent = pruneBoards.length + ? `${count(pruneBoards.length, "board")} with no open role in ${region}, ` + + `${count(roles, "open role")} between them:` + : `Every board that is on has a role in ${region}.`; + for (const board of pruneBoards) { + const li = document.createElement("li"); + li.textContent = `${board.label} (${board.target}), ${count(board.open_roles, "open role")}`; + list.appendChild(li); + } + $("#p-apply").disabled = pruneBoards.length === 0; + $("#p-apply").textContent = `Switch off these ${count(pruneBoards.length, "board")}`; + } catch (err) { + status.textContent = ""; + } + } + + async function applyPrune() { + const region = $("#p-region").value.trim(); + if (!window.confirm(`Switch off ${count(pruneBoards.length, "board")} and close their roles? ` + + "Each can be switched back on in the list above.")) return; + $("#p-apply").disabled = true; + try { + const result = await api("/api/prune", { method: "POST", body: { region } }); + $("#prune-status").textContent = `Switched off ${count(result.pruned, "board")}, ` + + `closed ${count(result.roles_closed, "role")}. ${result.boards_left} boards are on.`; + $("#prune-list").replaceChildren(); + $("#p-apply").textContent = "Switch off these boards"; + await loadCompanies(); + render(); + } catch (err) { + $("#p-apply").disabled = false; + } + } + + // -------------------------------------------------------------------- init + document.addEventListener("DOMContentLoaded", async () => { try { await loadCompanies(); @@ -45,6 +184,9 @@ } render(); $("#c-q").addEventListener("input", debounce(render, 150)); - $("#c-affinity").addEventListener("change", render); + $("#c-filter").addEventListener("change", render); + $("#board-form").addEventListener("submit", addBoard); + $("#prune-form").addEventListener("submit", previewPrune); + $("#p-apply").addEventListener("click", applyPrune); }); })(); diff --git a/app/static/sources.js b/app/static/sources.js index ac3d030..544f4e4 100644 --- a/app/static/sources.js +++ b/app/static/sources.js @@ -1,21 +1,20 @@ -/* The Searches page under Settings: saved searches, and for now the company - * boards and the prune by region as well. +/* The Searches page under Settings: saved searches only. Company boards and + * the prune by region moved to Companies, since a board is a company's own, + * not a search's. * - * The template is a shell; the lists come from /api/sources and every action - * is a fetch through `api()` from app.js, so a refusal (a search that finds - * nothing, a board that does not answer) is one toast with the server's own - * sentence. The catch blocks here only put a control back. + * The list comes from `/api/sources`, and every action is a fetch through + * `api()` from app.js, so a refusal (a search that finds nothing) is one + * toast with the server's own sentence. The catch blocks here only put a + * control back. */ (function () { "use strict"; - const { api, count, cell, debounce } = window; + const { api, count, debounce } = window; const $ = (sel, root = document) => root.querySelector(sel); - /** @type {{searches: object[], boards: object[], adzuna_key: boolean}} */ - let data = { searches: [], boards: [], adzuna_key: false }; - /** @type {object[]} the boards the last prune preview named */ - let pruneBoards = []; + /** @type {{searches: object[], adzuna_key: boolean}} */ + let data = { searches: [], adzuna_key: false }; /** "DK 120 · EU 4 · unknown 2", the three biggest. */ function countries(source) { @@ -25,19 +24,11 @@ return shown.join(" · "); } - function query(source) { - const p = source.params || {}; - const where = source.provider === "adzuna" - ? [p.country && p.country.toUpperCase(), p.where].filter(Boolean).join(", ") - : (p.area ? $(`#s-area option[value="${p.area}"]`)?.textContent : "All of Denmark"); - return `${p.q || ""}${where ? ` — ${where}` : ""}`; - } - function onSwitch(source, rerender) { const box = document.createElement("input"); box.type = "checkbox"; box.checked = source.on; - box.setAttribute("aria-label", `Pull ${source.label}`); + box.setAttribute("aria-label", `Run ${source.label}`); box.addEventListener("change", async () => { box.disabled = true; try { @@ -66,35 +57,41 @@ const body = $("#searches-list"); body.replaceChildren(); for (const source of data.searches) { - const tr = document.createElement("tr"); - if (!source.on) tr.classList.add("muted"); + const row = document.createElement("div"); + row.className = "srow"; + if (!source.on) row.dataset.muted = "true"; + const name = document.createElement("span"); - name.textContent = source.label; + name.className = "name"; + const label = document.createElement("span"); + label.textContent = source.label; const provider = document.createElement("span"); provider.className = "badge"; provider.textContent = source.provider; - const title = document.createElement("span"); - title.append(name, " ", provider); - cell(tr, "Search", title); - cell(tr, "Query", query(source)).className = "mono small"; - cell(tr, "Open roles", String(source.open_roles)).className = "num"; - cell(tr, "Countries", countries(source)).className = "small"; - cell(tr, "On", onSwitch(source, renderSearches)); - const actions = document.createElement("span"); - actions.className = "row-actions"; + name.append(label, provider); + row.appendChild(name); + row.appendChild(onSwitch(source, renderSearches)); + + const q = (source.params && source.params.q) || ""; + const sub = document.createElement("span"); + sub.className = "sub"; + const parts = [q, `${source.open_roles} open`]; + if (source.countries.length) parts.push(countries(source)); + sub.append(parts.join(" · "), " "); const edit = document.createElement("button"); edit.type = "button"; - edit.className = "secondary"; + edit.className = "linky"; edit.textContent = "Edit"; edit.addEventListener("click", () => fillSearchForm(source)); const remove = document.createElement("button"); remove.type = "button"; - remove.className = "secondary"; + remove.className = "linky"; remove.textContent = "Remove"; remove.addEventListener("click", () => removeSearch(source)); - actions.append(edit, remove); - cell(tr, "", actions); - body.appendChild(tr); + sub.append(edit, " ", remove); + row.appendChild(sub); + + body.appendChild(row); } const open = data.searches.reduce((sum, s) => sum + s.open_roles, 0); $("#searches-count").textContent = data.searches.length @@ -203,123 +200,6 @@ } } - // ------------------------------------------------------------------ boards - - function renderBoards() { - const q = $("#b-q").value.trim().toLowerCase(); - const on = $("#b-on").value; - const rows = data.boards - .filter((b) => !q || b.label.toLowerCase().includes(q) || b.target.includes(q)) - .filter((b) => !on || (on === "on") === b.on) - .sort((a, b) => Number(b.on) - Number(a.on) || b.open_roles - a.open_roles - || a.label.localeCompare(b.label)); - const body = $("#boards-list"); - body.replaceChildren(); - for (const board of rows) { - const tr = document.createElement("tr"); - if (!board.on) tr.classList.add("muted"); - const link = document.createElement("a"); - link.href = `/?company=${encodeURIComponent(board.label)}`; - link.title = "This company's open roles"; - link.textContent = board.label; - cell(tr, "Company", link); - cell(tr, "Board", board.target).className = "mono small"; - cell(tr, "Open roles", String(board.open_roles)).className = "num"; - cell(tr, "Countries", countries(board)).className = "small"; - cell(tr, "On", onSwitch(board, renderBoards)); - body.appendChild(tr); - } - const onCount = data.boards.filter((b) => b.on).length; - $("#boards-count").textContent = - `${count(data.boards.length, "board")}, ${onCount} on. Showing ${rows.length}.`; - } - - async function addBoard(event) { - event.preventDefault(); - const status = $("#board-status"); - const button = $("#board-form button[type=submit]"); - button.disabled = true; - status.textContent = "Reading the board once before following it…"; - try { - const result = await api("/api/boards", { - method: "POST", - body: { board: $("#b-board").value.trim(), name: $("#b-name").value.trim() }, - }); - data.boards.push(result.source); - renderBoards(); - $("#board-form").reset(); - status.textContent = `Following ${result.source.label}: ` - + `${count(result.found, "role")} listed. They arrive with the next pull.`; - } catch (err) { - status.textContent = ""; - } - button.disabled = false; - } - - // ------------------------------------------------------------------- prune - - async function previewPrune(event) { - event.preventDefault(); - const status = $("#prune-status"); - const list = $("#prune-list"); - const region = $("#p-region").value.trim(); - list.replaceChildren(); - $("#p-apply").disabled = true; - status.textContent = "Checking every board…"; - try { - const result = await api(`/api/prune?region=${encodeURIComponent(region)}`); - pruneBoards = result.boards; - const roles = pruneBoards.reduce((sum, b) => sum + b.open_roles, 0); - status.textContent = pruneBoards.length - ? `${count(pruneBoards.length, "board")} with no open role in ${region}, ` - + `${count(roles, "open role")} between them:` - : `Every board that is on has a role in ${region}.`; - for (const board of pruneBoards) { - const li = document.createElement("li"); - li.textContent = `${board.label} (${board.target}), ${count(board.open_roles, "open role")}`; - list.appendChild(li); - } - $("#p-apply").disabled = pruneBoards.length === 0; - } catch (err) { - status.textContent = ""; - } - } - - async function applyPrune() { - const region = $("#p-region").value.trim(); - if (!window.confirm(`Switch off ${count(pruneBoards.length, "board")} and close their roles? ` - + "Each can be switched back on in the list above.")) return; - $("#p-apply").disabled = true; - try { - const result = await api("/api/prune", { method: "POST", body: { region } }); - $("#prune-status").textContent = `Switched off ${count(result.pruned, "board")}, ` - + `closed ${count(result.roles_closed, "role")}. ${result.boards_left} boards are on.`; - $("#prune-list").replaceChildren(); - await load(); - renderBoards(); - } catch (err) { - $("#p-apply").disabled = false; - } - } - - // -------------------------------------------------------------------- pull - - async function pullNow() { - const button = $("#pull-now"); - button.disabled = true; - try { - await api("/api/jobs", { method: "POST", body: { kind: "pull", payload: {} } }); - $("#pull-status").replaceChildren("Pull started. "); - const link = document.createElement("a"); - link.href = "/settings/pulls"; - link.textContent = "Follow it under Pulls"; - $("#pull-status").appendChild(link); - } catch (err) { - /* already toasted */ - } - button.disabled = false; - } - // -------------------------------------------------------------------- init document.addEventListener("DOMContentLoaded", async () => { @@ -330,17 +210,10 @@ return; } renderSearches(); - renderBoards(); fillSearchForm(null); $("#s-provider").addEventListener("change", showProvider); $("#s-try").addEventListener("click", trySearch); $("#search-form").addEventListener("submit", saveSearch); $("#s-new").addEventListener("click", () => fillSearchForm(null)); - $("#b-q").addEventListener("input", debounce(renderBoards, 150)); - $("#b-on").addEventListener("change", renderBoards); - $("#board-form").addEventListener("submit", addBoard); - $("#prune-form").addEventListener("submit", previewPrune); - $("#p-apply").addEventListener("click", applyPrune); - $("#pull-now").addEventListener("click", pullNow); }); })(); diff --git a/app/templates/settings/companies.html b/app/templates/settings/companies.html index 579d0a1..9194426 100644 --- a/app/templates/settings/companies.html +++ b/app/templates/settings/companies.html @@ -5,26 +5,60 @@

Settings

{% include "settings/_tabs.html" %} -

Every company roledesk has seen, and how many of its roles are open. Mute keeps its roles out of the list, Like lifts them in Best match, and Favourite puts them at the top.

+

Every company roledesk has seen, and how many of its roles are open. Switching a board off stops reading it and closes its roles; hiding a company keeps reading it but leaves its roles out of the list and unscored, and favourite or like lifts one instead, in Best match.

+ +
+

Follow a company

+
+ + + +
+
+

+
- + + + + + +

- - - - - -
CompanyBoardOpen rolesAffinity
+
+ +
+ Switch off boards with no roles in a region +

A board none of whose open roles is in the region is switched off; a board whose roles name no country is kept.

+
+ +
+ + +
+

+ +
+
{% endblock %} {% block scripts %} diff --git a/app/templates/settings/searches.html b/app/templates/settings/searches.html index 35fc32c..7e7c3c7 100644 --- a/app/templates/settings/searches.html +++ b/app/templates/settings/searches.html @@ -5,105 +5,48 @@

Settings

{% include "settings/_tabs.html" %} -{# Still the old Sources page whole, company boards and prune included, until - the Companies page takes those over. #} -
-

Where roles come from: saved searches find them at any company, and a followed company's board lists every role it has. Switching one off closes its roles until you switch it back on.

- -
-

+

Saved searches find roles at any company, on Jobindex or Adzuna. Switching one off closes its roles until you switch it back on.

-
-

Searches

-

- - - - - -
SearchQueryOpen rolesCountriesOn
+
+

New search

+
+ + +
+ +
+ + + + +
+ +
+ + + +
+

+
    +
    -
    -

    New search

    -
    - - -
    - -
    - - - - -
    - -
    - - - -
    -

    -
      -
      -
      - -
      -

      Company boards

      -
      - - -
      -

      - - - - - -
      CompanyBoardOpen rolesCountriesOn
      - -
      -

      Follow a company

      -
      - - -
      -
      -

      -
      -
      - -
      -

      Prune boards by region

      -
      - -
      - - -
      -

      - -
      -
      +

      +
      {% endblock %} {% block scripts %} diff --git a/app/web/api.py b/app/web/api.py index c1f5736..755a479 100644 --- a/app/web/api.py +++ b/app/web/api.py @@ -17,7 +17,7 @@ from pydantic import BaseModel, Field from app import jobs from app.models import ( AFFINITY, Agent, Application, Company, Gate, Role, ScoredRole, Status, Subscription, - Weights, + Weights, company_key, ) from app.storage import Store from app.web.deps import ConfigDep, StoreDep @@ -173,23 +173,43 @@ def summarise_role(uid: str, store: StoreDep, config: ConfigDep, queue: QueueDep # --------------------------------------------------------------- companies class CompanyOut(BaseModel): - """A company row plus the two things only the store can join in: the ats - host it is read from, and how many of its roles are still open.""" + """A company row plus what only the store can join in: the ats host it is + read from (empty for a company known only from a search), the id of that + board's subscription, whether it is on, and how many of its roles are + still open.""" key: str name: str board: str + subscription_id: int | None = None + on: bool | None = None affinity: int open_roles: int +def _company_boards(store: Store) -> dict[str, tuple[int, str, bool]]: + """`company_key -> (subscription id, ats host, on)`, read off each + company's own subscription. Same join as `Store.company_boards`, with the + id and switch state a company row needs to draw its own on/off control + rather than fetching `/api/sources` as well.""" + boards: dict[str, tuple[int, str, bool]] = {} + for sub in store.subscriptions(source="ats"): + boards.setdefault(company_key(sub.company), (sub.id, sub.board, + bool(sub.subscribed and sub.fetch))) + return boards + + @router.get("/companies") def list_companies(store: StoreDep) -> list[CompanyOut]: - boards = store.company_boards() + boards = _company_boards(store) counts = store.open_role_counts() - return [CompanyOut(key=c.key, name=c.name, board=boards.get(c.key, ""), - affinity=c.affinity, open_roles=counts.get(c.key, 0)) - for c in store.companies()] + out = [] + for c in store.companies(): + sub_id, host, on = boards.get(c.key, (None, "", None)) + out.append(CompanyOut(key=c.key, name=c.name, board=host, + subscription_id=sub_id, on=on, affinity=c.affinity, + open_roles=counts.get(c.key, 0))) + return out class AffinityBody(BaseModel): @@ -197,13 +217,17 @@ class AffinityBody(BaseModel): @router.post("/companies/{key}/affinity") -def set_affinity(key: str, body: AffinityBody, store: StoreDep) -> Company: +def set_affinity(key: str, body: AffinityBody, store: StoreDep, queue: QueueDep) -> Company: + """A change here is not seen in Best match until `score` has run: the + queue dedupes to a live job of that kind, so several clicks are one run.""" if body.affinity not in AFFINITY: raise HTTPException(422, "affinity is -1, 0, 1 or 2") try: - return store.update_company(key, affinity=body.affinity) + company = store.update_company(key, affinity=body.affinity) except KeyError: raise HTTPException(404, f"no such company: {key}") from None + queue.enqueue("score") + return company # ----------------------------------------------------------------- sources diff --git a/tests/test_web.py b/tests/test_web.py index e232102..b4d60ec 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -7,6 +7,7 @@ from __future__ import annotations from collections.abc import Iterator from datetime import UTC, datetime, timedelta from pathlib import Path +from typing import Any import pytest from fastapi import FastAPI @@ -55,6 +56,11 @@ def store(app: FastAPI) -> Store: return app.state.store +@pytest.fixture +def queue(app: FastAPI) -> Any: + return app.state.queue + + @pytest.fixture def client(app: FastAPI) -> Iterator[TestClient]: with TestClient(app) as c: @@ -229,21 +235,26 @@ def test_companies_lists_board_and_open_role_count( sub = store.add_subscription("ats", "greenhouse:acme", company="Acme", board="greenhouse") store.add_company("Acme", key="acme") store.upsert_role(posting("1", company="Acme"), sub) + store.add_company("Other", key="other") # known only from a search: no board res = client.get("/api/companies") assert res.status_code == 200 [row] = [c for c in res.json() if c["key"] == "acme"] assert row == {"key": "acme", "name": "Acme", "board": "greenhouse", - "affinity": 0, "open_roles": 1} + "subscription_id": sub.id, "on": True, "affinity": 0, "open_roles": 1} + [other] = [c for c in res.json() if c["key"] == "other"] + assert (other["board"], other["subscription_id"], other["on"]) == ("", None, None) -def test_set_affinity_validates_and_updates(client: TestClient, store: Store) -> None: +def test_set_affinity_validates_updates_and_enqueues_a_score( + client: TestClient, store: Store, queue: Any) -> None: store.add_company("Acme", key="acme") res = client.post("/api/companies/acme/affinity", json={"affinity": 2}) assert res.status_code == 200 assert res.json()["affinity"] == 2 assert store.company("acme").affinity == 2 # type: ignore[union-attr] + assert queue.jobs.last("score", states=("queued", "running", "done")) is not None assert client.post("/api/companies/acme/affinity", json={"affinity": 9}).status_code == 422 assert client.post("/api/companies/nope/affinity", json={"affinity": 1}).status_code == 404 @@ -396,8 +407,21 @@ def test_the_ranking_page_edits_one_ranking(client: TestClient) -> None: def test_the_searches_page_offers_the_jobindex_areas(client: TestClient) -> None: page = client.get("/settings/searches").text - assert 'id="searches-list"' in page and 'id="boards-list"' in page + assert 'id="searches-list"' in page assert 'value="1" selected>Region Hovedstaden' in page # from plugins.search + # Boards and the prune tool moved to Companies; a search has no board. + assert 'id="boards-list"' not in page and 'id="prune-form"' not in page + assert 'id="pull-now"' not in page # moved to Pulls + + +def test_the_companies_page_offers_the_follow_form_and_the_prune_tool( + client: TestClient) -> None: + page = client.get("/settings/companies").text + assert 'id="companies-list"' in page + assert 'id="b-host"' in page and 'id="b-slug"' in page and 'id="b-name"' in page + assert '