B4 — Positions + skills + requirements editor
Positions (schedulable seats) CRUD + requirements editor. Governing rule:
a position with no is_core skill refuses to save as publishable.
Schema (src/db/schema.ts):
- skills table (B4 prerequisite of position_skills): id, slug (unique),
name, category_id/technology_id/function_id FKs, dedupe_key
(category|technology|function, NULLs -> ''), mentor_min_level (default
'expert'), stale_after_days (default 120), recert_required, sort_order,
active, created_at, updated_at. All FKs ON DELETE RESTRICT.
- position_skills join: position_id, skill_id, weight, required_level,
is_core; PK (position_id, skill_id).
- roles (positions) gained active (default true) + updated_at for
soft-delete/pickers/audit.
Data layer (src/db/positions.ts): list/create/update/deactivate for
positions and skills; getPositionSkills (skills merged into
position_skills in JS); setPositionSkills (replaces the whole set);
dedupeKey() helper.
Domain (src/domain/positions.ts + .test.ts): pure publishability rule —
isPublishable(skills) = has >=1 is_core skill. 8 tests named after the
rule.
API:
- src/app/api/dev/skills/route.ts — GET/POST/PATCH (slug + dedupe_key
generated at create; slug frozen on update).
- src/app/api/dev/positions/route.ts — GET/POST/PATCH (rename/edit or
deactivate via active:false).
- src/app/api/dev/positions/requirements/route.ts — GET (list a
position's requirements) + POST (set requirements; enforces the
publishability gate: published:true with no core skill -> 400).
Migration drizzle/0004_hesitant_ezekiel.sql.
Verification: typecheck ✓ lint ✓ test ✓ (44, +8) build ✓ db:migrate ✓;
runtime smoke /tmp/b4.sh (24 checks) — publish-with-core 200,
publish-without-core 400, weight-out-of-range 400, rename slug frozen,
deactivate hides from picker but row persists.
Decisions: skills table is a B4 prerequisite; requirements editor takes
positionId in the body (Next 15.5.29 rejects an explicitly-typed
{ params: { id } } route-handler second arg); publishability gate lives
in the domain and is enforced in the route; join resolved in JS
(drizzle 0.45.4 exports no join).
This commit is contained in:
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* Positions and their skill requirements (ARCHITECTURE §4.3). B4 writes these;
|
||||
* `skills` is created here as the prerequisite of `position_skills`, while the
|
||||
* name-composition UI arrives in C1.
|
||||
*
|
||||
* Integrity rules (enforced here, not just the UI):
|
||||
* - Deactivate, never delete — `active` flips to false; the row persists so
|
||||
* assignments and ratings are preserved.
|
||||
* - Slug freezes after creation — `update*` rewrites only editable fields and
|
||||
* never touches `slug`.
|
||||
* - `position_skills` is replaced wholesale on save (delete + insert in one
|
||||
* transaction), so the stored set always matches the editor.
|
||||
*
|
||||
* Read path: `listPositions({ active: true })` returns only rows shown in
|
||||
* pickers; `active: false` returns the full set (audit).
|
||||
*/
|
||||
|
||||
import { asc, eq, inArray } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import {
|
||||
roles,
|
||||
skills,
|
||||
positionSkills,
|
||||
type SkillLevel,
|
||||
} from "@/db/schema";
|
||||
import { slugify } from "@/lib/slug";
|
||||
|
||||
/* ---------------------------------------------------------- positions */
|
||||
|
||||
export type PositionCreate = {
|
||||
name: string;
|
||||
description?: string | null;
|
||||
colorHex?: string | null;
|
||||
callTimeOffsetMinutes?: number | null;
|
||||
requiresCertification?: boolean | null;
|
||||
defaultHeadcount?: number | null;
|
||||
sortOrder?: number;
|
||||
};
|
||||
|
||||
export async function createPosition(fields: PositionCreate) {
|
||||
const [row] = await db
|
||||
.insert(roles)
|
||||
.values({
|
||||
id: crypto.randomUUID(),
|
||||
slug: slugify(fields.name),
|
||||
name: fields.name,
|
||||
description: fields.description ?? null,
|
||||
colorHex: fields.colorHex ?? null,
|
||||
callTimeOffsetMinutes: fields.callTimeOffsetMinutes ?? null,
|
||||
requiresCertification: fields.requiresCertification ?? true,
|
||||
defaultHeadcount: fields.defaultHeadcount ?? 1,
|
||||
sortOrder: fields.sortOrder ?? 0,
|
||||
})
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
export type PositionUpdate = {
|
||||
name?: string;
|
||||
description?: string | null;
|
||||
colorHex?: string | null;
|
||||
callTimeOffsetMinutes?: number | null;
|
||||
requiresCertification?: boolean | null;
|
||||
defaultHeadcount?: number | null;
|
||||
sortOrder?: number;
|
||||
};
|
||||
|
||||
/** Rename / edit — `slug` is intentionally excluded (frozen after creation). */
|
||||
export async function updatePosition(id: string, fields: PositionUpdate) {
|
||||
const patch: Record<string, unknown> = { updatedAt: new Date() };
|
||||
if (fields.name !== undefined) patch.name = fields.name;
|
||||
if (fields.description !== undefined) patch.description = fields.description;
|
||||
if (fields.colorHex !== undefined) patch.colorHex = fields.colorHex;
|
||||
if (fields.callTimeOffsetMinutes !== undefined)
|
||||
patch.callTimeOffsetMinutes = fields.callTimeOffsetMinutes;
|
||||
if (fields.requiresCertification !== undefined)
|
||||
patch.requiresCertification = fields.requiresCertification;
|
||||
if (fields.defaultHeadcount !== undefined)
|
||||
patch.defaultHeadcount = fields.defaultHeadcount;
|
||||
if (fields.sortOrder !== undefined) patch.sortOrder = fields.sortOrder;
|
||||
const [row] = await db
|
||||
.update(roles)
|
||||
.set(patch)
|
||||
.where(eq(roles.id, id))
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
/** Soft-delete: flip `active` to false. The row persists for history. */
|
||||
export async function deactivatePosition(id: string) {
|
||||
const [row] = await db
|
||||
.update(roles)
|
||||
.set({ active: false, updatedAt: new Date() })
|
||||
.where(eq(roles.id, id))
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
export type PositionRow = {
|
||||
id: string;
|
||||
slug: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
colorHex: string | null;
|
||||
callTimeOffsetMinutes: number | null;
|
||||
requiresCertification: boolean;
|
||||
defaultHeadcount: number;
|
||||
sortOrder: number;
|
||||
active: boolean;
|
||||
};
|
||||
|
||||
/** List positions. `active: true` (default) → picker rows; `active: false` → all. */
|
||||
export async function listPositions({ active = true }: { active?: boolean } = {}) {
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(roles)
|
||||
.where(active ? eq(roles.active, true) : undefined)
|
||||
.orderBy(asc(roles.sortOrder), roles.name);
|
||||
return rows as PositionRow[];
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------- skills */
|
||||
|
||||
export type SkillCreate = {
|
||||
name: string;
|
||||
categoryId: string;
|
||||
technologyId?: string | null;
|
||||
functionId?: string | null;
|
||||
description?: string | null;
|
||||
mentorMinLevel?: string | null;
|
||||
staleAfterDays?: number | null;
|
||||
recertRequired?: boolean | null;
|
||||
sortOrder?: number;
|
||||
};
|
||||
|
||||
/** Build the unique `category|technology|function` dedupe key (NULLs → ""). */
|
||||
export function dedupeKey(
|
||||
categoryId: string,
|
||||
technologyId: string | null | undefined,
|
||||
functionId: string | null | undefined,
|
||||
): string {
|
||||
return `${categoryId}|${technologyId ?? ""}|${functionId ?? ""}`;
|
||||
}
|
||||
|
||||
export async function createSkill(fields: SkillCreate) {
|
||||
const now = new Date();
|
||||
const [row] = await db
|
||||
.insert(skills)
|
||||
.values({
|
||||
id: crypto.randomUUID(),
|
||||
slug: slugify(fields.name),
|
||||
name: fields.name,
|
||||
categoryId: fields.categoryId,
|
||||
technologyId: fields.technologyId ?? null,
|
||||
functionId: fields.functionId ?? null,
|
||||
dedupeKey: dedupeKey(fields.categoryId, fields.technologyId, fields.functionId),
|
||||
description: fields.description ?? null,
|
||||
mentorMinLevel: (fields.mentorMinLevel ?? "expert") as SkillLevel,
|
||||
staleAfterDays: fields.staleAfterDays ?? 120,
|
||||
recertRequired: fields.recertRequired ?? false,
|
||||
sortOrder: fields.sortOrder ?? 0,
|
||||
active: true,
|
||||
createdAt: now,
|
||||
})
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
export type SkillUpdate = {
|
||||
name?: string;
|
||||
description?: string | null;
|
||||
mentorMinLevel?: string | null;
|
||||
staleAfterDays?: number | null;
|
||||
recertRequired?: boolean | null;
|
||||
sortOrder?: number;
|
||||
};
|
||||
|
||||
/** Rename / edit — `slug` and the composing FKs are frozen after creation. */
|
||||
export async function updateSkill(id: string, fields: SkillUpdate) {
|
||||
const patch: Record<string, unknown> = { updatedAt: new Date() };
|
||||
if (fields.name !== undefined) patch.name = fields.name;
|
||||
if (fields.description !== undefined) patch.description = fields.description;
|
||||
if (fields.mentorMinLevel !== undefined) patch.mentorMinLevel = fields.mentorMinLevel;
|
||||
if (fields.staleAfterDays !== undefined) patch.staleAfterDays = fields.staleAfterDays;
|
||||
if (fields.recertRequired !== undefined) patch.recertRequired = fields.recertRequired;
|
||||
if (fields.sortOrder !== undefined) patch.sortOrder = fields.sortOrder;
|
||||
const [row] = await db
|
||||
.update(skills)
|
||||
.set(patch)
|
||||
.where(eq(skills.id, id))
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function deactivateSkill(id: string) {
|
||||
const [row] = await db
|
||||
.update(skills)
|
||||
.set({ active: false, updatedAt: new Date() })
|
||||
.where(eq(skills.id, id))
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
/** List skills. `active: true` (default) → picker rows; `active: false` → all. */
|
||||
export async function listSkills({ active = true }: { active?: boolean } = {}) {
|
||||
return db
|
||||
.select()
|
||||
.from(skills)
|
||||
.where(active ? eq(skills.active, true) : undefined)
|
||||
.orderBy(asc(skills.sortOrder), skills.name);
|
||||
}
|
||||
|
||||
/* ------------------------------------- position_skills (requirements) */
|
||||
|
||||
export interface PositionSkillInput {
|
||||
skillId: string;
|
||||
weight?: number;
|
||||
requiredLevel?: string | null;
|
||||
isCore?: boolean;
|
||||
}
|
||||
|
||||
/** A position's skill row with the underlying skill for display. */
|
||||
export type PositionSkillRow = {
|
||||
positionId: string;
|
||||
skillId: string;
|
||||
weight: number;
|
||||
requiredLevel: string | null;
|
||||
isCore: boolean;
|
||||
name: string;
|
||||
slug: string;
|
||||
};
|
||||
|
||||
/** Read a position's requirements in sort order (join resolved in JS). */
|
||||
export async function getPositionSkills(positionId: string): Promise<PositionSkillRow[]> {
|
||||
const rows = await db
|
||||
.select({
|
||||
positionId: positionSkills.positionId,
|
||||
skillId: positionSkills.skillId,
|
||||
weight: positionSkills.weight,
|
||||
requiredLevel: positionSkills.requiredLevel,
|
||||
isCore: positionSkills.isCore,
|
||||
})
|
||||
.from(positionSkills)
|
||||
.where(eq(positionSkills.positionId, positionId))
|
||||
.orderBy(asc(positionSkills.weight));
|
||||
|
||||
if (rows.length === 0) return rows as PositionSkillRow[];
|
||||
|
||||
const skillRows = await db
|
||||
.select({ id: skills.id, name: skills.name, slug: skills.slug })
|
||||
.from(skills)
|
||||
.where(inArray(skills.id, rows.map((r) => r.skillId)));
|
||||
const byId = new Map(skillRows.map((s) => [s.id, s]));
|
||||
|
||||
return rows.map((r) => ({
|
||||
positionId: r.positionId,
|
||||
skillId: r.skillId,
|
||||
weight: r.weight,
|
||||
requiredLevel: r.requiredLevel,
|
||||
isCore: r.isCore,
|
||||
name: byId.get(r.skillId)?.name ?? "",
|
||||
slug: byId.get(r.skillId)?.slug ?? "",
|
||||
})) as PositionSkillRow[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace a position's entire requirements set (delete + insert in one
|
||||
* transaction). Weights are validated to 1..5 here so the DB never stores an
|
||||
* out-of-range value. Publishability (≥1 core skill) is the route's concern —
|
||||
* it decides whether the save is allowed to be `published`.
|
||||
*/
|
||||
export async function setPositionSkills(
|
||||
positionId: string,
|
||||
inputs: readonly PositionSkillInput[],
|
||||
): Promise<PositionSkillRow[]> {
|
||||
for (const [i, input] of inputs.entries()) {
|
||||
const weight = input.weight ?? 1;
|
||||
if (!Number.isInteger(weight) || weight < 1 || weight > 5) {
|
||||
throw new Error(`skill[${i}].weight must be an integer from 1 to 5`);
|
||||
}
|
||||
}
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
await tx
|
||||
.delete(positionSkills)
|
||||
.where(eq(positionSkills.positionId, positionId));
|
||||
for (const input of inputs) {
|
||||
await tx
|
||||
.insert(positionSkills)
|
||||
.values({
|
||||
positionId,
|
||||
skillId: input.skillId,
|
||||
weight: input.weight ?? 1,
|
||||
requiredLevel: (input.requiredLevel ?? null) as SkillLevel | null,
|
||||
isCore: input.isCore ?? false,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return getPositionSkills(positionId);
|
||||
}
|
||||
+105
-5
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* Deliberately NOT here (added in later units, do not add "while I'm in the schema"):
|
||||
* - notification_templates/rules/outbox (later)
|
||||
* - skills, position_skills, user_skills, skill_assessments, growth_goals (C1-C6)
|
||||
* - user_skills, skill_assessments, growth_goals, skill_equivalencies (C1-C6)
|
||||
* - service_role_requirements, unavailability, events, notifications outbox
|
||||
*
|
||||
* Conventions (ARCHITECTURE §4.2):
|
||||
@@ -17,7 +17,7 @@
|
||||
*/
|
||||
|
||||
import { relations, sql } from "drizzle-orm";
|
||||
import { pgTable, text, integer, boolean, timestamp, date, numeric, index, uniqueIndex, check } from "drizzle-orm/pg-core";
|
||||
import { pgTable, text, integer, boolean, timestamp, date, numeric, index, uniqueIndex, check, primaryKey } from "drizzle-orm/pg-core";
|
||||
|
||||
/* ------------------------------------------------------------------ enums */
|
||||
|
||||
@@ -46,6 +46,14 @@ export type ConfirmedVia = (typeof CONFIRMED_VIAS)[number];
|
||||
export const SMS_CONSENT_SOURCES = ["web_signup", "paper_form", "admin_import"] as const;
|
||||
export type SmsConsentSource = (typeof SMS_CONSENT_SOURCES)[number];
|
||||
|
||||
/**
|
||||
* Verified-level ladder (ARCHITECTURE §5.8). `verified_level` on a user's
|
||||
* competency record and `required_level` on a position's core skills both live
|
||||
* here — the gate vocabulary is shared, never a local string.
|
||||
*/
|
||||
export const SKILL_LEVELS = ["none", "observer", "assisted", "qualified", "expert"] as const;
|
||||
export type SkillLevel = (typeof SKILL_LEVELS)[number];
|
||||
|
||||
const DEFAULT_TIMEZONE = "America/New_York";
|
||||
|
||||
/* ------------------------------------------------------------------ users */
|
||||
@@ -125,8 +133,14 @@ export const roles = pgTable(
|
||||
requiresCertification: boolean("requires_certification").notNull().default(true),
|
||||
defaultHeadcount: integer("default_headcount").notNull().default(1),
|
||||
sortOrder: integer("sort_order").notNull().default(0),
|
||||
/** Soft-delete flag; deactivated roles drop out of pickers (B4). */
|
||||
active: boolean("active").notNull().default(true),
|
||||
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }),
|
||||
},
|
||||
(table) => [index("roles_slug_idx").on(table.slug)],
|
||||
(table) => [
|
||||
index("roles_slug_idx").on(table.slug),
|
||||
index("roles_active_idx").on(table.active),
|
||||
],
|
||||
);
|
||||
|
||||
/* -------------------------------------------------------------- services */
|
||||
@@ -256,8 +270,9 @@ export const assignments = pgTable(
|
||||
/**
|
||||
* Skill taxonomy — five admin-defined tables with zero hardcoded lists
|
||||
* (ARCHITECTURE §4.3). B3 writes the four leaf tables; `skills` (composed from
|
||||
* them) arrives in C1. Integrity rules enforced here: deactivate-only (no hard
|
||||
* delete — `ON DELETE RESTRICT` on every FK), slugs frozen after creation.
|
||||
* them) and `position_skills` arrive in B4. Integrity rules enforced here:
|
||||
* deactivate-only (no hard delete — `ON DELETE RESTRICT` on every FK), slugs
|
||||
* frozen after creation.
|
||||
*/
|
||||
|
||||
export const skillCategories = pgTable(
|
||||
@@ -368,8 +383,91 @@ export const functions = pgTable(
|
||||
],
|
||||
);
|
||||
|
||||
/* -------------------------------------------------- skills (B4) */
|
||||
|
||||
/**
|
||||
* The rated unit — what a volunteer has a level in (ARCHITECTURE §4.3).
|
||||
* Composed from the four catalog tables: category (required) + optional
|
||||
* technology + optional function. `dedupe_key` = `category|technology|function`
|
||||
* so the SQL unique constraint treats NULLs as distinct. Slug freezes after
|
||||
* creation; the composed display name is freely editable. B4 creates these as a
|
||||
* prerequisite of `position_skills`; the name-composition UI is C1.
|
||||
*/
|
||||
export const skills = pgTable(
|
||||
"skills",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
slug: text("slug").unique().notNull(),
|
||||
name: text("name").notNull(),
|
||||
categoryId: text("category_id")
|
||||
.notNull()
|
||||
.references(() => skillCategories.id, { onDelete: "restrict" }),
|
||||
technologyId: text("technology_id")
|
||||
.references(() => technologies.id, { onDelete: "restrict" }),
|
||||
functionId: text("function_id")
|
||||
.references(() => functions.id, { onDelete: "restrict" }),
|
||||
/** category|technology|function — unique even with NULLs (encoded ""). */
|
||||
dedupeKey: text("dedupe_key").unique().notNull(),
|
||||
description: text("description"),
|
||||
mentorMinLevel: text("mentor_min_level", { enum: SKILL_LEVELS })
|
||||
.notNull()
|
||||
.default("expert"),
|
||||
staleAfterDays: integer("stale_after_days").notNull().default(120),
|
||||
recertRequired: boolean("recert_required").notNull().default(false),
|
||||
sortOrder: integer("sort_order").notNull().default(0),
|
||||
active: boolean("active").notNull().default(true),
|
||||
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }),
|
||||
},
|
||||
(table) => [
|
||||
index("skills_slug_idx").on(table.slug),
|
||||
index("skills_active_idx").on(table.active),
|
||||
index("skills_category_idx").on(table.categoryId),
|
||||
],
|
||||
);
|
||||
|
||||
/* ------------------------------------------- position_skills (B4) */
|
||||
|
||||
/**
|
||||
* What a schedulable position demands (ARCHITECTURE §4.3). The join that turns
|
||||
* "who is an audio person" into "who can run audio this Sunday". `is_core`
|
||||
* skills gate a position's publishability (a position with no core skill cannot
|
||||
* be published); non-core skills only rank. `weight` feeds the readiness score.
|
||||
*/
|
||||
export const positionSkills = pgTable(
|
||||
"position_skills",
|
||||
{
|
||||
positionId: text("position_id")
|
||||
.notNull()
|
||||
.references(() => roles.id, { onDelete: "restrict" }),
|
||||
skillId: text("skill_id")
|
||||
.notNull()
|
||||
.references(() => skills.id, { onDelete: "restrict" }),
|
||||
/** 1..5 — weight in the readiness score. */
|
||||
weight: integer("weight").notNull().default(1),
|
||||
/** Minimum verified level to run this position solo (nullable). */
|
||||
requiredLevel: text("required_level", { enum: SKILL_LEVELS }),
|
||||
/** Core skills gate hard; non-core only rank. */
|
||||
isCore: boolean("is_core").notNull().default(false),
|
||||
},
|
||||
(table) => [
|
||||
// One skill per position: the composite key is the PK.
|
||||
primaryKey({ name: "position_skills_pk", columns: [table.positionId, table.skillId] }),
|
||||
index("position_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.
|
||||
*/
|
||||
export const usersRelations = relations(users, ({ many }) => ({
|
||||
assignments: many(assignments),
|
||||
}));
|
||||
@@ -444,6 +542,8 @@ export const schema = {
|
||||
vendors,
|
||||
technologies,
|
||||
functions,
|
||||
skills,
|
||||
positionSkills,
|
||||
};
|
||||
|
||||
export type Schema = typeof schema;
|
||||
|
||||
Reference in New Issue
Block a user