C2 — Volunteer profile sliders (self_comfort; verified_level untouched)
Adds the user_skills record and slider save path so a volunteer can rate their own comfort without ever moving the verified level, which stays C3's to write.
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { getUserSkills, setSelfComfort } from "@/db/userSkills";
|
||||
import { validateSelfComfort } from "@/domain/userSkills";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
const idSchema = z.string().min(1);
|
||||
|
||||
/** A slider save: a volunteer rates their own comfort for one skill. */
|
||||
const selfComfortCreateSchema = z.object({
|
||||
userId: z.string().min(1),
|
||||
skillId: z.string().min(1),
|
||||
/** 0..100, or null to clear a rating. Validated in the domain layer. */
|
||||
selfComfort: z.number().int().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 = (row: unknown) =>
|
||||
new Response(JSON.stringify({ row }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
|
||||
/**
|
||||
* Map Postgres constraint violations to client errors (see catalog route):
|
||||
* 23505 = duplicate (user_id, skill_id); 23503 = dangling user/skill FK.
|
||||
*/
|
||||
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 competency 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,
|
||||
});
|
||||
};
|
||||
|
||||
/** GET /api/dev/user-skills?userId=<id> — a volunteer's competency records. */
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const userId = idSchema.safeParse(req.nextUrl.searchParams.get("userId"));
|
||||
if (!userId.success) return bad("invalid userId");
|
||||
const rows = await getUserSkills(userId.data);
|
||||
return new Response(JSON.stringify({ rows }), { status: 200, headers: JSON_HEADERS });
|
||||
};
|
||||
|
||||
/**
|
||||
* POST /api/dev/user-skills { userId, skillId, selfComfort } — set a
|
||||
* volunteer's self-reported comfort (the profile slider). Only
|
||||
* self_comfort / self_rated_at change; verified_level is never touched.
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const body = await readBody(req);
|
||||
if (!body || typeof body !== "object") return bad("invalid body");
|
||||
const parsed = selfComfortCreateSchema.safeParse(body);
|
||||
if (!parsed.success) return bad(parsed.error.message);
|
||||
const selfComfort = parsed.data.selfComfort ?? null;
|
||||
const problems = validateSelfComfort(selfComfort);
|
||||
if (problems.length > 0) return bad(problems[0]);
|
||||
try {
|
||||
const row = await setSelfComfort(parsed.data.userId, parsed.data.skillId, selfComfort);
|
||||
return ok(row);
|
||||
} catch (err) {
|
||||
return dbError(err);
|
||||
}
|
||||
};
|
||||
+49
-5
@@ -459,14 +459,57 @@ export const positionSkills = pgTable(
|
||||
],
|
||||
);
|
||||
|
||||
/* ------------------------------------------------- user_skills (C2) */
|
||||
|
||||
/**
|
||||
* A volunteer's competency record for one skill (ARCHITECTURE §4.3). The two
|
||||
* numbers that matter — `self_comfort` (the volunteer's own 0-100 rating, the
|
||||
* signal) and `verified_level` (the mentor/admin gate) — are independent: a
|
||||
* volunteer rating their comfort never moves the verified level. C2 owns the
|
||||
* self_comfort path; C3 owns verified_level (skill_assessments).
|
||||
*/
|
||||
export const userSkills = pgTable(
|
||||
"user_skills",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
skillId: text("skill_id")
|
||||
.notNull()
|
||||
.references(() => skills.id, { onDelete: "cascade" }),
|
||||
/** 0..100 — the volunteer's own rating; null until they rate it. */
|
||||
selfComfort: integer("self_comfort"),
|
||||
/** When they last rated their own comfort. */
|
||||
selfRatedAt: timestamp("self_rated_at", { mode: "date", withTimezone: true }),
|
||||
/** Verified level — the gate. Set by a mentor/admin, never by self-report. */
|
||||
verifiedLevel: text("verified_level", { enum: SKILL_LEVELS })
|
||||
.notNull()
|
||||
.default("none"),
|
||||
/** Mentor/admin who signed off. */
|
||||
verifiedBy: text("verified_by"),
|
||||
verifiedAt: timestamp("verified_at", { mode: "date", withTimezone: true }),
|
||||
/** Volunteer agrees to teach this skill (C5 mentor designation). */
|
||||
mentorOptIn: boolean("mentor_opt_in").notNull().default(false),
|
||||
/** Maintained by the system on assignment completion — never entered by hand. */
|
||||
lastServedOn: date("last_served_on"),
|
||||
notes: text("notes"),
|
||||
},
|
||||
(table) => [
|
||||
// Unique (user_id, skill_id) — one competency record per user per skill.
|
||||
uniqueIndex("user_skills_user_skill_idx").on(table.userId, table.skillId),
|
||||
index("user_skills_skill_idx").on(table.skillId),
|
||||
],
|
||||
);
|
||||
|
||||
/* ------------------------------------------------------------- relations */
|
||||
|
||||
/**
|
||||
* Skills compose from the four catalog tables (B3). `skills` and
|
||||
* `position_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.
|
||||
* 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.
|
||||
*/
|
||||
export const usersRelations = relations(users, ({ many }) => ({
|
||||
assignments: many(assignments),
|
||||
@@ -544,6 +587,7 @@ export const schema = {
|
||||
functions,
|
||||
skills,
|
||||
positionSkills,
|
||||
userSkills,
|
||||
};
|
||||
|
||||
export type Schema = typeof schema;
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Volunteer competency records — `user_skills` (ARCHITECTURE §4.3). C2 owns the
|
||||
* self-report path: a volunteer rates their own comfort (`self_comfort`, 0-100).
|
||||
*
|
||||
* Integrity rules (enforced here, not just the UI):
|
||||
* - Two numbers, one truth. `self_comfort` is the signal; `verified_level`
|
||||
* is the gate. Setting a volunteer's comfort NEVER touches `verified_level`
|
||||
* or its audit columns (`verified_by` / `verified_at`) — those are written
|
||||
* only by C3's verify flow (skill_assessments).
|
||||
* - One record per (user, skill) — the unique index enforces it.
|
||||
*
|
||||
* `user_skills` is excluded from schema relations (FK columns sit on a unique
|
||||
* key, which trips Drizzle 0.45.4's `one()` typing), so this queries directly.
|
||||
*/
|
||||
|
||||
import { eq } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import { userSkills, skills } from "@/db/schema";
|
||||
|
||||
/**
|
||||
* Set a volunteer's self-reported comfort for one skill (the profile slider).
|
||||
* Upserts on (user_id, skill_id). Creates the record if absent (verified_level
|
||||
* defaults to "none"); otherwise updates ONLY the self-report fields. The
|
||||
* verified level and its audit columns are never touched here.
|
||||
*/
|
||||
export async function setSelfComfort(
|
||||
userId: string,
|
||||
skillId: string,
|
||||
selfComfort: number | null,
|
||||
) {
|
||||
const now = new Date();
|
||||
const selfRatedAt = selfComfort === null ? null : now;
|
||||
const [row] = await db
|
||||
.insert(userSkills)
|
||||
.values({
|
||||
id: crypto.randomUUID(),
|
||||
userId,
|
||||
skillId,
|
||||
selfComfort,
|
||||
selfRatedAt,
|
||||
verifiedLevel: "none",
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: [userSkills.userId, userSkills.skillId],
|
||||
set: { selfComfort, selfRatedAt },
|
||||
})
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
/** A user's competency records, joined to the skill for display. */
|
||||
export async function getUserSkills(userId: string) {
|
||||
return db
|
||||
.select({
|
||||
id: userSkills.id,
|
||||
userId: userSkills.userId,
|
||||
skillId: userSkills.skillId,
|
||||
selfComfort: userSkills.selfComfort,
|
||||
selfRatedAt: userSkills.selfRatedAt,
|
||||
verifiedLevel: userSkills.verifiedLevel,
|
||||
verifiedBy: userSkills.verifiedBy,
|
||||
verifiedAt: userSkills.verifiedAt,
|
||||
mentorOptIn: userSkills.mentorOptIn,
|
||||
lastServedOn: userSkills.lastServedOn,
|
||||
notes: userSkills.notes,
|
||||
name: skills.name,
|
||||
slug: skills.slug,
|
||||
})
|
||||
.from(userSkills)
|
||||
.innerJoin(skills, eq(userSkills.skillId, skills.id))
|
||||
.where(eq(userSkills.userId, userId))
|
||||
.orderBy(skills.name);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { validateSelfComfort } from "./userSkills";
|
||||
|
||||
describe("validateSelfComfort", () => {
|
||||
it("accepts null (not yet rated)", () => {
|
||||
expect(validateSelfComfort(null)).toEqual([]);
|
||||
});
|
||||
|
||||
it("accepts the full 0..100 range", () => {
|
||||
expect(validateSelfComfort(0)).toEqual([]);
|
||||
expect(validateSelfComfort(50)).toEqual([]);
|
||||
expect(validateSelfComfort(100)).toEqual([]);
|
||||
});
|
||||
|
||||
it("rejects a value above 100", () => {
|
||||
expect(validateSelfComfort(101)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("rejects a negative value", () => {
|
||||
expect(validateSelfComfort(-1)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("rejects a non-integer", () => {
|
||||
expect(validateSelfComfort(42.5)).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Volunteer competency validation (ARCHITECTURE §4.3, unit C2). Pure — no DB,
|
||||
* no imports from `src/db`.
|
||||
*
|
||||
* `self_comfort` is the volunteer's own 0-100 rating. It is nullable (null =
|
||||
* not yet rated) and must be an integer in 0..100 when present. This never
|
||||
* touches `verified_level` — that is the gate, owned by C3.
|
||||
*/
|
||||
export function validateSelfComfort(value: number | null): string[] {
|
||||
const problems: string[] = [];
|
||||
if (value === null) return problems; // not yet rated — allowed
|
||||
if (!Number.isInteger(value) || value < 0 || value > 100) {
|
||||
problems.push("self_comfort must be an integer between 0 and 100");
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
Reference in New Issue
Block a user