- New resolveActiveDomain() helper in apps/web/lib/auth.ts: returns the
user's first existing domain (ordered by sort_order then created_at),
or auto-creates a default 'Personal' domain if they have none.
- 7 affected API routes (agents, canvases, domains, habits, projects,
search, tasks) now fall back to resolveActiveDomain when the request
omits a domain param. This eliminates the UNDEFINED_VALUE on domain_id
and 22P02 invalid uuid errors that broke 6+ UI flows.
- New POST /api/quick-capture route: switches on type=task|habit|note|project
to create the right entity, after resolving the active domain. This is
the API the dashboard quick-capture widget calls.
- packages/db/src/schema.ts: added ownerId: uuid('owner_id') to the
domains table so each user owns their domains.
- drizzle/0004_add_owner_id_to_domains.sql: matching migration with
column add + index.
- apps/web/__tests__/lib/auth.test.ts: unit tests for both branches of
resolveActiveDomain (returns existing / creates Personal).
- apps/web/app/(dashboard)/canvas/page.tsx: removed hardcoded
domain: 'personal' from the quick-create payload so server-side
resolution can do its job.
This unblocks all of: /tasks, /habits, /projects, /search, /settings/agents,
/settings/domains, /canvas, and dashboard quick-capture.
127 lines
4.0 KiB
TypeScript
127 lines
4.0 KiB
TypeScript
// AGENT INSTRUCTION: After every write (INSERT/UPDATE/DELETE), you MUST:
|
|
// 1. Insert activity feed entry
|
|
// 2. Call pg.notify('project_e_events', JSON.stringify({ type, action, id, workspace_id }))
|
|
// See AGENTS.md for full rules.
|
|
|
|
import { NextRequest, NextResponse } from 'next/server';
|
|
import { withAuth, createErrorResponse, resolveActiveDomain } from '@/lib/auth';
|
|
import { db, domains } from '@project-e/db';
|
|
import { and, asc, desc, eq, ilike, or, sql } from 'drizzle-orm';
|
|
import { z } from 'zod';
|
|
|
|
const createDomainSchema = z.object({
|
|
name: z.string().min(1, 'Name is required'),
|
|
slug: z.string().min(1, 'Slug is required'),
|
|
color: z.string().optional().nullable(),
|
|
icon: z.string().optional().nullable(),
|
|
parentId: z.string().uuid().optional().nullable(),
|
|
});
|
|
|
|
// GET /api/domains — List domains with filtering, sorting, pagination
|
|
export const GET = withAuth(async (request: NextRequest, user) => {
|
|
const { searchParams } = new URL(request.url);
|
|
const page = Math.max(1, parseInt(searchParams.get('page') || '1'));
|
|
const perPage = Math.min(100, Math.max(1, parseInt(searchParams.get('perPage') || '50')));
|
|
const sortParam = searchParams.get('sort') || 'sort_order';
|
|
const filter = searchParams.get('filter') || undefined;
|
|
|
|
// Build order by — whitelist safe column names
|
|
const sortDir = sortParam.startsWith('-') ? 'desc' : 'asc';
|
|
const sortField = sortParam.replace(/^-/, '');
|
|
const sortColumns: Record<string, any> = {
|
|
name: domains.name,
|
|
slug: domains.slug,
|
|
sort_order: domains.sortOrder,
|
|
created_at: domains.createdAt,
|
|
updated_at: domains.updatedAt,
|
|
};
|
|
const orderBy = sortDir === 'asc'
|
|
? asc(sortColumns[sortField] || domains.sortOrder)
|
|
: desc(sortColumns[sortField] || domains.sortOrder);
|
|
|
|
// Build where clause — filter by owner
|
|
const conditions: any[] = [eq(domains.ownerId, user.id)];
|
|
if (filter) {
|
|
conditions.push(
|
|
or(
|
|
ilike(domains.name, `%${filter}%`),
|
|
ilike(domains.slug, `%${filter}%`),
|
|
)!
|
|
);
|
|
}
|
|
|
|
const offset = (page - 1) * perPage;
|
|
|
|
const [items, countResult] = await Promise.all([
|
|
db.select()
|
|
.from(domains)
|
|
.where(and(...conditions))
|
|
.orderBy(orderBy)
|
|
.limit(perPage)
|
|
.offset(offset),
|
|
db.select({ count: sql<number>`count(*)` })
|
|
.from(domains)
|
|
.where(and(...conditions)),
|
|
]);
|
|
|
|
let totalItems = Number(countResult[0]?.count || 0);
|
|
|
|
// If user has no domains, auto-create a default "Personal" domain
|
|
if (totalItems === 0) {
|
|
const active = await resolveActiveDomain(user);
|
|
// Re-fetch to include the newly created domain
|
|
const [newItems, newCount] = await Promise.all([
|
|
db.select()
|
|
.from(domains)
|
|
.where(eq(domains.ownerId, user.id))
|
|
.orderBy(orderBy)
|
|
.limit(perPage)
|
|
.offset(offset),
|
|
db.select({ count: sql<number>`count(*)` })
|
|
.from(domains)
|
|
.where(eq(domains.ownerId, user.id)),
|
|
]);
|
|
return NextResponse.json({
|
|
items: newItems,
|
|
totalItems: Number(newCount[0]?.count || 0),
|
|
totalPages: Math.ceil(Number(newCount[0]?.count || 0) / perPage),
|
|
page,
|
|
perPage,
|
|
});
|
|
}
|
|
|
|
return NextResponse.json({
|
|
items,
|
|
totalItems,
|
|
totalPages: Math.ceil(totalItems / perPage),
|
|
page,
|
|
perPage,
|
|
});
|
|
});
|
|
|
|
// POST /api/domains — Create a domain
|
|
export const POST = withAuth(async (request: NextRequest, user) => {
|
|
try {
|
|
const body = await request.json();
|
|
const data = createDomainSchema.parse(body);
|
|
|
|
const [domain] = await db.insert(domains)
|
|
.values({
|
|
name: data.name,
|
|
slug: data.slug,
|
|
color: data.color || null,
|
|
icon: data.icon || null,
|
|
parentId: data.parentId || null,
|
|
ownerId: user.id,
|
|
})
|
|
.returning();
|
|
|
|
return NextResponse.json(domain, { status: 201 });
|
|
} catch (error) {
|
|
if (error instanceof z.ZodError) {
|
|
return createErrorResponse('VALIDATION_ERROR', 'Invalid input', 400, error.issues);
|
|
}
|
|
throw error;
|
|
}
|
|
});
|