From 5c789f63cca8db1aca935c3799d55f817d6cf84b Mon Sep 17 00:00:00 2001 From: Tiel Coder Date: Wed, 18 Nov 2026 01:34:24 +0000 Subject: [PATCH] =?UTF-8?q?B4=20=E2=80=94=20Positions=20+=20skills=20+=20r?= =?UTF-8?q?equirements=20editor=20Positions=20(schedulable=20seats)=20CRUD?= =?UTF-8?q?=20+=20requirements=20editor.=20Governing=20rule:=20a=20positio?= =?UTF-8?q?n=20with=20no=20is=5Fcore=20skill=20refuses=20to=20save=20as=20?= =?UTF-8?q?publishable.=20Schema=20(src/db/schema.ts):=20-=20skills=20tabl?= =?UTF-8?q?e=20(B4=20prerequisite=20of=20position=5Fskills):=20id,=20slug?= =?UTF-8?q?=20(unique),=20=20=20name,=20category=5Fid/technology=5Fid/func?= =?UTF-8?q?tion=5Fid=20FKs,=20dedupe=5Fkey=20=20=20(category|technology|fu?= =?UTF-8?q?nction,=20NULLs=20->=20''),=20mentor=5Fmin=5Flevel=20(default?= =?UTF-8?q?=20=20=20'expert'),=20stale=5Fafter=5Fdays=20(default=20120),?= =?UTF-8?q?=20recert=5Frequired,=20sort=5Forder,=20=20=20active,=20created?= =?UTF-8?q?=5Fat,=20updated=5Fat.=20All=20FKs=20ON=20DELETE=20RESTRICT.=20?= =?UTF-8?q?-=20position=5Fskills=20join:=20position=5Fid,=20skill=5Fid,=20?= =?UTF-8?q?weight,=20required=5Flevel,=20=20=20is=5Fcore;=20PK=20(position?= =?UTF-8?q?=5Fid,=20skill=5Fid).=20-=20roles=20(positions)=20gained=20acti?= =?UTF-8?q?ve=20(default=20true)=20+=20updated=5Fat=20for=20=20=20soft-del?= =?UTF-8?q?ete/pickers/audit.=20Data=20layer=20(src/db/positions.ts):=20li?= =?UTF-8?q?st/create/update/deactivate=20for=20positions=20and=20skills;?= =?UTF-8?q?=20getPositionSkills=20(skills=20merged=20into=20position=5Fski?= =?UTF-8?q?lls=20in=20JS);=20setPositionSkills=20(replaces=20the=20whole?= =?UTF-8?q?=20set);=20dedupeKey()=20helper.=20Domain=20(src/domain/positio?= =?UTF-8?q?ns.ts=20+=20.test.ts):=20pure=20publishability=20rule=20?= =?UTF-8?q?=E2=80=94=20isPublishable(skills)=20=3D=20has=20>=3D1=20is=5Fco?= =?UTF-8?q?re=20skill.=208=20tests=20named=20after=20the=20rule.=20API:=20?= =?UTF-8?q?-=20src/app/api/dev/skills/route.ts=20=E2=80=94=20GET/POST/PATC?= =?UTF-8?q?H=20(slug=20+=20dedupe=5Fkey=20=20=20generated=20at=20create;?= =?UTF-8?q?=20slug=20frozen=20on=20update).=20-=20src/app/api/dev/position?= =?UTF-8?q?s/route.ts=20=E2=80=94=20GET/POST/PATCH=20(rename/edit=20or=20?= =?UTF-8?q?=20=20deactivate=20via=20active:false).=20-=20src/app/api/dev/p?= =?UTF-8?q?ositions/requirements/route.ts=20=E2=80=94=20GET=20(list=20a=20?= =?UTF-8?q?=20=20position's=20requirements)=20+=20POST=20(set=20requiremen?= =?UTF-8?q?ts;=20enforces=20the=20=20=20publishability=20gate:=20published?= =?UTF-8?q?:true=20with=20no=20core=20skill=20->=20400).=20Migration=20dri?= =?UTF-8?q?zzle/0004=5Fhesitant=5Fezekiel.sql.=20Verification:=20typecheck?= =?UTF-8?q?=20=E2=9C=93=20lint=20=E2=9C=93=20test=20=E2=9C=93=20(44,=20+8)?= =?UTF-8?q?=20build=20=E2=9C=93=20db:migrate=20=E2=9C=93;=20runtime=20smok?= =?UTF-8?q?e=20/tmp/b4.sh=20(24=20checks)=20=E2=80=94=20publish-with-core?= =?UTF-8?q?=20200,=20publish-without-core=20400,=20weight-out-of-range=204?= =?UTF-8?q?00,=20rename=20slug=20frozen,=20deactivate=20hides=20from=20pic?= =?UTF-8?q?ker=20but=20row=20persists.=20Decisions:=20skills=20table=20is?= =?UTF-8?q?=20a=20B4=20prerequisite;=20requirements=20editor=20takes=20pos?= =?UTF-8?q?itionId=20in=20the=20body=20(Next=2015.5.29=20rejects=20an=20ex?= =?UTF-8?q?plicitly-typed=20{=20params:=20{=20id=20}=20}=20route-handler?= =?UTF-8?q?=20second=20arg);=20publishability=20gate=20lives=20in=20the=20?= =?UTF-8?q?domain=20and=20is=20enforced=20in=20the=20route;=20join=20resol?= =?UTF-8?q?ved=20in=20JS=20(drizzle=200.45.4=20exports=20no=20join).?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .agent/PROGRESS.md | 41 +- drizzle/0004_hesitant_ezekiel.sql | 41 + drizzle/meta/0004_snapshot.json | 1853 +++++++++++++++++ drizzle/meta/_journal.json | 7 + .../api/dev/positions/requirements/route.ts | 86 + src/app/api/dev/positions/route.ts | 137 ++ src/app/api/dev/skills/route.ts | 142 ++ src/db/positions.ts | 301 +++ src/db/schema.ts | 110 +- src/domain/positions.test.ts | 56 + src/domain/positions.ts | 53 + 11 files changed, 2821 insertions(+), 6 deletions(-) create mode 100644 drizzle/0004_hesitant_ezekiel.sql create mode 100644 drizzle/meta/0004_snapshot.json create mode 100644 src/app/api/dev/positions/requirements/route.ts create mode 100644 src/app/api/dev/positions/route.ts create mode 100644 src/app/api/dev/skills/route.ts create mode 100644 src/db/positions.ts create mode 100644 src/domain/positions.test.ts create mode 100644 src/domain/positions.ts diff --git a/.agent/PROGRESS.md b/.agent/PROGRESS.md index 28c4ed6..daeaf5a 100644 --- a/.agent/PROGRESS.md +++ b/.agent/PROGRESS.md @@ -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` 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).**** diff --git a/drizzle/0004_hesitant_ezekiel.sql b/drizzle/0004_hesitant_ezekiel.sql new file mode 100644 index 0000000..774451f --- /dev/null +++ b/drizzle/0004_hesitant_ezekiel.sql @@ -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"); \ No newline at end of file diff --git a/drizzle/meta/0004_snapshot.json b/drizzle/meta/0004_snapshot.json new file mode 100644 index 0000000..7e5a18f --- /dev/null +++ b/drizzle/meta/0004_snapshot.json @@ -0,0 +1,1853 @@ +{ + "id": "1cf0c37b-ed49-4013-bb63-783aae4616aa", + "prevId": "e5b56f4b-4851-4557-8013-15eb1ce13701", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.assignments": { + "name": "assignments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slot_id": { + "name": "slot_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'proposed'" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "assigned_by": { + "name": "assigned_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assigned_at": { + "name": "assigned_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "responded_at": { + "name": "responded_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "decline_reason": { + "name": "decline_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "confirmed_via": { + "name": "confirmed_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reminder_count": { + "name": "reminder_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "uq_active_assignment": { + "name": "uq_active_assignment", + "columns": [ + { + "expression": "slot_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"assignments\".\"status\" IN ('proposed','confirmed','completed')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "assignments_user_idx": { + "name": "assignments_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "assignments_slot_id_slots_id_fk": { + "name": "assignments_slot_id_slots_id_fk", + "tableFrom": "assignments", + "tableTo": "slots", + "columnsFrom": [ + "slot_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "assignments_user_id_users_id_fk": { + "name": "assignments_user_id_users_id_fk", + "tableFrom": "assignments", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.functions": { + "name": "functions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category_id": { + "name": "category_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "functions_slug_idx": { + "name": "functions_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "functions_active_idx": { + "name": "functions_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "functions_category_idx": { + "name": "functions_category_idx", + "columns": [ + { + "expression": "category_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "functions_category_id_skill_categories_id_fk": { + "name": "functions_category_id_skill_categories_id_fk", + "tableFrom": "functions", + "tableTo": "skill_categories", + "columnsFrom": [ + "category_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "functions_slug_unique": { + "name": "functions_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.notification_preferences": { + "name": "notification_preferences", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "email_enabled": { + "name": "email_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "sms_enabled": { + "name": "sms_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "sms_consent_at": { + "name": "sms_consent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "sms_consent_source": { + "name": "sms_consent_source", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sms_consent_ip": { + "name": "sms_consent_ip", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reminder_lead_days": { + "name": "reminder_lead_days", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 7 + }, + "quiet_hours_start": { + "name": "quiet_hours_start", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'21:00'" + }, + "quiet_hours_end": { + "name": "quiet_hours_end", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'08:00'" + }, + "digest_only": { + "name": "digest_only", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": {}, + "foreignKeys": { + "notification_preferences_user_id_users_id_fk": { + "name": "notification_preferences_user_id_users_id_fk", + "tableFrom": "notification_preferences", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.position_skills": { + "name": "position_skills", + "schema": "", + "columns": { + "position_id": { + "name": "position_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "weight": { + "name": "weight", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "required_level": { + "name": "required_level", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_core": { + "name": "is_core", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": { + "position_skills_skill_idx": { + "name": "position_skills_skill_idx", + "columns": [ + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "position_skills_position_id_roles_id_fk": { + "name": "position_skills_position_id_roles_id_fk", + "tableFrom": "position_skills", + "tableTo": "roles", + "columnsFrom": [ + "position_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "position_skills_skill_id_skills_id_fk": { + "name": "position_skills_skill_id_skills_id_fk", + "tableFrom": "position_skills", + "tableTo": "skills", + "columnsFrom": [ + "skill_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "position_skills_pk": { + "name": "position_skills_pk", + "columns": [ + "position_id", + "skill_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.roles": { + "name": "roles", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "color_hex": { + "name": "color_hex", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "call_time_offset_minutes": { + "name": "call_time_offset_minutes", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "requires_certification": { + "name": "requires_certification", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "default_headcount": { + "name": "default_headcount", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "roles_slug_idx": { + "name": "roles_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "roles_active_idx": { + "name": "roles_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "roles_slug_unique": { + "name": "roles_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.service_instances": { + "name": "service_instances", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "service_id": { + "name": "service_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "occurs_on": { + "name": "occurs_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "is_special": { + "name": "is_special", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "title_override": { + "name": "title_override", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "published_at": { + "name": "published_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "published_by": { + "name": "published_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "si_service_starts_at_idx": { + "name": "si_service_starts_at_idx", + "columns": [ + { + "expression": "service_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "starts_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "si_occurs_on_idx": { + "name": "si_occurs_on_idx", + "columns": [ + { + "expression": "occurs_on", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "si_status_idx": { + "name": "si_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "service_instances_service_id_services_id_fk": { + "name": "service_instances_service_id_services_id_fk", + "tableFrom": "service_instances", + "tableTo": "services", + "columnsFrom": [ + "service_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.services": { + "name": "services", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'America/New_York'" + }, + "rrule": { + "name": "rrule", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start_time_local": { + "name": "start_time_local", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "duration_minutes": { + "name": "duration_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 75 + }, + "doors_open_minutes_before": { + "name": "doors_open_minutes_before", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "services_active_idx": { + "name": "services_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "services_name_unique": { + "name": "services_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.skill_categories": { + "name": "skill_categories", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "color_hex": { + "name": "color_hex", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "skill_categories_slug_idx": { + "name": "skill_categories_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "skill_categories_active_idx": { + "name": "skill_categories_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "skill_categories_slug_unique": { + "name": "skill_categories_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.skills": { + "name": "skills", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category_id": { + "name": "category_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "technology_id": { + "name": "technology_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "function_id": { + "name": "function_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mentor_min_level": { + "name": "mentor_min_level", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'expert'" + }, + "stale_after_days": { + "name": "stale_after_days", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 120 + }, + "recert_required": { + "name": "recert_required", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "skills_slug_idx": { + "name": "skills_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "skills_active_idx": { + "name": "skills_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "skills_category_idx": { + "name": "skills_category_idx", + "columns": [ + { + "expression": "category_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "skills_category_id_skill_categories_id_fk": { + "name": "skills_category_id_skill_categories_id_fk", + "tableFrom": "skills", + "tableTo": "skill_categories", + "columnsFrom": [ + "category_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "skills_technology_id_technologies_id_fk": { + "name": "skills_technology_id_technologies_id_fk", + "tableFrom": "skills", + "tableTo": "technologies", + "columnsFrom": [ + "technology_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "skills_function_id_functions_id_fk": { + "name": "skills_function_id_functions_id_fk", + "tableFrom": "skills", + "tableTo": "functions", + "columnsFrom": [ + "function_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "skills_slug_unique": { + "name": "skills_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + }, + "skills_dedupe_key_unique": { + "name": "skills_dedupe_key_unique", + "nullsNotDistinct": false, + "columns": [ + "dedupe_key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.slots": { + "name": "slots", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "service_instance_id": { + "name": "service_instance_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slot_index": { + "name": "slot_index", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "call_time": { + "name": "call_time", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "slot_note": { + "name": "slot_note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_trainee_slot": { + "name": "is_trainee_slot", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "paired_with_user_id": { + "name": "paired_with_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "slots_instance_role_idx": { + "name": "slots_instance_role_idx", + "columns": [ + { + "expression": "service_instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "role_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "slot_index", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slots_status_idx": { + "name": "slots_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "slots_service_instance_id_service_instances_id_fk": { + "name": "slots_service_instance_id_service_instances_id_fk", + "tableFrom": "slots", + "tableTo": "service_instances", + "columnsFrom": [ + "service_instance_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "slots_role_id_roles_id_fk": { + "name": "slots_role_id_roles_id_fk", + "tableFrom": "slots", + "tableTo": "roles", + "columnsFrom": [ + "role_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "slots_paired_with_user_id_users_id_fk": { + "name": "slots_paired_with_user_id_users_id_fk", + "tableFrom": "slots", + "tableTo": "users", + "columnsFrom": [ + "paired_with_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "chk_slots_single_parent": { + "name": "chk_slots_single_parent", + "value": "(service_instance_id IS NOT NULL) <> (event_id IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.technologies": { + "name": "technologies", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "vendor_id": { + "name": "vendor_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category_id": { + "name": "category_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "model_number": { + "name": "model_number", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "version_label": { + "name": "version_label", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "docs_url": { + "name": "docs_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "purchased_on": { + "name": "purchased_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "serial_number": { + "name": "serial_number", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "retired_at": { + "name": "retired_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "successor_technology_id": { + "name": "successor_technology_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "technologies_slug_idx": { + "name": "technologies_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "technologies_active_idx": { + "name": "technologies_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "technologies_vendor_idx": { + "name": "technologies_vendor_idx", + "columns": [ + { + "expression": "vendor_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "technologies_category_idx": { + "name": "technologies_category_idx", + "columns": [ + { + "expression": "category_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "technologies_vendor_id_vendors_id_fk": { + "name": "technologies_vendor_id_vendors_id_fk", + "tableFrom": "technologies", + "tableTo": "vendors", + "columnsFrom": [ + "vendor_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "technologies_category_id_skill_categories_id_fk": { + "name": "technologies_category_id_skill_categories_id_fk", + "tableFrom": "technologies", + "tableTo": "skill_categories", + "columnsFrom": [ + "category_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "technologies_slug_unique": { + "name": "technologies_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "phone_e164": { + "name": "phone_e164", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "first_name": { + "name": "first_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_name": { + "name": "last_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "system_role": { + "name": "system_role", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'volunteer'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending_approval'" + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'America/New_York'" + }, + "emergency_contact": { + "name": "emergency_contact", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approved_by": { + "name": "approved_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approved_at": { + "name": "approved_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_served_at": { + "name": "last_served_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "reliability_score": { + "name": "reliability_score", + "type": "numeric(5, 2)", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "deactivated_at": { + "name": "deactivated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "users_email_lower_idx": { + "name": "users_email_lower_idx", + "columns": [ + { + "expression": "lower(\"email\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_status_idx": { + "name": "users_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_system_role_idx": { + "name": "users_system_role_idx", + "columns": [ + { + "expression": "system_role", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_email_unique": { + "name": "users_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.vendors": { + "name": "vendors", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "support_url": { + "name": "support_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "support_phone": { + "name": "support_phone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "vendors_slug_idx": { + "name": "vendors_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "vendors_active_idx": { + "name": "vendors_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "vendors_slug_unique": { + "name": "vendors_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 0a4c240..9804dfd 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -29,6 +29,13 @@ "when": 1794961261600, "tag": "0003_whole_crystal", "breakpoints": true + }, + { + "idx": 4, + "version": "7", + "when": 1794964903255, + "tag": "0004_hesitant_ezekiel", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/app/api/dev/positions/requirements/route.ts b/src/app/api/dev/positions/requirements/route.ts new file mode 100644 index 0000000..08a8278 --- /dev/null +++ b/src/app/api/dev/positions/requirements/route.ts @@ -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= — 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": "", "skills": [ { "skillId": "", "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); + } +}; diff --git a/src/app/api/dev/positions/route.ts b/src/app/api/dev/positions/route.ts new file mode 100644 index 0000000..bfd34a6 --- /dev/null +++ b/src/app/api/dev/positions/route.ts @@ -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); + } +}; diff --git a/src/app/api/dev/skills/route.ts b/src/app/api/dev/skills/route.ts new file mode 100644 index 0000000..6b16cc3 --- /dev/null +++ b/src/app/api/dev/skills/route.ts @@ -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); + } +}; diff --git a/src/db/positions.ts b/src/db/positions.ts new file mode 100644 index 0000000..904a608 --- /dev/null +++ b/src/db/positions.ts @@ -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 = { 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 = { 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 { + 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 { + 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); +} diff --git a/src/db/schema.ts b/src/db/schema.ts index 47ff1d1..69b8fd8 100644 --- a/src/db/schema.ts +++ b/src/db/schema.ts @@ -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; diff --git a/src/domain/positions.test.ts b/src/domain/positions.test.ts new file mode 100644 index 0000000..282f23d --- /dev/null +++ b/src/domain/positions.test.ts @@ -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/); + }); +}); diff --git a/src/domain/positions.ts b/src/domain/positions.ts new file mode 100644 index 0000000..79f5a16 --- /dev/null +++ b/src/domain/positions.ts @@ -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; +}