From 09c5dde113ff6fe5444f4779fcba5cda0f62ffef Mon Sep 17 00:00:00 2001 From: Wolf Date: Fri, 25 Sep 2026 21:51:48 +0200 Subject: [PATCH] Roles as a feed, a read page, votes that move the rank, unstar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Roles tab is news's feed row: the title opens /roles/{uid}, company, place and age under it, the badges, a one-line excerpt (summary, else the description's opening), and ▲ ● ▼ ★ on the right, under the text at 640px. The company affinity control leaves the row. A passed role and a hidden company's are dimmed and stay. The filter bar is one row: order, search and a Filters
holding the rest, with a judged select and "Show hidden companies". The list loads 60 and appends on an IntersectionObserver sentinel; back from a read page restores the filters, rows and scroll. GET /api/roles takes offset, defaults to 60 and answers {items, total}. judged= is a WHERE on roles.vote. Under a ranking the served score and the order are the stored score moved by the vote (x0.5 pass, x1.2 like, capped at 1), so a vote shows at once without a rescore. POST and DELETE /api/roles/{uid}/vote set and clear it; pressing the pressed stance clears. ★ saves; pressed again it calls DELETE /api/applications/{id}, which drops the application while it is still saved and answers 409 after. save_role no longer writes the placeholder next step. The read page (role.html, role.js) is news's reader: a bar with back, ▲ ● ▼ ★ and ↗, the company with its affinity control, place, badges, salary, summary, the text (fetched posting, else description) and the link out. It offers Fetch the posting for a teaser and Summarise without a summary, against the /text and /summarise routes B4 adds. The vote and star buttons are judge.js, shared by the feed and the reader. Applications: titles open the read page, the Next column is gone, a Saved column instead, and the lede says what the page is for. Co-Authored-By: Claude Fable 5.1 --- app/static/app.css | 213 ++++++++++++++++++++++---- app/static/applications.js | 29 +++- app/static/judge.js | 132 +++++++++++++++++ app/static/role.js | 200 +++++++++++++++++++++++++ app/static/roles.js | 255 ++++++++++++++++++++++++-------- app/storage/store.py | 99 +++++++++++-- app/templates/applications.html | 6 +- app/templates/role.html | 47 ++++++ app/templates/roles.html | 114 ++++++++------ app/web/api.py | 94 +++++++++--- app/web/pages.py | 13 +- tests/test_storage.py | 55 +++++++ tests/test_web.py | 151 +++++++++++++++++-- 13 files changed, 1216 insertions(+), 192 deletions(-) create mode 100644 app/static/judge.js create mode 100644 app/static/role.js create mode 100644 app/templates/role.html diff --git a/app/static/app.css b/app/static/app.css index 40a8e87..bdc4adb 100644 --- a/app/static/app.css +++ b/app/static/app.css @@ -311,38 +311,204 @@ textarea:focus-visible { .count { color: var(--dim); font-size: .85rem; margin: .75rem 0 .5rem; } -/* roles */ +/* == roles, the read page, applications ================================== */ +/* The feed row and the reader are news's (`newsdesk/web/static/app.css`): + * the row a grid with a bottom rule and no card, the actions on the right + * dropping under the text at 640px, a cast vote filled rather than tinted. + * Drawn by static/roles.js, static/role.js and static/judge.js; the phone + * and touch rules for all of it are at the end of this section rather than + * in the phone section below, so the section is one piece. */ -.roles { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: .5rem; } +/* The filter bar: the order, the search box, and Filters on one row at any + width. Filters is a `
` whose summary is lifted into that row, so + the panel it opens sits in the flow under the row and pushes the list + down instead of covering it. */ +.roles-filters { display: block; position: relative; } +.filter-line { display: flex; gap: .5rem; align-items: center; margin-right: 6.75rem; } +.filter-line select { flex: 0 1 auto; max-width: 45%; } +.filter-line input[type="search"] { flex: 1 1 8rem; } +.filter-more > summary { + position: absolute; top: .75rem; right: .75rem; + display: flex; align-items: center; justify-content: center; min-width: 6rem; + padding: .4rem .6rem; line-height: 1.2; + border: 1px solid var(--line); border-radius: .3rem; + color: var(--fg); background: var(--bg); cursor: pointer; + list-style: none; white-space: nowrap; +} +.filter-more > summary::-webkit-details-marker { display: none; } +.filter-more[open] > summary { border-color: var(--accent); color: var(--accent); } +.filter-active { margin-left: .3rem; color: var(--accent); font-weight: 600; } +.filter-panel { + display: flex; flex-wrap: wrap; gap: .5rem; align-items: center; + margin-top: .75rem; padding-top: .75rem; border-top: 1px solid var(--line); +} +.filter-panel select { flex: 1 1 9rem; } + +/* The feed. */ +.roles { + list-style: none; margin: 0; padding: 0; + background: var(--panel); + border: 1px solid var(--line); border-radius: var(--radius); +} +.roles:empty { display: none; } +.roles-end { height: 1px; } .role { - background: var(--panel); border: 1px solid var(--line); border-radius: .5rem; - padding: .6rem .8rem; - display: flex; flex-direction: column; gap: .35rem; + display: grid; grid-template-columns: minmax(0, 1fr) auto; + align-items: start; gap: .85rem; + padding: .8rem 1rem .85rem; + border-bottom: 1px solid var(--line); +} +.role:last-child { border-bottom: 0; } +.role-body { min-width: 0; } +.role-title { + display: block; max-width: 60ch; + color: var(--fg); text-decoration: none; + font-size: 1.05rem; font-weight: 600; line-height: 1.35; + overflow-wrap: anywhere; } -.role-main { display: flex; flex-wrap: wrap; align-items: baseline; gap: .5rem; } -.role-title { font-weight: 600; text-decoration: none; } @media (hover: hover) { - .role-title:hover { text-decoration: underline; } + .role-title:hover { text-decoration: underline; text-underline-offset: 2px; } } -.role-company { color: var(--dim); } -.role-meta { - display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; - color: var(--dim); font-size: .85rem; +.role-meta, .reader-meta { + display: flex; flex-wrap: wrap; gap: .1rem .55rem; align-items: baseline; + margin-top: .25rem; font-size: .85rem; color: var(--dim); } -.role-meta .badge { +/* The company is how you decide whether to read on: weight and full ink. */ +.role-meta b, .reader-meta b { font-weight: 600; color: var(--fg); } +.role-meta > :empty, .reader-meta > :empty { display: none; } +.role-meta > * + *::before { content: "· "; } +.role-badges { display: flex; flex-wrap: wrap; gap: .35rem; margin-top: .35rem; } +.role-badges > :empty { display: none; } +.role-badges:not(:has(> :not(:empty))) { display: none; } +.role-badges .badge { background: transparent; color: var(--dim); border: 1px solid var(--line); border-radius: 1rem; padding: .05rem .55rem; font-size: .78rem; } -.role-meta .badge:empty { display: none; } -.role-meta .role-score { +.role-badges .role-score { color: var(--accent); border-color: color-mix(in srgb, var(--accent) 45%, var(--line)); font-variant-numeric: tabular-nums; } -.role-gated { color: var(--error); font-size: .85rem; } -.role-age { margin-left: auto; } -.role.muted, tr.muted { opacity: .55; } -.role.gated { opacity: .7; } +.role-gated { color: var(--error); font-size: .8rem; } +.role-excerpt { + margin: .35rem 0 0; max-width: 68ch; + font-size: .9rem; color: var(--dim); + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; +} +.role-excerpt:empty { display: none; } +/* A pass and a hidden company are dimmed and stay: a stray tap has to be + visible to be undone. The buttons keep full contrast, so the undo does. */ +.role.muted .role-body, .role.passed .role-body { opacity: .55; } +.role.gated .role-body { opacity: .7; } +/* The Companies table dims a hidden company's row the same way. */ +tr.muted { opacity: .55; } + +/* ▲ ● ▼ ★, on a row and in the reader's bar (static/judge.js). */ +.judge { display: flex; gap: .15rem; align-items: center; } +.judge button { + padding: .2rem .45rem; font-size: 1rem; line-height: 1; + color: var(--dim); background: none; + border: 1px solid transparent; border-radius: .3rem; +} +@media (hover: hover) { + .judge button:hover { color: var(--fg); border-color: var(--line); } +} +/* Filled when cast: a reversed glyph on solid ground reads at arm's length + where a tint does not. `--panel` for the glyph because it is the opposite + end of the scale from every fill in both schemes. */ +.judge .up[aria-pressed="true"] { + color: var(--panel); background: var(--accent); border-color: var(--accent); +} +.judge .down[aria-pressed="true"] { + color: var(--panel); background: var(--error); border-color: var(--error); +} +/* Neither way is an answer and must be as loud as the other two, or it + cannot be told from unjudged; grey, since it is no direction. */ +.judge .mid[aria-pressed="true"] { + color: var(--panel); background: var(--dim); border-color: var(--dim); +} +/* Saved is a different question from judging: amber, and set apart. */ +.judge .star[aria-pressed="true"] { + color: var(--panel); background: var(--warn); border-color: var(--warn); +} +.judge .star { margin-left: .35rem; } + +/* The read page. */ +.reader { + background: var(--panel); + border: 1px solid var(--line); border-radius: var(--radius); +} +.reader-bar { + position: sticky; top: var(--header-h, 0px); z-index: 4; + display: flex; align-items: center; gap: .2rem; + padding: .35rem .6rem; + background: var(--panel); + border-bottom: 1px solid var(--line); + border-radius: var(--radius) var(--radius) 0 0; +} +.reader-bar .spacer { flex: 1; } +.reader-back, .reader-external { + display: inline-flex; align-items: center; justify-content: center; + padding: .2rem .55rem; font-size: 1rem; line-height: 1; + color: var(--dim); text-decoration: none; + border: 1px solid var(--line); border-radius: .3rem; +} +.reader-back { margin-right: .4rem; } +@media (hover: hover) { + .reader-back:hover, .reader-external:hover { color: var(--fg); border-color: var(--dim); } +} +.reader-body { padding: 1.4rem 2rem 2.5rem; overflow-wrap: anywhere; } +/* About 70 characters a line at the reading size. */ +.reader-body > * { max-width: 40rem; margin-inline: auto; } +.reader-meta { align-items: center; margin-top: 0; } +.reader-meta .affinity { font-size: .85rem; } +.reader h1 { font-size: 1.6rem; line-height: 1.25; margin: .6rem auto .5rem; } +.reader .role-badges { margin-top: 0; } +.reader-salary { margin: .6rem auto 0; font-weight: 600; } +.reader-summary { + margin-top: 1.1rem; padding: .7rem .9rem; + background: color-mix(in srgb, var(--accent) 7%, var(--panel)); + border-left: 3px solid var(--accent); border-radius: .3rem; +} +.reader-summary p { margin: 0; } +/* A label over a block rather than the posting's own heading. */ +.reader-label { + margin: 0 0 .3rem; font-size: .72rem; font-weight: 600; + letter-spacing: .08em; text-transform: uppercase; color: var(--dim); +} +.reader-tools { display: flex; flex-wrap: wrap; gap: .5rem; align-items: center; margin-top: 1rem; } +.reader-tools:not(:has(> :not([hidden], :empty))) { display: none; } +.prose { margin-top: 1.2rem; font-size: 1.02rem; line-height: 1.7; } +.prose p { margin: 0 0 1rem; } +.reader-out { margin-top: 1.5rem; padding-top: 1rem; border-top: 1px solid var(--line); } + +/* Applications: the table is the shared `table.list`. */ +table.applications td[data-label="Saved"] { white-space: nowrap; color: var(--dim); } + +@media (max-width: 640px) { + .filter-line { margin-right: 6.25rem; } + .filter-more > summary { right: 10px; min-width: 5.5rem; } + + /* Edge to edge, like every panel on a phone. */ + .roles, .reader { margin-inline: -10px; border-radius: 0; border-inline: 0; } + .reader { margin-top: -10px; border-top: 0; } + .reader-bar { border-radius: 0; } + .role { grid-template-columns: minmax(0, 1fr); gap: .45rem; padding: .75rem 10px; } + /* Under the text and to the right, where a thumb is. Two filled blocks + side by side need a gap or they read as one control. */ + .role-actions { justify-content: flex-end; gap: .4rem; } + .role-actions button { padding: .25rem .75rem; min-height: 32px; font-size: 1.2rem; } + .reader-body { padding: .9rem .75rem 1.5rem; } + .reader h1 { font-size: 1.3rem; } +} + +@media (pointer: coarse) { + .filter-more > summary { min-height: 2.75rem; } + .judge button { padding: .5rem .7rem; font-size: 1.15rem; } + .reader-bar { padding: .3rem .5rem; } + .reader-back, .reader-external { min-height: 2.75rem; min-width: 2.75rem; } +} +/* == end of roles, the read page, applications ============================ */ .affinity { display: inline-flex; gap: .15rem; } .role-main .affinity { margin-left: auto; } @@ -357,11 +523,6 @@ textarea:focus-visible { background: var(--error); border-color: var(--error); } -.save { align-self: flex-start; padding: .3rem .8rem; font-weight: 600; } -.save[disabled] { - background: var(--bg); color: var(--dim); border-color: var(--line); cursor: default; -} - /* agents */ .agents { list-style: none; margin: 0 0 1rem; padding: 0; display: flex; flex-direction: column; gap: .4rem; } @@ -437,10 +598,6 @@ table.list select { padding: .25rem .4rem; } } } -@media (max-width: 480px) { - .role-age, .role-main .affinity { margin-left: 0; } -} - /* -- the phone ------------------------------------------------------------ */ /* Two axes, and deliberately not the same one, as in newsdesk: width decides the layout, pointer decides the sizes. A tablet is wide and touched, a diff --git a/app/static/applications.js b/app/static/applications.js index 49f1bdc..cb120ce 100644 --- a/app/static/applications.js +++ b/app/static/applications.js @@ -2,7 +2,9 @@ * * The template renders an empty table; the rows come from /api/applications * and a status change is a fetch through `api()` from app.js, which toasts a - * refusal. The company names come from app.js's shared company list. + * refusal. A role's title opens its read page, where ★ unsaves it; one that + * was never a posting links out to where it was found, if anywhere. The + * company names come from app.js's shared company list. */ (function () { "use strict"; @@ -25,17 +27,30 @@ return select; } + /** "25 Sep", or "25 Sep 2025" when it is not this year. */ + function savedOn(iso) { + const at = new Date(iso); + if (Number.isNaN(at.getTime())) return ""; + const options = { day: "numeric", month: "short" }; + if (at.getFullYear() !== new Date().getFullYear()) options.year = "numeric"; + return at.toLocaleDateString("en-GB", options); + } + function render(applications) { const body = $("#applications-list"); body.replaceChildren(); for (const application of applications) { const tr = document.createElement("tr"); - if (application.url) { + if (application.role_uid || application.url) { const link = document.createElement("a"); - link.href = application.url; - link.target = "_blank"; - link.rel = "noopener"; link.textContent = application.role_title || "(untitled)"; + if (application.role_uid) { + link.href = `/roles/${encodeURIComponent(application.role_uid)}`; + } else { + link.href = application.url; + link.target = "_blank"; + link.rel = "noopener"; + } cell(tr, "Role", link); } else { cell(tr, "Role", application.role_title || "(untitled)"); @@ -45,8 +60,8 @@ const select = statusSelect(application.status); select.addEventListener("change", () => setStatus(application.id, select)); cell(tr, "Status", select); - cell(tr, "Next", [application.next_action, application.next_date] - .filter(Boolean).join(" · ")); + const saved = cell(tr, "Saved", savedOn(application.created_at)); + saved.title = application.created_at; body.appendChild(tr); } $("#applications-count").textContent = diff --git a/app/static/judge.js b/app/static/judge.js new file mode 100644 index 0000000..2bda4aa --- /dev/null +++ b/app/static/judge.js @@ -0,0 +1,132 @@ +/* ▲ ● ▼ ★ for one role: the feed row and the read page share them. + * + * news's `voteButtons`, `starButton` and `vote()`, adapted. Three stances and + * no stance is four states from three buttons; pressing the stance a role + * already has clears it, which is the only way back to unjudged, since ● is + * an answer ("neither way") and not the absence of one. A vote never hides a + * role: a stray tap stays on screen, pressed, and one more tap undoes it. + * + * ★ is Save. It files the role under Applications (`POST /api/applications`) + * and, pressed again, takes it back out (`DELETE /api/applications/{id}`), + * which the server allows only while the application is still at `saved`; a + * 409 is toasted by `api()` and the star stays lit. + * + * Both are optimistic: the button changes before the request and changes back + * if it fails. `api()` has already toasted the failure by then. + * + * await loadTracked(); + * container.append(judgeButtons(role, (role) => row.classList.toggle(...))); + */ +(function () { + "use strict"; + + const { api } = window; + + /** @type {Map} role_uid -> application, for roles saved */ + const tracked = new Map(); + + async function loadTracked() { + const applications = await api("/api/applications"); + tracked.clear(); + for (const a of applications) if (a.role_uid) tracked.set(a.role_uid, a); + return tracked; + } + + const STANCES = [ + { value: 1, cls: "up", glyph: "▲", said: "Like" }, + { value: 0, cls: "mid", glyph: "●", said: "Neither way" }, + { value: -1, cls: "down", glyph: "▼", said: "Pass" }, + ]; + + function button(cls, glyph) { + const b = document.createElement("button"); + b.type = "button"; + b.className = cls; + b.textContent = glyph; + return b; + } + + /* The four buttons as a fragment, bound to `role`, which they read and + write in place (`role.vote`), so the caller's copy is always current. + `onChange(role)` runs after every change, optimistic or reverted: the + feed dims a passed row with it. */ + function judgeButtons(role, onChange) { + const fragment = document.createDocumentFragment(); + const votes = STANCES.map((s) => { + const b = button(s.cls, s.glyph); + b.addEventListener("click", () => vote(s.value)); + fragment.appendChild(b); + return b; + }); + const star = button("star", "★"); + star.addEventListener("click", () => toggleSave()); + fragment.appendChild(star); + + function paint() { + STANCES.forEach((s, i) => { + const on = role.vote === s.value; + const said = on ? `${s.said} — tap again to undo` : s.said; + votes[i].setAttribute("aria-pressed", String(on)); + votes[i].title = said; + votes[i].setAttribute("aria-label", said); + }); + const saved = tracked.has(role.uid); + const said = saved ? "Saved to Applications — tap to unsave" : "Save to Applications"; + star.setAttribute("aria-pressed", String(saved)); + star.title = said; + star.setAttribute("aria-label", said); + if (onChange) onChange(role); + } + + async function vote(value) { + const before = role.vote ?? null; + const clearing = before === value; + role.vote = clearing ? null : value; + paint(); + const path = `/api/roles/${encodeURIComponent(role.uid)}/vote`; + try { + const updated = clearing + ? await api(path, { method: "DELETE" }) + : await api(path, { method: "POST", body: { value } }); + role.vote = updated.vote; + role.voted_at = updated.voted_at; + } catch (err) { + role.vote = before; + } + paint(); + } + + // One request at a time: a second tap while the first is in flight would + // unsave an application whose id has not come back yet. + async function toggleSave() { + if (star.disabled) return; + star.disabled = true; + const before = tracked.get(role.uid); + try { + if (before) { + tracked.delete(role.uid); + paint(); + await api(`/api/applications/${encodeURIComponent(before.id)}`, + { method: "DELETE" }); + } else { + tracked.set(role.uid, { role_uid: role.uid }); + paint(); + tracked.set(role.uid, await api("/api/applications", { + method: "POST", body: { role_uid: role.uid, status: "saved" }, + })); + } + } catch (err) { + if (before) tracked.set(role.uid, before); + else tracked.delete(role.uid); + } finally { + star.disabled = false; + } + paint(); + } + + paint(); + return fragment; + } + + Object.assign(window, { judgeButtons, loadTracked }); +})(); diff --git a/app/static/role.js b/app/static/role.js new file mode 100644 index 0000000..d1e4e65 --- /dev/null +++ b/app/static/role.js @@ -0,0 +1,200 @@ +/* The read page of one role, news's reader. + * + * The bar: back, ▲ ● ▼ ★ (judge.js, the same buttons as the feed row) and ↗ + * to the posting. Then the company with its ★ ▲ ⊘ control, the one place a + * company is judged outside the Companies page; place, badges, salary when + * stated; the summary when there is one; the text, which is the fetched + * posting when there is one and the board's description otherwise; and the + * way out once more at the end. + * + * A search role's description is a teaser of a couple of hundred characters, + * so under 500 of them, with nothing fetched yet, the page offers "Fetch the + * posting" (`POST /api/roles/{uid}/text`). "Summarise" is offered while there + * is no summary (`POST /api/roles/{uid}/summarise`). Both answer with the + * role, and the page is drawn again from it. A summary made by the queue + * rather than at once is waited for by asking for the role again. + */ +(function () { + "use strict"; + + const { api, companies, loadCompanies, affinityControl, judgeButtons, loadTracked } = window; + const $ = (sel, root = document) => root.querySelector(sel); + + const uid = $("#role").dataset.uid; + const path = `/api/roles/${encodeURIComponent(uid)}`; + /** Shorter than this and not fetched: the description is a teaser. */ + const TEASER = 500; + + /** @type {object|null} the role on screen, updated in place */ + let role = null; + + function relativeAge(iso) { + const minutes = Math.max(0, Math.floor((Date.now() - new Date(iso).getTime()) / 60000)); + if (minutes < 60) return `${minutes} min ago`; + const hours = Math.floor(minutes / 60); + if (hours < 24) return `${hours} h ago`; + return `${Math.floor(hours / 24)} d ago`; + } + + function salary(r) { + const n = (v) => new Intl.NumberFormat("en").format(v); + const unit = r.currency ? `${r.currency} ` : ""; + if (r.salary_min && r.salary_max && r.salary_min !== r.salary_max) { + return `${unit}${n(r.salary_min)}–${n(r.salary_max)}`; + } + if (r.salary_min || r.salary_max) { + const one = r.salary_min || r.salary_max; + return r.salary_min ? `From ${unit}${n(one)}` : `Up to ${unit}${n(one)}`; + } + return ""; + } + + function host(url) { + try { return new URL(url).host.replace(/^www\./, ""); } catch (e) { return ""; } + } + + /* Plain text in paragraphs: a fetched page keeps its line breaks, and a + board's description is one long line, which stays one paragraph. */ + function paragraphs(text) { + const box = document.createDocumentFragment(); + for (const part of text.split(/\n\s*\n|\n/).map((p) => p.trim()).filter(Boolean)) { + const p = document.createElement("p"); + p.textContent = part; + box.appendChild(p); + } + return box; + } + + function badge(text) { + const span = document.createElement("span"); + span.className = "badge"; + span.textContent = text; + return span; + } + + function renderAffinity() { + const slot = $("#role-affinity"); + const company = companies.get(role.company_key); + // A company seen only through a search has no row of its own to judge. + if (!company) { slot.replaceChildren(); return; } + slot.replaceChildren(affinityControl(role.company_key, company.affinity, renderAffinity)); + } + + function render() { + document.title = `${role.title || "Role"} — roledesk`; + $("#role").removeAttribute("aria-busy"); + + const out = role.original_url || ""; + $("#role-out").hidden = !out; + if (out) $("#role-out").href = out; + const end = $("#role-out-end"); + end.hidden = !out; + if (out) { + const a = end.querySelector("a"); + a.href = out; + a.textContent = `Read it on ${host(out) || "the board"} ↗`; + } + + $("#role-company").textContent = role.company || ""; + renderAffinity(); + $("#role-place").textContent = role.place || ""; + $("#role-age").textContent = role.first_seen ? relativeAge(role.first_seen) : ""; + $("#role-title").textContent = role.title || "(untitled)"; + + const badges = [role.remote, role.function, role.seniority].filter(Boolean).map(badge); + if (role.closed_at) badges.unshift(badge("closed")); + $("#role-badges").replaceChildren(...badges); + $("#role-badges").hidden = !badges.length; + + const pay = salary(role); + $("#role-salary").hidden = !pay; + $("#role-salary").textContent = pay; + + const summary = $("#role-summary"); + summary.hidden = !role.summary; + summary.querySelector("p").textContent = role.summary || ""; + + const text = (role.article_text || role.description || "").trim(); + $("#role-text").replaceChildren(text ? paragraphs(text) + : Object.assign(document.createElement("p"), { + className: "muted", textContent: "The board gave no description for this one.", + })); + + $("#role-summarise").hidden = Boolean(role.summary); + $("#role-fetch").hidden = Boolean(role.article_text) + || (role.description || "").length >= TEASER; + } + + function merge(updated) { + if (updated && updated.uid === role.uid) Object.assign(role, updated); + render(); + } + + /* Press, wait, draw again from the answer. A failure is toasted by `api()` + (a 404 included, while the route is not there yet) and the button comes + back as it was. */ + async function ask(button, busy, route) { + const label = button.textContent; + button.disabled = true; + button.textContent = busy; + try { + merge(await api(`${path}/${route}`, { method: "POST" })); + return true; + } catch (err) { + return false; + } finally { + button.disabled = false; + button.textContent = label; + } + } + + async function summarise() { + if (!(await ask($("#role-summarise"), "Summarising…", "summarise"))) return; + if (role.summary) return; + // Queued rather than done: ask again until it is there, for two minutes. + const note = $("#role-note"); + note.textContent = "The summary appears here when it is ready."; + $("#role-summarise").hidden = true; + for (let i = 0; i < 30 && !role.summary; i++) { + await new Promise((resolve) => setTimeout(resolve, 4000)); + try { merge(await api(path)); } catch (err) { break; } + } + note.textContent = ""; + render(); + } + + /* Back is back when this page was opened from one of this app's lists, so + the list keeps its place; a link from anywhere else goes to the roles. */ + function back(e) { + let from = null; + try { from = document.referrer ? new URL(document.referrer) : null; } catch (err) { /* */ } + if (from && from.origin === location.origin && history.length > 1) { + e.preventDefault(); + history.back(); + } + } + + /* The bar sticks under the top bar, whose height is the phone's or the + desktop's, and the notch's on a standalone phone. */ + function measureHeader() { + const top = document.querySelector("header.top"); + if (top) document.documentElement.style.setProperty("--header-h", `${top.offsetHeight}px`); + } + + document.addEventListener("DOMContentLoaded", async () => { + measureHeader(); + window.addEventListener("resize", measureHeader); + $("#role-back").addEventListener("click", back); + try { + [role] = await Promise.all([api(path), loadCompanies(), loadTracked()]); + } catch (err) { + $("#role-title").textContent = "This role could not be loaded."; + return; + } + $("#role-judge").appendChild(judgeButtons(role)); + render(); + $("#role-summarise").addEventListener("click", summarise); + $("#role-fetch").addEventListener("click", + () => ask($("#role-fetch"), "Fetching…", "text")); + }); +})(); diff --git a/app/static/roles.js b/app/static/roles.js index e847a5f..a269592 100644 --- a/app/static/roles.js +++ b/app/static/roles.js @@ -1,32 +1,56 @@ -/* The Roles tab: the filter bar and the list of open roles. +/* The Roles tab: the filter bar and the feed of open roles. * * The template renders an empty shell; everything on screen comes from the - * JSON routes in app/web/api.py, and every action (Save, an affinity click) - * is a fetch from here, not a form post. The company list and its affinity - * control are app.js's, shared with the Companies page. + * JSON routes in app/web/api.py. A row is news's feed row: the title (a link + * to the read page), company · place · age, the badges, a one-line excerpt, + * and ▲ ● ▼ ★ from judge.js. The company is not judged here; that is the + * Companies page and the read page. + * + * The list is paged: 60 rows, then 60 more each time a sentinel under the + * list comes within 600px of the screen (news's `loadFeed`), with the offset + * the rows already shown. Going back from a read page puts the same rows and + * the same scroll position back, from sessionStorage. * * Every request goes through `api()` from app.js, so a failure is one toast - * carrying the server's own sentence. The catch blocks here only put the - * control back the way it was. + * carrying the server's own sentence. */ (function () { "use strict"; - const { api, count, debounce, companies, loadCompanies, affinityControl } = window; + const { api, debounce, companies, loadCompanies, judgeButtons, loadTracked } = window; - /** @type {Map} role_uid -> application, for roles already tracked */ - let trackedByRole = new Map(); - /** @type {object[]} the last /api/roles response, already muted-filtered by the server */ - let roles = []; + const PAGE = 60; + /** What the list was when a read page was opened from it. */ + const KEPT = "roledesk.roles"; + + /** @type {object[]} the rows on screen, in order */ + let items = []; + /** How many roles the filters match in all. */ + let total = 0; /** @type {object[]} the enabled rankings, from /api/agents */ let agents = []; + let loading = false; + let request = 0; const $ = (sel, root = document) => root.querySelector(sel); + const number = new Intl.NumberFormat("en"); - async function loadApplications() { - const applications = await api("/api/applications"); - trackedByRole = new Map(applications.filter((a) => a.role_uid).map((a) => [a.role_uid, a])); - } + /* Every field of the filter bar, by id, and what it holds when unset. */ + const FIELDS = ["f-agent", "f-q", "f-company", "f-place", "f-function", "f-remote", + "f-days", "f-judged", "f-show-muted", "f-gated"]; + /* The ones inside Filters, which the summary counts. */ + const PANEL = ["f-company", "f-place", "f-function", "f-remote", "f-days", "f-judged", + "f-show-muted", "f-gated"]; + + const read = (id) => { + const el = document.getElementById(id); + return el.type === "checkbox" ? el.checked : el.value; + }; + const write = (id, value) => { + const el = document.getElementById(id); + if (el.type === "checkbox") el.checked = Boolean(value); + else el.value = value; + }; async function loadAgents() { agents = (await api("/api/agents")).filter((a) => a.enabled); @@ -38,7 +62,7 @@ const value = $(`#f-${key}`).value.trim(); if (value) params.set(key, value); } - for (const key of ["function", "remote", "days"]) { + for (const key of ["function", "remote", "days", "judged"]) { const value = $(`#f-${key}`).value; if (value) params.set(key, value); } @@ -51,13 +75,48 @@ return params; } - async function loadRoles() { + /* A reload starts the list again; an append asks for the rows after the + ones shown. `keep` asks for that many in one go, which is how the list is + put back as it was. The latch is let go only by the newest request: a + reload overtaking an append must not let a second append start with an + offset into the list being replaced. */ + async function load({ append = false, keep = 0 } = {}) { + if (append && (loading || items.length >= total)) return; + const params = filterParams(); + params.set("offset", String(append ? items.length : 0)); + params.set("limit", String(Math.min(1000, Math.max(PAGE, keep)))); + const mine = ++request; + loading = true; + let data; try { - roles = await api(`/api/roles?${filterParams().toString()}`); + data = await api(`/api/roles?${params}`); } catch (err) { return; + } finally { + if (mine === request) loading = false; } - renderRoles(); + if (mine !== request) return; + total = data.total; + if (append) { + items = items.concat(data.items); + renderRows(data.items); + } else { + items = data.items; + $("#roles-list").replaceChildren(); + renderRows(items); + } + renderCount(); + // Still within reach of the sentinel after a short page: the observer + // only fires on a change, and nothing changed, so ask again here. + requestAnimationFrame(() => { + const end = $("#roles-end").getBoundingClientRect(); + if (end.top < window.innerHeight + 600) load({ append: true }); + }); + } + + function reload() { + load().then(() => window.scrollTo(0, 0)); + renderActive(); } function relativeAge(iso) { @@ -69,67 +128,72 @@ return `${Math.floor(hours / 24)} d ago`; } - function renderRoles() { + /* The summary when there is one, else the description's opening, cut at a + word. One line on screen; the stylesheet clips it. */ + function excerpt(role) { + if (role.summary) return role.summary; + const text = (role.description || "").trim(); + if (text.length <= 160) return text; + const cut = text.slice(0, 160); + const space = cut.lastIndexOf(" "); + return `${(space > 100 ? cut.slice(0, space) : cut).replace(/[\s,.;:–-]+$/, "")}…`; + } + + /* A passed role and a hidden company's are dimmed, never dropped: the pass + has to stay visible to be undone. */ + function dim(li, role) { + const company = companies.get(role.company_key); + li.classList.toggle("muted", Boolean(company && company.affinity === -1)); + li.classList.toggle("passed", role.vote === -1); + } + + function renderRows(rows) { const list = $("#roles-list"); const template = $("#role-row"); - list.replaceChildren(); - - for (const role of roles) { + for (const role of rows) { const node = template.content.cloneNode(true); const li = node.querySelector(".role"); - const company = companies.get(role.company_key); + li.dataset.uid = role.uid; - 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 || "#"; + const title = node.querySelector(".role-title"); + title.textContent = role.title || "(untitled)"; + title.href = `/roles/${encodeURIComponent(role.uid)}`; node.querySelector(".role-company").textContent = role.company || ""; node.querySelector(".role-place").textContent = role.place || ""; + node.querySelector(".role-age").textContent = relativeAge(role.first_seen); 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 = "Match"; + badge.textContent = role.gated_reason ? "gated" : `match ${Math.round(role.score * 100)}`; + badge.title = role.gated_reason ? "Kept out of the ranking" : "How well it matches, of 100"; node.querySelector(".role-gated").textContent = role.gated_reason || ""; if (role.gated_reason) li.classList.add("gated"); } + node.querySelector(".role-excerpt").textContent = excerpt(role); - node.querySelector(".affinity").replaceWith( - affinityControl(role.company_key, company ? company.affinity : 0, loadRoles)); - - const saveButton = node.querySelector(".save"); - setSaveButton(saveButton, role.uid); - saveButton.addEventListener("click", () => saveRole(role.uid, saveButton)); - + node.querySelector(".role-actions").appendChild(judgeButtons(role, () => dim(li, role))); list.appendChild(node); } - - $("#roles-count").textContent = count(roles.length, "role"); } - function setSaveButton(button, uid) { - const saved = trackedByRole.has(uid); - button.textContent = saved ? "Saved" : "Save"; - button.disabled = saved; + function renderCount() { + const noun = total === 1 ? "role" : "roles"; + $("#roles-count").textContent = items.length < total + ? `${number.format(items.length)} of ${number.format(total)} ${noun}` + : `${number.format(total)} ${noun}`; } - async function saveRole(uid, button) { - button.disabled = true; - button.textContent = "Saving…"; - try { - const application = await api("/api/applications", { - method: "POST", body: { role_uid: uid, status: "saved" }, - }); - trackedByRole.set(uid, application); - setSaveButton(button, uid); - } catch (err) { - button.disabled = false; - button.textContent = "Save"; - } + /* How many filters inside the panel are set, on its summary, so a closed + panel still says the list is narrowed. */ + function renderActive() { + const set = PANEL.filter((id) => { + if (id === "f-gated" && $("#show-gated").hidden) return false; + const value = read(id); + return typeof value === "boolean" ? value : value.trim() !== ""; + }).length; + $("#f-active").textContent = set ? `· ${set}` : ""; } /* The filter bar's order: Newest, or a ranking's score. One ranking is the @@ -155,6 +219,7 @@ for (const key of ["q", "company", "place"]) { if (query.get(key)) $(`#f-${key}`).value = query.get(key); } + if (query.get("company") || query.get("place")) $("#f-more").open = true; const agent = query.get("agent"); if (agent && agents.some((a) => String(a.id) === agent)) { $("#f-agent").value = agent; @@ -162,27 +227,87 @@ } } + // ------------------------------------------------ back from a read page + + function keep() { + const filters = {}; + for (const id of FIELDS) filters[id] = read(id); + try { + sessionStorage.setItem(KEPT, JSON.stringify({ + filters, count: items.length, y: window.scrollY, open: $("#f-more").open, + })); + } catch (err) { /* private mode: back is a fresh list, which is fine */ } + } + + function kept() { + try { + return JSON.parse(sessionStorage.getItem(KEPT) || "null"); + } catch (err) { + return null; + } + } + + function cameBack() { + const [entry] = performance.getEntriesByType("navigation"); + return Boolean(entry && entry.type === "back_forward"); + } + + async function restore(state) { + for (const [id, value] of Object.entries(state.filters || {})) { + if (document.getElementById(id)) write(id, value); + } + if (!agents.some((a) => String(a.id) === $("#f-agent").value)) write("f-agent", ""); + $("#show-gated").hidden = !$("#f-agent").value; + $("#f-more").open = Boolean(state.open); + renderActive(); + await load({ keep: state.count || PAGE }); + window.scrollTo(0, state.y || 0); + } + document.addEventListener("DOMContentLoaded", async () => { try { - await Promise.all([loadCompanies(), loadApplications(), loadAgents()]); + await Promise.all([loadCompanies(), loadTracked(), loadAgents()]); } catch (err) { return; } renderAgentSelect(); - prefill(); - await loadRoles(); + const state = cameBack() ? kept() : null; + if (state) { + await restore(state); + } else { + prefill(); + renderActive(); + await load(); + } - const refetch = debounce(loadRoles, 300); + new IntersectionObserver((entries) => { + if (entries.some((e) => e.isIntersecting)) load({ append: true }); + }, { rootMargin: "600px" }).observe($("#roles-end")); + + const refetch = debounce(reload, 300); for (const key of ["q", "company", "place"]) { $(`#f-${key}`).addEventListener("input", refetch); } - for (const sel of ["#f-function", "#f-remote", "#f-days", "#f-show-muted", "#f-gated"]) { - $(sel).addEventListener("change", loadRoles); + for (const sel of ["#f-function", "#f-remote", "#f-days", "#f-judged", "#f-show-muted", + "#f-gated"]) { + $(sel).addEventListener("change", reload); } $("#f-agent").addEventListener("change", () => { $("#show-gated").hidden = !$("#f-agent").value; - loadRoles(); + reload(); }); $("#filters").addEventListener("submit", (e) => e.preventDefault()); + + // Kept on the way out, whichever way that is, so back finds it. + window.addEventListener("pagehide", keep); + // Back from the read page without a reload (the back/forward cache): the + // rows are the ones left, but a vote or a star may have changed there. + window.addEventListener("pageshow", async (e) => { + if (!e.persisted) return; + const y = window.scrollY; + await Promise.all([loadTracked(), loadCompanies()]).catch(() => {}); + await load({ keep: items.length }); + window.scrollTo(0, y); + }); }); })(); diff --git a/app/storage/store.py b/app/storage/store.py index c1318ed..a30f562 100644 --- a/app/storage/store.py +++ b/app/storage/store.py @@ -48,6 +48,23 @@ GIVE_UP_AFTER = 3 _EXTRACT_WAITING = (f"extracted_at IS NULL AND closed_at IS NULL " f"AND extract_tries < {GIVE_UP_AFTER}") +#: What a vote may be: 1 like, 0 neither way, -1 pass, None unjudged. +VOTES = (-1, 0, 1, None) + +#: The `judged` filter of `Store.roles`, as a `WHERE` on `roles.vote`. A +#: neutral vote is judged, and is neither liked nor passed. +JUDGED: dict[str, str] = { + "liked": "roles.vote = 1", + "unjudged": "roles.vote IS NULL", + "passed": "roles.vote = -1", +} + +#: A ranking's score as `Store.roles` serves and orders it: halved by a pass, +#: lifted a fifth by a like, capped at 1. Applied at read time, so a vote +#: moves the role at once and the stored score stays what `score` computed. +_VOTED_SCORE = ("MIN(1.0, s.score * CASE roles.vote WHEN -1 THEN 0.5 " + "WHEN 1 THEN 1.2 ELSE 1 END)") + _COMPANY_FIELDS = ("name", "domain", "affinity", "status", "careers_url", "notes") _SUBSCRIPTION_FIELDS = ("label", "company", "board", "params", "subscribed", "fetch", "show", "target_id") @@ -267,18 +284,35 @@ class Store: row = self._row("SELECT * FROM roles WHERE uid=?", (uid,)) return Role.from_row(row) if row else None + def set_vote(self, uid: str, value: int | None) -> Role: + """Judge one role: 1 like, 0 neither way, -1 pass, None unjudged again. + Stamps `voted_at`, or clears it with the vote. A vote never hides a + role; it moves it in a ranking (see `roles`). Raises ValueError for + another value and KeyError for an unknown uid.""" + if isinstance(value, bool) or value not in VOTES: + raise ValueError(f"a vote is -1, 0 or 1, not {value!r}") + stamp = None if value is None else self.now() + if not self._write("UPDATE roles SET vote=?, voted_at=? WHERE uid=?", + (value, stamp, uid)): + raise KeyError(uid) + role = self.role(uid) + assert role is not None + return role + def roles(self, limit: int = 100, company: str | None = None, place: str | None = None, open_only: bool = True, q: str | None = None, function: str | None = None, remote: str | None = None, days: int | None = None, hide_muted: bool = False, agent: int | None = None, - gated: bool = False) -> list[ScoredRole]: + gated: bool = False, judged: str | None = None, + offset: int = 0) -> list[ScoredRole]: """Newest first by `first_seen`. `company` and `place` are case-insensitive substrings of the columns a board wrote — not the key, so a search does not have to know the exact slug a company folds to. `q` is matched word by word against `title`; a role must match every word. `function` and `remote` match a gate column exactly. `days` keeps only roles first seen within that many days of now. + `judged` is a key of `JUDGED`: liked, unjudged or passed. `hide_muted` excludes a muted company's roles before `limit` is applied, in SQL rather than after the fact: a company that has @@ -290,8 +324,47 @@ class Store: `agent` orders by that agent's score instead, highest first, and carries `score` and `gated_reason` on each row. Only roles it has - scored are listed, and a gated one only when `gated` is set.""" - where, params = [], [] + scored are listed, and a gated one only when `gated` is set. The score + is the stored one moved by the role's vote (`_VOTED_SCORE`), so a vote + shows in the order at once and needs no rescore. + + `offset` skips that many rows of the same order, for the page that + loads the next 60 as it is scrolled; `count_roles` is the total.""" + sql, params = self._roles_from( + company=company, place=place, open_only=open_only, q=q, function=function, + remote=remote, days=days, hide_muted=hide_muted, agent=agent, gated=gated, + judged=judged) + if agent is None: + select = "SELECT roles.* " + order = "roles.first_seen DESC, roles.uid" + else: + select = f"SELECT roles.*, {_VOTED_SCORE} AS score, s.gated_reason " + order = "score DESC, roles.first_seen DESC, roles.uid" + return [ScoredRole.from_row(r) for r in self._rows( + f"{select}{sql} ORDER BY {order} LIMIT ? OFFSET ?", [*params, limit, offset])] + + def count_roles(self, company: str | None = None, place: str | None = None, + open_only: bool = True, q: str | None = None, + function: str | None = None, remote: str | None = None, + days: int | None = None, hide_muted: bool = False, + agent: int | None = None, gated: bool = False, + judged: str | None = None) -> int: + """How many roles `roles` would list with the same filters and no limit.""" + sql, params = self._roles_from( + company=company, place=place, open_only=open_only, q=q, function=function, + remote=remote, days=days, hide_muted=hide_muted, agent=agent, gated=gated, + judged=judged) + row = self._row(f"SELECT COUNT(*) AS n {sql}", params) + return int(row["n"]) if row else 0 + + def _roles_from(self, *, company: str | None, place: str | None, open_only: bool, + q: str | None, function: str | None, remote: str | None, + days: int | None, hide_muted: bool, agent: int | None, + gated: bool, judged: str | None) -> tuple[str, list[Any]]: + """The `FROM ... WHERE ...` that `roles` and `count_roles` share, with + its parameters in order.""" + where: list[str] = [] + params: list[Any] = [] if company: where.append("company LIKE ? ESCAPE '\\'") params.append(_like(company)) @@ -310,6 +383,10 @@ class Store: for word in (q or "").split(): where.append("title LIKE ? ESCAPE '\\'") params.append(_like(word)) + if judged: + if judged not in JUDGED: + raise ValueError(f"judged is {', '.join(JUDGED)}, not {judged!r}") + where.append(JUDGED[judged]) if open_only: where.append("closed_at IS NULL") if hide_muted: @@ -317,20 +394,15 @@ class Store: "(SELECT key FROM companies WHERE affinity = -1)") joins: list[Any] = [] if agent is None: - sql = "SELECT roles.* FROM roles" - order = "roles.first_seen DESC, roles.uid" + sql = "FROM roles" else: - sql = ("SELECT roles.*, s.score, s.gated_reason FROM roles " - "JOIN scores s ON s.uid = roles.uid AND s.agent_id = ?") + sql = "FROM roles JOIN scores s ON s.uid = roles.uid AND s.agent_id = ?" joins.append(agent) if not gated: where.append("s.gated_reason = ''") - order = "s.score DESC, roles.first_seen DESC, roles.uid" if where: sql += " WHERE " + " AND ".join(where) - sql += f" ORDER BY {order} LIMIT ?" - return [ScoredRole.from_row(r) - for r in self._rows(sql, [*joins, *params, limit])] + return sql, [*joins, *params] def mark_closed(self, source: str, seen_ids: Sequence[str], subscription_id: int) -> int: @@ -781,6 +853,11 @@ class Store: row = self._row("SELECT * FROM applications WHERE id=?", (app_id,)) return Application.from_row(row) if row else None + def delete_application(self, app_id: str) -> bool: + """Drop one application and its events. Whether that is allowed (only + while it is still `saved`) is the caller's rule, not the store's.""" + return self._write("DELETE FROM applications WHERE id=?", (app_id,)) > 0 + def applications(self, status: str | None = None) -> list[Application]: sql, params = "SELECT * FROM applications", [] if status: diff --git a/app/templates/applications.html b/app/templates/applications.html index a6fca10..eb3e46d 100644 --- a/app/templates/applications.html +++ b/app/templates/applications.html @@ -3,12 +3,12 @@ {% block content %}

Applications

-

Every role you saved on the Roles tab, and where it stands. Change the status as it moves.

+

The roles you starred, and where each one stands. Change the status as it moves; while it is still Saved, unstarring the role drops it from here.

- +
- +
RoleCompanyStatusNext
RoleCompanyStatusSaved
diff --git a/app/templates/role.html b/app/templates/role.html new file mode 100644 index 0000000..a1b8304 --- /dev/null +++ b/app/templates/role.html @@ -0,0 +1,47 @@ +{% extends "base.html" %} +{% block title %}Role — roledesk{% endblock %} + +{# The read page of one role, news's reader: a bar with the back arrow, + ▲ ● ▼ ★ and ↗, then the posting. An empty shell like every page; + `static/role.js` fetches `/api/roles/{uid}` and fills it. #} +{% block content %} +
+
+ ← + + + +
+
+
+ + + + +
+

Loading…

+
+ + +
+ + + +
+
+ +
+
+{% endblock %} + +{% block scripts %} + + +{% endblock %} diff --git a/app/templates/roles.html b/app/templates/roles.html index 61e5373..1db20c2 100644 --- a/app/templates/roles.html +++ b/app/templates/roles.html @@ -3,65 +3,87 @@ {# An empty shell: `static/roles.js` fills it and drives every action. The server renders only the select options, from `app.models` and - `plugins.ats.FUNCTIONS`, so they cannot drift from what the store accepts. #} + `plugins.ats.FUNCTIONS`, so they cannot drift from what the store accepts. + + The bar is one row at any width: the order, the search box, and a Filters + toggle. The toggle is a `
` whose summary is lifted into that row + by the stylesheet, so the panel it opens is in the flow under the row and + pushes the list down rather than covering it. #} {% block content %} -
- - - - - - - - - + +
+ + +
+
+ Filters +
+ + + + + + + + +
+

    + {% endblock %} {% block scripts %} + {% endblock %} diff --git a/app/web/api.py b/app/web/api.py index 2fd5a08..5c8691b 100644 --- a/app/web/api.py +++ b/app/web/api.py @@ -9,15 +9,15 @@ This is roledesk's own API, over the same store. Every refusal is from __future__ import annotations -from datetime import timedelta -from typing import Annotated, Any +from typing import Annotated, Any, Literal from fastapi import APIRouter, HTTPException, Query, Response from pydantic import BaseModel, Field from app import jobs from app.models import ( - AFFINITY, Agent, Application, Company, Gate, ScoredRole, Status, Subscription, Weights, + AFFINITY, Agent, Application, Company, Gate, Role, ScoredRole, Status, Subscription, + Weights, ) from app.storage import Store from app.web.deps import ConfigDep, StoreDep @@ -27,6 +27,45 @@ router = APIRouter(prefix="/api", tags=["roledesk"]) # ------------------------------------------------------------------- roles +class VoteBody(BaseModel): + value: Literal[-1, 0, 1] + + +@router.get("/roles/{uid}") +def get_role(uid: str, store: StoreDep) -> Role: + """One role, open or closed, for the read page.""" + role = store.role(uid) + if role is None: + raise HTTPException(404, f"no such role: {uid}") + return role + + +@router.post("/roles/{uid}/vote") +def vote_role(uid: str, body: VoteBody, store: StoreDep) -> Role: + """1 like, 0 neither way, -1 pass. The role stays listed either way; the + vote moves it in a ranking, see `Store.roles`.""" + try: + return store.set_vote(uid, body.value) + except KeyError: + raise HTTPException(404, f"no such role: {uid}") from None + + +@router.delete("/roles/{uid}/vote") +def unvote_role(uid: str, store: StoreDep) -> Role: + """Unjudged again: what pressing the stance a role already has does.""" + try: + return store.set_vote(uid, None) + except KeyError: + raise HTTPException(404, f"no such role: {uid}") from None + + +class RolesPage(BaseModel): + """One page of roles, and how many the same filters match in all.""" + + items: list[ScoredRole] + total: int + + @router.get("/roles") def list_roles( store: StoreDep, @@ -39,19 +78,26 @@ def list_roles( show_muted: bool = False, agent: int | None = None, gated: bool = False, - limit: Annotated[int, Query(ge=1, le=1000)] = 200, -) -> list[ScoredRole]: - """Open roles, newest first. See `Store.roles` for what each filter does. + judged: Literal["", "liked", "unjudged", "passed"] = "", + offset: Annotated[int, Query(ge=0)] = 0, + limit: Annotated[int, Query(ge=1, le=1000)] = 60, +) -> RolesPage: + """Open roles, newest first, `limit` of them from `offset`, with the + total. See `Store.roles` for what each filter does. A muted company's roles are left out unless `show_muted` is set. With - `agent`, ordered by that agent's score and carrying `score` and - `gated_reason`; a gated role only with `gated=1`.""" + `agent`, ordered by that agent's score moved by the role's vote, and + carrying `score` and `gated_reason`; a gated role only with `gated=1`. + `judged` keeps the liked, the unjudged or the passed.""" if agent is not None and store.agent(agent) is None: raise HTTPException(404, f"no such agent: {agent}") - return store.roles(limit=limit, q=q or None, company=company or None, - place=place or None, function=function or None, - remote=remote or None, days=days, hide_muted=not show_muted, - agent=agent, gated=gated) + filters: dict[str, Any] = { + "q": q or None, "company": company or None, "place": place or None, + "function": function or None, "remote": remote or None, "days": days, + "hide_muted": not show_muted, "agent": agent, "gated": gated, + "judged": judged or None} + return RolesPage(items=store.roles(limit=limit, offset=offset, **filters), + total=store.count_roles(**filters)) # --------------------------------------------------------------- companies @@ -258,23 +304,35 @@ class SaveBody(BaseModel): @router.post("/applications", status_code=201) def save_role(body: SaveBody, store: StoreDep) -> Application: - """Track one role. Pressing Save twice does not double-track it: the - existing row comes back rather than a second one starting at `saved` - over whatever status it has since moved to.""" + """Track one role: the ★ on a role. Pressing it twice does not + double-track it: the existing row comes back rather than a second one + starting at `saved` over whatever status it has since moved to.""" existing = next((a for a in store.applications() if a.role_uid == body.role_uid), None) if existing is not None: return existing role = store.role(body.role_uid) if role is None: raise HTTPException(404, f"no such role: {body.role_uid}") - next_date = (store.clock() + timedelta(days=2)).date().isoformat() application = Application( role_uid=role.uid, company_key=role.company_key, role_title=role.title, - url=role.original_url, status=body.status, source=role.source, - next_action="Read the posting and decide", next_date=next_date) + url=role.original_url, status=body.status, source=role.source) return store.save_application(application) +@router.delete("/applications/{app_id}", status_code=204) +def unsave_role(app_id: str, store: StoreDep) -> Response: + """The ★ pressed again. Only while the application is still `saved`: once + it has moved on, it is history, and withdrawn is the status for that.""" + application = store.application(app_id) + if application is None: + raise HTTPException(404, f"no such application: {app_id}") + if application.status != "saved": + raise HTTPException(409, f"This application is at {application.status} already, " + "so it stays. Set it to withdrawn instead.") + store.delete_application(app_id) + return Response(status_code=204) + + @router.get("/applications") def list_applications(store: StoreDep) -> list[Application]: """Every tracked application, with the role title and company key it was diff --git a/app/web/pages.py b/app/web/pages.py index e6bf339..663c942 100644 --- a/app/web/pages.py +++ b/app/web/pages.py @@ -31,11 +31,12 @@ from collections.abc import Callable from dataclasses import dataclass from pathlib import Path -from fastapi import APIRouter, Request +from fastapi import APIRouter, HTTPException, Request from fastapi.responses import HTMLResponse, RedirectResponse from fastapi.templating import Jinja2Templates from app.models import REMOTE, STATUSES +from app.web.deps import StoreDep _ROOT = Path(__file__).resolve().parents[2] if str(_ROOT) not in sys.path: @@ -121,6 +122,16 @@ def roles(request: Request) -> HTMLResponse: remote_options=REMOTE_OPTIONS) +@router.get("/roles/{uid}", response_class=HTMLResponse) +def role(request: Request, uid: str, store: StoreDep) -> HTMLResponse: + """The read page of one role. A shell like the others, filled by + `role.js`; the lookup here only makes an unknown uid a 404 page rather + than an empty one.""" + if store.role(uid) is None: + raise HTTPException(404, f"no such role: {uid}") + return page(request, "role.html", uid=uid) + + @router.get("/applications", response_class=HTMLResponse) def applications(request: Request) -> HTMLResponse: return page(request, "applications.html", status_options=STATUS_OPTIONS) diff --git a/tests/test_storage.py b/tests/test_storage.py index bcd6894..03e1e2f 100644 --- a/tests/test_storage.py +++ b/tests/test_storage.py @@ -205,6 +205,61 @@ def test_roles_hide_muted_excludes_before_the_limit(store: Store, clock: Clock) assert {r.source_id for r in store.roles()} == {"a0", "a1", "a2", "other"} +def test_roles_page_by_offset_and_count_the_same_filter( + store: Store, clock: Clock) -> None: + for sid in ("1", "2", "3", "4"): + store.upsert_role(posting(sid, company="Acme" if sid != "4" else "Other")) + clock.tick() + assert [r.source_id for r in store.roles(limit=2, offset=1)] == ["3", "2"] + assert [r.source_id for r in store.roles(limit=2, offset=3)] == ["1"] + assert store.count_roles() == 4 + assert store.count_roles(company="acme") == 3 + store.add_company("Other", key="other", affinity=-1) + assert store.count_roles(hide_muted=True) == 3 + + +def test_a_vote_is_stamped_cleared_and_filtered(store: Store, clock: Clock) -> None: + for sid in ("up", "down", "fine", "none"): + store.upsert_role(posting(sid)) + uid = {r.source_id: r.uid for r in store.roles()} + role = store.set_vote(uid["up"], 1) + assert (role.vote, role.voted_at) == (1, clock().isoformat(timespec="seconds")) + store.set_vote(uid["down"], -1) + store.set_vote(uid["fine"], 0) + + assert [r.source_id for r in store.roles(judged="liked")] == ["up"] + assert [r.source_id for r in store.roles(judged="passed")] == ["down"] + assert [r.source_id for r in store.roles(judged="unjudged")] == ["none"] + assert store.count_roles(judged="unjudged") == 1 + with pytest.raises(ValueError, match="judged"): + store.roles(judged="maybe") + + cleared = store.set_vote(uid["up"], None) + assert (cleared.vote, cleared.voted_at) == (None, None) + with pytest.raises(ValueError): + store.set_vote(uid["up"], 2) + with pytest.raises(ValueError): + store.set_vote(uid["up"], True) + with pytest.raises(KeyError): + store.set_vote("nope", 1) + + +def test_a_vote_moves_the_served_score_and_the_order(store: Store) -> None: + for sid in ("a", "b", "c"): + store.upsert_role(posting(sid)) + uid = {r.source_id: r.uid for r in store.roles()} + agent = store.save_agent("A") + store.replace_scores(agent.id, [(uid["a"], 0.9, ""), (uid["b"], 0.5, ""), + (uid["c"], 0.4, "")]) + store.set_vote(uid["a"], -1) # 0.45 + store.set_vote(uid["c"], 1) # 0.48 + ranked = [(r.source_id, round(r.score or 0, 3)) for r in store.roles(agent=agent.id)] + assert ranked == [("b", 0.5), ("c", 0.48), ("a", 0.45)] + assert store.scores(agent.id)[uid["a"]][0] == 0.9 # the stored score is kept + store.set_vote(uid["a"], 1) + assert store.roles(agent=agent.id, limit=1)[0].score == 1.0 + + def test_mark_closed_closes_what_the_board_no_longer_lists(store: Store) -> None: sub = store.add_subscription("ats", "greenhouse:acme") other = store.add_subscription("ats", "greenhouse:other") diff --git a/tests/test_web.py b/tests/test_web.py index 141c86d..3efce41 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -71,19 +71,19 @@ def test_list_roles_filters_by_query_place_and_function( res = client.get("/api/roles", params={"q": "engineer", "place": "Berlin"}) assert res.status_code == 200 - assert {r["source_id"] for r in res.json()} == {"1", "3"} + assert {r["source_id"] for r in res.json()["items"]} == {"1", "3"} res = client.get("/api/roles", params={"function": "sales"}) - assert [r["source_id"] for r in res.json()] == ["2"] + assert [r["source_id"] for r in res.json()["items"]] == ["2"] res = client.get("/api/roles", params={"company": "other"}) - assert [r["source_id"] for r in res.json()] == ["3"] + assert [r["source_id"] for r in res.json()["items"]] == ["3"] def test_list_roles_limit_is_bounded(client: TestClient, store: Store) -> None: for i in range(3): store.upsert_role(posting(str(i))) - assert len(client.get("/api/roles", params={"limit": 1}).json()) == 1 + assert len(client.get("/api/roles", params={"limit": 1}).json()["items"]) == 1 assert client.get("/api/roles", params={"limit": 0}).status_code == 422 assert client.get("/api/roles", params={"limit": 1001}).status_code == 422 @@ -93,12 +93,12 @@ def test_muted_roles_are_hidden_unless_show_muted(client: TestClient, store: Sto store.upsert_role(posting("1", company="Acme")) store.upsert_role(posting("2", company="Other")) - assert {r["source_id"] for r in client.get("/api/roles").json()} == {"1", "2"} + assert {r["source_id"] for r in client.get("/api/roles").json()["items"]} == {"1", "2"} assert client.post("/api/companies/acme/affinity", json={"affinity": -1}).status_code == 200 - assert {r["source_id"] for r in client.get("/api/roles").json()} == {"2"} + assert {r["source_id"] for r in client.get("/api/roles").json()["items"]} == {"2"} assert {r["source_id"] for r in - client.get("/api/roles", params={"show_muted": "true"}).json()} == {"1", "2"} + client.get("/api/roles", params={"show_muted": "true"}).json()["items"]} == {"1", "2"} def test_muted_is_excluded_before_the_limit_not_after( @@ -117,7 +117,109 @@ def test_muted_is_excluded_before_the_limit_not_after( clock.tick() res = client.get("/api/roles", params={"limit": 1}) - assert [r["source_id"] for r in res.json()] == ["other"] + assert [r["source_id"] for r in res.json()["items"]] == ["other"] + assert res.json()["total"] == 1 + + +def test_list_roles_pages_by_offset_and_counts_the_total( + client: TestClient, store: Store) -> None: + clock = Clock() + store.clock = clock + for i in range(5): + store.upsert_role(posting(str(i))) + clock.tick() + + first = client.get("/api/roles", params={"limit": 2}).json() + assert [r["source_id"] for r in first["items"]] == ["4", "3"] + assert first["total"] == 5 + rest = client.get("/api/roles", params={"limit": 2, "offset": 4}).json() + assert [r["source_id"] for r in rest["items"]] == ["0"] and rest["total"] == 5 + assert client.get("/api/roles", params={"offset": 9}).json() == {"items": [], "total": 5} + assert client.get("/api/roles", params={"offset": -1}).status_code == 422 + assert len(client.get("/api/roles").json()["items"]) == 5 # default 60 + + +def test_a_vote_is_set_cleared_and_filtered_on(client: TestClient, store: Store) -> None: + for sid in ("liked", "passed", "fine", "open"): + store.upsert_role(posting(sid)) + uid = {r.source_id: r.uid for r in store.roles()} + + res = client.post(f"/api/roles/{uid['liked']}/vote", json={"value": 1}) + assert res.status_code == 200 + assert res.json()["vote"] == 1 and res.json()["voted_at"] is not None + client.post(f"/api/roles/{uid['passed']}/vote", json={"value": -1}) + client.post(f"/api/roles/{uid['fine']}/vote", json={"value": 0}) + + def judged(value: str) -> set[str]: + page = client.get("/api/roles", params={"judged": value}).json() + return {r["source_id"] for r in page["items"]} + + assert judged("liked") == {"liked"} + assert judged("passed") == {"passed"} + assert judged("unjudged") == {"open"} + assert judged("") == {"liked", "passed", "fine", "open"} # a pass is not hidden + assert client.get("/api/roles", params={"judged": "maybe"}).status_code == 422 + + cleared = client.delete(f"/api/roles/{uid['liked']}/vote") + assert cleared.status_code == 200 + assert cleared.json()["vote"] is None and cleared.json()["voted_at"] is None + assert judged("unjudged") == {"open", "liked"} + + assert client.post(f"/api/roles/{uid['open']}/vote", + json={"value": 2}).status_code == 422 + assert client.post("/api/roles/nope/vote", json={"value": 1}).status_code == 404 + assert client.delete("/api/roles/nope/vote").status_code == 404 + + +def test_a_vote_moves_a_role_in_the_ranking_at_once( + client: TestClient, store: Store) -> None: + for sid in ("a", "b", "c"): + store.upsert_role(posting(sid)) + uid = {r.source_id: r.uid for r in store.roles()} + agent = store.save_agent("A") + store.replace_scores(agent.id, [(uid["a"], 0.9, ""), (uid["b"], 0.6, ""), + (uid["c"], 0.55, "")]) + + def ranked() -> list[tuple[str, float]]: + page = client.get("/api/roles", params={"agent": agent.id}).json() + return [(r["source_id"], round(r["score"], 3)) for r in page["items"]] + + assert ranked() == [("a", 0.9), ("b", 0.6), ("c", 0.55)] + client.post(f"/api/roles/{uid['a']}/vote", json={"value": -1}) + client.post(f"/api/roles/{uid['c']}/vote", json={"value": 1}) + assert ranked() == [("c", 0.66), ("b", 0.6), ("a", 0.45)] + client.post(f"/api/roles/{uid['b']}/vote", json={"value": 0}) + client.post(f"/api/roles/{uid['a']}/vote", json={"value": 1}) + assert ranked() == [("a", 1.0), ("c", 0.66), ("b", 0.6)] # capped at 1 + + +def test_one_role_and_its_read_page(client: TestClient, store: Store) -> None: + store.upsert_role(posting("1", company="Acme", place="Berlin")) + uid = posting("1").uid + + res = client.get(f"/api/roles/{uid}") + assert res.status_code == 200 + body = res.json() + assert (body["uid"], body["company"], body["description"]) == (uid, "Acme", + "Build things.") + assert body["vote"] is None and body["summary"] == "" and body["article_text"] == "" + assert client.get("/api/roles/nope").status_code == 404 + + page = client.get(f"/roles/{uid}") + assert page.status_code == 200 + assert 'id="role"' in page.text and "/static/role.js" in page.text + assert "/static/roles.js" not in page.text + missing = client.get("/roles/nope") + assert missing.status_code == 404 and "text/html" in missing.headers["content-type"] + + +def test_the_roles_page_offers_the_judged_filter_and_hidden_companies( + client: TestClient) -> None: + page = client.get("/").text + assert 'id="f-judged"' in page and "