import type { ListItem } from '@superlist/shared' import { isSameLocalDay } from './dates' export type SplitItems = { /** Items still to buy, in the API's order (by `order`). */ pending: ListItem[] /** Items bought during the current local day, most recent first. */ boughtToday: ListItem[] } /** * Splits a list's items into the two groups the UI renders: pending items * and items bought today. Items bought on a previous local day are dropped * entirely — they stay `completed` in the database but are only shown on * the day they were bought. */ export function splitItems(items: ListItem[], now: Date): SplitItems { const pending: ListItem[] = [] const boughtToday: ListItem[] = [] for (const item of items) { if (!item.completed) { pending.push(item) continue } // A completed item without `boughtAt` is legacy data with no known // purchase day, so it is not considered bought today. if (item.boughtAt && isSameLocalDay(new Date(item.boughtAt), now)) { boughtToday.push(item) } } boughtToday.sort( (a, b) => new Date(b.boughtAt ?? 0).getTime() - new Date(a.boughtAt ?? 0).getTime(), ) return { pending, boughtToday } } /** * The quantity to show at the right of an item's name, or `null` when it must * stay hidden. Only quantities above one earn their place in the row, so a * plain "1" does not add noise: the leading number of the string is parsed * ("2" → 2, "2 kg" → 2, "0,5" → 0.5) and anything without one is hidden. */ export function quantityLabel(quantity: string | null): string | null { if (!quantity) return null const trimmed = quantity.trim() const leadingNumber = /^(\d+(?:[.,]\d+)?)/.exec(trimmed) if (!leadingNumber) return null return Number.parseFloat(leadingNumber[1].replace(',', '.')) > 1 ? trimmed : null }