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:
@@ -0,0 +1,18 @@
|
|||||||
|
CREATE TABLE "skill_assessments" (
|
||||||
|
"id" text PRIMARY KEY NOT NULL,
|
||||||
|
"user_id" text NOT NULL,
|
||||||
|
"skill_id" text NOT NULL,
|
||||||
|
"assessor_id" text,
|
||||||
|
"kind" text DEFAULT 'admin' NOT NULL,
|
||||||
|
"level_from" text NOT NULL,
|
||||||
|
"level_to" text NOT NULL,
|
||||||
|
"comfort_at_time" integer,
|
||||||
|
"notes" text,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
ALTER TABLE "skill_assessments" ADD CONSTRAINT "skill_assessments_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "skill_assessments" ADD CONSTRAINT "skill_assessments_skill_id_skills_id_fk" FOREIGN KEY ("skill_id") REFERENCES "public"."skills"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "skill_assessments" ADD CONSTRAINT "skill_assessments_assessor_id_users_id_fk" FOREIGN KEY ("assessor_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||||
|
CREATE INDEX "skill_assessments_user_created_idx" ON "skill_assessments" USING btree ("user_id","created_at");--> statement-breakpoint
|
||||||
|
CREATE INDEX "skill_assessments_skill_idx" ON "skill_assessments" USING btree ("skill_id");
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -43,6 +43,13 @@
|
|||||||
"when": 1794973120521,
|
"when": 1794973120521,
|
||||||
"tag": "0005_keen_lenny_balinger",
|
"tag": "0005_keen_lenny_balinger",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 6,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1794975448394,
|
||||||
|
"tag": "0006_modern_shiver_man",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { NextRequest } from "next/server";
|
||||||
|
import { listAssessments } from "@/db/assessments";
|
||||||
|
|
||||||
|
const JSON_HEADERS = { "content-type": "application/json" };
|
||||||
|
|
||||||
|
const bad = (message: string) =>
|
||||||
|
new Response(JSON.stringify({ error: message }), {
|
||||||
|
status: 400,
|
||||||
|
headers: JSON_HEADERS,
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /api/dev/skills/assessments?userId=&skillId=&limit=
|
||||||
|
*
|
||||||
|
* Append-only assessment history, newest first — the audit trail shown beside
|
||||||
|
* the verify modal. There is intentionally no update or delete endpoint.
|
||||||
|
*/
|
||||||
|
export const GET = async (req: NextRequest) => {
|
||||||
|
const params = req.nextUrl.searchParams;
|
||||||
|
const rawLimit = params.get("limit");
|
||||||
|
let limit: number | undefined;
|
||||||
|
if (rawLimit !== null) {
|
||||||
|
limit = Number(rawLimit);
|
||||||
|
if (!Number.isInteger(limit) || limit < 1) return bad("limit must be a positive integer");
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = await listAssessments({
|
||||||
|
userId: params.get("userId") ?? undefined,
|
||||||
|
skillId: params.get("skillId") ?? undefined,
|
||||||
|
limit,
|
||||||
|
});
|
||||||
|
return new Response(JSON.stringify({ rows }), { status: 200, headers: JSON_HEADERS });
|
||||||
|
};
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { NextRequest } from "next/server";
|
||||||
|
import { listSkillsMatrix } from "@/db/assessments";
|
||||||
|
import { isSkillLevel, SKILL_LEVELS, type SkillLevel } from "@/domain/assessments";
|
||||||
|
|
||||||
|
const JSON_HEADERS = { "content-type": "application/json" };
|
||||||
|
|
||||||
|
const bad = (message: string) =>
|
||||||
|
new Response(JSON.stringify({ error: message }), {
|
||||||
|
status: 400,
|
||||||
|
headers: JSON_HEADERS,
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /api/dev/skills/matrix
|
||||||
|
* ?userId= &skillId= &categoryId= &level=
|
||||||
|
*
|
||||||
|
* The admin skills matrix grid: one row per competency record (person × skill)
|
||||||
|
* with the volunteer's self-comfort and the current verified level. Filters
|
||||||
|
* compose, so `?level=qualified` answers "who is currently signed off?".
|
||||||
|
*/
|
||||||
|
export const GET = async (req: NextRequest) => {
|
||||||
|
const params = req.nextUrl.searchParams;
|
||||||
|
const level = params.get("level");
|
||||||
|
if (level !== null && !isSkillLevel(level)) {
|
||||||
|
return bad(`level must be one of: ${SKILL_LEVELS.join(", ")}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = await listSkillsMatrix({
|
||||||
|
userId: params.get("userId") ?? undefined,
|
||||||
|
skillId: params.get("skillId") ?? undefined,
|
||||||
|
categoryId: params.get("categoryId") ?? undefined,
|
||||||
|
level: (level ?? undefined) as SkillLevel | undefined,
|
||||||
|
});
|
||||||
|
return new Response(JSON.stringify({ rows }), { status: 200, headers: JSON_HEADERS });
|
||||||
|
};
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { NextRequest } from "next/server";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { AssessmentError, verifySkillLevel } from "@/db/assessments";
|
||||||
|
import { ASSESSMENT_KINDS } from "@/db/schema";
|
||||||
|
import { SKILL_LEVELS } from "@/domain/assessments";
|
||||||
|
|
||||||
|
const JSON_HEADERS = { "content-type": "application/json" };
|
||||||
|
|
||||||
|
const verifySchema = z.object({
|
||||||
|
userId: z.string().min(1),
|
||||||
|
skillId: z.string().min(1),
|
||||||
|
/** The level being signed off — validated again by the domain rule. */
|
||||||
|
level: z.enum(SKILL_LEVELS),
|
||||||
|
assessorId: z.string().min(1).nullable().optional(),
|
||||||
|
kind: z.enum(ASSESSMENT_KINDS).optional(),
|
||||||
|
notes: z.string().nullable().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
async function readBody(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
return await req.json();
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const bad = (message: string) =>
|
||||||
|
new Response(JSON.stringify({ error: message }), {
|
||||||
|
status: 400,
|
||||||
|
headers: JSON_HEADERS,
|
||||||
|
});
|
||||||
|
|
||||||
|
const ok = (payload: unknown) =>
|
||||||
|
new Response(JSON.stringify(payload), { status: 200, headers: JSON_HEADERS });
|
||||||
|
|
||||||
|
/** Postgres constraint violations → client errors (same mapping as C2). */
|
||||||
|
const dbError = (err: unknown) => {
|
||||||
|
let code: string | undefined;
|
||||||
|
let node: { code?: string; cause?: unknown } | null = err as {
|
||||||
|
code?: string;
|
||||||
|
cause?: unknown;
|
||||||
|
} | null;
|
||||||
|
while (node) {
|
||||||
|
if (node.code) {
|
||||||
|
code = node.code;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
node = (node.cause as { code?: string; cause?: unknown } | null) ?? null;
|
||||||
|
}
|
||||||
|
if (code === "23505") {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({ error: "a record already exists for this user and skill" }),
|
||||||
|
{ status: 409, headers: JSON_HEADERS },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (code === "23503") {
|
||||||
|
return new Response(JSON.stringify({ error: "referenced row does not exist" }), {
|
||||||
|
status: 400,
|
||||||
|
headers: JSON_HEADERS,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return new Response(JSON.stringify({ error: "internal error" }), {
|
||||||
|
status: 500,
|
||||||
|
headers: JSON_HEADERS,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/dev/skills/verify { userId, skillId, level, assessorId?, kind?, notes? }
|
||||||
|
*
|
||||||
|
* The verify-level modal's save: appends a `skill_assessments` row and moves
|
||||||
|
* `user_skills.verified_level` in one transaction. The volunteer's
|
||||||
|
* `self_comfort` is untouched (C2's signal is not the gate).
|
||||||
|
*/
|
||||||
|
export const POST = async (req: NextRequest) => {
|
||||||
|
const body = await readBody(req);
|
||||||
|
if (!body || typeof body !== "object") return bad("invalid body");
|
||||||
|
const parsed = verifySchema.safeParse(body);
|
||||||
|
if (!parsed.success) return bad(parsed.error.message);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await verifySkillLevel(parsed.data);
|
||||||
|
return ok(result);
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof AssessmentError) return bad(err.problems.join("; "));
|
||||||
|
return dbError(err);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -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
@@ -54,6 +54,10 @@ export type SmsConsentSource = (typeof SMS_CONSENT_SOURCES)[number];
|
|||||||
export const SKILL_LEVELS = ["none", "observer", "assisted", "qualified", "expert"] as const;
|
export const SKILL_LEVELS = ["none", "observer", "assisted", "qualified", "expert"] as const;
|
||||||
export type SkillLevel = (typeof SKILL_LEVELS)[number];
|
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";
|
const DEFAULT_TIMEZONE = "America/New_York";
|
||||||
|
|
||||||
/* ------------------------------------------------------------------ users */
|
/* ------------------------------------------------------------------ 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 */
|
/* ------------------------------------------------------------- relations */
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Skills compose from the four catalog tables (B3). `skills`,
|
* Skills compose from the four catalog tables (B3). `skills`,
|
||||||
* `position_skills` and `user_skills` are intentionally excluded from `relations`:
|
* `position_skills`, `user_skills` and `skill_assessments` are intentionally
|
||||||
* their FK columns are themselves part of composite/unique keys, which trips
|
* excluded from `relations`: their FK columns are themselves part of
|
||||||
* Drizzle 0.45.4's `one()` typing (see the B2 note). Queried directly until a
|
* composite/unique keys, which trips Drizzle 0.45.4's `one()` typing (see the
|
||||||
* working eager-load pattern exists — the grid render in I2 pre-resolves the joins.
|
* 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 }) => ({
|
export const usersRelations = relations(users, ({ many }) => ({
|
||||||
assignments: many(assignments),
|
assignments: many(assignments),
|
||||||
@@ -588,6 +632,7 @@ export const schema = {
|
|||||||
skills,
|
skills,
|
||||||
positionSkills,
|
positionSkills,
|
||||||
userSkills,
|
userSkills,
|
||||||
|
skillAssessments,
|
||||||
};
|
};
|
||||||
|
|
||||||
export type Schema = typeof schema;
|
export type Schema = typeof schema;
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import {
|
||||||
|
buildAssessment,
|
||||||
|
isSkillLevel,
|
||||||
|
levelRank,
|
||||||
|
SKILL_LEVELS,
|
||||||
|
} from "./assessments";
|
||||||
|
import { SKILL_LEVELS as DB_SKILL_LEVELS } from "@/db/schema";
|
||||||
|
|
||||||
|
describe("skill level ladder", () => {
|
||||||
|
it("orders none < observer < assisted < qualified < expert", () => {
|
||||||
|
expect(["none", "observer", "assisted", "qualified", "expert"].map(levelRank)).toEqual([
|
||||||
|
0, 1, 2, 3, 4,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the domain ladder in sync with the database enum", () => {
|
||||||
|
expect([...SKILL_LEVELS]).toEqual([...DB_SKILL_LEVELS]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("recognizes only real levels", () => {
|
||||||
|
expect(isSkillLevel("qualified")).toBe(true);
|
||||||
|
expect(isSkillLevel("grandmaster")).toBe(false);
|
||||||
|
expect(isSkillLevel(null)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("buildAssessment", () => {
|
||||||
|
it("records an upward move with level_from taken from the stored level", () => {
|
||||||
|
const result = buildAssessment({
|
||||||
|
currentLevel: "none",
|
||||||
|
newLevel: "qualified",
|
||||||
|
selfComfort: 55,
|
||||||
|
});
|
||||||
|
expect(result.ok).toBe(true);
|
||||||
|
if (!result.ok) return;
|
||||||
|
expect(result.draft).toEqual({
|
||||||
|
levelFrom: "none",
|
||||||
|
levelTo: "qualified",
|
||||||
|
comfortAtTime: 55,
|
||||||
|
direction: "up",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("records a downward move too — demotions are audited", () => {
|
||||||
|
const result = buildAssessment({
|
||||||
|
currentLevel: "expert",
|
||||||
|
newLevel: "assisted",
|
||||||
|
selfComfort: 40,
|
||||||
|
});
|
||||||
|
expect(result.ok).toBe(true);
|
||||||
|
if (!result.ok) return;
|
||||||
|
expect(result.draft.direction).toBe("down");
|
||||||
|
expect(result.draft.levelFrom).toBe("expert");
|
||||||
|
expect(result.draft.levelTo).toBe("assisted");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects an unknown new level instead of storing it", () => {
|
||||||
|
const result = buildAssessment({
|
||||||
|
currentLevel: "none",
|
||||||
|
newLevel: "grandmaster",
|
||||||
|
selfComfort: null,
|
||||||
|
});
|
||||||
|
expect(result.ok).toBe(false);
|
||||||
|
if (result.ok) return;
|
||||||
|
expect(result.problems[0]).toContain("observer");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects an unknown current level", () => {
|
||||||
|
const result = buildAssessment({
|
||||||
|
currentLevel: "",
|
||||||
|
newLevel: "qualified",
|
||||||
|
selfComfort: null,
|
||||||
|
});
|
||||||
|
expect(result.ok).toBe(false);
|
||||||
|
if (result.ok) return;
|
||||||
|
expect(result.problems[0]).toContain("unknown current level");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("refuses an unchanged level — no silent no-op row", () => {
|
||||||
|
const result = buildAssessment({
|
||||||
|
currentLevel: "assisted",
|
||||||
|
newLevel: "assisted",
|
||||||
|
selfComfort: 70,
|
||||||
|
});
|
||||||
|
expect(result.ok).toBe(false);
|
||||||
|
if (result.ok) return;
|
||||||
|
expect(result.problems[0]).toContain("unchanged");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("snapshots a null comfort when the volunteer never rated the skill", () => {
|
||||||
|
const result = buildAssessment({
|
||||||
|
currentLevel: "none",
|
||||||
|
newLevel: "observer",
|
||||||
|
selfComfort: null,
|
||||||
|
});
|
||||||
|
expect(result.ok).toBe(true);
|
||||||
|
if (!result.ok) return;
|
||||||
|
expect(result.draft.comfortAtTime).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
/**
|
||||||
|
* Skill level assessment rules — unit C3 (ARCHITECTURE §4.3, §5.8.2).
|
||||||
|
*
|
||||||
|
* Pure: no DB, no imports from `src/db`, so the rule can be tested without a
|
||||||
|
* running server. The route and the data layer both call it; neither is allowed
|
||||||
|
* to invent a level move on its own.
|
||||||
|
*
|
||||||
|
* The rules:
|
||||||
|
* - Levels are an ordered ladder: none < observer < assisted < qualified < expert.
|
||||||
|
* - A move may go up or down — demotions are audited just like promotions.
|
||||||
|
* - `level_from` is always the volunteer's *current verified level*, read from
|
||||||
|
* the database. A caller cannot rewrite history by passing it in.
|
||||||
|
* - An unchanged level records nothing; a verify that does not verify is a
|
||||||
|
* mistake, not a silent no-op row.
|
||||||
|
* - `comfort_at_time` snapshots the volunteer's current self_comfort — the
|
||||||
|
* signal the assessor saw — and is null when they never rated it.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Ordered lowest → highest. Keep in sync with the DB enum (tested). */
|
||||||
|
export const SKILL_LEVELS = ["none", "observer", "assisted", "qualified", "expert"] as const;
|
||||||
|
|
||||||
|
export type SkillLevel = (typeof SKILL_LEVELS)[number];
|
||||||
|
|
||||||
|
export function isSkillLevel(value: unknown): value is SkillLevel {
|
||||||
|
return typeof value === "string" && (SKILL_LEVELS as readonly string[]).includes(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ladder position: 0 = none, 4 = expert. -1 for a value outside the ladder. */
|
||||||
|
export function levelRank(level: string): number {
|
||||||
|
return (SKILL_LEVELS as readonly string[]).indexOf(level);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AssessmentDraft {
|
||||||
|
/** Always the current verified level at assessment time. */
|
||||||
|
levelFrom: SkillLevel;
|
||||||
|
levelTo: SkillLevel;
|
||||||
|
/** The volunteer's self_comfort at assessment time (null = never rated). */
|
||||||
|
comfortAtTime: number | null;
|
||||||
|
direction: "up" | "down";
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AssessmentResult =
|
||||||
|
| { ok: true; draft: AssessmentDraft }
|
||||||
|
| { ok: false; problems: string[] };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the row to append for a level verification. `currentLevel` and
|
||||||
|
* `newLevel` are typed as strings on purpose: both arrive from untrusted input
|
||||||
|
* (the client for `newLevel`, the DB for `currentLevel`) and are validated here.
|
||||||
|
*/
|
||||||
|
export function buildAssessment(params: {
|
||||||
|
currentLevel: string;
|
||||||
|
newLevel: string;
|
||||||
|
selfComfort: number | null;
|
||||||
|
}): AssessmentResult {
|
||||||
|
const problems: string[] = [];
|
||||||
|
|
||||||
|
if (!isSkillLevel(params.currentLevel)) {
|
||||||
|
problems.push(`unknown current level "${params.currentLevel}"`);
|
||||||
|
}
|
||||||
|
if (!isSkillLevel(params.newLevel)) {
|
||||||
|
problems.push(`level must be one of: ${SKILL_LEVELS.join(", ")}`);
|
||||||
|
}
|
||||||
|
if (problems.length > 0) return { ok: false, problems };
|
||||||
|
|
||||||
|
const currentLevel = params.currentLevel as SkillLevel;
|
||||||
|
const newLevel = params.newLevel as SkillLevel;
|
||||||
|
|
||||||
|
if (currentLevel === newLevel) {
|
||||||
|
return { ok: false, problems: ["level is unchanged — nothing to assess"] };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
draft: {
|
||||||
|
// Server-owned: the from-level comes from the stored record, never input.
|
||||||
|
levelFrom: currentLevel,
|
||||||
|
levelTo: newLevel,
|
||||||
|
comfortAtTime: params.selfComfort,
|
||||||
|
direction: levelRank(newLevel) > levelRank(currentLevel) ? "up" : "down",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user