unit(D6): candidate ranking service (availability -> readiness -> score)
rankCandidates() implements ARCHITECTURE §5.8.4: availability-filtered first, then ranked by readiness. Reuses computeReadiness (C4), isUnavailable (D4), levelRank (C3). Pure — no DB, route, or migration. Pipeline precedence: inactive -> away -> already_serving -> unqualified -> eligible. Deterministic tie-break (score desc, name, id). Comfort lowers rank but never blocks (§7 rule 14); never-served is not stale. 18 tests (away excluded; unqualified + reason code; deterministic ordering; roster/instance gates; sort modes; picker signals). tsc/eslint/vitest (178) / next build all green.
This commit is contained in:
+20
-1
@@ -543,7 +543,26 @@ Build log for Media Team Hub. One unit per commit, top to bottom. Append after e
|
|||||||
- **Staleness takes a reference date.** The function is pure and deterministic, so `daysBetween(lastServedOn, today)` takes `today` as input rather than reading the clock — the test pins it to a fixed date.
|
- **Staleness takes a reference date.** The function is pure and deterministic, so `daysBetween(lastServedOn, today)` takes `today` as input rather than reading the clock — the test pins it to a fixed date.
|
||||||
- **Shadow mentor reuses `isMentorReady`.** A shadow slot (§7 rule 16) needs a mentor who is mentor-ready for that exact skill; the C5 predicate is called directly, and an unpaired shadow (`pairedMentor` null) is a hard conflict.
|
- **Shadow mentor reuses `isMentorReady`.** A shadow slot (§7 rule 16) needs a mentor who is mentor-ready for that exact skill; the C5 predicate is called directly, and an unpaired shadow (`pairedMentor` null) is a hard conflict.
|
||||||
|
|
||||||
**Next: D6 — candidate ranking service (availability filter → readiness → score).**
|
## D6 — Candidate ranking service (availability → readiness → score) — DONE 2026-11-18
|
||||||
|
|
||||||
|
**Scope (from BUILD-PLAN.md):** candidate ranking service — availability filter → readiness → score. Done when: Test: away user excluded; unqualified blocked with reason code; ordering deterministic. ARCHITECTURE §5.8.4 / §5.8.3.
|
||||||
|
|
||||||
|
**Delivered:**
|
||||||
|
- `src/domain/ranking.ts` — pure `rankCandidates({ position, candidates, sortBy })` returns `{ eligible, excluded }`. Pipeline is exactly §5.8.4: **availability-filtered first, then ranked by readiness**. Reuses `computeReadiness` (C4) for the score, `isUnavailable` (D4) for the blackout filter, `levelRank` (C3) for staleness. No DB, no route, no migration — the join-resolving data layer (D8/D9) passes facts in.
|
||||||
|
- `src/domain/ranking.test.ts` — 18 tests: the three DONE-when assertions (away excluded; unqualified + `core_skill_below_required` reason code; deterministic ordering), roster/instance gates (inactive, unapproved, already-serving), sort modes (bestMatch score-desc + name/id tie-break, availableOnly alphabetical), and picker signals (mentor badge, stale vs never-served, comfort-lowers-rank-never-blocks).
|
||||||
|
|
||||||
|
**Verification (all exit 0):**
|
||||||
|
- `tsc --noEmit` ✓ · `eslint .` ✓ (0 problems) · `vitest run` ✓ (**178** total; D6 = 18) · `next build` ✓
|
||||||
|
|
||||||
|
**Decisions:**
|
||||||
|
- **Precedence mirrors §5.8.4.** inactive → away → already_serving → unqualified → eligible. Availability is checked before the one-assignment-per-instance rule, matching "availability-filtered first".
|
||||||
|
- **`score` is always a number.** `computeReadiness` returns 0 for an empty skill set, so `RankedCandidate.score` is `number` (not `number | null`).
|
||||||
|
- **Null required level never blocks.** A position skill with no solo threshold is passed through as `none` to `computeReadiness`, so it still ranks but never hard-gates.
|
||||||
|
- **Comfort lowers rank, never blocks (§7 rule 14).** `comfort_below_50` is not a ranking exclusion — it only pulls the blended score down (70% level / 30% comfort).
|
||||||
|
- **Never-served is not stale.** A core skill with no `last_served_on` is a readiness concern, not a "needs refresher" — flagging a beginner as stale would mislead (same call as D5).
|
||||||
|
- **Deterministic tie-break.** bestMatch orders by score desc, then displayName, then userId; the excluded list is sorted by name then id, so a fixed input always yields the same picker order.
|
||||||
|
|
||||||
|
**Next: D7 — read-only grid UI (rows = instances, cols = positions, week nav).**
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,347 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import {
|
||||||
|
rankCandidates,
|
||||||
|
eligibleCandidates,
|
||||||
|
type RankingCandidateInput,
|
||||||
|
type RankingPositionInput,
|
||||||
|
type UnavailabilityRecord,
|
||||||
|
} from "./ranking";
|
||||||
|
|
||||||
|
/** A shared position: Audio is core (qualified), Lights is non-core (assisted). */
|
||||||
|
const audioPosition: RankingPositionInput = {
|
||||||
|
name: "Audio",
|
||||||
|
occursOn: "2026-11-22",
|
||||||
|
skills: [
|
||||||
|
{ skillId: "audio", name: "Audio", requiredLevel: "qualified", isCore: true, weight: 2 },
|
||||||
|
{ skillId: "lights", name: "Lights", requiredLevel: "assisted", isCore: false, weight: 1 },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
/** A competency record for the position's two skills. */
|
||||||
|
function comp(
|
||||||
|
verified: Record<string, "none" | "observer" | "assisted" | "qualified" | "expert">,
|
||||||
|
opts: {
|
||||||
|
comfort?: Record<string, number | null>;
|
||||||
|
lastServedOn?: string | null;
|
||||||
|
staleAfterDays?: number;
|
||||||
|
mentorReady?: boolean;
|
||||||
|
} = {},
|
||||||
|
) {
|
||||||
|
const comfort = opts.comfort ?? {};
|
||||||
|
const lastServedOn = opts.lastServedOn ?? null;
|
||||||
|
const staleAfterDays = opts.staleAfterDays ?? 120;
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
skillId: "audio",
|
||||||
|
verifiedLevel: verified.audio ?? "none",
|
||||||
|
selfComfort: comfort.audio ?? null,
|
||||||
|
lastServedOn,
|
||||||
|
staleAfterDays,
|
||||||
|
mentorReady: opts.mentorReady ?? false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
skillId: "lights",
|
||||||
|
verifiedLevel: verified.lights ?? "none",
|
||||||
|
selfComfort: comfort.lights ?? null,
|
||||||
|
lastServedOn,
|
||||||
|
staleAfterDays,
|
||||||
|
mentorReady: opts.mentorReady ?? false,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function candidate(
|
||||||
|
userId: string,
|
||||||
|
displayName: string,
|
||||||
|
overrides: Partial<RankingCandidateInput> = {},
|
||||||
|
): RankingCandidateInput {
|
||||||
|
return {
|
||||||
|
userId,
|
||||||
|
displayName,
|
||||||
|
userStatus: "active",
|
||||||
|
adminApproved: true,
|
||||||
|
competency: comp({ audio: "qualified", lights: "assisted" }),
|
||||||
|
unavailability: [],
|
||||||
|
alreadyAssignedInInstance: false,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A blackout covering the instance date. */
|
||||||
|
function blackout(userId: string): UnavailabilityRecord {
|
||||||
|
return {
|
||||||
|
id: `uv-${userId}`,
|
||||||
|
userId,
|
||||||
|
kind: "blackout",
|
||||||
|
startsOn: "2026-11-20",
|
||||||
|
endsOn: "2026-11-25",
|
||||||
|
allDay: true,
|
||||||
|
reason: "vacation",
|
||||||
|
rrule: null,
|
||||||
|
status: "active",
|
||||||
|
createdAt: new Date("2026-11-01T00:00:00Z"),
|
||||||
|
createdBy: "admin",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("rankCandidates — availability filter (D6 DONE-when: away excluded)", () => {
|
||||||
|
it("excludes an away volunteer from the eligible list", () => {
|
||||||
|
const { eligible, excluded } = rankCandidates({
|
||||||
|
position: audioPosition,
|
||||||
|
candidates: [
|
||||||
|
candidate("u1", "Available", { competency: comp({ audio: "qualified", lights: "assisted" }) }),
|
||||||
|
candidate("u2", "Away", {
|
||||||
|
competency: comp({ audio: "qualified", lights: "assisted" }),
|
||||||
|
unavailability: [blackout("u2")],
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(eligible.map((c) => c.userId)).toEqual(["u1"]);
|
||||||
|
const away = excluded.find((c) => c.userId === "u2");
|
||||||
|
expect(away?.status).toBe("away");
|
||||||
|
expect(away?.reasonCode).toBe("away");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps a volunteer whose blackout does not cover the date", () => {
|
||||||
|
const { eligible } = rankCandidates({
|
||||||
|
position: audioPosition,
|
||||||
|
candidates: [
|
||||||
|
candidate("u1", "Near", {
|
||||||
|
competency: comp({ audio: "qualified", lights: "assisted" }),
|
||||||
|
unavailability: [
|
||||||
|
{
|
||||||
|
...blackout("u1"),
|
||||||
|
startsOn: "2026-12-01",
|
||||||
|
endsOn: "2026-12-05",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(eligible.map((c) => c.userId)).toEqual(["u1"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("rankCandidates — readiness gate (D6 DONE-when: unqualified + reason code)", () => {
|
||||||
|
it("blocks a core skill below the required level with a reason code", () => {
|
||||||
|
const { eligible, excluded } = rankCandidates({
|
||||||
|
position: audioPosition,
|
||||||
|
candidates: [
|
||||||
|
candidate("u1", "Qualified", {
|
||||||
|
competency: comp({ audio: "qualified", lights: "assisted" }),
|
||||||
|
}),
|
||||||
|
candidate("u2", "Trainee", {
|
||||||
|
competency: comp({ audio: "assisted", lights: "assisted" }),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(eligible.map((c) => c.userId)).toEqual(["u1"]);
|
||||||
|
const blocked = excluded.find((c) => c.userId === "u2");
|
||||||
|
expect(blocked?.status).toBe("unqualified");
|
||||||
|
expect(blocked?.reasonCode).toBe("core_skill_below_required");
|
||||||
|
expect(blocked?.missing).toContain("Audio");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not block when the core skill is at the required level", () => {
|
||||||
|
const { eligible } = rankCandidates({
|
||||||
|
position: audioPosition,
|
||||||
|
candidates: [candidate("u1", "At", { competency: comp({ audio: "qualified", lights: "none" }) })],
|
||||||
|
});
|
||||||
|
expect(eligible.map((c) => c.userId)).toEqual(["u1"]);
|
||||||
|
expect(eligible[0].status).toBe("eligible");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not block on a non-core skill below its level", () => {
|
||||||
|
const { eligible } = rankCandidates({
|
||||||
|
position: audioPosition,
|
||||||
|
candidates: [
|
||||||
|
candidate("u1", "Low Lights", {
|
||||||
|
competency: comp({ audio: "qualified", lights: "none" }),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(eligible.map((c) => c.userId)).toEqual(["u1"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("self comfort lowers rank but never blocks", () => {
|
||||||
|
const { eligible } = rankCandidates({
|
||||||
|
position: audioPosition,
|
||||||
|
candidates: [
|
||||||
|
candidate("u1", "High Skill Low Comfort", {
|
||||||
|
competency: comp({ audio: "expert", lights: "expert" }, { comfort: { audio: 10, lights: 10 } }),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(eligible[0].status).toBe("eligible");
|
||||||
|
// Blended score pulls below the pure level score because comfort is low.
|
||||||
|
expect(eligible[0].score).toBeLessThan(100);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("rankCandidates — roster and instance gates", () => {
|
||||||
|
it("excludes an inactive volunteer", () => {
|
||||||
|
const { eligible, excluded } = rankCandidates({
|
||||||
|
position: audioPosition,
|
||||||
|
candidates: [
|
||||||
|
candidate("u1", "Inactive", {
|
||||||
|
userStatus: "inactive",
|
||||||
|
adminApproved: true,
|
||||||
|
competency: comp({ audio: "expert", lights: "expert" }),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(eligible).toHaveLength(0);
|
||||||
|
expect(excluded[0].status).toBe("inactive");
|
||||||
|
expect(excluded[0].reasonCode).toBe("inactive");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("excludes a volunteer an admin has not approved", () => {
|
||||||
|
const { eligible } = rankCandidates({
|
||||||
|
position: audioPosition,
|
||||||
|
candidates: [
|
||||||
|
candidate("u1", "Unapproved", {
|
||||||
|
userStatus: "active",
|
||||||
|
adminApproved: false,
|
||||||
|
competency: comp({ audio: "expert", lights: "expert" }),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(eligible).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("excludes a volunteer who already serves in this instance", () => {
|
||||||
|
const { eligible, excluded } = rankCandidates({
|
||||||
|
position: audioPosition,
|
||||||
|
candidates: [
|
||||||
|
candidate("u1", "Already", {
|
||||||
|
alreadyAssignedInInstance: true,
|
||||||
|
competency: comp({ audio: "expert", lights: "expert" }),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(eligible).toHaveLength(0);
|
||||||
|
expect(excluded[0].status).toBe("already_serving");
|
||||||
|
expect(excluded[0].reasonCode).toBe("already_serving");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("rankCandidates — ordering (D6 DONE-when: deterministic)", () => {
|
||||||
|
it("ranks best-match by readiness score, highest first", () => {
|
||||||
|
const { eligible } = rankCandidates({
|
||||||
|
position: audioPosition,
|
||||||
|
candidates: [
|
||||||
|
candidate("low", "Low", { competency: comp({ audio: "qualified", lights: "none" }) }),
|
||||||
|
candidate("high", "High", { competency: comp({ audio: "expert", lights: "expert" }) }),
|
||||||
|
candidate("mid", "Mid", { competency: comp({ audio: "qualified", lights: "assisted" }) }),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(eligible.map((c) => c.userId)).toEqual(["high", "mid", "low"]);
|
||||||
|
const scores = eligible.map((c) => c.score);
|
||||||
|
expect(scores).toEqual([...scores].sort((a, b) => b - a));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("breaks score ties by name then id so order is stable", () => {
|
||||||
|
// Same verified levels → same score; name then id decides the order.
|
||||||
|
const { eligible } = rankCandidates({
|
||||||
|
position: audioPosition,
|
||||||
|
candidates: [
|
||||||
|
candidate("z-user", "Zeta", { competency: comp({ audio: "qualified", lights: "assisted" }) }),
|
||||||
|
candidate("a-user", "Alpha", { competency: comp({ audio: "qualified", lights: "assisted" }) }),
|
||||||
|
candidate("m-user", "Mid", { competency: comp({ audio: "qualified", lights: "assisted" }) }),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(eligible.map((c) => c.userId)).toEqual(["a-user", "m-user", "z-user"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("availableOnly sorts eligible alphabetically by name", () => {
|
||||||
|
const { eligible } = rankCandidates({
|
||||||
|
position: audioPosition,
|
||||||
|
candidates: [
|
||||||
|
candidate("u2", "Zeta", { competency: comp({ audio: "expert", lights: "expert" }) }),
|
||||||
|
candidate("u1", "Alpha", { competency: comp({ audio: "qualified", lights: "assisted" }) }),
|
||||||
|
],
|
||||||
|
sortBy: "availableOnly",
|
||||||
|
});
|
||||||
|
expect(eligible.map((c) => c.displayName)).toEqual(["Alpha", "Zeta"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is deterministic across repeated runs", () => {
|
||||||
|
const build = () =>
|
||||||
|
rankCandidates({
|
||||||
|
position: audioPosition,
|
||||||
|
candidates: [
|
||||||
|
candidate("u3", "Cee", { competency: comp({ audio: "qualified", lights: "assisted" }) }),
|
||||||
|
candidate("u1", "Aaa", { competency: comp({ audio: "expert", lights: "expert" }) }),
|
||||||
|
candidate("u2", "Bee", { competency: comp({ audio: "qualified", lights: "assisted" }) }),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(build()).toEqual(build());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("rankCandidates — picker signals", () => {
|
||||||
|
it("flags a mentor badge on a mentor-ready core skill", () => {
|
||||||
|
const { eligible } = rankCandidates({
|
||||||
|
position: audioPosition,
|
||||||
|
candidates: [
|
||||||
|
candidate("u1", "Mentor", {
|
||||||
|
competency: comp({ audio: "expert", lights: "expert" }, { mentorReady: true }),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(eligible[0].mentorReady).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("flags a stale core skill as needs refresher", () => {
|
||||||
|
const { eligible } = rankCandidates({
|
||||||
|
position: { ...audioPosition, occursOn: "2026-06-01" },
|
||||||
|
candidates: [
|
||||||
|
candidate("u1", "Stale", {
|
||||||
|
competency: comp(
|
||||||
|
{ audio: "qualified", lights: "assisted" },
|
||||||
|
{ lastServedOn: "2026-01-01", staleAfterDays: 120 },
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
// 2026-01-01 → 2026-06-01 is 151 days > 120 → stale.
|
||||||
|
expect(eligible[0].needsRefresher).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("never-served is not stale (a beginner is not a refresher)", () => {
|
||||||
|
const { eligible } = rankCandidates({
|
||||||
|
position: { ...audioPosition, occursOn: "2026-06-01" },
|
||||||
|
candidates: [
|
||||||
|
candidate("u1", "Never", {
|
||||||
|
competency: comp({ audio: "qualified", lights: "assisted" }, { lastServedOn: null }),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(eligible[0].needsRefresher).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns empty lists for an empty pool", () => {
|
||||||
|
expect(rankCandidates({ position: audioPosition, candidates: [] })).toEqual({
|
||||||
|
eligible: [],
|
||||||
|
excluded: [],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("eligibleCandidates — convenience wrapper", () => {
|
||||||
|
it("returns only the ranked eligible list", () => {
|
||||||
|
const result = eligibleCandidates({
|
||||||
|
position: audioPosition,
|
||||||
|
candidates: [
|
||||||
|
candidate("u1", "A", { competency: comp({ audio: "qualified", lights: "assisted" }) }),
|
||||||
|
candidate("u2", "B", {
|
||||||
|
competency: comp({ audio: "assisted", lights: "assisted" }),
|
||||||
|
unavailability: [blackout("u2")],
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(result.map((c) => c.userId)).toEqual(["u1"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
/**
|
||||||
|
* Candidate ranking — unit D6 (ARCHITECTURE §5.8.4, §5.8.3).
|
||||||
|
*
|
||||||
|
* Pure: no DB, no imports from `src/db`. It turns a slot's requirements and a
|
||||||
|
* pool of resolved volunteers into an ordered picker list. The pipeline is
|
||||||
|
* exactly §5.8.4: **availability-filtered first, then ranked by readiness**.
|
||||||
|
*
|
||||||
|
* 1. availability — a volunteer unavailable on the instance date is excluded
|
||||||
|
* from the eligible list (shown greyed with their blackout range).
|
||||||
|
* 2. roster gate — an inactive or not-admin-approved volunteer cannot be
|
||||||
|
* assigned at all.
|
||||||
|
* 3. one-assignment-per-instance — a volunteer who already holds an
|
||||||
|
* assignment in this instance (§7 rule 1) cannot take another.
|
||||||
|
* 4. readiness gate — a CORE skill verified below the position's required
|
||||||
|
* level blocks solo assignment with a reason code (§7 rule 13, §5.8.3).
|
||||||
|
* 5. rank — the rest are ordered by readiness score (the §5.8.3 blend),
|
||||||
|
* ties broken by name then id so the order is deterministic.
|
||||||
|
*
|
||||||
|
* It reuses the predicates it sits on: `computeReadiness` (C4) for the score,
|
||||||
|
* `isUnavailable` (D4) for the blackout filter, `levelRank` (C3) for staleness.
|
||||||
|
* The data layer (D8/D9) resolves the joins and passes the facts in.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import {
|
||||||
|
computeReadiness,
|
||||||
|
type SkillReadinessInput,
|
||||||
|
type SkillLevel,
|
||||||
|
} from "./readiness";
|
||||||
|
import { isUnavailable, type UnavailabilityRecord } from "./availability";
|
||||||
|
|
||||||
|
export { computeReadiness };
|
||||||
|
export type { SkillReadinessInput, UnavailabilityRecord };
|
||||||
|
|
||||||
|
/** A position's required skills (its `position_skills` rows). */
|
||||||
|
export interface PositionSkill {
|
||||||
|
skillId: string;
|
||||||
|
name: string;
|
||||||
|
/** Minimum verified level to run solo; null = no threshold, never blocks. */
|
||||||
|
requiredLevel: SkillLevel | null;
|
||||||
|
/** Core skills gate hard; non-core skills only rank. */
|
||||||
|
isCore: boolean;
|
||||||
|
/** 1..5 — weight in the readiness score. */
|
||||||
|
weight: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A volunteer's competency on one skill (the caller resolves the join). */
|
||||||
|
export interface CandidateSkill {
|
||||||
|
skillId: string;
|
||||||
|
/** Verified level — the gate. */
|
||||||
|
verifiedLevel: SkillLevel;
|
||||||
|
/** Self-reported comfort 0..100, or null when never rated. */
|
||||||
|
selfComfort: number | null;
|
||||||
|
/** Last completed assignment on this skill (YYYY-MM-DD), or null. */
|
||||||
|
lastServedOn: string | null;
|
||||||
|
/** Days without a service before the skill is stale (§5.8.7). */
|
||||||
|
staleAfterDays: number;
|
||||||
|
/** Mentor-ready for this skill (§5.8.5) — drives the mentor badge. */
|
||||||
|
mentorReady: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RankingCandidateInput {
|
||||||
|
userId: string;
|
||||||
|
/** Display name — the alphabetical tie-break for `availableOnly`. */
|
||||||
|
displayName: string;
|
||||||
|
/** The volunteer's roster status (§7 gating). */
|
||||||
|
userStatus: string;
|
||||||
|
/** An admin has approved the volunteer. */
|
||||||
|
adminApproved: boolean;
|
||||||
|
/** The volunteer's competency per skill, keyed by skillId. */
|
||||||
|
competency: CandidateSkill[];
|
||||||
|
/** The volunteer's active blackout records (D4). */
|
||||||
|
unavailability: UnavailabilityRecord[];
|
||||||
|
/** True when the volunteer already holds an assignment in this instance. */
|
||||||
|
alreadyAssignedInInstance: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RankingPositionInput {
|
||||||
|
name: string;
|
||||||
|
/** The instance local date (YYYY-MM-DD) the picker is open for. */
|
||||||
|
occursOn: string;
|
||||||
|
skills: PositionSkill[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type RankingSortMode = "bestMatch" | "availableOnly";
|
||||||
|
|
||||||
|
/** A candidate's place in the picker. `eligible` is ranked; the rest are
|
||||||
|
* greyed with their reason. */
|
||||||
|
export type CandidateStatus =
|
||||||
|
| "eligible"
|
||||||
|
| "inactive"
|
||||||
|
| "away"
|
||||||
|
| "already_serving"
|
||||||
|
| "unqualified";
|
||||||
|
|
||||||
|
/** Why a candidate is not eligible — one per exclusion reason. */
|
||||||
|
export type RankingReasonCode =
|
||||||
|
| "inactive"
|
||||||
|
| "away"
|
||||||
|
| "already_serving"
|
||||||
|
| "core_skill_below_required";
|
||||||
|
|
||||||
|
export interface RankedCandidate {
|
||||||
|
userId: string;
|
||||||
|
displayName: string;
|
||||||
|
status: CandidateStatus;
|
||||||
|
/** Readiness score 0..100 (computeReadiness always returns a number). */
|
||||||
|
score: number;
|
||||||
|
/** Reason code when not eligible, else null. */
|
||||||
|
reasonCode: RankingReasonCode | null;
|
||||||
|
/** Core skill names below the required level (the "Why?" popover). */
|
||||||
|
missing: string[];
|
||||||
|
/** Per-skill verified level + comfort for the breakdown. */
|
||||||
|
breakdown: { name: string; verifiedLevel: SkillLevel; selfComfort: number | null }[];
|
||||||
|
/** True when the volunteer is mentor-ready for a core skill (§5.8.5). */
|
||||||
|
mentorReady: boolean;
|
||||||
|
/** True when a core skill is stale (§5.8.7) — "needs refresher". */
|
||||||
|
needsRefresher: boolean;
|
||||||
|
/** Earliest last_served_on across the position's core skills, or null. */
|
||||||
|
lastServedOn: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RankingResult {
|
||||||
|
/** Eligible volunteers, best-match (or available-only) first. */
|
||||||
|
eligible: RankedCandidate[];
|
||||||
|
/** Everyone else, greyed with their status/reason, deterministically ordered. */
|
||||||
|
excluded: RankedCandidate[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whole days between two YYYY-MM-DD dates (to - inclusive). */
|
||||||
|
function daysBetween(from: string, to: string): number {
|
||||||
|
const msPerDay = 86_400_000;
|
||||||
|
return Math.round(
|
||||||
|
(Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) /
|
||||||
|
msPerDay,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Join a candidate's competency onto the position's skills, producing the
|
||||||
|
* `SkillReadinessInput` set `computeReadiness` expects. A skill the candidate
|
||||||
|
* never touched is `none`. A null required level means no solo threshold, so
|
||||||
|
* it never blocks — passed through as `none`. */
|
||||||
|
function toReadinessSkills(
|
||||||
|
positionSkills: readonly PositionSkill[],
|
||||||
|
competency: readonly CandidateSkill[],
|
||||||
|
): SkillReadinessInput[] {
|
||||||
|
return positionSkills.map((skill) => {
|
||||||
|
const comp = competency.find((c) => c.skillId === skill.skillId);
|
||||||
|
return {
|
||||||
|
name: skill.name,
|
||||||
|
isCore: skill.isCore,
|
||||||
|
requiredLevel: skill.requiredLevel ?? "none",
|
||||||
|
weight: skill.weight,
|
||||||
|
verifiedLevel: comp?.verifiedLevel ?? "none",
|
||||||
|
selfComfort: comp?.selfComfort ?? null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Classify one candidate against the position. Precedence mirrors §5.8.4:
|
||||||
|
* roster gate, then availability, then the one-assignment-per-instance rule,
|
||||||
|
* then the readiness gate. */
|
||||||
|
function classify(
|
||||||
|
position: RankingPositionInput,
|
||||||
|
candidate: RankingCandidateInput,
|
||||||
|
): RankedCandidate {
|
||||||
|
const readinessSkills = toReadinessSkills(position.skills, candidate.competency);
|
||||||
|
const readiness = computeReadiness(readinessSkills);
|
||||||
|
|
||||||
|
const breakdown = readinessSkills.map((s) => ({
|
||||||
|
name: s.name,
|
||||||
|
verifiedLevel: s.verifiedLevel,
|
||||||
|
selfComfort: s.selfComfort,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Mentor badge: mentor-ready on any CORE skill the position lists.
|
||||||
|
const mentorReady = position.skills.some(
|
||||||
|
(p) =>
|
||||||
|
p.isCore &&
|
||||||
|
candidate.competency.find((c) => c.skillId === p.skillId)?.mentorReady ===
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Needs refresher: any CORE skill untouched past its stale threshold.
|
||||||
|
// Never-served (null) is a readiness concern, not stale — see D5.
|
||||||
|
const coreSkills = candidate.competency.filter((c) =>
|
||||||
|
position.skills.some((p) => p.skillId === c.skillId && p.isCore),
|
||||||
|
);
|
||||||
|
const needsRefresher = coreSkills.some(
|
||||||
|
(c) =>
|
||||||
|
c.lastServedOn != null &&
|
||||||
|
daysBetween(c.lastServedOn, position.occursOn) > c.staleAfterDays,
|
||||||
|
);
|
||||||
|
const lastServedOn = coreSkills
|
||||||
|
.map((c) => c.lastServedOn)
|
||||||
|
.filter((d): d is string => d != null)
|
||||||
|
.sort()
|
||||||
|
.at(0) ?? null;
|
||||||
|
|
||||||
|
const base: RankedCandidate = {
|
||||||
|
userId: candidate.userId,
|
||||||
|
displayName: candidate.displayName,
|
||||||
|
status: "eligible",
|
||||||
|
score: readiness.score,
|
||||||
|
reasonCode: null,
|
||||||
|
missing: readiness.missing,
|
||||||
|
breakdown,
|
||||||
|
mentorReady,
|
||||||
|
needsRefresher,
|
||||||
|
lastServedOn,
|
||||||
|
};
|
||||||
|
|
||||||
|
// 1. Roster gate — cannot be assigned at all.
|
||||||
|
if (candidate.userStatus !== "active" || !candidate.adminApproved) {
|
||||||
|
return { ...base, status: "inactive", reasonCode: "inactive" };
|
||||||
|
}
|
||||||
|
// 2. Availability — excluded from eligible, greyed with the blackout range.
|
||||||
|
if (isUnavailable(candidate.unavailability, position.occursOn)) {
|
||||||
|
return { ...base, status: "away", reasonCode: "away" };
|
||||||
|
}
|
||||||
|
// 3. One active assignment per instance (§7 rule 1).
|
||||||
|
if (candidate.alreadyAssignedInInstance) {
|
||||||
|
return { ...base, status: "already_serving", reasonCode: "already_serving" };
|
||||||
|
}
|
||||||
|
// 4. Readiness gate — a core skill below the required level blocks solo.
|
||||||
|
if (readiness.blocked) {
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
status: "unqualified",
|
||||||
|
reasonCode: "core_skill_below_required",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Deterministic comparator: score desc, then name, then id. */
|
||||||
|
function byBestMatch(a: RankedCandidate, b: RankedCandidate): number {
|
||||||
|
if (b.score !== a.score) return b.score - a.score;
|
||||||
|
if (a.displayName !== b.displayName) return a.displayName < b.displayName ? -1 : 1;
|
||||||
|
return a.userId < b.userId ? -1 : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Alphabetical comparator — the "available only" sort. */
|
||||||
|
function byName(a: RankedCandidate, b: RankedCandidate): number {
|
||||||
|
if (a.displayName !== b.displayName) return a.displayName < b.displayName ? -1 : 1;
|
||||||
|
return a.userId < b.userId ? -1 : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rank a pool of volunteers for one slot. Returns the eligible volunteers
|
||||||
|
* ordered by the chosen sort mode, and everyone else greyed with their reason.
|
||||||
|
* Both lists are deterministically ordered for a fixed input.
|
||||||
|
*/
|
||||||
|
export function rankCandidates(input: {
|
||||||
|
position: RankingPositionInput;
|
||||||
|
candidates: RankingCandidateInput[];
|
||||||
|
sortBy?: RankingSortMode;
|
||||||
|
}): RankingResult {
|
||||||
|
const sortBy = input.sortBy ?? "bestMatch";
|
||||||
|
const ranked = input.candidates.map((c) =>
|
||||||
|
classify(input.position, c),
|
||||||
|
);
|
||||||
|
|
||||||
|
const eligible = ranked.filter((r) => r.status === "eligible");
|
||||||
|
const excluded = ranked.filter((r) => r.status !== "eligible");
|
||||||
|
|
||||||
|
eligible.sort(
|
||||||
|
sortBy === "availableOnly" ? byName : byBestMatch,
|
||||||
|
);
|
||||||
|
// Excluded list is stable and predictable for the greyed picker rows.
|
||||||
|
excluded.sort(byName);
|
||||||
|
|
||||||
|
return { eligible, excluded };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Convenience for callers that only need the ranked, assignable list. */
|
||||||
|
export function eligibleCandidates(input: {
|
||||||
|
position: RankingPositionInput;
|
||||||
|
candidates: RankingCandidateInput[];
|
||||||
|
sortBy?: RankingSortMode;
|
||||||
|
}): RankedCandidate[] {
|
||||||
|
return rankCandidates(input).eligible;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user