feat: Phase 5 - Calendar + Dashboard + Search

Calendar:
- GET /api/domains/[domainId]/calendar/events?from=&to= — returns tasks, habits, projects, milestones
- PATCH /api/domains/[domainId]/tasks/[id]/schedule — drag-to-reschedule with activity feed
- Calendar UI with month/week/day views via react-big-calendar
- Drag-to-reschedule with SSE updates
- Filter by entity type and domain
- Keyboard shortcuts: t=today, m/w/d=view, ←/→=navigate
- Mobile: auto-switches to day view on small screens

Dashboard:
- GET/PUT /api/domains/[domainId]/dashboard — layout stored in domain custom_fields
- 8 per-widget data endpoints (today-tasks, habit-checklist, weekly-stats, project-progress, upcoming-calendar, recent-notes, activity-feed, quick-capture)
- react-grid-layout with responsive breakpoints (12/8/4 cols)
- Drag-to-reorder, resize, add/remove widgets
- Edit mode toggle, per-workspace layout persistence
- Widget error boundary

Search:
- tsvector columns + GIN indexes on tasks, notes, projects, habits, domains
- GET /api/search?q=&types=&domain= — ranked results with ts_headline snippets
- Dedicated search page with grouped results, filters, recent searches (localStorage)
- Empty state with hints

Schema:
- Added custom_fields jsonb column to domains table (migration 0002)
- Removed stale root app/ directory

Build: passes, typecheck: passes, tests: 18/18 wikilink-parser tests pass
This commit is contained in:
2026-07-29 07:32:47 -04:00
parent 40a26d2672
commit eba1d78fb9
39 changed files with 11525 additions and 768 deletions
@@ -0,0 +1,217 @@
// 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, tasks, habits, habitCompletions, projects, sections, domains } from '@project-e/db';
import { and, asc, between, eq, gte, isNull, lte, sql } from 'drizzle-orm';
type RouteContext = { params: Promise<{ domainId: string }> };
interface CalendarEvent {
id: string;
title: string;
start: string;
end: string;
type: 'task' | 'habit' | 'project' | 'milestone';
entityType: string;
entityId: string;
color: string;
domainId: string;
href: string;
priority?: string;
difficulty?: string;
status?: string;
}
// GET /api/domains/[domainId]/calendar/events?from=&to=
// Returns all events (tasks with due_date, habits scheduled for date range, project target dates)
// joined with domain for color/title
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 from = searchParams.get('from');
const to = searchParams.get('to');
const types = searchParams.get('types')?.split(',').filter(Boolean) || ['task', 'habit', 'project', 'milestone'];
if (!from || !to) {
return createErrorResponse('VALIDATION_ERROR', 'from and to query params are required (ISO dates)', 400);
}
const fromDate = new Date(from);
const toDate = new Date(to);
// Get domain for color
const [domain] = await db.select({ color: domains.color, name: domains.name })
.from(domains)
.where(eq(domains.id, domainId))
.limit(1);
const domainColor = domain?.color || '#3b82f6';
const events: CalendarEvent[] = [];
// 1. Tasks with due_date in range
if (types.includes('task')) {
const taskRows = await db.select()
.from(tasks)
.where(and(
eq(tasks.domainId, domainId),
isNull(tasks.deletedAt),
gte(tasks.dueDate, fromDate),
lte(tasks.dueDate, toDate),
))
.orderBy(asc(tasks.dueDate));
for (const task of taskRows) {
if (!task.dueDate) continue;
const color = task.priority === 'urgent' ? '#ef4444'
: task.priority === 'high' ? '#f97316'
: task.priority === 'medium' ? '#3b82f6'
: '#6b7280';
events.push({
id: `task-${task.id}`,
title: task.title,
start: task.dueDate.toISOString(),
end: task.dueDate.toISOString(),
type: 'task',
entityType: 'task',
entityId: task.id,
color,
domainId,
href: `/tasks/${task.id}`,
priority: task.priority,
status: task.status,
});
}
}
// 2. Habits — check if they have completions in range (scheduled habits)
if (types.includes('habit')) {
const habitRows = await db.select()
.from(habits)
.where(and(
eq(habits.domainId, domainId),
eq(habits.active, true),
isNull(habits.deletedAt),
));
for (const habit of habitRows) {
const color = habit.difficulty === 'hard' ? '#ef4444'
: habit.difficulty === 'medium' ? '#f97316'
: '#22c55e';
// Check if habit has completions in range
const completions = await db.select({ date: habitCompletions.date })
.from(habitCompletions)
.where(and(
eq(habitCompletions.habitId, habit.id),
gte(habitCompletions.date, fromDate),
lte(habitCompletions.date, toDate),
));
const completedDates = new Set(completions.map(c => c.date.toISOString().split('T')[0]));
// Generate events for each day in range (for daily habits)
// For weekly/custom, just show the habit as a recurring event
const current = new Date(fromDate);
while (current <= toDate) {
const dayOfWeek = current.getDay();
const skipDays = (habit.skipDays || []) as number[];
const dateStr = current.toISOString().split('T')[0];
if (!skipDays.includes(dayOfWeek)) {
const isCompleted = completedDates.has(dateStr);
events.push({
id: `habit-${habit.id}-${dateStr}`,
title: `${isCompleted ? '✅ ' : '○ '}${habit.name}`,
start: current.toISOString(),
end: current.toISOString(),
type: 'habit',
entityType: 'habit',
entityId: habit.id,
color,
domainId,
href: '/habits',
difficulty: habit.difficulty,
status: isCompleted ? 'completed' : 'pending',
});
}
current.setDate(current.getDate() + 1);
}
}
}
// 3. Projects with target_date in range
if (types.includes('project')) {
const projectRows = await db.select()
.from(projects)
.where(and(
eq(projects.domainId, domainId),
isNull(projects.deletedAt),
gte(projects.targetDate, fromDate),
lte(projects.targetDate, toDate),
))
.orderBy(asc(projects.targetDate));
for (const project of projectRows) {
if (!project.targetDate) continue;
events.push({
id: `project-${project.id}`,
title: `📁 ${project.name}`,
start: project.targetDate.toISOString(),
end: project.targetDate.toISOString(),
type: 'project',
entityType: 'project',
entityId: project.id,
color: project.color || '#8b5cf6',
domainId,
href: `/projects/${project.id}`,
status: project.status,
});
}
}
// 4. Sections (milestones) with target_date in range
if (types.includes('milestone')) {
const milestoneRows = await db.select({
id: sections.id,
name: sections.name,
targetDate: sections.targetDate,
projectId: sections.projectId,
status: sections.status,
kind: sections.kind,
})
.from(sections)
.innerJoin(projects, eq(sections.projectId, projects.id))
.where(and(
eq(projects.domainId, domainId),
eq(sections.kind, 'milestone'),
gte(sections.targetDate, fromDate),
lte(sections.targetDate, toDate),
))
.orderBy(asc(sections.targetDate));
for (const milestone of milestoneRows) {
if (!milestone.targetDate) continue;
events.push({
id: `milestone-${milestone.id}`,
title: `🏁 ${milestone.name}`,
start: milestone.targetDate.toISOString(),
end: milestone.targetDate.toISOString(),
type: 'milestone',
entityType: 'section',
entityId: milestone.id,
color: '#f59e0b',
domainId,
href: `/projects/${milestone.projectId}`,
status: milestone.status,
});
}
}
return NextResponse.json({ events });
});
@@ -0,0 +1,73 @@
// 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, domains } from '@project-e/db';
import { eq } from 'drizzle-orm';
import { z } from 'zod';
type RouteContext = { params: Promise<{ domainId: string }> };
const layoutItemSchema = z.object({
widgetId: z.string(),
order: z.number().int(),
enabled: z.boolean(),
config: z.record(z.string(), z.unknown()).optional(),
});
const updateLayoutSchema = z.object({
layout: z.array(layoutItemSchema),
});
// PUT /api/domains/[domainId]/dashboard/layout — Update dashboard layout
export const PUT = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
const { domainId } = await context!.params;
await requireWorkspaceAccess(domainId);
try {
const body = await request.json();
const data = updateLayoutSchema.parse(body);
const [domain] = await db.select({ id: domains.id, customFields: domains.customFields })
.from(domains)
.where(eq(domains.id, domainId))
.limit(1);
if (!domain) {
return createErrorResponse('NOT_FOUND', 'Domain not found', 404);
}
// Store layout in domain's custom_fields
const existingFields = (domain.customFields as Record<string, unknown>) || {};
await db.update(domains)
.set({
customFields: { ...existingFields, dashboard_layout: data.layout },
updatedAt: new Date(),
})
.where(eq(domains.id, domainId));
await recordActivity({
actor: user.name,
action: 'updated',
entityType: 'domain',
entityId: domainId,
changes: { dashboardLayout: data.layout },
workspaceId: domainId,
});
return NextResponse.json({ layout: data.layout });
} 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('[dashboard/layout PUT] error:', error);
return createErrorResponse('INTERNAL_ERROR', 'Failed to update dashboard layout', 500);
}
});
@@ -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, domains } from '@project-e/db';
import { eq } from 'drizzle-orm';
import { z } from 'zod';
type RouteContext = { params: Promise<{ domainId: string }> };
const layoutItemSchema = z.object({
widgetId: z.string(),
order: z.number().int(),
enabled: z.boolean(),
config: z.record(z.string(), z.unknown()).optional(),
});
const updateLayoutSchema = z.object({
layout: z.array(layoutItemSchema),
});
// GET /api/domains/[domainId]/dashboard — Returns layout (widget order) + widget data
export const GET = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
const { domainId } = await context!.params;
await requireWorkspaceAccess(domainId);
// Verify domain exists
const [domain] = await db.select({ id: domains.id, name: domains.name, color: domains.color, customFields: domains.customFields })
.from(domains)
.where(eq(domains.id, domainId))
.limit(1);
if (!domain) {
return createErrorResponse('NOT_FOUND', 'Domain not found', 404);
}
// Dashboard layout is stored in the domain's custom_fields as jsonb
// We use a convention: dashboard_layout key in custom_fields
const storedLayout = (domain.customFields as Record<string, unknown>)?.dashboard_layout as Array<{ widgetId: string; order: number; enabled: boolean; config?: Record<string, unknown> }> | undefined;
const defaultLayout = [
{ widgetId: 'today-tasks', order: 0, enabled: true },
{ widgetId: 'habit-checklist', order: 1, enabled: true },
{ widgetId: 'weekly-stats', order: 2, enabled: true },
{ widgetId: 'project-progress', order: 3, enabled: true },
{ widgetId: 'upcoming-calendar', order: 4, enabled: true },
{ widgetId: 'recent-notes', order: 5, enabled: true },
{ widgetId: 'activity-feed', order: 6, enabled: true },
{ widgetId: 'quick-capture', order: 7, enabled: true },
];
return NextResponse.json({ layout: storedLayout || defaultLayout });
});
// PUT /api/domains/[domainId]/dashboard/layout — Update dashboard layout
export const PUT = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
const { domainId } = await context!.params;
await requireWorkspaceAccess(domainId);
try {
const body = await request.json();
const data = updateLayoutSchema.parse(body);
const [domain] = await db.select({ id: domains.id, customFields: domains.customFields })
.from(domains)
.where(eq(domains.id, domainId))
.limit(1);
if (!domain) {
return createErrorResponse('NOT_FOUND', 'Domain not found', 404);
}
// Store layout in domain's custom_fields
const existingFields = (domain.customFields as Record<string, unknown>) || {};
await db.update(domains)
.set({
customFields: { ...existingFields, dashboard_layout: data.layout },
updatedAt: new Date(),
})
.where(eq(domains.id, domainId));
await recordActivity({
actor: user.name,
action: 'updated',
entityType: 'domain',
entityId: domainId,
changes: { dashboardLayout: data.layout },
workspaceId: domainId,
});
return NextResponse.json({ layout: data.layout });
} 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('[dashboard PUT] error:', error);
return createErrorResponse('INTERNAL_ERROR', 'Failed to update dashboard layout', 500);
}
});
@@ -0,0 +1,25 @@
// 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 } from '@/lib/auth';
import { db, activityFeed } from '@project-e/db';
import { and, desc, eq } from 'drizzle-orm';
type RouteContext = { params: Promise<{ domainId: string }> };
// GET /api/domains/[domainId]/dashboard/widgets/activity-feed
export const GET = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
const { domainId } = await context!.params;
await requireWorkspaceAccess(domainId);
const items = await db.select()
.from(activityFeed)
.where(eq(activityFeed.workspaceId, domainId))
.orderBy(desc(activityFeed.createdAt))
.limit(20);
return NextResponse.json({ items });
});
@@ -0,0 +1,50 @@
// 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 } from '@/lib/auth';
import { db, habits, habitCompletions } from '@project-e/db';
import { and, eq, gte, isNull, lte, sql } from 'drizzle-orm';
type RouteContext = { params: Promise<{ domainId: string }> };
// GET /api/domains/[domainId]/dashboard/widgets/habit-checklist
export const GET = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
const { domainId } = await context!.params;
await requireWorkspaceAccess(domainId);
const today = new Date();
today.setHours(0, 0, 0, 0);
const tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);
const activeHabits = await db.select()
.from(habits)
.where(and(
eq(habits.domainId, domainId),
eq(habits.active, true),
isNull(habits.deletedAt),
));
// Check which habits are completed today
const items = [];
for (const habit of activeHabits) {
const [completion] = await db.select({ count: sql<number>`count(*)` })
.from(habitCompletions)
.where(and(
eq(habitCompletions.habitId, habit.id),
gte(habitCompletions.date, today),
lte(habitCompletions.date, tomorrow),
));
const completed = Number(completion?.count || 0) > 0;
items.push({
...habit,
completedToday: completed,
});
}
return NextResponse.json({ items });
});
@@ -0,0 +1,54 @@
// 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 } from '@/lib/auth';
import { db, projects, tasks } from '@project-e/db';
import { and, eq, inArray, isNull, sql } from 'drizzle-orm';
type RouteContext = { params: Promise<{ domainId: string }> };
// GET /api/domains/[domainId]/dashboard/widgets/project-progress
export const GET = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
const { domainId } = await context!.params;
await requireWorkspaceAccess(domainId);
const activeProjects = await db.select()
.from(projects)
.where(and(
eq(projects.domainId, domainId),
inArray(projects.status, ['active', 'paused']),
isNull(projects.deletedAt),
));
// Compute progress for each project
const items = [];
for (const project of activeProjects) {
const [totalResult] = await db.select({ count: sql<number>`count(*)` })
.from(tasks)
.where(and(eq(tasks.projectId, project.id), isNull(tasks.deletedAt)));
const [completedResult] = await db.select({ count: sql<number>`count(*)` })
.from(tasks)
.where(and(eq(tasks.projectId, project.id), eq(tasks.status, 'done'), isNull(tasks.deletedAt)));
const total = Number(totalResult?.count || 0);
const completed = Number(completedResult?.count || 0);
const progress = total > 0 ? Math.round((completed / total) * 100) : 0;
items.push({
id: project.id,
name: project.name,
status: project.status,
color: project.color,
targetDate: project.targetDate,
taskCount: total,
completedCount: completed,
progress,
});
}
return NextResponse.json({ items });
});
@@ -0,0 +1,34 @@
// 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 } from '@/lib/auth';
import { db, notes } from '@project-e/db';
import { and, desc, eq, isNull } from 'drizzle-orm';
type RouteContext = { params: Promise<{ domainId: string }> };
// GET /api/domains/[domainId]/dashboard/widgets/recent-notes
export const GET = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
const { domainId } = await context!.params;
await requireWorkspaceAccess(domainId);
const items = await db.select({
id: notes.id,
title: notes.title,
updatedAt: notes.updatedAt,
isPinned: notes.isPinned,
})
.from(notes)
.where(and(
eq(notes.domainId, domainId),
eq(notes.isArchived, false),
isNull(notes.deletedAt),
))
.orderBy(desc(notes.updatedAt))
.limit(5);
return NextResponse.json({ items });
});
@@ -0,0 +1,35 @@
// 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 } from '@/lib/auth';
import { db, tasks, habits, habitCompletions, projects, notes, activityFeed, domains } from '@project-e/db';
import { and, asc, desc, eq, gte, inArray, isNull, lte, sql } from 'drizzle-orm';
type RouteContext = { params: Promise<{ domainId: string }> };
// GET /api/domains/[domainId]/dashboard/widgets/today-tasks
export const GET = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
const { domainId } = await context!.params;
await requireWorkspaceAccess(domainId);
const today = new Date();
today.setHours(0, 0, 0, 0);
const tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);
const items = await db.select()
.from(tasks)
.where(and(
eq(tasks.domainId, domainId),
isNull(tasks.deletedAt),
gte(tasks.dueDate, today),
lte(tasks.dueDate, tomorrow),
))
.orderBy(asc(tasks.priority))
.limit(10);
return NextResponse.json({ items });
});
@@ -0,0 +1,63 @@
// 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 } from '@/lib/auth';
import { db, tasks, projects, sections } from '@project-e/db';
import { and, asc, eq, gte, isNull, lte, sql } from 'drizzle-orm';
type RouteContext = { params: Promise<{ domainId: string }> };
// GET /api/domains/[domainId]/dashboard/widgets/upcoming-calendar
export const GET = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
const { domainId } = await context!.params;
await requireWorkspaceAccess(domainId);
const today = new Date();
today.setHours(0, 0, 0, 0);
const nextWeek = new Date(today);
nextWeek.setDate(nextWeek.getDate() + 7);
// Tasks due in next 7 days
const upcomingTasks = await db.select({
id: tasks.id,
title: tasks.title,
dueDate: tasks.dueDate,
priority: tasks.priority,
status: tasks.status,
})
.from(tasks)
.where(and(
eq(tasks.domainId, domainId),
isNull(tasks.deletedAt),
gte(tasks.dueDate, today),
lte(tasks.dueDate, nextWeek),
))
.orderBy(asc(tasks.dueDate))
.limit(10);
// Projects with target dates in next 7 days
const upcomingProjects = await db.select({
id: projects.id,
name: projects.name,
targetDate: projects.targetDate,
status: projects.status,
color: projects.color,
})
.from(projects)
.where(and(
eq(projects.domainId, domainId),
isNull(projects.deletedAt),
gte(projects.targetDate, today),
lte(projects.targetDate, nextWeek),
))
.orderBy(asc(projects.targetDate))
.limit(5);
return NextResponse.json({
tasks: upcomingTasks,
projects: upcomingProjects,
});
});
@@ -0,0 +1,66 @@
// 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 } from '@/lib/auth';
import { db, tasks, habits, habitCompletions } from '@project-e/db';
import { and, eq, gte, isNull, lte, sql } from 'drizzle-orm';
type RouteContext = { params: Promise<{ domainId: string }> };
// GET /api/domains/[domainId]/dashboard/widgets/weekly-stats
export const GET = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
const { domainId } = await context!.params;
await requireWorkspaceAccess(domainId);
const now = new Date();
const weekStart = new Date(now);
weekStart.setDate(weekStart.getDate() - weekStart.getDay());
weekStart.setHours(0, 0, 0, 0);
const weekEnd = new Date(weekStart);
weekEnd.setDate(weekEnd.getDate() + 7);
// Task completions this week
const [taskCompletions] = await db.select({ count: sql<number>`count(*)` })
.from(tasks)
.where(and(
eq(tasks.domainId, domainId),
eq(tasks.status, 'done'),
gte(tasks.completedAt, weekStart),
lte(tasks.completedAt, weekEnd),
isNull(tasks.deletedAt),
));
// Habit completions this week
const [habitCompletionsCount] = await db.select({ count: sql<number>`count(*)` })
.from(habitCompletions)
.innerJoin(habits, eq(habitCompletions.habitId, habits.id))
.where(and(
eq(habits.domainId, domainId),
gte(habitCompletions.date, weekStart),
lte(habitCompletions.date, weekEnd),
isNull(habits.deletedAt),
));
// Streak counts
const activeHabits = await db.select({ id: habits.id, streakCount: habits.streakCount, bestStreak: habits.bestStreak })
.from(habits)
.where(and(
eq(habits.domainId, domainId),
eq(habits.active, true),
isNull(habits.deletedAt),
));
const totalStreak = activeHabits.reduce((sum, h) => sum + (h.streakCount || 0), 0);
const bestStreak = Math.max(...activeHabits.map(h => h.bestStreak || 0), 0);
return NextResponse.json({
taskCompletions: Number(taskCompletions?.count || 0),
habitCompletions: Number(habitCompletionsCount?.count || 0),
totalStreak,
bestStreak,
activeHabits: activeHabits.length,
});
});
@@ -0,0 +1,67 @@
// 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, tasks } from '@project-e/db';
import { and, eq, isNull } from 'drizzle-orm';
import { z } from 'zod';
const scheduleSchema = z.object({
dueDate: z.string().datetime().nullable(),
});
type RouteContext = { params: Promise<{ domainId: string; id: string }> };
// PATCH /api/domains/[domainId]/tasks/[id]/schedule — Reschedule a task via drag
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 = scheduleSchema.parse(body);
// Verify task exists
const [existing] = await db.select()
.from(tasks)
.where(and(eq(tasks.id, id), eq(tasks.domainId, domainId), isNull(tasks.deletedAt)))
.limit(1);
if (!existing) {
return createErrorResponse('NOT_FOUND', 'Task not found', 404);
}
const [updated] = await db.update(tasks)
.set({
dueDate: data.dueDate ? new Date(data.dueDate) : null,
updatedAt: new Date(),
})
.where(eq(tasks.id, id))
.returning();
// Record activity
await recordActivity({
actor: user.name,
action: 'updated',
entityType: 'task',
entityId: id,
changes: { dueDate: data.dueDate, previousDueDate: existing.dueDate?.toISOString() || null },
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('[schedule PATCH] error:', error);
return createErrorResponse('INTERNAL_ERROR', 'Failed to reschedule task', 500);
}
});
+28 -62
View File
@@ -4,73 +4,39 @@
// See AGENTS.md for full rules.
import { NextRequest, NextResponse } from 'next/server';
import { withAuth } from '@/lib/auth';
import { createPocketBaseClient } from '@/lib/pocketbase';
import { withAuth, createErrorResponse } from '@/lib/auth';
import { searchEntities } from '@/lib/search-service';
// GET /api/search — Cross-entity full-text search
//
// Implementation note: the underlying data layer (`lib/database.ts`) uses a
// JavaScript filter parser that only supports `=, !=, <=, >=, <, >` — it does
// NOT understand PocketBase's `~` (contains) or `||` (or) operators. To make
// search actually return results we fetch each collection's full list and
// filter in-process with a case-insensitive substring match on the searchable
// fields. This is fine at the current data scale and avoids the silent
// zero-result bug.
export const GET = withAuth(async (request: NextRequest, _user) => {
// GET /api/search?q=&type=&domain=&limit=&offset=
// Full-text search across all entity types using PostgreSQL tsvector/tsquery
export const GET = withAuth(async (request: NextRequest, user) => {
const { searchParams } = new URL(request.url);
const query = (searchParams.get('q') || '').trim();
const types = (
searchParams.get('types')?.split(',') || ['tasks', 'habits', 'projects', 'notes', 'reports']
).filter((t) =>
['tasks', 'habits', 'projects', 'notes', 'reports'].includes(t)
);
const limit = Math.max(1, Math.min(50, parseInt(searchParams.get('limit') || '10')));
const q = (searchParams.get('q') || '').trim();
const types = searchParams.get('types')?.split(',').filter(Boolean) || ['task', 'note', 'project', 'habit', 'domain'];
const domain = searchParams.get('domain') || undefined;
const limit = Math.max(1, Math.min(50, parseInt(searchParams.get('limit') || '20')));
const offset = Math.max(0, parseInt(searchParams.get('offset') || '0'));
if (!query) {
return NextResponse.json({ results: [] });
if (!q) {
return NextResponse.json({ results: [], totalCount: 0 });
}
const needle = query.toLowerCase();
const pb = createPocketBaseClient();
const results: Array<{ type: string; items: unknown[] }> = [];
try {
const { results, totalCount } = await searchEntities({
query: q,
types,
domainId: domain,
limit,
offset,
});
type Searchable = Record<string, unknown> & { id: string };
const matches = (record: Searchable, fields: string[]): boolean => {
for (const f of fields) {
const value = record[f];
if (typeof value === 'string' && value.toLowerCase().includes(needle)) {
return true;
}
}
return false;
};
const searchableFields: Record<string, string[]> = {
tasks: ['title', 'description'],
habits: ['name', 'description'],
projects: ['name', 'description'],
notes: ['title', 'content'],
reports: ['title', 'content'],
};
for (const type of types) {
try {
const items = (await pb.collection(type).getFullList()) as Searchable[];
const filtered = items
.filter((record) => matches(record, searchableFields[type] || []))
.slice(0, limit)
.map((record) => ({ id: record.id, title: getTitle(record, type) }));
results.push({ type, items: filtered });
} catch {
// Skip collections that fail (e.g. missing or inaccessible)
}
return NextResponse.json({
results,
totalCount,
query: q,
});
} catch (error) {
console.error('[search GET] error:', error);
return createErrorResponse('INTERNAL_ERROR', 'Search failed', 500);
}
return NextResponse.json({ results });
});
function getTitle(record: Record<string, unknown>, type: string): string {
const title = record.title ?? record.name;
if (typeof title === 'string' && title.length > 0) return title;
return `Untitled ${type.slice(0, -1)}`;
}