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:
2026-07-29 06:37:37 -04:00
parent 1fcd12fc14
commit 064a46f97d
23 changed files with 3633 additions and 523 deletions
@@ -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);
}
});