"""The vocabulary and the SQLite store: applicants, their tags, and what happened to them. The vocabulary comes first. Every value was read off the follow-up spreadsheet; each list is the one place that names its values. The pages show the labels, the store checks the keys. Tweak here and everything follows. Then the store: three tables. An applicant is keyed by ASF id and every other fact about them is an attribute that may be empty. A tag is an (applicant, tag) pair. An event is one line of that applicant's story, with a date when one is known. The connection is synchronous sqlite3, used from an async app. The database is tiny and every query is one indexed lookup, so nothing waits long enough to matter. Revisit if that stops being true. """ from __future__ import annotations import datetime as dt import pathlib import sqlite3 from easydict import EasyDict as edict # noqa: N813 # Where an applicant stands right now. One per applicant, in the order a # person would want to read them: the ones that need something first. STATES = [ edict(key="not_applied", label="Not applied", hint="Has asked about the program but has not applied."), edict(key="applied", label="Applied", hint="Applied, waiting on the program for an answer."), edict(key="no_record", label="No record", hint="The program found no application; usually told to reapply."), edict(key="form_blocked", label="Form blocked", hint="The application form refuses them, so they cannot apply."), edict(key="held", label="On hold", hint="Told not to reapply while something is sorted out."), edict(key="approved", label="Approved, not active", hint="Approved, but the activation has not reached them."), edict(key="active", label="Active", hint="Has access."), edict(key="suspended", label="Suspended", hint="Had access; the account was suspended."), edict(key="rejected", label="Rejected", hint="The program said no."), ] STATE_KEYS = [s.key for s in STATES] STATE_LABELS = {s.key: s.label for s in STATES} DEFAULT_STATE = "applied" # What is in the way. Any number per applicant; they outlive a state change # (an applicant approved after a form problem still had the form problem). TAGS = [ edict( key="no_github_history", label="No GitHub history", hint="The form finds no contributions to an Apache repo.", ), edict(key="wrong_repo", label="Wrong repository", hint="The application named a repo other than the project's."), edict( key="activation_missing", label="Activation never arrived", hint="Approved; the activation email never came.", ), edict(key="activation_broken", label="Activation link broken", hint="Approved; the link did not work."), edict( key="corporate_account", label="Corporate account", hint="A company GitHub, or a company-paid Claude account.", ), edict( key="account_trouble", label="Account trouble", hint="Suspended, deleted, or an email that cannot be reused.", ), edict(key="non_code_role", label="Non-code role", hint="Security team, VP, writer: work the form cannot see."), edict(key="priority", label="Priority", hint="Someone asked that this one go first."), ] TAG_KEYS = [t.key for t in TAGS] TAG_LABELS = {t.key: t.label for t in TAGS} # What happened, in time order. Who said what to whom is the whole story of # a stuck application, so each event names its speaker. EVENT_KINDS = [ edict(key="applied", label="Applied", hint="The applicant submitted the form."), edict(key="reapplied", label="Reapplied", hint="Submitted it again."), edict(key="program_said", label="Program said", hint="What the program told us about this applicant."), edict(key="we_told", label="We told them", hint="What we told the applicant."), edict(key="applicant_wrote", label="Applicant wrote", hint="What the applicant told us."), edict(key="note", label="Note", hint="Anything else worth keeping."), edict(key="state", label="State changed", hint="Recorded by the tool when the state is set."), ] EVENT_KIND_KEYS = [k.key for k in EVENT_KINDS] EVENT_LABELS = {k.key: k.label for k in EVENT_KINDS} SCHEMA = """ CREATE TABLE IF NOT EXISTS applicant ( asf_id TEXT PRIMARY KEY, name TEXT NOT NULL DEFAULT '', github_login TEXT NOT NULL DEFAULT '', github_email TEXT NOT NULL DEFAULT '', claude_email TEXT NOT NULL DEFAULT '', roles TEXT NOT NULL DEFAULT '', country TEXT NOT NULL DEFAULT '', list_no INTEGER, state TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS tag ( asf_id TEXT NOT NULL REFERENCES applicant(asf_id) ON DELETE CASCADE, tag TEXT NOT NULL, PRIMARY KEY (asf_id, tag) ); CREATE TABLE IF NOT EXISTS event ( id INTEGER PRIMARY KEY, asf_id TEXT NOT NULL REFERENCES applicant(asf_id) ON DELETE CASCADE, at TEXT, kind TEXT NOT NULL, text TEXT NOT NULL, source TEXT NOT NULL DEFAULT '', recorded_at TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS event_by_applicant ON event (asf_id, id); """ # The applicant columns a form or an importer may set; state has its own call. ATTRIBUTES = ("name", "github_login", "github_email", "claude_email", "roles", "country", "list_no") class UnknownApplicantError(KeyError): pass def _now() -> str: return dt.datetime.now(dt.UTC).isoformat(timespec="seconds") def _check(value: str, allowed: list[str], what: str) -> None: if value not in allowed: raise ValueError(f"unknown {what}: {value!r}") def _check_attrs(attrs: dict) -> None: unknown = set(attrs) - set(ATTRIBUTES) if unknown: raise ValueError(f"unknown attribute: {', '.join(sorted(unknown))}") class Store: def __init__(self, path: pathlib.Path | str): self.path = pathlib.Path(path) if str(self.path) != ":memory:": self.path.parent.mkdir(parents=True, exist_ok=True) self.db = sqlite3.connect(self.path) self.db.row_factory = sqlite3.Row self.db.execute("PRAGMA foreign_keys = ON") self.db.executescript(SCHEMA) def close(self) -> None: self.db.close() # -- applicants --------------------------------------------------------- def add(self, asf_id: str, *, state: str = DEFAULT_STATE, **attrs) -> edict: """Create an applicant. An unknown attribute or state is refused, not stored.""" _check(state, STATE_KEYS, "state") _check_attrs(attrs) now = _now() columns = ["asf_id", "state", "created_at", "updated_at", *attrs] values = [asf_id, state, now, now, *attrs.values()] marks = ", ".join("?" for _ in columns) with self.db: self.db.execute(f"INSERT INTO applicant ({', '.join(columns)}) VALUES ({marks})", values) # noqa: S608 return self.get(asf_id) def get(self, asf_id: str) -> edict: row = self.db.execute("SELECT * FROM applicant WHERE asf_id = ?", (asf_id,)).fetchone() if row is None: raise UnknownApplicantError(asf_id) applicant = edict(dict(row)) tags = self.db.execute("SELECT tag FROM tag WHERE asf_id = ? ORDER BY tag", (asf_id,)) applicant.tags = [r["tag"] for r in tags] return applicant def exists(self, asf_id: str) -> bool: return self.db.execute("SELECT 1 FROM applicant WHERE asf_id = ?", (asf_id,)).fetchone() is not None def update(self, asf_id: str, **attrs) -> None: _check_attrs(attrs) if not attrs: return sets = ", ".join(f"{k} = ?" for k in attrs) with self.db: cur = self.db.execute( f"UPDATE applicant SET {sets}, updated_at = ? WHERE asf_id = ?", # noqa: S608 [*attrs.values(), _now(), asf_id], ) if cur.rowcount == 0: raise UnknownApplicantError(asf_id) def list(self, state: str | None = None) -> list[edict]: """Every applicant, or those in one state, with tags; priority first, then by name.""" if state: rows = self.db.execute("SELECT * FROM applicant WHERE state = ? ORDER BY name", (state,)) else: rows = self.db.execute("SELECT * FROM applicant ORDER BY name") applicants = [edict(dict(r)) for r in rows] tags: dict[str, list[str]] = {} for r in self.db.execute("SELECT asf_id, tag FROM tag ORDER BY tag"): tags.setdefault(r["asf_id"], []).append(r["tag"]) for a in applicants: a.tags = tags.get(a.asf_id, []) applicants.sort(key=lambda a: ("priority" not in a.tags, a.name.lower())) return applicants def counts(self) -> dict[str, int]: """How many applicants in each state; every state is present, zero included.""" counts = dict.fromkeys(STATE_KEYS, 0) for r in self.db.execute("SELECT state, COUNT(*) AS n FROM applicant GROUP BY state"): counts[r["state"]] = r["n"] return counts # -- state and tags ----------------------------------------------------- def set_state(self, asf_id: str, state: str, *, by: str = "", note: str = "") -> None: """Move an applicant to a state and record that it happened.""" _check(state, STATE_KEYS, "state") before = self.get(asf_id).state if before == state and not note: return with self.db: self.db.execute("UPDATE applicant SET state = ?, updated_at = ? WHERE asf_id = ?", (state, _now(), asf_id)) text = f"{before} -> {state}" if before != state else f"still {state}" if note: text = f"{text}: {note}" _ = self.add_event(asf_id, "state", text, at=dt.date.today().isoformat(), source=by) def set_tags(self, asf_id: str, tags: list[str]) -> None: for t in tags: _check(t, TAG_KEYS, "tag") if not self.exists(asf_id): raise UnknownApplicantError(asf_id) with self.db: self.db.execute("DELETE FROM tag WHERE asf_id = ?", (asf_id,)) self.db.executemany("INSERT INTO tag (asf_id, tag) VALUES (?, ?)", [(asf_id, t) for t in sorted(set(tags))]) def add_tag(self, asf_id: str, tag: str) -> None: _check(tag, TAG_KEYS, "tag") if not self.exists(asf_id): raise UnknownApplicantError(asf_id) with self.db: self.db.execute("INSERT OR IGNORE INTO tag (asf_id, tag) VALUES (?, ?)", (asf_id, tag)) # -- events ------------------------------------------------------------- def add_event(self, asf_id: str, kind: str, text: str, *, at: str | None = None, source: str = "") -> int: """One line of the story. ``at`` is an ISO date when known; None reads as undated.""" _check(kind, EVENT_KIND_KEYS, "event kind") if not self.exists(asf_id): raise UnknownApplicantError(asf_id) with self.db: cur = self.db.execute( "INSERT INTO event (asf_id, at, kind, text, source, recorded_at) VALUES (?, ?, ?, ?, ?, ?)", (asf_id, at or None, kind, text.strip(), source, _now()), ) return cur.lastrowid def events(self, asf_id: str) -> list[edict]: """In the order they were recorded, which is the order they were learned.""" rows = self.db.execute("SELECT * FROM event WHERE asf_id = ? ORDER BY id", (asf_id,)) return [edict(dict(r)) for r in rows]