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

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

172 lines
5.8 KiB
Python

"""The JSON routes the page uses: roles, companies, applications, agents.
`/api/jobs*`, `/_jobs/jobs.js` and `/ws/jobs` are `pipeline.web`'s, mounted by
`connect` in `app.py`. This is roledesk's own API, over the same store.
"""
from __future__ import annotations
from datetime import timedelta
from typing import Annotated
from fastapi import APIRouter, HTTPException, Query, Response
from pydantic import BaseModel, Field
from app.models import (
AFFINITY, Agent, Application, Company, Gate, ScoredRole, Status, Weights,
)
from app.web.deps import StoreDep
router = APIRouter(prefix="/api", tags=["roledesk"])
# ------------------------------------------------------------------- roles
@router.get("/roles")
def list_roles(
store: StoreDep,
q: str = "",
company: str = "",
place: str = "",
function: str = "",
remote: str = "",
days: int | None = None,
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.
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`."""
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)
# --------------------------------------------------------------- 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."""
key: str
name: str
board: str
affinity: int
open_roles: int
@router.get("/companies")
def list_companies(store: StoreDep) -> list[CompanyOut]:
boards = store.company_boards()
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()]
class AffinityBody(BaseModel):
affinity: int
@router.post("/companies/{key}/affinity")
def set_affinity(key: str, body: AffinityBody, store: StoreDep) -> Company:
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)
except KeyError:
raise HTTPException(404, f"no such company: {key}") from None
# ----------------------------------------------------------- applications
class SaveBody(BaseModel):
role_uid: str
status: Status = "saved"
@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."""
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)
return store.save_application(application)
@router.get("/applications")
def list_applications(store: StoreDep) -> list[Application]:
"""Every tracked application, with the role title and company key it was
saved with — enough for the page to list them without a join; the
company's full name comes from `/api/companies`, already on the page."""
return store.applications()
class StatusBody(BaseModel):
status: Status
@router.post("/applications/{app_id}/status")
def set_status(app_id: str, body: StatusBody, store: StoreDep) -> Application:
try:
return store.set_application_status(app_id, body.status)
except ValueError as exc:
raise HTTPException(422, str(exc)) from exc
except KeyError:
raise HTTPException(404, f"no such application: {app_id}") from None
# ------------------------------------------------------------------ agents
@router.get("/agents")
def list_agents(store: StoreDep) -> list[Agent]:
return store.agents()
class AgentBody(BaseModel):
"""Create when `id` is missing, replace that agent's fields when given."""
id: int | None = None
name: str = Field(min_length=1)
intent: str = ""
gates: list[Gate] = []
weights: Weights = Weights()
enabled: bool = True
@router.post("/agents")
def save_agent(body: AgentBody, store: StoreDep) -> Agent:
"""Scores are not recomputed here: that is the `score` task, which the
page starts after a save."""
try:
return store.save_agent(body.name, body.intent, body.gates, body.weights,
body.enabled, agent_id=body.id)
except ValueError as exc:
raise HTTPException(409, str(exc)) from exc
except KeyError:
raise HTTPException(404, f"no such agent: {body.id}") from None
@router.delete("/agents/{agent_id}", status_code=204)
def delete_agent(agent_id: int, store: StoreDep) -> Response:
if not store.delete_agent(agent_id):
raise HTTPException(404, f"no such agent: {agent_id}")
return Response(status_code=204)