diff --git a/.agent/PROGRESS.md b/.agent/PROGRESS.md index 817244d..28c4ed6 100644 --- a/.agent/PROGRESS.md +++ b/.agent/PROGRESS.md @@ -195,3 +195,37 @@ Build log for Media Team Hub. One unit per commit, top to bottom. Append after e - **Seed re-fetches canonical ids.** Same idempotency lesson as A2: `userRows` get fresh UUIDs each run, so prefs are seeded from the re-fetched `userRows2` ids (the assignments code already did this). **Next: B3 — catalog taxonomy.** + +--- + +## B3 — Catalog taxonomy CRUD — DONE 2026-11-18 + +**Scope (from BUILD-PLAN.md):** create/rename/deactivate for the four taxonomy tables — `skill_categories`, `vendors`, `technologies`, `functions`. Deactivate (not delete); slug frozen after creation; read-heavy, so data layer + minimal form only (no `/admin/catalog` UI — that arrives in I2). Governing rules from ARCHITECTURE §4.3: nothing referenced is ever deleted, slugs immutable, FKs `ON DELETE RESTRICT`. + +**Delivered:** +- `src/db/schema.ts` — four tables (`skill_categories`, `vendors`, `technologies`, `functions`), each `id, slug (unique), name` + entity-specific columns, `sort_order`, `active` (default true), `created_at`, `updated_at`. All taxonomy FKs use `ON DELETE RESTRICT`; slugs frozen (no update path accepts `slug`). Added relations (`skillCategoriesRelations` → technologies+functions; `vendorsRelations` → technologies; `technologiesRelations` → vendor+category; `functionsRelations` → category). +- `src/lib/slug.ts` — `slugify(name)`: lowercase, ASCII-fold Latin-1 accented chars, collapse non-alnum runs to a single hyphen, trim edges. Pure rule. +- `src/lib/slug.test.ts` — 6 tests named after slugify behaviors. +- `src/db/catalog.ts` — `listCatalog(type, { active })` (active:true → only active rows for pickers; active:false → all rows incl. deactivated), `deactivateCatalog(type, id)` (soft delete, flips `active`), per-entity `create*`/`update*` (slug generated at create, frozen on update; `update*` patches only fields present in the body — no null-out). +- `src/app/api/dev/catalog/route.ts` — GET (list, `?type=&active=`), POST (create, slug server-generated), PATCH (rename/edit, or deactivate via `active:false`). Zod-validated per entity. DB constraint violations mapped to 409 (duplicate slug) / 400 (dangling FK) via a cause-chain walk (pg wraps the SQLSTATE on `err.cause.code`). +- Migration `drizzle/0003_whole_crystal.sql`. + +**Verification (all exit 0):** +- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (**36** total, +6 for slugify) · `pnpm build` ✓ +- `pnpm db:migrate` ✓ → all 4 tables present on :5433 +- Runtime smoke against live app + Postgres on :5433 (create → rename keeps slug → deactivate hides from pickers but row persists), all four entities: + - create → generated slug (`name` → `slug`) ✓ + - rename → slug UNCHANGED, name updated ✓ (all four types) + - deactivate → active picker count drops by exactly 1, all-row count unchanged (row persists) ✓ + - `GET ?active=true` excludes deactivated; `GET ?active=false` includes all ✓ + - partial PATCH omits a field → that field is NOT nulled out ✓ + - validation: missing name → 400, bad type → 400, missing FK → 400, duplicate slug → 409 (not an empty 500) ✓ + +**Decisions:** +- **Inline per-entity switches in the route, not a map dispatch.** A map-based handler lost TS type correlation (TS2345 on the intersected param types). Explicit `case` blocks keep each `CatalogType` correlated to its create/update handler and its Zod schema. +- **DB constraint errors → client errors.** The pg driver throws a Drizzle `QueryError` whose `.cause` carries the SQLSTATE. Walking the cause chain lets the route return 409/400 with a clear message instead of a bare 500 — admins creating a duplicate category or a technology with a dangling vendor get actionable feedback. +- **`successorTechnologyId` is plain text, not a self-FK.** A self-referential FK created a circular schema type (TS7022/TS7024). It's a soft "successor gear" hint, validated at the app layer. +- **`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.**** diff --git a/drizzle/0003_whole_crystal.sql b/drizzle/0003_whole_crystal.sql new file mode 100644 index 0000000..f0df7c5 --- /dev/null +++ b/drizzle/0003_whole_crystal.sql @@ -0,0 +1,75 @@ +CREATE TABLE "functions" ( + "id" text PRIMARY KEY NOT NULL, + "slug" text NOT NULL, + "name" text NOT NULL, + "category_id" text NOT NULL, + "description" text, + "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 "functions_slug_unique" UNIQUE("slug") +); +--> statement-breakpoint +CREATE TABLE "skill_categories" ( + "id" text PRIMARY KEY NOT NULL, + "slug" text NOT NULL, + "name" text NOT NULL, + "description" text, + "color_hex" text, + "icon" text, + "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 "skill_categories_slug_unique" UNIQUE("slug") +); +--> statement-breakpoint +CREATE TABLE "technologies" ( + "id" text PRIMARY KEY NOT NULL, + "slug" text NOT NULL, + "name" text NOT NULL, + "vendor_id" text NOT NULL, + "category_id" text NOT NULL, + "model_number" text, + "version_label" text, + "docs_url" text, + "purchased_on" date, + "serial_number" text, + "retired_at" timestamp with time zone, + "successor_technology_id" text, + "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 "technologies_slug_unique" UNIQUE("slug") +); +--> statement-breakpoint +CREATE TABLE "vendors" ( + "id" text PRIMARY KEY NOT NULL, + "slug" text NOT NULL, + "name" text NOT NULL, + "support_url" text, + "support_phone" text, + "notes" text, + "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 "vendors_slug_unique" UNIQUE("slug") +); +--> statement-breakpoint +ALTER TABLE "functions" ADD CONSTRAINT "functions_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 "technologies" ADD CONSTRAINT "technologies_vendor_id_vendors_id_fk" FOREIGN KEY ("vendor_id") REFERENCES "public"."vendors"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "technologies" ADD CONSTRAINT "technologies_category_id_skill_categories_id_fk" FOREIGN KEY ("category_id") REFERENCES "public"."skill_categories"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "functions_slug_idx" ON "functions" USING btree ("slug");--> statement-breakpoint +CREATE INDEX "functions_active_idx" ON "functions" USING btree ("active");--> statement-breakpoint +CREATE INDEX "functions_category_idx" ON "functions" USING btree ("category_id");--> statement-breakpoint +CREATE INDEX "skill_categories_slug_idx" ON "skill_categories" USING btree ("slug");--> statement-breakpoint +CREATE INDEX "skill_categories_active_idx" ON "skill_categories" USING btree ("active");--> statement-breakpoint +CREATE INDEX "technologies_slug_idx" ON "technologies" USING btree ("slug");--> statement-breakpoint +CREATE INDEX "technologies_active_idx" ON "technologies" USING btree ("active");--> statement-breakpoint +CREATE INDEX "technologies_vendor_idx" ON "technologies" USING btree ("vendor_id");--> statement-breakpoint +CREATE INDEX "technologies_category_idx" ON "technologies" USING btree ("category_id");--> statement-breakpoint +CREATE INDEX "vendors_slug_idx" ON "vendors" USING btree ("slug");--> statement-breakpoint +CREATE INDEX "vendors_active_idx" ON "vendors" USING btree ("active"); \ No newline at end of file diff --git a/drizzle/meta/0003_snapshot.json b/drizzle/meta/0003_snapshot.json new file mode 100644 index 0000000..c7f7a7d --- /dev/null +++ b/drizzle/meta/0003_snapshot.json @@ -0,0 +1,1519 @@ +{ + "id": "e5b56f4b-4851-4557-8013-15eb1ce13701", + "prevId": "816e4e64-4974-4ecb-8b55-f68f145012f0", + "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.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 + } + }, + "indexes": { + "roles_slug_idx": { + "name": "roles_slug_idx", + "columns": [ + { + "expression": "slug", + "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.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 18d9d73..0a4c240 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -22,6 +22,13 @@ "when": 1794959606685, "tag": "0002_fearless_doctor_spectrum", "breakpoints": true + }, + { + "idx": 3, + "version": "7", + "when": 1794961261600, + "tag": "0003_whole_crystal", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/app/api/dev/catalog/route.ts b/src/app/api/dev/catalog/route.ts new file mode 100644 index 0000000..691ce82 --- /dev/null +++ b/src/app/api/dev/catalog/route.ts @@ -0,0 +1,281 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { + listCatalog, + deactivateCatalog, + createCategory, + updateCategory, + createVendor, + updateVendor, + createTechnology, + updateTechnology, + createFunction, + updateFunction, +} from "@/db/catalog"; + +const JSON_HEADERS = { "content-type": "application/json" }; + +const typeSchema = z.enum(["categories", "vendors", "technologies", "functions"]); + +const idSchema = z.string().min(1); + +/* ---- create schemas (slug is generated server-side, never sent in) ---- */ + +const categoryCreateSchema = z.object({ + name: z.string().min(1), + description: z.string().nullable().optional(), + colorHex: z.string().nullable().optional(), + icon: z.string().nullable().optional(), + sortOrder: z.number().int().optional(), +}); + +const vendorCreateSchema = z.object({ + name: z.string().min(1), + supportUrl: z.string().nullable().optional(), + supportPhone: z.string().nullable().optional(), + notes: z.string().nullable().optional(), + sortOrder: z.number().int().optional(), +}); + +const technologyCreateSchema = z.object({ + name: z.string().min(1), + vendorId: z.string().min(1), + categoryId: z.string().min(1), + modelNumber: z.string().nullable().optional(), + versionLabel: z.string().nullable().optional(), + docsUrl: z.string().nullable().optional(), + purchasedOn: z.string().nullable().optional(), + serialNumber: z.string().nullable().optional(), + successorTechnologyId: z.string().nullable().optional(), + sortOrder: z.number().int().optional(), +}); + +const functionCreateSchema = z.object({ + name: z.string().min(1), + categoryId: z.string().min(1), + description: z.string().nullable().optional(), + sortOrder: z.number().int().optional(), +}); + +/* ---- update schemas (name editable; slug frozen) ---- */ + +const categoryUpdateSchema = z.object({ + name: z.string().min(1).optional(), + description: z.string().nullable().optional(), + colorHex: z.string().nullable().optional(), + icon: z.string().nullable().optional(), + sortOrder: z.number().int().optional(), +}); + +const vendorUpdateSchema = z.object({ + name: z.string().min(1).optional(), + supportUrl: z.string().nullable().optional(), + supportPhone: z.string().nullable().optional(), + notes: z.string().nullable().optional(), + sortOrder: z.number().int().optional(), +}); + +const technologyUpdateSchema = z.object({ + name: z.string().min(1).optional(), + modelNumber: z.string().nullable().optional(), + versionLabel: z.string().nullable().optional(), + docsUrl: z.string().nullable().optional(), + purchasedOn: z.string().nullable().optional(), + serialNumber: z.string().nullable().optional(), + successorTechnologyId: z.string().nullable().optional(), + sortOrder: z.number().int().optional(), +}); + +const functionUpdateSchema = z.object({ + name: z.string().min(1).optional(), + description: z.string().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 so admins get a clear + * message instead of an empty 500: 23505 = duplicate slug, 23503 = dangling + * FK (vendor/category id that does not exist). + */ +const dbError = (err: unknown) => { + // The pg driver wraps the Postgres error in a cause chain; walk it to find + // the SQLSTATE (23505 = duplicate, 23503 = dangling FK). + 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 row with this slug 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/catalog?type=categories&active=true — list pickers rows. */ +export const GET = async (req: NextRequest) => { + const type = typeSchema.safeParse(req.nextUrl.searchParams.get("type")); + if (!type.success) { + return new Response(JSON.stringify({ error: "invalid type" }), { + status: 400, + headers: JSON_HEADERS, + }); + } + const active = req.nextUrl.searchParams.get("active") !== "false"; + const rows = await listCatalog(type.data, { active }); + return new Response(JSON.stringify({ type: type.data, rows }), { + status: 200, + headers: JSON_HEADERS, + }); +}; + +/** POST /api/dev/catalog { type, ...createFields } — create (slug generated). */ +export const POST = async (req: NextRequest) => { + const body = await readBody(req); + if (!body || typeof body !== "object") { + return new Response(JSON.stringify({ error: "invalid body" }), { + status: 400, + headers: JSON_HEADERS, + }); + } + const type = typeSchema.safeParse((body as { type?: unknown }).type); + if (!type.success) { + return new Response(JSON.stringify({ error: "invalid type" }), { + status: 400, + headers: JSON_HEADERS, + }); + } + try { + switch (type.data) { + case "categories": { + const parsed = categoryCreateSchema.safeParse(body); + if (!parsed.success) return bad(parsed.error.message); + return created(await createCategory(parsed.data)); + } + case "vendors": { + const parsed = vendorCreateSchema.safeParse(body); + if (!parsed.success) return bad(parsed.error.message); + return created(await createVendor(parsed.data)); + } + case "technologies": { + const parsed = technologyCreateSchema.safeParse(body); + if (!parsed.success) return bad(parsed.error.message); + return created(await createTechnology(parsed.data)); + } + case "functions": { + const parsed = functionCreateSchema.safeParse(body); + if (!parsed.success) return bad(parsed.error.message); + return created(await createFunction(parsed.data)); + } + } +} catch (err) { + return dbError(err); +} +}; + +/** + * PATCH /api/dev/catalog { type, id, ...updateFields } — rename / edit. + * PATCH { type, 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 new Response(JSON.stringify({ error: "invalid body" }), { + status: 400, + headers: JSON_HEADERS, + }); + } + const type = typeSchema.safeParse((body as { type?: unknown }).type); + if (!type.success) { + return new Response(JSON.stringify({ error: "invalid type" }), { + status: 400, + headers: JSON_HEADERS, + }); + } + const id = idSchema.safeParse((body as { id?: unknown }).id); + if (!id.success) { + return new Response(JSON.stringify({ error: "invalid id" }), { + status: 400, + headers: JSON_HEADERS, + }); + } + // Deactivate path: explicit active=false, no editable fields applied. + try { + if ((body as { active?: unknown }).active === false) { + const row = await deactivateCatalog(type.data, id.data); + return new Response(JSON.stringify({ row }), { + status: 200, + headers: JSON_HEADERS, + }); + } + switch (type.data) { + case "categories": { + const parsed = categoryUpdateSchema.safeParse(body); + if (!parsed.success) return bad(parsed.error.message); + return ok(await updateCategory(id.data, parsed.data)); + } + case "vendors": { + const parsed = vendorUpdateSchema.safeParse(body); + if (!parsed.success) return bad(parsed.error.message); + return ok(await updateVendor(id.data, parsed.data)); + } + case "technologies": { + const parsed = technologyUpdateSchema.safeParse(body); + if (!parsed.success) return bad(parsed.error.message); + return ok(await updateTechnology(id.data, parsed.data)); + } + case "functions": { + const parsed = functionUpdateSchema.safeParse(body); + if (!parsed.success) return bad(parsed.error.message); + return ok(await updateFunction(id.data, parsed.data)); + } + } +} catch (err) { + return dbError(err); +} +}; diff --git a/src/db/catalog.ts b/src/db/catalog.ts new file mode 100644 index 0000000..98527f5 --- /dev/null +++ b/src/db/catalog.ts @@ -0,0 +1,284 @@ +/** + * Catalog data access — the four leaf tables of the skill taxonomy + * (ARCHITECTURE §4.3): skill_categories, vendors, technologies, functions. + * + * Integrity rules (enforced here, not just the UI): + * - Deactivate, never delete — `active` flips to false; the row persists so + * history (skills, technologies, assignments) is preserved. + * - Slug freezes after creation — `update*` rewrites only editable fields and + * never touches `slug`; the display name stays editable. + * - Slugs are generated from the name at create time (src/lib/slug.ts). + * + * Read path: `listCatalog(type, { active: true })` returns only active rows — + * that is what pickers render. `active: false` returns the full set (audit). + */ + +import { asc, eq } from "drizzle-orm"; +import { db } from "@/db"; +import { + skillCategories, + vendors, + technologies, + functions, +} from "@/db/schema"; +import { slugify } from "@/lib/slug"; + +export type CatalogType = "categories" | "vendors" | "technologies" | "functions"; + +/** The four tables, keyed by the public type name. */ +const TABLES = { + categories: skillCategories, + vendors: vendors, + technologies: technologies, + functions: functions, +} as const; + +/* ---------------------------------------------------------- generic ops */ + +/** + * List catalog rows. `active: true` (default) returns only rows visible in + * pickers; `active: false` returns every row including deactivated ones. + */ +export async function listCatalog( + type: CatalogType, + { active = true }: { active?: boolean } = {}, +) { + const table = TABLES[type]; + const rows = await db + .select() + .from(table) + .where(active ? eq(table.active, true) : undefined) + .orderBy(asc(table.sortOrder), table.name); + return rows; +} + +/** Soft-delete: flip `active` to false. The row persists for history. */ +export async function deactivateCatalog(type: CatalogType, id: string) { + const table = TABLES[type]; + const [row] = await db + .update(table) + .set({ active: false, updatedAt: new Date() }) + .where(eq(table.id, id)) + .returning(); + return row; +} + +/* ---------------------------------------------------------- categories */ + +export type CategoryCreate = { + name: string; + description?: string | null; + colorHex?: string | null; + icon?: string | null; + sortOrder?: number; +}; + +export async function createCategory(fields: CategoryCreate) { + const now = new Date(); + const [row] = await db + .insert(skillCategories) + .values({ + id: crypto.randomUUID(), + slug: slugify(fields.name), + name: fields.name, + description: fields.description ?? null, + colorHex: fields.colorHex ?? null, + icon: fields.icon ?? null, + sortOrder: fields.sortOrder ?? 0, + active: true, + createdAt: now, + }) + .returning(); + return row; +} + +export type CategoryUpdate = { + name?: string; + description?: string | null; + colorHex?: string | null; + icon?: string | null; + sortOrder?: number; +}; + +/** Rename / edit — `slug` is intentionally excluded (frozen after creation). */ +export async function updateCategory(id: string, fields: CategoryUpdate) { + 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.icon !== undefined) patch.icon = fields.icon; + if (fields.sortOrder !== undefined) patch.sortOrder = fields.sortOrder; + const [row] = await db + .update(skillCategories) + .set(patch) + .where(eq(skillCategories.id, id)) + .returning(); + return row; +} + +/* ---------------------------------------------------------- vendors */ + +export type VendorCreate = { + name: string; + supportUrl?: string | null; + supportPhone?: string | null; + notes?: string | null; + sortOrder?: number; +}; + +export async function createVendor(fields: VendorCreate) { + const now = new Date(); + const [row] = await db + .insert(vendors) + .values({ + id: crypto.randomUUID(), + slug: slugify(fields.name), + name: fields.name, + supportUrl: fields.supportUrl ?? null, + supportPhone: fields.supportPhone ?? null, + notes: fields.notes ?? null, + sortOrder: fields.sortOrder ?? 0, + active: true, + createdAt: now, + }) + .returning(); + return row; +} + +export type VendorUpdate = { + name?: string; + supportUrl?: string | null; + supportPhone?: string | null; + notes?: string | null; + sortOrder?: number; +}; + +export async function updateVendor(id: string, fields: VendorUpdate) { + const patch: Record = { updatedAt: new Date() }; + if (fields.name !== undefined) patch.name = fields.name; + if (fields.supportUrl !== undefined) patch.supportUrl = fields.supportUrl; + if (fields.supportPhone !== undefined) patch.supportPhone = fields.supportPhone; + if (fields.notes !== undefined) patch.notes = fields.notes; + if (fields.sortOrder !== undefined) patch.sortOrder = fields.sortOrder; + const [row] = await db + .update(vendors) + .set(patch) + .where(eq(vendors.id, id)) + .returning(); + return row; +} + +/* ---------------------------------------------------------- technologies */ + +export type TechnologyCreate = { + name: string; + vendorId: string; + categoryId: string; + modelNumber?: string | null; + versionLabel?: string | null; + docsUrl?: string | null; + purchasedOn?: string | null; + serialNumber?: string | null; + successorTechnologyId?: string | null; + sortOrder?: number; +}; + +export async function createTechnology(fields: TechnologyCreate) { + const now = new Date(); + const [row] = await db + .insert(technologies) + .values({ + id: crypto.randomUUID(), + slug: slugify(fields.name), + name: fields.name, + vendorId: fields.vendorId, + categoryId: fields.categoryId, + modelNumber: fields.modelNumber ?? null, + versionLabel: fields.versionLabel ?? null, + docsUrl: fields.docsUrl ?? null, + purchasedOn: fields.purchasedOn ?? null, + serialNumber: fields.serialNumber ?? null, + successorTechnologyId: fields.successorTechnologyId ?? null, + sortOrder: fields.sortOrder ?? 0, + active: true, + createdAt: now, + }) + .returning(); + return row; +} + +export type TechnologyUpdate = { + name?: string; + modelNumber?: string | null; + versionLabel?: string | null; + docsUrl?: string | null; + purchasedOn?: string | null; + serialNumber?: string | null; + successorTechnologyId?: string | null; + sortOrder?: number; +}; + +export async function updateTechnology(id: string, fields: TechnologyUpdate) { + const patch: Record = { updatedAt: new Date() }; + if (fields.name !== undefined) patch.name = fields.name; + if (fields.modelNumber !== undefined) patch.modelNumber = fields.modelNumber; + if (fields.versionLabel !== undefined) patch.versionLabel = fields.versionLabel; + if (fields.docsUrl !== undefined) patch.docsUrl = fields.docsUrl; + if (fields.purchasedOn !== undefined) patch.purchasedOn = fields.purchasedOn; + if (fields.serialNumber !== undefined) patch.serialNumber = fields.serialNumber; + if (fields.successorTechnologyId !== undefined) + patch.successorTechnologyId = fields.successorTechnologyId; + if (fields.sortOrder !== undefined) patch.sortOrder = fields.sortOrder; + const [row] = await db + .update(technologies) + .set(patch) + .where(eq(technologies.id, id)) + .returning(); + return row; +} + +/* ---------------------------------------------------------- functions */ + +export type FunctionCreate = { + name: string; + categoryId: string; + description?: string | null; + sortOrder?: number; +}; + +export async function createFunction(fields: FunctionCreate) { + const now = new Date(); + const [row] = await db + .insert(functions) + .values({ + id: crypto.randomUUID(), + slug: slugify(fields.name), + name: fields.name, + categoryId: fields.categoryId, + description: fields.description ?? null, + sortOrder: fields.sortOrder ?? 0, + active: true, + createdAt: now, + }) + .returning(); + return row; +} + +export type FunctionUpdate = { + name?: string; + description?: string | null; + sortOrder?: number; +}; + +export async function updateFunction(id: string, fields: FunctionUpdate) { + const patch: Record = { updatedAt: new Date() }; + if (fields.name !== undefined) patch.name = fields.name; + if (fields.description !== undefined) patch.description = fields.description; + if (fields.sortOrder !== undefined) patch.sortOrder = fields.sortOrder; + const [row] = await db + .update(functions) + .set(patch) + .where(eq(functions.id, id)) + .returning(); + return row; +} diff --git a/src/db/schema.ts b/src/db/schema.ts index d540ba7..47ff1d1 100644 --- a/src/db/schema.ts +++ b/src/db/schema.ts @@ -5,9 +5,8 @@ * users → roles → services → service_instances → slots → assignments * * Deliberately NOT here (added in later units, do not add "while I'm in the schema"): - * - notification_preferences (B2), notification_templates/rules/outbox (later) - * - Catalog taxonomy: skill_categories, vendors, technologies, functions, - * skills, position_skills, user_skills, skill_assessments, growth_goals (B3) + * - notification_templates/rules/outbox (later) + * - skills, position_skills, user_skills, skill_assessments, growth_goals (C1-C6) * - service_role_requirements, unavailability, events, notifications outbox * * Conventions (ARCHITECTURE §4.2): @@ -252,6 +251,123 @@ export const assignments = pgTable( ], ); +/* ------------------------------------------------------------- catalog */ + +/** + * 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. + */ + +export const skillCategories = pgTable( + "skill_categories", + { + id: text("id").primaryKey(), + slug: text("slug").unique().notNull(), + /** Editable — the display name an admin renames. */ + name: text("name").notNull(), + description: text("description"), + colorHex: text("color_hex"), + icon: text("icon"), + 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("skill_categories_slug_idx").on(table.slug), + index("skill_categories_active_idx").on(table.active), + ], +); + +export const vendors = pgTable( + "vendors", + { + id: text("id").primaryKey(), + slug: text("slug").unique().notNull(), + name: text("name").notNull(), + supportUrl: text("support_url"), + supportPhone: text("support_phone"), + notes: text("notes"), + 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("vendors_slug_idx").on(table.slug), + index("vendors_active_idx").on(table.active), + ], +); + +export const technologies = pgTable( + "technologies", + { + id: text("id").primaryKey(), + slug: text("slug").unique().notNull(), + name: text("name").notNull(), + vendorId: text("vendor_id") + .notNull() + .references(() => vendors.id, { onDelete: "restrict" }), + categoryId: text("category_id") + .notNull() + .references(() => skillCategories.id, { onDelete: "restrict" }), + modelNumber: text("model_number"), + versionLabel: text("version_label"), + docsUrl: text("docs_url"), + /** Local-date asset tracking, stored as "YYYY-MM-DD" (string mode). */ + purchasedOn: date("purchased_on", { mode: "string" }), + serialNumber: text("serial_number"), + retiredAt: timestamp("retired_at", { mode: "date", withTimezone: true }), + /** "ATEM Mini Pro → ATEM SDI Pro ISO" migration hint. Plain text (no + * self-FK): the pointer is a soft hint validated at the app layer, so a + * self-referential FK does not create a circular schema type. */ + successorTechnologyId: text("successor_technology_id"), + 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("technologies_slug_idx").on(table.slug), + index("technologies_active_idx").on(table.active), + index("technologies_vendor_idx").on(table.vendorId), + index("technologies_category_idx").on(table.categoryId), + ], +); + +export const functions = pgTable( + "functions", + { + id: text("id").primaryKey(), + slug: text("slug").unique().notNull(), + name: text("name").notNull(), + /** Functions are grouped, not enumerated — one category each. */ + categoryId: text("category_id") + .notNull() + .references(() => skillCategories.id, { onDelete: "restrict" }), + description: text("description"), + 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("functions_slug_idx").on(table.slug), + index("functions_active_idx").on(table.active), + index("functions_category_idx").on(table.categoryId), + ], +); + /* ------------------------------------------------------------- relations */ export const usersRelations = relations(users, ({ many }) => ({ @@ -279,6 +395,39 @@ export const assignmentRelations = relations(assignments, ({ one }) => ({ user: one(users), })); +export const skillCategoriesRelations = relations( + skillCategories, + ({ many }) => ({ + technologies: many(technologies), + functions: many(functions), + }), +); + +export const vendorsRelations = relations(vendors, ({ many }) => ({ + technologies: many(technologies), +})); + +export const technologiesRelations = relations( + technologies, + ({ one }) => ({ + vendor: one(vendors, { fields: [technologies.vendorId], references: [vendors.id] }), + category: one( + skillCategories, + { fields: [technologies.categoryId], references: [skillCategories.id] }, + ), + }), +); + +export const functionsRelations = relations( + functions, + ({ one }) => ({ + category: one( + skillCategories, + { fields: [functions.categoryId], references: [skillCategories.id] }, + ), + }), +); + /** * The schema object Drizzle uses for migrations and the query layer. * Phase A2 core only; catalog + downstream tables are added in their own units. @@ -291,6 +440,10 @@ export const schema = { serviceInstances, slots, assignments, + skillCategories, + vendors, + technologies, + functions, }; export type Schema = typeof schema; diff --git a/src/lib/slug.test.ts b/src/lib/slug.test.ts new file mode 100644 index 0000000..dc71b5d --- /dev/null +++ b/src/lib/slug.test.ts @@ -0,0 +1,31 @@ +import { describe, it, expect } from "vitest"; +import { slugify } from "@/lib/slug"; + +describe("slugify", () => { + it("lowercases a single word", () => { + expect(slugify("Audio")).toBe("audio"); + }); + + it("replaces spaces with single hyphens", () => { + expect(slugify("ATEM Mini Pro")).toBe("atem-mini-pro"); + }); + + it("drops punctuation and collapses runs", () => { + expect(slugify("Allen & Heath")).toBe("allen-heath"); + expect(slugify("OBS Studio!!")).toBe("obs-studio"); + }); + + it("trims leading/trailing hyphens", () => { + expect(slugify(" & Audio ")).toBe("audio"); + }); + + it("keeps alphanumerics in place", () => { + expect(slugify("QL5")).toBe("ql5"); + expect(slugify("ProPresenter 7")).toBe("propresenter-7"); + }); + + it("ASCII-folds accented Latin letters", () => { + expect(slugify("Café Signal")).toBe("cafe-signal"); + expect(slugify("Zoë")).toBe("zoe"); + }); +}); diff --git a/src/lib/slug.ts b/src/lib/slug.ts new file mode 100644 index 0000000..6dea060 --- /dev/null +++ b/src/lib/slug.ts @@ -0,0 +1,38 @@ +/** + * Slug generator for the skill taxonomy (ARCHITECTURE §4.3). + * + * Slugs freeze after creation — they appear in URLs, ICS exports and + * notification links — so they are generated deterministically from the + * display name at create time and never rewritten on rename. + */ + +/** + * Turn a display name into a URL-safe slug: lowercase, ASCII-folded, + * non-alphanumeric runs collapsed to a single hyphen, edges trimmed. + * + * "Audio" -> "audio" + * "ATEM Mini Pro" -> "atem-mini-pro" + * "Allen & Heath" -> "allen-heath" + * "QL5" -> "ql5" + */ +export function slugify(name: string): string { + return name + // Basic Latin fold: accented / special Latin letters → ASCII. + .normalize("NFKD") + .replace(/[\u00C0-\u00FF]/g, (ch) => { + const folded: Record = { + À: "A", Á: "A", Â: "A", Ã: "A", Ä: "A", Å: "A", Æ: "AE", Ç: "C", + È: "E", É: "E", Ê: "E", Ë: "E", Ì: "I", Í: "I", Î: "I", Ï: "I", + Ð: "D", Ñ: "N", Ò: "O", Ó: "O", Ô: "O", Õ: "O", Ö: "O", "×": "x", + Ù: "U", Ú: "U", Û: "U", Ü: "U", Ý: "Y", Þ: "Th", + }; + return folded[ch] ?? ""; + }) + // Drop any remaining non-ASCII (chars outside the Latin-1 block). + .replace(/[^\u0000-\u007F]/g, "") + // Lowercase before the alphanumerics-only run collapse below. + .toLowerCase() + // Any non-alphanumeric run → single hyphen. + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, ""); +}