feat: Phase 3 - Habits + Projects CRUD API, frontend, completions, sections
Habits REST API: - GET/POST /api/domains/[domainId]/habits (list with filters, create) - GET/PATCH/DELETE /api/domains/[domainId]/habits/[id] (detail, update, soft delete) - POST /api/domains/[domainId]/habits/[id]/complete (completion + streak calc) - GET /api/domains/[domainId]/habits/[id]/completions (list with date range) - POST/DELETE /api/domains/[domainId]/habits/[id]/tags Projects REST API: - GET/POST /api/domains/[domainId]/projects (list with task counts, create) - GET/PATCH/DELETE /api/domains/[domainId]/projects/[id] (detail with sections/tasks, update, soft delete) Sections REST API: - GET/POST /api/domains/[domainId]/projects/[projectId]/sections (list, create) - GET/PATCH/DELETE /api/domains/[domainId]/projects/[projectId]/sections/[id] Frontend: - Habits page: checklist view, difficulty badges, streak display, filter - Habit create dialog: name, description, frequency, difficulty, goal, unit, reminder, mood toggle - Habit completion dialog: value, mood (1-5 emoji), notes - Calendar heatmap: 365-day grid, color by value, hover tooltip - Projects page: grid of cards with progress bars, status badges, tags - Project detail page: sections board, drag tasks between sections - Project create dialog: name, description, status, color picker, target date - Section dialog: name, kind (section/milestone), status, target date Keyboard shortcuts: c h (new habit), c p (new project), c s (new section) All write routes follow AGENTS.md contract (Drizzle + recordActivity + pg_notify). Build, typecheck, and 15 new tests pass.
This commit is contained in:
@@ -0,0 +1,138 @@
|
||||
// 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, requireWorkspaceAccess, createErrorResponse, ApiError } from '@/lib/auth';
|
||||
import { recordActivity } from '@/lib/activity';
|
||||
import { db, habits, habitCompletions, sql } from '@project-e/db';
|
||||
import { and, eq, isNull, gte, desc, count } from 'drizzle-orm';
|
||||
import { z } from 'zod';
|
||||
|
||||
const completeHabitSchema = z.object({
|
||||
value: z.number().int().positive().optional().default(1),
|
||||
mood: z.number().int().min(1).max(5).optional().nullable(),
|
||||
notes: z.string().optional().nullable(),
|
||||
});
|
||||
|
||||
type RouteContext = { params: Promise<{ domainId: string; id: string }> };
|
||||
|
||||
/**
|
||||
* Calculate the current streak for a habit.
|
||||
* Streak = consecutive days with at least one completion, going backwards from today.
|
||||
* Skip days (e.g. weekends) are excluded from the streak count.
|
||||
*/
|
||||
async function calculateStreak(habitId: string, skipDays: number[]): Promise<number> {
|
||||
// Get all completion dates for this habit, ordered desc
|
||||
const completions = await db.select({ date: habitCompletions.date })
|
||||
.from(habitCompletions)
|
||||
.where(eq(habitCompletions.habitId, habitId))
|
||||
.orderBy(desc(habitCompletions.date));
|
||||
|
||||
if (completions.length === 0) return 0;
|
||||
|
||||
const completionDates = new Set(
|
||||
completions.map(c => c.date.toISOString().split('T')[0])
|
||||
);
|
||||
|
||||
let streak = 0;
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
const checkDate = new Date(today);
|
||||
|
||||
// Check up to 365 days back
|
||||
for (let i = 0; i < 365; i++) {
|
||||
const dateStr = checkDate.toISOString().split('T')[0];
|
||||
const dayOfWeek = checkDate.getDay(); // 0=Sun, 6=Sat
|
||||
|
||||
if (skipDays.includes(dayOfWeek)) {
|
||||
// Skip day — move on without breaking streak
|
||||
checkDate.setDate(checkDate.getDate() - 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (completionDates.has(dateStr)) {
|
||||
streak++;
|
||||
checkDate.setDate(checkDate.getDate() - 1);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return streak;
|
||||
}
|
||||
|
||||
// POST /api/domains/[domainId]/habits/[id]/complete — Complete a habit
|
||||
export const POST = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { domainId, id } = await context!.params;
|
||||
await requireWorkspaceAccess(domainId);
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const data = completeHabitSchema.parse(body);
|
||||
|
||||
// Verify habit exists
|
||||
const [habit] = await db.select()
|
||||
.from(habits)
|
||||
.where(and(eq(habits.id, id), eq(habits.domainId, domainId), isNull(habits.deletedAt)))
|
||||
.limit(1);
|
||||
|
||||
if (!habit) {
|
||||
return createErrorResponse('NOT_FOUND', 'Habit not found', 404);
|
||||
}
|
||||
|
||||
// Create completion
|
||||
const [completion] = await db.insert(habitCompletions).values({
|
||||
habitId: id,
|
||||
date: new Date(),
|
||||
value: data.value,
|
||||
mood: data.mood ?? null,
|
||||
notes: data.notes ?? null,
|
||||
}).returning();
|
||||
|
||||
// Recalculate streak
|
||||
const skipDays = habit.skipDays || [];
|
||||
const newStreak = await calculateStreak(id, skipDays);
|
||||
|
||||
// Update habit with new streak
|
||||
const updateData: Record<string, unknown> = {
|
||||
streakCount: newStreak,
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
// Update best streak if current is higher
|
||||
if (newStreak > (habit.bestStreak || 0)) {
|
||||
updateData.bestStreak = newStreak;
|
||||
}
|
||||
|
||||
await db.update(habits)
|
||||
.set(updateData)
|
||||
.where(eq(habits.id, id));
|
||||
|
||||
// Record activity
|
||||
await recordActivity({
|
||||
actor: user.name,
|
||||
action: 'completed',
|
||||
entityType: 'habit',
|
||||
entityId: id,
|
||||
changes: { value: data.value, mood: data.mood, streak: newStreak },
|
||||
workspaceId: domainId,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
completion,
|
||||
streakCount: newStreak,
|
||||
bestStreak: Math.max(newStreak, habit.bestStreak || 0),
|
||||
}, { status: 201 });
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return createErrorResponse('VALIDATION_ERROR', 'Invalid input', 400, error.issues);
|
||||
}
|
||||
if (error instanceof ApiError) {
|
||||
return createErrorResponse(error.code, error.message, error.status);
|
||||
}
|
||||
console.error('[habit complete POST] error:', error);
|
||||
return createErrorResponse('INTERNAL_ERROR', 'Failed to complete habit', 500);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
// 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, requireWorkspaceAccess, createErrorResponse } from '@/lib/auth';
|
||||
import { db, habits, habitCompletions } from '@project-e/db';
|
||||
import { and, asc, desc, eq, gte, isNull, lte } from 'drizzle-orm';
|
||||
|
||||
type RouteContext = { params: Promise<{ domainId: string; id: string }> };
|
||||
|
||||
// GET /api/domains/[domainId]/habits/[id]/completions — List completions with date range
|
||||
export const GET = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { domainId, id } = await context!.params;
|
||||
await requireWorkspaceAccess(domainId);
|
||||
|
||||
// Verify habit exists
|
||||
const [habit] = await db.select({ id: habits.id })
|
||||
.from(habits)
|
||||
.where(and(eq(habits.id, id), eq(habits.domainId, domainId), isNull(habits.deletedAt)))
|
||||
.limit(1);
|
||||
|
||||
if (!habit) {
|
||||
return createErrorResponse('NOT_FOUND', 'Habit not found', 404);
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const from = searchParams.get('from');
|
||||
const to = searchParams.get('to');
|
||||
const limit = Math.min(parseInt(searchParams.get('limit') || '365'), 1000);
|
||||
const offset = parseInt(searchParams.get('offset') || '0');
|
||||
const order = searchParams.get('order') || 'desc';
|
||||
|
||||
const conditions: any[] = [eq(habitCompletions.habitId, id)];
|
||||
|
||||
if (from) conditions.push(gte(habitCompletions.date, new Date(from)));
|
||||
if (to) conditions.push(lte(habitCompletions.date, new Date(to)));
|
||||
|
||||
const orderFn = order === 'asc' ? asc : desc;
|
||||
|
||||
const [items, countResult] = await Promise.all([
|
||||
db.select()
|
||||
.from(habitCompletions)
|
||||
.where(and(...conditions))
|
||||
.orderBy(orderFn(habitCompletions.date))
|
||||
.limit(limit)
|
||||
.offset(offset),
|
||||
db.select({ count: db.$count(habitCompletions) })
|
||||
.from(habitCompletions)
|
||||
.where(and(...conditions)),
|
||||
]);
|
||||
|
||||
return NextResponse.json({
|
||||
items,
|
||||
totalItems: Number(countResult[0]?.count || 0),
|
||||
limit,
|
||||
offset,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,160 @@
|
||||
// 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, requireWorkspaceAccess, createErrorResponse, ApiError } from '@/lib/auth';
|
||||
import { recordActivity } from '@/lib/activity';
|
||||
import { db, habits, habitCompletions, habitTags, tags as tagsTable } from '@project-e/db';
|
||||
import { and, asc, desc, eq, gte, inArray, isNull, lte, sql } from 'drizzle-orm';
|
||||
import { z } from 'zod';
|
||||
|
||||
const habitFrequencyEnum = z.enum(['daily', 'weekly', 'custom']);
|
||||
const habitDifficultyEnum = z.enum(['easy', 'medium', 'hard']);
|
||||
|
||||
const updateHabitSchema = z.object({
|
||||
name: z.string().min(1).optional(),
|
||||
description: z.string().optional().nullable(),
|
||||
frequency: habitFrequencyEnum.optional(),
|
||||
difficulty: habitDifficultyEnum.optional(),
|
||||
goalPerPeriod: z.number().int().positive().optional(),
|
||||
unit: z.string().optional().nullable(),
|
||||
reminderTime: z.string().optional().nullable(),
|
||||
skipDays: z.array(z.number().int().min(0).max(6)).optional(),
|
||||
moodTracking: z.boolean().optional(),
|
||||
active: z.boolean().optional(),
|
||||
});
|
||||
|
||||
type RouteContext = { params: Promise<{ domainId: string; id: string }> };
|
||||
|
||||
// GET /api/domains/[domainId]/habits/[id] — Get a single habit with streak + recent completions
|
||||
export const GET = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { domainId, id } = await context!.params;
|
||||
await requireWorkspaceAccess(domainId);
|
||||
|
||||
const [habit] = await db.select()
|
||||
.from(habits)
|
||||
.where(and(eq(habits.id, id), eq(habits.domainId, domainId), isNull(habits.deletedAt)))
|
||||
.limit(1);
|
||||
|
||||
if (!habit) {
|
||||
return createErrorResponse('NOT_FOUND', 'Habit not found', 404);
|
||||
}
|
||||
|
||||
// Fetch recent completions (last 30 days)
|
||||
const thirtyDaysAgo = new Date();
|
||||
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
|
||||
|
||||
const recentCompletions = await db.select()
|
||||
.from(habitCompletions)
|
||||
.where(and(
|
||||
eq(habitCompletions.habitId, id),
|
||||
gte(habitCompletions.date, thirtyDaysAgo),
|
||||
))
|
||||
.orderBy(desc(habitCompletions.date));
|
||||
|
||||
// Fetch tags
|
||||
const tagRows = await db.select({
|
||||
id: tagsTable.id,
|
||||
name: tagsTable.name,
|
||||
color: tagsTable.color,
|
||||
})
|
||||
.from(habitTags)
|
||||
.innerJoin(tagsTable, eq(habitTags.tagId, tagsTable.id))
|
||||
.where(eq(habitTags.habitId, id));
|
||||
|
||||
return NextResponse.json({
|
||||
...habit,
|
||||
recentCompletions,
|
||||
tags: tagRows,
|
||||
});
|
||||
});
|
||||
|
||||
// PATCH /api/domains/[domainId]/habits/[id] — Update a habit
|
||||
export const PATCH = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { domainId, id } = await context!.params;
|
||||
await requireWorkspaceAccess(domainId);
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const data = updateHabitSchema.parse(body);
|
||||
|
||||
const [existing] = await db.select()
|
||||
.from(habits)
|
||||
.where(and(eq(habits.id, id), eq(habits.domainId, domainId), isNull(habits.deletedAt)))
|
||||
.limit(1);
|
||||
|
||||
if (!existing) {
|
||||
return createErrorResponse('NOT_FOUND', 'Habit not found', 404);
|
||||
}
|
||||
|
||||
const updateValues: Record<string, unknown> = {};
|
||||
if (data.name !== undefined) updateValues.name = data.name;
|
||||
if (data.description !== undefined) updateValues.description = data.description;
|
||||
if (data.frequency !== undefined) updateValues.frequency = data.frequency;
|
||||
if (data.difficulty !== undefined) updateValues.difficulty = data.difficulty;
|
||||
if (data.goalPerPeriod !== undefined) updateValues.goalPerPeriod = data.goalPerPeriod;
|
||||
if (data.unit !== undefined) updateValues.unit = data.unit;
|
||||
if (data.reminderTime !== undefined) updateValues.reminderTime = data.reminderTime;
|
||||
if (data.skipDays !== undefined) updateValues.skipDays = data.skipDays;
|
||||
if (data.moodTracking !== undefined) updateValues.moodTracking = data.moodTracking;
|
||||
if (data.active !== undefined) updateValues.active = data.active;
|
||||
updateValues.updatedAt = new Date();
|
||||
|
||||
const [updated] = await db.update(habits)
|
||||
.set(updateValues)
|
||||
.where(eq(habits.id, id))
|
||||
.returning();
|
||||
|
||||
await recordActivity({
|
||||
actor: user.name,
|
||||
action: 'updated',
|
||||
entityType: 'habit',
|
||||
entityId: id,
|
||||
changes: { ...data, previousName: existing.name },
|
||||
workspaceId: domainId,
|
||||
});
|
||||
|
||||
return NextResponse.json(updated);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return createErrorResponse('VALIDATION_ERROR', 'Invalid input', 400, error.issues);
|
||||
}
|
||||
if (error instanceof ApiError) {
|
||||
return createErrorResponse(error.code, error.message, error.status);
|
||||
}
|
||||
console.error('[habits PATCH] error:', error);
|
||||
return createErrorResponse('INTERNAL_ERROR', 'Failed to update habit', 500);
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE /api/domains/[domainId]/habits/[id] — Soft delete a habit
|
||||
export const DELETE = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { domainId, id } = await context!.params;
|
||||
await requireWorkspaceAccess(domainId);
|
||||
|
||||
const [existing] = await db.select()
|
||||
.from(habits)
|
||||
.where(and(eq(habits.id, id), eq(habits.domainId, domainId), isNull(habits.deletedAt)))
|
||||
.limit(1);
|
||||
|
||||
if (!existing) {
|
||||
return createErrorResponse('NOT_FOUND', 'Habit not found', 404);
|
||||
}
|
||||
|
||||
await db.update(habits)
|
||||
.set({ deletedAt: new Date(), updatedAt: new Date() })
|
||||
.where(eq(habits.id, id));
|
||||
|
||||
await recordActivity({
|
||||
actor: user.name,
|
||||
action: 'deleted',
|
||||
entityType: 'habit',
|
||||
entityId: id,
|
||||
changes: { name: existing.name },
|
||||
workspaceId: domainId,
|
||||
});
|
||||
|
||||
return new NextResponse(null, { status: 204 });
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
// 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, requireWorkspaceAccess, createErrorResponse, ApiError } from '@/lib/auth';
|
||||
import { recordActivity } from '@/lib/activity';
|
||||
import { db, habits, habitTags, tags as tagsTable } from '@project-e/db';
|
||||
import { and, eq, isNull } from 'drizzle-orm';
|
||||
import { z } from 'zod';
|
||||
|
||||
const tagActionSchema = z.object({
|
||||
tagId: z.string().uuid(),
|
||||
});
|
||||
|
||||
type RouteContext = { params: Promise<{ domainId: string; id: string }> };
|
||||
|
||||
// POST /api/domains/[domainId]/habits/[id]/tags — Add a tag to a habit
|
||||
export const POST = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { domainId, id } = await context!.params;
|
||||
await requireWorkspaceAccess(domainId);
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const data = tagActionSchema.parse(body);
|
||||
|
||||
// Verify habit exists
|
||||
const [habit] = await db.select()
|
||||
.from(habits)
|
||||
.where(and(eq(habits.id, id), eq(habits.domainId, domainId), isNull(habits.deletedAt)))
|
||||
.limit(1);
|
||||
|
||||
if (!habit) {
|
||||
return createErrorResponse('NOT_FOUND', 'Habit not found', 404);
|
||||
}
|
||||
|
||||
// Verify tag exists
|
||||
const [tag] = await db.select()
|
||||
.from(tagsTable)
|
||||
.where(eq(tagsTable.id, data.tagId))
|
||||
.limit(1);
|
||||
|
||||
if (!tag) {
|
||||
return createErrorResponse('NOT_FOUND', 'Tag not found', 404);
|
||||
}
|
||||
|
||||
// Check if already tagged
|
||||
const [existing] = await db.select()
|
||||
.from(habitTags)
|
||||
.where(and(eq(habitTags.habitId, id), eq(habitTags.tagId, data.tagId)))
|
||||
.limit(1);
|
||||
|
||||
if (existing) {
|
||||
return createErrorResponse('CONFLICT', 'Tag already added to this habit', 409);
|
||||
}
|
||||
|
||||
await db.insert(habitTags).values({ habitId: id, tagId: data.tagId });
|
||||
|
||||
await recordActivity({
|
||||
actor: user.name,
|
||||
action: 'tag_added',
|
||||
entityType: 'habit',
|
||||
entityId: id,
|
||||
changes: { tagId: data.tagId, tagName: tag.name },
|
||||
workspaceId: domainId,
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true }, { status: 201 });
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return createErrorResponse('VALIDATION_ERROR', 'Invalid input', 400, error.issues);
|
||||
}
|
||||
if (error instanceof ApiError) {
|
||||
return createErrorResponse(error.code, error.message, error.status);
|
||||
}
|
||||
console.error('[habit tags POST] error:', error);
|
||||
return createErrorResponse('INTERNAL_ERROR', 'Failed to add tag', 500);
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE /api/domains/[domainId]/habits/[id]/tags — Remove a tag from a habit
|
||||
export const DELETE = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { domainId, id } = await context!.params;
|
||||
await requireWorkspaceAccess(domainId);
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const data = tagActionSchema.parse(body);
|
||||
|
||||
const [existing] = await db.select()
|
||||
.from(habitTags)
|
||||
.where(and(eq(habitTags.habitId, id), eq(habitTags.tagId, data.tagId)))
|
||||
.limit(1);
|
||||
|
||||
if (!existing) {
|
||||
return createErrorResponse('NOT_FOUND', 'Tag not found on this habit', 404);
|
||||
}
|
||||
|
||||
await db.delete(habitTags)
|
||||
.where(and(eq(habitTags.habitId, id), eq(habitTags.tagId, data.tagId)));
|
||||
|
||||
await recordActivity({
|
||||
actor: user.name,
|
||||
action: 'tag_removed',
|
||||
entityType: 'habit',
|
||||
entityId: id,
|
||||
changes: { tagId: data.tagId },
|
||||
workspaceId: domainId,
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return createErrorResponse('VALIDATION_ERROR', 'Invalid input', 400, error.issues);
|
||||
}
|
||||
if (error instanceof ApiError) {
|
||||
return createErrorResponse(error.code, error.message, error.status);
|
||||
}
|
||||
console.error('[habit tags DELETE] error:', error);
|
||||
return createErrorResponse('INTERNAL_ERROR', 'Failed to remove tag', 500);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,167 @@
|
||||
// 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, requireWorkspaceAccess, createErrorResponse, ApiError } from '@/lib/auth';
|
||||
import { recordActivity } from '@/lib/activity';
|
||||
import { db, habits, habitTags, tags as tagsTable } from '@project-e/db';
|
||||
import { and, asc, desc, eq, ilike, inArray, isNull, or, sql } from 'drizzle-orm';
|
||||
import { z } from 'zod';
|
||||
|
||||
const habitFrequencyEnum = z.enum(['daily', 'weekly', 'custom']);
|
||||
const habitDifficultyEnum = z.enum(['easy', 'medium', 'hard']);
|
||||
|
||||
const createHabitSchema = z.object({
|
||||
name: z.string().min(1, 'Name is required'),
|
||||
description: z.string().optional().nullable(),
|
||||
frequency: habitFrequencyEnum.optional().default('daily'),
|
||||
difficulty: habitDifficultyEnum.optional().default('medium'),
|
||||
goalPerPeriod: z.number().int().positive().optional().default(1),
|
||||
unit: z.string().optional().nullable(),
|
||||
reminderTime: z.string().optional().nullable(),
|
||||
skipDays: z.array(z.number().int().min(0).max(6)).optional().default([]),
|
||||
moodTracking: z.boolean().optional().default(false),
|
||||
active: z.boolean().optional().default(true),
|
||||
tagIds: z.array(z.string().uuid()).optional(),
|
||||
});
|
||||
|
||||
type RouteContext = { params: Promise<{ domainId: string }> };
|
||||
|
||||
// GET /api/domains/[domainId]/habits — List habits with filtering
|
||||
export const GET = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { domainId } = await context!.params;
|
||||
await requireWorkspaceAccess(domainId);
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const active = searchParams.get('active');
|
||||
const frequency = searchParams.get('frequency');
|
||||
const difficulty = searchParams.get('difficulty');
|
||||
const search = searchParams.get('search');
|
||||
const limit = Math.min(parseInt(searchParams.get('limit') || '50'), 200);
|
||||
const offset = parseInt(searchParams.get('offset') || '0');
|
||||
const sort = searchParams.get('sort') || 'name';
|
||||
const order = searchParams.get('order') || 'asc';
|
||||
|
||||
const conditions: any[] = [
|
||||
eq(habits.domainId, domainId),
|
||||
isNull(habits.deletedAt),
|
||||
];
|
||||
|
||||
if (active === 'true') conditions.push(eq(habits.active, true));
|
||||
else if (active === 'false') conditions.push(eq(habits.active, false));
|
||||
if (frequency) conditions.push(eq(habits.frequency, frequency as any));
|
||||
if (difficulty) conditions.push(eq(habits.difficulty, difficulty as any));
|
||||
if (search) conditions.push(ilike(habits.name, `%${search}%`));
|
||||
|
||||
const orderFn = order === 'desc' ? desc : asc;
|
||||
let orderColumn;
|
||||
switch (sort) {
|
||||
case 'frequency': orderColumn = orderFn(habits.frequency); break;
|
||||
case 'difficulty': orderColumn = orderFn(habits.difficulty); break;
|
||||
case 'streak_count': orderColumn = orderFn(habits.streakCount); break;
|
||||
case 'created_at': orderColumn = orderFn(habits.createdAt); break;
|
||||
case 'updated_at': orderColumn = orderFn(habits.updatedAt); break;
|
||||
default: orderColumn = orderFn(habits.name); break;
|
||||
}
|
||||
|
||||
const [items, countResult] = await Promise.all([
|
||||
db.select()
|
||||
.from(habits)
|
||||
.where(and(...conditions))
|
||||
.orderBy(orderColumn)
|
||||
.limit(limit)
|
||||
.offset(offset),
|
||||
db.select({ count: sql<number>`count(*)` })
|
||||
.from(habits)
|
||||
.where(and(...conditions)),
|
||||
]);
|
||||
|
||||
const totalItems = Number(countResult[0]?.count || 0);
|
||||
|
||||
// Fetch tags for all habits
|
||||
let habitTagMap = new Map<string, { id: string; name: string; color: string | null }[]>();
|
||||
if (items.length > 0) {
|
||||
const habitIds = items.map(h => h.id);
|
||||
const tagRows = await db.select({
|
||||
habitId: habitTags.habitId,
|
||||
id: tagsTable.id,
|
||||
name: tagsTable.name,
|
||||
color: tagsTable.color,
|
||||
})
|
||||
.from(habitTags)
|
||||
.innerJoin(tagsTable, eq(habitTags.tagId, tagsTable.id))
|
||||
.where(inArray(habitTags.habitId, habitIds));
|
||||
|
||||
for (const row of tagRows) {
|
||||
if (!habitTagMap.has(row.habitId)) habitTagMap.set(row.habitId, []);
|
||||
habitTagMap.get(row.habitId)!.push({ id: row.id, name: row.name, color: row.color });
|
||||
}
|
||||
}
|
||||
|
||||
const itemsWithTags = items.map(h => ({
|
||||
...h,
|
||||
tags: habitTagMap.get(h.id) || [],
|
||||
}));
|
||||
|
||||
return NextResponse.json({
|
||||
items: itemsWithTags,
|
||||
totalItems,
|
||||
limit,
|
||||
offset,
|
||||
});
|
||||
});
|
||||
|
||||
// POST /api/domains/[domainId]/habits — Create a habit
|
||||
export const POST = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { domainId } = await context!.params;
|
||||
await requireWorkspaceAccess(domainId);
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const data = createHabitSchema.parse(body);
|
||||
|
||||
const [habit] = await db.insert(habits).values({
|
||||
name: data.name,
|
||||
description: data.description ?? null,
|
||||
domainId,
|
||||
frequency: data.frequency,
|
||||
difficulty: data.difficulty,
|
||||
goalPerPeriod: data.goalPerPeriod,
|
||||
unit: data.unit ?? null,
|
||||
reminderTime: data.reminderTime ?? null,
|
||||
skipDays: data.skipDays,
|
||||
moodTracking: data.moodTracking,
|
||||
active: data.active,
|
||||
}).returning();
|
||||
|
||||
// Insert tags if provided
|
||||
if (data.tagIds && data.tagIds.length > 0) {
|
||||
await db.insert(habitTags).values(
|
||||
data.tagIds.map(tagId => ({ habitId: habit.id, tagId }))
|
||||
);
|
||||
}
|
||||
|
||||
// Record activity
|
||||
await recordActivity({
|
||||
actor: user.name,
|
||||
action: 'created',
|
||||
entityType: 'habit',
|
||||
entityId: habit.id,
|
||||
changes: { name: habit.name, frequency: habit.frequency, difficulty: habit.difficulty },
|
||||
workspaceId: domainId,
|
||||
});
|
||||
|
||||
return NextResponse.json(habit, { status: 201 });
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return createErrorResponse('VALIDATION_ERROR', 'Invalid input', 400, error.issues);
|
||||
}
|
||||
if (error instanceof ApiError) {
|
||||
return createErrorResponse(error.code, error.message, error.status);
|
||||
}
|
||||
console.error('[habits POST] error:', error);
|
||||
return createErrorResponse('INTERNAL_ERROR', 'Failed to create habit', 500);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,160 @@
|
||||
// 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, requireWorkspaceAccess, createErrorResponse, ApiError } from '@/lib/auth';
|
||||
import { recordActivity } from '@/lib/activity';
|
||||
import { db, projects, tasks, sections, projectTags, tags as tagsTable } from '@project-e/db';
|
||||
import { and, asc, eq, inArray, isNull, sql } from 'drizzle-orm';
|
||||
import { z } from 'zod';
|
||||
|
||||
const projectStatusEnum = z.enum(['active', 'paused', 'completed', 'archived']);
|
||||
|
||||
const updateProjectSchema = z.object({
|
||||
name: z.string().min(1).optional(),
|
||||
description: z.string().optional().nullable(),
|
||||
status: projectStatusEnum.optional(),
|
||||
color: z.string().optional().nullable(),
|
||||
icon: z.string().optional().nullable(),
|
||||
targetDate: z.string().datetime().optional().nullable(),
|
||||
});
|
||||
|
||||
type RouteContext = { params: Promise<{ domainId: string; id: string }> };
|
||||
|
||||
// GET /api/domains/[domainId]/projects/[id] — Get a single project with sections, task counts, progress
|
||||
export const GET = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { domainId, id } = await context!.params;
|
||||
await requireWorkspaceAccess(domainId);
|
||||
|
||||
const [project] = await db.select()
|
||||
.from(projects)
|
||||
.where(and(eq(projects.id, id), eq(projects.domainId, domainId), isNull(projects.deletedAt)))
|
||||
.limit(1);
|
||||
|
||||
if (!project) {
|
||||
return createErrorResponse('NOT_FOUND', 'Project not found', 404);
|
||||
}
|
||||
|
||||
// Fetch sections
|
||||
const projectSections = await db.select()
|
||||
.from(sections)
|
||||
.where(eq(sections.projectId, id))
|
||||
.orderBy(asc(sections.sortOrder));
|
||||
|
||||
// Fetch tasks grouped by section
|
||||
const projectTasks = await db.select()
|
||||
.from(tasks)
|
||||
.where(and(eq(tasks.projectId, id), isNull(tasks.deletedAt)))
|
||||
.orderBy(asc(tasks.order));
|
||||
|
||||
// Fetch tags
|
||||
const tagRows = await db.select({
|
||||
id: tagsTable.id,
|
||||
name: tagsTable.name,
|
||||
color: tagsTable.color,
|
||||
})
|
||||
.from(projectTags)
|
||||
.innerJoin(tagsTable, eq(projectTags.tagId, tagsTable.id))
|
||||
.where(eq(projectTags.projectId, id));
|
||||
|
||||
// Compute counts
|
||||
const totalTasks = projectTasks.length;
|
||||
const completedTasks = projectTasks.filter(t => t.status === 'done').length;
|
||||
const progress = totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0;
|
||||
|
||||
return NextResponse.json({
|
||||
...project,
|
||||
sections: projectSections,
|
||||
tasks: projectTasks,
|
||||
tags: tagRows,
|
||||
taskCount: totalTasks,
|
||||
completedCount: completedTasks,
|
||||
progress,
|
||||
});
|
||||
});
|
||||
|
||||
// PATCH /api/domains/[domainId]/projects/[id] — Update a project
|
||||
export const PATCH = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { domainId, id } = await context!.params;
|
||||
await requireWorkspaceAccess(domainId);
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const data = updateProjectSchema.parse(body);
|
||||
|
||||
const [existing] = await db.select()
|
||||
.from(projects)
|
||||
.where(and(eq(projects.id, id), eq(projects.domainId, domainId), isNull(projects.deletedAt)))
|
||||
.limit(1);
|
||||
|
||||
if (!existing) {
|
||||
return createErrorResponse('NOT_FOUND', 'Project not found', 404);
|
||||
}
|
||||
|
||||
const updateValues: Record<string, unknown> = {};
|
||||
if (data.name !== undefined) updateValues.name = data.name;
|
||||
if (data.description !== undefined) updateValues.description = data.description;
|
||||
if (data.status !== undefined) updateValues.status = data.status;
|
||||
if (data.color !== undefined) updateValues.color = data.color;
|
||||
if (data.icon !== undefined) updateValues.icon = data.icon;
|
||||
if (data.targetDate !== undefined) updateValues.targetDate = data.targetDate ? new Date(data.targetDate) : null;
|
||||
updateValues.updatedAt = new Date();
|
||||
|
||||
const [updated] = await db.update(projects)
|
||||
.set(updateValues)
|
||||
.where(eq(projects.id, id))
|
||||
.returning();
|
||||
|
||||
await recordActivity({
|
||||
actor: user.name,
|
||||
action: 'updated',
|
||||
entityType: 'project',
|
||||
entityId: id,
|
||||
changes: { ...data, previousName: existing.name },
|
||||
workspaceId: domainId,
|
||||
});
|
||||
|
||||
return NextResponse.json(updated);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return createErrorResponse('VALIDATION_ERROR', 'Invalid input', 400, error.issues);
|
||||
}
|
||||
if (error instanceof ApiError) {
|
||||
return createErrorResponse(error.code, error.message, error.status);
|
||||
}
|
||||
console.error('[projects PATCH] error:', error);
|
||||
return createErrorResponse('INTERNAL_ERROR', 'Failed to update project', 500);
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE /api/domains/[domainId]/projects/[id] — Soft delete a project
|
||||
export const DELETE = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { domainId, id } = await context!.params;
|
||||
await requireWorkspaceAccess(domainId);
|
||||
|
||||
const [existing] = await db.select()
|
||||
.from(projects)
|
||||
.where(and(eq(projects.id, id), eq(projects.domainId, domainId), isNull(projects.deletedAt)))
|
||||
.limit(1);
|
||||
|
||||
if (!existing) {
|
||||
return createErrorResponse('NOT_FOUND', 'Project not found', 404);
|
||||
}
|
||||
|
||||
await db.update(projects)
|
||||
.set({ deletedAt: new Date(), updatedAt: new Date() })
|
||||
.where(eq(projects.id, id));
|
||||
|
||||
await recordActivity({
|
||||
actor: user.name,
|
||||
action: 'deleted',
|
||||
entityType: 'project',
|
||||
entityId: id,
|
||||
changes: { name: existing.name },
|
||||
workspaceId: domainId,
|
||||
});
|
||||
|
||||
return new NextResponse(null, { status: 204 });
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
// 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, requireWorkspaceAccess, createErrorResponse, ApiError } from '@/lib/auth';
|
||||
import { recordActivity } from '@/lib/activity';
|
||||
import { db, projects, sections } from '@project-e/db';
|
||||
import { and, eq, isNull } from 'drizzle-orm';
|
||||
import { z } from 'zod';
|
||||
|
||||
const sectionKindEnum = z.enum(['section', 'milestone']);
|
||||
const sectionStatusEnum = z.enum(['planned', 'in_progress', 'complete']);
|
||||
|
||||
const updateSectionSchema = z.object({
|
||||
name: z.string().min(1).optional(),
|
||||
kind: sectionKindEnum.optional(),
|
||||
status: sectionStatusEnum.optional(),
|
||||
targetDate: z.string().datetime().optional().nullable(),
|
||||
sortOrder: z.number().int().optional(),
|
||||
});
|
||||
|
||||
type RouteContext = { params: Promise<{ domainId: string; projectId: string; id: string }> };
|
||||
|
||||
// GET /api/domains/[domainId]/projects/[projectId]/sections/[id] — Get a single section
|
||||
export const GET = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { domainId, projectId, id } = await context!.params;
|
||||
await requireWorkspaceAccess(domainId);
|
||||
|
||||
const [section] = await db.select()
|
||||
.from(sections)
|
||||
.where(and(eq(sections.id, id), eq(sections.projectId, projectId)))
|
||||
.limit(1);
|
||||
|
||||
if (!section) {
|
||||
return createErrorResponse('NOT_FOUND', 'Section not found', 404);
|
||||
}
|
||||
|
||||
return NextResponse.json(section);
|
||||
});
|
||||
|
||||
// PATCH /api/domains/[domainId]/projects/[projectId]/sections/[id] — Update a section
|
||||
export const PATCH = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { domainId, projectId, id } = await context!.params;
|
||||
await requireWorkspaceAccess(domainId);
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const data = updateSectionSchema.parse(body);
|
||||
|
||||
const [existing] = await db.select()
|
||||
.from(sections)
|
||||
.where(and(eq(sections.id, id), eq(sections.projectId, projectId)))
|
||||
.limit(1);
|
||||
|
||||
if (!existing) {
|
||||
return createErrorResponse('NOT_FOUND', 'Section not found', 404);
|
||||
}
|
||||
|
||||
const updateValues: Record<string, unknown> = {};
|
||||
if (data.name !== undefined) updateValues.name = data.name;
|
||||
if (data.kind !== undefined) updateValues.kind = data.kind;
|
||||
if (data.status !== undefined) updateValues.status = data.status;
|
||||
if (data.targetDate !== undefined) updateValues.targetDate = data.targetDate ? new Date(data.targetDate) : null;
|
||||
if (data.sortOrder !== undefined) updateValues.sortOrder = data.sortOrder;
|
||||
updateValues.updatedAt = new Date();
|
||||
|
||||
const [updated] = await db.update(sections)
|
||||
.set(updateValues)
|
||||
.where(eq(sections.id, id))
|
||||
.returning();
|
||||
|
||||
await recordActivity({
|
||||
actor: user.name,
|
||||
action: 'updated',
|
||||
entityType: 'section',
|
||||
entityId: id,
|
||||
changes: { ...data, previousName: existing.name, projectId },
|
||||
workspaceId: domainId,
|
||||
});
|
||||
|
||||
return NextResponse.json(updated);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return createErrorResponse('VALIDATION_ERROR', 'Invalid input', 400, error.issues);
|
||||
}
|
||||
if (error instanceof ApiError) {
|
||||
return createErrorResponse(error.code, error.message, error.status);
|
||||
}
|
||||
console.error('[sections PATCH] error:', error);
|
||||
return createErrorResponse('INTERNAL_ERROR', 'Failed to update section', 500);
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE /api/domains/[domainId]/projects/[projectId]/sections/[id] — Delete a section
|
||||
export const DELETE = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { domainId, projectId, id } = await context!.params;
|
||||
await requireWorkspaceAccess(domainId);
|
||||
|
||||
const [existing] = await db.select()
|
||||
.from(sections)
|
||||
.where(and(eq(sections.id, id), eq(sections.projectId, projectId)))
|
||||
.limit(1);
|
||||
|
||||
if (!existing) {
|
||||
return createErrorResponse('NOT_FOUND', 'Section not found', 404);
|
||||
}
|
||||
|
||||
await db.delete(sections)
|
||||
.where(eq(sections.id, id));
|
||||
|
||||
await recordActivity({
|
||||
actor: user.name,
|
||||
action: 'deleted',
|
||||
entityType: 'section',
|
||||
entityId: id,
|
||||
changes: { name: existing.name, projectId },
|
||||
workspaceId: domainId,
|
||||
});
|
||||
|
||||
return new NextResponse(null, { status: 204 });
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
// 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, requireWorkspaceAccess, createErrorResponse, ApiError } from '@/lib/auth';
|
||||
import { recordActivity } from '@/lib/activity';
|
||||
import { db, projects, sections } from '@project-e/db';
|
||||
import { and, asc, eq, isNull, sql } from 'drizzle-orm';
|
||||
import { z } from 'zod';
|
||||
|
||||
const sectionKindEnum = z.enum(['section', 'milestone']);
|
||||
const sectionStatusEnum = z.enum(['planned', 'in_progress', 'complete']);
|
||||
|
||||
const createSectionSchema = z.object({
|
||||
name: z.string().min(1, 'Name is required'),
|
||||
kind: sectionKindEnum.optional().default('section'),
|
||||
status: sectionStatusEnum.optional().default('planned'),
|
||||
targetDate: z.string().datetime().optional().nullable(),
|
||||
sortOrder: z.number().int().optional(),
|
||||
});
|
||||
|
||||
type RouteContext = { params: Promise<{ domainId: string; projectId: string }> };
|
||||
|
||||
// GET /api/domains/[domainId]/projects/[projectId]/sections — List sections for a project
|
||||
export const GET = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { domainId, projectId } = await context!.params;
|
||||
await requireWorkspaceAccess(domainId);
|
||||
|
||||
// Verify project exists and belongs to domain
|
||||
const [project] = await db.select({ id: projects.id })
|
||||
.from(projects)
|
||||
.where(and(eq(projects.id, projectId), eq(projects.domainId, domainId), isNull(projects.deletedAt)))
|
||||
.limit(1);
|
||||
|
||||
if (!project) {
|
||||
return createErrorResponse('NOT_FOUND', 'Project not found', 404);
|
||||
}
|
||||
|
||||
const items = await db.select()
|
||||
.from(sections)
|
||||
.where(eq(sections.projectId, projectId))
|
||||
.orderBy(asc(sections.sortOrder));
|
||||
|
||||
return NextResponse.json({ items });
|
||||
});
|
||||
|
||||
// POST /api/domains/[domainId]/projects/[projectId]/sections — Create a section
|
||||
export const POST = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { domainId, projectId } = await context!.params;
|
||||
await requireWorkspaceAccess(domainId);
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const data = createSectionSchema.parse(body);
|
||||
|
||||
// Verify project exists
|
||||
const [project] = await db.select({ id: projects.id, name: projects.name })
|
||||
.from(projects)
|
||||
.where(and(eq(projects.id, projectId), eq(projects.domainId, domainId), isNull(projects.deletedAt)))
|
||||
.limit(1);
|
||||
|
||||
if (!project) {
|
||||
return createErrorResponse('NOT_FOUND', 'Project not found', 404);
|
||||
}
|
||||
|
||||
// Determine sort order if not provided
|
||||
let sortOrder = data.sortOrder;
|
||||
if (sortOrder === undefined) {
|
||||
const [maxOrder] = await db.select({ max: sql<number>`COALESCE(MAX(sort_order), -1)` })
|
||||
.from(sections)
|
||||
.where(eq(sections.projectId, projectId));
|
||||
sortOrder = Number(maxOrder?.max || -1) + 1;
|
||||
}
|
||||
|
||||
const [section] = await db.insert(sections).values({
|
||||
name: data.name,
|
||||
projectId,
|
||||
kind: data.kind,
|
||||
status: data.status,
|
||||
targetDate: data.targetDate ? new Date(data.targetDate) : null,
|
||||
sortOrder,
|
||||
}).returning();
|
||||
|
||||
await recordActivity({
|
||||
actor: user.name,
|
||||
action: 'created',
|
||||
entityType: 'section',
|
||||
entityId: section.id,
|
||||
changes: { name: section.name, projectId, projectName: project.name, kind: section.kind },
|
||||
workspaceId: domainId,
|
||||
});
|
||||
|
||||
return NextResponse.json(section, { status: 201 });
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return createErrorResponse('VALIDATION_ERROR', 'Invalid input', 400, error.issues);
|
||||
}
|
||||
if (error instanceof ApiError) {
|
||||
return createErrorResponse(error.code, error.message, error.status);
|
||||
}
|
||||
console.error('[sections POST] error:', error);
|
||||
return createErrorResponse('INTERNAL_ERROR', 'Failed to create section', 500);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,181 @@
|
||||
// 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, requireWorkspaceAccess, createErrorResponse, ApiError } from '@/lib/auth';
|
||||
import { recordActivity } from '@/lib/activity';
|
||||
import { db, projects, tasks, sections, projectTags, tags as tagsTable } from '@project-e/db';
|
||||
import { and, asc, desc, eq, ilike, inArray, isNull, sql } from 'drizzle-orm';
|
||||
import { z } from 'zod';
|
||||
|
||||
const projectStatusEnum = z.enum(['active', 'paused', 'completed', 'archived']);
|
||||
|
||||
const createProjectSchema = z.object({
|
||||
name: z.string().min(1, 'Name is required'),
|
||||
description: z.string().optional().nullable(),
|
||||
status: projectStatusEnum.optional().default('active'),
|
||||
color: z.string().optional().nullable(),
|
||||
icon: z.string().optional().nullable(),
|
||||
targetDate: z.string().datetime().optional().nullable(),
|
||||
tagIds: z.array(z.string().uuid()).optional(),
|
||||
});
|
||||
|
||||
type RouteContext = { params: Promise<{ domainId: string }> };
|
||||
|
||||
// GET /api/domains/[domainId]/projects — List projects with filtering
|
||||
export const GET = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { domainId } = await context!.params;
|
||||
await requireWorkspaceAccess(domainId);
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const status = searchParams.get('status');
|
||||
const search = searchParams.get('search');
|
||||
const limit = Math.min(parseInt(searchParams.get('limit') || '50'), 200);
|
||||
const offset = parseInt(searchParams.get('offset') || '0');
|
||||
const sort = searchParams.get('sort') || 'name';
|
||||
const order = searchParams.get('order') || 'asc';
|
||||
|
||||
const conditions: any[] = [
|
||||
eq(projects.domainId, domainId),
|
||||
isNull(projects.deletedAt),
|
||||
];
|
||||
|
||||
if (status) {
|
||||
const statuses = status.split(',');
|
||||
conditions.push(inArray(projects.status, statuses as any));
|
||||
}
|
||||
if (search) conditions.push(ilike(projects.name, `%${search}%`));
|
||||
|
||||
const orderFn = order === 'desc' ? desc : asc;
|
||||
let orderColumn;
|
||||
switch (sort) {
|
||||
case 'status': orderColumn = orderFn(projects.status); break;
|
||||
case 'target_date': orderColumn = orderFn(projects.targetDate); break;
|
||||
case 'created_at': orderColumn = orderFn(projects.createdAt); break;
|
||||
case 'updated_at': orderColumn = orderFn(projects.updatedAt); break;
|
||||
default: orderColumn = orderFn(projects.name); break;
|
||||
}
|
||||
|
||||
const [items, countResult] = await Promise.all([
|
||||
db.select()
|
||||
.from(projects)
|
||||
.where(and(...conditions))
|
||||
.orderBy(orderColumn)
|
||||
.limit(limit)
|
||||
.offset(offset),
|
||||
db.select({ count: sql<number>`count(*)` })
|
||||
.from(projects)
|
||||
.where(and(...conditions)),
|
||||
]);
|
||||
|
||||
const totalItems = Number(countResult[0]?.count || 0);
|
||||
|
||||
// Fetch task counts and tags for all projects
|
||||
let projectTagMap = new Map<string, { id: string; name: string; color: string | null }[]>();
|
||||
let taskCountMap = new Map<string, { total: number; completed: number }>();
|
||||
|
||||
if (items.length > 0) {
|
||||
const projectIds = items.map(p => p.id);
|
||||
|
||||
// Tags
|
||||
const tagRows = await db.select({
|
||||
projectId: projectTags.projectId,
|
||||
id: tagsTable.id,
|
||||
name: tagsTable.name,
|
||||
color: tagsTable.color,
|
||||
})
|
||||
.from(projectTags)
|
||||
.innerJoin(tagsTable, eq(projectTags.tagId, tagsTable.id))
|
||||
.where(inArray(projectTags.projectId, projectIds));
|
||||
|
||||
for (const row of tagRows) {
|
||||
if (!projectTagMap.has(row.projectId)) projectTagMap.set(row.projectId, []);
|
||||
projectTagMap.get(row.projectId)!.push({ id: row.id, name: row.name, color: row.color });
|
||||
}
|
||||
|
||||
// Task counts
|
||||
for (const projectId of projectIds) {
|
||||
const [totalResult] = await db.select({ count: sql<number>`count(*)` })
|
||||
.from(tasks)
|
||||
.where(and(eq(tasks.projectId, projectId), isNull(tasks.deletedAt)));
|
||||
|
||||
const [completedResult] = await db.select({ count: sql<number>`count(*)` })
|
||||
.from(tasks)
|
||||
.where(and(eq(tasks.projectId, projectId), eq(tasks.status, 'done'), isNull(tasks.deletedAt)));
|
||||
|
||||
taskCountMap.set(projectId, {
|
||||
total: Number(totalResult?.count || 0),
|
||||
completed: Number(completedResult?.count || 0),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const itemsWithMeta = items.map(p => {
|
||||
const counts = taskCountMap.get(p.id) || { total: 0, completed: 0 };
|
||||
return {
|
||||
...p,
|
||||
tags: projectTagMap.get(p.id) || [],
|
||||
taskCount: counts.total,
|
||||
completedCount: counts.completed,
|
||||
progress: counts.total > 0 ? Math.round((counts.completed / counts.total) * 100) : 0,
|
||||
};
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
items: itemsWithMeta,
|
||||
totalItems,
|
||||
limit,
|
||||
offset,
|
||||
});
|
||||
});
|
||||
|
||||
// POST /api/domains/[domainId]/projects — Create a project
|
||||
export const POST = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { domainId } = await context!.params;
|
||||
await requireWorkspaceAccess(domainId);
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const data = createProjectSchema.parse(body);
|
||||
|
||||
const [project] = await db.insert(projects).values({
|
||||
name: data.name,
|
||||
description: data.description ?? null,
|
||||
status: data.status,
|
||||
domainId,
|
||||
color: data.color ?? null,
|
||||
icon: data.icon ?? null,
|
||||
targetDate: data.targetDate ? new Date(data.targetDate) : null,
|
||||
}).returning();
|
||||
|
||||
// Insert tags if provided
|
||||
if (data.tagIds && data.tagIds.length > 0) {
|
||||
await db.insert(projectTags).values(
|
||||
data.tagIds.map(tagId => ({ projectId: project.id, tagId }))
|
||||
);
|
||||
}
|
||||
|
||||
// Record activity
|
||||
await recordActivity({
|
||||
actor: user.name,
|
||||
action: 'created',
|
||||
entityType: 'project',
|
||||
entityId: project.id,
|
||||
changes: { name: project.name, status: project.status },
|
||||
workspaceId: domainId,
|
||||
});
|
||||
|
||||
return NextResponse.json(project, { status: 201 });
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return createErrorResponse('VALIDATION_ERROR', 'Invalid input', 400, error.issues);
|
||||
}
|
||||
if (error instanceof ApiError) {
|
||||
return createErrorResponse(error.code, error.message, error.status);
|
||||
}
|
||||
console.error('[projects POST] error:', error);
|
||||
return createErrorResponse('INTERNAL_ERROR', 'Failed to create project', 500);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user