mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 01:44:13 +00:00
feat(costs): table view, and the wiki and help center for the new trip page
Costs gets a second view next to the ledger: the expenses as a table grouped by category, with name, date, total, persons and days editable in place and the per person and per day figures worked out beside them. A total with a payer or in a foreign currency stays locked and opens the expense instead, so balances and frozen rates are never changed behind the dialog. In the table view the side column shows a summary by category, day, payer and status. The switch sits in the bar and the choice is remembered; the ledger stays the default. On the Plan tab a place's reservation shows as one Reservation pill whose colour carries the status and which opens the booking, and the drop line of a drag that lost its source row now clears on the next mouse move. The booking detail formats its times in the user's clock, and a hotel without a check-out runs to the end of the last day in the timeline. The wiki pages of the trip are rewritten for the new layout, with new screenshots from the screenshot run (new Plan tab, bookings, transports, dialogs, costs table). The help center guides of the Plan tab are rewritten and translated into every locale, and every new string is translated.
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
// FE-COSTSVIEW-001 to FE-COSTSVIEW-004: the table as a second view of the Costs tab
|
||||
import { render, screen, waitFor, within } from '../../../tests/helpers/render'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { server } from '../../../tests/helpers/msw/server'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
|
||||
import { buildUser, buildTrip, buildBudgetItem } from '../../../tests/helpers/factories'
|
||||
import CostsPanel from './CostsPanel'
|
||||
|
||||
const tripMembers = [
|
||||
{ id: 1, username: 'alice', avatar_url: null },
|
||||
{ id: 2, username: 'bob', avatar_url: null },
|
||||
]
|
||||
|
||||
const lunch = { ...buildBudgetItem({ trip_id: 1, category: 'food', name: 'Lunch' }), id: 41, total_price: 24, persons: 2, expense_date: '2025-06-15', payers: [] }
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores()
|
||||
localStorage.removeItem('trek:costs-view')
|
||||
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true })
|
||||
seedStore(useTripStore, { trip: buildTrip({ id: 1, currency: 'EUR' }) })
|
||||
})
|
||||
|
||||
function serve(extra: Parameters<typeof server.use> = []) {
|
||||
server.use(
|
||||
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [lunch] })),
|
||||
http.get('/api/trips/1/budget/settlement', () => HttpResponse.json({ balances: [], flows: [], settlements: [] })),
|
||||
...extra,
|
||||
)
|
||||
}
|
||||
|
||||
describe('CostsPanel table view', () => {
|
||||
it('FE-COSTSVIEW-001: opens on the list, switches to the table and remembers it', async () => {
|
||||
serve()
|
||||
const user = userEvent.setup()
|
||||
const { unmount } = render(<CostsPanel tripId={1} tripMembers={tripMembers} />)
|
||||
await screen.findByText('Lunch')
|
||||
expect(screen.queryByRole('table')).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'List' })).toHaveAttribute('aria-pressed', 'true')
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Table' }))
|
||||
expect(screen.getByRole('table')).toBeInTheDocument()
|
||||
expect(localStorage.getItem('trek:costs-view')).toBe('table')
|
||||
unmount()
|
||||
|
||||
// Back on the tab later, the table is still the view.
|
||||
render(<CostsPanel tripId={1} tripMembers={tripMembers} />)
|
||||
expect(await screen.findByRole('table')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-COSTSVIEW-002: the table view swaps the category card for the four-way summary', async () => {
|
||||
localStorage.setItem('trek:costs-view', 'table')
|
||||
serve()
|
||||
render(<CostsPanel tripId={1} tripMembers={tripMembers} />)
|
||||
await screen.findByRole('table')
|
||||
expect(screen.getByRole('region', { name: 'Summary' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('region', { name: 'By category' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-COSTSVIEW-003: a cell edited in the table is saved to the expense', async () => {
|
||||
localStorage.setItem('trek:costs-view', 'table')
|
||||
let patched: Record<string, unknown> | null = null
|
||||
serve([http.put('/api/trips/1/budget/:id', async ({ request }) => {
|
||||
patched = (await request.json()) as Record<string, unknown>
|
||||
return HttpResponse.json({ item: { ...lunch, ...patched } })
|
||||
})])
|
||||
const user = userEvent.setup()
|
||||
render(<CostsPanel tripId={1} tripMembers={tripMembers} />)
|
||||
await user.click(await screen.findByRole('button', { name: 'Name: Lunch' }))
|
||||
const field = screen.getByRole('textbox', { name: 'Name' })
|
||||
await user.clear(field)
|
||||
await user.type(field, 'Team lunch{Enter}')
|
||||
await waitFor(() => expect(patched).toEqual({ name: 'Team lunch' }))
|
||||
})
|
||||
|
||||
it('FE-COSTSVIEW-004: a row added in a category is created empty with that category and date', async () => {
|
||||
localStorage.setItem('trek:costs-view', 'table')
|
||||
let posted: Record<string, unknown> | null = null
|
||||
serve([http.post('/api/trips/1/budget', async ({ request }) => {
|
||||
posted = (await request.json()) as Record<string, unknown>
|
||||
return HttpResponse.json({ item: { ...buildBudgetItem({ trip_id: 1, category: 'food', name: 'New Entry' }), id: 77, payers: [] } })
|
||||
})])
|
||||
const user = userEvent.setup()
|
||||
render(<CostsPanel tripId={1} tripMembers={tripMembers} />)
|
||||
const table = await screen.findByRole('table')
|
||||
await user.click(within(table).getByRole('button', { name: 'Add expense' }))
|
||||
await waitFor(() => expect(posted).toBeTruthy())
|
||||
expect(posted).toEqual(expect.objectContaining({ name: 'New Entry', category: 'food', total_price: 0, expense_date: '2025-06-15' }))
|
||||
})
|
||||
})
|
||||
@@ -34,7 +34,8 @@ import { Tooltip } from '../shared/Tooltip'
|
||||
import { DialogButton, DialogFooter, DialogHeader, DialogSection, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs } from '../shared/DialogShell'
|
||||
import { AddRowButton, EditorField, GRID_2, INPUT, PillSelect, Segmented, TEXTAREA } from '../shared/dialogParts'
|
||||
import { CountPill, EYEBROW } from '../Planner/bookings/bookingParts'
|
||||
import CostsToolbar from './CostsToolbar'
|
||||
import CostsToolbar, { type CostsView } from './CostsToolbar'
|
||||
import CostsTable, { CostsTableSummary } from './CostsTable'
|
||||
|
||||
interface CostsPanelProps {
|
||||
tripId: number
|
||||
@@ -82,9 +83,10 @@ type LedgerEntry =
|
||||
|
||||
const round2 = (n: number) => Math.round(n * 100) / 100
|
||||
const FIELD_H = 40 // shared height for the amount / currency / day row in the modal
|
||||
const COSTS_VIEW_KEY = 'trek:costs-view'
|
||||
|
||||
export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps) {
|
||||
const { trip, budgetItems, deleteBudgetItem, loadBudgetItems } = useTripStore()
|
||||
const { trip, budgetItems, deleteBudgetItem, loadBudgetItems, addBudgetItem, updateBudgetItem } = useTripStore()
|
||||
const me = useAuthStore(s => s.user?.id ?? -1)
|
||||
const can = useCanDo()
|
||||
const canEdit = can('budget_edit', trip)
|
||||
@@ -121,6 +123,15 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
const [expandedFinalId, setExpandedFinalId] = useState<number | null>(null)
|
||||
const [editingSettlement, setEditingSettlement] = useState<Settlement | null>(null)
|
||||
const [addingPayment, setAddingPayment] = useState(false)
|
||||
// The list stays what Costs opens with; the table is the planning view beside it,
|
||||
// remembered in this browser like the Bookings view.
|
||||
const [view, setViewState] = useState<CostsView>(() => {
|
||||
try { return localStorage.getItem(COSTS_VIEW_KEY) === 'table' ? 'table' : 'list' } catch { return 'list' }
|
||||
})
|
||||
const setView = (next: CostsView) => {
|
||||
setViewState(next)
|
||||
try { localStorage.setItem(COSTS_VIEW_KEY, next) } catch { /* storage unavailable: the choice lasts until reload */ }
|
||||
}
|
||||
|
||||
const people = tripMembers
|
||||
const personById = useCallback((id: number) => people.find(p => p.id === id), [people])
|
||||
@@ -304,6 +315,18 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
const handleDelete = async (id: number) => {
|
||||
try { await deleteBudgetItem(tripId, id); loadSettlement() } catch { toast.error(t('common.unknownError')) }
|
||||
}
|
||||
// The table's own writes: one cell at a time, and an empty row to type into.
|
||||
const updateFromTable = async (id: number, patch: Partial<BudgetItem>) => {
|
||||
try { await updateBudgetItem(tripId, id, patch); loadSettlement() } catch { toast.error(t('common.unknownError')) }
|
||||
}
|
||||
const addFromTable = async (category: string, expenseDate: string | null) => {
|
||||
try {
|
||||
return await addBudgetItem(tripId, { name: t('budget.newEntry'), category, total_price: 0, expense_date: expenseDate })
|
||||
} catch {
|
||||
toast.error(t('common.unknownError'))
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// CSV export of all expenses — the wiki-documented export that got lost in the
|
||||
// Costs rework (#1500). One row per expense, oldest first.
|
||||
@@ -399,6 +422,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
canEdit={canEdit} canSettle={(settlement?.flows || []).length > 0}
|
||||
onSettleAll={settleAll} onAddExpense={() => { setEditing(null); setModalOpen(true) }}
|
||||
onScanReceipt={receiptScan.offered ? receiptScan.open : undefined}
|
||||
view={view} onView={setView}
|
||||
filters={{
|
||||
query: search, onQuery: setSearch,
|
||||
owner: filter, onOwner: setFilter,
|
||||
@@ -441,7 +465,16 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
<div className="costs-main" style={{ gridColumn: 'span 3', minWidth: 0 }}>
|
||||
|
||||
{dayBanner}
|
||||
{dayGroups.length === 0 ? (
|
||||
{view === 'table' ? (
|
||||
filtered.length === 0 && budgetItems.length > 0 ? (
|
||||
<div className="text-content-faint" style={{ textAlign: 'center', padding: '60px 20px' }}>{t('costs.noMatch')}</div>
|
||||
) : (
|
||||
<CostsTable items={filtered} base={base} canEdit={canEdit}
|
||||
baseTotal={baseTotal} toBase={booked} currencyOf={curOf} fmt={v => fmt(v)} personName={personName}
|
||||
onUpdate={updateFromTable} onAdd={addFromTable}
|
||||
onOpen={e => { setEditing(e); setModalOpen(true) }} onDelete={id => void handleDelete(id)} />
|
||||
)
|
||||
) : dayGroups.length === 0 ? (
|
||||
search ? (
|
||||
<div className="text-content-faint" style={{ textAlign: 'center', padding: '60px 20px' }}>
|
||||
{t('costs.noMatch')}
|
||||
@@ -495,11 +528,15 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
<div className="px-4 py-4">{FinalBudgetList()}</div>
|
||||
</section>
|
||||
|
||||
{/* by category */}
|
||||
<section aria-label={t('costs.byCategory')} className={SIDE_CARD}>
|
||||
{sideHead(t('costs.byCategory'))}
|
||||
<div className="px-4 py-4">{CategoryBreakdown()}</div>
|
||||
</section>
|
||||
{/* by category; the table view sums up four ways instead */}
|
||||
{view === 'table' ? (
|
||||
<CostsTableSummary items={filtered} baseTotal={baseTotal} toBase={booked} fmt={v => fmt(v)} personName={personName} />
|
||||
) : (
|
||||
<section aria-label={t('costs.byCategory')} className={SIDE_CARD}>
|
||||
{sideHead(t('costs.byCategory'))}
|
||||
<div className="px-4 py-4">{CategoryBreakdown()}</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>)}
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
// FE-COSTSTABLE-001 to FE-COSTSTABLE-016
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, within, waitFor } from '../../../tests/helpers/render'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { resetAllStores } from '../../../tests/helpers/store'
|
||||
import { buildBudgetItem } from '../../../tests/helpers/factories'
|
||||
import type { BudgetItem } from '../../types'
|
||||
import CostsTable, { CostsTableSummary, type CostsTableProps } from './CostsTable'
|
||||
|
||||
const fmt = (v: number) => `${v.toFixed(2)} EUR`
|
||||
|
||||
function item(overrides: Partial<BudgetItem>): BudgetItem {
|
||||
return { ...buildBudgetItem(), persons: null, days: null, currency: 'EUR', payers: [], ...overrides } as BudgetItem
|
||||
}
|
||||
|
||||
function setup(items: BudgetItem[], overrides: Partial<CostsTableProps> = {}) {
|
||||
const props: CostsTableProps = {
|
||||
items,
|
||||
base: 'EUR',
|
||||
canEdit: true,
|
||||
baseTotal: e => e.total_price || 0,
|
||||
toBase: amount => amount,
|
||||
currencyOf: e => e.currency || 'EUR',
|
||||
fmt,
|
||||
personName: id => (id === 1 ? 'ada' : 'bob'),
|
||||
onUpdate: vi.fn().mockResolvedValue(undefined),
|
||||
onAdd: vi.fn().mockResolvedValue(null),
|
||||
onOpen: vi.fn(),
|
||||
onDelete: vi.fn(),
|
||||
...overrides,
|
||||
}
|
||||
render(<CostsTable {...props} />)
|
||||
return props
|
||||
}
|
||||
|
||||
beforeEach(() => resetAllStores())
|
||||
|
||||
describe('CostsTable', () => {
|
||||
it('FE-COSTSTABLE-001: groups expenses under their category with a subtotal and a trip total', () => {
|
||||
setup([
|
||||
item({ id: 1, name: 'Hotel', category: 'accommodation', total_price: 120 }),
|
||||
item({ id: 2, name: 'Ramen', category: 'food', total_price: 30 }),
|
||||
item({ id: 3, name: 'Snacks', category: 'food', total_price: 10 }),
|
||||
])
|
||||
const food = screen.getByRole('button', { name: /Food/ })
|
||||
expect(food).toHaveAttribute('aria-expanded', 'true')
|
||||
expect(within(food.closest('tr')!).getByText('40.00 EUR')).toBeInTheDocument()
|
||||
expect(within(screen.getByRole('button', { name: /Accommodation/ }).closest('tr')!).getByText('120.00 EUR')).toBeInTheDocument()
|
||||
expect(screen.getByRole('rowheader', { name: /Total/ }).closest('tr')).toHaveTextContent('160.00 EUR')
|
||||
})
|
||||
|
||||
it('FE-COSTSTABLE-002: works out per person, per day and per person per day', () => {
|
||||
setup([item({ id: 1, name: 'Ferry', category: 'transport', total_price: 80, persons: 2, days: 4 })])
|
||||
const row = screen.getByRole('button', { name: 'Name: Ferry' }).closest('tr')!
|
||||
expect(row).toHaveTextContent('40.00')
|
||||
expect(row).toHaveTextContent('20.00')
|
||||
expect(row).toHaveTextContent('10.00')
|
||||
})
|
||||
|
||||
it('FE-COSTSTABLE-003: an uneven split leaves the per-person columns empty', () => {
|
||||
setup([item({
|
||||
id: 1, name: 'Dinner', category: 'food', total_price: 90, persons: 2, days: 3,
|
||||
members: [{ user_id: 1, paid: 0, username: 'ada', amount: 60 }, { user_id: 2, paid: 0, username: 'bob', amount: 30 }],
|
||||
} as Partial<BudgetItem>)])
|
||||
const cells = screen.getByRole('button', { name: 'Name: Dinner' }).closest('tr')!.querySelectorAll('td')
|
||||
expect(cells[5].textContent).toBe('')
|
||||
expect(cells[6].textContent).toBe('30.00')
|
||||
expect(cells[7].textContent).toBe('')
|
||||
})
|
||||
|
||||
it('FE-COSTSTABLE-004: a name edits in place, Enter keeps it and Escape leaves it', async () => {
|
||||
const user = userEvent.setup()
|
||||
const props = setup([item({ id: 7, name: 'Taxi', category: 'transport', total_price: 15 })])
|
||||
await user.click(screen.getByRole('button', { name: 'Name: Taxi' }))
|
||||
const field = screen.getByRole('textbox', { name: 'Name' })
|
||||
await user.clear(field)
|
||||
await user.type(field, 'Airport taxi{Enter}')
|
||||
expect(props.onUpdate).toHaveBeenCalledWith(7, { name: 'Airport taxi' })
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Name: Taxi' }))
|
||||
await user.type(screen.getByRole('textbox', { name: 'Name' }), 'x{Escape}')
|
||||
expect(props.onUpdate).toHaveBeenCalledTimes(1)
|
||||
expect(screen.queryByRole('textbox', { name: 'Name' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-COSTSTABLE-005: an empty name is not saved', async () => {
|
||||
const user = userEvent.setup()
|
||||
const props = setup([item({ id: 7, name: 'Taxi', category: 'transport' })])
|
||||
await user.click(screen.getByRole('button', { name: 'Name: Taxi' }))
|
||||
await user.clear(screen.getByRole('textbox', { name: 'Name' }))
|
||||
await user.keyboard('{Enter}')
|
||||
expect(props.onUpdate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COSTSTABLE-006: a total nobody paid edits in place, with a comma as the decimal mark', async () => {
|
||||
const user = userEvent.setup()
|
||||
const props = setup([item({ id: 3, name: 'Museum', category: 'activities', total_price: 12 })])
|
||||
await user.click(screen.getByRole('button', { name: 'Total: 12.00 EUR' }))
|
||||
const field = screen.getByRole('textbox', { name: 'Total' })
|
||||
await user.clear(field)
|
||||
await user.type(field, '14,50')
|
||||
fireEvent.blur(field)
|
||||
expect(props.onUpdate).toHaveBeenCalledWith(3, { total_price: 14.5 })
|
||||
})
|
||||
|
||||
it('FE-COSTSTABLE-007: a total someone paid is locked and opens the expense instead', async () => {
|
||||
const user = userEvent.setup()
|
||||
const paid = item({ id: 4, name: 'Hotel', category: 'accommodation', total_price: 200, payers: [{ user_id: 1, amount: 200 }] } as Partial<BudgetItem>)
|
||||
const props = setup([paid])
|
||||
const total = screen.getByRole('button', { name: 'Total: 200.00 EUR' })
|
||||
fireEvent.mouseEnter(total)
|
||||
expect(await screen.findByRole('tooltip')).toHaveTextContent(/change the amount in the expense/)
|
||||
await user.click(total)
|
||||
expect(props.onOpen).toHaveBeenCalledWith(paid)
|
||||
expect(screen.queryByRole('textbox', { name: 'Total' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-COSTSTABLE-008: a total in another currency is locked and shows what was entered', async () => {
|
||||
setup([item({ id: 5, name: 'Swiss train', category: 'transport', total_price: 62, currency: 'CHF' })], {
|
||||
baseTotal: () => 66.4,
|
||||
})
|
||||
const total = screen.getByRole('button', { name: 'Total: 66.40 EUR' })
|
||||
expect(total).toHaveTextContent('62.00 CHF')
|
||||
fireEvent.mouseEnter(total)
|
||||
expect(await screen.findByRole('tooltip')).toHaveTextContent('Entered in CHF')
|
||||
})
|
||||
|
||||
it('FE-COSTSTABLE-009: persons and days fill in from an empty pill and clear again', async () => {
|
||||
const user = userEvent.setup()
|
||||
const props = setup([item({ id: 6, name: 'Boat', category: 'transport', total_price: 60 })])
|
||||
await user.click(screen.getByRole('button', { name: 'Persons' }))
|
||||
await user.type(screen.getByRole('textbox', { name: 'Persons' }), '3{Enter}')
|
||||
expect(props.onUpdate).toHaveBeenCalledWith(6, { persons: 3 })
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Days' }))
|
||||
await user.type(screen.getByRole('textbox', { name: 'Days' }), '0{Enter}')
|
||||
expect(props.onUpdate).toHaveBeenLastCalledWith(6, { days: null })
|
||||
})
|
||||
|
||||
it('FE-COSTSTABLE-010: a row added to a category takes its latest date and opens its name', async () => {
|
||||
const user = userEvent.setup()
|
||||
const created = item({ id: 99, name: 'New Entry', category: 'food' })
|
||||
const onAdd = vi.fn().mockResolvedValue(created)
|
||||
render(<CostsTable items={[
|
||||
item({ id: 1, name: 'Lunch', category: 'food', expense_date: '2025-06-02' }),
|
||||
item({ id: 2, name: 'Dinner', category: 'food', expense_date: '2025-06-04' }),
|
||||
created,
|
||||
]} base="EUR" canEdit baseTotal={e => e.total_price || 0} toBase={a => a} currencyOf={() => 'EUR'} fmt={fmt}
|
||||
personName={() => ''} onUpdate={vi.fn()} onAdd={onAdd} onOpen={vi.fn()} onDelete={vi.fn()} />)
|
||||
await user.click(screen.getByRole('button', { name: 'Add expense' }))
|
||||
expect(onAdd).toHaveBeenCalledWith('food', '2025-06-04')
|
||||
await waitFor(() => expect(screen.getByRole('textbox', { name: 'Name' })).toHaveValue('New Entry'))
|
||||
})
|
||||
|
||||
it('FE-COSTSTABLE-011: a category folds away and back', async () => {
|
||||
const user = userEvent.setup()
|
||||
setup([item({ id: 1, name: 'Ramen', category: 'food' })])
|
||||
await user.click(screen.getByRole('button', { name: /Food/ }))
|
||||
expect(screen.queryByText('Ramen')).not.toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: /Food/ }))
|
||||
expect(screen.getByText('Ramen')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-COSTSTABLE-012: the row menu edits in the dialog and deletes', async () => {
|
||||
const user = userEvent.setup()
|
||||
const e = item({ id: 8, name: 'Gift', category: 'shopping' })
|
||||
const props = setup([e])
|
||||
await user.click(screen.getByRole('button', { name: 'More options' }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Edit' }))
|
||||
expect(props.onOpen).toHaveBeenCalledWith(e)
|
||||
await user.click(screen.getByRole('button', { name: 'More options' }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Delete' }))
|
||||
expect(props.onDelete).toHaveBeenCalledWith(8)
|
||||
})
|
||||
|
||||
it('FE-COSTSTABLE-013: without edit rights the table reads only', async () => {
|
||||
const user = userEvent.setup()
|
||||
const e = item({ id: 9, name: 'Tip', category: 'tips', total_price: 5, expense_date: '2025-06-03' })
|
||||
const props = setup([e], { canEdit: false })
|
||||
expect(screen.queryByRole('button', { name: /^Name:/ })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Add expense' })).not.toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'More options' }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Open' }))
|
||||
expect(props.onOpen).toHaveBeenCalledWith(e)
|
||||
expect(screen.queryByRole('button', { name: 'Delete' })).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('CostsTableSummary', () => {
|
||||
const summaryItems = [
|
||||
item({ id: 1, name: 'Hotel', category: 'accommodation', total_price: 100, expense_date: '2025-06-02', payers: [{ user_id: 1, amount: 100 }] } as Partial<BudgetItem>),
|
||||
item({ id: 2, name: 'Ramen', category: 'food', total_price: 30, expense_date: '2025-06-01', payers: [{ user_id: 2, amount: 30 }] } as Partial<BudgetItem>),
|
||||
item({ id: 3, name: 'Snacks', category: 'food', total_price: 10 }),
|
||||
]
|
||||
const renderSummary = () => render(<CostsTableSummary items={summaryItems} baseTotal={e => e.total_price || 0} toBase={a => a} fmt={fmt} personName={id => (id === 1 ? 'ada' : 'bob')} />)
|
||||
|
||||
it('FE-COSTSTABLE-014: sums up by category, largest first', () => {
|
||||
renderSummary()
|
||||
const rows = within(screen.getByRole('region', { name: 'Summary' })).getAllByRole('listitem')
|
||||
expect(rows[0]).toHaveTextContent(/Accommodation.*100\.00 EUR/)
|
||||
expect(rows[1]).toHaveTextContent(/Food.*40\.00 EUR/)
|
||||
})
|
||||
|
||||
it('FE-COSTSTABLE-015: by day oldest first, the undated last', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderSummary()
|
||||
await user.click(screen.getByRole('button', { name: 'Day' }))
|
||||
const rows = within(screen.getByRole('region', { name: 'Summary' })).getAllByRole('listitem')
|
||||
expect(rows[0]).toHaveTextContent('30.00 EUR')
|
||||
expect(rows[1]).toHaveTextContent('100.00 EUR')
|
||||
expect(rows[2]).toHaveTextContent(/No date.*10\.00 EUR/)
|
||||
})
|
||||
|
||||
it('FE-COSTSTABLE-016: by payer with the unpaid on their own line, and paid against open', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderSummary()
|
||||
await user.click(screen.getByRole('button', { name: 'Payer' }))
|
||||
const region = screen.getByRole('region', { name: 'Summary' })
|
||||
expect(region).toHaveTextContent(/ada.*100\.00 EUR/)
|
||||
expect(region).toHaveTextContent(/bob.*30\.00 EUR/)
|
||||
expect(region).toHaveTextContent(/No payer yet.*10\.00 EUR/)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Status' }))
|
||||
expect(region).toHaveTextContent(/Paid.*130\.00 EUR/)
|
||||
expect(region).toHaveTextContent(/Open.*10\.00 EUR/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,387 @@
|
||||
import { useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'
|
||||
import { ChevronDown, Lock, Pencil, Plus, Trash2 } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import type { BudgetItem } from '../../types'
|
||||
import { NEUTRAL_TINT, fs } from '../shared/DialogShell'
|
||||
import { Segmented } from '../shared/dialogParts'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { CustomDatePicker } from '../shared/CustomDateTimePicker'
|
||||
import { MoreButton, tintOf } from '../Planner/planParts'
|
||||
import { COST_CATEGORY_LIST, catMeta } from './costsCategories'
|
||||
import { calcPD, calcPP, calcPPD, hasCustomMemberSplit, normalizePastedAmount } from './BudgetPanel.helpers'
|
||||
|
||||
/**
|
||||
* The Costs tab as a categorized table: the planning view the old budget had,
|
||||
* built on the same expenses the list shows. Name, date, total, persons and days
|
||||
* edit in place; everything a split or a payer needs stays in the expense
|
||||
* dialog, which each row opens.
|
||||
*/
|
||||
|
||||
type EditableField = 'name' | 'total_price' | 'persons' | 'days'
|
||||
|
||||
export interface CostsTableProps {
|
||||
/** The expenses left after the bar's search and filters. */
|
||||
items: BudgetItem[]
|
||||
/** The display currency everything is shown in. */
|
||||
base: string
|
||||
canEdit: boolean
|
||||
/** An expense's total in the display currency, booked at its frozen rate. */
|
||||
baseTotal: (e: BudgetItem) => number
|
||||
/** Any amount of an expense in the display currency. */
|
||||
toBase: (amount: number, e: BudgetItem) => number
|
||||
/** The currency an expense was entered in. */
|
||||
currencyOf: (e: BudgetItem) => string
|
||||
fmt: (amount: number) => string
|
||||
personName: (userId: number) => string
|
||||
onUpdate: (id: number, patch: Partial<BudgetItem>) => Promise<unknown>
|
||||
/** Creates an empty expense in a category and resolves with it. */
|
||||
onAdd: (category: string, expenseDate: string | null) => Promise<BudgetItem | null | undefined>
|
||||
onOpen: (e: BudgetItem) => void
|
||||
onDelete: (id: number) => void
|
||||
}
|
||||
|
||||
// Every column is centred on its title except the name, which reads from the left.
|
||||
const HEAD_BASE = 'px-3 py-2.5 font-geist font-bold uppercase tracking-[.08em] text-content-faint'
|
||||
const HEAD = `${HEAD_BASE} text-center`
|
||||
const CELL = 'px-3 py-2 text-center tabular-nums text-content'
|
||||
/** The three worked-out columns sit on their own quiet ground, apart from what is typed in. */
|
||||
const CALC = 'bg-surface-secondary'
|
||||
/** A value you can change, shown the way the rest of the app shows a fact: a white badge. */
|
||||
const BADGE = 'inline-flex h-6 min-w-[40px] items-center justify-center rounded-full bg-surface-card px-2.5 font-geist tabular-nums text-content shadow-sm ring-1 ring-edge-faint'
|
||||
/** The same place with nothing in it yet: a dashed outline and a plus that says it takes a value. */
|
||||
const BADGE_EMPTY = 'inline-flex h-6 min-w-[40px] items-center justify-center rounded-full border border-dashed border-edge text-content-faint transition-colors group-hover:border-content-faint'
|
||||
/** Shown and edited, a cell keeps one height, so a row never grows while you type in it. */
|
||||
const CELL_H = 'h-7'
|
||||
const INPUT = `${CELL_H} w-full min-w-0 rounded-[8px] border border-edge bg-surface-input px-1.5 py-0 leading-none text-content outline-none focus:ring-2 focus:ring-[color:var(--text-primary)]`
|
||||
|
||||
const hasPayers = (e: BudgetItem) => (e.payers || []).some(p => p.amount !== 0)
|
||||
|
||||
export default function CostsTable(p: CostsTableProps) {
|
||||
const { t, locale } = useTranslation()
|
||||
const [collapsed, setCollapsed] = useState<Set<string>>(new Set())
|
||||
const [editing, setEditing] = useState<{ id: number; field: EditableField } | null>(null)
|
||||
|
||||
const groups = useMemo(() => {
|
||||
const byKey = new Map<string, BudgetItem[]>()
|
||||
for (const e of p.items) {
|
||||
const key = catMeta(e.category).key
|
||||
if (!byKey.has(key)) byKey.set(key, [])
|
||||
byKey.get(key)!.push(e)
|
||||
}
|
||||
// The category order of the dialog, each group oldest first like a ledger on paper.
|
||||
return COST_CATEGORY_LIST
|
||||
.filter(c => byKey.has(c.key))
|
||||
.map(c => ({ meta: c, items: byKey.get(c.key)!.slice().sort((a, b) => (a.expense_date || '').localeCompare(b.expense_date || '') || a.id - b.id) }))
|
||||
}, [p.items])
|
||||
|
||||
const grandTotal = p.items.reduce((sum, e) => sum + p.baseTotal(e), 0)
|
||||
const numFmt = (v: number | null) => v == null ? '' : new Intl.NumberFormat(locale, { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(v)
|
||||
|
||||
const toggle = (key: string) => setCollapsed(prev => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(key)) next.delete(key); else next.add(key)
|
||||
return next
|
||||
})
|
||||
|
||||
// A new row takes the latest date of its category, so back-filling a day goes quickly.
|
||||
const add = async (category: string) => {
|
||||
const dates = p.items.filter(e => catMeta(e.category).key === category && e.expense_date).map(e => e.expense_date as string).sort()
|
||||
const created = await p.onAdd(category, dates.length ? dates[dates.length - 1] : null)
|
||||
if (created) setEditing({ id: created.id, field: 'name' })
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="overflow-x-auto rounded-2xl border border-edge-faint bg-surface-card">
|
||||
<table className="w-full min-w-[820px] border-collapse" style={fs(13, 'body')}>
|
||||
<colgroup>
|
||||
<col />
|
||||
<col className="w-[132px]" />
|
||||
<col className="w-[128px]" />
|
||||
<col className="w-[84px]" />
|
||||
<col className="w-[72px]" />
|
||||
<col className={`w-[104px] ${CALC}`} />
|
||||
<col className={`w-[96px] ${CALC}`} />
|
||||
<col className={`w-[104px] ${CALC}`} />
|
||||
<col className="w-11" />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr className="border-b border-edge-faint bg-surface-tertiary" style={fs(10)}>
|
||||
<th scope="col" className={`${HEAD_BASE} text-left`}>{t('budget.table.name')}</th>
|
||||
<th scope="col" className={HEAD}>{t('budget.table.date')}</th>
|
||||
<th scope="col" className={HEAD}>{t('budget.table.total')}</th>
|
||||
<th scope="col" className={HEAD}>{t('budget.table.persons')}</th>
|
||||
<th scope="col" className={HEAD}>{t('budget.table.days')}</th>
|
||||
<th scope="col" className={HEAD}>{t('budget.table.perPerson')}</th>
|
||||
<th scope="col" className={HEAD}>{t('budget.table.perDay')}</th>
|
||||
<th scope="col" className={HEAD}>{t('budget.table.perPersonDay')}</th>
|
||||
<th scope="col"><span className="sr-only">{t('files.menu')}</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
{groups.map(({ meta, items }) => {
|
||||
const open = !collapsed.has(meta.key)
|
||||
const subtotal = items.reduce((sum, e) => sum + p.baseTotal(e), 0)
|
||||
return (
|
||||
<tbody key={meta.key}>
|
||||
<tr className="border-t border-edge-faint" style={{ background: tintOf(meta.color, 9) }}>
|
||||
<th scope="rowgroup" colSpan={2} className="px-2 py-2 text-left font-normal">
|
||||
<button type="button" onClick={() => toggle(meta.key)} aria-expanded={open}
|
||||
className="inline-flex items-center gap-2.5 rounded-[10px] py-0.5 pl-1 pr-2 hover:bg-surface-card">
|
||||
<ChevronDown size={14} strokeWidth={2.2} className={`text-content-faint transition-transform ${open ? '' : '-rotate-90'}`} />
|
||||
<span className="grid h-7 w-7 place-items-center rounded-[9px] bg-surface-card shadow-sm">
|
||||
<meta.Icon size={14} strokeWidth={2.2} style={{ color: meta.color }} />
|
||||
</span>
|
||||
<span className="font-semibold text-content">{t(meta.labelKey)}</span>
|
||||
<span className="rounded-full bg-surface-card px-2 py-px font-geist tabular-nums text-content-muted shadow-sm" style={fs(10.5)}>{items.length}</span>
|
||||
</button>
|
||||
</th>
|
||||
<td className="px-3 py-2 text-center">
|
||||
<span className="inline-flex rounded-full bg-surface-card px-2.5 py-[3px] font-geist font-semibold tabular-nums text-content shadow-sm" style={fs(12, 'body')}>{p.fmt(subtotal)}</span>
|
||||
</td>
|
||||
<td colSpan={6} />
|
||||
</tr>
|
||||
{open && items.map(e => (
|
||||
<Row key={e.id} e={e} p={p} editing={editing} setEditing={setEditing} numFmt={numFmt} />
|
||||
))}
|
||||
{open && p.canEdit && (
|
||||
<tr className="border-t border-edge-faint">
|
||||
<td colSpan={9} className="px-3 py-1.5">
|
||||
<button type="button" onClick={() => void add(meta.key)}
|
||||
className="inline-flex items-center gap-2 rounded-full py-1 pl-1 pr-3 font-medium text-content-muted hover:bg-surface-hover hover:text-content"
|
||||
style={fs(12, 'body')}>
|
||||
<span className="grid h-5 w-5 place-items-center rounded-full bg-surface-card shadow-sm ring-1 ring-edge-faint"><Plus size={12} strokeWidth={2.4} /></span>
|
||||
{t('costs.addExpense')}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
)
|
||||
})}
|
||||
<tfoot>
|
||||
<tr className="border-t border-edge" style={{ background: NEUTRAL_TINT }}>
|
||||
<th scope="row" colSpan={2} className="px-3 py-3 text-left font-geist font-bold uppercase tracking-[.08em] text-content-muted" style={fs(10.5)}>
|
||||
{t('budget.total')}
|
||||
<span className="ml-2 rounded-full bg-surface-card px-2 py-px font-normal normal-case tracking-normal text-content-muted shadow-sm" style={fs(10.5)}>{p.items.length}</span>
|
||||
</th>
|
||||
<td className="px-3 py-3 text-center">
|
||||
<span className="inline-flex rounded-full bg-accent px-3 py-1 font-geist font-bold tabular-nums text-accent-text" style={fs(13, 'body')}>{p.fmt(grandTotal)}</span>
|
||||
</td>
|
||||
<td colSpan={6} />
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** One expense as a table row, its own cells editable in place. */
|
||||
function Row({ e, p, editing, setEditing, numFmt }: {
|
||||
e: BudgetItem
|
||||
p: CostsTableProps
|
||||
editing: { id: number; field: EditableField } | null
|
||||
setEditing: (v: { id: number; field: EditableField } | null) => void
|
||||
numFmt: (v: number | null) => string
|
||||
}) {
|
||||
const { t, locale } = useTranslation()
|
||||
const total = p.baseTotal(e)
|
||||
const custom = hasCustomMemberSplit(e)
|
||||
const persons = e.persons ?? null
|
||||
const days = e.days ?? null
|
||||
const foreign = p.currencyOf(e) !== p.base
|
||||
// A total someone paid is the sum of what they paid, and a foreign one is shown
|
||||
// converted: both change in the expense itself, where the split and the rate live.
|
||||
const totalLock = hasPayers(e) ? t('costs.table.lockedPayer') : foreign ? t('costs.table.lockedCurrency', { currency: p.currencyOf(e) }) : null
|
||||
const isEditing = (field: EditableField) => editing?.id === e.id && editing.field === field
|
||||
const save = (patch: Partial<BudgetItem>) => { setEditing(null); void p.onUpdate(e.id, patch) }
|
||||
const dateText = e.expense_date
|
||||
? (() => { try { return new Date(e.expense_date + 'T00:00:00Z').toLocaleDateString(locale, { day: 'numeric', month: 'short', timeZone: 'UTC' }) } catch { return e.expense_date } })()
|
||||
: ''
|
||||
|
||||
return (
|
||||
<tr className="group border-t border-edge-faint hover:bg-surface-hover">
|
||||
<td className="px-3 py-2 text-left">
|
||||
<EditCell label={t('budget.table.name')} text={e.name} canEdit={p.canEdit} editing={isEditing('name')} onEdit={() => setEditing({ id: e.id, field: 'name' })}
|
||||
display={<span className="block truncate font-medium">{e.name}</span>}
|
||||
input={<TextInput value={e.name} onSave={v => { if (v.trim()) save({ name: v.trim() }); else setEditing(null) }} onCancel={() => setEditing(null)} label={t('budget.table.name')} />} />
|
||||
</td>
|
||||
<td className="px-3 py-2 text-center">
|
||||
{p.canEdit ? (
|
||||
// The app's own calendar, the way the old table picked a day.
|
||||
<div className={`mx-auto flex ${CELL_H} w-fit max-w-[132px] items-center rounded-full bg-surface-tertiary px-2`} aria-label={t('budget.table.date')}>
|
||||
<CustomDatePicker value={e.expense_date || ''} onChange={v => void p.onUpdate(e.id, { expense_date: v || null })} placeholder={t('costs.noDate')} compact borderless />
|
||||
</div>
|
||||
) : (
|
||||
<span className="inline-flex rounded-full bg-surface-tertiary px-3.5 py-[3px] text-content-secondary" style={fs(12, 'body')}>{dateText || t('costs.noDate')}</span>
|
||||
)}
|
||||
</td>
|
||||
<td className={CELL}>
|
||||
{totalLock ? (
|
||||
<Tooltip label={totalLock} placement="top">
|
||||
<button type="button" onClick={() => p.onOpen(e)} aria-label={`${t('budget.table.total')}: ${p.fmt(total)}`}
|
||||
className="inline-flex min-h-7 w-full items-center justify-center gap-1.5 rounded-[8px] px-1.5 hover:bg-surface-card">
|
||||
<Lock size={10} strokeWidth={2.4} className="flex-none text-content-faint" />
|
||||
<span className="flex flex-col items-center leading-tight">
|
||||
<span className="font-semibold">{p.fmt(total)}</span>
|
||||
{foreign && <span className="mt-0.5 rounded-full bg-surface-tertiary px-1.5 font-geist text-content-muted" style={fs(10)}>{numFmt(e.total_price || 0)} {p.currencyOf(e)}</span>}
|
||||
</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<EditCell label={t('budget.table.total')} text={p.fmt(total)} canEdit={p.canEdit} editing={isEditing('total_price')} onEdit={() => setEditing({ id: e.id, field: 'total_price' })} align="center"
|
||||
display={<span className="font-semibold">{p.fmt(total)}</span>}
|
||||
input={<TextInput value={String(e.total_price ?? '')} numeric onSave={v => {
|
||||
const n = Number(normalizePastedAmount(v))
|
||||
if (v.trim() && Number.isFinite(n)) save({ total_price: n }); else setEditing(null)
|
||||
}} onCancel={() => setEditing(null)} label={t('budget.table.total')} />} />
|
||||
)}
|
||||
</td>
|
||||
{(['persons', 'days'] as const).map(field => {
|
||||
const value = field === 'persons' ? persons : days
|
||||
return (
|
||||
<td key={field} className="px-2 py-2 text-center tabular-nums">
|
||||
<EditCell label={t(`budget.table.${field}`)} text={value == null ? '' : String(value)} canEdit={p.canEdit} editing={isEditing(field)} onEdit={() => setEditing({ id: e.id, field })} align="center"
|
||||
display={value == null
|
||||
? <span className={BADGE_EMPTY}>{p.canEdit ? <Plus size={11} strokeWidth={2.4} /> : null}</span>
|
||||
: <span className={BADGE} style={fs(12, 'body')}>{value}</span>}
|
||||
input={<TextInput value={value == null ? '' : String(value)} numeric onSave={v => {
|
||||
const n = Number.parseInt(v, 10)
|
||||
save({ [field]: v.trim() === '' ? null : Number.isFinite(n) && n > 0 ? n : null } as Partial<BudgetItem>)
|
||||
}} onCancel={() => setEditing(null)} label={t(`budget.table.${field}`)} />} />
|
||||
</td>
|
||||
)
|
||||
})}
|
||||
{/* An uneven split has no single share per person, so those columns stay empty (#1458). */}
|
||||
<td className={`${CELL} text-content-secondary`}>{custom ? '' : numFmt(calcPP(total, persons))}</td>
|
||||
<td className={`${CELL} text-content-secondary`}>{numFmt(calcPD(total, days))}</td>
|
||||
<td className={`${CELL} text-content-secondary`}>{custom ? '' : numFmt(calcPPD(total, persons, days))}</td>
|
||||
<td className="px-1 py-1 text-center">
|
||||
<MoreButton label={t('files.menu')} items={[
|
||||
{ label: p.canEdit ? t('common.edit') : t('common.open'), icon: Pencil, onClick: () => p.onOpen(e) },
|
||||
p.canEdit && { divider: true },
|
||||
p.canEdit && { label: t('common.delete'), icon: Trash2, danger: true, onClick: () => p.onDelete(e.id) },
|
||||
]} size={26} />
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
}
|
||||
|
||||
/** A value that turns into a field on a click (or Enter), when the viewer may edit. */
|
||||
function EditCell({ label, text, canEdit, editing, onEdit, display, input, align = 'left' }: {
|
||||
label: string
|
||||
/** The value as words, for the button's name: "Total: 45.00". */
|
||||
text: string
|
||||
canEdit: boolean
|
||||
editing: boolean
|
||||
onEdit: () => void
|
||||
display: ReactNode
|
||||
input: ReactNode
|
||||
align?: 'left' | 'right' | 'center'
|
||||
}) {
|
||||
const justify = align === 'right' ? 'justify-end' : align === 'center' ? 'justify-center' : 'justify-start'
|
||||
if (editing) return <>{input}</>
|
||||
if (!canEdit) return <span className={`flex ${CELL_H} min-w-0 items-center ${justify}`}>{display}</span>
|
||||
return (
|
||||
<button type="button" onClick={onEdit} aria-label={text ? `${label}: ${text}` : label}
|
||||
className={`flex ${CELL_H} w-full min-w-0 items-center rounded-[8px] px-1.5 hover:bg-surface-card ${justify}`}>
|
||||
{display}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/** The field a cell becomes: Enter or Tab keeps it, Escape leaves it as it was. */
|
||||
function TextInput({ value, onSave, onCancel, label, numeric = false }: {
|
||||
value: string
|
||||
onSave: (v: string) => void
|
||||
onCancel: () => void
|
||||
label: string
|
||||
numeric?: boolean
|
||||
}) {
|
||||
const [draft, setDraft] = useState(value)
|
||||
const done = useRef(false)
|
||||
const finish = (fn: () => void) => { if (done.current) return; done.current = true; fn() }
|
||||
const onKey = (ev: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (ev.key === 'Enter') { ev.preventDefault(); finish(() => onSave(draft)) }
|
||||
// Spent here: the field lets go, the page around it stays.
|
||||
if (ev.key === 'Escape') { ev.preventDefault(); ev.stopPropagation(); finish(onCancel) }
|
||||
}
|
||||
return (
|
||||
<input autoFocus type="text" value={draft} aria-label={label} inputMode={numeric ? 'decimal' : undefined}
|
||||
onChange={ev => setDraft(ev.target.value)} onKeyDown={onKey} onBlur={() => finish(() => onSave(draft))}
|
||||
className={`${INPUT} ${numeric ? 'text-center tabular-nums' : ''}`} />
|
||||
)
|
||||
}
|
||||
|
||||
export type CostsSummaryTab = 'category' | 'date' | 'payer' | 'status'
|
||||
|
||||
/** The four ways the old budget summed the table up: by category, by day, by payer, paid against open. */
|
||||
export function CostsTableSummary({ items, baseTotal, toBase, fmt, personName }: Pick<CostsTableProps, 'items' | 'baseTotal' | 'toBase' | 'fmt' | 'personName'>) {
|
||||
const { t, locale } = useTranslation()
|
||||
const [tab, setTab] = useState<CostsSummaryTab>('category')
|
||||
|
||||
const rows = useMemo((): { key: string; label: string; amount: number; color?: string }[] => {
|
||||
const sum = new Map<string, { label: string; amount: number; color?: string }>()
|
||||
const addTo = (key: string, label: string, amount: number, color?: string) => {
|
||||
const prev = sum.get(key)
|
||||
sum.set(key, { label, amount: (prev?.amount ?? 0) + amount, color })
|
||||
}
|
||||
for (const e of items) {
|
||||
const total = baseTotal(e)
|
||||
if (tab === 'category') {
|
||||
const m = catMeta(e.category)
|
||||
addTo(m.key, t(m.labelKey), total, m.color)
|
||||
} else if (tab === 'date') {
|
||||
const d = e.expense_date || ''
|
||||
const label = d
|
||||
? (() => { try { return new Date(d + 'T00:00:00Z').toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' }) } catch { return d } })()
|
||||
: t('costs.noDate')
|
||||
addTo(d || '', label, total)
|
||||
} else if (tab === 'payer') {
|
||||
const paid = (e.payers || []).filter(x => x.amount !== 0)
|
||||
if (paid.length === 0) addTo('none', t('costs.table.noPayer'), total)
|
||||
for (const x of paid) addTo(String(x.user_id), personName(x.user_id), toBase(x.amount, e))
|
||||
} else if (hasPayers(e)) {
|
||||
addTo('paid', t('costs.table.paid'), total, 'var(--success)')
|
||||
} else {
|
||||
addTo('open', t('costs.table.open'), total, 'var(--warning)')
|
||||
}
|
||||
}
|
||||
const list = Array.from(sum.entries()).map(([key, v]) => ({ key, ...v }))
|
||||
if (tab === 'date') return list.sort((a, b) => a.key.localeCompare(b.key))
|
||||
return list.sort((a, b) => b.amount - a.amount)
|
||||
}, [items, tab, baseTotal, toBase, personName, locale, t])
|
||||
|
||||
const max = Math.max(1, ...rows.map(r => Math.abs(r.amount)))
|
||||
|
||||
return (
|
||||
<section aria-label={t('costs.table.summary')} className="overflow-hidden rounded-2xl border border-edge-faint bg-surface-secondary">
|
||||
<div className="flex flex-col gap-2.5 border-b border-edge-faint px-4 py-3" style={{ background: NEUTRAL_TINT }}>
|
||||
<span className="font-geist font-bold uppercase tracking-[.08em] text-content-faint" style={fs(11)}>{t('costs.table.summary')}</span>
|
||||
<Segmented<CostsSummaryTab> value={tab} onChange={setTab} label={t('costs.table.summary')} fill options={[
|
||||
{ value: 'category', label: t('costs.table.byCategory') },
|
||||
{ value: 'date', label: t('costs.table.byDate') },
|
||||
{ value: 'payer', label: t('costs.table.byPayer') },
|
||||
{ value: 'status', label: t('costs.table.byStatus') },
|
||||
]} />
|
||||
</div>
|
||||
<ul className="m-0 flex list-none flex-col gap-3 p-4">
|
||||
{rows.length === 0 && <li className="text-content-faint" style={fs(12.5, 'body')}>{t('costs.emptyText')}</li>}
|
||||
{rows.map(r => (
|
||||
<li key={r.key} className="flex flex-col gap-1.5">
|
||||
<div className="flex items-center justify-between gap-2" style={fs(12.5, 'body')}>
|
||||
<span className="flex min-w-0 items-center gap-1.5 text-content">
|
||||
{r.color && <span className="h-2 w-2 flex-none rounded-full" style={{ background: r.color }} />}
|
||||
<span className="truncate">{r.label}</span>
|
||||
</span>
|
||||
<span className="flex-none rounded-full bg-surface-card px-2 py-px font-geist font-semibold tabular-nums text-content shadow-sm">{fmt(r.amount)}</span>
|
||||
</div>
|
||||
<span className="block h-1.5 overflow-hidden rounded-full bg-surface-tertiary">
|
||||
<span className="block h-full rounded-full" style={{ width: `${Math.round((Math.abs(r.amount) / max) * 100)}%`, background: r.color || 'var(--accent)' }} />
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
// FE-COSTSBAR-001 to FE-COSTSBAR-008
|
||||
// FE-COSTSBAR-001 to FE-COSTSBAR-013
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent } from '../../../tests/helpers/render'
|
||||
import { render, screen, fireEvent, within } from '../../../tests/helpers/render'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import type { CostsFilterProps } from './CostsToolbar'
|
||||
import CostsToolbar from './CostsToolbar'
|
||||
import type { TripMember } from './BudgetPanelMemberChips'
|
||||
|
||||
@@ -80,4 +82,83 @@ describe('CostsToolbar', () => {
|
||||
setup()
|
||||
expect(screen.queryByRole('button', { name: 'Scan receipt' })).toBeNull()
|
||||
})
|
||||
|
||||
describe('search and filters', () => {
|
||||
function filters(over: Partial<CostsFilterProps> = {}): CostsFilterProps {
|
||||
return {
|
||||
query: '', onQuery: vi.fn(), owner: 'all', onOwner: vi.fn(),
|
||||
category: '', categoryOptions: [{ value: '', label: 'All categories' }, { value: 'Food', label: 'Food' }], onCategory: vi.fn(),
|
||||
day: '', dayOptions: [{ value: '', label: 'All days' }, { value: '2025-06-01', label: 'Day 1' }], onDay: vi.fn(),
|
||||
onResetFilters: vi.fn(), onExport: vi.fn(), canExport: true, ...over,
|
||||
}
|
||||
}
|
||||
|
||||
it('FE-COSTSBAR-009: the search reports what is typed, clears with its button and on Escape', async () => {
|
||||
const user = userEvent.setup()
|
||||
const f = filters({ query: 'taxi' })
|
||||
setup({ filters: f })
|
||||
const search = screen.getByRole('textbox', { name: 'Search' })
|
||||
await user.type(search, 's')
|
||||
expect(f.onQuery).toHaveBeenLastCalledWith('taxis')
|
||||
await user.click(screen.getByRole('button', { name: 'Clear' }))
|
||||
expect(f.onQuery).toHaveBeenLastCalledWith('')
|
||||
vi.mocked(f.onQuery).mockClear()
|
||||
fireEvent.keyDown(search, { key: 'Escape' })
|
||||
expect(f.onQuery).toHaveBeenCalledWith('')
|
||||
})
|
||||
|
||||
it('FE-COSTSBAR-010: the filter menu picks whose, which category and which day', async () => {
|
||||
const user = userEvent.setup()
|
||||
const f = filters()
|
||||
setup({ filters: f })
|
||||
await user.click(screen.getByRole('button', { name: 'Filter' }))
|
||||
const menu = screen.getByRole('menu')
|
||||
await user.click(within(menu).getByRole('button', { name: 'Paid by me' }))
|
||||
await user.click(within(menu).getByRole('button', { name: 'Food' }))
|
||||
await user.click(within(menu).getByRole('button', { name: 'Day 1' }))
|
||||
expect(f.onOwner).toHaveBeenCalledWith('mine')
|
||||
expect(f.onCategory).toHaveBeenCalledWith('Food')
|
||||
expect(f.onDay).toHaveBeenCalledWith('2025-06-01')
|
||||
expect(within(menu).queryByRole('button', { name: 'Reset filters' })).toBeNull()
|
||||
fireEvent.keyDown(menu, { key: 'Escape' })
|
||||
expect(screen.queryByRole('menu')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-COSTSBAR-011: with filters on, the button counts them and the menu resets them', async () => {
|
||||
const user = userEvent.setup()
|
||||
const f = filters({ owner: 'owed', category: 'Food', day: '2025-06-01' })
|
||||
setup({ filters: f })
|
||||
const button = screen.getByRole('button', { name: 'Filter' })
|
||||
expect(within(button).getByText('3')).toBeInTheDocument()
|
||||
await user.click(button)
|
||||
await user.click(within(screen.getByRole('menu')).getByRole('button', { name: 'Reset filters' }))
|
||||
expect(f.onResetFilters).toHaveBeenCalledTimes(1)
|
||||
expect(screen.queryByRole('menu')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-COSTSBAR-012: export runs while there is something to export', async () => {
|
||||
const user = userEvent.setup()
|
||||
const f = filters()
|
||||
const { unmount } = render(
|
||||
<CostsToolbar dateMeta={null} people={PEOPLE} me={1} colorFor={() => '#000'} canEdit canSettle
|
||||
onSettleAll={vi.fn()} onAddExpense={vi.fn()} filters={f} />,
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'Export CSV' }))
|
||||
expect(f.onExport).toHaveBeenCalledTimes(1)
|
||||
unmount()
|
||||
setup({ filters: filters({ canExport: false }) })
|
||||
expect(screen.getByRole('button', { name: 'Export CSV' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('FE-COSTSBAR-013: the view switch marks the current view and reports a new one', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onView = vi.fn()
|
||||
setup({ view: 'list', onView })
|
||||
const group = screen.getByRole('group')
|
||||
const buttons = within(group).getAllByRole('button')
|
||||
expect(buttons[0]).toHaveAttribute('aria-pressed', 'true')
|
||||
await user.click(buttons[1])
|
||||
expect(onView).toHaveBeenCalledWith('table')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useRef, useState, type ReactNode } from 'react'
|
||||
import { Check, Download, Filter, Plus, RotateCcw, ScanLine, Search, X } from 'lucide-react'
|
||||
import { Check, Download, Filter, Plus, RotateCcw, Rows3, ScanLine, Search, Table2, X } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import type { TripMember } from './BudgetPanelMemberChips'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
@@ -7,6 +7,8 @@ import { POPOVER, POPOVER_CAPTION, POPOVER_DIVIDER, useDismissOnOutside } from '
|
||||
import { PopoverItem } from '../Packing/PackingPopover'
|
||||
|
||||
export type OwnerFilter = 'all' | 'mine' | 'owed'
|
||||
/** The day-by-day list, or the categorized table the old budget had. */
|
||||
export type CostsView = 'list' | 'table'
|
||||
|
||||
export interface CostsFilterProps {
|
||||
query: string
|
||||
@@ -41,6 +43,9 @@ interface CostsToolbarProps {
|
||||
onScanReceipt?: () => void
|
||||
/** Search, filters and export, the way the Transports and Bookings bars carry them. */
|
||||
filters?: CostsFilterProps
|
||||
/** The switch between the list and the table; left out, the bar has none. */
|
||||
view?: CostsView
|
||||
onView?: (view: CostsView) => void
|
||||
}
|
||||
|
||||
const BODY_SIZE = 'calc(13px * var(--fs-scale-body, 1))'
|
||||
@@ -52,7 +57,7 @@ const BAR_BTN = 'relative grid h-9 w-9 flex-none place-items-center rounded-[10p
|
||||
* Bookings, Lists and Files open with: the tab's name and what the numbers
|
||||
* cover, then how to narrow the ledger and the actions on the right.
|
||||
*/
|
||||
export default function CostsToolbar({ dateMeta, people, me, colorFor, canEdit, canSettle, onSettleAll, onAddExpense, onScanReceipt, filters }: CostsToolbarProps) {
|
||||
export default function CostsToolbar({ dateMeta, people, me, colorFor, canEdit, canSettle, onSettleAll, onAddExpense, onScanReceipt, filters, view, onView }: CostsToolbarProps) {
|
||||
const { t } = useTranslation()
|
||||
const searchRef = useRef<HTMLInputElement>(null)
|
||||
const chip = 'inline-flex items-center whitespace-nowrap rounded-full bg-surface-card px-3 py-1.5 font-medium text-content-muted shadow-sm'
|
||||
@@ -118,6 +123,20 @@ export default function CostsToolbar({ dateMeta, people, me, colorFor, canEdit,
|
||||
</>
|
||||
)}
|
||||
|
||||
{view && onView && (
|
||||
// The same switch the Bookings bar has for its views.
|
||||
<div role="group" aria-label={t('costs.view.label')} className="inline-flex flex-none rounded-[10px] bg-surface-card p-[3px]">
|
||||
{([['list', Rows3, t('costs.view.list')], ['table', Table2, t('costs.view.table')]] as const).map(([v, Icon, label]) => (
|
||||
<Tooltip key={v} label={label}>
|
||||
<button type="button" onClick={() => onView(v)} aria-pressed={view === v} aria-label={label}
|
||||
className={`grid h-[30px] w-[34px] place-items-center rounded-[8px] transition-colors ${view === v ? 'bg-accent text-accent-text' : 'text-content-muted hover:text-content'}`}>
|
||||
<Icon size={15} strokeWidth={2} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{canEdit && (
|
||||
<>
|
||||
{filters && <span className="mx-0.5 h-[22px] w-px flex-none bg-edge-faint" />}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
// FE-COSTS-EXPRECEIPT-001 to FE-COSTS-EXPRECEIPT-004
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, within } from '../../../tests/helpers/render'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
|
||||
import { buildBudgetItem, buildTrip, buildUser } from '../../../tests/helpers/factories'
|
||||
import type { BudgetItem } from '../../types'
|
||||
import { ExpenseModal } from './CostsPanel'
|
||||
|
||||
vi.mock('../../api/authUrl', () => ({ getAuthUrl: vi.fn().mockResolvedValue('http://test/receipt') }))
|
||||
|
||||
const people = [
|
||||
{ id: 1, username: 'alice', avatar_url: null },
|
||||
{ id: 2, username: 'bob', avatar_url: null },
|
||||
]
|
||||
|
||||
function renderModal(editing: BudgetItem | null) {
|
||||
return render(<ExpenseModal tripId={1} base="EUR" people={people} me={1} editing={editing} onClose={vi.fn()} onSaved={vi.fn()} />)
|
||||
}
|
||||
|
||||
const receiptsCard = () => screen.getByText('Receipts & Invoices').closest('section') as HTMLElement
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores()
|
||||
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true })
|
||||
seedStore(useTripStore, { trip: buildTrip({ id: 1, currency: 'EUR' }) })
|
||||
})
|
||||
|
||||
describe('ExpenseModal receipts and note', () => {
|
||||
it('FE-COSTS-EXPRECEIPT-001: a new expense starts without receipts and takes picked files', async () => {
|
||||
renderModal(null)
|
||||
expect(within(receiptsCard()).getByText('No receipts attached')).toBeInTheDocument()
|
||||
const input = receiptsCard().querySelector('input[type="file"]') as HTMLInputElement
|
||||
fireEvent.change(input, { target: { files: [new File(['a'], 'lunch.jpg', { type: 'image/jpeg' }), new File(['b'], 'taxi.pdf', { type: 'application/pdf' })] } })
|
||||
expect(within(receiptsCard()).getByText('lunch.jpg')).toBeInTheDocument()
|
||||
expect(within(receiptsCard()).getByText('taxi.pdf')).toBeInTheDocument()
|
||||
// The picker is emptied, so the same file can be picked again.
|
||||
expect(input.value).toBe('')
|
||||
})
|
||||
|
||||
it('FE-COSTS-EXPRECEIPT-002: a picked file is taken off again before saving', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderModal(null)
|
||||
const input = receiptsCard().querySelector('input[type="file"]') as HTMLInputElement
|
||||
fireEvent.change(input, { target: { files: [new File(['a'], 'lunch.jpg', { type: 'image/jpeg' })] } })
|
||||
fireEvent.change(input, { target: { files: [] } })
|
||||
await user.click(within(receiptsCard()).getByRole('button', { name: 'Remove receipt' }))
|
||||
expect(within(receiptsCard()).queryByText('lunch.jpg')).toBeNull()
|
||||
expect(within(receiptsCard()).getByText('No receipts attached')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-COSTS-EXPRECEIPT-003: a saved receipt opens in the preview and can be taken off the expense', async () => {
|
||||
const user = userEvent.setup()
|
||||
const editing = buildBudgetItem({
|
||||
name: 'Dinner',
|
||||
receipts: [
|
||||
{ id: 31, filename: 'a.pdf', original_name: 'dinner-bill.pdf', mime_type: 'application/pdf', url: '/api/trips/1/budget/receipts/31' },
|
||||
{ id: 32, filename: 'b.jpg', original_name: 'tip.jpg', mime_type: 'image/jpeg', url: '/api/trips/1/budget/receipts/32' },
|
||||
],
|
||||
} as never)
|
||||
renderModal(editing)
|
||||
const shownBefore = screen.getAllByText('dinner-bill.pdf').length
|
||||
await user.click(within(receiptsCard()).getByRole('button', { name: 'dinner-bill.pdf' }))
|
||||
// The preview names the receipt in its own head.
|
||||
expect(screen.getAllByText('dinner-bill.pdf').length).toBeGreaterThan(shownBefore)
|
||||
|
||||
const removes = within(receiptsCard()).getAllByRole('button', { name: 'Remove receipt' })
|
||||
await user.click(removes[1])
|
||||
expect(within(receiptsCard()).queryByText('tip.jpg')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-COSTS-EXPRECEIPT-004: the note takes what is typed', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderModal(null)
|
||||
const note = screen.getByRole('textbox', { name: 'Note' })
|
||||
await user.type(note, 'Paid in cash')
|
||||
expect(note).toHaveValue('Paid in cash')
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-BUDGET-SCAN-001 to FE-BUDGET-SCAN-010
|
||||
// FE-BUDGET-SCAN-001 to FE-BUDGET-SCAN-011
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render'
|
||||
@@ -148,4 +148,20 @@ describe('MReceiptScanButton', () => {
|
||||
await new Promise(r => setTimeout(r, 20))
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('FE-BUDGET-SCAN-011: the drop zone lights up while a photo is dragged over it, and a click on it opens the picker', async () => {
|
||||
render(<Harness />)
|
||||
await openDialog()
|
||||
const zone = screen.getByText('Drop the receipt photo here, or click to pick or take one').closest('button')!
|
||||
fireEvent.dragEnter(zone)
|
||||
expect(screen.getByText('Drop the photo to scan it')).toBeInTheDocument()
|
||||
// Leaving for a child of the zone keeps it lit, leaving the zone itself does not.
|
||||
fireEvent.dragLeave(zone.firstElementChild!)
|
||||
expect(screen.getByText('Drop the photo to scan it')).toBeInTheDocument()
|
||||
fireEvent.dragLeave(zone)
|
||||
expect(screen.getByText('Drop the receipt photo here, or click to pick or take one')).toBeInTheDocument()
|
||||
const pick = vi.spyOn(input(), 'click')
|
||||
fireEvent.click(zone)
|
||||
expect(pick).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-COMP-LINKS-001 to FE-COMP-LINKS-013
|
||||
// FE-COMP-LINKS-001 to FE-COMP-LINKS-015
|
||||
|
||||
vi.mock('../../api/websocket', () => ({
|
||||
connect: vi.fn(),
|
||||
@@ -231,4 +231,37 @@ describe('CollabLinks', () => {
|
||||
expect(await screen.findByText(/no shared links yet|collab\.links\.empty/i)).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /add link|collab\.links\.add/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-LINKS-014: pinning a link saves it and turns the pin into an unpin', async () => {
|
||||
const user = userEvent.setup();
|
||||
let put: Record<string, unknown> | null = null;
|
||||
server.use(
|
||||
http.get('/api/trips/1/collab/links', () => HttpResponse.json({ links: [buildLink()] })),
|
||||
http.put('/api/trips/1/collab/links/1', async ({ request }) => {
|
||||
put = await request.json() as Record<string, unknown>;
|
||||
return HttpResponse.json({ link: buildLink({ pinned: 1 }) });
|
||||
}),
|
||||
);
|
||||
render(<CollabLinks tripId={1} />);
|
||||
await user.click(await screen.findByRole('button', { name: /^pin link$|^collab\.links\.pin$/i }));
|
||||
expect(await screen.findByRole('button', { name: /^unpin link$|^collab\.links\.unpin$/i })).toBeInTheDocument();
|
||||
expect(put).toEqual({ pinned: true });
|
||||
});
|
||||
|
||||
it('FE-COMP-LINKS-015: a failed pin says so and leaves the link as it was', async () => {
|
||||
const user = userEvent.setup();
|
||||
const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
const toasts: string[] = [];
|
||||
window.__addToast = ((message: string) => { toasts.push(message); return 1; }) as unknown as typeof window.__addToast;
|
||||
server.use(
|
||||
http.get('/api/trips/1/collab/links', () => HttpResponse.json({ links: [buildLink()] })),
|
||||
http.put('/api/trips/1/collab/links/1', () => new HttpResponse(null, { status: 500 })),
|
||||
);
|
||||
render(<CollabLinks tripId={1} />);
|
||||
await user.click(await screen.findByRole('button', { name: /^pin link$|^collab\.links\.pin$/i }));
|
||||
await waitFor(() => expect(toasts.length).toBe(1));
|
||||
expect(screen.getByRole('button', { name: /^pin link$|^collab\.links\.pin$/i })).toBeInTheDocument();
|
||||
delete window.__addToast;
|
||||
errors.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
// FE-COLLAB-PANELHEAD-001 to FE-COLLAB-PANELHEAD-004
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { StickyNote } from 'lucide-react';
|
||||
import CollabPanelHead, { HEAD_ACTION } from './CollabPanelHead';
|
||||
|
||||
describe('CollabPanelHead', () => {
|
||||
it('FE-COLLAB-PANELHEAD-001: names the panel as a heading with how many there are', () => {
|
||||
render(<CollabPanelHead icon={StickyNote} title="Notes" count={4} />);
|
||||
expect(screen.getByRole('heading', { level: 3, name: 'Notes' })).toBeInTheDocument();
|
||||
expect(screen.getByText('4')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COLLAB-PANELHEAD-002: an empty or unknown count is left out', () => {
|
||||
const { rerender } = render(<CollabPanelHead icon={StickyNote} title="Notes" count={0} />);
|
||||
expect(screen.queryByText('0')).toBeNull();
|
||||
rerender(<CollabPanelHead icon={StickyNote} title="Notes" />);
|
||||
expect(screen.getByRole('heading', { name: 'Notes' }).parentElement?.querySelectorAll('span')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('FE-COLLAB-PANELHEAD-003: its actions sit on the right and work', async () => {
|
||||
const onAdd = vi.fn();
|
||||
render(<CollabPanelHead icon={StickyNote} title="Polls" actions={<button type="button" className={HEAD_ACTION} onClick={onAdd}>New poll</button>} />);
|
||||
await userEvent.click(screen.getByRole('button', { name: 'New poll' }));
|
||||
expect(onAdd).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-COLLAB-PANELHEAD-004: without actions there is no action area', () => {
|
||||
render(<CollabPanelHead icon={StickyNote} title="Chat" count={2} />);
|
||||
expect(screen.queryByRole('button')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
// FE-FILES-ROW-001 to FE-FILES-ROW-006
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { buildPlace, buildReservation, buildTrip, buildTripFile } from '../../../tests/helpers/factories';
|
||||
import { downloadFile } from '../../utils/fileDownload';
|
||||
import type { TripFile } from '../../types';
|
||||
import type { FileManagerState } from './useFileManager';
|
||||
import { FileRow } from './FileManagerRow';
|
||||
|
||||
vi.mock('../../utils/fileDownload', () => ({ downloadFile: vi.fn(async () => {}) }));
|
||||
|
||||
const handlers = {
|
||||
handleStar: vi.fn(),
|
||||
handleRestore: vi.fn(),
|
||||
handlePermanentDelete: vi.fn(),
|
||||
handleDelete: vi.fn(),
|
||||
openFile: vi.fn(),
|
||||
setAssignFileId: vi.fn(),
|
||||
};
|
||||
|
||||
const labels: Record<string, string> = {
|
||||
'common.open': 'Open', 'common.delete': 'Delete', 'files.download': 'Download', 'files.star': 'Star', 'files.unstar': 'Unstar',
|
||||
'files.assign': 'Assign', 'files.restore': 'Restore', 'files.sourcePlan': 'Day Plan', 'files.sourceBooking': 'Booking',
|
||||
'files.sourceTransport': 'Transport', 'files.sourceCollab': 'From Collab Notes',
|
||||
};
|
||||
|
||||
function renderRow(file: TripFile, { isTrash = false, allowed = true } = {}) {
|
||||
const state = {
|
||||
...handlers,
|
||||
places: [buildPlace({ id: 71, name: 'Louvre' })],
|
||||
reservations: [buildReservation({ id: 81, title: 'Shinkansen', type: 'train' }), buildReservation({ id: 82, title: '', type: 'restaurant' })],
|
||||
t: (k: string) => labels[k] ?? k,
|
||||
locale: 'en-US',
|
||||
can: () => allowed,
|
||||
trip: buildTrip({ id: 1 }),
|
||||
} as unknown as FileManagerState;
|
||||
return render(<FileRow {...state} file={file} isTrash={isTrash} />);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
Object.values(handlers).forEach(fn => fn.mockClear());
|
||||
vi.mocked(downloadFile).mockClear();
|
||||
});
|
||||
|
||||
describe('FileRow', () => {
|
||||
it('FE-FILES-ROW-001: opens the file from its tile, its name and the Open action', async () => {
|
||||
const user = userEvent.setup();
|
||||
const file = buildTripFile({ original_name: 'ticket.pdf' });
|
||||
renderRow(file);
|
||||
await user.click(screen.getByRole('button', { name: 'Open' }));
|
||||
await user.click(screen.getAllByRole('button', { name: 'ticket.pdf' })[0]);
|
||||
expect(handlers.openFile).toHaveBeenCalledTimes(2);
|
||||
expect(handlers.openFile).toHaveBeenCalledWith(file);
|
||||
});
|
||||
|
||||
it('FE-FILES-ROW-002: Download fetches the file under its own name', async () => {
|
||||
const user = userEvent.setup();
|
||||
const file = buildTripFile({ original_name: 'ticket.pdf', url: '/api/trips/1/files/9/download' });
|
||||
renderRow(file);
|
||||
await user.click(screen.getByRole('button', { name: 'Download' }));
|
||||
expect(downloadFile).toHaveBeenCalledWith('/api/trips/1/files/9/download', 'ticket.pdf');
|
||||
});
|
||||
|
||||
it('FE-FILES-ROW-003: star, assign and delete reach their handlers', async () => {
|
||||
const user = userEvent.setup();
|
||||
const file = buildTripFile({ id: 555, starred: 1 } as never);
|
||||
renderRow(file);
|
||||
await user.click(screen.getByRole('button', { name: 'Unstar' }));
|
||||
await user.click(screen.getByRole('button', { name: 'Assign' }));
|
||||
await user.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
expect(handlers.handleStar).toHaveBeenCalledWith(555);
|
||||
expect(handlers.setAssignFileId).toHaveBeenCalledWith(555);
|
||||
expect(handlers.handleDelete).toHaveBeenCalledWith(555);
|
||||
});
|
||||
|
||||
it('FE-FILES-ROW-004: without the rights there is nothing to assign or delete', () => {
|
||||
renderRow(buildTripFile({}), { allowed: false });
|
||||
expect(screen.getByRole('button', { name: 'Star' })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Assign' })).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: 'Delete' })).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-FILES-ROW-005: a file in the trash restores or goes for good, and does not open', async () => {
|
||||
const user = userEvent.setup();
|
||||
const file = buildTripFile({ id: 556, original_name: 'old.pdf' });
|
||||
renderRow(file, { isTrash: true });
|
||||
expect(screen.getAllByRole('button', { name: 'old.pdf' })[0]).toBeDisabled();
|
||||
await user.click(screen.getByRole('button', { name: 'Restore' }));
|
||||
await user.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
expect(handlers.handleRestore).toHaveBeenCalledWith(556);
|
||||
expect(handlers.handlePermanentDelete).toHaveBeenCalledWith(556);
|
||||
expect(screen.queryByRole('button', { name: 'Open' })).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-FILES-ROW-006: says where the file came from: a place, a transport, a booking, a note', () => {
|
||||
const file = buildTripFile({ place_id: 71, reservation_id: 81, linked_reservation_ids: [82], note_id: 3, description: 'Seat map', file_size: 2048 } as never);
|
||||
renderRow(file);
|
||||
expect(screen.getByText('Louvre')).toBeInTheDocument();
|
||||
expect(screen.getByText('Shinkansen')).toBeInTheDocument();
|
||||
expect(screen.getByText('Booking')).toBeInTheDocument();
|
||||
expect(screen.getByText('From Collab Notes')).toBeInTheDocument();
|
||||
expect(screen.getByText('Seat map')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-PLANNER-DAYPLAN-001 to FE-PLANNER-DAYPLAN-231
|
||||
// FE-PLANNER-DAYPLAN-001 to FE-PLANNER-DAYPLAN-232
|
||||
import { render, screen, waitFor, fireEvent, within } from '../../../tests/helpers/render'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
@@ -2202,7 +2202,7 @@ describe('DayPlanSidebar', () => {
|
||||
|
||||
// ── Edit reservation pencil button ───────────────────────────────────────
|
||||
|
||||
it('FE-PLANNER-DAYPLAN-097: pencil button on non-transport reservation calls onEditReservation', async () => {
|
||||
it('FE-PLANNER-DAYPLAN-097: the reservation pill of a non-transport booking opens its editor', async () => {
|
||||
const user = userEvent.setup()
|
||||
const place = buildPlace({ id: 1, name: 'Hotel du Lac' })
|
||||
const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' })
|
||||
@@ -2214,13 +2214,18 @@ describe('DayPlanSidebar', () => {
|
||||
days: [day], places: [place], assignments: { '10': [assignment] }, reservations: [res],
|
||||
onEditReservation, onEditTransport,
|
||||
})} />)
|
||||
const pencil = screen.getByLabelText(/edit/i)
|
||||
await user.click(pencil)
|
||||
// The pill says "Reservation"; its colour and tooltip carry the status.
|
||||
const pill = screen.getByRole('button', { name: /^Reservation\s*Pending$/ })
|
||||
fireEvent.mouseEnter(pill)
|
||||
expect(await screen.findByRole('tooltip')).toHaveTextContent('Pending')
|
||||
await user.click(pill)
|
||||
expect(onEditReservation).toHaveBeenCalledWith(res)
|
||||
expect(onEditTransport).not.toHaveBeenCalled()
|
||||
// No separate pencil beside it any more.
|
||||
expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-PLANNER-DAYPLAN-098: pencil button on transport reservation calls onEditTransport', async () => {
|
||||
it('FE-PLANNER-DAYPLAN-098: the reservation pill of a transport opens the transport editor', async () => {
|
||||
const user = userEvent.setup()
|
||||
const place = buildPlace({ id: 1, name: 'Geneva Airport' })
|
||||
const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' })
|
||||
@@ -2232,8 +2237,7 @@ describe('DayPlanSidebar', () => {
|
||||
days: [day], places: [place], assignments: { '10': [assignment] }, reservations: [res],
|
||||
onEditReservation, onEditTransport,
|
||||
})} />)
|
||||
const pencil = screen.getByLabelText(/edit/i)
|
||||
await user.click(pencil)
|
||||
await user.click(screen.getByRole('button', { name: /^Reservation\s*Pending$/ }))
|
||||
expect(onEditTransport).toHaveBeenCalledWith(res)
|
||||
expect(onEditReservation).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -3680,6 +3684,24 @@ describe('DayPlanSidebar', () => {
|
||||
expect(row.style.borderTop).toBe('')
|
||||
})
|
||||
|
||||
it('FE-PLANNER-DAYPLAN-232: a drop line left behind by a drag that never reported its end goes on the next mouse move', () => {
|
||||
const { day, placeA, placeB, bus, assignments } = dayWithBusAndPlaces()
|
||||
render(<DayPlanSidebar {...makeDefaultProps({ days: [day], places: [placeA, placeB], assignments, reservations: [bus] })} />)
|
||||
const row = cardRow(screen.getByText('City bus'))
|
||||
fireEvent.dragStart(row, { dataTransfer: emptyDataTransfer })
|
||||
fireEvent.dragOver(row, { dataTransfer: emptyDataTransfer, clientY: 0 })
|
||||
expect(row.style.borderTop).toContain('2px')
|
||||
// No dragend reaches the document (its source re-rendered away); the pointer moves on.
|
||||
fireEvent.mouseMove(document)
|
||||
expect(row.style.borderTop).toBe('')
|
||||
|
||||
// A press clears it just the same.
|
||||
fireEvent.dragOver(row, { dataTransfer: emptyDataTransfer, clientY: 0 })
|
||||
expect(row.style.borderTop).toContain('2px')
|
||||
fireEvent.pointerDown(document.body)
|
||||
expect(row.style.borderTop).toBe('')
|
||||
})
|
||||
|
||||
it('FE-PLANNER-DAYPLAN-160: cross-day payloads dropped on a booking row move onto its day', () => {
|
||||
const moveAssignment = vi.fn(async () => undefined)
|
||||
const moveDayNote = vi.fn(async () => undefined)
|
||||
@@ -3757,10 +3779,7 @@ describe('DayPlanSidebar', () => {
|
||||
expect(screen.getByText('Air France AF1235')).toBeInTheDocument()
|
||||
await user.click(screen.getByLabelText('Show booking routes'))
|
||||
expect(onToggleConnection).toHaveBeenCalledWith(520)
|
||||
const edit = screen.getByLabelText('Edit')
|
||||
fireEvent.mouseEnter(edit)
|
||||
fireEvent.mouseLeave(edit)
|
||||
await user.click(edit)
|
||||
await user.click(screen.getByRole('button', { name: /^Reservation\s*Confirmed$/ }))
|
||||
expect(onEditTransport).toHaveBeenCalledWith(linked)
|
||||
})
|
||||
|
||||
@@ -3776,7 +3795,8 @@ describe('DayPlanSidebar', () => {
|
||||
days: [day], places: [place], assignments: { '10': [a] }, reservations: [linked],
|
||||
})} />)
|
||||
expect(screen.getAllByText('ICE 599').length).toBeGreaterThan(0)
|
||||
expect(screen.getByText(/Reservation pending/)).toBeInTheDocument()
|
||||
// The pill names the booking; the status travels with it for a screen reader.
|
||||
expect(screen.getByText('Reservation').parentElement).toHaveTextContent(/Reservation\s*Pending/)
|
||||
})
|
||||
|
||||
it('FE-PLANNER-DAYPLAN-163b: every booking on the stop gets its own chip line (#2201)', async () => {
|
||||
@@ -3800,10 +3820,11 @@ describe('DayPlanSidebar', () => {
|
||||
})} />)
|
||||
expect(screen.getByText('09:00 – 09:30')).toBeInTheDocument()
|
||||
expect(screen.getByText('10:15')).toBeInTheDocument()
|
||||
expect(screen.getByText(/Reservation confirmed/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/Reservation pending/)).toBeInTheDocument()
|
||||
// Earliest first, so the first pencil belongs to the parking pass.
|
||||
await user.click(screen.getAllByLabelText('Edit')[0])
|
||||
const pills = screen.getAllByRole('button', { name: /^Reservation/ })
|
||||
expect(pills[0]).toHaveAccessibleName(/Confirmed/)
|
||||
expect(pills[1]).toHaveAccessibleName(/Pending/)
|
||||
// Earliest first, so the first pill belongs to the parking pass.
|
||||
await user.click(pills[0])
|
||||
expect(onEditReservation).toHaveBeenCalledWith(parking)
|
||||
})
|
||||
|
||||
@@ -4374,7 +4395,7 @@ describe('DayPlanSidebar', () => {
|
||||
expect(screen.queryByText('Gare du Nord')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-PLANNER-DAYPLAN-231: the pencil on a booking pinned to a stop still goes straight to the editor', async () => {
|
||||
it('FE-PLANNER-DAYPLAN-231: with the booking popup, a booking pinned to a stop opens there first', async () => {
|
||||
const user = userEvent.setup()
|
||||
const place = buildPlace({ id: 1, name: 'Geneva Airport' })
|
||||
const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' })
|
||||
@@ -4387,10 +4408,10 @@ describe('DayPlanSidebar', () => {
|
||||
onEditTransport, onOpenBooking,
|
||||
})} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Edit' }))
|
||||
await user.click(screen.getByRole('button', { name: /^Reservation\s*Pending$/ }))
|
||||
|
||||
expect(onEditTransport).toHaveBeenCalledWith(res)
|
||||
expect(onOpenBooking).not.toHaveBeenCalled()
|
||||
expect(onOpenBooking).toHaveBeenCalledWith(res)
|
||||
expect(onEditTransport).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-PLANNER-DAYPLAN-178: the add-transport shortcut targets the day it sits on', async () => {
|
||||
|
||||
@@ -401,6 +401,27 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
||||
return () => document.removeEventListener('dragend', cleanup)
|
||||
}, [])
|
||||
|
||||
// A drag whose source row re-rendered away never sends its dragend to the
|
||||
// document, and the drop line then stayed on a row until the next reload. The
|
||||
// browser sends no mousemove during a drag, so the first plain mouse move or
|
||||
// press after one means it is over.
|
||||
useEffect(() => {
|
||||
if (!draggingId && !dropTargetKey && !dragOverDayId) return
|
||||
const settle = () => {
|
||||
setDraggingId(null)
|
||||
setDropTargetKey(null)
|
||||
setDragOverDayId(null)
|
||||
dragDataRef.current = null
|
||||
window.__dragData = null
|
||||
}
|
||||
document.addEventListener('mousemove', settle)
|
||||
document.addEventListener('pointerdown', settle, true)
|
||||
return () => {
|
||||
document.removeEventListener('mousemove', settle)
|
||||
document.removeEventListener('pointerdown', settle, true)
|
||||
}
|
||||
}, [draggingId, dropTargetKey, dragOverDayId])
|
||||
|
||||
// Initialize missing transport positions outside of render to avoid setState-during-render
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
useEffect(() => { days.forEach(day => initTransportPositions(day.id)) }, [days, reservations])
|
||||
@@ -2278,13 +2299,31 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
? (meta.airline && meta.flight_number ? `${meta.airline} ${meta.flight_number}` : meta.flight_number || meta.train_number || '')
|
||||
: ''
|
||||
const editHandler = canEditDays ? (TRANSPORT_TYPES.has(res.type) ? onEditTransport : onEditReservation) : undefined
|
||||
const openPinned = onOpenBooking ?? editHandler
|
||||
return (
|
||||
// No wrapping: the time belongs to the status it qualifies, so the
|
||||
// pills stay on one line even when the row gets narrow.
|
||||
<div key={res.id} className="flex max-w-full flex-nowrap items-center gap-1">
|
||||
<SoftPill tone={tone} icon={<RI size={10} strokeWidth={2.2} />}>
|
||||
<span className="hidden sm:inline">{confirmed ? t('planner.resConfirmed') : t('planner.resPending')}</span>
|
||||
</SoftPill>
|
||||
{/* The colour carries the status; the word is in the tooltip and read out after the label.
|
||||
The pill opens the booking: its popup where there is one, else its editor. */}
|
||||
<Tooltip label={confirmed ? t('reservations.confirmed') : t('reservations.pending')} placement="top">
|
||||
{openPinned ? (
|
||||
<button type="button" data-dp="res-pill" onClick={e => { e.stopPropagation(); openPinned(res) }}
|
||||
className="inline-flex flex-none rounded-full hover:opacity-80">
|
||||
<SoftPill tone={tone} icon={<RI size={10} strokeWidth={2.2} />}>
|
||||
<span className="hidden sm:inline">{t('places.formReservation')}</span>
|
||||
<span className="sr-only">{confirmed ? t('reservations.confirmed') : t('reservations.pending')}</span>
|
||||
</SoftPill>
|
||||
</button>
|
||||
) : (
|
||||
<span className="inline-flex flex-none">
|
||||
<SoftPill tone={tone} icon={<RI size={10} strokeWidth={2.2} />}>
|
||||
<span className="hidden sm:inline">{t('places.formReservation')}</span>
|
||||
<span className="sr-only">{confirmed ? t('reservations.confirmed') : t('reservations.pending')}</span>
|
||||
</SoftPill>
|
||||
</span>
|
||||
)}
|
||||
</Tooltip>
|
||||
{timeLabel && <SoftPill tone={tone}>{timeLabel}</SoftPill>}
|
||||
{carrierLabel && <SoftPill tone={tone}>{carrierLabel}</SoftPill>}
|
||||
{hasEndpoints && (
|
||||
@@ -2299,17 +2338,6 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
{editHandler && (
|
||||
<Tooltip label={t('common.edit')} placement="top">
|
||||
<button aria-label={t('common.edit')}
|
||||
type="button"
|
||||
onClick={e => { e.stopPropagation(); editHandler(res) }}
|
||||
className={`${ROW_ROUND} h-5 w-5 text-content-muted hover:text-content`}
|
||||
>
|
||||
<Pencil size={11} strokeWidth={2.2} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
@@ -2330,6 +2358,8 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{/* The row's own controls, with room between them so each is its own target. */}
|
||||
<div className="flex flex-none items-center gap-2.5 pl-1">
|
||||
{canEditDays && <div className="reorder-buttons" style={{ flexShrink: 0, display: 'flex', gap: 1, transition: 'opacity 0.15s' }}>
|
||||
<button type="button" onClick={moveUp} disabled={idx === 0} aria-label={t('dayplan.moveUp')} className="flex text-content-faint hover:text-content disabled:cursor-default disabled:text-edge">
|
||||
<ChevronUp size={12} strokeWidth={2} />
|
||||
@@ -2352,6 +2382,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
</Tooltip>
|
||||
)}
|
||||
<MoreButton label={t('files.menu')} items={placeMenu()} size={24} />
|
||||
</div>
|
||||
</div>
|
||||
{daySchedule.byAssignment[day.id]?.[assignment.id]?.map(si => <PluginDayScheduleRow key={`${si.pluginId}:${si.id}`} item={si} />)}
|
||||
{routeLegs[day.id]?.[assignment.id] && (canEditDays ? (
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-COMP-PLACEFORM-001 to FE-COMP-PLACEFORM-036, FE-PLANNER-PLACEFORM-016 to FE-PLANNER-PLACEFORM-067, plus FE-PLANNER-PLACEFORM-068 to -121
|
||||
// FE-COMP-PLACEFORM-001 to FE-COMP-PLACEFORM-036, FE-PLANNER-PLACEFORM-016 to FE-PLANNER-PLACEFORM-067, plus FE-PLANNER-PLACEFORM-068 to -124
|
||||
import { render, screen, waitFor, fireEvent, within, act } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
@@ -2685,3 +2685,65 @@ describe('PlaceFormModal in the look of the booking editors', () => {
|
||||
expect(beside).toHaveClass('sm:w-80');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PlaceFormModal and the columns beside it', () => {
|
||||
it('FE-PLANNER-PLACEFORM-122: a picture picked and a description adopted in the details column are saved with the place', async () => {
|
||||
seedStore(useAuthStore, { placesEnrichEnabled: true });
|
||||
const photoUrl = '/api/maps/place-photo/way%3A122~p0/bytes';
|
||||
server.use(
|
||||
http.post('/api/maps/enrichment', () => HttpResponse.json({
|
||||
photos: [{ key: 'way:122~p0', url: photoUrl, attribution: 'Alice', license: 'CC BY 4.0', licenseUrl: null, sourceUrl: null, source: 'wikimedia' }],
|
||||
facts: [],
|
||||
description: { text: 'A museum by the river.', source: 'wikipedia', sourceUrl: null, license: 'CC BY-SA 4.0' },
|
||||
rating: null,
|
||||
hours: null,
|
||||
})),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
render(<PlaceFormModal {...defaultProps} onSave={onSave} prefillCoords={{ lat: 50.9, lng: 6.96, name: 'Museum 122', osm_id: 'way:122' }} />);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Use this text' }));
|
||||
expect(screen.getByLabelText('Description')).toHaveValue('A museum by the river.');
|
||||
// With a description in place, the column asks for it to be cleared first.
|
||||
expect(screen.getByRole('button', { name: 'Use this text' })).toBeDisabled();
|
||||
|
||||
const tile = screen.getByRole('button', { name: /^Pick a picture/ });
|
||||
await user.click(tile);
|
||||
expect(tile).toHaveAttribute('aria-pressed', 'true');
|
||||
await user.click(tile);
|
||||
expect(tile).toHaveAttribute('aria-pressed', 'false');
|
||||
await user.click(tile);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /^Add$/i }));
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
|
||||
expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ image_url: photoUrl, description: 'A museum by the river.' }));
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLACEFORM-123: the notes for this day are saved when they changed', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
const place = buildPlace({ name: 'Cafe 123' });
|
||||
const assignment = buildAssignment({ id: 123, day_id: 5, place, notes: 'Old note' });
|
||||
render(<PlaceFormModal {...defaultProps} onSave={onSave} place={place} assignmentId={123} dayAssignments={[assignment]} />);
|
||||
|
||||
const notes = screen.getByRole('textbox', { name: 'Notes for this day' });
|
||||
expect(notes).toHaveValue('Old note');
|
||||
await user.clear(notes);
|
||||
await user.type(notes, 'Book a table by the window');
|
||||
await user.click(screen.getByRole('button', { name: /^Update$/i }));
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
|
||||
expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ assignment_notes: 'Book a table by the window' }));
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLACEFORM-124: unchanged notes for the day are left out of the save', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
const place = buildPlace({ name: 'Cafe 124' });
|
||||
const assignment = buildAssignment({ id: 124, day_id: 5, place, notes: 'Keep me' });
|
||||
render(<PlaceFormModal {...defaultProps} onSave={onSave} place={place} assignmentId={124} dayAssignments={[assignment]} />);
|
||||
await user.click(screen.getByRole('button', { name: /^Update$/i }));
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
|
||||
expect(onSave.mock.calls[0][0]).not.toHaveProperty('assignment_notes');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-COMP-PLACES-001 to FE-COMP-PLACES-015 + FE-PLANNER-SIDEBAR-016 to 043
|
||||
// FE-COMP-PLACES-001 to FE-COMP-PLACES-015 + FE-PLANNER-SIDEBAR-016 to 067
|
||||
import { render, screen, fireEvent, waitFor, act, within } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
@@ -1114,3 +1114,23 @@ describe('select mode and import menu', () => {
|
||||
expect(screen.queryByPlaceholderText(/naver\.me/)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Category filter: places without a category', () => {
|
||||
it('FE-PLANNER-SIDEBAR-067: "No Category" keeps only the places without one, and is offered only while there are some', async () => {
|
||||
const user = userEvent.setup();
|
||||
const cat = buildCategory({ name: 'Cafe', color: '#f97316' });
|
||||
const withCat = buildPlace({ name: 'Blue Bottle', category_id: cat.id, address: 'Kyoto' });
|
||||
const noCat = buildPlace({ name: 'Loose Stop', category_id: null, address: 'Osaka' });
|
||||
const { unmount } = render(<PlacesSidebar {...defaultProps} places={[withCat, noCat]} categories={[cat]} />);
|
||||
await openCategories(user);
|
||||
await user.click(screen.getByRole('button', { name: 'No Category' }));
|
||||
expect(screen.getByRole('button', { name: 'No Category' })).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(screen.getByText('Loose Stop')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Blue Bottle')).not.toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
render(<PlacesSidebar {...defaultProps} places={[withCat]} categories={[cat]} />);
|
||||
await openCategories(user);
|
||||
expect(screen.queryByRole('button', { name: 'No Category' })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
// FE-PLANNER-RESVIEW-001 to FE-PLANNER-RESVIEW-020
|
||||
import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { usePermissionsStore } from '../../store/permissionsStore';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { buildUser, buildTrip, buildReservation, buildDay, buildBudgetItem } from '../../../tests/helpers/factories';
|
||||
import { resetBodyScrollLock } from '../../utils/bodyScrollLock';
|
||||
import type { Reservation } from '../../types';
|
||||
import ReservationsPanel from './ReservationsPanel';
|
||||
|
||||
const onAdd = vi.fn();
|
||||
const onEdit = vi.fn();
|
||||
const onDelete = vi.fn();
|
||||
|
||||
const d1 = buildDay({ id: 1101, day_number: 1, date: '2025-06-01', title: 'Arrival' });
|
||||
const d2 = buildDay({ id: 1102, day_number: 2, date: '2025-06-02', title: null });
|
||||
|
||||
const flight = buildReservation({
|
||||
id: 1201, title: 'LH 716', type: 'flight', status: 'confirmed', reservation_time: '2025-06-01T08:00', reservation_end_time: '2025-06-01T12:00',
|
||||
confirmation_number: 'ABC123', metadata: JSON.stringify({ airline: 'Lufthansa', flight_number: 'LH716', seat: '12A' }),
|
||||
travelers: [{ user_id: 1, username: 'ada' }],
|
||||
endpoints: [
|
||||
{ role: 'from', sequence: 0, name: 'Frankfurt', code: 'FRA', lat: 50, lng: 8, timezone: null, local_time: null, local_date: null },
|
||||
{ role: 'to', sequence: 1, name: 'Haneda', code: 'HND', lat: 35, lng: 139, timezone: null, local_time: null, local_date: null },
|
||||
],
|
||||
});
|
||||
const dinner = buildReservation({ id: 1202, title: 'Kaiseki dinner', type: 'restaurant', status: 'pending', day_id: 1102, reservation_time: '19:00', location: 'Gion' });
|
||||
const metro = buildReservation({
|
||||
id: 1203, title: 'Metro ride', type: 'transit', status: 'confirmed', day_id: 1102,
|
||||
metadata: JSON.stringify({ transit: { legs: [{ mode: 'SUBWAY', line: 'Ginza', from: { name: 'Ueno' }, to: { name: 'Ginza' } }] } }),
|
||||
});
|
||||
|
||||
function renderPanel(reservations: Reservation[] = [flight, dinner], props: Partial<Parameters<typeof ReservationsPanel>[0]> = {}) {
|
||||
return render(
|
||||
<ReservationsPanel
|
||||
tripId={1}
|
||||
reservations={reservations}
|
||||
days={[d1, d2]}
|
||||
assignments={{}}
|
||||
files={[]}
|
||||
onAdd={onAdd}
|
||||
onEdit={onEdit}
|
||||
onDelete={onDelete}
|
||||
onNavigateToFiles={vi.fn()}
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
const viewButton = (name: 'Cards' | 'List' | 'Timeline') => within(screen.getByRole('group', { name: 'View' })).getByRole('button', { name });
|
||||
|
||||
async function openViewOptions(user: ReturnType<typeof userEvent.setup>) {
|
||||
await user.click(screen.getByRole('button', { name: 'View options' }));
|
||||
return screen.getByRole('menu');
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
onAdd.mockClear();
|
||||
onEdit.mockClear();
|
||||
onDelete.mockClear();
|
||||
resetAllStores();
|
||||
resetBodyScrollLock();
|
||||
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
|
||||
seedStore(useTripStore, { trip: buildTrip({ id: 1, start_date: '2025-06-01', end_date: '2025-06-02' }), budgetItems: [] });
|
||||
seedStore(useSettingsStore, { settings: { time_format: '24h', blur_booking_codes: false, language: 'en' } });
|
||||
server.use(http.get('/api/view-contributions/:view/:tripId', () => HttpResponse.json({ contributions: [] })));
|
||||
});
|
||||
|
||||
describe('ReservationsPanel views', () => {
|
||||
it('FE-PLANNER-RESVIEW-001: the list shows one row per booking, grouped by day, and remembers the view', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
await user.click(viewButton('List'));
|
||||
expect(viewButton('List')).toHaveAttribute('aria-pressed', 'true');
|
||||
const row = screen.getByRole('button', { name: 'LH 716', pressed: false });
|
||||
expect(row).toHaveTextContent('FRA → HND');
|
||||
expect(row).toHaveTextContent('Lufthansa LH716');
|
||||
expect(row).toHaveTextContent('12A');
|
||||
expect(screen.getByRole('button', { name: /Day 1/, expanded: true })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /Day 2/, expanded: true })).toBeInTheDocument();
|
||||
expect(localStorage.getItem('trek:bookings-bookings-view')).toBe('"list"');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESVIEW-002: a list row opens the detail, and its Edit hands the booking on', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
await user.click(viewButton('List'));
|
||||
await user.click(screen.getByRole('button', { name: 'Kaiseki dinner' }));
|
||||
const dialog = screen.getByRole('dialog', { name: 'Kaiseki dinner' });
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Edit' }));
|
||||
expect(onEdit).toHaveBeenCalledWith(dinner);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESVIEW-003: the arrow keys walk the rows and Enter opens the one in focus', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
await user.click(viewButton('List'));
|
||||
const first = screen.getByRole('button', { name: 'LH 716' });
|
||||
first.focus();
|
||||
await user.keyboard('{ArrowDown}');
|
||||
expect(screen.getByRole('button', { name: 'Kaiseki dinner' })).toHaveFocus();
|
||||
await user.keyboard('{ArrowUp}');
|
||||
expect(first).toHaveFocus();
|
||||
await user.keyboard('{Enter}');
|
||||
expect(screen.getByRole('dialog', { name: 'LH 716' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESVIEW-004: a list group collapses and opens again', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
await user.click(viewButton('List'));
|
||||
await user.click(screen.getByRole('button', { name: /Day 2/ }));
|
||||
expect(screen.queryByRole('button', { name: 'Kaiseki dinner' })).toBeNull();
|
||||
await user.click(screen.getByRole('button', { name: /Day 2/ }));
|
||||
expect(screen.getByRole('button', { name: 'Kaiseki dinner' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESVIEW-005: a list row edits, deletes after a question and switches status', async () => {
|
||||
const user = userEvent.setup();
|
||||
const toggleReservationStatus = vi.fn(async () => undefined);
|
||||
useTripStore.setState({ toggleReservationStatus } as never);
|
||||
renderPanel();
|
||||
await user.click(viewButton('List'));
|
||||
const row = screen.getByRole('button', { name: 'Kaiseki dinner' });
|
||||
await user.click(within(row).getByRole('button', { name: 'Edit' }));
|
||||
expect(onEdit).toHaveBeenCalledWith(dinner);
|
||||
await user.click(within(row).getByRole('button', { name: 'Set to Confirmed' }));
|
||||
expect(toggleReservationStatus).toHaveBeenCalledWith(1, 1202);
|
||||
await user.click(within(row).getByRole('button', { name: 'Delete' }));
|
||||
expect(screen.getByText(/will be permanently deleted/)).toBeInTheDocument();
|
||||
const deletes = screen.getAllByRole('button', { name: 'Delete' });
|
||||
await user.click(deletes[deletes.length - 1]);
|
||||
await waitFor(() => expect(onDelete).toHaveBeenCalledWith(1202));
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESVIEW-006: a failed status switch says so', async () => {
|
||||
const user = userEvent.setup();
|
||||
const toasts: string[] = [];
|
||||
window.__addToast = ((message: string) => { toasts.push(message); return 1; }) as unknown as typeof window.__addToast;
|
||||
useTripStore.setState({ toggleReservationStatus: vi.fn(async () => { throw new Error('offline'); }) } as never);
|
||||
renderPanel();
|
||||
await user.click(within(screen.getByRole('article', { name: 'Kaiseki dinner' })).getByRole('button', { name: 'Set to Confirmed' }));
|
||||
await waitFor(() => expect(toasts.length).toBe(1));
|
||||
delete window.__addToast;
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESVIEW-007: a transit journey shows its legs in the list, and linked costs and files on the row', async () => {
|
||||
const user = userEvent.setup();
|
||||
seedStore(useTripStore, { budgetItems: [buildBudgetItem({ reservation_id: 1202, total_price: 80, currency: 'JPY' } as never)] });
|
||||
renderPanel([flight, dinner, metro], { files: [{ id: 5, trip_id: 1, filename: 'a.pdf', original_name: 'menu.pdf', mime_type: 'application/pdf', url: '/f', reservation_id: 1202, created_at: '' } as never] });
|
||||
await user.click(viewButton('List'));
|
||||
expect(screen.getByRole('button', { name: 'Metro ride' })).toHaveTextContent('Ginza');
|
||||
const dinnerRow = screen.getByRole('button', { name: 'Kaiseki dinner' });
|
||||
expect(dinnerRow).toHaveTextContent('80');
|
||||
expect(within(dinnerRow).getByText('1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESVIEW-008: the timeline draws the bookings and a bar opens the detail', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
await user.click(viewButton('Timeline'));
|
||||
expect(screen.getByRole('group', { name: 'Zoom' })).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'LH 716' }));
|
||||
expect(screen.getByRole('dialog', { name: 'LH 716' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESVIEW-009: the timeline options switch the type lanes and the other tab', async () => {
|
||||
const user = userEvent.setup();
|
||||
const hotel = buildReservation({ id: 1204, type: 'hotel', title: 'Ryokan', accommodation_start_day_id: 1101, accommodation_end_day_id: 1102 });
|
||||
renderPanel([flight, dinner], { contributionView: 'transports', contextReservations: [hotel] });
|
||||
await user.click(viewButton('Timeline'));
|
||||
const menu = await openViewOptions(user);
|
||||
await user.click(within(menu).getByRole('button', { name: 'One lane per type' }));
|
||||
expect(screen.getByText('All')).toBeInTheDocument();
|
||||
await user.click(within(screen.getByRole('menu')).getByRole('button', { name: 'Show the other tab' }));
|
||||
expect(JSON.parse(localStorage.getItem('trek:bookings-transports-timeline') || '{}')).toMatchObject({ byType: false, context: false });
|
||||
await user.click(within(screen.getByRole('menu')).getByRole('button', { name: 'Reset view' }));
|
||||
expect(JSON.parse(localStorage.getItem('trek:bookings-transports-timeline') || '{}')).toMatchObject({ byType: true, context: true });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESVIEW-010: the view options group and sort the cards', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
let menu = await openViewOptions(user);
|
||||
// "Type" names both a grouping and a sort key; the grouping comes first.
|
||||
await user.click(within(menu).getAllByRole('button', { name: 'Type' })[0]);
|
||||
expect(screen.getByRole('button', { name: /Restaurant/, expanded: true })).toBeInTheDocument();
|
||||
menu = screen.getByRole('menu');
|
||||
await user.click(within(menu).getByRole('button', { name: 'No grouping' }));
|
||||
expect(screen.queryByRole('button', { name: /Restaurant/, expanded: true })).toBeNull();
|
||||
await user.click(within(screen.getByRole('menu')).getByRole('button', { name: 'Title' }));
|
||||
expect(within(screen.getByRole('menu')).getByRole('button', { name: 'A to Z' })).toBeInTheDocument();
|
||||
await user.click(within(screen.getByRole('menu')).getByRole('button', { name: 'A to Z' }));
|
||||
expect(within(screen.getByRole('menu')).getByRole('button', { name: 'Z to A' })).toBeInTheDocument();
|
||||
const titles = screen.getAllByRole('article').map(a => a.getAttribute('aria-label'));
|
||||
expect(titles).toEqual(['LH 716', 'Kaiseki dinner']);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESVIEW-011: sorting by date says earliest or latest first, and reset view restores the defaults', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
const menu = await openViewOptions(user);
|
||||
await user.click(within(menu).getByRole('button', { name: 'Earliest first' }));
|
||||
expect(within(screen.getByRole('menu')).getByRole('button', { name: 'Latest first' })).toBeInTheDocument();
|
||||
await user.click(within(screen.getByRole('menu')).getByRole('button', { name: 'Reset view' }));
|
||||
expect(screen.queryByRole('menu')).toBeNull();
|
||||
const again = await openViewOptions(user);
|
||||
expect(within(again).getByRole('button', { name: 'Earliest first' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESVIEW-012: with transit on the tab, cards can put it in its own section', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPanel([flight, dinner, metro]);
|
||||
expect(screen.queryByRole('button', { name: /Automated public transit/, expanded: true })).toBeNull();
|
||||
const menu = await openViewOptions(user);
|
||||
const apart = within(menu).getByRole('button', { name: 'Public transit as its own section' });
|
||||
expect(apart).toHaveAttribute('aria-pressed', 'false');
|
||||
await user.click(apart);
|
||||
expect(screen.getByRole('button', { name: /Automated public transit/, expanded: true })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESVIEW-013: the view options close on Escape', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
const menu = await openViewOptions(user);
|
||||
fireEvent.keyDown(menu, { key: 'Escape' });
|
||||
expect(screen.queryByRole('menu')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESVIEW-014: search narrows the cards, counts the results and clears again', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
const search = screen.getByRole('textbox', { name: 'Search' });
|
||||
await user.type(search, 'gion');
|
||||
expect(screen.queryByRole('article', { name: 'LH 716' })).toBeNull();
|
||||
expect(screen.getByRole('article', { name: 'Kaiseki dinner' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /1 of 2/ })).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Clear' }));
|
||||
expect(search).toHaveValue('');
|
||||
await user.type(search, 'zzz');
|
||||
expect(screen.getByText('Nothing matches these filters')).toBeInTheDocument();
|
||||
await user.keyboard('{Escape}');
|
||||
expect(search).toHaveValue('');
|
||||
await user.type(search, 'abc123');
|
||||
await user.click(screen.getByRole('button', { name: /1 of 2/ }));
|
||||
expect(search).toHaveValue('');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESVIEW-015: the status filter keeps confirmed or pending bookings and counts on the button', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
await user.click(screen.getByRole('button', { name: 'Filter' }));
|
||||
const menu = screen.getByRole('menu');
|
||||
await user.click(within(menu).getByRole('button', { name: 'Pending' }));
|
||||
expect(screen.queryByRole('article', { name: 'LH 716' })).toBeNull();
|
||||
expect(within(screen.getByRole('button', { name: 'Filter' })).getByText('1')).toBeInTheDocument();
|
||||
await user.click(within(menu).getByRole('button', { name: 'Reset filters' }));
|
||||
expect(screen.getByRole('article', { name: 'LH 716' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESVIEW-016: a card opens the detail on click or Enter, and Close shuts it', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
await user.click(screen.getByRole('article', { name: 'LH 716' }));
|
||||
expect(screen.getByRole('dialog', { name: 'LH 716' })).toBeInTheDocument();
|
||||
await user.click(within(screen.getByRole('dialog', { name: 'LH 716' })).getByRole('button', { name: 'Close' }));
|
||||
expect(screen.queryByRole('dialog', { name: 'LH 716' })).toBeNull();
|
||||
screen.getByRole('article', { name: 'LH 716' }).focus();
|
||||
await user.keyboard('{Enter}');
|
||||
expect(screen.getByRole('dialog', { name: 'LH 716' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESVIEW-017: deleting the booking the detail shows closes the detail first', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPanel();
|
||||
await user.click(screen.getByRole('article', { name: 'Kaiseki dinner' }));
|
||||
expect(screen.getByRole('dialog', { name: 'Kaiseki dinner' })).toBeInTheDocument();
|
||||
await user.click(within(screen.getByRole('article', { name: 'Kaiseki dinner' })).getByRole('button', { name: 'Delete' }));
|
||||
const deletes = screen.getAllByRole('button', { name: 'Delete' });
|
||||
await user.click(deletes[deletes.length - 1]);
|
||||
await waitFor(() => expect(onDelete).toHaveBeenCalledWith(1202));
|
||||
expect(screen.queryByRole('dialog', { name: 'Kaiseki dinner' })).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESVIEW-018: an empty transports tab offers adding, importing and AirTrail', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onImport = vi.fn();
|
||||
const onAirTrailImport = vi.fn();
|
||||
renderPanel([], { contributionView: 'transports', addManualKey: 'transport.addManual', onImport, bookingImportAvailable: true, onAirTrailImport, airTrailAvailable: true });
|
||||
await user.click(screen.getByRole('button', { name: 'Import from file' }));
|
||||
expect(onImport).toHaveBeenCalled();
|
||||
await user.click(screen.getByRole('button', { name: 'AirTrail' }));
|
||||
expect(onAirTrailImport).toHaveBeenCalled();
|
||||
expect(screen.queryByRole('textbox', { name: 'Search' })).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESVIEW-019: a card shows its linked expense and a transit card its journey', () => {
|
||||
seedStore(useTripStore, { budgetItems: [buildBudgetItem({ reservation_id: 1201, total_price: 420, currency: 'EUR' } as never)] });
|
||||
renderPanel([flight, metro]);
|
||||
expect(within(screen.getByRole('article', { name: 'LH 716' })).getByText(/420/)).toBeInTheDocument();
|
||||
expect(within(screen.getByRole('article', { name: 'Metro ride' })).getByText('Ueno')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESVIEW-020: without the booking right the list rows have no actions', async () => {
|
||||
const user = userEvent.setup();
|
||||
seedStore(usePermissionsStore, { permissions: { reservation_edit: 'admin' } });
|
||||
renderPanel();
|
||||
await user.click(viewButton('List'));
|
||||
const row = screen.getByRole('button', { name: 'LH 716' });
|
||||
expect(within(row).queryByRole('button', { name: 'Edit' })).toBeNull();
|
||||
expect(within(row).queryByRole('button', { name: /Set to/ })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-PLANNER-TRANSMODAL-001 to FE-PLANNER-TRANSMODAL-080
|
||||
// FE-PLANNER-TRANSMODAL-001 to FE-PLANNER-TRANSMODAL-082
|
||||
import { render, screen, waitFor, fireEvent, within, act } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
@@ -1619,4 +1619,45 @@ describe('TransportModal', () => {
|
||||
expect(hint).not.toHaveClass('truncate');
|
||||
expect(screen.queryByText('Title *')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TRANSMODAL-081: a car stop moves up and keeps the time given to it', async () => {
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
render(<TransportModal {...defaultProps} days={routeDays} selectedDayId={10} onSave={onSave} />);
|
||||
|
||||
await pickType(/^Car$/i);
|
||||
await userEvent.type(screen.getByPlaceholderText(/e.g. Lufthansa/i), 'Mietwagen');
|
||||
await userEvent.click(screen.getByRole('button', { name: /Add stop/i }));
|
||||
await userEvent.click(screen.getByRole('button', { name: /Add stop/i }));
|
||||
|
||||
const fields = screen.getAllByTestId('location-select');
|
||||
fireEvent.change(fields[0], { target: { value: 'Berlin' } });
|
||||
fireEvent.change(fields[1], { target: { value: 'Prag' } });
|
||||
fireEvent.change(fields[2], { target: { value: 'Dresden' } });
|
||||
fireEvent.change(fields[3], { target: { value: 'Bastei' } });
|
||||
// The stops' own time fields come first, before the pick-up and return times.
|
||||
fireEvent.change(screen.getAllByTestId('time-picker')[1], { target: { value: '14:30' } });
|
||||
|
||||
await userEvent.click(screen.getAllByRole('button', { name: /Move up/i })[1]);
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /^Add$/i }));
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalled());
|
||||
const payload = onSave.mock.calls[0][0];
|
||||
expect(payload.endpoints.map((e: { name: string }) => e.name)).toEqual(['Berlin', 'Bastei', 'Dresden', 'Prag']);
|
||||
expect(payload.endpoints.find((e: { name: string }) => e.name === 'Bastei').local_time).toBe('14:30');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TRANSMODAL-082: a multi-leg train saves the code typed for one of its segments', async () => {
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
render(<TransportModal {...defaultProps} days={routeDays} reservation={multiLegTrain()} onSave={onSave} />);
|
||||
|
||||
const codes = screen.getAllByPlaceholderText('e.g. ABC12345') as HTMLInputElement[];
|
||||
// One code per segment, then the booking's own.
|
||||
expect(codes).toHaveLength(3);
|
||||
fireEvent.change(codes[1], { target: { value: 'SEG-TWO' } });
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /^Update$/i }));
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalled());
|
||||
const legs = onSave.mock.calls[0][0].metadata.legs as { confirmation_number?: string }[];
|
||||
expect(legs.map(l => l.confirmation_number ?? null)).toEqual([null, 'SEG-TWO']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
// FE-PLANNER-BKDETAIL-001 to FE-PLANNER-BKDETAIL-013
|
||||
import { render, screen, waitFor, within } from '../../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../../tests/helpers/msw/server';
|
||||
import { resetAllStores, seedStore } from '../../../../tests/helpers/store';
|
||||
import { buildAssignment, buildDay, buildPlace, buildReservation, buildTrip, buildUser } from '../../../../tests/helpers/factories';
|
||||
import { resetBodyScrollLock } from '../../../utils/bodyScrollLock';
|
||||
import { useAuthStore } from '../../../store/authStore';
|
||||
import { useTripStore } from '../../../store/tripStore';
|
||||
import { usePluginStore } from '../../../store/pluginStore';
|
||||
import { useSettingsStore } from '../../../store/settingsStore';
|
||||
import type { Reservation, ReservationEndpoint } from '../../../types';
|
||||
import BookingDetailHost, { type BookingDetailHostProps } from './BookingDetailHost';
|
||||
|
||||
function ep(over: Partial<ReservationEndpoint>): ReservationEndpoint {
|
||||
return { role: 'from', sequence: 0, name: 'Stop', code: null, lat: 1, lng: 1, timezone: null, local_time: null, local_date: null, ...over };
|
||||
}
|
||||
|
||||
const onClose = vi.fn();
|
||||
const toasts: Array<{ message: string; type: string }> = [];
|
||||
|
||||
const d1 = buildDay({ id: 1301, day_number: 1, date: '2025-06-01', title: 'Arrival' });
|
||||
const d2 = buildDay({ id: 1302, day_number: 2, date: '2025-06-02', title: null });
|
||||
const d3 = buildDay({ id: 1303, day_number: 3, date: '2025-06-04', title: null });
|
||||
|
||||
function renderDetail(r: Reservation, props: Partial<BookingDetailHostProps> = {}) {
|
||||
return render(
|
||||
<BookingDetailHost r={r} tripId={1} days={[d1, d2, d3]} assignments={{}} files={[]} canEdit contributions={[]}
|
||||
onClose={onClose} onDelete={vi.fn()} onNavigateToFiles={vi.fn()} {...props} />,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
onClose.mockClear();
|
||||
toasts.length = 0;
|
||||
resetAllStores();
|
||||
resetBodyScrollLock();
|
||||
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
|
||||
seedStore(useTripStore, { trip: buildTrip({ id: 1, currency: 'EUR' }), budgetItems: [] });
|
||||
seedStore(useSettingsStore, { settings: { time_format: '24h', blur_booking_codes: false, language: 'en' } });
|
||||
usePluginStore.setState({ plugins: [] });
|
||||
window.__addToast = ((message: string, type: string) => { toasts.push({ message, type }); return 1; }) as unknown as typeof window.__addToast;
|
||||
server.use(http.get('/api/view-contributions/:view/:tripId', () => HttpResponse.json({ contributions: [] })));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete window.__addToast;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('BookingDetailDialog', () => {
|
||||
it('FE-PLANNER-BKDETAIL-001: a transport states its carrier and route in the head, its times as tiles', () => {
|
||||
const r = buildReservation({
|
||||
title: 'LH 716', type: 'flight', day_id: 1301, reservation_time: '2025-06-01T08:00', reservation_end_time: '2025-06-01T12:30',
|
||||
metadata: JSON.stringify({ airline: 'Lufthansa', flight_number: 'LH716', platform: 'B', seat: '12A', class: 'Business' }),
|
||||
endpoints: [ep({ role: 'from', name: 'Frankfurt', code: 'FRA' }), ep({ role: 'to', sequence: 1, name: 'Haneda', code: 'HND' })],
|
||||
});
|
||||
renderDetail(r);
|
||||
const dialog = screen.getByRole('dialog', { name: 'LH 716' });
|
||||
expect(within(dialog).getByText('Lufthansa LH716 FRA → HND', { normalizer: s => s })).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('08:00')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('Frankfurt')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('12:30')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('Haneda')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('12A')).toBeInTheDocument();
|
||||
// Seat and platform stand as tiles, not a second time in the fields.
|
||||
expect(within(dialog).queryByText('12A, Business')).toBeNull();
|
||||
expect(within(dialog).getByText('Arrival')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('Sun, Jun 1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKDETAIL-002: without endpoints the tiles fall back to Start and End', () => {
|
||||
renderDetail(buildReservation({ title: 'Rental', type: 'car', reservation_time: '2025-06-01T09:00', reservation_end_time: '2025-06-02T18:00' }));
|
||||
expect(screen.getByText('Start')).toBeInTheDocument();
|
||||
expect(screen.getByText('End')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKDETAIL-003: a stay shows check-in, check-out and its nights, without repeating the date', () => {
|
||||
const r = buildReservation({
|
||||
title: 'Ryokan', type: 'hotel', accommodation_start_day_id: 1301, accommodation_end_day_id: 1303,
|
||||
metadata: JSON.stringify({ check_in_time: '15:00', check_out_time: '10:00' }),
|
||||
});
|
||||
renderDetail(r);
|
||||
expect(screen.getByText('Check-in 15:00')).toBeInTheDocument();
|
||||
expect(screen.getByText('Check-out 10:00')).toBeInTheDocument();
|
||||
expect(screen.getByText('Jun 1')).toBeInTheDocument();
|
||||
expect(screen.getByText('Jun 4')).toBeInTheDocument();
|
||||
expect(screen.getByText('3')).toBeInTheDocument();
|
||||
expect(screen.getByText('Nights')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Jun 1 → Jun 4')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKDETAIL-004: a stay without an end has no night count', () => {
|
||||
renderDetail(buildReservation({ title: 'Guesthouse', type: 'hotel', day_id: 1302 }));
|
||||
expect(screen.getByText('Check-in')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Nights')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKDETAIL-005: a route with stops is listed stop by stop, and segment codes under it', () => {
|
||||
const r = buildReservation({
|
||||
title: 'Via Munich', type: 'flight',
|
||||
metadata: JSON.stringify({ legs: [{ from: 'FRA', to: 'MUC', confirmation_number: 'SEG1' }, { from: 'MUC', to: 'HND', confirmation_number: 'SEG2' }] }),
|
||||
endpoints: [
|
||||
ep({ role: 'from', name: 'Frankfurt', code: 'FRA', local_time: '07:00' }),
|
||||
ep({ role: 'stop', sequence: 1, name: 'Munich', code: null }),
|
||||
ep({ role: 'to', sequence: 2, name: 'Haneda', code: 'HND', local_time: '09:00' }),
|
||||
],
|
||||
});
|
||||
renderDetail(r);
|
||||
expect(screen.getByText('Route')).toBeInTheDocument();
|
||||
expect(screen.getByText('Munich')).toBeInTheDocument();
|
||||
expect(screen.getByText('Segment codes')).toBeInTheDocument();
|
||||
expect(screen.getByText('FRA → MUC')).toBeInTheDocument();
|
||||
expect(screen.getByText('#SEG2')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKDETAIL-006: place, accommodation, linked stop, link, travelers and notes', () => {
|
||||
const place = buildPlace({ name: 'Kinkaku-ji', place_time: '10:00' });
|
||||
const a = buildAssignment({ id: 4401, day_id: 1302, place });
|
||||
const r = buildReservation({
|
||||
title: 'Temple tour', type: 'tour', location: 'Kyoto', accommodation_name: 'Ryokan', assignment_id: 4401, url: 'https://example.com/tour',
|
||||
notes: '**Bring** cash', travelers: [{ user_id: 3, username: 'maria' }],
|
||||
metadata: JSON.stringify({ price: '30' }),
|
||||
});
|
||||
renderDetail(r, { assignments: { '1302': [a] } });
|
||||
expect(screen.getByText('Kyoto')).toBeInTheDocument();
|
||||
expect(screen.getByText('Ryokan')).toBeInTheDocument();
|
||||
expect(screen.getByText('Day 2, Kinkaku-ji, 10:00')).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: 'https://example.com/tour' })).toHaveAttribute('href', 'https://example.com/tour');
|
||||
expect(screen.getByText('maria')).toBeInTheDocument();
|
||||
expect(screen.getByText('Bring')).toBeInTheDocument();
|
||||
expect(screen.getByText('Price')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKDETAIL-007: a link that is not safe stays text', () => {
|
||||
renderDetail(buildReservation({ title: 'Odd link', url: 'call the hotel' }));
|
||||
expect(screen.getByText('call the hotel')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('link', { name: 'call the hotel' })).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKDETAIL-008: the booking code copies to the clipboard and says so', async () => {
|
||||
const user = userEvent.setup();
|
||||
const writeText = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(undefined);
|
||||
renderDetail(buildReservation({ title: 'Dinner', confirmation_number: 'XYZ9' }));
|
||||
expect(screen.getByText('#XYZ9')).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Copy booking code' }));
|
||||
expect(writeText).toHaveBeenCalledWith('XYZ9');
|
||||
await waitFor(() => expect(toasts).toContainEqual({ message: 'Copied', type: 'success' }));
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKDETAIL-009: a failed copy says so', async () => {
|
||||
const user = userEvent.setup();
|
||||
vi.spyOn(navigator.clipboard, 'writeText').mockRejectedValue(new Error('denied'));
|
||||
renderDetail(buildReservation({ title: 'Dinner', confirmation_number: 'XYZ9' }));
|
||||
await user.click(screen.getByRole('button', { name: 'Copy booking code' }));
|
||||
await waitFor(() => expect(toasts).toContainEqual({ message: 'Could not copy', type: 'error' }));
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKDETAIL-010: clicking the title renames the booking through the store', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateReservation = vi.fn(async () => undefined);
|
||||
useTripStore.setState({ updateReservation } as never);
|
||||
const r = buildReservation({ title: 'Dinner' });
|
||||
renderDetail(r);
|
||||
await user.click(screen.getByRole('button', { name: 'Dinner' }));
|
||||
const field = screen.getByRole('textbox', { name: 'Rename' });
|
||||
expect(field).toHaveValue('Dinner');
|
||||
// Escape leaves the rename, not the detail under it.
|
||||
await user.keyboard('{Escape}');
|
||||
expect(screen.queryByRole('textbox', { name: 'Rename' })).toBeNull();
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Dinner' }));
|
||||
await user.clear(screen.getByRole('textbox', { name: 'Rename' }));
|
||||
await user.type(screen.getByRole('textbox', { name: 'Rename' }), 'Kaiseki at Kikunoi');
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
expect(updateReservation).toHaveBeenCalledWith(1, r.id, { title: 'Kaiseki at Kikunoi' });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKDETAIL-011: an unchanged name saves nothing, a failed rename says so', async () => {
|
||||
const user = userEvent.setup();
|
||||
const updateReservation = vi.fn(async () => { throw new Error('offline'); });
|
||||
useTripStore.setState({ updateReservation } as never);
|
||||
renderDetail(buildReservation({ title: 'Dinner' }));
|
||||
await user.click(screen.getByRole('button', { name: 'Dinner' }));
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
expect(updateReservation).not.toHaveBeenCalled();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Dinner' }));
|
||||
await user.type(screen.getByRole('textbox', { name: 'Rename' }), ' 2');
|
||||
await user.keyboard('{Enter}');
|
||||
await waitFor(() => expect(toasts).toContainEqual({ message: 'Failed to update', type: 'error' }));
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKDETAIL-012: without the booking right the title is only read', () => {
|
||||
renderDetail(buildReservation({ title: 'Dinner', status: 'pending' }), { canEdit: false });
|
||||
expect(screen.queryByRole('button', { name: 'Dinner' })).toBeNull();
|
||||
expect(screen.getByRole('heading', { name: 'Dinner' })).toBeInTheDocument();
|
||||
expect(screen.getByText('Pending')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKDETAIL-013: a booking with only an end time shows it in the clock format of the user', () => {
|
||||
seedStore(useSettingsStore, { settings: { time_format: '12h', blur_booking_codes: false, language: 'en' } });
|
||||
const r = buildReservation({ id: 950, type: 'train', title: 'Night train', status: 'confirmed', reservation_time: null, reservation_end_time: '2025-06-01T15:00' } as never);
|
||||
renderDetail(r);
|
||||
expect(screen.getByText('3:00 PM')).toBeInTheDocument();
|
||||
expect(screen.queryByText('15:00')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -85,8 +85,9 @@ export default function BookingDetailDialog(p: BookingDetailDialogProps) {
|
||||
} else {
|
||||
const from = facts.endpoints[0]
|
||||
const to = facts.endpoints[facts.endpoints.length - 1]
|
||||
if (facts.startTime) stats.push({ value: facts.time?.split(' → ')[0] || facts.startTime, label: from?.name || t('reservations.start') })
|
||||
if (facts.endTime) stats.push({ value: facts.time?.split(' → ')[1] || facts.endTime, label: to?.name || t('reservations.end') })
|
||||
// Each tile formats its own time: a booking with only an end has no "start → end" line to cut up.
|
||||
if (facts.startTime) stats.push({ value: formatTime(facts.startTime, locale, timeFormat), label: from?.name || t('reservations.start') })
|
||||
if (facts.endTime) stats.push({ value: formatTime(facts.endTime, locale, timeFormat), label: to?.name || t('reservations.end') })
|
||||
if (transit?.duration) stats.push({ value: fmtTransitDuration(transit.duration, t), label: t('transit.durationLabel') })
|
||||
if (transit && transit.legs.length > 0) stats.push({ value: String(transit.transfers), label: t('transit.transfersLabel') })
|
||||
// Under a minute of walking is not worth a tile.
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
// FE-PLANNER-BKTIMELINEVIEW-001 to FE-PLANNER-BKTIMELINEVIEW-016
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, within } from '../../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { resetAllStores, seedStore } from '../../../../tests/helpers/store';
|
||||
import { buildDay, buildReservation } from '../../../../tests/helpers/factories';
|
||||
import { useSettingsStore } from '../../../store/settingsStore';
|
||||
import type { Day, Reservation, ReservationEndpoint } from '../../../types';
|
||||
import { bookingFacts } from './bookingFacts';
|
||||
import BookingsTimeline, { type BookingsTimelineProps } from './BookingsTimeline';
|
||||
|
||||
function ep(over: Partial<ReservationEndpoint>): ReservationEndpoint {
|
||||
return { role: 'from', sequence: 0, name: 'Stop', code: null, lat: 1, lng: 1, timezone: null, local_time: null, local_date: null, ...over };
|
||||
}
|
||||
|
||||
// The lanes are laid out from the width the observer reports; jsdom has no layout, so this one reports a wide screen.
|
||||
let reportedWidth = 1400;
|
||||
class WideObserver {
|
||||
constructor(private cb: ResizeObserverCallback) {}
|
||||
observe() { this.cb([{ contentRect: { width: reportedWidth } } as ResizeObserverEntry], this as unknown as ResizeObserver); }
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
}
|
||||
|
||||
const d1 = buildDay({ id: 801, day_number: 1, date: '2025-06-01', title: 'Arrival' });
|
||||
const d2 = buildDay({ id: 802, day_number: 2, date: '2025-06-02', title: null });
|
||||
const d3 = buildDay({ id: 803, day_number: 3, date: '2025-06-03', title: null });
|
||||
const days: Day[] = [d1, d2, d3];
|
||||
|
||||
const flight = buildReservation({
|
||||
id: 8801, type: 'flight', title: 'LH 716', status: 'confirmed', reservation_time: '2025-06-01T08:00', reservation_end_time: '2025-06-01T12:00',
|
||||
location: 'Frankfurt',
|
||||
endpoints: [ep({ role: 'from', name: 'Frankfurt', code: 'FRA' }), ep({ role: 'to', sequence: 1, name: 'Haneda', code: 'HND' })],
|
||||
});
|
||||
const train = buildReservation({ id: 8802, type: 'train', title: 'Shinkansen', status: 'pending', reservation_time: '2025-06-02T09:00', reservation_end_time: '2025-06-02T11:30' });
|
||||
const early = buildReservation({ id: 8803, type: 'restaurant', title: 'Farewell dinner', reservation_time: '2025-05-20T19:00' });
|
||||
const late = buildReservation({ id: 8804, type: 'tour', title: 'Bonus tour', status: 'pending', reservation_time: '2025-07-01T10:00' });
|
||||
const loose = buildReservation({ id: 8805, type: 'transit', title: 'Metro ride' });
|
||||
|
||||
const factsOf = (r: Reservation) => bookingFacts(r, {
|
||||
t: (k, p) => (p && 'n' in p ? `Day ${p.n}` : k), locale: 'en-US', timeFormat: '24h', days, assignmentLookup: {}, tripCurrency: 'EUR', hasLinkedCost: false,
|
||||
});
|
||||
|
||||
const onSelect = vi.fn();
|
||||
const onZoom = vi.fn();
|
||||
|
||||
function renderTimeline(props: Partial<BookingsTimelineProps> = {}) {
|
||||
return render(
|
||||
<BookingsTimeline
|
||||
items={[flight, train]}
|
||||
context={[]}
|
||||
contextLabel="Bookings"
|
||||
days={days}
|
||||
zoom="trip"
|
||||
onZoom={onZoom}
|
||||
byType
|
||||
showContext
|
||||
selectedId={null}
|
||||
onSelect={onSelect}
|
||||
factsOf={factsOf}
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, time_format: '24h', language: 'en' } });
|
||||
reportedWidth = 1400;
|
||||
vi.stubGlobal('ResizeObserver', WideObserver);
|
||||
onSelect.mockClear();
|
||||
onZoom.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('BookingsTimeline: trip view', () => {
|
||||
it('FE-PLANNER-BKTIMELINEVIEW-001: states the trip\'s range and length, with one lane per type', () => {
|
||||
renderTimeline();
|
||||
expect(screen.getByText('Jun 1 → Jun 3')).toBeInTheDocument();
|
||||
expect(screen.getByText('3 days')).toBeInTheDocument();
|
||||
expect(screen.getByText('Flight')).toBeInTheDocument();
|
||||
expect(screen.getByText('Train')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINEVIEW-002: a bar is a button named by its booking that selects it', async () => {
|
||||
renderTimeline();
|
||||
await userEvent.click(screen.getByRole('button', { name: 'LH 716' }));
|
||||
expect(onSelect).toHaveBeenCalledWith(flight);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINEVIEW-003: without lanes per type everything shares one lane', () => {
|
||||
renderTimeline({ byType: false });
|
||||
expect(screen.getByText('All')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Flight')).toBeNull();
|
||||
expect(screen.getByRole('button', { name: 'Shinkansen' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINEVIEW-004: a day head opens that day by the hour', async () => {
|
||||
renderTimeline();
|
||||
await userEvent.click(screen.getByRole('button', { name: /Day 2/ }));
|
||||
expect(onZoom).toHaveBeenCalledWith('day');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINEVIEW-005: the zoom switch reports trip and day', async () => {
|
||||
renderTimeline();
|
||||
const zoom = screen.getByRole('group', { name: 'Zoom' });
|
||||
expect(within(zoom).getByRole('button', { name: 'Trip' })).toHaveAttribute('aria-pressed', 'true');
|
||||
await userEvent.click(within(zoom).getByRole('button', { name: 'Day' }));
|
||||
await userEvent.click(within(zoom).getByRole('button', { name: 'Trip' }));
|
||||
expect(onZoom.mock.calls).toEqual([['day'], ['trip']]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINEVIEW-006: what the axis cannot place waits below, grouped, and selects on click', async () => {
|
||||
renderTimeline({ items: [flight, early, late, loose], selectedId: 8805 });
|
||||
expect(screen.getByText('Before the trip')).toBeInTheDocument();
|
||||
expect(screen.getByText('After the trip')).toBeInTheDocument();
|
||||
expect(screen.getByText('No date')).toBeInTheDocument();
|
||||
const metro = screen.getByRole('button', { name: /Metro ride/ });
|
||||
expect(metro).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(screen.getByRole('button', { name: /Bonus tour/ })).toHaveTextContent('Tour, Pending');
|
||||
expect(screen.getByRole('button', { name: /Farewell dinner/ })).toHaveTextContent('Restaurant, Confirmed');
|
||||
await userEvent.click(screen.getByRole('button', { name: /Farewell dinner/ }));
|
||||
expect(onSelect).toHaveBeenCalledWith(early);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINEVIEW-007: nothing dated says so', () => {
|
||||
renderTimeline({ items: [loose] });
|
||||
expect(screen.getByText('None of these has a date yet.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINEVIEW-008: the other tab shows as a dimmed lane, only while asked for', () => {
|
||||
const hotel = buildReservation({ id: 8806, type: 'hotel', title: 'Ryokan', accommodation_start_day_id: 801, accommodation_end_day_id: 803 });
|
||||
const { rerender } = renderTimeline({ context: [hotel], contextLabel: 'Bookings' });
|
||||
expect(screen.getByText('Bookings')).toBeInTheDocument();
|
||||
expect(screen.getByText('Ryokan')).toBeInTheDocument();
|
||||
rerender(
|
||||
<BookingsTimeline items={[flight]} context={[hotel]} contextLabel="Bookings" days={days} zoom="trip" onZoom={onZoom}
|
||||
byType showContext={false} selectedId={null} onSelect={onSelect} factsOf={factsOf} />,
|
||||
);
|
||||
expect(screen.queryByText('Ryokan')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINEVIEW-009: resting on a bar shows what it holds, leaving hides it', async () => {
|
||||
renderTimeline();
|
||||
const bar = screen.getByRole('button', { name: 'LH 716' });
|
||||
fireEvent.mouseEnter(bar);
|
||||
const card = screen.getByRole('tooltip');
|
||||
expect(card).toHaveTextContent('LH 716');
|
||||
expect(card).toHaveTextContent('Flight, Confirmed');
|
||||
expect(card).toHaveTextContent('08:00 → 12:00');
|
||||
expect(card).toHaveTextContent('FRA → HND');
|
||||
expect(card).toHaveTextContent('Frankfurt');
|
||||
fireEvent.mouseLeave(bar);
|
||||
expect(screen.queryByRole('tooltip')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINEVIEW-010: the focus shows the same card, near the bottom of the window above the bar', () => {
|
||||
renderTimeline();
|
||||
const bar = screen.getByRole('button', { name: 'Shinkansen' });
|
||||
vi.spyOn(bar, 'getBoundingClientRect').mockReturnValue({ top: 700, bottom: 740, left: 5000, right: 5100, width: 100, height: 40, x: 5000, y: 700, toJSON: () => ({}) } as DOMRect);
|
||||
fireEvent.focus(bar);
|
||||
const card = screen.getByRole('tooltip');
|
||||
expect(card).toHaveTextContent('Train, Pending');
|
||||
expect(card.style.transform).toBe('translateY(-100%)');
|
||||
fireEvent.blur(bar);
|
||||
expect(screen.queryByRole('tooltip')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINEVIEW-011: on a trip without dates the days are counted, not dated', () => {
|
||||
const a = buildDay({ id: 811, day_number: 1, date: null });
|
||||
const b = buildDay({ id: 812, day_number: 2, date: null });
|
||||
const bus = buildReservation({ id: 8807, type: 'bus', title: 'Night bus', reservation_time: '21:00', day_id: 812 });
|
||||
reportedWidth = 0;
|
||||
renderTimeline({ days: [a, b], items: [bus] });
|
||||
expect(screen.queryByText(/days$/)).toBeNull();
|
||||
expect(screen.getByRole('button', { name: 'Night bus' })).toBeInTheDocument();
|
||||
// Too narrow for "Day 2", so the head keeps only the number.
|
||||
expect(screen.getByRole('button', { name: '2' })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('BookingsTimeline: day view', () => {
|
||||
it('FE-PLANNER-BKTIMELINEVIEW-012: opens on the first day with something on it, and walks the days', async () => {
|
||||
renderTimeline({ zoom: 'day', items: [train] });
|
||||
expect(screen.getByText('Day 2')).toBeInTheDocument();
|
||||
expect(screen.getByText('Mon, Jun 2')).toBeInTheDocument();
|
||||
expect(screen.getByText('09:00')).toBeInTheDocument();
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Previous day' }));
|
||||
expect(screen.getByText('Arrival')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Previous day' })).toBeDisabled();
|
||||
expect(screen.getByText('Nothing on this day.')).toBeInTheDocument();
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Next day' }));
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Next day' }));
|
||||
expect(screen.getByRole('button', { name: 'Next day' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINEVIEW-013: a detailed bar carries its times and route', () => {
|
||||
renderTimeline({ zoom: 'day', items: [flight] });
|
||||
const bar = screen.getByRole('button', { name: 'LH 716' });
|
||||
expect(bar).toHaveTextContent('LH 716');
|
||||
expect(bar).toHaveTextContent('08:00 → 12:00 FRA → HND');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINEVIEW-014: a bar running past the day in view marks the cut', () => {
|
||||
const rental = buildReservation({ id: 8808, type: 'car', title: 'Rental', reservation_time: '2025-06-01T10:00', reservation_end_time: '2025-06-03T10:00' });
|
||||
renderTimeline({ zoom: 'day', items: [rental] });
|
||||
expect(screen.getByRole('button', { name: 'Rental' }).querySelectorAll('svg').length).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINEVIEW-015: during the trip the day view opens on today, marks now and offers a way back', async () => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
vi.setSystemTime(new Date(2025, 5, 3, 14, 30));
|
||||
renderTimeline({ zoom: 'day', items: [flight, train] });
|
||||
expect(screen.getByText('now')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Today' })).toBeNull();
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Previous day' }));
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Today' }));
|
||||
expect(screen.getByText('now')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Today' })).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINEVIEW-016: a long trip scrolls in the trip view, and Today scrolls to now', async () => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
vi.setSystemTime(new Date(2025, 5, 20, 9, 0));
|
||||
const many = Array.from({ length: 30 }, (_, i) => buildDay({ id: 900 + i, day_number: i + 1, date: `2025-06-${String(i + 1).padStart(2, '0')}` }));
|
||||
reportedWidth = 600;
|
||||
const original = Element.prototype.scrollTo;
|
||||
const scrollTo = vi.fn();
|
||||
Element.prototype.scrollTo = scrollTo as unknown as typeof Element.prototype.scrollTo;
|
||||
try {
|
||||
renderTimeline({ days: many, items: [flight] });
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Today' }));
|
||||
expect(scrollTo).toHaveBeenCalledWith(expect.objectContaining({ behavior: 'smooth' }));
|
||||
} finally {
|
||||
Element.prototype.scrollTo = original;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,192 @@
|
||||
// FE-PLANNER-BKFACTS-001 to FE-PLANNER-BKFACTS-020
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { buildDay, buildReservation } from '../../../../tests/helpers/factories';
|
||||
import type { ReservationEndpoint } from '../../../types';
|
||||
import { bookingFacts, formatDay, type FactsContext } from './bookingFacts';
|
||||
|
||||
function ep(over: Partial<ReservationEndpoint>): ReservationEndpoint {
|
||||
return { role: 'from', sequence: 0, name: 'Stop', code: null, lat: 1, lng: 1, timezone: null, local_time: null, local_date: null, ...over };
|
||||
}
|
||||
|
||||
const t: FactsContext['t'] = (key, params) => (params && 'n' in params ? `${key}#${params.n}` : key);
|
||||
|
||||
const d1 = buildDay({ id: 701, day_number: 1, date: '2025-06-01', title: 'Arrival' });
|
||||
const d2 = buildDay({ id: 702, day_number: 2, date: '2025-06-02', title: null });
|
||||
const d3 = buildDay({ id: 703, day_number: 3, date: null, title: null });
|
||||
|
||||
function ctx(over: Partial<FactsContext> = {}): FactsContext {
|
||||
return { t, locale: 'en-US', timeFormat: '24h', days: [d1, d2, d3], assignmentLookup: {}, tripCurrency: 'EUR', hasLinkedCost: false, ...over };
|
||||
}
|
||||
|
||||
const cell = (facts: ReturnType<typeof bookingFacts>, label: string) => facts.cells.find(c => c.label === label)?.value;
|
||||
|
||||
describe('formatDay', () => {
|
||||
it('FE-PLANNER-BKFACTS-001: prints a date with or without its weekday, in UTC', () => {
|
||||
expect(formatDay('2025-06-02', 'en-US')).toBe('Mon, Jun 2');
|
||||
expect(formatDay('2025-06-02', 'en-US', false)).toBe('Jun 2');
|
||||
});
|
||||
});
|
||||
|
||||
describe('bookingFacts: day', () => {
|
||||
it('FE-PLANNER-BKFACTS-002: one linked day gives its title and the date with a weekday', () => {
|
||||
const f = bookingFacts(buildReservation({ day_id: 701 }), ctx());
|
||||
expect(f.day).toEqual({ label: 'Arrival', date: 'Sun, Jun 1', range: false });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKFACTS-003: a day range names both days and both dates without weekdays', () => {
|
||||
const f = bookingFacts(buildReservation({ day_id: 701, end_day_id: 702 }), ctx());
|
||||
expect(f.day).toEqual({ label: 'Arrival → dayplan.dayN#2', date: 'Jun 1 → Jun 2', range: true });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKFACTS-004: a day without a date has no date beside it', () => {
|
||||
const f = bookingFacts(buildReservation({ day_id: 703, end_day_id: 703 }), ctx());
|
||||
expect(f.day).toEqual({ label: 'dayplan.dayN#3', date: null, range: false });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKFACTS-005: without a day the booking dates stand in, a range when they differ', () => {
|
||||
expect(bookingFacts(buildReservation({ reservation_time: '2025-06-02T10:00' }), ctx()).day)
|
||||
.toEqual({ label: 'Mon, Jun 2', date: null, range: false });
|
||||
expect(bookingFacts(buildReservation({ reservation_time: '2025-06-02T10:00', reservation_end_time: '2025-06-04T10:00' }), ctx()).day)
|
||||
.toEqual({ label: 'Mon, Jun 2 → Wed, Jun 4', date: null, range: true });
|
||||
expect(bookingFacts(buildReservation({ reservation_time: '2025-06-02T10:00', reservation_end_time: '2025-06-02T12:00' }), ctx()).day?.range).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKFACTS-006: without day or date there is no day', () => {
|
||||
expect(bookingFacts(buildReservation({}), ctx()).day).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKFACTS-007: a hotel takes its range from the accommodation', () => {
|
||||
const f = bookingFacts(buildReservation({ type: 'hotel', accommodation_start_day_id: 701, accommodation_end_day_id: 702 }), ctx());
|
||||
expect(f.day?.label).toBe('Arrival → dayplan.dayN#2');
|
||||
expect(f.isHotel).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('bookingFacts: time', () => {
|
||||
it('FE-PLANNER-BKFACTS-008: start and end time with an arrow', () => {
|
||||
const f = bookingFacts(buildReservation({ reservation_time: '2025-06-01T09:05', reservation_end_time: '2025-06-01T11:30' }), ctx());
|
||||
expect(f.time).toBe('09:05 → 11:30');
|
||||
expect(f.startTime).toBe('09:05');
|
||||
expect(f.endTime).toBe('11:30');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKFACTS-009: follows the 12 hour setting', () => {
|
||||
const f = bookingFacts(buildReservation({ reservation_time: '2025-06-01T15:00' }), ctx({ timeFormat: '12h' }));
|
||||
expect(f.time).toMatch(/^3:00\s?PM$/);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKFACTS-010: only an end time still reads as one', () => {
|
||||
const f = bookingFacts(buildReservation({ reservation_end_time: '2025-06-01T11:30' }), ctx());
|
||||
expect(f.time).toBe('→ 11:30');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKFACTS-011: the endpoints\' local times stand in for a transport', () => {
|
||||
const r = buildReservation({
|
||||
type: 'flight',
|
||||
endpoints: [ep({ role: 'from', sequence: 0, local_time: '07:10', local_date: '2025-06-01' }), ep({ role: 'to', sequence: 1, local_time: '09:40', local_date: '2025-06-02' })],
|
||||
});
|
||||
const f = bookingFacts(r, ctx());
|
||||
expect(f.time).toBe('07:10 → 09:40');
|
||||
expect(f.startDate).toBe('2025-06-01');
|
||||
expect(f.endDate).toBe('2025-06-02');
|
||||
expect(f.endpoints).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKFACTS-012: a stay backed by an accommodation shows no time of its own', () => {
|
||||
const r = buildReservation({ type: 'hotel', reservation_time: '2025-06-01T15:00', accommodation_start_day_id: 701 });
|
||||
expect(bookingFacts(r, ctx()).time).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKFACTS-013: without times nothing is shown and the dates fall back to the days', () => {
|
||||
const f = bookingFacts(buildReservation({ day_id: 701, end_day_id: 702 }), ctx());
|
||||
expect(f.time).toBeNull();
|
||||
expect(f.startDate).toBe('2025-06-01');
|
||||
expect(f.endDate).toBe('2025-06-02');
|
||||
expect(bookingFacts(buildReservation({}), ctx())).toMatchObject({ startDate: null, endDate: null, endpoints: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('bookingFacts: cells', () => {
|
||||
it('FE-PLANNER-BKFACTS-014: flight facts, the airports only when there is no route', () => {
|
||||
const meta = { airline: 'ANA', flight_number: 'NH204', departure_airport: 'FRA', arrival_airport: 'HND', seat: '12A', class: 'Economy', platform: '7' };
|
||||
const bare = bookingFacts(buildReservation({ type: 'flight', metadata: JSON.stringify(meta) }), ctx());
|
||||
expect(cell(bare, 'reservations.meta.airline')).toBe('ANA');
|
||||
expect(cell(bare, 'reservations.meta.flightNumber')).toBe('NH204');
|
||||
expect(cell(bare, 'reservations.meta.from')).toBe('FRA');
|
||||
expect(cell(bare, 'reservations.meta.to')).toBe('HND');
|
||||
expect(cell(bare, 'reservations.meta.seat')).toBe('12A, Economy');
|
||||
expect(cell(bare, 'reservations.meta.platform')).toBe('7');
|
||||
|
||||
const routed = bookingFacts(buildReservation({
|
||||
type: 'flight', metadata: JSON.stringify(meta),
|
||||
endpoints: [ep({ role: 'from' }), ep({ role: 'to', sequence: 1 })],
|
||||
}), ctx());
|
||||
expect(cell(routed, 'reservations.meta.from')).toBeUndefined();
|
||||
expect(cell(routed, 'reservations.meta.to')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKFACTS-015: a seat without a class, and the train number', () => {
|
||||
const f = bookingFacts(buildReservation({ type: 'train', metadata: JSON.stringify({ seat: '44', train_number: 'ICE 71' }) }), ctx());
|
||||
expect(cell(f, 'reservations.meta.seat')).toBe('44');
|
||||
expect(cell(f, 'reservations.meta.trainNumber')).toBe('ICE 71');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKFACTS-016: the stored price shows only while no expense is linked', () => {
|
||||
const r = buildReservation({ metadata: JSON.stringify({ price: '120', priceCurrency: 'usd' }) });
|
||||
const price = cell(bookingFacts(r, ctx()), 'reservations.price');
|
||||
expect(price).toContain('120');
|
||||
expect(price).toContain('$');
|
||||
expect(cell(bookingFacts(r, ctx({ hasLinkedCost: true })), 'reservations.price')).toBeUndefined();
|
||||
expect(cell(bookingFacts(buildReservation({ metadata: JSON.stringify({ price: '' }) }), ctx()), 'reservations.price')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKFACTS-017: check-in with its window and check-out', () => {
|
||||
const f = bookingFacts(buildReservation({ type: 'hotel', metadata: JSON.stringify({ check_in_time: '15:00', check_in_end_time: '22:00', check_out_time: '11:00' }) }), ctx({ locale: 'de-DE' }));
|
||||
expect(cell(f, 'reservations.meta.checkIn')).toBe('15:00 Uhr → 22:00 Uhr');
|
||||
expect(cell(f, 'reservations.meta.checkOut')).toBe('11:00 Uhr');
|
||||
const open = bookingFacts(buildReservation({ type: 'hotel', metadata: JSON.stringify({ check_in_time: '15:00' }) }), ctx());
|
||||
expect(cell(open, 'reservations.meta.checkIn')).toBe('15:00');
|
||||
});
|
||||
});
|
||||
|
||||
describe('bookingFacts: codes, links and places', () => {
|
||||
it('FE-PLANNER-BKFACTS-018: per-segment codes only on a booking with more than one leg', () => {
|
||||
const legs = [
|
||||
{ from: 'FRA', to: 'MUC', confirmation_number: 'SEG1' },
|
||||
{ from: 'MUC', to: null, confirmation_number: 'SEG2' },
|
||||
{ from: 'X', to: 'Y' },
|
||||
];
|
||||
const flight = bookingFacts(buildReservation({ type: 'flight', metadata: JSON.stringify({ legs }) }), ctx());
|
||||
expect(flight.legCodes).toEqual([{ route: 'FRA → MUC', code: 'SEG1' }, { route: 'MUC', code: 'SEG2' }]);
|
||||
const train = bookingFacts(buildReservation({ type: 'train', metadata: JSON.stringify({ legs }) }), ctx());
|
||||
expect(train.legCodes).toHaveLength(2);
|
||||
const single = bookingFacts(buildReservation({ type: 'flight', metadata: JSON.stringify({ legs: [legs[0]] }) }), ctx());
|
||||
expect(single.legCodes).toEqual([]);
|
||||
const bus = bookingFacts(buildReservation({ type: 'bus', metadata: JSON.stringify({ legs }) }), ctx());
|
||||
expect(bus.legCodes).toEqual([]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKFACTS-019: a booking linked to a plan stop names the day, place and time', () => {
|
||||
const lookup = {
|
||||
11: { dayNumber: 2, dayTitle: null, dayDate: '2025-06-02', placeName: 'Louvre', startTime: '10:00', endTime: '12:00' },
|
||||
12: { dayNumber: 1, dayTitle: 'Arrival', dayDate: '2025-06-01', placeName: 'Hotel', startTime: '18:00', endTime: null },
|
||||
13: { dayNumber: 1, dayTitle: 'Arrival', dayDate: null, placeName: 'Park', startTime: null, endTime: null },
|
||||
};
|
||||
expect(bookingFacts(buildReservation({ assignment_id: 11 }), ctx({ assignmentLookup: lookup })).linked).toBe('dayplan.dayN#2, Louvre, 10:00 → 12:00');
|
||||
expect(bookingFacts(buildReservation({ assignment_id: 12 }), ctx({ assignmentLookup: lookup })).linked).toBe('Arrival, Hotel, 18:00');
|
||||
expect(bookingFacts(buildReservation({ assignment_id: 13 }), ctx({ assignmentLookup: lookup })).linked).toBe('Arrival, Park');
|
||||
expect(bookingFacts(buildReservation({ assignment_id: 99 }), ctx({ assignmentLookup: lookup })).linked).toBeNull();
|
||||
expect(bookingFacts(buildReservation({}), ctx()).linked).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKFACTS-020: place, accommodation and a link made safe for an href', () => {
|
||||
const f = bookingFacts(buildReservation({ location: 'Gion', place_name: 'Kikunoi', accommodation_name: 'Ryokan', url: 'www.kikunoi.jp' }), ctx());
|
||||
expect(f.place).toBe('Gion');
|
||||
expect(f.accommodation).toBe('Ryokan');
|
||||
expect(f.url).toEqual({ href: 'https://www.kikunoi.jp', text: 'www.kikunoi.jp' });
|
||||
expect(bookingFacts(buildReservation({ place_name: 'Kikunoi' }), ctx()).place).toBe('Kikunoi');
|
||||
const plain = bookingFacts(buildReservation({}), ctx());
|
||||
expect(plain).toMatchObject({ place: null, accommodation: null, url: null });
|
||||
expect(bookingFacts(buildReservation({ url: 'javascript:alert(1)' }), ctx()).url?.href).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,353 @@
|
||||
// FE-PLANNER-BKMODEL-001 to FE-PLANNER-BKMODEL-040
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { Plane, TramFront, FileText, Hotel } from 'lucide-react';
|
||||
import { buildAssignment, buildDay, buildPlace, buildReservation } from '../../../../tests/helpers/factories';
|
||||
import type { Day, Reservation, ReservationEndpoint } from '../../../types';
|
||||
import {
|
||||
TYPE_ORDER,
|
||||
applyFilters,
|
||||
buildAssignmentLookup,
|
||||
costsFor,
|
||||
daySpan,
|
||||
displayTitle,
|
||||
groupReservations,
|
||||
parseMeta,
|
||||
phaseOf,
|
||||
searchText,
|
||||
sortReservations,
|
||||
startKey,
|
||||
typeInfo,
|
||||
type BookingFilters,
|
||||
type GroupLabels,
|
||||
} from './bookingsModel';
|
||||
|
||||
const label = (type: string) => `L:${type}`;
|
||||
|
||||
function ep(over: Partial<ReservationEndpoint>): ReservationEndpoint {
|
||||
return { role: 'from', sequence: 0, name: 'Somewhere', code: null, lat: 1, lng: 1, timezone: null, local_time: null, local_date: null, ...over };
|
||||
}
|
||||
|
||||
function filters(over: Partial<BookingFilters> = {}): BookingFilters {
|
||||
return { types: new Set(), status: 'all', travelers: new Set(), query: '', ...over };
|
||||
}
|
||||
|
||||
const labels: GroupLabels = {
|
||||
confirmed: 'Confirmed',
|
||||
pending: 'Pending',
|
||||
transit: 'Transit',
|
||||
before: 'Before the trip',
|
||||
after: 'After the trip',
|
||||
undated: 'No date',
|
||||
dayN: n => `Day ${n}`,
|
||||
typeLabel: t => `Type ${t}`,
|
||||
dayDate: d => `on ${d}`,
|
||||
};
|
||||
|
||||
const d1 = buildDay({ id: 501, day_number: 1, date: '2025-06-01', title: 'Arrival' });
|
||||
const d2 = buildDay({ id: 502, day_number: 2, date: '2025-06-02', title: null });
|
||||
const d3 = buildDay({ id: 503, day_number: 3, date: '2025-06-03', title: 'Hike' });
|
||||
const days: Day[] = [d1, d2, d3];
|
||||
|
||||
describe('typeInfo', () => {
|
||||
it('FE-PLANNER-BKMODEL-001: a known type gets its icon, label key and the phone colour', () => {
|
||||
const info = typeInfo('flight');
|
||||
expect(info.Icon).toBe(Plane);
|
||||
expect(info.labelKey).toBe('reservations.type.flight');
|
||||
expect(info.chipKey).toBe('reservations.type.flight');
|
||||
expect(info.color).toBe('#3b82f6');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-002: transit carries a shorter chip label than its full name', () => {
|
||||
const info = typeInfo('transit');
|
||||
expect(info.Icon).toBe(TramFront);
|
||||
expect(info.labelKey).toBe('reservations.type.transit');
|
||||
expect(info.chipKey).toBe('reservations.typeShort.transit');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-003: a booking type takes its colour from the bookings palette', () => {
|
||||
const info = typeInfo('hotel');
|
||||
expect(info.Icon).toBe(Hotel);
|
||||
expect(info.color).toBe('#8b5cf6');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-004: an unknown type reads as "other"', () => {
|
||||
const info = typeInfo('spaceship');
|
||||
expect(info.Icon).toBe(FileText);
|
||||
expect(info.labelKey).toBe('reservations.type.other');
|
||||
expect(info.chipKey).toBe('reservations.type.other');
|
||||
expect(info.color).toBe('#6b7280');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-005: every type in the pill order resolves to itself', () => {
|
||||
for (const type of TYPE_ORDER) expect(typeInfo(type).labelKey).toBe(`reservations.type.${type}`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseMeta', () => {
|
||||
it('FE-PLANNER-BKMODEL-006: reads plain and double-encoded metadata, and nothing from garbage', () => {
|
||||
expect(parseMeta(buildReservation({ metadata: '{"airline":"LH"}' }))).toEqual({ airline: 'LH' });
|
||||
expect(parseMeta(buildReservation({ metadata: JSON.stringify('{"seat":"12A"}') }))).toEqual({ seat: '12A' });
|
||||
expect(parseMeta(buildReservation({ metadata: 'not json' }))).toEqual({});
|
||||
expect(parseMeta(buildReservation({ metadata: null }))).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildAssignmentLookup', () => {
|
||||
it('FE-PLANNER-BKMODEL-007: names each assignment by its day, place and times', () => {
|
||||
const place = buildPlace({ name: 'Louvre', place_time: '10:00', end_time: '12:00' });
|
||||
const a = buildAssignment({ id: 9001, day_id: d1.id, place });
|
||||
const lookup = buildAssignmentLookup(days, { [String(d1.id)]: [a] });
|
||||
expect(lookup[9001]).toEqual({ dayNumber: 1, dayTitle: 'Arrival', dayDate: '2025-06-01', placeName: 'Louvre', startTime: '10:00', endTime: '12:00' });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-008: skips assignments without a place and survives missing inputs', () => {
|
||||
const a = buildAssignment({ id: 9002, day_id: d2.id });
|
||||
const orphan = { ...buildAssignment({ id: 9003, day_id: d2.id }), place: undefined } as unknown as typeof a;
|
||||
const lookup = buildAssignmentLookup(days, { [String(d2.id)]: [orphan, a] });
|
||||
expect(Object.keys(lookup)).toEqual(['9002']);
|
||||
expect(lookup[9002].dayTitle).toBeNull();
|
||||
expect(lookup[9002].startTime).toBeNull();
|
||||
expect(buildAssignmentLookup(days, undefined)).toEqual({});
|
||||
expect(buildAssignmentLookup(undefined as unknown as Day[], {})).toEqual({});
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-009: a day without a date or title leaves both null', () => {
|
||||
const bare = buildDay({ id: 504, day_number: 4, date: null, title: undefined });
|
||||
const a = buildAssignment({ id: 9004, day_id: 504 });
|
||||
expect(buildAssignmentLookup([bare], { '504': [a] })[9004]).toMatchObject({ dayDate: null, dayTitle: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe('daySpan and startKey', () => {
|
||||
it('FE-PLANNER-BKMODEL-010: a hotel reads its range from the accommodation', () => {
|
||||
const r = buildReservation({ type: 'hotel', day_id: d1.id, accommodation_start_day_id: d2.id, accommodation_end_day_id: d3.id });
|
||||
expect(daySpan(r, days)).toEqual({ start: d2, end: d3 });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-011: anything else reads its own day and end day', () => {
|
||||
const r = buildReservation({ type: 'train', day_id: d1.id, end_day_id: d2.id });
|
||||
expect(daySpan(r, days)).toEqual({ start: d1, end: d2 });
|
||||
expect(daySpan(buildReservation({ type: 'hotel', day_id: d3.id }), days)).toEqual({ start: d3, end: undefined });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-012: startKey uses the booking date and time', () => {
|
||||
expect(startKey(buildReservation({ reservation_time: '2025-06-02T14:30' }), days)).toBe('2025-06-02T14:30');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-013: a time without a date takes the linked day, a hotel its first stay day', () => {
|
||||
expect(startKey(buildReservation({ reservation_time: '08:15', day_id: d2.id }), days)).toBe('2025-06-02T08:15');
|
||||
expect(startKey(buildReservation({ type: 'hotel', accommodation_start_day_id: d3.id, day_id: d1.id }), days)).toBe('2025-06-03T00:00');
|
||||
expect(startKey(buildReservation({ type: 'hotel', day_id: d1.id }), days)).toBe('2025-06-01T00:00');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-014: without any date there is no key', () => {
|
||||
expect(startKey(buildReservation({ reservation_time: null }), days)).toBeNull();
|
||||
expect(startKey(buildReservation({ day_id: 99999 }), days)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('phaseOf', () => {
|
||||
it('FE-PLANNER-BKMODEL-015: places a key before, during or after the trip', () => {
|
||||
expect(phaseOf(null, '2025-06-01', '2025-06-03')).toBe('undated');
|
||||
expect(phaseOf('2025-05-30T10:00', '2025-06-01', '2025-06-03')).toBe('before');
|
||||
expect(phaseOf('2025-06-04T10:00', '2025-06-01', '2025-06-03')).toBe('after');
|
||||
expect(phaseOf('2025-06-02T10:00', '2025-06-01', '2025-06-03')).toBe('during');
|
||||
expect(phaseOf('1999-01-01T00:00', null, null)).toBe('during');
|
||||
});
|
||||
});
|
||||
|
||||
describe('searchText and applyFilters', () => {
|
||||
const flight = buildReservation({
|
||||
id: 7001,
|
||||
type: 'flight',
|
||||
title: 'To Tokyo',
|
||||
status: 'confirmed',
|
||||
confirmation_number: 'ABC123',
|
||||
metadata: JSON.stringify({ airline: 'Lufthansa', flight_number: 'LH716', legs: [{ confirmation_number: 'LEG9', flight_number: 'NH1' }] }),
|
||||
endpoints: [ep({ name: 'Frankfurt', code: 'FRA' }), ep({ role: 'to', sequence: 1, name: 'Haneda', code: 'HND' })],
|
||||
travelers: [{ user_id: 11, username: 'Maria' }],
|
||||
});
|
||||
const dinner = buildReservation({ id: 7002, type: 'restaurant', title: 'Dinner', status: 'pending', location: 'Gion', travelers: [{ user_id: 12, username: 'Ken' }] });
|
||||
const ride = buildReservation({ id: 7003, type: 'transit', title: 'Metro', status: 'pending' });
|
||||
const list = [flight, dinner, ride];
|
||||
|
||||
it('FE-PLANNER-BKMODEL-016: search text holds title, type label, codes, carrier, legs and travelers in lower case', () => {
|
||||
const text = searchText(flight, 'Flight');
|
||||
for (const word of ['to tokyo', 'flight', 'abc123', 'lufthansa', 'lh716', 'fra', 'haneda', 'leg9', 'nh1', 'maria']) {
|
||||
expect(text).toContain(word);
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-017: search text ignores metadata legs that are not a list', () => {
|
||||
const r = buildReservation({ title: 'Bus', metadata: JSON.stringify({ legs: 'nope' }) });
|
||||
expect(searchText(r, 'Bus')).toBe('bus bus');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-018: with no filter every booking stays', () => {
|
||||
expect(applyFilters(list, filters(), label)).toEqual(list);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-019: the type filter keeps only the picked types', () => {
|
||||
expect(applyFilters(list, filters({ types: new Set(['restaurant']) }), label)).toEqual([dinner]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-020: a status filter leaves transit out, pending keeps everything unconfirmed', () => {
|
||||
expect(applyFilters(list, filters({ status: 'confirmed' }), label)).toEqual([flight]);
|
||||
expect(applyFilters(list, filters({ status: 'pending' }), label)).toEqual([dinner]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-021: the traveler filter keeps bookings for one of the picked people', () => {
|
||||
expect(applyFilters(list, filters({ travelers: new Set([12]) }), label)).toEqual([dinner]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-022: the query matches case-insensitively, the type label included', () => {
|
||||
expect(applyFilters(list, filters({ query: ' GION ' }), label)).toEqual([dinner]);
|
||||
expect(applyFilters(list, filters({ query: 'l:transit' }), label)).toEqual([ride]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sortReservations', () => {
|
||||
const early = buildReservation({ id: 7101, title: 'Bravo', type: 'train', status: 'pending', reservation_time: '2025-06-01T09:00', created_at: '2025-01-02' });
|
||||
const late = buildReservation({ id: 7102, title: 'Alpha', type: 'flight', status: 'confirmed', reservation_time: '2025-06-03T09:00', created_at: '2025-01-01' });
|
||||
const undatedA = buildReservation({ id: 7103, title: 'Charlie', type: 'transit', status: 'pending', created_at: '2025-01-01' });
|
||||
const undatedB = buildReservation({ id: 7104, title: 'Delta', type: 'bus', status: 'confirmed', created_at: '2025-01-05' });
|
||||
const sameTime = buildReservation({ id: 7105, title: 'Echo', type: 'bus', status: 'confirmed', reservation_time: '2025-06-01T09:00', created_at: '2025-01-01' });
|
||||
const ids = (list: Reservation[]) => list.map(r => r.id);
|
||||
|
||||
it('FE-PLANNER-BKMODEL-023: by date: chronological, creation order on a tie, undated last', () => {
|
||||
expect(ids(sortReservations([undatedB, late, undatedA, early, sameTime], days, 'date', 'asc', label))).toEqual([7105, 7101, 7102, 7103, 7104]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-024: by date descending keeps the undated entries at the bottom', () => {
|
||||
expect(ids(sortReservations([undatedB, early, undatedA, late], days, 'date', 'desc', label))).toEqual([7102, 7101, 7103, 7104]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-025: by title in both directions', () => {
|
||||
expect(ids(sortReservations([early, late, undatedA], days, 'title', 'asc', label))).toEqual([7102, 7101, 7103]);
|
||||
expect(ids(sortReservations([early, late, undatedA], days, 'title', 'desc', label))).toEqual([7103, 7101, 7102]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-026: by type uses the translated label and falls back to date on a tie', () => {
|
||||
expect(ids(sortReservations([undatedB, sameTime, late], days, 'type', 'asc', label))).toEqual([7105, 7104, 7102]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-027: by status puts confirmed first and transit last while it is apart', () => {
|
||||
expect(ids(sortReservations([undatedA, early, late], days, 'status', 'asc', label))).toEqual([7102, 7101, 7103]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-028: with transit not apart it sorts as if confirmed', () => {
|
||||
expect(ids(sortReservations([early, undatedA, late], days, 'status', 'asc', label, false))).toEqual([7102, 7103, 7101]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-029: a missing creation date still sorts', () => {
|
||||
const a = buildReservation({ id: 7106, created_at: undefined });
|
||||
const b = buildReservation({ id: 7107, created_at: '2025-01-01' });
|
||||
expect(ids(sortReservations([b, a], days, 'date', 'asc', label))).toEqual([7106, 7107]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('groupReservations', () => {
|
||||
const confirmed = buildReservation({ id: 7201, type: 'train', status: 'confirmed', day_id: d1.id });
|
||||
const pending = buildReservation({ id: 7202, type: 'restaurant', status: 'pending', day_id: d2.id });
|
||||
const transit = buildReservation({ id: 7203, type: 'transit', status: 'pending', day_id: d2.id });
|
||||
const sorted = [confirmed, pending, transit];
|
||||
|
||||
it('FE-PLANNER-BKMODEL-030: none puts everything in one unnamed group', () => {
|
||||
expect(groupReservations(sorted, 'none', days, null, null, labels)).toEqual([{ id: 'all', label: '', items: sorted }]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-031: by status: confirmed, pending, transit, empty groups dropped', () => {
|
||||
const groups = groupReservations(sorted, 'status', days, null, null, labels);
|
||||
expect(groups.map(g => [g.id, g.label, g.items.map(r => r.id)])).toEqual([
|
||||
['confirmed', 'Confirmed', [7201]],
|
||||
['pending', 'Pending', [7202]],
|
||||
['transit', 'Transit', [7203]],
|
||||
]);
|
||||
expect(groupReservations([pending], 'status', days, null, null, labels).map(g => g.id)).toEqual(['pending']);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-032: by status without transit apart, transit sits among the confirmed', () => {
|
||||
const groups = groupReservations(sorted, 'status', days, null, null, labels, false);
|
||||
expect(groups.map(g => [g.id, g.items.map(r => r.id)])).toEqual([
|
||||
['confirmed', [7201, 7203]],
|
||||
['pending', [7202]],
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-033: by type keeps the order types first appear in', () => {
|
||||
const groups = groupReservations([pending, confirmed, buildReservation({ id: 7204, type: 'restaurant' })], 'type', days, null, null, labels);
|
||||
expect(groups.map(g => [g.id, g.label, g.items.map(r => r.id)])).toEqual([
|
||||
['type-restaurant', 'Type restaurant', [7202, 7204]],
|
||||
['type-train', 'Type train', [7201]],
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-034: by day: the day with its date and title, then after the trip, then undated', () => {
|
||||
const before = buildReservation({ id: 7205, reservation_time: '2025-05-20T10:00' });
|
||||
const after = buildReservation({ id: 7206, reservation_time: '2025-07-01T10:00' });
|
||||
const undated = buildReservation({ id: 7207 });
|
||||
const groups = groupReservations([undated, after, confirmed, pending, before], 'day', days, '2025-06-01', '2025-06-03', labels);
|
||||
expect(groups.map(g => [g.id, g.label, g.sub, g.items.map(r => r.id)])).toEqual([
|
||||
['before', 'Before the trip', undefined, [7205]],
|
||||
['day-501', 'Day 1', 'on 2025-06-01 Arrival', [7201]],
|
||||
['day-502', 'Day 2', 'on 2025-06-02', [7202]],
|
||||
['after', 'After the trip', undefined, [7206]],
|
||||
['undated', 'No date', undefined, [7207]],
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-035: by day finds the day from the date, or groups by the bare date when no day matches', () => {
|
||||
const onDay = buildReservation({ id: 7208, reservation_time: '2025-06-03T08:00' });
|
||||
const offDays = buildReservation({ id: 7209, reservation_time: '2025-06-10T08:00' });
|
||||
const groups = groupReservations([onDay, offDays], 'day', days, null, null, labels);
|
||||
expect(groups.map(g => [g.id, g.label, g.sub])).toEqual([
|
||||
['day-503', 'Day 3', 'on 2025-06-03 Hike'],
|
||||
['date-2025-06-10', 'on 2025-06-10', undefined],
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-036: a day without date or title has no second part', () => {
|
||||
const bare = buildDay({ id: 505, day_number: 5, date: null, title: null });
|
||||
const r = buildReservation({ id: 7210, day_id: 505, reservation_time: '2025-06-02T10:00' });
|
||||
expect(groupReservations([r], 'day', [bare], null, null, labels)[0]).toMatchObject({ id: 'day-505', label: 'Day 5', sub: undefined });
|
||||
});
|
||||
});
|
||||
|
||||
describe('costsFor', () => {
|
||||
it('FE-PLANNER-BKMODEL-037: sums the linked expenses per currency and never across currencies', () => {
|
||||
const items = [
|
||||
{ reservation_id: 1, total_price: 10.1, currency: 'eur' },
|
||||
{ reservation_id: 1, total_price: 0.2, currency: 'EUR' },
|
||||
{ reservation_id: 1, total_price: 5, currency: 'USD' },
|
||||
{ reservation_id: 2, total_price: 99, currency: 'EUR' },
|
||||
{ reservation_id: 1, total_price: 1, currency: null },
|
||||
];
|
||||
expect(costsFor(1, items, 'jpy')).toEqual([
|
||||
{ currency: 'EUR', amount: 10.3 },
|
||||
{ currency: 'USD', amount: 5 },
|
||||
{ currency: 'JPY', amount: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-038: without any currency it falls back to EUR, and nothing linked is an empty list', () => {
|
||||
expect(costsFor(3, [{ reservation_id: 3, total_price: 4 }], '')).toEqual([{ currency: 'EUR', amount: 4 }]);
|
||||
expect(costsFor(4, [{ reservation_id: 3, total_price: 4 }], 'EUR')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('displayTitle', () => {
|
||||
it('FE-PLANNER-BKMODEL-039: a title wins; without one the route in sequence order, codes before names', () => {
|
||||
expect(displayTitle(buildReservation({ title: 'Named' }))).toBe('Named');
|
||||
const r = buildReservation({
|
||||
title: ' ',
|
||||
endpoints: [ep({ role: 'to', sequence: 2, name: 'Kyoto', code: null }), ep({ role: 'from', sequence: 1, name: 'Tokyo', code: 'TYO' })],
|
||||
});
|
||||
expect(displayTitle(r)).toBe('TYO → Kyoto');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-040: without a route the place, then the location, then nothing', () => {
|
||||
expect(displayTitle(buildReservation({ title: '', place_name: 'Hotel Sakura', location: 'Kyoto' }))).toBe('Hotel Sakura');
|
||||
expect(displayTitle(buildReservation({ title: '', location: 'Kyoto', endpoints: [ep({})] }))).toBe('Kyoto');
|
||||
expect(displayTitle(buildReservation({ title: '' }))).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
// FE-PLANNER-BKONMAP-001 to FE-PLANNER-BKONMAP-009
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { buildReservation } from '../../../../tests/helpers/factories';
|
||||
import type { ReservationEndpoint } from '../../../types';
|
||||
import { canShowOnMap, hasRoute, showReservationOnMap, type ShowOnMapDeps } from './showOnMap';
|
||||
|
||||
function ep(over: Partial<ReservationEndpoint>): ReservationEndpoint {
|
||||
return { role: 'from', sequence: 0, name: 'Stop', code: null, lat: 35.6, lng: 139.7, timezone: null, local_time: null, local_date: null, ...over };
|
||||
}
|
||||
|
||||
const route = [ep({ role: 'from' }), ep({ role: 'to', sequence: 1, lat: 34.9, lng: 135.7 })];
|
||||
|
||||
function deps(visible: number[] = []): ShowOnMapDeps {
|
||||
return { visibleConnections: visible, toggleConnection: vi.fn(), selectDay: vi.fn(), selectPlace: vi.fn(), openPlan: vi.fn() };
|
||||
}
|
||||
|
||||
describe('hasRoute', () => {
|
||||
it('FE-PLANNER-BKONMAP-001: two endpoints with coordinates make a route', () => {
|
||||
expect(hasRoute(buildReservation({ endpoints: route }))).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKONMAP-002: endpoints without usable coordinates, one endpoint or none do not', () => {
|
||||
expect(hasRoute(buildReservation({ endpoints: [route[0], ep({ role: 'to', sequence: 1, lat: Number.NaN })] }))).toBe(false);
|
||||
expect(hasRoute(buildReservation({ endpoints: [route[0]] }))).toBe(false);
|
||||
expect(hasRoute(buildReservation({}))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('showReservationOnMap', () => {
|
||||
it('FE-PLANNER-BKONMAP-003: a transport switches its route on and opens the plan on its day', () => {
|
||||
const d = deps();
|
||||
showReservationOnMap(buildReservation({ id: 41, type: 'train', day_id: 7, endpoints: route }), d);
|
||||
expect(d.toggleConnection).toHaveBeenCalledWith(41);
|
||||
expect(d.selectDay).toHaveBeenCalledWith(7);
|
||||
expect(d.openPlan).toHaveBeenCalled();
|
||||
expect(d.selectPlace).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKONMAP-004: without a start day it opens on the end day, or on no day', () => {
|
||||
const d = deps();
|
||||
showReservationOnMap(buildReservation({ id: 42, type: 'train', end_day_id: 8, endpoints: route }), d);
|
||||
expect(d.selectDay).toHaveBeenCalledWith(8);
|
||||
const e = deps();
|
||||
showReservationOnMap(buildReservation({ id: 43, type: 'train', endpoints: route }), e);
|
||||
expect(e.selectDay).toHaveBeenCalledWith(null);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKONMAP-005: pressed again while the route is drawn, it only switches the route off', () => {
|
||||
const d = deps([44]);
|
||||
showReservationOnMap(buildReservation({ id: 44, type: 'flight', day_id: 7, endpoints: route }), d);
|
||||
expect(d.toggleConnection).toHaveBeenCalledWith(44);
|
||||
expect(d.selectDay).not.toHaveBeenCalled();
|
||||
expect(d.openPlan).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKONMAP-006: a booking with a place opens the plan on that place and its day', () => {
|
||||
const d = deps();
|
||||
showReservationOnMap(buildReservation({ type: 'restaurant', place_id: 90, day_id: 3 }), d);
|
||||
expect(d.selectDay).toHaveBeenCalledWith(3);
|
||||
expect(d.selectPlace).toHaveBeenCalledWith(90);
|
||||
expect(d.openPlan).toHaveBeenCalled();
|
||||
const e = deps();
|
||||
showReservationOnMap(buildReservation({ type: 'restaurant', place_id: 91 }), e);
|
||||
expect(e.selectDay).toHaveBeenCalledWith(null);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKONMAP-007: a hotel uses its accommodation place and first night, falling back to its own', () => {
|
||||
const d = deps();
|
||||
showReservationOnMap(buildReservation({ type: 'hotel', accommodation_place_id: 55, place_id: 56, accommodation_start_day_id: 4, day_id: 5 }), d);
|
||||
expect(d.selectPlace).toHaveBeenCalledWith(55);
|
||||
expect(d.selectDay).toHaveBeenCalledWith(4);
|
||||
const e = deps();
|
||||
showReservationOnMap(buildReservation({ type: 'hotel', place_id: 56, day_id: 5 }), e);
|
||||
expect(e.selectPlace).toHaveBeenCalledWith(56);
|
||||
expect(e.selectDay).toHaveBeenCalledWith(5);
|
||||
const f = deps();
|
||||
showReservationOnMap(buildReservation({ type: 'hotel', place_id: 57 }), f);
|
||||
expect(f.selectDay).toHaveBeenCalledWith(null);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKONMAP-008: without a route or a place nothing happens', () => {
|
||||
const d = deps();
|
||||
showReservationOnMap(buildReservation({ type: 'event' }), d);
|
||||
expect(d.toggleConnection).not.toHaveBeenCalled();
|
||||
expect(d.selectDay).not.toHaveBeenCalled();
|
||||
expect(d.openPlan).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('canShowOnMap', () => {
|
||||
it('FE-PLANNER-BKONMAP-009: true for a route or a place, false otherwise', () => {
|
||||
expect(canShowOnMap(buildReservation({ endpoints: route }))).toBe(true);
|
||||
expect(canShowOnMap(buildReservation({ place_id: 1 }))).toBe(true);
|
||||
expect(canShowOnMap(buildReservation({ type: 'hotel', accommodation_place_id: 2 }))).toBe(true);
|
||||
expect(canShowOnMap(buildReservation({ type: 'hotel', place_id: 3 }))).toBe(true);
|
||||
expect(canShowOnMap(buildReservation({ type: 'hotel' }))).toBe(false);
|
||||
expect(canShowOnMap(buildReservation({}))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,192 @@
|
||||
// FE-PLANNER-BKTIMELINE-001 to FE-PLANNER-BKTIMELINE-026
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { buildDay, buildReservation } from '../../../../tests/helpers/factories';
|
||||
import type { Day, ReservationEndpoint } from '../../../types';
|
||||
import { absHour, buildAxis, dayWindow, packBars, placeReservation, type Moment } from './timelineModel';
|
||||
|
||||
function ep(over: Partial<ReservationEndpoint>): ReservationEndpoint {
|
||||
return { role: 'from', sequence: 0, name: 'Stop', code: null, lat: 1, lng: 1, timezone: null, local_time: null, local_date: null, ...over };
|
||||
}
|
||||
|
||||
const d1 = buildDay({ id: 601, day_number: 1, date: '2025-06-01', title: 'One' });
|
||||
const d2 = buildDay({ id: 602, day_number: 2, date: '2025-06-02', title: null });
|
||||
const d3 = buildDay({ id: 603, day_number: 3, date: '2025-06-03' });
|
||||
const days: Day[] = [d3, d1, d2];
|
||||
const axis = buildAxis(days);
|
||||
|
||||
describe('buildAxis', () => {
|
||||
it('FE-PLANNER-BKTIMELINE-001: dated days in calendar order', () => {
|
||||
expect(axis).toEqual([
|
||||
{ date: '2025-06-01', dayNumber: 1, dayId: 601, title: 'One' },
|
||||
{ date: '2025-06-02', dayNumber: 2, dayId: 602, title: null },
|
||||
{ date: '2025-06-03', dayNumber: 3, dayId: 603, title: null },
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-002: a trip with some dated days leaves the undated ones off the axis', () => {
|
||||
const loose = buildDay({ id: 604, day_number: 4, date: null });
|
||||
expect(buildAxis([loose, d2, d1]).map(a => a.dayId)).toEqual([601, 602]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-003: without any dates the axis is day 1..N', () => {
|
||||
const a = buildDay({ id: 611, day_number: 2, date: null, title: 'Second' });
|
||||
const b = buildDay({ id: 612, day_number: 1, date: null });
|
||||
expect(buildAxis([a, b])).toEqual([
|
||||
{ date: null, dayNumber: 1, dayId: 612, title: null },
|
||||
{ date: null, dayNumber: 2, dayId: 611, title: 'Second' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-004: two days on the same date keep their order', () => {
|
||||
const twin = buildDay({ id: 605, day_number: 5, date: '2025-06-01' });
|
||||
expect(buildAxis([d1, twin]).map(a => a.dayId)).toEqual([601, 605]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('placeReservation', () => {
|
||||
it('FE-PLANNER-BKTIMELINE-005: a booking with start and end sits between them', () => {
|
||||
const r = buildReservation({ type: 'train', reservation_time: '2025-06-02T10:30', reservation_end_time: '2025-06-02T12:00' });
|
||||
expect(placeReservation(r, axis, days)).toEqual({ kind: 'on', start: { day: 1, hour: 10.5 }, end: { day: 1, hour: 12 } });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-006: without an end it gets one hour', () => {
|
||||
const r = buildReservation({ type: 'restaurant', reservation_time: '2025-06-03T19:00' });
|
||||
expect(placeReservation(r, axis, days)).toEqual({ kind: 'on', start: { day: 2, hour: 19 }, end: { day: 2, hour: 20 } });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-007: a date without a time starts at nine', () => {
|
||||
const r = buildReservation({ type: 'tour', reservation_time: '2025-06-01' });
|
||||
expect(placeReservation(r, axis, days)).toEqual({ kind: 'on', start: { day: 0, hour: 9 }, end: { day: 0, hour: 10 } });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-008: a hotel runs from check-in to check-out across its stay', () => {
|
||||
const r = buildReservation({ type: 'hotel', accommodation_start_day_id: 601, accommodation_end_day_id: 603, metadata: JSON.stringify({ check_in_time: '14:00', check_out_time: '10:30' }) });
|
||||
expect(placeReservation(r, axis, days)).toEqual({ kind: 'on', start: { day: 0, hour: 14 }, end: { day: 2, hour: 10.5 } });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-009: a hotel without times takes 15:00 and 11:00, one night when the end is unknown', () => {
|
||||
const r = buildReservation({ type: 'hotel', day_id: 602 });
|
||||
expect(placeReservation(r, axis, days)).toEqual({ kind: 'on', start: { day: 1, hour: 15 }, end: { day: 2, hour: 11 } });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-010: a hotel checked into on the last day runs to the end of that day', () => {
|
||||
const r = buildReservation({ type: 'hotel', day_id: 603 });
|
||||
// Its night lies past the axis, so the bar fills the rest of the last day instead of pointing back before check-in.
|
||||
expect(placeReservation(r, axis, days)).toEqual({ kind: 'on', start: { day: 2, hour: 15 }, end: { day: 2, hour: 24 } });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-011: a transport reads its endpoints\' local dates and times', () => {
|
||||
const r = buildReservation({
|
||||
type: 'flight',
|
||||
endpoints: [
|
||||
ep({ role: 'to', sequence: 1, local_date: '2025-06-02', local_time: '09:15' }),
|
||||
ep({ role: 'from', sequence: 0, local_date: '2025-06-01', local_time: '07:00' }),
|
||||
],
|
||||
});
|
||||
expect(placeReservation(r, axis, days)).toEqual({ kind: 'on', start: { day: 0, hour: 7 }, end: { day: 1, hour: 9.25 } });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-012: a transport without dates falls back to its linked days', () => {
|
||||
const r = buildReservation({ type: 'car', day_id: 601, end_day_id: 603 });
|
||||
expect(placeReservation(r, axis, days)).toEqual({ kind: 'on', start: { day: 0, hour: 9 }, end: { day: 2, hour: 10 } });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-013: before and after the trip are said, not drawn', () => {
|
||||
expect(placeReservation(buildReservation({ reservation_time: '2025-05-20T10:00' }), axis, days)).toEqual({ kind: 'before' });
|
||||
expect(placeReservation(buildReservation({ reservation_time: '2025-06-20T10:00' }), axis, days)).toEqual({ kind: 'after' });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-014: no date, an empty axis or a date between the axis days is undated', () => {
|
||||
expect(placeReservation(buildReservation({}), axis, days)).toEqual({ kind: 'undated' });
|
||||
expect(placeReservation(buildReservation({ reservation_time: '2025-06-02T10:00' }), [], days)).toEqual({ kind: 'undated' });
|
||||
const gappy = buildAxis([d1, d3]);
|
||||
expect(placeReservation(buildReservation({ reservation_time: '2025-06-02T10:00' }), gappy, [d1, d3])).toEqual({ kind: 'undated' });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-015: an end past the trip runs to the end of the last day', () => {
|
||||
const r = buildReservation({ type: 'car', reservation_time: '2025-06-02T08:00', reservation_end_time: '2025-06-30T18:00' });
|
||||
expect(placeReservation(r, axis, days)).toEqual({ kind: 'on', start: { day: 1, hour: 8 }, end: { day: 2, hour: 24 } });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-016: an end before the trip keeps one hour', () => {
|
||||
const r = buildReservation({ type: 'car', reservation_time: '2025-06-02T08:00', reservation_end_time: '2025-05-01T18:00' });
|
||||
expect(placeReservation(r, axis, days)).toEqual({ kind: 'on', start: { day: 1, hour: 8 }, end: { day: 1, hour: 9 } });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-017: an arrival earlier than the departure keeps a small bar', () => {
|
||||
const r = buildReservation({ type: 'flight', reservation_time: '2025-06-02T22:00', reservation_end_time: '2025-06-01T06:00' });
|
||||
expect(placeReservation(r, axis, days)).toEqual({ kind: 'on', start: { day: 1, hour: 22 }, end: { day: 1, hour: 23 } });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-018: an end date missing from the axis stays on the start day', () => {
|
||||
const gappy = buildAxis([d1, d3]);
|
||||
const r = buildReservation({ type: 'train', reservation_time: '2025-06-01T10:00', reservation_end_time: '2025-06-02T12:00' });
|
||||
expect(placeReservation(r, gappy, [d1, d3])).toEqual({ kind: 'on', start: { day: 0, hour: 10 }, end: { day: 0, hour: 12 } });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-019: a garbled time falls back to the default hour', () => {
|
||||
const r = buildReservation({ type: 'hotel', day_id: 601, end_day_id: 602, metadata: JSON.stringify({ check_in_time: 'late', check_out_time: '10' }) });
|
||||
expect(placeReservation(r, axis, days)).toEqual({ kind: 'on', start: { day: 0, hour: 15 }, end: { day: 1, hour: 10 } });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-020: on a trip without dates the linked day places the booking', () => {
|
||||
const a = buildDay({ id: 621, day_number: 1, date: null });
|
||||
const b = buildDay({ id: 622, day_number: 2, date: null });
|
||||
const undatedAxis = buildAxis([a, b]);
|
||||
const r = buildReservation({ type: 'bus', reservation_time: '11:00', day_id: 622 });
|
||||
expect(placeReservation(r, undatedAxis, [a, b])).toEqual({ kind: 'on', start: { day: 1, hour: 11 }, end: { day: 1, hour: 12 } });
|
||||
expect(placeReservation(buildReservation({ type: 'bus' }), undatedAxis, [a, b])).toEqual({ kind: 'undated' });
|
||||
expect(placeReservation(buildReservation({ type: 'bus', day_id: 999 }), undatedAxis, [a, b])).toEqual({ kind: 'undated' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('absHour and dayWindow', () => {
|
||||
it('FE-PLANNER-BKTIMELINE-021: absHour counts hours from the first day', () => {
|
||||
expect(absHour({ day: 2, hour: 6.5 })).toBe(54.5);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-022: an empty day shows 06:00 to 22:00', () => {
|
||||
expect(dayWindow([], 0)).toEqual({ from: 6, to: 22 });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-023: widens to fit what starts or ends early or late, within 0..24', () => {
|
||||
const at = (day: number, hour: number): Moment => ({ day, hour });
|
||||
expect(dayWindow([{ start: at(0, 4.5), end: at(0, 5.5) }], 0)).toEqual({ from: 4, to: 22 });
|
||||
expect(dayWindow([{ start: at(0, 21), end: at(0, 23.5) }], 0)).toEqual({ from: 6, to: 24 });
|
||||
expect(dayWindow([{ start: at(0, 23.5), end: at(1, 0.5) }], 1)).toEqual({ from: 0, to: 22 });
|
||||
// An item on another day changes nothing.
|
||||
expect(dayWindow([{ start: at(3, 1), end: at(3, 23) }], 0)).toEqual({ from: 6, to: 22 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('packBars', () => {
|
||||
const r1 = buildReservation({ id: 8101 });
|
||||
const r2 = buildReservation({ id: 8102 });
|
||||
const r3 = buildReservation({ id: 8103 });
|
||||
const toX = (m: Moment) => absHour(m) * 10;
|
||||
const at = (hour: number): Moment => ({ day: 0, hour });
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-024: overlapping bars get their own lanes, a later one reuses a free lane', () => {
|
||||
const { bars, lanes } = packBars([
|
||||
{ r: r1, start: at(0), end: at(10) },
|
||||
{ r: r2, start: at(5), end: at(8) },
|
||||
{ r: r3, start: at(12), end: at(14) },
|
||||
], toX, 240);
|
||||
expect(lanes).toBe(2);
|
||||
const byId = Object.fromEntries(bars.map(b => [b.r.id, b]));
|
||||
expect(byId[8101]).toMatchObject({ lane: 0, x: 0, w: 100, cutStart: false, cutEnd: false });
|
||||
expect(byId[8102]).toMatchObject({ lane: 1, x: 50, w: 30 });
|
||||
expect(byId[8103]).toMatchObject({ lane: 0, x: 120, w: 26 });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-025: bars reaching past either edge are cut there and say so', () => {
|
||||
const { bars } = packBars([{ r: r1, start: { day: -1, hour: 20 }, end: at(30) }], toX, 240);
|
||||
expect(bars[0]).toMatchObject({ x: 0, w: 240, cutStart: true, cutEnd: true });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTIMELINE-026: nothing to pack is still one lane, and a short bar at the edge stays inside', () => {
|
||||
expect(packBars([], toX, 240)).toEqual({ bars: [], lanes: 1 });
|
||||
const { bars } = packBars([{ r: r2, start: at(23.9), end: at(24) }], toX, 240, 26, 4);
|
||||
expect(bars[0]).toMatchObject({ x: 214, w: 26 });
|
||||
});
|
||||
});
|
||||
@@ -65,9 +65,12 @@ export function placeReservation(r: Reservation, axis: AxisDay[], days: Day[]):
|
||||
const endDate = hotel ? span.end?.date ?? e.date : e.date ?? to?.local_date ?? span.end?.date ?? startDate
|
||||
const endDayId = hotel ? span.end?.id ?? r.end_day_id : r.end_day_id ?? span.end?.id ?? startDayId
|
||||
let ei = index(endDate, endDayId)
|
||||
const openEnded = ei === null
|
||||
if (ei === null) ei = hotel ? Math.min(si + 1, axis.length - 1) : si
|
||||
const endHourRaw = hotel ? toHour(meta.check_out_time, 11) : toHour(e.time || to?.local_time, startHour + 1)
|
||||
const end: Moment = ei === 'after' ? { day: axis.length - 1, hour: 24 } : ei === 'before' ? { day: si, hour: startHour + 1 } : { day: ei, hour: endHourRaw }
|
||||
let end: Moment = ei === 'after' ? { day: axis.length - 1, hour: 24 } : ei === 'before' ? { day: si, hour: startHour + 1 } : { day: ei, hour: endHourRaw }
|
||||
// A stay checked into on the last day with no end runs to the end of the axis, not back before its check-in.
|
||||
if (hotel && openEnded && end.day === si && end.hour <= startHour) end = { day: si, hour: 24 }
|
||||
// An arrival that reads earlier than the departure in local time (a date line, a typo) keeps a small bar.
|
||||
if (end.day < si || (end.day === si && end.hour <= startHour)) return { kind: 'on', start: { day: si, hour: startHour }, end: { day: si, hour: startHour + 1 } }
|
||||
return { kind: 'on', start: { day: si, hour: startHour }, end }
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
// FE-PLANNER-BKTRANSIT-001 to FE-PLANNER-BKTRANSIT-008
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '../../../../tests/helpers/render';
|
||||
import type { TransitLegDisplay } from '../transitDisplay';
|
||||
import { TransitLegs, transitSummary } from './transitParts';
|
||||
|
||||
const ride: TransitLegDisplay = {
|
||||
mode: 'SUBWAY',
|
||||
line: 'U2',
|
||||
line_color: '#dc2626',
|
||||
line_text_color: '#ffffff',
|
||||
duration: 600,
|
||||
headsign: 'Pankow',
|
||||
agency: 'BVG',
|
||||
stops: 5,
|
||||
from: { name: 'Alexanderplatz', time: '10:02', track: '1' },
|
||||
to: { name: 'Eberswalder Str.', time: '10:12' },
|
||||
};
|
||||
const walk: TransitLegDisplay = { mode: 'WALK', duration: 240, to: { name: 'Mauerpark' } };
|
||||
|
||||
describe('transitSummary', () => {
|
||||
it('FE-PLANNER-BKTRANSIT-001: anything that is not a transit journey has no summary', () => {
|
||||
expect(transitSummary({})).toBeNull();
|
||||
expect(transitSummary({ transit: { legs: 'none' } })).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTRANSIT-002: reads the stored totals', () => {
|
||||
const s = transitSummary({ transit: { legs: [ride, walk], duration: 1500, transfers: 2, walk_seconds: 300 } });
|
||||
expect(s).toEqual({ legs: [ride, walk], duration: 1500, transfers: 2, walk: 300 });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTRANSIT-003: an older entry counts transfers and walking from its legs', () => {
|
||||
const s = transitSummary({ transit: { legs: [walk, ride, { ...ride, line: 'U8' }, { mode: 'WALK' }] } });
|
||||
expect(s).toMatchObject({ duration: null, transfers: 1, walk: 240 });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTRANSIT-004: a zero duration or a walk-only journey', () => {
|
||||
expect(transitSummary({ transit: { legs: [walk], duration: 0 } })).toMatchObject({ duration: null, transfers: 0, walk: 240 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('TransitLegs', () => {
|
||||
it('FE-PLANNER-BKTRANSIT-005: a ride shows its line, stops and facts', () => {
|
||||
render(<TransitLegs legs={[ride]} />);
|
||||
const line = screen.getByText('U2');
|
||||
expect(line).toHaveStyle({ background: '#dc2626', color: '#ffffff' });
|
||||
expect(screen.getByText('Alexanderplatz')).toBeInTheDocument();
|
||||
expect(screen.getByText('Eberswalder Str.')).toBeInTheDocument();
|
||||
expect(screen.getByText('10:02 → 10:12')).toBeInTheDocument();
|
||||
expect(screen.getByText('10 min')).toBeInTheDocument();
|
||||
expect(screen.getByText('5 stops')).toBeInTheDocument();
|
||||
expect(screen.getByText('Platform 1')).toBeInTheDocument();
|
||||
expect(screen.getByText('Pankow')).toBeInTheDocument();
|
||||
expect(screen.getByText('BVG')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTRANSIT-006: a walk reads as one and leaves out the ride facts', () => {
|
||||
render(<TransitLegs legs={[walk]} compact />);
|
||||
expect(screen.getByText('Walk to Mauerpark')).toBeInTheDocument();
|
||||
expect(screen.getByText('4 min')).toBeInTheDocument();
|
||||
expect(screen.queryByText(/stops/)).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTRANSIT-007: a line without its own colour and a leg without times or name', () => {
|
||||
render(<TransitLegs legs={[{ mode: 'BUS', from: { name: 'A' }, to: { name: 'B' } }, { mode: 'WALK' }]} compact />);
|
||||
expect(screen.getByText('BUS')).toHaveStyle({ background: 'var(--bg-tertiary)' });
|
||||
expect(screen.getByText('Walk to')).toBeInTheDocument();
|
||||
expect(screen.queryByText(/min$/)).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTRANSIT-008: a coloured line without a text colour is written in white', () => {
|
||||
render(<TransitLegs legs={[{ mode: 'TRAM', line: 'M10', line_color: '#16a34a', from: { name: 'A', time: '09:00' }, to: { name: 'B' } }]} />);
|
||||
expect(screen.getByText('M10')).toHaveStyle({ color: '#fff' });
|
||||
expect(screen.getByText('09:00')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,199 @@
|
||||
// FE-PLANNER-BKVIEW-001 to FE-PLANNER-BKVIEW-016
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { useBookingsView } from './useBookingsView';
|
||||
|
||||
const stored = (store: Storage, key: string) => JSON.parse(store.getItem(key) ?? 'null');
|
||||
|
||||
afterEach(() => { vi.restoreAllMocks(); });
|
||||
|
||||
describe('useBookingsView', () => {
|
||||
it('FE-PLANNER-BKVIEW-001: starts on cards grouped by status, sorted by date, nothing filtered', () => {
|
||||
const { result } = renderHook(() => useBookingsView('transports', 1));
|
||||
expect(result.current.view).toBe('cards');
|
||||
expect(result.current.group).toBe('status');
|
||||
expect(result.current.sort).toEqual({ by: 'date', dir: 'asc' });
|
||||
expect(result.current.timeline).toEqual({ zoom: 'trip', byType: true, context: true });
|
||||
expect(result.current.transitApart).toBe(false);
|
||||
expect(result.current.status).toBe('all');
|
||||
expect(result.current.types.size).toBe(0);
|
||||
expect(result.current.travelers.size).toBe(0);
|
||||
expect(result.current.filtering).toBe(false);
|
||||
expect(result.current.viewIsDefault).toBe(true);
|
||||
expect(result.current.selectedId).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKVIEW-002: the view is remembered per tab', () => {
|
||||
const { result, unmount } = renderHook(() => useBookingsView('transports', 1));
|
||||
act(() => result.current.setView('list'));
|
||||
expect(result.current.view).toBe('list');
|
||||
expect(stored(localStorage, 'trek:bookings-transports-view')).toBe('list');
|
||||
unmount();
|
||||
expect(renderHook(() => useBookingsView('transports', 1)).result.current.view).toBe('list');
|
||||
expect(renderHook(() => useBookingsView('bookings', 1)).result.current.view).toBe('cards');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKVIEW-003: the list groups by day, and each view keeps its own grouping', () => {
|
||||
const { result } = renderHook(() => useBookingsView('bookings', 1));
|
||||
act(() => result.current.setGroup('type'));
|
||||
expect(result.current.group).toBe('type');
|
||||
act(() => result.current.setView('list'));
|
||||
expect(result.current.group).toBe('day');
|
||||
act(() => result.current.setGroup('none'));
|
||||
expect(stored(localStorage, 'trek:bookings-bookings-group')).toEqual({ cards: 'type', list: 'none' });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKVIEW-004: the timeline is never grouped, and grouping there changes nothing', () => {
|
||||
const { result } = renderHook(() => useBookingsView('bookings', 1));
|
||||
act(() => result.current.setView('timeline'));
|
||||
expect(result.current.group).toBe('none');
|
||||
act(() => result.current.setGroup('type'));
|
||||
expect(result.current.group).toBe('none');
|
||||
expect(localStorage.getItem('trek:bookings-bookings-group')).toBeNull();
|
||||
expect(result.current.transitApart).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKVIEW-005: a new sort key starts ascending, the same key keeps its direction, flip turns it', () => {
|
||||
const { result } = renderHook(() => useBookingsView('bookings', 1));
|
||||
act(() => result.current.flipSort());
|
||||
expect(result.current.sort).toEqual({ by: 'date', dir: 'desc' });
|
||||
act(() => result.current.setSort('date'));
|
||||
expect(result.current.sort).toEqual({ by: 'date', dir: 'desc' });
|
||||
act(() => result.current.setSort('title'));
|
||||
expect(result.current.sort).toEqual({ by: 'title', dir: 'asc' });
|
||||
act(() => result.current.flipSort());
|
||||
act(() => result.current.flipSort());
|
||||
expect(result.current.sort).toEqual({ by: 'title', dir: 'asc' });
|
||||
expect(stored(localStorage, 'trek:bookings-bookings-sort')).toEqual({ by: 'title', dir: 'asc' });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKVIEW-006: the timeline zoom, type rows and context are remembered', () => {
|
||||
const { result } = renderHook(() => useBookingsView('transports', 1));
|
||||
act(() => result.current.setZoom('day'));
|
||||
act(() => result.current.toggleByType());
|
||||
act(() => result.current.toggleContext());
|
||||
expect(result.current.timeline).toEqual({ zoom: 'day', byType: false, context: false });
|
||||
expect(stored(localStorage, 'trek:bookings-transports-timeline')).toEqual({ zoom: 'day', byType: false, context: false });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKVIEW-007: a zoom stored by an older build opens on the whole trip', () => {
|
||||
localStorage.setItem('trek:bookings-transports-timeline', JSON.stringify({ zoom: 'week', byType: false, context: true }));
|
||||
const { result } = renderHook(() => useBookingsView('transports', 1));
|
||||
expect(result.current.timeline).toEqual({ zoom: 'trip', byType: false, context: true });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKVIEW-008: cards can put transit in its own section', () => {
|
||||
const { result } = renderHook(() => useBookingsView('transports', 1));
|
||||
act(() => result.current.toggleTransitApart());
|
||||
expect(result.current.transitApart).toBe(true);
|
||||
expect(result.current.viewIsDefault).toBe(false);
|
||||
expect(stored(localStorage, 'trek:bookings-transports-transitApart')).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKVIEW-009: status, types and travelers filter, per trip in the session', () => {
|
||||
const { result } = renderHook(() => useBookingsView('bookings', 9));
|
||||
act(() => result.current.setStatus('pending'));
|
||||
act(() => result.current.toggleType('hotel'));
|
||||
act(() => result.current.toggleType('tour'));
|
||||
act(() => result.current.toggleTraveler(3));
|
||||
expect(result.current.status).toBe('pending');
|
||||
expect([...result.current.types]).toEqual(['hotel', 'tour']);
|
||||
expect([...result.current.travelers]).toEqual([3]);
|
||||
expect(result.current.filtering).toBe(true);
|
||||
expect(stored(sessionStorage, 'trek-bookings-filters-bookings-9')).toEqual({ types: ['hotel', 'tour'], status: 'pending', travelers: [3] });
|
||||
|
||||
act(() => result.current.toggleType('hotel'));
|
||||
act(() => result.current.toggleTraveler(3));
|
||||
expect([...result.current.types]).toEqual(['tour']);
|
||||
expect(result.current.travelers.size).toBe(0);
|
||||
|
||||
// Another trip starts unfiltered.
|
||||
expect(renderHook(() => useBookingsView('bookings', 10)).result.current.status).toBe('all');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKVIEW-010: clearing types and travelers leaves the status alone', () => {
|
||||
const { result } = renderHook(() => useBookingsView('bookings', 1));
|
||||
act(() => result.current.setStatus('confirmed'));
|
||||
act(() => result.current.toggleType('hotel'));
|
||||
act(() => result.current.toggleTraveler(4));
|
||||
act(() => result.current.clearTypes());
|
||||
act(() => result.current.clearTravelers());
|
||||
expect(result.current.types.size).toBe(0);
|
||||
expect(result.current.travelers.size).toBe(0);
|
||||
expect(result.current.status).toBe('confirmed');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKVIEW-011: a search counts as filtering, and reset clears it along with the filters', () => {
|
||||
const { result } = renderHook(() => useBookingsView('bookings', 1));
|
||||
act(() => result.current.setQuery(' '));
|
||||
expect(result.current.filtering).toBe(false);
|
||||
act(() => result.current.setQuery('kyoto'));
|
||||
act(() => result.current.toggleType('hotel'));
|
||||
expect(result.current.filtering).toBe(true);
|
||||
act(() => result.current.resetFilters());
|
||||
expect(result.current.query).toBe('');
|
||||
expect(result.current.types.size).toBe(0);
|
||||
expect(result.current.filtering).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKVIEW-012: reset view on cards restores grouping, sort and the transit section', () => {
|
||||
const { result } = renderHook(() => useBookingsView('transports', 1));
|
||||
act(() => result.current.setGroup('type'));
|
||||
act(() => result.current.setSort('title'));
|
||||
act(() => result.current.toggleTransitApart());
|
||||
expect(result.current.viewIsDefault).toBe(false);
|
||||
act(() => result.current.resetView());
|
||||
expect(result.current.group).toBe('status');
|
||||
expect(result.current.sort).toEqual({ by: 'date', dir: 'asc' });
|
||||
expect(result.current.transitApart).toBe(false);
|
||||
expect(result.current.viewIsDefault).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKVIEW-013: reset view on the list and on the timeline', () => {
|
||||
const { result } = renderHook(() => useBookingsView('transports', 1));
|
||||
act(() => result.current.setView('list'));
|
||||
act(() => result.current.flipSort());
|
||||
expect(result.current.viewIsDefault).toBe(false);
|
||||
act(() => result.current.resetView());
|
||||
expect(result.current.viewIsDefault).toBe(true);
|
||||
expect(result.current.group).toBe('day');
|
||||
|
||||
act(() => result.current.setView('timeline'));
|
||||
act(() => result.current.toggleContext());
|
||||
expect(result.current.viewIsDefault).toBe(false);
|
||||
act(() => result.current.resetView());
|
||||
expect(result.current.timeline).toMatchObject({ byType: true, context: true });
|
||||
expect(result.current.viewIsDefault).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKVIEW-014: collapsed groups are remembered per trip and per grouping', () => {
|
||||
const { result } = renderHook(() => useBookingsView('bookings', 5));
|
||||
expect(result.current.collapsed('pending')).toBe(false);
|
||||
act(() => result.current.toggleGroup('pending'));
|
||||
expect(result.current.collapsed('pending')).toBe(true);
|
||||
expect(stored(localStorage, 'trek:bookings-bookings-collapsed:5')).toEqual({ 'status:pending': true });
|
||||
act(() => result.current.setGroup('type'));
|
||||
expect(result.current.collapsed('pending')).toBe(false);
|
||||
act(() => result.current.setGroup('status'));
|
||||
act(() => result.current.toggleGroup('pending'));
|
||||
expect(result.current.collapsed('pending')).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKVIEW-015: blocked or garbled storage starts fresh and choices still apply', () => {
|
||||
localStorage.setItem('trek:bookings-bookings-sort', '{not json');
|
||||
expect(renderHook(() => useBookingsView('bookings', 1)).result.current.sort).toEqual({ by: 'date', dir: 'asc' });
|
||||
|
||||
vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new Error('blocked'); });
|
||||
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('blocked'); });
|
||||
const { result } = renderHook(() => useBookingsView('bookings', 1));
|
||||
expect(result.current.view).toBe('cards');
|
||||
act(() => result.current.setView('timeline'));
|
||||
expect(result.current.view).toBe('timeline');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKVIEW-016: remembers the selected booking while mounted', () => {
|
||||
const { result } = renderHook(() => useBookingsView('bookings', 1));
|
||||
act(() => result.current.setSelectedId(12));
|
||||
expect(result.current.selectedId).toBe(12);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
// FE-PLANNER-PLACEDLGPARTS-001 to FE-PLANNER-PLACEDLGPARTS-004
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '../../../tests/helpers/render';
|
||||
import { COLUMN_CARD, ColumnHead, HintCard, SIDE_COLUMN, WHITE_BUTTON } from './placeDialogParts';
|
||||
|
||||
describe('placeDialogParts', () => {
|
||||
it('FE-PLANNER-PLACEDLGPARTS-001: ColumnHead names its column as a heading, with its icon beside it', () => {
|
||||
render(<ColumnHead icon={<span data-testid="col-icon" />}>Place details</ColumnHead>);
|
||||
expect(screen.getByRole('heading', { level: 3, name: 'Place details' })).toBeInTheDocument();
|
||||
expect(screen.getByTestId('col-icon')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLACEDLGPARTS-002: HintCard says its line next to its icon', () => {
|
||||
render(<HintCard icon={<span data-testid="hint-icon" />}>Pick a place to see its details</HintCard>);
|
||||
expect(screen.getByText('Pick a place to see its details')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('hint-icon')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLACEDLGPARTS-003: the column frame stretches with the dialog and clips its cards', () => {
|
||||
expect(SIDE_COLUMN).toContain('self-stretch');
|
||||
expect(SIDE_COLUMN).toContain('overflow-hidden');
|
||||
expect(COLUMN_CARD).toContain('bg-surface-card');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLACEDLGPARTS-004: the white button dims when disabled', () => {
|
||||
expect(WHITE_BUTTON).toContain('disabled:opacity-50');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
// FE-PLANNER-PLANPARTS-001 to FE-PLANNER-PLANPARTS-012
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { Pencil, Trash2 } from 'lucide-react';
|
||||
import { BarButton, MoreButton, PANEL_BAR, SoftPill, TimePill, WhiteBadge, tintOf } from './planParts';
|
||||
|
||||
describe('BarButton', () => {
|
||||
it('FE-PLANNER-PLANPARTS-001: is a button named by its label that runs its action', async () => {
|
||||
const onClick = vi.fn();
|
||||
render(<BarButton label="Undo" onClick={onClick}><span>icon</span></BarButton>);
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Undo' }));
|
||||
expect(onClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLANPARTS-002: carries its pressed, expanded and popup states', () => {
|
||||
render(
|
||||
<BarButton label="Filter" onClick={vi.fn()} active ariaPressed ariaExpanded={false} ariaHaspopup="menu" className="extra">
|
||||
<span>icon</span>
|
||||
</BarButton>,
|
||||
);
|
||||
const button = screen.getByRole('button', { name: 'Filter' });
|
||||
expect(button).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(button).toHaveAttribute('aria-expanded', 'false');
|
||||
expect(button).toHaveAttribute('aria-haspopup', 'menu');
|
||||
expect(button.className).toContain('extra');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLANPARTS-003: a disabled one does nothing', async () => {
|
||||
const onClick = vi.fn();
|
||||
render(<BarButton label="Optimize" onClick={onClick} disabled placement="top"><span>icon</span></BarButton>);
|
||||
const button = screen.getByRole('button', { name: 'Optimize' });
|
||||
expect(button).toBeDisabled();
|
||||
await userEvent.click(button);
|
||||
expect(onClick).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLANPARTS-004: shows its label as a tooltip on hover', async () => {
|
||||
render(<BarButton label="Export" onClick={vi.fn()}><span>icon</span></BarButton>);
|
||||
await userEvent.hover(screen.getByRole('button', { name: 'Export' }));
|
||||
expect(await screen.findByRole('tooltip')).toHaveTextContent('Export');
|
||||
});
|
||||
});
|
||||
|
||||
describe('MoreButton', () => {
|
||||
it('FE-PLANNER-PLANPARTS-005: opens the row\'s actions as a menu and runs the picked one', async () => {
|
||||
const onEdit = vi.fn();
|
||||
const onDelete = vi.fn();
|
||||
render(
|
||||
<MoreButton label="More actions" items={[
|
||||
{ label: 'Edit', icon: Pencil, onClick: onEdit },
|
||||
false,
|
||||
null,
|
||||
{ divider: true },
|
||||
{ label: 'Delete', icon: Trash2, onClick: onDelete, danger: true },
|
||||
]} />,
|
||||
);
|
||||
const trigger = screen.getByRole('button', { name: 'More actions' });
|
||||
expect(trigger).toHaveAttribute('aria-haspopup', 'menu');
|
||||
fireEvent.click(trigger);
|
||||
expect(screen.getByRole('button', { name: 'Edit' })).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
expect(onDelete).toHaveBeenCalledTimes(1);
|
||||
expect(onEdit).not.toHaveBeenCalled();
|
||||
expect(screen.queryByRole('button', { name: 'Edit' })).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLANPARTS-006: nothing but dividers or hidden entries renders nothing', () => {
|
||||
const { container } = render(<MoreButton label="More" items={[{ divider: true }, false, undefined]} />);
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
expect(screen.queryByRole('button', { name: 'More' })).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLANPARTS-007: stays visible when asked to, and takes a custom size', () => {
|
||||
render(<MoreButton label="More" alwaysVisible size={32} className="own" items={[{ label: 'Rename', onClick: vi.fn() }]} />);
|
||||
const trigger = screen.getByRole('button', { name: 'More' });
|
||||
expect(trigger.className).toContain('opacity-100');
|
||||
expect(trigger.className).toContain('own');
|
||||
expect(trigger.style.width).toBe('32px');
|
||||
expect(trigger.style.height).toBe('32px');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLANPARTS-008: stays quiet at rest until its row is hovered', () => {
|
||||
render(<MoreButton label="More" items={[{ label: 'Rename', onClick: vi.fn() }]} />);
|
||||
expect(screen.getByRole('button', { name: 'More' }).className).toContain('opacity-0');
|
||||
});
|
||||
});
|
||||
|
||||
describe('badges and pills', () => {
|
||||
it('FE-PLANNER-PLANPARTS-009: WhiteBadge and TimePill show their content with an optional icon', () => {
|
||||
render(
|
||||
<>
|
||||
<WhiteBadge icon={<span data-testid="badge-icon" />} className="mine">Check-in</WhiteBadge>
|
||||
<TimePill className="time">10:00</TimePill>
|
||||
</>,
|
||||
);
|
||||
expect(screen.getByText('Check-in').className).toContain('mine');
|
||||
expect(screen.getByTestId('badge-icon')).toBeInTheDocument();
|
||||
const time = screen.getByText('10:00');
|
||||
expect(time.className).toContain('time');
|
||||
expect(time.querySelector('svg')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLANPARTS-010: SoftPill colours its words by tone and can set them in capitals', () => {
|
||||
render(
|
||||
<>
|
||||
<SoftPill>Plain</SoftPill>
|
||||
<SoftPill tone="success">Confirmed</SoftPill>
|
||||
<SoftPill tone="warning">Pending</SoftPill>
|
||||
<SoftPill tone="danger">Cancelled</SoftPill>
|
||||
<SoftPill tone="info">Info</SoftPill>
|
||||
<SoftPill tone="accent" caps icon={<span data-testid="pill-icon" />} className="x">Start</SoftPill>
|
||||
</>,
|
||||
);
|
||||
expect(screen.getByText('Plain').className).toContain('text-content-secondary');
|
||||
expect(screen.getByText('Confirmed').className).toContain('text-success');
|
||||
expect(screen.getByText('Pending').className).toContain('text-warning');
|
||||
expect(screen.getByText('Cancelled').className).toContain('text-danger');
|
||||
expect(screen.getByText('Info').className).toContain('text-info');
|
||||
const start = screen.getByText('Start');
|
||||
expect(start.className).toContain('bg-accent');
|
||||
expect(start.className).toContain('uppercase');
|
||||
expect(start.className).toContain('x');
|
||||
expect(screen.getByTestId('pill-icon')).toBeInTheDocument();
|
||||
expect(screen.getByText('Plain').className).not.toContain('uppercase');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLANPARTS-011: tintOf mixes a colour into transparency', () => {
|
||||
expect(tintOf('#ff0000')).toBe('color-mix(in srgb, #ff0000 11%, transparent)');
|
||||
expect(tintOf('var(--accent)', 20)).toBe('color-mix(in srgb, var(--accent) 20%, transparent)');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLANPARTS-012: the panel bar is a band with a hairline under it', () => {
|
||||
expect(PANEL_BAR).toContain('border-b');
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render'
|
||||
import { render, screen, waitFor, fireEvent } from '../../../tests/helpers/render'
|
||||
import { resetAllStores } from '../../../tests/helpers/store'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import WeatherWidget from './WeatherWidget'
|
||||
@@ -249,4 +249,29 @@ describe('WeatherWidget', () => {
|
||||
})
|
||||
expect(weatherApi.get).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-WEATHERWIDGET-018: the stacked badge shows the icon over the temperature, without a tooltip when it has no place', async () => {
|
||||
vi.mocked(weatherApi.get).mockResolvedValue(buildWeather({ temp: 21 }))
|
||||
useSettingsStore.setState({ settings: { ...useSettingsStore.getState().settings, temperature_unit: 'celsius' } })
|
||||
const { container } = render(<WeatherWidget lat={48.86} lng={2.35} date="2025-06-01" stacked />)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('21°')).toBeInTheDocument()
|
||||
})
|
||||
expect(container.querySelector('svg')).not.toBeNull()
|
||||
fireEvent.mouseEnter(screen.getByText('21°').parentElement!)
|
||||
await new Promise(r => setTimeout(r, 300))
|
||||
expect(screen.queryByRole('tooltip')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-COMP-WEATHERWIDGET-019: without its icon the stacked badge names the sky and the place in its tooltip', async () => {
|
||||
vi.mocked(weatherApi.get).mockResolvedValue(buildWeather({ temp: 18, type: 'climate' }))
|
||||
useSettingsStore.setState({ settings: { ...useSettingsStore.getState().settings, temperature_unit: 'celsius' } })
|
||||
const { container } = render(<WeatherWidget lat={48.86} lng={2.35} date="2025-06-01" stacked hideIcon locationName="Rome" />)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Ø18°')).toBeInTheDocument()
|
||||
})
|
||||
expect(container.querySelector('svg')).toBeNull()
|
||||
fireEvent.mouseEnter(screen.getByText('Ø18°').parentElement!)
|
||||
expect(await screen.findByRole('tooltip')).toHaveTextContent('clear sky, Rome')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -154,4 +154,31 @@ describe('ConfirmDialog', () => {
|
||||
fireEvent.click(backdrop);
|
||||
expect(onClose).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
describe('on a phone', () => {
|
||||
const desktopWidth = window.innerWidth;
|
||||
beforeEach(() => { Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 390 }); });
|
||||
afterEach(() => { Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: desktopWidth }); });
|
||||
|
||||
it('FE-COMP-CONFIRM-014: the phone card answers like the desktop one, and a tap on it does not close it', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<ConfirmDialog isOpen onClose={onClose} onConfirm={onConfirm} title="Delete note?" message="It is gone for good." confirmLabel="Remove" />);
|
||||
await user.click(screen.getByText('It is gone for good.'));
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
await user.click(screen.getByRole('button', { name: 'Remove' }));
|
||||
expect(onConfirm).toHaveBeenCalledOnce();
|
||||
expect(onClose).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('FE-COMP-CONFIRM-015: the phone card without danger uses the accent and the default labels', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<ConfirmDialog isOpen onClose={onClose} onConfirm={onConfirm} message="Leave?" danger={false}><p>More</p></ConfirmDialog>);
|
||||
expect(screen.getByText('Confirm')).toBeInTheDocument();
|
||||
expect(screen.getByText('More')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Delete' })).toHaveClass('bg-accent');
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
expect(onClose).toHaveBeenCalledOnce();
|
||||
expect(onConfirm).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
// FE-COMP-DIALOGSHELL-001 to FE-COMP-DIALOGSHELL-013
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { resetBodyScrollLock } from '../../utils/bodyScrollLock';
|
||||
import {
|
||||
DeleteButton,
|
||||
DialogButton,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogSection,
|
||||
DialogShell,
|
||||
DialogTile,
|
||||
FooterSpacer,
|
||||
NEUTRAL_TINT,
|
||||
fs,
|
||||
} from './DialogShell';
|
||||
|
||||
const onClose = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
onClose.mockClear();
|
||||
resetBodyScrollLock();
|
||||
document.body.style.overflow = '';
|
||||
});
|
||||
|
||||
describe('fs', () => {
|
||||
it('FE-COMP-DIALOGSHELL-001: scales a size by the user\'s text size for its tier', () => {
|
||||
expect(fs(12)).toEqual({ fontSize: 'calc(12px * var(--fs-scale-caption, 1))' });
|
||||
expect(fs(20, 'subtitle')).toEqual({ fontSize: 'calc(20px * var(--fs-scale-subtitle, 1))' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('DialogShell', () => {
|
||||
it('FE-COMP-DIALOGSHELL-002: a dialog that is all head and foot has no body, and takes its width and alignment', () => {
|
||||
render(
|
||||
<DialogShell onClose={onClose} labelledBy="q-title" width="narrow" align="top"
|
||||
header={<DialogHeader tile={<DialogTile><span>i</span></DialogTile>} tint={NEUTRAL_TINT} labelId="q-title" onClose={onClose} title="Leave?" />}
|
||||
footer={<DialogFooter><DialogButton>Stay</DialogButton><FooterSpacer /><DialogButton variant="primary">Leave</DialogButton></DialogFooter>} />,
|
||||
);
|
||||
const dialog = screen.getByRole('dialog', { name: 'Leave?' });
|
||||
expect(dialog.className).toContain('max-w-[520px]');
|
||||
expect(document.querySelector('.trek-modal-backdrop')?.className).toContain('items-start');
|
||||
expect(dialog.querySelector('form')).toBeNull();
|
||||
expect(dialog.children).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-COMP-DIALOGSHELL-003: a body class replaces the padded column, and a paste anywhere reaches the dialog', () => {
|
||||
const onPaste = vi.fn();
|
||||
render(
|
||||
<DialogShell onClose={onClose} labelledBy="p-title" width="xwide" bodyClassName="preview-body" onPaste={onPaste}
|
||||
header={<DialogHeader tile={null} tint={NEUTRAL_TINT} labelId="p-title" onClose={onClose} title="Preview" />}>
|
||||
<p>Document</p>
|
||||
</DialogShell>,
|
||||
);
|
||||
expect(screen.getByText('Document').parentElement?.className).toBe('preview-body');
|
||||
fireEvent.paste(screen.getByRole('dialog', { name: 'Preview' }));
|
||||
expect(onPaste).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DialogHeader', () => {
|
||||
it('FE-COMP-DIALOGSHELL-004: a plain title is the heading the dialog is named by', () => {
|
||||
render(<DialogHeader tile={<DialogTile><span data-testid="tile-icon" /></DialogTile>} tint={NEUTRAL_TINT} labelId="t1" onClose={onClose} title="Export" />);
|
||||
expect(screen.getByRole('heading', { level: 2, name: 'Export' })).toHaveAttribute('id', 't1');
|
||||
expect(screen.getByTestId('tile-icon')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-DIALOGSHELL-005: a title with a click is a rename button, the eyebrow then names the dialog', async () => {
|
||||
const onTitleClick = vi.fn();
|
||||
render(<DialogHeader tile={null} tint={NEUTRAL_TINT} labelId="t2" onClose={onClose} eyebrow="Booking" title="Hotel Sakura" onTitleClick={onTitleClick} titleTooltip="Rename" />);
|
||||
expect(screen.getByRole('heading', { name: 'Booking' })).toHaveAttribute('id', 't2');
|
||||
const rename = screen.getByRole('button', { name: 'Hotel Sakura' });
|
||||
expect(rename).not.toHaveAttribute('id');
|
||||
await userEvent.click(rename);
|
||||
expect(onTitleClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-DIALOGSHELL-006: a rename button without a tooltip still works', async () => {
|
||||
const onTitleClick = vi.fn();
|
||||
render(<DialogHeader tile={null} tint={NEUTRAL_TINT} labelId="t3" onClose={onClose} title="Dinner" onTitleClick={onTitleClick} />);
|
||||
const rename = screen.getByRole('button', { name: 'Dinner' });
|
||||
expect(rename).toHaveAttribute('id', 't3');
|
||||
await userEvent.click(rename);
|
||||
expect(onTitleClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-DIALOGSHELL-007: Enter in the title field is spent there, other keys and the blur reach the caller', () => {
|
||||
const onKeyDown = vi.fn();
|
||||
const onBlur = vi.fn();
|
||||
const onChange = vi.fn();
|
||||
render(
|
||||
<DialogHeader tile={null} tint={NEUTRAL_TINT} labelId="t4" onClose={onClose}
|
||||
titleInput={{ value: 'Old', onChange, label: 'Title', required: true, maxLength: 40, onKeyDown, onBlur }} />,
|
||||
);
|
||||
const input = screen.getByRole('textbox', { name: 'Title' });
|
||||
expect(input).toHaveAttribute('id', 't4');
|
||||
expect(input).toBeRequired();
|
||||
expect(input).toHaveAttribute('maxLength', '40');
|
||||
const enter = fireEvent.keyDown(input, { key: 'Enter' });
|
||||
expect(enter).toBe(false);
|
||||
const other = fireEvent.keyDown(input, { key: 'a' });
|
||||
expect(other).toBe(true);
|
||||
expect(onKeyDown).toHaveBeenCalledTimes(2);
|
||||
fireEvent.blur(input);
|
||||
expect(onBlur).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-DIALOGSHELL-008: the title field works without a key handler', () => {
|
||||
render(<DialogHeader tile={null} tint={NEUTRAL_TINT} labelId="t5" onClose={onClose} titleInput={{ value: '', onChange: vi.fn(), label: 'Name' }} />);
|
||||
expect(fireEvent.keyDown(screen.getByRole('textbox', { name: 'Name' }), { key: 'Enter' })).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-COMP-DIALOGSHELL-009: Close calls onClose, and the pills sit under the title', async () => {
|
||||
render(<DialogHeader tile={null} tint={NEUTRAL_TINT} labelId="t6" onClose={onClose} title="Stay" sub="Kyoto" pills={<span>3 nights</span>} />);
|
||||
expect(screen.getByText('Kyoto')).toBeInTheDocument();
|
||||
expect(screen.getByText('3 nights')).toBeInTheDocument();
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Close' }));
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('body and footer parts', () => {
|
||||
it('FE-COMP-DIALOGSHELL-010: a section is labelled and can carry an action', async () => {
|
||||
const onAdd = vi.fn();
|
||||
render(
|
||||
<>
|
||||
<DialogSection label="Travelers" action={<button type="button" onClick={onAdd}>Add</button>} className="own"><p>Maria</p></DialogSection>
|
||||
<DialogSection label="Notes"><p>None</p></DialogSection>
|
||||
</>,
|
||||
);
|
||||
expect(screen.getByText('Travelers')).toBeInTheDocument();
|
||||
expect(screen.getByText('Maria').closest('section')?.className).toBe('own');
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Add' }));
|
||||
expect(onAdd).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getAllByRole('button')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-DIALOGSHELL-011: footer buttons are plain buttons by default, the primary one can submit', async () => {
|
||||
const onSave = vi.fn();
|
||||
render(
|
||||
<DialogFooter>
|
||||
<DialogButton icon={<span data-testid="btn-icon" />}>Cancel</DialogButton>
|
||||
<DialogButton active>On map</DialogButton>
|
||||
<DialogButton variant="primary" type="submit" onClick={onSave} disabled={false}>Save</DialogButton>
|
||||
<DialogButton disabled>Later</DialogButton>
|
||||
</DialogFooter>,
|
||||
);
|
||||
expect(screen.getByRole('button', { name: 'Cancel' })).toHaveAttribute('type', 'button');
|
||||
expect(screen.getByTestId('btn-icon')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'On map' }).className).toContain('bg-accent');
|
||||
expect(screen.getByRole('button', { name: 'Cancel' }).className).not.toContain('bg-accent');
|
||||
const save = screen.getByRole('button', { name: 'Save' });
|
||||
expect(save).toHaveAttribute('type', 'submit');
|
||||
await userEvent.click(save);
|
||||
expect(onSave).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByRole('button', { name: 'Later' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-DIALOGSHELL-012: the delete button is named "Delete" unless told otherwise', async () => {
|
||||
const onDelete = vi.fn();
|
||||
const { rerender } = render(<DeleteButton onClick={onDelete} />);
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
expect(onDelete).toHaveBeenCalledTimes(1);
|
||||
rerender(<DeleteButton onClick={onDelete} label="Delete note" disabled />);
|
||||
expect(screen.getByRole('button', { name: 'Delete note' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-DIALOGSHELL-013: the neutral tint is a faint wash of the accent', () => {
|
||||
expect(NEUTRAL_TINT).toContain('var(--accent)');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user