Compare commits

...

2 Commits

Author SHA1 Message Date
Jose Selesan
4ff864a557 feat: show bought items in a collapsible section for the current day only
Some checks failed
CI / Verify (push) Has been cancelled
Bought items now move down to a 'Comprados hoy' collapsible section
(expanded by default) below the pending ones, and are only visible on
the local day they were bought. Items bought on previous days stay
completed in the database but are hidden from the list.
2026-10-16 11:08:42 -03:00
Jose Selesan
c4f6b8bc85 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.
2026-10-16 10:44:23 -03:00
19 changed files with 629 additions and 45 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 { model ListItem {
id String @id @default(cuid()) id String @id @default(cuid())
shoppingListId String @map("shopping_list_id") shoppingListId String @map("shopping_list_id")
name String name String
completed Boolean @default(false) completed Boolean @default(false)
quantity String? @map("quantity") boughtAt DateTime? @map("bought_at")
notes String? @map("notes") quantity String? @map("quantity")
order Int @default(0) @map("order") notes String? @map("notes")
createdAt DateTime @default(now()) @map("created_at") order Int @default(0) @map("order")
updatedAt DateTime @updatedAt @map("updated_at") createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
shoppingList ShoppingList @relation(fields: [shoppingListId], references: [id], onDelete: Cascade) 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 { createItemRoute } from './create/route'
import { listItemsRoute } from './list/route' import { listItemsRoute } from './list/route'
import { updateItemRoute } from './update/route'
/** `items` sub-module of `lists`: mounted at `/lists/:listId/items`. */ /** `items` sub-module of `lists`: mounted at `/lists/:listId/items`. */
export const listItemsModule = new Hono<AppEnv>() export const listItemsModule = new Hono<AppEnv>()
.route('/', listItemsRoute) .route('/', listItemsRoute)
.route('/', createItemRoute) .route('/', createItemRoute)
.route('/', updateItemRoute)

View File

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

@@ -0,0 +1,36 @@
import type { ListItem } from '@superlist/shared'
import { ChevronDownIcon } from 'lucide-react'
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
import type { useUpdateItem } from '@/hooks/use-items'
import { ItemRow } from './item-row'
type BoughtItemListProps = {
items: ListItem[]
updateItem: ReturnType<typeof useUpdateItem>
}
/**
* Collapsible "Comprados hoy" section below the pending items. Expanded by
* default so marking an item visibly moves it down; the user can fold it.
* Tapping an item here un-buys it and it returns to the pending list.
*/
export function BoughtItemList({ items, updateItem }: BoughtItemListProps) {
return (
<Collapsible defaultOpen>
<CollapsibleTrigger className="group flex w-full items-center gap-1.5 py-1 text-left">
<ChevronDownIcon className="text-muted-foreground size-4 transition-transform group-data-[state=closed]:-rotate-90" />
<span className="text-muted-foreground text-sm font-medium">Comprados hoy</span>
<span className="text-muted-foreground text-sm">({items.length})</span>
</CollapsibleTrigger>
<CollapsibleContent>
<ul className="flex flex-col gap-2 pt-2">
{items.map((item) => (
<ItemRow key={item.id} item={item} updateItem={updateItem} />
))}
</ul>
</CollapsibleContent>
</Collapsible>
)
}

View File

@@ -1,19 +1,30 @@
import { CheckIcon, ShoppingBasketIcon } from 'lucide-react' import { ShoppingBasketIcon } from 'lucide-react'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert' import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Card, CardContent } from '@/components/ui/card' import { Card, CardContent } from '@/components/ui/card'
import { Separator } from '@/components/ui/separator'
import { Skeleton } from '@/components/ui/skeleton' import { Skeleton } from '@/components/ui/skeleton'
import { useItems } from '@/hooks/use-items' import { useItems, useUpdateItem } from '@/hooks/use-items'
import { useToday } from '@/hooks/use-today'
import { ApiError } from '@/lib/api-client' import { ApiError } from '@/lib/api-client'
import { cn } from '@/lib/utils' import { splitItems } from '@/lib/items'
import { BoughtItemList } from './bought-item-list'
import { ItemRow } from './item-row'
type ItemListProps = { type ItemListProps = {
listId: string 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; bought items move to a collapsible "Comprados hoy" section below
* and are only shown on the day they were bought.
*/
export function ItemList({ listId }: ItemListProps) { export function ItemList({ listId }: ItemListProps) {
const { data: items, isPending, error } = useItems(listId) const { data: items, isPending, error } = useItems(listId)
const updateItem = useUpdateItem(listId)
const today = useToday()
if (error) { if (error) {
return ( return (
@@ -38,7 +49,9 @@ export function ItemList({ listId }: ItemListProps) {
) )
} }
if (items.length === 0) { const { pending, boughtToday } = splitItems(items, today)
if (pending.length === 0 && boughtToday.length === 0) {
return ( return (
<Card> <Card>
<CardContent className="flex flex-col items-center gap-3 py-10 text-center"> <CardContent className="flex flex-col items-center gap-3 py-10 text-center">
@@ -57,37 +70,21 @@ export function ItemList({ listId }: ItemListProps) {
} }
return ( return (
<ul className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
{items.map((item) => ( {pending.length > 0 && (
<li key={item.id}> <ul className="flex flex-col gap-2">
<Card> {pending.map((item) => (
<CardContent className="flex items-center gap-3 p-3"> <ItemRow key={item.id} item={item} updateItem={updateItem} />
<span ))}
className={cn( </ul>
'flex size-5 shrink-0 items-center justify-center rounded-full border', )}
item.completed
? 'bg-primary text-primary-foreground border-primary' {boughtToday.length > 0 && (
: 'border-muted-foreground/40 text-transparent', <>
)} {pending.length > 0 && <Separator className="mt-2" />}
aria-hidden <BoughtItemList items={boughtToday} updateItem={updateItem} />
> </>
<CheckIcon className="size-3" /> )}
</span> </div>
<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>
)}
</CardContent>
</Card>
</li>
))}
</ul>
) )
} }

View File

@@ -0,0 +1,53 @@
import type { ListItem } from '@superlist/shared'
import { CheckIcon } from 'lucide-react'
import { Card, CardContent } from '@/components/ui/card'
import type { useUpdateItem } from '@/hooks/use-items'
import { cn } from '@/lib/utils'
type ItemRowProps = {
item: ListItem
updateItem: ReturnType<typeof useUpdateItem>
}
/** A single item row: tapping it toggles its bought state. */
export function ItemRow({ item, updateItem }: ItemRowProps) {
return (
<li>
<Card>
<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"
>
<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>
)}
</button>
</CardContent>
</Card>
</li>
)
}

View File

@@ -0,0 +1,19 @@
import { Collapsible as CollapsiblePrimitive } from 'radix-ui'
function Collapsible({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
}
function CollapsibleTrigger({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
return <CollapsiblePrimitive.CollapsibleTrigger data-slot="collapsible-trigger" {...props} />
}
function CollapsibleContent({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
return <CollapsiblePrimitive.CollapsibleContent data-slot="collapsible-content" {...props} />
}
export { Collapsible, CollapsibleContent, CollapsibleTrigger }

View File

@@ -25,3 +25,38 @@ export function useCreateItem(listId: string) {
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] }), 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

@@ -0,0 +1,35 @@
import { useEffect, useState } from 'react'
/** Milliseconds until the next local midnight, plus a small buffer. */
function msUntilNextLocalDay(now: Date): number {
const nextMidnight = new Date(now)
nextMidnight.setHours(24, 0, 0, 0)
return nextMidnight.getTime() - now.getTime() + 5_000
}
/**
* The current date, refreshed when the local day changes (via a timer set to
* the next midnight) and when the tab regains focus. Components selling a
* "today only" view use it so bought items disappear once the day rolls over
* even if the page has been open all night.
*/
export function useToday(): Date {
const [today, setToday] = useState(() => new Date())
useEffect(() => {
const refresh = () => setToday(new Date())
const timer = setTimeout(refresh, msUntilNextLocalDay(new Date()))
window.addEventListener('focus', refresh)
document.addEventListener('visibilitychange', refresh)
return () => {
clearTimeout(timer)
window.removeEventListener('focus', refresh)
document.removeEventListener('visibilitychange', refresh)
}
}, [])
return today
}

View File

@@ -0,0 +1,28 @@
import { describe, expect, it } from 'vitest'
import { isSameLocalDay } from './dates'
describe('isSameLocalDay', () => {
it('matches two moments of the same local day', () => {
const morning = new Date(2026, 9, 15, 8, 30)
const night = new Date(2026, 9, 15, 23, 59)
expect(isSameLocalDay(morning, night)).toBe(true)
})
it('does not match moments across local midnight', () => {
const justBefore = new Date(2026, 9, 15, 23, 59)
const justAfter = new Date(2026, 9, 16, 0, 1)
expect(isSameLocalDay(justBefore, justAfter)).toBe(false)
})
it('compares in the local timezone, not in UTC', () => {
// 23:30 local on Oct 15th is already Oct 16th in UTC for UTC-negative
// timezones, so a naive UTC comparison would report different days.
const localNight = new Date(2026, 9, 15, 23, 30)
const nextLocalMidnight = new Date(2026, 9, 16, 0, 0)
expect(isSameLocalDay(localNight, nextLocalMidnight)).toBe(false)
})
})

14
apps/web/src/lib/dates.ts Normal file
View File

@@ -0,0 +1,14 @@
/**
* Local-day helpers. A shopping day belongs to the user's timezone (the
* browser's), which the API cannot know, so "bought today" is decided here
* and never on the server.
*/
/** True when both moments fall on the same calendar day in the local timezone. */
export function isSameLocalDay(a: Date, b: Date): boolean {
return (
a.getFullYear() === b.getFullYear() &&
a.getMonth() === b.getMonth() &&
a.getDate() === b.getDate()
)
}

View File

@@ -0,0 +1,87 @@
import type { ListItem } from '@superlist/shared'
import { describe, expect, it } from 'vitest'
import { splitItems } from './items'
function item(overrides: Partial<ListItem>): ListItem {
return {
id: 'item-1',
listId: 'list-1',
name: 'Leche',
completed: false,
boughtAt: null,
quantity: null,
notes: null,
order: 0,
createdAt: '2026-10-15T10:00:00.000Z',
updatedAt: '2026-10-15T10:00:00.000Z',
...overrides,
}
}
const NOW = new Date(2026, 9, 15, 18, 0)
describe('splitItems', () => {
it('keeps pending items untouched, in API order', () => {
const first = item({ id: 'a', order: 1 })
const second = item({ id: 'b', order: 2 })
const { pending, boughtToday } = splitItems([first, second], NOW)
expect(pending).toEqual([first, second])
expect(boughtToday).toEqual([])
})
it('moves items bought today to boughtToday, most recent first', () => {
const boughtEarlier = item({
id: 'a',
completed: true,
boughtAt: new Date(2026, 9, 15, 9, 0).toISOString(),
})
const boughtJustNow = item({
id: 'b',
completed: true,
boughtAt: new Date(2026, 9, 15, 17, 30).toISOString(),
})
const { pending, boughtToday } = splitItems([boughtEarlier, boughtJustNow], NOW)
expect(pending).toEqual([])
expect(boughtToday.map((i) => i.id)).toEqual(['b', 'a'])
})
it('hides items bought on a previous local day', () => {
const boughtYesterday = item({
completed: true,
boughtAt: new Date(2026, 9, 14, 23, 30).toISOString(),
})
const { pending, boughtToday } = splitItems([boughtYesterday], NOW)
expect(pending).toEqual([])
expect(boughtToday).toEqual([])
})
it('compares in the local timezone, not in UTC', () => {
// 23:30 local on Oct 15th already belongs to Oct 16th in UTC for
// UTC-negative timezones; the item must still count as bought today.
const boughtLateAtNight = item({
completed: true,
boughtAt: new Date(2026, 9, 15, 23, 30).toISOString(),
})
const lateNightNow = new Date(2026, 9, 15, 23, 45)
const { boughtToday } = splitItems([boughtLateAtNight], lateNightNow)
expect(boughtToday).toHaveLength(1)
})
it('hides completed items without boughtAt', () => {
const legacy = item({ completed: true, boughtAt: null })
const { pending, boughtToday } = splitItems([legacy], NOW)
expect(pending).toEqual([])
expect(boughtToday).toEqual([])
})
})

40
apps/web/src/lib/items.ts Normal file
View File

@@ -0,0 +1,40 @@
import type { ListItem } from '@superlist/shared'
import { isSameLocalDay } from './dates'
export type SplitItems = {
/** Items still to buy, in the API's order (by `order`). */
pending: ListItem[]
/** Items bought during the current local day, most recent first. */
boughtToday: ListItem[]
}
/**
* Splits a list's items into the two groups the UI renders: pending items
* and items bought today. Items bought on a previous local day are dropped
* entirely — they stay `completed` in the database but are only shown on
* the day they were bought.
*/
export function splitItems(items: ListItem[], now: Date): SplitItems {
const pending: ListItem[] = []
const boughtToday: ListItem[] = []
for (const item of items) {
if (!item.completed) {
pending.push(item)
continue
}
// A completed item without `boughtAt` is legacy data with no known
// purchase day, so it is not considered bought today.
if (item.boughtAt && isSameLocalDay(new Date(item.boughtAt), now)) {
boughtToday.push(item)
}
}
boughtToday.sort(
(a, b) => new Date(b.boughtAt ?? 0).getTime() - new Date(a.boughtAt ?? 0).getTime(),
)
return { pending, boughtToday }
}

View File

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