Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

feat(tours): tour revisions, conflicts and a live editor (P2C-03)

Mauriced72352911e1a
diff --git a/client/src/components/Tours/conversion/useGpxConversion.ts b/client/src/components/Tours/conversion/useGpxConversion.ts
index c6662ce1a..f2807d855 100644
--- a/client/src/components/Tours/conversion/useGpxConversion.ts
+++ b/client/src/components/Tours/conversion/useGpxConversion.ts
@@ -99,6 +99,7 @@ export function useGpxConversion(planner: TourPlannerController) {
points: current.points,
sourcePlaceId: tour.place_id,
inPlace: how === 'replace',
+ revision: tour.revision,
...(paddle ? { tourType: 'kayak' as const, paddle: paddleFieldsOf(tour) } : {}),
});
if (started) setState(IDLE);
diff --git a/client/src/components/Tours/planner/TourPlannerPanels.tsx b/client/src/components/Tours/planner/TourPlannerPanels.tsx
index 79e8ace22..e87e635ca 100644
--- a/client/src/components/Tours/planner/TourPlannerPanels.tsx
+++ b/client/src/components/Tours/planner/TourPlannerPanels.tsx
@@ -39,6 +39,7 @@ import type { TourGpxImport } from '../useTourGpxImport'
import { type AssignTourToDay, useTourDayAssignment } from '../useTourDayAssignment'
import WandererMark from '../wanderer/WandererMark'
import { TourGpxExportBarButton } from '../TourGpxExportButton'
+import { TourRemoteChangeNotice, TourRevisionConflictDialog } from './TourRevisionNotice'
const STATUS_KEY: Partial<Record<TourPlannerStatus, string>> = {
dirty: 'tours.planner.status.dirty',
@@ -145,11 +146,13 @@ function RailStatusBadges({ planner }: { planner: TourPlannerController }) {
const statusKey = planner.isSaving ? STATUS_KEY.saving : STATUS_KEY[planner.status]
const restored = planner.draftRestored && planner.hasUnsavedChanges
const onFerrata = useTourFerrataCrossingStore(state => state.crossings.length > 0)
- const failed = planner.error === 'save'
+ const failed = planner.error === 'save' || planner.error === 'conflict'
const canRetry = retryable(planner)
if (!restored && !statusKey && !failed && !onFerrata) return null
const warning = planner.error != null || canRetry
- const statusLabel = failed ? t('tours.planner.status.saveFailed') : statusKey ? statusText(planner, statusKey, t) : null
+ const statusLabel = failed
+ ? t(planner.error === 'conflict' ? 'tours.revision.conflictTitle' : 'tours.planner.status.saveFailed')
+ : statusKey ? statusText(planner, statusKey, t) : null
const busy = planner.isSaving || planner.status === 'routing' || planner.status === 'enriching-elevation'
return (
<span role="status" data-testid="tour-planner-status" className="ms-1.5 flex flex-none items-center gap-1">
@@ -418,6 +421,7 @@ export function TourPlannerRail({ planner,
</div>
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-3 py-3.5">
+ <TourRemoteChangeNotice planner={planner} />
<TourNameField planner={planner} locked={locked} />
<TourTypeFields planner={planner} locked={locked} />
@@ -452,6 +456,7 @@ export function TourPlannerRail({ planner,
confirmLabel={t('tours.planner.discardChanges')}
/>
<NewTourConfirmDialog planner={planner} canEdit={canEdit} />
+ <TourRevisionConflictDialog planner={planner} />
<ConfirmDialog
isOpen={pendingDifficulty !== null && !isSaving}
onClose={() => setPendingDifficulty(null)}
diff --git a/client/src/components/Tours/planner/TourRevisionNotice.tsx b/client/src/components/Tours/planner/TourRevisionNotice.tsx
new file mode 100644
index 000000000..35865e687
--- /dev/null
+++ b/client/src/components/Tours/planner/TourRevisionNotice.tsx
@@ -0,0 +1,150 @@
+import { CopyPlus, History, RefreshCw, Save, X } from 'lucide-react';
+import { useId, useState } from 'react';
+import { useTranslation } from '../../../i18n';
+import ConfirmDialog from '../../shared/ConfirmDialog';
+import {
+ DialogButton,
+ DialogFooter,
+ DialogHeader,
+ DialogShell,
+ DialogTile,
+ FooterSpacer,
+ NEUTRAL_TINT,
+ fs,
+} from '../../shared/DialogShell';
+import type { TourPlannerController } from './useTourPlanner';
+
+/** The tour open in the editor again as it is saved now: the draft here is thrown away. */
+function reloadSaved(planner: TourPlannerController) {
+ if (planner.mode.type !== 'edit-saved') return;
+ void planner.openTour({ place_id: planner.mode.placeId });
+}
+
+/**
+ * P2C-03, said while editing: someone else saved this tour since it was
+ * opened here, and this draft has changes of its own. Nothing is lost yet;
+ * the newer tour can be loaded (after a confirm, since the draft goes), or the
+ * draft kept, and its save then asks what to do.
+ */
+export function TourRemoteChangeNotice({ planner }: { planner: TourPlannerController }) {
+ const { t } = useTranslation();
+ const [confirming, setConfirming] = useState(false);
+ if (planner.revision.remote === null || !planner.hasUnsavedChanges || planner.revision.conflict) return null;
+ return (
+ <section
+ role="status"
+ data-testid="tour-remote-change"
+ className="ring-warning/25 flex items-start gap-2.5 rounded-[12px] bg-warning-soft px-3 py-2.5 ring-1 ring-inset"
+ >
+ <History size={15} strokeWidth={2} className="mt-0.5 flex-none text-warning" />
+ <div className="min-w-0 flex-1">
+ <p className="m-0 font-semibold text-content" style={fs(12.5, 'body')}>
+ {t('tours.revision.remoteTitle')}
+ </p>
+ <p className="m-0 mt-0.5 leading-snug text-content-secondary" style={fs(12, 'body')}>
+ {t('tours.revision.remoteBody')}
+ </p>
+ <button
+ type="button"
+ onClick={() => setConfirming(true)}
+ className="mt-2 inline-flex h-7 items-center gap-1.5 rounded-full bg-surface-card px-2.5 font-semibold text-content shadow-sm ring-1 ring-inset ring-edge-faint transition-colors hover:bg-surface-hover focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"
+ style={fs(11.5, 'body')}
+ >
+ <RefreshCw size={12} strokeWidth={2.2} />
+ {t('tours.revision.loadNewer')}
+ </button>
+ </div>
+ <button
+ type="button"
+ onClick={planner.revision.dismissRemote}
+ aria-label={t('common.close')}
+ className="grid h-6 w-6 flex-none place-items-center rounded-full text-content-faint transition-colors hover:bg-surface-card hover:text-content"
+ >
+ <X size={13} strokeWidth={2.2} />
+ </button>
+ <ConfirmDialog
+ isOpen={confirming}
+ onClose={() => setConfirming(false)}
+ onConfirm={() => reloadSaved(planner)}
+ title={t('tours.revision.loadNewerTitle')}
+ message={t('tours.revision.loadNewerBody')}
+ confirmLabel={t('tours.revision.loadNewer')}
+ />
+ </section>
+ );
+}
+
+/**
+ * P2C-03 when a save was refused because the tour moved on meanwhile. Three
+ * ways on, none of them silent: keep both by saving this draft as a tour of
+ * its own (the one that loses nothing, so it leads), load the newer tour and
+ * drop the draft, or save the draft over the newer tour on purpose. Closing
+ * keeps editing; the next save asks again.
+ */
+export function TourRevisionConflictDialog({ planner }: { planner: TourPlannerController }) {
+ const { t } = useTranslation();
+ const labelId = useId();
+ const { conflict } = planner.revision;
+ if (!conflict || planner.mode.type !== 'edit-saved') return null;
+ const busy = planner.isSaving;
+ const close = planner.revision.dismissConflict;
+ return (
+ <DialogShell
+ onClose={close}
+ labelledBy={labelId}
+ width="detail"
+ blocked={busy}
+ header={
+ <DialogHeader
+ tile={
+ <DialogTile>
+ <History size={20} strokeWidth={2} className="text-content" />
+ </DialogTile>
+ }
+ tint={NEUTRAL_TINT}
+ labelId={labelId}
+ onClose={close}
+ eyebrow={t('tours.revision.conflictEyebrow')}
+ title={t('tours.revision.conflictTitle')}
+ sub={t('tours.revision.conflictBody')}
+ subWraps
+ />
+ }
+ footer={
+ <DialogFooter>
+ <DialogButton
+ data-testid="tour-conflict-overwrite"
+ disabled={busy}
+ icon={<Save size={14} strokeWidth={2} />}
+ onClick={() => {
+ planner.revision.takeOver();
+ void planner.save();
+ }}
+ >
+ {t('tours.revision.overwrite')}
+ </DialogButton>
+ <FooterSpacer />
+ <DialogButton
+ data-testid="tour-conflict-reload"
+ disabled={busy}
+ icon={<RefreshCw size={14} strokeWidth={2} />}
+ onClick={() => reloadSaved(planner)}
+ >
+ {t('tours.revision.loadNewer')}
+ </DialogButton>
+ <DialogButton
+ variant="primary"
+ data-testid="tour-conflict-save-new"
+ disabled={busy}
+ icon={<CopyPlus size={14} strokeWidth={2} />}
+ onClick={() =>
+ void planner.save({ asNew: true, name: t('tours.revision.mineName', { name: planner.name.trim() }) })
+ }
+ >
+ {t('tours.revision.saveAsNew')}
+ </DialogButton>
+ </DialogFooter>
+ }
+ />
+ );
+}
diff --git a/client/src/components/Tours/planner/tourPlannerDraft.ts b/client/src/components/Tours/planner/tourPlannerDraft.ts
index 62ee66114..cc2871b35 100644
--- a/client/src/components/Tours/planner/tourPlannerDraft.ts
+++ b/client/src/components/Tours/planner/tourPlannerDraft.ts
@@ -28,6 +28,8 @@ export interface DraftPayload {
derivedFromPlaceId?: number | null;
tourType?: PlannableTourType;
paddle?: PaddleFieldValues;
+ /** P2C-03: the revision of the tour the draft edits, as it was loaded. */
+ baseRevision?: number | null;
}
const DRAFT_VERSIONS: ReadonlyArray<DraftPayload['version']> = [1, 2, 3, 4, 5, 6, 7, 8, 9];
@@ -77,6 +79,7 @@ export function validDraft(value: unknown): value is DraftPayload {
optionalMinutes(draft.breakAdditionalMinutes) &&
optionalPlaceId(draft.editingPlaceId) &&
optionalPlaceId(draft.derivedFromPlaceId) &&
+ optionalPlaceId(draft.baseRevision) &&
optionalDifficulty(draft.maxHikingDifficulty) &&
(draft.tourType === undefined || plannableTourTypeSchema.safeParse(draft.tourType).success) &&
Array.isArray(draft.waypoints) &&
diff --git a/client/src/components/Tours/planner/tourPlannerFacts.ts b/client/src/components/Tours/planner/tourPlannerFacts.ts
new file mode 100644
index 000000000..3e9effde3
--- /dev/null
+++ b/client/src/components/Tours/planner/tourPlannerFacts.ts
@@ -0,0 +1,100 @@
+import {
+ MAX_PLANNED_TOUR_DURATION_MINUTES,
+ tourWebsiteSchema,
+ type PaddleBoatType,
+ type PaddleLakeStyle,
+ type PaddleWaterContext,
+ type PlannableTourType,
+ type TourMaxHikingDifficulty,
+} from '@trek/shared';
+import type { RouteGeometryAnalysis } from '../../../utils/routeGeometry';
+import { hikingTimeMinutes } from '../hikingTime';
+
+/** What the planner's facts are read from: the draft's fields and the route as last computed. */
+export interface TourPlannerFactsInput {
+ tourType: PlannableTourType;
+ maxHikingDifficulty: TourMaxHikingDifficulty;
+ website: string;
+ plannedDurationMinutes: number | null;
+ breakAdditionalMinutes: number | null;
+ paddle: {
+ boatType: PaddleBoatType | null;
+ waterContext: PaddleWaterContext | null;
+ speedKmh: number | null;
+ portageSpeedKmh: number | null;
+ lakeStyle: PaddleLakeStyle | null;
+ };
+ paddleSpeedInvalid: boolean;
+ /** A paddle tour's estimate on the water; null for a hike. */
+ paddleEstimate: { waterMinutes: number | null; estimateMinutes: number | null } | null;
+ routeAnalysis: RouteGeometryAnalysis | null;
+ /** The router's own time, seconds; stands in for a hike until the heights are in. */
+ durationSeconds: number | null;
+}
+
+function invalidMinutes(value: number | null): boolean {
+ return value !== null && (!Number.isInteger(value) || value < 0 || value > MAX_PLANNED_TOUR_DURATION_MINUTES);
+}
+
+/**
+ * What the planner derives from its draft, worked out in one place: whether
+ * the fields hold, the times, and the fields the tour type adds to a save.
+ * A paddle tour is timed on the water at its speed; a hike by the signposts'
+ * rule over distance, climb and descent once the route has its heights, and
+ * by the router's own time before that.
+ */
+export function tourPlannerFacts(input: TourPlannerFactsInput) {
+ const isPaddle = input.tourType === 'kayak';
+ const { paddleEstimate, routeAnalysis, durationSeconds, breakAdditionalMinutes, plannedDurationMinutes } = input;
+ const walkingDurationMinutes = paddleEstimate
+ ? paddleEstimate.waterMinutes === null
+ ? null
+ : paddleEstimate.estimateMinutes
+ : routeAnalysis?.gain != null && routeAnalysis.loss != null
+ ? hikingTimeMinutes(routeAnalysis.distanceKm, routeAnalysis.gain, routeAnalysis.loss)
+ : durationSeconds === null
+ ? null
+ : Math.round(durationSeconds / 60);
+ const automaticPlannedTotalMinutes =
+ walkingDurationMinutes === null ? null : walkingDurationMinutes + (breakAdditionalMinutes ?? 0);
+ const { boatType, waterContext, speedKmh, portageSpeedKmh, lakeStyle } = input.paddle;
+ return {
+ isPaddle,
+ websiteInvalid: input.website.trim().length > 0 && !tourWebsiteSchema.safeParse(input.website).success,
+ plannedDurationInvalid: invalidMinutes(plannedDurationMinutes),
+ breakAdditionalInvalid: invalidMinutes(breakAdditionalMinutes),
+ paddleIncomplete: isPaddle && (boatType === null || waterContext === null),
+ walkingDurationMinutes,
+ automaticPlannedTotalMinutes,
+ plannedTotalMinutes: plannedDurationMinutes ?? automaticPlannedTotalMinutes,
+ plannedTotalInvalid:
+ plannedDurationMinutes === null &&
+ automaticPlannedTotalMinutes !== null &&
+ automaticPlannedTotalMinutes > MAX_PLANNED_TOUR_DURATION_MINUTES,
+ // The router's own time stands in for a hike without heights; a paddle tour has only its speed.
+ savedDurationSeconds:
+ walkingDurationMinutes === null ? (isPaddle ? null : durationSeconds) : walkingDurationMinutes * 60,
+ // What the type adds to a save: a hike its routing limit, a paddle tour its boat, water and speed.
+ typeFields: isPaddle
+ ? {
+ tour_type: input.tourType,
+ max_hiking_difficulty: null,
+ boat_type: boatType,
+ water_context: waterContext,
+ paddle_speed_kmh: speedKmh,
+ portage_speed_kmh: portageSpeedKmh,
+ paddle_lake_style: lakeStyle,
+ }
+ : {
+ tour_type: input.tourType,
+ max_hiking_difficulty: input.maxHikingDifficulty,
+ boat_type: null,
+ water_context: null,
+ paddle_speed_kmh: null,
+ portage_speed_kmh: null,
+ paddle_lake_style: null,
+ },
+ };
+}
+
+export type TourPlannerFacts = ReturnType<typeof tourPlannerFacts>;
diff --git a/client/src/components/Tours/planner/tourPlannerParts.test.ts b/client/src/components/Tours/planner/tourPlannerParts.test.ts
new file mode 100644
index 000000000..08cf28a4b
--- /dev/null
+++ b/client/src/components/Tours/planner/tourPlannerParts.test.ts
@@ -0,0 +1,131 @@
+import { act, renderHook } from '@testing-library/react';
+import { describe, expect, it } from 'vitest';
+import { tourPlannerFacts, type TourPlannerFactsInput } from './tourPlannerFacts';
+import { usePlannerHistory } from './usePlannerHistory';
+import { useTourDraftStorage } from './useTourDraftStorage';
+
+const hike = (overrides: Partial<TourPlannerFactsInput> = {}): TourPlannerFactsInput => ({
+ tourType: 'hike',
+ maxHikingDifficulty: 3,
+ website: '',
+ plannedDurationMinutes: null,
+ breakAdditionalMinutes: null,
+ paddle: { boatType: null, waterContext: null, speedKmh: null, portageSpeedKmh: null, lakeStyle: null },
+ paddleSpeedInvalid: false,
+ paddleEstimate: null,
+ routeAnalysis: null,
+ durationSeconds: null,
+ ...overrides,
+});
+
+describe('tourPlannerFacts', () => {
+ it('times a hike by the router until its heights are in, then by the signposts, breaks on top', () => {
+ expect(tourPlannerFacts(hike({ durationSeconds: 3_570 })).walkingDurationMinutes).toBe(60);
+ const analysis = { distanceKm: 8, gain: 600, loss: 600 } as TourPlannerFactsInput['routeAnalysis'];
+ const facts = tourPlannerFacts(
+ hike({ routeAnalysis: analysis, durationSeconds: 3_600, breakAdditionalMinutes: 30 })
+ );
+ expect(facts.walkingDurationMinutes).toBeGreaterThan(60);
+ expect(facts.plannedTotalMinutes).toBe(facts.walkingDurationMinutes! + 30);
+ expect(facts.savedDurationSeconds).toBe(facts.walkingDurationMinutes! * 60);
+ expect(facts.typeFields).toMatchObject({ tour_type: 'hike', max_hiking_difficulty: 3, boat_type: null });
+ });
+
+ it('holds the fields to their bounds, and a total that runs past a day without an override', () => {
+ const facts = tourPlannerFacts(
+ hike({ website: 'http://plain.example', plannedDurationMinutes: 1.5, breakAdditionalMinutes: -1 })
+ );
+ expect(facts).toMatchObject({ websiteInvalid: true, plannedDurationInvalid: true, breakAdditionalInvalid: true });
+ expect(tourPlannerFacts(hike({ durationSeconds: 1_500 * 60 })).plannedTotalInvalid).toBe(true);
+ expect(
+ tourPlannerFacts(hike({ durationSeconds: 1_500 * 60, plannedDurationMinutes: 600 })).plannedTotalInvalid
+ ).toBe(false);
+ expect(tourPlannerFacts(hike({ website: 'https://ok.example' })).websiteInvalid).toBe(false);
+ });
+
+ it('times a paddle tour on the water and asks for its boat and water', () => {
+ const paddle = hike({
+ tourType: 'kayak',
+ paddle: { boatType: 'canoe', waterContext: null, speedKmh: 5, portageSpeedKmh: 3, lakeStyle: 'shore' },
+ paddleEstimate: { waterMinutes: 80, estimateMinutes: 95 },
+ durationSeconds: 999,
+ });
+ const facts = tourPlannerFacts(paddle);
+ expect(facts.walkingDurationMinutes).toBe(95);
+ expect(facts.paddleIncomplete).toBe(true);
+ expect(facts.typeFields).toMatchObject({
+ tour_type: 'kayak',
+ max_hiking_difficulty: null,
+ boat_type: 'canoe',
+ paddle_lake_style: 'shore',
+ });
+ const unknown = tourPlannerFacts({ ...paddle, paddleEstimate: { waterMinutes: null, estimateMinutes: null } });
+ expect(unknown.walkingDurationMinutes).toBeNull();
+ expect(unknown.savedDurationSeconds).toBeNull();
+ });
+});
+
+describe('usePlannerHistory', () => {
+ it('goes back and forth, forgets the undone on a new step, and keeps at most thirty', () => {
+ const { result } = renderHook(() => usePlannerHistory<number>());
+ act(() => result.current.record(1));
+ act(() => result.current.record(2));
+ let step: number | null = null;
+ act(() => {
+ step = result.current.undo(3);
+ });
+ expect(step).toBe(2);
+ expect(result.current.canRedo).toBe(true);
+ act(() => {
+ step = result.current.redo(2);
+ });
+ expect(step).toBe(3);
+ act(() => {
+ result.current.undo(3);
+ });
+ act(() => result.current.record(9));
+ expect(result.current.canRedo).toBe(false);
+ act(() => {
+ step = result.current.redo(9);
+ });
+ expect(step).toBeNull();
+ act(() => result.current.clear());
+ expect(result.current.canUndo).toBe(false);
+ act(() => {
+ step = result.current.undo(0);
+ });
+ expect(step).toBeNull();
+ for (let i = 0; i < 40; i++) act(() => result.current.record(i));
+ let undone = 0;
+ for (let i = 0; i < 40; i++)
+ act(() => {
+ if (result.current.undo(-1) !== null) undone++;
+ });
+ expect(undone).toBe(30);
+ });
+});
+
+describe('useTourDraftStorage', () => {
+ it('keeps a draft per trip, gives back only one that passes the check, and forgets it', () => {
+ localStorage.clear();
+ const draft = {
+ version: 9 as const,
+ name: 'Ridge',
+ waypoints: [{ id: 'a', lat: 47, lng: 11, role: 'start' as const }],
+ baseRevision: 4,
+ };
+ const first = renderHook(() => useTourDraftStorage(1));
+ act(() => first.result.current.keep(draft));
+ expect(renderHook(() => useTourDraftStorage(1)).result.current.restored).toMatchObject({
+ name: 'Ridge',
+ baseRevision: 4,
+ });
+ expect(renderHook(() => useTourDraftStorage(2)).result.current.restored).toBeNull();
+ localStorage.setItem('tour-draft-3', JSON.stringify({ ...draft, baseRevision: 0 }));
+ expect(renderHook(() => useTourDraftStorage(3)).result.current.restored).toBeNull();
+ localStorage.setItem('tour-draft-4', '{not json');
+ expect(renderHook(() => useTourDraftStorage(4)).result.current.restored).toBeNull();
+ act(() => first.result.current.forget());
+ expect(localStorage.getItem('tour-draft-1')).toBeNull();
+ });
+});
diff --git a/client/src/components/Tours/planner/tourRevision.test.tsx b/client/src/components/Tours/planner/tourRevision.test.tsx
new file mode 100644
index 000000000..8c4a6f82a
--- /dev/null
+++ b/client/src/components/Tours/planner/tourRevision.test.tsx
@@ -0,0 +1,199 @@
+import { act, fireEvent, render, renderHook, screen } from '@testing-library/react';
+import type { TourListItem } from '@trek/shared';
+import { AxiosError, AxiosHeaders } from 'axios';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { TourRemoteChangeNotice, TourRevisionConflictDialog } from './TourRevisionNotice';
+import type { TourPlannerController } from './useTourPlanner';
+import { revisionConflictOf, useTourRevisionGuard } from './useTourRevisionGuard';
+import { useTourRevisionWatch } from './useTourRevisionWatch';
+
+const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }));
+vi.mock('../../shared/Toast', () => ({ useToast: () => toast }));
+
+function refused(status: number, data: unknown) {
+ const headers = new AxiosHeaders();
+ return new AxiosError('refused', 'ERR', undefined, undefined, {
+ status,
+ statusText: '',
+ headers,
+ config: { headers },
+ data,
+ });
+}
+
+const CONFLICT = refused(409, {
+ error: 'This tour was changed in the meantime',
+ code: 'tour_revision_conflict',
+ revision: 5,
+});
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('revisionConflictOf (P2C-03)', () => {
+ it('reads the revision off a refused save, and nothing off anything else', () => {
+ expect(revisionConflictOf(CONFLICT)).toBe(5);
+ expect(revisionConflictOf(refused(409, { error: 'conflict', server: {} }))).toBeNull();
+ expect(revisionConflictOf(refused(500, { code: 'tour_revision_conflict', revision: 5 }))).toBeNull();
+ expect(revisionConflictOf(refused(409, { code: 'tour_revision_conflict', revision: 'x' }))).toBeNull();
+ expect(revisionConflictOf(new Error('offline'))).toBeNull();
+ });
+});
+
+describe('useTourRevisionGuard (P2C-03)', () => {
+ it('keeps the base a save names, and hears of a newer revision only once one is known', () => {
+ const { result } = renderHook(() => useTourRevisionGuard());
+ expect(result.current.notice(4)).toBe(false);
+ act(() => result.current.adopt(3));
+ expect(result.current.base).toBe(3);
+ expect(result.current.baseRef.current).toBe(3);
+ let noticed = false;
+ act(() => {
+ noticed = result.current.notice(3);
+ });
+ expect(noticed).toBe(false);
+ act(() => {
+ noticed = result.current.notice(4);
+ });
+ expect(noticed).toBe(true);
+ expect(result.current.remote).toBe(4);
+ act(() => result.current.dismissRemote());
+ expect(result.current.remote).toBeNull();
+ });
+
+ it('turns a refused save into a conflict, and taking it over makes the next save name the newer revision', () => {
+ const { result } = renderHook(() => useTourRevisionGuard(3));
+ let refusedForRevision = false;
+ act(() => {
+ refusedForRevision = result.current.refuse(new Error('network'));
+ });
+ expect(refusedForRevision).toBe(false);
+ act(() => {
+ refusedForRevision = result.current.refuse(CONFLICT);
+ });
+ expect(refusedForRevision).toBe(true);
+ expect(result.current.conflict).toEqual({ revision: 5 });
+ act(() => result.current.takeOver());
+ expect(result.current.conflict).toBeNull();
+ expect(result.current.baseRef.current).toBe(5);
+ });
+
+ it('forgets the base and what it knew of others when the planner moves on', () => {
+ const { result } = renderHook(() => useTourRevisionGuard(3));
+ act(() => {
+ result.current.refuse(CONFLICT);
+ });
+ act(() => result.current.adopt(null));
+ expect(result.current.base).toBeNull();
+ expect(result.current.conflict).toBeNull();
+ act(() => result.current.dismissConflict());
+ act(() => result.current.takeOver());
+ expect(result.current.base).toBeNull();
+ });
+});
+
+function plannerWith(
+ overrides: Omit<Partial<TourPlannerController>, 'revision'> & {
+ revision?: Partial<TourPlannerController['revision']>;
+ } = {}
+) {
+ const revision = {
+ base: 3,
+ baseRef: { current: 3 },
+ conflict: null,
+ remote: null,
+ adopt: vi.fn(),
+ notice: vi.fn(() => false),
+ refuse: vi.fn(),
+ takeOver: vi.fn(),
+ dismissConflict: vi.fn(),
+ dismissRemote: vi.fn(),
+ ...overrides.revision,
+ };
+ return {
+ mode: { type: 'edit-saved', placeId: 7 },
+ name: 'Kramer',
+ hasUnsavedChanges: true,
+ isSaving: false,
+ openTour: vi.fn(async () => true),
+ save: vi.fn(async () => null),
+ ...overrides,
+ revision,
+ } as unknown as TourPlannerController;
+}
+
+describe('TourRemoteChangeNotice (P2C-03)', () => {
+ it('says so while the draft has changes of its own, and loads the newer tour only after a confirm', () => {
+ const planner = plannerWith({ revision: { remote: 4 } });
+ render(<TourRemoteChangeNotice planner={planner} />);
+ expect(screen.getByTestId('tour-remote-change')).toHaveTextContent('tours.revision.remoteTitle');
+ fireEvent.click(screen.getByRole('button', { name: /tours.revision.loadNewer/ }));
+ expect(planner.openTour).not.toHaveBeenCalled();
+ fireEvent.click(screen.getAllByRole('button', { name: 'tours.revision.loadNewer' })[1]);
+ expect(planner.openTour).toHaveBeenCalledWith({ place_id: 7 });
+ });
+
+ it('stays away without news, without changes, or while a conflict asks instead; closing dismisses it', () => {
+ const { rerender } = render(<TourRemoteChangeNotice planner={plannerWith()} />);
+ expect(screen.queryByTestId('tour-remote-change')).toBeNull();
+ rerender(<TourRemoteChangeNotice planner={plannerWith({ hasUnsavedChanges: false, revision: { remote: 4 } })} />);
+ expect(screen.queryByTestId('tour-remote-change')).toBeNull();
+ rerender(<TourRemoteChangeNotice planner={plannerWith({ revision: { remote: 4, conflict: { revision: 4 } } })} />);
+ expect(screen.queryByTestId('tour-remote-change')).toBeNull();
+ const planner = plannerWith({ revision: { remote: 4 } });
+ rerender(<TourRemoteChangeNotice planner={planner} />);
+ fireEvent.click(screen.getByRole('button', { name: 'common.close' }));
+ expect(planner.revision.dismissRemote).toHaveBeenCalled();
+ });
+});
+
+describe('TourRevisionConflictDialog (P2C-03)', () => {
+ it('offers three ways on: save as a tour of its own, load the newer one, or overwrite on purpose', () => {
+ const planner = plannerWith({ revision: { conflict: { revision: 5 } } });
+ render(<TourRevisionConflictDialog planner={planner} />);
+ fireEvent.click(screen.getByTestId('tour-conflict-save-new'));
+ expect(planner.save).toHaveBeenCalledWith({ asNew: true, name: 'tours.revision.mineName' });
+ fireEvent.click(screen.getByTestId('tour-conflict-reload'));
+ expect(planner.openTour).toHaveBeenCalledWith({ place_id: 7 });
+ fireEvent.click(screen.getByTestId('tour-conflict-overwrite'));
+ expect(planner.revision.takeOver).toHaveBeenCalled();
+ expect(planner.save).toHaveBeenLastCalledWith();
+ });
+
+ it('is not there without a conflict, or once the tour is no longer the one in the editor', () => {
+ const { rerender } = render(<TourRevisionConflictDialog planner={plannerWith()} />);
+ expect(screen.queryByTestId('tour-conflict-reload')).toBeNull();
+ rerender(
+ <TourRevisionConflictDialog
+ planner={plannerWith({ mode: { type: 'new-draft' }, revision: { conflict: { revision: 5 } } })}
+ />
+ );
+ expect(screen.queryByTestId('tour-conflict-reload')).toBeNull();
+ });
+});
+
+describe('useTourRevisionWatch (P2C-03)', () => {
+ const listed = (revision: number) => [{ place_id: 7, revision } as TourListItem];
+
+ it('loads a newer revision at once while the editor has no changes, and says so', async () => {
+ const planner = plannerWith({ hasUnsavedChanges: false, revision: { notice: vi.fn(() => true) } });
+ renderHook(() => useTourRevisionWatch(planner, listed(4)));
+ await act(async () => undefined);
+ expect(planner.revision.notice).toHaveBeenCalledWith(4);
+ expect(planner.openTour).toHaveBeenCalledWith({ place_id: 7 });
+ expect(toast.info).toHaveBeenCalledWith('tours.revision.reloaded');
+ });
+
+ it('keeps an editor with changes as it is, and asks nothing of one that is saving or shows no saved tour', async () => {
+ const editing = plannerWith({ revision: { notice: vi.fn(() => true) } });
+ renderHook(() => useTourRevisionWatch(editing, listed(4)));
+ const saving = plannerWith({ hasUnsavedChanges: false, isSaving: true, revision: { notice: vi.fn(() => true) } });
+ renderHook(() => useTourRevisionWatch(saving, listed(4)));
+ const drafting = plannerWith({ mode: { type: 'new-draft' }, revision: { notice: vi.fn(() => true) } });
+ renderHook(() => useTourRevisionWatch(drafting, listed(4)));
+ await act(async () => undefined);
+ expect(editing.revision.notice).toHaveBeenCalledWith(4);
+ expect(saving.revision.notice).not.toHaveBeenCalled();
+ expect(drafting.revision.notice).not.toHaveBeenCalled();
+ for (const planner of [editing, saving, drafting]) expect(planner.openTour).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/Tours/planner/usePlannerHistory.ts b/client/src/components/Tours/planner/usePlannerHistory.ts
new file mode 100644
index 000000000..7dec177ea
--- /dev/null
+++ b/client/src/components/Tours/planner/usePlannerHistory.ts
@@ -0,0 +1,49 @@
+import { useCallback, useState } from 'react';
+
+const HISTORY_LIMIT = 30;
+
+/**
+ * The planner's undo and redo: snapshots of what a step changed, the newest
+ * last, at most thirty each way. Taking a new step forgets what was undone.
+ * The planner says what a snapshot is and how it is put back.
+ */
+export function usePlannerHistory<Entry>() {
+ const [past, setPast] = useState<Entry[]>([]);
+ const [future, setFuture] = useState<Entry[]>([]);
+
+ /** A new step: the state before it goes on the stack, and nothing is left to redo. */
+ const record = useCallback((before: Entry) => {
+ setPast((current) => [...current, before].slice(-HISTORY_LIMIT));
+ setFuture([]);
+ }, []);
+
+ /** The step to go back to, with the present kept for redo; null when there is none. */
+ const undo = useCallback(
+ (present: Entry): Entry | null => {
+ const previous = past[past.length - 1];
+ if (previous === undefined) return null;
+ setPast(past.slice(0, -1));
+ setFuture([present, ...future].slice(0, HISTORY_LIMIT));
+ return previous;
+ },
+ [future, past]
+ );
+
+ const redo = useCallback(
+ (present: Entry): Entry | null => {
+ const next = future[0];
+ if (next === undefined) return null;
+ setPast([...past, present].slice(-HISTORY_LIMIT));
+ setFuture(future.slice(1));
+ return next;
+ },
+ [future, past]
+ );
+
+ const clear = useCallback(() => {
+ setPast([]);
+ setFuture([]);
+ }, []);
+
+ return { record, undo, redo, clear, canUndo: past.length > 0, canRedo: future.length > 0 };
+}
diff --git a/client/src/components/Tours/planner/useTourDraftStorage.ts b/client/src/components/Tours/planner/useTourDraftStorage.ts
new file mode 100644
index 000000000..00d217141
--- /dev/null
+++ b/client/src/components/Tours/planner/useTourDraftStorage.ts
@@ -0,0 +1,44 @@
+import { useCallback, useMemo } from 'react';
+import { validDraft, type DraftPayload } from './tourPlannerDraft';
+import { normalizePlannerWaypoints } from './tourPlannerWaypoints';
+
+/**
+ * The planner's draft kept in this browser between visits, one per trip: the
+ * draft found when the planner opens (null for none, or one that does not
+ * pass the check), keeping the current one, and forgetting it once it is
+ * saved or thrown away. Storage that is full or blocked keeps nothing.
+ */
+export function useTourDraftStorage(tripId: number | string) {
+ const storageKey = `tour-draft-${tripId}`;
+ const restored = useMemo(() => {
+ try {
+ const parsed = JSON.parse(localStorage.getItem(storageKey) || 'null') as unknown;
+ return validDraft(parsed)
+ ? { ...parsed, waypoints: normalizePlannerWaypoints(parsed.waypoints, parsed.tourType === 'kayak') }
+ : null;
+ } catch {
+ return null;
+ }
+ }, [storageKey]);
+
+ const keep = useCallback(
+ (draft: DraftPayload) => {
+ try {
+ localStorage.setItem(storageKey, JSON.stringify(draft));
+ } catch {
+ // Full or blocked storage: the draft lives on in the page until it is saved.
+ }
+ },
+ [storageKey]
+ );
+
+ const forget = useCallback(() => {
+ try {
+ localStorage.removeItem(storageKey);
+ } catch {
+ // Blocked storage held nothing to forget.
+ }
+ }, [storageKey]);
+
+ return { restored, keep, forget };
+}
diff --git a/client/src/components/Tours/planner/useTourPlanner.ts b/client/src/components/Tours/planner/useTourPlanner.ts
index 94323569d..cb3b11850 100644
--- a/client/src/components/Tours/planner/useTourPlanner.ts
+++ b/client/src/components/Tours/planner/useTourPlanner.ts
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import { MAX_PLANNED_TOUR_DURATION_MINUTES, paddleSpeedKmhSchema, tourWebsiteSchema, type PlannableTourType, type TourCreateResponse, type TourFixedLeg, type TourListItem, type TourMaxHikingDifficulty } from '@trek/shared'
+import { paddleSpeedKmhSchema, tourWebsiteSchema, type PlannableTourType, type TourCreateResponse, type TourFixedLeg, type TourListItem, type TourMaxHikingDifficulty } from '@trek/shared'
import { paddleRouteRepo } from '../../../repo/paddleRouteRepo'
import { tourRepo } from '../../../repo/tourRepo'
import { randomId } from '../../../utils/randomId'
@@ -7,13 +7,16 @@ import { analyzeRouteGeometry, type RouteProfileFocus } from '../../../utils/rou
import { enrichTourElevations, routeWalkingTour, type TourElevationPoint, type TourRoutePart } from './tourRouting'
import { closeLoop, isClosedLoop, reverseRoute, toggleFreeLeg } from './tourRouteActions'
import { normalizePlannerWaypoints, plannerWaypointsOf, sameWaypointSnapshot, savedWaypointsOf, tourWaypointKey, type TourPlannerWaypoint } from './tourPlannerWaypoints'
+import { tourPlannerFacts } from './tourPlannerFacts'
+import { usePlannerHistory } from './usePlannerHistory'
+import { useTourDraftStorage } from './useTourDraftStorage'
+import { useTourRevisionGuard } from './useTourRevisionGuard'
import { useRouteShaping } from './useRouteShaping'
import { useTourMapView } from './useTourMapView'
-import { validDraft, type DraftPayload } from './tourPlannerDraft'
+import type { DraftPayload } from './tourPlannerDraft'
import { paddleEstimateOf } from './paddlePlanOf'
import { adoptChangedPoints, planPaddleStep, type PaddleTourRoute } from './paddleRouting'
import { NO_PADDLE_FIELDS, paddleFieldsOf, usePaddleFields, type PaddleFieldValues } from './usePaddleFields'
-import { hikingTimeMinutes } from '../hikingTime'
import { useTourPermissions, type TourPermissionProps } from '../useTourPermissions'
/** What a tour planned from an import starts with. */
@@ -30,6 +33,8 @@ export interface DerivedTourDraft {
* keeps the recorded track to go back to), rather than as a new tour beside it.
*/
inPlace: boolean
+ /** P2C-03: the import's revision, which a save planned over in place names. */
+ revision?: number
/** A paddle import stays a paddle tour, with its boat and water. */
tourType?: PlannableTourType
paddle?: PaddleFieldValues
@@ -49,13 +54,7 @@ export type TourPlannerStatus =
/** One step of the history: the route, and what the route depends on. */
interface HistoryEntry { waypoints: TourPlannerWaypoint[]; difficulty: TourMaxHikingDifficulty; tourType: PlannableTourType }
-interface HistoryState {
- past: HistoryEntry[]
- future: HistoryEntry[]
-}
-
const ROUTE_DEBOUNCE_MS = 450
-const HISTORY_LIMIT = 30
function hasCompleteElevation(points: TourElevationPoint[] | null): points is [number, number, number][] {
return !!points && points.every(point => point.length === 3 && Number.isFinite(point[2]))
@@ -103,15 +102,8 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
const { canEdit, canAssign } = useTourPermissions({ tripId, canEdit: editPermission, canAssign: assignPermission })
const editPermissionRef = useRef(canEdit)
editPermissionRef.current = canEdit
- const storageKey = `tour-draft-${tripId}`
- const restored = useMemo(() => {
- try {
- const parsed = JSON.parse(localStorage.getItem(storageKey) || 'null') as unknown
- return validDraft(parsed) ? { ...parsed, waypoints: normalizePlannerWaypoints(parsed.waypoints, parsed.tourType === 'kayak') } : null
- } catch {
- return null
- }
- }, [storageKey])
+ const draftStorage = useTourDraftStorage(tripId)
+ const { restored, keep: keepDraft, forget: forgetDraft } = draftStorage
const [name, setNameState] = useState(restored?.name ?? '')
const [description, setDescriptionState] = useState(restored?.description ?? '')
@@ -122,7 +114,10 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
const [maxHikingDifficulty, setMaxHikingDifficultyState] = useState<TourMaxHikingDifficulty>(restored?.maxHikingDifficulty ?? 2)
const [tourType, setTourTypeState] = useState<PlannableTourType>(restored?.tourType ?? 'hike')
const [selectedWaypointId, setSelectedWaypointId] = useState<string | null>(restored?.waypoints[0]?.id ?? null)
- const [history, setHistory] = useState<HistoryState>({ past: [], future: [] })
+ const history = usePlannerHistory<HistoryEntry>()
+ const { record: recordStep, clear: clearHistory } = history
+ const revision = useTourRevisionGuard(restored?.baseRevision ?? null)
+ const { adopt: adoptRevision, refuse: refuseRevision, baseRef: revisionBaseRef } = revision
const [status, setStatus] = useState<TourPlannerStatus>(restored?.waypoints.length ? 'dirty' : 'empty')
const [route, setRoute] = useState<[number, number][] | null>(null)
const [routeParts, setRouteParts] = useState<TourRoutePart[] | null>(null)
@@ -219,15 +214,14 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
invalidateDetailRequest()
interruptRouting()
draftRevisionRef.current += 1
- const entry = snapshot()
- setHistory(previous => ({ past: [...previous.past, entry].slice(-HISTORY_LIMIT), future: [] }))
+ recordStep(snapshot())
waypointsRef.current = next
setWaypoints(next)
setHasUnsavedChanges(true)
setSaveOutcome(null)
setStatus('dirty')
setError(null)
- }, [invalidateDetailRequest, interruptRouting, snapshot])
+ }, [recordStep, invalidateDetailRequest, interruptRouting, snapshot])
// Detail laid in after the step that asked for it (a portage's way on land), with no step of its own.
const amendWaypoints = useCallback((change: (current: TourPlannerWaypoint[]) => TourPlannerWaypoint[]) => {
@@ -248,15 +242,14 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
invalidateDetailRequest()
interruptRouting()
draftRevisionRef.current += 1
- const entry = snapshot()
- setHistory(current => ({ past: [...current.past, entry].slice(-HISTORY_LIMIT), future: [] }))
+ recordStep(snapshot())
difficultyRef.current = value
setMaxHikingDifficultyState(value)
setHasUnsavedChanges(true)
setSaveOutcome(null)
setStatus('dirty')
setError(null)
- }, [invalidateDetailRequest, interruptRouting, snapshot])
+ }, [recordStep, invalidateDetailRequest, interruptRouting, snapshot])
const addWaypoint = useCallback((lat: number, lng: number) => {
if (!editPermissionRef.current) return
@@ -360,47 +353,35 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
[commitWaypoints]
);
- const undo = useCallback(() => {
- if (!editPermissionRef.current) return
- const previous = history.past[history.past.length - 1]
- if (!previous) return
+ /** A snapshot of the history put back: the route and what it depends on. */
+ const restoreStep = useCallback((entry: HistoryEntry) => {
invalidateDetailRequest()
interruptRouting()
draftRevisionRef.current += 1
- const present = snapshot()
- waypointsRef.current = previous.waypoints
- difficultyRef.current = previous.difficulty
- tourTypeRef.current = previous.tourType
- setWaypoints(previous.waypoints)
- setMaxHikingDifficultyState(previous.difficulty)
- setTourTypeState(previous.tourType)
- setSelectedWaypointId(id => previous.waypoints.some(point => point.id === id) ? id : previous.waypoints[0]?.id ?? null)
- setHistory({ past: history.past.slice(0, -1), future: [present, ...history.future].slice(0, HISTORY_LIMIT) })
+ waypointsRef.current = entry.waypoints
+ difficultyRef.current = entry.difficulty
+ tourTypeRef.current = entry.tourType
+ setWaypoints(entry.waypoints)
+ setMaxHikingDifficultyState(entry.difficulty)
+ setTourTypeState(entry.tourType)
+ setSelectedWaypointId(id => entry.waypoints.some(point => point.id === id) ? id : entry.waypoints[0]?.id ?? null)
setHasUnsavedChanges(true)
setStatus('dirty')
setError(null)
- }, [history, invalidateDetailRequest, interruptRouting, snapshot])
+ }, [invalidateDetailRequest, interruptRouting])
+
+ const { undo: undoStep, redo: redoStep } = history
+ const undo = useCallback(() => {
+ if (!editPermissionRef.current) return
+ const previous = undoStep(snapshot())
+ if (previous) restoreStep(previous)
+ }, [restoreStep, snapshot, undoStep])
const redo = useCallback(() => {
if (!editPermissionRef.current) return
- const next = history.future[0]
- if (!next) return
- invalidateDetailRequest()
- interruptRouting()
- draftRevisionRef.current += 1
- const present = snapshot()
- waypointsRef.current = next.waypoints
- difficultyRef.current = next.difficulty
- tourTypeRef.current = next.tourType
- setWaypoints(next.waypoints)
- setMaxHikingDifficultyState(next.difficulty)
- setTourTypeState(next.tourType)
- setSelectedWaypointId(id => next.waypoints.some(point => point.id === id) ? id : next.waypoints[0]?.id ?? null)
- setHistory({ past: [...history.past, present].slice(-HISTORY_LIMIT), future: history.future.slice(1) })
- setHasUnsavedChanges(true)
- setStatus('dirty')
- setError(null)
- }, [history, invalidateDetailRequest, interruptRouting, snapshot])
+ const next = redoStep(snapshot())
+ if (next) restoreStep(next)
+ }, [redoStep, restoreStep, snapshot])
/** A field other than the route changed: the draft is unsaved again, and a finished save is no longer current. */
const markEdited = useCallback(() => {
@@ -448,8 +429,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
invalidateDetailRequest()
interruptRouting()
draftRevisionRef.current += 1
- const entry = snapshot()
- setHistory(current => ({ past: [...current.past, entry].slice(-HISTORY_LIMIT), future: [] }))
+ recordStep(snapshot())
tourTypeRef.current = value
setTourTypeState(value)
const next = normalizePlannerWaypoints(waypointsRef.current, value === 'kayak')
@@ -459,48 +439,27 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setSaveOutcome(null)
setStatus('dirty')
setError(null)
- }, [invalidateDetailRequest, interruptRouting, snapshot])
+ }, [recordStep, invalidateDetailRequest, interruptRouting, snapshot])
- const websiteInvalid = website.trim().length > 0 && !tourWebsiteSchema.safeParse(website).success
- const plannedDurationInvalid = plannedDurationMinutes !== null
- && (!Number.isInteger(plannedDurationMinutes) || plannedDurationMinutes < 0 || plannedDurationMinutes > MAX_PLANNED_TOUR_DURATION_MINUTES)
const routeAnalysis = useMemo(
() => analyzeRouteGeometry(JSON.stringify(enrichedGeometry ?? route)),
[enrichedGeometry, route],
)
- // The router's time only stands in until the route has its heights; from then on the
- // walking time is the signposts' rule over distance, climb and descent.
const isPaddle = tourType === 'kayak'
const paddleSpeedInvalid = paddle.speedKmh !== null && !paddleSpeedKmhSchema.safeParse(paddle.speedKmh).success
- const paddleIncomplete = isPaddle && (paddle.boatType === null || paddle.waterContext === null)
- // A paddle tour is timed on the water at its speed; a hike by the signposts' rule once the heights are in.
- const { effectiveSpeedKmh, portageSpeedKmh } = paddle
+ const { effectiveSpeedKmh, portageSpeedKmh, boatType, waterContext, speedKmh, lakeStyle } = paddle
// The routed length of each leg while the route is the current points' (PAD-11); straight lines before that.
const routedLegLengths = paddleRoute && routeForKey === tourWaypointKey(waypoints) ? paddleRoute.legLengths : undefined
const paddleEstimate = useMemo(() => isPaddle ? paddleEstimateOf(waypoints, { effectiveSpeedKmh, portageSpeedKmh }, paddleSpeedInvalid, routedLegLengths) : null,
[effectiveSpeedKmh, isPaddle, paddleSpeedInvalid, portageSpeedKmh, routedLegLengths, waypoints])
- const walkingDurationMinutes = paddleEstimate
- ? paddleEstimate.waterMinutes === null ? null : paddleEstimate.estimateMinutes
- : routeAnalysis?.gain != null && routeAnalysis.loss != null
- ? hikingTimeMinutes(routeAnalysis.distanceKm, routeAnalysis.gain, routeAnalysis.loss)
- : durationSeconds === null ? null : Math.round(durationSeconds / 60)
- const automaticPlannedTotalMinutes = walkingDurationMinutes === null
- ? null
- : walkingDurationMinutes + (breakAdditionalMinutes ?? 0)
- const breakAdditionalInvalid = breakAdditionalMinutes !== null
- && (!Number.isInteger(breakAdditionalMinutes) || breakAdditionalMinutes < 0 || breakAdditionalMinutes > MAX_PLANNED_TOUR_DURATION_MINUTES)
- const plannedTotalMinutes = plannedDurationMinutes ?? automaticPlannedTotalMinutes
- // What the type adds to a save: a hike its routing limit, a paddle tour its boat, water and speed.
- const { boatType, waterContext, speedKmh, lakeStyle } = paddle
- const typeFields = useMemo(() => tourType === 'kayak'
- ? { tour_type: tourType, max_hiking_difficulty: null, boat_type: boatType, water_context: waterContext, paddle_speed_kmh: speedKmh, portage_speed_kmh: portageSpeedKmh, paddle_lake_style: lakeStyle }
- : { tour_type: tourType, max_hiking_difficulty: maxHikingDifficulty, boat_type: null, water_context: null, paddle_speed_kmh: null, portage_speed_kmh: null, paddle_lake_style: null },
- [boatType, lakeStyle, maxHikingDifficulty, portageSpeedKmh, speedKmh, tourType, waterContext])
- // The router's own time stands in for a hike without heights; a paddle tour has only its speed.
- const savedDurationSeconds = walkingDurationMinutes === null ? (isPaddle ? null : durationSeconds) : walkingDurationMinutes * 60
- const plannedTotalInvalid = plannedDurationMinutes === null
- && automaticPlannedTotalMinutes !== null
- && automaticPlannedTotalMinutes > MAX_PLANNED_TOUR_DURATION_MINUTES
+ const facts = useMemo(() => tourPlannerFacts({
+ tourType, maxHikingDifficulty, website, plannedDurationMinutes, breakAdditionalMinutes,
+ paddle: { boatType, waterContext, speedKmh, portageSpeedKmh, lakeStyle },
+ paddleSpeedInvalid, paddleEstimate, routeAnalysis, durationSeconds,
+ }), [boatType, breakAdditionalMinutes, durationSeconds, lakeStyle, maxHikingDifficulty, paddleEstimate, paddleSpeedInvalid,
+ plannedDurationMinutes, portageSpeedKmh, routeAnalysis, speedKmh, tourType, waterContext, website])
+ const { websiteInvalid, plannedDurationInvalid, breakAdditionalInvalid, paddleIncomplete, walkingDurationMinutes,
+ plannedTotalMinutes, plannedTotalInvalid, savedDurationSeconds, typeFields } = facts
const returnToNeutral = useCallback(() => {
if (saveInFlightRef.current) return
@@ -509,7 +468,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
contextGenerationRef.current += 1
draftRevisionRef.current += 1
setRouteProfileFocus(null)
- localStorage.removeItem(storageKey)
+ forgetDraft()
setNameState('')
setDescriptionState('')
setWebsiteState('')
@@ -523,7 +482,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
difficultyRef.current = 2
tourTypeRef.current = 'hike'
setSelectedWaypointId(null)
- setHistory({ past: [], future: [] })
+ clearHistory()
setStatus('empty')
setRoute(null)
setRouteParts(null)
@@ -538,6 +497,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setEditingPlaceId(null)
editingPlaceIdRef.current = null
setDerivedFromPlaceId(null)
+ adoptRevision(null)
setOpeningTourId(null)
setSaveOutcome(null)
setReadOnlyGpxTour(null)
@@ -545,7 +505,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setElevationProfileExpanded(true)
setNewDraftGeneration(generation => generation + 1)
setMapFocusKey(key => key + 1)
- }, [invalidateDetailRequest, interruptRouting, loadPaddle, storageKey])
+ }, [clearHistory, invalidateDetailRequest, interruptRouting, loadPaddle, forgetDraft])
const forgetDeletedTour = useCallback((placeId: number) => {
deletedTourPlaceIdsRef.current.add(placeId)
@@ -601,6 +561,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
if (draft.inPlace) {
setEditingPlaceId(draft.sourcePlaceId)
editingPlaceIdRef.current = draft.sourcePlaceId
+ adoptRevision(draft.revision)
} else {
setDerivedFromPlaceId(draft.sourcePlaceId)
}
@@ -632,7 +593,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setReadOnlyGpxTour(null)
}, [invalidateDetailRequest])
- const openTour = useCallback(async (tour: TourListItem) => {
+ const openTour = useCallback(async (tour: Pick<TourListItem, 'place_id'> & Partial<TourListItem>) => {
if (!mountedRef.current || !activeRef.current || saveInFlightRef.current || deletedTourPlaceIdsRef.current.has(tour.place_id)) return false
detailAbortRef.current?.abort()
const controller = new AbortController()
@@ -668,7 +629,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
interruptRouting()
const openedType: PlannableTourType = result.tour.tour_type === 'kayak' ? 'kayak' : 'hike'
const nextWaypoints = normalizePlannerWaypoints(plannerWaypointsOf(result.waypoints, randomId), openedType === 'kayak')
- localStorage.removeItem(storageKey)
+ forgetDraft()
contextGenerationRef.current += 1
draftRevisionRef.current += 1
setNameState(result.tour.name)
@@ -684,7 +645,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
difficultyRef.current = result.tour.max_hiking_difficulty ?? 2
tourTypeRef.current = openedType
setSelectedWaypointId(nextWaypoints[0]?.id ?? null)
- setHistory({ past: [], future: [] })
+ clearHistory()
setStatus('dirty')
setRoute(null)
setRouteParts(null)
@@ -697,6 +658,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setDraftRestored(false)
setEditingPlaceId(result.tour.place_id)
editingPlaceIdRef.current = result.tour.place_id
+ adoptRevision(result.tour.revision)
setMapFocusKey(key => key + 1)
setSaveOutcome(null)
setReadOnlyGpxTour(null)
@@ -711,7 +673,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setOpeningTourId(null)
}
}
- }, [interruptRouting, loadPaddle, storageKey, tripId])
+ }, [clearHistory, interruptRouting, loadPaddle, forgetDraft, tripId])
const retry = useCallback(() => {
if (waypointsRef.current.length < 2) return
@@ -842,13 +804,13 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
useEffect(() => {
if (!hasUnsavedChanges) return
const draft: DraftPayload = { version: 9, name, description, website, plannedDurationMinutes, breakAdditionalMinutes, waypoints, maxHikingDifficulty, editingPlaceId,
- derivedFromPlaceId, tourType,
+ derivedFromPlaceId, tourType, baseRevision: revision.base,
paddle: { boatType: paddle.boatType, waterContext: paddle.waterContext, speedKmh: paddle.speedKmh, portageSpeedKmh: paddle.portageSpeedKmh, lakeStyle: paddle.lakeStyle },
}
- localStorage.setItem(storageKey, JSON.stringify(draft))
+ keepDraft(draft)
}, [breakAdditionalMinutes,
- derivedFromPlaceId, description, editingPlaceId, hasUnsavedChanges, maxHikingDifficulty, name, plannedDurationMinutes, storageKey, waypoints, website,
- tourType, paddle.boatType, paddle.waterContext, paddle.speedKmh, paddle.portageSpeedKmh, paddle.lakeStyle])
+ derivedFromPlaceId, description, editingPlaceId, hasUnsavedChanges, maxHikingDifficulty, name, plannedDurationMinutes, keepDraft, waypoints, website,
+ tourType, paddle.boatType, paddle.waterContext, paddle.speedKmh, paddle.portageSpeedKmh, paddle.lakeStyle, revision.base])
useEffect(() => {
if (!hasUnsavedChanges) return
@@ -862,7 +824,12 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
&& description.length <= 2000 && !websiteInvalid && !plannedDurationInvalid && !breakAdditionalInvalid && !plannedTotalInvalid
&& !paddleIncomplete && !(isPaddle && paddleSpeedInvalid)
- const save = useCallback(async () => {
+ /**
+ * Saves the draft: over the tour it edits, naming the revision it was loaded
+ * at (P2C-03), or with `asNew` as a tour of its own under `name`, the way out
+ * of a refused save that keeps both versions.
+ */
+ const save = useCallback(async (options: { asNew?: boolean; name?: string } = {}) => {
if (!mountedRef.current || saveInFlightRef.current || !editPermissionRef.current || !canSave || !hasCompleteElevation(enrichedGeometry)) return null
if (editingPlaceId !== null && deletedTourPlaceIdsRef.current.has(editingPlaceId)) return null
invalidateDetailRequest()
@@ -872,8 +839,10 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
const submittedContextGeneration = contextGenerationRef.current
const submittedTripId = String(tripId)
const submittedPlaceId = editingPlaceId
+ const targetPlaceId = options.asNew ? null : submittedPlaceId
+ const expectedRevision = targetPlaceId === null ? null : revisionBaseRef.current
const payload = {
- name: name.trim(),
+ name: (options.name ?? name).trim(),
description: trimmedOrNull(description),
website: parsedWebsiteOrNull(website),
...typeFields,
@@ -882,7 +851,8 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
duration_seconds: savedDurationSeconds,
planned_duration_minutes: plannedDurationMinutes,
break_additional_minutes: breakAdditionalMinutes,
- ...derivedFromField(submittedPlaceId, derivedFromPlaceId),
+ ...derivedFromField(targetPlaceId, derivedFromPlaceId),
+ ...(expectedRevision !== null ? { expected_revision: expectedRevision } : {}),
} as const
setStatus('saving')
setIsSaving(true)
@@ -894,14 +864,16 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
&& contextGenerationRef.current === submittedContextGeneration
&& draftRevisionRef.current === submittedRevision
try {
- const result = submittedPlaceId === null
+ const result = targetPlaceId === null
? await tourRepo.create(tripId, payload)
- : await tourRepo.update(tripId, submittedPlaceId, payload)
+ : await tourRepo.update(tripId, targetPlaceId, payload)
if (stillCurrent()) {
- localStorage.removeItem(storageKey)
+ forgetDraft()
+ adoptRevision(result.tour.revision)
+ if (options.name) setNameState(options.name.trim())
setHasUnsavedChanges(false)
setStatus('saved')
- setHistory({ past: [], future: [] })
+ clearHistory()
setEditingPlaceId(result.tour.place_id)
editingPlaceIdRef.current = result.tour.place_id
setSaveOutcome(result.tour)
@@ -910,10 +882,11 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
try { await onSaved?.(result) } catch { return result }
}
return result
- } catch {
+ } catch (failure: unknown) {
if (stillCurrent()) {
setStatus('ready')
- setError('save')
+ // A save refused because someone else saved the tour meanwhile keeps the draft and asks what to do.
+ setError(refuseRevision(failure) ? 'conflict' : 'save')
}
return null
} finally {
@@ -922,9 +895,9 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setIsSaving(false)
}
}
- }, [breakAdditionalMinutes, canSave,
+ }, [clearHistory, breakAdditionalMinutes, canSave,
derivedFromPlaceId,
- description, savedDurationSeconds, editingPlaceId, enrichedGeometry, invalidateDetailRequest, name, onSaved, plannedDurationMinutes, storageKey, tripId, typeFields, waypoints, website])
+ description, savedDurationSeconds, editingPlaceId, enrichedGeometry, invalidateDetailRequest, name, onSaved, plannedDurationMinutes, forgetDraft, tripId, typeFields, waypoints, website])
return {
tripId, canEdit, canAssign,
@@ -938,7 +911,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
addWaypoint, appendFixedLeg, setWaypointPosition, removeWaypoint, moveWaypoint, reorderWaypoint,
reverse, returnToStart, isLoop: isClosedLoop(waypoints), toggleWaypointFreeLeg, editPaddlePoints, amendWaypoints, paddleEstimate,
...shaping, paddleRoute, routeCurrent: routeForKey === waypointKey,
- undo, redo, canUndo: history.past.length > 0, canRedo: history.future.length > 0,
+ undo, redo, canUndo: history.canUndo, canRedo: history.canRedo,
status, error, retry, isSaving,
route, routeParts, enrichedGeometry, routeAnalysis, distanceMeters, durationSeconds,
routeProfileFocus, setRouteProfileFocus,
@@ -950,7 +923,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
newTourConfirmationOpen, cancelNewTour, forgetDeletedTour,
elevationProfileExpanded, toggleElevationProfile, newDraftGeneration, draftRestored, mapFocusKey,
editingPlaceId, openingTourId, openTour,
- saveOutcome, hasUnsavedChanges, canSave, save, discard, returnToNeutral,
+ saveOutcome, hasUnsavedChanges, canSave, save, discard, returnToNeutral, revision,
}
}
diff --git a/client/src/components/Tours/planner/useTourRevisionGuard.ts b/client/src/components/Tours/planner/useTourRevisionGuard.ts
new file mode 100644
index 000000000..45e91ec64
--- /dev/null
+++ b/client/src/components/Tours/planner/useTourRevisionGuard.ts
@@ -0,0 +1,70 @@
+import { TOUR_REVISION_CONFLICT } from '@trek/shared';
+import { isAxiosError } from 'axios';
+import { useCallback, useRef, useState } from 'react';
+
+/** The revision a refused save names, read off its 409; null for any other failure. */
+export function revisionConflictOf(error: unknown): number | null {
+ if (!isAxiosError(error) || error.response?.status !== 409) return null;
+ const body = error.response.data as { code?: unknown; revision?: unknown } | undefined;
+ return body?.code === TOUR_REVISION_CONFLICT && Number.isInteger(body.revision) ? Number(body.revision) : null;
+}
+
+/**
+ * P2C-03 in the planner: the revision the open tour was loaded at, which a
+ * save names so the server refuses it once someone else saved the tour, and
+ * what is known about such a change.
+ *
+ * - `conflict`: a save was refused; the draft is kept until the planner
+ * chooses to load the newer tour, save the draft as a tour of its own, or
+ * save it over the newer one on purpose.
+ * - `remote`: the trip's tours say someone saved this tour meanwhile, known
+ * before any save. A planner without changes simply loads it again.
+ *
+ * The base lives in a ref as well, so a save started in the same tick as the
+ * choice to overwrite names the revision just taken over.
+ */
+export function useTourRevisionGuard(initial: number | null = null) {
+ const [base, setBase] = useState<number | null>(initial);
+ const baseRef = useRef<number | null>(initial);
+ const [conflict, setConflict] = useState<{ revision: number } | null>(null);
+ const [remote, setRemote] = useState<number | null>(null);
+
+ /** The revision the planner now works from; null for a new tour. Clears what was known about others. */
+ const adopt = useCallback((revision: number | null | undefined) => {
+ baseRef.current = revision ?? null;
+ setBase(revision ?? null);
+ setConflict(null);
+ setRemote(null);
+ }, []);
+
+ /** The trip's tours list this tour at `revision`: newer than the base means someone else saved it. */
+ const notice = useCallback((revision: number | null | undefined) => {
+ if (revision == null || baseRef.current == null || revision <= baseRef.current) return false;
+ setRemote(revision);
+ return true;
+ }, []);
+
+ /** A refused save; answers whether it was refused for the revision. */
+ const refuse = useCallback((error: unknown) => {
+ const revision = revisionConflictOf(error);
+ if (revision === null) return false;
+ setConflict({ revision });
+ setRemote(null);
+ return true;
+ }, []);
+
+ /** The choice to save over the newer tour: the next save names the revision it saw. */
+ const takeOver = useCallback(() => {
+ if (!conflict) return;
+ baseRef.current = conflict.revision;
+ setBase(conflict.revision);
+ setConflict(null);
+ }, [conflict]);
+
+ const dismissConflict = useCallback(() => setConflict(null), []);
+ const dismissRemote = useCallback(() => setRemote(null), []);
+
+ return { base, baseRef, conflict, remote, adopt, notice, refuse, takeOver, dismissConflict, dismissRemote };
+}
+
+export type TourRevisionGuard = ReturnType<typeof useTourRevisionGuard>;
diff --git a/client/src/components/Tours/planner/useTourRevisionWatch.ts b/client/src/components/Tours/planner/useTourRevisionWatch.ts
new file mode 100644
index 000000000..5cb9d179a
--- /dev/null
+++ b/client/src/components/Tours/planner/useTourRevisionWatch.ts
@@ -0,0 +1,29 @@
+import type { TourListItem } from '@trek/shared';
+import { useEffect } from 'react';
+import { useTranslation } from '../../../i18n';
+import { useToast } from '../../shared/Toast';
+import type { TourPlannerController } from './useTourPlanner';
+
+/**
+ * P2C-03, live: the trip's tours follow every save over the websocket, so a
+ * newer revision of the tour open in the editor means someone else saved it.
+ * An editor without changes of its own loads it again at once and says so; an
+ * editor with changes keeps them and shows the notice (TourRemoteChangeNotice),
+ * and its save asks what to do instead of overwriting.
+ */
+export function useTourRevisionWatch(planner: TourPlannerController, tours: readonly TourListItem[]) {
+ const { t } = useTranslation();
+ const toast = useToast();
+ const placeId = planner.mode.type === 'edit-saved' ? planner.mode.placeId : null;
+ const listed = placeId === null ? undefined : tours.find((tour) => tour.place_id === placeId)?.revision;
+ const { notice } = planner.revision;
+ const { hasUnsavedChanges, isSaving, openTour } = planner;
+
+ useEffect(() => {
+ if (placeId === null || isSaving || !notice(listed)) return;
+ if (hasUnsavedChanges) return;
+ void openTour({ place_id: placeId }).then((opened) => {
+ if (opened) toast.info(t('tours.revision.reloaded'));
+ });
+ }, [hasUnsavedChanges, isSaving, listed, notice, openTour, placeId, t, toast]);
+}
diff --git a/client/src/pages/tripPlanner/useTourWorkspace.ts b/client/src/pages/tripPlanner/useTourWorkspace.ts
index 05f5869d3..8eb79efe8 100644
--- a/client/src/pages/tripPlanner/useTourWorkspace.ts
+++ b/client/src/pages/tripPlanner/useTourWorkspace.ts
@@ -4,6 +4,7 @@ import { useGpxConversion } from '../../components/Tours/conversion/useGpxConver
import { usePaddleChecklist } from '../../components/Tours/paddle/usePaddleChecklist';
import { useTrackPaddlePlan } from '../../components/Tours/paddle/useTrackPaddlePlan';
import { useTourPlanner } from '../../components/Tours/planner/useTourPlanner';
+import { useTourRevisionWatch } from '../../components/Tours/planner/useTourRevisionWatch';
import { useRecordedTrack } from '../../components/Tours/useRecordedTrack';
import { useTourGpxImport } from '../../components/Tours/useTourGpxImport';
import { useWandererBrowser } from '../../components/Tours/wanderer/useWandererBrowser';
@@ -52,6 +53,9 @@ export function useTourWorkspace(
},
});
+ // P2C-03: someone else saved the tour open in the editor; the trip's tours follow every save live.
+ useTourRevisionWatch(tourPlanner, tours);
+
// A tour of the trip opened in the planner: an import has no waypoints of its own and
// shows as it came in, a planned tour opens in the editor. Never over an edit it would
// replace.
diff --git a/client/src/repo/tourRepo.test.ts b/client/src/repo/tourRepo.test.ts
index 04fb891ba..611cbb783 100644
--- a/client/src/repo/tourRepo.test.ts
+++ b/client/src/repo/tourRepo.test.ts
@@ -225,6 +225,27 @@ describe('tourRepo.update', () => {
})
})
+describe('tourRepo writes and the revision (P2C-03)', () => {
+ it('FE-REPO-TOUR-030: online, the revision the draft was based on goes along; queued, it stays behind', async () => {
+ let sentBody: Record<string, unknown> | null = null
+ server.use(http.put('/api/trips/3/tours/40', async ({ request }) => {
+ sentBody = await request.json() as Record<string, unknown>
+ return HttpResponse.json({ tour: tour({ revision: 5 }), waypoints: body.waypoints })
+ }))
+ const online = await tourRepo.update(3, 40, { ...body, expected_revision: 4 })
+ expect(sentBody).toMatchObject({ expected_revision: 4 })
+ expect(online.tour.revision).toBe(5)
+
+ setOnline(false)
+ await tourRepo.update(3, 40, { ...body, expected_revision: 5 })
+ await offlineDb.tours.put({ ...tour({ tour_type: 'kayak', has_waypoints: false }), trip_id: 3 })
+ await tourRepo.updatePaddlePlan(3, 40, { paddle_speed_kmh: 4, portage_speed_kmh: null, track_marks: { portages: [], locks: [] }, expected_revision: 5 })
+ const queued = await offlineDb.mutationQueue.toArray()
+ expect(queued).toHaveLength(2)
+ for (const mutation of queued) expect(mutation.body).not.toHaveProperty('expected_revision')
+ })
+})
+
describe('replaceTripTours', () => {
it('FE-REPO-TOUR-013: keeps control points only while the route reads the same, drops what the server no longer lists, keeps unsynced tours', async () => {
await offlineDb.tours.bulkPut([
diff --git a/client/src/repo/tourRepo.ts b/client/src/repo/tourRepo.ts
index 4c2084d80..2e418c9c0 100644
--- a/client/src/repo/tourRepo.ts
+++ b/client/src/repo/tourRepo.ts
@@ -28,6 +28,17 @@ function staleCheck(tour: CachedTour, mutationId: string): CachedTour {
return tour.paddle_check ? { ...tour, paddle_check: { ...tour.paddle_check, revision: `local:${mutationId}` } } : tour
}
+/**
+ * P2C-03: a write that waits in the queue goes without the revision its draft
+ * was based on. By the time it replays the revision is history (an earlier
+ * queued write of this device raised it), and the queue has no way to ask the
+ * user about a tour that moved on; queued tour writes land as they always did.
+ */
+function withoutRevisionBase<T extends { expected_revision?: number | null }>(body: T): Omit<T, 'expected_revision'> {
+ const { expected_revision: _base, ...rest } = body
+ return rest
+}
+
/** Newest first, as the server lists them: offline creates (negative ids) on top. */
function newestFirst(a: CachedTour, b: CachedTour): number {
if ((a.place_id < 0) !== (b.place_id < 0)) return a.place_id < 0 ? -1 : 1
@@ -192,7 +203,7 @@ export const tourRepo = {
tripId: tid,
method: 'PUT',
url: isTemp ? `/trips/${tripId}/tours/{id}` : `/trips/${tripId}/tours/${placeId}`,
- body,
+ body: withoutRevisionBase(body),
resource: 'tours',
entityId: placeId,
...(isTemp ? { tempEntityId: placeId } : {}),
@@ -236,7 +247,7 @@ export const tourRepo = {
tripId: tid,
method: 'PUT',
url: `/trips/${tripId}/tours/${placeId}/paddle-plan`,
- body,
+ body: withoutRevisionBase(body),
resource: 'tours',
entityId: placeId,
})
@@ -255,10 +266,6 @@ export const tourRepo = {
return result
},
- /**
- * P2C-07, online only like the restore: the copy is made from the server's
- * stored line and control points, so it needs the server to answer.
- */
/**
* PR1-06A: the saved tour as the GPX file the server writes. Online only on
* purpose, since the file is the server's; offline it answers `offline`
@@ -273,6 +280,10 @@ export const tourRepo = {
return { offline: false, ...(await tourGpxExportApi.download(tripId, placeId, signal)) }
},
+ /**
+ * P2C-07, online only like the restore: the copy is made from the server's
+ * stored line and control points, so it needs the server to answer.
+ */
async copy(tripId: number | string, placeId: number, name: string): Promise<TourCreateResponse> {
const result = await tourCopiesApi.copy(tripId, placeId, { name })
await cacheTourAnswer(Number(tripId), result)
diff --git a/server/src/db/entities/Tours.entity.ts b/server/src/db/entities/Tours.entity.ts
index 5ed2837de..cdd808189 100644
--- a/server/src/db/entities/Tours.entity.ts
+++ b/server/src/db/entities/Tours.entity.ts
@@ -34,6 +34,7 @@ export class Tours {
portage_speed_kmh?: number | null;
track_marks?: string | null;
paddle_lake_style?: TToursPaddleLakeStyle | null;
+ revision: number & Opt = 1;
tourTypeRef!: Ref<TourTypes>;
tour_obstacle_reviews_collection = new Collection<TourObstacleReviews>(this);
tour_sources: Ref<TourSources> | null = null;
@@ -81,6 +82,7 @@ export const ToursSchema = defineEntity({
properties: ['derived_from_place_id'],
},
],
+ checks: [{ name: 'tours_revision_check', expression: 'revision >= 1' }],
properties: {
place: () => p.oneToOne(Places).primary().ref().deleteRule('cascade').nullable().hidden(),
place_id: p.integer().nullable().persist(false),
@@ -107,6 +109,7 @@ export const ToursSchema = defineEntity({
portage_speed_kmh: p.double().nullable(),
track_marks: p.text().nullable(),
paddle_lake_style: p.enum(() => ToursPaddleLakeStyle).nullable(),
+ revision: p.integer().default(1),
tourTypeRef: () => p.manyToOne(TourTypes).ref().joinColumn('tour_type').hidden().index('idx_tours_tour_type'),
tour_obstacle_reviews_collection: () => p.oneToMany(TourObstacleReviews).mappedBy('place').hidden(),
tour_sources: () => p.oneToOne(TourSources).ref().mappedBy('place').hidden(),
diff --git a/server/src/db/kysely/Tours.table.ts b/server/src/db/kysely/Tours.table.ts
index 7be41ce6f..b22cdb9f2 100644
--- a/server/src/db/kysely/Tours.table.ts
+++ b/server/src/db/kysely/Tours.table.ts
@@ -26,4 +26,5 @@ export interface ToursTable {
portage_speed_kmh: InsertOptional<number | null>;
track_marks: InsertOptional<string | null>;
paddle_lake_style: InsertOptional<string | null>;
+ revision: InsertOptional<number>;
}
diff --git a/server/src/db/migrations/Migration20200101044800_a_tour_counts_its_revisions.ts b/server/src/db/migrations/Migration20200101044800_a_tour_counts_its_revisions.ts
new file mode 100644
index 000000000..2a18d7e83
--- /dev/null
+++ b/server/src/db/migrations/Migration20200101044800_a_tour_counts_its_revisions.ts
@@ -0,0 +1,16 @@
+import { Migration } from '@mikro-orm/migrations';
+
+/**
+ * P2C-03: the technical revision of a saved tour, raised by every write that
+ * changes it. A write that names the revision it was based on is refused
+ * while the tour has moved on, so a stale draft never overwrites a newer one
+ * unseen. Every tour there is starts at 1; it is not the version of a source
+ * a tour was imported from, which `tour_sources` keeps apart.
+ */
+export class Migration20200101044800_a_tour_counts_its_revisions extends Migration {
+ override name = 'Migration20200101044800_a_tour_counts_its_revisions';
+
+ override up(): void {
+ this.addSql('ALTER TABLE tours ADD COLUMN revision INTEGER NOT NULL DEFAULT 1 CHECK (revision >= 1)');
+ }
+}
diff --git a/server/src/db/repositories/Tours.repository.ts b/server/src/db/repositories/Tours.repository.ts
index c98608429..d19aa4a6d 100644
--- a/server/src/db/repositories/Tours.repository.ts
+++ b/server/src/db/repositories/Tours.repository.ts
@@ -38,6 +38,8 @@ export interface TourListRow {
has_recorded_track: number;
planned: number;
has_waypoints: number;
+ /** P2C-03: the tour's technical revision. */
+ revision: number;
}
/** Every `tours` column, as the trip copy reads and re-inserts it. */
@@ -65,6 +67,7 @@ export interface TourRow {
portage_speed_kmh: number | null;
paddle_lake_style: string | null;
track_marks: string | null;
+ revision: number;
}
const _tourRowKeys: AssertRowKeys<TourRow, Tours> = true;
@@ -200,6 +203,7 @@ export class ToursRepository extends TrekRepository<Tours> {
't.portage_speed_kmh as portage_speed_kmh',
't.paddle_lake_style as paddle_lake_style',
't.track_marks as track_marks',
+ 't.revision as revision',
eb('t.recorded_route_geometry', 'is not', null).as('has_recorded_track'),
eb
.exists(eb.selectFrom('day_assignments as da').select('da.id').whereRef('da.place_id', '=', 'p.id'))
@@ -478,10 +482,38 @@ export class ToursRepository extends TrekRepository<Tours> {
...row,
place_id,
derived_from_place_id: derivedFrom === null ? null : (copiedPlaceIds.get(derivedFrom) ?? null),
+ // A copy is a tour of its own, not a revision of the one it came from.
+ revision: 1,
})
.execute();
}
+ /**
+ * P2C-03: raises the tour's revision by one and answers the new one. Given
+ * the revision a write was based on, only that revision is raised, so a
+ * write against a tour that moved on meanwhile changes nothing and answers
+ * null. Runs inside the write's transaction, as the first change it makes.
+ */
+ async advanceRevision(place_id: number, expected?: number | null): Promise<number | null> {
+ let query = this.db()
+ .updateTable('tours')
+ .set((eb) => ({ revision: eb('revision', '+', 1) }))
+ .where('place_id', '=', place_id);
+ if (expected != null) query = query.where('revision', '=', expected);
+ const row = await query.returning('revision').executeTakeFirst();
+ return row?.revision ?? null;
+ }
+
+ /** The tour's current revision, `undefined` when the place is no tour. */
+ async revisionOf(place_id: number): Promise<number | undefined> {
+ const row = await this.db()
+ .selectFrom('tours')
+ .select('revision')
+ .where('place_id', '=', place_id)
+ .executeTakeFirst();
+ return row?.revision;
+ }
+
/**
* TO9 — `UPDATE tours SET tour_type = ?, distance = ?, ... WHERE place_id =
* ? AND place_id IN (SELECT id FROM places WHERE trip_id = ?)`. Returns
diff --git a/server/src/nest/tours/tour-paddle-plan.service.ts b/server/src/nest/tours/tour-paddle-plan.service.ts
index 3873553a1..7e73842bd 100644
--- a/server/src/nest/tours/tour-paddle-plan.service.ts
+++ b/server/src/nest/tours/tour-paddle-plan.service.ts
@@ -8,6 +8,7 @@ import { DomainError } from '../common/domain-error';
import { toRowId } from '../common/row-id';
import { UnitOfWork } from '../database/unit-of-work';
import { PlacesService } from '../places/places.service';
+import { advanceTourRevision } from './tour-revision';
import { computeTourMetrics, parseRouteGeometry } from './tours.helpers';
import { ToursService } from './tours.service';
import { InjectRepository } from '@mikro-orm/nestjs';
@@ -91,6 +92,7 @@ export class TourPaddlePlanService {
});
const moving = paddleMovingSeconds(estimate);
const empty = marks.portages.length === 0 && marks.locks.length === 0;
+ await advanceTourRevision(this.toursRepo, pid, input.expected_revision);
await this.toursRepo.updatePaddlePlanInTrip(tid, pid, {
paddle_speed_kmh: input.paddle_speed_kmh,
portage_speed_kmh: input.portage_speed_kmh,
diff --git a/server/src/nest/tours/tour-revision.ts b/server/src/nest/tours/tour-revision.ts
new file mode 100644
index 000000000..d947a65dd
--- /dev/null
+++ b/server/src/nest/tours/tour-revision.ts
@@ -0,0 +1,29 @@
+import type { ToursRepository } from '../../db/repositories/Tours.repository';
+import { DomainError } from '../common/domain-error';
+import { NotFoundException } from '@nestjs/common';
+import { TOUR_REVISION_CONFLICT } from '@trek/shared';
+
+/**
+ * P2C-03: the one revision contract of a saved tour. Every write that changes
+ * a tour (its route and controls, the plan laid onto a recorded track, going
+ * back to that track) raises the revision inside its own transaction through
+ * here, before anything else of it is written. A write naming the revision it
+ * was based on is refused with a 409 while the tour has moved on, so a stale
+ * draft never overwrites a newer tour unseen; a write naming none writes as
+ * before. A copy starts at 1, and the version of an imported source is its
+ * provenance, never this.
+ */
+export async function advanceTourRevision(
+ toursRepo: ToursRepository,
+ placeId: number,
+ expected?: number | null,
+): Promise<number> {
+ const next = await toursRepo.advanceRevision(placeId, expected);
+ if (next !== null) return next;
+ const current = await toursRepo.revisionOf(placeId);
+ if (current === undefined) throw new NotFoundException('Tour not found');
+ throw new DomainError(409, 'This tour was changed in the meantime', {
+ code: TOUR_REVISION_CONFLICT,
+ details: { code: TOUR_REVISION_CONFLICT, revision: current },
+ });
+}
diff --git a/server/src/nest/tours/tours.mcp.ts b/server/src/nest/tours/tours.mcp.ts
index 74fc0db42..d1700feaa 100644
--- a/server/src/nest/tours/tours.mcp.ts
+++ b/server/src/nest/tours/tours.mcp.ts
@@ -48,7 +48,7 @@ export class ToursMcp {
@Tool({
name: 'list_tours',
description:
- 'List the saved tours of a trip (hikes and paddle tours planned or imported in the Tours addon): name, type (hike, or kayak for a paddle tour), where it came from (origin: trek, gpx or wanderer), distance in km, ascent and descent in metres, the stored routing limit of a hike (max_hiking_difficulty, SAC T1 to T6), the boat, water and chosen speed of a paddle tour (boat_type, water_context, paddle_speed_kmh in km/h, null while the suggested speed of the boat applies), the check bench of a paddle tour (paddle_check: how far the OpenStreetMap obstacle data covers its line and how many obstacles are open, to check again or decided by the travellers; a planning status, never a safety or legal clearance), and the days of the trip each tour is on.',
+ 'List the saved tours of a trip (hikes and paddle tours planned or imported in the Tours addon): name, type (hike, or kayak for a paddle tour), where it came from (origin: trek, gpx or wanderer), distance in km, ascent and descent in metres, the stored routing limit of a hike (max_hiking_difficulty, SAC T1 to T6), the boat, water and chosen speed of a paddle tour (boat_type, water_context, paddle_speed_kmh in km/h, null while the suggested speed of the boat applies), the check bench of a paddle tour (paddle_check: how far the OpenStreetMap obstacle data covers its line and how many obstacles are open, to check again or decided by the travellers; a planning status, never a safety or legal clearance), the revision (raised by every saved change of the tour), and the days of the trip each tour is on.',
inputSchema: { tripId: idSchema },
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.TOURS),
diff --git a/server/src/nest/tours/tours.service.ts b/server/src/nest/tours/tours.service.ts
index a7a1655be..94a64d985 100644
--- a/server/src/nest/tours/tours.service.ts
+++ b/server/src/nest/tours/tours.service.ts
@@ -20,6 +20,7 @@ import { UnitOfWork } from '../database/unit-of-work';
import { PlaceImportService } from '../place-import/place-import.service';
import { PlacesService } from '../places/places.service';
import { TourPaddleCheckService } from './tour-paddle-check.service';
+import { advanceTourRevision } from './tour-revision';
import {
computeTourMetrics,
localHashOf,
@@ -110,6 +111,7 @@ export class ToursService {
planned: Boolean(r.planned),
caution: r.match_confidence !== null && r.match_confidence < LOW_CONFIDENCE_THRESHOLD,
has_waypoints: Boolean(r.has_waypoints),
+ revision: r.revision,
};
}
@@ -346,6 +348,7 @@ export class ToursService {
details: { code: 'no_recorded_track' },
});
const metrics = computeTourMetrics(geometry);
+ await advanceTourRevision(this.toursRepo, pid);
await this.placesRepo.updateTourRoute(pid, tid, {
name: row.name,
lat: start[0],
@@ -478,6 +481,8 @@ export class ToursService {
// one, and a place deleted meanwhile answers 404 instead of failing a
// waypoint insert on its foreign key.
if (!(await this.toursRepo.findInTrip(tid, pid))) throw new NotFoundException('Tour not found');
+ // P2C-03: refused here, before anything is written, while the draft's tour has moved on.
+ await advanceTourRevision(this.toursRepo, pid, input.expected_revision);
// An import planned over for the first time keeps the track it was recorded with.
await this.toursRepo.keepRecordedTrack(pid);
const placeUpdated = await this.placesRepo.updateTourRoute(pid, tid, {
@@ -589,6 +594,7 @@ export class ToursService {
has_recorded_track: 0,
planned: 0,
has_waypoints: 0,
+ revision: 1,
}),
);
}
diff --git a/server/tests/e2e/tours-planned.e2e.test.ts b/server/tests/e2e/tours-planned.e2e.test.ts
index 98abe2f06..7bf4f59b0 100644
--- a/server/tests/e2e/tours-planned.e2e.test.ts
+++ b/server/tests/e2e/tours-planned.e2e.test.ts
@@ -8,7 +8,6 @@
* Fixtures: user 1 owns trips 5 and 6, user 2 is a member of trip 5 whom the
* permission spy denies 'place_edit', user 3 has no access to either trip.
*/
-import { db } from '../../src/db/database';
import { DayAssignments } from '../../src/db/entities/DayAssignments.entity';
import { Places } from '../../src/db/entities/Places.entity';
import { Tours } from '../../src/db/entities/Tours.entity';
@@ -20,6 +19,7 @@ import { PermissionsService } from '../../src/nest/permissions/permissions.servi
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
import { ToursModule } from '../../src/nest/tours/tours.module';
+import { createSnapshotTestDb } from '../helpers/db-mock';
import { makePlace } from '../helpers/factories/places';
import { deleteRows, findRow, insertRows } from '../helpers/factories/rows';
import { setAddonEnabled } from '../helpers/factories/settings';
@@ -37,10 +37,6 @@ import type { Server } from 'http';
import request from 'supertest';
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi, type MockInstance } from 'vitest';
-vi.mock('../../src/db/database', async () => {
- const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
- return buildDbMock(createSnapshotTestDb());
-});
vi.mock('../../src/nest/audit/audit-log.logger', () => ({
LOG_LEVEL: 'error',
logInfo: vi.fn(),
@@ -58,6 +54,7 @@ const { journeyHooks } = vi.hoisted(() => ({
},
}));
+const db = createSnapshotTestDb();
const realtime = new FakeRealtimeService();
let orm: TestOrm;
@@ -251,4 +248,105 @@ describe('Tours planned e2e (real guards + temp SQLite)', () => {
expect(off.body).toEqual({ error: 'Tours addon is not enabled' });
});
});
+
+ describe('revisions and conflicts (P2C-03)', () => {
+ const put = (placeId: number, body: Record<string, unknown>) =>
+ request(server).put(`/api/trips/5/tours/${placeId}`).set('Cookie', sessionCookie(OWNER)).send(body);
+
+ it('a tour starts at 1, and every saved change raises it by one, in the list and the detail', async () => {
+ const placeId = await createViaApi();
+ const detail = await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', sessionCookie(OWNER));
+ expect(detail.body.tour.revision).toBe(1);
+
+ const saved = await put(placeId, tourBody({ name: 'Renamed', expected_revision: 1 }));
+ expect(saved.status).toBe(200);
+ expect(saved.body.tour).toMatchObject({ name: 'Renamed', revision: 2 });
+ const list = await request(server).get('/api/trips/5/tours').set('Cookie', sessionCookie(OWNER));
+ expect(list.body.tours[0].revision).toBe(2);
+ });
+
+ it('409 for a draft based on a revision the tour has left, and nothing of it is written', async () => {
+ const placeId = await createViaApi();
+ expect((await put(placeId, tourBody({ name: 'First', expected_revision: 1 }))).status).toBe(200);
+ realtime.broadcastMock.mockClear();
+
+ const stale = await put(
+ placeId,
+ tourBody({
+ name: 'Stale',
+ expected_revision: 1,
+ waypoints: [
+ { lat: 47, lng: 11, role: 'start', sequence: 0 },
+ { lat: 47.01, lng: 11.01, role: 'via', sequence: 1 },
+ { lat: 47.02, lng: 11.02, role: 'end', sequence: 2 },
+ ],
+ }),
+ );
+ expect(stale.status).toBe(409);
+ expect(stale.body).toEqual({
+ error: 'This tour was changed in the meantime',
+ code: 'tour_revision_conflict',
+ revision: 2,
+ });
+ const after = await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', sessionCookie(OWNER));
+ expect(after.body.tour).toMatchObject({ name: 'First', revision: 2 });
+ expect(after.body.waypoints).toHaveLength(2);
+ expect(realtime.broadcastMock).not.toHaveBeenCalled();
+ });
+
+ it('a write naming no revision writes as before, so an older client or a queued write still lands', async () => {
+ const placeId = await createViaApi();
+ expect((await put(placeId, tourBody({ name: 'One', expected_revision: 1 }))).status).toBe(200);
+ const blind = await put(placeId, tourBody({ name: 'Two' }));
+ expect(blind.status).toBe(200);
+ expect(blind.body.tour).toMatchObject({ name: 'Two', revision: 3 });
+ });
+
+ it('a copy starts at 1 of its own, and the original keeps its count', async () => {
+ const placeId = await createViaApi();
+ await put(placeId, tourBody({ expected_revision: 1 }));
+ const copy = await request(server)
+ .post(`/api/trips/5/tours/${placeId}/copy`)
+ .set('Cookie', sessionCookie(OWNER))
+ .send({ name: 'Copy' });
+ expect(copy.status).toBe(201);
+ expect(copy.body.tour.revision).toBe(1);
+ expect((await findRow(orm, Tours, { place: placeId }))?.revision).toBe(2);
+ });
+
+ it('the plan laid onto a recorded paddle track names its revision too', async () => {
+ const place = await makePlace(orm, 5, {
+ name: 'Canal',
+ route_geometry: JSON.stringify([
+ [48, 12],
+ [48.01, 12.01],
+ ]),
+ });
+ await makeTour(orm, place.id, {
+ tourTypeRef: 'kayak',
+ boat_type: 'kayak',
+ water_context: 'river',
+ origin: 'gpx',
+ });
+ const plan = { paddle_speed_kmh: 5, portage_speed_kmh: null, track_marks: { portages: [], locks: [] } };
+ const putPlan = (body: Record<string, unknown>) =>
+ request(server)
+ .put(`/api/trips/5/tours/${place.id}/paddle-plan`)
+ .set('Cookie', sessionCookie(OWNER))
+ .send(body);
+
+ const first = await putPlan({ ...plan, expected_revision: 1 });
+ expect(first.status).toBe(200);
+ expect(first.body.tour.revision).toBe(2);
+ const stale = await putPlan({ ...plan, paddle_speed_kmh: 3, expected_revision: 1 });
+ expect(stale.status).toBe(409);
+ expect(stale.body).toMatchObject({ code: 'tour_revision_conflict', revision: 2 });
+ expect((await findRow(orm, Tours, { place: place.id }))?.paddle_speed_kmh).toBe(5);
+ });
+
+ it('rejects a revision below 1 at the boundary', async () => {
+ const placeId = await createViaApi();
+ expect((await put(placeId, tourBody({ expected_revision: 0 }))).status).toBe(400);
+ });
+ });
});
diff --git a/server/tests/unit/db/legacy-baseline.test.ts b/server/tests/unit/db/legacy-baseline.test.ts
index c6ef23fc7..58f5d4d34 100644
--- a/server/tests/unit/db/legacy-baseline.test.ts
+++ b/server/tests/unit/db/legacy-baseline.test.ts
@@ -59,6 +59,7 @@ const UNNUMBERED = [
'Migration20200101044500_a_tour_waypoint_can_shape_the_route',
'Migration20200101044600_a_paddle_tour_remembers_how_it_crosses_lakes',
'Migration20200101044700_paddle_water_data_loads_where_a_paddler_plans',
+ 'Migration20200101044800_a_tour_counts_its_revisions',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
diff --git a/server/tests/unit/db/repositories/Tours.repository.test.ts b/server/tests/unit/db/repositories/Tours.repository.test.ts
index 340c4def7..af48b3a71 100644
--- a/server/tests/unit/db/repositories/Tours.repository.test.ts
+++ b/server/tests/unit/db/repositories/Tours.repository.test.ts
@@ -99,6 +99,7 @@ describe('ToursRepository reads', () => {
paddle_lake_style: null,
track_marks: null,
has_recorded_track: 0,
+ revision: 1,
},
{
place_id: older.id,
@@ -127,6 +128,7 @@ describe('ToursRepository reads', () => {
paddle_lake_style: null,
track_marks: null,
has_recorded_track: 0,
+ revision: 1,
},
]);
expect((await repo.listForTrip(trip.id)).map((r) => r.place_id)).not.toContain(plain.id);
@@ -211,6 +213,7 @@ describe('ToursRepository writes', () => {
paddle_lake_style: null,
track_marks: null,
has_recorded_track: 0,
+ revision: 1,
});
});
@@ -289,14 +292,35 @@ describe('ToursRepository writes', () => {
portage_speed_kmh: null,
paddle_lake_style: null,
track_marks: null,
+ revision: 1,
},
]);
expect(await repo.listRowsForTrip(other.id)).toEqual([]);
+ // A copy is a tour of its own: every column comes along but the revision, which starts again at 1.
+ await repo.advanceRevision(source.id);
+ const [advanced] = await repo.listRowsForTrip(trip.id);
+ expect(advanced.revision).toBe(2);
const copy = createPlace(testDb, other.id);
- const { place_id: _sourceId, ...columns } = rows[0];
+ const { place_id: _sourceId, ...columns } = advanced;
await repo.insertCopy(copy.id, columns, new Map());
- expect(await repo.listRowsForTrip(other.id)).toEqual([{ ...rows[0], place_id: copy.id }]);
+ expect(await repo.listRowsForTrip(other.id)).toEqual([{ ...advanced, place_id: copy.id, revision: 1 }]);
+ });
+
+ it('TOURREPO-012: advanceRevision raises the revision, only from the one expected, and revisionOf reads it (P2C-03)', async () => {
+ const { trip } = fixture();
+ const place = createPlace(testDb, trip.id);
+ createTour(testDb, place.id);
+ expect(await repo.revisionOf(place.id)).toBe(1);
+ expect(await repo.advanceRevision(place.id)).toBe(2);
+ expect(await repo.advanceRevision(place.id, 2)).toBe(3);
+ // A write based on a revision the tour has left changes nothing.
+ expect(await repo.advanceRevision(place.id, 2)).toBeNull();
+ expect(await repo.revisionOf(place.id)).toBe(3);
+ expect(await repo.advanceRevision(place.id, null)).toBe(4);
+ const plain = createPlace(testDb, trip.id);
+ expect(await repo.advanceRevision(plain.id)).toBeNull();
+ expect(await repo.revisionOf(plain.id)).toBeUndefined();
});
it('TOURREPO-009: insertCopy points a planned tour at the copied import, and drops a link the copy has no import for', async () => {
diff --git a/server/tests/unit/nest/tour-revision.test.ts b/server/tests/unit/nest/tour-revision.test.ts
new file mode 100644
index 000000000..166e4ff2a
--- /dev/null
+++ b/server/tests/unit/nest/tour-revision.test.ts
@@ -0,0 +1,45 @@
+/**
+ * advanceTourRevision (P2C-03): the one revision contract every tour write runs
+ * inside its transaction. The SQL is covered by Tours.repository.test.ts and
+ * the routes by tours-planned.e2e.test.ts; this pins the three answers.
+ */
+import type { ToursRepository } from '../../../src/db/repositories/Tours.repository';
+import { DomainError } from '../../../src/nest/common/domain-error';
+import { advanceTourRevision } from '../../../src/nest/tours/tour-revision';
+import { NotFoundException } from '@nestjs/common';
+
+import { describe, expect, it, vi } from 'vitest';
+
+function repo(next: number | null, current: number | undefined) {
+ return {
+ advanceRevision: vi.fn(async () => next),
+ revisionOf: vi.fn(async () => current),
+ } as unknown as ToursRepository & {
+ advanceRevision: ReturnType<typeof vi.fn>;
+ revisionOf: ReturnType<typeof vi.fn>;
+ };
+}
+
+describe('advanceTourRevision', () => {
+ it('answers the raised revision and passes the expected one on', async () => {
+ const tours = repo(4, 4);
+ expect(await advanceTourRevision(tours, 7, 3)).toBe(4);
+ expect(tours.advanceRevision).toHaveBeenCalledWith(7, 3);
+ expect(tours.revisionOf).not.toHaveBeenCalled();
+ });
+
+ it('refuses a stale base with a 409 that names the revision the tour has now', async () => {
+ const refusal = await advanceTourRevision(repo(null, 5), 7, 3).catch((err: unknown) => err);
+ expect(refusal).toBeInstanceOf(DomainError);
+ expect((refusal as DomainError).getStatus()).toBe(409);
+ expect((refusal as DomainError).toBody()).toEqual({
+ error: 'This tour was changed in the meantime',
+ code: 'tour_revision_conflict',
+ revision: 5,
+ });
+ });
+
+ it('is a 404 when the tour went away meanwhile', async () => {
+ await expect(advanceTourRevision(repo(null, undefined), 7)).rejects.toBeInstanceOf(NotFoundException);
+ });
+});
diff --git a/server/tests/unit/nest/tours.controller.test.ts b/server/tests/unit/nest/tours.controller.test.ts
index 1741702fb..8003dc5b2 100644
--- a/server/tests/unit/nest/tours.controller.test.ts
+++ b/server/tests/unit/nest/tours.controller.test.ts
@@ -14,6 +14,7 @@ import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator'
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
import type { PlacesService } from '../../../src/nest/places/places.service';
+import type { TourGpxExportService } from '../../../src/nest/tours/tour-gpx-export.service';
import type { TourObstacleReviewsService } from '../../../src/nest/tours/tour-obstacle-reviews.service';
import type { TourPaddlePlanService } from '../../../src/nest/tours/tour-paddle-plan.service';
import { ToursImportController } from '../../../src/nest/tours/tours-import.controller';
@@ -102,6 +103,7 @@ function importFixture(
const paddlePlansStub = { update: vi.fn() } as unknown as TourPaddlePlanService;
const reviewsStub = { save: vi.fn() } as unknown as TourObstacleReviewsService;
+const gpxExportStub = { export: vi.fn() } as unknown as TourGpxExportService;
describe('ToursController planner routes', () => {
it('does not access the legacy global database initializer', () => {
@@ -136,7 +138,7 @@ describe('ToursController planner routes', () => {
it('TOURS-CTL-002: POST /tours delegates the validated payload and socket id', async () => {
const result = { tour: { place_id: 1 }, waypoints: request.waypoints };
const service = { createTour: vi.fn().mockResolvedValue(result) } as unknown as ToursService;
- const controller = new ToursController(service, paddlePlansStub, reviewsStub);
+ const controller = new ToursController(service, paddlePlansStub, reviewsStub, gpxExportStub);
expect(await controller.create('7', request, 'socket-1')).toBe(result);
expect(service.createTour).toHaveBeenCalledWith('7', request, 'socket-1');
@@ -145,7 +147,7 @@ describe('ToursController planner routes', () => {
it('TOURS-CTL-003: GET /tours/:placeId delegates within the guarded trip', async () => {
const result = { tour: { place_id: 1 }, waypoints: request.waypoints };
const service = { getTour: vi.fn().mockResolvedValue(result) } as unknown as ToursService;
- const controller = new ToursController(service, paddlePlansStub, reviewsStub);
+ const controller = new ToursController(service, paddlePlansStub, reviewsStub, gpxExportStub);
expect(await controller.detail('7', '1')).toBe(result);
expect(service.getTour).toHaveBeenCalledWith('7', '1');
@@ -154,7 +156,7 @@ describe('ToursController planner routes', () => {
it('TOURS-CTL-004: PUT /tours/:placeId delegates the validated payload and socket id', async () => {
const result = { tour: { place_id: 1 }, waypoints: request.waypoints };
const service = { updateTour: vi.fn().mockResolvedValue(result) } as unknown as ToursService;
- const controller = new ToursController(service, paddlePlansStub, reviewsStub);
+ const controller = new ToursController(service, paddlePlansStub, reviewsStub, gpxExportStub);
expect(await controller.update('7', '1', request, 'socket-2')).toBe(result);
expect(service.updateTour).toHaveBeenCalledWith('7', '1', request, 'socket-2');
@@ -163,7 +165,7 @@ describe('ToursController planner routes', () => {
it('TOURS-CTL-006: PUT /tours/:placeId/paddle-plan delegates the validated plan and socket id (PAD-03)', async () => {
const result = { tour: { place_id: 1 }, waypoints: [] };
const paddlePlans = { update: vi.fn().mockResolvedValue(result) } as unknown as TourPaddlePlanService;
- const controller = new ToursController({} as ToursService, paddlePlans, reviewsStub);
+ const controller = new ToursController({} as ToursService, paddlePlans, reviewsStub, gpxExportStub);
const plan = { paddle_speed_kmh: 4, portage_speed_kmh: null, track_marks: { portages: [], locks: [] } };
expect(await controller.updatePaddlePlan('7', '1', plan, 'socket-3')).toBe(result);
@@ -173,7 +175,7 @@ describe('ToursController planner routes', () => {
it('TOURS-CTL-007: PUT /tours/:placeId/obstacle-reviews delegates the changes with the user and socket id (PAD-06)', async () => {
const result = { tour: { place_id: 1 }, waypoints: [] };
const reviews = { save: vi.fn().mockResolvedValue(result) } as unknown as TourObstacleReviewsService;
- const controller = new ToursController({} as ToursService, paddlePlansStub, reviews);
+ const controller = new ToursController({} as ToursService, paddlePlansStub, reviews, gpxExportStub);
const body = { ops: [{ key: 'node/1', op: 'clear' as const, decision: null, note: null, basis: null }] };
expect(await controller.saveObstacleReviews('7', '1', body, { id: 4 } as User, 'socket-4')).toBe(result);
@@ -184,7 +186,9 @@ describe('ToursController planner routes', () => {
const tours = [{ place_id: 1 }];
const service = { listTours: vi.fn().mockResolvedValue(tours) } as unknown as ToursService;
- expect(await new ToursController(service, paddlePlansStub, reviewsStub).list('7')).toEqual({ tours });
+ expect(await new ToursController(service, paddlePlansStub, reviewsStub, gpxExportStub).list('7')).toEqual({
+ tours,
+ });
expect(service.listTours).toHaveBeenCalledWith('7');
});
});
diff --git a/server/tests/unit/nest/tours.permissions.boundaries.mock-only.test.ts b/server/tests/unit/nest/tours.permissions.boundaries.mock-only.test.ts
index 23c72b24e..51cc8af92 100644
--- a/server/tests/unit/nest/tours.permissions.boundaries.mock-only.test.ts
+++ b/server/tests/unit/nest/tours.permissions.boundaries.mock-only.test.ts
@@ -285,6 +285,7 @@ function tourRepositoryFixture(ownerTripId: number) {
),
updateInTrip: vi.fn(async () => true),
keepRecordedTrack: vi.fn(async () => undefined),
+ advanceRevision: vi.fn(async () => 2),
};
const waypointsRepo = {
listForPlace: vi.fn(async () => input.waypoints),
diff --git a/server/tests/unit/nest/tours.service.permissions.test.ts b/server/tests/unit/nest/tours.service.permissions.test.ts
index 347fe73ca..9a0040209 100644
--- a/server/tests/unit/nest/tours.service.permissions.test.ts
+++ b/server/tests/unit/nest/tours.service.permissions.test.ts
@@ -111,6 +111,7 @@ function makeService() {
insertTour: inTx(undefined),
updateInTrip: inTx(true),
keepRecordedTrack: inTx(undefined),
+ advanceRevision: inTx(2),
};
const waypointsRepo = {
listForPlace: vi.fn(async () => request.waypoints),
diff --git a/shared/src/i18n/ar/tours.ts b/shared/src/i18n/ar/tours.ts
index 52deeb169..659684abe 100644
--- a/shared/src/i18n/ar/tours.ts
+++ b/shared/src/i18n/ar/tours.ts
@@ -289,6 +289,19 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'يتطلب تنزيل ملف GPX اتصالًا بالخادم.',
'tours.gpxExport.noRoute': 'لا يوجد لهذه الجولة مسار محفوظ للتصدير.',
'tours.gpxExport.failed': 'تعذّر إنشاء ملف GPX.',
+ 'tours.revision.remoteTitle': 'حُفظت هذه الجولة في مكان آخر',
+ 'tours.revision.remoteBody': 'حفظها شخص ما، أو أنت على جهاز آخر، أثناء تعديلك. تبقى تغييراتك حتى تقرّر.',
+ 'tours.revision.loadNewer': 'تحميل الأحدث',
+ 'tours.revision.loadNewerTitle': 'تحميل النسخة الأحدث؟',
+ 'tours.revision.loadNewerBody': 'ستُلغى تغييراتك غير المحفوظة على هذه الجولة.',
+ 'tours.revision.conflictEyebrow': 'لم يُحفظ',
+ 'tours.revision.conflictTitle': 'تغيّرت في هذه الأثناء',
+ 'tours.revision.conflictBody':
+ 'حُفظت هذه الجولة في مكان آخر بعد أن فتحتها، لذا لم يُستبدل شيء. احفظ نسختك كجولة جديدة للاحتفاظ بالاثنتين، أو حمّل النسخة الأحدث، أو استبدلها عن قصد.',
+ 'tours.revision.overwrite': 'استبدال',
+ 'tours.revision.saveAsNew': 'حفظ كجولة جديدة',
+ 'tours.revision.mineName': '{name} (نسختي)',
+ 'tours.revision.reloaded': 'حُفظت هذه الجولة في مكان آخر وتظهر الآن نسختها الأحدث.',
'tours.planner.tourType': 'نوع الجولة',
'tours.paddle.boat': 'القارب',
'tours.paddle.boat.kayak': 'كاياك',
diff --git a/shared/src/i18n/az/tours.ts b/shared/src/i18n/az/tours.ts
index 3ade373b9..a27a21ea2 100644
--- a/shared/src/i18n/az/tours.ts
+++ b/shared/src/i18n/az/tours.ts
@@ -278,6 +278,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'GPX faylını endirmək üçün serverə bağlantı lazımdır.',
'tours.gpxExport.noRoute': 'Bu turun ixrac ediləcək saxlanmış marşrutu yoxdur.',
'tours.gpxExport.failed': 'GPX faylını yaratmaq olmadı.',
+ 'tours.revision.remoteTitle': 'Bu tur başqa yerdə saxlanıb',
+ 'tours.revision.remoteBody':
+ 'Siz redaktə edərkən kimsə və ya başqa cihazda siz özünüz onu saxladı. Dəyişiklikləriniz qərar verənə qədər qalır.',
+ 'tours.revision.loadNewer': 'Yenisini yüklə',
+ 'tours.revision.loadNewerTitle': 'Yeni versiya yüklənsin?',
+ 'tours.revision.loadNewerBody': 'Bu turdakı saxlanmamış dəyişiklikləriniz silinəcək.',
+ 'tours.revision.conflictEyebrow': 'Saxlanmadı',
+ 'tours.revision.conflictTitle': 'Bu arada dəyişib',
+ 'tours.revision.conflictBody':
+ 'Siz açandan sonra tur başqa yerdə saxlanıb, ona görə heç nə üzərinə yazılmayıb. Hər ikisini saxlamaq üçün özünüzünkünü yeni tur kimi saxlayın, yeni versiyanı yükləyin və ya bilərəkdən üzərinə yazın.',
+ 'tours.revision.overwrite': 'Üzərinə yaz',
+ 'tours.revision.saveAsNew': 'Yeni tur kimi saxla',
+ 'tours.revision.mineName': '{name} (mənim versiyam)',
+ 'tours.revision.reloaded': 'Bu tur başqa yerdə saxlanıb və indi yeni versiyası göstərilir.',
'tours.planner.tourType': 'Tur növü',
'tours.paddle.boat': 'Qayıq',
'tours.paddle.boat.kayak': 'Kayak', // same-as-en
diff --git a/shared/src/i18n/br/tours.ts b/shared/src/i18n/br/tours.ts
index 94df9112f..fd988d563 100644
--- a/shared/src/i18n/br/tours.ts
+++ b/shared/src/i18n/br/tours.ts
@@ -284,6 +284,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'Baixar um arquivo GPX exige conexão com o servidor.',
'tours.gpxExport.noRoute': 'Este passeio não tem uma rota salva para exportar.',
'tours.gpxExport.failed': 'Não foi possível criar o arquivo GPX.',
+ 'tours.revision.remoteTitle': 'Este passeio foi salvo em outro lugar',
+ 'tours.revision.remoteBody':
+ 'Alguém, ou você em outro aparelho, salvou enquanto você editava. Suas alterações ficam até você decidir.',
+ 'tours.revision.loadNewer': 'Carregar a mais nova',
+ 'tours.revision.loadNewerTitle': 'Carregar a versão mais nova?',
+ 'tours.revision.loadNewerBody': 'Suas alterações não salvas neste passeio serão descartadas.',
+ 'tours.revision.conflictEyebrow': 'Não salvo',
+ 'tours.revision.conflictTitle': 'Alterado nesse meio-tempo',
+ 'tours.revision.conflictBody':
+ 'O passeio foi salvo em outro lugar depois que você o abriu, então nada foi sobrescrito. Salve o seu como novo passeio para manter os dois, carregue a versão mais nova ou sobrescreva de propósito.',
+ 'tours.revision.overwrite': 'Sobrescrever',
+ 'tours.revision.saveAsNew': 'Salvar como novo passeio',
+ 'tours.revision.mineName': '{name} (minha versão)',
+ 'tours.revision.reloaded': 'Este passeio foi salvo em outro lugar e agora mostra a versão mais nova.',
'tours.planner.tourType': 'Tipo de passeio',
'tours.paddle.boat': 'Embarcação',
'tours.paddle.boat.kayak': 'Caiaque',
diff --git a/shared/src/i18n/ca/tours.ts b/shared/src/i18n/ca/tours.ts
index 3a916ffab..0825975c7 100644
--- a/shared/src/i18n/ca/tours.ts
+++ b/shared/src/i18n/ca/tours.ts
@@ -284,6 +284,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'Per baixar un fitxer GPX cal connexió amb el servidor.',
'tours.gpxExport.noRoute': 'Aquesta excursió no té cap ruta desada per exportar.',
'tours.gpxExport.failed': 'No s’ha pogut crear el fitxer GPX.',
+ 'tours.revision.remoteTitle': 'Aquesta excursió s’ha desat en un altre lloc',
+ 'tours.revision.remoteBody':
+ 'Algú, o tu en un altre dispositiu, l’ha desada mentre l’editaves. Els teus canvis es conserven fins que decideixis.',
+ 'tours.revision.loadNewer': 'Carrega la més nova',
+ 'tours.revision.loadNewerTitle': 'Vols carregar la versió més nova?',
+ 'tours.revision.loadNewerBody': 'Es descartaran els canvis no desats d’aquesta excursió.',
+ 'tours.revision.conflictEyebrow': 'No desat',
+ 'tours.revision.conflictTitle': 'Canviada mentrestant',
+ 'tours.revision.conflictBody':
+ 'L’excursió s’ha desat en un altre lloc després que l’obrissis, així que no s’ha sobreescrit res. Desa la teva com a nova excursió per conservar-les totes dues, carrega la versió més nova o sobreescriu-la expressament.',
+ 'tours.revision.overwrite': 'Sobreescriu',
+ 'tours.revision.saveAsNew': 'Desa com a nova excursió',
+ 'tours.revision.mineName': '{name} (la meva versió)',
+ 'tours.revision.reloaded': 'Aquesta excursió s’ha desat en un altre lloc i ara en mostra la versió més nova.',
'tours.planner.tourType': 'Tipus de ruta',
'tours.paddle.boat': 'Embarcació',
'tours.paddle.boat.kayak': 'Caiac',
diff --git a/shared/src/i18n/cs/tours.ts b/shared/src/i18n/cs/tours.ts
index 587fc3ccc..a2e249793 100644
--- a/shared/src/i18n/cs/tours.ts
+++ b/shared/src/i18n/cs/tours.ts
@@ -278,6 +278,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'Ke stažení souboru GPX je potřeba připojení k serveru.',
'tours.gpxExport.noRoute': 'Tato túra nemá uloženou trasu k exportu.',
'tours.gpxExport.failed': 'Soubor GPX se nepodařilo vytvořit.',
+ 'tours.revision.remoteTitle': 'Tato túra byla uložena jinde',
+ 'tours.revision.remoteBody':
+ 'Někdo, nebo ty na jiném zařízení, ji uložil, zatímco ji upravuješ. Tvoje změny zůstanou, dokud se nerozhodneš.',
+ 'tours.revision.loadNewer': 'Načíst novější',
+ 'tours.revision.loadNewerTitle': 'Načíst novější verzi?',
+ 'tours.revision.loadNewerBody': 'Neuložené změny této túry se zahodí.',
+ 'tours.revision.conflictEyebrow': 'Neuloženo',
+ 'tours.revision.conflictTitle': 'Mezitím změněno',
+ 'tours.revision.conflictBody':
+ 'Túra byla uložena jinde poté, co jsi ji otevřel, takže se nic nepřepsalo. Ulož svou jako novou túru a ponech si obě, načti novější verzi, nebo ji vědomě přepiš.',
+ 'tours.revision.overwrite': 'Přepsat',
+ 'tours.revision.saveAsNew': 'Uložit jako novou túru',
+ 'tours.revision.mineName': '{name} (moje verze)',
+ 'tours.revision.reloaded': 'Túra byla uložena jinde a teď zobrazuje novější verzi.',
'tours.planner.tourType': 'Typ túry',
'tours.paddle.boat': 'Loď',
'tours.paddle.boat.kayak': 'Kajak',
diff --git a/shared/src/i18n/de/tours.ts b/shared/src/i18n/de/tours.ts
index 610088c5c..209bbe193 100644
--- a/shared/src/i18n/de/tours.ts
+++ b/shared/src/i18n/de/tours.ts
@@ -286,6 +286,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'Für den GPX-Download braucht es eine Verbindung zum Server.',
'tours.gpxExport.noRoute': 'Diese Tour hat keine gespeicherte Route zum Exportieren.',
'tours.gpxExport.failed': 'Die GPX-Datei konnte nicht erstellt werden.',
+ 'tours.revision.remoteTitle': 'Diese Tour wurde woanders gespeichert',
+ 'tours.revision.remoteBody':
+ 'Jemand, oder du auf einem anderen Gerät, hat sie gespeichert, während du sie bearbeitest. Deine Änderungen bleiben, bis du entscheidest.',
+ 'tours.revision.loadNewer': 'Neuere laden',
+ 'tours.revision.loadNewerTitle': 'Neuere Fassung laden?',
+ 'tours.revision.loadNewerBody': 'Deine ungespeicherten Änderungen an dieser Tour werden verworfen.',
+ 'tours.revision.conflictEyebrow': 'Nicht gespeichert',
+ 'tours.revision.conflictTitle': 'Inzwischen geändert',
+ 'tours.revision.conflictBody':
+ 'Die Tour wurde woanders gespeichert, nachdem du sie geöffnet hast, deshalb wurde nichts überschrieben. Speichere deine als neue Tour, um beide zu behalten, lade die neuere Fassung oder überschreibe sie bewusst.',
+ 'tours.revision.overwrite': 'Überschreiben',
+ 'tours.revision.saveAsNew': 'Als neue Tour speichern',
+ 'tours.revision.mineName': '{name} (meine Fassung)',
+ 'tours.revision.reloaded': 'Diese Tour wurde woanders gespeichert und zeigt jetzt die neuere Fassung.',
'tours.planner.tourType': 'Tourtyp',
'tours.paddle.boat': 'Boot',
'tours.paddle.boat.kayak': 'Kajak',
diff --git a/shared/src/i18n/en/tours.ts b/shared/src/i18n/en/tours.ts
index 14289c46a..40911c7ff 100644
--- a/shared/src/i18n/en/tours.ts
+++ b/shared/src/i18n/en/tours.ts
@@ -277,6 +277,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'Downloading a GPX file needs a connection to the server.',
'tours.gpxExport.noRoute': 'This tour has no saved route to export.',
'tours.gpxExport.failed': 'The GPX file could not be created.',
+ 'tours.revision.remoteTitle': 'This tour was saved elsewhere',
+ 'tours.revision.remoteBody':
+ 'Someone, or you on another device, saved it while you were editing. Your changes are kept until you decide.',
+ 'tours.revision.loadNewer': 'Load newer',
+ 'tours.revision.loadNewerTitle': 'Load the newer version?',
+ 'tours.revision.loadNewerBody': 'Your unsaved changes to this tour will be discarded.',
+ 'tours.revision.conflictEyebrow': 'Not saved',
+ 'tours.revision.conflictTitle': 'Changed in the meantime',
+ 'tours.revision.conflictBody':
+ 'This tour was saved elsewhere after you opened it, so nothing was overwritten. Save yours as a new tour to keep both, load the newer version, or overwrite it on purpose.',
+ 'tours.revision.overwrite': 'Overwrite',
+ 'tours.revision.saveAsNew': 'Save as new tour',
+ 'tours.revision.mineName': '{name} (my version)',
+ 'tours.revision.reloaded': 'This tour was saved elsewhere and now shows its newer version.',
'tours.planner.tourType': 'Tour type',
'tours.paddle.boat': 'Boat',
'tours.paddle.boat.kayak': 'Kayak',
diff --git a/shared/src/i18n/es/tours.ts b/shared/src/i18n/es/tours.ts
index 61ab0f539..dbe8967d8 100644
--- a/shared/src/i18n/es/tours.ts
+++ b/shared/src/i18n/es/tours.ts
@@ -283,6 +283,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'Para descargar un archivo GPX hace falta conexión con el servidor.',
'tours.gpxExport.noRoute': 'Esta excursión no tiene una ruta guardada que exportar.',
'tours.gpxExport.failed': 'No se pudo crear el archivo GPX.',
+ 'tours.revision.remoteTitle': 'Esta excursión se guardó en otro lugar',
+ 'tours.revision.remoteBody':
+ 'Alguien, o tú en otro dispositivo, la guardó mientras la editabas. Tus cambios se mantienen hasta que decidas.',
+ 'tours.revision.loadNewer': 'Cargar la más reciente',
+ 'tours.revision.loadNewerTitle': '¿Cargar la versión más reciente?',
+ 'tours.revision.loadNewerBody': 'Se descartarán los cambios sin guardar de esta excursión.',
+ 'tours.revision.conflictEyebrow': 'No guardado',
+ 'tours.revision.conflictTitle': 'Cambiada mientras tanto',
+ 'tours.revision.conflictBody':
+ 'La excursión se guardó en otro lugar después de abrirla, así que no se sobrescribió nada. Guarda la tuya como nueva excursión para conservar ambas, carga la versión más reciente o sobrescríbela a propósito.',
+ 'tours.revision.overwrite': 'Sobrescribir',
+ 'tours.revision.saveAsNew': 'Guardar como nueva excursión',
+ 'tours.revision.mineName': '{name} (mi versión)',
+ 'tours.revision.reloaded': 'Esta excursión se guardó en otro lugar y ahora muestra su versión más reciente.',
'tours.planner.tourType': 'Tipo de ruta',
'tours.paddle.boat': 'Embarcación',
'tours.paddle.boat.kayak': 'Kayak', // same-as-en
diff --git a/shared/src/i18n/et/tours.ts b/shared/src/i18n/et/tours.ts
index 697583d70..6fe509078 100644
--- a/shared/src/i18n/et/tours.ts
+++ b/shared/src/i18n/et/tours.ts
@@ -280,6 +280,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'GPX-faili allalaadimiseks on vaja ühendust serveriga.',
'tours.gpxExport.noRoute': 'Sellel matkal pole eksportimiseks salvestatud marsruuti.',
'tours.gpxExport.failed': 'GPX-faili ei õnnestunud luua.',
+ 'tours.revision.remoteTitle': 'Seda matka salvestati mujal',
+ 'tours.revision.remoteBody':
+ 'Keegi või sina teises seadmes salvestas selle sinu muutmise ajal. Sinu muudatused jäävad alles, kuni otsustad.',
+ 'tours.revision.loadNewer': 'Laadi uuem',
+ 'tours.revision.loadNewerTitle': 'Kas laadida uuem versioon?',
+ 'tours.revision.loadNewerBody': 'Selle matka salvestamata muudatused visatakse ära.',
+ 'tours.revision.conflictEyebrow': 'Pole salvestatud',
+ 'tours.revision.conflictTitle': 'Vahepeal muudetud',
+ 'tours.revision.conflictBody':
+ 'Matk salvestati mujal pärast seda, kui sa selle avasid, seega midagi üle ei kirjutatud. Salvesta enda oma uue matkana, et mõlemad alles jääksid, laadi uuem versioon või kirjuta teadlikult üle.',
+ 'tours.revision.overwrite': 'Kirjuta üle',
+ 'tours.revision.saveAsNew': 'Salvesta uue matkana',
+ 'tours.revision.mineName': '{name} (minu versioon)',
+ 'tours.revision.reloaded': 'Seda matka salvestati mujal ja nüüd on näha uuem versioon.',
'tours.planner.tourType': 'Matka tüüp',
'tours.paddle.boat': 'Paat',
'tours.paddle.boat.kayak': 'Süst',
diff --git a/shared/src/i18n/fr/tours.ts b/shared/src/i18n/fr/tours.ts
index c6ad30b5b..da7dfa993 100644
--- a/shared/src/i18n/fr/tours.ts
+++ b/shared/src/i18n/fr/tours.ts
@@ -289,6 +289,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'Le téléchargement d’un fichier GPX nécessite une connexion au serveur.',
'tours.gpxExport.noRoute': 'Cette sortie n’a pas d’itinéraire enregistré à exporter.',
'tours.gpxExport.failed': 'Le fichier GPX n’a pas pu être créé.',
+ 'tours.revision.remoteTitle': 'Cette sortie a été enregistrée ailleurs',
+ 'tours.revision.remoteBody':
+ 'Quelqu’un, ou vous sur un autre appareil, l’a enregistrée pendant votre modification. Vos changements restent jusqu’à votre décision.',
+ 'tours.revision.loadNewer': 'Charger la plus récente',
+ 'tours.revision.loadNewerTitle': 'Charger la version plus récente ?',
+ 'tours.revision.loadNewerBody': 'Vos modifications non enregistrées de cette sortie seront abandonnées.',
+ 'tours.revision.conflictEyebrow': 'Non enregistré',
+ 'tours.revision.conflictTitle': 'Modifiée entre-temps',
+ 'tours.revision.conflictBody':
+ 'La sortie a été enregistrée ailleurs après son ouverture, donc rien n’a été écrasé. Enregistrez la vôtre comme nouvelle sortie pour garder les deux, chargez la version récente ou écrasez-la en connaissance de cause.',
+ 'tours.revision.overwrite': 'Écraser',
+ 'tours.revision.saveAsNew': 'Enregistrer comme nouvelle sortie',
+ 'tours.revision.mineName': '{name} (ma version)',
+ 'tours.revision.reloaded': 'Cette sortie a été enregistrée ailleurs et affiche maintenant sa version récente.',
'tours.planner.tourType': 'Type de sortie',
'tours.paddle.boat': 'Embarcation',
'tours.paddle.boat.kayak': 'Kayak', // same-as-en
diff --git a/shared/src/i18n/gr/tours.ts b/shared/src/i18n/gr/tours.ts
index c6e98d496..bc32de41d 100644
--- a/shared/src/i18n/gr/tours.ts
+++ b/shared/src/i18n/gr/tours.ts
@@ -290,6 +290,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'Η λήψη αρχείου GPX χρειάζεται σύνδεση με τον διακομιστή.',
'tours.gpxExport.noRoute': 'Αυτή η εκδρομή δεν έχει αποθηκευμένη διαδρομή για εξαγωγή.',
'tours.gpxExport.failed': 'Το αρχείο GPX δεν δημιουργήθηκε.',
+ 'tours.revision.remoteTitle': 'Αυτή η εκδρομή αποθηκεύτηκε αλλού',
+ 'tours.revision.remoteBody':
+ 'Κάποιος, ή εσείς σε άλλη συσκευή, την αποθήκευσε ενώ την επεξεργαζόσασταν. Οι αλλαγές σας μένουν μέχρι να αποφασίσετε.',
+ 'tours.revision.loadNewer': 'Φόρτωση νεότερης',
+ 'tours.revision.loadNewerTitle': 'Φόρτωση της νεότερης έκδοσης;',
+ 'tours.revision.loadNewerBody': 'Οι μη αποθηκευμένες αλλαγές σας σε αυτή την εκδρομή θα απορριφθούν.',
+ 'tours.revision.conflictEyebrow': 'Δεν αποθηκεύτηκε',
+ 'tours.revision.conflictTitle': 'Άλλαξε στο μεταξύ',
+ 'tours.revision.conflictBody':
+ 'Η εκδρομή αποθηκεύτηκε αλλού αφού την ανοίξατε, οπότε τίποτα δεν αντικαταστάθηκε. Αποθηκεύστε τη δική σας ως νέα εκδρομή για να κρατήσετε και τις δύο, φορτώστε τη νεότερη έκδοση ή αντικαταστήστε τη συνειδητά.',
+ 'tours.revision.overwrite': 'Αντικατάσταση',
+ 'tours.revision.saveAsNew': 'Αποθήκευση ως νέα εκδρομή',
+ 'tours.revision.mineName': '{name} (η δική μου έκδοση)',
+ 'tours.revision.reloaded': 'Η εκδρομή αποθηκεύτηκε αλλού και τώρα δείχνει τη νεότερη έκδοση.',
'tours.planner.tourType': 'Τύπος διαδρομής',
'tours.paddle.boat': 'Σκάφος',
'tours.paddle.boat.kayak': 'Καγιάκ',
diff --git a/shared/src/i18n/hu/tours.ts b/shared/src/i18n/hu/tours.ts
index 7dd9aff78..40477da39 100644
--- a/shared/src/i18n/hu/tours.ts
+++ b/shared/src/i18n/hu/tours.ts
@@ -284,6 +284,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'A GPX-fájl letöltéséhez kapcsolat kell a szerverrel.',
'tours.gpxExport.noRoute': 'Ennek a túrának nincs exportálható mentett útvonala.',
'tours.gpxExport.failed': 'A GPX-fájlt nem sikerült létrehozni.',
+ 'tours.revision.remoteTitle': 'Ezt a túrát máshol mentették',
+ 'tours.revision.remoteBody':
+ 'Valaki, vagy te egy másik eszközön, elmentette, miközben szerkesztetted. A módosításaid megmaradnak, amíg nem döntesz.',
+ 'tours.revision.loadNewer': 'Újabb betöltése',
+ 'tours.revision.loadNewerTitle': 'Betöltöd az újabb változatot?',
+ 'tours.revision.loadNewerBody': 'A túra nem mentett módosításai elvesznek.',
+ 'tours.revision.conflictEyebrow': 'Nincs mentve',
+ 'tours.revision.conflictTitle': 'Közben módosult',
+ 'tours.revision.conflictBody':
+ 'A túrát máshol mentették, miután megnyitottad, így semmi nem íródott felül. Mentsd a sajátodat új túraként, hogy mindkettő megmaradjon, töltsd be az újabb változatot, vagy írd felül tudatosan.',
+ 'tours.revision.overwrite': 'Felülírás',
+ 'tours.revision.saveAsNew': 'Mentés új túraként',
+ 'tours.revision.mineName': '{name} (saját változat)',
+ 'tours.revision.reloaded': 'Ezt a túrát máshol mentették, most az újabb változat látszik.',
'tours.planner.tourType': 'Túratípus',
'tours.paddle.boat': 'Hajó',
'tours.paddle.boat.kayak': 'Kajak',
diff --git a/shared/src/i18n/id/tours.ts b/shared/src/i18n/id/tours.ts
index e96a16b1d..287553d37 100644
--- a/shared/src/i18n/id/tours.ts
+++ b/shared/src/i18n/id/tours.ts
@@ -277,6 +277,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'Mengunduh file GPX memerlukan koneksi ke server.',
'tours.gpxExport.noRoute': 'Tur ini tidak punya rute tersimpan untuk diekspor.',
'tours.gpxExport.failed': 'File GPX tidak dapat dibuat.',
+ 'tours.revision.remoteTitle': 'Tur ini disimpan di tempat lain',
+ 'tours.revision.remoteBody':
+ 'Seseorang, atau kamu di perangkat lain, menyimpannya saat kamu mengedit. Perubahanmu tetap ada sampai kamu memutuskan.',
+ 'tours.revision.loadNewer': 'Muat yang terbaru',
+ 'tours.revision.loadNewerTitle': 'Muat versi yang lebih baru?',
+ 'tours.revision.loadNewerBody': 'Perubahan yang belum disimpan pada tur ini akan dibuang.',
+ 'tours.revision.conflictEyebrow': 'Belum disimpan',
+ 'tours.revision.conflictTitle': 'Diubah sementara itu',
+ 'tours.revision.conflictBody':
+ 'Tur ini disimpan di tempat lain setelah kamu membukanya, jadi tidak ada yang ditimpa. Simpan versimu sebagai tur baru agar keduanya tetap ada, muat versi terbaru, atau timpa dengan sengaja.',
+ 'tours.revision.overwrite': 'Timpa',
+ 'tours.revision.saveAsNew': 'Simpan sebagai tur baru',
+ 'tours.revision.mineName': '{name} (versiku)',
+ 'tours.revision.reloaded': 'Tur ini disimpan di tempat lain dan kini menampilkan versi terbaru.',
'tours.planner.tourType': 'Jenis tur',
'tours.paddle.boat': 'Perahu',
'tours.paddle.boat.kayak': 'Kayak', // same-as-en
diff --git a/shared/src/i18n/it/tours.ts b/shared/src/i18n/it/tours.ts
index db3704d24..e1a252e4d 100644
--- a/shared/src/i18n/it/tours.ts
+++ b/shared/src/i18n/it/tours.ts
@@ -284,6 +284,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'Per scaricare un file GPX serve una connessione al server.',
'tours.gpxExport.noRoute': 'Questo tour non ha un percorso salvato da esportare.',
'tours.gpxExport.failed': 'Non è stato possibile creare il file GPX.',
+ 'tours.revision.remoteTitle': 'Questo tour è stato salvato altrove',
+ 'tours.revision.remoteBody':
+ 'Qualcuno, o tu su un altro dispositivo, l’ha salvato mentre lo modificavi. Le tue modifiche restano finché non decidi.',
+ 'tours.revision.loadNewer': 'Carica la più recente',
+ 'tours.revision.loadNewerTitle': 'Caricare la versione più recente?',
+ 'tours.revision.loadNewerBody': 'Le modifiche non salvate a questo tour andranno perse.',
+ 'tours.revision.conflictEyebrow': 'Non salvato',
+ 'tours.revision.conflictTitle': 'Modificato nel frattempo',
+ 'tours.revision.conflictBody':
+ 'Il tour è stato salvato altrove dopo che l’hai aperto, quindi non è stato sovrascritto nulla. Salva il tuo come nuovo tour per tenerli entrambi, carica la versione più recente o sovrascrivilo di proposito.',
+ 'tours.revision.overwrite': 'Sovrascrivi',
+ 'tours.revision.saveAsNew': 'Salva come nuovo tour',
+ 'tours.revision.mineName': '{name} (la mia versione)',
+ 'tours.revision.reloaded': 'Questo tour è stato salvato altrove e ora mostra la versione più recente.',
'tours.planner.tourType': 'Tipo di tour',
'tours.paddle.boat': 'Imbarcazione',
'tours.paddle.boat.kayak': 'Kayak', // same-as-en
diff --git a/shared/src/i18n/ja/tours.ts b/shared/src/i18n/ja/tours.ts
index 58dae4155..369762e2a 100644
--- a/shared/src/i18n/ja/tours.ts
+++ b/shared/src/i18n/ja/tours.ts
@@ -271,6 +271,19 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'GPXファイルのダウンロードにはサーバーへの接続が必要です。',
'tours.gpxExport.noRoute': 'このツアーにはエクスポートできる保存済みルートがありません。',
'tours.gpxExport.failed': 'GPXファイルを作成できませんでした。',
+ 'tours.revision.remoteTitle': 'このツアーは別の場所で保存されました',
+ 'tours.revision.remoteBody': '編集中に、誰か(または別の端末のあなた)が保存しました。変更は決めるまで残ります。',
+ 'tours.revision.loadNewer': '新しい版を読み込む',
+ 'tours.revision.loadNewerTitle': '新しい版を読み込みますか?',
+ 'tours.revision.loadNewerBody': 'このツアーの未保存の変更は破棄されます。',
+ 'tours.revision.conflictEyebrow': '保存されていません',
+ 'tours.revision.conflictTitle': 'その間に変更されました',
+ 'tours.revision.conflictBody':
+ '開いた後にこのツアーが別の場所で保存されたため、何も上書きされていません。両方を残すには自分の版を新しいツアーとして保存するか、新しい版を読み込むか、意図して上書きしてください。',
+ 'tours.revision.overwrite': '上書き',
+ 'tours.revision.saveAsNew': '新しいツアーとして保存',
+ 'tours.revision.mineName': '{name}(自分の版)',
+ 'tours.revision.reloaded': 'このツアーは別の場所で保存されたため、新しい版を表示しています。',
'tours.planner.tourType': 'ツアーの種類',
'tours.paddle.boat': 'ボート',
'tours.paddle.boat.kayak': 'カヤック',
diff --git a/shared/src/i18n/ko/tours.ts b/shared/src/i18n/ko/tours.ts
index 947a1acee..129dcc2e8 100644
--- a/shared/src/i18n/ko/tours.ts
+++ b/shared/src/i18n/ko/tours.ts
@@ -269,6 +269,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'GPX 파일을 다운로드하려면 서버 연결이 필요합니다.',
'tours.gpxExport.noRoute': '이 투어에는 내보낼 저장된 경로가 없습니다.',
'tours.gpxExport.failed': 'GPX 파일을 만들지 못했습니다.',
+ 'tours.revision.remoteTitle': '이 투어가 다른 곳에서 저장되었습니다',
+ 'tours.revision.remoteBody':
+ '편집하는 동안 누군가 또는 다른 기기의 내가 저장했습니다. 결정할 때까지 변경 내용은 그대로 남습니다.',
+ 'tours.revision.loadNewer': '새 버전 불러오기',
+ 'tours.revision.loadNewerTitle': '새 버전을 불러올까요?',
+ 'tours.revision.loadNewerBody': '이 투어의 저장되지 않은 변경 내용은 버려집니다.',
+ 'tours.revision.conflictEyebrow': '저장되지 않음',
+ 'tours.revision.conflictTitle': '그사이 변경됨',
+ 'tours.revision.conflictBody':
+ '투어를 연 뒤 다른 곳에서 저장되어 아무것도 덮어쓰지 않았습니다. 둘 다 남기려면 내 버전을 새 투어로 저장하거나, 새 버전을 불러오거나, 의도적으로 덮어쓰세요.',
+ 'tours.revision.overwrite': '덮어쓰기',
+ 'tours.revision.saveAsNew': '새 투어로 저장',
+ 'tours.revision.mineName': '{name} (내 버전)',
+ 'tours.revision.reloaded': '이 투어가 다른 곳에서 저장되어 새 버전을 표시합니다.',
'tours.planner.tourType': '투어 유형',
'tours.paddle.boat': '보트',
'tours.paddle.boat.kayak': '카약',
diff --git a/shared/src/i18n/nl/tours.ts b/shared/src/i18n/nl/tours.ts
index 307ebdc90..0a4e4f1e7 100644
--- a/shared/src/i18n/nl/tours.ts
+++ b/shared/src/i18n/nl/tours.ts
@@ -285,6 +285,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'Voor het downloaden van een GPX-bestand is een verbinding met de server nodig.',
'tours.gpxExport.noRoute': 'Deze tocht heeft geen opgeslagen route om te exporteren.',
'tours.gpxExport.failed': 'Het GPX-bestand kon niet worden gemaakt.',
+ 'tours.revision.remoteTitle': 'Deze tocht is elders opgeslagen',
+ 'tours.revision.remoteBody':
+ 'Iemand, of jij op een ander apparaat, heeft hem opgeslagen terwijl je bewerkte. Je wijzigingen blijven tot je beslist.',
+ 'tours.revision.loadNewer': 'Nieuwere laden',
+ 'tours.revision.loadNewerTitle': 'Nieuwere versie laden?',
+ 'tours.revision.loadNewerBody': 'Je niet-opgeslagen wijzigingen aan deze tocht worden verworpen.',
+ 'tours.revision.conflictEyebrow': 'Niet opgeslagen',
+ 'tours.revision.conflictTitle': 'Intussen gewijzigd',
+ 'tours.revision.conflictBody':
+ 'De tocht is elders opgeslagen nadat jij hem opende, dus er is niets overschreven. Sla de jouwe op als nieuwe tocht om beide te houden, laad de nieuwere versie of overschrijf hem bewust.',
+ 'tours.revision.overwrite': 'Overschrijven',
+ 'tours.revision.saveAsNew': 'Opslaan als nieuwe tocht',
+ 'tours.revision.mineName': '{name} (mijn versie)',
+ 'tours.revision.reloaded': 'Deze tocht is elders opgeslagen en toont nu de nieuwere versie.',
'tours.planner.tourType': 'Soort tocht',
'tours.paddle.boat': 'Boot',
'tours.paddle.boat.kayak': 'Kajak',
diff --git a/shared/src/i18n/pl/tours.ts b/shared/src/i18n/pl/tours.ts
index 0f90e8d6c..f2758038d 100644
--- a/shared/src/i18n/pl/tours.ts
+++ b/shared/src/i18n/pl/tours.ts
@@ -291,6 +291,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'Pobranie pliku GPX wymaga połączenia z serwerem.',
'tours.gpxExport.noRoute': 'Ta trasa nie ma zapisanego przebiegu do eksportu.',
'tours.gpxExport.failed': 'Nie udało się utworzyć pliku GPX.',
+ 'tours.revision.remoteTitle': 'Ta trasa została zapisana gdzie indziej',
+ 'tours.revision.remoteBody':
+ 'Ktoś, albo ty na innym urządzeniu, zapisał ją podczas twojej edycji. Twoje zmiany zostają, dopóki nie zdecydujesz.',
+ 'tours.revision.loadNewer': 'Wczytaj nowszą',
+ 'tours.revision.loadNewerTitle': 'Wczytać nowszą wersję?',
+ 'tours.revision.loadNewerBody': 'Niezapisane zmiany tej trasy zostaną odrzucone.',
+ 'tours.revision.conflictEyebrow': 'Nie zapisano',
+ 'tours.revision.conflictTitle': 'Zmieniono w międzyczasie',
+ 'tours.revision.conflictBody':
+ 'Trasa została zapisana gdzie indziej po tym, jak ją otworzyłeś, więc nic nie zostało nadpisane. Zapisz swoją jako nową trasę, aby zachować obie, wczytaj nowszą wersję albo świadomie ją nadpisz.',
+ 'tours.revision.overwrite': 'Nadpisz',
+ 'tours.revision.saveAsNew': 'Zapisz jako nową trasę',
+ 'tours.revision.mineName': '{name} (moja wersja)',
+ 'tours.revision.reloaded': 'Ta trasa została zapisana gdzie indziej i teraz pokazuje nowszą wersję.',
'tours.planner.tourType': 'Rodzaj wycieczki',
'tours.paddle.boat': 'Łódź',
'tours.paddle.boat.kayak': 'Kajak',
diff --git a/shared/src/i18n/ru/tours.ts b/shared/src/i18n/ru/tours.ts
index 29d36a501..ae102e7c2 100644
--- a/shared/src/i18n/ru/tours.ts
+++ b/shared/src/i18n/ru/tours.ts
@@ -294,6 +294,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'Для скачивания файла GPX нужно соединение с сервером.',
'tours.gpxExport.noRoute': 'У этого похода нет сохранённого маршрута для экспорта.',
'tours.gpxExport.failed': 'Не удалось создать файл GPX.',
+ 'tours.revision.remoteTitle': 'Этот поход сохранили в другом месте',
+ 'tours.revision.remoteBody':
+ 'Кто-то, или вы на другом устройстве, сохранил его во время правки. Ваши изменения останутся, пока вы не решите.',
+ 'tours.revision.loadNewer': 'Загрузить новую',
+ 'tours.revision.loadNewerTitle': 'Загрузить более новую версию?',
+ 'tours.revision.loadNewerBody': 'Несохранённые изменения этого похода будут отброшены.',
+ 'tours.revision.conflictEyebrow': 'Не сохранено',
+ 'tours.revision.conflictTitle': 'Изменён тем временем',
+ 'tours.revision.conflictBody':
+ 'Поход сохранили в другом месте после того, как вы его открыли, поэтому ничего не перезаписано. Сохраните свою версию как новый поход, чтобы оставить обе, загрузите новую или перезапишите сознательно.',
+ 'tours.revision.overwrite': 'Перезаписать',
+ 'tours.revision.saveAsNew': 'Сохранить как новый поход',
+ 'tours.revision.mineName': '{name} (моя версия)',
+ 'tours.revision.reloaded': 'Этот поход сохранили в другом месте, теперь показана новая версия.',
'tours.planner.tourType': 'Тип тура',
'tours.paddle.boat': 'Лодка',
'tours.paddle.boat.kayak': 'Каяк',
diff --git a/shared/src/i18n/sk/tours.ts b/shared/src/i18n/sk/tours.ts
index 461d77d6d..7f0faaf20 100644
--- a/shared/src/i18n/sk/tours.ts
+++ b/shared/src/i18n/sk/tours.ts
@@ -279,6 +279,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'Na stiahnutie súboru GPX je potrebné pripojenie k serveru.',
'tours.gpxExport.noRoute': 'Táto túra nemá uloženú trasu na export.',
'tours.gpxExport.failed': 'Súbor GPX sa nepodarilo vytvoriť.',
+ 'tours.revision.remoteTitle': 'Táto túra bola uložená inde',
+ 'tours.revision.remoteBody':
+ 'Niekto, alebo ty na inom zariadení, ju uložil, kým ju upravuješ. Tvoje zmeny zostanú, kým sa nerozhodneš.',
+ 'tours.revision.loadNewer': 'Načítať novšiu',
+ 'tours.revision.loadNewerTitle': 'Načítať novšiu verziu?',
+ 'tours.revision.loadNewerBody': 'Neuložené zmeny tejto túry sa zahodia.',
+ 'tours.revision.conflictEyebrow': 'Neuložené',
+ 'tours.revision.conflictTitle': 'Medzitým zmenené',
+ 'tours.revision.conflictBody':
+ 'Túra bola uložená inde potom, čo si ju otvoril, takže sa nič neprepísalo. Ulož svoju ako novú túru a ponechaj si obe, načítaj novšiu verziu, alebo ju vedome prepíš.',
+ 'tours.revision.overwrite': 'Prepísať',
+ 'tours.revision.saveAsNew': 'Uložiť ako novú túru',
+ 'tours.revision.mineName': '{name} (moja verzia)',
+ 'tours.revision.reloaded': 'Túra bola uložená inde a teraz zobrazuje novšiu verziu.',
'tours.planner.tourType': 'Typ túry',
'tours.paddle.boat': 'Loď',
'tours.paddle.boat.kayak': 'Kajak',
diff --git a/shared/src/i18n/sv/tours.ts b/shared/src/i18n/sv/tours.ts
index 5175d260f..ff8197e2c 100644
--- a/shared/src/i18n/sv/tours.ts
+++ b/shared/src/i18n/sv/tours.ts
@@ -276,6 +276,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'För att ladda ner en GPX-fil behövs en anslutning till servern.',
'tours.gpxExport.noRoute': 'Den här turen har ingen sparad rutt att exportera.',
'tours.gpxExport.failed': 'GPX-filen kunde inte skapas.',
+ 'tours.revision.remoteTitle': 'Den här turen sparades någon annanstans',
+ 'tours.revision.remoteBody':
+ 'Någon, eller du på en annan enhet, sparade den medan du redigerade. Dina ändringar finns kvar tills du bestämmer dig.',
+ 'tours.revision.loadNewer': 'Ladda nyare',
+ 'tours.revision.loadNewerTitle': 'Ladda den nyare versionen?',
+ 'tours.revision.loadNewerBody': 'Dina osparade ändringar av turen kastas.',
+ 'tours.revision.conflictEyebrow': 'Inte sparad',
+ 'tours.revision.conflictTitle': 'Ändrad under tiden',
+ 'tours.revision.conflictBody':
+ 'Turen sparades någon annanstans efter att du öppnade den, så inget skrevs över. Spara din som en ny tur för att behålla båda, ladda den nyare versionen eller skriv över den med avsikt.',
+ 'tours.revision.overwrite': 'Skriv över',
+ 'tours.revision.saveAsNew': 'Spara som ny tur',
+ 'tours.revision.mineName': '{name} (min version)',
+ 'tours.revision.reloaded': 'Turen sparades någon annanstans och visar nu den nyare versionen.',
'tours.planner.tourType': 'Turtyp',
'tours.paddle.boat': 'Båt',
'tours.paddle.boat.kayak': 'Kajak',
diff --git a/shared/src/i18n/th/tours.ts b/shared/src/i18n/th/tours.ts
index 99dd075cd..694bf718d 100644
--- a/shared/src/i18n/th/tours.ts
+++ b/shared/src/i18n/th/tours.ts
@@ -265,6 +265,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'การดาวน์โหลดไฟล์ GPX ต้องเชื่อมต่อกับเซิร์ฟเวอร์',
'tours.gpxExport.noRoute': 'ทัวร์นี้ไม่มีเส้นทางที่บันทึกไว้ให้ส่งออก',
'tours.gpxExport.failed': 'สร้างไฟล์ GPX ไม่สำเร็จ',
+ 'tours.revision.remoteTitle': 'ทัวร์นี้ถูกบันทึกจากที่อื่น',
+ 'tours.revision.remoteBody':
+ 'มีคนหรือคุณจากอุปกรณ์อื่นบันทึกไว้ระหว่างที่คุณแก้ไข การเปลี่ยนแปลงของคุณยังอยู่จนกว่าคุณจะตัดสินใจ',
+ 'tours.revision.loadNewer': 'โหลดฉบับใหม่กว่า',
+ 'tours.revision.loadNewerTitle': 'โหลดเวอร์ชันที่ใหม่กว่าหรือไม่',
+ 'tours.revision.loadNewerBody': 'การเปลี่ยนแปลงที่ยังไม่บันทึกของทัวร์นี้จะถูกทิ้ง',
+ 'tours.revision.conflictEyebrow': 'ยังไม่ได้บันทึก',
+ 'tours.revision.conflictTitle': 'ถูกเปลี่ยนในระหว่างนั้น',
+ 'tours.revision.conflictBody':
+ 'ทัวร์นี้ถูกบันทึกจากที่อื่นหลังจากที่คุณเปิด จึงยังไม่มีอะไรถูกเขียนทับ บันทึกของคุณเป็นทัวร์ใหม่เพื่อเก็บไว้ทั้งสอง โหลดเวอร์ชันใหม่กว่า หรือตั้งใจเขียนทับ',
+ 'tours.revision.overwrite': 'เขียนทับ',
+ 'tours.revision.saveAsNew': 'บันทึกเป็นทัวร์ใหม่',
+ 'tours.revision.mineName': '{name} (เวอร์ชันของฉัน)',
+ 'tours.revision.reloaded': 'ทัวร์นี้ถูกบันทึกจากที่อื่น ตอนนี้แสดงเวอร์ชันที่ใหม่กว่า',
'tours.planner.tourType': 'ประเภททริป',
'tours.paddle.boat': 'เรือ',
'tours.paddle.boat.kayak': 'เรือคายัก',
diff --git a/shared/src/i18n/tr/tours.ts b/shared/src/i18n/tr/tours.ts
index 734a27d13..6eee9f414 100644
--- a/shared/src/i18n/tr/tours.ts
+++ b/shared/src/i18n/tr/tours.ts
@@ -278,6 +278,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'GPX dosyası indirmek için sunucuya bağlantı gerekir.',
'tours.gpxExport.noRoute': 'Bu turun dışa aktarılacak kayıtlı bir rotası yok.',
'tours.gpxExport.failed': 'GPX dosyası oluşturulamadı.',
+ 'tours.revision.remoteTitle': 'Bu tur başka yerde kaydedildi',
+ 'tours.revision.remoteBody':
+ 'Sen düzenlerken biri, ya da başka bir cihazda sen, kaydetti. Değişikliklerin karar verene kadar kalır.',
+ 'tours.revision.loadNewer': 'Yenisini yükle',
+ 'tours.revision.loadNewerTitle': 'Daha yeni sürüm yüklensin mi?',
+ 'tours.revision.loadNewerBody': 'Bu turdaki kaydedilmemiş değişikliklerin silinecek.',
+ 'tours.revision.conflictEyebrow': 'Kaydedilmedi',
+ 'tours.revision.conflictTitle': 'Bu arada değişti',
+ 'tours.revision.conflictBody':
+ 'Sen açtıktan sonra tur başka yerde kaydedildi, bu yüzden hiçbir şeyin üzerine yazılmadı. İkisini de tutmak için kendininkini yeni tur olarak kaydet, daha yeni sürümü yükle ya da bilerek üzerine yaz.',
+ 'tours.revision.overwrite': 'Üzerine yaz',
+ 'tours.revision.saveAsNew': 'Yeni tur olarak kaydet',
+ 'tours.revision.mineName': '{name} (benim sürümüm)',
+ 'tours.revision.reloaded': 'Bu tur başka yerde kaydedildi ve şimdi daha yeni sürümü gösteriliyor.',
'tours.planner.tourType': 'Tur türü',
'tours.paddle.boat': 'Tekne',
'tours.paddle.boat.kayak': 'Kano (kayak)',
diff --git a/shared/src/i18n/uk/tours.ts b/shared/src/i18n/uk/tours.ts
index 0e9e8f6df..361f12059 100644
--- a/shared/src/i18n/uk/tours.ts
+++ b/shared/src/i18n/uk/tours.ts
@@ -291,6 +291,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'Для завантаження файлу GPX потрібне з’єднання із сервером.',
'tours.gpxExport.noRoute': 'У цього походу немає збереженого маршруту для експорту.',
'tours.gpxExport.failed': 'Не вдалося створити файл GPX.',
+ 'tours.revision.remoteTitle': 'Цей похід збережено деінде',
+ 'tours.revision.remoteBody':
+ 'Хтось, або ви на іншому пристрої, зберіг його під час редагування. Ваші зміни лишаються, доки ви не вирішите.',
+ 'tours.revision.loadNewer': 'Завантажити новішу',
+ 'tours.revision.loadNewerTitle': 'Завантажити новішу версію?',
+ 'tours.revision.loadNewerBody': 'Незбережені зміни цього походу буде відкинуто.',
+ 'tours.revision.conflictEyebrow': 'Не збережено',
+ 'tours.revision.conflictTitle': 'Змінено тим часом',
+ 'tours.revision.conflictBody':
+ 'Похід збережено деінде після того, як ви його відкрили, тож нічого не перезаписано. Збережіть свою версію як новий похід, щоб лишити обидві, завантажте новішу або свідомо перезапишіть.',
+ 'tours.revision.overwrite': 'Перезаписати',
+ 'tours.revision.saveAsNew': 'Зберегти як новий похід',
+ 'tours.revision.mineName': '{name} (моя версія)',
+ 'tours.revision.reloaded': 'Цей похід збережено деінде, тепер показано новішу версію.',
'tours.planner.tourType': 'Тип туру',
'tours.paddle.boat': 'Човен',
'tours.paddle.boat.kayak': 'Каяк',
diff --git a/shared/src/i18n/vi/tours.ts b/shared/src/i18n/vi/tours.ts
index 50739c048..9c381ce83 100644
--- a/shared/src/i18n/vi/tours.ts
+++ b/shared/src/i18n/vi/tours.ts
@@ -278,6 +278,20 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': 'Cần kết nối tới máy chủ để tải tệp GPX.',
'tours.gpxExport.noRoute': 'Chuyến đi bộ này không có tuyến đường đã lưu để xuất.',
'tours.gpxExport.failed': 'Không thể tạo tệp GPX.',
+ 'tours.revision.remoteTitle': 'Chuyến đi bộ này đã được lưu ở nơi khác',
+ 'tours.revision.remoteBody':
+ 'Ai đó, hoặc chính bạn trên thiết bị khác, đã lưu trong lúc bạn chỉnh sửa. Thay đổi của bạn vẫn giữ cho tới khi bạn quyết định.',
+ 'tours.revision.loadNewer': 'Tải bản mới hơn',
+ 'tours.revision.loadNewerTitle': 'Tải phiên bản mới hơn?',
+ 'tours.revision.loadNewerBody': 'Các thay đổi chưa lưu của chuyến đi bộ này sẽ bị bỏ.',
+ 'tours.revision.conflictEyebrow': 'Chưa lưu',
+ 'tours.revision.conflictTitle': 'Đã thay đổi trong lúc đó',
+ 'tours.revision.conflictBody':
+ 'Chuyến đi bộ đã được lưu ở nơi khác sau khi bạn mở, nên chưa có gì bị ghi đè. Lưu bản của bạn thành chuyến mới để giữ cả hai, tải bản mới hơn, hoặc chủ động ghi đè.',
+ 'tours.revision.overwrite': 'Ghi đè',
+ 'tours.revision.saveAsNew': 'Lưu thành chuyến mới',
+ 'tours.revision.mineName': '{name} (bản của tôi)',
+ 'tours.revision.reloaded': 'Chuyến đi bộ này đã được lưu ở nơi khác và giờ hiển thị bản mới hơn.',
'tours.planner.tourType': 'Loại chuyến',
'tours.paddle.boat': 'Thuyền',
'tours.paddle.boat.kayak': 'Thuyền kayak',
diff --git a/shared/src/i18n/zh-TW/tours.ts b/shared/src/i18n/zh-TW/tours.ts
index 130703287..9cf3ba7be 100644
--- a/shared/src/i18n/zh-TW/tours.ts
+++ b/shared/src/i18n/zh-TW/tours.ts
@@ -254,6 +254,19 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': '下載 GPX 檔案需要連線到伺服器。',
'tours.gpxExport.noRoute': '這個遊程沒有可匯出的已儲存路線。',
'tours.gpxExport.failed': '無法建立 GPX 檔案。',
+ 'tours.revision.remoteTitle': '這個遊程已在別處儲存',
+ 'tours.revision.remoteBody': '在你編輯時,有人(或你在另一台裝置上)儲存了它。你的變更會保留,直到你做出決定。',
+ 'tours.revision.loadNewer': '載入較新版本',
+ 'tours.revision.loadNewerTitle': '載入較新的版本?',
+ 'tours.revision.loadNewerBody': '這個遊程中未儲存的變更將被捨棄。',
+ 'tours.revision.conflictEyebrow': '未儲存',
+ 'tours.revision.conflictTitle': '期間已被變更',
+ 'tours.revision.conflictBody':
+ '你開啟後這個遊程在別處被儲存,因此沒有任何內容被覆寫。把你的版本另存為新遊程以保留兩者,載入較新版本,或刻意覆寫它。',
+ 'tours.revision.overwrite': '覆寫',
+ 'tours.revision.saveAsNew': '另存為新遊程',
+ 'tours.revision.mineName': '{name}(我的版本)',
+ 'tours.revision.reloaded': '這個遊程已在別處儲存,現在顯示較新的版本。',
'tours.planner.tourType': '路線類型',
'tours.paddle.boat': '船隻',
'tours.paddle.boat.kayak': '獨木舟(Kayak)',
diff --git a/shared/src/i18n/zh/tours.ts b/shared/src/i18n/zh/tours.ts
index 4b1321e36..884a54163 100644
--- a/shared/src/i18n/zh/tours.ts
+++ b/shared/src/i18n/zh/tours.ts
@@ -255,6 +255,19 @@ const tours: TranslationStrings = {
'tours.gpxExport.offline': '下载 GPX 文件需要连接服务器。',
'tours.gpxExport.noRoute': '这条路线没有可导出的已保存线路。',
'tours.gpxExport.failed': '无法创建 GPX 文件。',
+ 'tours.revision.remoteTitle': '这条路线已在别处保存',
+ 'tours.revision.remoteBody': '在你编辑时,有人(或你在另一台设备上)保存了它。你的更改会保留,直到你做出决定。',
+ 'tours.revision.loadNewer': '加载较新版本',
+ 'tours.revision.loadNewerTitle': '加载较新的版本?',
+ 'tours.revision.loadNewerBody': '这条路线中未保存的更改将被丢弃。',
+ 'tours.revision.conflictEyebrow': '未保存',
+ 'tours.revision.conflictTitle': '期间已被更改',
+ 'tours.revision.conflictBody':
+ '你打开后这条路线在别处被保存,因此没有任何内容被覆盖。把你的版本另存为新路线以保留两者,加载较新版本,或有意覆盖它。',
+ 'tours.revision.overwrite': '覆盖',
+ 'tours.revision.saveAsNew': '另存为新路线',
+ 'tours.revision.mineName': '{name}(我的版本)',
+ 'tours.revision.reloaded': '这条路线已在别处保存,现在显示较新的版本。',
'tours.planner.tourType': '路线类型',
'tours.paddle.boat': '船只',
'tours.paddle.boat.kayak': '皮划艇',
diff --git a/shared/src/tours/paddle-plan.schema.ts b/shared/src/tours/paddle-plan.schema.ts
index 6f9cea444..3b075def4 100644
--- a/shared/src/tours/paddle-plan.schema.ts
+++ b/shared/src/tours/paddle-plan.schema.ts
@@ -77,5 +77,7 @@ export const tourPaddlePlanRequestSchema = z.object({
paddle_speed_kmh: z.number().finite().min(0.5).max(20).nullable(),
portage_speed_kmh: portageSpeedKmhSchema.nullable(),
track_marks: trackMarksSchema,
+ /** P2C-03: the revision the plan was laid onto; refused with a 409 once the tour moved on. */
+ expected_revision: z.number().int().min(1).nullable().optional(),
});
export type TourPaddlePlanRequest = z.infer<typeof tourPaddlePlanRequestSchema>;
diff --git a/shared/src/tours/tours.schema.ts b/shared/src/tours/tours.schema.ts
index e97419b09..64c28c121 100644
--- a/shared/src/tours/tours.schema.ts
+++ b/shared/src/tours/tours.schema.ts
@@ -134,6 +134,29 @@ export const tourSchema = z.object({
});
export type Tour = z.infer<typeof tourSchema>;
+/**
+ * P2C-03: the technical revision of a saved tour, raised by every write that
+ * changes it. Not the version of a source the tour was imported from (that is
+ * its provenance), and not a copy (a copy is a tour of its own at 1).
+ */
+export const tourRevisionSchema = z.number().int().min(1);
+
+/**
+ * The revision a write was based on. Given, the write is refused with a 409
+ * while the tour has moved on; left out, it writes as before, so an older
+ * client or a queued offline write keeps working.
+ */
+export const expectedTourRevisionSchema = tourRevisionSchema.nullable().optional();
+
+/** The 409 a write against a tour that has moved on answers with: the revision it has now. */
+export const TOUR_REVISION_CONFLICT = 'tour_revision_conflict';
+export const tourRevisionConflictSchema = z.object({
+ error: z.string(),
+ code: z.literal(TOUR_REVISION_CONFLICT),
+ revision: tourRevisionSchema,
+});
+export type TourRevisionConflict = z.infer<typeof tourRevisionConflictSchema>;
+
export const tourTypeListResponseSchema = z.object({
tourTypes: z.array(tourTypeSchema),
});
@@ -166,6 +189,8 @@ export const tourListItemSchema = tourSchema.extend({
* server) is dropped rather than refused, so a queued write still lands.
*/
paddle_check: paddleCheckSchema.nullable().optional().catch(undefined),
+ /** P2C-03: the revision a write names to be refused once the tour moved on; absent in a list cached before it existed. */
+ revision: tourRevisionSchema.optional(),
});
export type TourListItem = z.infer<typeof tourListItemSchema>;
@@ -278,6 +303,8 @@ export const tourCreateRequestSchema = z
* where the tour came from, so an edit later neither sets nor changes it.
*/
derived_from_place_id: z.number().int().positive().nullable().optional(),
+ /** P2C-03, editing only: the revision the draft was opened at. A create ignores it. */
+ expected_revision: expectedTourRevisionSchema,
})
.superRefine((value, ctx) => {
if (
diff --git a/wiki/MCP-Addon-Tools.md b/wiki/MCP-Addon-Tools.md
index f7add1680..2a096341f 100644
--- a/wiki/MCP-Addon-Tools.md
+++ b/wiki/MCP-Addon-Tools.md
@@ -237,7 +237,7 @@ Read only: the saved tours of a trip, as the Tours list and the tour detail show
| Tool | Description | Scope |
|---|---|---|
-| `list_tours` | The saved tours of a trip: name, type (`hike`, or `kayak` for a paddle tour), origin (`trek` for planned in TREK, `gpx` for a GPX import, `wanderer` for a wanderer snapshot), distance, ascent and descent (unknown for a paddle tour drawn in the planner), the stored routing limit of a hike on the SAC scale, the boat, water and chosen speed of a paddle tour, the check bench of a paddle tour (`paddle_check`: how far the OpenStreetMap obstacle data covers its route and how many obstacles are open, to check again or decided; a planning status, never a safety or legal clearance), and the days of the trip each tour is on | `trips:read` |
+| `list_tours` | The saved tours of a trip: name, type (`hike`, or `kayak` for a paddle tour), origin (`trek` for planned in TREK, `gpx` for a GPX import, `wanderer` for a wanderer snapshot), distance, ascent and descent (unknown for a paddle tour drawn in the planner), the stored routing limit of a hike on the SAC scale, the boat, water and chosen speed of a paddle tour, the check bench of a paddle tour (`paddle_check`: how far the OpenStreetMap obstacle data covers its route and how many obstacles are open, to check again or decided; a planning status, never a safety or legal clearance), the `revision` (raised by every saved change of the tour), and the days of the trip each tour is on | `trips:read` |
| `get_tour_plan` | One tour: its facts, its ordered control points, its provenance (where it came from, when, and whether it was changed in TREK since) and its days. A control point can carry a fixed leg to the next one: a via ferrata (`ferrata`) or a stretch drawn by hand (`free`), which no router planned or checked. A shaping point (`shaping: true`) only steers the route and is no stop. A paddle tour also carries its obstacle checklist (`obstacle_check`): the obstacles of the OpenStreetMap data along its route, what the travellers decided about each, and their own portages and locks. The full track geometry is not included | `trips:read` |
| `find_tours_for_day` | The tours put on one day of a trip, with the same facts as `list_tours` | `trips:read` |
| `export_tour_gpx` | One saved tour as a GPX file: its whole saved line as one track, with the heights it carries and none it lacks, and a file name. A tour without a line cannot be exported | `trips:read` |