From 99cc2fc1c4d1da4cc1260bb1c0af9a700467e68e Mon Sep 17 00:00:00 2001 From: le king fu Date: Mon, 2 Nov 2026 21:16:47 -0500 Subject: [PATCH] feat(web): show, add and remove task tags and filter by tag in the companion - web/src/lib/taskQueries.ts: list task query (existing filters + tags), subtasks, loadTaskTags (one query, live tags of the account only) and the account tags, shared by the list page and GET /api/lists/[id]/tasks. - ?tags= validated by zod (at most 20 UUIDs, count checked first); the tag filter joins sl_tags on the account and deleted_at IS NULL; 400 on a malformed value. - TaskItem: tag pills on tasks and subtasks; the detail view adds an existing tag and removes one through the task-tag API. - Sidebar: a click on a tag filters the current view by ?tags=, a second click removes it; FilterBar shows the active tag filter. - FR/EN strings. Refs #179 Refs #168 Co-Authored-By: Claude Opus 5.5 --- web/src/app/(app)/lists/[id]/page.tsx | 87 ++++------ web/src/app/api/lists/[id]/tasks/route.ts | 80 +++------ web/src/components/FilterBar.tsx | 28 +++- web/src/components/Sidebar.tsx | 69 ++++++-- web/src/components/TaskItem.tsx | 110 ++++++++++++- web/src/components/TaskList.tsx | 12 +- web/src/i18n/en.json | 14 +- web/src/i18n/fr.json | 14 +- web/src/lib/taskQueries.test.ts | 188 ++++++++++++++++++++++ web/src/lib/taskQueries.ts | 123 ++++++++++++++ web/src/lib/types.ts | 7 + web/src/lib/validators.test.ts | 40 ++++- web/src/lib/validators.ts | 20 +++ 13 files changed, 648 insertions(+), 144 deletions(-) create mode 100644 web/src/lib/taskQueries.test.ts create mode 100644 web/src/lib/taskQueries.ts diff --git a/web/src/app/(app)/lists/[id]/page.tsx b/web/src/app/(app)/lists/[id]/page.tsx index d4e93de..b4b2713 100644 --- a/web/src/app/(app)/lists/[id]/page.tsx +++ b/web/src/app/(app)/lists/[id]/page.tsx @@ -3,11 +3,17 @@ export const dynamic = "force-dynamic"; import { notFound, redirect } from "next/navigation"; import { getAuthenticatedUser } from "@/lib/auth"; import { db } from "@/db/client"; -import { slLists, slTasks } from "@/db/schema"; -import { eq, and, isNull, asc, desc } from "drizzle-orm"; +import { slLists } from "@/db/schema"; +import { eq, and, isNull } from "drizzle-orm"; import { TaskList } from "@/components/TaskList"; import type { Task } from "@/lib/types"; -import type { SQL } from "drizzle-orm"; +import { parseTagFilter } from "@/lib/validators"; +import { + queryListTasks, + loadSubtasks, + loadTaskTags, + loadAccountTags, +} from "@/lib/taskQueries"; export default async function ListPage({ params, @@ -37,70 +43,31 @@ export default async function ListPage({ if (!list) notFound(); - // Build conditions - const conditions: SQL[] = [ - eq(slTasks.listId, listId), - eq(slTasks.userId, userId), - isNull(slTasks.deletedAt), - isNull(slTasks.parentId), - ]; - const completed = typeof search.completed === "string" ? search.completed : undefined; - if (completed === "true" || completed === "false") { - conditions.push(eq(slTasks.completed, completed === "true")); - } + // A malformed ?tags= in the address bar shows the list unfiltered (the API + // answers 400 to the same value). + const tagFilter = parseTagFilter(typeof search.tags === "string" ? search.tags : undefined); - const sortBy = (typeof search.sortBy === "string" ? search.sortBy : "position") as string; - const sortOrder = (typeof search.sortOrder === "string" ? search.sortOrder : "asc") as string; + const tasks = await queryListTasks(userId, listId, { + completed: completed === "true" || completed === "false" ? completed === "true" : undefined, + tagIds: tagFilter.ok ? tagFilter.tagIds : null, + sortBy: typeof search.sortBy === "string" ? search.sortBy : "position", + sortOrder: typeof search.sortOrder === "string" ? search.sortOrder : "asc", + }); - const sortColumn = - sortBy === "priority" - ? slTasks.priority - : sortBy === "dueDate" - ? slTasks.dueDate - : sortBy === "createdAt" - ? slTasks.createdAt - : sortBy === "title" - ? slTasks.title - : slTasks.position; - - const orderFn = sortOrder === "desc" ? desc : asc; - - const tasks = await db - .select() - .from(slTasks) - .where(and(...conditions)) - .orderBy(orderFn(sortColumn)); - - // Fetch subtasks for all parent tasks - const parentIds = tasks.map((t) => t.id); - const subtasksMap: Record = {}; - - if (parentIds.length > 0) { - const allSubtasks = await db - .select() - .from(slTasks) - .where( - and( - eq(slTasks.userId, userId), - isNull(slTasks.deletedAt) - ) - ) - .orderBy(asc(slTasks.position)); - - const parentIdSet = new Set(parentIds); - for (const sub of allSubtasks) { - if (sub.parentId && parentIdSet.has(sub.parentId)) { - if (!subtasksMap[sub.parentId]) subtasksMap[sub.parentId] = []; - subtasksMap[sub.parentId].push(sub as Task); - } - } - } + const subtasksMap = await loadSubtasks(userId, tasks.map((t) => t.id)); + const subtaskIds = Object.values(subtasksMap).flat().map((s) => s.id); + const [tagsMap, accountTags] = await Promise.all([ + loadTaskTags(userId, [...tasks.map((t) => t.id), ...subtaskIds]), + loadAccountTags(userId), + ]); return ( } + tagsMap={tagsMap} + accountTags={accountTags} listId={listId} listName={list.name} /> diff --git a/web/src/app/api/lists/[id]/tasks/route.ts b/web/src/app/api/lists/[id]/tasks/route.ts index af319e4..290f003 100644 --- a/web/src/app/api/lists/[id]/tasks/route.ts +++ b/web/src/app/api/lists/[id]/tasks/route.ts @@ -1,9 +1,11 @@ import { NextRequest, NextResponse } from 'next/server'; import { db } from '@/db/client'; -import { slTasks, slLists, slTaskTags } from '@/db/schema'; -import { eq, and, isNull, asc, desc, inArray, SQL } from 'drizzle-orm'; +import { slLists } from '@/db/schema'; +import { eq, and } from 'drizzle-orm'; import { requireAuth } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; +import { parseTagFilter } from '@/lib/validators'; +import { queryListTasks } from '@/lib/taskQueries'; export async function GET( request: NextRequest, @@ -16,6 +18,15 @@ export async function GET( const { id: listId } = await params; + const url = request.nextUrl; + const completed = url.searchParams.get('completed'); + const priority = url.searchParams.get('priority'); + const dueDate = url.searchParams.get('dueDate'); + const tagFilter = parseTagFilter(url.searchParams.get('tags')); + if (!tagFilter.ok) { + return NextResponse.json({ error: 'Invalid tags' }, { status: 400 }); + } + // Verify list belongs to user const [list] = await db .select({ id: slLists.id }) @@ -26,63 +37,14 @@ export async function GET( return NextResponse.json({ error: 'List not found' }, { status: 404 }); } - const url = request.nextUrl; - const completed = url.searchParams.get('completed'); - const priority = url.searchParams.get('priority'); - const dueDate = url.searchParams.get('dueDate'); - const tags = url.searchParams.get('tags'); - const sortBy = url.searchParams.get('sortBy') || 'position'; - const sortOrder = url.searchParams.get('sortOrder') || 'asc'; - - const conditions: SQL[] = [ - eq(slTasks.listId, listId), - eq(slTasks.userId, auth.userId), - isNull(slTasks.deletedAt), - isNull(slTasks.parentId), - ]; - - if (completed !== null) { - conditions.push(eq(slTasks.completed, completed === 'true')); - } - if (priority !== null) { - conditions.push(eq(slTasks.priority, parseInt(priority, 10))); - } - - // Build query - const query = db - .select() - .from(slTasks) - .where(and(...conditions)); - - // Sort - const sortColumn = sortBy === 'priority' ? slTasks.priority - : sortBy === 'dueDate' ? slTasks.dueDate - : sortBy === 'createdAt' ? slTasks.createdAt - : sortBy === 'title' ? slTasks.title - : slTasks.position; - - const orderFn = sortOrder === 'desc' ? desc : asc; - const tasks = await query.orderBy(orderFn(sortColumn)); - - // Filter by tags if specified (post-query since it's a join table) - if (tags) { - const tagIds = tags.split(','); - const taskTagRows = await db - .select({ taskId: slTaskTags.taskId }) - .from(slTaskTags) - .where(inArray(slTaskTags.tagId, tagIds)); - - const taskIdsWithTags = new Set(taskTagRows.map((r) => r.taskId)); - return NextResponse.json(tasks.filter((t) => taskIdsWithTags.has(t.id))); - } - - // Filter by dueDate if specified (before/on that date) - if (dueDate) { - const cutoff = new Date(dueDate); - return NextResponse.json( - tasks.filter((t) => t.dueDate && t.dueDate <= cutoff) - ); - } + const tasks = await queryListTasks(auth.userId, listId, { + completed: completed !== null ? completed === 'true' : undefined, + priority: priority !== null ? parseInt(priority, 10) : undefined, + dueBefore: dueDate ? new Date(dueDate) : undefined, + tagIds: tagFilter.tagIds, + sortBy: url.searchParams.get('sortBy') || 'position', + sortOrder: url.searchParams.get('sortOrder') || 'asc', + }); return NextResponse.json(tasks); } diff --git a/web/src/components/FilterBar.tsx b/web/src/components/FilterBar.tsx index 77debd8..3e03891 100644 --- a/web/src/components/FilterBar.tsx +++ b/web/src/components/FilterBar.tsx @@ -1,10 +1,15 @@ "use client"; import { useRouter, useSearchParams, usePathname } from "next/navigation"; -import { Filter, ArrowUpDown } from "lucide-react"; +import { Filter, ArrowUpDown, Tag, X } from "lucide-react"; import { useTranslation } from "react-i18next"; +import type { TagPill } from "@/lib/types"; -export function FilterBar() { +interface FilterBarProps { + accountTags?: TagPill[]; +} + +export function FilterBar({ accountTags = [] }: FilterBarProps) { const { t } = useTranslation(); const router = useRouter(); const pathname = usePathname(); @@ -27,6 +32,11 @@ export function FilterBar() { const completed = searchParams.get("completed") ?? ""; const sortBy = searchParams.get("sortBy") ?? "position"; const sortOrder = searchParams.get("sortOrder") ?? "asc"; + // Tag filter set from the sidebar (one tag at a time, as on mobile). + const tagFilterId = searchParams.get("tags") ?? ""; + const tagFilter = accountTags.find((tag) => tag.id === tagFilterId); + // A filter on a tag that no longer exists still shows, so it can be removed. + const tagFilterName = tagFilter?.name ?? t("filter.unknownTag"); const updateParam = (key: string, value: string) => { const params = new URLSearchParams(searchParams.toString()); @@ -80,6 +90,20 @@ export function FilterBar() { {sortOrder === "asc" ? "↑" : "↓"} + + {/* Active tag filter */} + {tagFilterId && ( + + )} ); } diff --git a/web/src/components/Sidebar.tsx b/web/src/components/Sidebar.tsx index 4bae51c..fbf1aa8 100644 --- a/web/src/components/Sidebar.tsx +++ b/web/src/components/Sidebar.tsx @@ -1,8 +1,8 @@ "use client"; -import { useState } from "react"; +import { Suspense, useState } from "react"; import Link from "next/link"; -import { usePathname, useRouter } from "next/navigation"; +import { usePathname, useRouter, useSearchParams } from "next/navigation"; import { Inbox, Plus, @@ -16,6 +16,56 @@ import { import { useTranslation } from "react-i18next"; import type { List as ListType, Tag as TagType } from "@/lib/types"; +// Sidebar tags: a click filters the current view by `?tags=` (one tag at +// a time, as in src/components/FilterMenu.tsx of the app); a second click on +// the active tag removes the filter. +function SidebarTags({ tags, onNavigate }: { tags: TagType[]; onNavigate: () => void }) { + const { t } = useTranslation(); + const pathname = usePathname(); + const router = useRouter(); + const searchParams = useSearchParams(); + const activeTagId = searchParams.get("tags"); + + const toggleTag = (tagId: string) => { + const params = new URLSearchParams(searchParams.toString()); + if (activeTagId === tagId) { + params.delete("tags"); + } else { + params.set("tags", tagId); + } + const query = params.toString(); + router.push(query ? `${pathname}?${query}` : pathname); + onNavigate(); + }; + + return ( + <> + {tags.map((tag) => { + const isActive = activeTagId === tag.id; + const label = isActive + ? t("filter.clearTag", { name: tag.name }) + : t("sidebar.filterByTag", { name: tag.name }); + return ( + + ); + })} + + ); +} + interface SidebarProps { lists: ListType[]; tags: TagType[]; @@ -122,16 +172,11 @@ export function Sidebar({ lists, tags }: SidebarProps) { )} {t("sidebar.tags")} - {tagsExpanded && - tags.map((tag) => ( -
- - {tag.name} -
- ))} + {tagsExpanded && ( + + setMobileOpen(false)} /> + + )} diff --git a/web/src/components/TaskItem.tsx b/web/src/components/TaskItem.tsx index e4bac37..c5619f4 100644 --- a/web/src/components/TaskItem.tsx +++ b/web/src/components/TaskItem.tsx @@ -10,9 +10,10 @@ import { Repeat, Check, Search, + X, } from "lucide-react"; import { useTranslation } from "react-i18next"; -import type { Task } from "@/lib/types"; +import type { Task, TagPill } from "@/lib/types"; import { TaskForm } from "./TaskForm"; const PRIORITY_COLORS: Record = { @@ -31,13 +32,40 @@ function formatDate(dateStr: string | Date | null): string { }); } +// Tag pill: the tag name on its color, for tasks and subtasks alike. +function TagChip({ tag, onRemove, removeLabel }: { tag: TagPill; onRemove?: () => void; removeLabel?: string }) { + return ( + + {tag.name} + {onRemove && ( + + )} + + ); +} + interface TaskItemProps { task: Task; subtasks?: Task[]; depth?: number; + // Tags of this task and of its subtasks, by task id. + tagsMap?: Record; + // Live tags of the account, offered in the detail view. + accountTags?: TagPill[]; } -export function TaskItem({ task, subtasks = [], depth = 0 }: TaskItemProps) { +export function TaskItem({ task, subtasks = [], depth = 0, tagsMap = {}, accountTags = [] }: TaskItemProps) { const { t } = useTranslation(); const router = useRouter(); const [expanded, setExpanded] = useState(false); @@ -52,6 +80,11 @@ export function TaskItem({ task, subtasks = [], depth = 0 }: TaskItemProps) { const [recurrence, setRecurrence] = useState(task.recurrence || ""); const [showSubtaskForm, setShowSubtaskForm] = useState(false); const [saving, setSaving] = useState(false); + const [tagBusy, setTagBusy] = useState(false); + + const taskTags = tagsMap[task.id] ?? []; + const assignedIds = new Set(taskTags.map((tag) => tag.id)); + const availableTags = accountTags.filter((tag) => !assignedIds.has(tag.id)); const PRIORITY_LABELS: Record = { 0: t("priority.none"), @@ -113,6 +146,33 @@ export function TaskItem({ task, subtasks = [], depth = 0 }: TaskItemProps) { } }; + // Add or remove an existing tag through the task-tag API, then reload. + const addTag = async (tagId: string) => { + if (!tagId || tagBusy) return; + setTagBusy(true); + try { + await fetch(`/api/tasks/${task.id}/tags`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ tagIds: [tagId] }), + }); + router.refresh(); + } finally { + setTagBusy(false); + } + }; + + const removeTag = async (tagId: string) => { + if (tagBusy) return; + setTagBusy(true); + try { + await fetch(`/api/tasks/${task.id}/tags/${tagId}`, { method: "DELETE" }); + router.refresh(); + } finally { + setTagBusy(false); + } + }; + const deleteTask = async () => { await fetch(`/api/tasks/${task.id}`, { method: "DELETE" }); router.refresh(); @@ -168,6 +228,13 @@ export function TaskItem({ task, subtasks = [], depth = 0 }: TaskItemProps) { {/* Badges */} + {taskTags.length > 0 && ( + + {taskTags.map((tag) => ( + + ))} + + )} {task.dueDate && ( @@ -274,6 +341,37 @@ export function TaskItem({ task, subtasks = [], depth = 0 }: TaskItemProps) { {t("task.recurrenceLabel", { value: RECURRENCE_LABELS[task.recurrence] || task.recurrence })} )} + {/* Tags: remove an assigned tag, add an existing one */} +
+ {t("tag.label")} + {taskTags.length === 0 && ( + {t("tag.none")} + )} + {taskTags.map((tag) => ( + removeTag(tag.id)} + removeLabel={t("tag.remove", { name: tag.name })} + /> + ))} + {availableTags.length > 0 && ( + + )} +
); diff --git a/web/src/components/TaskList.tsx b/web/src/components/TaskList.tsx index 310d5e7..cd135ff 100644 --- a/web/src/components/TaskList.tsx +++ b/web/src/components/TaskList.tsx @@ -1,6 +1,6 @@ "use client"; -import type { Task } from "@/lib/types"; +import type { Task, TagPill } from "@/lib/types"; import { TaskItem } from "./TaskItem"; import { TaskForm } from "./TaskForm"; import { FilterBar } from "./FilterBar"; @@ -12,11 +12,15 @@ import { useTranslation } from "react-i18next"; interface TaskListProps { tasks: Task[]; subtasksMap: Record; + // Tags of every task and subtask shown, by task id. + tagsMap: Record; + // Live tags of the account, for the tag picker and the active filter. + accountTags: TagPill[]; listId: string; listName: string; } -export function TaskList({ tasks, subtasksMap, listId, listName }: TaskListProps) { +export function TaskList({ tasks, subtasksMap, tagsMap, accountTags, listId, listName }: TaskListProps) { const { t } = useTranslation(); const router = useRouter(); const [refreshing, setRefreshing] = useState(false); @@ -44,7 +48,7 @@ export function TaskList({ tasks, subtasksMap, listId, listName }: TaskListProps - + @@ -66,6 +70,8 @@ export function TaskList({ tasks, subtasksMap, listId, listName }: TaskListProps key={task.id} task={task} subtasks={subtasksMap[task.id] || []} + tagsMap={tagsMap} + accountTags={accountTags} /> ))} diff --git a/web/src/i18n/en.json b/web/src/i18n/en.json index 857b386..2fb5887 100644 --- a/web/src/i18n/en.json +++ b/web/src/i18n/en.json @@ -12,7 +12,8 @@ "lists": "Lists", "tags": "Tags", "newList": "New list", - "newListPlaceholder": "List name..." + "newListPlaceholder": "List name...", + "filterByTag": "Filter by {{name}}" }, "task": { "add": "Add a task", @@ -32,6 +33,12 @@ "dueDate": "Due: {{value}}", "recurrenceLabel": "Recurrence: {{value}}" }, + "tag": { + "label": "Tags:", + "none": "None", + "add": "+ Tag", + "remove": "Remove tag {{name}}" + }, "priority": { "none": "None", "noneExplicit": "No priority", @@ -49,7 +56,10 @@ "filter": { "all": "All", "active": "Active", - "completed": "Completed" + "completed": "Completed", + "tag": "Tag: {{name}}", + "clearTag": "Remove filter {{name}}", + "unknownTag": "not found" }, "sort": { "position": "Position", diff --git a/web/src/i18n/fr.json b/web/src/i18n/fr.json index 4e659c0..6cfebff 100644 --- a/web/src/i18n/fr.json +++ b/web/src/i18n/fr.json @@ -12,7 +12,8 @@ "lists": "Listes", "tags": "Étiquettes", "newList": "Nouvelle liste", - "newListPlaceholder": "Nom de la liste..." + "newListPlaceholder": "Nom de la liste...", + "filterByTag": "Filtrer par {{name}}" }, "task": { "add": "Ajouter une tâche", @@ -32,6 +33,12 @@ "dueDate": "Échéance : {{value}}", "recurrenceLabel": "Récurrence : {{value}}" }, + "tag": { + "label": "Étiquettes :", + "none": "Aucune", + "add": "+ Étiquette", + "remove": "Retirer l'étiquette {{name}}" + }, "priority": { "none": "Aucune", "noneExplicit": "Aucune priorité", @@ -49,7 +56,10 @@ "filter": { "all": "Toutes", "active": "Actives", - "completed": "Complétées" + "completed": "Complétées", + "tag": "Étiquette : {{name}}", + "clearTag": "Retirer le filtre {{name}}", + "unknownTag": "introuvable" }, "sort": { "position": "Position", diff --git a/web/src/lib/taskQueries.test.ts b/web/src/lib/taskQueries.test.ts new file mode 100644 index 0000000..fc85fc0 --- /dev/null +++ b/web/src/lib/taskQueries.test.ts @@ -0,0 +1,188 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { randomUUID as u } from 'node:crypto'; +import { describe, it, expect, beforeAll, vi } from 'vitest'; +import type { PGlite } from 'electric-sql-pglite'; + +// Task reads of the list page and of GET /api/lists/[id]/tasks (#179), against +// an in-memory Postgres (PGlite) with the companion migrations, as in +// web/src/app/api/sync/route.test.ts. Auth and rate limiting are stubbed. + +const h = await vi.hoisted(async () => { + const { PGlite } = await import('electric-sql-pglite'); + return { pg: new PGlite() as PGlite, userId: '' }; +}); + +vi.mock('@/db/client', async () => { + const { drizzle } = await import('drizzle-orm/pglite'); + const schema = await import('@/db/schema'); + return { db: drizzle(h.pg, { schema }) }; +}); + +vi.mock('@/lib/auth', () => ({ getAuthenticatedUser: async () => null })); +vi.mock('@/lib/api', async (importOriginal) => ({ + ...(await importOriginal()), + requireAuth: async () => ({ userId: h.userId }), +})); +vi.mock('@/lib/rateLimit', () => ({ rateLimit: () => null })); + +const { loadTaskTags, queryListTasks, loadSubtasks } = await import('./taskQueries'); +const { GET } = await import('@/app/api/lists/[id]/tasks/route'); +const { NextRequest } = await import('next/server'); + +beforeAll(async () => { + const dir = path.join(__dirname, '../db/migrations'); + for (const f of fs.readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()) { + for (const stmt of fs.readFileSync(path.join(dir, f), 'utf8').split('--> statement-breakpoint')) { + if (stmt.trim()) await h.pg.exec(stmt); + } + } +}); + +async function exec(sql: string, params: unknown[]) { + await h.pg.query(sql, params); +} + +// One account: a list, three tasks (one with a subtask), and tags. +async function seedAccount() { + const a = { + userId: `user-${u()}`, list: u(), + t1: u(), t2: u(), t3: u(), sub: u(), + red: u(), blue: u(), gone: u(), + }; + await exec('INSERT INTO sl_lists (id, user_id, name) VALUES ($1, $2, $3)', [a.list, a.userId, 'L']); + for (const [id, title, pos] of [[a.t1, 't1', 0], [a.t2, 't2', 1], [a.t3, 't3', 2]] as const) { + await exec('INSERT INTO sl_tasks (id, user_id, title, list_id, position) VALUES ($1, $2, $3, $4, $5)', [id, a.userId, title, a.list, pos]); + } + await exec('INSERT INTO sl_tasks (id, user_id, title, list_id, parent_id) VALUES ($1, $2, $3, $4, $5)', [a.sub, a.userId, 'sub', a.list, a.t1]); + await exec('INSERT INTO sl_tags (id, user_id, name, color) VALUES ($1, $2, $3, $4)', [a.red, a.userId, 'red', '#E57373']); + await exec('INSERT INTO sl_tags (id, user_id, name, color) VALUES ($1, $2, $3, $4)', [a.blue, a.userId, 'blue', '#4A90A4']); + await exec('INSERT INTO sl_tags (id, user_id, name, deleted_at) VALUES ($1, $2, $3, now())', [a.gone, a.userId, 'gone']); + const links: [string, string][] = [[a.t1, a.red], [a.t1, a.blue], [a.t2, a.blue], [a.t3, a.gone], [a.sub, a.red]]; + for (const [taskId, tagId] of links) { + await exec('INSERT INTO sl_task_tags (task_id, tag_id) VALUES ($1, $2)', [taskId, tagId]); + } + return a; +} + +// A tag of another account linked to a task of `a`: rows the sync can never +// produce (it checks the tag owner), but the reads must not trust that. +async function foreignTagOn(taskId: string) { + const other = { userId: `user-${u()}`, tag: u() }; + await exec('INSERT INTO sl_tags (id, user_id, name) VALUES ($1, $2, $3)', [other.tag, other.userId, 'foreign']); + await exec('INSERT INTO sl_task_tags (task_id, tag_id) VALUES ($1, $2)', [taskId, other.tag]); + return other; +} + +async function getTasks(userId: string, listId: string, query: string) { + h.userId = userId; + const req = new NextRequest(`http://localhost/api/lists/${listId}/tasks${query}`); + return GET(req, { params: Promise.resolve({ id: listId }) }); +} + +describe('loadTaskTags', () => { + it('loads the tags of N tasks in a single query', async () => { + const a = await seedAccount(); + const spy = vi.spyOn(h.pg, 'query'); + const map = await loadTaskTags(a.userId, [a.t1, a.t2, a.t3, a.sub]); + expect(spy).toHaveBeenCalledTimes(1); + spy.mockRestore(); + expect(map[a.t1].map((t) => t.name)).toEqual(['blue', 'red']); + expect(map[a.t2]).toEqual([{ id: a.blue, name: 'blue', color: '#4A90A4' }]); + expect(map[a.sub].map((t) => t.id)).toEqual([a.red]); + }); + + it('runs no query for no task', async () => { + const spy = vi.spyOn(h.pg, 'query'); + expect(await loadTaskTags('user-x', [])).toEqual({}); + expect(spy).not.toHaveBeenCalled(); + spy.mockRestore(); + }); + + it('never returns a deleted tag', async () => { + const a = await seedAccount(); + const map = await loadTaskTags(a.userId, [a.t1, a.t2, a.t3]); + expect(map[a.t3]).toBeUndefined(); + expect(Object.values(map).flat().some((t) => t.id === a.gone)).toBe(false); + }); + + it('never returns a tag of another account', async () => { + const a = await seedAccount(); + const other = await foreignTagOn(a.t2); + const map = await loadTaskTags(a.userId, [a.t1, a.t2]); + expect(map[a.t2].map((t) => t.id)).toEqual([a.blue]); + // Nor are the tags of `a` returned to the other account. + expect(await loadTaskTags(other.userId, [a.t1, a.t2])).toEqual({ [a.t2]: [{ id: other.tag, name: 'foreign', color: '#4A90A4' }] }); + }); +}); + +describe('queryListTasks', () => { + it('filters by a live tag of the account', async () => { + const a = await seedAccount(); + expect((await queryListTasks(a.userId, a.list, { tagIds: [a.red] })).map((t) => t.id)).toEqual([a.t1]); + expect((await queryListTasks(a.userId, a.list, { tagIds: [a.blue] })).map((t) => t.id)).toEqual([a.t1, a.t2]); + }); + + it('matches nothing on a deleted tag', async () => { + const a = await seedAccount(); + expect(await queryListTasks(a.userId, a.list, { tagIds: [a.gone] })).toEqual([]); + }); + + it('returns every top-level task without a tag filter', async () => { + const a = await seedAccount(); + expect((await queryListTasks(a.userId, a.list, { tagIds: null })).map((t) => t.id)).toEqual([a.t1, a.t2, a.t3]); + }); +}); + +describe('loadSubtasks', () => { + it('groups the live subtasks of the account by parent', async () => { + const a = await seedAccount(); + const map = await loadSubtasks(a.userId, [a.t1, a.t2]); + expect(Object.keys(map)).toEqual([a.t1]); + expect(map[a.t1].map((t) => t.id)).toEqual([a.sub]); + expect(await loadSubtasks(`user-${u()}`, [a.t1])).toEqual({}); + }); +}); + +describe('GET /api/lists/[id]/tasks?tags=', () => { + it('filters by a tag of the account', async () => { + const a = await seedAccount(); + const res = await getTasks(a.userId, a.list, `?tags=${a.red}`); + expect(res.status).toBe(200); + expect((await res.json() as { id: string }[]).map((t) => t.id)).toEqual([a.t1]); + }); + + it('returns an empty list for a tag of another account', async () => { + const a = await seedAccount(); + const other = await foreignTagOn(a.t2); + const res = await getTasks(a.userId, a.list, `?tags=${other.tag}`); + expect(res.status).toBe(200); + expect(await res.json()).toEqual([]); + }); + + it('answers 400 to a malformed id', async () => { + const a = await seedAccount(); + const res = await getTasks(a.userId, a.list, '?tags=pas-un-uuid'); + expect(res.status).toBe(400); + }); + + it('answers 400 to 21 ids and 200 to 20', async () => { + const a = await seedAccount(); + const ids = (n: number) => Array.from({ length: n }, () => u()).join(','); + expect((await getTasks(a.userId, a.list, `?tags=${ids(21)}`)).status).toBe(400); + expect((await getTasks(a.userId, a.list, `?tags=${ids(20)}`)).status).toBe(200); + }); + + it('keeps the other filters with a tag filter', async () => { + const a = await seedAccount(); + await exec('UPDATE sl_tasks SET completed = true WHERE id = $1', [a.t1]); + const res = await getTasks(a.userId, a.list, `?tags=${a.blue}&completed=false`); + expect((await res.json() as { id: string }[]).map((t) => t.id)).toEqual([a.t2]); + }); + + it('still answers 404 for a list of another account', async () => { + const a = await seedAccount(); + const res = await getTasks(`user-${u()}`, a.list, ''); + expect(res.status).toBe(404); + }); +}); diff --git a/web/src/lib/taskQueries.ts b/web/src/lib/taskQueries.ts new file mode 100644 index 0000000..a6d9bd6 --- /dev/null +++ b/web/src/lib/taskQueries.ts @@ -0,0 +1,123 @@ +// Task reads shared by the list page (web/src/app/(app)/lists/[id]/page.tsx) +// and GET /api/lists/[id]/tasks (#179). Every query is scoped to the account: +// tasks by sl_tasks.user_id, tags by sl_tags.user_id and deleted_at IS NULL. + +import { db } from '@/db/client'; +import { slTasks, slTags, slTaskTags } from '@/db/schema'; +import { eq, and, isNull, asc, desc, inArray, lte, type SQL } from 'drizzle-orm'; +import type { TagPill } from './types'; + +export interface ListTaskFilters { + completed?: boolean; + priority?: number; + // Tasks due on or before this date. + dueBefore?: Date; + // Tasks carrying at least one of these tags (ids already validated). + tagIds?: string[] | null; + sortBy?: string; + sortOrder?: string; +} + +export type TaskTagPill = TagPill; + +function sortColumn(sortBy: string | undefined) { + switch (sortBy) { + case 'priority': return slTasks.priority; + case 'dueDate': return slTasks.dueDate; + case 'createdAt': return slTasks.createdAt; + case 'title': return slTasks.title; + default: return slTasks.position; + } +} + +// Top-level tasks of a list, filtered and sorted. The caller has checked that +// the list belongs to the account. +export async function queryListTasks(userId: string, listId: string, filters: ListTaskFilters = {}) { + const conditions: SQL[] = [ + eq(slTasks.listId, listId), + eq(slTasks.userId, userId), + isNull(slTasks.deletedAt), + isNull(slTasks.parentId), + ]; + + if (filters.completed !== undefined) { + conditions.push(eq(slTasks.completed, filters.completed)); + } + if (filters.priority !== undefined && Number.isInteger(filters.priority)) { + conditions.push(eq(slTasks.priority, filters.priority)); + } + if (filters.dueBefore && !Number.isNaN(filters.dueBefore.getTime())) { + conditions.push(lte(slTasks.dueDate, filters.dueBefore)); + } + if (filters.tagIds && filters.tagIds.length > 0) { + // Only a live tag of this account can select a task: an id from another + // account, or a deleted tag, matches nothing. + const tagged = db + .select({ taskId: slTaskTags.taskId }) + .from(slTaskTags) + .innerJoin(slTags, eq(slTags.id, slTaskTags.tagId)) + .where(and( + inArray(slTaskTags.tagId, filters.tagIds), + eq(slTags.userId, userId), + isNull(slTags.deletedAt), + )); + conditions.push(inArray(slTasks.id, tagged)); + } + + const orderFn = filters.sortOrder === 'desc' ? desc : asc; + return db + .select() + .from(slTasks) + .where(and(...conditions)) + .orderBy(orderFn(sortColumn(filters.sortBy))); +} + +// Live subtasks of the given parents, grouped by parent id. +export async function loadSubtasks(userId: string, parentIds: string[]) { + const map: Record = {}; + if (parentIds.length === 0) return map; + const rows = await db + .select() + .from(slTasks) + .where(and( + eq(slTasks.userId, userId), + isNull(slTasks.deletedAt), + inArray(slTasks.parentId, parentIds), + )) + .orderBy(asc(slTasks.position)); + for (const row of rows) { + if (!row.parentId) continue; + (map[row.parentId] ??= []).push(row); + } + return map; +} + +// Tags of the given tasks, grouped by task id, in one query. Deleted tags and +// tags of another account never appear. +export async function loadTaskTags(userId: string, taskIds: string[]) { + const map: Record = {}; + if (taskIds.length === 0) return map; + const rows = await db + .select({ taskId: slTaskTags.taskId, id: slTags.id, name: slTags.name, color: slTags.color }) + .from(slTaskTags) + .innerJoin(slTags, eq(slTags.id, slTaskTags.tagId)) + .where(and( + inArray(slTaskTags.taskId, taskIds), + eq(slTags.userId, userId), + isNull(slTags.deletedAt), + )) + .orderBy(asc(slTags.name)); + for (const { taskId, ...tag } of rows) { + (map[taskId] ??= []).push(tag); + } + return map; +} + +// Live tags of the account, by name (tag picker of a task). +export async function loadAccountTags(userId: string): Promise { + return db + .select({ id: slTags.id, name: slTags.name, color: slTags.color }) + .from(slTags) + .where(and(eq(slTags.userId, userId), isNull(slTags.deletedAt))) + .orderBy(asc(slTags.name)); +} diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts index c44b140..d0a079e 100644 --- a/web/src/lib/types.ts +++ b/web/src/lib/types.ts @@ -39,3 +39,10 @@ export interface Tag { createdAt: Date | string; deletedAt: Date | string | null; } + +// A tag as shown on a task (pill) and in the tag picker. +export interface TagPill { + id: string; + name: string; + color: string; +} diff --git a/web/src/lib/validators.test.ts b/web/src/lib/validators.test.ts index 1bad621..7352680 100644 --- a/web/src/lib/validators.test.ts +++ b/web/src/lib/validators.test.ts @@ -1,6 +1,6 @@ import { randomUUID as u } from 'node:crypto'; import { describe, it, expect } from 'vitest'; -import { syncPushSchema, reorderSchema, assignTagsSchema, SYNC_MAX_OPERATIONS } from './validators'; +import { syncPushSchema, reorderSchema, assignTagsSchema, SYNC_MAX_OPERATIONS, tagFilterSchema, parseTagFilter, TAG_FILTER_MAX } from './validators'; // Length bounds checked before the elements (#147). @@ -81,3 +81,41 @@ describe('assignTagsSchema', () => { expect(assignTagsSchema.safeParse({ tagIds: Array.from({ length: 100 }, () => u()) }).success).toBe(true); }); }); + +describe('tagFilterSchema / parseTagFilter (#179)', () => { + it('bounds the filter at 20 tags', () => { + expect(TAG_FILTER_MAX).toBe(20); + }); + + it('accepts 20 ids and refuses 21 with a single issue', () => { + expect(tagFilterSchema.safeParse(Array.from({ length: 20 }, () => u())).success).toBe(true); + const r = tagFilterSchema.safeParse(Array.from({ length: 21 }, () => u())); + expect(r.success).toBe(false); + expect(r.error!.issues).toHaveLength(1); + expect(r.error!.issues[0].code).toBe('too_big'); + }); + + it('checks the count before the ids: 10000 invalid ids give one issue', () => { + const r = tagFilterSchema.safeParse(Array.from({ length: 10_000 }, () => 'x')); + expect(r.success).toBe(false); + expect(r.error!.issues).toHaveLength(1); + }); + + it('treats an absent or empty value as no filter', () => { + expect(parseTagFilter(null)).toEqual({ ok: true, tagIds: null }); + expect(parseTagFilter(undefined)).toEqual({ ok: true, tagIds: null }); + expect(parseTagFilter('')).toEqual({ ok: true, tagIds: null }); + }); + + it('splits comma-separated ids', () => { + const a = u(); + const b = u(); + expect(parseTagFilter(`${a},${b}`)).toEqual({ ok: true, tagIds: [a, b] }); + }); + + it('refuses a malformed id, an empty element and 21 ids', () => { + expect(parseTagFilter('pas-un-uuid').ok).toBe(false); + expect(parseTagFilter(`${u()},`).ok).toBe(false); + expect(parseTagFilter(Array.from({ length: 21 }, () => u()).join(',')).ok).toBe(false); + }); +}); diff --git a/web/src/lib/validators.ts b/web/src/lib/validators.ts index 02f148b..aab19b0 100644 --- a/web/src/lib/validators.ts +++ b/web/src/lib/validators.ts @@ -60,6 +60,26 @@ export const assignTagsSchema = z.object({ tagIds: z.array(z.unknown()).min(1).max(100).pipe(z.array(z.string().uuid())), }).strict(); +// Tag filter of GET /api/lists/[id]/tasks and of the list page (`?tags=a,b`). +// Same bound-first pattern: the count is checked before each id is parsed. +export const TAG_FILTER_MAX = 20; + +export const tagFilterSchema = z + .array(z.unknown()) + .min(1) + .max(TAG_FILTER_MAX) + .pipe(z.array(z.string().uuid())); + +// `?tags=` absent or empty: no filter (null). Otherwise the comma-separated +// ids, validated by tagFilterSchema. +export function parseTagFilter( + raw: string | null | undefined, +): { ok: true; tagIds: string[] | null } | { ok: false } { + if (raw === null || raw === undefined || raw === '') return { ok: true, tagIds: null }; + const r = tagFilterSchema.safeParse(raw.split(',')); + return r.success ? { ok: true, tagIds: r.data } : { ok: false }; +} + // Sync // Maximum operations in one POST /api/sync. The app sends batches of 50