ubiquitous-invention/apps/web/server/routers/objects.ts
Randall Stillwell f64d307f72 feat(web): wire workspace-home dashboard to real tRPC queries
Path-A task 2/5. Replaces the hardcoded `stats` (24/8/12) and
hardcoded `recent` list on the workspace-home page with real
workspace-scoped data.

* server/routers/objects.ts: add two new procedures.
  - `objects.stats` returns { openTasks, containers }. Open-task count
    treats null status as open; only `done` and `closed` (per
    packages/shared object-statuses) are terminal. Container count
    aggregates project + space + group rows.
  - `objects.listRecent({ limit })` returns the N most-recently-updated
    rows, descending by updated_at. Excludes archived and excludes
    `workspace`/`group` from the activity feed (containers clutter
    "what did I just touch" recency).
  Both go through workspaceProcedure, so the workspace_id filter
  comes from the middleware-resolved ctx.workspace.id rather than
  any user input.

* app/(app)/[workspaceSlug]/page.tsx: rewrite to consume the new
  procedures via @trpc/react-query. Adds:
  - Skeleton loading state (no flash of zeros).
  - Empty state with a "New task" CTA on workspaces with no objects.
  - Real "X ago" labels on the recent feed.
  - Click-through links from recent rows to /{slug}/{id}.
  - A locally-mounted CreateObjectDialog instance independent of the
    global one in AppShell so the empty-state CTA can pre-seed
    defaultType="task" without coordinating shared state.

* components/ui/skeleton.tsx: new (standard shadcn pulse skeleton).
  Used by the dashboard but reusable across the app.

The scaffolded "Due this week" stat is dropped: `objects` has no
due_at column and the task explicitly preferred dropping a card to
schema-creep.

`pnpm lint && pnpm type-check` clean. Closes
plans/Plan-daily-driver-finish/Epic-shipping-the-shell/
Task-wire-workspace-home-dashboard.md.

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

484 lines
14 KiB
TypeScript

import { TRPCError } from "@trpc/server";
import { z } from "zod";
import {
and,
asc,
desc,
eq,
getTableColumns,
inArray,
isNull,
notInArray,
or,
sql,
} from "drizzle-orm";
import { objectTypes } from "@tasks/shared";
import { objectAssignees, objects } from "@tasks/database/schema";
import { router, workspaceProcedure } from "@/server/trpc";
const objectTypeSchema = z.enum(objectTypes);
const TREE_TYPES = [
"project",
"space",
"group",
"document",
"whiteboard",
] as const;
export type ObjectTreeNode = {
id: string;
title: string;
type: string;
icon: string | null;
parentId: string | null;
childCount: number;
children: ObjectTreeNode[];
};
/**
* Reusable: confirm a given object id belongs to the resolved workspace, throwing
* NOT_FOUND otherwise. Prevents cross-tenant ID guessing on per-id mutations.
*/
async function assertObjectInWorkspace(
db: typeof import("@tasks/database").db,
objectId: string,
workspaceId: string,
): Promise<void> {
const [row] = await db
.select({ id: objects.id })
.from(objects)
.where(and(eq(objects.id, objectId), eq(objects.workspaceId, workspaceId)))
.limit(1);
if (!row) {
throw new TRPCError({ code: "NOT_FOUND", message: "Object not found" });
}
}
export const objectsRouter = router({
list: workspaceProcedure
.input(
z.object({
parentId: z.string().uuid().nullable().optional(),
type: objectTypeSchema.optional(),
status: z.string().optional(),
limit: z.number().int().positive().max(500).optional(),
offset: z.number().int().nonnegative().optional(),
}),
)
.query(async ({ ctx, input }) => {
const limit = input.limit ?? 50;
const offset = input.offset ?? 0;
const conditions = [
eq(objects.workspaceId, ctx.workspace.id),
isNull(objects.archivedAt),
];
if (input.parentId === null) {
conditions.push(isNull(objects.parentId));
} else if (input.parentId !== undefined) {
conditions.push(eq(objects.parentId, input.parentId));
}
if (input.type !== undefined) {
conditions.push(eq(objects.type, input.type));
}
if (input.status !== undefined) {
conditions.push(eq(objects.status, input.status));
}
const rows = await ctx.db
.select({
...getTableColumns(objects),
assigneeCount: sql<number>`(
select count(*)::int from object_assignees
where object_id = ${objects.id}
)`.mapWith(Number),
})
.from(objects)
.where(and(...conditions))
.orderBy(asc(objects.sortOrder), asc(objects.id))
.limit(limit)
.offset(offset);
return { objects: rows };
}),
getById: workspaceProcedure
.input(z.object({ id: z.string().uuid() }))
.query(async ({ ctx, input }) => {
const obj = await ctx.db.query.objects.findFirst({
where: and(
eq(objects.id, input.id),
eq(objects.workspaceId, ctx.workspace.id),
),
with: {
children: true,
assignees: { with: { user: true } },
propertyValues: { with: { propertyDefinition: true } },
},
});
if (!obj) {
throw new TRPCError({ code: "NOT_FOUND", message: "Object not found" });
}
const children = [...obj.children].sort((a, b) => {
if (a.sortOrder !== b.sortOrder) {
return a.sortOrder - b.sortOrder;
}
return a.id.localeCompare(b.id);
});
return { ...obj, children };
}),
getTree: workspaceProcedure
.input(
z.object({
maxDepth: z.number().int().positive().max(100).optional(),
}),
)
.query(async ({ ctx, input }) => {
const maxDepth = input.maxDepth ?? 50;
const rows = await ctx.db
.select()
.from(objects)
.where(
and(
eq(objects.workspaceId, ctx.workspace.id),
inArray(objects.type, [...TREE_TYPES]),
isNull(objects.archivedAt),
),
)
.orderBy(asc(objects.sortOrder), asc(objects.id));
const ids = new Set(rows.map((r) => r.id));
const childCountMap = new Map<string, number>();
for (const row of rows) {
if (row.parentId) {
childCountMap.set(
row.parentId,
(childCountMap.get(row.parentId) ?? 0) + 1,
);
}
}
function buildTree(parentId: string | null, depth: number): ObjectTreeNode[] {
if (depth > maxDepth) {
return [];
}
const directChildren = rows.filter((r) => r.parentId === parentId);
return directChildren.map((r) => ({
id: r.id,
title: r.title,
type: r.type,
icon: r.icon,
parentId: r.parentId,
childCount: childCountMap.get(r.id) ?? 0,
children: buildTree(r.id, depth + 1),
}));
}
const roots = rows.filter(
(r) => r.parentId === null || !ids.has(r.parentId),
);
const tree: ObjectTreeNode[] = roots.map((r) => ({
id: r.id,
title: r.title,
type: r.type,
icon: r.icon,
parentId: r.parentId,
childCount: childCountMap.get(r.id) ?? 0,
children: buildTree(r.id, 1),
}));
return { tree };
}),
create: workspaceProcedure
.input(
z.object({
type: objectTypeSchema,
title: z.string().min(1).max(500),
parentId: z.string().uuid().nullable().optional(),
description: z.string().optional(),
icon: z.string().optional(),
status: z.string().optional(),
templateId: z.string().uuid().nullable().optional(),
}),
)
.mutation(async ({ ctx, input }) => {
const userId = ctx.session.user.id;
if (!userId) {
throw new TRPCError({ code: "UNAUTHORIZED", message: "Missing user id" });
}
if (input.parentId) {
await assertObjectInWorkspace(ctx.db, input.parentId, ctx.workspace.id);
}
const [created] = await ctx.db
.insert(objects)
.values({
type: input.type,
title: input.title,
parentId: input.parentId ?? null,
workspaceId: ctx.workspace.id,
description: input.description,
icon: input.icon,
status: input.status,
templateId: input.templateId ?? null,
createdBy: userId,
})
.returning();
if (!created) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Failed to create object",
});
}
return created;
}),
update: workspaceProcedure
.input(
z.object({
id: z.string().uuid(),
title: z.string().min(1).max(500).optional(),
description: z.string().nullable().optional(),
icon: z.string().nullable().optional(),
status: z.string().nullable().optional(),
coverImage: z.string().nullable().optional(),
content: z.any().optional(),
}),
)
.mutation(async ({ ctx, input }) => {
const { id, ...patch } = input;
await assertObjectInWorkspace(ctx.db, id, ctx.workspace.id);
const updatedAt = new Date();
const [updated] = await ctx.db
.update(objects)
.set({
...(patch.title !== undefined ? { title: patch.title } : {}),
...(patch.description !== undefined ? { description: patch.description } : {}),
...(patch.icon !== undefined ? { icon: patch.icon } : {}),
...(patch.status !== undefined ? { status: patch.status } : {}),
...(patch.coverImage !== undefined ? { coverImage: patch.coverImage } : {}),
...(patch.content !== undefined ? { content: patch.content } : {}),
updatedAt,
})
.where(eq(objects.id, id))
.returning();
if (!updated) {
throw new TRPCError({ code: "NOT_FOUND", message: "Object not found" });
}
return updated;
}),
archive: workspaceProcedure
.input(z.object({ id: z.string().uuid() }))
.mutation(async ({ ctx, input }) => {
await assertObjectInWorkspace(ctx.db, input.id, ctx.workspace.id);
const archivedAt = new Date();
const [row] = await ctx.db
.update(objects)
.set({ archivedAt, updatedAt: archivedAt })
.where(eq(objects.id, input.id))
.returning();
if (!row) {
throw new TRPCError({ code: "NOT_FOUND", message: "Object not found" });
}
return row;
}),
delete: workspaceProcedure
.input(z.object({ id: z.string().uuid() }))
.mutation(async ({ ctx, input }) => {
await assertObjectInWorkspace(ctx.db, input.id, ctx.workspace.id);
const deleted = await ctx.db
.delete(objects)
.where(eq(objects.id, input.id))
.returning({ id: objects.id });
if (deleted.length === 0) {
throw new TRPCError({ code: "NOT_FOUND", message: "Object not found" });
}
return deleted[0];
}),
reorder: workspaceProcedure
.input(
z.object({
id: z.string().uuid(),
sortOrder: z.number().int(),
newParentId: z.string().uuid().nullable().optional(),
}),
)
.mutation(async ({ ctx, input }) => {
await assertObjectInWorkspace(ctx.db, input.id, ctx.workspace.id);
if (input.newParentId) {
await assertObjectInWorkspace(ctx.db, input.newParentId, ctx.workspace.id);
}
const updates: {
sortOrder: number;
updatedAt: Date;
parentId?: string | null;
} = {
sortOrder: input.sortOrder,
updatedAt: new Date(),
};
if (input.newParentId !== undefined) {
updates.parentId = input.newParentId;
}
const [row] = await ctx.db
.update(objects)
.set(updates)
.where(eq(objects.id, input.id))
.returning();
if (!row) {
throw new TRPCError({ code: "NOT_FOUND", message: "Object not found" });
}
return row;
}),
assign: workspaceProcedure
.input(
z.object({
objectId: z.string().uuid(),
userId: z.string().uuid(),
role: z.string().max(50).optional(),
action: z.enum(["add", "remove"]),
}),
)
.mutation(async ({ ctx, input }) => {
await assertObjectInWorkspace(ctx.db, input.objectId, ctx.workspace.id);
if (input.action === "remove") {
const deleted = await ctx.db
.delete(objectAssignees)
.where(
and(
eq(objectAssignees.objectId, input.objectId),
eq(objectAssignees.userId, input.userId),
),
)
.returning({ id: objectAssignees.id });
if (deleted.length === 0) {
throw new TRPCError({ code: "NOT_FOUND", message: "Assignee not found" });
}
return { ok: true as const, action: "remove" as const };
}
const role = input.role ?? "assignee";
await ctx.db
.insert(objectAssignees)
.values({
objectId: input.objectId,
userId: input.userId,
role,
})
.onConflictDoUpdate({
target: [objectAssignees.objectId, objectAssignees.userId],
set: { role },
});
return { ok: true as const, action: "add" as const };
}),
/**
* Workspace-home dashboard summary: counts that don't require expensive joins.
* "Open tasks" treats null status as open (a task with no explicit status
* isn't done). Terminal statuses are `done` and `closed` per
* `packages/shared/src/types/objects.ts`.
*/
stats: workspaceProcedure.query(async ({ ctx }) => {
const TERMINAL_STATUSES = ["done", "closed"] as const;
const CONTAINER_TYPES = ["project", "space", "group"] as const;
const [openTasksRow] = await ctx.db
.select({ count: sql<number>`count(*)::int`.mapWith(Number) })
.from(objects)
.where(
and(
eq(objects.workspaceId, ctx.workspace.id),
isNull(objects.archivedAt),
eq(objects.type, "task"),
or(
isNull(objects.status),
notInArray(objects.status, [...TERMINAL_STATUSES]),
),
),
);
const [containersRow] = await ctx.db
.select({ count: sql<number>`count(*)::int`.mapWith(Number) })
.from(objects)
.where(
and(
eq(objects.workspaceId, ctx.workspace.id),
isNull(objects.archivedAt),
inArray(objects.type, [...CONTAINER_TYPES]),
),
);
return {
openTasks: openTasksRow?.count ?? 0,
containers: containersRow?.count ?? 0,
};
}),
/**
* Recently-updated objects for the workspace-home "Recent activity" panel.
* Excludes archived. Excludes group/space rows from the feed (they show up
* elsewhere and clutter the recency view).
*/
listRecent: workspaceProcedure
.input(
z.object({
limit: z.number().int().positive().max(50).optional(),
}),
)
.query(async ({ ctx, input }) => {
const limit = input.limit ?? 5;
const FEED_EXCLUDED_TYPES = ["workspace", "group"] as const;
const rows = await ctx.db
.select({
id: objects.id,
title: objects.title,
type: objects.type,
status: objects.status,
icon: objects.icon,
updatedAt: objects.updatedAt,
})
.from(objects)
.where(
and(
eq(objects.workspaceId, ctx.workspace.id),
isNull(objects.archivedAt),
notInArray(objects.type, [...FEED_EXCLUDED_TYPES]),
),
)
.orderBy(desc(objects.updatedAt))
.limit(limit);
return { objects: rows };
}),
});