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

@@ -6,3 +6,9 @@ BETTER_AUTH_URL="http://localhost:4100"
NODE_ENV="development"
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
# LOG_LEVEL="info"
# Resend API key used to send invitation emails. Without it, emails are logged instead.
# RESEND_API_KEY="re_xxxxxxxx"
# From address for outgoing email (must be a verified Resend sender)
# MAIL_FROM="Superlist <invitaciones@superlist.app>"
# Public URL of the web app, used to build the accept-invitation links
WEB_APP_URL="http://localhost:7153"

View File

@@ -25,6 +25,7 @@
"pg": "^8.23.1",
"pino": "^10.4.0",
"pino-pretty": "^13.2.0",
"resend": "^6.32.1",
"zod": "^4.6.7"
},
"devDependencies": {

View File

@@ -0,0 +1,157 @@
-- CreateEnum
CREATE TYPE "list_role" AS ENUM ('owner', 'collaborator');
-- CreateEnum
CREATE TYPE "invitation_status" AS ENUM ('pending', 'accepted', 'revoked', 'expired');
-- CreateTable
CREATE TABLE "users" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"email" TEXT NOT NULL,
"email_verified" BOOLEAN NOT NULL DEFAULT false,
"image" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "users_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "sessions" (
"id" TEXT NOT NULL,
"expires_at" TIMESTAMP(3) NOT NULL,
"token" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"ip_address" TEXT,
"user_agent" TEXT,
"user_id" TEXT NOT NULL,
CONSTRAINT "sessions_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "accounts" (
"id" TEXT NOT NULL,
"account_id" TEXT NOT NULL,
"provider_id" TEXT NOT NULL,
"user_id" TEXT NOT NULL,
"access_token" TEXT,
"refresh_token" TEXT,
"id_token" TEXT,
"access_token_expires_at" TIMESTAMP(3),
"refresh_token_expires_at" TIMESTAMP(3),
"scope" TEXT,
"password" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "accounts_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "verifications" (
"id" TEXT NOT NULL,
"identifier" TEXT NOT NULL,
"value" TEXT NOT NULL,
"expires_at" TIMESTAMP(3) NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "verifications_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "shopping_lists" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"owner_id" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "shopping_lists_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "shopping_list_members" (
"id" TEXT NOT NULL,
"list_id" TEXT NOT NULL,
"user_id" TEXT NOT NULL,
"role" "list_role" NOT NULL DEFAULT 'collaborator',
"is_primary" BOOLEAN NOT NULL DEFAULT false,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "shopping_list_members_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "shopping_list_invitations" (
"id" TEXT NOT NULL,
"list_id" TEXT NOT NULL,
"email" TEXT NOT NULL,
"token" TEXT NOT NULL,
"status" "invitation_status" NOT NULL DEFAULT 'pending',
"invited_by_id" TEXT NOT NULL,
"expires_at" TIMESTAMP(3) NOT NULL,
"accepted_at" TIMESTAMP(3),
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "shopping_list_invitations_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "users_email_key" ON "users"("email");
-- CreateIndex
CREATE INDEX "sessions_user_id_idx" ON "sessions"("user_id");
-- CreateIndex
CREATE UNIQUE INDEX "sessions_token_key" ON "sessions"("token");
-- CreateIndex
CREATE INDEX "accounts_user_id_idx" ON "accounts"("user_id");
-- CreateIndex
CREATE INDEX "verifications_identifier_idx" ON "verifications"("identifier");
-- CreateIndex
CREATE INDEX "shopping_lists_owner_id_idx" ON "shopping_lists"("owner_id");
-- CreateIndex
CREATE INDEX "shopping_list_members_user_id_is_primary_idx" ON "shopping_list_members"("user_id", "is_primary");
-- CreateIndex
CREATE UNIQUE INDEX "shopping_list_members_list_id_user_id_key" ON "shopping_list_members"("list_id", "user_id");
-- CreateIndex
CREATE INDEX "shopping_list_invitations_list_id_status_idx" ON "shopping_list_invitations"("list_id", "status");
-- CreateIndex
CREATE INDEX "shopping_list_invitations_email_status_idx" ON "shopping_list_invitations"("email", "status");
-- CreateIndex
CREATE UNIQUE INDEX "shopping_list_invitations_token_key" ON "shopping_list_invitations"("token");
-- AddForeignKey
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "accounts" ADD CONSTRAINT "accounts_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "shopping_lists" ADD CONSTRAINT "shopping_lists_owner_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "shopping_list_members" ADD CONSTRAINT "shopping_list_members_list_id_fkey" FOREIGN KEY ("list_id") REFERENCES "shopping_lists"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "shopping_list_members" ADD CONSTRAINT "shopping_list_members_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "shopping_list_invitations" ADD CONSTRAINT "shopping_list_invitations_list_id_fkey" FOREIGN KEY ("list_id") REFERENCES "shopping_lists"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "shopping_list_invitations" ADD CONSTRAINT "shopping_list_invitations_invited_by_id_fkey" FOREIGN KEY ("invited_by_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View File

@@ -0,0 +1,20 @@
-- CreateTable
CREATE TABLE "list_items" (
"id" TEXT NOT NULL,
"shopping_list_id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"completed" BOOLEAN NOT NULL DEFAULT false,
"quantity" TEXT,
"notes" TEXT,
"order" INTEGER NOT NULL DEFAULT 0,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "list_items_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "list_items_shopping_list_id_order_idx" ON "list_items"("shopping_list_id", "order");
-- AddForeignKey
ALTER TABLE "list_items" ADD CONSTRAINT "list_items_shopping_list_id_fkey" FOREIGN KEY ("shopping_list_id") REFERENCES "shopping_lists"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View File

@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"

View File

@@ -1,5 +1,12 @@
// Prisma schema. Docs: https://pris.ly/d/prisma-schema
//
// Naming convention (see AGENTS.md): tables are plural snake_case
// (`shopping_lists`, `users`), columns are snake_case (`created_at`,
// `owner_id`) and enum types are snake_case (`list_role`), declared through
// `@@map` / `@map`. The Prisma *model* and *field* names stay PascalCase /
// camelCase because BetterAuth and the generated client address models by
// those names.
//
// After editing this file run `bun run db:migrate` (creates + applies a migration)
// and commit the generated migration under `prisma/migrations`.
@@ -14,67 +21,164 @@ generator client {
// --- BetterAuth core models -------------------------------------------------
// Shape generated by `bunx @better-auth/cli generate`. Keep in sync with the
// fields the auth config expects.
// fields the auth config expects, and keep the snake_case mapping below if you
// regenerate it.
model User {
id String @id
name String
email String
emailVerified Boolean @default(false)
emailVerified Boolean @default(false) @map("email_verified")
image String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
sessions Session[]
accounts Account[]
ownedLists ShoppingList[] @relation("ListOwner")
memberships ShoppingListMember[]
invitations ShoppingListInvitation[] @relation("InvitedBy")
@@unique([email])
@@map("user")
@@map("users")
}
model Session {
id String @id
expiresAt DateTime
expiresAt DateTime @map("expires_at")
token String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
ipAddress String?
userAgent String?
userId String
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
ipAddress String? @map("ip_address")
userAgent String? @map("user_agent")
userId String @map("user_id")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([token])
@@index([userId])
@@map("session")
@@map("sessions")
}
model Account {
id String @id
accountId String
providerId String
userId String
accountId String @map("account_id")
providerId String @map("provider_id")
userId String @map("user_id")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
accessToken String?
refreshToken String?
idToken String?
accessTokenExpiresAt DateTime?
refreshTokenExpiresAt DateTime?
accessToken String? @map("access_token")
refreshToken String? @map("refresh_token")
idToken String? @map("id_token")
accessTokenExpiresAt DateTime? @map("access_token_expires_at")
refreshTokenExpiresAt DateTime? @map("refresh_token_expires_at")
scope String?
password String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@index([userId])
@@map("account")
@@map("accounts")
}
model Verification {
id String @id
identifier String
value String
expiresAt DateTime
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
expiresAt DateTime @map("expires_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@index([identifier])
@@map("verification")
@@map("verifications")
}
// --- Domain models ----------------------------------------------------------
/// A collaborative shopping list. Membership (and therefore access) lives in
/// `ShoppingListMember`, not in this table.
model ShoppingList {
id String @id @default(uuid())
name String
ownerId String @map("owner_id")
owner User @relation("ListOwner", fields: [ownerId], references: [id], onDelete: Cascade)
members ShoppingListMember[]
invitations ShoppingListInvitation[]
items ListItem[]
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@index([ownerId])
@@map("shopping_lists")
}
model ListItem {
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")
shoppingList ShoppingList @relation(fields: [shoppingListId], references: [id], onDelete: Cascade)
@@index([shoppingListId, order])
@@map("list_items")
}
enum ListRole {
owner
collaborator
@@map("list_role")
}
/// Join table between a user and a list. `isPrimary` is per user: each person
/// picks their own main list among the ones they belong to.
model ShoppingListMember {
id String @id @default(uuid())
listId String @map("list_id")
list ShoppingList @relation(fields: [listId], references: [id], onDelete: Cascade)
userId String @map("user_id")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
role ListRole @default(collaborator)
isPrimary Boolean @default(false) @map("is_primary")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@unique([listId, userId])
@@index([userId, isPrimary])
@@map("shopping_list_members")
}
enum InvitationStatus {
pending
accepted
revoked
expired
@@map("invitation_status")
}
/// Pending or historical invitation of an email address to a list. When the
/// email already belongs to a user the membership is created immediately and
/// this record is stored as `accepted` for history.
model ShoppingListInvitation {
id String @id @default(uuid())
listId String @map("list_id")
list ShoppingList @relation(fields: [listId], references: [id], onDelete: Cascade)
email String
token String
status InvitationStatus @default(pending)
invitedById String @map("invited_by_id")
invitedBy User @relation("InvitedBy", fields: [invitedById], references: [id], onDelete: Cascade)
expiresAt DateTime @map("expires_at")
acceptedAt DateTime? @map("accepted_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@unique([token])
@@index([listId, status])
@@index([email, status])
@@map("shopping_list_invitations")
}

View File

@@ -7,6 +7,8 @@ import { auth } from '@/lib/auth'
import { logger } from '@/lib/logger'
import { errorHandler, notFoundHandler } from '@/lib/problem-details'
import { healthModule } from '@/modules/health'
import { invitationsModule } from '@/modules/invitations'
import { listsModule } from '@/modules/lists'
import type { AppEnv } from '@/types'
const allowedOrigins = (process.env.CORS_ORIGIN ?? 'http://localhost:7153')
@@ -41,6 +43,8 @@ export function createApp() {
app.on(['POST', 'GET'], '/api/auth/*', (c) => auth.handler(c.req.raw))
app.route('/health', healthModule)
app.route('/lists', listsModule)
app.route('/invitations', invitationsModule)
app.notFound(notFoundHandler)
app.onError(errorHandler)

View File

@@ -0,0 +1,42 @@
import { problems } from '@superlist/shared'
import type { Context, MiddlewareHandler } from 'hono'
import { auth } from '@/lib/auth'
import { problemResponse } from '@/lib/problem-details'
import type { AppEnv, SessionUser } from '@/types'
/** Reads the BetterAuth session for the current request, or `null`. */
export async function getSession(c: Context<AppEnv>) {
return auth.api.getSession({ headers: c.req.raw.headers })
}
/**
* Middleware for protected routes: resolves the BetterAuth session, exposes the
* user/session on the context and answers `401` when there is none.
*
* ```ts
* app.get('/', requireSession, (c) => {
* const user = c.get('user')
* ...
* })
* ```
*/
export const requireSession: MiddlewareHandler<AppEnv> = async (c, next) => {
const session = await auth.api.getSession({ headers: c.req.raw.headers })
if (!session) {
return problemResponse(c, problems.unauthorized())
}
const user: SessionUser = {
id: session.user.id,
name: session.user.name,
email: session.user.email,
image: session.user.image,
}
c.set('user', user)
c.set('session', { id: session.session.id, userId: session.user.id })
await next()
}

View File

@@ -1,6 +1,7 @@
import { betterAuth } from 'better-auth'
import { prismaAdapter } from 'better-auth/adapters/prisma'
import { acceptPendingInvitations, ensurePrimaryList } from '@/lib/list-membership'
import { prisma } from '@/lib/prisma'
const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
@@ -15,6 +16,20 @@ export const auth = betterAuth({
trustedOrigins,
emailAndPassword: {
enabled: true,
minPasswordLength: 8,
requireEmailVerification: false,
},
databaseHooks: {
user: {
create: {
// People invited before signing up get their shared lists on creation,
// and everyone ends up with at least one list of their own.
after: async (user) => {
await acceptPendingInvitations(prisma, { userId: user.id, email: user.email })
await ensurePrimaryList(prisma, { userId: user.id })
},
},
},
},
})

View File

@@ -0,0 +1,52 @@
import type { Email } from '@/lib/mailer'
type InvitationEmailInput = {
inviterName: string
listName: string
acceptUrl: string
}
/** Builds the "you have been invited to a list" email (in Spanish). */
export function invitationEmail({
inviterName,
listName,
acceptUrl,
}: InvitationEmailInput): Omit<Email, 'to'> {
const subject = `${inviterName} te invitó a la lista «${listName}»`
const text = [
`${inviterName} te invitó a colaborar en la lista de compras «${listName}» en Superlist.`,
'',
'Abre este enlace para aceptar la invitación:',
acceptUrl,
'',
'Si no tienes cuenta, podrás crear una en el mismo enlace.',
].join('\n')
const html = `<!doctype html>
<html lang="es">
<body style="font-family: ui-sans-serif, system-ui, sans-serif; background:#f4f4f5; padding:32px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:480px; margin:0 auto; background:#ffffff; border-radius:12px; padding:32px;">
<tr><td>
<h1 style="font-size:20px; margin:0 0 16px;">Te invitaron a una lista</h1>
<p style="font-size:15px; line-height:1.5; color:#3f3f46; margin:0 0 8px;">
<strong>${inviterName}</strong> te invitó a colaborar en la lista de compras
<strong>«${listName}»</strong> en Superlist.
</p>
<p style="font-size:15px; line-height:1.5; color:#3f3f46; margin:0 0 24px;">
Si todavía no tienes cuenta, podrás crear una en el mismo enlace.
</p>
<a href="${acceptUrl}" style="display:inline-block; background:#18181b; color:#ffffff; text-decoration:none; padding:12px 20px; border-radius:8px; font-size:15px;">
Aceptar invitación
</a>
<p style="font-size:13px; line-height:1.5; color:#71717a; margin:24px 0 0;">
Si el botón no funciona, copia y pega este enlace en tu navegador:<br />
<a href="${acceptUrl}" style="color:#2563eb;">${acceptUrl}</a>
</p>
</td></tr>
</table>
</body>
</html>`
return { subject, html, text }
}

View File

@@ -0,0 +1,58 @@
import type { Database } from '@/lib/prisma'
/**
* Grants membership for every `pending`, non-expired invitation that matches the
* email and marks those invitations as accepted.
*
* Called right after a BetterAuth user is created, so people who are invited
* before signing up see the shared lists as soon as they register.
*
* @returns how many invitations were accepted
*/
export async function acceptPendingInvitations(
db: Database,
{ userId, email }: { userId: string; email: string },
): Promise<number> {
const pending = await db.shoppingListInvitation.findMany({
where: { email, status: 'pending', expiresAt: { gt: new Date() } },
})
for (const invitation of pending) {
await db.$transaction([
db.shoppingListMember.upsert({
where: { listId_userId: { listId: invitation.listId, userId } },
update: {},
create: { listId: invitation.listId, userId, role: 'collaborator' },
}),
db.shoppingListInvitation.update({
where: { id: invitation.id },
data: { status: 'accepted', acceptedAt: new Date() },
}),
])
}
return pending.length
}
/**
* Guarantees the user has at least one list: when they belong to none, creates a
* "Lista principal" owned by them and marks it as their primary list. Called
* right after a BetterAuth user is created (after pending invitations are
* accepted) so every account has a starting point.
*/
export async function ensurePrimaryList(
db: Database,
{ userId }: { userId: string },
): Promise<void> {
const memberships = await db.shoppingListMember.count({ where: { userId } })
if (memberships > 0) return
await db.shoppingList.create({
data: {
name: 'Lista principal',
ownerId: userId,
members: { create: { userId, role: 'owner', isPrimary: true } },
},
})
}

View File

@@ -0,0 +1,46 @@
import { Resend } from 'resend'
import { logger } from '@/lib/logger'
/** Minimal email payload the API sends. */
export type Email = {
to: string
subject: string
html: string
text: string
}
const apiKey = process.env.RESEND_API_KEY
const from = process.env.MAIL_FROM ?? 'Superlist <onboarding@resend.dev>'
let client: Resend | null = null
function getClient(): Resend | null {
if (!apiKey) return null
client ??= new Resend(apiKey)
return client
}
/**
* Sends an email through Resend. Without `RESEND_API_KEY` (local development)
* it logs the message with Pino instead of sending it, so invitation links are
* still discoverable in the terminal.
*/
export async function sendEmail(email: Email): Promise<void> {
const resend = getClient()
if (!resend) {
logger.info(
{ to: email.to, subject: email.subject, text: email.text },
'email not sent (RESEND_API_KEY is not set) — logging payload instead',
)
return
}
const { error } = await resend.emails.send({ from, ...email })
if (error) {
throw new Error(`Resend failed to send the email: ${error.message}`)
}
}

View File

@@ -0,0 +1,13 @@
const configured = process.env.WEB_APP_URL?.trim()
const corsOrigin = (process.env.CORS_ORIGIN ?? 'http://localhost:7153')
.split(',')
.map((origin) => origin.trim())
.filter(Boolean)[0]
/** Public URL of the web app, used to build links inside emails. */
export const webAppUrl = configured || corsOrigin || 'http://localhost:7153'
/** Deep link the invited user opens to accept an invitation. */
export function invitationUrl(token: string): string {
return `${webAppUrl}/invitations/${token}`
}

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 },
})),
)
}
}

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(),
})
}
}

View File

@@ -1,9 +1,25 @@
import type { Logger } from '@/lib/logger'
/** Hono environment shared by every route: `c.get('logger')`, `c.get('requestId')`. */
/** Authenticated user attached to a request by the `requireSession` middleware. */
export type SessionUser = {
id: string
name: string
email: string
image?: string | null
}
/** Authenticated session attached to a request by the `requireSession` middleware. */
export type SessionContext = {
id: string
userId: string
}
/** Hono environment shared by every route: `c.get('logger')`, `c.get('requestId')`, … */
export type AppEnv = {
Variables: {
logger: Logger
requestId: string
user: SessionUser
session: SessionContext
}
}