Files
jobboard/app/web/pages.py
T
WolfandClaude Fable 5.1 c69fb0b6c4 Merge main: read state and tags meet per-agent votes and affinity
The per-agent migration becomes v6 behind main's v5. A vote still stamps
the role's read_at, tag counts hide the agent's hidden companies, and
/api/filters takes the agent like /api/roles.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 12:59:41 +02:00

192 lines
7.6 KiB
Python

"""The pages: two tabs, a cog, and three settings pages behind it.
`TABS` is the top bar, Roles and Applications, and `SETTINGS` is the row of
sub-tabs under the cog at `/settings/<name>`: Search agents, Sources, Account.
`base.html` renders the first, `settings/_tabs.html` the second, every page
marks itself active by its own `path`, and adding one is one entry here plus
one template. `/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, one per plugin: job boards (the
`search` plugin's queries), company boards (`ats`) and the runs that read
them, with the message log at the end. Its scripts are the ones the sections
had as pages of their own, each guarding on its own root element.
Every path a page has had before (`/agents`, `/companies`, `/sources`,
`/jobs`, `/schedules`, `/messages`, `/account`, and the six sub-tabs the
settings shell started with) answers 301 to its place now, query string
kept, so a bookmark still lands. A merged page's old path lands on its
section's anchor.
`FUNCTIONS` is `plugins.ats`'s, not `app`'s: the nine job functions are the
classifier's vocabulary, 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 and Adzuna countries on the Sources page come from
`plugins.search` for the same reason.
"""
from __future__ import annotations
import sys
from collections.abc import Callable
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.models import REMOTE, 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.ats import FUNCTIONS # noqa: E402
from plugins.search import ADZUNA_COUNTRIES, JOBINDEX_AREAS # 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"),
)
#: The sub-tabs under the cog, in order; `settings/_tabs.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"),
)
#: Where each page that used to be a tab or a sub-tab lives now. The fragment
#: is the section on the merged page; a browser keeps it across the 301.
MOVED: dict[str, str] = {
"/agents": "/settings/agents",
"/settings/ranking": "/settings/agents",
"/companies": "/settings/sources#company-boards",
"/settings/companies": "/settings/sources#company-boards",
"/sources": "/settings/sources#job-boards",
"/settings/searches": "/settings/sources#job-boards",
"/jobs": "/settings/sources#runs",
"/schedules": "/settings/sources#runs",
"/settings/pulls": "/settings/sources#runs",
"/messages": "/settings/sources#messages",
"/settings/messages": "/settings/sources#messages",
"/account": "/settings/account",
}
#: `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]
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)]
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["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, 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, 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("/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)
@router.get("/settings/account", response_class=HTMLResponse)
def account(request: Request) -> HTMLResponse:
return page(request, "settings/account.html")
def _moved(to: str) -> Callable[[Request], RedirectResponse]:
"""A 301 to `to`, carrying the query string, so `/agents?x=1` keeps it.
The query goes before `to`'s fragment, if it has one, or the browser
would read `#runs?x=1` as one fragment."""
path, _, fragment = to.partition("#")
def redirect(request: Request) -> RedirectResponse:
query = request.url.query
target = f"{path}?{query}" if query else path
return RedirectResponse(f"{target}#{fragment}" if fragment else target,
status_code=301)
return redirect
for _old, _new in MOVED.items():
router.add_api_route(_old, _moved(_new), methods=["GET"],
response_class=RedirectResponse)