Merge pull request 'Bug sweep fixes: 6 logic bugs across tasks/habits, graph/reports, worker (R2 pipeline test)' (#13) from integration/sweep-fixes into main
This commit is contained in:
@@ -4,32 +4,91 @@
|
||||
// See AGENTS.md for full rules.
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { withAuth, createErrorResponse } from '@/lib/auth';
|
||||
import { createPocketBaseClient } from '@/lib/pocketbase';
|
||||
import { updateHabitSchema } from '@project-e/shared';
|
||||
import { withAuth, createErrorResponse, requireWorkspaceAccess } from '@/lib/auth';
|
||||
import { recordActivity } from '@/lib/activity';
|
||||
import { db, habits, habitTags } from '@project-e/db';
|
||||
import { and, eq, isNull } 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, 'Name is required').optional(),
|
||||
description: z.string().nullable().optional(),
|
||||
domain: z.string().min(1, 'Domain is required').optional(),
|
||||
frequency: habitFrequencyEnum.optional(),
|
||||
difficulty: habitDifficultyEnum.optional(),
|
||||
goalPerPeriod: z.number().int().positive().optional(),
|
||||
active: z.boolean().optional(),
|
||||
tagIds: z.array(z.string().uuid()).optional(),
|
||||
});
|
||||
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
// GET /api/habits/[id] — Get a single habit
|
||||
export const GET = withAuth<RouteContext>(async (request: NextRequest, _user, context) => {
|
||||
const { id } = await context!.params;
|
||||
|
||||
const pb = createPocketBaseClient();
|
||||
const habit = await pb.collection('habits').getOne(id);
|
||||
const [habit] = await db.select()
|
||||
.from(habits)
|
||||
.where(and(eq(habits.id, id), isNull(habits.deletedAt)))
|
||||
.limit(1);
|
||||
|
||||
if (!habit) {
|
||||
return createErrorResponse('NOT_FOUND', 'Habit not found', 404);
|
||||
}
|
||||
|
||||
return NextResponse.json(habit);
|
||||
});
|
||||
|
||||
// PATCH /api/habits/[id] — Update a habit
|
||||
export const PATCH = withAuth<RouteContext>(async (request: NextRequest, _user, context) => {
|
||||
export const PATCH = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { id } = await context!.params;
|
||||
|
||||
try {
|
||||
const { id } = await context!.params;
|
||||
const body = await request.json();
|
||||
const data = updateHabitSchema.parse(body);
|
||||
|
||||
const pb = createPocketBaseClient();
|
||||
const habit = await pb.collection('habits').update(id, data);
|
||||
if (data.domain) {
|
||||
await requireWorkspaceAccess(data.domain);
|
||||
}
|
||||
|
||||
const updateValues: Record<string, any> = { updatedAt: new Date() };
|
||||
if (data.name !== undefined) updateValues.name = data.name;
|
||||
if (data.description !== undefined) updateValues.description = data.description;
|
||||
if (data.domain !== undefined) updateValues.domainId = data.domain;
|
||||
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.active !== undefined) updateValues.active = data.active;
|
||||
|
||||
const [habit] = await db.update(habits)
|
||||
.set(updateValues)
|
||||
.where(and(eq(habits.id, id), isNull(habits.deletedAt)))
|
||||
.returning();
|
||||
|
||||
if (!habit) {
|
||||
return createErrorResponse('NOT_FOUND', 'Habit not found', 404);
|
||||
}
|
||||
|
||||
if (data.tagIds) {
|
||||
await db.delete(habitTags).where(eq(habitTags.habitId, id));
|
||||
if (data.tagIds.length > 0) {
|
||||
await db.insert(habitTags).values(
|
||||
data.tagIds.map(tagId => ({ habitId: id, tagId }))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await recordActivity({
|
||||
actor: user.name,
|
||||
action: 'updated',
|
||||
entityType: 'habit',
|
||||
entityId: habit.id,
|
||||
changes: { name: habit.name },
|
||||
workspaceId: habit.domainId,
|
||||
});
|
||||
|
||||
return NextResponse.json(habit);
|
||||
} catch (error) {
|
||||
@@ -40,12 +99,27 @@ export const PATCH = withAuth<RouteContext>(async (request: NextRequest, _user,
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE /api/habits/[id] — Delete a habit
|
||||
export const DELETE = withAuth<RouteContext>(async (request: NextRequest, _user, context) => {
|
||||
// DELETE /api/habits/[id] — Soft-delete a habit
|
||||
export const DELETE = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { id } = await context!.params;
|
||||
|
||||
const pb = createPocketBaseClient();
|
||||
await pb.collection('habits').delete(id);
|
||||
const [habit] = await db.update(habits)
|
||||
.set({ deletedAt: new Date(), updatedAt: new Date() })
|
||||
.where(and(eq(habits.id, id), isNull(habits.deletedAt)))
|
||||
.returning();
|
||||
|
||||
if (!habit) {
|
||||
return createErrorResponse('NOT_FOUND', 'Habit not found', 404);
|
||||
}
|
||||
|
||||
await recordActivity({
|
||||
actor: user.name,
|
||||
action: 'deleted',
|
||||
entityType: 'habit',
|
||||
entityId: habit.id,
|
||||
changes: { name: habit.name },
|
||||
workspaceId: habit.domainId,
|
||||
});
|
||||
|
||||
return new NextResponse(null, { status: 204 });
|
||||
});
|
||||
|
||||
@@ -5,31 +5,92 @@
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { withAuth, createErrorResponse } from '@/lib/auth';
|
||||
import { createPocketBaseClient } from '@/lib/pocketbase';
|
||||
import { updateTaskSchema } from '@project-e/shared';
|
||||
import { recordActivity } from '@/lib/activity';
|
||||
import { db, tasks } from '@project-e/db';
|
||||
import { and, eq, isNull } from 'drizzle-orm';
|
||||
import { z } from 'zod';
|
||||
|
||||
const taskStatusEnum = z.enum(['todo', 'in_progress', 'done', 'cancelled']);
|
||||
const taskPriorityEnum = z.enum(['low', 'medium', 'high', 'urgent']);
|
||||
|
||||
const updateTaskSchema = z.object({
|
||||
title: z.string().min(1, 'Title is required').optional(),
|
||||
description: z.string().nullable().optional(),
|
||||
status: taskStatusEnum.optional(),
|
||||
priority: taskPriorityEnum.optional(),
|
||||
projectId: z.string().uuid().nullable().optional(),
|
||||
sectionId: z.string().uuid().nullable().optional(),
|
||||
parentId: z.string().uuid().nullable().optional(),
|
||||
dueDate: z.string().datetime().nullable().optional(),
|
||||
estimatedMinutes: z.number().int().positive().nullable().optional(),
|
||||
order: z.number().int().optional(),
|
||||
});
|
||||
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
// GET /api/tasks/[id] — Get a single task
|
||||
export const GET = withAuth<RouteContext>(async (request: NextRequest, _user, context) => {
|
||||
const { id } = await context!.params;
|
||||
|
||||
const pb = createPocketBaseClient();
|
||||
const task = await pb.collection('tasks').getOne(id);
|
||||
const [task] = await db.select()
|
||||
.from(tasks)
|
||||
.where(and(eq(tasks.id, id), isNull(tasks.deletedAt)))
|
||||
.limit(1);
|
||||
|
||||
if (!task) {
|
||||
return createErrorResponse('NOT_FOUND', 'Task not found', 404);
|
||||
}
|
||||
|
||||
return NextResponse.json(task);
|
||||
});
|
||||
|
||||
// PATCH /api/tasks/[id] — Update a task
|
||||
export const PATCH = withAuth<RouteContext>(async (request: NextRequest, _user, context) => {
|
||||
export const PATCH = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { id } = await context!.params;
|
||||
|
||||
try {
|
||||
const { id } = await context!.params;
|
||||
const body = await request.json();
|
||||
const data = updateTaskSchema.parse(body);
|
||||
|
||||
const pb = createPocketBaseClient();
|
||||
const task = await pb.collection('tasks').update(id, data);
|
||||
if (data.parentId) {
|
||||
const [parent] = await db.select({ id: tasks.id })
|
||||
.from(tasks)
|
||||
.where(and(eq(tasks.id, data.parentId), isNull(tasks.deletedAt)))
|
||||
.limit(1);
|
||||
if (!parent) {
|
||||
return createErrorResponse('NOT_FOUND', 'Parent task not found', 404);
|
||||
}
|
||||
}
|
||||
|
||||
const updateValues: Record<string, any> = { updatedAt: new Date() };
|
||||
if (data.title !== undefined) updateValues.title = data.title;
|
||||
if (data.description !== undefined) updateValues.description = data.description;
|
||||
if (data.status !== undefined) updateValues.status = data.status;
|
||||
if (data.priority !== undefined) updateValues.priority = data.priority;
|
||||
if (data.projectId !== undefined) updateValues.projectId = data.projectId;
|
||||
if (data.sectionId !== undefined) updateValues.sectionId = data.sectionId;
|
||||
if (data.parentId !== undefined) updateValues.parentId = data.parentId;
|
||||
if (data.dueDate !== undefined) updateValues.dueDate = data.dueDate ? new Date(data.dueDate) : null;
|
||||
if (data.estimatedMinutes !== undefined) updateValues.estimatedMinutes = data.estimatedMinutes;
|
||||
if (data.order !== undefined) updateValues.order = data.order;
|
||||
|
||||
const [task] = await db.update(tasks)
|
||||
.set(updateValues)
|
||||
.where(and(eq(tasks.id, id), isNull(tasks.deletedAt)))
|
||||
.returning();
|
||||
|
||||
if (!task) {
|
||||
return createErrorResponse('NOT_FOUND', 'Task not found', 404);
|
||||
}
|
||||
|
||||
await recordActivity({
|
||||
actor: user.name,
|
||||
action: 'updated',
|
||||
entityType: 'task',
|
||||
entityId: task.id,
|
||||
changes: { title: task.title, status: task.status },
|
||||
workspaceId: task.domainId,
|
||||
});
|
||||
|
||||
return NextResponse.json(task);
|
||||
} catch (error) {
|
||||
@@ -40,12 +101,27 @@ export const PATCH = withAuth<RouteContext>(async (request: NextRequest, _user,
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE /api/tasks/[id] — Delete a task
|
||||
export const DELETE = withAuth<RouteContext>(async (request: NextRequest, _user, context) => {
|
||||
// DELETE /api/tasks/[id] — Soft-delete a task
|
||||
export const DELETE = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
|
||||
const { id } = await context!.params;
|
||||
|
||||
const pb = createPocketBaseClient();
|
||||
await pb.collection('tasks').delete(id);
|
||||
const [task] = await db.update(tasks)
|
||||
.set({ deletedAt: new Date(), updatedAt: new Date() })
|
||||
.where(and(eq(tasks.id, id), isNull(tasks.deletedAt)))
|
||||
.returning();
|
||||
|
||||
if (!task) {
|
||||
return createErrorResponse('NOT_FOUND', 'Task not found', 404);
|
||||
}
|
||||
|
||||
await recordActivity({
|
||||
actor: user.name,
|
||||
action: 'deleted',
|
||||
entityType: 'task',
|
||||
entityId: task.id,
|
||||
changes: { title: task.title },
|
||||
workspaceId: task.domainId,
|
||||
});
|
||||
|
||||
return new NextResponse(null, { status: 204 });
|
||||
});
|
||||
|
||||
@@ -34,6 +34,7 @@ export const GET = withAuth(async (request: NextRequest, _user) => {
|
||||
const page = Math.max(1, parseInt(searchParams.get('page') || '1'));
|
||||
const perPage = Math.min(100, Math.max(1, parseInt(searchParams.get('perPage') || '50')));
|
||||
const filter = searchParams.get('filter') || undefined;
|
||||
const status = searchParams.get('status');
|
||||
const sort = searchParams.get('sort') || '-created';
|
||||
const domainId = searchParams.get('domain') || undefined;
|
||||
|
||||
@@ -54,6 +55,10 @@ export const GET = withAuth(async (request: NextRequest, _user) => {
|
||||
|
||||
const conditions: any[] = [isNull(tasks.deletedAt)];
|
||||
if (domainId) conditions.push(eq(tasks.domainId, domainId));
|
||||
if (status) {
|
||||
const statuses = status.split(',');
|
||||
conditions.push(inArray(tasks.status, statuses as any));
|
||||
}
|
||||
if (filter) {
|
||||
conditions.push(
|
||||
or(
|
||||
|
||||
@@ -12,7 +12,8 @@ interface Task {
|
||||
title: string;
|
||||
status: string;
|
||||
priority: string;
|
||||
domain: string;
|
||||
domainId?: string;
|
||||
domain?: string;
|
||||
}
|
||||
|
||||
interface Domain { id: string; name: string; color: string; }
|
||||
@@ -43,7 +44,7 @@ export function TodayTasksWidget() {
|
||||
async function fetchTasks() {
|
||||
try {
|
||||
const response = await fetch(
|
||||
'/api/tasks?filter=status!%3D%22done%22&perPage=5&sort=-priority'
|
||||
'/api/tasks?status=todo,in_progress&perPage=5&sort=-priority'
|
||||
);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
@@ -115,7 +116,7 @@ export function TodayTasksWidget() {
|
||||
{task.title}
|
||||
</span>
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{domainMap.get(task.domain) || task.domain}
|
||||
{domainMap.get(task.domainId ?? task.domain ?? '') || task.domainId || task.domain}
|
||||
</Badge>
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -60,7 +60,7 @@ export async function getGraphData(domainId: string): Promise<GraphData> {
|
||||
}
|
||||
|
||||
// Fetch all entities in this domain
|
||||
const projectIds = (await db.select({ id: projects.id }).from(projects).where(eq(projects.domainId, domainId))).map(p => p.id);
|
||||
const projectIds = (await db.select({ id: projects.id }).from(projects).where(and(eq(projects.domainId, domainId), isNull(projects.deletedAt)))).map(p => p.id);
|
||||
const [noteRows, taskRows, habitRows, projectRows, sectionRows, tagRows, domainRows] = await Promise.all([
|
||||
db.select({ id: notes.id, title: notes.title }).from(notes).where(and(eq(notes.domainId, domainId), isNull(notes.deletedAt))),
|
||||
db.select({ id: tasks.id, title: tasks.title, projectId: tasks.projectId }).from(tasks).where(and(eq(tasks.domainId, domainId), isNull(tasks.deletedAt))),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createAdminClient } from '../pocketbase';
|
||||
import { createAdminClient, createPocketBaseClient } from '../pocketbase';
|
||||
import type {
|
||||
Task,
|
||||
Habit,
|
||||
@@ -46,7 +46,7 @@ export async function generateWeeklySummary(
|
||||
streaks: Array<{ name: string; streak: number }>;
|
||||
byDomain: Record<string, { tasks: number; habits: number }>;
|
||||
}> {
|
||||
const pb = token ? createAdminClient() : createAdminClient();
|
||||
const pb = token ? createPocketBaseClient(token) : createAdminClient();
|
||||
|
||||
// Tasks completed this week
|
||||
const taskResults = await pb.collection('tasks').getFullList({
|
||||
@@ -112,7 +112,7 @@ export async function generateProjectHealth(
|
||||
milestoneStatus: Record<string, number>;
|
||||
completionRate: number;
|
||||
}> {
|
||||
const pb = token ? createAdminClient() : createAdminClient();
|
||||
const pb = token ? createPocketBaseClient(token) : createAdminClient();
|
||||
|
||||
const taskResults = await pb.collection('tasks').getFullList({
|
||||
filter: `project_id = "${projectId}"`,
|
||||
@@ -169,7 +169,7 @@ export async function generateHabitAnalysis(
|
||||
}>;
|
||||
atRiskHabits: string[];
|
||||
}> {
|
||||
const pb = token ? createAdminClient() : createAdminClient();
|
||||
const pb = token ? createPocketBaseClient(token) : createAdminClient();
|
||||
|
||||
const startDate = new Date();
|
||||
startDate.setDate(startDate.getDate() - days);
|
||||
@@ -225,7 +225,7 @@ export async function generateTimeAudit(
|
||||
byProject: Record<string, number>;
|
||||
byTag: Record<string, number>;
|
||||
}> {
|
||||
const pb = token ? createAdminClient() : createAdminClient();
|
||||
const pb = token ? createPocketBaseClient(token) : createAdminClient();
|
||||
|
||||
const entryResults = await pb.collection('time_entries').getFullList({
|
||||
filter: `started_at >= "${startDate}" && started_at <= "${endDate}"`,
|
||||
|
||||
+6
-4
@@ -1,5 +1,5 @@
|
||||
import { db, jobs, webhooks, webhookDeliveries, scheduledJobs, tasks, habits, habitCompletions } from '@project-e/db';
|
||||
import { and, eq, lte, isNull, sql } from 'drizzle-orm';
|
||||
import { and, eq, lte, isNull, or } from 'drizzle-orm';
|
||||
import { createHmac } from 'node:crypto';
|
||||
import rrule from 'rrule';
|
||||
const { RRule } = rrule;
|
||||
@@ -21,12 +21,13 @@ async function poll(): Promise<void> {
|
||||
try {
|
||||
const now = new Date();
|
||||
|
||||
// Get pending jobs that are due
|
||||
// Get pending jobs that are due.
|
||||
// nextRetryAt is NULL for freshly-queued jobs, which are due immediately.
|
||||
const pendingJobs = await db.select()
|
||||
.from(jobs)
|
||||
.where(and(
|
||||
eq(jobs.status, 'pending'),
|
||||
lte(jobs.nextRetryAt ?? sql`now()`, now),
|
||||
or(isNull(jobs.nextRetryAt), lte(jobs.nextRetryAt, now)),
|
||||
))
|
||||
.orderBy(jobs.createdAt)
|
||||
.limit(10);
|
||||
@@ -90,8 +91,9 @@ async function processJob(job: typeof jobs.$inferSelect): Promise<void> {
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
const attempts = (job.attempts || 0) + 1;
|
||||
const maxAttempts = job.maxAttempts || MAX_RETRIES;
|
||||
|
||||
if (attempts >= MAX_RETRIES) {
|
||||
if (attempts >= maxAttempts) {
|
||||
// Max retries reached — mark as failed
|
||||
await db.update(jobs)
|
||||
.set({
|
||||
|
||||
Reference in New Issue
Block a user