ubiquitous-invention/apps/web/server/routers/templates.ts
Randall Stillwell c582d621ce multi-tenancy: promote workspaces to top-level table
Block A of the EchoDo plan. Workspaces used to live as `objects(type='workspace')`,
which made it impossible to put a real RLS-friendly tenant boundary on the schema
or to give each workspace a stable URL slug. This commit:

- Adds a top-level `workspaces` table (slug unique, owner FK, plan_tier hook).
- Migrates the 8 anchor tables (objects, workspace_members, object_type_defs,
  property_definitions, templates, forms, markdown_backlog_items,
  cursor_sync_mappings) to FK into `workspaces.id` instead of `objects.id`,
  with a hand-augmented data-copy migration that preserves IDs and slug-collision-
  proofs on backfill.
- Introduces a `workspaceProcedure` tRPC middleware + `resolveWorkspace` helper
  that take a UUID-or-slug `workspace` handle and expose `ctx.workspace`. All
  tenant-scoped routers (objects, types, properties, templates, forms, search,
  ai, relations, favorites) now flow through it.
- Updates the web app to pass `workspace` slugs from the URL (or store) instead
  of the old `workspaceId`, including a workspace-sync layer that rewrites
  /<UUID>/... links to /<slug>/...
- Updates the MCP tools (list_objects, create_object, search_objects) and the
  workspace://{handle}/tree resource to accept either a slug or UUID so existing
  agents keep working.
- Adds a Create Workspace dialog and a Workspace Settings page (rename + slug
  rename with redirect, owner-only archive).

Verified locally against a fresh Postgres: migration applies cleanly, slug
uniqueness holds, tenant data is isolated by workspace_id, slug↔UUID resolution
works in both directions, and ON DELETE CASCADE cleans up child rows in the
correct workspace only.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-06 23:02:55 -05:00

288 lines
7.6 KiB
TypeScript

import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { and, asc, desc, eq, sql } from "drizzle-orm";
import {
objects,
propertyDefinitions,
propertyValues,
templates,
} from "@tasks/database/schema";
import { type Context, router, workspaceProcedure } from "@/server/trpc";
const templatePropertySchema = z.object({
name: z.string().min(1).max(255),
fieldType: z.string().min(1).max(50),
defaultValue: z.unknown().optional(),
});
export const templateSchemaJson = z
.object({
properties: z.array(templatePropertySchema).optional(),
defaultContent: z.string().optional(),
})
.optional();
export type TemplateSchemaJson = z.infer<typeof templateSchemaJson>;
function escapeHtml(s: string): string {
return s
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
function defaultContentToHtml(text: string): string {
const trimmed = text.trim();
if (!trimmed) return "<p></p>";
const paragraphs = trimmed.split(/\n\n+/);
return paragraphs
.map((p) => `<p>${escapeHtml(p).replace(/\n/g, "<br/>")}</p>`)
.join("");
}
async function getMaxPropertySortOrder(
db: Context["db"],
workspaceId: string,
): Promise<number> {
const [row] = await db
.select({
m: sql<number>`coalesce(max(${propertyDefinitions.sortOrder}), 0)`.mapWith(
Number,
),
})
.from(propertyDefinitions)
.where(eq(propertyDefinitions.workspaceId, workspaceId));
return row?.m ?? 0;
}
export const templatesRouter = router({
list: workspaceProcedure
.input(
z.object({
targetType: z.string().max(50).optional(),
}),
)
.query(async ({ ctx, input }) => {
const conditions = [eq(templates.workspaceId, ctx.workspace.id)];
if (input.targetType !== undefined) {
conditions.push(eq(templates.targetType, input.targetType));
}
const rows = await ctx.db
.select()
.from(templates)
.where(and(...conditions))
.orderBy(asc(templates.name), desc(templates.updatedAt));
return { templates: rows };
}),
getById: workspaceProcedure
.input(z.object({ id: z.string().uuid() }))
.query(async ({ ctx, input }) => {
const row = await ctx.db.query.templates.findFirst({
where: and(
eq(templates.id, input.id),
eq(templates.workspaceId, ctx.workspace.id),
),
});
if (!row) {
throw new TRPCError({ code: "NOT_FOUND", message: "Template not found" });
}
return row;
}),
create: workspaceProcedure
.input(
z.object({
name: z.string().min(1).max(255),
targetType: z.string().min(1).max(50),
schema: templateSchemaJson,
}),
)
.mutation(async ({ ctx, input }) => {
const now = new Date();
const [created] = await ctx.db
.insert(templates)
.values({
workspaceId: ctx.workspace.id,
name: input.name,
targetType: input.targetType,
schema: input.schema ?? null,
createdAt: now,
updatedAt: now,
})
.returning();
if (!created) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Failed to create template",
});
}
return created;
}),
update: workspaceProcedure
.input(
z.object({
id: z.string().uuid(),
name: z.string().min(1).max(255).optional(),
schema: templateSchemaJson,
}),
)
.mutation(async ({ ctx, input }) => {
const { id, ...patch } = input;
const now = new Date();
const [updated] = await ctx.db
.update(templates)
.set({
...(patch.name !== undefined ? { name: patch.name } : {}),
...(patch.schema !== undefined ? { schema: patch.schema } : {}),
updatedAt: now,
})
.where(
and(eq(templates.id, id), eq(templates.workspaceId, ctx.workspace.id)),
)
.returning();
if (!updated) {
throw new TRPCError({ code: "NOT_FOUND", message: "Template not found" });
}
return updated;
}),
delete: workspaceProcedure
.input(z.object({ id: z.string().uuid() }))
.mutation(async ({ ctx, input }) => {
const deleted = await ctx.db
.delete(templates)
.where(
and(
eq(templates.id, input.id),
eq(templates.workspaceId, ctx.workspace.id),
),
)
.returning({ id: templates.id });
if (deleted.length === 0) {
throw new TRPCError({ code: "NOT_FOUND", message: "Template not found" });
}
}),
applyTemplate: workspaceProcedure
.input(
z.object({
objectId: z.string().uuid(),
templateId: z.string().uuid(),
}),
)
.mutation(async ({ ctx, input }) => {
const template = await ctx.db.query.templates.findFirst({
where: and(
eq(templates.id, input.templateId),
eq(templates.workspaceId, ctx.workspace.id),
),
});
if (!template) {
throw new TRPCError({ code: "NOT_FOUND", message: "Template not found" });
}
const obj = await ctx.db.query.objects.findFirst({
where: and(
eq(objects.id, input.objectId),
eq(objects.workspaceId, ctx.workspace.id),
),
});
if (!obj) {
throw new TRPCError({ code: "NOT_FOUND", message: "Object not found" });
}
const schema = (template.schema ?? {}) as {
properties?: { name: string; fieldType: string; defaultValue?: unknown }[];
defaultContent?: string;
};
const workspaceId = ctx.workspace.id;
let nextSort = (await getMaxPropertySortOrder(ctx.db, workspaceId)) + 1;
const now = new Date();
const contentPatch =
typeof schema.defaultContent === "string" && schema.defaultContent.trim() !== ""
? { content: defaultContentToHtml(schema.defaultContent) }
: {};
const [updatedObject] = await ctx.db
.update(objects)
.set({
templateId: template.id,
...contentPatch,
updatedAt: now,
})
.where(eq(objects.id, input.objectId))
.returning();
if (!updatedObject) {
throw new TRPCError({ code: "NOT_FOUND", message: "Object not found" });
}
let propertyCount = 0;
const props = schema.properties ?? [];
for (const prop of props) {
let def = await ctx.db.query.propertyDefinitions.findFirst({
where: and(
eq(propertyDefinitions.workspaceId, workspaceId),
eq(propertyDefinitions.name, prop.name),
),
});
if (!def) {
const [createdDef] = await ctx.db
.insert(propertyDefinitions)
.values({
workspaceId,
name: prop.name,
fieldType: prop.fieldType,
sortOrder: nextSort++,
})
.returning();
def = createdDef;
}
if (!def) continue;
await ctx.db
.insert(propertyValues)
.values({
objectId: input.objectId,
propertyDefId: def.id,
value: prop.defaultValue ?? null,
updatedAt: now,
})
.onConflictDoUpdate({
target: [propertyValues.objectId, propertyValues.propertyDefId],
set: {
value: prop.defaultValue ?? null,
updatedAt: now,
},
});
propertyCount += 1;
}
return {
object: updatedObject,
applied: { propertyCount },
};
}),
});