feat: add collaborative shopping lists with items and invitations
Some checks failed
CI / Verify (push) Has been cancelled

API: lists, items and invitations modules (list, create, get, update,
set-primary, items create/list, invitation create/accept/list-pending),
BetterAuth session helper, list membership, mailer and Prisma schema plus
migrations.

Web: lists overview, list detail (items) and list management (settings)
views, item and invitation forms/hooks, sign-up and invitation accept pages.

Shared: shopping list DTOs.

Tooling: ignore the generated TanStack Router cache (apps/web/.tanstack).
This commit is contained in:
Jose Selesan
2026-10-16 10:12:11 -03:00
parent 964a3c7217
commit 6aa86a3b68
81 changed files with 3476 additions and 269 deletions

View File

@@ -0,0 +1,26 @@
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 { CreateListSchema } from './schema'
import { CreateShoppingList } from './use-case'
/** POST /lists — creates a shopping list. */
export const createListRoute = new Hono<AppEnv>().post(
'/',
requireSession,
validate.json(CreateListSchema),
async (c) => {
const body = c.req.valid('json')
const result = await new CreateShoppingList(prisma).execute({
name: body.name,
userId: c.get('user').id,
})
return resultJson(c, result, { status: 201 })
},
)

View File

@@ -0,0 +1,8 @@
import { z } from 'zod'
/** Body of `POST /lists`. */
export const CreateListSchema = z.object({
name: z.string().trim().min(1, 'El nombre es obligatorio').max(80, 'Máximo 80 caracteres'),
})
export type CreateListInput = z.infer<typeof CreateListSchema>

View File

@@ -0,0 +1,84 @@
import { describe, expect, it } from 'bun:test'
import type { Database } from '@/lib/prisma'
import { CreateShoppingList } from './use-case'
type CreateInput = {
data: {
name: string
ownerId: string
members: { create: { isPrimary: boolean; userId: string; role: string } }
}
}
function createDb({
existingMemberships,
membershipsOnCreate,
}: {
existingMemberships: number
membershipsOnCreate: number
}) {
const created: CreateInput[] = []
const db = {
shoppingListMember: { count: async () => existingMemberships },
shoppingList: {
create: async (args: unknown) => {
const input = args as CreateInput
created.push(input)
return {
id: 'list-1',
name: input.data.name,
createdAt: new Date('2026-10-15T00:00:00.000Z'),
updatedAt: new Date('2026-10-15T00:00:00.000Z'),
_count: { members: membershipsOnCreate },
members: [
{
id: 'member-1',
role: 'owner',
isPrimary: input.data.members.create.isPrimary,
},
],
}
},
},
}
return { db: db as unknown as Database, created }
}
describe('CreateShoppingList', () => {
it('makes the first list the primary one', async () => {
const { db, created } = createDb({ existingMemberships: 0, membershipsOnCreate: 1 })
const result = await new CreateShoppingList(db).execute({
name: 'Compra semanal',
userId: 'user-1',
})
expect(result.ok).toBe(true)
if (!result.ok) throw new Error('expected the use case to succeed')
expect(created[0]?.data.members.create.isPrimary).toBe(true)
expect(result.value).toEqual({
id: 'list-1',
name: 'Compra semanal',
role: 'owner',
isPrimary: true,
memberCount: 1,
createdAt: '2026-10-15T00:00:00.000Z',
updatedAt: '2026-10-15T00:00:00.000Z',
})
})
it('does not steal the primary flag from an existing list', async () => {
const { db, created } = createDb({ existingMemberships: 3, membershipsOnCreate: 4 })
const result = await new CreateShoppingList(db).execute({
name: 'Otra lista',
userId: 'user-1',
})
expect(result.ok).toBe(true)
expect(created[0]?.data.members.create.isPrimary).toBe(false)
})
})

View File

@@ -0,0 +1,57 @@
import { Ok, type ProblemDetails, type Result, type ShoppingListSummary } from '@superlist/shared'
import type { Database } from '@/lib/prisma'
import { toSummary } from '../serialize'
/** Creates a shopping list owned by the user. The first list becomes primary. */
export class CreateShoppingList {
constructor(private readonly db: Database) {}
async execute(input: {
name: string
userId: string
}): Promise<Result<ShoppingListSummary, ProblemDetails>> {
const existingCount = await this.db.shoppingListMember.count({
where: { userId: input.userId },
})
const list = await this.db.shoppingList.create({
data: {
name: input.name,
ownerId: input.userId,
members: {
create: {
userId: input.userId,
role: 'owner',
isPrimary: existingCount === 0,
},
},
},
include: {
_count: { select: { members: true } },
members: { where: { userId: input.userId } },
},
})
const membership = list.members[0]
if (!membership) {
throw new Error('Membership was not created for the new list')
}
return Ok(
toSummary({
role: membership.role,
isPrimary: membership.isPrimary,
list: {
id: list.id,
name: list.name,
createdAt: list.createdAt,
updatedAt: list.updatedAt,
_count: list._count,
},
}),
)
}
}

View File

@@ -0,0 +1,26 @@
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 { ListParamsSchema } from '../schema'
import { GetShoppingList } from './use-case'
/** GET /lists/:listId — list detail with its members. */
export const getListRoute = new Hono<AppEnv>().get(
'/:listId',
requireSession,
validate.param(ListParamsSchema),
async (c) => {
const { listId } = c.req.valid('param')
const result = await new GetShoppingList(prisma).execute({
listId,
userId: c.get('user').id,
})
return resultJson(c, result)
},
)

View File

@@ -0,0 +1,46 @@
import {
Failure,
Ok,
type ProblemDetails,
problems,
type Result,
type ShoppingListDetail,
} from '@superlist/shared'
import type { Database } from '@/lib/prisma'
import { toDetail } from '../serialize'
/** Returns a list with its members. Only members can read it. */
export class GetShoppingList {
constructor(private readonly db: Database) {}
async execute(input: {
listId: string
userId: string
}): Promise<Result<ShoppingListDetail, ProblemDetails>> {
const membership = await this.db.shoppingListMember.findUnique({
where: { listId_userId: { listId: input.listId, userId: input.userId } },
include: {
list: {
include: {
members: {
include: { user: true },
orderBy: [{ role: 'asc' }, { createdAt: 'asc' }],
},
invitations: {
where: { status: 'pending' },
orderBy: { createdAt: 'desc' },
},
},
},
},
})
if (!membership) {
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
}
return Ok(toDetail(membership))
}
}

View File

@@ -0,0 +1,19 @@
import { Hono } from 'hono'
import type { AppEnv } from '@/types'
import { createListRoute } from './create/route'
import { getListRoute } from './get/route'
import { listItemsModule } from './items'
import { listListsRoute } from './list/route'
import { setPrimaryListRoute } from './set-primary/route'
import { updateListRoute } from './update/route'
/** `lists` module: every feature of the module is mounted here. */
export const listsModule = new Hono<AppEnv>()
.route('/', listListsRoute)
.route('/', createListRoute)
.route('/', getListRoute)
.route('/', updateListRoute)
.route('/', setPrimaryListRoute)
.route('/:listId/items', listItemsModule)

View File

@@ -0,0 +1,32 @@
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 { ListParamsSchema } from '@/modules/lists/schema'
import type { AppEnv } from '@/types'
import { CreateItemSchema } from './schema'
import { CreateItem } from './use-case'
/** POST /lists/:listId/items — adds an item to a list the user belongs to. */
export const createItemRoute = new Hono<AppEnv>().post(
'/',
requireSession,
validate.param(ListParamsSchema),
validate.json(CreateItemSchema),
async (c) => {
const { listId } = c.req.valid('param')
const body = c.req.valid('json')
const result = await new CreateItem(prisma).execute({
listId,
userId: c.get('user').id,
name: body.name,
quantity: body.quantity,
notes: body.notes,
})
return resultJson(c, result, { status: 201 })
},
)

View File

@@ -0,0 +1,10 @@
import { z } from 'zod'
/** Body of `POST /lists/:listId/items`. */
export const CreateItemSchema = z.object({
name: z.string().trim().min(1, 'El nombre es obligatorio').max(120, 'Máximo 120 caracteres'),
quantity: z.string().trim().max(40, 'Máximo 40 caracteres').optional(),
notes: z.string().trim().max(280, 'Máximo 280 caracteres').optional(),
})
export type CreateItemInput = z.infer<typeof CreateItemSchema>

View File

@@ -0,0 +1,44 @@
import {
Failure,
type ListItem,
Ok,
type ProblemDetails,
problems,
type Result,
} from '@superlist/shared'
import type { Database } from '@/lib/prisma'
import { toListItem } from '../serialize'
/** Adds an item to a shopping list. Only members can add items. */
export class CreateItem {
constructor(private readonly db: Database) {}
async execute(input: {
listId: string
userId: string
name: string
quantity?: string
notes?: string
}): 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.create({
data: {
shoppingListId: input.listId,
name: input.name,
quantity: input.quantity || null,
notes: input.notes || null,
},
})
return Ok(toListItem(item))
}
}

View File

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

View File

@@ -0,0 +1,26 @@
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 { ListParamsSchema } from '@/modules/lists/schema'
import type { AppEnv } from '@/types'
import { ListItems } from './use-case'
/** GET /lists/:listId/items — every item of a list the user belongs to. */
export const listItemsRoute = new Hono<AppEnv>().get(
'/',
requireSession,
validate.param(ListParamsSchema),
async (c) => {
const { listId } = c.req.valid('param')
const result = await new ListItems(prisma).execute({
listId,
userId: c.get('user').id,
})
return resultJson(c, result)
},
)

View File

@@ -0,0 +1,34 @@
import type { ListItem, ProblemDetails, Result } from '@superlist/shared'
import { Failure, Ok, problems } from '@superlist/shared'
import type { Database } from '@/lib/prisma'
import { toListItem } from '../serialize'
/**
* Lists every item of a shopping list, pending ones first.
* Only members of the list can read it.
*/
export class ListItems {
constructor(private readonly db: Database) {}
async execute(input: {
listId: string
userId: string
}): 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 items = await this.db.listItem.findMany({
where: { shoppingListId: input.listId },
orderBy: [{ completed: 'asc' }, { order: 'asc' }, { createdAt: 'asc' }],
})
return Ok(items.map(toListItem))
}
}

View File

@@ -0,0 +1,28 @@
import type { ListItem } from '@superlist/shared'
type ItemRow = {
id: string
shoppingListId: string
name: string
completed: boolean
quantity: string | null
notes: string | null
order: number
createdAt: Date
updatedAt: Date
}
/** Maps a `ListItem` row to the DTO shared with the web app. */
export function toListItem(item: ItemRow): ListItem {
return {
id: item.id,
listId: item.shoppingListId,
name: item.name,
completed: item.completed,
quantity: item.quantity,
notes: item.notes,
order: item.order,
createdAt: item.createdAt.toISOString(),
updatedAt: item.updatedAt.toISOString(),
}
}

View File

@@ -0,0 +1,15 @@
import { Hono } from 'hono'
import { requireSession } from '@/lib/auth-session'
import { prisma } from '@/lib/prisma'
import { resultJson } from '@/lib/result-json'
import type { AppEnv } from '@/types'
import { ListShoppingLists } from './use-case'
/** GET /lists — every list the signed-in user belongs to. */
export const listListsRoute = new Hono<AppEnv>().get('/', requireSession, async (c) => {
const result = await new ListShoppingLists(prisma).execute({ userId: c.get('user').id })
return resultJson(c, result)
})

View File

@@ -0,0 +1,28 @@
import { Ok, type ProblemDetails, type Result, type ShoppingListSummary } from '@superlist/shared'
import type { Database } from '@/lib/prisma'
/** Lists every shopping list the user belongs to (owned or shared). */
export class ListShoppingLists {
constructor(private readonly db: Database) {}
async execute(input: { userId: string }): Promise<Result<ShoppingListSummary[], ProblemDetails>> {
const memberships = await this.db.shoppingListMember.findMany({
where: { userId: input.userId },
include: { list: { include: { _count: { select: { members: true } } } } },
orderBy: [{ isPrimary: 'desc' }, { list: { createdAt: 'desc' } }],
})
const lists = memberships.map((membership) => ({
id: membership.list.id,
name: membership.list.name,
role: membership.role,
isPrimary: membership.isPrimary,
memberCount: membership.list._count.members,
createdAt: membership.list.createdAt.toISOString(),
updatedAt: membership.list.updatedAt.toISOString(),
}))
return Ok(lists)
}
}

View File

@@ -0,0 +1,8 @@
import { z } from 'zod'
/** Path params shared by the list features: `/:listId`. */
export const ListParamsSchema = z.object({
listId: z.uuid('El identificador de la lista no es válido'),
})
export type ListParams = z.infer<typeof ListParamsSchema>

View File

@@ -0,0 +1,79 @@
import type { ListMember, ShoppingListDetail, ShoppingListSummary } from '@superlist/shared'
type ListRow = {
id: string
name: string
createdAt: Date
updatedAt: Date
}
type MemberRow = {
role: 'owner' | 'collaborator'
isPrimary: boolean
list: ListRow & { _count: { members: number } }
}
/** Maps a membership (with its list and member count) to the summary DTO. */
export function toSummary(member: MemberRow): ShoppingListSummary {
return {
id: member.list.id,
name: member.list.name,
role: member.role,
isPrimary: member.isPrimary,
memberCount: member.list._count.members,
createdAt: member.list.createdAt.toISOString(),
updatedAt: member.list.updatedAt.toISOString(),
}
}
type DetailRow = {
role: 'owner' | 'collaborator'
isPrimary: boolean
list: ListRow & {
members: Array<{
id: string
role: 'owner' | 'collaborator'
isPrimary: boolean
user: { id: string; name: string; email: string; image: string | null }
}>
invitations: Array<{
id: string
email: string
status: 'pending' | 'accepted' | 'revoked' | 'expired'
expiresAt: Date
createdAt: Date
}>
}
}
/** Maps a membership (with its list and members) to the detail DTO. */
export function toDetail(member: DetailRow): ShoppingListDetail {
const members: ListMember[] = member.list.members.map((row) => ({
id: row.id,
role: row.role,
isPrimary: row.isPrimary,
user: {
id: row.user.id,
name: row.user.name,
email: row.user.email,
image: row.user.image,
},
}))
return {
id: member.list.id,
name: member.list.name,
role: member.role,
isPrimary: member.isPrimary,
members,
invitations: member.list.invitations.map((invitation) => ({
id: invitation.id,
email: invitation.email,
status: invitation.status,
expiresAt: invitation.expiresAt.toISOString(),
createdAt: invitation.createdAt.toISOString(),
})),
createdAt: member.list.createdAt.toISOString(),
updatedAt: member.list.updatedAt.toISOString(),
}
}

View File

@@ -0,0 +1,26 @@
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 { ListParamsSchema } from '../schema'
import { SetPrimaryList } from './use-case'
/** POST /lists/:listId/primary — marks the list as the user's primary one. */
export const setPrimaryListRoute = new Hono<AppEnv>().post(
'/:listId/primary',
requireSession,
validate.param(ListParamsSchema),
async (c) => {
const { listId } = c.req.valid('param')
const result = await new SetPrimaryList(prisma).execute({
listId,
userId: c.get('user').id,
})
return resultJson(c, result, { status: 204 })
},
)

View File

@@ -0,0 +1,65 @@
import { describe, expect, it } from 'bun:test'
import type { Database } from '@/lib/prisma'
import { SetPrimaryList } from './use-case'
function createDb(membership: unknown) {
const calls: { cleared: unknown[]; marked: unknown[] } = { cleared: [], marked: [] }
const db = {
shoppingListMember: {
findUnique: async () => membership,
updateMany: async (args: unknown) => {
calls.cleared.push(args)
return { count: 1 }
},
update: async (args: unknown) => {
calls.marked.push(args)
return args
},
},
$transaction: async (operations: Promise<unknown>[]) => Promise.all(operations),
}
return { db: db as unknown as Database, calls }
}
describe('SetPrimaryList', () => {
it('answers 404 when the user does not belong to the list', async () => {
const { db, calls } = createDb(null)
const result = await new SetPrimaryList(db).execute({
listId: 'list-1',
userId: 'user-1',
})
expect(result.ok).toBe(false)
if (result.ok) throw new Error('expected the use case to fail')
expect(result.error.status).toBe(404)
expect(calls.cleared).toHaveLength(0)
expect(calls.marked).toHaveLength(0)
})
it('clears the previous primary list and marks the new one', async () => {
const { db, calls } = createDb({ isPrimary: false })
const result = await new SetPrimaryList(db).execute({
listId: 'list-2',
userId: 'user-1',
})
expect(result.ok).toBe(true)
expect(calls.cleared).toEqual([
{
where: { userId: 'user-1', isPrimary: true, listId: { not: 'list-2' } },
data: { isPrimary: false },
},
])
expect(calls.marked).toEqual([
{
where: { listId_userId: { listId: 'list-2', userId: 'user-1' } },
data: { isPrimary: true },
},
])
})
})

View File

@@ -0,0 +1,31 @@
import { Failure, Ok, type ProblemDetails, problems, type Result } from '@superlist/shared'
import type { Database } from '@/lib/prisma'
/** Marks one list as the user's primary list (per user, not per list). */
export class SetPrimaryList {
constructor(private readonly db: Database) {}
async execute(input: { listId: string; userId: string }): Promise<Result<void, 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.'))
}
await this.db.$transaction([
this.db.shoppingListMember.updateMany({
where: { userId: input.userId, isPrimary: true, listId: { not: input.listId } },
data: { isPrimary: false },
}),
this.db.shoppingListMember.update({
where: { listId_userId: { listId: input.listId, userId: input.userId } },
data: { isPrimary: true },
}),
])
return Ok(undefined)
}
}

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 { ListParamsSchema } from '../schema'
import { UpdateListSchema } from './schema'
import { UpdateShoppingList } from './use-case'
/** PATCH /lists/:listId — renames a list (owner only). */
export const updateListRoute = new Hono<AppEnv>().patch(
'/:listId',
requireSession,
validate.param(ListParamsSchema),
validate.json(UpdateListSchema),
async (c) => {
const { listId } = c.req.valid('param')
const body = c.req.valid('json')
const result = await new UpdateShoppingList(prisma).execute({
listId,
userId: c.get('user').id,
name: body.name,
})
return resultJson(c, result)
},
)

View File

@@ -0,0 +1,8 @@
import { z } from 'zod'
/** Body of `PATCH /lists/:listId`. */
export const UpdateListSchema = z.object({
name: z.string().trim().min(1, 'El nombre es obligatorio').max(80, 'Máximo 80 caracteres'),
})
export type UpdateListInput = z.infer<typeof UpdateListSchema>

View File

@@ -0,0 +1,49 @@
import {
Failure,
Ok,
type ProblemDetails,
problems,
type Result,
type ShoppingListSummary,
} from '@superlist/shared'
import type { Database } from '@/lib/prisma'
/** Renames a list. Only the owner (`role: owner`) may do it. */
export class UpdateShoppingList {
constructor(private readonly db: Database) {}
async execute(input: {
listId: string
userId: string
name: string
}): Promise<Result<ShoppingListSummary, 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.'))
}
if (membership.role !== 'owner') {
return Failure(problems.forbidden('Solo el propietario puede renombrar la lista.'))
}
const list = await this.db.shoppingList.update({
where: { id: input.listId },
data: { name: input.name },
include: { _count: { select: { members: true } } },
})
return Ok({
id: list.id,
name: list.name,
role: membership.role,
isPrimary: membership.isPrimary,
memberCount: list._count.members,
createdAt: list.createdAt.toISOString(),
updatedAt: list.updatedAt.toISOString(),
})
}
}