merge: fix all 10 UX bugs (P0 root cause + 9 regressions/polish) — PR #11
This commit is contained in:
@@ -0,0 +1,83 @@
|
|||||||
|
/**
|
||||||
|
* Unit tests for resolveActiveDomain helper in lib/auth.ts.
|
||||||
|
* Tests both branches: existing domain returned, and auto-creation of "Personal" domain.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { describe, it, expect, jest, beforeEach } from '@jest/globals';
|
||||||
|
|
||||||
|
// Mock the database module
|
||||||
|
const mockDb = {
|
||||||
|
select: jest.fn(),
|
||||||
|
insert: jest.fn(),
|
||||||
|
};
|
||||||
|
const mockDomains = {};
|
||||||
|
|
||||||
|
jest.mock('@project-e/db', () => ({
|
||||||
|
db: mockDb,
|
||||||
|
domains: mockDomains,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Mock next-auth
|
||||||
|
jest.mock('next-auth', () => ({
|
||||||
|
getServerSession: jest.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Mock next-auth config
|
||||||
|
jest.mock('@/lib/auth-config', () => ({
|
||||||
|
authOptions: {},
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('resolveActiveDomain', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return the user\'s first existing domain without creating one', async () => {
|
||||||
|
const { resolveActiveDomain } = await import('@/lib/auth');
|
||||||
|
|
||||||
|
const mockUser = { id: 'user-1', email: 'test@example.com', name: 'Test' };
|
||||||
|
const mockDomain = { id: 'domain-1', name: 'Work' };
|
||||||
|
|
||||||
|
// Mock the select chain to return an existing domain
|
||||||
|
const mockLimit = jest.fn().mockResolvedValue([mockDomain]);
|
||||||
|
const mockOrderBy = jest.fn().mockReturnValue({ limit: mockLimit });
|
||||||
|
const mockWhere = jest.fn().mockReturnValue({ orderBy: mockOrderBy });
|
||||||
|
const mockFrom = jest.fn().mockReturnValue({ where: mockWhere });
|
||||||
|
mockDb.select.mockReturnValue({ from: mockFrom });
|
||||||
|
|
||||||
|
const result = await resolveActiveDomain(mockUser);
|
||||||
|
|
||||||
|
expect(result).toEqual({ id: 'domain-1', name: 'Work', created: false });
|
||||||
|
expect(mockDb.select).toHaveBeenCalledWith({ id: expect.anything(), name: expect.anything() });
|
||||||
|
expect(mockDb.insert).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create a "Personal" domain when the user has none', async () => {
|
||||||
|
const { resolveActiveDomain } = await import('@/lib/auth');
|
||||||
|
|
||||||
|
const mockUser = { id: 'user-2', email: 'new@example.com', name: 'New User' };
|
||||||
|
const mockCreatedDomain = { id: 'new-domain-id', name: 'Personal' };
|
||||||
|
|
||||||
|
// First call: no existing domain
|
||||||
|
const mockLimit1 = jest.fn().mockResolvedValue([]);
|
||||||
|
const mockOrderBy1 = jest.fn().mockReturnValue({ limit: mockLimit1 });
|
||||||
|
const mockWhere1 = jest.fn().mockReturnValue({ orderBy: mockOrderBy1 });
|
||||||
|
const mockFrom1 = jest.fn().mockReturnValue({ where: mockWhere1 });
|
||||||
|
mockDb.select.mockReturnValue({ from: mockFrom1 });
|
||||||
|
|
||||||
|
// Insert returns the created domain
|
||||||
|
const mockReturning = jest.fn().mockResolvedValue([mockCreatedDomain]);
|
||||||
|
const mockValues = jest.fn().mockReturnValue({ returning: mockReturning });
|
||||||
|
mockDb.insert.mockReturnValue({ values: mockValues });
|
||||||
|
|
||||||
|
const result = await resolveActiveDomain(mockUser);
|
||||||
|
|
||||||
|
expect(result).toEqual({ id: 'new-domain-id', name: 'Personal', created: true });
|
||||||
|
expect(mockDb.insert).toHaveBeenCalled();
|
||||||
|
expect(mockValues).toHaveBeenCalledWith(expect.objectContaining({
|
||||||
|
ownerId: 'user-2',
|
||||||
|
name: 'Personal',
|
||||||
|
sortOrder: 0,
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -58,6 +58,7 @@ interface Canvas {
|
|||||||
|
|
||||||
function CanvasBoard({ canvas, onBack }: { canvas: Canvas; onBack: () => void }) {
|
function CanvasBoard({ canvas, onBack }: { canvas: Canvas; onBack: () => void }) {
|
||||||
const [cards, setCards] = useState<CanvasCard[]>(canvas.cards || []);
|
const [cards, setCards] = useState<CanvasCard[]>(canvas.cards || []);
|
||||||
|
const [connections] = useState<CanvasConnection[]>(canvas.connections || []);
|
||||||
const [dragging, setDragging] = useState<string | null>(null);
|
const [dragging, setDragging] = useState<string | null>(null);
|
||||||
const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
|
const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
|
||||||
const [viewport, setViewport] = useState(canvas.viewport || { x: 0, y: 0, zoom: 1 });
|
const [viewport, setViewport] = useState(canvas.viewport || { x: 0, y: 0, zoom: 1 });
|
||||||
@@ -252,7 +253,7 @@ function CanvasBoard({ canvas, onBack }: { canvas: Canvas; onBack: () => void })
|
|||||||
>
|
>
|
||||||
{/* Connections */}
|
{/* Connections */}
|
||||||
<svg className="pointer-events-none absolute inset-0" style={{ width: 4000, height: 4000 }}>
|
<svg className="pointer-events-none absolute inset-0" style={{ width: 4000, height: 4000 }}>
|
||||||
{canvas.connections.map((conn) => {
|
{connections.map((conn) => {
|
||||||
const source = cards.find((c) => c.id === conn.source_card_id);
|
const source = cards.find((c) => c.id === conn.source_card_id);
|
||||||
const target = cards.find((c) => c.id === conn.target_card_id);
|
const target = cards.find((c) => c.id === conn.target_card_id);
|
||||||
if (!source || !target) return null;
|
if (!source || !target) return null;
|
||||||
@@ -399,7 +400,6 @@ export default function CanvasPage() {
|
|||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
name: 'New canvas',
|
name: 'New canvas',
|
||||||
mode: 'freeform',
|
mode: 'freeform',
|
||||||
domain: 'personal',
|
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
if (!res.ok) throw new Error('Unable to create canvas.');
|
if (!res.ok) throw new Error('Unable to create canvas.');
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ import { HabitEditDialog } from "@/components/habits/habit-edit-dialog";
|
|||||||
import { HabitCompletionDialog } from "@/components/habits/habit-completion-dialog";
|
import { HabitCompletionDialog } from "@/components/habits/habit-completion-dialog";
|
||||||
import { HabitCalendarHeatmap } from "@/components/habits/habit-calendar-heatmap";
|
import { HabitCalendarHeatmap } from "@/components/habits/habit-calendar-heatmap";
|
||||||
import { HabitAnalytics } from "@/components/habits/habit-analytics";
|
import { HabitAnalytics } from "@/components/habits/habit-analytics";
|
||||||
|
import { CreateItemDialog } from "@/components/create-item-dialog";
|
||||||
|
import { useCreateDialogStore } from "@/lib/stores/use-create-dialog-store";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
|
||||||
interface Habit {
|
interface Habit {
|
||||||
@@ -54,6 +56,7 @@ export default function HabitsPage() {
|
|||||||
const [domainId, setDomainId] = useState<string | null>(null);
|
const [domainId, setDomainId] = useState<string | null>(null);
|
||||||
const [domains, setDomains] = useState<{ id: string; name: string }[]>([]);
|
const [domains, setDomains] = useState<{ id: string; name: string }[]>([]);
|
||||||
const [createOpen, setCreateOpen] = useState(false);
|
const [createOpen, setCreateOpen] = useState(false);
|
||||||
|
const { open: storeOpen, openCreate, closeCreate } = useCreateDialogStore();
|
||||||
const [editHabit, setEditHabit] = useState<Habit | null>(null);
|
const [editHabit, setEditHabit] = useState<Habit | null>(null);
|
||||||
const [completionHabit, setCompletionHabit] = useState<Habit | null>(null);
|
const [completionHabit, setCompletionHabit] = useState<Habit | null>(null);
|
||||||
const [deleteHabit, setDeleteHabit] = useState<Habit | null>(null);
|
const [deleteHabit, setDeleteHabit] = useState<Habit | null>(null);
|
||||||
@@ -154,7 +157,7 @@ export default function HabitsPage() {
|
|||||||
Active
|
Active
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<Button onClick={() => setCreateOpen(true)}>
|
<Button onClick={() => { setCreateOpen(true); openCreate('habit'); }}>
|
||||||
<Plus className="mr-2 h-4 w-4" aria-hidden="true" />
|
<Plus className="mr-2 h-4 w-4" aria-hidden="true" />
|
||||||
New habit
|
New habit
|
||||||
</Button>
|
</Button>
|
||||||
@@ -255,11 +258,19 @@ export default function HabitsPage() {
|
|||||||
|
|
||||||
<HabitCreateDialog
|
<HabitCreateDialog
|
||||||
open={createOpen}
|
open={createOpen}
|
||||||
onOpenChange={setCreateOpen}
|
onOpenChange={(o) => { setCreateOpen(o); if (!o) closeCreate(); }}
|
||||||
domainId={domainId || ''}
|
domainId={domainId || ''}
|
||||||
onCreated={fetchHabits}
|
onCreated={fetchHabits}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* Global CreateItemDialog from useCreateDialogStore — opened by topbar 'New habit' button */}
|
||||||
|
<CreateItemDialog
|
||||||
|
type="habit"
|
||||||
|
open={storeOpen}
|
||||||
|
onOpenChange={(o) => { if (!o) closeCreate(); else openCreate('habit'); }}
|
||||||
|
onCreated={fetchHabits}
|
||||||
|
/>
|
||||||
|
|
||||||
{editHabit && (
|
{editHabit && (
|
||||||
<HabitEditDialog
|
<HabitEditDialog
|
||||||
open={!!editHabit}
|
open={!!editHabit}
|
||||||
|
|||||||
@@ -24,6 +24,8 @@ import {
|
|||||||
} from "@/components/ui/alert-dialog";
|
} from "@/components/ui/alert-dialog";
|
||||||
import { ProjectCreateDialog } from "@/components/projects/project-create-dialog";
|
import { ProjectCreateDialog } from "@/components/projects/project-create-dialog";
|
||||||
import { ProjectEditDialog } from "@/components/projects/project-edit-dialog";
|
import { ProjectEditDialog } from "@/components/projects/project-edit-dialog";
|
||||||
|
import { CreateItemDialog } from "@/components/create-item-dialog";
|
||||||
|
import { useCreateDialogStore } from "@/lib/stores/use-create-dialog-store";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
|
||||||
@@ -54,6 +56,7 @@ export default function ProjectsPage() {
|
|||||||
const [domainId, setDomainId] = useState<string | null>(null);
|
const [domainId, setDomainId] = useState<string | null>(null);
|
||||||
const [domains, setDomains] = useState<{ id: string; name: string }[]>([]);
|
const [domains, setDomains] = useState<{ id: string; name: string }[]>([]);
|
||||||
const [createOpen, setCreateOpen] = useState(false);
|
const [createOpen, setCreateOpen] = useState(false);
|
||||||
|
const { open: storeOpen, openCreate, closeCreate } = useCreateDialogStore();
|
||||||
const [editProject, setEditProject] = useState<Project | null>(null);
|
const [editProject, setEditProject] = useState<Project | null>(null);
|
||||||
const [archiveProject, setArchiveProject] = useState<Project | null>(null);
|
const [archiveProject, setArchiveProject] = useState<Project | null>(null);
|
||||||
const [archiving, setArchiving] = useState(false);
|
const [archiving, setArchiving] = useState(false);
|
||||||
@@ -119,7 +122,7 @@ export default function ProjectsPage() {
|
|||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
)}
|
)}
|
||||||
<Button onClick={() => setCreateOpen(true)}>
|
<Button onClick={() => { setCreateOpen(true); openCreate('project'); }}>
|
||||||
<Plus className="mr-2 h-4 w-4" aria-hidden="true" />
|
<Plus className="mr-2 h-4 w-4" aria-hidden="true" />
|
||||||
New project
|
New project
|
||||||
</Button>
|
</Button>
|
||||||
@@ -220,11 +223,19 @@ export default function ProjectsPage() {
|
|||||||
|
|
||||||
<ProjectCreateDialog
|
<ProjectCreateDialog
|
||||||
open={createOpen}
|
open={createOpen}
|
||||||
onOpenChange={setCreateOpen}
|
onOpenChange={(o) => { setCreateOpen(o); if (!o) closeCreate(); }}
|
||||||
domainId={domainId || ''}
|
domainId={domainId || ''}
|
||||||
onCreated={fetchProjects}
|
onCreated={fetchProjects}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* Global CreateItemDialog from useCreateDialogStore — opened by topbar 'New project' button */}
|
||||||
|
<CreateItemDialog
|
||||||
|
type="project"
|
||||||
|
open={storeOpen}
|
||||||
|
onOpenChange={(o) => { if (!o) closeCreate(); else openCreate('project'); }}
|
||||||
|
onCreated={fetchProjects}
|
||||||
|
/>
|
||||||
|
|
||||||
{editProject && (
|
{editProject && (
|
||||||
<ProjectEditDialog
|
<ProjectEditDialog
|
||||||
open={!!editProject}
|
open={!!editProject}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// See AGENTS.md for full rules.
|
// See AGENTS.md for full rules.
|
||||||
|
|
||||||
import { NextRequest, NextResponse } from 'next/server';
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
import { withAuth, createErrorResponse } from '@/lib/auth';
|
import { withAuth, createErrorResponse, resolveActiveDomain } from '@/lib/auth';
|
||||||
import { createPocketBaseClient } from '@/lib/pocketbase';
|
import { createPocketBaseClient } from '@/lib/pocketbase';
|
||||||
import { createAgentSchema } from '@project-e/shared';
|
import { createAgentSchema } from '@project-e/shared';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
@@ -33,10 +33,13 @@ export const GET = withAuth(async (request: NextRequest, _user) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// POST /api/agents — Create an agent with auto-generated API key
|
// POST /api/agents — Create an agent with auto-generated API key
|
||||||
export const POST = withAuth(async (request: NextRequest, _user) => {
|
export const POST = withAuth(async (request: NextRequest, user) => {
|
||||||
try {
|
try {
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const data = createAgentSchema.parse(body);
|
const data = createAgentSchema.parse({
|
||||||
|
...body,
|
||||||
|
domain: body.domain || (await resolveActiveDomain(user)).id,
|
||||||
|
});
|
||||||
|
|
||||||
const pb = createPocketBaseClient();
|
const pb = createPocketBaseClient();
|
||||||
const agent = await pb.collection('agents').create({
|
const agent = await pb.collection('agents').create({
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// See AGENTS.md for full rules.
|
// See AGENTS.md for full rules.
|
||||||
|
|
||||||
import { NextRequest, NextResponse } from 'next/server';
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
import { withAuth, createErrorResponse } from '@/lib/auth';
|
import { withAuth, createErrorResponse, resolveActiveDomain } from '@/lib/auth';
|
||||||
import { createPocketBaseClient } from '@/lib/pocketbase';
|
import { createPocketBaseClient } from '@/lib/pocketbase';
|
||||||
import { createCanvasSchema } from '@project-e/shared';
|
import { createCanvasSchema } from '@project-e/shared';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
@@ -33,10 +33,13 @@ export const GET = withAuth(async (request: NextRequest, _user) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// POST /api/canvases — Create a canvas
|
// POST /api/canvases — Create a canvas
|
||||||
export const POST = withAuth(async (request: NextRequest, _user) => {
|
export const POST = withAuth(async (request: NextRequest, user) => {
|
||||||
try {
|
try {
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const data = createCanvasSchema.parse(body);
|
const data = createCanvasSchema.parse({
|
||||||
|
...body,
|
||||||
|
domain: body.domain || (await resolveActiveDomain(user)).id,
|
||||||
|
});
|
||||||
|
|
||||||
const pb = createPocketBaseClient();
|
const pb = createPocketBaseClient();
|
||||||
const canvas = await pb.collection('canvases').create(data);
|
const canvas = await pb.collection('canvases').create(data);
|
||||||
|
|||||||
@@ -4,21 +4,21 @@
|
|||||||
// See AGENTS.md for full rules.
|
// See AGENTS.md for full rules.
|
||||||
|
|
||||||
import { NextRequest, NextResponse } from 'next/server';
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
import { withAuth, createErrorResponse } from '@/lib/auth';
|
import { withAuth, createErrorResponse, resolveActiveDomain } from '@/lib/auth';
|
||||||
import { db, domains } from '@project-e/db';
|
import { db, domains } from '@project-e/db';
|
||||||
import { and, asc, desc, eq, ilike, or, sql } from 'drizzle-orm';
|
import { and, asc, desc, eq, ilike, or, sql } from 'drizzle-orm';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
const createDomainSchema = z.object({
|
const createDomainSchema = z.object({
|
||||||
name: z.string().min(1, 'Name is required'),
|
name: z.string().min(1, 'Name is required'),
|
||||||
slug: z.string().min(1, 'Slug is required'),
|
slug: z.string().min(1).optional(),
|
||||||
color: z.string().optional().nullable(),
|
color: z.string().optional().nullable(),
|
||||||
icon: z.string().optional().nullable(),
|
icon: z.string().optional().nullable(),
|
||||||
parentId: z.string().uuid().optional().nullable(),
|
parentId: z.string().uuid().optional().nullable(),
|
||||||
});
|
});
|
||||||
|
|
||||||
// GET /api/domains — List domains with filtering, sorting, pagination
|
// GET /api/domains — List domains with filtering, sorting, pagination
|
||||||
export const GET = withAuth(async (request: NextRequest, _user) => {
|
export const GET = withAuth(async (request: NextRequest, user) => {
|
||||||
const { searchParams } = new URL(request.url);
|
const { searchParams } = new URL(request.url);
|
||||||
const page = Math.max(1, parseInt(searchParams.get('page') || '1'));
|
const page = Math.max(1, parseInt(searchParams.get('page') || '1'));
|
||||||
const perPage = Math.min(100, Math.max(1, parseInt(searchParams.get('perPage') || '50')));
|
const perPage = Math.min(100, Math.max(1, parseInt(searchParams.get('perPage') || '50')));
|
||||||
@@ -39,8 +39,8 @@ export const GET = withAuth(async (request: NextRequest, _user) => {
|
|||||||
? asc(sortColumns[sortField] || domains.sortOrder)
|
? asc(sortColumns[sortField] || domains.sortOrder)
|
||||||
: desc(sortColumns[sortField] || domains.sortOrder);
|
: desc(sortColumns[sortField] || domains.sortOrder);
|
||||||
|
|
||||||
// Build where clause
|
// Build where clause — filter by owner
|
||||||
const conditions: any[] = [];
|
const conditions: any[] = [eq(domains.ownerId, user.id)];
|
||||||
if (filter) {
|
if (filter) {
|
||||||
conditions.push(
|
conditions.push(
|
||||||
or(
|
or(
|
||||||
@@ -64,7 +64,31 @@ export const GET = withAuth(async (request: NextRequest, _user) => {
|
|||||||
.where(and(...conditions)),
|
.where(and(...conditions)),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const totalItems = Number(countResult[0]?.count || 0);
|
let totalItems = Number(countResult[0]?.count || 0);
|
||||||
|
|
||||||
|
// If user has no domains, auto-create a default "Personal" domain
|
||||||
|
if (totalItems === 0) {
|
||||||
|
const active = await resolveActiveDomain(user);
|
||||||
|
// Re-fetch to include the newly created domain
|
||||||
|
const [newItems, newCount] = await Promise.all([
|
||||||
|
db.select()
|
||||||
|
.from(domains)
|
||||||
|
.where(eq(domains.ownerId, user.id))
|
||||||
|
.orderBy(orderBy)
|
||||||
|
.limit(perPage)
|
||||||
|
.offset(offset),
|
||||||
|
db.select({ count: sql<number>`count(*)` })
|
||||||
|
.from(domains)
|
||||||
|
.where(eq(domains.ownerId, user.id)),
|
||||||
|
]);
|
||||||
|
return NextResponse.json({
|
||||||
|
items: newItems,
|
||||||
|
totalItems: Number(newCount[0]?.count || 0),
|
||||||
|
totalPages: Math.ceil(Number(newCount[0]?.count || 0) / perPage),
|
||||||
|
page,
|
||||||
|
perPage,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
items,
|
items,
|
||||||
@@ -76,18 +100,22 @@ export const GET = withAuth(async (request: NextRequest, _user) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// POST /api/domains — Create a domain
|
// POST /api/domains — Create a domain
|
||||||
export const POST = withAuth(async (request: NextRequest, _user) => {
|
export const POST = withAuth(async (request: NextRequest, user) => {
|
||||||
try {
|
try {
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const data = createDomainSchema.parse(body);
|
const data = createDomainSchema.parse(body);
|
||||||
|
|
||||||
|
// Auto-generate slug from name if not provided
|
||||||
|
const slug = data.slug || data.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '') || 'domain';
|
||||||
|
|
||||||
const [domain] = await db.insert(domains)
|
const [domain] = await db.insert(domains)
|
||||||
.values({
|
.values({
|
||||||
name: data.name,
|
name: data.name,
|
||||||
slug: data.slug,
|
slug,
|
||||||
color: data.color || null,
|
color: data.color || null,
|
||||||
icon: data.icon || null,
|
icon: data.icon || null,
|
||||||
parentId: data.parentId || null,
|
parentId: data.parentId || null,
|
||||||
|
ownerId: user.id,
|
||||||
})
|
})
|
||||||
.returning();
|
.returning();
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// See AGENTS.md for full rules.
|
// See AGENTS.md for full rules.
|
||||||
|
|
||||||
import { NextRequest, NextResponse } from 'next/server';
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
import { withAuth, createErrorResponse } from '@/lib/auth';
|
import { withAuth, createErrorResponse, resolveActiveDomain } from '@/lib/auth';
|
||||||
import { recordActivity } from '@/lib/activity';
|
import { recordActivity } from '@/lib/activity';
|
||||||
import { db, habits, habitTags, tags as tagsTable } from '@project-e/db';
|
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 { and, asc, desc, eq, ilike, inArray, isNull, or, sql } from 'drizzle-orm';
|
||||||
@@ -25,13 +25,17 @@ const createHabitSchema = z.object({
|
|||||||
});
|
});
|
||||||
|
|
||||||
// GET /api/habits — List habits with filtering, sorting, pagination
|
// GET /api/habits — List habits with filtering, sorting, pagination
|
||||||
export const GET = withAuth(async (request: NextRequest, _user) => {
|
export const GET = withAuth(async (request: NextRequest, user) => {
|
||||||
const { searchParams } = new URL(request.url);
|
const { searchParams } = new URL(request.url);
|
||||||
const page = Math.max(1, parseInt(searchParams.get('page') || '1'));
|
const page = Math.max(1, parseInt(searchParams.get('page') || '1'));
|
||||||
const perPage = Math.min(100, Math.max(1, parseInt(searchParams.get('perPage') || '50')));
|
const perPage = Math.min(100, Math.max(1, parseInt(searchParams.get('perPage') || '50')));
|
||||||
const filter = searchParams.get('filter') || undefined;
|
const filter = searchParams.get('filter') || undefined;
|
||||||
const sort = searchParams.get('sort') || '-created';
|
const sort = searchParams.get('sort') || '-created';
|
||||||
const domainId = searchParams.get('domain') || undefined;
|
let domainId = searchParams.get('domain') || undefined;
|
||||||
|
if (!domainId) {
|
||||||
|
const active = await resolveActiveDomain(user);
|
||||||
|
domainId = active.id;
|
||||||
|
}
|
||||||
|
|
||||||
const sortDir = sort.startsWith('-') ? 'desc' : 'asc';
|
const sortDir = sort.startsWith('-') ? 'desc' : 'asc';
|
||||||
const sortField = sort.replace(/^-/, '');
|
const sortField = sort.replace(/^-/, '');
|
||||||
@@ -81,7 +85,10 @@ export const GET = withAuth(async (request: NextRequest, _user) => {
|
|||||||
export const POST = withAuth(async (request: NextRequest, user) => {
|
export const POST = withAuth(async (request: NextRequest, user) => {
|
||||||
try {
|
try {
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const data = createHabitSchema.parse(body);
|
const data = createHabitSchema.parse({
|
||||||
|
...body,
|
||||||
|
domain: body.domain || (await resolveActiveDomain(user)).id,
|
||||||
|
});
|
||||||
|
|
||||||
const [habit] = await db.insert(habits).values({
|
const [habit] = await db.insert(habits).values({
|
||||||
name: data.name,
|
name: data.name,
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// See AGENTS.md for full rules.
|
// See AGENTS.md for full rules.
|
||||||
|
|
||||||
import { NextRequest, NextResponse } from 'next/server';
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
import { withAuth, createErrorResponse } from '@/lib/auth';
|
import { withAuth, createErrorResponse, resolveActiveDomain } from '@/lib/auth';
|
||||||
import { recordActivity } from '@/lib/activity';
|
import { recordActivity } from '@/lib/activity';
|
||||||
import { db, projects, projectTags, tags as tagsTable } from '@project-e/db';
|
import { db, projects, projectTags, tags as tagsTable } from '@project-e/db';
|
||||||
import { and, asc, desc, eq, ilike, inArray, isNull, or, sql } from 'drizzle-orm';
|
import { and, asc, desc, eq, ilike, inArray, isNull, or, sql } from 'drizzle-orm';
|
||||||
@@ -24,13 +24,17 @@ const createProjectSchema = z.object({
|
|||||||
});
|
});
|
||||||
|
|
||||||
// GET /api/projects — List projects with filtering, sorting, pagination
|
// GET /api/projects — List projects with filtering, sorting, pagination
|
||||||
export const GET = withAuth(async (request: NextRequest, _user) => {
|
export const GET = withAuth(async (request: NextRequest, user) => {
|
||||||
const { searchParams } = new URL(request.url);
|
const { searchParams } = new URL(request.url);
|
||||||
const page = Math.max(1, parseInt(searchParams.get('page') || '1'));
|
const page = Math.max(1, parseInt(searchParams.get('page') || '1'));
|
||||||
const perPage = Math.min(100, Math.max(1, parseInt(searchParams.get('perPage') || '50')));
|
const perPage = Math.min(100, Math.max(1, parseInt(searchParams.get('perPage') || '50')));
|
||||||
const filter = searchParams.get('filter') || undefined;
|
const filter = searchParams.get('filter') || undefined;
|
||||||
const sort = searchParams.get('sort') || '-created';
|
const sort = searchParams.get('sort') || '-created';
|
||||||
const domainId = searchParams.get('domain') || undefined;
|
let domainId = searchParams.get('domain') || undefined;
|
||||||
|
if (!domainId) {
|
||||||
|
const active = await resolveActiveDomain(user);
|
||||||
|
domainId = active.id;
|
||||||
|
}
|
||||||
|
|
||||||
const sortDir = sort.startsWith('-') ? 'desc' : 'asc';
|
const sortDir = sort.startsWith('-') ? 'desc' : 'asc';
|
||||||
const sortField = sort.replace(/^-/, '');
|
const sortField = sort.replace(/^-/, '');
|
||||||
@@ -79,7 +83,10 @@ export const GET = withAuth(async (request: NextRequest, _user) => {
|
|||||||
export const POST = withAuth(async (request: NextRequest, user) => {
|
export const POST = withAuth(async (request: NextRequest, user) => {
|
||||||
try {
|
try {
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const data = createProjectSchema.parse(body);
|
const data = createProjectSchema.parse({
|
||||||
|
...body,
|
||||||
|
domain: body.domain || (await resolveActiveDomain(user)).id,
|
||||||
|
});
|
||||||
|
|
||||||
const [project] = await db.insert(projects).values({
|
const [project] = await db.insert(projects).values({
|
||||||
name: data.name,
|
name: data.name,
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
// AGENT INSTRUCTION: After every write (INSERT/UPDATE/DELETE), you MUST:
|
||||||
|
// 1. Insert activity feed entry
|
||||||
|
// 2. Call pg.notify('project_e_events', JSON.stringify({ type, action, id, workspace_id }))
|
||||||
|
// See AGENTS.md for full rules.
|
||||||
|
|
||||||
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
|
import { withAuth, createErrorResponse, resolveActiveDomain } from '@/lib/auth';
|
||||||
|
import { recordActivity } from '@/lib/activity';
|
||||||
|
import { db, tasks, habits, notes, projects } from '@project-e/db';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
const quickCaptureSchema = z.object({
|
||||||
|
type: z.enum(['task', 'habit', 'note', 'project']),
|
||||||
|
text: z.string().min(1, 'Text is required'),
|
||||||
|
description: z.string().optional().nullable(),
|
||||||
|
priority: z.enum(['low', 'medium', 'high', 'urgent']).optional().default('medium'),
|
||||||
|
domain: z.string().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// POST /api/quick-capture — Create an entity from quick text input
|
||||||
|
// Forwards to the appropriate create logic after resolving the active domain.
|
||||||
|
export const POST = withAuth(async (request: NextRequest, user) => {
|
||||||
|
try {
|
||||||
|
const body = await request.json();
|
||||||
|
const data = quickCaptureSchema.parse(body);
|
||||||
|
const domainId = data.domain || (await resolveActiveDomain(user)).id;
|
||||||
|
|
||||||
|
let result;
|
||||||
|
|
||||||
|
switch (data.type) {
|
||||||
|
case 'task': {
|
||||||
|
const [task] = await db.insert(tasks).values({
|
||||||
|
title: data.text,
|
||||||
|
description: data.description ?? null,
|
||||||
|
domainId,
|
||||||
|
priority: data.priority,
|
||||||
|
}).returning();
|
||||||
|
result = task;
|
||||||
|
await recordActivity({
|
||||||
|
actor: user.name,
|
||||||
|
action: 'created',
|
||||||
|
entityType: 'task',
|
||||||
|
entityId: task.id,
|
||||||
|
changes: { title: task.title },
|
||||||
|
workspaceId: domainId,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'habit': {
|
||||||
|
const [habit] = await db.insert(habits).values({
|
||||||
|
name: data.text,
|
||||||
|
description: data.description ?? null,
|
||||||
|
domainId,
|
||||||
|
}).returning();
|
||||||
|
result = habit;
|
||||||
|
await recordActivity({
|
||||||
|
actor: user.name,
|
||||||
|
action: 'created',
|
||||||
|
entityType: 'habit',
|
||||||
|
entityId: habit.id,
|
||||||
|
changes: { name: habit.name },
|
||||||
|
workspaceId: domainId,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'note': {
|
||||||
|
const [note] = await db.insert(notes).values({
|
||||||
|
title: data.text,
|
||||||
|
content: data.description ?? null,
|
||||||
|
domainId,
|
||||||
|
}).returning();
|
||||||
|
result = note;
|
||||||
|
await recordActivity({
|
||||||
|
actor: user.name,
|
||||||
|
action: 'created',
|
||||||
|
entityType: 'note',
|
||||||
|
entityId: note.id,
|
||||||
|
changes: { title: note.title },
|
||||||
|
workspaceId: domainId,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'project': {
|
||||||
|
const [project] = await db.insert(projects).values({
|
||||||
|
name: data.text,
|
||||||
|
description: data.description ?? null,
|
||||||
|
domainId,
|
||||||
|
}).returning();
|
||||||
|
result = project;
|
||||||
|
await recordActivity({
|
||||||
|
actor: user.name,
|
||||||
|
action: 'created',
|
||||||
|
entityType: 'project',
|
||||||
|
entityId: project.id,
|
||||||
|
changes: { name: project.name },
|
||||||
|
workspaceId: domainId,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json(result, { status: 201 });
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof z.ZodError) {
|
||||||
|
return createErrorResponse('VALIDATION_ERROR', 'Invalid input', 400, error.issues);
|
||||||
|
}
|
||||||
|
console.error('[quick-capture POST] error:', error);
|
||||||
|
return createErrorResponse('INTERNAL_ERROR', 'Failed to create', 500);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
// See AGENTS.md for full rules.
|
// See AGENTS.md for full rules.
|
||||||
|
|
||||||
import { NextRequest, NextResponse } from 'next/server';
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
import { withAuth, createErrorResponse } from '@/lib/auth';
|
import { withAuth, createErrorResponse, resolveActiveDomain } from '@/lib/auth';
|
||||||
import { searchEntities } from '@/lib/search-service';
|
import { searchEntities } from '@/lib/search-service';
|
||||||
|
|
||||||
// GET /api/search?q=&type=&domain=&limit=&offset=
|
// GET /api/search?q=&type=&domain=&limit=&offset=
|
||||||
@@ -13,7 +13,11 @@ export const GET = withAuth(async (request: NextRequest, user) => {
|
|||||||
const { searchParams } = new URL(request.url);
|
const { searchParams } = new URL(request.url);
|
||||||
const q = (searchParams.get('q') || '').trim();
|
const q = (searchParams.get('q') || '').trim();
|
||||||
const types = searchParams.get('types')?.split(',').filter(Boolean) || ['task', 'note', 'project', 'habit', 'domain'];
|
const types = searchParams.get('types')?.split(',').filter(Boolean) || ['task', 'note', 'project', 'habit', 'domain'];
|
||||||
const domain = searchParams.get('domain') || undefined;
|
let domain = searchParams.get('domain') || undefined;
|
||||||
|
if (!domain) {
|
||||||
|
const active = await resolveActiveDomain(user);
|
||||||
|
domain = active.id;
|
||||||
|
}
|
||||||
const limit = Math.max(1, Math.min(50, parseInt(searchParams.get('limit') || '20')));
|
const limit = Math.max(1, Math.min(50, parseInt(searchParams.get('limit') || '20')));
|
||||||
const offset = Math.max(0, parseInt(searchParams.get('offset') || '0'));
|
const offset = Math.max(0, parseInt(searchParams.get('offset') || '0'));
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// See AGENTS.md for full rules.
|
// See AGENTS.md for full rules.
|
||||||
|
|
||||||
import { NextRequest, NextResponse } from 'next/server';
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
import { withAuth, createErrorResponse } from '@/lib/auth';
|
import { withAuth, createErrorResponse, resolveActiveDomain } from '@/lib/auth';
|
||||||
import { recordActivity } from '@/lib/activity';
|
import { recordActivity } from '@/lib/activity';
|
||||||
import { db, tasks, taskTags, tags as tagsTable } from '@project-e/db';
|
import { db, tasks, taskTags, tags as tagsTable } from '@project-e/db';
|
||||||
import { and, asc, desc, eq, ilike, inArray, isNull, or, sql } from 'drizzle-orm';
|
import { and, asc, desc, eq, ilike, inArray, isNull, or, sql } from 'drizzle-orm';
|
||||||
@@ -29,13 +29,17 @@ const createTaskSchema = z.object({
|
|||||||
});
|
});
|
||||||
|
|
||||||
// GET /api/tasks — List tasks with filtering, sorting, pagination
|
// GET /api/tasks — List tasks with filtering, sorting, pagination
|
||||||
export const GET = withAuth(async (request: NextRequest, _user) => {
|
export const GET = withAuth(async (request: NextRequest, user) => {
|
||||||
const { searchParams } = new URL(request.url);
|
const { searchParams } = new URL(request.url);
|
||||||
const page = Math.max(1, parseInt(searchParams.get('page') || '1'));
|
const page = Math.max(1, parseInt(searchParams.get('page') || '1'));
|
||||||
const perPage = Math.min(100, Math.max(1, parseInt(searchParams.get('perPage') || '50')));
|
const perPage = Math.min(100, Math.max(1, parseInt(searchParams.get('perPage') || '50')));
|
||||||
const filter = searchParams.get('filter') || undefined;
|
const filter = searchParams.get('filter') || undefined;
|
||||||
const sort = searchParams.get('sort') || '-created';
|
const sort = searchParams.get('sort') || '-created';
|
||||||
const domainId = searchParams.get('domain') || undefined;
|
let domainId = searchParams.get('domain') || undefined;
|
||||||
|
if (!domainId) {
|
||||||
|
const active = await resolveActiveDomain(user);
|
||||||
|
domainId = active.id;
|
||||||
|
}
|
||||||
|
|
||||||
const sortDir = sort.startsWith('-') ? 'desc' : 'asc';
|
const sortDir = sort.startsWith('-') ? 'desc' : 'asc';
|
||||||
const sortField = sort.replace(/^-/, '');
|
const sortField = sort.replace(/^-/, '');
|
||||||
@@ -92,7 +96,10 @@ export const GET = withAuth(async (request: NextRequest, _user) => {
|
|||||||
export const POST = withAuth(async (request: NextRequest, user) => {
|
export const POST = withAuth(async (request: NextRequest, user) => {
|
||||||
try {
|
try {
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const data = createTaskSchema.parse(body);
|
const data = createTaskSchema.parse({
|
||||||
|
...body,
|
||||||
|
domain: body.domain || (await resolveActiveDomain(user)).id,
|
||||||
|
});
|
||||||
|
|
||||||
const [task] = await db.insert(tasks).values({
|
const [task] = await db.insert(tasks).values({
|
||||||
title: data.title,
|
title: data.title,
|
||||||
|
|||||||
@@ -129,7 +129,7 @@ export function BigCalendarWrapper({
|
|||||||
eventPropGetter={eventStyleGetter}
|
eventPropGetter={eventStyleGetter}
|
||||||
onSelectEvent={handleSelectEvent}
|
onSelectEvent={handleSelectEvent}
|
||||||
views={['month', 'week', 'day']}
|
views={['month', 'week', 'day']}
|
||||||
defaultView={defaultView}
|
view={defaultView}
|
||||||
date={date}
|
date={date}
|
||||||
onNavigate={handleNavigate}
|
onNavigate={handleNavigate}
|
||||||
onView={handleViewChange}
|
onView={handleViewChange}
|
||||||
|
|||||||
@@ -6,48 +6,36 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
|||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||||
import { useRouter } from 'next/navigation';
|
import { toast } from 'sonner';
|
||||||
|
|
||||||
export function QuickCaptureWidget() {
|
export function QuickCaptureWidget() {
|
||||||
const [type, setType] = useState('task');
|
const [type, setType] = useState('task');
|
||||||
const [title, setTitle] = useState('');
|
const [title, setTitle] = useState('');
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
const router = useRouter();
|
|
||||||
|
|
||||||
async function handleSubmit(e: React.FormEvent) {
|
async function handleSubmit(e: React.FormEvent) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
if (!title.trim()) return;
|
if (!title.trim()) return;
|
||||||
|
|
||||||
setSubmitting(true);
|
setSubmitting(true);
|
||||||
try {
|
try {
|
||||||
const endpoint = type === 'task' ? '/api/tasks'
|
const res = await fetch('/api/quick-capture', {
|
||||||
: type === 'habit' ? '/api/habits'
|
|
||||||
: '/api/notes';
|
|
||||||
|
|
||||||
const body: Record<string, unknown> = { title: title.trim() };
|
|
||||||
if (type === 'task') {
|
|
||||||
body.status = 'todo';
|
|
||||||
body.priority = 'medium';
|
|
||||||
}
|
|
||||||
if (type === 'habit') {
|
|
||||||
body.name = title.trim();
|
|
||||||
delete body.title;
|
|
||||||
body.frequency = 'daily';
|
|
||||||
body.difficulty = 'medium';
|
|
||||||
}
|
|
||||||
|
|
||||||
const res = await fetch(endpoint, {
|
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(body),
|
body: JSON.stringify({ type, text: title.trim() }),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
setTitle('');
|
setTitle('');
|
||||||
router.refresh();
|
toast.success(type.charAt(0).toUpperCase() + type.slice(1) + ' created');
|
||||||
|
} else {
|
||||||
|
const err = await res.json().catch(() => ({ error: 'Unknown error' }));
|
||||||
|
toast.error(err.error || 'Failed to create');
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Quick capture failed:', err);
|
console.error('Quick capture failed:', err);
|
||||||
|
toast.error('Failed to create');
|
||||||
} finally {
|
} finally {
|
||||||
setSubmitting(false);
|
setSubmitting(false);
|
||||||
}
|
}
|
||||||
@@ -71,6 +59,7 @@ export function QuickCaptureWidget() {
|
|||||||
<SelectItem value="task">Task</SelectItem>
|
<SelectItem value="task">Task</SelectItem>
|
||||||
<SelectItem value="habit">Habit</SelectItem>
|
<SelectItem value="habit">Habit</SelectItem>
|
||||||
<SelectItem value="note">Note</SelectItem>
|
<SelectItem value="note">Note</SelectItem>
|
||||||
|
<SelectItem value="project">Project</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
<Input
|
<Input
|
||||||
@@ -79,7 +68,7 @@ export function QuickCaptureWidget() {
|
|||||||
placeholder="Quick add..."
|
placeholder="Quick add..."
|
||||||
className="flex-1"
|
className="flex-1"
|
||||||
/>
|
/>
|
||||||
<Button type="submit" size="icon" disabled={submitting || !title.trim()}>
|
<Button type="button" size="icon" disabled={submitting || !title.trim()} onClick={(e) => { e.stopPropagation(); handleSubmit(e); }}>
|
||||||
<Send className="h-4 w-4" />
|
<Send className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -128,7 +128,7 @@ export function NoteEditor({ content, onChange, onBlur }: NoteEditorProps) {
|
|||||||
|
|
||||||
{/* Editor content */}
|
{/* Editor content */}
|
||||||
<div className="flex-1 overflow-auto">
|
<div className="flex-1 overflow-auto">
|
||||||
<EditorContent editor={editor} className="tiptap-editor min-h-[400px]" />
|
<EditorContent editor={editor} className="tiptap-editor min-h-[400px]" tabIndex={0} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -203,7 +203,7 @@ export function SettingsDomains() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Add new domain */}
|
{/* Add new domain */}
|
||||||
<div className="flex gap-2">
|
<div className="relative z-50 flex gap-2">
|
||||||
<label htmlFor="new-domain-name" className="sr-only">
|
<label htmlFor="new-domain-name" className="sr-only">
|
||||||
New domain name
|
New domain name
|
||||||
</label>
|
</label>
|
||||||
@@ -226,7 +226,7 @@ export function SettingsDomains() {
|
|||||||
disabled={creating}
|
disabled={creating}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<Button onClick={addDomain} disabled={creating || !newDomainName.trim()}>
|
<Button type="button" onClick={(e) => { e.stopPropagation(); addDomain(); }} disabled={creating || !newDomainName.trim()}>
|
||||||
<Plus className="mr-1 h-4 w-4" />
|
<Plus className="mr-1 h-4 w-4" />
|
||||||
{creating ? 'Adding...' : 'Add'}
|
{creating ? 'Adding...' : 'Add'}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ function TaskCard({
|
|||||||
onClick: () => void;
|
onClick: () => void;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<Card className="mb-2 cursor-pointer hover:shadow-md transition-shadow" onClick={onClick}>
|
<Card className="mb-2 cursor-pointer hover:shadow-md transition-shadow" onClick={onClick} role="button" tabIndex={0} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onClick(); } }} aria-label={task.title}>
|
||||||
<CardContent className="p-3">
|
<CardContent className="p-3">
|
||||||
<div className="mb-2 flex items-start justify-between gap-2">
|
<div className="mb-2 flex items-start justify-between gap-2">
|
||||||
<span className="flex-1 text-sm font-medium leading-tight">
|
<span className="flex-1 text-sm font-medium leading-tight">
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useEffect, useState, useCallback, useMemo } from 'react';
|
import { useEffect, useState, useCallback, useMemo, useRef } from 'react';
|
||||||
import { useRouter, useSearchParams, usePathname } from 'next/navigation';
|
import { useRouter, useSearchParams, usePathname } from 'next/navigation';
|
||||||
import {
|
import {
|
||||||
Table,
|
Table,
|
||||||
@@ -177,6 +177,7 @@ export function TasksListView({
|
|||||||
const [offset, setOffset] = useState(0);
|
const [offset, setOffset] = useState(0);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [loadingMore, setLoadingMore] = useState(false);
|
const [loadingMore, setLoadingMore] = useState(false);
|
||||||
|
const lastErrorRef = useRef<string | null>(null);
|
||||||
const [selectedTask, setSelectedTask] = useState<Task | null>(null);
|
const [selectedTask, setSelectedTask] = useState<Task | null>(null);
|
||||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||||
const [deleting, setDeleting] = useState(false);
|
const [deleting, setDeleting] = useState(false);
|
||||||
@@ -249,9 +250,22 @@ export function TasksListView({
|
|||||||
setOffset(0);
|
setOffset(0);
|
||||||
}
|
}
|
||||||
setTotalCount(data.totalItems || 0);
|
setTotalCount(data.totalItems || 0);
|
||||||
|
// Successful fetch — reset the dedup tracker so the next error
|
||||||
|
// class toasts fresh instead of being suppressed.
|
||||||
|
lastErrorRef.current = null;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to fetch tasks:', error);
|
console.error('Failed to fetch tasks:', error);
|
||||||
toast.error('Unable to load tasks');
|
// Only toast once per unique error message to prevent infinite spam
|
||||||
|
// when realtime subscriptions re-trigger fetchTasks() on every event.
|
||||||
|
const message = error instanceof Error ? error.message : 'Unable to load tasks';
|
||||||
|
if (message !== lastErrorRef.current) {
|
||||||
|
lastErrorRef.current = message;
|
||||||
|
if (message.includes('429') || message.toLowerCase().includes('rate')) {
|
||||||
|
toast.error('Rate limited — slowing down');
|
||||||
|
} else {
|
||||||
|
toast.error('Unable to load tasks');
|
||||||
|
}
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
setLoadingMore(false);
|
setLoadingMore(false);
|
||||||
@@ -286,13 +300,26 @@ export function TasksListView({
|
|||||||
// Subscribe to realtime updates
|
// Subscribe to realtime updates
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!domainId) return;
|
if (!domainId) return;
|
||||||
const unsubscribe = subscribe(['task'], (event: any) => {
|
// Debounce realtime-triggered refetches so a burst of events does
|
||||||
if (event.type === 'task') {
|
// not cause a flood of fetchTasks() calls + toasts.
|
||||||
|
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
const debouncedRefetch = () => {
|
||||||
|
if (timer) clearTimeout(timer);
|
||||||
|
timer = setTimeout(() => {
|
||||||
fetchTasks();
|
fetchTasks();
|
||||||
onRefresh?.();
|
onRefresh?.();
|
||||||
|
}, 750);
|
||||||
|
};
|
||||||
|
debouncedRefetch.cancel = () => { if (timer) { clearTimeout(timer); timer = null; } };
|
||||||
|
const unsubscribe = subscribe(['task'], (event: any) => {
|
||||||
|
if (event.type === 'task') {
|
||||||
|
debouncedRefetch();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return unsubscribe;
|
return () => {
|
||||||
|
debouncedRefetch.cancel();
|
||||||
|
unsubscribe;
|
||||||
|
};
|
||||||
}, [domainId, subscribe, fetchTasks, onRefresh]);
|
}, [domainId, subscribe, fetchTasks, onRefresh]);
|
||||||
|
|
||||||
// Clear selection when tasks change
|
// Clear selection when tasks change
|
||||||
|
|||||||
@@ -17,9 +17,11 @@ export function TopBar() {
|
|||||||
if (pathname.startsWith('/projects')) openCreate('project');
|
if (pathname.startsWith('/projects')) openCreate('project');
|
||||||
else if (pathname.startsWith('/habits')) openCreate('habit');
|
else if (pathname.startsWith('/habits')) openCreate('habit');
|
||||||
else if (pathname.startsWith('/tasks')) openCreate('task');
|
else if (pathname.startsWith('/tasks')) openCreate('task');
|
||||||
else {
|
// On other pages (e.g. /settings) the topbar's "Quick add" button
|
||||||
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'k', metaKey: true }));
|
// visually overlaps form action buttons (e.g. Domain "Add") because
|
||||||
}
|
// both are anchored top-right. Dispatching Cmd+K here would cause
|
||||||
|
// those form clicks to be mis-interpreted as opening the palette.
|
||||||
|
// So we no-op on those pages — the form buttons handle their own actions.
|
||||||
}
|
}
|
||||||
|
|
||||||
const label = pathname.startsWith('/projects') ? 'New project'
|
const label = pathname.startsWith('/projects') ? 'New project'
|
||||||
@@ -39,10 +41,14 @@ export function TopBar() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div className="ml-auto flex items-center gap-2">
|
<div className="ml-auto flex items-center gap-2">
|
||||||
<Button variant="outline" size="sm" onClick={handleCreate} aria-label={label === 'Quick add' ? 'Quick add' : `Create ${label.toLowerCase()}`}>
|
{(pathname.startsWith('/projects') ||
|
||||||
<Plus className="mr-1 h-4 w-4" aria-hidden="true" />
|
pathname.startsWith('/habits') ||
|
||||||
{label}
|
pathname.startsWith('/tasks')) && (
|
||||||
</Button>
|
<Button variant="outline" size="sm" onClick={handleCreate} aria-label={label === 'Quick add' ? 'Quick add' : `Create ${label.toLowerCase()}`}>
|
||||||
|
<Plus className="mr-1 h-4 w-4" aria-hidden="true" />
|
||||||
|
{label}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
<NotificationBell />
|
<NotificationBell />
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|||||||
+29
-1
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
|
|||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import { authOptions } from './auth-config';
|
import { authOptions } from './auth-config';
|
||||||
import { db, domains } from '@project-e/db';
|
import { db, domains } from '@project-e/db';
|
||||||
import { eq } from 'drizzle-orm';
|
import { asc, eq } from 'drizzle-orm';
|
||||||
|
|
||||||
export interface AuthUser {
|
export interface AuthUser {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -56,6 +56,34 @@ export async function requireWorkspaceAccess(workspaceId: string): Promise<void>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the user's active workspace/domain. If the user has any domain,
|
||||||
|
* return the first one (ordered by sort_order then created_at). If they
|
||||||
|
* have none (onboarding skipped), auto-create a default "Personal"
|
||||||
|
* domain for them and return that.
|
||||||
|
*
|
||||||
|
* This is the single source of truth for "what domain is this user
|
||||||
|
* working in right now?" -- every ambiguous caller should route through
|
||||||
|
* this before touching the DB.
|
||||||
|
*/
|
||||||
|
export async function resolveActiveDomain(user: { id: string; email: string; name?: string | null }): Promise<{ id: string; name: string; created: boolean }> {
|
||||||
|
const [existing] = await db
|
||||||
|
.select({ id: domains.id, name: domains.name })
|
||||||
|
.from(domains)
|
||||||
|
.where(eq(domains.ownerId, user.id))
|
||||||
|
.orderBy(asc(domains.sortOrder), asc(domains.createdAt))
|
||||||
|
.limit(1);
|
||||||
|
if (existing) return { ...existing, created: false };
|
||||||
|
const slug = 'personal-' + user.id.slice(0, 8);
|
||||||
|
const [created] = await db.insert(domains).values({
|
||||||
|
ownerId: user.id,
|
||||||
|
name: 'Personal',
|
||||||
|
slug: slug,
|
||||||
|
sortOrder: 0,
|
||||||
|
}).returning({ id: domains.id, name: domains.name });
|
||||||
|
return { ...created, created: true };
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Auth middleware for API routes
|
* Auth middleware for API routes
|
||||||
* Wraps a route handler and ensures authentication
|
* Wraps a route handler and ensures authentication
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
ALTER TABLE "domains" ADD COLUMN "owner_id" uuid REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE INDEX "domains_owner_id_idx" ON "domains" USING btree ("owner_id");
|
||||||
@@ -57,6 +57,7 @@ export const domains = pgTable(
|
|||||||
slug: text('slug').notNull().unique(),
|
slug: text('slug').notNull().unique(),
|
||||||
color: text('color'),
|
color: text('color'),
|
||||||
icon: text('icon'),
|
icon: text('icon'),
|
||||||
|
ownerId: uuid('owner_id').references(() => users.id, { onDelete: 'cascade' }),
|
||||||
parentId: uuid('parent_id').references((): any => domains.id, { onDelete: 'set null' }),
|
parentId: uuid('parent_id').references((): any => domains.id, { onDelete: 'set null' }),
|
||||||
sortOrder: integer('sort_order').default(0),
|
sortOrder: integer('sort_order').default(0),
|
||||||
customFields: jsonb('custom_fields').$type<Record<string, unknown>>().default({}),
|
customFields: jsonb('custom_fields').$type<Record<string, unknown>>().default({}),
|
||||||
|
|||||||
@@ -36,9 +36,9 @@ export const agentTaskSchema = z.object({
|
|||||||
id: z.string(),
|
id: z.string(),
|
||||||
agent_id: z.string(),
|
agent_id: z.string(),
|
||||||
task_type: z.string(),
|
task_type: z.string(),
|
||||||
input: z.record(z.unknown()),
|
input: z.record(z.string(), z.unknown()),
|
||||||
status: z.enum(['pending', 'running', 'completed', 'failed']).default('pending'),
|
status: z.enum(['pending', 'running', 'completed', 'failed']).default('pending'),
|
||||||
output: z.record(z.unknown()).optional(),
|
output: z.record(z.string(), z.unknown()).optional(),
|
||||||
error_message: z.string().optional(),
|
error_message: z.string().optional(),
|
||||||
started_at: z.string().datetime().optional(),
|
started_at: z.string().datetime().optional(),
|
||||||
completed_at: z.string().datetime().optional(),
|
completed_at: z.string().datetime().optional(),
|
||||||
@@ -70,8 +70,8 @@ export const agentSchema = z.object({
|
|||||||
last_active_at: z.string().datetime().optional(),
|
last_active_at: z.string().datetime().optional(),
|
||||||
domain: z.string(),
|
domain: z.string(),
|
||||||
tags: z.array(z.string()).default([]),
|
tags: z.array(z.string()).default([]),
|
||||||
config: z.record(z.unknown()).optional(),
|
config: z.record(z.string(), z.unknown()).optional(),
|
||||||
custom_fields: z.record(z.unknown()).optional(),
|
custom_fields: z.record(z.string(), z.unknown()).optional(),
|
||||||
created: z.string().datetime(),
|
created: z.string().datetime(),
|
||||||
updated: z.string().datetime(),
|
updated: z.string().datetime(),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ export const canvasSchema = z.object({
|
|||||||
zoom: z.number().positive().default(1),
|
zoom: z.number().positive().default(1),
|
||||||
}).optional(),
|
}).optional(),
|
||||||
background: z.string().optional(),
|
background: z.string().optional(),
|
||||||
custom_fields: z.record(z.unknown()).optional(),
|
custom_fields: z.record(z.string(), z.unknown()).optional(),
|
||||||
created: z.string().datetime(),
|
created: z.string().datetime(),
|
||||||
updated: z.string().datetime(),
|
updated: z.string().datetime(),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -110,7 +110,7 @@ export const errorLogSchema = z.object({
|
|||||||
source: z.string(),
|
source: z.string(),
|
||||||
message: z.string(),
|
message: z.string(),
|
||||||
stack_trace: z.string().optional(),
|
stack_trace: z.string().optional(),
|
||||||
metadata: z.record(z.unknown()).optional(),
|
metadata: z.record(z.string(), z.unknown()).optional(),
|
||||||
resolved: z.boolean().default(false),
|
resolved: z.boolean().default(false),
|
||||||
created: z.string().datetime(),
|
created: z.string().datetime(),
|
||||||
updated: z.string().datetime(),
|
updated: z.string().datetime(),
|
||||||
@@ -134,11 +134,11 @@ export const queueJobSchema = z.object({
|
|||||||
id: z.string(),
|
id: z.string(),
|
||||||
queue: z.string(),
|
queue: z.string(),
|
||||||
type: z.string(),
|
type: z.string(),
|
||||||
payload: z.record(z.unknown()),
|
payload: z.record(z.string(), z.unknown()),
|
||||||
status: queueJobStatusEnum.default('pending'),
|
status: queueJobStatusEnum.default('pending'),
|
||||||
attempts: z.number().int().nonnegative().default(0),
|
attempts: z.number().int().nonnegative().default(0),
|
||||||
max_attempts: z.number().int().positive().default(3),
|
max_attempts: z.number().int().positive().default(3),
|
||||||
result: z.record(z.unknown()).optional(),
|
result: z.record(z.string(), z.unknown()).optional(),
|
||||||
error_message: z.string().optional(),
|
error_message: z.string().optional(),
|
||||||
scheduled_at: z.string().datetime().optional(),
|
scheduled_at: z.string().datetime().optional(),
|
||||||
started_at: z.string().datetime().optional(),
|
started_at: z.string().datetime().optional(),
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ export const habitSchema = z.object({
|
|||||||
score_config: habitScoreConfigSchema.optional(),
|
score_config: habitScoreConfigSchema.optional(),
|
||||||
active: z.boolean().default(true),
|
active: z.boolean().default(true),
|
||||||
tags: z.array(z.string()).default([]),
|
tags: z.array(z.string()).default([]),
|
||||||
custom_fields: z.record(z.unknown()).optional(),
|
custom_fields: z.record(z.string(), z.unknown()).optional(),
|
||||||
created: z.string().datetime(),
|
created: z.string().datetime(),
|
||||||
updated: z.string().datetime(),
|
updated: z.string().datetime(),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ export const milestoneSchema = z.object({
|
|||||||
completed_at: z.string().datetime().optional(),
|
completed_at: z.string().datetime().optional(),
|
||||||
tasks: z.array(z.string()).default([]),
|
tasks: z.array(z.string()).default([]),
|
||||||
dependencies: z.array(milestoneDependencySchema).default([]),
|
dependencies: z.array(milestoneDependencySchema).default([]),
|
||||||
custom_fields: z.record(z.unknown()).optional(),
|
custom_fields: z.record(z.string(), z.unknown()).optional(),
|
||||||
created: z.string().datetime(),
|
created: z.string().datetime(),
|
||||||
updated: z.string().datetime(),
|
updated: z.string().datetime(),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ export const noteSchema = z.object({
|
|||||||
size: z.number(),
|
size: z.number(),
|
||||||
url: z.string(),
|
url: z.string(),
|
||||||
})).default([]),
|
})).default([]),
|
||||||
custom_fields: z.record(z.unknown()).optional(),
|
custom_fields: z.record(z.string(), z.unknown()).optional(),
|
||||||
created: z.string().datetime(),
|
created: z.string().datetime(),
|
||||||
updated: z.string().datetime(),
|
updated: z.string().datetime(),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ export const projectSettingsSchema = z.object({
|
|||||||
pomodoro_focus_minutes: z.number().int().positive().default(25),
|
pomodoro_focus_minutes: z.number().int().positive().default(25),
|
||||||
pomodoro_break_minutes: z.number().int().positive().default(5),
|
pomodoro_break_minutes: z.number().int().positive().default(5),
|
||||||
notifications_enabled: z.boolean().default(true),
|
notifications_enabled: z.boolean().default(true),
|
||||||
custom_fields: z.record(z.unknown()).optional(),
|
custom_fields: z.record(z.string(), z.unknown()).optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── Project Schema ───────────────────────────────────────────────────────────
|
// ── Project Schema ───────────────────────────────────────────────────────────
|
||||||
@@ -33,7 +33,7 @@ export const projectSchema = z.object({
|
|||||||
target_date: z.string().datetime().optional(),
|
target_date: z.string().datetime().optional(),
|
||||||
completed_at: z.string().datetime().optional(),
|
completed_at: z.string().datetime().optional(),
|
||||||
settings: projectSettingsSchema.optional(),
|
settings: projectSettingsSchema.optional(),
|
||||||
custom_fields: z.record(z.unknown()).optional(),
|
custom_fields: z.record(z.string(), z.unknown()).optional(),
|
||||||
created: z.string().datetime(),
|
created: z.string().datetime(),
|
||||||
updated: z.string().datetime(),
|
updated: z.string().datetime(),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ export const reportTemplateSchema = z.object({
|
|||||||
sections: z.array(z.object({
|
sections: z.array(z.object({
|
||||||
title: z.string(),
|
title: z.string(),
|
||||||
type: z.enum(['summary', 'chart', 'table', 'list', 'text']).default('text'),
|
type: z.enum(['summary', 'chart', 'table', 'list', 'text']).default('text'),
|
||||||
config: z.record(z.unknown()).optional(),
|
config: z.record(z.string(), z.unknown()).optional(),
|
||||||
sort_order: z.number().int().nonnegative().default(0),
|
sort_order: z.number().int().nonnegative().default(0),
|
||||||
})).default([]),
|
})).default([]),
|
||||||
created: z.string().datetime(),
|
created: z.string().datetime(),
|
||||||
@@ -42,14 +42,14 @@ export const reportSchema = z.object({
|
|||||||
sections: z.array(z.object({
|
sections: z.array(z.object({
|
||||||
title: z.string(),
|
title: z.string(),
|
||||||
content: z.string().optional(),
|
content: z.string().optional(),
|
||||||
data: z.record(z.unknown()).optional(),
|
data: z.record(z.string(), z.unknown()).optional(),
|
||||||
sort_order: z.number().int().nonnegative().default(0),
|
sort_order: z.number().int().nonnegative().default(0),
|
||||||
})).default([]),
|
})).default([]),
|
||||||
summary: z.string().optional(),
|
summary: z.string().optional(),
|
||||||
is_draft: z.boolean().default(true),
|
is_draft: z.boolean().default(true),
|
||||||
generated_at: z.string().datetime().optional(),
|
generated_at: z.string().datetime().optional(),
|
||||||
tags: z.array(z.string()).default([]),
|
tags: z.array(z.string()).default([]),
|
||||||
custom_fields: z.record(z.unknown()).optional(),
|
custom_fields: z.record(z.string(), z.unknown()).optional(),
|
||||||
created: z.string().datetime(),
|
created: z.string().datetime(),
|
||||||
updated: z.string().datetime(),
|
updated: z.string().datetime(),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ export const taskSchema = z.object({
|
|||||||
attachments: z.array(attachmentSchema).default([]),
|
attachments: z.array(attachmentSchema).default([]),
|
||||||
dependencies: z.array(z.string()).default([]),
|
dependencies: z.array(z.string()).default([]),
|
||||||
subtasks: z.array(subtaskSchema).default([]),
|
subtasks: z.array(subtaskSchema).default([]),
|
||||||
custom_fields: z.record(z.unknown()).optional(),
|
custom_fields: z.record(z.string(), z.unknown()).optional(),
|
||||||
completed_at: z.string().datetime().optional(),
|
completed_at: z.string().datetime().optional(),
|
||||||
created: z.string().datetime(),
|
created: z.string().datetime(),
|
||||||
updated: z.string().datetime(),
|
updated: z.string().datetime(),
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ export const webhookDeliverySchema = z.object({
|
|||||||
id: z.string(),
|
id: z.string(),
|
||||||
webhook_id: z.string(),
|
webhook_id: z.string(),
|
||||||
event: z.string(),
|
event: z.string(),
|
||||||
payload: z.record(z.unknown()),
|
payload: z.record(z.string(), z.unknown()),
|
||||||
status: z.enum(['success', 'failed', 'pending']).default('pending'),
|
status: z.enum(['success', 'failed', 'pending']).default('pending'),
|
||||||
status_code: z.number().int().optional(),
|
status_code: z.number().int().optional(),
|
||||||
response_body: z.string().optional(),
|
response_body: z.string().optional(),
|
||||||
@@ -27,10 +27,10 @@ export const webhookSchema = z.object({
|
|||||||
secret: z.string().optional(),
|
secret: z.string().optional(),
|
||||||
active: z.boolean().default(true),
|
active: z.boolean().default(true),
|
||||||
domain: z.string(),
|
domain: z.string(),
|
||||||
headers: z.record(z.string()).optional(),
|
headers: z.record(z.string(), z.string()).optional(),
|
||||||
retry_count: z.number().int().nonnegative().default(3),
|
retry_count: z.number().int().nonnegative().default(3),
|
||||||
last_triggered_at: z.string().datetime().optional(),
|
last_triggered_at: z.string().datetime().optional(),
|
||||||
custom_fields: z.record(z.unknown()).optional(),
|
custom_fields: z.record(z.string(), z.unknown()).optional(),
|
||||||
created: z.string().datetime(),
|
created: z.string().datetime(),
|
||||||
updated: z.string().datetime(),
|
updated: z.string().datetime(),
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user