feat: mark list items as bought on tap and record boughtAt

Tapping an item in the list toggles it via a new
PATCH /lists/:listId/items/:itemId endpoint. Marking an item as bought
stores boughtAt (for future stats) and clearing it back to pending
resets the timestamp. The web app updates optimistically and each row is
now a real button with aria-pressed.
This commit is contained in:
Jose Selesan
2026-10-16 10:44:23 -03:00
parent 6aa86a3b68
commit c4f6b8bc85
11 changed files with 315 additions and 31 deletions

View File

@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "list_items" ADD COLUMN "bought_at" TIMESTAMP(3);

View File

@@ -110,15 +110,16 @@ model ShoppingList {
}
model ListItem {
id String @id @default(cuid())
shoppingListId String @map("shopping_list_id")
id String @id @default(cuid())
shoppingListId String @map("shopping_list_id")
name String
completed Boolean @default(false)
quantity String? @map("quantity")
notes String? @map("notes")
order Int @default(0) @map("order")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
completed Boolean @default(false)
boughtAt DateTime? @map("bought_at")
quantity String? @map("quantity")
notes String? @map("notes")
order Int @default(0) @map("order")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
shoppingList ShoppingList @relation(fields: [shoppingListId], references: [id], onDelete: Cascade)

View File

@@ -4,8 +4,10 @@ import type { AppEnv } from '@/types'
import { createItemRoute } from './create/route'
import { listItemsRoute } from './list/route'
import { updateItemRoute } from './update/route'
/** `items` sub-module of `lists`: mounted at `/lists/:listId/items`. */
export const listItemsModule = new Hono<AppEnv>()
.route('/', listItemsRoute)
.route('/', createItemRoute)
.route('/', updateItemRoute)

View File

@@ -5,6 +5,7 @@ type ItemRow = {
shoppingListId: string
name: string
completed: boolean
boughtAt: Date | null
quantity: string | null
notes: string | null
order: number
@@ -19,6 +20,7 @@ export function toListItem(item: ItemRow): ListItem {
listId: item.shoppingListId,
name: item.name,
completed: item.completed,
boughtAt: item.boughtAt?.toISOString() ?? null,
quantity: item.quantity,
notes: item.notes,
order: item.order,

View File

@@ -0,0 +1,30 @@
import { Hono } from 'hono'
import { requireSession } from '@/lib/auth-session'
import { prisma } from '@/lib/prisma'
import { resultJson } from '@/lib/result-json'
import { validate } from '@/lib/validate'
import type { AppEnv } from '@/types'
import { ItemParamsSchema, UpdateItemSchema } from './schema'
import { UpdateItem } from './use-case'
/** PATCH /lists/:listId/items/:itemId — marks an item as bought or pending. */
export const updateItemRoute = new Hono<AppEnv>().patch(
'/:itemId',
requireSession,
validate.param(ItemParamsSchema),
validate.json(UpdateItemSchema),
async (c) => {
const { listId, itemId } = c.req.valid('param')
const { completed } = c.req.valid('json')
const result = await new UpdateItem(prisma).execute({
listId,
itemId,
userId: c.get('user').id,
completed,
})
return resultJson(c, result)
},
)

View File

@@ -0,0 +1,16 @@
import { z } from 'zod'
/** Path params of `PATCH /lists/:listId/items/:itemId`. */
export const ItemParamsSchema = z.object({
listId: z.uuid('El identificador de la lista no es válido'),
itemId: z.string().min(1, 'El identificador del artículo no es válido'),
})
export type ItemParams = z.infer<typeof ItemParamsSchema>
/** Body of `PATCH /lists/:listId/items/:itemId`. */
export const UpdateItemSchema = z.object({
completed: z.boolean(),
})
export type UpdateItemInput = z.infer<typeof UpdateItemSchema>

View File

@@ -0,0 +1,131 @@
import { describe, expect, it } from 'bun:test'
import type { Database } from '@/lib/prisma'
import { UpdateItem } from './use-case'
type ItemRow = {
id: string
shoppingListId: string
name: string
completed: boolean
boughtAt: Date | null
quantity: string | null
notes: string | null
order: number
createdAt: Date
updatedAt: Date
}
const now = new Date('2026-10-16T10:00:00.000Z')
function itemRow(completed: boolean, boughtAt: Date | null): ItemRow {
return {
id: 'item-1',
shoppingListId: 'list-1',
name: 'Leche',
completed,
boughtAt,
quantity: '1 L',
notes: null,
order: 0,
createdAt: now,
updatedAt: now,
}
}
function createDb(options: { membership: unknown; item: ItemRow | null }) {
const updates: unknown[] = []
const db = {
shoppingListMember: {
findUnique: async () => options.membership,
},
listItem: {
findFirst: async () => options.item,
update: async (args: { data: { completed: boolean; boughtAt: Date | null } }) => {
updates.push(args)
return itemRow(args.data.completed, args.data.boughtAt)
},
},
}
return { db: db as unknown as Database, updates }
}
describe('UpdateItem', () => {
it('answers 404 when the user does not belong to the list', async () => {
const { db, updates } = createDb({ membership: null, item: itemRow(false, null) })
const result = await new UpdateItem(db).execute({
listId: 'list-1',
itemId: 'item-1',
userId: 'user-1',
completed: true,
})
expect(result.ok).toBe(false)
if (result.ok) throw new Error('expected the use case to fail')
expect(result.error.status).toBe(404)
expect(updates).toHaveLength(0)
})
it('answers 404 when the item does not belong to the list', async () => {
const { db, updates } = createDb({ membership: { role: 'owner' }, item: null })
const result = await new UpdateItem(db).execute({
listId: 'list-1',
itemId: 'item-of-another-list',
userId: 'user-1',
completed: true,
})
expect(result.ok).toBe(false)
if (result.ok) throw new Error('expected the use case to fail')
expect(result.error.status).toBe(404)
expect(updates).toHaveLength(0)
})
it('marks the item as bought and records boughtAt', async () => {
const { db, updates } = createDb({ membership: { role: 'owner' }, item: itemRow(false, null) })
const result = await new UpdateItem(db).execute({
listId: 'list-1',
itemId: 'item-1',
userId: 'user-1',
completed: true,
})
expect(result.ok).toBe(true)
if (!result.ok) throw new Error('expected the use case to succeed')
expect(updates).toHaveLength(1)
const data = updates[0] as { data: { completed: boolean; boughtAt: Date | null } }
expect(data.data.completed).toBe(true)
expect(data.data.boughtAt).toBeInstanceOf(Date)
expect(result.value.completed).toBe(true)
expect(result.value.boughtAt).toBe(data.data.boughtAt?.toISOString() ?? null)
})
it('marks the item back to pending and clears boughtAt', async () => {
const { db, updates } = createDb({
membership: { role: 'collaborator' },
item: itemRow(true, new Date('2026-10-15T12:00:00.000Z')),
})
const result = await new UpdateItem(db).execute({
listId: 'list-1',
itemId: 'item-1',
userId: 'user-1',
completed: false,
})
expect(result.ok).toBe(true)
if (!result.ok) throw new Error('expected the use case to succeed')
expect(updates).toHaveLength(1)
const data = updates[0] as { data: { completed: boolean; boughtAt: Date | null } }
expect(data.data.completed).toBe(false)
expect(data.data.boughtAt).toBeNull()
expect(result.value.completed).toBe(false)
expect(result.value.boughtAt).toBeNull()
})
})

View File

@@ -0,0 +1,54 @@
import {
Failure,
type ListItem,
Ok,
type ProblemDetails,
problems,
type Result,
} from '@superlist/shared'
import type { Database } from '@/lib/prisma'
import { toListItem } from '../serialize'
/**
* Marks an item as bought (or back to pending). Only members can do it.
* `boughtAt` records the moment it was marked as bought, for future
* statistics, and is cleared when the item goes back to pending.
*/
export class UpdateItem {
constructor(private readonly db: Database) {}
async execute(input: {
listId: string
itemId: string
userId: string
completed: boolean
}): Promise<Result<ListItem, ProblemDetails>> {
const membership = await this.db.shoppingListMember.findUnique({
where: { listId_userId: { listId: input.listId, userId: input.userId } },
})
if (!membership) {
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
}
const item = await this.db.listItem.findFirst({
where: { id: input.itemId, shoppingListId: input.listId },
})
if (!item) {
return Failure(problems.notFound('El artículo no existe en esta lista.'))
}
const updated = await this.db.listItem.update({
where: { id: item.id },
data: {
completed: input.completed,
boughtAt: input.completed ? new Date() : null,
},
})
return Ok(toListItem(updated))
}
}

View File

@@ -3,7 +3,7 @@ import { CheckIcon, ShoppingBasketIcon } from 'lucide-react'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Card, CardContent } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { useItems } from '@/hooks/use-items'
import { useItems, useUpdateItem } from '@/hooks/use-items'
import { ApiError } from '@/lib/api-client'
import { cn } from '@/lib/utils'
@@ -11,9 +11,10 @@ type ItemListProps = {
listId: string
}
/** Items loaded from the API, pending ones first. */
/** Items loaded from the API, pending ones first. Tapping an item marks it as bought. */
export function ItemList({ listId }: ItemListProps) {
const { data: items, isPending, error } = useItems(listId)
const updateItem = useUpdateItem(listId)
if (error) {
return (
@@ -61,29 +62,37 @@ export function ItemList({ listId }: ItemListProps) {
{items.map((item) => (
<li key={item.id}>
<Card>
<CardContent className="flex items-center gap-3 p-3">
<span
className={cn(
'flex size-5 shrink-0 items-center justify-center rounded-full border',
item.completed
? 'bg-primary text-primary-foreground border-primary'
: 'border-muted-foreground/40 text-transparent',
)}
aria-hidden
<CardContent className="p-0">
<button
type="button"
aria-pressed={item.completed}
disabled={updateItem.isPending}
onClick={() => updateItem.mutate({ itemId: item.id, completed: !item.completed })}
className="flex w-full cursor-pointer items-center gap-3 p-3 text-left disabled:cursor-default disabled:opacity-60"
>
<CheckIcon className="size-3" />
</span>
<span
className={cn(
'min-w-0 flex-1 truncate',
item.completed && 'text-muted-foreground line-through',
<span
className={cn(
'flex size-5 shrink-0 items-center justify-center rounded-full border',
item.completed
? 'bg-primary text-primary-foreground border-primary'
: 'border-muted-foreground/40 text-transparent',
)}
aria-hidden
>
<CheckIcon className="size-3" />
</span>
<span
className={cn(
'min-w-0 flex-1 truncate',
item.completed && 'text-muted-foreground line-through',
)}
>
{item.name}
</span>
{item.quantity && (
<span className="text-muted-foreground shrink-0 text-sm">{item.quantity}</span>
)}
>
{item.name}
</span>
{item.quantity && (
<span className="text-muted-foreground shrink-0 text-sm">{item.quantity}</span>
)}
</button>
</CardContent>
</Card>
</li>

View File

@@ -25,3 +25,38 @@ export function useCreateItem(listId: string) {
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] }),
})
}
export function useUpdateItem(listId: string) {
const queryClient = useQueryClient()
const queryKey = ['lists', listId, 'items']
return useMutation({
mutationFn: (input: { itemId: string; completed: boolean }) =>
apiFetch<ListItem>(`/lists/${listId}/items/${input.itemId}`, {
method: 'PATCH',
body: JSON.stringify({ completed: input.completed }),
}),
onMutate: async ({ itemId, completed }) => {
// Cancel the outgoing refetch so it cannot overwrite our optimistic one.
await queryClient.cancelQueries({ queryKey })
const previous = queryClient.getQueriesData<ListItem[]>({ queryKey })
queryClient.setQueriesData<ListItem[]>({ queryKey }, (items) =>
items?.map((item) =>
item.id === itemId
? { ...item, completed, boughtAt: completed ? new Date().toISOString() : null }
: item,
),
)
return { previous }
},
onError: (_error, _variables, context) => {
context?.previous.forEach(([key, items]) => {
queryClient.setQueryData(key, items)
})
},
onSettled: () => queryClient.invalidateQueries({ queryKey }),
})
}

View File

@@ -91,6 +91,8 @@ export type ListItem = {
listId: string
name: string
completed: boolean
/** When the item was marked as bought; `null` while it is pending. */
boughtAt: string | null
quantity: string | null
notes: string | null
order: number