C3 — Admin skills matrix + verify-level modal

Adds the append-only skill_assessments history and the verify path, so a
level can only move together with the row recording who moved it, from
what level, and the comfort they saw.
This commit is contained in:
Tiel Coder
2026-11-18 04:19:04 +00:00
parent a915e4236c
commit bc1dc91e35
10 changed files with 2793 additions and 4 deletions
+229
View File
@@ -0,0 +1,229 @@
/**
* Skill assessment data layer — unit C3 (ARCHITECTURE §4.3).
*
* Two responsibilities:
* 1. `verifySkillLevel` — the one write path that moves a volunteer's
* `verified_level`. It appends a `skill_assessments` row and updates
* `user_skills` in a single transaction, so a level can never move without
* its audit row. It deliberately does NOT touch `self_comfort` /
* `self_rated_at` — those are the volunteer's own signal (C2).
* 2. The read models behind the admin matrix (grid + filters) and the
* assessment history beside the verify modal.
*
* Append-only: there is no update or delete function for `skill_assessments`.
*/
import { and, asc, desc, eq, inArray, sql, type SQL } from "drizzle-orm";
import { db } from "@/db";
import {
skillAssessments,
skillCategories,
skills,
userSkills,
users,
type AssessmentKind,
type SkillLevel,
} from "@/db/schema";
import { buildAssessment } from "@/domain/assessments";
/** Validation failure from a verify request (route maps this to 400). */
export class AssessmentError extends Error {
constructor(readonly problems: string[]) {
super(problems[0] ?? "invalid assessment");
this.name = "AssessmentError";
}
}
/** Display name expression shared by the read models. */
const userName = sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`;
export type VerifyInput = {
userId: string;
skillId: string;
/** Requested new verified level (validated by the domain rule). */
level: string;
/** Mentor/admin signing off; null for self/quiz assessments. */
assessorId?: string | null;
kind?: AssessmentKind;
notes?: string | null;
};
/**
* Verify a volunteer's level: append the assessment, move the gate. Both rows
* are written in one transaction; if either fails nothing changes. Verifying a
* skill the volunteer has never rated is allowed — the `user_skills` record is
* created with `self_comfort` null (verification is not self-report).
*/
export async function verifySkillLevel(input: VerifyInput) {
return db.transaction(async (tx) => {
const [existing] = await tx
.select()
.from(userSkills)
.where(
and(eq(userSkills.userId, input.userId), eq(userSkills.skillId, input.skillId)),
)
.limit(1);
const result = buildAssessment({
currentLevel: existing?.verifiedLevel ?? "none",
newLevel: input.level,
selfComfort: existing?.selfComfort ?? null,
});
if (!result.ok) throw new AssessmentError(result.problems);
const now = new Date();
const [assessment] = await tx
.insert(skillAssessments)
.values({
id: crypto.randomUUID(),
userId: input.userId,
skillId: input.skillId,
assessorId: input.assessorId ?? null,
kind: input.kind ?? "admin",
levelFrom: result.draft.levelFrom,
levelTo: result.draft.levelTo,
comfortAtTime: result.draft.comfortAtTime,
notes: input.notes ?? null,
createdAt: now,
})
.returning();
let userSkill;
if (existing) {
[userSkill] = await tx
.update(userSkills)
.set({
verifiedLevel: result.draft.levelTo,
verifiedBy: input.assessorId ?? null,
verifiedAt: now,
// self_comfort / self_rated_at intentionally untouched (C2 rule).
})
.where(eq(userSkills.id, existing.id))
.returning();
} else {
[userSkill] = await tx
.insert(userSkills)
.values({
id: crypto.randomUUID(),
userId: input.userId,
skillId: input.skillId,
selfComfort: null,
selfRatedAt: null,
verifiedLevel: result.draft.levelTo,
verifiedBy: input.assessorId ?? null,
verifiedAt: now,
})
.returning();
}
return { assessment, userSkill };
});
}
export type MatrixFilters = {
userId?: string;
skillId?: string;
categoryId?: string;
/** Only rows currently at this verified level. */
level?: SkillLevel;
};
/**
* The admin skills matrix: one row per competency record, joined to the person
* and the skill, grouped by category → skill → person. Filters compose (all
* are ANDed). Rows without a slider or a verification simply do not exist yet;
* the grid is not a cross-product of every user and every skill.
*/
export async function listSkillsMatrix(filters: MatrixFilters = {}) {
const conditions: SQL[] = [];
if (filters.userId) conditions.push(eq(userSkills.userId, filters.userId));
if (filters.skillId) conditions.push(eq(userSkills.skillId, filters.skillId));
if (filters.categoryId) conditions.push(eq(skills.categoryId, filters.categoryId));
if (filters.level) conditions.push(eq(userSkills.verifiedLevel, filters.level));
return db
.select({
userId: userSkills.userId,
userName,
email: users.email,
skillId: userSkills.skillId,
skillName: skills.name,
categoryId: skills.categoryId,
categoryName: skillCategories.name,
selfComfort: userSkills.selfComfort,
selfRatedAt: userSkills.selfRatedAt,
verifiedLevel: userSkills.verifiedLevel,
verifiedBy: userSkills.verifiedBy,
verifiedAt: userSkills.verifiedAt,
lastServedOn: userSkills.lastServedOn,
})
.from(userSkills)
.innerJoin(users, eq(userSkills.userId, users.id))
.innerJoin(skills, eq(userSkills.skillId, skills.id))
.innerJoin(skillCategories, eq(skills.categoryId, skillCategories.id))
.where(conditions.length > 0 ? and(...conditions) : undefined)
.orderBy(
asc(skillCategories.name),
asc(skills.name),
asc(users.firstName),
asc(users.lastName),
);
}
export type AssessmentFilters = {
userId?: string;
skillId?: string;
limit?: number;
};
/**
* Assessment history, newest first — the rows the verify modal shows after a
* save. Assessor names are resolved in JS (same approach as the position
* requirements join) to avoid a second self-join alias.
*/
export async function listAssessments(filters: AssessmentFilters = {}) {
const conditions: SQL[] = [];
if (filters.userId) conditions.push(eq(skillAssessments.userId, filters.userId));
if (filters.skillId) conditions.push(eq(skillAssessments.skillId, filters.skillId));
const limit = Math.min(Math.max(filters.limit ?? 50, 1), 200);
const rows = await db
.select({
id: skillAssessments.id,
userId: skillAssessments.userId,
userName,
skillId: skillAssessments.skillId,
skillName: skills.name,
assessorId: skillAssessments.assessorId,
kind: skillAssessments.kind,
levelFrom: skillAssessments.levelFrom,
levelTo: skillAssessments.levelTo,
comfortAtTime: skillAssessments.comfortAtTime,
notes: skillAssessments.notes,
createdAt: skillAssessments.createdAt,
})
.from(skillAssessments)
.innerJoin(users, eq(skillAssessments.userId, users.id))
.innerJoin(skills, eq(skillAssessments.skillId, skills.id))
.where(conditions.length > 0 ? and(...conditions) : undefined)
.orderBy(desc(skillAssessments.createdAt))
.limit(limit);
const assessorIds = [...new Set(rows.map((row) => row.assessorId).filter(Boolean))] as string[];
const assessors =
assessorIds.length > 0
? await db
.select({
id: users.id,
name: userName,
})
.from(users)
.where(inArray(users.id, assessorIds))
: [];
const nameById = new Map(assessors.map((a) => [a.id, a.name]));
return rows.map((row) => ({
...row,
assessorName: row.assessorId ? (nameById.get(row.assessorId) ?? null) : null,
}));
}
+49 -4
View File
@@ -54,6 +54,10 @@ export type SmsConsentSource = (typeof SMS_CONSENT_SOURCES)[number];
export const SKILL_LEVELS = ["none", "observer", "assisted", "qualified", "expert"] as const;
export type SkillLevel = (typeof SKILL_LEVELS)[number];
/** Who produced an assessment row — durable evidence for the audit trail. */
export const ASSESSMENT_KINDS = ["self", "mentor", "admin", "quiz"] as const;
export type AssessmentKind = (typeof ASSESSMENT_KINDS)[number];
const DEFAULT_TIMEZONE = "America/New_York";
/* ------------------------------------------------------------------ users */
@@ -502,14 +506,54 @@ export const userSkills = pgTable(
],
);
/* ------------------------------------------- skill_assessments (C3) */
/**
* Append-only progression history (ARCHITECTURE §4.3). Every movement of a
* volunteer's verified level — up or down — writes exactly one row here, and
* there is deliberately no update or delete path: this table is the audit trail
* that answers "why was this person cleared?". `comfort_at_time` snapshots the
* volunteer's self-reported comfort at the moment of the decision, so a later
* slider move cannot rewrite the context the assessor saw.
*/
export const skillAssessments = pgTable(
"skill_assessments",
{
id: text("id").primaryKey(),
userId: text("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
skillId: text("skill_id")
.notNull()
.references(() => skills.id, { onDelete: "cascade" }),
/** Mentor/admin who signed off; null for self or quiz assessments. */
assessorId: text("assessor_id").references(() => users.id, { onDelete: "set null" }),
kind: text("kind", { enum: ASSESSMENT_KINDS }).notNull().default("admin"),
/** The verified level before this assessment (server-owned, never client-set). */
levelFrom: text("level_from", { enum: SKILL_LEVELS }).notNull(),
levelTo: text("level_to", { enum: SKILL_LEVELS }).notNull(),
/** Snapshot of `user_skills.self_comfort` when the assessment was recorded. */
comfortAtTime: integer("comfort_at_time"),
notes: text("notes"),
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
.notNull()
.defaultNow(),
},
(table) => [
index("skill_assessments_user_created_idx").on(table.userId, table.createdAt),
index("skill_assessments_skill_idx").on(table.skillId),
],
);
/* ------------------------------------------------------------- relations */
/**
* Skills compose from the four catalog tables (B3). `skills`,
* `position_skills` and `user_skills` are intentionally excluded from `relations`:
* their FK columns are themselves part of composite/unique keys, which trips
* Drizzle 0.45.4's `one()` typing (see the B2 note). Queried directly until a
* working eager-load pattern exists — the grid render in I2 pre-resolves the joins.
* `position_skills`, `user_skills` and `skill_assessments` are intentionally
* excluded from `relations`: their FK columns are themselves part of
* composite/unique keys, which trips Drizzle 0.45.4's `one()` typing (see the
* B2 note). Queried directly until a working eager-load pattern exists — the
* grid render in I2 pre-resolves the joins.
*/
export const usersRelations = relations(users, ({ many }) => ({
assignments: many(assignments),
@@ -588,6 +632,7 @@ export const schema = {
skills,
positionSkills,
userSkills,
skillAssessments,
};
export type Schema = typeof schema;