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,32 @@
import { Hono } from 'hono'
import { z } from 'zod'
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 { AcceptInvitation } from './use-case'
const TokenParamSchema = z.object({
token: z.uuid('El identificador de la invitación no es válido'),
})
/** POST /invitations/:token/accept — accepts an invitation for the signed-in user. */
export const acceptInvitationRoute = new Hono<AppEnv>().post(
'/:token/accept',
requireSession,
validate.param(TokenParamSchema),
async (c) => {
const { token } = c.req.valid('param')
const user = c.get('user')
const result = await new AcceptInvitation(prisma).execute({
token,
userId: user.id,
email: user.email,
})
return resultJson(c, result)
},
)

View File

@@ -0,0 +1,133 @@
import { describe, expect, it } from 'bun:test'
import type { Database } from '@/lib/prisma'
import { AcceptInvitation } from './use-case'
const NOW = new Date('2026-10-15T00:00:00.000Z')
const INVITATION = {
id: 'inv-1',
listId: 'list-1',
email: 'beto@ejemplo.com',
status: 'pending',
expiresAt: new Date('2026-10-20T00:00:00.000Z'),
list: { id: 'list-1', name: 'Compra semanal' },
}
function createDb({
invitation,
membership = null,
}: {
invitation?: typeof INVITATION
membership?: unknown
}) {
const updates: unknown[] = []
const created: unknown[] = []
const db = {
shoppingListInvitation: {
findUnique: async () => invitation,
update: async (args: unknown) => {
updates.push(args)
return args
},
},
shoppingListMember: {
findUnique: async () => membership,
create: async (args: unknown) => {
created.push(args)
return args
},
},
$transaction: async (operations: Promise<unknown>[]) => Promise.all(operations),
}
return { db: db as unknown as Database, updates, created }
}
describe('AcceptInvitation', () => {
it('answers 404 for an unknown token', async () => {
const { db } = createDb({ invitation: undefined })
const result = await new AcceptInvitation(db, () => NOW).execute({
token: 'nope',
userId: 'user-1',
email: 'beto@ejemplo.com',
})
expect(result.ok).toBe(false)
if (result.ok) throw new Error('expected the use case to fail')
expect(result.error.status).toBe(404)
})
it('rejects an invitation addressed to another email', async () => {
const { db, created } = createDb({ invitation: INVITATION })
const result = await new AcceptInvitation(db, () => NOW).execute({
token: INVITATION.id,
userId: 'user-1',
email: 'ana@ejemplo.com',
})
expect(result.ok).toBe(false)
if (result.ok) throw new Error('expected the use case to fail')
expect(result.error.status).toBe(403)
expect(created).toHaveLength(0)
})
it('is idempotent for somebody who is already a member', async () => {
const { db, updates } = createDb({
invitation: INVITATION,
membership: { id: 'member-1' },
})
const result = await new AcceptInvitation(db, () => NOW).execute({
token: INVITATION.id,
userId: 'user-1',
email: 'beto@ejemplo.com',
})
expect(result.ok).toBe(true)
if (!result.ok) throw new Error('expected the use case to succeed')
expect(result.value).toEqual({ listId: 'list-1', listName: 'Compra semanal' })
expect(updates).toHaveLength(0)
})
it('answers 400 and marks expired invitations', async () => {
const { db, updates, created } = createDb({
invitation: {
...INVITATION,
expiresAt: new Date('2026-10-01T00:00:00.000Z'),
},
})
const result = await new AcceptInvitation(db, () => NOW).execute({
token: INVITATION.id,
userId: 'user-1',
email: 'beto@ejemplo.com',
})
expect(result.ok).toBe(false)
if (result.ok) throw new Error('expected the use case to fail')
expect(result.error.status).toBe(400)
expect(updates).toHaveLength(1)
expect(created).toHaveLength(0)
})
it('grants access and marks the invitation as accepted', async () => {
const { db, updates, created } = createDb({ invitation: INVITATION })
const result = await new AcceptInvitation(db, () => NOW).execute({
token: INVITATION.id,
userId: 'user-1',
// Compared in lower case, so the casing of the session email does not matter.
email: 'Beto@Ejemplo.com',
})
expect(result.ok).toBe(true)
if (!result.ok) throw new Error('expected the use case to succeed')
expect(result.value).toEqual({ listId: 'list-1', listName: 'Compra semanal' })
expect(created).toEqual([
{
data: { listId: 'list-1', userId: 'user-1', role: 'collaborator' },
},
])
expect(updates).toHaveLength(1)
})
})

View File

@@ -0,0 +1,71 @@
import {
type AcceptInvitationResult,
Failure,
Ok,
type ProblemDetails,
problems,
type Result,
} from '@superlist/shared'
import type { Database } from '@/lib/prisma'
/** Accepts an invitation for the signed-in user, matching it by token and email. */
export class AcceptInvitation {
constructor(
private readonly db: Database,
private readonly now: () => Date = () => new Date(),
) {}
async execute(input: {
token: string
userId: string
email: string
}): Promise<Result<AcceptInvitationResult, ProblemDetails>> {
const invitation = await this.db.shoppingListInvitation.findUnique({
where: { token: input.token },
include: { list: { select: { id: true, name: true } } },
})
if (!invitation) {
return Failure(problems.notFound('La invitación no existe o fue cancelada.'))
}
if (invitation.email !== input.email.trim().toLowerCase()) {
return Failure(problems.forbidden('Esta invitación pertenece a otro correo electrónico.'))
}
const membership = await this.db.shoppingListMember.findUnique({
where: { listId_userId: { listId: invitation.listId, userId: input.userId } },
})
// Already a member (e.g. accepted at signup): idempotent success.
if (membership) {
return Ok({ listId: invitation.list.id, listName: invitation.list.name })
}
if (invitation.status !== 'pending') {
return Failure(problems.conflict('Esta invitación ya no está disponible.'))
}
if (invitation.expiresAt.getTime() < this.now().getTime()) {
await this.db.shoppingListInvitation.update({
where: { id: invitation.id },
data: { status: 'expired' },
})
return Failure(problems.badRequest('Esta invitación ha expirado.'))
}
await this.db.$transaction([
this.db.shoppingListMember.create({
data: { listId: invitation.listId, userId: input.userId, role: 'collaborator' },
}),
this.db.shoppingListInvitation.update({
where: { id: invitation.id },
data: { status: 'accepted', acceptedAt: this.now() },
}),
])
return Ok({ listId: invitation.list.id, listName: invitation.list.name })
}
}

View File

@@ -0,0 +1,27 @@
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 { CreateInvitationSchema } from './schema'
import { CreateInvitation } from './use-case'
/** POST /invitations — invites an email address to a list. */
export const createInvitationRoute = new Hono<AppEnv>().post(
'/',
requireSession,
validate.json(CreateInvitationSchema),
async (c) => {
const body = c.req.valid('json')
const result = await new CreateInvitation(prisma).execute({
listId: body.listId,
email: body.email,
invitedById: c.get('user').id,
})
return resultJson(c, result, { status: 201 })
},
)

View File

@@ -0,0 +1,9 @@
import { z } from 'zod'
/** Body of `POST /invitations`. */
export const CreateInvitationSchema = z.object({
listId: z.uuid('El identificador de la lista no es válido'),
email: z.email('Introduce un correo electrónico válido'),
})
export type CreateInvitationInput = z.infer<typeof CreateInvitationSchema>

View File

@@ -0,0 +1,154 @@
import { randomUUID } from 'node:crypto'
import {
type CreateInvitationResult,
Failure,
Ok,
type ProblemDetails,
problems,
type Result,
} from '@superlist/shared'
import { invitationEmail } from '@/lib/emails/invitation'
import { logger } from '@/lib/logger'
import { type Email, sendEmail } from '@/lib/mailer'
import type { Database } from '@/lib/prisma'
import { invitationUrl } from '@/lib/web-app-url'
/** Invitations expire after seven days. */
const INVITATION_TTL_MS = 7 * 24 * 60 * 60 * 1000
type Mailer = (email: Email) => Promise<void>
type CreateInvitationDependencies = {
mailer?: Mailer
now?: () => Date
generateToken?: () => string
}
/**
* Invites an email address to collaborate on a list.
*
* - If the email already has an account, membership is granted immediately so
* the list shows up the next time they sign in.
* - Otherwise a `pending` invitation is stored and the accept link is emailed.
*/
export class CreateInvitation {
private readonly mailer: Mailer
private readonly now: () => Date
private readonly generateToken: () => string
constructor(
private readonly db: Database,
dependencies: CreateInvitationDependencies = {},
) {
this.mailer = dependencies.mailer ?? sendEmail
this.now = dependencies.now ?? (() => new Date())
this.generateToken = dependencies.generateToken ?? (() => randomUUID())
}
async execute(input: {
listId: string
email: string
invitedById: string
}): Promise<Result<CreateInvitationResult, ProblemDetails>> {
const email = input.email.trim().toLowerCase()
const inviterMembership = await this.db.shoppingListMember.findUnique({
where: { listId_userId: { listId: input.listId, userId: input.invitedById } },
})
if (!inviterMembership) {
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
}
if (inviterMembership.role !== 'owner') {
return Failure(problems.forbidden('Solo el propietario puede invitar colaboradores.'))
}
const list = await this.db.shoppingList.findUnique({
where: { id: input.listId },
select: { id: true, name: true },
})
if (!list) {
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
}
const invitedUser = await this.db.user.findUnique({ where: { email } })
if (invitedUser) {
const alreadyMember = await this.db.shoppingListMember.findUnique({
where: { listId_userId: { listId: input.listId, userId: invitedUser.id } },
})
if (alreadyMember) {
return Failure(problems.conflict('Esa persona ya colabora en la lista.'))
}
} else {
const pending = await this.db.shoppingListInvitation.findFirst({
where: { listId: input.listId, email, status: 'pending' },
})
if (pending) {
return Failure(problems.conflict('Ya hay una invitación pendiente para ese correo.'))
}
}
const token = this.generateToken()
const invitation = await this.db.shoppingListInvitation.create({
data: {
listId: input.listId,
email,
token,
invitedById: input.invitedById,
expiresAt: new Date(this.now().getTime() + INVITATION_TTL_MS),
status: invitedUser ? 'accepted' : 'pending',
acceptedAt: invitedUser ? this.now() : null,
},
})
if (invitedUser) {
await this.db.shoppingListMember.create({
data: { listId: input.listId, userId: invitedUser.id, role: 'collaborator' },
})
}
const inviter = await this.db.user.findUnique({
where: { id: input.invitedById },
select: { name: true },
})
const message = {
to: email,
...invitationEmail({
inviterName: inviter?.name ?? 'Alguien',
listName: list.name,
acceptUrl: invitationUrl(token),
}),
}
if (invitedUser) {
// Best effort: the person already sees the list, so a mail failure is not fatal.
await this.mailer(message).catch((error: unknown) => {
logger.warn({ err: error, to: email }, 'could not send the invitation email')
})
return Ok({ status: 'added', email })
}
try {
await this.mailer(message)
} catch (error) {
// Without the email the invitee cannot know about the list: undo everything.
await this.db.shoppingListInvitation.delete({ where: { id: invitation.id } })
logger.error({ err: error, to: email }, 'failed to send the invitation email')
return Failure(
problems.unavailable('No pudimos enviar la invitación por correo. Inténtalo de nuevo.'),
)
}
return Ok({ status: 'invited', email })
}
}

View File

@@ -0,0 +1,13 @@
import { Hono } from 'hono'
import type { AppEnv } from '@/types'
import { acceptInvitationRoute } from './accept/route'
import { createInvitationRoute } from './create/route'
import { listPendingInvitationsRoute } from './list-pending/route'
/** `invitations` module: every feature of the module is mounted here. */
export const invitationsModule = new Hono<AppEnv>()
.route('/', listPendingInvitationsRoute)
.route('/', createInvitationRoute)
.route('/', acceptInvitationRoute)

View File

@@ -0,0 +1,21 @@
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 { ListPendingInvitations } from './use-case'
/** GET /invitations/pending — pending invitations for the signed-in user. */
export const listPendingInvitationsRoute = new Hono<AppEnv>().get(
'/pending',
requireSession,
async (c) => {
const result = await new ListPendingInvitations(prisma).execute({
email: c.get('user').email,
})
return resultJson(c, result)
},
)

View File

@@ -0,0 +1,38 @@
import { Ok, type PendingInvitation, type ProblemDetails, type Result } from '@superlist/shared'
import type { Database } from '@/lib/prisma'
/** Lists the still-pending invitations addressed to the signed-in user's email. */
export class ListPendingInvitations {
constructor(
private readonly db: Database,
private readonly now: () => Date = () => new Date(),
) {}
async execute(input: { email: string }): Promise<Result<PendingInvitation[], ProblemDetails>> {
const invitations = await this.db.shoppingListInvitation.findMany({
where: {
email: input.email.trim().toLowerCase(),
status: 'pending',
expiresAt: { gt: this.now() },
},
include: {
list: { select: { id: true, name: true } },
invitedBy: { select: { id: true, name: true } },
},
orderBy: { createdAt: 'desc' },
})
return Ok(
invitations.map((invitation) => ({
id: invitation.id,
email: invitation.email,
status: invitation.status,
expiresAt: invitation.expiresAt.toISOString(),
createdAt: invitation.createdAt.toISOString(),
list: { id: invitation.list.id, name: invitation.list.name },
invitedBy: { id: invitation.invitedBy.id, name: invitation.invitedBy.name },
})),
)
}
}