diff --git a/apps/api/prisma/migrations/20261125121747_pinned_lists/migration.sql b/apps/api/prisma/migrations/20261125121747_pinned_lists/migration.sql new file mode 100644 index 0000000..9c6c955 --- /dev/null +++ b/apps/api/prisma/migrations/20261125121747_pinned_lists/migration.sql @@ -0,0 +1,7 @@ +-- AlterTable +ALTER TABLE "shopping_list_members" ADD COLUMN "icon" TEXT, +ADD COLUMN "is_pinned" BOOLEAN NOT NULL DEFAULT false, +ADD COLUMN "pinned_order" INTEGER; + +-- CreateIndex +CREATE INDEX "shopping_list_members_user_id_is_pinned_idx" ON "shopping_list_members"("user_id", "is_pinned"); diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index e6f2267..63ad81c 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -168,11 +168,18 @@ model ShoppingListMember { user User @relation(fields: [userId], references: [id], onDelete: Cascade) role ListRole @default(collaborator) isPrimary Boolean @default(false) @map("is_primary") + /// Per user: the list is pinned to the always-visible bar (at most 4 per user). + isPinned Boolean @default(false) @map("is_pinned") + /// Position among the user's pinned lists (pin order); null when not pinned. + pinnedOrder Int? @map("pinned_order") + /// Per user: key of the icon chosen for the list (see `LIST_ICONS` in `@superlist/shared`). + icon String? createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") @@unique([listId, userId]) @@index([userId, isPrimary]) + @@index([userId, isPinned]) @@map("shopping_list_members") } diff --git a/apps/api/src/modules/lists/create/use-case.test.ts b/apps/api/src/modules/lists/create/use-case.test.ts index 8e72158..fe006a7 100644 --- a/apps/api/src/modules/lists/create/use-case.test.ts +++ b/apps/api/src/modules/lists/create/use-case.test.ts @@ -33,12 +33,14 @@ function createDb({ 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 }, + _count: { members: membershipsOnCreate, items: 0 }, members: [ { id: 'member-1', role: 'owner', isPrimary: input.data.members.create.isPrimary, + isPinned: false, + icon: null, }, ], } @@ -65,6 +67,9 @@ describe('CreateShoppingList', () => { name: 'Compra semanal', role: 'owner', isPrimary: true, + isPinned: false, + icon: null, + pendingCount: 0, memberCount: 1, createdAt: '2026-10-15T00:00:00.000Z', updatedAt: '2026-10-15T00:00:00.000Z', diff --git a/apps/api/src/modules/lists/create/use-case.ts b/apps/api/src/modules/lists/create/use-case.ts index 80c97b1..fa596ee 100644 --- a/apps/api/src/modules/lists/create/use-case.ts +++ b/apps/api/src/modules/lists/create/use-case.ts @@ -2,7 +2,7 @@ import { Ok, type ProblemDetails, type Result, type ShoppingListSummary } from ' import type { Database } from '@/lib/prisma' -import { toSummary } from '../serialize' +import { summaryCountInclude, toSummary } from '../serialize' /** Creates a shopping list owned by the user. The first list becomes primary. */ export class CreateShoppingList { @@ -29,7 +29,7 @@ export class CreateShoppingList { }, }, include: { - _count: { select: { members: true } }, + ...summaryCountInclude, members: { where: { userId: input.userId } }, }, }) @@ -44,6 +44,8 @@ export class CreateShoppingList { toSummary({ role: membership.role, isPrimary: membership.isPrimary, + isPinned: membership.isPinned, + icon: membership.icon, list: { id: list.id, name: list.name, diff --git a/apps/api/src/modules/lists/index.ts b/apps/api/src/modules/lists/index.ts index 59e5d78..fcb07bf 100644 --- a/apps/api/src/modules/lists/index.ts +++ b/apps/api/src/modules/lists/index.ts @@ -7,6 +7,7 @@ import { listEventsRoute } from './events/route' import { getListRoute } from './get/route' import { listItemsModule } from './items' import { listListsRoute } from './list/route' +import { updateListPreferencesRoute } from './preferences/route' import { setPrimaryListRoute } from './set-primary/route' import { updateListRoute } from './update/route' @@ -17,5 +18,6 @@ export const listsModule = new Hono() .route('/', getListRoute) .route('/', updateListRoute) .route('/', setPrimaryListRoute) + .route('/', updateListPreferencesRoute) .route('/:listId/items', listItemsModule) .route('/:listId/events', listEventsRoute) diff --git a/apps/api/src/modules/lists/list/use-case.test.ts b/apps/api/src/modules/lists/list/use-case.test.ts new file mode 100644 index 0000000..e147044 --- /dev/null +++ b/apps/api/src/modules/lists/list/use-case.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from 'bun:test' + +import type { Database } from '@/lib/prisma' + +import { ListShoppingLists } from './use-case' + +describe('ListShoppingLists', () => { + it('returns the pending count and the user preferences of each list', async () => { + const queries: unknown[] = [] + const db = { + shoppingListMember: { + findMany: async (args: unknown) => { + queries.push(args) + + return [ + { + role: 'owner', + isPrimary: false, + isPinned: true, + icon: 'unknown-icon', + list: { + id: 'list-1', + name: 'Verdulería', + createdAt: new Date('2026-11-01T00:00:00.000Z'), + updatedAt: new Date('2026-11-02T00:00:00.000Z'), + _count: { members: 1, items: 4 }, + }, + }, + ] + }, + }, + } + + const result = await new ListShoppingLists(db as unknown as Database).execute({ + userId: 'user-1', + }) + + expect(result.ok).toBe(true) + if (!result.ok) throw new Error('expected the use case to succeed') + expect(result.value).toEqual([ + { + id: 'list-1', + name: 'Verdulería', + role: 'owner', + isPrimary: false, + isPinned: true, + icon: null, + pendingCount: 4, + memberCount: 1, + createdAt: '2026-11-01T00:00:00.000Z', + updatedAt: '2026-11-02T00:00:00.000Z', + }, + ]) + expect(queries[0]).toMatchObject({ + include: { + list: { include: { _count: { select: { items: { where: { completed: false } } } } } }, + }, + }) + }) +}) diff --git a/apps/api/src/modules/lists/list/use-case.ts b/apps/api/src/modules/lists/list/use-case.ts index 6a12446..c0ed8cd 100644 --- a/apps/api/src/modules/lists/list/use-case.ts +++ b/apps/api/src/modules/lists/list/use-case.ts @@ -2,27 +2,27 @@ import { Ok, type ProblemDetails, type Result, type ShoppingListSummary } from ' import type { Database } from '@/lib/prisma' -/** Lists every shopping list the user belongs to (owned or shared). */ +import { summaryCountInclude, toSummary } from '../serialize' + +/** + * Lists every shopping list the user belongs to (owned or shared): the primary + * one first, then the pinned ones in pin order, then the rest, newest first. + */ export class ListShoppingLists { constructor(private readonly db: Database) {} async execute(input: { userId: string }): Promise> { const memberships = await this.db.shoppingListMember.findMany({ where: { userId: input.userId }, - include: { list: { include: { _count: { select: { members: true } } } } }, - orderBy: [{ isPrimary: 'desc' }, { list: { createdAt: 'desc' } }], + include: { list: { include: summaryCountInclude } }, + orderBy: [ + { isPrimary: 'desc' }, + { isPinned: 'desc' }, + { pinnedOrder: { sort: 'asc', nulls: 'last' } }, + { 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) + return Ok(memberships.map(toSummary)) } } diff --git a/apps/api/src/modules/lists/preferences/route.ts b/apps/api/src/modules/lists/preferences/route.ts new file mode 100644 index 0000000..61bf951 --- /dev/null +++ b/apps/api/src/modules/lists/preferences/route.ts @@ -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 { UpdateListPreferencesSchema } from './schema' +import { UpdateListPreferences } from './use-case' + +/** PATCH /lists/:listId/preferences — pins the list or changes its icon (per user). */ +export const updateListPreferencesRoute = new Hono().patch( + '/:listId/preferences', + requireSession, + validate.param(ListParamsSchema), + validate.json(UpdateListPreferencesSchema), + async (c) => { + const { listId } = c.req.valid('param') + const body = c.req.valid('json') + const result = await new UpdateListPreferences(prisma).execute({ + listId, + userId: c.get('user').id, + ...body, + }) + + return resultJson(c, result) + }, +) diff --git a/apps/api/src/modules/lists/preferences/schema.ts b/apps/api/src/modules/lists/preferences/schema.ts new file mode 100644 index 0000000..f12bfe9 --- /dev/null +++ b/apps/api/src/modules/lists/preferences/schema.ts @@ -0,0 +1,14 @@ +import { ListIconSchema } from '@superlist/shared' +import { z } from 'zod' + +/** Body of `PATCH /lists/:listId/preferences`: the user's own settings for the list. */ +export const UpdateListPreferencesSchema = z + .object({ + isPinned: z.boolean().optional(), + icon: ListIconSchema.nullable().optional(), + }) + .refine((body) => body.isPinned !== undefined || body.icon !== undefined, { + message: 'Indica al menos una preferencia para actualizar', + }) + +export type UpdateListPreferencesInput = z.infer diff --git a/apps/api/src/modules/lists/preferences/use-case.test.ts b/apps/api/src/modules/lists/preferences/use-case.test.ts new file mode 100644 index 0000000..07c4320 --- /dev/null +++ b/apps/api/src/modules/lists/preferences/use-case.test.ts @@ -0,0 +1,147 @@ +import { describe, expect, it } from 'bun:test' + +import type { Database } from '@/lib/prisma' + +import { UpdateListPreferences } from './use-case' + +type Membership = { + role: 'owner' | 'collaborator' + isPrimary: boolean + isPinned: boolean + icon: string | null +} + +function createDb({ + membership, + pinnedCount = 0, + maxPinnedOrder = null, +}: { + membership: Membership | null + pinnedCount?: number + maxPinnedOrder?: number | null +}) { + const updates: Array<{ data: Record }> = [] + + const tx = { + shoppingListMember: { + findUnique: async () => membership, + aggregate: async () => ({ + _count: { _all: pinnedCount }, + _max: { pinnedOrder: maxPinnedOrder }, + }), + update: async (args: { data: Record }) => { + updates.push(args) + + return { + ...membership, + ...args.data, + list: { + id: 'list-1', + name: 'Casa de fin de semana', + createdAt: new Date('2026-11-01T00:00:00.000Z'), + updatedAt: new Date('2026-11-01T00:00:00.000Z'), + _count: { members: 2, items: 3 }, + }, + } + }, + }, + } + + const db = { $transaction: async (fn: (client: typeof tx) => unknown) => fn(tx) } + + return { db: db as unknown as Database, updates } +} + +const collaborator: Membership = { + role: 'collaborator', + isPrimary: false, + isPinned: false, + icon: null, +} + +describe('UpdateListPreferences', () => { + it('answers 404 when the user does not belong to the list', async () => { + const { db, updates } = createDb({ membership: null }) + const result = await new UpdateListPreferences(db).execute({ + listId: 'list-1', + userId: 'user-1', + isPinned: true, + }) + + expect(result.ok).toBe(false) + if (result.ok) throw new Error('expected the use case to fail') + expect(result.error.status).toBe(404) + expect(updates).toHaveLength(0) + }) + + it('pins the list after the last pinned one and returns its pending count', async () => { + const { db, updates } = createDb({ + membership: collaborator, + pinnedCount: 2, + maxPinnedOrder: 5, + }) + const result = await new UpdateListPreferences(db).execute({ + listId: 'list-1', + userId: 'user-1', + isPinned: true, + icon: 'park', + }) + + expect(result.ok).toBe(true) + if (!result.ok) throw new Error('expected the use case to succeed') + expect(updates[0]?.data).toEqual({ isPinned: true, pinnedOrder: 6, icon: 'park' }) + expect(result.value).toMatchObject({ + isPinned: true, + icon: 'park', + pendingCount: 3, + memberCount: 2, + }) + }) + + it('refuses to pin more than four lists', async () => { + const { db, updates } = createDb({ + membership: collaborator, + pinnedCount: 4, + maxPinnedOrder: 4, + }) + const result = await new UpdateListPreferences(db).execute({ + listId: 'list-1', + userId: 'user-1', + isPinned: true, + }) + + expect(result.ok).toBe(false) + if (result.ok) throw new Error('expected the use case to fail') + expect(result.error.status).toBe(409) + expect(updates).toHaveLength(0) + }) + + it('unpins the list and clears its position', async () => { + const { db, updates } = createDb({ membership: { ...collaborator, isPinned: true } }) + const result = await new UpdateListPreferences(db).execute({ + listId: 'list-1', + userId: 'user-1', + isPinned: false, + }) + + expect(result.ok).toBe(true) + expect(updates[0]?.data).toEqual({ isPinned: false, pinnedOrder: null }) + }) + + it('changes only the icon of an already pinned list', async () => { + const { db, updates } = createDb({ + membership: { ...collaborator, isPinned: true, icon: 'carrot' }, + }) + const result = await new UpdateListPreferences(db).execute({ + listId: 'list-1', + userId: 'user-1', + isPinned: true, + icon: null, + }) + + expect(result.ok).toBe(true) + if (!result.ok) throw new Error('expected the use case to succeed') + expect(updates[0]?.data).toEqual({ icon: null }) + expect(result.value.icon).toBeNull() + }) +}) diff --git a/apps/api/src/modules/lists/preferences/use-case.ts b/apps/api/src/modules/lists/preferences/use-case.ts new file mode 100644 index 0000000..493f325 --- /dev/null +++ b/apps/api/src/modules/lists/preferences/use-case.ts @@ -0,0 +1,76 @@ +import { + Failure, + type ListIcon, + MAX_PINNED_LISTS, + Ok, + type ProblemDetails, + problems, + type Result, + type ShoppingListSummary, +} from '@superlist/shared' + +import type { Database } from '@/lib/prisma' + +import { summaryCountInclude, toSummary } from '../serialize' + +/** + * Updates the user's own settings for a list: whether it is pinned to the + * always-visible bar and which icon it shows. Any member may do it, because + * the settings are per user (like the primary list), not shared with the list. + */ +export class UpdateListPreferences { + constructor(private readonly db: Database) {} + + async execute(input: { + listId: string + userId: string + isPinned?: boolean + icon?: ListIcon | null + }): Promise> { + const where = { listId_userId: { listId: input.listId, userId: input.userId } } + + return this.db.$transaction(async (tx) => { + const membership = await tx.shoppingListMember.findUnique({ where }) + + if (!membership) { + return Failure(problems.notFound('La lista no existe o no tienes acceso.')) + } + + const data: { isPinned?: boolean; pinnedOrder?: number | null; icon?: ListIcon | null } = {} + + if (input.icon !== undefined) data.icon = input.icon + + if (input.isPinned === true && !membership.isPinned) { + const pinned = await tx.shoppingListMember.aggregate({ + where: { userId: input.userId, isPinned: true }, + _count: { _all: true }, + _max: { pinnedOrder: true }, + }) + + if (pinned._count._all >= MAX_PINNED_LISTS) { + return Failure( + problems.conflict( + `Puedes fijar hasta ${MAX_PINNED_LISTS} listas. Desfija otra para fijar esta.`, + ), + ) + } + + data.isPinned = true + data.pinnedOrder = (pinned._max.pinnedOrder ?? 0) + 1 + } + + if (input.isPinned === false && membership.isPinned) { + data.isPinned = false + data.pinnedOrder = null + } + + const updated = await tx.shoppingListMember.update({ + where, + data, + include: { list: { include: summaryCountInclude } }, + }) + + return Ok(toSummary(updated)) + }) + } +} diff --git a/apps/api/src/modules/lists/serialize.ts b/apps/api/src/modules/lists/serialize.ts index 0a86889..60efa42 100644 --- a/apps/api/src/modules/lists/serialize.ts +++ b/apps/api/src/modules/lists/serialize.ts @@ -1,4 +1,17 @@ -import type { ListMember, ShoppingListDetail, ShoppingListSummary } from '@superlist/shared' +import { + type ListIcon, + ListIconSchema, + type ListMember, + type ShoppingListDetail, + type ShoppingListSummary, +} from '@superlist/shared' + +/** Reads a stored icon key; unknown keys (e.g. one removed from the set) fall back to none. */ +export function toListIcon(icon: string | null): ListIcon | null { + const parsed = ListIconSchema.safeParse(icon) + + return parsed.success ? parsed.data : null +} type ListRow = { id: string @@ -10,16 +23,29 @@ type ListRow = { type MemberRow = { role: 'owner' | 'collaborator' isPrimary: boolean - list: ListRow & { _count: { members: number } } + isPinned: boolean + icon: string | null + list: ListRow & { _count: { members: number; items: number } } } -/** Maps a membership (with its list and member count) to the summary DTO. */ +/** + * Prisma `include` for a summary: the member count plus the pending items + * (`items` counts only the ones not bought yet). + */ +export const summaryCountInclude = { + _count: { select: { members: true, items: { where: { completed: false } } } }, +} as const + +/** Maps a membership (with its list, member and pending counts) 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, + isPinned: member.isPinned, + icon: toListIcon(member.icon), + pendingCount: member.list._count.items, memberCount: member.list._count.members, createdAt: member.list.createdAt.toISOString(), updatedAt: member.list.updatedAt.toISOString(), @@ -29,6 +55,8 @@ export function toSummary(member: MemberRow): ShoppingListSummary { type DetailRow = { role: 'owner' | 'collaborator' isPrimary: boolean + isPinned: boolean + icon: string | null list: ListRow & { members: Array<{ id: string @@ -65,6 +93,8 @@ export function toDetail(member: DetailRow): ShoppingListDetail { name: member.list.name, role: member.role, isPrimary: member.isPrimary, + isPinned: member.isPinned, + icon: toListIcon(member.icon), members, invitations: member.list.invitations.map((invitation) => ({ id: invitation.id, diff --git a/apps/api/src/modules/lists/update/use-case.ts b/apps/api/src/modules/lists/update/use-case.ts index a78abe5..a39b1c4 100644 --- a/apps/api/src/modules/lists/update/use-case.ts +++ b/apps/api/src/modules/lists/update/use-case.ts @@ -10,6 +10,8 @@ import { import { type ListEvents, listEvents } from '@/lib/events' import type { Database } from '@/lib/prisma' +import { summaryCountInclude, toSummary } from '../serialize' + /** Renames a list. Only the owner (`role: owner`) may do it. */ export class UpdateShoppingList { constructor( @@ -37,19 +39,11 @@ export class UpdateShoppingList { const list = await this.db.shoppingList.update({ where: { id: input.listId }, data: { name: input.name }, - include: { _count: { select: { members: true } } }, + include: summaryCountInclude, }) this.events.publish({ type: 'list.updated', listId: list.id, name: list.name }) - 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(), - }) + return Ok(toSummary({ ...membership, list })) } } diff --git a/apps/web/src/components/install-prompt.tsx b/apps/web/src/components/install-prompt.tsx index 2036845..7546b77 100644 --- a/apps/web/src/components/install-prompt.tsx +++ b/apps/web/src/components/install-prompt.tsx @@ -9,7 +9,7 @@ export function InstallPrompt() { if (!visible) return null return ( -
+
{needsManualInstructions ? ( diff --git a/apps/web/src/components/items/dictate-fab.tsx b/apps/web/src/components/items/dictate-fab.tsx index 0161bbd..fe44548 100644 --- a/apps/web/src/components/items/dictate-fab.tsx +++ b/apps/web/src/components/items/dictate-fab.tsx @@ -57,7 +57,7 @@ export function DictateFab({ listId }: DictateFabProps) { aria-label="Dictar ítems" aria-haspopup="dialog" aria-expanded={open} - className="fixed right-4 bottom-[calc(4.5rem+env(safe-area-inset-bottom)+0.75rem)] z-40 size-14 rounded-full shadow-lg md:right-6 md:bottom-6" + className="fixed right-4 bottom-[calc(var(--bottom-nav-height,4.5rem)+env(safe-area-inset-bottom)+0.75rem)] z-40 size-14 rounded-full shadow-lg md:right-6 md:bottom-6" onClick={() => { setOpen(true) // Called right in the click, before any state update, so the browser still diff --git a/apps/web/src/components/layout/app-sidebar.tsx b/apps/web/src/components/layout/app-sidebar.tsx index 8fc79f1..ee81376 100644 --- a/apps/web/src/components/layout/app-sidebar.tsx +++ b/apps/web/src/components/layout/app-sidebar.tsx @@ -3,6 +3,7 @@ import { AppLogo } from '@/components/app-logo' import { focusNewItemInput } from '@/components/items/create-item-form' import { isNavItemActive, NAV_ITEMS } from '@/components/layout/nav-items' import { NavUser } from '@/components/layout/nav-user' +import { PinnedListsSidebarGroup } from '@/components/layout/pinned-lists' import { Sidebar, SidebarContent, @@ -60,6 +61,7 @@ export function AppSidebar() { ))} + diff --git a/apps/web/src/components/layout/bottom-nav.tsx b/apps/web/src/components/layout/bottom-nav.tsx index 54a6c6a..d338d7a 100644 --- a/apps/web/src/components/layout/bottom-nav.tsx +++ b/apps/web/src/components/layout/bottom-nav.tsx @@ -2,6 +2,7 @@ import { Link, useRouterState } from '@tanstack/react-router' import { focusNewItemInput } from '@/components/items/create-item-form' import { isNavItemActive, NAV_ITEMS } from '@/components/layout/nav-items' +import { PinnedListsBar } from '@/components/layout/pinned-lists' import { cn } from '@/lib/utils' export function BottomNav() { @@ -9,6 +10,7 @@ export function BottomNav() { return (