import { useEffect, useState } from 'react' import { useFormat, useTranslation } from '@xenia/i18n' import client from '../api/client' import { apiError } from '../api/errors' import db from '../db/posdb' // A table's earlier orders (plan step 4.7): GET /api/tables/{id}/history, never older than // the venue's `history` module allows. The last answer is kept on the phone (`kv` // history:) and shown while offline, marked as saved. const CACHE = id => `history:${id}` export default function TableHistory({ tableId }) { const { t } = useTranslation('waiter') const { formatTime, formatDate, formatMoney } = useFormat() const [state, setState] = useState({ loading: true, data: null, cached: false, error: '' }) const [open, setOpen] = useState(null) useEffect(() => { let alive = true client.get(`/api/tables/${tableId}/history`) .then(async r => { try { await db.kv.put({ key: CACHE(tableId), value: { ...r.data, saved_at: new Date().toISOString() } }) } catch { /* storage full: still shown */ } if (alive) setState({ loading: false, data: r.data, cached: false, error: '' }) }) .catch(async err => { const saved = await db.kv.get(CACHE(tableId)).then(row => row?.value ?? null).catch(() => null) if (alive) setState({ loading: false, data: saved, cached: !!saved, error: saved ? '' : apiError(err, t('history.failed')) }) }) return () => { alive = false } }, [tableId]) // eslint-disable-line react-hooks/exhaustive-deps if (state.loading) return

{t('common.loading')}

if (state.error) return

{state.error}

const orders = state.data?.orders ?? [] const days = state.data?.history_days return (
{state.cached && (
{t('history.cached', { time: formatTime(state.data.saved_at) })}
)} {orders.length === 0 && (

{t('history.none')}

)} {orders.map(o => { const expanded = open === o.id return (
{expanded && (
{o.items.map(i => (
×{i.quantity} {i.name} {i.options.length > 0 && · {i.options.join(', ')}} {formatMoney(i.total)}
))}
)}
) })} {days != null && (
{t('history.limit', { count: days })}
)}
) }