feat: add collaborative shopping lists with items and invitations
Some checks failed
CI / Verify (push) Has been cancelled
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:
@@ -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)
|
||||
|
||||
42
apps/api/src/lib/auth-session.ts
Normal file
42
apps/api/src/lib/auth-session.ts
Normal 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()
|
||||
}
|
||||
@@ -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 })
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
52
apps/api/src/lib/emails/invitation.ts
Normal file
52
apps/api/src/lib/emails/invitation.ts
Normal 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 }
|
||||
}
|
||||
58
apps/api/src/lib/list-membership.ts
Normal file
58
apps/api/src/lib/list-membership.ts
Normal 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 } },
|
||||
},
|
||||
})
|
||||
}
|
||||
46
apps/api/src/lib/mailer.ts
Normal file
46
apps/api/src/lib/mailer.ts
Normal 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}`)
|
||||
}
|
||||
}
|
||||
13
apps/api/src/lib/web-app-url.ts
Normal file
13
apps/api/src/lib/web-app-url.ts
Normal 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}`
|
||||
}
|
||||
32
apps/api/src/modules/invitations/accept/route.ts
Normal file
32
apps/api/src/modules/invitations/accept/route.ts
Normal 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)
|
||||
},
|
||||
)
|
||||
133
apps/api/src/modules/invitations/accept/use-case.test.ts
Normal file
133
apps/api/src/modules/invitations/accept/use-case.test.ts
Normal 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)
|
||||
})
|
||||
})
|
||||
71
apps/api/src/modules/invitations/accept/use-case.ts
Normal file
71
apps/api/src/modules/invitations/accept/use-case.ts
Normal 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 })
|
||||
}
|
||||
}
|
||||
27
apps/api/src/modules/invitations/create/route.ts
Normal file
27
apps/api/src/modules/invitations/create/route.ts
Normal 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 })
|
||||
},
|
||||
)
|
||||
9
apps/api/src/modules/invitations/create/schema.ts
Normal file
9
apps/api/src/modules/invitations/create/schema.ts
Normal 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>
|
||||
154
apps/api/src/modules/invitations/create/use-case.ts
Normal file
154
apps/api/src/modules/invitations/create/use-case.ts
Normal 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 })
|
||||
}
|
||||
}
|
||||
13
apps/api/src/modules/invitations/index.ts
Normal file
13
apps/api/src/modules/invitations/index.ts
Normal 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)
|
||||
21
apps/api/src/modules/invitations/list-pending/route.ts
Normal file
21
apps/api/src/modules/invitations/list-pending/route.ts
Normal 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)
|
||||
},
|
||||
)
|
||||
38
apps/api/src/modules/invitations/list-pending/use-case.ts
Normal file
38
apps/api/src/modules/invitations/list-pending/use-case.ts
Normal 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 },
|
||||
})),
|
||||
)
|
||||
}
|
||||
}
|
||||
26
apps/api/src/modules/lists/create/route.ts
Normal file
26
apps/api/src/modules/lists/create/route.ts
Normal 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 })
|
||||
},
|
||||
)
|
||||
8
apps/api/src/modules/lists/create/schema.ts
Normal file
8
apps/api/src/modules/lists/create/schema.ts
Normal 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>
|
||||
84
apps/api/src/modules/lists/create/use-case.test.ts
Normal file
84
apps/api/src/modules/lists/create/use-case.test.ts
Normal 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)
|
||||
})
|
||||
})
|
||||
57
apps/api/src/modules/lists/create/use-case.ts
Normal file
57
apps/api/src/modules/lists/create/use-case.ts
Normal 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,
|
||||
},
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
26
apps/api/src/modules/lists/get/route.ts
Normal file
26
apps/api/src/modules/lists/get/route.ts
Normal 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)
|
||||
},
|
||||
)
|
||||
46
apps/api/src/modules/lists/get/use-case.ts
Normal file
46
apps/api/src/modules/lists/get/use-case.ts
Normal 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))
|
||||
}
|
||||
}
|
||||
19
apps/api/src/modules/lists/index.ts
Normal file
19
apps/api/src/modules/lists/index.ts
Normal 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)
|
||||
32
apps/api/src/modules/lists/items/create/route.ts
Normal file
32
apps/api/src/modules/lists/items/create/route.ts
Normal 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 })
|
||||
},
|
||||
)
|
||||
10
apps/api/src/modules/lists/items/create/schema.ts
Normal file
10
apps/api/src/modules/lists/items/create/schema.ts
Normal 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>
|
||||
44
apps/api/src/modules/lists/items/create/use-case.ts
Normal file
44
apps/api/src/modules/lists/items/create/use-case.ts
Normal 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))
|
||||
}
|
||||
}
|
||||
11
apps/api/src/modules/lists/items/index.ts
Normal file
11
apps/api/src/modules/lists/items/index.ts
Normal 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)
|
||||
26
apps/api/src/modules/lists/items/list/route.ts
Normal file
26
apps/api/src/modules/lists/items/list/route.ts
Normal 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)
|
||||
},
|
||||
)
|
||||
34
apps/api/src/modules/lists/items/list/use-case.ts
Normal file
34
apps/api/src/modules/lists/items/list/use-case.ts
Normal 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))
|
||||
}
|
||||
}
|
||||
28
apps/api/src/modules/lists/items/serialize.ts
Normal file
28
apps/api/src/modules/lists/items/serialize.ts
Normal 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(),
|
||||
}
|
||||
}
|
||||
15
apps/api/src/modules/lists/list/route.ts
Normal file
15
apps/api/src/modules/lists/list/route.ts
Normal 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)
|
||||
})
|
||||
28
apps/api/src/modules/lists/list/use-case.ts
Normal file
28
apps/api/src/modules/lists/list/use-case.ts
Normal 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)
|
||||
}
|
||||
}
|
||||
8
apps/api/src/modules/lists/schema.ts
Normal file
8
apps/api/src/modules/lists/schema.ts
Normal 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>
|
||||
79
apps/api/src/modules/lists/serialize.ts
Normal file
79
apps/api/src/modules/lists/serialize.ts
Normal 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(),
|
||||
}
|
||||
}
|
||||
26
apps/api/src/modules/lists/set-primary/route.ts
Normal file
26
apps/api/src/modules/lists/set-primary/route.ts
Normal 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 })
|
||||
},
|
||||
)
|
||||
65
apps/api/src/modules/lists/set-primary/use-case.test.ts
Normal file
65
apps/api/src/modules/lists/set-primary/use-case.test.ts
Normal 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 },
|
||||
},
|
||||
])
|
||||
})
|
||||
})
|
||||
31
apps/api/src/modules/lists/set-primary/use-case.ts
Normal file
31
apps/api/src/modules/lists/set-primary/use-case.ts
Normal 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)
|
||||
}
|
||||
}
|
||||
30
apps/api/src/modules/lists/update/route.ts
Normal file
30
apps/api/src/modules/lists/update/route.ts
Normal 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)
|
||||
},
|
||||
)
|
||||
8
apps/api/src/modules/lists/update/schema.ts
Normal file
8
apps/api/src/modules/lists/update/schema.ts
Normal 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>
|
||||
49
apps/api/src/modules/lists/update/use-case.ts
Normal file
49
apps/api/src/modules/lists/update/use-case.ts
Normal 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(),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user