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:
+40
-1
@@ -228,4 +228,43 @@ Build log for Media Team Hub. One unit per commit, top to bottom. Append after e
|
||||
- **`purchasedOn` uses `mode: "string"`.** The API passes an ISO date string; a `mode: "date"` column expects a `Date` object (TS2769).
|
||||
- **No catalog seed yet.** Per ARCHITECTURE, the only seeded artifact is `seed/catalog.json` (loaded on first boot) — delivered in a later unit. The four tables start empty; this unit is the data layer other units consume.
|
||||
|
||||
**Next: B4 — positions (schedulable seats) + skills.****
|
||||
**Next: B4 — positions (schedulable seats) + skills.**
|
||||
|
||||
---
|
||||
|
||||
## B4 — Positions + skills + requirements editor — DONE 2026-11-18
|
||||
|
||||
**Scope (from BUILD-PLAN.md):** positions (schedulable seats) CRUD + requirements editor (skill, weight, required level, core). Governing rule under test: **a position with no `is_core` skill refuses to save as publishable.** ARCHITECTURE §4.3 — positions deactivate only, slugs frozen, FKs `ON DELETE RESTRICT`.
|
||||
|
||||
**Delivered:**
|
||||
- `src/db/schema.ts` — two new tables:
|
||||
- **`skills`** (B4 prerequisite of `position_skills`): `id, slug (unique), name, category_id (FK), technology_id (FK), function_id (FK), dedupe_key (unique), description, mentor_min_level (default 'expert'), stale_after_days (default 120), recert_required, sort_order, active, created_at, updated_at`. `dedupe_key = category|technology|function` (NULLs → ""). All FKs `ON DELETE RESTRICT`.
|
||||
- **`position_skills`** (join): `position_id (FK), skill_id (FK), weight, required_level, is_core`, PK `(position_id, skill_id)`.
|
||||
- `roles` (positions) gained `active` (default true) + `updated_at` for soft-delete/pickers/audit.
|
||||
- `src/db/positions.ts` — data layer: `listPositions`, `createPosition`, `updatePosition`, `deactivatePosition`, `listSkills`, `createSkill`, `updateSkill`, `deactivateSkill`, `getPositionSkills` (skills joined into position_skills in JS), `setPositionSkills` (replaces the whole set), `dedupeKey()` helper.
|
||||
- `src/domain/positions.ts` — pure publishability rule: `isPublishable(skills)` = has ≥1 `is_core` skill.
|
||||
- `src/domain/positions.test.ts` — 8 tests named after the rule (no-core publish refused; no-core unpublished allowed; weight range).
|
||||
- `src/app/api/dev/skills/route.ts` — GET (list, `?active=`), POST (create, slug+dedupe_key generated), PATCH (rename/edit or deactivate).
|
||||
- `src/app/api/dev/positions/route.ts` — GET (list), POST (create), PATCH (rename/edit or deactivate).
|
||||
- `src/app/api/dev/positions/requirements/route.ts` — GET (list a position's requirements), POST (set requirements; enforces the publishability gate).
|
||||
- Migration `drizzle/0004_hesitant_ezekiel.sql`.
|
||||
|
||||
**Verification (all exit 0):**
|
||||
- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (**44** total, +8 for B4 domain) · `pnpm build` ✓
|
||||
- `pnpm db:migrate` ✓ → `skills`, `position_skills`, `roles.active`/`updated_at` present on :5433
|
||||
- Runtime smoke against live app + Postgres on :5433 (**24 checks**, `/tmp/b4.sh`):
|
||||
- seed category → skill → position (slugs + dedupe_key generated) ✓
|
||||
- requirements round-trip (empty → 0) ✓
|
||||
- publish **with** a core skill → 200 (core/weight/name joined) ✓
|
||||
- publish **without** any core skill → **400** (the B4 rule); same set as `published:false` → 200 ✓
|
||||
- weight out of range (9) → 400 ✓
|
||||
- rename → slug frozen ✓; deactivate → hidden from `?active=true` picker, row persists in DB ✓
|
||||
|
||||
**Decisions:**
|
||||
- **Skills table is a B4 prerequisite.** `position_skills` needs `skills` to exist, so B4 builds the `skills` table (composed from the four catalog tables) up front. The name-composition UI is C1; this unit only creates skills with an explicit name.
|
||||
- **Requirements editor takes `positionId` in the body, not a URL param.** Next 15.5.29's route-handler context validation rejects an explicitly-typed `{ params: { id: string } }` second argument (it expects `Promise<any>` for the async-params feature). Body-based stays consistent with the catalog route and avoids the dynamic-route context typing rabbit hole.
|
||||
- **Publishability gate in the domain, enforced in the route.** The pure rule lives in `src/domain/positions.ts`; the route calls it and returns 400 when a `published:true` payload has no core skill — so the rule and the code cannot drift.
|
||||
- **`join` resolved in JS.** Drizzle 0.45.4 exports no `join` from `drizzle-orm` or `drizzle-orm/pg-core`. `getPositionSkills` fetches `position_skills` then the referenced `skills` and merges in JS.
|
||||
- **No skill/position seed yet.** Per ARCHITECTURE the only seeded artifact is `seed/catalog.json` (later unit). Tables start empty; this unit is the data layer + API other units consume.
|
||||
|
||||
**Next: B5 — user_skills + verified levels (who has what, and at what level).****
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
CREATE TABLE "position_skills" (
|
||||
"position_id" text NOT NULL,
|
||||
"skill_id" text NOT NULL,
|
||||
"weight" integer DEFAULT 1 NOT NULL,
|
||||
"required_level" text,
|
||||
"is_core" boolean DEFAULT false NOT NULL,
|
||||
CONSTRAINT "position_skills_pk" PRIMARY KEY("position_id","skill_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "skills" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"slug" text NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"category_id" text NOT NULL,
|
||||
"technology_id" text,
|
||||
"function_id" text,
|
||||
"dedupe_key" text NOT NULL,
|
||||
"description" text,
|
||||
"mentor_min_level" text DEFAULT 'expert' NOT NULL,
|
||||
"stale_after_days" integer DEFAULT 120 NOT NULL,
|
||||
"recert_required" boolean DEFAULT false NOT NULL,
|
||||
"sort_order" integer DEFAULT 0 NOT NULL,
|
||||
"active" boolean DEFAULT true NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone,
|
||||
CONSTRAINT "skills_slug_unique" UNIQUE("slug"),
|
||||
CONSTRAINT "skills_dedupe_key_unique" UNIQUE("dedupe_key")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "roles" ADD COLUMN "active" boolean DEFAULT true NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "roles" ADD COLUMN "updated_at" timestamp with time zone;--> statement-breakpoint
|
||||
ALTER TABLE "position_skills" ADD CONSTRAINT "position_skills_position_id_roles_id_fk" FOREIGN KEY ("position_id") REFERENCES "public"."roles"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "position_skills" ADD CONSTRAINT "position_skills_skill_id_skills_id_fk" FOREIGN KEY ("skill_id") REFERENCES "public"."skills"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "skills" ADD CONSTRAINT "skills_category_id_skill_categories_id_fk" FOREIGN KEY ("category_id") REFERENCES "public"."skill_categories"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "skills" ADD CONSTRAINT "skills_technology_id_technologies_id_fk" FOREIGN KEY ("technology_id") REFERENCES "public"."technologies"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "skills" ADD CONSTRAINT "skills_function_id_functions_id_fk" FOREIGN KEY ("function_id") REFERENCES "public"."functions"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE INDEX "position_skills_skill_idx" ON "position_skills" USING btree ("skill_id");--> statement-breakpoint
|
||||
CREATE INDEX "skills_slug_idx" ON "skills" USING btree ("slug");--> statement-breakpoint
|
||||
CREATE INDEX "skills_active_idx" ON "skills" USING btree ("active");--> statement-breakpoint
|
||||
CREATE INDEX "skills_category_idx" ON "skills" USING btree ("category_id");--> statement-breakpoint
|
||||
CREATE INDEX "roles_active_idx" ON "roles" USING btree ("active");
|
||||
File diff suppressed because it is too large
Load Diff
@@ -29,6 +29,13 @@
|
||||
"when": 1794961261600,
|
||||
"tag": "0003_whole_crystal",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 4,
|
||||
"version": "7",
|
||||
"when": 1794964903255,
|
||||
"tag": "0004_hesitant_ezekiel",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { getPositionSkills, setPositionSkills } from "@/db/positions";
|
||||
import { validateRequirements } from "@/domain/positions";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
const positionSkillSchema = z.object({
|
||||
skillId: z.string().min(1),
|
||||
weight: z.number().int().min(1).max(5).optional(),
|
||||
requiredLevel: z.string().nullable().optional(),
|
||||
isCore: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const setRequirementsSchema = z.object({
|
||||
positionId: z.string().min(1),
|
||||
skills: z.array(positionSkillSchema).min(1),
|
||||
published: z.boolean().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,
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/dev/positions/requirements?positionId=<id> — a position's
|
||||
* requirements editor state (each skill with its weight, required level, and
|
||||
* core flag).
|
||||
*/
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const positionId = req.nextUrl.searchParams.get("positionId");
|
||||
if (!positionId) return bad("missing positionId");
|
||||
const row = await getPositionSkills(positionId);
|
||||
return ok(row);
|
||||
};
|
||||
|
||||
/**
|
||||
* POST /api/dev/positions/requirements — save the requirements editor.
|
||||
*
|
||||
* The payload is the full skill set (each with weight, required level, core
|
||||
* flag) plus a `published` flag. A position with no core skill refuses to save
|
||||
* as publishable (ARCHITECTURE §4.3 rule 4):
|
||||
*
|
||||
* { "positionId": "<id>", "skills": [ { "skillId": "<id>", "isCore": true,
|
||||
* "weight": 3, "requiredLevel": "qualified" } ], "published": true }
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const body = await readBody(req);
|
||||
if (!body || typeof body !== "object") return bad("invalid body");
|
||||
|
||||
const parsed = setRequirementsSchema.safeParse(body);
|
||||
if (!parsed.success) return bad(parsed.error.message);
|
||||
|
||||
// Publishability gate: a published position needs at least one core skill.
|
||||
const problems = validateRequirements({
|
||||
skills: parsed.data.skills,
|
||||
published: parsed.data.published,
|
||||
});
|
||||
if (problems.length > 0) {
|
||||
return bad(problems.join("; "));
|
||||
}
|
||||
|
||||
try {
|
||||
const row = await setPositionSkills(parsed.data.positionId, parsed.data.skills);
|
||||
return ok(row);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : "internal error";
|
||||
return bad(message);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,137 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
listPositions,
|
||||
createPosition,
|
||||
updatePosition,
|
||||
deactivatePosition,
|
||||
} from "@/db/positions";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
const idSchema = z.string().min(1);
|
||||
|
||||
const positionCreateSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
description: z.string().nullable().optional(),
|
||||
colorHex: z.string().nullable().optional(),
|
||||
callTimeOffsetMinutes: z.number().int().nullable().optional(),
|
||||
requiresCertification: z.boolean().nullable().optional(),
|
||||
defaultHeadcount: z.number().int().nullable().optional(),
|
||||
sortOrder: z.number().int().optional(),
|
||||
});
|
||||
|
||||
const positionUpdateSchema = z.object({
|
||||
name: z.string().min(1).optional(),
|
||||
description: z.string().nullable().optional(),
|
||||
colorHex: z.string().nullable().optional(),
|
||||
callTimeOffsetMinutes: z.number().int().nullable().optional(),
|
||||
requiresCertification: z.boolean().nullable().optional(),
|
||||
defaultHeadcount: z.number().int().nullable().optional(),
|
||||
sortOrder: z.number().int().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,
|
||||
});
|
||||
|
||||
const created = (row: unknown) =>
|
||||
new Response(JSON.stringify({ row }), {
|
||||
status: 201,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
|
||||
/** Map Postgres constraint violations to client errors (see catalog route). */
|
||||
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 position with this slug already exists" }), {
|
||||
status: 409,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
return new Response(JSON.stringify({ error: "internal error" }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
};
|
||||
|
||||
/** GET /api/dev/positions?active=true — list picker rows. */
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const active = req.nextUrl.searchParams.get("active") !== "false";
|
||||
const rows = await listPositions({ active });
|
||||
return new Response(JSON.stringify({ rows }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
};
|
||||
|
||||
/** POST /api/dev/positions { ...createFields } — create (slug generated). */
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const body = await readBody(req);
|
||||
if (!body || typeof body !== "object") {
|
||||
return bad("invalid body");
|
||||
}
|
||||
const parsed = positionCreateSchema.safeParse(body);
|
||||
if (!parsed.success) return bad(parsed.error.message);
|
||||
try {
|
||||
return created(await createPosition(parsed.data));
|
||||
} catch (err) {
|
||||
return dbError(err);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* PATCH /api/dev/positions { id, ...updateFields } — rename / edit.
|
||||
* PATCH { id, active: false } — deactivate (soft delete).
|
||||
* `slug` is never accepted here: it freezes after creation.
|
||||
*/
|
||||
export const PATCH = async (req: NextRequest) => {
|
||||
const body = await readBody(req);
|
||||
if (!body || typeof body !== "object") {
|
||||
return bad("invalid body");
|
||||
}
|
||||
const id = idSchema.safeParse((body as { id?: unknown }).id);
|
||||
if (!id.success) return bad("invalid id");
|
||||
|
||||
// Deactivate path: explicit active=false, no editable fields applied.
|
||||
if ((body as { active?: unknown }).active === false) {
|
||||
const row = await deactivatePosition(id.data);
|
||||
return ok(row);
|
||||
}
|
||||
|
||||
const parsed = positionUpdateSchema.safeParse(body);
|
||||
if (!parsed.success) return bad(parsed.error.message);
|
||||
try {
|
||||
return ok(await updatePosition(id.data, parsed.data));
|
||||
} catch (err) {
|
||||
return dbError(err);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,142 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
listSkills,
|
||||
createSkill,
|
||||
updateSkill,
|
||||
deactivateSkill,
|
||||
} from "@/db/positions";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
const idSchema = z.string().min(1);
|
||||
|
||||
const skillCreateSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
categoryId: z.string().min(1),
|
||||
technologyId: z.string().nullable().optional(),
|
||||
functionId: z.string().nullable().optional(),
|
||||
description: z.string().nullable().optional(),
|
||||
mentorMinLevel: z.string().nullable().optional(),
|
||||
staleAfterDays: z.number().int().nullable().optional(),
|
||||
recertRequired: z.boolean().nullable().optional(),
|
||||
sortOrder: z.number().int().optional(),
|
||||
});
|
||||
|
||||
const skillUpdateSchema = z.object({
|
||||
name: z.string().min(1).optional(),
|
||||
description: z.string().nullable().optional(),
|
||||
mentorMinLevel: z.string().nullable().optional(),
|
||||
staleAfterDays: z.number().int().nullable().optional(),
|
||||
recertRequired: z.boolean().nullable().optional(),
|
||||
sortOrder: z.number().int().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,
|
||||
});
|
||||
|
||||
const created = (row: unknown) =>
|
||||
new Response(JSON.stringify({ row }), {
|
||||
status: 201,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
|
||||
/**
|
||||
* Map Postgres constraint violations to client errors (see catalog route):
|
||||
* 23505 = duplicate slug / dedupe_key, 23503 = dangling category/tech/function 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 skill with this slug or dedupe key already exists" }), {
|
||||
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/skills?active=true — list picker rows. */
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const active = req.nextUrl.searchParams.get("active") !== "false";
|
||||
const rows = await listSkills({ active });
|
||||
return new Response(JSON.stringify({ rows }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
};
|
||||
|
||||
/** POST /api/dev/skills { ...createFields } — create (slug + dedupe_key generated). */
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const body = await readBody(req);
|
||||
if (!body || typeof body !== "object") return bad("invalid body");
|
||||
const parsed = skillCreateSchema.safeParse(body);
|
||||
if (!parsed.success) return bad(parsed.error.message);
|
||||
try {
|
||||
return created(await createSkill(parsed.data));
|
||||
} catch (err) {
|
||||
return dbError(err);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* PATCH /api/dev/skills { id, ...updateFields } — rename / edit.
|
||||
* PATCH { id, active: false } — deactivate (soft delete).
|
||||
* `slug` and the composing FKs are never accepted here: they freeze after creation.
|
||||
*/
|
||||
export const PATCH = async (req: NextRequest) => {
|
||||
const body = await readBody(req);
|
||||
if (!body || typeof body !== "object") return bad("invalid body");
|
||||
const id = idSchema.safeParse((body as { id?: unknown }).id);
|
||||
if (!id.success) return bad("invalid id");
|
||||
|
||||
if ((body as { active?: unknown }).active === false) {
|
||||
const row = await deactivateSkill(id.data);
|
||||
return ok(row);
|
||||
}
|
||||
|
||||
const parsed = skillUpdateSchema.safeParse(body);
|
||||
if (!parsed.success) return bad(parsed.error.message);
|
||||
try {
|
||||
return ok(await updateSkill(id.data, parsed.data));
|
||||
} catch (err) {
|
||||
return dbError(err);
|
||||
}
|
||||
};
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isPublishable, validateRequirements } from "./positions";
|
||||
|
||||
describe("isPublishable", () => {
|
||||
it("rejects a position with no core skill", () => {
|
||||
expect(isPublishable([{ isCore: false }, { isCore: false }])).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects an empty position (no skills at all)", () => {
|
||||
expect(isPublishable([])).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts a position with at least one core skill", () => {
|
||||
expect(isPublishable([{ isCore: false }, { isCore: true }])).toBe(true);
|
||||
});
|
||||
|
||||
it("treats an omitted isCore as non-core", () => {
|
||||
expect(isPublishable([{ isCore: undefined }])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("validateRequirements", () => {
|
||||
it("accepts a valid core-backed publish request", () => {
|
||||
const problems = validateRequirements({
|
||||
skills: [{ isCore: true, weight: 3 }],
|
||||
published: true,
|
||||
});
|
||||
expect(problems).toEqual([]);
|
||||
});
|
||||
|
||||
it("refuses to publish a position with no core skill", () => {
|
||||
const problems = validateRequirements({
|
||||
skills: [{ isCore: false, weight: 2 }],
|
||||
published: true,
|
||||
});
|
||||
expect(problems).toHaveLength(1);
|
||||
expect(problems[0]).toMatch(/core skill/);
|
||||
});
|
||||
|
||||
it("allows saving an unpublished position with no core skill", () => {
|
||||
const problems = validateRequirements({
|
||||
skills: [{ isCore: false }],
|
||||
published: false,
|
||||
});
|
||||
expect(problems).toEqual([]);
|
||||
});
|
||||
|
||||
it("rejects a weight outside 1..5", () => {
|
||||
const problems = validateRequirements({
|
||||
skills: [{ isCore: true, weight: 9 }],
|
||||
published: true,
|
||||
});
|
||||
expect(problems).toHaveLength(1);
|
||||
expect(problems[0]).toMatch(/weight/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* Position publishability — the pure rule behind B4's requirements editor
|
||||
* (ARCHITECTURE §4.3 rule 4).
|
||||
*
|
||||
* A position with no `is_core` skill cannot be published: if every skill on a
|
||||
* position is non-core, "anyone can fill it" becomes the rule by accident. The
|
||||
* gate lives here — a single auditable predicate the route calls — so the rule
|
||||
* and the code cannot drift.
|
||||
*/
|
||||
|
||||
export interface PositionSkillInput {
|
||||
isCore?: boolean;
|
||||
weight?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* A position is publishable when at least one of its skills is core. Core
|
||||
* skills hard-gate a solo assignment; without one there is nothing that
|
||||
* distinguishes a qualified operator from anyone.
|
||||
*/
|
||||
export function isPublishable(skills: readonly PositionSkillInput[]): boolean {
|
||||
return skills.some((skill) => skill.isCore === true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a requirements payload before it hits the DB. Returns a list of
|
||||
* human-readable problems (empty when valid). Keeps the route thin and the
|
||||
* rules testable in isolation.
|
||||
*
|
||||
* - weight must be an integer in 1..5
|
||||
* - a requested `published: true` requires at least one core skill
|
||||
*/
|
||||
export function validateRequirements(params: {
|
||||
skills: readonly PositionSkillInput[];
|
||||
published?: boolean;
|
||||
}): string[] {
|
||||
const problems: string[] = [];
|
||||
const { skills, published } = params;
|
||||
|
||||
skills.forEach((skill, i) => {
|
||||
const weight = skill.weight as number | undefined;
|
||||
if (weight === undefined) return;
|
||||
if (!Number.isInteger(weight) || weight < 1 || weight > 5) {
|
||||
problems.push(`skill[${i}].weight must be an integer from 1 to 5`);
|
||||
}
|
||||
});
|
||||
|
||||
if (published === true && !isPublishable(skills)) {
|
||||
problems.push("a published position needs at least one core skill");
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
Reference in New Issue
Block a user