fix(journey): mark only the days a run reaches as prepared, name trips out of reach, show editors their own status in the day review and say when a fetch is already running

This commit is contained in:
Maurice
2026-10-21 17:53:39 +02:00
parent 94c369b913
commit bb10b94046
48 changed files with 544 additions and 62 deletions
@@ -1,4 +1,4 @@
// FE-JRN-DAYIMPORT-DIALOG-001 to FE-JRN-DAYIMPORT-DIALOG-006
// FE-JRN-DAYIMPORT-DIALOG-001 to FE-JRN-DAYIMPORT-DIALOG-008
//
// JRN-02: the desktop dialog that takes a recorded day over with its stays. It
// names the journey and the day, shows the stays on the map and in a list to
@@ -9,6 +9,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildDayStay, buildDayStays, buildRecordingPreview } from '../../../tests/helpers/journeyRecording';
import { render, screen, waitFor, within } from '../../../tests/helpers/render';
import JourneyDayImportDialog from './JourneyDayImportDialog';
import type { JourneyRecordingPrepState } from './useJourneyRecordingPrep';
const repo = vi.hoisted(() => ({
reviewDay: vi.fn(),
@@ -30,7 +31,7 @@ vi.mock('./JourneyMapAuto', () => ({
},
}));
function renderDialog() {
function renderDialog(prep?: JourneyRecordingPrepState) {
const props = { onTakenOver: vi.fn(), onKept: vi.fn(), onClose: vi.fn() };
render(
<JourneyDayImportDialog
@@ -39,12 +40,33 @@ function renderDialog() {
date="2026-05-14"
dayColor="#ff0055"
storedRoute={undefined}
prep={prep}
{...props}
/>
);
return props;
}
function prepState(over: Partial<JourneyRecordingPrepState> = {}): JourneyRecordingPrepState {
return {
prep: {
enabled: true,
connection: 'ready',
lastAttemptAt: '2026-05-16T08:00:00.000Z',
lastSuccessAt: '2026-05-14T18:00:00.000Z',
lastError: 'unreachable',
},
saving: false,
fetching: false,
statusLine: { text: 'The last refresh failed: Dawarich did not answer.', tone: 'warning' },
canFetch: true,
setEnabled: vi.fn(),
fetchNow: vi.fn(async () => {}),
dayPrep: () => ({ state: 'provisional', failed: true, lastSuccessAt: '2026-05-14T18:00:00.000Z' }),
...over,
};
}
const rowOf = (name: string) =>
screen.getByRole('checkbox', { name: `Take over ${name}` }).closest('[data-stay-id]') as HTMLElement;
@@ -153,4 +175,26 @@ describe('JourneyDayImportDialog', () => {
expect(screen.getByText(/Some stays may be missing/)).toBeInTheDocument();
expect(screen.getByRole('checkbox', { name: 'Take over Rialto' })).toBeChecked();
});
it('FE-JRN-DAYIMPORT-DIALOG-007: an unsettled prepared day says why, with the caller status and a fetch by hand', async () => {
const user = userEvent.setup();
const prep = prepState();
renderDialog(prep);
expect(await screen.findByText(/before the day ended, so stays may be missing/)).toBeInTheDocument();
expect(screen.getByText(/this is the older state/)).toBeInTheDocument();
expect(screen.getByTestId('journey-prep-status')).toHaveTextContent(
'The last refresh failed: Dawarich did not answer.'
);
await user.click(screen.getByRole('button', { name: 'Fetch now' }));
expect(prep.fetchNow).toHaveBeenCalledTimes(1);
});
it('FE-JRN-DAYIMPORT-DIALOG-008: without the journey preparing its days, no status and no day notice', async () => {
renderDialog(prepState({ statusLine: null, canFetch: false, dayPrep: () => null }));
expect(await screen.findByRole('checkbox', { name: 'Take over Parcheggio' })).toBeChecked();
expect(screen.queryByTestId('journey-prep-status')).not.toBeInTheDocument();
expect(screen.queryByText(/this is the older state/)).not.toBeInTheDocument();
});
});
@@ -13,6 +13,7 @@ export default function JourneyDayImportDialog({
date,
dayColor,
onClose,
prep,
...rest
}: JourneyDayImportViewProps) {
const { t } = useTranslation();
@@ -26,7 +27,7 @@ export default function JourneyDayImportDialog({
onClose={onClose}
footer={<JourneyDayImportActions state={state} onCancel={onClose} />}
>
<JourneyDayImportReview state={state} dayColor={dayColor} />
<JourneyDayImportReview state={state} dayColor={dayColor} prep={prep} />
</DawarichDayDialog>
);
}
@@ -11,16 +11,25 @@ import { Tooltip } from '../shared/Tooltip';
import { JourneyDayImportStays } from './JourneyDayImportStays';
import JourneyMap from './JourneyMapAuto';
import { reasonText } from './journeyRecordingModel';
import { dayPrepNotice } from './journeyRecordingPrepModel';
import { JourneyRecordingPrepStatus } from './JourneyRecordingPrepSetting';
import { Notice } from './JourneyRecordingReview';
import { stayMarkerId, type JourneyDayImportState } from './useJourneyDayImport';
import type { JourneyRecordingPrepState } from './useJourneyRecordingPrep';
type Props = { state: JourneyDayImportState; dayColor: string };
type Props = { state: JourneyDayImportState; dayColor: string; prep?: JourneyRecordingPrepState };
/** Why the list may not be the whole day, and what went wrong on the way. */
function DayNotices({ state }: { state: JourneyDayImportState }) {
/**
* Why the list may not be the whole day, and what went wrong on the way. With
* the journey preparing its days, why this day is not final yet and how the
* caller's own preparation stands, so an editor sees it without the settings.
*/
function DayNotices({ state, prep }: { state: JourneyDayImportState; prep?: JourneyRecordingPrepState }) {
const { t, locale } = useTranslation();
const { review, outcome } = state;
const reason = review ? reasonText(review.error, t) : '';
const day = prep?.dayPrep(state.date);
const dayNotice = day ? dayPrepNotice(day, t, locale) : '';
return (
<>
{outcome?.kind === 'failed' && (
@@ -41,6 +50,8 @@ function DayNotices({ state }: { state: JourneyDayImportState }) {
)}
{review?.truncated && <Notice tone="warning">{t('journey.dayImport.truncated')}</Notice>}
{state.running && <Notice tone="info">{t('journey.dayImport.running')}</Notice>}
{dayNotice && <Notice tone="warning">{dayNotice}</Notice>}
{prep && <JourneyRecordingPrepStatus prep={prep} />}
</>
);
}
@@ -137,7 +148,7 @@ function scrollToStay(id: string): void {
* holds on the day already, and who will see the drafts. The body of the
* desktop dialog and of the phone sheet alike.
*/
export function JourneyDayImportReview({ state, dayColor }: Props) {
export function JourneyDayImportReview({ state, dayColor, prep }: Props) {
const { t } = useTranslation();
const { review, choice } = state;
if (!review) {
@@ -162,7 +173,7 @@ export function JourneyDayImportReview({ state, dayColor }: Props) {
}
return (
<>
<DayNotices state={state} />
<DayNotices state={state} prep={prep} />
<DialogSection label={t('journey.dayImport.map')}>
<div className="flex flex-col gap-2.5">
<div className="overflow-hidden rounded-[12px] border border-edge-faint">
@@ -1,9 +1,16 @@
// FE-JRN-PREP-MODEL-001 to FE-JRN-PREP-MODEL-006
// FE-JRN-PREP-MODEL-001 to FE-JRN-PREP-MODEL-009
//
// JRN-03: where preparing a journey day stands, and the line under the switch.
import type { JourneyRecordingPrep } from '@trek/shared';
import { describe, expect, it } from 'vitest';
import { dayPrepOf, dayPrepText, dayPrepUnsettled, prepStatusLine } from './journeyRecordingPrepModel';
import {
dayPrepNotice,
dayPrepOf,
dayPrepText,
dayPrepUnsettled,
prepReachOf,
prepStatusLine,
} from './journeyRecordingPrepModel';
/** Keys come back as they are, with their params; a Dawarich reason reads as its code, as reasonText needs a hit. */
const t = (key: string, params?: Record<string, string | number>) => {
@@ -13,6 +20,7 @@ const t = (key: string, params?: Record<string, string | number>) => {
const NOW = new Date(2026, 4, 16, 12, 0);
const PERIOD = new Set(['2026-05-14', '2026-05-15', '2026-05-16', '2026-05-17']);
const REACHED = { prepared: true, outOfReach: false };
function prep(over: Partial<JourneyRecordingPrep> = {}): JourneyRecordingPrep {
return {
@@ -81,30 +89,71 @@ describe('prepStatusLine', () => {
const now = NOW.getTime();
it('FE-JRN-PREP-MODEL-005: says when the last fetch came through, or that none did yet', () => {
expect(prepStatusLine(prep(), true, t, 'en', now)).toEqual({
expect(prepStatusLine(prep(), REACHED, t, 'en', now)).toEqual({
text: 'journey.prep.lastSuccess {"time":"2 hours ago"}',
tone: 'muted',
});
expect(prepStatusLine(prep({ lastSuccessAt: null, lastAttemptAt: null }), true, t, 'en', now)).toEqual({
expect(prepStatusLine(prep({ lastSuccessAt: null, lastAttemptAt: null }), REACHED, t, 'en', now)).toEqual({
text: 'journey.prep.never',
tone: 'muted',
});
expect(prepStatusLine(prep({ enabled: false }), true, t, 'en', now)).toBeNull();
expect(prepStatusLine(prep({ enabled: false }), REACHED, t, 'en', now)).toBeNull();
});
it('FE-JRN-PREP-MODEL-006: warns about what keeps it from working, a failure first and beside the state still shown', () => {
expect(prepStatusLine(prep({ connection: 'not_connected' }), true, t, 'en', now)?.text).toBe(
expect(prepStatusLine(prep({ connection: 'not_connected' }), REACHED, t, 'en', now)?.text).toBe(
'journey.prep.notConnected'
);
expect(prepStatusLine(prep(), false, t, 'en', now)?.text).toBe('journey.prep.noPeriods');
expect(prepStatusLine(prep({ connection: 'sync_off' }), true, t, 'en', now)?.text).toBe('journey.prep.syncOff');
expect(prepStatusLine(prep({ lastError: 'unreachable' }), true, t, 'en', now)).toEqual({
expect(prepStatusLine(prep(), { prepared: false, outOfReach: false }, t, 'en', now)?.text).toBe(
'journey.prep.noPeriods'
);
expect(prepStatusLine(prep({ connection: 'sync_off' }), REACHED, t, 'en', now)?.text).toBe('journey.prep.syncOff');
expect(prepStatusLine(prep({ lastError: 'unreachable' }), REACHED, t, 'en', now)).toEqual({
text: 'journey.prep.failed {"reason":"UNREACHABLE","time":"2 hours ago"}',
tone: 'warning',
});
expect(prepStatusLine(prep({ lastError: 'unauthorized', lastSuccessAt: null }), true, t, 'en', now)).toEqual({
expect(prepStatusLine(prep({ lastError: 'unauthorized', lastSuccessAt: null }), REACHED, t, 'en', now)).toEqual({
text: 'journey.prep.failedNever {"reason":"UNAUTHORIZED"}',
tone: 'warning',
});
});
});
describe('prepReachOf', () => {
it('FE-JRN-PREP-MODEL-007: only the periods the server reaches are prepared, an open trip up to today', () => {
const linked = new Set(['2024-01-10', '2024-01-11', ...PERIOD]);
const reach = prepReachOf(prep({ periods: [{ start: '2026-05-14', end: null }] }), linked, NOW);
expect([...reach.dates]).toEqual(['2026-05-14', '2026-05-15', '2026-05-16']);
expect(reach.outOfReach).toBe(true);
expect(dayPrepOf('2024-01-10', prep(), reach.dates, NOW)).toBeNull();
expect(prepReachOf(prep({ periods: [{ start: '2026-05-14', end: '2026-05-17' }] }), PERIOD, NOW)).toEqual({
dates: PERIOD,
outOfReach: false,
});
});
it('FE-JRN-PREP-MODEL-008: without periods in the answer the linked dates stand in, nothing out of reach', () => {
expect(prepReachOf(prep(), PERIOD, NOW)).toEqual({ dates: PERIOD, outOfReach: false });
expect(prepReachOf(null, PERIOD, NOW)).toEqual({ dates: PERIOD, outOfReach: false });
});
it('FE-JRN-PREP-MODEL-009: trips out of reach are named, alone when none is reached and after the state otherwise', () => {
const now = NOW.getTime();
expect(prepStatusLine(prep(), { prepared: false, outOfReach: true }, t, 'en', now)).toEqual({
text: 'journey.prep.outOfReach {"count":400}',
tone: 'warning',
});
expect(prepStatusLine(prep(), { prepared: true, outOfReach: true }, t, 'en', now)).toEqual({
text: 'journey.prep.lastSuccess {"time":"2 hours ago"} journey.prep.outOfReach {"count":400}',
tone: 'muted',
});
expect(dayPrepNotice({ state: 'running', failed: false, lastSuccessAt: null }, t, 'en', now)).toBe('');
expect(dayPrepNotice({ state: 'running', failed: true, lastSuccessAt: null }, t, 'en', now)).toBe(
'journey.prep.dayFailed'
);
expect(dayPrepNotice({ state: 'pending', failed: false, lastSuccessAt: null }, t, 'en', now)).toBe(
'journey.prep.dayPending'
);
});
});
@@ -1,4 +1,4 @@
import type { JourneyRecordingPrep } from '@trek/shared';
import { JOURNEY_RECORDING_PREP_REACH_DAYS, type JourneyRecordingPrep } from '@trek/shared';
import { localIsoDate } from '../../utils/localDate';
import { relativeTime } from '../../utils/relativeTime';
import { reasonText } from './journeyRecordingModel';
@@ -19,7 +19,36 @@ export interface JourneyDayPrep {
}
/**
* A day of a linked trip period while the journey prepares its days for a
* Which days the caller's runs reach and whether some linked day is left out.
* The server names the trips its runs read; a trip still open runs up to
* today. Without that answer the linked dates stand in for them.
*/
export interface PrepReach {
dates: ReadonlySet<string>;
/** A linked day that is over is read by no run, its trip ended too long ago. */
outOfReach: boolean;
}
export function prepReachOf(
prep: JourneyRecordingPrep | null,
linkedDates: ReadonlySet<string>,
now: Date = new Date()
): PrepReach {
if (!prep?.periods) return { dates: linkedDates, outOfReach: false };
const today = localIsoDate(now);
const dates = new Set<string>();
for (const period of prep.periods) {
const end = new Date(`${period.end ?? today}T00:00:00`);
for (let d = new Date(`${period.start}T00:00:00`); d <= end; d.setDate(d.getDate() + 1)) {
dates.add(localIsoDate(d));
}
}
const outOfReach = [...linkedDates].some((date) => date < today && !dates.has(date));
return { dates, outOfReach };
}
/**
* A day the caller's runs reach while the journey prepares its days for a
* connected caller; null for every other day, including those still ahead.
*/
export function dayPrepOf(
@@ -56,6 +85,11 @@ export function dayPrepText(day: JourneyDayPrep, t: Translate, locale: string, n
return parts.join(' ');
}
/** The same for the day review, which says on its own that the day is still running. */
export function dayPrepNotice(day: JourneyDayPrep, t: Translate, locale: string, now: number = Date.now()): string {
return day.state === 'running' ? (day.failed ? t('journey.prep.dayFailed') : '') : dayPrepText(day, t, locale, now);
}
/** The line under the switch in the journey settings, and whether it asks for attention. */
export interface PrepStatusLine {
text: string;
@@ -64,20 +98,29 @@ export interface PrepStatusLine {
/**
* What the caller's own preparation of a journey looks like right now, for
* the settings: why nothing happens (no connection, no dated trip, background
* sync off), the last failure next to the state still shown, or when it last
* came through. Null while the switch is off.
* the settings and the day review: why nothing happens (no connection, no
* dated trip, every trip out of reach, background sync off), the last failure
* next to the state still shown, or when it last came through, followed by a
* word on trips left out. Null while the switch is off.
*/
export function prepStatusLine(
prep: JourneyRecordingPrep,
hasPeriods: boolean,
reach: { prepared: boolean; outOfReach: boolean },
t: Translate,
locale: string,
now: number = Date.now()
): PrepStatusLine | null {
if (!prep.enabled) return null;
if (prep.connection === 'not_connected') return { text: t('journey.prep.notConnected'), tone: 'warning' };
if (!hasPeriods) return { text: t('journey.prep.noPeriods'), tone: 'warning' };
const outOfReachText = t('journey.prep.outOfReach', { count: JOURNEY_RECORDING_PREP_REACH_DAYS });
if (!reach.prepared) {
return { text: reach.outOfReach ? outOfReachText : t('journey.prep.noPeriods'), tone: 'warning' };
}
const line = baseStatusLine(prep, t, locale, now);
return reach.outOfReach ? { ...line, text: `${line.text} ${outOfReachText}` } : line;
}
function baseStatusLine(prep: JourneyRecordingPrep, t: Translate, locale: string, now: number): PrepStatusLine {
const success = prep.lastSuccessAt ? relativeTime(Date.parse(prep.lastSuccessAt), locale, now) : null;
if (prep.lastError) {
const reason = reasonText(prep.lastError, t);
@@ -26,6 +26,7 @@ import {
} from './journeyDayImportModel';
import { recordingErrorText } from './journeyRecordingModel';
import { useJourneyRecordingDay } from './useJourneyRecordingDay';
import type { JourneyRecordingPrepState } from './useJourneyRecordingPrep';
/** What the desktop dialog and the phone sheet are opened with. */
export interface JourneyDayImportViewProps {
@@ -40,6 +41,8 @@ export interface JourneyDayImportViewProps {
onTakenOver: () => void;
onKept: (day: JourneyRecordedDay) => void;
onClose: () => void;
/** The caller's own preparation of the journey's days (JRN-03), for editors too; absent while it is off or unread. */
prep?: JourneyRecordingPrepState;
}
/**
@@ -259,7 +262,7 @@ export function useJourneyDayImport({
onTakenOver,
onKept,
onClose,
}: Omit<JourneyDayImportViewProps, 'journeyTitle'>) {
}: Omit<JourneyDayImportViewProps, 'journeyTitle' | 'prep'>) {
const { t, locale } = useTranslation();
const day = useDayReview(journeyId, date);
const route = useJourneyRecordingDay({ journeyId, date, onKept, onRemoved: noop, onClose: noop });
@@ -291,6 +294,7 @@ export function useJourneyDayImport({
const problem = choice ? problemOf(choice, stays, reportDefault) : 'nothing';
return {
date,
review: day.review,
loading: day.loading,
/** The day is today: stays recorded later still arrive. */
@@ -1,4 +1,4 @@
// FE-JRN-PREP-HOOK-001 to FE-JRN-PREP-HOOK-005
// FE-JRN-PREP-HOOK-001 to FE-JRN-PREP-HOOK-007
//
// JRN-03: a journey preparing its recorded days, as the journey page, the
// phone screen and both settings shells read it: the caller's status, the
@@ -48,6 +48,7 @@ beforeEach(() => {
dawarich.syncNow.mockReset().mockResolvedValue({ state: 'ok', created: 0, updated: 0, missing: 0 });
updateJourney.mockClear();
toast.error.mockClear();
toast.info.mockClear();
useJourneyStore.setState({ updateJourney });
});
@@ -126,4 +127,30 @@ describe('useJourneyRecordingPrep', () => {
expect(toast.error).toHaveBeenCalledWith('Dawarich could not be asked right now.');
await waitFor(() => expect(repo.prep).toHaveBeenCalledTimes(3));
});
it('FE-JRN-PREP-HOOK-006: a fetch while the background run is busy says so instead of looking like nothing happened', async () => {
dawarich.syncNow.mockResolvedValue({ state: 'ok', created: 0, updated: 0, missing: 0, alreadyRunning: true });
const { result } = renderHook(() => useJourneyRecordingPrep(options()));
await waitFor(() => expect(result.current.prep).not.toBeNull());
await act(async () => {
await result.current.fetchNow();
});
expect(toast.info).toHaveBeenCalledWith(
'A fetch is already running in the background. Its stays show up once it is through.'
);
});
it('FE-JRN-PREP-HOOK-007: a journey whose trips all ended out of reach marks no day and offers no fetch', async () => {
repo.prep.mockResolvedValue(status({ periods: [] }));
const { result } = renderHook(() => useJourneyRecordingPrep(options()));
await waitFor(() => expect(result.current.prep).not.toBeNull());
expect(result.current.dayPrep('2026-05-14')).toBeNull();
expect(result.current.canFetch).toBe(false);
expect(result.current.statusLine).toEqual({
text: 'Trips that ended more than 400 days ago are not prepared in the background. Open one of their days to fetch it by hand.',
tone: 'warning',
});
});
});
@@ -5,7 +5,13 @@ import { dawarichRepo } from '../../repo/dawarichRepo';
import { journeyRecordingsRepo } from '../../repo/journeyRecordingsRepo';
import { useJourneyStore } from '../../store/journeyStore';
import { useToast } from '../shared/Toast';
import { dayPrepOf, prepStatusLine, type JourneyDayPrep, type PrepStatusLine } from './journeyRecordingPrepModel';
import {
dayPrepOf,
prepReachOf,
prepStatusLine,
type JourneyDayPrep,
type PrepStatusLine,
} from './journeyRecordingPrepModel';
export interface JourneyRecordingPrepOptions {
/** The journey the route names, or null while it loads. */
@@ -14,7 +20,7 @@ export interface JourneyRecordingPrepOptions {
enabled: boolean;
/** An editor with the Dawarich addon on: nobody else has anything of their own prepared. */
active: boolean;
/** The dates of the linked trips, the only days that are prepared. */
/** The dates of the linked trips; only those the server says its runs reach are prepared. */
periodDates: ReadonlySet<string>;
/** The switch was saved: the journey is read again. */
onSwitched: () => void;
@@ -28,7 +34,7 @@ export interface JourneyRecordingPrepState {
saving: boolean;
/** A fetch asked for by hand is running. */
fetching: boolean;
/** The line under the switch in the settings; null while it is off or not read yet. */
/** The line under the switch in the settings and in the day review; null while it is off or not read yet. */
statusLine: PrepStatusLine | null;
/** Whether a fetch by hand would reach anything. */
canFetch: boolean;
@@ -39,9 +45,10 @@ export interface JourneyRecordingPrepState {
/**
* A journey preparing its recorded days (JRN-03), for the journey page, the
* phone screen and both settings shells: the caller's own status, the owner's
* switch, a fetch by hand and where each day stands. Switching it on fetches
* at once, so the days fill without waiting for the next background run.
* phone screen, both settings shells and the day review: the caller's own
* status, the owner's switch, a fetch by hand and where each day stands.
* Switching it on fetches at once, so the days fill without waiting for the
* next background run.
*/
export function useJourneyRecordingPrep({
journeyId,
@@ -73,7 +80,8 @@ export function useJourneyRecordingPrep({
const fetchNow = useCallback(async () => {
setFetching(true);
try {
await dawarichRepo.syncNow();
const result = await dawarichRepo.syncNow();
if (result.alreadyRunning) toast.info(t('journey.prep.alreadyRunning'));
onFetched();
} catch {
toast.error(t('journey.prep.fetchFailed'));
@@ -101,18 +109,20 @@ export function useJourneyRecordingPrep({
[journeyId, updateJourney, onSwitched, toast, t, prep?.connection, fetchNow]
);
const reach = useMemo(() => prepReachOf(prep, periodDates), [prep, periodDates]);
const prepared = reach.dates.size > 0;
const statusLine = useMemo(
() => (prep ? prepStatusLine(prep, periodDates.size > 0, t, locale) : null),
[prep, periodDates, t, locale]
() => (prep ? prepStatusLine(prep, { prepared, outOfReach: reach.outOfReach }, t, locale) : null),
[prep, prepared, reach.outOfReach, t, locale]
);
const dayPrep = useCallback((date: string) => dayPrepOf(date, prep, periodDates), [prep, periodDates]);
const dayPrep = useCallback((date: string) => dayPrepOf(date, prep, reach.dates), [prep, reach.dates]);
return {
prep,
saving,
fetching,
statusLine,
canFetch: !!prep?.enabled && prep.connection !== 'not_connected' && periodDates.size > 0,
canFetch: !!prep?.enabled && prep.connection !== 'not_connected' && prepared,
setEnabled,
fetchNow,
dayPrep,