B3: catalog taxonomy CRUD (categories, vendors, technologies, functions)
Create/rename/deactivate for the four taxonomy tables. Deactivate not delete; slug frozen after creation; FKs ON DELETE RESTRICT. - src/db/schema.ts: four tables + relations (ON DELETE RESTRICT FKs) - src/lib/slug.ts: slugify (lowercase, ASCII-fold, collapse runs) + 6 tests - src/db/catalog.ts: listCatalog (active filter), deactivateCatalog (soft delete), per-entity create*/update* (slug generated at create, frozen on update; update patches only present fields) - src/app/api/dev/catalog/route.ts: GET/POST/PATCH; Zod per entity; DB constraint errors mapped to 409 (dup slug) / 400 (dangling FK) via cause chain - drizzle/0003_whole_crystal.sql Verification: typecheck, lint, 36 unit tests (+6), build, db:migrate all exit 0. Runtime smoke: create -> rename keeps slug -> deactivate hides from pickers but row persists (all four types); partial PATCH preserves omitted fields; validation 400/400/400/409.
This commit is contained in:
@@ -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.****
|
||||
|
||||
@@ -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");
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
};
|
||||
@@ -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<string, unknown> = { updatedAt: new Date() };
|
||||
if (fields.name !== undefined) patch.name = fields.name;
|
||||
if (fields.description !== undefined) patch.description = fields.description;
|
||||
if (fields.colorHex !== undefined) patch.colorHex = fields.colorHex;
|
||||
if (fields.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<string, unknown> = { 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<string, unknown> = { 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<string, unknown> = { 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;
|
||||
}
|
||||
+156
-3
@@ -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;
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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<string, string> = {
|
||||
À: "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, "");
|
||||
}
|
||||
Reference in New Issue
Block a user