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:
Tiel Coder
2026-11-18 01:00:10 +00:00
parent 26b31978e2
commit 9f7a65b136
9 changed files with 2425 additions and 3 deletions
+284
View File
@@ -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
View File
@@ -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;