Files
jobboard/app/web/pages.py
T
WolfandClaude Sonnet 5.5 6e6e655203 Wire freehire, Jobnet and Akademikernes Jobbank into the CLI, the Sources form, dupes and the docs
Provider names, the CLI's choices and the dupes rule's search hosts now come from readers.PROVIDERS, and the regions, work modes and remote words from the modules' REGIONS, MODES and REMOTE, read with getattr so main works before and after the readers merge.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-03 12:24:34 +02:00

214 lines
9.2 KiB
Python

"""The pages: three tabs, a cog, and three settings pages behind it.
`TABS` is the top bar, Roles, Applications and Watchlist, and `SETTINGS` is the rail
beside every page under the cog at `/settings/<name>`: Search agents,
Sources, Account. `base.html` renders the first, `settings/_rail.html` the
second, every page marks itself active by its own `path`, and adding one is
one entry here plus one template. `SECTIONS` is the rows the rail indents
under a page that is shown one section at a time, which is only Sources.
`/settings` itself is Search agents.
Every page is a shell. Each is filled and driven by its own script under
`static/` from the JSON routes in `web/api.py`; the Runs section of Sources
and the Account page are shells around the modules' own elements.
`/roles/{uid}` is the Roles page again, with that role open in its reader:
one page, so a link to a role and the role opened from the feed are the same
screen. What the server renders is only what a select needs to offer, so the
options cannot drift from what the store accepts.
Sources is one page in three sections: job boards (the `search` plugin's
queries), company boards (`ats`), and the runs that read them, which end in
the message log. One is shown at a time, the one the URL fragment names or
contains; the others stay in the page, hidden, so each section's script (the
ones they had as pages of their own, each guarding on its own root element)
keeps working.
`FUNCTIONS` and `HOSTS` are `plugins.ats`'s, not `app`'s: the nine job
functions are the classifier's vocabulary and the hosts are what it parses,
and this reaches `plugins/` the same way `app.cli` does, since a plugin is
app-agnostic and never reaches back into `app`. The
Jobindex areas, Adzuna countries, the regions of Platsbanken, Jobnet and
Jobbank, freehire's work modes and Jobbank's remote words on the Sources page
come from the search readers in `plugins/readers/` for the same reason. The
last four and the select's other providers are read from `readers.PROVIDERS`,
so the page works whether or not a provider's module is loaded.
"""
from __future__ import annotations
import sys
from dataclasses import dataclass
from pathlib import Path
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from app import jobs
from app.models import LADDER, REMOTE, RUNGS, STATUSES
from app.web.deps import StoreDep
_ROOT = Path(__file__).resolve().parents[2]
if str(_ROOT) not in sys.path:
sys.path.insert(0, str(_ROOT))
from plugins import readers # noqa: E402
from plugins.ats import FUNCTIONS, HOSTS # noqa: E402
from plugins.readers.adzuna import COUNTRIES as ADZUNA_COUNTRIES # noqa: E402
from plugins.readers.jobindex import AREAS as JOBINDEX_AREAS # noqa: E402
from plugins.readers.platsbanken import REGIONS as PLATSBANKEN_REGIONS # noqa: E402
TEMPLATE_DIR = Path(__file__).resolve().parent.parent / "templates"
STATIC_DIR = Path(__file__).resolve().parent.parent / "static"
@dataclass(frozen=True, slots=True)
class Tab:
path: str
label: str
template: str
#: The top bar, in order. One list; `base.html` is its only reader.
TABS: tuple[Tab, ...] = (
Tab("/", "Roles", "roles.html"),
Tab("/applications", "Applications", "applications.html"),
Tab("/watchlist", "Watchlist", "watchlist.html"),
)
#: The pages under the cog, in order; `settings/_rail.html` renders them.
SETTINGS: tuple[Tab, ...] = (
Tab("/settings/agents", "Search agents", "settings/agents.html"),
Tab("/settings/sources", "Sources", "settings/sources.html"),
Tab("/settings/account", "Account", "settings/account.html"),
)
#: `anchor, label` for each section of a settings page that shows one at a
#: time, keyed by the page's path. The anchor is the section's element id and
#: the fragment that picks it; the first is what the page opens on without one.
SECTIONS: dict[str, tuple[tuple[str, str], ...]] = {
"/settings/sources": (
("job-boards", "Job boards"),
("company-boards", "Company boards"),
("runs", "Runs"),
("unmapped", "Unmapped"),
),
}
#: `value, label` for each select option. `FUNCTIONS` is already the value a
#: role's `function` column holds; only the label is dressed up.
FUNCTION_OPTIONS = [(f, f.replace("/", " / ").capitalize()) for f in FUNCTIONS]
REMOTE_OPTIONS = [(r, r.capitalize()) for r in REMOTE if r]
#: The feed's Pay filter, in `Store.PAY`'s own keys — see its docstring for
#: what each one keeps.
PAY_OPTIONS = [("stated", "Stated or normalised"), ("normalised", "Normalised only"),
("stated_only", "Stated but not normalised")]
STATUS_OPTIONS = [(s, s.capitalize()) for s in STATUSES]
AREA_OPTIONS = list(JOBINDEX_AREAS.items())
COUNTRY_OPTIONS = [(c, c.upper()) for c in sorted(ADZUNA_COUNTRIES)]
REGION_OPTIONS = sorted(PLATSBANKEN_REGIONS.items(), key=lambda kv: kv[1])
#: The ATS hosts `plugins.ats` reads, for the Follow and Set board selects.
HOST_OPTIONS = list(HOSTS.items())
#: The seniority ladder as `roles.js` reads it: the rungs in order, and each
#: level's rung (an index into them) and track, so the words are `app.models`'
#: alone. The page carries it as JSON.
LADDER_JSON = {"rungs": list(RUNGS), "levels": {k: list(v) for k, v in LADDER.items()}}
def search_options() -> dict[str, list[tuple[str, str]]]:
"""The `value, label` options the Sources form's providers add to its
selects, read from `readers.PROVIDERS` on each request: the providers the
template does not name itself, and the regions of Jobnet and Jobbank,
freehire's work modes and Jobbank's remote words, each in the reader's
order and without its empty value, which the form puts first as "all". All
empty for a provider whose module is not loaded."""
def options(provider: str, table: str) -> list[tuple[str, str]]:
return [(value, label) for value, label in jobs.sources.provider_table(provider, table).items()
if value]
return {"providers": [(n, m.LABEL) for n, m in readers.PROVIDERS.items()
if n not in ("jobindex", "adzuna", "platsbanken")],
"jobnet_regions": options("jobnet", "REGIONS"),
"jobbank_regions": options("jobbank", "REGIONS"),
"modes": options("freehire", "MODES"),
"jobbank_remote": options("jobbank", "REMOTE")}
def asset(path: str) -> str:
"""A static URL stamped with the file's modification time, so a changed
file is a different URL and a cached stale copy is never the answer."""
name = path.lstrip("/")
try:
stamp = int((STATIC_DIR / name).stat().st_mtime)
except OSError:
return f"/static/{name}"
return f"/static/{name}?v={stamp}"
templates = Jinja2Templates(directory=str(TEMPLATE_DIR))
templates.env.globals["TABS"] = TABS
templates.env.globals["SETTINGS"] = SETTINGS
templates.env.globals["SECTIONS"] = SECTIONS
templates.env.globals["asset"] = asset
#: Out of the OpenAPI schema: these are pages.
router = APIRouter(include_in_schema=False)
def page(request: Request, name: str, **context: object) -> HTMLResponse:
return templates.TemplateResponse(request, name, context)
@router.get("/", response_class=HTMLResponse)
def roles(request: Request) -> HTMLResponse:
return page(request, "roles.html", functions=FUNCTION_OPTIONS,
remote_options=REMOTE_OPTIONS, pay_options=PAY_OPTIONS,
ladder=LADDER_JSON, role=None)
@router.get("/roles/{uid}", response_class=HTMLResponse)
def role(request: Request, uid: str, store: StoreDep) -> HTMLResponse:
"""The Roles page with one role open in its reader, which is where
opening a role from the feed puts the address bar. `roles.js` reads the
uid from the path; the lookup here makes an unknown uid a 404 page rather
than an empty reader, and gives the tab the role's title. `active_path`
keeps Roles lit in the top bar."""
found = store.role(uid)
if found is None:
raise HTTPException(404, f"no such role: {uid}")
return page(request, "roles.html", functions=FUNCTION_OPTIONS,
remote_options=REMOTE_OPTIONS, pay_options=PAY_OPTIONS,
ladder=LADDER_JSON, role=found, active_path="/")
@router.get("/applications", response_class=HTMLResponse)
def applications(request: Request) -> HTMLResponse:
return page(request, "applications.html", status_options=STATUS_OPTIONS)
@router.get("/watchlist", response_class=HTMLResponse)
def watchlist(request: Request) -> HTMLResponse:
return page(request, "watchlist.html")
@router.get("/settings", response_class=RedirectResponse)
def settings() -> RedirectResponse:
return RedirectResponse(SETTINGS[0].path, status_code=302)
@router.get("/settings/agents", response_class=HTMLResponse)
def agents(request: Request) -> HTMLResponse:
return page(request, "settings/agents.html")
@router.get("/settings/sources", response_class=HTMLResponse)
def sources(request: Request) -> HTMLResponse:
return page(request, "settings/sources.html", areas=AREA_OPTIONS,
countries=COUNTRY_OPTIONS, regions=REGION_OPTIONS, hosts=HOST_OPTIONS,
**search_options())
@router.get("/settings/account", response_class=HTMLResponse)
def account(request: Request) -> HTMLResponse:
return page(request, "settings/account.html")