diff --git a/apps/api/src/modules/lists/items/update/route.ts b/apps/api/src/modules/lists/items/update/route.ts index b16466a..1e939d4 100644 --- a/apps/api/src/modules/lists/items/update/route.ts +++ b/apps/api/src/modules/lists/items/update/route.ts @@ -9,7 +9,7 @@ import type { AppEnv } from '@/types' import { ItemParamsSchema, UpdateItemSchema } from './schema' import { UpdateItem } from './use-case' -/** PATCH /lists/:listId/items/:itemId — updates an item's bought state and/or quantity. */ +/** PATCH /lists/:listId/items/:itemId — updates an item's bought state, quantity and/or notes. */ export const updateItemRoute = new Hono().patch( '/:itemId', requireSession, @@ -17,13 +17,14 @@ export const updateItemRoute = new Hono().patch( validate.json(UpdateItemSchema), async (c) => { const { listId, itemId } = c.req.valid('param') - const { completed, quantity } = c.req.valid('json') + const { completed, quantity, notes } = c.req.valid('json') const result = await new UpdateItem(prisma).execute({ listId, itemId, userId: c.get('user').id, completed, quantity, + notes, }) return resultJson(c, result) diff --git a/apps/api/src/modules/lists/items/update/schema.ts b/apps/api/src/modules/lists/items/update/schema.ts index e38c200..5229186 100644 --- a/apps/api/src/modules/lists/items/update/schema.ts +++ b/apps/api/src/modules/lists/items/update/schema.ts @@ -13,9 +13,14 @@ export const UpdateItemSchema = z .object({ completed: z.boolean().optional(), quantity: z.string().trim().max(40, 'Máximo 40 caracteres').nullable().optional(), + notes: z.string().trim().max(280, 'Máximo 280 caracteres').nullable().optional(), }) - .refine((value) => value.completed !== undefined || value.quantity !== undefined, { - message: 'Indica al menos un campo para actualizar.', - }) + .refine( + (value) => + value.completed !== undefined || value.quantity !== undefined || value.notes !== undefined, + { + message: 'Indica al menos un campo para actualizar.', + }, + ) export type UpdateItemInput = z.infer diff --git a/apps/api/src/modules/lists/items/update/use-case.test.ts b/apps/api/src/modules/lists/items/update/use-case.test.ts index f394fa3..770bd6e 100644 --- a/apps/api/src/modules/lists/items/update/use-case.test.ts +++ b/apps/api/src/modules/lists/items/update/use-case.test.ts @@ -48,7 +48,7 @@ function createDb(options: { membership: unknown; item: ItemRow | null }) { // The use case only sends the fields it changes, so the stored row is // simulated by merging those fields into the row the query returned. update: async (args: { - data: Partial> + data: Partial> }) => { updates.push(args) return { ...options.item, ...args.data } as ItemRow @@ -170,6 +170,45 @@ describe('UpdateItem', () => { expect(result.value.quantity).toBeNull() }) + it('updates only the notes, leaving the rest untouched', async () => { + const { db, updates } = createDb({ membership: { role: 'owner' }, item: itemRow(false, null) }) + const { events, published } = createBus() + const result = await new UpdateItem(db, events).execute({ + listId: 'list-1', + itemId: 'item-1', + userId: 'user-1', + notes: ' sin lactosa ', + }) + + expect(result.ok).toBe(true) + if (!result.ok) throw new Error('expected the use case to succeed') + + const data = updates[0] as { data: { notes?: string | null } } + expect(data.data).toEqual({ notes: 'sin lactosa' }) + expect(result.value.notes).toBe('sin lactosa') + expect(result.value.quantity).toBe('1 L') + + expect(published).toEqual([{ type: 'item.updated', listId: 'list-1', item: result.value }]) + }) + + it('clears the notes when an empty value is sent', async () => { + const { db, updates } = createDb({ membership: { role: 'owner' }, item: itemRow(false, null) }) + const { events } = createBus() + const result = await new UpdateItem(db, events).execute({ + listId: 'list-1', + itemId: 'item-1', + userId: 'user-1', + notes: '', + }) + + expect(result.ok).toBe(true) + if (!result.ok) throw new Error('expected the use case to succeed') + + const data = updates[0] as { data: { notes?: string | null } } + expect(data.data).toEqual({ notes: null }) + expect(result.value.notes).toBeNull() + }) + it('marks the item back to pending, clears boughtAt and publishes item.updated', async () => { const { db, updates } = createDb({ membership: { role: 'collaborator' }, diff --git a/apps/api/src/modules/lists/items/update/use-case.ts b/apps/api/src/modules/lists/items/update/use-case.ts index 3ff4d5f..db7ca15 100644 --- a/apps/api/src/modules/lists/items/update/use-case.ts +++ b/apps/api/src/modules/lists/items/update/use-case.ts @@ -20,10 +20,12 @@ type UpdateItemFields = { completed?: boolean /** New quantity (`null` or an empty string clears it); when omitted it stays untouched. */ quantity?: string | null + /** New notes (`null` or an empty string clears them); when omitted they stay untouched. */ + notes?: string | null } /** - * Updates an item's bought state and/or its quantity. Only members can do it. + * Updates an item's bought state, its quantity and/or its notes. Only members can do it. * `boughtAt` records the moment an item was marked as bought, for future * statistics, and is cleared when the item goes back to pending. */ @@ -50,7 +52,12 @@ export class UpdateItem { return Failure(problems.notFound('El artículo no existe en esta lista.')) } - const data: { completed?: boolean; boughtAt?: Date | null; quantity?: string | null } = {} + const data: { + completed?: boolean + boughtAt?: Date | null + quantity?: string | null + notes?: string | null + } = {} if (input.completed !== undefined) { data.completed = input.completed @@ -61,6 +68,10 @@ export class UpdateItem { data.quantity = input.quantity?.trim() || null } + if (input.notes !== undefined) { + data.notes = input.notes?.trim() || null + } + const updated = await this.db.listItem.update({ where: { id: item.id }, data, diff --git a/apps/web/src/components/items/bought-item-list.tsx b/apps/web/src/components/items/bought-item-list.tsx index 450f75f..3df8e4c 100644 --- a/apps/web/src/components/items/bought-item-list.tsx +++ b/apps/web/src/components/items/bought-item-list.tsx @@ -5,12 +5,14 @@ import { Card } from '@/components/ui/card' import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible' import type { useUpdateItem } from '@/hooks/use-items' -import { ItemRow } from './item-row' +import { ItemRow, type ItemRowProps } from './item-row' type BoughtItemListProps = { items: ListItem[] updateItem: ReturnType savingIds: string[] + /** The editing state of each row, owned by the parent so only one row edits at a time. */ + editingProps: (itemId: string) => Pick } /** @@ -18,7 +20,12 @@ type BoughtItemListProps = { * marking an item visibly moves it down; the user can fold it. Tapping an item * here un-buys it and it returns to the pending list. */ -export function BoughtItemList({ items, updateItem, savingIds }: BoughtItemListProps) { +export function BoughtItemList({ + items, + updateItem, + savingIds, + editingProps, +}: BoughtItemListProps) { return ( @@ -34,6 +41,7 @@ export function BoughtItemList({ items, updateItem, savingIds }: BoughtItemListP item={item} updateItem={updateItem} isSaving={savingIds.includes(item.id)} + {...editingProps(item.id)} /> ))} diff --git a/apps/web/src/components/items/edit-quantity-dialog.tsx b/apps/web/src/components/items/edit-quantity-dialog.tsx deleted file mode 100644 index 95372a0..0000000 --- a/apps/web/src/components/items/edit-quantity-dialog.tsx +++ /dev/null @@ -1,101 +0,0 @@ -import { zodResolver } from '@hookform/resolvers/zod' -import type { ListItem } from '@superlist/shared' -import { useEffect } from 'react' -import { useForm } from 'react-hook-form' -import { z } from 'zod' - -import { Button } from '@/components/ui/button' -import { - Dialog, - DialogClose, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, -} from '@/components/ui/dialog' -import { Field, FieldError } from '@/components/ui/field' -import { Input } from '@/components/ui/input' -import type { useUpdateItem } from '@/hooks/use-items' - -const quantitySchema = z.object({ - // Free text so "2 kg" works; the API trims it and an empty value clears it. - quantity: z.string().trim().max(40, 'Máximo 40 caracteres'), -}) - -type QuantityValues = z.infer - -type EditQuantityDialogProps = { - item: ListItem - open: boolean - onOpenChange: (open: boolean) => void - updateItem: ReturnType -} - -/** Editor for an item's quantity: opened by swiping the row or right-clicking it. */ -export function EditQuantityDialog({ - item, - open, - onOpenChange, - updateItem, -}: EditQuantityDialogProps) { - const form = useForm({ - resolver: zodResolver(quantitySchema), - defaultValues: { quantity: item.quantity ?? '' }, - }) - - // The dialog always opens showing the current value, which may have changed - // while it was closed (another member's edit over SSE, or a failed optimistic - // update rolling back). - useEffect(() => { - if (open) form.reset({ quantity: item.quantity ?? '' }) - }, [open, item.quantity, form]) - - const onSubmit = form.handleSubmit((values) => { - updateItem.mutate( - { itemId: item.id, quantity: values.quantity || null }, - { - // The row already shows the new value optimistically, so on success - // nothing else is left to do. On error the hook reports the problem - // details and this dialog stays open, keeping the typed text for a retry. - onSuccess: () => onOpenChange(false), - }, - ) - }) - - return ( - - -
- - Editar cantidad - - Cantidad de «{item.name}». Déjala vacía para quitarla. - - - - - - -
- - - - - - -
-
- ) -} diff --git a/apps/web/src/components/items/item-editor.tsx b/apps/web/src/components/items/item-editor.tsx new file mode 100644 index 0000000..44d2ca3 --- /dev/null +++ b/apps/web/src/components/items/item-editor.tsx @@ -0,0 +1,106 @@ +import { zodResolver } from '@hookform/resolvers/zod' +import type { ListItem } from '@superlist/shared' +import type { Ref } from 'react' +import { useForm } from 'react-hook-form' +import { z } from 'zod' + +import { Button } from '@/components/ui/button' +import { Field, FieldError } from '@/components/ui/field' +import { Input } from '@/components/ui/input' +import { Textarea } from '@/components/ui/textarea' +import type { useUpdateItem } from '@/hooks/use-items' + +const itemDetailsSchema = z.object({ + // Free text so "2 kg" works; the API trims it and an empty value clears it. + quantity: z.string().trim().max(40, 'Máximo 40 caracteres'), + notes: z.string().trim().max(280, 'Máximo 280 caracteres'), +}) + +type ItemDetailsValues = z.infer + +type ItemEditorProps = { + item: ListItem + updateItem: ReturnType + onClose: () => void + /** + * Receives the quantity input, so the row can focus it synchronously from the + * gesture that opened the editor (iOS only shows the keyboard that way). + */ + quantityInputRef?: Ref +} + +/** + * Inline editor for an item's quantity and notes, shown right below its row. + * Opened by swiping the row to the left or right-clicking it. + */ +export function ItemEditor({ item, updateItem, onClose, quantityInputRef }: ItemEditorProps) { + // The editor only exists while open, so it always starts from the current + // values (including another member's edit received over SSE). + const form = useForm({ + resolver: zodResolver(itemDetailsSchema), + defaultValues: { quantity: item.quantity ?? '', notes: item.notes ?? '' }, + }) + + const { ref: registerQuantityRef, ...quantityField } = form.register('quantity') + + const onSubmit = form.handleSubmit((values) => { + updateItem.mutate( + { itemId: item.id, quantity: values.quantity || null, notes: values.notes || null }, + { + // The row already shows the new values optimistically, so on success + // nothing else is left to do. On error the hook reports the problem + // details and the editor stays open, keeping the typed text for a retry. + onSuccess: onClose, + }, + ) + }) + + return ( +
{ + if (event.key !== 'Escape') return + event.preventDefault() + onClose() + }} + className="bg-muted/40 flex flex-col gap-3 border-t px-4 py-3" + > + + { + registerQuantityRef(element) + if (typeof quantityInputRef === 'function') quantityInputRef(element) + else if (quantityInputRef) quantityInputRef.current = element + }} + /> + + + +