172 lines
6.1 KiB
TypeScript
172 lines
6.1 KiB
TypeScript
import type { ListItem } from '@superlist/shared'
|
|
import { useRef } from 'react'
|
|
import { toast } from 'sonner'
|
|
|
|
import type { PreviewItem } from '@/components/items/item-input-preview'
|
|
import {
|
|
isOptimisticItem,
|
|
useCreateItem,
|
|
useItems,
|
|
useRemoveItems,
|
|
useUpdateItem,
|
|
} from '@/hooks/use-items'
|
|
import { useVoiceSplit } from '@/hooks/use-voice-split'
|
|
import { ApiError } from '@/lib/api-client'
|
|
import { findDuplicate, mergeBatch, mergeInto } from '@/lib/natural-input/merge'
|
|
import { literalItem, parseItemInput } from '@/lib/natural-input/parse-item'
|
|
|
|
/** How long the "Deshacer" of a dictation stays on screen. */
|
|
const DICTATION_UNDO_MS = 8000
|
|
|
|
/** Why a read item cannot be sent as is, mirroring the API limits, or `null`. */
|
|
export function itemLimitError(item: PreviewItem): string | null {
|
|
if (item.name.length > 120) return `«${item.name.slice(0, 20)}…»: máximo 120 caracteres`
|
|
if ((item.quantity?.length ?? 0) > 40) return `«${item.name}»: la cantidad es demasiado larga`
|
|
if ((item.notes?.length ?? 0) > 280) return `«${item.name}»: la nota es demasiado larga`
|
|
|
|
return null
|
|
}
|
|
|
|
/** The items `text` adds, each with the pending item it repeats, if any. */
|
|
export function readItems(text: string, literal: boolean, existing: ListItem[]): PreviewItem[] {
|
|
if (!text.trim()) return []
|
|
|
|
const items = literal ? [literalItem(text)] : mergeBatch(parseItemInput(text))
|
|
|
|
return items.map((item) => ({ ...item, duplicate: findDuplicate(existing, item.name) }))
|
|
}
|
|
|
|
/** What adding a batch of items did, so a dictation can be undone. */
|
|
type AddedItems = {
|
|
/** Ids of the items created (failed ones are left out). */
|
|
created: Promise<string[]>
|
|
/** The previous quantity/notes of the pending items that were added to. */
|
|
merged: { itemId: string; quantity: string | null; notes: string | null }[]
|
|
}
|
|
|
|
type UseAddItemsOptions = {
|
|
/** An item could not be created: `source` is the text it was read from. */
|
|
onItemFailed: (source: string, message: string) => void
|
|
/** A dictation was not added because an item breaks the API limits. */
|
|
onDictationRejected: (transcript: string, message: string) => void
|
|
}
|
|
|
|
/**
|
|
* Adds items to a list the way the "add an item" input does: an item already pending is
|
|
* added to instead of repeated, and a dictation is split into items by the API (with AI)
|
|
* and can be undone as a whole.
|
|
*/
|
|
export function useAddItems(
|
|
listId: string,
|
|
{ onItemFailed, onDictationRejected }: UseAddItemsOptions,
|
|
) {
|
|
const createItem = useCreateItem(listId)
|
|
const updateItem = useUpdateItem(listId)
|
|
const removeItems = useRemoveItems(listId)
|
|
const voiceSplit = useVoiceSplit()
|
|
const { data: items } = useItems(listId)
|
|
// Placeholders have no server id yet, so they cannot be added to.
|
|
const existing = (items ?? []).filter((item) => !isOptimisticItem(item))
|
|
// A dictation finishes after a request: by then the list may have changed.
|
|
const existingRef = useRef(existing)
|
|
existingRef.current = existing
|
|
|
|
/** Adds the items, or adds to the pending ones they repeat. */
|
|
const addItems = (toAdd: PreviewItem[]): AddedItems => {
|
|
const created: Promise<string | null>[] = []
|
|
const merged: AddedItems['merged'] = []
|
|
|
|
for (const item of toAdd) {
|
|
if (item.duplicate) {
|
|
const patch = mergeInto(item.duplicate, item)
|
|
if (patch.quantity !== undefined || patch.notes !== undefined) {
|
|
updateItem.mutate({ itemId: item.duplicate.id, ...patch })
|
|
merged.push({
|
|
itemId: item.duplicate.id,
|
|
quantity: item.duplicate.quantity,
|
|
notes: item.duplicate.notes,
|
|
})
|
|
}
|
|
toast(
|
|
patch.quantity
|
|
? `Se sumó a «${item.duplicate.name}» (${patch.quantity})`
|
|
: `«${item.duplicate.name}» ya está en la lista`,
|
|
)
|
|
continue
|
|
}
|
|
|
|
created.push(
|
|
createItem
|
|
.mutateAsync({
|
|
name: item.name,
|
|
quantity: item.quantity ?? undefined,
|
|
notes: item.notes ?? undefined,
|
|
})
|
|
.then(
|
|
(createdItem) => createdItem.id,
|
|
(error) => {
|
|
onItemFailed(
|
|
item.source,
|
|
error instanceof ApiError
|
|
? (error.problem.detail ?? error.problem.title)
|
|
: 'No pudimos añadir el artículo.',
|
|
)
|
|
return null
|
|
},
|
|
),
|
|
)
|
|
}
|
|
|
|
return {
|
|
created: Promise.all(created).then((ids) => ids.filter((id): id is string => id !== null)),
|
|
merged,
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The API splits the transcript into one string per item and each one is read by the
|
|
* usual parser. If the request fails, the transcript is read as typed text when it is
|
|
* already split into lines, and added as a single item otherwise.
|
|
*
|
|
* @returns how many items were understood (0 when the dictation had none).
|
|
*/
|
|
const addDictation = async (transcript: string): Promise<number> => {
|
|
let toAdd: PreviewItem[]
|
|
try {
|
|
const { items: spoken } = await voiceSplit.mutateAsync({ text: transcript })
|
|
toAdd = readItems(spoken.join('; '), false, existingRef.current)
|
|
} catch {
|
|
toAdd = readItems(transcript, !/[;\n]/.test(transcript), existingRef.current)
|
|
}
|
|
|
|
if (toAdd.length === 0) return 0
|
|
|
|
const limitError = toAdd.map(itemLimitError).find(Boolean)
|
|
if (limitError) {
|
|
onDictationRejected(transcript, limitError)
|
|
return toAdd.length
|
|
}
|
|
|
|
const { created, merged } = addItems(toAdd)
|
|
const createdIds = await created
|
|
const count = createdIds.length + merged.length
|
|
if (count === 0) return toAdd.length
|
|
|
|
toast(`Se ${count === 1 ? 'agregó 1 producto' : `agregaron ${count} productos`}`, {
|
|
// Longer than a plain toast: the user has to check what was understood first.
|
|
duration: DICTATION_UNDO_MS,
|
|
action: {
|
|
label: 'Deshacer',
|
|
onClick: () => {
|
|
void removeItems(createdIds)
|
|
for (const previous of merged) updateItem.mutate(previous)
|
|
},
|
|
},
|
|
})
|
|
|
|
return toAdd.length
|
|
}
|
|
|
|
return { existing, addItems, addDictation, processing: voiceSplit.isPending }
|
|
}
|